code
stringlengths
3
1.01M
repo_name
stringlengths
5
116
path
stringlengths
3
311
language
stringclasses
30 values
license
stringclasses
15 values
size
int64
3
1.01M
const express = require('express'); const router = express.Router(); const routes = require('./routes')(router); module.exports = router;
abhaydgarg/Simplenote
api/v1/index.js
JavaScript
mit
139
package simulation.generators; import simulation.data.PetrolStation; import simulation.data.Road; /** * Created by user on 03.06.2017. */ public class PetrolStationGenerator { private Road road; private int minimalDistanceBetweenStations = 50; private int maximumDistanceBetweenStations = 200; private float minimalFuelPrice = 3.5f; private float maximumFuelPrice = 4f; public PetrolStationGenerator(Road road) { this.road = road; } public void generateStationsOnTheRoad(){ RandomIntegerGenerator generator = new RandomIntegerGenerator(); int lastStationPosition = 0; road.addPetrolStation(generateStation(lastStationPosition)); while (lastStationPosition < road.getDistance()){ int nextStationDistance = generator.generateNumberFromRange(minimalDistanceBetweenStations,maximumDistanceBetweenStations); if(lastStationPosition+nextStationDistance <= road.getDistance()){ road.addPetrolStation(generateStation(lastStationPosition+nextStationDistance)); lastStationPosition += nextStationDistance; }else{ break; } } } private PetrolStation generateStation(int positionOnRoad){ float fuelPrice = new RandomFloatGenerator().generateNumberFromRange(minimalFuelPrice,maximumFuelPrice); return new PetrolStation(positionOnRoad,fuelPrice); } public Road getRoad() { return road; } public void setRoad(Road road) { this.road = road; } public int getMinimalDistanceBetweenStations() { return minimalDistanceBetweenStations; } public void setMinimalDistanceBetweenStations(int minimalDistanceBetweenStations) { this.minimalDistanceBetweenStations = minimalDistanceBetweenStations; } public int getMaximumDistanceBetweenStations() { return maximumDistanceBetweenStations; } public void setMaximumDistanceBetweenStations(int maximumDistanceBetweenStations) { this.maximumDistanceBetweenStations = maximumDistanceBetweenStations; } public float getMinimalFuelPrice() { return minimalFuelPrice; } public void setMinimalFuelPrice(float minimalFuelPrice) { this.minimalFuelPrice = minimalFuelPrice; } public float getMaximumFuelPrice() { return maximumFuelPrice; } public void setMaximumFuelPrice(float maximumFuelPrice) { this.maximumFuelPrice = maximumFuelPrice; } }
MiszelHub/FuzzyDriverRefueling
Fuzzy-Driver/src/main/java/simulation/generators/PetrolStationGenerator.java
Java
mit
2,533
var HDWalletProvider = require("truffle-hdwallet-provider"); var mnemonic = "candy maple cake sugar pudding cream honey rich smooth crumble sweet treat"; module.exports = { networks: { development: { provider: function () { return new HDWalletProvider(mnemonic, "http://127.0.0.1:7545/", 0, 50); }, network_id: "*", }, }, compilers: { solc: { version: "^0.5.2", }, }, };
manishbisht/Competitive-Programming
Hiring Challenges/Bosch/Blockchain Developer Hiring/Round 2/truffle.js
JavaScript
mit
484
<!DOCTYPE html> <!--[if lt IE 9]><html class="no-js lt-ie9" lang="en" dir="ltr"><![endif]--> <!--[if gt IE 8]><!--> <html class="no-js" lang="en" dir="ltr"> <!--<![endif]--> <!-- Usage: /eic/site/ccc-rec.nsf/tpl-eng/template-1col.html?Open&id=3 (optional: ?Open&page=filename.html&id=x) --> <!-- Created: ; Product Code: 536; Server: stratnotes2.ic.gc.ca --> <head> <!-- Title begins / Début du titre --> <title> Groupe Giroux - Complete profile - Canadian Company Capabilities - Industries and Business - Industry Canada </title> <!-- Title ends / Fin du titre --> <!-- Meta-data begins / Début des métadonnées --> <meta charset="utf-8" /> <meta name="dcterms.language" title="ISO639-2" content="eng" /> <meta name="dcterms.title" content="" /> <meta name="description" content="" /> <meta name="dcterms.description" content="" /> <meta name="dcterms.type" content="report, data set" /> <meta name="dcterms.subject" content="businesses, industry" /> <meta name="dcterms.subject" content="businesses, industry" /> <meta name="dcterms.issued" title="W3CDTF" content="" /> <meta name="dcterms.modified" title="W3CDTF" content="" /> <meta name="keywords" content="" /> <meta name="dcterms.creator" content="" /> <meta name="author" content="" /> <meta name="dcterms.created" title="W3CDTF" content="" /> <meta name="dcterms.publisher" content="" /> <meta name="dcterms.audience" title="icaudience" content="" /> <meta name="dcterms.spatial" title="ISO3166-1" content="" /> <meta name="dcterms.spatial" title="gcgeonames" content="" /> <meta name="dcterms.format" content="HTML" /> <meta name="dcterms.identifier" title="ICsiteProduct" content="536" /> <!-- EPI-11240 --> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <!-- MCG-202 --> <meta content="width=device-width,initial-scale=1" name="viewport"> <!-- EPI-11567 --> <meta name = "format-detection" content = "telephone=no"> <!-- EPI-12603 --> <meta name="robots" content="noarchive"> <!-- EPI-11190 - Webtrends --> <script> var startTime = new Date(); startTime = startTime.getTime(); </script> <!--[if gte IE 9 | !IE ]><!--> <link href="/utils/scripts/_WET_4-0/apps/themes-dist/gcweb/assets/favicon.ico" rel="icon" type="image/x-icon"> <link rel="stylesheet" href="/utils/scripts/_WET_4-0/apps/themes-dist/gcweb/css/wet-boew.min.css"> <!--<![endif]--> <link rel="stylesheet" href="/utils/scripts/_WET_4-0/apps/themes-dist/gcweb/css/theme.min.css"> <!--[if lt IE 9]> <link href="/utils/scripts/_WET_4-0/apps/themes-dist/gcweb/assets/favicon.ico" rel="shortcut icon" /> <link rel="stylesheet" href="/utils/scripts/_WET_4-0/apps/themes-dist/gcweb/css/ie8-wet-boew.min.css" /> <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script> <script src="/utils/scripts/_WET_4-0/apps/themes-dist/gcweb/js/ie8-wet-boew.min.js"></script> <![endif]--> <!--[if lte IE 9]> <![endif]--> <noscript><link rel="stylesheet" href="/utils/scripts/_WET_4-0/apps/themes-dist/gcweb/css/noscript.min.css" /></noscript> <!-- Google Tag Manager DO NOT REMOVE OR MODIFY - NE PAS SUPPRIMER OU MODIFIER --> <script>dataLayer1 = [];</script> <!-- End Google Tag Manager --> <!-- EPI-11235 --> <link rel="stylesheet" href="/eic/home.nsf/css/add_WET_4-0_Canada_Apps.css"> <link href="//netdna.bootstrapcdn.com/font-awesome/4.0.3/css/font-awesome.css" rel="stylesheet"> <link href="/app/ccc/srch/css/print.css" media="print" rel="stylesheet" type="text/css" /> </head> <body class="home" vocab="http://schema.org/" typeof="WebPage"> <!-- EPIC HEADER BEGIN --> <!-- Google Tag Manager DO NOT REMOVE OR MODIFY - NE PAS SUPPRIMER OU MODIFIER --> <noscript><iframe title="Google Tag Manager" src="//www.googletagmanager.com/ns.html?id=GTM-TLGQ9K" height="0" width="0" style="display:none;visibility:hidden"></iframe></noscript> <script>(function(w,d,s,l,i){w[l]=w[l]||[];w[l].push({'gtm.start': new Date().getTime(),event:'gtm.js'});var f=d.getElementsByTagName(s)[0], j=d.createElement(s),dl=l!='dataLayer1'?'&l='+l:'';j.async=true;j.src='//www.googletagmanager.com/gtm.js?id='+i+dl;f.parentNode.insertBefore(j,f);})(window,document,'script','dataLayer1','GTM-TLGQ9K');</script> <!-- End Google Tag Manager --> <!-- EPI-12801 --> <span typeof="Organization"><meta property="legalName" content="Department_of_Industry"></span> <ul id="wb-tphp"> <li class="wb-slc"> <a class="wb-sl" href="#wb-cont">Skip to main content</a> </li> <li class="wb-slc visible-sm visible-md visible-lg"> <a class="wb-sl" href="#wb-info">Skip to "About this site"</a> </li> </ul> <header role="banner"> <div id="wb-bnr" class="container"> <section id="wb-lng" class="visible-md visible-lg text-right"> <h2 class="wb-inv">Language selection</h2> <div class="row"> <div class="col-md-12"> <ul class="list-inline mrgn-bttm-0"> <li><a href="nvgt.do?V_TOKEN=1492289850357&V_SEARCH.docsCount=3&V_DOCUMENT.docRank=20428&V_SEARCH.docsStart=20427&V_SEARCH.command=navigate&V_SEARCH.resultsJSP=/prfl.do&lang=fra&redirectUrl=/app/scr/imbs/ccc/rgstrtn/updt.sec?_flId?_flxKy=e1s1&amp;estblmntNo=234567041301&amp;profileId=61&amp;_evId=bck&amp;lang=eng&amp;V_SEARCH.showStricts=false&amp;prtl=1&amp;_flId?_flId?_flxKy=e1s1" title="Français" lang="fr">Français</a></li> </ul> </div> </div> </section> <div class="row"> <div class="brand col-xs-8 col-sm-9 col-md-6"> <a href="http://www.canada.ca/en/index.html"><object type="image/svg+xml" tabindex="-1" data="/utils/scripts/_WET_4-0/apps/themes-dist/gcweb/assets/sig-blk-en.svg"></object><span class="wb-inv"> Government of Canada</span></a> </div> <section class="wb-mb-links col-xs-4 col-sm-3 visible-sm visible-xs" id="wb-glb-mn"> <h2>Search and menus</h2> <ul class="list-inline text-right chvrn"> <li><a href="#mb-pnl" title="Search and menus" aria-controls="mb-pnl" class="overlay-lnk" role="button"><span class="glyphicon glyphicon-search"><span class="glyphicon glyphicon-th-list"><span class="wb-inv">Search and menus</span></span></span></a></li> </ul> <div id="mb-pnl"></div> </section> <!-- Site Search Removed --> </div> </div> <nav role="navigation" id="wb-sm" class="wb-menu visible-md visible-lg" data-trgt="mb-pnl" data-ajax-fetch="//cdn.canada.ca/gcweb-cdn-dev/sitemenu/sitemenu-en.html" typeof="SiteNavigationElement"> <h2 class="wb-inv">Topics menu</h2> <div class="container nvbar"> <div class="row"> <ul class="list-inline menu"> <li><a href="https://www.canada.ca/en/services/jobs.html">Jobs</a></li> <li><a href="http://www.cic.gc.ca/english/index.asp">Immigration</a></li> <li><a href="https://travel.gc.ca/">Travel</a></li> <li><a href="https://www.canada.ca/en/services/business.html">Business</a></li> <li><a href="https://www.canada.ca/en/services/benefits.html">Benefits</a></li> <li><a href="http://healthycanadians.gc.ca/index-eng.php">Health</a></li> <li><a href="https://www.canada.ca/en/services/taxes.html">Taxes</a></li> <li><a href="https://www.canada.ca/en/services.html">More services</a></li> </ul> </div> </div> </nav> <!-- EPIC BODY BEGIN --> <nav role="navigation" id="wb-bc" class="" property="breadcrumb"> <h2 class="wb-inv">You are here:</h2> <div class="container"> <div class="row"> <ol class="breadcrumb"> <li><a href="/eic/site/icgc.nsf/eng/home" title="Home">Home</a></li> <li><a href="/eic/site/icgc.nsf/eng/h_07063.html" title="Industries and Business">Industries and Business</a></li> <li><a href="/eic/site/ccc-rec.nsf/tpl-eng/../eng/home" >Canadian Company Capabilities</a></li> </ol> </div> </div> </nav> </header> <main id="wb-cont" role="main" property="mainContentOfPage" class="container"> <!-- End Header --> <!-- Begin Body --> <!-- Begin Body Title --> <!-- End Body Title --> <!-- Begin Body Head --> <!-- End Body Head --> <!-- Begin Body Content --> <br> <!-- Complete Profile --> <!-- Company Information above tabbed area--> <input id="showMore" type="hidden" value='more'/> <input id="showLess" type="hidden" value='less'/> <h1 id="wb-cont"> Company profile - Canadian Company Capabilities </h1> <div class="profileInfo hidden-print"> <ul class="list-inline"> <li><a href="cccSrch.do?lang=eng&profileId=&prtl=1&key.hitsPerPage=25&searchPage=%252Fapp%252Fccc%252Fsrch%252FcccBscSrch.do%253Flang%253Deng%2526amp%253Bprtl%253D1%2526amp%253Btagid%253D&V_SEARCH.scopeCategory=CCC.Root&V_SEARCH.depth=1&V_SEARCH.showStricts=false&V_SEARCH.sortSpec=title+asc&amp;rstBtn.x=" class="btn btn-link">New Search</a>&nbsp;|</li> <li><form name="searchForm" method="post" action="/app/ccc/srch/bscSrch.do"> <input type="hidden" name="lang" value="eng" /> <input type="hidden" name="profileId" value="" /> <input type="hidden" name="prtl" value="1" /> <input type="hidden" name="searchPage" value="%2Fapp%2Fccc%2Fsrch%2FcccBscSrch.do%3Flang%3Deng%26amp%3Bprtl%3D1%26amp%3Btagid%3D" /> <input type="hidden" name="V_SEARCH.scopeCategory" value="CCC.Root" /> <input type="hidden" name="V_SEARCH.depth" value="1" /> <input type="hidden" name="V_SEARCH.showStricts" value="false" /> <input id="repeatSearchBtn" class="btn btn-link" type="submit" value="Return to search results" /> </form></li> <li>|&nbsp;<a href="nvgt.do?V_SEARCH.docsStart=20426&amp;V_DOCUMENT.docRank=20427&amp;V_SEARCH.docsCount=3&amp;lang=eng&amp;prtl=1&amp;sbPrtl=&amp;profile=cmpltPrfl&amp;V_TOKEN=1492289857012&amp;V_SEARCH.command=navigate&amp;V_SEARCH.resultsJSP=%2fprfl.do&amp;estblmntNo=234567088754&amp;profileId=&amp;key.newSearchLabel=">Previous Company</a></li> <li>|&nbsp;<a href="nvgt.do?V_SEARCH.docsStart=20428&amp;V_DOCUMENT.docRank=20429&amp;V_SEARCH.docsCount=3&amp;lang=eng&amp;prtl=1&amp;sbPrtl=&amp;profile=cmpltPrfl&amp;V_TOKEN=1492289857012&amp;V_SEARCH.command=navigate&amp;V_SEARCH.resultsJSP=%2fprfl.do&amp;estblmntNo=234567144903&amp;profileId=&amp;key.newSearchLabel=">Next Company</a></li> </ul> </div> <details> <summary>Third-Party Information Liability Disclaimer</summary> <p>Some of the information on this Web page has been provided by external sources. The Government of Canada is not responsible for the accuracy, reliability or currency of the information supplied by external sources. Users wishing to rely upon this information should consult directly with the source of the information. Content provided by external sources is not subject to official languages, privacy and accessibility requirements.</p> </details> <h2> Groupe Giroux </h2> <div class="row"> <div class="col-md-5"> <h2 class="h5 mrgn-bttm-0">Legal/Operating Name:</h2> <p>Groupe Giroux</p> <div class="mrgn-tp-md"></div> <p class="mrgn-bttm-0" ><a href="http://www.arpentage.com" target="_blank" title="Website URL">http://www.arpentage.com</a></p> <p><a href="mailto:[email protected]" title="[email protected]">[email protected]</a></p> </div> <div class="col-md-4 mrgn-sm-sm"> <h2 class="h5 mrgn-bttm-0">Mailing Address:</h2> <address class="mrgn-bttm-md"> 675, boul. Alphonse-Desjardins<br/> Bureau 102<br/> LÉVIS, Quebec<br/> G6V 5T3 <br/> </address> <h2 class="h5 mrgn-bttm-0">Location Address:</h2> <address class="mrgn-bttm-md"> 675, boul. Alphonse-Desjardins<br/> Bureau 102<br/> LÉVIS, Quebec<br/> G6V 5T3 <br/> </address> <p class="mrgn-bttm-0"><abbr title="Telephone">Tel.</abbr>: (418) 652-8838 </p> <p class="mrgn-bttm-0"><abbr title="Telephone">Tel.</abbr>: (866) 838-9961</p> <p class="mrgn-bttm-lg"><abbr title="Facsimile">Fax</abbr>: (418) 652-0119</p> </div> <div class="col-md-3 mrgn-tp-md"> </div> </div> <div class="row mrgn-tp-md mrgn-bttm-md"> <div class="col-md-12"> <h2 class="wb-inv">Company Profile</h2> <br> Services en arpentage foncier et de construction. <br>Cadastres, certificats de localisation, relevés topographiques, <br>Mesurage d&#39;espaces locatifs, cadastre vertical (copropriété). <br>Implantation de structures et de bâtiments de toutes natures, <br>etc..<br> </div> </div> <!-- <div class="wb-tabs ignore-session update-hash wb-eqht-off print-active"> --> <div class="wb-tabs ignore-session"> <div class="tabpanels"> <details id="details-panel1"> <summary> Full profile </summary> <!-- Tab 1 --> <h2 class="wb-invisible"> Full profile </h2> <!-- Contact Information --> <h3 class="page-header"> Contact information </h3> <section class="container-fluid"> <div class="row mrgn-tp-lg"> <div class="col-md-3"> <strong> ALAIN GOSSELIN </strong></div> </div> <div class="row mrgn-lft-md"> <div class="col-md-5"> <strong> Title: </strong> </div> <div class="col-md-7"> ARPENTEUR-GEOMETRE <br> </div> </div> <div class="row mrgn-lft-md"> <div class="col-md-5"> <strong> Telephone: </strong> </div> <div class="col-md-7"> (418) 838-9961 </div> </div> <div class="row mrgn-lft-md"> <div class="col-md-5"> <strong> Facsimile: </strong> </div> <div class="col-md-7"> (418) 832-7180 </div> </div> <div class="row mrgn-lft-md"> <div class="col-md-5"> <strong> Email: </strong> </div> <div class="col-md-7"> [email protected] </div> </div> </section> <p class="mrgn-tp-lg text-right small hidden-print"> <a href="#wb-cont">top of page</a> </p> <!-- Company Description --> <h3 class="page-header"> Company description </h3> <section class="container-fluid"> <div class="row"> <div class="col-md-5"> <strong> Country of Ownership: </strong> </div> <div class="col-md-7"> Canada &nbsp; </div> </div> <div class="row"> <div class="col-md-5"> <strong> Year Established: </strong> </div> <div class="col-md-7"> 1971 </div> </div> <div class="row"> <div class="col-md-5"> <strong> Exporting: </strong> </div> <div class="col-md-7"> No &nbsp; </div> </div> <div class="row"> <div class="col-md-5"> <strong> Primary Industry (NAICS): </strong> </div> <div class="col-md-7"> 541370 - Surveying and Mapping (except Geophysical) Services </div> </div> <div class="row"> <div class="col-md-5"> <strong> Primary Business Activity: </strong> </div> <div class="col-md-7"> Services &nbsp; </div> </div> <div class="row"> <div class="col-md-5"> <strong> Number of Employees: </strong> </div> <div class="col-md-7"> 12&nbsp; </div> </div> </section> <!-- Products / Services / Licensing --> <h3 class="page-header"> Product / Service / Licensing </h3> <section class="container-fluid"> <div class="row mrgn-bttm-md"> <div class="col-md-3"> <strong> Service Name: </strong> </div> <div class="col-md-9"> Land surveying <br> </div> </div> </section> <p class="mrgn-tp-lg text-right small hidden-print"> <a href="#wb-cont">top of page</a> </p> <!-- Technology Profile --> <!-- Market Profile --> <!-- Sector Information --> <details class="mrgn-tp-md mrgn-bttm-md"> <summary> Third-Party Information Liability Disclaimer </summary> <p> Some of the information on this Web page has been provided by external sources. The Government of Canada is not responsible for the accuracy, reliability or currency of the information supplied by external sources. Users wishing to rely upon this information should consult directly with the source of the information. Content provided by external sources is not subject to official languages, privacy and accessibility requirements. </p> </details> </details> <details id="details-panel2"> <summary> Contacts </summary> <h2 class="wb-invisible"> Contact information </h2> <!-- Contact Information --> <section class="container-fluid"> <div class="row mrgn-tp-lg"> <div class="col-md-3"> <strong> ALAIN GOSSELIN </strong></div> </div> <div class="row mrgn-lft-md"> <div class="col-md-5"> <strong> Title: </strong> </div> <div class="col-md-7"> ARPENTEUR-GEOMETRE <br> </div> </div> <div class="row mrgn-lft-md"> <div class="col-md-5"> <strong> Telephone: </strong> </div> <div class="col-md-7"> (418) 838-9961 </div> </div> <div class="row mrgn-lft-md"> <div class="col-md-5"> <strong> Facsimile: </strong> </div> <div class="col-md-7"> (418) 832-7180 </div> </div> <div class="row mrgn-lft-md"> <div class="col-md-5"> <strong> Email: </strong> </div> <div class="col-md-7"> [email protected] </div> </div> </section> </details> <details id="details-panel3"> <summary> Description </summary> <h2 class="wb-invisible"> Company description </h2> <section class="container-fluid"> <div class="row"> <div class="col-md-5"> <strong> Country of Ownership: </strong> </div> <div class="col-md-7"> Canada &nbsp; </div> </div> <div class="row"> <div class="col-md-5"> <strong> Year Established: </strong> </div> <div class="col-md-7"> 1971 </div> </div> <div class="row"> <div class="col-md-5"> <strong> Exporting: </strong> </div> <div class="col-md-7"> No &nbsp; </div> </div> <div class="row"> <div class="col-md-5"> <strong> Primary Industry (NAICS): </strong> </div> <div class="col-md-7"> 541370 - Surveying and Mapping (except Geophysical) Services </div> </div> <div class="row"> <div class="col-md-5"> <strong> Primary Business Activity: </strong> </div> <div class="col-md-7"> Services &nbsp; </div> </div> <div class="row"> <div class="col-md-5"> <strong> Number of Employees: </strong> </div> <div class="col-md-7"> 12&nbsp; </div> </div> </section> </details> <details id="details-panel4"> <summary> Products, services and licensing </summary> <h2 class="wb-invisible"> Product / Service / Licensing </h2> <section class="container-fluid"> <div class="row mrgn-bttm-md"> <div class="col-md-3"> <strong> Service Name: </strong> </div> <div class="col-md-9"> Land surveying <br> </div> </div> </section> </details> </div> </div> <div class="row"> <div class="col-md-12 text-right"> Last Update Date 2017-03-03 </div> </div> <!-- - Artifact ID: CBW - IMBS - CCC Search WAR - Group ID: ca.gc.ic.strategis.imbs.ccc.search - Version: 3.26 - Built-By: bamboo - Build Timestamp: 2017-03-02T21:29:28Z --> <!-- End Body Content --> <!-- Begin Body Foot --> <!-- End Body Foot --> <!-- END MAIN TABLE --> <!-- End body --> <!-- Begin footer --> <div class="row pagedetails"> <div class="col-sm-5 col-xs-12 datemod"> <dl id="wb-dtmd"> <dt class=" hidden-print">Date Modified:</dt> <dd class=" hidden-print"> <span><time>2017-03-02</time></span> </dd> </dl> </div> <div class="clear visible-xs"></div> <div class="col-sm-4 col-xs-6"> </div> <div class="col-sm-3 col-xs-6 text-right"> </div> <div class="clear visible-xs"></div> </div> </main> <footer role="contentinfo" id="wb-info"> <nav role="navigation" class="container wb-navcurr"> <h2 class="wb-inv">About government</h2> <!-- EPIC FOOTER BEGIN --> <!-- EPI-11638 Contact us --> <ul class="list-unstyled colcount-sm-2 colcount-md-3"> <li><a href="http://www.ic.gc.ca/eic/site/icgc.nsf/eng/h_07026.html#pageid=E048-H00000&amp;from=Industries">Contact us</a></li> <li><a href="https://www.canada.ca/en/government/dept.html">Departments and agencies</a></li> <li><a href="https://www.canada.ca/en/government/publicservice.html">Public service and military</a></li> <li><a href="https://www.canada.ca/en/news.html">News</a></li> <li><a href="https://www.canada.ca/en/government/system/laws.html">Treaties, laws and regulations</a></li> <li><a href="https://www.canada.ca/en/transparency/reporting.html">Government-wide reporting</a></li> <li><a href="http://pm.gc.ca/eng">Prime Minister</a></li> <li><a href="https://www.canada.ca/en/government/system.html">How government works</a></li> <li><a href="http://open.canada.ca/en/">Open government</a></li> </ul> </nav> <div class="brand"> <div class="container"> <div class="row"> <nav class="col-md-10 ftr-urlt-lnk"> <h2 class="wb-inv">About this site</h2> <ul> <li><a href="https://www.canada.ca/en/social.html">Social media</a></li> <li><a href="https://www.canada.ca/en/mobile.html">Mobile applications</a></li> <li><a href="http://www1.canada.ca/en/newsite.html">About Canada.ca</a></li> <li><a href="http://www.ic.gc.ca/eic/site/icgc.nsf/eng/h_07033.html">Terms and conditions</a></li> <li><a href="http://www.ic.gc.ca/eic/site/icgc.nsf/eng/h_07033.html#p1">Privacy</a></li> </ul> </nav> <div class="col-xs-6 visible-sm visible-xs tofpg"> <a href="#wb-cont">Top of Page <span class="glyphicon glyphicon-chevron-up"></span></a> </div> <div class="col-xs-6 col-md-2 text-right"> <object type="image/svg+xml" tabindex="-1" role="img" data="/utils/scripts/_WET_4-0/apps/themes-dist/gcweb/assets/wmms-blk.svg" aria-label="Symbol of the Government of Canada"></object> </div> </div> </div> </div> </footer> <!--[if gte IE 9 | !IE ]><!--> <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <script src="/utils/scripts/_WET_4-0/apps/themes-dist/gcweb/js/wet-boew.min.js"></script> <!--<![endif]--> <!--[if lt IE 9]> <script src="/utils/scripts/_WET_4-0/apps/themes-dist/gcweb/js/ie8-wet-boew2.min.js"></script> <![endif]--> <script src="/utils/scripts/_WET_4-0/apps/themes-dist/gcweb/js/theme.min.js"></script> <!-- EPI-10519 --> <span class="wb-sessto" data-wb-sessto='{"inactivity": 1800000, "reactionTime": 180000, "sessionalive": 1800000, "logouturl": "/app/ccc/srch/cccSrch.do?lang=eng&prtl=1"}'></span> <script src="/eic/home.nsf/js/jQuery.externalOpensInNewWindow.js"></script> <!-- EPI-11190 - Webtrends --> <script src="/eic/home.nsf/js/webtrends.js"></script> <script>var endTime = new Date();</script> <noscript> <div><img alt="" id="DCSIMG" width="1" height="1" src="//wt-sdc.ic.gc.ca/dcs6v67hwe0ei7wsv8g9fv50d_3k6i/njs.gif?dcsuri=/nojavascript&amp;WT.js=No&amp;WT.tv=9.4.0&amp;dcssip=www.ic.gc.ca"/></div> </noscript> <!-- /Webtrends --> <!-- JS deps --> <script src="/eic/home.nsf/js/jquery.imagesloaded.js"></script> <!-- EPI-11262 - Util JS --> <script src="/eic/home.nsf/js/_WET_4-0_utils_canada.min.js"></script> <!-- EPI-11383 --> <script src="/eic/home.nsf/js/jQuery.icValidationErrors.js"></script> <span style="display:none;" id='app-info' data-project-groupid='' data-project-artifactid='' data-project-version='' data-project-build-timestamp='' data-issue-tracking='' data-scm-sha1='' data-scm-sha1-abbrev='' data-scm-branch='' data-scm-commit-date=''></span> </body></html> <!-- End Footer --> <!-- - Artifact ID: CBW - IMBS - CCC Search WAR - Group ID: ca.gc.ic.strategis.imbs.ccc.search - Version: 3.26 - Built-By: bamboo - Build Timestamp: 2017-03-02T21:29:28Z -->
GoC-Spending/data-corporations
html/123456225077.html
HTML
mit
34,161
# What is fakeLoader.js fakeLoader.js is a lightweight jQuery plugin that helps you create an animated spinner with a fullscreen loading mask to simulate the page preloading effect. Check out the demo [http://joaopereirawd.github.io/fakeLoader.js/](http://joaopereirawd.github.io/fakeLoader.js) ## Current Version `V2.0.0` ### 1. Installing ```js yarn add jq-fakeloader or npm i jq-fakeloader ``` ### 2. Include CSS ```css <link rel="stylesheet" href="../node_modules/dist/fakeLoader.min.css"> ``` ### 3. Include `javascript` dependencies ``` <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"> <script src="../node_modules/dist/fakeLoader.min.js"> ``` ### 4. Include `fakeLoader` placeholder in the HTML Document ``` <div class="fakeLoader"></div> ``` ### 5. Basic Initialize ```js <script> $.fakeLoader(); </script> ``` ### 6. Options `timeToHide` //Time in milliseconds for fakeLoader disappear `spinner` //'spinner1', 'spinner2', 'spinner3', 'spinner4', 'spinner5', 'spinner6', 'spinner7' `bgColor` //Hex, RGB or RGBA colors ### Support If you encounter an issue or want to request a feature, you can create an [issue](https://github.com/joaopereirawd/fakeLoader.js/issues)
joaopereirawd/fakeLoader.js
README.md
Markdown
mit
1,232
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv="Content-Type" content="text/xhtml;charset=UTF-8"/> <meta http-equiv="X-UA-Compatible" content="IE=9"/> <meta name="generator" content="Doxygen 1.8.13"/> <meta name="viewport" content="width=device-width, initial-scale=1"/> <title>alternative Standard Libary: Elementverzeichnis</title> <link href="../../tabs.css" rel="stylesheet" type="text/css"/> <script type="text/javascript" src="../../jquery.js"></script> <script type="text/javascript" src="../../dynsections.js"></script> <link href="../../navtree.css" rel="stylesheet" type="text/css"/> <script type="text/javascript" src="../../resize.js"></script> <script type="text/javascript" src="../../navtreedata.js"></script> <script type="text/javascript" src="../../navtree.js"></script> <script type="text/javascript"> $(document).ready(initResizable); </script> <link href="../../doxygen.css" rel="stylesheet" type="text/css" /> </head> <body> <div id="top"><!-- do not remove this div, it is closed by doxygen! --> <div id="titlearea"> <table cellspacing="0" cellpadding="0"> <tbody> <tr style="height: 56px;"> <td id="projectlogo"><img alt="Logo" src="../../Logo128x128.png"/></td> <td id="projectalign" style="padding-left: 0.5em;"> <div id="projectname">alternative Standard Libary &#160;<span id="projectnumber">0.29.8</span> </div> </td> </tr> </tbody> </table> </div> <!-- end header part --> <!-- Erzeugt von Doxygen 1.8.13 --> <script type="text/javascript" src="../../menudata.js"></script> <script type="text/javascript" src="../../menu.js"></script> <script type="text/javascript"> $(function() { initMenu('../../',false,false,'search.php','Suchen'); }); </script> <div id="main-nav"></div> </div><!-- top --> <div id="side-nav" class="ui-resizable side-nav-resizable"> <div id="nav-tree"> <div id="nav-tree-contents"> <div id="nav-sync" class="sync"></div> </div> </div> <div id="splitbar" style="-moz-user-select:none;" class="ui-resizable-handle"> </div> </div> <script type="text/javascript"> $(document).ready(function(){initNavTree('da/d13/classstd_1_1_sys.html','../../');}); </script> <div id="doc-content"> <div class="header"> <div class="headertitle"> <div class="title">std::Sys Elementverzeichnis</div> </div> </div><!--header--> <div class="contents"> <p>Vollständige Aufstellung aller Elemente für <a class="el" href="../../da/d13/classstd_1_1_sys.html">std::Sys</a> einschließlich aller geerbten Elemente.</p> <table class="directory"> <tr class="even"><td class="entry"><a class="el" href="../../da/d13/classstd_1_1_sys.html#ac9f240e055773c6ef6b320ed3d9f3acf">fClose</a>(void *file)</td><td class="entry"><a class="el" href="../../da/d13/classstd_1_1_sys.html">std::Sys</a></td><td class="entry"><span class="mlabel">static</span></td></tr> <tr><td class="entry"><a class="el" href="../../da/d13/classstd_1_1_sys.html#ac9cb96093b35fe96793d756c2888a1f1">fEOF</a>(void *file)</td><td class="entry"><a class="el" href="../../da/d13/classstd_1_1_sys.html">std::Sys</a></td><td class="entry"><span class="mlabel">static</span></td></tr> <tr class="even"><td class="entry"><a class="el" href="../../da/d13/classstd_1_1_sys.html#a8fd94047f1bedca9a81b335874d2733a">fError</a>(void *file)</td><td class="entry"><a class="el" href="../../da/d13/classstd_1_1_sys.html">std::Sys</a></td><td class="entry"><span class="mlabel">static</span></td></tr> <tr><td class="entry"><a class="el" href="../../da/d13/classstd_1_1_sys.html#a610720c05d13d45ac5f1ad892feaef7f">fFlush</a>(void *file)</td><td class="entry"><a class="el" href="../../da/d13/classstd_1_1_sys.html">std::Sys</a></td><td class="entry"><span class="mlabel">static</span></td></tr> <tr class="even"><td class="entry"><a class="el" href="../../da/d13/classstd_1_1_sys.html#ae69ad2e413c751ae56644ccf69daba3a">fGetc</a>(void *file)</td><td class="entry"><a class="el" href="../../da/d13/classstd_1_1_sys.html">std::Sys</a></td><td class="entry"><span class="mlabel">static</span></td></tr> <tr><td class="entry"><a class="el" href="../../da/d13/classstd_1_1_sys.html#a6e4d49f77b2b856c91a44a38b64c1d53">fIsFile</a>(const char *file)</td><td class="entry"><a class="el" href="../../da/d13/classstd_1_1_sys.html">std::Sys</a></td><td class="entry"><span class="mlabel">static</span></td></tr> <tr class="even"><td class="entry"><a class="el" href="../../da/d13/classstd_1_1_sys.html#aee6ea3afc7237d4234b5bc43dc3231c6">fOpen</a>(const char *file, const char *fmt)</td><td class="entry"><a class="el" href="../../da/d13/classstd_1_1_sys.html">std::Sys</a></td><td class="entry"><span class="mlabel">static</span></td></tr> <tr><td class="entry"><a class="el" href="../../da/d13/classstd_1_1_sys.html#a025c18bdd6a88e4d26482d10429a95ec">fPrintf</a>(void *file, const char *str)</td><td class="entry"><a class="el" href="../../da/d13/classstd_1_1_sys.html">std::Sys</a></td><td class="entry"><span class="mlabel">static</span></td></tr> <tr class="even"><td class="entry"><a class="el" href="../../da/d13/classstd_1_1_sys.html#a2f3038727c96c808d92532b62382e037">fPutc</a>(int c, void *file)</td><td class="entry"><a class="el" href="../../da/d13/classstd_1_1_sys.html">std::Sys</a></td><td class="entry"><span class="mlabel">static</span></td></tr> <tr><td class="entry"><a class="el" href="../../da/d13/classstd_1_1_sys.html#a27592f565d19984eac4e5c16dbb52429">fPuts</a>(const char *str, void *file)</td><td class="entry"><a class="el" href="../../da/d13/classstd_1_1_sys.html">std::Sys</a></td><td class="entry"><span class="mlabel">static</span></td></tr> <tr class="even"><td class="entry"><a class="el" href="../../da/d13/classstd_1_1_sys.html#a8e07d03fdef76804b9a6eea7e97e1035">fRead</a>(void *data, const int count, const int size, void *file)</td><td class="entry"><a class="el" href="../../da/d13/classstd_1_1_sys.html">std::Sys</a></td><td class="entry"><span class="mlabel">static</span></td></tr> <tr><td class="entry"><a class="el" href="../../da/d13/classstd_1_1_sys.html#ac14981aad284603b985b1e6470843e88">fSeek</a>(void *file, int off, int org)</td><td class="entry"><a class="el" href="../../da/d13/classstd_1_1_sys.html">std::Sys</a></td><td class="entry"><span class="mlabel">static</span></td></tr> <tr class="even"><td class="entry"><a class="el" href="../../da/d13/classstd_1_1_sys.html#aca38e582c676c1087650aef98c7c0543">fTell</a>(void *file)</td><td class="entry"><a class="el" href="../../da/d13/classstd_1_1_sys.html">std::Sys</a></td><td class="entry"><span class="mlabel">static</span></td></tr> <tr><td class="entry"><a class="el" href="../../da/d13/classstd_1_1_sys.html#a8032132dd583eb289416a1b19ce85e37">fWrite</a>(void *data, const int count, const int size, void *file)</td><td class="entry"><a class="el" href="../../da/d13/classstd_1_1_sys.html">std::Sys</a></td><td class="entry"><span class="mlabel">static</span></td></tr> <tr class="even"><td class="entry"><a class="el" href="../../da/d13/classstd_1_1_sys.html#a3ae3057f26fbb3e72e4a8af62efdf5c6">mAlloc</a>(size_t size)</td><td class="entry"><a class="el" href="../../da/d13/classstd_1_1_sys.html">std::Sys</a></td><td class="entry"><span class="mlabel">static</span></td></tr> <tr><td class="entry"><a class="el" href="../../da/d13/classstd_1_1_sys.html#a04e4cc78efb94cd4b50162d1637288ae">mAllocE</a>(int elements)</td><td class="entry"><a class="el" href="../../da/d13/classstd_1_1_sys.html">std::Sys</a></td><td class="entry"><span class="mlabel">inline</span><span class="mlabel">static</span></td></tr> <tr class="even"><td class="entry"><a class="el" href="../../da/d13/classstd_1_1_sys.html#a9c9c270714511ce17ca1ffd134597907">MemCpy</a>(void *to, const void *from, size_t bytes)</td><td class="entry"><a class="el" href="../../da/d13/classstd_1_1_sys.html">std::Sys</a></td><td class="entry"><span class="mlabel">static</span></td></tr> <tr><td class="entry"><a class="el" href="../../da/d13/classstd_1_1_sys.html#abf561c077094bd7b266b7734c73e66da">MemMove</a>(void *to, const void *from, size_t bytes)</td><td class="entry"><a class="el" href="../../da/d13/classstd_1_1_sys.html">std::Sys</a></td><td class="entry"><span class="mlabel">static</span></td></tr> <tr class="even"><td class="entry"><a class="el" href="../../da/d13/classstd_1_1_sys.html#ad5bfc790ccaf985e62ad98da9c947ab0">MemSet</a>(void *buf, unsigned char value, size_t bytes)</td><td class="entry"><a class="el" href="../../da/d13/classstd_1_1_sys.html">std::Sys</a></td><td class="entry"><span class="mlabel">static</span></td></tr> <tr><td class="entry"><a class="el" href="../../da/d13/classstd_1_1_sys.html#a9a9b2d41667f1c106815c6f9edc698fc">mFree</a>(void *mem)</td><td class="entry"><a class="el" href="../../da/d13/classstd_1_1_sys.html">std::Sys</a></td><td class="entry"><span class="mlabel">static</span></td></tr> <tr class="even"><td class="entry"><a class="el" href="../../da/d13/classstd_1_1_sys.html#a0d71e77caef7d86e01af361b1cb13353">mReAlloc</a>(void *old, size_t newSize)</td><td class="entry"><a class="el" href="../../da/d13/classstd_1_1_sys.html">std::Sys</a></td><td class="entry"><span class="mlabel">static</span></td></tr> <tr><td class="entry"><a class="el" href="../../da/d13/classstd_1_1_sys.html#ac4f3ff28de45a311f03a1e72af0c15f9">mutex_init_t</a> enum-Bezeichner</td><td class="entry"><a class="el" href="../../da/d13/classstd_1_1_sys.html">std::Sys</a></td><td class="entry"></td></tr> <tr class="even"><td class="entry"><a class="el" href="../../da/d13/classstd_1_1_sys.html#af9f019109cea02d650c0da099f1d70a2">mutex_type</a> typedef</td><td class="entry"><a class="el" href="../../da/d13/classstd_1_1_sys.html">std::Sys</a></td><td class="entry"></td></tr> <tr><td class="entry"><a class="el" href="../../da/d13/classstd_1_1_sys.html#abfb1f1b9ac68790344334a2200e8021c">mutexDestroy</a>(mutex_type *mutex)</td><td class="entry"><a class="el" href="../../da/d13/classstd_1_1_sys.html">std::Sys</a></td><td class="entry"><span class="mlabel">static</span></td></tr> <tr class="even"><td class="entry"><a class="el" href="../../da/d13/classstd_1_1_sys.html#a6c0d6b0dc8bbe584027581f446d4279d">mutexInit</a>(mutex_type *mutex, mutex_init_t type=mutex_init_t::Normal, bool shared=false, bool robust=false)</td><td class="entry"><a class="el" href="../../da/d13/classstd_1_1_sys.html">std::Sys</a></td><td class="entry"><span class="mlabel">static</span></td></tr> <tr><td class="entry"><a class="el" href="../../da/d13/classstd_1_1_sys.html#acef59477c62a5153727cba3626c5e259">mutexLock</a>(mutex_type *mutex)</td><td class="entry"><a class="el" href="../../da/d13/classstd_1_1_sys.html">std::Sys</a></td><td class="entry"><span class="mlabel">static</span></td></tr> <tr class="even"><td class="entry"><a class="el" href="../../da/d13/classstd_1_1_sys.html#abe695d31d915cdc7c2476bfbeae35a0e">mutexTryLock</a>(mutex_type *mutex)</td><td class="entry"><a class="el" href="../../da/d13/classstd_1_1_sys.html">std::Sys</a></td><td class="entry"><span class="mlabel">static</span></td></tr> <tr><td class="entry"><a class="el" href="../../da/d13/classstd_1_1_sys.html#a7221035092b3fa10172d60c821a1064a">mutexUnLock</a>(mutex_type *mutex)</td><td class="entry"><a class="el" href="../../da/d13/classstd_1_1_sys.html">std::Sys</a></td><td class="entry"><span class="mlabel">static</span></td></tr> <tr class="even"><td class="entry"><a class="el" href="../../da/d13/classstd_1_1_sys.html#a2fa77232e349020516438ac4940e8f1a">pTotalMem</a>()</td><td class="entry"><a class="el" href="../../da/d13/classstd_1_1_sys.html">std::Sys</a></td><td class="entry"><span class="mlabel">static</span></td></tr> <tr><td class="entry"><a class="el" href="../../da/d13/classstd_1_1_sys.html#a19eaed4ae0cf3ec1e333b6f9901d67a7">spinlk_type</a> typedef</td><td class="entry"><a class="el" href="../../da/d13/classstd_1_1_sys.html">std::Sys</a></td><td class="entry"></td></tr> <tr class="even"><td class="entry"><a class="el" href="../../da/d13/classstd_1_1_sys.html#a3e7ba115ebb0f563e37927cfb7e85344">spinlockDestroy</a>(spinlk_type *mutex)</td><td class="entry"><a class="el" href="../../da/d13/classstd_1_1_sys.html">std::Sys</a></td><td class="entry"><span class="mlabel">static</span></td></tr> <tr><td class="entry"><a class="el" href="../../da/d13/classstd_1_1_sys.html#a65e031f3724520464f9a98dc7bb48e9e">spinlockInit</a>(spinlk_type *mutex, const void *attr)</td><td class="entry"><a class="el" href="../../da/d13/classstd_1_1_sys.html">std::Sys</a></td><td class="entry"><span class="mlabel">static</span></td></tr> <tr class="even"><td class="entry"><a class="el" href="../../da/d13/classstd_1_1_sys.html#abcb5c5bcc747c46c3670944a327727af">spinlockLock</a>(spinlk_type *mutex)</td><td class="entry"><a class="el" href="../../da/d13/classstd_1_1_sys.html">std::Sys</a></td><td class="entry"><span class="mlabel">static</span></td></tr> <tr><td class="entry"><a class="el" href="../../da/d13/classstd_1_1_sys.html#a9453448f147d0c2d83187ec2c8033089">spinlockTryLock</a>(spinlk_type *mutex)</td><td class="entry"><a class="el" href="../../da/d13/classstd_1_1_sys.html">std::Sys</a></td><td class="entry"><span class="mlabel">static</span></td></tr> <tr class="even"><td class="entry"><a class="el" href="../../da/d13/classstd_1_1_sys.html#ae408c7a7438d031c7c853229a31eff63">spinlockUnLock</a>(spinlk_type *mutex)</td><td class="entry"><a class="el" href="../../da/d13/classstd_1_1_sys.html">std::Sys</a></td><td class="entry"><span class="mlabel">static</span></td></tr> <tr><td class="entry"><a class="el" href="../../da/d13/classstd_1_1_sys.html#a478df7ee0c293a50d589680380c9cbfc">vsnPrintf</a>(char *buffer, size_t count, const char *format, va_list argptr)</td><td class="entry"><a class="el" href="../../da/d13/classstd_1_1_sys.html">std::Sys</a></td><td class="entry"><span class="mlabel">static</span></td></tr> <tr class="even"><td class="entry"><a class="el" href="../../da/d13/classstd_1_1_sys.html#aac49efae5fffa0c4ab9fd88060b8f218">wMemCpy</a>(void *to, const void *from, size_t bytes)</td><td class="entry"><a class="el" href="../../da/d13/classstd_1_1_sys.html">std::Sys</a></td><td class="entry"><span class="mlabel">static</span></td></tr> <tr><td class="entry"><a class="el" href="../../da/d13/classstd_1_1_sys.html#a3979b4517ff8cad46e14abf65d9604cc">wMemMove</a>(void *to, const void *from, size_t bytes)</td><td class="entry"><a class="el" href="../../da/d13/classstd_1_1_sys.html">std::Sys</a></td><td class="entry"><span class="mlabel">static</span></td></tr> <tr class="even"><td class="entry"><a class="el" href="../../da/d13/classstd_1_1_sys.html#a7df3f8541dc4ba26336983134b6772d3">wMemSet</a>(void *buf, unsigned char value, size_t bytes)</td><td class="entry"><a class="el" href="../../da/d13/classstd_1_1_sys.html">std::Sys</a></td><td class="entry"><span class="mlabel">static</span></td></tr> </table></div><!-- contents --> </div><!-- doc-content --> <!-- start footer part --> <div id="nav-path" class="navpath"><!-- id is needed for treeview function! --> <ul> <li class="footer">Erzeugt von <a href="http://www.doxygen.org/index.html"> <img class="footer" src="../../doxygen.png" alt="doxygen"/></a> 1.8.13 </li> </ul> </div> </body> </html>
RoseLeBlood/aSTL
docs/html/da/d52/classstd_1_1_sys-members.html
HTML
mit
15,410
var ExtractTextPlugin = require("extract-text-webpack-plugin"); var HtmlWebpackPlugin = require("html-webpack-plugin"); var path = require("path"); var webpack = require("webpack"); var projectTemplatesRoot = "../../ppb/templates/"; module.exports = { context: path.resolve(__dirname, "src"), entry: { app: "./js/main.js" }, output: { path: path.resolve(__dirname, "dist"), filename: "js/site.js?[hash]", publicPath: "/site_media/static" }, module: { loaders: [ { test: /\.(gif|png|ico|jpg|svg)$/, include: [ path.resolve(__dirname, "src/images") ], loader: "file-loader?name=/images/[name].[ext]" }, { test: /\.less$/, loader: ExtractTextPlugin.extract("style-loader", "css-loader!less-loader") }, { test: /\.(woff|woff2|ttf|eot|svg)(\?v=[0-9]\.[0-9]\.[0-9])?$/, include: [ path.resolve(__dirname, "/src/fonts"), path.resolve(__dirname, "../node_modules") ], loader: "file-loader?name=/fonts/[name].[ext]?[hash]" }, { test: /\.jsx?$/, loader: "babel-loader", query: {compact: false} }, ] }, resolve: { extensions: ["", ".js", ".jsx"], }, plugins: [ new webpack.IgnorePlugin(/^\.\/locale$/, /moment$/), new ExtractTextPlugin("css/site.css?[hash]"), new HtmlWebpackPlugin({ filename: projectTemplatesRoot + "_styles.html", templateContent: function(templateParams, compilation) { var link = ""; for (var css in templateParams.htmlWebpackPlugin.files.css) { link += "<link href='" + templateParams.htmlWebpackPlugin.files.css[css] + "' rel='stylesheet' />\n" } return link; } }), new HtmlWebpackPlugin({ filename: projectTemplatesRoot + "_scripts.html", templateContent: function(templateParams, compilation) { var script = ""; for (var js in templateParams.htmlWebpackPlugin.files.js) { script += "<script src='" + templateParams.htmlWebpackPlugin.files.js[js] + "'></script>\n" } return script; } }) ] };
pinax/blog.pinaxproject.com
static/webpack.config.js
JavaScript
mit
2,456
var h = require('hyperscript') var human = require('human-time') exports.needs = {} exports.gives = 'message_meta' exports.create = function () { function updateTimestampEl(el) { el.firstChild.nodeValue = human(new Date(el.timestamp)) return el } setInterval(function () { var els = [].slice.call(document.querySelectorAll('.timestamp')) els.forEach(updateTimestampEl) }, 60e3) return function (msg) { return updateTimestampEl(h('a.enter.timestamp', { href: '#'+msg.key, timestamp: msg.value.timestamp, title: new Date(msg.value.timestamp) }, '')) } }
cryptix/talebay
modules_basic/timestamp.js
JavaScript
mit
613
import { HookContext, Application, createContext, getServiceOptions } from '@feathersjs/feathers'; import { NotFound, MethodNotAllowed, BadRequest } from '@feathersjs/errors'; import { createDebug } from '@feathersjs/commons'; import isEqual from 'lodash/isEqual'; import { CombinedChannel } from '../channels/channel/combined'; import { RealTimeConnection } from '../channels/channel/base'; const debug = createDebug('@feathersjs/transport-commons'); export const DEFAULT_PARAMS_POSITION = 1; export const paramsPositions: { [key: string]: number } = { find: 0, update: 2, patch: 2 }; export function normalizeError (e: any) { const hasToJSON = typeof e.toJSON === 'function'; const result = hasToJSON ? e.toJSON() : {}; if (!hasToJSON) { Object.getOwnPropertyNames(e).forEach(key => { result[key] = e[key]; }); } if (process.env.NODE_ENV === 'production') { delete result.stack; } delete result.hook; return result; } export function getDispatcher (emit: string, socketMap: WeakMap<RealTimeConnection, any>, socketKey?: any) { return function (event: string, channel: CombinedChannel, context: HookContext, data?: any) { debug(`Dispatching '${event}' to ${channel.length} connections`); channel.connections.forEach(connection => { // The reference between connection and socket is set in `app.setup` const socket = socketKey ? connection[socketKey] : socketMap.get(connection); if (socket) { const eventName = `${context.path || ''} ${event}`.trim(); let result = channel.dataFor(connection) || context.dispatch || context.result; // If we are getting events from an array but try to dispatch individual data // try to get the individual item to dispatch from the correct index. if (!Array.isArray(data) && Array.isArray(context.result) && Array.isArray(result)) { result = context.result.find(resultData => isEqual(resultData, data)); } debug(`Dispatching '${eventName}' to Socket ${socket.id} with`, result); socket[emit](eventName, result); } }); }; } export async function runMethod (app: Application, connection: RealTimeConnection, path: string, method: string, args: any[]) { const trace = `method '${method}' on service '${path}'`; const methodArgs = args.slice(0); const callback = typeof methodArgs[methodArgs.length - 1] === 'function' ? methodArgs.pop() : function () {}; debug(`Running ${trace}`, connection, args); const handleError = (error: any) => { debug(`Error in ${trace}`, error); callback(normalizeError(error)); }; try { const lookup = app.lookup(path); // No valid service was found throw a NotFound error if (lookup === null) { throw new NotFound(`Service '${path}' not found`); } const { service, params: route = {} } = lookup; const { methods } = getServiceOptions(service); // Only service methods are allowed if (!methods.includes(method)) { throw new MethodNotAllowed(`Method '${method}' not allowed on service '${path}'`); } const position = paramsPositions[method] !== undefined ? paramsPositions[method] : DEFAULT_PARAMS_POSITION; const query = methodArgs[position] || {}; // `params` have to be re-mapped to the query and added with the route const params = Object.assign({ query, route, connection }, connection); // `params` is always the last parameter. Error if we got more arguments. if (methodArgs.length > (position + 1)) { throw new BadRequest(`Too many arguments for '${method}' method`); } methodArgs[position] = params; const ctx = createContext(service, method); const returnedCtx: HookContext = await (service as any)[method](...methodArgs, ctx); const result = returnedCtx.dispatch || returnedCtx.result; debug(`Returned successfully ${trace}`, result); callback(null, result); } catch (error: any) { handleError(error); } }
feathersjs/feathers
packages/transport-commons/src/socket/utils.ts
TypeScript
mit
3,996
/* * Generated by class-dump 3.3.4 (64 bit). * * class-dump is Copyright (C) 1997-1998, 2000-2001, 2004-2011 by Steve Nygard. */ #import <CoreData/NSSQLIntermediate.h> // Not exported @interface NSSQLLimitIntermediate : NSSQLIntermediate { unsigned long long _limit; } - (id)generateSQLStringInContext:(id)arg1; - (id)initWithLimit:(unsigned long long)arg1 inScope:(id)arg2; @end
matthewsot/CocoaSharp
Headers/Frameworks/CoreData/NSSQLLimitIntermediate.h
C
mit
401
version https://git-lfs.github.com/spec/v1 oid sha256:e40a08695f05163cfb0eaeeef4588fcfad55a6576cfadfb079505495605beb33 size 27133
yogeshsaroya/new-cdnjs
ajax/libs/fuelux/2.5.0/datepicker.js
JavaScript
mit
130
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta http-equiv="X-UA-Compatible" content="ie=edge"> <title>Stranger Things Wall</title> <link rel="stylesheet" href="css/styles.css" /> </head> <body> <img src="img/vacio.gif" alt="" id="img" class="img"/> <p class="txt">Presiona una tecla</p> <script src="js/script.js"></script> </body> </html>
chepegeek/stranger-things
index.html
HTML
mit
441
<?php class Thread extends Eloquent { public static $table = 'threads'; public static $timestamps = true; public function replies() { return $this->has_many('Reply'); } }
hassan-c/laravelapp
application/models/thread.php
PHP
mit
193
<html> <head> <meta charset="utf-8"/> <meta http-equiv="X-UA-Compatible" content="IE=Edge"/> <title>Blog | Guilherme Matheus Costa</title> <meta name="viewport" content="width=device-width, initial-scale=1"/> <link href="/css/essentials.min.css" rel="stylesheet" type="text/css"/> <meta property="og:site_name" content="Guilherme Matheus Costa"/> </head> <body> <h1>Guilherme Matheus Costa</h1> <h2>Resume</h2> </body> </html>
GuilhermeMatheus/GuilhermeMatheus.github.io
pages/resume.html
HTML
mit
467
#!/usr/bin/env python from hdf5handler import HDF5Handler handler = HDF5Handler('mydata.hdf5') handler.open() for i in range(100): handler.put(i, 'numbers') handler.close()
iambernie/hdf5handler
examples/opening.py
Python
mit
183
/** * The MIT License (MIT) * * Copyright (c) 2015 Famous Industries Inc. * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ 'use strict'; import { Geometry } from '../Geometry'; import { GeometryHelper } from '../GeometryHelper'; /** * This function generates custom buffers and passes them to * a new static geometry, which is returned to the user. * * @class Tetrahedron * @constructor * * @param {Object} options Parameters that alter the * vertex buffers of the generated geometry. * * @return {Object} constructed geometry */ class Tetrahedron extends Geometry { constructor(options) { //handled by es6 transpiler //if (!(this instanceof Tetrahedron)) return new Tetrahedron(options); var textureCoords = []; var normals = []; var detail; var i; var t = Math.sqrt(3); var vertices = [ // Back 1, -1, -1 / t, -1, -1, -1 / t, 0, 1, 0, // Right 0, 1, 0, 0, -1, t - 1 / t, 1, -1, -1 / t, // Left 0, 1, 0, -1, -1, -1 / t, 0, -1, t - 1 / t, // Bottom 0, -1, t - 1 / t, -1, -1, -1 / t, 1, -1, -1 / t ]; var indices = [ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11 ]; for (i = 0; i < 4; i++) { textureCoords.push( 0.0, 0.0, 0.5, 1.0, 1.0, 0.0 ); } options = options || {}; while (--detail) GeometryHelper.subdivide(indices, vertices, textureCoords); normals = GeometryHelper.computeNormals(vertices, indices); options.buffers = [ { name: 'a_pos', data: vertices }, { name: 'a_texCoord', data: textureCoords, size: 2 }, { name: 'a_normals', data: normals }, { name: 'indices', data: indices, size: 1 } ]; super(options); } } export { Tetrahedron };
talves/famous-engine
src/webgl-geometries/primitives/Tetrahedron.js
JavaScript
mit
2,960
/* * Copyright 2016 Christoph Brill <[email protected]> * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ using System; using System.Collections.Generic; using System.Diagnostics; using System.IO; using System.Linq; using System.Reflection; using System.Text; using libldt3.attributes; using libldt3.model.enums; using libldt3.model.regel; using libldt3.model.regel.kontext; using libldt3.model.saetze; using NodaTime; namespace libldt3 { /** * Simple, reflection and annotation based reader for LDT 3.0. * * @author Christoph Brill &lt;[email protected]&gt; */ public class LdtReader { readonly IDictionary<Type, Regel> regelCache = new Dictionary<Type, Regel>(); readonly LdtConstants.Mode mode; public LdtReader(LdtConstants.Mode mode) { this.mode = mode; } /** * Read the LDT found on a given path. * * @param path * the path of the LDT file (any format handled by NIO * {@link Path}) * @return the list of Satz elements found in the LDT file * @throws IOException * thrown if reading the file failed */ public IList<Satz> Read(string path) { using (var f = File.Open(path, FileMode.Open)) { return Read(f); } } /** * Read the LDT found on a given path. * * @param path * the path of the LDT file * @return the list of Satz elements found in the LDT file * @throws IOException * thrown if reading the file failed */ public IList<Satz> Read(FileStream path) { var stream = new StreamReader(path, Encoding.GetEncoding("ISO-8859-1")); return Read(stream); } /** * Read the LDT from a given string stream. * * @param stream * the LDT lines as string stream * @return the list of Satz elements found in the LDT file */ public IList<Satz> Read(StreamReader stream) { Stack<object> stack = new Stack<object>(); IList<Satz> data = new List<Satz>(); string line; int integer = 0; while ((line = stream.ReadLine()) != null) { HandleInput(line, stack, data, integer++); } return data; } void HandleInput(string line, Stack<object> stack, IList<Satz> data, int lineNo) { Trace.TraceInformation("Reading line {0}", line); // Check if the line meets the minimum requirements (3 digits for // length, 4 digits for the identifier) if (line.Length < 7) { if (mode == LdtConstants.Mode.STRICT) { throw new ArgumentException("Line '" + line + "' (" + lineNo + ") was less than 7 characters, aborting"); } else { Trace.TraceInformation("Line '{0}' ({1}) was less than 7 characters, continuing anyway", line, lineNo); } } // Read the length and check whether it had the correct length int length = int.Parse(line.Substring(0, 3)); if (length != line.Length + 2) { if (mode == LdtConstants.Mode.STRICT) { throw new ArgumentException( "Line '" + line + "' (" + lineNo + ") should have length " + (line.Length + 2) + ", but was " + length); } else { Trace.TraceInformation("Line '{0}' ({1}) should have length {2}, but was {3}. Ignoring specified length", line, lineNo, (line.Length + 2), length); length = line.Length + 2; } } // Read identifier and payload string identifier = line.Substring(3, 7 - 3); string payload = line.Substring(7, length - 2 - 7); switch (identifier) { case "8000": { // Start: Satz AssureLength(line, length, 13); if (stack.Count > 0) { if (mode == LdtConstants.Mode.STRICT) { throw new InvalidOperationException( "Stack must be empty when starting a new Satz, but was " + stack.Count + " long"); } else { Trace.TraceInformation("Stack must be empty when starting a new Satz, but was {0}. Clearing and continuing", stack); stack.Clear(); } } // Extract Satzart from payload and create Satz matching it Satzart satzart = GetSatzart(payload); switch (satzart) { case Satzart.Befund: stack.Push(new Befund()); break; case Satzart.Auftrag: stack.Push(new Auftrag()); break; case Satzart.LaborDatenpaketHeader: stack.Push(new LaborDatenpaketHeader()); break; case Satzart.LaborDatenpaketAbschluss: stack.Push(new LaborDatenpaketAbschluss()); break; case Satzart.PraxisDatenpaketHeader: stack.Push(new PraxisDatenpaketHeader()); break; case Satzart.PraxisDatenpaketAbschluss: stack.Push(new PraxisDatenpaketAbschluss()); break; default: throw new ArgumentException("Unsupported Satzart '" + payload + "' found"); } break; } case "8001": { // End: Satz AssureLength(line, length, 13); object o = stack.Pop(); Datenpaket datenpaket = o.GetType().GetCustomAttribute<Datenpaket>(); if (datenpaket != null) { EvaluateContextRules(o, datenpaket.Kontextregeln); } if (stack.Count == 0) { data.Add((Satz)o); } break; } case "8002": { // Start: Objekt AssureLength(line, length, 17); object currentObject1 = PeekCurrentObject(stack); Objekt annotation1 = currentObject1.GetType().GetCustomAttribute<Objekt>(); if (annotation1 != null) { if (annotation1.Value.Length == 0) { // If annotation is empty, the parent object would actually // be the one to deal with } else { // Match found, everything is fine if (payload.Equals("Obj_" + annotation1.Value)) { break; } // No match found, abort or inform the developer if (mode == LdtConstants.Mode.STRICT) { throw new ArgumentException( "In line '" + line + "' (" + lineNo + ") expected Obj_" + annotation1.Value + ", got " + payload); } else { Trace.TraceError("In line {0} ({1}) expected Obj_{2}, got {3}", line, lineNo, annotation1.Value, payload); break; } } } if (mode == LdtConstants.Mode.STRICT) { throw new ArgumentException("Line '" + line + "' (" + lineNo + ") started an unexpeted object, stack was " + stack.ToArray()); } else { Trace.TraceWarning("Line '{0}' ({1}) started an unexpeted object, stack was {2}", line, lineNo, stack); } break; } case "8003": { // End: Objekt AssureLength(line, length, 17); object o; Objekt annotation1; do { o = stack.Pop(); annotation1 = o.GetType().GetCustomAttribute<Objekt>(); if (annotation1 != null) { if (annotation1.Value.Length != 0 && !("Obj_" + annotation1.Value).Equals(payload)) { Trace.TraceWarning("Line: {0} ({1}), annotation {2}, payload {3}", line, lineNo, annotation1.Value, payload); } EvaluateContextRules(o, annotation1.Kontextregeln); } } while (annotation1 != null && annotation1.Value.Length == 0); if (stack.Count == 0) { data.Add((Satz)o); } break; } default: // Any line not starting or completing a Satz or Objekt object currentObject = PeekCurrentObject(stack); if (currentObject == null) { throw new InvalidOperationException("No object when appplying line " + line + " (" + lineNo + ")"); } // XXX iterating the fields could be replaced by a map to be a bit // faster when dealing with the same class foreach (FieldInfo info in currentObject.GetType().GetFields()) { // Check if we found a Feld annotation, if not this is not our // field Feld annotation2 = info.GetCustomAttribute<Feld>(); if (annotation2 == null) { continue; } // Check if the annotation matches the identifier, if not, this // is not our field if (!identifier.Equals(annotation2.Value)) { continue; } try { // Check if there is currently a value set object o = info.GetValue(currentObject); if (o != null && GetGenericList(info.FieldType) == null) { if (mode == LdtConstants.Mode.STRICT) { throw new InvalidOperationException( "Line '" + line + "' (" + lineNo + ") would overwrite existing value " + o + " of " + currentObject + "." + info.Name); } else { Trace.TraceWarning("Line '{0}' ({1}) would overwrite existing value {2} in object {3}.{4}", line, lineNo, o, currentObject, info); } } ValidateFieldPayload(info, payload); // Convert the value to its target type ... object value = ConvertType(info, info.FieldType, payload, stack); // .. and set the value on the target object info.SetValue(currentObject, value); } catch (Exception e) { if (mode == LdtConstants.Mode.STRICT) { throw new InvalidOperationException(e.Message, e); } else { Trace.TraceError(e.Message); } } // We are done with this line return; } // No field with a matching Feld annotation found, check if we are // an Objekt with an empty value (anonymous object), if so try our // parent Objekt annotation = currentObject.GetType().GetCustomAttribute<Objekt>(); if (annotation != null && annotation.Value.Length == 0) { stack.Pop(); HandleInput(line, stack, data, lineNo); return; } // Neither we nor our parent could deal with this line if (mode == LdtConstants.Mode.STRICT) { throw new ArgumentException("Failed reading line " + line + " (" + lineNo + "), current stack: " + string.Join(" ", stack.ToArray())); } else { Trace.TraceWarning("Failed reading line {0} ({1}), current stack: {2}, skipping line", line, lineNo, string.Join(" ", stack.ToArray())); } break; } } private void EvaluateContextRules(object o, Type[] kontextRegeln) { foreach (Type kontextregel in kontextRegeln) { try { if (!((Kontextregel)Activator.CreateInstance(kontextregel)).IsValid(o)) { if (mode == LdtConstants.Mode.STRICT) { throw new ArgumentException("Context rule " + kontextregel.Name + " failed on object " + o); } else { Trace.TraceWarning("Context rule {} failed on object {}", kontextregel.Name, o); } } } catch (Exception e) { if (mode == LdtConstants.Mode.STRICT) { throw new ArgumentException("Context rule " + kontextregel.Name + " failed on object " + o, e); } else { Trace.TraceWarning("Context rule {} failed on object {}", kontextregel.Name, o, e); } } } } void ValidateFieldPayload(FieldInfo field, string payload) { foreach (Regelsatz regelsatz in field.GetCustomAttributes<Regelsatz>()) { if (regelsatz.Laenge >= 0) { if (payload.Length != regelsatz.Laenge) { ValidationFailed(field.DeclaringType.Name + "." + field.Name + ": Value " + payload + " did not match expected length " + regelsatz.Laenge + ", was " + payload.Length); } } if (regelsatz.MinLaenge >= 0) { if (payload.Length < regelsatz.MinLaenge) { ValidationFailed(field.DeclaringType.Name + "." + field.Name + ": Value " + payload + " did not match expected minimum length " + regelsatz.MinLaenge + ", was " + payload.Length); } } if (regelsatz.MaxLaenge >= 0) { if (payload.Length > regelsatz.MaxLaenge) { ValidationFailed(field.DeclaringType.Name + "." + field.Name + ": Value " + payload + " did not match expected maximum length " + regelsatz.MaxLaenge + ", was " + payload.Length); } } // No specific rules given, likely only length checks if (regelsatz.Value.Length == 0) { continue; } bool found = false; foreach (Type regel in regelsatz.Value) { if (GetRegel(regel).IsValid(payload)) { found = true; break; } } if (!found) { ValidationFailed(field.DeclaringType.Name + "." + field.Name + ": Value " + payload + " did not confirm to any rule of " + ToString(regelsatz.Value)); } } } void ValidationFailed(string message) { if (mode == LdtConstants.Mode.STRICT) { throw new InvalidOperationException(message); } else { Trace.TraceWarning(message); } } string ToString(Type[] regeln) { StringBuilder buffer = new StringBuilder(); foreach (Type regel in regeln) { if (buffer.Length > 0) { buffer.Append(" or "); } buffer.Append(regel.Name); } return buffer.ToString(); } Regel GetRegel(Type regel) { Regel instance; regelCache.TryGetValue(regel, out instance); if (instance == null) { instance = (Regel)Activator.CreateInstance(regel); regelCache[regel] = instance; } return instance; } /** * Extract the Satzart form a given payload * * @param payload * the payload of the line * @return the Satzart or {@code null} */ Satzart GetSatzart(string payload) { foreach (Satzart sa in Enum.GetValues(typeof(Satzart)).Cast<Satzart>()) { if (sa.GetCode().Equals(payload)) { return sa; } } throw new ArgumentException("Unsupported Satzart '" + payload + "' found"); } /** * Peek the current objekt from the stack, if any. * * @param stack * the stack to peek the object from * @return the current top level element of the stack or {@code null} */ static object PeekCurrentObject(Stack<object> stack) { if (stack.Count == 0) { return null; } return stack.Peek(); } /** * Check if the line matches the expected length. * * @param line * the line to check * @param length * the actual length * @param target * the length specified by the line */ void AssureLength(string line, int length, int target) { if (length != target) { if (mode == LdtConstants.Mode.STRICT) { throw new ArgumentException( "Line '" + line + "' must have length " + target + ", was " + length); } else { Trace.TraceInformation("Line '{0}' must have length {1}, was {2}", line, target, length); } } } /** * Convert the string payload into a target class. (Note: There are * certainly better options out there but this one is simple enough for our * needs.) */ static object ConvertType(FieldInfo field, Type type, string payload, Stack<object> stack) { if (type == typeof(string)) { return payload; } if (type == typeof(float) || type == typeof(float?)) { return float.Parse(payload); } if (type == typeof(int) || type == typeof(int?)) { return int.Parse(payload); } if (type == typeof(long) || type == typeof(long?)) { return long.Parse(payload); } if (type == typeof(bool) || type == typeof(bool?)) { return "1".Equals(payload); } if (type == typeof(LocalDate?)) { return LdtConstants.FORMAT_DATE.Parse(payload).Value; } if (type == typeof(LocalTime?)) { return LdtConstants.FORMAT_TIME.Parse(payload).Value; } if (IsNullableEnum(type)) { Type enumType = Nullable.GetUnderlyingType(type); MethodInfo method = Type.GetType(enumType.FullName + "Extensions").GetMethod("GetCode"); if (method != null) { foreach (object e in Enum.GetValues(enumType)) { string code = (string)method.Invoke(e, new object[] { e }); if (payload.Equals(code)) { return e; } } return null; } } if (type.IsEnum) { MethodInfo method = Type.GetType(type.FullName + "Extensions").GetMethod("GetCode"); if (method != null) { foreach (object e in Enum.GetValues(type)) { string code = (string)method.Invoke(e, new object[] { e }); if (payload.Equals(code)) { return e; } } return null; } } Type genericType = GetGenericList(type); if (genericType != null) { object currentObject = PeekCurrentObject(stack); var o = (System.Collections.IList) field.GetValue(currentObject); if (o == null) { o = (System.Collections.IList) Activator.CreateInstance(typeof(List<>).MakeGenericType(genericType.GetGenericArguments()[0])); field.SetValue(currentObject, o); } o.Add(ConvertType(field, type.GenericTypeArguments[0], payload, stack)); return o; } if (type.GetCustomAttribute<Objekt>() != null) { object instance = Activator.CreateInstance(type); stack.Push(instance); FieldInfo declaredField = type.GetField("Value"); if (declaredField != null) { declaredField.SetValue(instance, ConvertType(declaredField, declaredField.FieldType, payload, stack)); } return instance; } throw new ArgumentException("Don't know how to handle type " + type); } static bool IsNullableEnum(Type t) { Type u = Nullable.GetUnderlyingType(t); return (u != null) && u.IsEnum; } static Type GetGenericList(Type type) { if (type.IsGenericType && type.GetGenericTypeDefinition() == typeof(IList<>)) { return type; } foreach (Type interfaceType in type.GetInterfaces()) { if (interfaceType.IsGenericType && interfaceType.GetGenericTypeDefinition() == typeof(IList<>)) { return interfaceType; } } return null; } } }
egore/libldt3-cs
libldt3/LdtReader.cs
C#
mit
18,803
var map; var bounds; var markers = {}; var cluster_polygons = {}; var zoomTimeout; var cluster_center_overlay; var white_overlay; var overlay_opacity = 50; var OPACITY_MAX_PIXELS = 57; var active_cluster_poly; var marker_image; var center_marker; var cluster_center_marker_icon; function createMap() { bounds = new google.maps.LatLngBounds (); markers; cluster_polygons; marker_image = { url: STATIC_URL + "images/red_marker.png", anchor: new google.maps.Point(4,4)}; center_marker = { url: STATIC_URL + "images/black_marker.png", size: new google.maps.Size(20, 20), anchor: new google.maps.Point(10,10)}; cluster_center_marker_icon = { url: STATIC_URL + "images/transparent_marker_20_20.gif", size: new google.maps.Size(20, 20), anchor: new google.maps.Point(10,10)}; var mapOptions = { center: new google.maps.LatLng(0, 0), zoom: 4, mapTypeId: google.maps.MapTypeId.ROADMAP, scaleControl: true }; map = new google.maps.Map(document.getElementById("canvas"), mapOptions); // google.maps.event.addListener(map, 'bounds_changed', function(e) { // if (zoomTimeout) { // window.clearTimeout(zoomTimeout); // } // zoomTimeout = window.setTimeout(query_points_for_view, 5000); // }) $.getScript(STATIC_URL + "script/CustomTileOverlay.js", function() { white_overlay = new CustomTileOverlay(map, overlay_opacity); white_overlay.show(); google.maps.event.addListener(map, 'tilesloaded', function () { white_overlay.deleteHiddenTiles(map.getZoom()); }); createOpacityControl(map, overlay_opacity); }); } // Thanks https://github.com/gavinharriss/google-maps-v3-opacity-control/! function createOpacityControl(map, opacity) { var sliderImageUrl = STATIC_URL + "images/opacity-slider3d14.png"; // Create main div to hold the control. var opacityDiv = document.createElement('DIV'); opacityDiv.setAttribute("style", "margin:5px;overflow-x:hidden;overflow-y:hidden;background:url(" + sliderImageUrl + ") no-repeat;width:71px;height:21px;cursor:pointer;"); // Create knob var opacityKnobDiv = document.createElement('DIV'); opacityKnobDiv.setAttribute("style", "padding:0;margin:0;overflow-x:hidden;overflow-y:hidden;background:url(" + sliderImageUrl + ") no-repeat -71px 0;width:14px;height:21px;"); opacityDiv.appendChild(opacityKnobDiv); var opacityCtrlKnob = new ExtDraggableObject(opacityKnobDiv, { restrictY: true, container: opacityDiv }); google.maps.event.addListener(opacityCtrlKnob, "dragend", function () { set_overlay_opacity(opacityCtrlKnob.valueX()); }); // google.maps.event.addDomListener(opacityDiv, "click", function (e) { // var left = findPosLeft(this); // var x = e.pageX - left - 5; // - 5 as we're using a margin of 5px on the div // opacityCtrlKnob.setValueX(x); // set_overlay_opacity(x); // }); map.controls[google.maps.ControlPosition.TOP_RIGHT].push(opacityDiv); // Set initial value var initialValue = OPACITY_MAX_PIXELS / (100 / opacity); opacityCtrlKnob.setValueX(initialValue); set_overlay_opacity(initialValue); } // Thanks https://github.com/gavinharriss/google-maps-v3-opacity-control/! function findPosLeft(obj) { var curleft = 0; if (obj.offsetParent) { do { curleft += obj.offsetLeft; } while (obj = obj.offsetParent); return curleft; } return undefined; } function set_overlay_opacity(value) { overlay_opacity = (100.0 / OPACITY_MAX_PIXELS) * value; if (value < 0) value = 0; if (value == 0) { if (white_overlay.visible == true) { white_overlay.hide(); } } else { white_overlay.setOpacity(overlay_opacity); if (white_overlay.visible == false) { white_overlay.show(); } } } function query_points_for_view() { var bounds = map.getBounds(); var x0 = bounds.getNorthEast().lng(); var y0 = bounds.getNorthEast().lat(); var x1 = bounds.getSouthWest().lng(); var y1 = bounds.getSouthWest().lat(); // Remove stuff off screen var to_remove = []; // What to remove $.each(markers, function(idx, marker){ if (!bounds.contains(marker.getPosition())) { marker.setMap(null); to_remove.push(idx); } }); $.each(to_remove, function(i, idx){ delete markers[idx]; }) // $.getJSON("/rest/photos_box_contains?x0=" + x0 + "&y0=" + y0 + "&x1=" + x1 + "&y1=" + y1, function(data){ // console.log("got " + data.features.length); // add_photo_to_map(data.features, 0, 128); // }) $.getJSON("/rest/clusters_box_contains?x0=" + x0 + "&y0=" + y0 + "&x1=" + x1 + "&y1=" + y1, function(data){ console.log("got " + data.features.length); add_cluster_to_map(data.features, 0); }) } function create_photo_marker(photo_info) { var loc = new google.maps.LatLng(photo_info.geometry.coordinates[1], photo_info.geometry.coordinates[0]); var marker = new google.maps.Marker({ map: map, position: loc, icon: marker_image }); var infowindow = new google.maps.InfoWindow({ content: "<div style='width:200px;height:200px'><a href='" + photo_info.properties.photo_url + "'><img src='" + photo_info.properties.photo_thumb_url + "' style='max-width:100%;max-height:100%;'/></div>" }); google.maps.event.addListener(marker, 'click', function() { infowindow.open(map,marker); }); markers[photo_info.id] = marker; } function add_photo_to_map(photos, i, step) { for (var j = 0; j < step; j++) { if (i + j >= photos.length) { break; } var photo_info = photos[i + j]; if (!markers[photo_info.id]) { create_photo_marker(photo_info); } } i += step; if (i < photos.length) { window.setTimeout(function(){add_photo_to_map(photos, i, step);}, 1); } } function add_clustering_run_to_map(data){ $.each(cluster_polygons, function(idx, poly){ poly.setMap(null); }); bounds = new google.maps.LatLngBounds (); cluster_polygons = []; cluster_center_overlay = new google.maps.OverlayView(); cluster_center_overlay.onAdd = function() { var layer = d3.select(this.getPanes().overlayMouseTarget).append("div") .attr("class", "cluster_center"); var projection = this.getProjection(); var max_size = 300; var max_size_per_2 = max_size / 2; var marker = layer.selectAll("svg") .data(data.features) .each(transform) .enter().append("svg:svg") .each(transform) .each(tie_to_g_marker) .attr("class", "marker") .style("z-index", function(cluster) { return set_default_z_index(cluster); }) .append("svg:g"); function set_default_z_index(cluster) { return parseInt(cluster.properties.point_count_relative * 1000 + 100000); } marker.append("svg:polygon") .attr("points", function(cluster){ var out = []; var last_phase = 0.0; var last_length = 1.0 / 12.0 * (max_size_per_2 - 1); var min_l = 0.0;//0.3 * max_size_per_2 * (Math.sqrt(cluster.properties.point_count_relative) * 0.7 + 0.3); for (var j = 1.0; j <= 12.0; j += 1.0){ var phase = j / 12.0 * 2 * Math.PI; out.push([max_size_per_2 + Math.sin(last_phase) * min_l, max_size_per_2 - Math.cos(last_phase) * min_l]); out.push([max_size_per_2 + Math.sin(phase) * min_l, max_size_per_2 - Math.cos(phase) * min_l]); var second_poly = []; var l = ( (cluster.properties["points_month_" + parseInt(j) + "_relative"]) * 0.9 + 0.1) * max_size_per_2 * (cluster.properties.point_count_relative * 0.8 + 0.2); second_poly.push([max_size_per_2 + Math.sin(last_phase) * min_l, max_size_per_2 - Math.cos(last_phase) * min_l]); second_poly.push([max_size_per_2 + Math.sin(last_phase) * l, max_size_per_2 - Math.cos(last_phase) * l]); second_poly.push([max_size_per_2 + Math.sin(phase) * l, max_size_per_2 - Math.cos(phase) * l]); second_poly.push([max_size_per_2 + Math.sin(phase) * min_l, max_size_per_2 - Math.cos(phase) * min_l]); second_poly.push(second_poly[0]); last_phase = phase; d3.select(this.parentElement) .append("svg:polygon") .attr("points", second_poly.join(" ")) .attr("class", "month_" + parseInt(j)); } return out.join(" "); }) .attr("class", "cluster_center_marker"); function transform(cluster) { var coords = cluster.geometry.geometries[0].coordinates; var d = new google.maps.LatLng(coords[1], coords[0]); d = projection.fromLatLngToDivPixel(d); return d3.select(this) .style("left", (d.x - max_size_per_2) + "px") .style("top", (d.y - max_size_per_2) + "px"); } function tie_to_g_marker(cluster){ var coords = cluster.geometry.geometries[0].coordinates; var d = new google.maps.LatLng(coords[1], coords[0]); var marker = new google.maps.Marker({ map: map, position: d, icon: cluster_center_marker_icon, zIndex: set_default_z_index(d3.select(this).data()[0]) }); var cluster_center = this; google.maps.event.addListener(marker, 'mouseover', function() { d3_cluster_center = d3.select(cluster_center); d3_cluster_center .style("transform", "scale(3.0)") .style("animation-name", "cluster_center_highlight") .style("z-index", 1001001); }); google.maps.event.addListener(marker, 'click', function() { if (active_cluster_poly) { active_cluster_poly.setMap(null); } sidebar_display_cluster_info(d3_cluster_center.data()[0]["id"]); d3_cluster_center = d3.select(cluster_center); poly_bounds = new google.maps.LatLngBounds (); // Define the LatLng coordinates for the polygon's path. var coords = d3_cluster_center.data()[0].geometry.geometries[1].coordinates[0]; var g_coords = []; for (j in coords) { var c = coords[j]; var co = new google.maps.LatLng(c[1], c[0]); g_coords.push(co); poly_bounds.extend(co); } // Construct the polygon. var poly = new google.maps.Polygon({ paths: g_coords, strokeColor: '#FF0000', strokeOpacity: 0.8, strokeWeight: 2, fillColor: '#FF0000', fillOpacity: 0.35 }); poly.setMap(map); active_cluster_poly = poly; map.fitBounds(poly_bounds); }); google.maps.event.addListener(marker, 'mouseout', function() { d3.select(cluster_center) .style("transform", "scale(1.0)") .style("animation-name", "cluster_center_unhighlight") .style("z-index", function(cluster) { return set_default_z_index(cluster); }); }); bounds.extend(d); } map.fitBounds(bounds); cluster_center_overlay.draw = function() { var projection = this.getProjection(); layer.selectAll("svg") .data(data.features) .each(transform); }; }; cluster_center_overlay.setMap(map); } function finalize_clustering_run_to_map(clusters){ console.log("finalizing"); map.fitBounds(bounds); } function show_clusters_lame() { var $form = $("#clustering_run_get_form"), url = $form.attr("action"); // Fire some AJAX! $.ajax({ type: "GET", url: url, dataType: "json", data: {id: $("#clustering_run_get_form_select").val()} }) .done(function(msg){ add_cluster_to_map(msg.features, 0); }); } function show_cluster_centers_lame() { var $form = $("#clustering_run_get_form"), url = $form.attr("action"); // Fire some AJAX! $.ajax({ type: "GET", url: url, dataType: "json", data: {id: $("#clustering_run_get_form_select").val()} }) .done(function(msg){ add_cluster_center_to_map(msg.features, 0); }); } function add_cluster_to_map(clusters, i){ // Define the LatLng coordinates for the polygon's path. var cluster = clusters[i]; var coords = []; var points = cluster.geometry.geometries[1].coordinates[0]; for (var j = 0; j < points.length; j += 1) { coords.push(new google.maps.LatLng( points[j][1], points[j][0])); } var center = cluster.geometry.geometries[0].coordinates; var loc = new google.maps.LatLng( center[1], center[0]) bounds.extend(loc); // Construct the polygon. var poly = new google.maps.Polygon({ paths: coords, strokeColor: '#000000', strokeOpacity: 1.0, strokeWeight: 1, fillColor: '#FF0000', fillOpacity: 0.1 }); poly.setMap(map); // cluster_polygons.push(poly); if (i < clusters.length - 1) { window.setTimeout(function(){add_cluster_to_map(clusters, i + 1);}, 1); } else { finalize_clustering_run_to_map(clusters); } } function add_cluster_center_to_map(clusters, i){ // Define the LatLng coordinates for the polygon's path. var cluster = clusters[i]; var coords = []; var center = cluster.geometry.geometries[0].coordinates; var loc = new google.maps.LatLng( center[1], center[0]) bounds.extend(loc); var marker = new google.maps.Marker({ map: map, position: loc }); if (i < clusters.length - 1) { window.setTimeout(function(){add_cluster_center_to_map(clusters, i + 1);}, 1); } else { finalize_clustering_run_to_map(clusters); } } function show_all() { map.fitBounds(bounds); }
joonamo/photoplaces
photoplaces/static/script/map.js
JavaScript
mit
15,053
#include "sendcoinsdialog.h" #include "ui_sendcoinsdialog.h" #include "walletmodel.h" #include "bitcoinunits.h" #include "addressbookpage.h" #include "optionsmodel.h" #include "sendcoinsentry.h" #include "guiutil.h" #include "askpassphrasedialog.h" #include "base58.h" #include <QMessageBox> #include <QLocale> #include <QTextDocument> #include <QScrollBar> SendCoinsDialog::SendCoinsDialog(QWidget *parent) : QDialog(parent), ui(new Ui::SendCoinsDialog), model(0) { ui->setupUi(this); #ifdef Q_OS_MAC // Icons on push buttons are very uncommon on Mac ui->addButton->setIcon(QIcon()); ui->clearButton->setIcon(QIcon()); ui->sendButton->setIcon(QIcon()); #endif addEntry(); connect(ui->addButton, SIGNAL(clicked()), this, SLOT(addEntry())); connect(ui->clearButton, SIGNAL(clicked()), this, SLOT(clear())); fNewRecipientAllowed = true; } void SendCoinsDialog::setModel(WalletModel *model) { this->model = model; for(int i = 0; i < ui->entries->count(); ++i) { SendCoinsEntry *entry = qobject_cast<SendCoinsEntry*>(ui->entries->itemAt(i)->widget()); if(entry) { entry->setModel(model); } } if(model && model->getOptionsModel()) { setBalance(model->getBalance(), model->getStake(), model->getUnconfirmedBalance(), model->getImmatureBalance()); connect(model, SIGNAL(balanceChanged(qint64, qint64, qint64, qint64)), this, SLOT(setBalance(qint64, qint64, qint64, qint64))); connect(model->getOptionsModel(), SIGNAL(displayUnitChanged(int)), this, SLOT(updateDisplayUnit())); } } SendCoinsDialog::~SendCoinsDialog() { delete ui; } void SendCoinsDialog::on_sendButton_clicked() { QList<SendCoinsRecipient> recipients; bool valid = true; if(!model) return; for(int i = 0; i < ui->entries->count(); ++i) { SendCoinsEntry *entry = qobject_cast<SendCoinsEntry*>(ui->entries->itemAt(i)->widget()); if(entry) { if(entry->validate()) { recipients.append(entry->getValue()); } else { valid = false; } } } if(!valid || recipients.isEmpty()) { return; } // Format confirmation message QStringList formatted; foreach(const SendCoinsRecipient &rcp, recipients) { #if QT_VERSION < 0x050000 formatted.append(tr("<b>%1</b> to %2 (%3)").arg(BitcoinUnits::formatWithUnit(BitcoinUnits::BTC, rcp.amount), Qt::escape(rcp.label), rcp.address)); #else formatted.append(tr("<b>%1</b> to %2 (%3)").arg(BitcoinUnits::formatWithUnit(BitcoinUnits::BTC, rcp.amount), rcp.label.toHtmlEscaped(), rcp.address)); #endif } fNewRecipientAllowed = false; QMessageBox::StandardButton retval = QMessageBox::question(this, tr("Confirm send coins"), tr("Are you sure you want to send %1?").arg(formatted.join(tr(" and "))), QMessageBox::Yes|QMessageBox::Cancel, QMessageBox::Cancel); if(retval != QMessageBox::Yes) { fNewRecipientAllowed = true; return; } WalletModel::UnlockContext ctx(model->requestUnlock()); if(!ctx.isValid()) { // Unlock wallet was cancelled fNewRecipientAllowed = true; return; } WalletModel::SendCoinsReturn sendstatus = model->sendCoins(recipients); switch(sendstatus.status) { case WalletModel::InvalidAddress: QMessageBox::warning(this, tr("Send Coins"), tr("The recipient address is not valid, please recheck."), QMessageBox::Ok, QMessageBox::Ok); break; case WalletModel::InvalidAmount: QMessageBox::warning(this, tr("Send Coins"), tr("The amount to pay must be larger than 0."), QMessageBox::Ok, QMessageBox::Ok); break; case WalletModel::AmountExceedsBalance: QMessageBox::warning(this, tr("Send Coins"), tr("The amount exceeds your balance."), QMessageBox::Ok, QMessageBox::Ok); break; case WalletModel::AmountWithFeeExceedsBalance: QMessageBox::warning(this, tr("Send Coins"), tr("The total exceeds your balance when the %1 transaction fee is included."). arg(BitcoinUnits::formatWithUnit(BitcoinUnits::BTC, sendstatus.fee)), QMessageBox::Ok, QMessageBox::Ok); break; case WalletModel::DuplicateAddress: QMessageBox::warning(this, tr("Send Coins"), tr("Duplicate address found, can only send to each address once per send operation."), QMessageBox::Ok, QMessageBox::Ok); break; case WalletModel::TransactionCreationFailed: QMessageBox::warning(this, tr("Send Coins"), tr("Error: Transaction creation failed."), QMessageBox::Ok, QMessageBox::Ok); break; case WalletModel::TransactionCommitFailed: QMessageBox::warning(this, tr("Send Coins"), tr("Error: The transaction was rejected. This might happen if some of the coins in your wallet were already spent, such as if you used a copy of wallet.dat and coins were spent in the copy but not marked as spent here."), QMessageBox::Ok, QMessageBox::Ok); break; case WalletModel::Aborted: // User aborted, nothing to do break; case WalletModel::OK: accept(); break; } fNewRecipientAllowed = true; } void SendCoinsDialog::clear() { // Remove entries until only one left while(ui->entries->count()) { delete ui->entries->takeAt(0)->widget(); } addEntry(); updateRemoveEnabled(); ui->sendButton->setDefault(true); } void SendCoinsDialog::reject() { clear(); } void SendCoinsDialog::accept() { clear(); } SendCoinsEntry *SendCoinsDialog::addEntry() { SendCoinsEntry *entry = new SendCoinsEntry(this); entry->setModel(model); ui->entries->addWidget(entry); connect(entry, SIGNAL(removeEntry(SendCoinsEntry*)), this, SLOT(removeEntry(SendCoinsEntry*))); updateRemoveEnabled(); // Focus the field, so that entry can start immediately entry->clear(); entry->setFocus(); ui->scrollAreaWidgetContents->resize(ui->scrollAreaWidgetContents->sizeHint()); QCoreApplication::instance()->processEvents(); QScrollBar* bar = ui->scrollArea->verticalScrollBar(); if(bar) bar->setSliderPosition(bar->maximum()); return entry; } void SendCoinsDialog::updateRemoveEnabled() { // Remove buttons are enabled as soon as there is more than one send-entry bool enabled = (ui->entries->count() > 1); for(int i = 0; i < ui->entries->count(); ++i) { SendCoinsEntry *entry = qobject_cast<SendCoinsEntry*>(ui->entries->itemAt(i)->widget()); if(entry) { entry->setRemoveEnabled(enabled); } } setupTabChain(0); } void SendCoinsDialog::removeEntry(SendCoinsEntry* entry) { delete entry; updateRemoveEnabled(); } QWidget *SendCoinsDialog::setupTabChain(QWidget *prev) { for(int i = 0; i < ui->entries->count(); ++i) { SendCoinsEntry *entry = qobject_cast<SendCoinsEntry*>(ui->entries->itemAt(i)->widget()); if(entry) { prev = entry->setupTabChain(prev); } } QWidget::setTabOrder(prev, ui->addButton); QWidget::setTabOrder(ui->addButton, ui->sendButton); return ui->sendButton; } void SendCoinsDialog::pasteEntry(const SendCoinsRecipient &rv) { if(!fNewRecipientAllowed) return; SendCoinsEntry *entry = 0; // Replace the first entry if it is still unused if(ui->entries->count() == 1) { SendCoinsEntry *first = qobject_cast<SendCoinsEntry*>(ui->entries->itemAt(0)->widget()); if(first->isClear()) { entry = first; } } if(!entry) { entry = addEntry(); } entry->setValue(rv); } bool SendCoinsDialog::handleURI(const QString &uri) { SendCoinsRecipient rv; // URI has to be valid if (GUIUtil::parseBitcoinURI(uri, &rv)) { CBitcoinAddress address(rv.address.toStdString()); if (!address.IsValid()) return false; pasteEntry(rv); return true; } return false; } void SendCoinsDialog::setBalance(qint64 balance, qint64 stake, qint64 unconfirmedBalance, qint64 immatureBalance) { Q_UNUSED(stake); Q_UNUSED(unconfirmedBalance); Q_UNUSED(immatureBalance); if(!model || !model->getOptionsModel()) return; int unit = model->getOptionsModel()->getDisplayUnit(); ui->labelBalance->setText(BitcoinUnits::formatWithUnit(unit, balance)); } void SendCoinsDialog::updateDisplayUnit() { if(model && model->getOptionsModel()) { // Update labelBalance with the current balance and the current unit ui->labelBalance->setText(BitcoinUnits::formatWithUnit(model->getOptionsModel()->getDisplayUnit(), model->getBalance())); } }
devxxxcoin/xxxcoin
src/qt/sendcoinsdialog.cpp
C++
mit
9,070
{!! Form::select( 'routes[]', $allRoutes, (isset($routes) ? array_keys($routes) : []), array( 'class' => 'form-control select2', 'placeholder' => 'Enter Routes', 'multiple' => true ) ) !!}
stevebauman/maintenance
resources/views/select/routes.blade.php
PHP
mit
273
<?php namespace Aquatic; use Aquatic\FedEx\Contract\Address; use Aquatic\FedEx\Contract\Shipment; use Aquatic\FedEx\Response\Contract as ResponseContract; use Aquatic\FedEx\Request\ValidateAddress as ValidateAddressRequest; use Aquatic\FedEx\Response\ValidateAddress as ValidateAddressResponse; use Aquatic\FedEx\Request\Shipment\Track as TrackShipmentRequest; use Aquatic\FedEx\Response\Shipment\Track as TrackShipmentResponse; use Aquatic\FedEx\Request\Shipment\CustomsAndDuties as CustomsAndDutiesRequest; use Aquatic\FedEx\Response\Shipment\CustomsAndDuties as CustomsAndDutiesResponse; // Facade for FedEx requests class FedEx { public static function trackShipment(int $tracking_number): ResponseContract { return (new TrackShipmentRequest($tracking_number)) ->setCredentials(getenv('FEDEX_KEY'), getenv('FEDEX_PASSWORD'), getenv('FEDEX_ACCOUNT_NUMBER'), getenv('FEDEX_METER_NUMBER')) ->send(new TrackShipmentResponse); } public static function customsAndDuties(Shipment $shipment, Address $shipper) { return (new CustomsAndDutiesRequest($shipment, $shipper)) ->setCredentials(getenv('FEDEX_KEY'), getenv('FEDEX_PASSWORD'), getenv('FEDEX_ACCOUNT_NUMBER'), getenv('FEDEX_METER_NUMBER')) ->send(new CustomsAndDutiesResponse($shipment->getItems())); } public static function validateAddress(Address $address) { return (new ValidateAddressRequest($address)) ->setCredentials(getenv('FEDEX_KEY'), getenv('FEDEX_PASSWORD'), getenv('FEDEX_ACCOUNT_NUMBER'), getenv('FEDEX_METER_NUMBER')) ->send(new ValidateAddressResponse); } }
aquaticpond/fedex
src/Aquatic/FedEx.php
PHP
mit
1,667
using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; // General Information about an assembly is controlled through the following // set of attributes. Change these attribute values to modify the information // associated with an assembly. [assembly: AssemblyTitle("Pesho")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("Pesho")] [assembly: AssemblyCopyright("Copyright © 2013")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. [assembly: ComVisible(false)] // The following GUID is for the ID of the typelib if this project is exposed to COM [assembly: Guid("fc740c6d-ec21-40c6-ad6d-6823d61e8446")] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Build and Revision Numbers // by using the '*' as shown below: [assembly: AssemblyVersion("1.0.0.0")] [assembly: AssemblyFileVersion("1.0.0.0")]
d-georgiev-91/TelerikAcademy
Programming/HighQualityProgrammingCode/ConsoleApplication1/Pesho/Properties/AssemblyInfo.cs
C#
mit
1,346
@charset "utf-8"; /* CSS Document */ /* -------------------------------------------------------------------------- */ /* BASE AD - typically, we do not mess with this section /* -------------------------------------------------------------------------- */ body, body * { vertical-align: baseline; border: 0; outline: 0; padding: 0; margin: 0; } /* Div layer for the entire banner. */ #adkit_container { position: absolute; width: {{width}}px; height: {{height}}px; border: #9b9b9b 1px solid; top: 0; left: 0; margin: auto; overflow: hidden; display: none; } #adkit_content { position: absolute; width: 100%; height: 100%; top: 0; left: 0; z-index: 100; } /* Invisible button for background clickthrough. */ #adkit_background_exit { position: absolute; width: 100%; height: 100%; top: 0; left: 0; cursor: pointer; opacity: 0; z-index: 400; } :focus { outline: none; } ::-moz-focus-inner { border: 0; } /* -------------------------------------------------------------------------- */ /* Your ad styles here */
tsantor/banner-ad-toolkit
adkit/templates/style.css
CSS
mit
1,134
<article class="home_single_post gallery_post_type" typeof="BlogPosting"> {{ partial "post/image_area.html" . }} <div class="post_content_area"> <div class="row"> <div class="col-xs-12 col-sm-8 col-md-8 col-lg-8 col-xs-offset-0 col-sm-offset-2 col-md-offset-2 col-lg-offset-2"> <div class="post_list" property="articleBody"> <header><h2><a href="{{ .Permalink }}" property="headline">{{ .Title }}</a></h2></header> </div> {{ partial "post/info.html" . }} </div> </div> </div> </article>
pcdummy/hugo-theme-persona
layouts/post/list.html
HTML
mit
617
import React, { Component } from 'react' import PropTypes from 'prop-types' import { MultiSelect } from '../../src' class MultiSelectWithStringValues extends Component { constructor(props) { super(props) this.state = { value: [] } } handleChange = (event) => { const { valueKey } = this.props this.setState({ value: event.value.map((val) => val[valueKey]) }) } render() { const { value } = this.state return <MultiSelect {...this.props} onChange={this.handleChange} value={value} /> } } MultiSelectWithStringValues.propTypes = { valueKey: PropTypes.string.isRequired } export default MultiSelectWithStringValues
sthomas1618/react-crane
stories/components/MultiSelectWithStringValues.js
JavaScript
mit
667
/* util/operators.hpp * * Copyright (C) 2007 Antonio Di Monaco * * This software may be modified and distributed under the terms * of the MIT license. See the LICENSE file for details. */ #ifndef __OPERATORS_HPP__ #define __OPERATORS_HPP__ template< typename T > struct EqualComparable { friend bool operator!=(const T &a,const T &b) { return !(a == b); } }; template< typename T > struct Comparable : public EqualComparable< T > { friend bool operator<=(const T &a, const T &b) { return (a < b) || (a == b); } friend bool operator>(const T &a,const T &b) { return !(a <= b); } friend bool operator>=(const T &a,const T &b) { return !(a < b); } }; #endif
becrux/xfspp
util/operators.hpp
C++
mit
700
""" [2015-07-13] Challenge #223 [Easy] Garland words https://www.reddit.com/r/dailyprogrammer/comments/3d4fwj/20150713_challenge_223_easy_garland_words/ # Description A [_garland word_](http://blog.vivekhaldar.com/post/89763722591/garland-words) is one that starts and ends with the same N letters in the same order, for some N greater than 0, but less than the length of the word. I'll call the maximum N for which this works the garland word's _degree_. For instance, "onion" is a garland word of degree 2, because its first 2 letters "on" are the same as its last 2 letters. The name "garland word" comes from the fact that you can make chains of the word in this manner: onionionionionionionionionionion... Today's challenge is to write a function `garland` that, given a lowercase word, returns the degree of the word if it's a garland word, and 0 otherwise. # Examples garland("programmer") -> 0 garland("ceramic") -> 1 garland("onion") -> 2 garland("alfalfa") -> 4 # Optional challenges 1. Given a garland word, print out the chain using that word, as with "onion" above. You can make it as long or short as you like, even infinite. 1. Find the largest degree of any garland word in the [enable1 English word list](https://code.google.com/p/dotnetperls-controls/downloads/detail?name=enable1.txt). 1. Find a word list for some other language, and see if you can find a language with a garland word with a higher degree. *Thanks to /u/skeeto for submitting this challenge on /r/dailyprogrammer_ideas!* """ def main(): pass if __name__ == "__main__": main()
DayGitH/Python-Challenges
DailyProgrammer/DP20150713A.py
Python
mit
1,597
/** * * Licensed Property to China UnionPay Co., Ltd. * * (C) Copyright of China UnionPay Co., Ltd. 2010 * All Rights Reserved. * * * Modification History: * ============================================================================= * Author Date Description * ------------ ---------- --------------------------------------------------- * xshu 2014-05-28 MPI插件包常量定义 * ============================================================================= */ package com.boyuanitsm.pay.unionpay.config; public class SDKConstants { public final static String COLUMN_DEFAULT = "-"; public final static String KEY_DELIMITER = "#"; /** memeber variable: blank. */ public static final String BLANK = ""; /** member variabel: space. */ public static final String SPACE = " "; /** memeber variable: unline. */ public static final String UNLINE = "_"; /** memeber varibale: star. */ public static final String STAR = "*"; /** memeber variable: line. */ public static final String LINE = "-"; /** memeber variable: add. */ public static final String ADD = "+"; /** memeber variable: colon. */ public final static String COLON = "|"; /** memeber variable: point. */ public final static String POINT = "."; /** memeber variable: comma. */ public final static String COMMA = ","; /** memeber variable: slash. */ public final static String SLASH = "/"; /** memeber variable: div. */ public final static String DIV = "/"; /** memeber variable: left . */ public final static String LB = "("; /** memeber variable: right. */ public final static String RB = ")"; /** memeber variable: rmb. */ public final static String CUR_RMB = "RMB"; /** memeber variable: .page size */ public static final int PAGE_SIZE = 10; /** memeber variable: String ONE. */ public static final String ONE = "1"; /** memeber variable: String ZERO. */ public static final String ZERO = "0"; /** memeber variable: number six. */ public static final int NUM_SIX = 6; /** memeber variable: equal mark. */ public static final String EQUAL = "="; /** memeber variable: operation ne. */ public static final String NE = "!="; /** memeber variable: operation le. */ public static final String LE = "<="; /** memeber variable: operation ge. */ public static final String GE = ">="; /** memeber variable: operation lt. */ public static final String LT = "<"; /** memeber variable: operation gt. */ public static final String GT = ">"; /** memeber variable: list separator. */ public static final String SEP = "./"; /** memeber variable: Y. */ public static final String Y = "Y"; /** memeber variable: AMPERSAND. */ public static final String AMPERSAND = "&"; /** memeber variable: SQL_LIKE_TAG. */ public static final String SQL_LIKE_TAG = "%"; /** memeber variable: @. */ public static final String MAIL = "@"; /** memeber variable: number zero. */ public static final int NZERO = 0; public static final String LEFT_BRACE = "{"; public static final String RIGHT_BRACE = "}"; /** memeber variable: string true. */ public static final String TRUE_STRING = "true"; /** memeber variable: string false. */ public static final String FALSE_STRING = "false"; /** memeber variable: forward success. */ public static final String SUCCESS = "success"; /** memeber variable: forward fail. */ public static final String FAIL = "fail"; /** memeber variable: global forward success. */ public static final String GLOBAL_SUCCESS = "$success"; /** memeber variable: global forward fail. */ public static final String GLOBAL_FAIL = "$fail"; public static final String UTF_8_ENCODING = "UTF-8"; public static final String GBK_ENCODING = "GBK"; public static final String CONTENT_TYPE = "Content-type"; public static final String APP_XML_TYPE = "application/xml;charset=utf-8"; public static final String APP_FORM_TYPE = "application/x-www-form-urlencoded;charset="; /******************************************** 5.0报文接口定义 ********************************************/ /** 版本号. */ public static final String param_version = "version"; /** 证书ID. */ public static final String param_certId = "certId"; /** 签名. */ public static final String param_signature = "signature"; /** 编码方式. */ public static final String param_encoding = "encoding"; /** 交易类型. */ public static final String param_txnType = "txnType"; /** 交易子类. */ public static final String param_txnSubType = "txnSubType"; /** 业务类型. */ public static final String param_bizType = "bizType"; /** 前台通知地址 . */ public static final String param_frontUrl = "frontUrl"; /** 后台通知地址. */ public static final String param_backUrl = "backUrl"; /** 接入类型. */ public static final String param_accessType = "accessType"; /** 收单机构代码. */ public static final String param_acqInsCode = "acqInsCode"; /** 商户类别. */ public static final String param_merCatCode = "merCatCode"; /** 商户类型. */ public static final String param_merType = "merType"; /** 商户代码. */ public static final String param_merId = "merId"; /** 商户名称. */ public static final String param_merName = "merName"; /** 商户简称. */ public static final String param_merAbbr = "merAbbr"; /** 二级商户代码. */ public static final String param_subMerId = "subMerId"; /** 二级商户名称. */ public static final String param_subMerName = "subMerName"; /** 二级商户简称. */ public static final String param_subMerAbbr = "subMerAbbr"; /** Cupsecure 商户代码. */ public static final String param_csMerId = "csMerId"; /** 商户订单号. */ public static final String param_orderId = "orderId"; /** 交易时间. */ public static final String param_txnTime = "txnTime"; /** 发送时间. */ public static final String param_txnSendTime = "txnSendTime"; /** 订单超时时间间隔. */ public static final String param_orderTimeoutInterval = "orderTimeoutInterval"; /** 支付超时时间. */ public static final String param_payTimeoutTime = "payTimeoutTime"; /** 默认支付方式. */ public static final String param_defaultPayType = "defaultPayType"; /** 支持支付方式. */ public static final String param_supPayType = "supPayType"; /** 支付方式. */ public static final String param_payType = "payType"; /** 自定义支付方式. */ public static final String param_customPayType = "customPayType"; /** 物流标识. */ public static final String param_shippingFlag = "shippingFlag"; /** 收货地址-国家. */ public static final String param_shippingCountryCode = "shippingCountryCode"; /** 收货地址-省. */ public static final String param_shippingProvinceCode = "shippingProvinceCode"; /** 收货地址-市. */ public static final String param_shippingCityCode = "shippingCityCode"; /** 收货地址-地区. */ public static final String param_shippingDistrictCode = "shippingDistrictCode"; /** 收货地址-详细. */ public static final String param_shippingStreet = "shippingStreet"; /** 商品总类. */ public static final String param_commodityCategory = "commodityCategory"; /** 商品名称. */ public static final String param_commodityName = "commodityName"; /** 商品URL. */ public static final String param_commodityUrl = "commodityUrl"; /** 商品单价. */ public static final String param_commodityUnitPrice = "commodityUnitPrice"; /** 商品数量. */ public static final String param_commodityQty = "commodityQty"; /** 是否预授权. */ public static final String param_isPreAuth = "isPreAuth"; /** 币种. */ public static final String param_currencyCode = "currencyCode"; /** 账户类型. */ public static final String param_accType = "accType"; /** 账号. */ public static final String param_accNo = "accNo"; /** 支付卡类型. */ public static final String param_payCardType = "payCardType"; /** 发卡机构代码. */ public static final String param_issInsCode = "issInsCode"; /** 持卡人信息. */ public static final String param_customerInfo = "customerInfo"; /** 交易金额. */ public static final String param_txnAmt = "txnAmt"; /** 余额. */ public static final String param_balance = "balance"; /** 地区代码. */ public static final String param_districtCode = "districtCode"; /** 附加地区代码. */ public static final String param_additionalDistrictCode = "additionalDistrictCode"; /** 账单类型. */ public static final String param_billType = "billType"; /** 账单号码. */ public static final String param_billNo = "billNo"; /** 账单月份. */ public static final String param_billMonth = "billMonth"; /** 账单查询要素. */ public static final String param_billQueryInfo = "billQueryInfo"; /** 账单详情. */ public static final String param_billDetailInfo = "billDetailInfo"; /** 账单金额. */ public static final String param_billAmt = "billAmt"; /** 账单金额符号. */ public static final String param_billAmtSign = "billAmtSign"; /** 绑定标识号. */ public static final String param_bindId = "bindId"; /** 风险级别. */ public static final String param_riskLevel = "riskLevel"; /** 绑定信息条数. */ public static final String param_bindInfoQty = "bindInfoQty"; /** 绑定信息集. */ public static final String param_bindInfoList = "bindInfoList"; /** 批次号. */ public static final String param_batchNo = "batchNo"; /** 总笔数. */ public static final String param_totalQty = "totalQty"; /** 总金额. */ public static final String param_totalAmt = "totalAmt"; /** 文件类型. */ public static final String param_fileType = "fileType"; /** 文件名称. */ public static final String param_fileName = "fileName"; /** 批量文件内容. */ public static final String param_fileContent = "fileContent"; /** 商户摘要. */ public static final String param_merNote = "merNote"; /** 商户自定义域. */ // public static final String param_merReserved = "merReserved";//接口变更删除 /** 请求方保留域. */ public static final String param_reqReserved = "reqReserved";// 新增接口 /** 保留域. */ public static final String param_reserved = "reserved"; /** 终端号. */ public static final String param_termId = "termId"; /** 终端类型. */ public static final String param_termType = "termType"; /** 交互模式. */ public static final String param_interactMode = "interactMode"; /** 发卡机构识别模式. */ // public static final String param_recognitionMode = "recognitionMode"; public static final String param_issuerIdentifyMode = "issuerIdentifyMode";// 接口名称变更 /** 商户端用户号. */ public static final String param_merUserId = "merUserId"; /** 持卡人IP. */ public static final String param_customerIp = "customerIp"; /** 查询流水号. */ public static final String param_queryId = "queryId"; /** 原交易查询流水号. */ public static final String param_origQryId = "origQryId"; /** 系统跟踪号. */ public static final String param_traceNo = "traceNo"; /** 交易传输时间. */ public static final String param_traceTime = "traceTime"; /** 清算日期. */ public static final String param_settleDate = "settleDate"; /** 清算币种. */ public static final String param_settleCurrencyCode = "settleCurrencyCode"; /** 清算金额. */ public static final String param_settleAmt = "settleAmt"; /** 清算汇率. */ public static final String param_exchangeRate = "exchangeRate"; /** 兑换日期. */ public static final String param_exchangeDate = "exchangeDate"; /** 响应时间. */ public static final String param_respTime = "respTime"; /** 原交易应答码. */ public static final String param_origRespCode = "origRespCode"; /** 原交易应答信息. */ public static final String param_origRespMsg = "origRespMsg"; /** 应答码. */ public static final String param_respCode = "respCode"; /** 应答码信息. */ public static final String param_respMsg = "respMsg"; // 新增四个报文字段merUserRegDt merUserEmail checkFlag activateStatus /** 商户端用户注册时间. */ public static final String param_merUserRegDt = "merUserRegDt"; /** 商户端用户注册邮箱. */ public static final String param_merUserEmail = "merUserEmail"; /** 验证标识. */ public static final String param_checkFlag = "checkFlag"; /** 开通状态. */ public static final String param_activateStatus = "activateStatus"; /** 加密证书ID. */ public static final String param_encryptCertId = "encryptCertId"; /** 用户MAC、IMEI串号、SSID. */ public static final String param_userMac = "userMac"; /** 关联交易. */ // public static final String param_relationTxnType = "relationTxnType"; /** 短信类型 */ public static final String param_smsType = "smsType"; /** 风控信息域 */ public static final String param_riskCtrlInfo = "riskCtrlInfo"; /** IC卡交易信息域 */ public static final String param_ICTransData = "ICTransData"; /** VPC交易信息域 */ public static final String param_VPCTransData = "VPCTransData"; /** 安全类型 */ public static final String param_securityType = "securityType"; /** 银联订单号 */ public static final String param_tn = "tn"; /** 分期付款手续费率 */ public static final String param_instalRate = "instalRate"; /** 分期付款手续费率 */ public static final String param_mchntFeeSubsidy = "mchntFeeSubsidy"; }
smjie2800/spring-cloud-microservice-redis-activemq-hibernate-mysql
microservice-provider-pay/src/main/java/com/boyuanitsm/pay/unionpay/config/SDKConstants.java
Java
mit
13,548
require 'faraday' require 'simple_ratings/foursquare/meta/venue' module SimpleRatings class Foursquare < Faraday::Connection def initialize super(url: 'https://api.foursquare.com/v2/') end def default_params { client_id: ENV['FOURSQUARE_CLIENT_ID'], client_secret: ENV['FOURSQUARE_CLIENT_SECRET'], v: 20130214 } end def search(params) get('venues/search', default_params.merge(params)) end def get(url = nil, params = nil, headers = nil) params ||= {} params = default_params.merge(params) super(url, params, headers) end # def get(*args) # super(*build_default_request_arguments(*args)) # end # def build_default_request_arguments(url = nil, params = nil, headers = nil) # params ||= {} # params = default_params.merge(params) # [url, params, headers] # end end end
benastan/simple_ratings
lib/simple_ratings/foursquare.rb
Ruby
mit
918
// // Copyright (C) 2006-2008 Mateusz Loskot // Distributed under the Boost Software License, Version 1.0. // (See accompanying file LICENSE_1_0.txt or copy at // http://www.boost.org/LICENSE_1_0.txt) // #ifndef SOCI_PLATFORM_H_INCLUDED #define SOCI_PLATFORM_H_INCLUDED #if defined(_MSC_VER) || defined(__MINGW32__) #define LL_FMT_FLAGS "I64" #else #define LL_FMT_FLAGS "ll" #endif // Portability hacks for Microsoft Visual C++ compiler #ifdef _MSC_VER #include <stdlib.h> // Define if you have the vsnprintf variants. #if _MSC_VER < 1500 # define vsnprintf _vsnprintf #endif // Define if you have the snprintf variants. #if _MSC_VER < 1900 #define snprintf _snprintf #endif // Define if you have the strtoll and strtoull variants. #if _MSC_VER < 1300 # error "Visual C++ versions prior 1300 don't support _strtoi64 and _strtoui64" #elif _MSC_VER >= 1300 && _MSC_VER < 1800 namespace std { inline long long strtoll(char const* str, char** str_end, int base) { return _strtoi64(str, str_end, base); } inline unsigned long long strtoull(char const* str, char** str_end, int base) { return _strtoui64(str, str_end, base); } } #endif // _MSC_VER < 1800 #endif // _MSC_VER #if defined(__CYGWIN__) || defined(__MINGW32__) #include <stdlib.h> namespace std { using ::strtoll; using ::strtoull; } #endif #endif // SOCI_PLATFORM_H_INCLUDED
LedgerHQ/lib-ledger-core
core/lib/soci/core/soci-platform.h
C
mit
1,445
using System; using System.Text; namespace ExifLibrary { /// <summary> /// Represents an enumerated value. /// </summary> public class ExifEnumProperty<T> : ExifProperty { protected T mValue; protected bool mIsBitField; protected override object _Value { get { return Value; } set { Value = (T)value; } } public new T Value { get { return mValue; } set { mValue = value; } } public bool IsBitField { get { return mIsBitField; } } static public implicit operator T(ExifEnumProperty<T> obj) { return (T)obj.mValue; } public override string ToString() { return mValue.ToString(); } public ExifEnumProperty(ExifTag tag, T value, bool isbitfield) : base(tag) { mValue = value; mIsBitField = isbitfield; } public ExifEnumProperty(ExifTag tag, T value) : this(tag, value, false) { ; } public override ExifInterOperability Interoperability { get { ushort tagid = ExifTagFactory.GetTagID(mTag); Type type = typeof(T); Type basetype = Enum.GetUnderlyingType(type); if (type == typeof(FileSource) || type == typeof(SceneType)) { // UNDEFINED return new ExifInterOperability(tagid, 7, 1, new byte[] { (byte)((object)mValue) }); } else if (type == typeof(GPSLatitudeRef) || type == typeof(GPSLongitudeRef) || type == typeof(GPSStatus) || type == typeof(GPSMeasureMode) || type == typeof(GPSSpeedRef) || type == typeof(GPSDirectionRef) || type == typeof(GPSDistanceRef)) { // ASCII return new ExifInterOperability(tagid, 2, 2, new byte[] { (byte)((object)mValue), 0 }); } else if (basetype == typeof(byte)) { // BYTE return new ExifInterOperability(tagid, 1, 1, new byte[] { (byte)((object)mValue) }); } else if (basetype == typeof(ushort)) { // SHORT return new ExifInterOperability(tagid, 3, 1, ExifBitConverter.GetBytes((ushort)((object)mValue), BitConverterEx.SystemByteOrder, BitConverterEx.SystemByteOrder)); } else throw new UnknownEnumTypeException(); } } } /// <summary> /// Represents an ASCII string. (EXIF Specification: UNDEFINED) Used for the UserComment field. /// </summary> public class ExifEncodedString : ExifProperty { protected string mValue; private Encoding mEncoding; protected override object _Value { get { return Value; } set { Value = (string)value; } } public new string Value { get { return mValue; } set { mValue = value; } } public Encoding Encoding { get { return mEncoding; } set { mEncoding = value; } } static public implicit operator string(ExifEncodedString obj) { return obj.mValue; } public override string ToString() { return mValue; } public ExifEncodedString(ExifTag tag, string value, Encoding encoding) : base(tag) { mValue = value; mEncoding = encoding; } public override ExifInterOperability Interoperability { get { string enc = ""; if (mEncoding == null) enc = "\0\0\0\0\0\0\0\0"; else if (mEncoding.EncodingName == "US-ASCII") enc = "ASCII\0\0\0"; else if (mEncoding.EncodingName == "Japanese (JIS 0208-1990 and 0212-1990)") enc = "JIS\0\0\0\0\0"; else if (mEncoding.EncodingName == "Unicode") enc = "Unicode\0"; else enc = "\0\0\0\0\0\0\0\0"; byte[] benc = Encoding.ASCII.GetBytes(enc); byte[] bstr = (mEncoding == null ? Encoding.ASCII.GetBytes(mValue) : mEncoding.GetBytes(mValue)); byte[] data = new byte[benc.Length + bstr.Length]; Array.Copy(benc, 0, data, 0, benc.Length); Array.Copy(bstr, 0, data, benc.Length, bstr.Length); return new ExifInterOperability(ExifTagFactory.GetTagID(mTag), 7, (uint)data.Length, data); } } } /// <summary> /// Represents an ASCII string formatted as DateTime. (EXIF Specification: ASCII) Used for the date time fields. /// </summary> public class ExifDateTime : ExifProperty { protected DateTime mValue; protected override object _Value { get { return Value; } set { Value = (DateTime)value; } } public new DateTime Value { get { return mValue; } set { mValue = value; } } static public implicit operator DateTime(ExifDateTime obj) { return obj.mValue; } public override string ToString() { return mValue.ToString("yyyy.MM.dd HH:mm:ss"); } public ExifDateTime(ExifTag tag, DateTime value) : base(tag) { mValue = value; } public override ExifInterOperability Interoperability { get { return new ExifInterOperability(ExifTagFactory.GetTagID(mTag), 2, (uint)20, ExifBitConverter.GetBytes(mValue, true)); } } } /// <summary> /// Represents the exif version as a 4 byte ASCII string. (EXIF Specification: UNDEFINED) /// Used for the ExifVersion, FlashpixVersion, InteroperabilityVersion and GPSVersionID fields. /// </summary> public class ExifVersion : ExifProperty { protected string mValue; protected override object _Value { get { return Value; } set { Value = (string)value; } } public new string Value { get { return mValue; } set { mValue = value.Substring(0, 4); } } public ExifVersion(ExifTag tag, string value) : base(tag) { if (value.Length > 4) mValue = value.Substring(0, 4); else if (value.Length < 4) mValue = value + new string(' ', 4 - value.Length); else mValue = value; } public override string ToString() { return mValue; } public override ExifInterOperability Interoperability { get { if (mTag == ExifTag.ExifVersion || mTag == ExifTag.FlashpixVersion || mTag == ExifTag.InteroperabilityVersion) return new ExifInterOperability(ExifTagFactory.GetTagID(mTag), 7, 4, Encoding.ASCII.GetBytes(mValue)); else { byte[] data = new byte[4]; for (int i = 0; i < 4; i++) data[i] = byte.Parse(mValue[0].ToString()); return new ExifInterOperability(ExifTagFactory.GetTagID(mTag), 7, 4, data); } } } } /// <summary> /// Represents the location and area of the subject (EXIF Specification: 2xSHORT) /// The coordinate values, width, and height are expressed in relation to the /// upper left as origin, prior to rotation processing as per the Rotation tag. /// </summary> public class ExifPointSubjectArea : ExifUShortArray { protected new ushort[] Value { get { return mValue; } set { mValue = value; } } public ushort X { get { return mValue[0]; } set { mValue[0] = value; } } public ushort Y { get { return mValue[1]; } set { mValue[1] = value; } } public override string ToString() { StringBuilder sb = new StringBuilder(); sb.AppendFormat("({0:d}, {1:d})", mValue[0], mValue[1]); return sb.ToString(); } public ExifPointSubjectArea(ExifTag tag, ushort[] value) : base(tag, value) { ; } public ExifPointSubjectArea(ExifTag tag, ushort x, ushort y) : base(tag, new ushort[] { x, y }) { ; } } /// <summary> /// Represents the location and area of the subject (EXIF Specification: 3xSHORT) /// The coordinate values, width, and height are expressed in relation to the /// upper left as origin, prior to rotation processing as per the Rotation tag. /// </summary> public class ExifCircularSubjectArea : ExifPointSubjectArea { public ushort Diamater { get { return mValue[2]; } set { mValue[2] = value; } } public override string ToString() { StringBuilder sb = new StringBuilder(); sb.AppendFormat("({0:d}, {1:d}) {2:d}", mValue[0], mValue[1], mValue[2]); return sb.ToString(); } public ExifCircularSubjectArea(ExifTag tag, ushort[] value) : base(tag, value) { ; } public ExifCircularSubjectArea(ExifTag tag, ushort x, ushort y, ushort d) : base(tag, new ushort[] { x, y, d }) { ; } } /// <summary> /// Represents the location and area of the subject (EXIF Specification: 4xSHORT) /// The coordinate values, width, and height are expressed in relation to the /// upper left as origin, prior to rotation processing as per the Rotation tag. /// </summary> public class ExifRectangularSubjectArea : ExifPointSubjectArea { public ushort Width { get { return mValue[2]; } set { mValue[2] = value; } } public ushort Height { get { return mValue[3]; } set { mValue[3] = value; } } public override string ToString() { StringBuilder sb = new StringBuilder(); sb.AppendFormat("({0:d}, {1:d}) ({2:d} x {3:d})", mValue[0], mValue[1], mValue[2], mValue[3]); return sb.ToString(); } public ExifRectangularSubjectArea(ExifTag tag, ushort[] value) : base(tag, value) { ; } public ExifRectangularSubjectArea(ExifTag tag, ushort x, ushort y, ushort w, ushort h) : base(tag, new ushort[] { x, y, w, h }) { ; } } /// <summary> /// Represents GPS latitudes and longitudes (EXIF Specification: 3xRATIONAL) /// </summary> public class GPSLatitudeLongitude : ExifURationalArray { protected new MathEx.UFraction32[] Value { get { return mValue; } set { mValue = value; } } public MathEx.UFraction32 Degrees { get { return mValue[0]; } set { mValue[0] = value; } } public MathEx.UFraction32 Minutes { get { return mValue[1]; } set { mValue[1] = value; } } public MathEx.UFraction32 Seconds { get { return mValue[2]; } set { mValue[2] = value; } } public static explicit operator float(GPSLatitudeLongitude obj) { return obj.ToFloat(); } public float ToFloat() { return (float)Degrees + ((float)Minutes) / 60.0f + ((float)Seconds) / 3600.0f; } public override string ToString() { return string.Format("{0:F2}°{1:F2}'{2:F2}\"", (float)Degrees, (float)Minutes, (float)Seconds); } public GPSLatitudeLongitude(ExifTag tag, MathEx.UFraction32[] value) : base(tag, value) { ; } public GPSLatitudeLongitude(ExifTag tag, float d, float m, float s) : base(tag, new MathEx.UFraction32[] { new MathEx.UFraction32(d), new MathEx.UFraction32(m), new MathEx.UFraction32(s) }) { ; } } /// <summary> /// Represents a GPS time stamp as UTC (EXIF Specification: 3xRATIONAL) /// </summary> public class GPSTimeStamp : ExifURationalArray { protected new MathEx.UFraction32[] Value { get { return mValue; } set { mValue = value; } } public MathEx.UFraction32 Hour { get { return mValue[0]; } set { mValue[0] = value; } } public MathEx.UFraction32 Minute { get { return mValue[1]; } set { mValue[1] = value; } } public MathEx.UFraction32 Second { get { return mValue[2]; } set { mValue[2] = value; } } public override string ToString() { return string.Format("{0:F2}:{1:F2}:{2:F2}\"", (float)Hour, (float)Minute, (float)Second); } public GPSTimeStamp(ExifTag tag, MathEx.UFraction32[] value) : base(tag, value) { ; } public GPSTimeStamp(ExifTag tag, float h, float m, float s) : base(tag, new MathEx.UFraction32[] { new MathEx.UFraction32(h), new MathEx.UFraction32(m), new MathEx.UFraction32(s) }) { ; } } /// <summary> /// Represents an ASCII string. (EXIF Specification: BYTE) /// Used by Windows XP. /// </summary> public class WindowsByteString : ExifProperty { protected string mValue; protected override object _Value { get { return Value; } set { Value = (string)value; } } public new string Value { get { return mValue; } set { mValue = value; } } static public implicit operator string(WindowsByteString obj) { return obj.mValue; } public override string ToString() { return mValue; } public WindowsByteString(ExifTag tag, string value) : base(tag) { mValue = value; } public override ExifInterOperability Interoperability { get { byte[] data = Encoding.Unicode.GetBytes(mValue); return new ExifInterOperability(ExifTagFactory.GetTagID(mTag), 1, (uint)data.Length, data); } } } }
ahzf/ExifLibrary
ExifLibrary/ExifExtendedProperty.cs
C#
mit
13,977
using System.Collections.Generic; using System.Threading.Tasks; using MongoDB.Bson; using MongoDB.Driver; using ShowFinder.Models; namespace ShowFinder.Repositories.Interfaces { public interface IMongoRepository { IMongoDatabase Database(string name); Task<BsonDocument> GetUserProfile(IMongoCollection<BsonDocument> userProfilesCollection, string hash); Task<bool> UpdateShows(IMongoCollection<BsonDocument> userProfilesCollection, string userHash, IEnumerable<string> showList); Task<bool> UpdateDownloadedEpisode(IMongoCollection<BsonDocument> userProfilesCollection, string profileId, string episodeId, string filteredShowName, DownloadedEpisode downloadedEpisodeData); Task<bool> DeleteDownloadedEpisode(IMongoCollection<BsonDocument> userProfilesCollection, string profileId, string episodeId, string filtereShowdName); Task<bool> UpdateTimeSpan(IMongoCollection<BsonDocument> userProfilesCollection, UserProfile profile); Task<BsonDocument> GetFromCache(IMongoCollection<BsonDocument> collection, string id); Task<bool> SetToCache(IMongoCollection<BsonDocument> collection, string id, BsonDocument doc, int daysToExpire); } }
YanivHaramati/ShowFinder
ShowFinder/Repositories/Interfaces/IMongoRepository.cs
C#
mit
1,257
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv="Content-Type" content="text/xhtml;charset=UTF-8"/> <meta http-equiv="X-UA-Compatible" content="IE=9"/> <meta name="generator" content="Doxygen 1.8.6"/> <title>/home/pavm/programming/lib/gft/src/gft_stack.cpp File Reference</title> <link href="tabs.css" rel="stylesheet" type="text/css"/> <script type="text/javascript" src="jquery.js"></script> <script type="text/javascript" src="dynsections.js"></script> <link href="doxygen.css" rel="stylesheet" type="text/css" /> </head> <body> <div id="top"><!-- do not remove this div, it is closed by doxygen! --> <!-- end header part --> <!-- Generated by Doxygen 1.8.6 --> <div id="navrow1" class="tabs"> <ul class="tablist"> <li><a href="index.html"><span>Main&#160;Page</span></a></li> <li><a href="namespaces.html"><span>Namespaces</span></a></li> <li><a href="annotated.html"><span>Classes</span></a></li> <li class="current"><a href="files.html"><span>Files</span></a></li> </ul> </div> <div id="navrow2" class="tabs2"> <ul class="tablist"> <li><a href="files.html"><span>File&#160;List</span></a></li> <li><a href="globals.html"><span>File&#160;Members</span></a></li> </ul> </div> <div id="nav-path" class="navpath"> <ul> <li class="navelem"><a class="el" href="dir_68267d1309a1af8e8297ef4c3efbcdba.html">src</a></li> </ul> </div> </div><!-- top --> <div class="header"> <div class="summary"> <a href="#namespaces">Namespaces</a> &#124; <a href="#func-members">Functions</a> </div> <div class="headertitle"> <div class="title">gft_stack.cpp File Reference</div> </div> </div><!--header--> <div class="contents"> <div class="textblock"><code>#include &quot;<a class="el" href="gft__stack_8h_source.html">gft_stack.h</a>&quot;</code><br/> </div><table class="memberdecls"> <tr class="heading"><td colspan="2"><h2 class="groupheader"><a name="namespaces"></a> Namespaces</h2></td></tr> <tr class="memitem:namespacegft"><td class="memItemLeft" align="right" valign="top">&#160;</td><td class="memItemRight" valign="bottom"><a class="el" href="namespacegft.html">gft</a></td></tr> <tr class="memdesc:namespacegft"><td class="mdescLeft">&#160;</td><td class="mdescRight">Base namespace for common definitions and prototypes. <br/></td></tr> <tr class="separator:"><td class="memSeparator" colspan="2">&#160;</td></tr> <tr class="memitem:namespacegft_1_1Stack"><td class="memItemLeft" align="right" valign="top">&#160;</td><td class="memItemRight" valign="bottom"><a class="el" href="namespacegft_1_1Stack.html">gft::Stack</a></td></tr> <tr class="separator:"><td class="memSeparator" colspan="2">&#160;</td></tr> </table><table class="memberdecls"> <tr class="heading"><td colspan="2"><h2 class="groupheader"><a name="func-members"></a> Functions</h2></td></tr> <tr class="memitem:aae4b11552918128f72c2c0ce6769ea00"><td class="memItemLeft" align="right" valign="top">Stack *&#160;</td><td class="memItemRight" valign="bottom"><a class="el" href="namespacegft_1_1Stack.html#aae4b11552918128f72c2c0ce6769ea00">gft::Stack::Create</a> (int n)</td></tr> <tr class="separator:aae4b11552918128f72c2c0ce6769ea00"><td class="memSeparator" colspan="2">&#160;</td></tr> <tr class="memitem:ac9833a76111d61f284fe131a8439ea79"><td class="memItemLeft" align="right" valign="top">void&#160;</td><td class="memItemRight" valign="bottom"><a class="el" href="namespacegft_1_1Stack.html#ac9833a76111d61f284fe131a8439ea79">gft::Stack::Destroy</a> (Stack **S)</td></tr> <tr class="separator:ac9833a76111d61f284fe131a8439ea79"><td class="memSeparator" colspan="2">&#160;</td></tr> <tr class="memitem:a9d1618c9defa1ad3e683b7c57d0e3075"><td class="memItemLeft" align="right" valign="top">void&#160;</td><td class="memItemRight" valign="bottom"><a class="el" href="namespacegft_1_1Stack.html#a9d1618c9defa1ad3e683b7c57d0e3075">gft::Stack::Push</a> (Stack *S, int p)</td></tr> <tr class="separator:a9d1618c9defa1ad3e683b7c57d0e3075"><td class="memSeparator" colspan="2">&#160;</td></tr> <tr class="memitem:a58729721489e11127a35700782ed0ae2"><td class="memItemLeft" align="right" valign="top">int&#160;</td><td class="memItemRight" valign="bottom"><a class="el" href="namespacegft_1_1Stack.html#a58729721489e11127a35700782ed0ae2">gft::Stack::Pop</a> (Stack *S)</td></tr> <tr class="separator:a58729721489e11127a35700782ed0ae2"><td class="memSeparator" colspan="2">&#160;</td></tr> </table> </div><!-- contents --> <!-- start footer part --> <hr class="footer"/><address class="footer"><small> Generated on Wed Feb 25 2015 10:27:50 by &#160;<a href="http://www.doxygen.org/index.html"> <img class="footer" src="doxygen.png" alt="doxygen"/> </a> 1.8.6 </small></address> </body> </html>
ademirtc/bandeirantes
lib/gft/doc/html/gft__stack_8cpp.html
HTML
mit
4,861
// // BABAudioPlaylist.h // Pods // // Created by Bryn Bodayle on May/12/2015. // // #import <Foundation/Foundation.h> @interface BABAudioPlaylist : NSObject + (instancetype)audioPlaylistWithArray:(NSArray *)array; - (instancetype)initWithArray:(NSArray *)array; - (id)objectAtIndexedSubscript:(NSUInteger)idx; - (void)setObject:(id)obj atIndexedSubscript:(NSUInteger)idx; @property (nonatomic, readonly) NSInteger count; @end
brynbodayle/BABAudioPlayer
Pod/Classes/BABAudioPlaylist.h
C
mit
437
/*! * Module dependencies. */ var util = require('util'), moment = require('moment'), super_ = require('../Type'); /** * Date FieldType Constructor * @extends Field * @api public */ function datearray(list, path, options) { this._nativeType = [Date]; this._defaultSize = 'medium'; this._underscoreMethods = ['format']; this._properties = ['formatString']; this.parseFormatString = options.parseFormat || 'YYYY-MM-DD'; this.formatString = (options.format === false) ? false : (options.format || 'Do MMM YYYY'); if (this.formatString && 'string' !== typeof this.formatString) { throw new Error('FieldType.Date: options.format must be a string.'); } datearray.super_.call(this, list, path, options); } /*! * Inherit from Field */ util.inherits(datearray, super_); /** * Formats the field value * * @api public */ datearray.prototype.format = function(item, format) { if (format || this.formatString) { return item.get(this.path) ? moment(item.get(this.path)).format(format || this.formatString) : ''; } else { return item.get(this.path) || ''; } }; /** * Checks that a valid array of dates has been provided in a data object * * An empty value clears the stored value and is considered valid * * @api public */ datearray.prototype.inputIsValid = function(data, required, item) { var value = this.getValueFromData(data); var parseFormatString = this.parseFormatString; if ('string' === typeof value) { if (!moment(value, parseFormatString).isValid()) { return false; } value = [value]; } if (required) { if (value === undefined && item && item.get(this.path) && item.get(this.path).length) { return true; } if (value === undefined || !Array.isArray(value)) { return false; } if (Array.isArray(value) && !value.length) { return false; } } if (Array.isArray(value)) { // filter out empty fields value = value.filter(function(date) { return date.trim() !== ''; }); // if there are no values left, and requried is true, return false if (required && !value.length) { return false; } // if any date in the array is invalid, return false if (value.some(function (dateValue) { return !moment(dateValue, parseFormatString).isValid(); })) { return false; } } return (value === undefined || Array.isArray(value)); }; /** * Updates the value for this field in the item from a data object * * @api public */ datearray.prototype.updateItem = function(item, data, callback) { var value = this.getValueFromData(data); if (value !== undefined) { if (Array.isArray(value)) { // Only save valid dates value = value.filter(function(date) { return moment(date).isValid(); }); } if (value === null) { value = []; } if ('string' === typeof value) { if (moment(value).isValid()) { value = [value]; } } if (Array.isArray(value)) { item.set(this.path, value); } } else item.set(this.path, []); process.nextTick(callback); }; /*! * Export class */ module.exports = datearray;
riyadhalnur/keystone
fields/types/datearray/DateArrayType.js
JavaScript
mit
3,038
# -*- coding: utf-8 -*- require "em-websocket" require "eventmachine-tail" module Tailer # Extends FileTail to push data tailed to an EM::Channel. All open websockets # subscribe to a channel for the request stack and this pushes the data to # all of them at once. class StackTail < EventMachine::FileTail def initialize(filename, channel, startpos=-1) super(filename, startpos) @channel = channel @buffer = BufferedTokenizer.new end # This method is called whenever FileTail receives an inotify event for # the tailed file. It breaks up the data per line and pushes a line at a # time. This is to prevent the last javascript line from being broken up # over 2 pushes thus breaking the eval on the front end. def receive_data(data) # replace non UTF-8 characters with ? data.encode!('UTF-8', invalid: :replace, undef: :replace, replace: '�') @buffer.extract(data).each do |line| @channel.push line end end end # Checks if stack log symlink exists and creates Tailer for it def self.stack_tail(stack, channel, channel_count) if Deployinator.get_visible_stacks.include?(stack) filename = "#{Deployinator::Helpers::RUN_LOG_PATH}current-#{stack}" start_pos = (channel_count == 0) ? 0 : -1 File.exists?(filename) ? StackTail.new(filename, channel, start_pos) : false end end end
etsy/deployinator
lib/deployinator/stack-tail.rb
Ruby
mit
1,403
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <!--NewPage--> <HTML> <HEAD> <!-- Generated by javadoc (build 1.5.0_05) on Thu Jul 03 13:49:54 PDT 2008 --> <TITLE> edu.sdsc.inca </TITLE> <META NAME="keywords" CONTENT="edu.sdsc.inca package"> <LINK REL ="stylesheet" TYPE="text/css" HREF="../../../stylesheet.css" TITLE="Style"> </HEAD> <BODY BGCOLOR="white"> <FONT size="+1" CLASS="FrameTitleFont"> <A HREF="../../../edu/sdsc/inca/package-summary.html" target="classFrame">edu.sdsc.inca</A></FONT> <TABLE BORDER="0" WIDTH="100%" SUMMARY=""> <TR> <TD NOWRAP><FONT size="+1" CLASS="FrameHeadingFont"> Classes</FONT>&nbsp; <FONT CLASS="FrameItemFont"> <BR> <A HREF="Consumer.html" title="class in edu.sdsc.inca" target="classFrame">Consumer</A> <BR> <A HREF="ConsumerTest.html" title="class in edu.sdsc.inca" target="classFrame">ConsumerTest</A> <BR> <A HREF="ConsumerTest.ConsumerTester.html" title="class in edu.sdsc.inca" target="classFrame">ConsumerTest.ConsumerTester</A> <BR> <A HREF="ConsumerTest.MockAgent.html" title="class in edu.sdsc.inca" target="classFrame">ConsumerTest.MockAgent</A> <BR> <A HREF="ConsumerTest.MockDepot.html" title="class in edu.sdsc.inca" target="classFrame">ConsumerTest.MockDepot</A></FONT></TD> </TR> </TABLE> </BODY> </HTML>
IncaProject/IncaProject.github.io
releases/2.4/docs/javadocs/inca-consumers/edu/sdsc/inca/package-frame.html
HTML
mit
1,321
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. namespace DotNetty.Transport.Channels.Sockets { using System; using System.Diagnostics.Contracts; using System.Net; using System.Net.NetworkInformation; using System.Net.Sockets; public class DefaultDatagramChannelConfig : DefaultChannelConfiguration, IDatagramChannelConfig { const int DefaultFixedBufferSize = 2048; readonly Socket socket; public DefaultDatagramChannelConfig(IDatagramChannel channel, Socket socket) : base(channel, new FixedRecvByteBufAllocator(DefaultFixedBufferSize)) { Contract.Requires(socket != null); this.socket = socket; } public override T GetOption<T>(ChannelOption<T> option) { if (ChannelOption.SoBroadcast.Equals(option)) { return (T)(object)this.Broadcast; } if (ChannelOption.SoRcvbuf.Equals(option)) { return (T)(object)this.ReceiveBufferSize; } if (ChannelOption.SoSndbuf.Equals(option)) { return (T)(object)this.SendBufferSize; } if (ChannelOption.SoReuseaddr.Equals(option)) { return (T)(object)this.ReuseAddress; } if (ChannelOption.IpMulticastLoopDisabled.Equals(option)) { return (T)(object)this.LoopbackModeDisabled; } if (ChannelOption.IpMulticastTtl.Equals(option)) { return (T)(object)this.TimeToLive; } if (ChannelOption.IpMulticastAddr.Equals(option)) { return (T)(object)this.Interface; } if (ChannelOption.IpMulticastIf.Equals(option)) { return (T)(object)this.NetworkInterface; } if (ChannelOption.IpTos.Equals(option)) { return (T)(object)this.TrafficClass; } return base.GetOption(option); } public override bool SetOption<T>(ChannelOption<T> option, T value) { if (base.SetOption(option, value)) { return true; } if (ChannelOption.SoBroadcast.Equals(option)) { this.Broadcast = (bool)(object)value; } else if (ChannelOption.SoRcvbuf.Equals(option)) { this.ReceiveBufferSize = (int)(object)value; } else if (ChannelOption.SoSndbuf.Equals(option)) { this.SendBufferSize = (int)(object)value; } else if (ChannelOption.SoReuseaddr.Equals(option)) { this.ReuseAddress = (bool)(object)value; } else if (ChannelOption.IpMulticastLoopDisabled.Equals(option)) { this.LoopbackModeDisabled = (bool)(object)value; } else if (ChannelOption.IpMulticastTtl.Equals(option)) { this.TimeToLive = (short)(object)value; } else if (ChannelOption.IpMulticastAddr.Equals(option)) { this.Interface = (EndPoint)(object)value; } else if (ChannelOption.IpMulticastIf.Equals(option)) { this.NetworkInterface = (NetworkInterface)(object)value; } else if (ChannelOption.IpTos.Equals(option)) { this.TrafficClass = (int)(object)value; } else { return false; } return true; } public int SendBufferSize { get { try { return this.socket.SendBufferSize; } catch (ObjectDisposedException ex) { throw new ChannelException(ex); } catch (SocketException ex) { throw new ChannelException(ex); } } set { try { this.socket.SendBufferSize = value; } catch (ObjectDisposedException ex) { throw new ChannelException(ex); } catch (SocketException ex) { throw new ChannelException(ex); } } } public int ReceiveBufferSize { get { try { return this.socket.ReceiveBufferSize; } catch (ObjectDisposedException ex) { throw new ChannelException(ex); } catch (SocketException ex) { throw new ChannelException(ex); } } set { try { this.socket.ReceiveBufferSize = value; } catch (ObjectDisposedException ex) { throw new ChannelException(ex); } catch (SocketException ex) { throw new ChannelException(ex); } } } public int TrafficClass { get { try { return (int)this.socket.GetSocketOption(SocketOptionLevel.Socket, SocketOptionName.TypeOfService); } catch (ObjectDisposedException ex) { throw new ChannelException(ex); } catch (SocketException ex) { throw new ChannelException(ex); } } set { try { this.socket.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.TypeOfService, value); } catch (ObjectDisposedException ex) { throw new ChannelException(ex); } catch (SocketException ex) { throw new ChannelException(ex); } } } public bool ReuseAddress { get { try { return (int)this.socket.GetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReuseAddress) != 0; } catch (ObjectDisposedException ex) { throw new ChannelException(ex); } catch (SocketException ex) { throw new ChannelException(ex); } } set { try { this.socket.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReuseAddress, value ? 1 : 0); } catch (ObjectDisposedException ex) { throw new ChannelException(ex); } catch (SocketException ex) { throw new ChannelException(ex); } } } public bool Broadcast { get { try { return this.socket.EnableBroadcast; } catch (ObjectDisposedException ex) { throw new ChannelException(ex); } catch (SocketException ex) { throw new ChannelException(ex); } } set { try { this.socket.EnableBroadcast = value; } catch (ObjectDisposedException ex) { throw new ChannelException(ex); } catch (SocketException ex) { throw new ChannelException(ex); } } } public bool LoopbackModeDisabled { get { try { return !this.socket.MulticastLoopback; } catch (ObjectDisposedException ex) { throw new ChannelException(ex); } catch (SocketException ex) { throw new ChannelException(ex); } } set { try { this.socket.MulticastLoopback = !value; } catch (ObjectDisposedException ex) { throw new ChannelException(ex); } catch (SocketException ex) { throw new ChannelException(ex); } } } public short TimeToLive { get { try { return (short)this.socket.GetSocketOption( this.AddressFamilyOptionLevel, SocketOptionName.MulticastTimeToLive); } catch (ObjectDisposedException ex) { throw new ChannelException(ex); } catch (SocketException ex) { throw new ChannelException(ex); } } set { try { this.socket.SetSocketOption( this.AddressFamilyOptionLevel, SocketOptionName.MulticastTimeToLive, value); } catch (ObjectDisposedException ex) { throw new ChannelException(ex); } catch (SocketException ex) { throw new ChannelException(ex); } } } public EndPoint Interface { get { try { return this.socket.LocalEndPoint; } catch (ObjectDisposedException ex) { throw new ChannelException(ex); } catch (SocketException ex) { throw new ChannelException(ex); } } set { Contract.Requires(value != null); try { this.socket.Bind(value); } catch (ObjectDisposedException ex) { throw new ChannelException(ex); } catch (SocketException ex) { throw new ChannelException(ex); } } } public NetworkInterface NetworkInterface { get { try { NetworkInterface[] interfaces = NetworkInterface.GetAllNetworkInterfaces(); int value = (int)this.socket.GetSocketOption( this.AddressFamilyOptionLevel, SocketOptionName.MulticastInterface); int index = IPAddress.NetworkToHostOrder(value); if (interfaces.Length > 0 && index >= 0 && index < interfaces.Length) { return interfaces[index]; } return null; } catch (ObjectDisposedException ex) { throw new ChannelException(ex); } catch (SocketException ex) { throw new ChannelException(ex); } } set { Contract.Requires(value != null); try { int index = this.GetNetworkInterfaceIndex(value); if (index >= 0) { this.socket.SetSocketOption( this.AddressFamilyOptionLevel, SocketOptionName.MulticastInterface, index); } } catch (ObjectDisposedException ex) { throw new ChannelException(ex); } catch (SocketException ex) { throw new ChannelException(ex); } } } internal SocketOptionLevel AddressFamilyOptionLevel { get { if (this.socket.AddressFamily == AddressFamily.InterNetwork) { return SocketOptionLevel.IP; } if (this.socket.AddressFamily == AddressFamily.InterNetworkV6) { return SocketOptionLevel.IPv6; } throw new NotSupportedException($"Socket address family {this.socket.AddressFamily} not supported, expecting InterNetwork or InterNetworkV6"); } } internal int GetNetworkInterfaceIndex(NetworkInterface networkInterface) { Contract.Requires(networkInterface != null); NetworkInterface[] interfaces = NetworkInterface.GetAllNetworkInterfaces(); for (int index = 0; index < interfaces.Length; index++) { if (interfaces[index].Id == networkInterface.Id) { return index; } } return -1; } } }
dragonphoenix/proto-java-csharp
DotNetty/DotNetty.Transport/Channels/Sockets/DefaultDatagramChannelConfig.cs
C#
mit
14,695
/* * Search first occurence of a particular string in a given text [Finite Automata] * Author: Progyan Bhattacharya <[email protected]> * Repo: Design-And-Analysis-of-Algorithm [MIT LICENSE] */ #include "Search.h" static int NextState(int m, char* pattern, int state, int symbol) { if (state < m && pattern[state] == symbol) { return state + 1; } for (int next = state, prev = next - 1, i = 0; next > 0; next--) { if (pattern[prev] == symbol) { for (i = 0; i < prev; i++) { if (pattern[i] != pattern[state - next + 1 + i]) { break; } } if (i == prev) { return next; } } } return 0; } static void GenerateTable(int m, char* pattern, int Table[m][CHAR_MAX]) { for (int state = 0, symbol = 0; symbol < CHAR_MAX || (symbol = 0, ++state) < m; symbol++) { Table[state][symbol] = NextState(m, pattern, state, symbol); } } int Search(int n, char* haystack, int m, char* needle) { int Table[m + 1][CHAR_MAX], state = 0; GenerateTable(m + 1, needle, Table); for (int i = 0; i < n; i++) { state = Table[state][haystack[i]]; if (state == m) { return (i - m + 1); } } return -1; }
Progyan1997/Design-and-Analysis-of-Algorithm
String Search/Finite Automata/Search.c
C
mit
1,307
require File.expand_path(File.dirname(__FILE__) + '/../spec_helper') class Video include Claire::Client::Item end describe Claire::Client::Item do #@session.should_receive(:post).with("url", "data", "headers") #@session = mock("session") before do Claire::Client.stub(:get).with('videos/id').and_return xml :item @video = Video.new(hash_from_xml(:item)) end describe "its initializer" do describe "its base_url class attribute" do it "should default to the class name, pluralized" do Video.base_url.should == "videos" end it "should accept manual overwrite on the class" do Video.base_url = "lists" Video.base_url.should == "lists" Video.base_url = nil Video.base_url.should == "videos" end it "if the class is in a module, it should get the class name only" do eval %( module Testing class Video include Claire::Client::Item end end ) Testing::Video.base_url.should == "videos" end end context "upon receiving a Hash" do before :each do @video = Video.new(hash_from_xml(:item)) end it "should set partial do true" do @video.should be_partial end it "should skip the <rss> container if it is present" do @video.title.should be_a_kind_of String @video.should_not respond_to :rss end it "should skip the <channel> container if its present" do video = Video.new(hash_from_xml(:item_with_channel)) video.title.should be_a_kind_of String video.should_not respond_to :channel end it "should never set 'items' attributes " do %w(item item_with_channel).each do |type| video = Video.new(hash_from_xml(type)) video.should_not respond_to :item video.title.should be_a_kind_of String end end it "should set the link attribute properly (eg ignoring links to other objects/pages)" do video = Video.new hash_from_xml :item_with_channel video.link.should be_a_kind_of String end it "should set its key/values as properties of the element" do %w(title link category keywords description).each do |item| @video.send(item).should be_a_kind_of String end %w(thumbnail content).each{ |item| @video.send(item).should be_a_kind_of Array } end it "should fail if there is not a link attribute" do lambda { Video.new( {:rss => {:item => {:name => 'bla'}}} ) }.should raise_error Claire::Error end end context "upon receiving a String" do before { @video = Video.new 'id' } it "should open the given string" do lambda { Video.new "" }.should raise_error lambda { Video.new "id" }.should_not raise_error end it "should parse the result using the XML parsing rules" do @video.title.should be_a_kind_of String end it "should set partial to false" do @video.should_not be_partial end end end describe "its comparison (spaceship) operator" do it "should be defined" do @video.should respond_to '<=>' end it "should compare items by title" do @video2 = @video.clone (@video <=> @video2).should be 0 end end context "when an undefined method is called" do it "it should raise error if partial is false" context "if the item is partial" do it "should request the full object from server, and replace itself" it "should return the asked attribute" end end it "should have a list of its children as the children class attribute" do Claire::Client::Item.children.include?(Video).should be true end end
memuller/claire.client
spec/claire_client/item_spec.rb
Ruby
mit
3,595
PathMission =========== ### Prefix: pm ------------------------------------------------------------------------ `Enum` PathMissionDisplayType ---------------------- - **Soldier\_Assassination** - **Soldier\_Defend** - **Soldier\_Demolition** - **Soldier\_FirstStrike** - **Soldier\_Holdout** - **Soldier\_RescueOp** - **Soldier\_Security** - **Soldier\_Swat** - **Settler\_Cache** - **Settler\_CivilService** - **Settler\_Expansion** - **Settler\_Project** - **Settler\_PublicSafety** - **Scientist\_Analysis** - **Scientist\_Archaeology** - **Scientist\_Biology** - **Scientist\_Botany** - **Scientist\_Chemistry** - **Scientist\_DatacubeDecryption** - **Scientist\_Diagnostics** - **Scientist\_Experimentation** - **Scientist\_FieldStudy** - **Scientist\_SpecimenSurvey** - **Explorer\_Cartography** - **Explorer\_Exploration** - **Explorer\_Operations** - **Explorer\_ScavengerHunt** - **Explorer\_StakingClaim** - **Explorer\_Surveillance** - **Explorer\_Tracking** - **Explorer\_Vista** ------------------------------------------------------------------------ `Function` is() ---- ------------------------------------------------------------------------ `Method` \_\_eq() (Deprecated) --------------------- ------------------------------------------------------------------------ `Method` \_\_gc() (Deprecated) --------------------- ------------------------------------------------------------------------ `Method` AttemptScientistExperimentation() --------------------------------- ------------------------------------------------------------------------ `Method` GetCompletedString() -------------------- ------------------------------------------------------------------------ `Method` GetDisplayType() ---------------- ------------------------------------------------------------------------ `Method` GetDistance() ------------- ------------------------------------------------------------------------ `Method` GetEpisode() ------------ ------------------------------------------------------------------------ `Method` GetExplorerClueRatio() ---------------------- ------------------------------------------------------------------------ `Method` GetExplorerClueStatus() ----------------------- ------------------------------------------------------------------------ `Method` GetExplorerClueString() ----------------------- ------------------------------------------------------------------------ `Method` GetExplorerClueType() --------------------- ------------------------------------------------------------------------ `Method` GetExplorerHuntSprite() ----------------------- ------------------------------------------------------------------------ `Method` GetExplorerHuntStartCreature() ------------------------------ ------------------------------------------------------------------------ `Method` GetExplorerHuntStartText() -------------------------- ------------------------------------------------------------------------ `Method` GetExplorerNodeCount() ---------------------- ------------------------------------------------------------------------ `Method` GetExplorerNodeInfo() --------------------- ------------------------------------------------------------------------ `Method` GetExplorerPowerMapInfo() ------------------------- ------------------------------------------------------------------------ `Method` GetExplorerPowerMapReadyText() ------------------------------ ------------------------------------------------------------------------ `Method` GetId() ------- ------------------------------------------------------------------------ `Method` GetMapIcon() ------------ ------------------------------------------------------------------------ `Method` GetMapLocations() ----------------- ------------------------------------------------------------------------ `Method` GetMapRegions() --------------- ------------------------------------------------------------------------ `Method` GetMissionState() ----------------- ------------------------------------------------------------------------ `Method` GetName() --------- ------------------------------------------------------------------------ `Method` GetNumCompleted() ----------------- ------------------------------------------------------------------------ `Method` GetNumNeeded() -------------- ------------------------------------------------------------------------ `Method` GetRewardData() --------------- ------------------------------------------------------------------------ `Method` GetRewardXp() ------------- ------------------------------------------------------------------------ `Method` GetScientistDatacubeDiscoveryZone() ----------------------------------- ------------------------------------------------------------------------ `Method` GetScientistExperimentationCurrentPatterns() -------------------------------------------- ------------------------------------------------------------------------ `Method` GetScientistExperimentationInfo() --------------------------------- ------------------------------------------------------------------------ `Method` GetScientistFieldStudy() ------------------------ ------------------------------------------------------------------------ `Method` GetScientistIcon() ------------------ ------------------------------------------------------------------------ `Method` GetScientistSpecimenSurvey() ---------------------------- ------------------------------------------------------------------------ `Method` GetSettlerMayorInfo() --------------------- ------------------------------------------------------------------------ `Method` GetSettlerResourceRegions() --------------------------- ------------------------------------------------------------------------ `Method` GetSettlerScoutInfo() --------------------- ------------------------------------------------------------------------ `Method` GetSettlerSheriffInfo() ----------------------- ------------------------------------------------------------------------ `Method` GetSoldierHoldout() ------------------- ------------------------------------------------------------------------ `Method` GetSpell() ---------- ------------------------------------------------------------------------ `Method` GetSubType() ------------ ------------------------------------------------------------------------ `Method` GetSummary() ------------ ------------------------------------------------------------------------ `Method` GetType() --------- ------------------------------------------------------------------------ `Method` GetUnlockString() ----------------- ------------------------------------------------------------------------ `Method` IsComplete() ------------ ------------------------------------------------------------------------ `Method` IsExplorerPowerMapActive() -------------------------- ------------------------------------------------------------------------ `Method` IsExplorerPowerMapReady() ------------------------- ------------------------------------------------------------------------ `Method` IsInArea() ---------- ------------------------------------------------------------------------ `Method` IsOptional() ------------ ------------------------------------------------------------------------ `Method` IsStarted() ----------- ------------------------------------------------------------------------ `Method` RefreshScientistExperimentation() --------------------------------- ------------------------------------------------------------------------ `Method` ScientistCreatureType\_History() (Deprecated) --------------------------------------------- ------------------------------------------------------------------------ `Method` ShowExplorerClueHintArrow() --------------------------- ------------------------------------------------------------------------ `Method` ShowHintArrow() --------------- ------------------------------------------------------------------------ `Method` ShowPathChecklistHintArrow() ----------------------------
Hammster/wildstar-api-docs
Classes/PathMission.md
Markdown
mit
8,646
<?php namespace Zanson\SMParser\Traits\Song; use Zanson\SMParser\SMException; trait Banner { public $banner = ''; /** * @return string */ public function getBanner() { return $this->banner; } /** * @param string $banner * * @return $this * @throws SMException */ public function setBanner($banner) { if (!is_string($banner)) { throw new SMException("Banner must be a string"); } $this->banner = $banner; return $this; } }
jasonwatt/SMParser
src/Traits/Song/Banner.php
PHP
mit
541
if ( !window.console ) window.console = { log:function(){} }; jQuery(document).ready(function($) { console.log('Keep being awesome.'); });
shampine/180
public/js/src/script.js
JavaScript
mit
143
package parser import ( "monkey/ast" "monkey/token" ) func (p *Parser) parseStringLiteralExpression() ast.Expression { return &ast.StringLiteral{Token: p.curToken, Value: p.curToken.Literal} } func (p *Parser) parseInterpolatedString() ast.Expression { is := &ast.InterpolatedString{Token: p.curToken, Value: p.curToken.Literal, ExprMap: make(map[byte]ast.Expression)} key := "0"[0] for { if p.curTokenIs(token.LBRACE) { p.nextToken() expr := p.parseExpression(LOWEST) is.ExprMap[key] = expr key++ } p.nextInterpToken() if p.curTokenIs(token.ISTRING) { break } } return is }
mayoms/monkey
parser/strings.go
GO
mit
612
using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Windows.Forms; using System.Timers; using System.Diagnostics; namespace ForumHelper { public partial class ToastForm : Form { public ToastForm() { InitializeComponent(); TopMost = true; ShowInTaskbar = false; timer = new System.Windows.Forms.Timer(); timer.Interval = 500; timer.Tick += timer_Tick; } private System.Windows.Forms.Timer timer; private int startPosX; private int startPosY; private void ToastForm_Load(object sender, EventArgs e) { } protected override void OnLoad(EventArgs e) { startPosX = Screen.PrimaryScreen.WorkingArea.Width - Width; startPosY = Screen.PrimaryScreen.WorkingArea.Height - Height; SetDesktopLocation(startPosX, startPosY); pageLinkLabel.Text = URLEventArgs.Url; // base.OnLoad(e); timer.Start(); } void timer_Tick(object sender, EventArgs e) { startPosY -= 50; if (startPosY < Screen.PrimaryScreen.WorkingArea.Height - Height) timer.Stop(); else { SetDesktopLocation(startPosX, startPosY); timer.Stop(); } } private void ToastForm_Click(object sender, EventArgs e) { this.Close(); } private void pageLinkLabelClick(object sender, EventArgs e) { Process.Start(this.pageLinkLabel.Text); this.Close(); } } }
ttitto/PersonalProjects
ForumHelper/ForumHelper/ToastForm.cs
C#
mit
1,852
<?php /* * The MIT License (MIT) * * Copyright (c) 2014-2018 Spomky-Labs * * This software may be modified and distributed under the terms * of the MIT license. See the LICENSE file for details. */ use Base64Url\Base64Url; use Jose\Decrypter; use Jose\Encrypter; use Jose\Factory\JWEFactory; use Jose\Loader; use Jose\Object\JWEInterface; use Jose\Object\JWK; use Jose\Object\JWKSet; use Jose\Test\Stub\FakeLogger; use Jose\Test\BaseTestCase; /** * Class EncrypterTest. * * @group Encrypter * @group Functional */ class EncrypterBaseTest extends BaseTestCase { public function testEncryptWithJWTInput() { $encrypter = Encrypter::createEncrypter(['RSA-OAEP-256'], ['A256CBC-HS512'], ['DEF'], new FakeLogger()); $decrypter = Decrypter::createDecrypter(['RSA-OAEP-256'], ['A256CBC-HS512'], ['DEF'], new FakeLogger()); $jwe = JWEFactory::createJWE( 'FOO', [ 'enc' => 'A256CBC-HS512', 'alg' => 'RSA-OAEP-256', 'zip' => 'DEF', ], [], 'foo,bar,baz' ); $jwe = $jwe->addRecipientInformation($this->getRSARecipientKey()); $encrypter->encrypt($jwe); $encrypted = $jwe->toFlattenedJSON(0); $loader = new Loader(new FakeLogger()); $loaded = $loader->load($encrypted); self::assertInstanceOf(JWEInterface::class, $loaded); self::assertEquals('RSA-OAEP-256', $loaded->getSharedProtectedHeader('alg')); self::assertEquals('A256CBC-HS512', $loaded->getSharedProtectedHeader('enc')); self::assertEquals('DEF', $loaded->getSharedProtectedHeader('zip')); self::assertNull($loaded->getPayload()); $decrypter->decryptUsingKeySet($loaded, $this->getPrivateKeySet(), $index); self::assertEquals(0, $index); self::assertEquals('FOO', $loaded->getPayload()); } public function testCreateCompactJWEUsingFactory() { $jwe = JWEFactory::createJWEToCompactJSON( 'FOO', $this->getRSARecipientKey(), [ 'enc' => 'A256CBC-HS512', 'alg' => 'RSA-OAEP-256', 'zip' => 'DEF', ] ); $loader = new Loader(new FakeLogger()); $loaded = $loader->load($jwe); self::assertInstanceOf(JWEInterface::class, $loaded); self::assertEquals('RSA-OAEP-256', $loaded->getSharedProtectedHeader('alg')); self::assertEquals('A256CBC-HS512', $loaded->getSharedProtectedHeader('enc')); self::assertEquals('DEF', $loaded->getSharedProtectedHeader('zip')); self::assertNull($loaded->getPayload()); $decrypter = Decrypter::createDecrypter(['RSA-OAEP-256'], ['A256CBC-HS512'], ['DEF'], new FakeLogger()); $decrypter->decryptUsingKeySet($loaded, $this->getPrivateKeySet(), $index); self::assertEquals(0, $index); self::assertEquals('FOO', $loaded->getPayload()); } public function testCreateFlattenedJWEUsingFactory() { $jwe = JWEFactory::createJWEToFlattenedJSON( 'FOO', $this->getRSARecipientKey(), [ 'enc' => 'A256CBC-HS512', 'alg' => 'RSA-OAEP-256', 'zip' => 'DEF', ], [ 'foo' => 'bar', ], [ 'plic' => 'ploc', ], 'A,B,C,D' ); $loader = new Loader(new FakeLogger()); $loaded = $loader->load($jwe); self::assertInstanceOf(JWEInterface::class, $loaded); self::assertEquals('RSA-OAEP-256', $loaded->getSharedProtectedHeader('alg')); self::assertEquals('A256CBC-HS512', $loaded->getSharedProtectedHeader('enc')); self::assertEquals('DEF', $loaded->getSharedProtectedHeader('zip')); self::assertEquals('bar', $loaded->getSharedHeader('foo')); self::assertEquals('A,B,C,D', $loaded->getAAD('foo')); self::assertEquals('ploc', $loaded->getRecipient(0)->getHeader('plic')); self::assertNull($loaded->getPayload()); $decrypter = Decrypter::createDecrypter(['RSA-OAEP-256'], ['A256CBC-HS512'], ['DEF'], new FakeLogger()); $decrypter->decryptUsingKeySet($loaded, $this->getPrivateKeySet(), $index); self::assertEquals(0, $index); self::assertEquals('FOO', $loaded->getPayload()); } public function testEncryptAndLoadFlattenedWithAAD() { $encrypter = Encrypter::createEncrypter(['RSA-OAEP-256'], ['A256CBC-HS512'], ['DEF'], new FakeLogger()); $decrypter = Decrypter::createDecrypter(['RSA-OAEP-256'], ['A256CBC-HS512'], ['DEF'], new FakeLogger()); $jwe = JWEFactory::createJWE( $this->getKeyToEncrypt(), [ 'enc' => 'A256CBC-HS512', 'alg' => 'RSA-OAEP-256', 'zip' => 'DEF', ], [], 'foo,bar,baz' ); $jwe = $jwe->addRecipientInformation($this->getRSARecipientKey()); $encrypter->encrypt($jwe); $encrypted = $jwe->toFlattenedJSON(0); $loader = new Loader(new FakeLogger()); $loaded = $loader->load($encrypted); self::assertInstanceOf(JWEInterface::class, $loaded); self::assertEquals('RSA-OAEP-256', $loaded->getSharedProtectedHeader('alg')); self::assertEquals('A256CBC-HS512', $loaded->getSharedProtectedHeader('enc')); self::assertEquals('DEF', $loaded->getSharedProtectedHeader('zip')); self::assertNull($loaded->getPayload()); $decrypter->decryptUsingKeySet($loaded, $this->getPrivateKeySet(), $index); self::assertEquals(0, $index); self::assertTrue(is_array($loaded->getPayload())); self::assertEquals($this->getKeyToEncrypt(), new JWK($loaded->getPayload())); } /** * @expectedException \InvalidArgumentException * @expectedExceptionMessage Compression method "FIP" not supported */ public function testCompressionAlgorithmNotSupported() { $encrypter = Encrypter::createEncrypter(['RSA-OAEP-256'], ['A256CBC-HS512'], ['DEF'], new FakeLogger()); $jwe = JWEFactory::createJWE( $this->getKeyToEncrypt(), [ 'enc' => 'A256CBC-HS512', 'alg' => 'RSA-OAEP-256', 'zip' => 'FIP', ], [], 'foo,bar,baz' ); $jwe = $jwe->addRecipientInformation($this->getRSARecipientKey()); $encrypter->encrypt($jwe); } public function testMultipleInstructionsNotAllowedWithCompactSerialization() { $encrypter = Encrypter::createEncrypter(['RSA-OAEP', 'RSA-OAEP-256'], ['A256CBC-HS512'], ['DEF'], new FakeLogger()); $jwe = JWEFactory::createJWE('Live long and Prosper.'); $jwe = $jwe->withSharedProtectedHeaders([ 'enc' => 'A256CBC-HS512', ]); $jwe = $jwe->addRecipientInformation($this->getRSARecipientKeyWithAlgorithm(), ['alg' => 'RSA-OAEP']); $jwe = $jwe->addRecipientInformation($this->getRSARecipientKey(), ['alg' => 'RSA-OAEP-256']); $encrypter->encrypt($jwe); self::assertEquals(2, $jwe->countRecipients()); } public function testMultipleInstructionsNotAllowedWithFlattenedSerialization() { $encrypter = Encrypter::createEncrypter(['RSA-OAEP-256', 'ECDH-ES+A256KW'], ['A256CBC-HS512'], ['DEF'], new FakeLogger()); $jwe = JWEFactory::createJWE('Live long and Prosper.'); $jwe = $jwe->withSharedProtectedHeaders([ 'enc' => 'A256CBC-HS512', ]); $jwe = $jwe->addRecipientInformation( $this->getECDHRecipientPublicKey(), ['kid' => 'e9bc097a-ce51-4036-9562-d2ade882db0d', 'alg' => 'ECDH-ES+A256KW'] ); $jwe = $jwe->addRecipientInformation( $this->getRSARecipientKey(), ['kid' => '123456789', 'alg' => 'RSA-OAEP-256'] ); $encrypter->encrypt($jwe); self::assertEquals(2, $jwe->countRecipients()); } /** * @expectedException \InvalidArgumentException * @expectedExceptionMessage Foreign key management mode forbidden. */ public function testForeignKeyManagementModeForbidden() { $encrypter = Encrypter::createEncrypter(['dir', 'ECDH-ES+A256KW'], ['A256CBC-HS512'], ['DEF'], new FakeLogger()); $jwe = JWEFactory::createJWE('Live long and Prosper.'); $jwe = $jwe->withSharedProtectedHeaders([ 'enc' => 'A256CBC-HS512', ]); $jwe = $jwe->addRecipientInformation( $this->getECDHRecipientPublicKey(), ['kid' => 'e9bc097a-ce51-4036-9562-d2ade882db0d', 'alg' => 'ECDH-ES+A256KW'] ); $jwe = $jwe->addRecipientInformation( $this->getDirectKey(), ['kid' => 'DIR_1', 'alg' => 'dir'] ); $encrypter->encrypt($jwe); } /** * @expectedException \InvalidArgumentException * @expectedExceptionMessage Key cannot be used to encrypt */ public function testOperationNotAllowedForTheKey() { $encrypter = Encrypter::createEncrypter(['RSA-OAEP-256'], ['A256CBC-HS512'], ['DEF'], new FakeLogger()); $jwe = JWEFactory::createJWE( 'Foo', [ 'enc' => 'A256CBC-HS512', 'alg' => 'RSA-OAEP-256', 'zip' => 'DEF', ], [], 'foo,bar,baz' ); $jwe = $jwe->addRecipientInformation( $this->getSigningKey() ); $encrypter->encrypt($jwe); } /** * @expectedException \InvalidArgumentException * @expectedExceptionMessage Key is only allowed for algorithm "RSA-OAEP". */ public function testAlgorithmNotAllowedForTheKey() { $encrypter = Encrypter::createEncrypter(['RSA-OAEP-256'], ['A256CBC-HS512'], ['DEF'], new FakeLogger()); $jwe = JWEFactory::createJWE( 'FOO', [ 'enc' => 'A256CBC-HS512', 'alg' => 'RSA-OAEP-256', 'zip' => 'DEF', ], [], 'foo,bar,baz' ); $jwe = $jwe->addRecipientInformation( $this->getRSARecipientKeyWithAlgorithm() ); $encrypter->encrypt($jwe); } public function testEncryptAndLoadFlattenedWithDeflateCompression() { $encrypter = Encrypter::createEncrypter(['RSA-OAEP-256'], ['A128CBC-HS256'], ['DEF'], new FakeLogger()); $decrypter = Decrypter::createDecrypter(['RSA-OAEP-256'], ['A128CBC-HS256'], ['DEF'], new FakeLogger()); $jwe = JWEFactory::createJWE($this->getKeySetToEncrypt()); $jwe = $jwe->withSharedProtectedHeaders([ 'kid' => '123456789', 'enc' => 'A128CBC-HS256', 'alg' => 'RSA-OAEP-256', 'zip' => 'DEF', ]); $jwe = $jwe->addRecipientInformation( $this->getRSARecipientKey() ); $encrypter->encrypt($jwe); $encrypted = $jwe->toCompactJSON(0); $loader = new Loader(new FakeLogger()); $loaded = $loader->load($encrypted); self::assertInstanceOf(JWEInterface::class, $loaded); self::assertEquals('RSA-OAEP-256', $loaded->getSharedProtectedHeader('alg')); self::assertEquals('A128CBC-HS256', $loaded->getSharedProtectedHeader('enc')); self::assertEquals('DEF', $loaded->getSharedProtectedHeader('zip')); self::assertNull($loaded->getPayload()); $decrypter->decryptUsingKeySet($loaded, $this->getPrivateKeySet(), $index); self::assertEquals(0, $index); self::assertTrue(is_array($loaded->getPayload())); self::assertEquals($this->getKeySetToEncrypt(), new JWKSet($loaded->getPayload())); } /** * @expectedException \InvalidArgumentException * @expectedExceptionMessage Parameter "alg" is missing. */ public function testAlgParameterIsMissing() { $encrypter = Encrypter::createEncrypter(['A256CBC-HS512'], [], ['DEF'], new FakeLogger()); $jwe = JWEFactory::createJWE($this->getKeyToEncrypt()); $jwe = $jwe->withSharedProtectedHeaders([ 'kid' => '123456789', 'enc' => 'A256CBC-HS512', 'zip' => 'DEF', ]); $jwe = $jwe->addRecipientInformation( $this->getRSARecipientKey() ); $encrypter->encrypt($jwe); } /** * @expectedException \InvalidArgumentException * @expectedExceptionMessage Parameter "enc" is missing. */ public function testEncParameterIsMissing() { $encrypter = Encrypter::createEncrypter(['RSA-OAEP-256'], [], ['DEF'], new FakeLogger()); $jwe = JWEFactory::createJWE($this->getKeyToEncrypt()); $jwe = $jwe->withSharedProtectedHeaders([ 'kid' => '123456789', 'alg' => 'RSA-OAEP-256', 'zip' => 'DEF', ]); $jwe = $jwe->addRecipientInformation( $this->getRSARecipientKey() ); $encrypter->encrypt($jwe); } /** * @expectedException \InvalidArgumentException * @expectedExceptionMessage The key encryption algorithm "A256CBC-HS512" is not supported or not a key encryption algorithm instance. */ public function testNotAKeyEncryptionAlgorithm() { $encrypter = Encrypter::createEncrypter(['A256CBC-HS512'], [], ['DEF'], new FakeLogger()); $jwe = JWEFactory::createJWE($this->getKeyToEncrypt()); $jwe = $jwe->withSharedProtectedHeaders([ 'kid' => '123456789', 'enc' => 'A256CBC-HS512', 'alg' => 'A256CBC-HS512', 'zip' => 'DEF', ]); $jwe = $jwe->addRecipientInformation( $this->getRSARecipientKey() ); $encrypter->encrypt($jwe); } /** * @expectedException \InvalidArgumentException * @expectedExceptionMessage The content encryption algorithm "RSA-OAEP-256" is not supported or not a content encryption algorithm instance. */ public function testNotAContentEncryptionAlgorithm() { $encrypter = Encrypter::createEncrypter(['RSA-OAEP-256'], [], ['DEF'], new FakeLogger()); $jwe = JWEFactory::createJWE($this->getKeyToEncrypt()); $jwe = $jwe->withSharedProtectedHeaders([ 'kid' => '123456789', 'enc' => 'RSA-OAEP-256', 'alg' => 'RSA-OAEP-256', 'zip' => 'DEF', ]); $jwe = $jwe->addRecipientInformation( $this->getRSARecipientKey() ); $encrypter->encrypt($jwe); } public function testEncryptAndLoadCompactWithDirectKeyEncryption() { $encrypter = Encrypter::createEncrypter(['dir'], ['A192CBC-HS384'], ['DEF'], new FakeLogger()); $decrypter = Decrypter::createDecrypter(['dir'], ['A192CBC-HS384'], ['DEF'], new FakeLogger()); $jwe = JWEFactory::createJWE($this->getKeyToEncrypt()); $jwe = $jwe->withSharedProtectedHeaders([ 'kid' => 'DIR_1', 'enc' => 'A192CBC-HS384', 'alg' => 'dir', ]); $jwe = $jwe->addRecipientInformation( $this->getDirectKey() ); $encrypter->encrypt($jwe); $encrypted = $jwe->toFlattenedJSON(0); $loader = new Loader(new FakeLogger()); $loaded = $loader->load($encrypted); self::assertInstanceOf(JWEInterface::class, $loaded); self::assertEquals('dir', $loaded->getSharedProtectedHeader('alg')); self::assertEquals('A192CBC-HS384', $loaded->getSharedProtectedHeader('enc')); self::assertFalse($loaded->hasSharedHeader('zip')); self::assertNull($loaded->getPayload()); $decrypter->decryptUsingKeySet($loaded, $this->getSymmetricKeySet(), $index); self::assertEquals(0, $index); self::assertTrue(is_array($loaded->getPayload())); self::assertEquals($this->getKeyToEncrypt(), new JWK($loaded->getPayload())); } public function testEncryptAndLoadCompactKeyAgreement() { $encrypter = Encrypter::createEncrypter(['ECDH-ES'], ['A192CBC-HS384'], ['DEF'], new FakeLogger()); $decrypter = Decrypter::createDecrypter(['ECDH-ES'], ['A192CBC-HS384'], ['DEF'], new FakeLogger()); $jwe = JWEFactory::createJWE(['user_id' => '1234', 'exp' => time() + 3600]); $jwe = $jwe->withSharedProtectedHeaders([ 'kid' => 'e9bc097a-ce51-4036-9562-d2ade882db0d', 'enc' => 'A192CBC-HS384', 'alg' => 'ECDH-ES', ]); $jwe = $jwe->addRecipientInformation( $this->getECDHRecipientPublicKey() ); $encrypter->encrypt($jwe); $loader = new Loader(new FakeLogger()); $loaded = $loader->load($jwe->toFlattenedJSON(0)); self::assertInstanceOf(JWEInterface::class, $loaded); self::assertEquals('ECDH-ES', $loaded->getSharedProtectedHeader('alg')); self::assertEquals('A192CBC-HS384', $loaded->getSharedProtectedHeader('enc')); self::assertFalse($loaded->hasSharedProtectedHeader('zip')); self::assertNull($loaded->getPayload()); $decrypter->decryptUsingKeySet($loaded, $this->getPrivateKeySet(), $index); self::assertEquals(0, $index); self::assertTrue($loaded->hasClaims()); self::assertTrue($loaded->hasClaim('user_id')); self::assertEquals('1234', $loaded->getClaim('user_id')); } public function testEncryptAndLoadCompactKeyAgreementWithWrappingCompact() { $encrypter = Encrypter::createEncrypter(['ECDH-ES+A256KW'], ['A256CBC-HS512'], ['DEF'], new FakeLogger()); $decrypter = Decrypter::createDecrypter(['ECDH-ES+A256KW'], ['A256CBC-HS512'], ['DEF'], new FakeLogger()); $jwe = JWEFactory::createJWE('Live long and Prosper.'); $jwe = $jwe->withSharedProtectedHeaders([ 'kid' => 'e9bc097a-ce51-4036-9562-d2ade882db0d', 'enc' => 'A256CBC-HS512', 'alg' => 'ECDH-ES+A256KW', ]); $jwe = $jwe->addRecipientInformation( $this->getECDHRecipientPublicKey() ); $encrypter->encrypt($jwe); $loader = new Loader(new FakeLogger()); $loaded = $loader->load($jwe->toFlattenedJSON(0)); self::assertInstanceOf(JWEInterface::class, $loaded); self::assertEquals('ECDH-ES+A256KW', $loaded->getSharedProtectedHeader('alg')); self::assertEquals('A256CBC-HS512', $loaded->getSharedProtectedHeader('enc')); self::assertFalse($loaded->hasSharedProtectedHeader('zip')); self::assertFalse($loaded->hasSharedHeader('zip')); self::assertNull($loaded->getPayload()); $decrypter->decryptUsingKeySet($loaded, $this->getPrivateKeySet(), $index); self::assertEquals(0, $index); self::assertTrue(is_string($loaded->getPayload())); self::assertEquals('Live long and Prosper.', $loaded->getPayload()); } public function testEncryptAndLoadWithGCMAndAAD() { $encrypter = Encrypter::createEncrypter(['ECDH-ES+A256KW'], ['A256GCM'], ['DEF'], new FakeLogger()); $jwe = JWEFactory::createJWE( 'Live long and Prosper.', [ 'kid' => 'e9bc097a-ce51-4036-9562-d2ade882db0d', 'enc' => 'A256GCM', 'alg' => 'ECDH-ES+A256KW', ], [], 'foo,bar,baz' ); $jwe = $jwe->addRecipientInformation( $this->getECDHRecipientPublicKey() ); $encrypter->encrypt($jwe); $loader = new Loader(new FakeLogger()); $loaded = $loader->load($jwe->toFlattenedJSON(0)); $decrypter = Decrypter::createDecrypter(['A256GCM'], ['ECDH-ES+A256KW'], ['DEF'], new FakeLogger()); self::assertInstanceOf(JWEInterface::class, $loaded); self::assertEquals('ECDH-ES+A256KW', $loaded->getSharedProtectedHeader('alg')); self::assertEquals('A256GCM', $loaded->getSharedProtectedHeader('enc')); self::assertFalse($loaded->hasSharedProtectedHeader('zip')); self::assertFalse($loaded->hasSharedHeader('zip')); self::assertNull($loaded->getPayload()); $decrypter->decryptUsingKeySet($loaded, $this->getPrivateKeySet(), $index); self::assertEquals(0, $index); self::assertTrue(is_string($loaded->getPayload())); self::assertEquals('Live long and Prosper.', $loaded->getPayload()); } public function testEncryptAndLoadCompactKeyAgreementWithWrapping() { $encrypter = Encrypter::createEncrypter(['RSA-OAEP-256', 'ECDH-ES+A256KW'], ['A256CBC-HS512'], ['DEF'], new FakeLogger()); $decrypter = Decrypter::createDecrypter(['RSA-OAEP-256', 'ECDH-ES+A256KW'], ['A256CBC-HS512'], ['DEF'], new FakeLogger()); $jwe = JWEFactory::createJWE('Live long and Prosper.'); $jwe = $jwe->withSharedProtectedHeaders(['enc' => 'A256CBC-HS512']); $jwe = $jwe->addRecipientInformation( $this->getECDHRecipientPublicKey(), ['kid' => 'e9bc097a-ce51-4036-9562-d2ade882db0d', 'alg' => 'ECDH-ES+A256KW'] ); $jwe = $jwe->addRecipientInformation( $this->getRSARecipientKey(), ['kid' => '123456789', 'alg' => 'RSA-OAEP-256'] ); $encrypter->encrypt($jwe); $loader = new Loader(new FakeLogger()); $loaded = $loader->load($jwe->toJSON()); self::assertEquals(2, $loaded->countRecipients()); self::assertInstanceOf(JWEInterface::class, $loaded); self::assertEquals('A256CBC-HS512', $loaded->getSharedProtectedHeader('enc')); self::assertEquals('ECDH-ES+A256KW', $loaded->getRecipient(0)->getHeader('alg')); self::assertEquals('RSA-OAEP-256', $loaded->getRecipient(1)->getHeader('alg')); self::assertFalse($loaded->hasSharedHeader('zip')); self::assertFalse($loaded->hasSharedProtectedHeader('zip')); self::assertNull($loaded->getPayload()); $decrypter->decryptUsingKeySet($loaded, $this->getPrivateKeySet(), $index); self::assertEquals(0, $index); self::assertTrue(is_string($loaded->getPayload())); self::assertEquals('Live long and Prosper.', $loaded->getPayload()); } /** * @return JWK */ private function getKeyToEncrypt() { $key = new JWK([ 'kty' => 'EC', 'use' => 'enc', 'crv' => 'P-256', 'x' => 'f83OJ3D2xF1Bg8vub9tLe1gHMzV76e8Tus9uPHvRVEU', 'y' => 'x_FEzRu9m36HLN_tue659LNpXW6pCyStikYjKIWI5a0', 'd' => 'jpsQnnGQmL-YBIffH1136cspYG6-0iY7X1fCE9-E9LI', ]); return $key; } /** * @return JWKSet */ private function getKeySetToEncrypt() { $key = new JWK([ 'kty' => 'EC', 'use' => 'enc', 'crv' => 'P-256', 'x' => 'f83OJ3D2xF1Bg8vub9tLe1gHMzV76e8Tus9uPHvRVEU', 'y' => 'x_FEzRu9m36HLN_tue659LNpXW6pCyStikYjKIWI5a0', 'd' => 'jpsQnnGQmL-YBIffH1136cspYG6-0iY7X1fCE9-E9LI', ]); $key_set = new JWKSet(); $key_set->addKey($key); return $key_set; } /** * @return JWK */ private function getRSARecipientKey() { $key = new JWK([ 'kty' => 'RSA', 'use' => 'enc', 'n' => 'tpS1ZmfVKVP5KofIhMBP0tSWc4qlh6fm2lrZSkuKxUjEaWjzZSzs72gEIGxraWusMdoRuV54xsWRyf5KeZT0S-I5Prle3Idi3gICiO4NwvMk6JwSBcJWwmSLFEKyUSnB2CtfiGc0_5rQCpcEt_Dn5iM-BNn7fqpoLIbks8rXKUIj8-qMVqkTXsEKeKinE23t1ykMldsNaaOH-hvGti5Jt2DMnH1JjoXdDXfxvSP_0gjUYb0ektudYFXoA6wekmQyJeImvgx4Myz1I4iHtkY_Cp7J4Mn1ejZ6HNmyvoTE_4OuY1uCeYv4UyXFc1s1uUyYtj4z57qsHGsS4dQ3A2MJsw', 'e' => 'AQAB', ]); return $key; } /** * @return JWK */ private function getRSARecipientKeyWithAlgorithm() { $key = new JWK([ 'kty' => 'RSA', 'use' => 'enc', 'alg' => 'RSA-OAEP', 'n' => 'tpS1ZmfVKVP5KofIhMBP0tSWc4qlh6fm2lrZSkuKxUjEaWjzZSzs72gEIGxraWusMdoRuV54xsWRyf5KeZT0S-I5Prle3Idi3gICiO4NwvMk6JwSBcJWwmSLFEKyUSnB2CtfiGc0_5rQCpcEt_Dn5iM-BNn7fqpoLIbks8rXKUIj8-qMVqkTXsEKeKinE23t1ykMldsNaaOH-hvGti5Jt2DMnH1JjoXdDXfxvSP_0gjUYb0ektudYFXoA6wekmQyJeImvgx4Myz1I4iHtkY_Cp7J4Mn1ejZ6HNmyvoTE_4OuY1uCeYv4UyXFc1s1uUyYtj4z57qsHGsS4dQ3A2MJsw', 'e' => 'AQAB', ]); return $key; } /** * @return JWK */ private function getSigningKey() { $key = new JWK([ 'kty' => 'EC', 'key_ops' => ['sign', 'verify'], 'crv' => 'P-256', 'x' => 'f83OJ3D2xF1Bg8vub9tLe1gHMzV76e8Tus9uPHvRVEU', 'y' => 'x_FEzRu9m36HLN_tue659LNpXW6pCyStikYjKIWI5a0', 'd' => 'jpsQnnGQmL-YBIffH1136cspYG6-0iY7X1fCE9-E9LI', ]); return $key; } /** * @return JWK */ private function getECDHRecipientPublicKey() { $key = new JWK([ 'kty' => 'EC', 'key_ops' => ['encrypt', 'decrypt'], 'crv' => 'P-256', 'x' => 'f83OJ3D2xF1Bg8vub9tLe1gHMzV76e8Tus9uPHvRVEU', 'y' => 'x_FEzRu9m36HLN_tue659LNpXW6pCyStikYjKIWI5a0', ]); return $key; } /** * @return JWK */ private function getDirectKey() { $key = new JWK([ 'kid' => 'DIR_1', 'key_ops' => ['encrypt', 'decrypt'], 'kty' => 'oct', 'k' => Base64Url::encode(hex2bin('00112233445566778899AABBCCDDEEFF000102030405060708090A0B0C0D0E0F')), ]); return $key; } }
Spomky-Labs/jose
tests/Functional/EncrypterBaseTest.php
PHP
mit
25,820
// Fill out your copyright notice in the Description page of Project Settings. using UnrealBuildTool; using System.Collections.Generic; public class UnrealCamDemoTarget : TargetRules { public UnrealCamDemoTarget(TargetInfo Target) : base(Target) { Type = TargetType.Game; ExtraModuleNames.AddRange( new string[] { "UnrealCamDemo" } ); } }
mrayy/UnityCam
UnrealCamDemo/Source/UnrealCamDemo.Target.cs
C#
mit
349
package br.com.gamemods.tutorial.ctf; import org.bukkit.plugin.java.JavaPlugin; public class CTFGameMods extends JavaPlugin { }
joserobjr/CTFGameMods
src/main/java/br/com/gamemods/tutorial/ctf/CTFGameMods.java
Java
mit
131
--- category: Components type: Navigation title: Dropdown cover: https://gw.alipayobjects.com/zos/alicdn/eedWN59yJ/Dropdown.svg --- A dropdown list. ## When To Use When there are more than a few options to choose from, you can wrap them in a `Dropdown`. By hovering or clicking on the trigger, a dropdown menu will appear, which allows you to choose an option and execute the relevant action. ## API ### Dropdown | Property | Description | Type | Default | Version | | --- | --- | --- | --- | --- | | arrow | Whether the dropdown arrow should be visible | boolean \| { pointAtCenter: boolean } | false | | | disabled | Whether the dropdown menu is disabled | boolean | - | | | destroyPopupOnHide | Whether destroy dropdown when hidden | boolean | false | | | getPopupContainer | To set the container of the dropdown menu. The default is to create a div element in body, but you can reset it to the scrolling area and make a relative reposition. [Example on CodePen](https://codepen.io/afc163/pen/zEjNOy?editors=0010) | (triggerNode: HTMLElement) => HTMLElement | () => document.body | | | overlay | The dropdown menu | [Menu](/components/menu) \| () => Menu | - | | | overlayClassName | The class name of the dropdown root element | string | - | | | overlayStyle | The style of the dropdown root element | CSSProperties | - | | | placement | Placement of popup menu: `bottom` `bottomLeft` `bottomRight` `top` `topLeft` `topRight` | string | `bottomLeft` | | | trigger | The trigger mode which executes the dropdown action. Note that hover can't be used on touchscreens | Array&lt;`click`\|`hover`\|`contextMenu`> | \[`hover`] | | | visible | Whether the dropdown menu is currently visible | boolean | - | | | onVisibleChange | Called when the visible state is changed. Not trigger when hidden by click item | (visible: boolean) => void | - | | You should use [Menu](/components/menu/) as `overlay`. The menu items and dividers are also available by using `Menu.Item` and `Menu.Divider`. > Warning: You must set a unique `key` for `Menu.Item`. > > Menu of Dropdown is unselectable by default, you can make it selectable via `<Menu selectable>`. ### Dropdown.Button | Property | Description | Type | Default | Version | | --- | --- | --- | --- | --- | | buttonsRender | Custom buttons inside Dropdown.Button | (buttons: ReactNode\[]) => ReactNode\[] | - | | | loading | Set the loading status of button | boolean \| { delay: number } | false | | | disabled | Whether the dropdown menu is disabled | boolean | - | | | icon | Icon (appears on the right) | ReactNode | - | | | overlay | The dropdown menu | [Menu](/components/menu) | - | | | placement | Placement of popup menu: `bottom` `bottomLeft` `bottomRight` `top` `topLeft` `topRight` | string | `bottomLeft` | | | size | Size of the button, the same as [Button](/components/button/#API) | string | `default` | | | trigger | The trigger mode which executes the dropdown action | Array&lt;`click`\|`hover`\|`contextMenu`> | \[`hover`] | | | type | Type of the button, the same as [Button](/components/button/#API) | string | `default` | | | visible | Whether the dropdown menu is currently visible | boolean | - | | | onClick | The same as [Button](/components/button/#API): called when you click the button on the left | (event) => void | - | | | onVisibleChange | Called when the visible state is changed | (visible: boolean) => void | - | |
ant-design/ant-design
components/dropdown/index.en-US.md
Markdown
mit
3,428
/************************ BUBBLE SORT Author:Rhysn Date:2015 *************************/ #include <stdio.h> #include <stdlib.h> typedef int ElemType; void swap(ElemType *left,ElemType *right){ ElemType temp = *left; *left = *right; *right = temp; } void BubbleSort(ElemType *array,int num){ if(num == 1) return; ElemType *left = array,*right = array + 1; int key = num; while(--key){ if(*left > *right) swap(left,right); left++; right++; } BubbleSort(array,--num); } int main(){ int a[14]; int *b=a; int num = 14; srand((unsigned)time(NULL)); while (num--) *b++ = rand()%10; b=a; num=14; while(num--){ printf("%d ",*b++ ); } printf("\n"); BubbleSort(a,14); num = 14; b=a; while(num--){ printf("%d ",*b++ ); } printf("\n"); return 0; }
Rhysn/Data-Structure-And-Algorithm
Sort/BubbleSort.c
C
mit
917
/** * Keyframes. */ @-webkit-keyframes rotation { 0% { -moz-transform: rotate(0deg); -ms-transform: rotate(0deg); -webkit-transform: rotate(0deg); transform: rotate(0deg); } 100% { -moz-transform: rotate(360deg); -ms-transform: rotate(360deg); -webkit-transform: rotate(360deg); transform: rotate(360deg); } } @keyframes rotation { 0% { -moz-transform: rotate(0deg); -ms-transform: rotate(0deg); -webkit-transform: rotate(0deg); transform: rotate(0deg); } 100% { -moz-transform: rotate(360deg); -ms-transform: rotate(360deg); -webkit-transform: rotate(360deg); transform: rotate(360deg); } } @-webkit-keyframes rotation-reverse { 0% { -moz-transform: rotate(0deg); -ms-transform: rotate(0deg); -webkit-transform: rotate(0deg); transform: rotate(0deg); } 100% { -moz-transform: rotate(-360deg); -ms-transform: rotate(-360deg); -webkit-transform: rotate(-360deg); transform: rotate(-360deg); } } @keyframes rotation-reverse { 0% { -moz-transform: rotate(0deg); -ms-transform: rotate(0deg); -webkit-transform: rotate(0deg); transform: rotate(0deg); } 100% { -moz-transform: rotate(-360deg); -ms-transform: rotate(-360deg); -webkit-transform: rotate(-360deg); transform: rotate(-360deg); } } body { background-color: #000; } #sun { background-color: #aa0; height: 50px; left: calc(50% - 25px); position: absolute; top: calc(50% - 25px); width: 50px; -moz-border-radius: 50%; -webkit-border-radius: 50%; border-radius: 50%; -moz-box-shadow: 0 0 10px 2px #aa5500; -webkit-box-shadow: 0 0 10px 2px #aa5500; box-shadow: 0 0 10px 2px #aa5500; } #mercury-orbit { -webkit-animation: rotation 8s linear infinite; animation: rotation 8s linear infinite; height: 10%; left: 45%; position: absolute; top: 45%; width: 10%; -moz-border-radius: 50%; -webkit-border-radius: 50%; border-radius: 50%; } #mercury { background: #953; height: 10px; width: 10px; -moz-border-radius: 50%; -webkit-border-radius: 50%; border-radius: 50%; -moz-box-shadow: inset 0 0 5px 1px #222222; -webkit-box-shadow: inset 0 0 5px 1px #222222; box-shadow: inset 0 0 5px 1px #222222; } #venus-orbit { -webkit-animation: rotation-reverse 16s linear infinite; animation: rotation-reverse 16s linear infinite; height: 14%; left: 43%; position: absolute; top: 43%; width: 14%; } #venus { background: #db5; height: 15px; width: 15px; -moz-border-radius: 50%; -webkit-border-radius: 50%; border-radius: 50%; -moz-box-shadow: 0 0 3px 0 #ffff88; -webkit-box-shadow: 0 0 3px 0 #ffff88; box-shadow: 0 0 3px 0 #ffff88; } #earth-orbit { -webkit-animation: rotation 24s linear infinite; animation: rotation 24s linear infinite; height: 20%; left: 40%; position: absolute; top: 40%; width: 20%; } #earth { background-color: #0bf; height: 20px; width: 20px; -moz-border-radius: 50%; -webkit-border-radius: 50%; border-radius: 50%; -moz-box-shadow: 0 0 8px 1px white; -webkit-box-shadow: 0 0 8px 1px white; box-shadow: 0 0 8px 1px white; } #mars-orbit { -webkit-animation: rotation 44s linear infinite; animation: rotation 44s linear infinite; height: 30%; left: 35%; position: absolute; top: 35%; width: 30%; } #mars { background-color: #833; height: 18px; width: 18px; -moz-border-radius: 50%; -webkit-border-radius: 50%; border-radius: 50%; -moz-box-shadow: inset 0 0 5px #220000; -webkit-box-shadow: inset 0 0 5px #220000; box-shadow: inset 0 0 5px #220000; } #jupiter-orbit { -webkit-animation: rotation 68s linear infinite; animation: rotation 68s linear infinite; height: 40%; left: 30%; position: absolute; top: 30%; width: 40%; } #jupiter { background-color: #ffa500; height: 40px; width: 40px; -moz-border-radius: 50%; -webkit-border-radius: 50%; border-radius: 50%; -moz-box-shadow: inset 0 0 10px 1px black; -webkit-box-shadow: inset 0 0 10px 1px black; box-shadow: inset 0 0 10px 1px black; } #jupiter-spot { background-color: rgba(160, 0, 0, 0.5); height: 8px; left: 20px; position: absolute; top: 19px; width: 8px; -moz-border-radius: 50%; -webkit-border-radius: 50%; border-radius: 50%; -moz-box-shadow: 0 0 5px 0 #990000; -webkit-box-shadow: 0 0 5px 0 #990000; box-shadow: 0 0 5px 0 #990000; } #saturn-orbit { -webkit-animation: rotation 80s linear infinite; animation: rotation 80s linear infinite; height: 48%; left: 26%; position: absolute; top: 26%; width: 48%; } #saturn { background-color: #ab5; height: 36px; width: 36px; -moz-border-radius: 50%; -webkit-border-radius: 50%; border-radius: 50%; -moz-box-shadow: inset 0 0 5px #445511; -webkit-box-shadow: inset 0 0 5px #445511; box-shadow: inset 0 0 5px #445511; } #uranus-orbit { -webkit-animation: rotation 100s linear infinite; animation: rotation 100s linear infinite; height: 60%; left: 20%; position: absolute; top: 20%; width: 60%; } #uranus { background-color: #3da; height: 30px; width: 30px; -moz-border-radius: 50%; -webkit-border-radius: 50%; border-radius: 50%; -moz-box-shadow: inset 0 0 5px #445511; -webkit-box-shadow: inset 0 0 5px #445511; box-shadow: inset 0 0 5px #445511; } #neptune-orbit { -webkit-animation: rotation 120s linear infinite; animation: rotation 120s linear infinite; height: 70%; left: 15%; position: absolute; top: 15%; width: 70%; } #neptune { background-color: #05a; height: 32px; width: 32px; -moz-border-radius: 50%; -webkit-border-radius: 50%; border-radius: 50%; -moz-box-shadow: inset 0 0 10px 1px black; -webkit-box-shadow: inset 0 0 10px 1px black; box-shadow: inset 0 0 10px 1px black; } #pluto-orbit { -webkit-animation: rotation 120s linear infinite; animation: rotation 120s linear infinite; height: 70%; left: 15%; position: absolute; top: 15%; width: 70%; } #pluto { background-color: #7a7474; height: 10px; width: 10px; -moz-border-radius: 50%; -webkit-border-radius: 50%; border-radius: 50%; -moz-box-shadow: inset 0 0 10px 1px black; -webkit-box-shadow: inset 0 0 10px 1px black; box-shadow: inset 0 0 10px 1px black; }
jonahkirangi/solarsystem
css/style.css
CSS
mit
6,321
<!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> <title>18 --> 19</title> <link href="./../../assets/style.css" rel="stylesheet"> </head> <body> <h2>You have to be fast</h2> <a href="./b89c9c584be36686b5c8c1699d0ab37f2ca82f649a1f817843cceb1bafd56a45.html">Teleport</a> <hr> <a href="./../../about.md">About</a> (Spoilers! ) <script src="./../../assets/md5.js"></script> <script> window.currentLevel = 7; </script> <script src="./../../assets/script.js"></script> </body> </html>
simonmysun/praxis
TAIHAO2019/pub/SmallGame/AsFastAsYouCan2/c5cb57467c267c20a35f92318f4692026c064ad7ef73843ba6db5d1bcd65b843.html
HTML
mit
550
<!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> <title>18 --> 19</title> <link href="./../../assets/style.css" rel="stylesheet"> </head> <body> <h2>You have to be fast</h2> <a href="./111c39a5fd93aebe64e0345eaa4a3fa383b808cd19ce3e292b38f80817041e92.html">Teleport</a> <hr> <a href="./../../about.md">About</a> (Spoilers! ) <script src="./../../assets/md5.js"></script> <script> window.currentLevel = 7; </script> <script src="./../../assets/script.js"></script> </body> </html>
simonmysun/praxis
TAIHAO2019/pub/SmallGame/AsFastAsYouCan2/cfa46991bdb810d48aaad070e86d32606ad11ab98dba37c82ee2433179f9b2ce.html
HTML
mit
550
/**************************************************************** Copyright (C) 2014 All rights reserved. > File Name: < echo_server.c > > Author: < Sean Guo > > Mail: < [email protected] > > Created Time: < 2014/06/19 > > Last Changed: < 2015/11/30 > > Description: echo server for ARM //{{{ int bind(int sockfd, struct sockaddr * my_addr, int addrlen); bind()用来设置给参数sockfd 的socket 一个名称. 此名称由参数my_addr 指向一个sockaddr 结构, 对于不同的socket domain 定义了一个通用的数据结构 struct sockaddr { unsigned short int sa_family; char sa_data[14]; }; 1、sa_family 为调用socket()时的domain 参数, 即AF_xxxx 值. 2、sa_data 最多使用14 个字符长度. 此sockaddr 结构会因使用不同的socket domain 而有不同结构定义, 例如使用AF_INET domain,其socketaddr 结构定义便为 struct socketaddr_in { unsigned short int sin_family; uint16_t sin_port; struct in_addr sin_addr; unsigned char sin_zero[8]; }; struct in_addr { uint32_t s_addr; }; 1、sin_family 即为sa_family 2、sin_port 为使用的port 编号 3、sin_addr. s_addr 为IP 地址 sin_zero 未使用. 参数 addrlen 为sockaddr 的结构长度. 返回值:成功则返回0, 失败返回-1, 错误原因存于errno 中. 错误代码: 1、EBADF 参数sockfd 非合法socket 处理代码. 2、EACCESS 权限不足 3、ENOTSOCK 参数sockfd 为一文件描述词, 非socket. //}}} Usage: ./echo_server ****************************************************************/ //{{{ include files #include <stdio.h> #include <sys/socket.h> #include <sys/wait.h> // waitpid() #include <stdlib.h> // exit(); #include <string.h> // bzero(); #include <netinet/in.h> // struct sockaddr_in; #include <time.h> // time(); #include <arpa/inet.h> // inet_pton(); #include <unistd.h> // write(); #include <errno.h> // errno #include <signal.h> // SIGCHLD //}}} #define MAXLINE 4096 /* max text line length */ #define LISTENQ 1024 /* 2nd argument to listen() , 排队的最大连接数*/ #define LISTEN_PORT 9669 //服务器监听端口 //参数: 已连接的socket描述符. //功能: echo此socket发送的一切数据; //阻塞函数, 直到对方socket关闭. void str_echo(int sockfd); //信号处理函数, 将等待一个子进程的结束。 void sig_child(int signo); int main(int argc, char **argv) //{{{ { int listenfd, connfd; struct sockaddr_in server_addr, client_addr; socklen_t addr_len; char buffer[MAXLINE]; pid_t child_pid; listenfd = socket(AF_INET, SOCK_STREAM, 0); bzero(&server_addr, sizeof(server_addr)); server_addr.sin_family = AF_INET; server_addr.sin_addr.s_addr = htonl(INADDR_ANY); server_addr.sin_port = htons(LISTEN_PORT); // int bind(int sockfd, struct sockaddr * my_addr, int addrlen); // bind()用来设置给参数sockfd 的socket 一个名称. // 此名称由参数my_addr 指向一个sockaddr 结构, 对于不同的socket domain 定义了一个通用的数据结构 bind(listenfd, (struct sockaddr *) &server_addr, sizeof(server_addr)); // int listen(int s, int backlog); // listen()用来监听描述符s 的socket连接请求. // 参数backlog 指定同时能处理的最大连接要求, 如果连接数目达此上限则client 端将收到ECONNREFUSED 的错误. // listen()并未开始接收连接请求, 只设置socket 为listen 模式,真正接收client 端连线的是accept(). // 通常listen()会在socket(), bind()之后调用, 接着才调用accept(). // 成功则返回0, 失败返回-1, 错误原因存于errno // listen()只适用SOCK_STREAM 或SOCK_SEQPACKET 的socket 类型. // 如果socket 为AF_INET 则参数backlog 最大值可设至128. listen(listenfd, LISTENQ); signal(SIGCHLD, sig_child); //为SIGCHLD匹配自定义的函数, 使得处理子进程僵死的问题. //主进程就为一个监听端口, 为每个连接fork一个新的进程. for ( ; ; ) { addr_len = sizeof(client_addr); // int accept(int s, struct sockaddr * addr, int * addrlen); // accept()用来接受描述符s 的socket连接请求. // socket 必需先经bind()、listen()函数处理过, // 当有连接请求进来时, accept()会返回一个新的socket 处理代码, 往后的数据传送与读取就是经由新的socket处理, // 而原来参数s 的socket 能继续使用accept()来接受新的连线要求. // 连线成功时, 参数addr 所指的结构会被系统填入远程主机的地址数据, 参数addrlen 为scokaddr 的结构长度. // 成功则返回新的socket 处理代码, 失败返回-1, 错误原因存于errno 中. connfd = accept(listenfd, (struct sockaddr *) &client_addr, &addr_len); //创建子进程处理客户端请求, 主进程继续监听. child_pid = fork(); if(child_pid < 0) //failed to fork a process. { fprintf(stderr, "error: failed in fork()\n"); exit(1); } else if(child_pid == 0) //the child process. { close(listenfd); //close listenfd in child process. str_echo(connfd); //the task of child process - As a echo server. exit(0); } else // the parent process. close(connfd); //close connfd in parent process. //调用close()只会减少对应socket描述符的引用数, 当引用数为0才会清楚对应的socket. } }//}}} void str_echo(int sockfd) //{{{ { ssize_t n; char buf[1024]; again: while( (n = read(sockfd, buf, 1024)) > 0) //不断从sockfd中读取数据 write(sockfd, buf, n); if(n < 0 && errno == EINTR) //由于信号中断(EINTR)而没有读取到数据时, 返回while循环. goto again; else if( n < 0) //无法读取数据 perror("str_echo: read error"); }//}}} //信号处理函数, 将等待一个子进程的结束。 void sig_child(int signo) //{{{ { pid_t pid; int state; //pid = wait(&state); //等待一个子进程的结束 while( (pid = waitpid(-1, &state, WNOHANG)) > 0) //使用非阻塞的waitpid等待可结束的所有子进程 printf("child pid[%d] terminated.\n", pid); }//}}}
SeanXP/ARM-Tiny6410
linux/linux-example/socket_echo_server/echo_server.c
C
mit
6,157
'use strict'; var emojiArr = require('./emojis'); var i = 0; var existingRules = {}; var generateEmoji = function(selector) { if (!existingRules[selector]) { existingRules[selector] = emojiArr[i]; if (i !== emojiArr.length) { i++ } else { i = 0; } } return existingRules[selector]; } module.exports = generateEmoji;
thuongvu/postcss-emoji
emojify.js
JavaScript
mit
382
// ------------------------------------------------------------------------------ // Copyright (c) Microsoft Corporation. All Rights Reserved. Licensed under the MIT License. See License in the project root for license information. // ------------------------------------------------------------------------------ // **NOTE** This file was generated by a tool and any changes will be overwritten. // Template Source: Templates\CSharp\Requests\MethodRequest.cs.tt namespace Microsoft.Graph { using System; using System.Collections.Generic; using System.IO; using System.Net.Http; using System.Threading; /// <summary> /// The type WorkbookFunctionsBesselIRequest. /// </summary> public partial class WorkbookFunctionsBesselIRequest : BaseRequest, IWorkbookFunctionsBesselIRequest { /// <summary> /// Constructs a new WorkbookFunctionsBesselIRequest. /// </summary> public WorkbookFunctionsBesselIRequest( string requestUrl, IBaseClient client, IEnumerable<Option> options) : base(requestUrl, client, options) { this.ContentType = "application/json"; this.RequestBody = new WorkbookFunctionsBesselIRequestBody(); } /// <summary> /// Gets the request body. /// </summary> public WorkbookFunctionsBesselIRequestBody RequestBody { get; private set; } /// <summary> /// Issues the POST request. /// </summary> public System.Threading.Tasks.Task<WorkbookFunctionResult> PostAsync() { return this.PostAsync(CancellationToken.None); } /// <summary> /// Issues the POST request. /// </summary> /// <param name="cancellationToken">The <see cref="CancellationToken"/> for the request.</param> /// <returns>The task to await for async call.</returns> public System.Threading.Tasks.Task<WorkbookFunctionResult> PostAsync( CancellationToken cancellationToken) { this.Method = "POST"; return this.SendAsync<WorkbookFunctionResult>(this.RequestBody, cancellationToken); } /// <summary> /// Adds the specified expand value to the request. /// </summary> /// <param name="value">The expand value.</param> /// <returns>The request object to send.</returns> public IWorkbookFunctionsBesselIRequest Expand(string value) { this.QueryOptions.Add(new QueryOption("$expand", value)); return this; } /// <summary> /// Adds the specified select value to the request. /// </summary> /// <param name="value">The select value.</param> /// <returns>The request object to send.</returns> public IWorkbookFunctionsBesselIRequest Select(string value) { this.QueryOptions.Add(new QueryOption("$select", value)); return this; } } }
ginach/msgraph-sdk-dotnet
src/Microsoft.Graph/Requests/Generated/WorkbookFunctionsBesselIRequest.cs
C#
mit
3,043
# -*- coding: utf-8 -*- require 'helper' class TestRegressionSetColumn07 < Test::Unit::TestCase def setup setup_dir_var end def teardown File.delete(@xlsx) if File.exist?(@xlsx) end def test_set_column07 @xlsx = 'set_column07.xlsx' workbook = WriteXLSX.new(@xlsx) worksheet = workbook.add_worksheet bold = workbook.add_format(:bold => 1) italic = workbook.add_format(:italic => 1) bold_italic = workbook.add_format(:bold => 1, :italic => 1) data = [ [1, 2, 3, 4, 5], [2, 4, 6, 8, 10], [3, 6, 9, 12, 15] ] worksheet.write('A1', 'Foo', italic) worksheet.write('B1', 'Bar', bold) worksheet.write('A2', data) worksheet.set_row(12, nil, italic) worksheet.set_column('F:F', nil, bold) worksheet.write('F13', nil, bold_italic) worksheet.insert_image('E12', File.join(@test_dir, 'regression', 'images/logo.png')) workbook.close compare_xlsx_for_regression(File.join(@regression_output, @xlsx), @xlsx) end end
Orphist/write_xlsx
test/regression/test_set_column07.rb
Ruby
mit
1,095
var fractal = fractal || {}; fractal.workerPaths = { "mandelbrot": "public/js/mandel.js", }; fractal.Fractal = function (canvas, workerCount) { this.canvas = canvas; this.workerCount = workerCount; this.workerDoneCount = 0; this.ctx = canvas.getContext("2d"); this.width = canvas.width; this.height = canvas.height; this.workerPath = fractal.workerPaths["mandelbrot"]; this.topLeft = new Complex(-1.5, 1.1); this.bottomRight = new Complex(0.8, -1.1); this.maxIter = 1200; var lingrad = this.ctx.createLinearGradient(0, 0, this.width, 0); lingrad.addColorStop(0, '#00f'); lingrad.addColorStop(0.1, '#fa0'); lingrad.addColorStop(0.5, '#ff0'); lingrad.addColorStop(0.7, '#f1b'); lingrad.addColorStop(1, '#fff'); this.ctx.fillStyle = lingrad; this.ctx.fillRect(0, 0, this.width, 2); this.gradientImage = this.ctx.getImageData(0, 0, this.width, 1); this.imgData = this.ctx.getImageData(0, 0, this.width, this.height); this.ondone = null; this.workers = []; }; fractal.Fractal.prototype = function () { var computeRow = function (workerIndex, row) { var args = { action: "computeRow", row: row, workerIndex: workerIndex }; this.workers[workerIndex].postMessage(args); }; var initializeWorker = function (workerIndex) { var drow = (this.bottomRight.imag - this.topLeft.imag) / this.height; var dcol = (this.bottomRight.real - this.topLeft.real) / this.width; var args = { action: "setup", maxIter: this.maxIter, width: this.width, height: this.height, topLeft: this.topLeft, bottomRight: this.bottomRight, drow: drow, dcol: dcol, workerIndex: workerIndex, juliaPoint: this.juliaPoint }; this.workers[workerIndex].postMessage(args); }; var createWorkers = function (workerPath) { var obj = this; var rowData = obj.ctx.createImageData(obj.width, 1); for (var workerIndex = 0; workerIndex < obj.workerCount; workerIndex++) { obj.workers[workerIndex] = new Worker(obj.workerPath); this.workers[workerIndex].onmessage = function (event) { if (event.data.logData) { console.log("Worker: " + event.data.logData); } if (event.data.row >= 0) { var wIndex = event.data.workerIndex; for (var index = 0; index < obj.width; index++) { var color = getColor.call(obj, event.data.iterData[index]); var destIndex = 4 * index; rowData.data[destIndex] = color.red; rowData.data[destIndex + 1] = color.green; rowData.data[destIndex + 2] = color.blue; rowData.data[destIndex + 3] = color.alpha; } obj.ctx.putImageData(rowData, 0, event.data.row); if (obj.nextRow < obj.height) { console.log("Worker: " + wIndex, " nextRow: " + obj.nextRow); computeRow.call(obj, wIndex, obj.nextRow); obj.nextRow = obj.nextRow + 1; } else { obj.workerDoneCount++; if (obj.workerDoneCount == obj.workerCount) { var duration = new Date().getTime() - obj.startTime; if (typeof obj.ondone === 'function') { obj.ondone(duration); } } } } }; } }; var getColor = function (iter) { if (iter == this.maxIter) { return { red: 0, green: 0, blue: 0, alpha: 255 }; } var index = (iter % this.gradientImage.width) * 4; return { red: this.gradientImage.data[index], green: this.gradientImage.data[index + 1], blue: this.gradientImage.data[index + 2], alpha: this.gradientImage.data[index + 3] }; }, render = function () { this.startTime = new Date().getTime(); this.workerDoneCount = 0; createWorkers.call(this, this.workerPath); this.nextRow = this.workerCount; for (var workerIndex = 0; workerIndex < this.workerCount; workerIndex++) { initializeWorker.call(this, workerIndex); computeRow.call(this, workerIndex, workerIndex); } } return { render: render }; } (); jQuery(function($) { var fra = new fractal.Fractal(document.getElementById("fractal"), 2); $('#draw-fractal').on('click',function() { fra.render(); }); });
hectoregm/hectoregm
Practica3/public/js/canvas_fractal.js
JavaScript
mit
4,312
describe('raureif', function () { it('test', function () { }); });
chrmod/raureif
tests/node/index-test.js
JavaScript
mit
71
<html> <head> <title>OGRE: OgreProperty.h File Reference - OGRE Documentation</title> <meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1"> <link type="text/css" rel="stylesheet" href="doxygen.css"> <link type="text/css" rel="stylesheet" href="tabs.css"> </head> <body> <!-- Generated by Doxygen 1.6.2 --> <div class="navigation" id="top"> <div class="tabs"> <ul> <li><a href="index.html"><span>Main&nbsp;Page</span></a></li> <li><a href="pages.html"><span>Related&nbsp;Pages</span></a></li> <li><a href="modules.html"><span>Modules</span></a></li> <li><a href="namespaces.html"><span>Namespaces</span></a></li> <li><a href="annotated.html"><span>Classes</span></a></li> <li class="current"><a href="files.html"><span>Files</span></a></li> <li><a href="dirs.html"><span>Directories</span></a></li> </ul> </div> <div class="tabs"> <ul> <li><a href="files.html"><span>File&nbsp;List</span></a></li> <li><a href="globals.html"><span>File&nbsp;Members</span></a></li> </ul> </div> <div class="navpath"><a class="el" href="dir_0b8281b69943ad565aee8137b1bafaf9.html">Components</a>&nbsp;&raquo;&nbsp;<a class="el" href="dir_2ea5e14f44ca0532a19372d0108d4e30.html">Property</a>&nbsp;&raquo;&nbsp;<a class="el" href="dir_d0b811453e63f36c97352e3f2c575189.html">include</a> </div> </div> <div class="contents"> <h1>OgreProperty.h File Reference</h1> <p>OGRE's property system allows you to associate values of arbitrary type with names, and have those values exposed via a self-describing interface. <a href="#_details">More...</a></p> <code>#include &quot;<a class="el" href="OgrePropertyPrerequisites_8h_source.html">OgrePropertyPrerequisites.h</a>&quot;</code><br/> <code>#include &quot;<a class="el" href="OgreAny_8h_source.html">OgreAny.h</a>&quot;</code><br/> <code>#include &quot;<a class="el" href="OgreIteratorWrappers_8h_source.html">OgreIteratorWrappers.h</a>&quot;</code><br/> <code>#include &quot;<a class="el" href="OgreString_8h_source.html">OgreString.h</a>&quot;</code><br/> <code>#include &quot;<a class="el" href="OgreException_8h_source.html">OgreException.h</a>&quot;</code><br/> <code>#include &quot;<a class="el" href="OgreVector2_8h_source.html">OgreVector2.h</a>&quot;</code><br/> <code>#include &quot;<a class="el" href="OgreVector3_8h_source.html">OgreVector3.h</a>&quot;</code><br/> <code>#include &quot;<a class="el" href="OgreVector4_8h_source.html">OgreVector4.h</a>&quot;</code><br/> <code>#include &quot;<a class="el" href="OgreColourValue_8h_source.html">OgreColourValue.h</a>&quot;</code><br/> <code>#include &quot;<a class="el" href="OgreQuaternion_8h_source.html">OgreQuaternion.h</a>&quot;</code><br/> <code>#include &quot;<a class="el" href="OgreMatrix3_8h_source.html">OgreMatrix3.h</a>&quot;</code><br/> <code>#include &quot;<a class="el" href="OgreMatrix4_8h_source.html">OgreMatrix4.h</a>&quot;</code><br/> <code>#include &lt;boost/bind.hpp&gt;</code><br/> <code>#include &lt;boost/function.hpp&gt;</code><br/> <p><a href="OgreProperty_8h_source.html">Go to the source code of this file.</a></p> <table border="0" cellpadding="0" cellspacing="0"> <tr><td colspan="2"><h2>Classes</h2></td></tr> <tr><td class="memItemLeft" align="right" valign="top">class &nbsp;</td><td class="memItemRight" valign="bottom"><a class="el" href="classOgre_1_1PropertyDef.html">Ogre::PropertyDef</a></td></tr> <tr><td class="mdescLeft">&nbsp;</td><td class="mdescRight">Definition of a property of an object. <a href="classOgre_1_1PropertyDef.html#_details">More...</a><br/></td></tr> <tr><td class="memItemLeft" align="right" valign="top">class &nbsp;</td><td class="memItemRight" valign="bottom"><a class="el" href="classOgre_1_1PropertyBase.html">Ogre::PropertyBase</a></td></tr> <tr><td class="mdescLeft">&nbsp;</td><td class="mdescRight">Base interface for an instance of a property. <a href="classOgre_1_1PropertyBase.html#_details">More...</a><br/></td></tr> <tr><td class="memItemLeft" align="right" valign="top">class &nbsp;</td><td class="memItemRight" valign="bottom"><a class="el" href="classOgre_1_1Property.html">Ogre::Property&lt; T &gt;</a></td></tr> <tr><td class="mdescLeft">&nbsp;</td><td class="mdescRight"><a class="el" href="classOgre_1_1Property.html" title="Property instance with passthrough calls to a given object.">Property</a> instance with passthrough calls to a given object. <a href="classOgre_1_1Property.html#_details">More...</a><br/></td></tr> <tr><td class="memItemLeft" align="right" valign="top">struct &nbsp;</td><td class="memItemRight" valign="bottom"><a class="el" href="structOgre_1_1PropertyValue.html">Ogre::PropertyValue</a></td></tr> <tr><td class="mdescLeft">&nbsp;</td><td class="mdescRight">A simple structure designed just as a holder of property values between the instances of objects they might target. <a href="structOgre_1_1PropertyValue.html#_details">More...</a><br/></td></tr> <tr><td class="memItemLeft" align="right" valign="top">class &nbsp;</td><td class="memItemRight" valign="bottom"><a class="el" href="classOgre_1_1PropertySet.html">Ogre::PropertySet</a></td></tr> <tr><td class="mdescLeft">&nbsp;</td><td class="mdescRight">Defines a complete set of properties for a single object instance. <a href="classOgre_1_1PropertySet.html#_details">More...</a><br/></td></tr> <tr><td colspan="2"><h2>Namespaces</h2></td></tr> <tr><td class="memItemLeft" align="right" valign="top">namespace &nbsp;</td><td class="memItemRight" valign="bottom"><a class="el" href="namespaceOgre.html">Ogre</a></td></tr> <p><tr><td class="mdescLeft">&nbsp;</td><td class="mdescRight"><p>----------------------------------------------------------------------------- This source file is part of OGRE (Object-oriented Graphics Rendering Engine) For the latest info, see <a href="http://www.ogre3d.org/">http://www.ogre3d.org/</a> </p> <br/></td></tr> </p> <tr><td colspan="2"><h2>Typedefs</h2></td></tr> <tr><td class="memItemLeft" align="right" valign="top">typedef map&lt; String, <br class="typebreak"/> PropertyDef &gt;::type&nbsp;</td><td class="memItemRight" valign="bottom"><a class="el" href="group__Property.html#gaa2af9dd0402adef0e54243e3ee3dc86e">Ogre::PropertyDefMap</a></td></tr> <tr><td class="mdescLeft">&nbsp;</td><td class="mdescRight">Map from property name to shared definition. <a href="group__Property.html#gaa2af9dd0402adef0e54243e3ee3dc86e"></a><br/></td></tr> <tr><td class="memItemLeft" align="right" valign="top">typedef map&lt; String, <br class="typebreak"/> PropertyValue &gt;::type&nbsp;</td><td class="memItemRight" valign="bottom"><a class="el" href="group__Property.html#gac473fdb476888c7a1a0a4a857948cc5c">Ogre::PropertyValueMap</a></td></tr> <tr><td class="mdescLeft">&nbsp;</td><td class="mdescRight">Defines a transferable map of properties using wrapped value types (<a class="el" href="classOgre_1_1Any.html" title="Variant type that can hold Any other type.">Ogre::Any</a>). <a href="group__Property.html#gac473fdb476888c7a1a0a4a857948cc5c"></a><br/></td></tr> <tr><td colspan="2"><h2>Enumerations</h2></td></tr> <tr><td class="memItemLeft" align="right" valign="top">enum &nbsp;</td><td class="memItemRight" valign="bottom"><a class="el" href="group__Property.html#ga0883a5af9197151407965df0bacc4f3a">Ogre::PropertyType</a> { <br/> &nbsp;&nbsp;<a class="el" href="group__Property.html#gga0883a5af9197151407965df0bacc4f3aa19d90ad1680589279aafec448c4e75d3">Ogre::PROP_SHORT</a> = 0, <a class="el" href="group__Property.html#gga0883a5af9197151407965df0bacc4f3aa8807d302197c648340522a66196f46f1">Ogre::PROP_UNSIGNED_SHORT</a> = 1, <a class="el" href="group__Property.html#gga0883a5af9197151407965df0bacc4f3aa93d4b54300df506764ebb8af6bf4d5c8">Ogre::PROP_INT</a> = 2, <a class="el" href="group__Property.html#gga0883a5af9197151407965df0bacc4f3aa9fb3644ad2ce148f77291a0d3eaea6a1">Ogre::PROP_UNSIGNED_INT</a> = 3, <br/> &nbsp;&nbsp;<a class="el" href="group__Property.html#gga0883a5af9197151407965df0bacc4f3aa3d3a41849ca836ff178c8f2618629794">Ogre::PROP_LONG</a> = 4, <a class="el" href="group__Property.html#gga0883a5af9197151407965df0bacc4f3aabb2c30d9d8af27d83d4aafed018aa84d">Ogre::PROP_UNSIGNED_LONG</a> = 5, <a class="el" href="group__Property.html#gga0883a5af9197151407965df0bacc4f3aa269350183053663ed0e36a69b72dc4c8">Ogre::PROP_REAL</a> = 6, <a class="el" href="group__Property.html#gga0883a5af9197151407965df0bacc4f3aa7964244e71bea1a0b721d42e6fa4ae53">Ogre::PROP_STRING</a> = 7, <br/> &nbsp;&nbsp;<a class="el" href="group__Property.html#gga0883a5af9197151407965df0bacc4f3aa5f081dc286c25333c43e8467d6c7c8b6">Ogre::PROP_VECTOR2</a> = 8, <a class="el" href="group__Property.html#gga0883a5af9197151407965df0bacc4f3aacd225d4bbfbd47f0473b7d56f834f3b6">Ogre::PROP_VECTOR3</a> = 9, <a class="el" href="group__Property.html#gga0883a5af9197151407965df0bacc4f3aaa5b410ea31e3954eeba233240dfb67ec">Ogre::PROP_VECTOR4</a> = 10, <a class="el" href="group__Property.html#gga0883a5af9197151407965df0bacc4f3aa4dbf2ba96cd6b8774fc4cd98b0bfca01">Ogre::PROP_COLOUR</a> = 11, <br/> &nbsp;&nbsp;<a class="el" href="group__Property.html#gga0883a5af9197151407965df0bacc4f3aa4811d3c1f6bce61a13fedbcfa19e1b32">Ogre::PROP_BOOL</a> = 12, <a class="el" href="group__Property.html#gga0883a5af9197151407965df0bacc4f3aa161aabceab220d04e7aa8704ff8e5293">Ogre::PROP_QUATERNION</a> = 13, <a class="el" href="group__Property.html#gga0883a5af9197151407965df0bacc4f3aa1a10d1f71eb0804ab6ec20a598a1ac93">Ogre::PROP_MATRIX3</a> = 14, <a class="el" href="group__Property.html#gga0883a5af9197151407965df0bacc4f3aad1ccdd4ffa8de819d5f96bac1a405a32">Ogre::PROP_MATRIX4</a> = 15, <br/> &nbsp;&nbsp;<a class="el" href="group__Property.html#gga0883a5af9197151407965df0bacc4f3aa593a0408d46ccf3061cb27c372b25e8d">Ogre::PROP_UNKNOWN</a> = 999 <br/> }</td></tr> <tr><td class="mdescLeft">&nbsp;</td><td class="mdescRight"><p>The type of a property. </p> <a href="group__Property.html#ga0883a5af9197151407965df0bacc4f3a">More...</a><br/></td></tr> </table> <hr/><a name="_details"></a><h2>Detailed Description</h2> <p>OGRE's property system allows you to associate values of arbitrary type with names, and have those values exposed via a self-describing interface. </p> <p>Unlike <a class="el" href="classOgre_1_1StringInterface.html" title="Class defining the common interface which classes can use to present a reflection-style...">Ogre::StringInterface</a>, the values are passed as their native types without needing conversion to or from strings; they are simply wrapped in an <a class="el" href="classOgre_1_1Any.html" title="Variant type that can hold Any other type.">Ogre::Any</a> and casts are performed to access them. </p> <dl class="user"><dt><b></b></dt><dd>Property values are actually not stored in this system; instead the property definitions reference getter &amp; setter methods which provide the 'backing' for the property. This means you can directly expose features of your classes as properties without any duplication. </dd></dl> <dl class="user"><dt><b></b></dt><dd>There are two aspects to exposing a property on your class. One is exposing the definition of the property (PropertyDef), which should be shared between all instances and probably stored in a static PropertyDefMap somewhere. The second is the instance 'wiring' which ensures that a call to set a property calls a method on this particular instance of the class; this is formed by a number of Property instances, contained in a PropertySet. Each Property has an explicit binding to getter and setter instance methods. </dd></dl> <dl class="user"><dt><b></b></dt><dd>So, here's an example of setting up properties on an instance:</dd></dl> <div class="fragment"><pre class="fragment"> <span class="comment">// Make sure the property definition is created </span> <span class="comment">// propertyDefs is a variable of type PropertyDefMap, shared between instances</span> PropertyDefMap::iterator defi = propertyDefs.find(<span class="stringliteral">&quot;name&quot;</span>); <span class="keywordflow">if</span> (defi == propertyDefs.end()) { defi = propertyDefs.insert(PropertyDefMap::value_type(<span class="stringliteral">&quot;name&quot;</span>, PropertyDef(<span class="stringliteral">&quot;name&quot;</span>, <span class="stringliteral">&quot;The name of the object.&quot;</span>, <a class="code" href="group__Property.html#gga0883a5af9197151407965df0bacc4f3aa7964244e71bea1a0b721d42e6fa4ae53">PROP_STRING</a>))).first; } <span class="comment">// This has established the property definition, and its description.</span> <span class="comment">// Now, we need to &#39;wire&#39; a property instance for this object instance</span> <span class="comment">// We assume the class is called &#39;Foo&#39; and the instance is pointed to by a variable called &#39;inst&#39;</span> <span class="comment">// &#39;props&#39; is a PropertySet, specific to the instance</span> props.addProperty( <a class="code" href="group__Memory.html#gab5fc1358fd5a889de0a06d07e45df1ff">OGRE_NEW</a> Property&lt;String&gt;(&amp;(defi-&gt;second), boost::bind(&amp;Foo::getName, inst), boost::bind(&amp;Foo::setName, inst, _1))); </pre></div> <p>Definition in file <a class="el" href="OgreProperty_8h_source.html">OgreProperty.h</a>.</p> </div> <hr> <p> Copyright &copy; 2012 Torus Knot Software Ltd<br /> <!--Creative Commons License--><a rel="license" href="http://creativecommons.org/licenses/by-sa/3.0/"><img alt="Creative Commons License" style="border-width:0" src="http://i.creativecommons.org/l/by-sa/3.0/88x31.png" /></a><br />This work is licensed under a <a rel="license" href="http://creativecommons.org/licenses/by-sa/3.0/">Creative Commons Attribution-ShareAlike 3.0 Unported License</a>.<br/> <!--/Creative Commons License--><!-- <rdf:RDF xmlns="http://web.resource.org/cc/" xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#"> <Work rdf:about=""> <license rdf:resource="http://creativecommons.org/licenses/by-sa/2.5/" /> <dc:type rdf:resource="http://purl.org/dc/dcmitype/Text" /> </Work> <License rdf:about="http://creativecommons.org/licenses/by-sa/2.5/"><permits rdf:resource="http://web.resource.org/cc/Reproduction"/><permits rdf:resource="http://web.resource.org/cc/Distribution"/><requires rdf:resource="http://web.resource.org/cc/Notice"/><requires rdf:resource="http://web.resource.org/cc/Attribution"/><permits rdf:resource="http://web.resource.org/cc/DerivativeWorks"/><requires rdf:resource="http://web.resource.org/cc/ShareAlike"/></License></rdf:RDF> --> Last modified Sun Sep 2 08:16:13 2012 </p> </body> </html>
lennonchan/OgreSource
Docs/api/html/OgreProperty_8h.html
HTML
mit
14,771
/** * @file ui/core/styleguide/index//html/01-body/40-main/main.js * @description Listeners on the body, iframe, and rightpull bar. */ /* istanbul ignore if */ if (typeof window === 'object') { document.addEventListener('DOMContentLoaded', () => { const $orgs = FEPPER_UI.requerio.$orgs; const { uiFns, uiProps } = FEPPER_UI; $orgs['#sg-rightpull'].on('mouseenter', function () { $orgs['#sg-cover'].dispatchAction('addClass', 'shown-by-rightpull-hover'); }); $orgs['#sg-rightpull'].on('mouseleave', function () { $orgs['#sg-cover'].dispatchAction('removeClass', 'shown-by-rightpull-hover'); }); // Handle manually resizing the viewport. // 1. On "mousedown" store the click location. // 2. Make a hidden div visible so that the cursor doesn't get lost in the iframe. // 3. On "mousemove" calculate the math, save the results to a cookie, and update the viewport. $orgs['#sg-rightpull'].on('mousedown', function (e) { uiProps.sgRightpull.posX = e.pageX; uiProps.sgRightpull.vpWidth = uiProps.vpWidth; // Show the cover. $orgs['#sg-cover'].dispatchAction('addClass', 'shown-by-rightpull-drag'); }); // Add the mouse move event and capture data. Also update the viewport width. $orgs['#patternlab-body'].on('mousemove', function (e) { if ($orgs['#sg-cover'].getState().classArray.includes('shown-by-rightpull-drag')) { let vpWidthNew = uiProps.sgRightpull.vpWidth; if (uiProps.dockPosition === 'bottom') { vpWidthNew += 2 * (e.pageX - uiProps.sgRightpull.posX); } else { vpWidthNew += e.pageX - uiProps.sgRightpull.posX; } if (vpWidthNew > uiProps.minViewportWidth) { uiFns.sizeIframe(vpWidthNew, false); } } }); // Handle letting go of rightpull bar after dragging to resize. $orgs['#patternlab-body'].on('mouseup', function () { uiProps.sgRightpull.posX = null; uiProps.sgRightpull.vpWidth = null; $orgs['#sg-cover'].dispatchAction('removeClass', 'shown-by-rightpull-hover'); $orgs['#sg-cover'].dispatchAction('removeClass', 'shown-by-rightpull-drag'); }); }); }
electric-eloquence/fepper-npm
ui/core/styleguide/index/html/01-body/40-main/main.js
JavaScript
mit
2,224
<div> <table class="table table-bordered"> <tr> <td> <div km-term-check name="root-traits" locales="locales" required ng-change="onRootTraitsChange()" ng-model="rootTraits" terms="options.rootTraits()" binding-type="term[]"></div> </td> </tr> <tr ng-if="traits['81799D15-669E-4346-9AEC-6834893D2BE4'].selected"> <td> <legend>Resistencia a enfermedades y plagas</legend> <div km-term-check name="traits" locales="locales" required ng-model="traits['81799D15-669E-4346-9AEC-6834893D2BE4'].items" ng-change="onTraitsChange()" terms="options.traits('81799D15-669E-4346-9AEC-6834893D2BE4')" binding-type="term[]"></div> </td> </tr> <tr ng-if="traits['0C74FEB2-78E8-4163-81EF-2D410FB2FBBC'].selected"> <td> <legend>Resistencia a herbicidas</legend> <div km-term-check name="traits" locales="locales" required ng-model="traits['0C74FEB2-78E8-4163-81EF-2D410FB2FBBC'].items" ng-change="onTraitsChange()" terms="options.traits('0C74FEB2-78E8-4163-81EF-2D410FB2FBBC')" binding-type="term[]"></div> </td> </tr> <tr ng-if="traits['87D98E42-4757-42DE-9C3F-815BFAA35218'].selected"> <td> <legend>Resistencia a los antibióticos</legend> <div km-term-check name="traits" locales="locales" required ng-model="traits['87D98E42-4757-42DE-9C3F-815BFAA35218'].items" ng-change="onTraitsChange()" terms="options.traits('87D98E42-4757-42DE-9C3F-815BFAA35218')" binding-type="term[]"></div> </td> </tr> <tr ng-if="traits['31396BD1-9E3E-4EB3-A29E-9A22B7230221'].selected"> <td> <legend>Tolerancia al estrés abiótico</legend> <div km-term-check name="traits" locales="locales" required ng-model="traits['31396BD1-9E3E-4EB3-A29E-9A22B7230221'].items" ng-change="onTraitsChange()" terms="options.traits('31396BD1-9E3E-4EB3-A29E-9A22B7230221')" binding-type="term[]"></div> </td> </tr> <tr ng-if="traits['337747E5-522D-42DF-8C57-FE626C1572EC'].selected"> <td> <legend>Cambios en la fisiología y/o producción</legend> <div km-term-check name="traits" locales="locales" required ng-model="traits['337747E5-522D-42DF-8C57-FE626C1572EC'].items" ng-change="onTraitsChange()" terms="options.traits('337747E5-522D-42DF-8C57-FE626C1572EC')" binding-type="term[]"></div> </td> </tr> <tr ng-if="traits['3B427EA6-5260-47F1-B424-FAAA5960FB52'].selected"> <td> <legend>Cambios en la calidad y/o el contenido metabólico</legend> <div km-term-check name="traits" locales="locales" required ng-model="traits['3B427EA6-5260-47F1-B424-FAAA5960FB52'].items" ng-change="onTraitsChange()" terms="options.traits('3B427EA6-5260-47F1-B424-FAAA5960FB52')" binding-type="term[]"></div> </td> </tr> <tr ng-if="traits['5B9DB3B4-90A1-451A-A10C-E3A47995344F'].selected"> <td> <legend>Producción de compuestos médicos o farmacéuticos (humanos o animales)</legend> <div km-term-check name="traits" locales="locales" required ng-model="traits['5B9DB3B4-90A1-451A-A10C-E3A47995344F'].items" ng-change="onTraitsChange()" terms="options.traits('5B9DB3B4-90A1-451A-A10C-E3A47995344F')" binding-type="term[]"></div> </td> </tr> <tr ng-if="traits['C8C662E2-D633-4C69-96EA-C9853997A3A5'].selected"> <td> <legend>Uso en aplicaciones industriales</legend> <div km-term-check name="traits" locales="locales" required ng-model="traits['C8C662E2-D633-4C69-96EA-C9853997A3A5'].items" ng-change="onTraitsChange()" terms="options.traits('C8C662E2-D633-4C69-96EA-C9853997A3A5')" binding-type="term[]"></div> </td> </tr> <tr ng-if="traits['75DE5726-4C52-442C-8BF8-B77A6EBE48E2'].selected"> <td> <legend>Modificación genética por aplicación de impulsores genéticos</legend> <div km-term-check name="traits" locales="locales" required ng-change="onTraitsChange()" ng-model="traits['75DE5726-4C52-442C-8BF8-B77A6EBE48E2'].items" terms="options.traits('75DE5726-4C52-442C-8BF8-B77A6EBE48E2')" binding-type="term[]"></div> </td> </tr> <tr ng-if="traits['traitsOtherSection'].selected"> <td> <div km-term-check name="traits" locales="locales" required ng-change="onTraitsChange()" ng-model="traits['traitsOtherSection'].items" terms="options.traitsOtherSection()" binding-type="term[]"> </div> </td> </tr> <tr ng-if="traits['0C74FEB2-78E8-4163-81EF-2D410FB2FBBC'].selected"> <td> </td> </tr> </table> </div>
scbd/absch.cbd.int
i18n/es/app/views/forms/directives/traits-selector.directive.html
HTML
mit
5,390
<?php namespace Checkdomain\Holiday; use Checkdomain\Holiday\Model\Holiday; /** * Class Util */ class Util { /** * Instantiates a provider for a given iso code * * @param string $iso * * @return ProviderInterface */ protected function getProvider($iso) { $instance = null; $class = '\\Checkdomain\\Holiday\\Provider\\' . $iso; if (class_exists($class)) { $instance = new $class; } return $instance; } /** * @param \DateTime|string $date * * @return \DateTime */ protected function getDateTime($date) { if (!$date instanceof \DateTime) { $date = new \DateTime($date); } return $date; } /** * @param string $iso * * @return string */ protected function getIsoCode($iso) { return strtoupper($iso); } /** * Checks wether a given date is a holiday * * This method can be used to check whether a specific date is a holiday * in a specified country and state * * @param string $iso * @param \DateTime|string $date * @param string $state * * @return bool */ public function isHoliday($iso, $date = 'now', $state = null) { return ($this->getHoliday($iso, $date, $state) !== null); } /** * Provides detailed information about a specific holiday * * @param string $iso * @param \DateTime|string $date * @param string $state * * @return Holiday|null */ public function getHoliday($iso, $date = 'now', $state = null) { $iso = $this->getIsoCode($iso); $date = $this->getDateTime($date); $provider = $this->getProvider($iso); $holiday = $provider->getHolidayByDate($date, $state); return $holiday; } }
checkdomain/Holiday
src/Util.php
PHP
mit
1,932
namespace Votter.Services { using System; using System.Linq; using Microsoft.Owin; using Owin; [assembly: OwinStartup(typeof(Votter.Services.Startup))] public partial class Startup { public void Configuration(IAppBuilder app) { this.ConfigureAuth(app); } } }
Team-Papaya-Web-Services-and-Cloud/Web-Services-and-Cloud-Teamwork-2014
Votter/Votter.Services/Startup.cs
C#
mit
331
#ifndef BUTTONS_H #define BUTTONS_H #include "FreeRTOS.h" /* hardware button state */ struct button_state_t { /* STATE WRITTEN IN IRQ HANDLER */ /* current button state: 0 (up, released) or 1 (down, pressed) */ int st; /* the cpu-tick time when the current state (up or down) was recorded */ TickType_t tick; /* STATE UPDATED IN OS TASK */ /* the cpu-tick time when the button was last pressed; * used for detecting short and long button clicks in ButtonTask */ TickType_t kdwn_tick; /* the cpu-tick time when the event BTN_LONGCLICK was last sent */ TickType_t longclick_sent_tick; }; /* buttons identification */ #define BTN0 0 #define BTN1 1 #define BTN2 2 /* mask for BTNx */ #define BTNx_M 0xFF /* button event */ #define BTN_DOWN 0x100 #define BTN_UP 0x200 #define BTN_SHORTCLICK 0x400 #define BTN_LONGCLICK 0x800 /* hardware ports and pins */ #define HW_BTN0_Port GPIOB #define HW_BTN1_Port GPIOB #define HW_BTN2_Port GPIOB #define HW_BTN0_Pin GPIO_Pin_5 #define HW_BTN1_Pin GPIO_Pin_6 #define HW_BTN2_Pin GPIO_Pin_7 /* dead time in milliseconds - supress hardware glitches */ #define BUTTON_DEAD_TM 10 /* max short click time in miliseconds */ #define BUTTON_SHORTCLICK_TM 1000 /* repetition time of BTN_LONGCLICK events once long-click is recognized */ #define BUTTON_LONGCLICK_REPE_TM 800 /* current button state */ extern struct button_state_t btnsts[3]; /* IRQ handler for button state change */ void EXTI9_5_IRQHandler(void); /* OS task handling buttons events */ void ButtonsTask(void *pvParameters); #endif
jsyk/PIP-Watch
pipwatch_zero-fw/buttons.h
C
mit
1,579
<div class="panel panel-default movie-container"> <div class="panel-body"> <div class="row top-part"> <div class="col-xs-12 col-md-4 movie-image"> <img ng-show="movie.Poster" class="img-rounded" src="{{movie.Poster}}" /> <div ng-show="!movie.Poster" class="img-rounded img-alt"> <span>{{movie.Title}}</span> </div> </div> <div class="col-xs-12 col-md-8 movie-desc"> <h2 ng-show="movie.Title">{{movie.Title}}<span ng-show="movie.Year">-{{movie.Year}}</span></h2> <p ng-show="movie.Plot"><span ng-show="movie.Type"><strong>In this {{movie.Type}}, </strong></span>{{movie.Plot}}</p> <p ng-hide="!movie.Released && !movie.Runtime && !movie.Rated"> <span ng-show="movie.Released && movie.Released!=='N/A'" class="badge">{{movie.Released}}</span> <span ng-show="movie.Runtime && movie.Runtime!=='N/A'" class="badge">{{movie.Runtime}}</span> <span ng-show="movie.Rated && movie.Rated!=='N/A'" class="badge">{{movie.Rated}}</span> </p> <p class="movieGenra" ng-show="movie.Genre[0]!==''"> <span ng-repeat="Genre in movie.Genre" class="badge">{{Genre}}</span> </p> <p class="movieActors" ng-show="movie.Actors[0]!==''"> <span><strong>Starring - </strong></span> <span ng-repeat="Actors in movie.Actors">{{Actors}}<span ng-hide="$index===(movie.Actors.length-1)">,</span></span> </p> <p class="movieDirector" ng-show="movie.Director[0] !== ''"> <span><strong>Directed By - </strong></span> <span ng-repeat="Director in movie.Director">{{Director}}</span> </p> <p class="movieWriter" ng-show="movie.Writer[0] !== ''"> <span><strong>Written By -</strong></span> <span ng-repeat="Writer in movie.Writer">{{Writer}}<span ng-hide="$index===(movie.Writer.length-1)">,</span></span> </p> </div> </div> <div class="bottom-part"> <div class="row"> <div class="col-xs-12 col-md-6 languageAc"> <div class="panel-group" id="langAccordion" role="tablist" aria-multiselectable="true"> <div class="panel panel-default"> <div class="panel-heading" role="tab" id="langHeading"> <h4 class="panel-title"> <a data-toggle="collapse" onclick="return false;" data-parent="#langAccordion" href="#Lcollapse" aria-expanded="true" aria-controls="Lcollapse"> Language Availability </a> </h4> </div> <div id="Lcollapse" class="panel-collapse collapse in" role="tabpanel" aria-labelledby="langHeading"> <div class="panel-body"> <span ng-repeat="lan in movie.Language">{{lan}}<span ng-hide="$index===(movie.Language.length-1)">,</span></span> </div> </div> </div> </div> </div> <div class="col-xs-12 col-md-6 countryAc"> <div class="panel-group" id="counAccordion" role="tablist" aria-multiselectable="true"> <div class="panel panel-default"> <div class="panel-heading" role="tab" id="conHeading"> <h4 class="panel-title"> <a data-toggle="collapse" onclick="return false;" data-parent="#counAccordion" href="#Ccollapse" aria-expanded="true" aria-controls="Ccollapse"> Country Availability </a> </h4> </div> <div id="Ccollapse" class="panel-collapse collapse in" role="tabpanel" aria-labelledby="conHeading"> <div class="panel-body"> <span ng-repeat="con in movie.Country">{{con}}<span ng-hide="$index===(movie.Country.length-1)">,</span></span> </div> </div> </div> </div> </div> </div> <div class="row imdbrow"> <div class="col-xs-12 col-md-12 imdbAc"> <div class="panel-group" id="imdbAccordion" role="tablist" aria-multiselectable="true"> <div class="panel panel-default"> <div class="panel-heading" role="tab" id="imdbHeading"> <h4 class="panel-title"> <a data-toggle="collapse" onclick="return false;" data-parent="#imdbAccordion" href="#imdbcollapse" aria-expanded="true" aria-controls="imdbcollapse"> IMDB DATA </a> </h4> </div> <div id="imdbcollapse" class="panel-collapse collapse in" role="tabpanel" aria-labelledby="imdbHeading"> <div class="panel-body"> <div class="col-xs-12 col-md-6"> <span>IMDB Rating -</span><span>> {{movie.imdbRating}}</span> <!-- rating --> <div class="critic-rating"> <h5>Relative Star Rating</h5> <div class="rating star-{{movie.imdbRating | getRatingClass}}"> <i class="fa fa-star star-1-on"></i> <i class="fa fa-star star-off star-1-off"></i> <i class="fa fa-star-half star-1-half"></i> <i class="fa fa-star star-2-on"></i> <i class="fa fa-star star-off star-2-off"></i> <i class="fa fa-star-half star-2-half"></i> <i class="fa fa-star star-3-on"></i> <i class="fa fa-star star-off star-3-off"></i> <i class="fa fa-star-half star-3-half"></i> <i class="fa fa-star star-4-on"></i> <i class="fa fa-star star-off star-4-off"></i> <i class="fa fa-star-half star-4-half"></i> <i class="fa fa-star star-5-on"></i> <i class="fa fa-star star-off star-5-off"></i> <i class="fa fa-star-half star-5-half"></i> <!-- commented as we created half equivalent 5 star according to IMDB data <i class="fa fa-star star-6-on"></i> <i class="fa fa-star star-off star-6-off"></i> <i class="fa fa-star-half star-6-half"></i> <i class="fa fa-star star-7-on"></i> <i class="fa fa-star star-off star-7-off"></i> <i class="fa fa-star-half star-7-half"></i> <i class="fa fa-star star-8-on"></i> <i class="fa fa-star star-off star-8-off"></i> <i class="fa fa-star-half star-8-half"></i> <i class="fa fa-star star-9-on"></i> <i class="fa fa-star star-off star-9-off"></i> <i class="fa fa-star-half star-9-half"></i> <i class="fa fa-star star-10-on"></i> <i class="fa fa-star star-off star-10-off"></i> <i class="fa fa-star-half star-10-half"></i> --> </div> </div> <!-- end rating--> </div> <div class="col-xs-12 col-md-6"> <span>IMDB Votes-</span><span>> {{movie.imdbVotes}}</span> </div> </div> </div> </div> </div> </div> </div> </div> </div> </div>
bhavindesai20/MovieBazar
public/templates/movie.html
HTML
mit
9,600
import java.io.BufferedReader; import java.io.IOException; import java.nio.charset.Charset; import java.nio.charset.StandardCharsets; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; public class CharCounterMain{ final static Charset enc = StandardCharsets.US_ASCII ; public CharCounterMain(String ch, String filedir){ if(ch.length() != 1){ System.out.println("The first argument needs to be a char, found string of length "+ch.length()); System.exit(1); } char c = ch.charAt(0); if( c != ' ' && c != '.' && Character.getNumericValue(c) < 97 && Character.getNumericValue(c) > 122 ){ //compare against the ascii integer values System.out.println("Need a character in range a-z (lowercase only) or a whitespace or a dot, found "+c+"!"); System.exit(1); } Path p = Paths.get(filedir); try { BufferedReader bf = Files.newBufferedReader(p,enc); String line; String line2 = null ; while((line = bf.readLine()) != null){ line2 += line ; } CharCounter cc = new CharCounter(c,line2); int freq = cc.getFrequency(); System.out.println(String.format("Frequency of character %c was %d", c,freq)); } catch (IOException e) { e.printStackTrace(); } System.out.println("Finished, exiting..."); } public static void main(String[] args){ if(args.length != 2){ System.out.println("Usage : CharCounterMain <char-to-look-for> <text-file-dir>"); }else{ new CharCounterMain(args[0],args[1]); } } }
dperezmavro/courseworks_uni
year_3/large_scale_and_distributed_systems/src/CharCounterMain.java
Java
mit
1,792
"use strict"; (function() { // "todos-angular" is just a hard-code id for storage var LOCAL_STORAGE_KEY = 'todos-angular'; var ENTER_KEY = 13; var ESC_KEY = 27; var internalFilters = { active: function(toDoItem) { return !toDoItem.completed; }, completed: function(toDoItem) { return toDoItem.completed; } }; angular.module('ToDoAngular', ['ngRoute']) .service('storage', function($q) { // Storage service return { save: function(toDoCollection) { localStorage.setItem(LOCAL_STORAGE_KEY, JSON.stringify(toDoCollection)); }, load: function() { var itemCollectionString = localStorage.getItem(LOCAL_STORAGE_KEY); return itemCollectionString && JSON.parse(itemCollectionString) || []; } } }) .directive('escHandler', function() { // Define directive for esc key return { restrict: 'A', link: function(scope, iElement, iAttrs) { function keyEventHandler(event) { if (event.keyCode === ESC_KEY) { scope.$apply(iAttrs.escHandler); } } iElement.on('keydown', keyEventHandler); scope.$on('$destroy', function() { iElement.off('keydown', keyEventHandler); }); } }; }) .directive('enterHandler', function() { // Define directive for enter key return { restrict: 'A', link: function (scope, iElement, iAttrs) { function keyEventHandler(event) { if (event.keyCode === ENTER_KEY) { scope.$apply(iAttrs.enterHandler); } } iElement.on('keydown', keyEventHandler); scope.$on('$destroy', function () { iElement.off('keydown', keyEventHandler); }); } }; }) .directive('selectAndFocus', function($timeout) { // Define directive for focus return { restrict: 'A', link: function(scope, iElement, iAttrs) { var focusPromise; scope.$watch(iAttrs.selectAndFocus, function(newValue) { if (newValue && !focusPromise) { focusPromise = $timeout(function focus() { focusPromise = null; iElement[0].focus(); }, 0, false); } }); scope.$on('$destroy', function() { if (focusPromise) { $timeout.cancel(focusPromise); focusPromise = null; } }); } }; }) .directive('toDoItem', function() { // Define directive for to-do item return { restrict: 'A', templateUrl: 'angular-item-template.html', scope: { itemViewModel: '=toDoItem' }, link: function (scope, iElement, iAttrs) { scope.editing = false; scope.originalTitle = ''; scope.$watch('itemViewModel.toDoItem.completed', function(newCompleted) { iElement.toggleClass('completed', newCompleted); }); scope.$watch('editing', function(newEditing) { iElement.toggleClass('editing', newEditing); }); scope.$watch('itemViewModel.isHidden', function(newHidden) { iElement.toggleClass('hidden', newHidden); }); scope.$watchGroup([ 'itemViewModel.toDoItem.title', 'itemViewModel.toDoItem.completed'], function() { scope.$emit('item-updated'); }); scope.destroy = function() { scope.$emit('remove-item', scope.itemViewModel); }; scope.edit = function() { scope.originalTitle = scope.itemViewModel.toDoItem.title; scope.editing = true; }; scope.update = function() { var title = scope.itemViewModel.toDoItem.title || ''; var trimmedTitle = title.trim(); if (scope.editing) { if (title !== trimmedTitle) { scope.itemViewModel.toDoItem.title = trimmedTitle; } if (!trimmedTitle) { scope.destroy(); } scope.editing = false; } }; scope.revert = function() { scope.editing = false; scope.itemViewModel.toDoItem.title = scope.originalTitle; }; } }; }) .controller('AppController', function AppController( $scope, $routeParams, storedToDoCollection, storage) { // Define app controller $scope.toDoCollection = storedToDoCollection.map(function(storedToDo) { return { toDoItem: storedToDo, isHidden: $scope.filter ? !$scope.filter(storedToDo): false }; }); $scope.currentTitle = ''; $scope.$on('$routeChangeSuccess', function() { var filterString = $routeParams.filter; if (filterString && (filterString in internalFilters)) { $scope.filterString = filterString; $scope.filter = internalFilters[filterString]; } else { $scope.filterString = ''; $scope.filter = null; } }); function save() { storage.save($scope.toDoCollection.map(function(toDoViewModel) { return toDoViewModel.toDoItem; })); } $scope.$watch('filter', function(newFilter) { $scope.toDoCollection.forEach(function(toDoViewModel) { toDoViewModel.isHidden = newFilter ? !newFilter(toDoViewModel.toDoItem) : false; }); }); $scope.$watch(function() { return $scope.toDoCollection.filter(function(toDoViewModel){ return !toDoViewModel.toDoItem.completed; }).length; }, function(newValue) { if (newValue == null) { $scope.remainingLabel = ''; } else { $scope.remainingLabel = newValue === 1 ? (newValue + ' item left') : (newValue + ' items left'); } }); $scope.$watchCollection('toDoCollection', function() { save(); }); $scope.$on('item-updated', function() { save(); }); $scope.$on('remove-item', function(scope, toDoViewModel) { for(var index = 0; index < $scope.toDoCollection.length; index++) { if ($scope.toDoCollection[index] === toDoViewModel) { $scope.toDoCollection.splice(index, 1); return; } } }); $scope.create = function() { var currentTitle = $scope.currentTitle.trim(); if (currentTitle) { var toDoItem = { title: currentTitle, completed: false }; var toDoItemViewModel = { toDoItem: toDoItem, isHidden: $scope.filter ? !$scope.filter(toDoItem): false }; $scope.toDoCollection.push(toDoItemViewModel); $scope.currentTitle = ''; } }; }) .config(function($routeProvider) { // Define routing var routeConfig = { controller: 'AppController', templateUrl: 'angular-app-template.html', resolve: { storedToDoCollection: function(storage) { return storage.load(); } } }; $routeProvider .when('/', routeConfig) .when('/:filter', routeConfig) .otherwise({ redirectTo: '/' }); }); })();
sasyomaru/advanced-javascript-training-material
module3/scripts/angular-app.js
JavaScript
mit
9,478
<?php namespace Params; /** * @codeCoverageIgnore */ trait SafeAccess { public function __set($name, $value) { throw new \Exception("Property [$name] doesn't exist for class [".get_class($this)."] so can't set it"); } public function __get($name) { throw new \Exception("Property [$name] doesn't exist for class [".get_class($this)."] so can't get it"); } }
Danack/Blog
vendor/danack/params/lib/Params/SafeAccess.php
PHP
mit
403
html{ height: 100%; margin: 0; background-color:#323232; } body{ font-family: 'Lato', sans-serif; font-size: 11pt; font-weight: 300; color: #C8C8C8 } ul { list-style: none; } a:link {color:#6c6c6c;} a:visited {color:#757575;} a:hover {color:white;} a:active {color:white;} .header{ text-align: center; padding-top: 10%; color: white; } .user_info{ text-align: center; padding-top: 1% } .profile_pic{ height: 25%; width: auto; } input:not([type=submit]):not([type=file]) { border: none; padding: 5px; background: rgba(255,255,255,0.08); margin: 0 0 10px 0; }
prinnb/cs242-final-project
restaurant/static/restaurant/account.css
CSS
mit
602
from decimal import Decimal from django import forms from django.template.loader import render_to_string from django.template.defaultfilters import slugify class BaseWidget(forms.TextInput): """ Base widget. Do not use this directly. """ template = None instance = None def get_parent_id(self, name, attrs): final_attrs = self.build_attrs(attrs, type=self.input_type, name=name) return final_attrs['id'] def get_widget_id(self, prefix, name, key=''): if self.instance: opts = self.instance._meta widget_id = '%s-%s-%s_%s-%s' % (prefix, name, opts.app_label, opts.module_name, self.instance.pk) else: widget_id = '%s-%s' % (prefix, name) if key: widget_id = '%s_%s' % (widget_id, slugify(key)) return widget_id def get_values(self, min_value, max_value, step=1): decimal_step = Decimal(str(step)) value = Decimal(str(min_value)) while value <= max_value: yield value value += decimal_step class SliderWidget(BaseWidget): """ Slider widget. In order to use this widget you must load the jQuery.ui slider javascript. This widget triggers the following javascript events: - *slider_change* with the vote value as argument (fired when the user changes his vote) - *slider_delete* without arguments (fired when the user deletes his vote) It's easy to bind these events using jQuery, e.g.:: $(document).bind('slider_change', function(event, value) { alert('New vote: ' + value); }); """ def __init__(self, min_value, max_value, step, instance=None, can_delete_vote=True, key='', read_only=False, default='', template='ratings/slider_widget.html', attrs=None): """ The argument *default* is used when the initial value is None. """ super(SliderWidget, self).__init__(attrs) self.min_value = min_value self.max_value = max_value self.step = step self.instance = instance self.can_delete_vote = can_delete_vote self.read_only = read_only self.default = default self.template = template self.key = key def get_context(self, name, value, attrs=None): # here we convert *min_value*, *max_value*, *step* and *value* # to string to avoid odd behaviours of Django localization # in the template (and, for backward compatibility we do not # want to use the *unlocalize* filter) attrs['type'] = 'hidden' return { 'min_value': str(self.min_value), 'max_value': str(self.max_value), 'step': str(self.step), 'can_delete_vote': self.can_delete_vote, 'read_only': self.read_only, 'default': self.default, 'parent': super(SliderWidget, self).render(name, value, attrs), 'parent_id': self.get_parent_id(name, attrs), 'value': str(value), 'has_value': bool(value), 'slider_id': self.get_widget_id('slider', name, self.key), 'label_id': 'slider-label-%s' % name, 'remove_id': 'slider-remove-%s' % name, } def render(self, name, value, attrs=None): context = self.get_context(name, value, attrs or {}) return render_to_string(self.template, context) class StarWidget(BaseWidget): """ Starrating widget. In order to use this widget you must download the jQuery Star Rating Plugin available at http://www.fyneworks.com/jquery/star-rating/#tab-Download and then load the required javascripts and css, e.g.:: <link href="/path/to/jquery.rating.css" rel="stylesheet" type="text/css" /> <script type="text/javascript" src="/path/to/jquery.MetaData.js"></script> <script type="text/javascript" src="/path/to/jquery.rating.js"></script> This widget triggers the following javascript events: - *star_change* with the vote value as argument (fired when the user changes his vote) - *star_delete* without arguments (fired when the user deletes his vote) It's easy to bind these events using jQuery, e.g.:: $(document).bind('star_change', function(event, value) { alert('New vote: ' + value); }); """ def __init__(self, min_value, max_value, step, instance=None, can_delete_vote=True, key='', read_only=False, template='ratings/star_widget.html', attrs=None): super(StarWidget, self).__init__(attrs) self.min_value = min_value self.max_value = max_value self.step = step self.instance = instance self.can_delete_vote = can_delete_vote self.read_only = read_only self.template = template self.key = key def get_context(self, name, value, attrs=None): # here we convert *min_value*, *max_value* and *step* # to string to avoid odd behaviours of Django localization # in the template (and, for backward compatibility we do not # want to use the *unlocalize* filter) attrs['type'] = 'hidden' split_value = int(1 / self.step) if split_value == 1: values = range(1, self.max_value+1) split = u'' else: values = self.get_values(self.min_value, self.max_value, self.step) split = u' {split:%d}' % split_value return { 'min_value': str(self.min_value), 'max_value': str(self.max_value), 'step': str(self.step), 'can_delete_vote': self.can_delete_vote, 'read_only': self.read_only, 'values': values, 'split': split, 'parent': super(StarWidget, self).render(name, value, attrs), 'parent_id': self.get_parent_id(name, attrs), 'value': self._get_value(value, split_value), 'star_id': self.get_widget_id('star', name, self.key), } def _get_value(self, original, split): if original: value = round(original * split) / split return Decimal(str(value)) def render(self, name, value, attrs=None): context = self.get_context(name, value, attrs or {}) return render_to_string(self.template, context) class LikeWidget(BaseWidget): def __init__(self, min_value, max_value, instance=None, can_delete_vote=True, template='ratings/like_widget.html', attrs=None): super(LikeWidget, self).__init__(attrs) self.min_value = min_value self.max_value = max_value self.instance = instance self.can_delete_vote = can_delete_vote self.template = template def get_context(self, name, value, attrs=None): # here we convert *min_value*, *max_value* and *step* # to string to avoid odd behaviours of Django localization # in the template (and, for backward compatibility we do not # want to use the *unlocalize* filter) attrs['type'] = 'hidden' return { 'min_value': str(self.min_value), 'max_value': str(self.max_value), 'can_delete_vote': self.can_delete_vote, 'parent': super(LikeWidget, self).render(name, value, attrs), 'parent_id': self.get_parent_id(name, attrs), 'value': str(value), 'like_id': self.get_widget_id('like', name), } def render(self, name, value, attrs=None): context = self.get_context(name, value, attrs or {}) return render_to_string(self.template, context)
redsolution/django-generic-ratings
ratings/forms/widgets.py
Python
mit
7,704
define(function() { return { draw: function(context, t) { var x = this.getNumber("x", t, 100), y = this.getNumber("y", t, 100), size = this.getNumber("size", t, 60), h = this.getNumber("h", t, 40), colorLeft = this.getColor("colorLeft", t, "#999999"), colorRight = this.getColor("colorRight", t, "#cccccc"), colorTop = this.getColor("colorTop", t, "#eeeeee"), scaleX = this.getNumber("scaleX", t, 1), scaleY = this.getNumber("scaleY", t, 1); context.translate(x, y); context.scale(scaleX, scaleY); if(h >= 0) { context.fillStyle = colorTop; context.beginPath(); context.moveTo(-size / 2, -h); context.lineTo(0, -size / 4 - h); context.lineTo(size / 2, -h); context.lineTo(size / 2, -1); context.lineTo(0, size / 4 - 1); context.lineTo(-size / 2, -1); context.lineTo(-size / 2, -h); this.drawFillAndStroke(context, t, true, false); context.fillStyle = colorLeft; context.beginPath(); context.moveTo(-size / 2, 0); context.lineTo(0, size / 4); context.lineTo(0, size / 4 - h); context.lineTo(-size / 2, -h); context.lineTo(-size / 2, 0); this.drawFillAndStroke(context, t, true, false); context.fillStyle = colorRight; context.beginPath(); context.moveTo(size / 2, 0); context.lineTo(0, size / 4); context.lineTo(0, size / 4 - h); context.lineTo(size / 2, -h); context.lineTo(size / 2, 0); this.drawFillAndStroke(context, t, true, false); } else { // clip path context.beginPath(); context.moveTo(-size / 2, 0); context.lineTo(0, -size / 4); context.lineTo(size / 2, 0); context.lineTo(0, size / 4); context.lineTo(-size / 2, 0); context.clip(); context.fillStyle = colorRight; context.beginPath(); context.moveTo(-size / 2, 0); context.lineTo(0, -size / 4); context.lineTo(0, -size / 4 -h); context.lineTo(-size / 2, -h); context.lineTo(-size / 2, 0); this.drawFillAndStroke(context, t, true, false); context.fillStyle = colorLeft; context.beginPath(); context.moveTo(size / 2, 0); context.lineTo(0, -size / 4); context.lineTo(0, -size / 4 -h); context.lineTo(size / 2, -h); context.lineTo(size / 2, 0); this.drawFillAndStroke(context, t, true, false); context.fillStyle = colorTop; context.beginPath(); context.moveTo(-size / 2, -h); context.lineTo(0, -size / 4 - h); context.lineTo(size / 2, -h); context.lineTo(0, size / 4 - h); context.lineTo(-size / 2, -h); this.drawFillAndStroke(context, t, true, false); } } } });
bit101/gifloopcoder
src/src/app/render/shapes/isobox.js
JavaScript
mit
2,755
<?php namespace BoundedContext\Contracts\Generator; use BoundedContext\Contracts\ValueObject\Identifier as IdentifierVO; interface Identifier extends ValueObject { /** * Generates a new random Identifier. * * @return IdentifierVO */ public function generate(); /** * Generates a null Identifier. * * @return IdentifierVO */ public function null(); /** * Generates a new Identifier from a string. * * @param string $identifier * @return IdentifierVO */ public function string($identifier); }
lyonscf/bounded-context
src/Contracts/Generator/Identifier.php
PHP
mit
587
<?php return array ( 'id' => 'softbank_v702nk2_ver1', 'fallback' => 'softbank_generic', 'capabilities' => array ( 'physical_screen_height' => '41', 'columns' => '15', 'physical_screen_width' => '34', 'max_image_width' => '176', 'rows' => '6', 'resolution_width' => '176', 'resolution_height' => '208', 'max_image_height' => '173', 'colors' => '262144', 'max_deck_size' => '357000', 'mms_max_size' => '307200', 'mms_max_width' => '640', 'mms_max_height' => '480', 'nokia_series' => '60', 'nokia_feature_pack' => '2', 'nokia_edition' => '2', 'model_name' => '702NKII(NOKIA 6680)', 'uaprof' => 'http://nds1.nds.nokia.com/uaprof/N6680r100-VFKK3G.xml', 'model_extra_info' => 'Vodafone', 'release_date' => '2005_may', 'directdownload_support' => 'true', 'oma_support' => 'true', 'aac' => 'true', 'mp3' => 'true', 'oma_v_1_0_separate_delivery' => 'true', 'flash_lite_version' => '', 'xhtml_file_upload' => 'supported', ), );
cuckata23/wurfl-data
data/softbank_v702nk2_ver1.php
PHP
mit
1,037
<!DOCTYPE html><html><head><title>https://andrivanoff.github.io/categories/%D0%B8%D0%B7-%D1%87%D0%B5%D0%B3%D0%BE/</title><link rel="canonical" href="https://andrivanoff.github.io/categories/%D0%B8%D0%B7-%D1%87%D0%B5%D0%B3%D0%BE/"/><meta http-equiv="content-type" content="text/html; charset=utf-8" /><meta http-equiv="refresh" content="0; url=https://andrivanoff.github.io/categories/%D0%B8%D0%B7-%D1%87%D0%B5%D0%B3%D0%BE/" /></head></html>
andrivanoff/andrivanoff.github.io
categories/из-чего/page/1/index.html
HTML
mit
440
package com.company; import java.util.Scanner; public class Greeting { public static void main(String[] args) { Scanner scanner = new Scanner(System.in); String firstName = scanner.nextLine(); String lastName = scanner.nextLine(); int age = Integer.parseInt(scanner.nextLine()); System.out.printf("Hello, %s %s. You are %d years old.", firstName, lastName, age); } }
ivelin1936/Studing-SoftUni-
Programming Fundamentals/DataTypesAndVariables-Lab/src/com/company/Greeting.java
Java
mit
419
package sbahjsic.runtime; import java.util.HashMap; import java.util.HashSet; import java.util.Map; import java.util.Set; import sbahjsic.core.Warnings; import sbahjsic.core.Warnings.Level; import sbahjsic.runtime.Operator.BiOperator; import sbahjsic.runtime.Operator.UnOperator; import sbahjsic.runtime.Operator.VarargOperator; import sbahjsic.runtime.type.AnyType; import sbahjsic.runtime.type.SVoid; /** Describes a Sbahjsic type. * * <p>For all subclasses, there must only exist one instance. To enforce * this, this class implements final {@code equals()} and {@code hashCode()} * methods as they are defined in {@code Object}.*/ public abstract class Type { private final Map<String, Operator> operators = new HashMap<>(); private final Set<Type> supertypes = new HashSet<>(); private final Set<String> fields = new HashSet<>(); private final Map<String, Method> methods = new HashMap<>(); private int priority = 0; protected Type() { // Fixes a bug where AnyType tried to add AnyType.INSTANCE, which // was null at that point, to its own supertypes if(!getClass().equals(AnyType.class)) { addSupertype(AnyType.INSTANCE); } } /** Registers a new supertype for this type. * @param supertype the new supertype*/ public final void addSupertype(Type supertype) { if(getSupertypes().contains(supertype) || supertype.getSupertypes().contains(this)) { throw new RecursiveTypedefException(this.toString()); } if(this != supertype) { supertypes.add(supertype); } } /** Removes a supertype from this type if it exists. * @param supertype the supertype to remove*/ public final void removeSupertype(Type supertype) { supertypes.remove(supertype); } /** Registers an unary operator for this type. * @param op the operator to register * @param func a function that applies this operator*/ public final void addUnOperator(String op, UnOperator func) { operators.put(op, Operator.unaryOperator(func)); } /** Registers a binary operator for this type. * @param op the operator to register * @param func a function that applies this operator*/ public final void addBiOperator(String op, BiOperator func) { operators.put(op, Operator.binaryOperator(func)); } /** Adds an operator that can accept one or two arguments. * @param op the operator * @param unary the unary operator * @param binary the binary operator*/ protected final void addDoubleOperator(String op, UnOperator unary, BiOperator binary) { operators.put(op, (con, args) -> { if(args.length == 1) return unary.apply(con, args[0]); else if(args.length == 2) return binary.apply(con, args[0], args[1]); throw new OperatorCallException("Called with " + args.length + " arguments, expected 1 or 2"); }); } /** Registers a vararg operator for this type.*/ public void addVarargOperator(String op, VarargOperator func) { operators.put(op, Operator.varargOperator(func)); } /** Adds a field to this type. * @param field the field to add*/ protected final void addField(String field) { fields.add(field); } /** Returns a specific operator of this type. * @param op the operator to search * @return the operator matching {@code op} * @throws OperatorCallException if {@code op} isn't defined*/ public final Operator getOperator(String op) { if(operators.containsKey(op)) { return operators.get(op); } Operator operator = operatorLookup(op); if(operator == null) { throw new OperatorCallException("Operator " + op + " not defined on type " + getName()); } return operator; } private final Operator operatorLookup(String op) { for(Type supertype : supertypes) { if(supertype.operators.containsKey(op)) { return supertype.operators.get(op); } } for(Type supertype : supertypes) { Operator operator = supertype.operatorLookup(op); if(operator != null) { return operator; } } return null; } /** Returns a set of all defined operators of this type. * @return a set of the defined operators of this type*/ public final Set<String> getDefinedOperators() { Set<String> ops = new HashSet<>(); ops.addAll(operators.keySet()); for(Type supertype : getSupertypes()) { ops.addAll(supertype.getDefinedOperators()); } return ops; } /** Returns a set of the supertypes of this type. * @return a set of the supertypes of this type*/ public final Set<Type> getSupertypes() { Set<Type> types = new HashSet<>(); types.addAll(supertypes); for(Type supertype : supertypes) { types.addAll(supertype.getSupertypes()); } return types; } /** Returns the fields declared for this type. * @return a set of fields declared for this type*/ public final Set<String> getFields() { Set<String> allFields = new HashSet<>(); allFields.addAll(fields); for(Type supertype : getSupertypes()) { allFields.addAll(supertype.getFields()); } return allFields; } /** Adds a method to this type. * @param name the name of the method * @param method the method*/ public final void addMethod(String name, Method method) { methods.put(name, method); } /** Returns all methods defined for this type. * @return all methods defined for this type*/ public final Set<String> getMethods() { Map<String, Method> allMethods = new HashMap<>(); allMethods.putAll(methods); for(Type supertype : getSupertypes()) { allMethods.putAll(supertype.methods); } return allMethods.keySet(); } /** Returns a method of this type. * @param name the name of the method * @return the method * @throws MethodCallException if the method isn't defined for this type*/ public final Method getMethod(String name) { if(methods.containsKey(name)) { return methods.get(name); } Method method = methodLookup(name); if(method == null) { throw new MethodCallException("Method " + name + " not defined for type " + getName()); } return method; } private final Method methodLookup(String name) { for(Type supertype : supertypes) { if(supertype.methods.containsKey(name)) { return supertype.methods.get(name); } } for(Type supertype : supertypes) { Method method = supertype.methodLookup(name); if(method != null) { return method; } } return null; } /** Returns the name of this type. * @return the name of this type*/ public abstract String getName(); /** Casts a value to this type. * @param object the value to cast * @return the casted value*/ public SValue cast(SValue object) { Warnings.warn(Level.ADVICE, "Undefined cast from " + object.getType() + " to " + this); return object; } /** Returns whether this type is the subtype of some other type. That is * true if this type or any if its supertypes is the other type. * @param other the other type * @return whether this type is the subtype of the other type */ public boolean isSubtype(Type other) { return this.equals(other) || getSupertypes().contains(other); } /** Constructs an instance of this type * @param context the RuntimeContext * @param args the arguments passed to the constructor*/ public SValue construct(RuntimeContext context, SValue...args) { Warnings.warn(Level.NOTIFICATION, "Cannot instantiate " + getName()); return SVoid.VOID; } /** Returns the priority of this type, used to determine which operand * should choose the implementation of a binary operator. Defaults to zero.*/ public int priority() { return priority; } /** Sets the priority for this type.*/ public void setPriority(int p) { priority = p; } @Override public final boolean equals(Object o) { return super.equals(o); } @Override public final int hashCode() { return super.hashCode(); } @Override public final String toString() { return getName(); } }
expositionrabbit/Sbahjsic-runtime
src/sbahjsic/runtime/Type.java
Java
mit
7,839
{ "date": "2018-02-19", "type": "post", "title": "Report for Monday 19th of February 2018", "slug": "2018\/02\/19", "categories": [ "Daily report" ], "images": [], "health": { "weight": 79.6, "height": 173, "age": 13578 }, "nutrition": { "calories": 1939.89, "fat": 142.55, "carbohydrates": 101.78, "protein": 65.78 }, "exercise": { "pushups": 0, "crunches": 0, "steps": 12906 }, "media": { "books": [], "podcast": [], "youtube": [], "movies": [], "photos": [] } } Today I am <strong>13578 days</strong> old and my weight is <strong>79.6 kg</strong>. During the day, I consumed <strong>1939.89 kcal</strong> coming from <strong>142.55 g</strong> fat, <strong>101.78 g</strong> carbohydrates and <strong>65.78 g</strong> protein. Managed to do <strong>0 push-ups</strong>, <strong>0 crunches</strong> and walked <strong>12906 steps</strong> during the day which is approximately <strong>9.83 km</strong>.
aquilax/quantified.avtobiografia.com
content/post/2018-02-19.md
Markdown
mit
1,092
#!/bin/sh # CYBERWATCH SAS - 2017 # # Security fix for USN-2166-1 # # Security announcement date: 2014-04-14 00:00:00 UTC # Script generation date: 2017-01-01 21:03:46 UTC # # Operating System: Ubuntu 12.04 LTS # Architecture: x86_64 # # Vulnerable packages fix on version: # - libsnmp15:5.4.3~dfsg-2.4ubuntu1.2 # # Last versions recommanded by security team: # - libsnmp15:5.4.3~dfsg-2.4ubuntu1.3 # # CVE List: # - CVE-2012-6151 # - CVE-2014-2284 # - CVE-2014-2285 # - CVE-2014-2310 # # More details: # - https://www.cyberwatch.fr/vulnerabilites # # Licence: Released under The MIT License (MIT), See LICENSE FILE sudo apt-get install --only-upgrade libsnmp15=5.4.3~dfsg-2.4ubuntu1.3 -y
Cyberwatch/cbw-security-fixes
Ubuntu_12.04_LTS/x86_64/2014/USN-2166-1.sh
Shell
mit
706
class Person < ActiveRecord::Base has_many :addresses, dependent: :destroy accepts_nested_attributes_for :addresses end
scotthelm/fencepost
spec/dummy/app/models/person.rb
Ruby
mit
125
import React from 'react'; import {connect} from 'cerebral-view-react'; import styles from './styles.css'; import { isObject, isArray, isString, isBoolean, isNumber, isNull } from 'common/utils'; import JSONInput from './JSONInput'; import connector from 'connector'; function isInPath(source, target) { if (!source || !target) { return false; } return target.reduce((isInPath, key, index) => { if (!isInPath) { return false; } return String(source[index]) === String(key); }, true); } function renderType(value, hasNext, path, propertyKey, highlightPath) { if (value === undefined) { return null; } if (isArray(value)) { return ( <ArrayValue value={value} hasNext={hasNext} path={path} propertyKey={propertyKey} highlightPath={highlightPath}/> ); } if (isObject(value)) { return ( <ObjectValue value={value} hasNext={hasNext} path={path} propertyKey={propertyKey} highlightPath={highlightPath}/> ); } return ( <Value value={value} hasNext={hasNext} path={path} propertyKey={propertyKey} highlightPath={highlightPath}/> ); } class ObjectValue extends React.Component { static contextTypes = { options: React.PropTypes.object.isRequired } constructor(props, context) { super(props); const numberOfKeys = Object.keys(props.value).length; const isHighlightPath = !!(this.props.highlightPath && isInPath(this.props.highlightPath, this.props.path)); const preventCollapse = this.props.path.length === 0 && context.options.expanded; this.state = { isCollapsed: !preventCollapse && !isHighlightPath && (numberOfKeys > 3 || numberOfKeys === 0 ? true : context.options.expanded ? false : true) }; this.onCollapseClick = this.onCollapseClick.bind(this); this.onExpandClick = this.onExpandClick.bind(this); } shouldComponentUpdate(nextProps, nextState) { return ( nextState.isCollapsed !== this.state.isCollapsed || this.context.options.canEdit || nextProps.path !== this.props.path || nextProps.highlightPath !== this.props.highlightPath ); } componentWillReceiveProps(nextProps) { const context = this.context; const props = nextProps; const numberOfKeys = Object.keys(props.value).length; const isHighlightPath = !!(props.highlightPath && isInPath(props.highlightPath, props.path)); const preventCollapse = props.path.length === 0 && context.options.expanded; if (this.state.isCollapsed) { this.setState({ isCollapsed: !preventCollapse && !isHighlightPath && (numberOfKeys > 3 || numberOfKeys === 0 ? true : context.options.expanded ? false : true) }); } } onExpandClick() { this.setState({isCollapsed: false}) } onCollapseClick() { this.setState({isCollapsed: true}); } renderProperty(key, value, index, hasNext, path) { this.props.path.push(key); const property = ( <div className={styles.objectProperty} key={index}> <div className={styles.objectPropertyValue}>{renderType(value, hasNext, path.slice(), key, this.props.highlightPath)}</div> </div> ); this.props.path.pop(); return property; } renderKeys(keys) { if (keys.length > 3) { return keys.slice(0, 3).join(', ') + '...' } return keys.join(', '); } render() { const {value, hasNext} = this.props; const isExactHighlightPath = this.props.highlightPath && String(this.props.highlightPath) === String(this.props.path); if (this.state.isCollapsed) { return ( <div className={isExactHighlightPath ? styles.highlightObject : styles.object} onClick={this.onExpandClick}> {this.props.propertyKey ? this.props.propertyKey + ': ' : null} <strong>{'{ '}</strong>{this.renderKeys(Object.keys(value))}<strong>{' }'}</strong> {hasNext ? ',' : null} </div> ); } else if (this.props.propertyKey) { const keys = Object.keys(value); return ( <div className={isExactHighlightPath ? styles.highlightObject : styles.object}> <div onClick={this.onCollapseClick}>{this.props.propertyKey}: <strong>{'{ '}</strong></div> {keys.map((key, index) => this.renderProperty(key, value[key], index, index < keys.length - 1, this.props.path))} <div><strong>{' }'}</strong>{hasNext ? ',' : null}</div> </div> ); } else { const keys = Object.keys(value); return ( <div className={isExactHighlightPath ? styles.highlightObject : styles.object}> <div onClick={this.onCollapseClick}><strong>{'{ '}</strong></div> {keys.map((key, index) => this.renderProperty(key, value[key], index, index < keys.length - 1, this.props.path, this.props.highlightPath))} <div><strong>{' }'}</strong>{hasNext ? ',' : null}</div> </div> ); } } } class ArrayValue extends React.Component { static contextTypes = { options: React.PropTypes.object.isRequired } constructor(props, context) { super(props); const numberOfItems = props.value.length; const isHighlightPath = this.props.highlightPath && isInPath(this.props.highlightPath, this.props.path); this.state = { isCollapsed: !isHighlightPath && (numberOfItems > 3 || numberOfItems === 0) ? true : context.options.expanded ? false : true }; this.onCollapseClick = this.onCollapseClick.bind(this); this.onExpandClick = this.onExpandClick.bind(this); } shouldComponentUpdate(nextProps, nextState) { return ( nextState.isCollapsed !== this.state.isCollapsed || this.context.options.canEdit || nextProps.path !== this.props.path || nextProps.highlightPath !== this.props.highlightPath ); } componentWillReceiveProps(nextProps) { const context = this.context; const props = nextProps; const numberOfItems = props.value.length; const isHighlightPath = props.highlightPath && isInPath(props.highlightPath, props.path); if (this.state.isCollapsed) { this.setState({ isCollapsed: !isHighlightPath && (numberOfItems > 3 || numberOfItems === 0) ? true : context.options.expanded ? false : true }); } } onExpandClick() { this.setState({isCollapsed: false}) } onCollapseClick() { this.setState({isCollapsed: true}); } renderItem(item, index, hasNext, path) { this.props.path.push(index); const arrayItem = ( <div className={styles.arrayItem} key={index}> {renderType(item, hasNext, path.slice())} </div> ); this.props.path.pop(); return arrayItem; } render() { const {value, hasNext} = this.props; const isExactHighlightPath = this.props.highlightPath && String(this.props.highlightPath) === String(this.props.path); if (this.state.isCollapsed) { return ( <div className={isExactHighlightPath ? styles.highlightArray : styles.array} onClick={this.onExpandClick}> {this.props.propertyKey ? this.props.propertyKey + ': ' : null} <strong>{'[ '}</strong>{value.length}<strong>{' ]'}</strong> {hasNext ? ',' : null} </div> ); } else if (this.props.propertyKey) { const keys = Object.keys(value); return ( <div className={isExactHighlightPath ? styles.highlightArray : styles.array}> <div onClick={this.onCollapseClick}>{this.props.propertyKey}: <strong>{'[ '}</strong></div> {value.map((item, index) => this.renderItem(item, index, index < value.length - 1, this.props.path))} <div><strong>{' ]'}</strong>{hasNext ? ',' : null}</div> </div> ); } else { return ( <div className={isExactHighlightPath ? styles.highlightArray : styles.array}> <div onClick={this.onCollapseClick}><strong>{'[ '}</strong></div> {value.map((item, index) => this.renderItem(item, index, index < value.length - 1, this.props.path))} <div><strong>{' ]'}</strong>{hasNext ? ',' : null}</div> </div> ); } } } @connect() class Value extends React.Component { static contextTypes = { options: React.PropTypes.object.isRequired } constructor(props) { super(props); this.state = { isEditing: false, path: props.path.slice() }; this.onSubmit = this.onSubmit.bind(this); this.onBlur = this.onBlur.bind(this); this.onClick = this.onClick.bind(this); } shouldComponentUpdate(nextProps, nextState) { return ( nextProps.value !== this.props.value || nextState.isEditing !== this.state.isEditing || nextProps.path !== this.props.path ); } onClick() { this.setState({ isEditing: this.context.options.canEdit ? true : false }); } onSubmit(value) { this.props.signals.debugger.modelChanged({ path: this.state.path, value }) this.setState({isEditing: false}); connector.sendEvent('changeModel', { path: this.state.path, value: value }); } onBlur() { this.setState({isEditing: false}); } renderValue(value, hasNext) { const isExactHighlightPath = this.props.highlightPath && String(this.props.highlightPath) === String(this.props.path); if (this.state.isEditing) { return ( <div className={isExactHighlightPath ? styles.highlightValue : null}> {this.props.propertyKey ? this.props.propertyKey + ': ' : <span/>} <span> <JSONInput value={value} onBlur={this.onBlur} onSubmit={this.onSubmit}/> </span> {hasNext ? ',' : null} </div> ); } else { return ( <div className={isExactHighlightPath ? styles.highlightValue : null}> {this.props.propertyKey ? this.props.propertyKey + ': ' : <span/>} <span onClick={this.onClick}>{isString(value) ? '"' + value + '"' : String(value)}</span> {hasNext ? ',' : null} </div> ); } } render() { let className = styles.string; if (isNumber(this.props.value)) className = styles.number; if (isBoolean(this.props.value)) className = styles.boolean; if (isNull(this.props.value)) className = styles.null; return ( <div className={className}> {this.renderValue(this.props.value, this.props.hasNext)} </div> ); } } class Inspector extends React.Component { static childContextTypes = { options: React.PropTypes.object.isRequired } getChildContext() { return { options: { expanded: this.props.expanded || false, canEdit: this.props.canEdit || false } } } render() { return renderType(this.props.value, false, [], null, this.props.path); } } export default Inspector;
cerebral/cerebral-debugger-prototype
versions/v1/components/Debugger/Inspector/index.js
JavaScript
mit
10,888
// Package storagedatalake implements the Azure ARM Storagedatalake service API version 2019-10-31. // // Azure Data Lake Storage provides storage for Hadoop and other big data workloads. package storagedatalake // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. See License.txt in the project root for license information. // // Code generated by Microsoft (R) AutoRest Code Generator. // Changes may cause incorrect behavior and will be lost if the code is regenerated. import ( "github.com/Azure/go-autorest/autorest" ) const ( // DefaultDNSSuffix is the default value for dns suffix DefaultDNSSuffix = "dfs.core.windows.net" ) // BaseClient is the base client for Storagedatalake. type BaseClient struct { autorest.Client XMsVersion string AccountName string DNSSuffix string } // New creates an instance of the BaseClient client. func New(xMsVersion string, accountName string) BaseClient { return NewWithoutDefaults(xMsVersion, accountName, DefaultDNSSuffix) } // NewWithoutDefaults creates an instance of the BaseClient client. func NewWithoutDefaults(xMsVersion string, accountName string, dNSSuffix string) BaseClient { return BaseClient{ Client: autorest.NewClientWithUserAgent(UserAgent()), XMsVersion: xMsVersion, AccountName: accountName, DNSSuffix: dNSSuffix, } }
Azure/azure-sdk-for-go
services/storage/datalake/2019-10-31/storagedatalake/client.go
GO
mit
1,358
'use strict'; function valuefy(value) { if (typeof value !== 'object') { return (typeof value === 'string') ? `"${value}"` : value; } let values = []; if (Array.isArray(value)) { for (const v of value) { values.push(valuefy(v)); } values = `[${values.join(',')}]`; } else { for (let v in value) { if ({}.hasOwnProperty.call(value, v)) { values.push(`"${v}":${valuefy(value[v])}`); } } values = `{${values.join(',')}}`; } return values; } function serialize(target) { if (!target || typeof target !== 'object') { throw new TypeError('Invalid type of target'); } let values = []; for (let t in target) { if ({}.hasOwnProperty.call(target, t)) { values.push(`${t}=${valuefy(target[t])}`); } } return values; } function extract(t, outter, onlyContent) { const start = onlyContent ? 1 : 0; const pad = onlyContent ? 0 : 1; return t.slice(start, t.lastIndexOf(outter) + pad); } function objectify(v) { if (v[0] === '{') { return JSON.parse(extract(v, '}')); } else if (v[0] === '[') { const set = []; const es = extract(v, ']', true); if (es[0] === '[' || es[0] === '{') { set.push(objectify(es)); } else { for (const e of es.split(',')) { set.push(objectify(e)); } } return set; } else if (v[0] === '"') { v = extract(v, '"', true); } return v; } function deserialize(values) { if (!values) { throw new TypeError('Invalid type of values'); } else if (!Array.isArray(values)) { values = [values]; } const target = {}; for (const v of values) { const fieldValue = v.split('=', 2); target[fieldValue[0]] = objectify(fieldValue[1]); } return target; } module.exports = { pairify: serialize, parse: deserialize };
ragingwind/field-value
index.js
JavaScript
mit
1,725
<?php namespace App\Notifications\Mship; use App\Notifications\Notification; use Illuminate\Bus\Queueable; use Illuminate\Contracts\Queue\ShouldQueue; use Illuminate\Notifications\Messages\MailMessage; class ForgottenPasswordLink extends Notification implements ShouldQueue { use Queueable; private $token; /** * Create a new notification instance. * * @return void */ public function __construct($token) { parent::__construct(); $this->token = $token; } /** * Get the notification's delivery channels. * * @param mixed $notifiable * @return array */ public function via($notifiable) { return ['mail', 'database']; } /** * Get the mail representation of the notification. * * @param mixed $notifiable * @return \Illuminate\Notifications\Messages\MailMessage */ public function toMail($notifiable) { $subject = 'SSO Password Reset'; return (new MailMessage) ->from(config('mail.from.address'), 'VATSIM UK Web Services') ->subject($subject) ->view('emails.mship.security.reset_confirmation', ['subject' => $subject, 'recipient' => $notifiable, 'account' => $notifiable, 'token' => route('password.reset', $this->token)]); } /** * Get the array representation of the notification. * * @param mixed $notifiable * @return array */ public function toArray($notifiable) { return ['token' => $this->token]; } }
atoff/core
app/Notifications/Mship/ForgottenPasswordLink.php
PHP
mit
1,567
export default class TasksService { static async fetchTasks() { const delay = (ms) => new Promise((resolve) => setTimeout(resolve, ms)); await delay(1000); return [ { id: 0, description: "task1", status: "Active" }, { id: 1, description: "task2", status: "Active" }, ]; } }
guptag/js-frameworks
React/examples/hello-world/src/data/TasksService.js
JavaScript
mit
308
// // GUISlider.h // GUIPlayerView // // Created by Guilherme Araújo on 08/12/14. // Copyright (c) 2014 Guilherme Araújo. All rights reserved. // #import <UIKit/UIKit.h> @interface GUISlider : UISlider - (void)setSecondaryValue:(float)value; - (void)setSecondaryTintColor:(UIColor *)tintColor; @property (nonatomic, retain) NSNumber * thick; @end @interface GUISlider (extra) @property(nonatomic, assign) NSNumber* thickNess; @end
tthufo/THPod
THPod/Classes/GUISlider.h
C
mit
446
#ifndef RUBY_EXT_UTILS_HPP_ #define RUBY_EXT_UTILS_HPP_ 1 #include <functional> #include <ruby.h> #include <stdlib.h> #include <string.h> #include <stdarg.h> #include <typeinfo> #ifdef __GNUC__ #include <cxxabi.h> #endif template <typename T> static const char * type_name() { #ifdef __GNUC__ const int buf_size = 32; static char tname[buf_size]; if (tname[0] != 0) { return tname; } const std::type_info& id = typeid(T); int status; char *name = abi::__cxa_demangle(id.name(), NULL, 0, &status); if (name != NULL) { if (status == 0) { strncpy(tname, name, buf_size - 1); } else { strncpy(tname, id.name(), buf_size - 1); } free(name); } return tname; #else return typeid(T).name(); #endif } /* * undefined reference to ... [g++ (tdm-1) 4.5.2] */ // template<typename T> // static void // tmp_obj_free(T ptr) // { // if (ptr) { // delete ptr; // } // } // template<typename T> // static void // tmp_ary_free(T ptr) // { // if (ptr) { // delete[] ptr; // } // } template<typename T> static void tmp_obj_free(void *ptr) { if (ptr) { T obj = static_cast<T>(ptr); delete obj; } } template<typename T> static void tmp_ary_free(void *ptr) { if (ptr) { T obj = static_cast<T>(ptr); delete[] obj; } } template<typename T> static inline VALUE wrap_tmp_obj(T ptr) { return Data_Wrap_Struct(rb_cObject, 0, tmp_obj_free<T>, ptr); } template<typename T> static inline VALUE wrap_tmp_ary(T ptr) { return Data_Wrap_Struct(rb_cObject, 0, tmp_ary_free<T>, ptr); } void delete_tmp_obj(volatile VALUE *store); #define delete_tmp_ary(x) delete_tmp_obj(x) /* * http://masamitsu-murase.blogspot.jp/2013/12/sevenzipruby-2-c-ruby.html */ extern "C" VALUE rxu_run_functor(VALUE p); #define RXU_PROTECT_FUNC(func) ((VALUE (*)(VALUE))(func)) template<typename T> static inline VALUE _rb_protect(T func, int *state) { typedef std::function<VALUE ()> func_type; func_type f = func; return rb_protect(rxu_run_functor, reinterpret_cast<VALUE>(&f), state); } template<typename T1, typename T2> static inline VALUE _rb_rescue(T1 func1, T2 func2) { typedef std::function<VALUE ()> func_type; func_type f1 = func1; func_type f2 = func2; return rb_rescue( RUBY_METHOD_FUNC(rxu_run_functor), reinterpret_cast<VALUE>(&f1), RUBY_METHOD_FUNC(rxu_run_functor), reinterpret_cast<VALUE>(&f2)); } #if defined(_MSC_VER) && _MSC_VER <= 1800 template<VALUE& e1, typename T1, typename T2> static inline VALUE _rb_rescue2(T1 func1, T2 func2) { typedef std::function<VALUE ()> func_type; func_type f1 = func1; func_type f2 = func2; return rb_rescue2( RUBY_METHOD_FUNC(rxu_run_functor), reinterpret_cast<VALUE>(&f1), RUBY_METHOD_FUNC(rxu_run_functor), reinterpret_cast<VALUE>(&f2), e1, NULL); } template<VALUE& e1, VALUE& e2, typename T1, typename T2> static inline VALUE _rb_rescue2(T1 func1, T2 func2) { typedef std::function<VALUE ()> func_type; func_type f1 = func1; func_type f2 = func2; return rb_rescue2( RUBY_METHOD_FUNC(rxu_run_functor), reinterpret_cast<VALUE>(&f1), RUBY_METHOD_FUNC(rxu_run_functor), reinterpret_cast<VALUE>(&f2), e1, e2, NULL); } template<VALUE& e1, VALUE& e2, VALUE& e3, typename T1, typename T2> static inline VALUE _rb_rescue2(T1 func1, T2 func2) { typedef std::function<VALUE ()> func_type; func_type f1 = func1; func_type f2 = func2; return rb_rescue2( RUBY_METHOD_FUNC(rxu_run_functor), reinterpret_cast<VALUE>(&f1), RUBY_METHOD_FUNC(rxu_run_functor), reinterpret_cast<VALUE>(&f2), e1, e2, e3, NULL); } template<VALUE& e1, VALUE& e2, VALUE& e3, VALUE& e4, typename T1, typename T2> static inline VALUE _rb_rescue2(T1 func1, T2 func2) { typedef std::function<VALUE ()> func_type; func_type f1 = func1; func_type f2 = func2; return rb_rescue2( RUBY_METHOD_FUNC(rxu_run_functor), reinterpret_cast<VALUE>(&f1), RUBY_METHOD_FUNC(rxu_run_functor), reinterpret_cast<VALUE>(&f2), e1, e2, e3, e4, NULL); } template<VALUE& e1, VALUE& e2, VALUE& e3, VALUE& e4, VALUE& e5, typename T1, typename T2> static inline VALUE _rb_rescue2(T1 func1, T2 func2) { typedef std::function<VALUE ()> func_type; func_type f1 = func1; func_type f2 = func2; return rb_rescue2( RUBY_METHOD_FUNC(rxu_run_functor), reinterpret_cast<VALUE>(&f1), RUBY_METHOD_FUNC(rxu_run_functor), reinterpret_cast<VALUE>(&f2), e1, e2, e3, e4, e5, NULL); } #else template<VALUE&... exceptions, typename T1, typename T2> static inline VALUE _rb_rescue2(T1 func1, T2 func2) { typedef std::function<VALUE ()> func_type; func_type f1 = func1; func_type f2 = func2; return rb_rescue2( RUBY_METHOD_FUNC(rxu_run_functor), reinterpret_cast<VALUE>(&f1), RUBY_METHOD_FUNC(rxu_run_functor), reinterpret_cast<VALUE>(&f2), exceptions..., NULL); } #endif template<typename T1, typename T2> static inline VALUE _rb_rescue2(T1 func1, T2 func2, VALUE e1) { typedef std::function<VALUE ()> func_type; func_type f1 = func1; func_type f2 = func2; return rb_rescue2( RUBY_METHOD_FUNC(rxu_run_functor), reinterpret_cast<VALUE>(&f1), RUBY_METHOD_FUNC(rxu_run_functor), reinterpret_cast<VALUE>(&f2), e1, NULL); } template<typename T1, typename T2> static inline VALUE _rb_rescue2(T1 func1, T2 func2, VALUE e1, VALUE e2) { typedef std::function<VALUE ()> func_type; func_type f1 = func1; func_type f2 = func2; return rb_rescue2( RUBY_METHOD_FUNC(rxu_run_functor), reinterpret_cast<VALUE>(&f1), RUBY_METHOD_FUNC(rxu_run_functor), reinterpret_cast<VALUE>(&f2), e1, e2, NULL); } template<typename T1, typename T2> static inline VALUE _rb_rescue2(T1 func1, T2 func2, VALUE e1, VALUE e2, VALUE e3) { typedef std::function<VALUE ()> func_type; func_type f1 = func1; func_type f2 = func2; return rb_rescue2( RUBY_METHOD_FUNC(rxu_run_functor), reinterpret_cast<VALUE>(&f1), RUBY_METHOD_FUNC(rxu_run_functor), reinterpret_cast<VALUE>(&f2), e1, e2, e3, NULL); } template<typename T1, typename T2> static inline VALUE _rb_rescue2(T1 func1, T2 func2, VALUE e1, VALUE e2, VALUE e3, VALUE e4) { typedef std::function<VALUE ()> func_type; func_type f1 = func1; func_type f2 = func2; return rb_rescue2( RUBY_METHOD_FUNC(rxu_run_functor), reinterpret_cast<VALUE>(&f1), RUBY_METHOD_FUNC(rxu_run_functor), reinterpret_cast<VALUE>(&f2), e1, e2, e3, e4, NULL); } template<typename T1, typename T2> static inline VALUE _rb_rescue2(T1 func1, T2 func2, VALUE e1, VALUE e2, VALUE e3, VALUE e4, VALUE e5) { typedef std::function<VALUE ()> func_type; func_type f1 = func1; func_type f2 = func2; return rb_rescue2( RUBY_METHOD_FUNC(rxu_run_functor), reinterpret_cast<VALUE>(&f1), RUBY_METHOD_FUNC(rxu_run_functor), reinterpret_cast<VALUE>(&f2), e1, e2, e3, e4, e5, NULL); } template<typename T1, typename T2> static inline VALUE _rb_ensure(T1 func1, T2 func2) { typedef std::function<VALUE ()> func_type; func_type f1 = func1; func_type f2 = func2; return rb_ensure( RUBY_METHOD_FUNC(rxu_run_functor), reinterpret_cast<VALUE>(&f1), RUBY_METHOD_FUNC(rxu_run_functor), reinterpret_cast<VALUE>(&f2)); } extern "C" int rxu_run_functor_foreach(VALUE key, VALUE val, VALUE p); #define RXU_FOREACH_FUNC(func) ((int (*)(ANYARGS))(func)) template<typename T> static inline void _rb_hash_foreach(VALUE obj, T func) { typedef std::function<int (VALUE, VALUE)> func_type; func_type f = func; rb_hash_foreach(obj, RXU_FOREACH_FUNC(rxu_run_functor_foreach), reinterpret_cast<VALUE>(&f)); } #endif /* RUBY_EXT_UTILS_HPP_ */
yagisumi/ruby-gdiplus
ext/gdiplus/ruby_ext_utils.hpp
C++
mit
8,156
/** * Vasya Hobot * * Copyright (c) 2013-2014 Vyacheslav Slinko * Licensed under the MIT License */ function Message(chat, body) { this._chat = chat; this._body = body; } Message.prototype.getChat = function() { return this._chat; }; Message.prototype.getBody = function() { return this._body; }; module.exports = Message;
vslinko-archive/vasya-hobot
src/client/api/Message.js
JavaScript
mit
351
<?php namespace PLL\SocialBundle\Form\Type; use Symfony\Component\Form\AbstractType; use Symfony\Component\Form\Extension\Core\Type\TextareaType; use Symfony\Component\Form\Extension\Core\Type\SubmitType; use Symfony\Component\Form\FormBuilderInterface; use Symfony\Component\OptionsResolver\OptionsResolver; use Symfony\Component\Translation\TranslatorInterface; class PostType extends AbstractType { public function buildForm(FormBuilderInterface $builder, array $options) { $builder ->add('content', TextareaType::class, array( 'required' => true, 'label' => false, )) ->add('save', SubmitType::class, array( 'label' => 'timelinepost.label.post', 'translation_domain' => 'forms', 'attr' => array( 'class' => 'post-btn w3-btn w3-theme', ) )) ; } public function configureOptions(OptionsResolver $resolver) { $resolver->setDefaults(array( 'data_class' => 'PLL\SocialBundle\Entity\Post' )); } } ?>
Kishlin/Ehub
src/PLL/SocialBundle/Form/Type/PostType.php
PHP
mit
1,072
package septemberpack.september; import android.graphics.Bitmap; import android.graphics.Canvas; import android.graphics.Rect; import java.util.Random; /** * Created by Vlady on 22.10.2015. */ /** * Данный класс реализует отрисовку астероидов */ public class Asteroid { Bitmap bitmap; /** * Координаты первого астероида */ private int line1x; private int line1y; /** * Координаты второго астероида */ private int line2x; private int line2y; /** * Координаты третьего астероида */ private int line3x; private int line3y; private Random random; /** * Конструктор получающий объект картинки будущего астероида и * задающий астероидам рандомные координаты * @param bmp - объект картинки астероида */ public Asteroid(Bitmap bmp){ this.bitmap = bmp; random = new Random(); line1x = random.nextInt(880); line2x = random.nextInt(880); line3x = random.nextInt(880); line1y = -random.nextInt(300); line2y = -random.nextInt(300) - 400; // За пределом экрана минус 400 line3y = -random.nextInt(300) - 800; // За пределом экрана минус 800 } /** * Метод отрисовки астероидов * @param canvas - прямоугольная область экрана для рисования */ public void draw(Canvas canvas){ canvas.drawBitmap(bitmap, line1x, line1y, null); // Первая линия canvas.drawBitmap(bitmap, line2x, line2y, null); // Вторая линия canvas.drawBitmap(bitmap, line3x, line3y, null); // Третья линия } /** * Метод обновляющий координаты астероидов и задающий новые координаты при уплытии за границы фона */ public void update(){ if(line1y > 1400) { line1y = -80; line1x = random.nextInt(880); } else if(line2y > 1400) { line2y = -80; line2x = random.nextInt(880); } else if(line3y > 1400) { line3y = -80; line3x = random.nextInt(880); } line1y += GamePanel.speed; line2y += GamePanel.speed; line3y += GamePanel.speed; } /* * Методы возвращают прямоугольную область астероида по его координатам, для проверки столкновения с кораблем * Реализацию можно было уместить в один метод с четырьмя параметрами, но его вызов был бы нечитаемым * Поскольку присутствуют всего три астероида, мы имеем возможность сделать для каждого свой метод */ public Rect getAsteroid1(){ return new Rect(line1x, line1y, line1x + 100, line1y + 120); } public Rect getAsteroid2(){ return new Rect(line2x, line2y, line2x + 100, line2y + 120); } public Rect getAsteroid3(){ return new Rect(line3x, line3y, line3x + 100, line3y + 120); } }
vladb55/SeptemberRepository
app/src/main/java/septemberpack/september/Asteroid.java
Java
mit
3,547
import React from 'react'; import { shallow } from 'enzyme'; import UserProfile from '../UserProfile'; import Wrapper from '../Wrapper'; describe('<UserProfile />', () => { it('should render <Wrapper />', () => { const wrapper = shallow(<UserProfile />); expect(wrapper.find(Wrapper).length).toEqual(1); }); });
on3iro/Gloomhaven-scenario-creator
src/containers/Auth/tests/UserProfile.test.js
JavaScript
mit
327
class CreateWriMetadataSources < ActiveRecord::Migration[5.1] def change create_table :wri_metadata_sources do |t| t.text :name t.timestamps end end end
Vizzuality/climate-watch
db/migrate/20171016113108_create_wri_metadata_sources.rb
Ruby
mit
177
## Examples: **As filters:** ```twig {{ subject | preg_filter(pattern, replacement, limit) }} {{ subject | preg_grep(pattern) }} {{ subject | preg_match(pattern) }} {{ subject | preg_quote(delimiter) }} {{ subject | preg_replace(pattern, replacement, limit) }} {{ subject | preg_split(pattern) }} ``` **As functions:** ```twig {{ preg_filter(subject, pattern, replacement, limit) }} {{ preg_grep(subject, pattern) }} {{ preg_match(subject, pattern) }} {{ preg_quote(subject, delimiter) }} {{ preg_replace(subject, pattern, replacement, limit) }} {{ preg_split(subject, pattern) }} ``` Please read the PHP docs for a more detailed explanation of all functions. **Usage Examples:** *Simple Word Replacement* ```twig {{ "This is a simple example." | preg_replace('/simple/', 'beautiful') }} ``` will output: ```twig This is a beautiful example. ``` *Whitespace cleaning up (Specifically from the results of a Twig macro)* ```twig {% macro generateItemUrl(item, falseLink) %} {% if (falseLink) or item.url is empty %} # {% else %} {{ item.url }} {% endif %} {% endmacro %} <a href="{{ _self.generateItemUrl(item, false) | preg_replace('/\\s+/', ' ') | trim | raw }}">{{ item.name }}</a> ```
LukeTowers/oc-queencityhack2k17-site
plugins/luketowers/twigpcre/DOCUMENTATION.md
Markdown
mit
1,210
<ul class="menu-item"> <li class="home"><a href="/">{{ site.title }}</a></li> {% for link in site.data.navigation %} {% if link.url_en contains 'http' %} {% assign domain = '' %} {% else %} {% assign domain = site.url_en %} {% endif %} <li><a href="{{ domain }}{{ link.url_en }}" {% if link.url contains 'http' %}target="_blank"{% endif %}>{{ link.title_en }}</a></li> {% endfor %} </ul>
TsinStudio/tsinstudio.github.com
_includes/navigation_en.html
HTML
mit
427
<?php namespace Davidsneal\MaxCDN\OAuth; class OAuthDataStore { function lookup_consumer($consumer_key) { // implement me } function lookup_token($consumer, $token_type, $token) { // implement me } function lookup_nonce($consumer, $token, $nonce, $timestamp) { // implement me } function new_request_token($consumer, $callback = null) { // return a new token attached to this consumer } function new_access_token($token, $consumer, $verifier = null) { // return a new access token attached to this consumer // for the user associated with this token if the request token // is authorized // should also invalidate the request token } }
davidsneal/laravel-maxcdn
src/MaxCDN/OAuth/OAuthDataStore.php
PHP
mit
747
import React from 'react'; import { ActivityIndicator, StyleSheet, Image, Text, View, ListView, TouchableOpacity } from 'react-native'; import Dimensions from 'Dimensions'; const {width, height} = Dimensions.get('window'); import globalVariables from '../globalVariables.js'; import LookCell from './LookCell.js'; import User from './User.js'; import DoneFooter from './DoneFooter.js'; import Icon from 'react-native-vector-icons/Ionicons'; const LookDetail = React.createClass({ getInitialState() { return { dataSource: new ListView.DataSource({rowHasChanged: (r1, r2) => r1 !== r2}), comments: [], next:true, pageNo:1, animating:true }; }, getDefaultProps() { return { look:{}, navigator:"", }; }, componentWillMount() { this.queryRromServer(1); }, getDataSource(comments) { // return false; return this.state.dataSource.cloneWithRows(comments); }, renderFooter() { if (!this.state.next) { return ( <DoneFooter/> ); } return <ActivityIndicator style={styles.scrollSpinner} animating={this.state.animating}/>; }, renderHeader() { return ( <LookCell look={this.props.look} navigator={this.props.navigator} onSelect={function(){}} userCell={true} /> ); }, onEndReached() { if(this.props.look.comments_count==0){ this.setState({ next:false, }); return; } if (this.state.next && !this.state.animating) { this.setState({ animating: true }); this.queryRromServer(this.state.pageNo); } }, onSelectUser(user) { this.props.navigator.push({ component: User, title: user.name, backButtonTitle:' ', passProps: { user:user, navigator:this.props.navigator, }, }); }, // shouldComponentUpdate: function(nextProps, nextState) { // console.log('LookDetail.js.js-shouldComponentUpdate'); // return JSON.stringify(nextState)!=JSON.stringify(this.state); // }, renderRow(comments) { if(!comments.comment||!comments.comment.user){ return false; } return ( <TouchableOpacity activeOpacity={0.8} onPress={()=>this.onSelectUser(comments.comment.user)} style={styles.flexContainer}> <Image source={{uri:comments.comment.user.photo}} style={styles.avatar}/> <View style={styles.commentBody}> <View style={styles.commentHeader}> <View style={{flex:1}}> <Text style={styles.userName}>{comments.comment.user.name}</Text> </View> <View style={styles.timeView}> <Icon name="ios-clock-outline" color={globalVariables.textBase} size={15}/> <Text style={styles.time}> {globalVariables.formatDateToString(comments.comment.created_at)}</Text> </View> </View> <Text style={styles.commentText}>{comments.comment.body}</Text> </View> </TouchableOpacity> ); }, render() { console.log(new Date()-0); console.log('LookDetail.js.js-render'); return ( <ListView dataSource={this.state.dataSource} renderRow={this.renderRow} onEndReached={this.onEndReached} renderHeader={this.renderHeader} renderFooter={this.renderFooter} onEndReachedThreshold={10} automaticallyAdjustContentInsets={false} keyboardDismissMode='on-drag' keyboardShouldPersistTaps={false} showsVerticalScrollIndicator={true} style={styles.container} /> ); }, queryRromServer(page) { globalVariables.queryRromServer(globalVariables.apiLookServer+this.props.look.id+'/comments/'+(page||1),this.processsResults); }, processsResults(data) { if (!data||!data.comments||!data.comments.length) { this.setState({ animating: false, next:false, }); return; } var newComments= this.state.comments.concat(data.comments); var next=newComments.length>=this.props.look.comments_count?false:true; this.setState({ comments: newComments, animating: false, dataSource: this.getDataSource(newComments), pageNo: this.state.pageNo+1, next:next, }); } }); const styles = StyleSheet.create({ container: { paddingTop: 64, backgroundColor: globalVariables.background, }, flexContainer: { opacity:0.97, padding: 10, flexDirection: 'row', justifyContent: 'flex-start', }, commentBody: { flex: 1, flexDirection: "column", justifyContent: "center", }, commentHeader: { flexDirection: "row", alignItems: "flex-start" }, userName: { color:globalVariables.base, // fontSize:12, }, timeView:{ // width:50, flexDirection: "row", alignItems:'center', marginRight:5, }, time:{ color:globalVariables.textBase, fontSize:12, // , }, commentText: { // fontSize:12, marginTop:8, flexDirection: "row", color:globalVariables.textBase, }, avatar: { borderRadius: 18, width: 36, height: 36, marginRight: 10, marginLeft: 5, backgroundColor:globalVariables.textBase2, }, scrollSpinner: { marginVertical: 20, }, }); export default LookDetail;
rollo-zhou/look
src/components/LookDetail.js
JavaScript
mit
5,317
#!/usr/bin/env python import sys import os from treestore import Treestore try: taxonomy = sys.argv[1] except: taxonomy = None t = Treestore() treebase_uri = 'http://purl.org/phylo/treebase/phylows/tree/%s' tree_files = [x for x in os.listdir('trees') if x.endswith('.nex')] base_uri = 'http://www.phylocommons.org/trees/%s' tree_list = set(t.list_trees()) for tree_uri in tree_list: if not 'TB2_' in tree_uri: continue tree_id = t.id_from_uri(tree_uri) tb_uri = treebase_uri % (tree_id.replace('_', ':')) print tree_id, tb_uri t.annotate(tree_uri, annotations='?tree bibo:cites <%s> .' % tb_uri)
NESCent/phylocommons
tools/treebase_scraper/annotate_trees.py
Python
mit
622
<?php /** * This file belongs to the AnoynmFramework * * @author vahitserifsaglam <[email protected]> * @see http://gemframework.com * * Thanks for using */ namespace Anonym\Facades; use Anonym\Patterns\Facade; /** * Class Validation * @package Anonym\Facades */ class Validation extends Facade { /** * return the validation facade * * @return string */ protected static function getFacadeClass(){ return 'validation'; } }
AnonymPHP/Anonym-Library
src/Anonym/Facades/Validation.php
PHP
mit
487
/* * The contents of this file are subject to the Mozilla Public * License Version 1.1 (the "License"); you may not use this * file except in compliance with the License. You may obtain * a copy of the License at http://www.mozilla.org/MPL/ * * Software distributed under the License is distributed on an * "AS IS" basis, WITHOUT WARRANTY OF ANY KIND, either express * or implied. See the License for the specific language governing * rights and limitations under the License. * * * The Original Code is OIOSAML Java Service Provider. * * The Initial Developer of the Original Code is Trifork A/S. Portions * created by Trifork A/S are Copyright (C) 2008 Danish National IT * and Telecom Agency (http://www.itst.dk). All Rights Reserved. * * Contributor(s): * Joakim Recht <[email protected]> * Rolf Njor Jensen <[email protected]> * Aage Nielsen <[email protected]> * */ package dk.itst.oiosaml.sp.service; import java.io.IOException; import java.util.HashMap; import java.util.Map; import java.util.concurrent.atomic.AtomicBoolean; import javax.servlet.Filter; import javax.servlet.FilterChain; import javax.servlet.FilterConfig; import javax.servlet.RequestDispatcher; import javax.servlet.ServletException; import javax.servlet.ServletRequest; import javax.servlet.ServletResponse; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletRequestWrapper; import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpSession; import dk.itst.oiosaml.logging.Logger; import dk.itst.oiosaml.logging.LoggerFactory; import org.apache.commons.configuration.Configuration; import org.opensaml.DefaultBootstrap; import org.opensaml.xml.ConfigurationException; import dk.itst.oiosaml.common.SAMLUtil; import dk.itst.oiosaml.configuration.FileConfiguration; import dk.itst.oiosaml.configuration.SAMLConfiguration; import dk.itst.oiosaml.configuration.SAMLConfigurationFactory; import dk.itst.oiosaml.error.Layer; import dk.itst.oiosaml.error.WrappedException; import dk.itst.oiosaml.logging.Audit; import dk.itst.oiosaml.logging.Operation; import dk.itst.oiosaml.sp.UserAssertion; import dk.itst.oiosaml.sp.UserAssertionHolder; import dk.itst.oiosaml.sp.bindings.BindingHandler; import dk.itst.oiosaml.sp.develmode.DevelMode; import dk.itst.oiosaml.sp.develmode.DevelModeImpl; import dk.itst.oiosaml.sp.metadata.CRLChecker; import dk.itst.oiosaml.sp.metadata.IdpMetadata; import dk.itst.oiosaml.sp.metadata.SPMetadata; import dk.itst.oiosaml.sp.service.session.Request; import dk.itst.oiosaml.sp.service.session.SessionCleaner; import dk.itst.oiosaml.sp.service.session.SessionHandler; import dk.itst.oiosaml.sp.service.session.SessionHandlerFactory; import dk.itst.oiosaml.sp.service.util.Constants; /** * Servlet filter for checking if the user is authenticated. * * <p> * If the user is authenticated, a session attribute, * {@link Constants#SESSION_USER_ASSERTION} is set to contain a * {@link UserAssertion} representing the user. The application layer can access * this object to retrieve SAML attributes for the user. * </p> * * <p> * If the user is not authenticated, a &lt;AuthnRequest&gt; is created and sent * to the IdP. The protocol used for this is selected automatically based on th * available bindings in the SP and IdP metadata. * </p> * * <p> * The atual redirects are done by {@link BindingHandler} objects. * </p> * * <p> * Discovery profile is supported by looking at a request parameter named * _saml_idp. If the parameter does not exist, the browser is redirected to * {@link Constants#DISCOVERY_LOCATION}, which reads the domain cookie. If the * returned value contains ids, one of the ids is selected. If none of the ids * in the list is registered, an exception is thrown. If no value has been set, * the first configured IdP is selected automatically. * </p> * * @author Joakim Recht <[email protected]> * @author Rolf Njor Jensen <[email protected]> * @author Aage Nielsen <[email protected]> */ public class SPFilter implements Filter { private static final Logger log = LoggerFactory.getLogger(SPFilter.class); private CRLChecker crlChecker = new CRLChecker(); private boolean filterInitialized; private SAMLConfiguration conf; private String hostname; private SessionHandlerFactory sessionHandlerFactory; private AtomicBoolean cleanerRunning = new AtomicBoolean(false); private DevelMode develMode; /** * Static initializer for bootstrapping OpenSAML. */ static { try { DefaultBootstrap.bootstrap(); } catch (ConfigurationException e) { throw new WrappedException(Layer.DATAACCESS, e); } } public void destroy() { SessionCleaner.stopCleaner(); crlChecker.stopChecker(); if (sessionHandlerFactory != null) { sessionHandlerFactory.close(); } SessionHandlerFactory.Factory.close(); } /** * Check whether the user is authenticated i.e. having session with a valid * assertion. If the user is not authenticated an &lt;AuthnRequest&gt; is * sent to the Login Site. * * @param request * The servletRequest * @param response * The servletResponse */ public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException { if (log.isDebugEnabled()) log.debug("OIOSAML-J SP Filter invoked"); if (!(request instanceof HttpServletRequest)) { throw new RuntimeException("Not supported operation..."); } HttpServletRequest servletRequest = ((HttpServletRequest) request); Audit.init(servletRequest); if (!isFilterInitialized()) { try { Configuration conf = SAMLConfigurationFactory.getConfiguration().getSystemConfiguration(); setRuntimeConfiguration(conf); } catch (IllegalStateException e) { request.getRequestDispatcher("/saml/configure").forward(request, response); return; } } if (conf.getSystemConfiguration().getBoolean(Constants.PROP_DEVEL_MODE, false)) { log.warn("Running in debug mode, skipping regular filter"); develMode.doFilter(servletRequest, (HttpServletResponse) response, chain, conf.getSystemConfiguration()); return; } if (cleanerRunning.compareAndSet(false, true)) { SessionCleaner.startCleaner(sessionHandlerFactory.getHandler(), ((HttpServletRequest) request).getSession().getMaxInactiveInterval(), 30); } SessionHandler sessionHandler = sessionHandlerFactory.getHandler(); if (servletRequest.getServletPath().equals(conf.getSystemConfiguration().getProperty(Constants.PROP_SAML_SERVLET))) { log.debug("Request to SAML servlet, access granted"); chain.doFilter(new SAMLHttpServletRequest(servletRequest, hostname, null), response); return; } final HttpSession session = servletRequest.getSession(); if (log.isDebugEnabled()) log.debug("sessionId....:" + session.getId()); Boolean forceAuthn = false; if(request.getParameterMap().containsKey(Constants.QUERY_STRING_FORCE_AUTHN)) { String forceAuthnAsString = request.getParameter(Constants.QUERY_STRING_FORCE_AUTHN); forceAuthn = forceAuthnAsString.toLowerCase().equals("true"); } // Is the user logged in? if (sessionHandler.isLoggedIn(session.getId()) && session.getAttribute(Constants.SESSION_USER_ASSERTION) != null && !forceAuthn) { int actualAssuranceLevel = sessionHandler.getAssertion(session.getId()).getAssuranceLevel(); int assuranceLevel = conf.getSystemConfiguration().getInt(Constants.PROP_ASSURANCE_LEVEL); if ((actualAssuranceLevel > 0) && (actualAssuranceLevel < assuranceLevel)) { sessionHandler.logOut(session); log.warn("Assurance level too low: " + actualAssuranceLevel + ", required: " + assuranceLevel); throw new RuntimeException("Assurance level too low: " + actualAssuranceLevel + ", required: " + assuranceLevel); } UserAssertion ua = (UserAssertion) session.getAttribute(Constants.SESSION_USER_ASSERTION); if (log.isDebugEnabled()) log.debug("Everything is ok... Assertion: " + ua); Audit.log(Operation.ACCESS, servletRequest.getRequestURI()); try { UserAssertionHolder.set(ua); HttpServletRequestWrapper requestWrap = new SAMLHttpServletRequest(servletRequest, ua, hostname); chain.doFilter(requestWrap, response); return; } finally { UserAssertionHolder.set(null); } } else { session.removeAttribute(Constants.SESSION_USER_ASSERTION); UserAssertionHolder.set(null); saveRequestAndGotoLogin((HttpServletResponse) response, servletRequest); } } protected void saveRequestAndGotoLogin(HttpServletResponse response, HttpServletRequest request) throws ServletException, IOException { SessionHandler sessionHandler = sessionHandlerFactory.getHandler(); String relayState = sessionHandler.saveRequest(Request.fromHttpRequest(request)); String protocol = conf.getSystemConfiguration().getString(Constants.PROP_PROTOCOL, "saml20"); String loginUrl = conf.getSystemConfiguration().getString(Constants.PROP_SAML_SERVLET, "/saml"); String protocolUrl = conf.getSystemConfiguration().getString(Constants.PROP_PROTOCOL + "." + protocol); if (protocolUrl == null) { throw new RuntimeException("No protocol url configured for " + Constants.PROP_PROTOCOL + "." + protocol); } loginUrl += protocolUrl; if (log.isDebugEnabled()) log.debug("Redirecting to " + protocol + " login handler at " + loginUrl); RequestDispatcher dispatch = request.getRequestDispatcher(loginUrl); dispatch.forward(new SAMLHttpServletRequest(request, hostname, relayState), response); } public void init(FilterConfig filterConfig) throws ServletException { conf = SAMLConfigurationFactory.getConfiguration(); if (conf.isConfigured()) { try { Configuration conf = SAMLConfigurationFactory.getConfiguration().getSystemConfiguration(); if (conf.getBoolean(Constants.PROP_DEVEL_MODE, false)) { develMode = new DevelModeImpl(); setConfiguration(conf); setFilterInitialized(true); return; } setRuntimeConfiguration(conf); setFilterInitialized(true); return; } catch (IllegalStateException e) { log.error("Unable to configure", e); } } setFilterInitialized(false); } private void setRuntimeConfiguration(Configuration conf) { restartCRLChecker(conf); setFilterInitialized(true); setConfiguration(conf); if (!IdpMetadata.getInstance().enableDiscovery()) { log.info("Discovery profile disabled, only one metadata file found"); } else { if (conf.getString(Constants.DISCOVERY_LOCATION) == null) { throw new IllegalStateException("Discovery location cannot be null when discovery profile is active"); } } setHostname(); sessionHandlerFactory = SessionHandlerFactory.Factory.newInstance(conf); sessionHandlerFactory.getHandler().resetReplayProtection(conf.getInt(Constants.PROP_NUM_TRACKED_ASSERTIONIDS)); log.info("Home url: " + conf.getString(Constants.PROP_HOME)); log.info("Assurance level: " + conf.getInt(Constants.PROP_ASSURANCE_LEVEL)); log.info("SP entity ID: " + SPMetadata.getInstance().getEntityID()); log.info("Base hostname: " + hostname); } private void setHostname() { String url = SPMetadata.getInstance().getDefaultAssertionConsumerService().getLocation(); setHostname(url.substring(0, url.indexOf('/', 8))); } private void restartCRLChecker(Configuration conf) { crlChecker.stopChecker(); int period = conf.getInt(Constants.PROP_CRL_CHECK_PERIOD, 600); if (period > 0) { crlChecker.startChecker(period, IdpMetadata.getInstance(), conf); } } public void setHostname(String hostname) { this.hostname = hostname; } public void setFilterInitialized(boolean b) { filterInitialized = b; } public boolean isFilterInitialized() { return filterInitialized; } public void setConfiguration(Configuration configuration) { SAMLConfigurationFactory.getConfiguration().setConfiguration(configuration); conf = SAMLConfigurationFactory.getConfiguration(); } public void setSessionHandlerFactory(SessionHandlerFactory sessionHandlerFactory) { this.sessionHandlerFactory = sessionHandlerFactory; } public void setDevelMode(DevelMode develMode) { this.develMode = develMode; } }
Safewhere/kombit-web-java
Kombit.Samples.CH.WebsiteDemo/src/java/dk/itst/oiosaml/sp/service/SPFilter.java
Java
mit
12,213
{% extends 'swp/base.html' %} {% load static %} {% block content %} <div class="container-fluid"> <div class="page-header"> <h1>{{ event.title }}</h1> </div> {% if user.is_authenticated %} <form action="{% url 'new_event' event.slug.hex %}" method="POST" enctype="multipart/form-data" class="form-inline" > {% csrf_token %} <div class="form-group"> <input type="text" name="caption" value="" placeholder="Caption" required="required" class="form-control" autocomplete="off" /> </div> <div class="form-group"> <label for="new-photo-original">Original</label> <input id="new-photo-original" type="file" name="original" required="required" class="form-control" /> </div> <div class="form-group"> <label for="new-photo-enhanced">Enhanced (optional)</label> <input id="new-photo-enhanced" type="file" name="enhanced" class="form-control" /> </div> <button type="submit" class="btn btn-primary">Upload</button> </form> {% endif %} <div class="row"> {% for photo in photos %} <div class="col-xs-12 col-md-4"> <a href="#" data-toggle="modal" data-target="#swp-all-images-dialog" ><img src="{% static photo.image.thumbnail_path %}" alt="{{ photo.caption }}" class="swp-thumbnail" /></a> <br/> {% if user.is_authenticated %} {% if photo.enhanced %} <div class="btn-group" role="group"> <a href="{% url 'original_file' photo.original.slug.hex %}" role="button" class="btn btn-default btn-sm" >Original</a> <a href="{% url 'original_file' photo.enhanced.slug.hex %}" role="button" class="btn btn-default btn-sm" >Full resolution</a> </div> {% else %} <a href="{% url 'original_file' photo.original.slug.hex %}" role="button" class="btn btn-default btn-sm" >Full resolution</a> {% endif %} {% endif %} </div> {% endfor %} </div> </div> <div class="modal fade" id="swp-all-images-dialog" tabindex="-1" role="dialog" > <div class="modal-dialog modal-lg" role="document"> <div class="modal-content"> <div class="modal-header"> <button type="button" class="close" data-dismiss="modal" ><span aria-hidden="true">&times;</span></button> <h4 class="modal-title" id="myModalLabel">Image Slideshow</h4> </div> <div class="modal-body"> <div id="swp-all-images-carousel" class="carousel slide" data-ride="carousel" data-interval="false" > <!-- Indicators --> <ol class="carousel-indicators"> {% for photo in photos %} <li data-target="SWPCarousel" data-slide-to="{{ forloop.counter0 }}" {% if forloop.counter0 == 0 %} class="active" {% endif %} ></li> {% endfor %} </ol> <!-- Wrapper for slides --> <div class="carousel-inner" role="listbox"> {% for photo in photos %} <div class="item {% if forloop.counter0 == 0 %}active{% endif %}" > <img src="{% static photo.image.image_path %}" class="swp-carousel-image" alt="{{ photo.caption }}" /> <div class="carousel-caption"> <h3>{{ photo.caption }}</h3> </div> </div> {% endfor %} </div> <!-- Left and right controls --> <a class="left carousel-control" href="#swp-all-images-carousel" role="button" data-slide="prev" > <span class="glyphicon glyphicon-chevron-left" aria-hidden="true" ></span> <span class="sr-only">Previous</span> </a> <a class="right carousel-control" href="#swp-all-images-carousel" role="button" data-slide="next" > <span class="glyphicon glyphicon-chevron-right" aria-hidden="true" ></span> <span class="sr-only">Next</span> </a> </div> </div> </div> </div> </div> {% endblock %}
merry-bits/SWP
swp/templates/swp/event.html
HTML
mit
4,577