text
stringlengths
2
1.04M
meta
dict
<?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:context="http://www.springframework.org/schema/context" xmlns:tx="http://www.springframework.org/schema/tx" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd"> <!--扫描service包下所有使用注解的类型--> <context:component-scan base-package="cn.edu.henau.service"/> <!--配置事务管理器--> <bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager"> <!--注入数据库连接池--> <property name="dataSource" ref="dataSource"/> </bean> <!--配置基于注解的声明式事务 默认使用注解来管理事务行为--> <tx:annotation-driven transaction-manager="transactionManager"/> </beans>
{ "content_hash": "c6632906d4cf8517eed127e2fcfe9e9d", "timestamp": "", "source": "github", "line_count": 25, "max_line_length": 216, "avg_line_length": 43.16, "alnum_prop": 0.7117701575532901, "repo_name": "lei1160427600/marksystem", "id": "4d671055bf4bc4c79e031c87bb404ea1fc41107e", "size": "1185", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/main/resources/spring/spring-service.xml", "mode": "33188", "license": "mit", "language": [ { "name": "HTML", "bytes": "557" }, { "name": "Java", "bytes": "58864" } ], "symlink_target": "" }
var options = { websocket: { server: window.location.protocol + '//' + window.location.host + ':6001' } }; module.exports = options;
{ "content_hash": "7ba3c31453e8b4475b8968ef43814c79", "timestamp": "", "source": "github", "line_count": 9, "max_line_length": 80, "avg_line_length": 17.11111111111111, "alnum_prop": 0.577922077922078, "repo_name": "itsrachelfish/laravel-voldb", "id": "541c56a4df05050bdad98580dcd6502e0786cd74", "size": "154", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "laravel/resources/js/config.example.js", "mode": "33188", "license": "mit", "language": [ { "name": "ApacheConf", "bytes": "412" }, { "name": "CSS", "bytes": "3377" }, { "name": "JavaScript", "bytes": "10474" }, { "name": "PHP", "bytes": "181161" } ], "symlink_target": "" }
<!DOCTYPE html> <html> <head> <meta http-equiv="content-type" content="text/html; charset=utf-8"/> <title></title> <link rel="Stylesheet" href="../css/analysis.css" /> <script type="text/javascript"> function init() { if (window.location.hash) { var parentDiv, nodes, i, helpId; helpId = window.location.hash.substring(1); parentDiv = document.getElementById("topics"); nodes = parentDiv.children; for(i=0; i < nodes.length; i++) { if(nodes[i].id !== helpId) { nodes[i].style.display ="none"; } } } } </script> </head> <body onload="init()"> <div id="topics"> <div id="toolDescription" class="largesize"> <h2>Gebieden op basis van reistijd maken</h2><p/> <h2><img src="../images/GUID-989C4173-4BB2-4D42-ADA5-F5D1BB8CB0CB-web.png" alt="Gebieden op basis van reistijd maken"></h2> <hr/> <p>Met Gebieden op basis van reistijd maken kunt u gebieden maken die kunnen worden bereikt binnen een opgegeven reistijd, reisafstand, wandelafstand enzovoort. Het meet de afstanden vanaf een of meerdere punten (maximaal 1000) langs wegen of wandelpaden om een laag te maken die u helpt de volgende vragen te beantwoorden: <ul> <li>Waar kan ik heen binnen een reisduur van 30 minuten vanaf hier? </li> <li>Waar kan ik naartoe binnen een reisduur van 30 minuten vanaf hier om 17.30 uur tijdens het spitsuur? </li> <li>Wat bevindt zich binnen een afstand van twee kilometer wandelen van mijn hotel? </li> <li>Welke stadsdelen kan de brandweer binnen vijf minuten bereiken? </li> <li>In hoeverre zou de dekking van de reactietijd bij een brandalarm verbeteren door hier een nieuwe brandweerkazerne te bouwen? </li> <li>Welke marktgebieden worden door mijn bedrijf gedekt? </li> </ul> </p> <p>Misschien kunt u uw vragen alleen al beantwoorden door de uitvoergebieden te visualiseren. U kunt ook een verdere ruimtelijke analyse uitvoeren aan de hand van de uitvoergebieden. Als u bijvoorbeeld Punten aggregeren uitvoert met behulp van reistijdgebieden met demografische gegevens, kunt u daarmee bepalen welke potenti&euml;le winkellocatie de beste klantbasis zou zijn voor uw type bedrijf. </p> <p> <table> <tr><td colspan="3"><hr size="1" noshade="noshade"></td></tr> <tr><td valign="baseline"><img src="../images/tip.png"></td><td valign="baseline"><h2>Tip:&ensp;</h2></td> <td valign="baseline"> <p>Voor het maken van gebieden door afstanden in rechte lijnen te meten in plaats van langs wegen, gebruikt u in plaats daarvan de tool Buffers maken. </p> </td></tr> <tr><td colspan="3"><hr size="1" noshade="noshade"></td></tr> </table> </p> <p>Als <b>Huidig kaartextent gebruiken</b> is geselecteerd, worden alleen de objecten die binnen het huidige kaartextent zichtbaar zijn, gebruikt om gebieden op basis van reistijd of reisafstand te maken. Als deze optie niet is aangevinkt, worden alle objecten in de invoerlaag gebruikt, ook als ze zich buiten het huidige kaartextent bevinden. </p> </div> <!--Parameter divs for each param--> <div id="MeasurementMethod"> <div><h2>Meten</h2></div> <hr/> <div> <p>Kies uw manier van reizen (auto, vrachtwagen, wandelen) en meeteenheid (tijd of afstand). Nadat u uw manier van reizen en uw meeteenheid hebt gekozen, voert u een duur of afstand in van maximaal 5 uur (300 minuten) of300 mijl (482,80 kilometer). </p> <p>Als u <b>Reistijd</b> kiest, hebt u opties voor het meten van de reistijd. <ul> <li> <p>Vink <b>Verkeer gebruiken</b> uit om gebieden voor reistijd te maken op basis van vaste snelheden. Dit is een geschikte optie als u een algemeen reistijdgebied wilt, en niet een gebied dat wordt berekend aan de hand van vari&euml;rende verkeersomstandigheden voor een bepaalde vertrektijd. </p> </li> <li> <p>Vink <b>Verkeer gebruiken</b> aan om reistijdgebieden te maken op basis van een gegeven vertrektijd en veranderende verkeersomstandigheden. Door eveneens de optie <b>Actueel verkeer</b> te kiezen wordt de vertrektijd van de invoerpunten ingesteld op de huidige tijd, en wordt gebruikgemaakt van huidige en voorspelde verkeerssnelheden via sensors en invoergegevens om de reistijdgebieden te maken. De voorspelde verkeerssnelheden worden berekend op basis van actuele verkeerssnelheden, historische snelheden en huidige omstandigheden zoals het weer. Verkeerssnelheden worden tot 12 uur in de toekomst voorspeld, dus u kunt de schuifregelaar verplaatsen om de vertrektijd maximaal 12 uur naar de toekomst te verplaatsen. </p> <p>Gebruik deze actuele verkeersinstellingen om te ontdekken welke gebieden bereikbaar zijn als u nu vertrekt, over een uur vertrekt, enzovoort. </p> </li> <li> <p>Als u <b>Verkeer gebruiken</b> aanvinkt en <b>Verkeer op basis van gemiddelde omstandigheden voor</b> een dag en een tijdstip selecteert, maakt de tool reistijdgebieden op basis van historische gemiddelde snelheden voor elk interval van vijf minuten gedurende een gewone week. De resultaten houden rekening met het verkeer, maar laten de invloed van huidige verkeersomstandigheden en gebeurtenissen buiten beschouwing die aanzienlijk van het gemiddelde kunnen verschillen. </p> <p>U kunt deze historische verkeersinstellingen bijvoorbeeld gebruiken voor de vraag: 'Welke gebieden kan ik gewoonlijk bereiken wanneer ik op een woensdag om 11:30 uur vertrek?' </p> <p>De tijd die u instelt, verwijst naar de tijdzone waarop uw invoerpunten zich bevinden. Als u de tijd dus instelt op 8:00 uur en twee startpunten hebt, een in New York City en een ander in Los Angeles, worden de reistijdgebieden gegenereerd voor respectievelijk 8:00 uur Eastern Time en 8:00 uur Pacific Time. </p> </li> </ul> </p> <p>Houd er rekening mee dat wanneer een voertuig wegrijdt vanaf een bepaald punt, de tijd verstrijkt en de verkeersomstandigheden wijzigen. De tool Reistijdgebieden houdt rekening met deze variaties wanneer u <b>Reistijd</b> kiest en <b>Verkeer gebruiken</b> selecteert. Niet alle regio's echter ondersteunen verkeer. Klik op de koppeling <b>Beschikbaarheid bekijken</b> om erachter te komen of deze optie voor uw onderzoeksgebied van toepassing is. </p> <p> <b>Wandeltijd</b> en <b>Wandelafstand</b> gebruiken een vaste snelheid van5 kilometer per uur (3,1 mijl per uur) en volgen wandelpaden en straten voor voetgangers (zonder rekening te houden met regels die van toepassing zijn op automobilisten, zoals eenrichtingswegen). </p> <p> <b>Trucktijd</b> en <b>Truckafstand</b> gebruiken vaste snelheden en volgen regels die van toepassing zijn op zware vrachtwagens. </p> </div> </div> <div id="DissolveType"> <div><h2>Gebieden vanaf verschillende punten</h2></div> <hr/> <div> <p>Kies hoe met gedeelde gebieden van verschillende invoerpunten wordt omgegaan wanneer ze elkaar bereiken. Ze kunnen: <ul> <li> <b>Overlappen</b>&mdash;Gebieden van verschillende invoerpunten dekken dezelfde weg. Dit is handig wanneer u alle invoerpunten moet weten vanwaar een bepaalde locatie bereikbaar is binnen de gegeven tijd of afstand. </li> <li> <b>Oplossen</b>&mdash;Alle gebieden worden tot &eacute;&eacute;n gebied samengevoegd, en slechts &eacute;&eacute;n gebied dekt een bepaalde locatie. Dit is handig wanneer u alleen maar hoeft te weten dat een gebied bereikbaar is binnen een gegeven tijd of afstand, maar u niet hoeft te weten vanaf welke specifieke invoerpunten de locatie kan worden bereikt. </li> <li> <b>Splitsen</b>&mdash;De gebieden van verschillende invoerpunten die elkaar zouden overlappen, worden in het midden gesplitst, zodat ze nu aan elkaar grenzen. Dit is handig wanneer u wilt zien welke gebieden zich binnen een gegeven tijd of afstand van de invoerpunten bevinden, en u tegelijk wilt vaststellen welk invoerpunt het dichtst bij dat gebied ligt. </li> </ul> </p> </div> </div> <div id="OutputLayer"> <div><h2>Naam resultaatlaag</h2></div> <hr/> <div> <p>Dit is de naam van de kaartlaag die in <b>Mijn Content</b> wordt gemaakt en aan de kaart wordt toegevoegd. De standaardnaam is gebaseerd op de naam van de analyselaag. Als de laag al bestaat, wordt u gevraagd om te aan te geven of u deze wilt overschrijven. </p> <p>Als u de vervolgkeuzelijst <b>Resultaat opslaan in</b> gebruikt, kunt u de naam opgeven van een map in <b>Mijn Content</b> waarin het resultaat wordt opgeslagen. </p> </div> </div> </div> </html>
{ "content_hash": "216d25a87789f4e22c8957bd5d938d9b", "timestamp": "", "source": "github", "line_count": 128, "max_line_length": 747, "avg_line_length": 75.3515625, "alnum_prop": 0.6520476931052359, "repo_name": "aconyteds/Esri-Ozone-Map-Widget", "id": "cb0e538128b54668aeedfde5e208c72ec649bf7e", "size": "9645", "binary": false, "copies": "6", "ref": "refs/heads/master", "path": "vendor/js/esri/arcgis_js_api/library/3.11/3.11/esri/dijit/analysis/help/nl/CreateDriveTimeAreas.html", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "CSS", "bytes": "534847" }, { "name": "HTML", "bytes": "60280" }, { "name": "JavaScript", "bytes": "3997563" }, { "name": "Ruby", "bytes": "4740" }, { "name": "Shell", "bytes": "1157" } ], "symlink_target": "" }
Welcome to Clock on Exercism's Rust Track. If you need help running the tests or submitting your code, check out `HELP.md`. ## Instructions Implement a clock that handles times without dates. You should be able to add and subtract minutes to it. Two clocks that represent the same time should be equal to each other. You will also need to implement `.to_string()` for the `Clock` struct. We will be using this to display the Clock's state. You can either do it via implementing it directly or using the [Display trait](https://doc.rust-lang.org/std/fmt/trait.Display.html). Did you implement `.to_string()` for the `Clock` struct? If so, try implementing the [Display trait](https://doc.rust-lang.org/std/fmt/trait.Display.html) for `Clock` instead. Traits allow for a common way to implement functionality for various types. For additional learning, consider how you might implement `String::from` for the `Clock` type. You don't have to actually implement this—it's redundant with `Display`, which is generally the better choice when the destination type is `String`—but it's useful to have a few type-conversion traits in your toolkit. ## Source ### Created by - @sacherjj ### Contributed to by - @attilahorvath - @coriolinus - @cwhakes - @danieljl - @eddyp - @efx - @ErikSchierboom - @felix91gr - @kunaltyagi - @lutostag - @nfiles - @petertseng - @rofrol - @shaaraddalvi - @stringparser - @tmccombs - @xakon - @ZapAnton ### Based on Pairing session with Erin Drummond - https://twitter.com/ebdrummond
{ "content_hash": "ff139546c48959abd5ed901be1563cdf", "timestamp": "", "source": "github", "line_count": 55, "max_line_length": 257, "avg_line_length": 27.654545454545456, "alnum_prop": 0.7488494411571335, "repo_name": "rootulp/exercism", "id": "aa089214cad3c5ced0baf63b2464385a64e4bb22", "size": "1534", "binary": false, "copies": "2", "ref": "refs/heads/main", "path": "rust/clock/README.md", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "18900" }, { "name": "CoffeeScript", "bytes": "15342" }, { "name": "Elm", "bytes": "48222" }, { "name": "Go", "bytes": "594636" }, { "name": "HTML", "bytes": "81617" }, { "name": "Java", "bytes": "231244" }, { "name": "JavaScript", "bytes": "126832" }, { "name": "Python", "bytes": "242540" }, { "name": "Ruby", "bytes": "192051" }, { "name": "Rust", "bytes": "77292" }, { "name": "TypeScript", "bytes": "78185" } ], "symlink_target": "" }
/* * DO NOT EDIT. THIS FILE IS GENERATED FROM e:/builds/tinderbox/XR-Trunk/WINNT_5.2_Depend/mozilla/dom/public/idl/base/nsIDOMScreen.idl */ #ifndef __gen_nsIDOMScreen_h__ #define __gen_nsIDOMScreen_h__ #ifndef __gen_domstubs_h__ #include "domstubs.h" #endif /* For IDL files that don't want to include root IDL files. */ #ifndef NS_NO_VTABLE #define NS_NO_VTABLE #endif /* starting interface: nsIDOMScreen */ #define NS_IDOMSCREEN_IID_STR "77947960-b4af-11d2-bd93-00805f8ae3f4" #define NS_IDOMSCREEN_IID \ {0x77947960, 0xb4af, 0x11d2, \ { 0xbd, 0x93, 0x00, 0x80, 0x5f, 0x8a, 0xe3, 0xf4 }} class NS_NO_VTABLE NS_SCRIPTABLE nsIDOMScreen : public nsISupports { public: NS_DECLARE_STATIC_IID_ACCESSOR(NS_IDOMSCREEN_IID) /* readonly attribute long top; */ NS_SCRIPTABLE NS_IMETHOD GetTop(PRInt32 *aTop) = 0; /* readonly attribute long left; */ NS_SCRIPTABLE NS_IMETHOD GetLeft(PRInt32 *aLeft) = 0; /* readonly attribute long width; */ NS_SCRIPTABLE NS_IMETHOD GetWidth(PRInt32 *aWidth) = 0; /* readonly attribute long height; */ NS_SCRIPTABLE NS_IMETHOD GetHeight(PRInt32 *aHeight) = 0; /* readonly attribute long pixelDepth; */ NS_SCRIPTABLE NS_IMETHOD GetPixelDepth(PRInt32 *aPixelDepth) = 0; /* readonly attribute long colorDepth; */ NS_SCRIPTABLE NS_IMETHOD GetColorDepth(PRInt32 *aColorDepth) = 0; /* readonly attribute long availWidth; */ NS_SCRIPTABLE NS_IMETHOD GetAvailWidth(PRInt32 *aAvailWidth) = 0; /* readonly attribute long availHeight; */ NS_SCRIPTABLE NS_IMETHOD GetAvailHeight(PRInt32 *aAvailHeight) = 0; /* readonly attribute long availLeft; */ NS_SCRIPTABLE NS_IMETHOD GetAvailLeft(PRInt32 *aAvailLeft) = 0; /* readonly attribute long availTop; */ NS_SCRIPTABLE NS_IMETHOD GetAvailTop(PRInt32 *aAvailTop) = 0; }; NS_DEFINE_STATIC_IID_ACCESSOR(nsIDOMScreen, NS_IDOMSCREEN_IID) /* Use this macro when declaring classes that implement this interface. */ #define NS_DECL_NSIDOMSCREEN \ NS_SCRIPTABLE NS_IMETHOD GetTop(PRInt32 *aTop); \ NS_SCRIPTABLE NS_IMETHOD GetLeft(PRInt32 *aLeft); \ NS_SCRIPTABLE NS_IMETHOD GetWidth(PRInt32 *aWidth); \ NS_SCRIPTABLE NS_IMETHOD GetHeight(PRInt32 *aHeight); \ NS_SCRIPTABLE NS_IMETHOD GetPixelDepth(PRInt32 *aPixelDepth); \ NS_SCRIPTABLE NS_IMETHOD GetColorDepth(PRInt32 *aColorDepth); \ NS_SCRIPTABLE NS_IMETHOD GetAvailWidth(PRInt32 *aAvailWidth); \ NS_SCRIPTABLE NS_IMETHOD GetAvailHeight(PRInt32 *aAvailHeight); \ NS_SCRIPTABLE NS_IMETHOD GetAvailLeft(PRInt32 *aAvailLeft); \ NS_SCRIPTABLE NS_IMETHOD GetAvailTop(PRInt32 *aAvailTop); /* Use this macro to declare functions that forward the behavior of this interface to another object. */ #define NS_FORWARD_NSIDOMSCREEN(_to) \ NS_SCRIPTABLE NS_IMETHOD GetTop(PRInt32 *aTop) { return _to GetTop(aTop); } \ NS_SCRIPTABLE NS_IMETHOD GetLeft(PRInt32 *aLeft) { return _to GetLeft(aLeft); } \ NS_SCRIPTABLE NS_IMETHOD GetWidth(PRInt32 *aWidth) { return _to GetWidth(aWidth); } \ NS_SCRIPTABLE NS_IMETHOD GetHeight(PRInt32 *aHeight) { return _to GetHeight(aHeight); } \ NS_SCRIPTABLE NS_IMETHOD GetPixelDepth(PRInt32 *aPixelDepth) { return _to GetPixelDepth(aPixelDepth); } \ NS_SCRIPTABLE NS_IMETHOD GetColorDepth(PRInt32 *aColorDepth) { return _to GetColorDepth(aColorDepth); } \ NS_SCRIPTABLE NS_IMETHOD GetAvailWidth(PRInt32 *aAvailWidth) { return _to GetAvailWidth(aAvailWidth); } \ NS_SCRIPTABLE NS_IMETHOD GetAvailHeight(PRInt32 *aAvailHeight) { return _to GetAvailHeight(aAvailHeight); } \ NS_SCRIPTABLE NS_IMETHOD GetAvailLeft(PRInt32 *aAvailLeft) { return _to GetAvailLeft(aAvailLeft); } \ NS_SCRIPTABLE NS_IMETHOD GetAvailTop(PRInt32 *aAvailTop) { return _to GetAvailTop(aAvailTop); } /* Use this macro to declare functions that forward the behavior of this interface to another object in a safe way. */ #define NS_FORWARD_SAFE_NSIDOMSCREEN(_to) \ NS_SCRIPTABLE NS_IMETHOD GetTop(PRInt32 *aTop) { return !_to ? NS_ERROR_NULL_POINTER : _to->GetTop(aTop); } \ NS_SCRIPTABLE NS_IMETHOD GetLeft(PRInt32 *aLeft) { return !_to ? NS_ERROR_NULL_POINTER : _to->GetLeft(aLeft); } \ NS_SCRIPTABLE NS_IMETHOD GetWidth(PRInt32 *aWidth) { return !_to ? NS_ERROR_NULL_POINTER : _to->GetWidth(aWidth); } \ NS_SCRIPTABLE NS_IMETHOD GetHeight(PRInt32 *aHeight) { return !_to ? NS_ERROR_NULL_POINTER : _to->GetHeight(aHeight); } \ NS_SCRIPTABLE NS_IMETHOD GetPixelDepth(PRInt32 *aPixelDepth) { return !_to ? NS_ERROR_NULL_POINTER : _to->GetPixelDepth(aPixelDepth); } \ NS_SCRIPTABLE NS_IMETHOD GetColorDepth(PRInt32 *aColorDepth) { return !_to ? NS_ERROR_NULL_POINTER : _to->GetColorDepth(aColorDepth); } \ NS_SCRIPTABLE NS_IMETHOD GetAvailWidth(PRInt32 *aAvailWidth) { return !_to ? NS_ERROR_NULL_POINTER : _to->GetAvailWidth(aAvailWidth); } \ NS_SCRIPTABLE NS_IMETHOD GetAvailHeight(PRInt32 *aAvailHeight) { return !_to ? NS_ERROR_NULL_POINTER : _to->GetAvailHeight(aAvailHeight); } \ NS_SCRIPTABLE NS_IMETHOD GetAvailLeft(PRInt32 *aAvailLeft) { return !_to ? NS_ERROR_NULL_POINTER : _to->GetAvailLeft(aAvailLeft); } \ NS_SCRIPTABLE NS_IMETHOD GetAvailTop(PRInt32 *aAvailTop) { return !_to ? NS_ERROR_NULL_POINTER : _to->GetAvailTop(aAvailTop); } #if 0 /* Use the code below as a template for the implementation class for this interface. */ /* Header file */ class nsDOMScreen : public nsIDOMScreen { public: NS_DECL_ISUPPORTS NS_DECL_NSIDOMSCREEN nsDOMScreen(); private: ~nsDOMScreen(); protected: /* additional members */ }; /* Implementation file */ NS_IMPL_ISUPPORTS1(nsDOMScreen, nsIDOMScreen) nsDOMScreen::nsDOMScreen() { /* member initializers and constructor code */ } nsDOMScreen::~nsDOMScreen() { /* destructor code */ } /* readonly attribute long top; */ NS_IMETHODIMP nsDOMScreen::GetTop(PRInt32 *aTop) { return NS_ERROR_NOT_IMPLEMENTED; } /* readonly attribute long left; */ NS_IMETHODIMP nsDOMScreen::GetLeft(PRInt32 *aLeft) { return NS_ERROR_NOT_IMPLEMENTED; } /* readonly attribute long width; */ NS_IMETHODIMP nsDOMScreen::GetWidth(PRInt32 *aWidth) { return NS_ERROR_NOT_IMPLEMENTED; } /* readonly attribute long height; */ NS_IMETHODIMP nsDOMScreen::GetHeight(PRInt32 *aHeight) { return NS_ERROR_NOT_IMPLEMENTED; } /* readonly attribute long pixelDepth; */ NS_IMETHODIMP nsDOMScreen::GetPixelDepth(PRInt32 *aPixelDepth) { return NS_ERROR_NOT_IMPLEMENTED; } /* readonly attribute long colorDepth; */ NS_IMETHODIMP nsDOMScreen::GetColorDepth(PRInt32 *aColorDepth) { return NS_ERROR_NOT_IMPLEMENTED; } /* readonly attribute long availWidth; */ NS_IMETHODIMP nsDOMScreen::GetAvailWidth(PRInt32 *aAvailWidth) { return NS_ERROR_NOT_IMPLEMENTED; } /* readonly attribute long availHeight; */ NS_IMETHODIMP nsDOMScreen::GetAvailHeight(PRInt32 *aAvailHeight) { return NS_ERROR_NOT_IMPLEMENTED; } /* readonly attribute long availLeft; */ NS_IMETHODIMP nsDOMScreen::GetAvailLeft(PRInt32 *aAvailLeft) { return NS_ERROR_NOT_IMPLEMENTED; } /* readonly attribute long availTop; */ NS_IMETHODIMP nsDOMScreen::GetAvailTop(PRInt32 *aAvailTop) { return NS_ERROR_NOT_IMPLEMENTED; } /* End of implementation class template. */ #endif #endif /* __gen_nsIDOMScreen_h__ */
{ "content_hash": "2504b0cf8efb72608a5737f1fbe248fd", "timestamp": "", "source": "github", "line_count": 199, "max_line_length": 143, "avg_line_length": 36.05527638190955, "alnum_prop": 0.7381184668989547, "repo_name": "leighpauls/k2cro4", "id": "49ef5adb0372574aece08574a96529bc7f23fae1", "size": "7175", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "third_party/xulrunner-sdk/win/include/dom/nsIDOMScreen.h", "mode": "33188", "license": "bsd-3-clause", "language": [ { "name": "ASP", "bytes": "3062" }, { "name": "AppleScript", "bytes": "25392" }, { "name": "Arduino", "bytes": "464" }, { "name": "Assembly", "bytes": "68131038" }, { "name": "C", "bytes": "242794338" }, { "name": "C#", "bytes": "11024" }, { "name": "C++", "bytes": "353525184" }, { "name": "Common Lisp", "bytes": "3721" }, { "name": "D", "bytes": "1931" }, { "name": "Emacs Lisp", "bytes": "1639" }, { "name": "F#", "bytes": "4992" }, { "name": "FORTRAN", "bytes": "10404" }, { "name": "Java", "bytes": "3845159" }, { "name": "JavaScript", "bytes": "39146656" }, { "name": "Lua", "bytes": "13768" }, { "name": "Matlab", "bytes": "22373" }, { "name": "Objective-C", "bytes": "21887598" }, { "name": "PHP", "bytes": "2344144" }, { "name": "Perl", "bytes": "49033099" }, { "name": "Prolog", "bytes": "2926122" }, { "name": "Python", "bytes": "39863959" }, { "name": "R", "bytes": "262" }, { "name": "Racket", "bytes": "359" }, { "name": "Ruby", "bytes": "304063" }, { "name": "Scheme", "bytes": "14853" }, { "name": "Shell", "bytes": "9195117" }, { "name": "Tcl", "bytes": "1919771" }, { "name": "Verilog", "bytes": "3092" }, { "name": "Visual Basic", "bytes": "1430" }, { "name": "eC", "bytes": "5079" } ], "symlink_target": "" }
declare module "crypto" { import * as stream from "stream"; interface Certificate { exportChallenge(spkac: BinaryLike): Buffer; exportPublicKey(spkac: BinaryLike): Buffer; verifySpkac(spkac: NodeJS.ArrayBufferView): boolean; } const Certificate: { new(): Certificate; (): Certificate; }; namespace constants { // https://nodejs.org/dist/latest-v10.x/docs/api/crypto.html#crypto_crypto_constants const OPENSSL_VERSION_NUMBER: number; /** Applies multiple bug workarounds within OpenSSL. See https://www.openssl.org/docs/man1.0.2/ssl/SSL_CTX_set_options.html for detail. */ const SSL_OP_ALL: number; /** Allows legacy insecure renegotiation between OpenSSL and unpatched clients or servers. See https://www.openssl.org/docs/man1.0.2/ssl/SSL_CTX_set_options.html. */ const SSL_OP_ALLOW_UNSAFE_LEGACY_RENEGOTIATION: number; /** Attempts to use the server's preferences instead of the client's when selecting a cipher. See https://www.openssl.org/docs/man1.0.2/ssl/SSL_CTX_set_options.html. */ const SSL_OP_CIPHER_SERVER_PREFERENCE: number; /** Instructs OpenSSL to use Cisco's "speshul" version of DTLS_BAD_VER. */ const SSL_OP_CISCO_ANYCONNECT: number; /** Instructs OpenSSL to turn on cookie exchange. */ const SSL_OP_COOKIE_EXCHANGE: number; /** Instructs OpenSSL to add server-hello extension from an early version of the cryptopro draft. */ const SSL_OP_CRYPTOPRO_TLSEXT_BUG: number; /** Instructs OpenSSL to disable a SSL 3.0/TLS 1.0 vulnerability workaround added in OpenSSL 0.9.6d. */ const SSL_OP_DONT_INSERT_EMPTY_FRAGMENTS: number; /** Instructs OpenSSL to always use the tmp_rsa key when performing RSA operations. */ const SSL_OP_EPHEMERAL_RSA: number; /** Allows initial connection to servers that do not support RI. */ const SSL_OP_LEGACY_SERVER_CONNECT: number; const SSL_OP_MICROSOFT_BIG_SSLV3_BUFFER: number; const SSL_OP_MICROSOFT_SESS_ID_BUG: number; /** Instructs OpenSSL to disable the workaround for a man-in-the-middle protocol-version vulnerability in the SSL 2.0 server implementation. */ const SSL_OP_MSIE_SSLV2_RSA_PADDING: number; const SSL_OP_NETSCAPE_CA_DN_BUG: number; const SSL_OP_NETSCAPE_CHALLENGE_BUG: number; const SSL_OP_NETSCAPE_DEMO_CIPHER_CHANGE_BUG: number; const SSL_OP_NETSCAPE_REUSE_CIPHER_CHANGE_BUG: number; /** Instructs OpenSSL to disable support for SSL/TLS compression. */ const SSL_OP_NO_COMPRESSION: number; const SSL_OP_NO_QUERY_MTU: number; /** Instructs OpenSSL to always start a new session when performing renegotiation. */ const SSL_OP_NO_SESSION_RESUMPTION_ON_RENEGOTIATION: number; const SSL_OP_NO_SSLv2: number; const SSL_OP_NO_SSLv3: number; const SSL_OP_NO_TICKET: number; const SSL_OP_NO_TLSv1: number; const SSL_OP_NO_TLSv1_1: number; const SSL_OP_NO_TLSv1_2: number; const SSL_OP_PKCS1_CHECK_1: number; const SSL_OP_PKCS1_CHECK_2: number; /** Instructs OpenSSL to always create a new key when using temporary/ephemeral DH parameters. */ const SSL_OP_SINGLE_DH_USE: number; /** Instructs OpenSSL to always create a new key when using temporary/ephemeral ECDH parameters. */ const SSL_OP_SINGLE_ECDH_USE: number; const SSL_OP_SSLEAY_080_CLIENT_DH_BUG: number; const SSL_OP_SSLREF2_REUSE_CERT_TYPE_BUG: number; const SSL_OP_TLS_BLOCK_PADDING_BUG: number; const SSL_OP_TLS_D5_BUG: number; /** Instructs OpenSSL to disable version rollback attack detection. */ const SSL_OP_TLS_ROLLBACK_BUG: number; const ENGINE_METHOD_RSA: number; const ENGINE_METHOD_DSA: number; const ENGINE_METHOD_DH: number; const ENGINE_METHOD_RAND: number; const ENGINE_METHOD_EC: number; const ENGINE_METHOD_CIPHERS: number; const ENGINE_METHOD_DIGESTS: number; const ENGINE_METHOD_PKEY_METHS: number; const ENGINE_METHOD_PKEY_ASN1_METHS: number; const ENGINE_METHOD_ALL: number; const ENGINE_METHOD_NONE: number; const DH_CHECK_P_NOT_SAFE_PRIME: number; const DH_CHECK_P_NOT_PRIME: number; const DH_UNABLE_TO_CHECK_GENERATOR: number; const DH_NOT_SUITABLE_GENERATOR: number; const ALPN_ENABLED: number; const RSA_PKCS1_PADDING: number; const RSA_SSLV23_PADDING: number; const RSA_NO_PADDING: number; const RSA_PKCS1_OAEP_PADDING: number; const RSA_X931_PADDING: number; const RSA_PKCS1_PSS_PADDING: number; /** Sets the salt length for RSA_PKCS1_PSS_PADDING to the digest size when signing or verifying. */ const RSA_PSS_SALTLEN_DIGEST: number; /** Sets the salt length for RSA_PKCS1_PSS_PADDING to the maximum permissible value when signing data. */ const RSA_PSS_SALTLEN_MAX_SIGN: number; /** Causes the salt length for RSA_PKCS1_PSS_PADDING to be determined automatically when verifying a signature. */ const RSA_PSS_SALTLEN_AUTO: number; const POINT_CONVERSION_COMPRESSED: number; const POINT_CONVERSION_UNCOMPRESSED: number; const POINT_CONVERSION_HYBRID: number; /** Specifies the built-in default cipher list used by Node.js (colon-separated values). */ const defaultCoreCipherList: string; /** Specifies the active default cipher list used by the current Node.js process (colon-separated values). */ const defaultCipherList: string; } interface HashOptions extends stream.TransformOptions { /** * For XOF hash functions such as `shake256`, the * outputLength option can be used to specify the desired output length in bytes. */ outputLength?: number; } /** @deprecated since v10.0.0 */ const fips: boolean; function createHash(algorithm: string, options?: HashOptions): Hash; function createHmac(algorithm: string, key: BinaryLike | KeyObject, options?: stream.TransformOptions): Hmac; type Utf8AsciiLatin1Encoding = "utf8" | "ascii" | "latin1"; type HexBase64Latin1Encoding = "latin1" | "hex" | "base64"; type Utf8AsciiBinaryEncoding = "utf8" | "ascii" | "binary"; type HexBase64BinaryEncoding = "binary" | "base64" | "hex"; type ECDHKeyFormat = "compressed" | "uncompressed" | "hybrid"; class Hash extends stream.Transform { private constructor(); copy(): Hash; update(data: BinaryLike): Hash; update(data: string, input_encoding: Utf8AsciiLatin1Encoding): Hash; digest(): Buffer; digest(encoding: HexBase64Latin1Encoding): string; } class Hmac extends stream.Transform { private constructor(); update(data: BinaryLike): Hmac; update(data: string, input_encoding: Utf8AsciiLatin1Encoding): Hmac; digest(): Buffer; digest(encoding: HexBase64Latin1Encoding): string; } type KeyObjectType = 'secret' | 'public' | 'private'; interface KeyExportOptions<T extends KeyFormat> { type: 'pkcs1' | 'spki' | 'pkcs8' | 'sec1'; format: T; cipher?: string; passphrase?: string | Buffer; } class KeyObject { private constructor(); asymmetricKeyType?: KeyType; /** * For asymmetric keys, this property represents the size of the embedded key in * bytes. This property is `undefined` for symmetric keys. */ asymmetricKeySize?: number; export(options: KeyExportOptions<'pem'>): string | Buffer; export(options?: KeyExportOptions<'der'>): Buffer; symmetricKeySize?: number; type: KeyObjectType; } type CipherCCMTypes = 'aes-128-ccm' | 'aes-192-ccm' | 'aes-256-ccm' | 'chacha20-poly1305'; type CipherGCMTypes = 'aes-128-gcm' | 'aes-192-gcm' | 'aes-256-gcm'; type BinaryLike = string | NodeJS.ArrayBufferView; type CipherKey = BinaryLike | KeyObject; interface CipherCCMOptions extends stream.TransformOptions { authTagLength: number; } interface CipherGCMOptions extends stream.TransformOptions { authTagLength?: number; } /** @deprecated since v10.0.0 use createCipheriv() */ function createCipher(algorithm: CipherCCMTypes, password: BinaryLike, options: CipherCCMOptions): CipherCCM; /** @deprecated since v10.0.0 use createCipheriv() */ function createCipher(algorithm: CipherGCMTypes, password: BinaryLike, options?: CipherGCMOptions): CipherGCM; /** @deprecated since v10.0.0 use createCipheriv() */ function createCipher(algorithm: string, password: BinaryLike, options?: stream.TransformOptions): Cipher; function createCipheriv( algorithm: CipherCCMTypes, key: CipherKey, iv: BinaryLike | null, options: CipherCCMOptions ): CipherCCM; function createCipheriv( algorithm: CipherGCMTypes, key: CipherKey, iv: BinaryLike | null, options?: CipherGCMOptions ): CipherGCM; function createCipheriv( algorithm: string, key: CipherKey, iv: BinaryLike | null, options?: stream.TransformOptions ): Cipher; class Cipher extends stream.Transform { private constructor(); update(data: BinaryLike): Buffer; update(data: string, input_encoding: Utf8AsciiBinaryEncoding): Buffer; update(data: NodeJS.ArrayBufferView, input_encoding: undefined, output_encoding: HexBase64BinaryEncoding): string; update(data: string, input_encoding: Utf8AsciiBinaryEncoding | undefined, output_encoding: HexBase64BinaryEncoding): string; final(): Buffer; final(output_encoding: BufferEncoding): string; setAutoPadding(auto_padding?: boolean): this; // getAuthTag(): Buffer; // setAAD(buffer: Buffer): this; // docs only say buffer } interface CipherCCM extends Cipher { setAAD(buffer: Buffer, options: { plaintextLength: number }): this; getAuthTag(): Buffer; } interface CipherGCM extends Cipher { setAAD(buffer: Buffer, options?: { plaintextLength: number }): this; getAuthTag(): Buffer; } /** @deprecated since v10.0.0 use createDecipheriv() */ function createDecipher(algorithm: CipherCCMTypes, password: BinaryLike, options: CipherCCMOptions): DecipherCCM; /** @deprecated since v10.0.0 use createDecipheriv() */ function createDecipher(algorithm: CipherGCMTypes, password: BinaryLike, options?: CipherGCMOptions): DecipherGCM; /** @deprecated since v10.0.0 use createDecipheriv() */ function createDecipher(algorithm: string, password: BinaryLike, options?: stream.TransformOptions): Decipher; function createDecipheriv( algorithm: CipherCCMTypes, key: CipherKey, iv: BinaryLike | null, options: CipherCCMOptions, ): DecipherCCM; function createDecipheriv( algorithm: CipherGCMTypes, key: CipherKey, iv: BinaryLike | null, options?: CipherGCMOptions, ): DecipherGCM; function createDecipheriv(algorithm: string, key: CipherKey, iv: BinaryLike | null, options?: stream.TransformOptions): Decipher; class Decipher extends stream.Transform { private constructor(); update(data: NodeJS.ArrayBufferView): Buffer; update(data: string, input_encoding: HexBase64BinaryEncoding): Buffer; update(data: NodeJS.ArrayBufferView, input_encoding: HexBase64BinaryEncoding | undefined, output_encoding: Utf8AsciiBinaryEncoding): string; update(data: string, input_encoding: HexBase64BinaryEncoding | undefined, output_encoding: Utf8AsciiBinaryEncoding): string; final(): Buffer; final(output_encoding: BufferEncoding): string; setAutoPadding(auto_padding?: boolean): this; // setAuthTag(tag: NodeJS.ArrayBufferView): this; // setAAD(buffer: NodeJS.ArrayBufferView): this; } interface DecipherCCM extends Decipher { setAuthTag(buffer: NodeJS.ArrayBufferView): this; setAAD(buffer: NodeJS.ArrayBufferView, options: { plaintextLength: number }): this; } interface DecipherGCM extends Decipher { setAuthTag(buffer: NodeJS.ArrayBufferView): this; setAAD(buffer: NodeJS.ArrayBufferView, options?: { plaintextLength: number }): this; } interface PrivateKeyInput { key: string | Buffer; format?: KeyFormat; type?: 'pkcs1' | 'pkcs8' | 'sec1'; passphrase?: string | Buffer; } interface PublicKeyInput { key: string | Buffer; format?: KeyFormat; type?: 'pkcs1' | 'spki'; } function createPrivateKey(key: PrivateKeyInput | string | Buffer): KeyObject; function createPublicKey(key: PublicKeyInput | string | Buffer | KeyObject): KeyObject; function createSecretKey(key: Buffer): KeyObject; function createSign(algorithm: string, options?: stream.WritableOptions): Signer; interface SigningOptions { /** * @See crypto.constants.RSA_PKCS1_PADDING */ padding?: number; saltLength?: number; } interface SignPrivateKeyInput extends PrivateKeyInput, SigningOptions { } type KeyLike = string | Buffer | KeyObject; class Signer extends stream.Writable { private constructor(); update(data: BinaryLike): Signer; update(data: string, input_encoding: Utf8AsciiLatin1Encoding): Signer; sign(private_key: SignPrivateKeyInput | KeyLike): Buffer; sign(private_key: SignPrivateKeyInput | KeyLike, output_format: HexBase64Latin1Encoding): string; } function createVerify(algorithm: string, options?: stream.WritableOptions): Verify; class Verify extends stream.Writable { private constructor(); update(data: BinaryLike): Verify; update(data: string, input_encoding: Utf8AsciiLatin1Encoding): Verify; verify(object: object | KeyLike, signature: NodeJS.ArrayBufferView): boolean; verify(object: object | KeyLike, signature: string, signature_format?: HexBase64Latin1Encoding): boolean; // https://nodejs.org/api/crypto.html#crypto_verifier_verify_object_signature_signature_format // The signature field accepts a TypedArray type, but it is only available starting ES2017 } function createDiffieHellman(prime_length: number, generator?: number | NodeJS.ArrayBufferView): DiffieHellman; function createDiffieHellman(prime: NodeJS.ArrayBufferView): DiffieHellman; function createDiffieHellman(prime: string, prime_encoding: HexBase64Latin1Encoding): DiffieHellman; function createDiffieHellman(prime: string, prime_encoding: HexBase64Latin1Encoding, generator: number | NodeJS.ArrayBufferView): DiffieHellman; function createDiffieHellman(prime: string, prime_encoding: HexBase64Latin1Encoding, generator: string, generator_encoding: HexBase64Latin1Encoding): DiffieHellman; class DiffieHellman { private constructor(); generateKeys(): Buffer; generateKeys(encoding: HexBase64Latin1Encoding): string; computeSecret(other_public_key: NodeJS.ArrayBufferView): Buffer; computeSecret(other_public_key: string, input_encoding: HexBase64Latin1Encoding): Buffer; computeSecret(other_public_key: NodeJS.ArrayBufferView, output_encoding: HexBase64Latin1Encoding): string; computeSecret(other_public_key: string, input_encoding: HexBase64Latin1Encoding, output_encoding: HexBase64Latin1Encoding): string; getPrime(): Buffer; getPrime(encoding: HexBase64Latin1Encoding): string; getGenerator(): Buffer; getGenerator(encoding: HexBase64Latin1Encoding): string; getPublicKey(): Buffer; getPublicKey(encoding: HexBase64Latin1Encoding): string; getPrivateKey(): Buffer; getPrivateKey(encoding: HexBase64Latin1Encoding): string; setPublicKey(public_key: NodeJS.ArrayBufferView): void; setPublicKey(public_key: string, encoding: BufferEncoding): void; setPrivateKey(private_key: NodeJS.ArrayBufferView): void; setPrivateKey(private_key: string, encoding: BufferEncoding): void; verifyError: number; } function getDiffieHellman(group_name: string): DiffieHellman; function pbkdf2( password: BinaryLike, salt: BinaryLike, iterations: number, keylen: number, digest: string, callback: (err: Error | null, derivedKey: Buffer) => any, ): void; function pbkdf2Sync(password: BinaryLike, salt: BinaryLike, iterations: number, keylen: number, digest: string): Buffer; function randomBytes(size: number): Buffer; function randomBytes(size: number, callback: (err: Error | null, buf: Buffer) => void): void; function pseudoRandomBytes(size: number): Buffer; function pseudoRandomBytes(size: number, callback: (err: Error | null, buf: Buffer) => void): void; function randomFillSync<T extends NodeJS.ArrayBufferView>(buffer: T, offset?: number, size?: number): T; function randomFill<T extends NodeJS.ArrayBufferView>(buffer: T, callback: (err: Error | null, buf: T) => void): void; function randomFill<T extends NodeJS.ArrayBufferView>(buffer: T, offset: number, callback: (err: Error | null, buf: T) => void): void; function randomFill<T extends NodeJS.ArrayBufferView>(buffer: T, offset: number, size: number, callback: (err: Error | null, buf: T) => void): void; interface ScryptOptions { N?: number; r?: number; p?: number; maxmem?: number; } function scrypt( password: BinaryLike, salt: BinaryLike, keylen: number, callback: (err: Error | null, derivedKey: Buffer) => void, ): void; function scrypt( password: BinaryLike, salt: BinaryLike, keylen: number, options: ScryptOptions, callback: (err: Error | null, derivedKey: Buffer) => void, ): void; function scryptSync(password: BinaryLike, salt: BinaryLike, keylen: number, options?: ScryptOptions): Buffer; interface RsaPublicKey { key: KeyLike; padding?: number; } interface RsaPrivateKey { key: KeyLike; passphrase?: string; /** * @default 'sha1' */ oaepHash?: string; oaepLabel?: NodeJS.TypedArray; padding?: number; } function publicEncrypt(key: RsaPublicKey | RsaPrivateKey | KeyLike, buffer: NodeJS.ArrayBufferView): Buffer; function publicDecrypt(key: RsaPublicKey | RsaPrivateKey | KeyLike, buffer: NodeJS.ArrayBufferView): Buffer; function privateDecrypt(private_key: RsaPrivateKey | KeyLike, buffer: NodeJS.ArrayBufferView): Buffer; function privateEncrypt(private_key: RsaPrivateKey | KeyLike, buffer: NodeJS.ArrayBufferView): Buffer; function getCiphers(): string[]; function getCurves(): string[]; function getHashes(): string[]; class ECDH { private constructor(); static convertKey( key: BinaryLike, curve: string, inputEncoding?: HexBase64Latin1Encoding, outputEncoding?: "latin1" | "hex" | "base64", format?: "uncompressed" | "compressed" | "hybrid", ): Buffer | string; generateKeys(): Buffer; generateKeys(encoding: HexBase64Latin1Encoding, format?: ECDHKeyFormat): string; computeSecret(other_public_key: NodeJS.ArrayBufferView): Buffer; computeSecret(other_public_key: string, input_encoding: HexBase64Latin1Encoding): Buffer; computeSecret(other_public_key: NodeJS.ArrayBufferView, output_encoding: HexBase64Latin1Encoding): string; computeSecret(other_public_key: string, input_encoding: HexBase64Latin1Encoding, output_encoding: HexBase64Latin1Encoding): string; getPrivateKey(): Buffer; getPrivateKey(encoding: HexBase64Latin1Encoding): string; getPublicKey(): Buffer; getPublicKey(encoding: HexBase64Latin1Encoding, format?: ECDHKeyFormat): string; setPrivateKey(private_key: NodeJS.ArrayBufferView): void; setPrivateKey(private_key: string, encoding: HexBase64Latin1Encoding): void; } function createECDH(curve_name: string): ECDH; function timingSafeEqual(a: NodeJS.ArrayBufferView, b: NodeJS.ArrayBufferView): boolean; /** @deprecated since v10.0.0 */ const DEFAULT_ENCODING: BufferEncoding; type KeyType = 'rsa' | 'dsa' | 'ec'; type KeyFormat = 'pem' | 'der'; interface BasePrivateKeyEncodingOptions<T extends KeyFormat> { format: T; cipher?: string; passphrase?: string; } interface KeyPairKeyObjectResult { publicKey: KeyObject; privateKey: KeyObject; } interface ECKeyPairKeyObjectOptions { /** * Name of the curve to use. */ namedCurve: string; } interface RSAKeyPairKeyObjectOptions { /** * Key size in bits */ modulusLength: number; /** * @default 0x10001 */ publicExponent?: number; } interface DSAKeyPairKeyObjectOptions { /** * Key size in bits */ modulusLength: number; /** * Size of q in bits */ divisorLength: number; } interface RSAKeyPairOptions<PubF extends KeyFormat, PrivF extends KeyFormat> { /** * Key size in bits */ modulusLength: number; /** * @default 0x10001 */ publicExponent?: number; publicKeyEncoding: { type: 'pkcs1' | 'spki'; format: PubF; }; privateKeyEncoding: BasePrivateKeyEncodingOptions<PrivF> & { type: 'pkcs1' | 'pkcs8'; }; } interface DSAKeyPairOptions<PubF extends KeyFormat, PrivF extends KeyFormat> { /** * Key size in bits */ modulusLength: number; /** * Size of q in bits */ divisorLength: number; publicKeyEncoding: { type: 'spki'; format: PubF; }; privateKeyEncoding: BasePrivateKeyEncodingOptions<PrivF> & { type: 'pkcs8'; }; } interface ECKeyPairOptions<PubF extends KeyFormat, PrivF extends KeyFormat> { /** * Name of the curve to use. */ namedCurve: string; publicKeyEncoding: { type: 'pkcs1' | 'spki'; format: PubF; }; privateKeyEncoding: BasePrivateKeyEncodingOptions<PrivF> & { type: 'sec1' | 'pkcs8'; }; } interface KeyPairSyncResult<T1 extends string | Buffer, T2 extends string | Buffer> { publicKey: T1; privateKey: T2; } function generateKeyPairSync(type: 'rsa', options: RSAKeyPairOptions<'pem', 'pem'>): KeyPairSyncResult<string, string>; function generateKeyPairSync(type: 'rsa', options: RSAKeyPairOptions<'pem', 'der'>): KeyPairSyncResult<string, Buffer>; function generateKeyPairSync(type: 'rsa', options: RSAKeyPairOptions<'der', 'pem'>): KeyPairSyncResult<Buffer, string>; function generateKeyPairSync(type: 'rsa', options: RSAKeyPairOptions<'der', 'der'>): KeyPairSyncResult<Buffer, Buffer>; function generateKeyPairSync(type: 'rsa', options: RSAKeyPairKeyObjectOptions): KeyPairKeyObjectResult; function generateKeyPairSync(type: 'dsa', options: DSAKeyPairOptions<'pem', 'pem'>): KeyPairSyncResult<string, string>; function generateKeyPairSync(type: 'dsa', options: DSAKeyPairOptions<'pem', 'der'>): KeyPairSyncResult<string, Buffer>; function generateKeyPairSync(type: 'dsa', options: DSAKeyPairOptions<'der', 'pem'>): KeyPairSyncResult<Buffer, string>; function generateKeyPairSync(type: 'dsa', options: DSAKeyPairOptions<'der', 'der'>): KeyPairSyncResult<Buffer, Buffer>; function generateKeyPairSync(type: 'dsa', options: DSAKeyPairKeyObjectOptions): KeyPairKeyObjectResult; function generateKeyPairSync(type: 'ec', options: ECKeyPairOptions<'pem', 'pem'>): KeyPairSyncResult<string, string>; function generateKeyPairSync(type: 'ec', options: ECKeyPairOptions<'pem', 'der'>): KeyPairSyncResult<string, Buffer>; function generateKeyPairSync(type: 'ec', options: ECKeyPairOptions<'der', 'pem'>): KeyPairSyncResult<Buffer, string>; function generateKeyPairSync(type: 'ec', options: ECKeyPairOptions<'der', 'der'>): KeyPairSyncResult<Buffer, Buffer>; function generateKeyPairSync(type: 'ec', options: ECKeyPairKeyObjectOptions): KeyPairKeyObjectResult; function generateKeyPair(type: 'rsa', options: RSAKeyPairOptions<'pem', 'pem'>, callback: (err: Error | null, publicKey: string, privateKey: string) => void): void; function generateKeyPair(type: 'rsa', options: RSAKeyPairOptions<'pem', 'der'>, callback: (err: Error | null, publicKey: string, privateKey: Buffer) => void): void; function generateKeyPair(type: 'rsa', options: RSAKeyPairOptions<'der', 'pem'>, callback: (err: Error | null, publicKey: Buffer, privateKey: string) => void): void; function generateKeyPair(type: 'rsa', options: RSAKeyPairOptions<'der', 'der'>, callback: (err: Error | null, publicKey: Buffer, privateKey: Buffer) => void): void; function generateKeyPair(type: 'rsa', options: RSAKeyPairKeyObjectOptions, callback: (err: Error | null, publicKey: KeyObject, privateKey: KeyObject) => void): void; function generateKeyPair(type: 'dsa', options: DSAKeyPairOptions<'pem', 'pem'>, callback: (err: Error | null, publicKey: string, privateKey: string) => void): void; function generateKeyPair(type: 'dsa', options: DSAKeyPairOptions<'pem', 'der'>, callback: (err: Error | null, publicKey: string, privateKey: Buffer) => void): void; function generateKeyPair(type: 'dsa', options: DSAKeyPairOptions<'der', 'pem'>, callback: (err: Error | null, publicKey: Buffer, privateKey: string) => void): void; function generateKeyPair(type: 'dsa', options: DSAKeyPairOptions<'der', 'der'>, callback: (err: Error | null, publicKey: Buffer, privateKey: Buffer) => void): void; function generateKeyPair(type: 'dsa', options: DSAKeyPairKeyObjectOptions, callback: (err: Error | null, publicKey: KeyObject, privateKey: KeyObject) => void): void; function generateKeyPair(type: 'ec', options: ECKeyPairOptions<'pem', 'pem'>, callback: (err: Error | null, publicKey: string, privateKey: string) => void): void; function generateKeyPair(type: 'ec', options: ECKeyPairOptions<'pem', 'der'>, callback: (err: Error | null, publicKey: string, privateKey: Buffer) => void): void; function generateKeyPair(type: 'ec', options: ECKeyPairOptions<'der', 'pem'>, callback: (err: Error | null, publicKey: Buffer, privateKey: string) => void): void; function generateKeyPair(type: 'ec', options: ECKeyPairOptions<'der', 'der'>, callback: (err: Error | null, publicKey: Buffer, privateKey: Buffer) => void): void; function generateKeyPair(type: 'ec', options: ECKeyPairKeyObjectOptions, callback: (err: Error | null, publicKey: KeyObject, privateKey: KeyObject) => void): void; namespace generateKeyPair { function __promisify__(type: "rsa", options: RSAKeyPairOptions<'pem', 'pem'>): Promise<{ publicKey: string, privateKey: string }>; function __promisify__(type: "rsa", options: RSAKeyPairOptions<'pem', 'der'>): Promise<{ publicKey: string, privateKey: Buffer }>; function __promisify__(type: "rsa", options: RSAKeyPairOptions<'der', 'pem'>): Promise<{ publicKey: Buffer, privateKey: string }>; function __promisify__(type: "rsa", options: RSAKeyPairOptions<'der', 'der'>): Promise<{ publicKey: Buffer, privateKey: Buffer }>; function __promisify__(type: "rsa", options: RSAKeyPairKeyObjectOptions): Promise<KeyPairKeyObjectResult>; function __promisify__(type: "dsa", options: DSAKeyPairOptions<'pem', 'pem'>): Promise<{ publicKey: string, privateKey: string }>; function __promisify__(type: "dsa", options: DSAKeyPairOptions<'pem', 'der'>): Promise<{ publicKey: string, privateKey: Buffer }>; function __promisify__(type: "dsa", options: DSAKeyPairOptions<'der', 'pem'>): Promise<{ publicKey: Buffer, privateKey: string }>; function __promisify__(type: "dsa", options: DSAKeyPairOptions<'der', 'der'>): Promise<{ publicKey: Buffer, privateKey: Buffer }>; function __promisify__(type: "dsa", options: DSAKeyPairKeyObjectOptions): Promise<KeyPairKeyObjectResult>; function __promisify__(type: "ec", options: ECKeyPairOptions<'pem', 'pem'>): Promise<{ publicKey: string, privateKey: string }>; function __promisify__(type: "ec", options: ECKeyPairOptions<'pem', 'der'>): Promise<{ publicKey: string, privateKey: Buffer }>; function __promisify__(type: "ec", options: ECKeyPairOptions<'der', 'pem'>): Promise<{ publicKey: Buffer, privateKey: string }>; function __promisify__(type: "ec", options: ECKeyPairOptions<'der', 'der'>): Promise<{ publicKey: Buffer, privateKey: Buffer }>; function __promisify__(type: "ec", options: ECKeyPairKeyObjectOptions): Promise<KeyPairKeyObjectResult>; } /** * Calculates and returns the signature for `data` using the given private key and * algorithm. If `algorithm` is `null` or `undefined`, then the algorithm is * dependent upon the key type (especially Ed25519 and Ed448). * * If `key` is not a [`KeyObject`][], this function behaves as if `key` had been * passed to [`crypto.createPrivateKey()`][]. */ function sign(algorithm: string | null | undefined, data: NodeJS.ArrayBufferView, key: KeyLike | SignPrivateKeyInput): Buffer; interface VerifyKeyWithOptions extends KeyObject, SigningOptions { } /** * Calculates and returns the signature for `data` using the given private key and * algorithm. If `algorithm` is `null` or `undefined`, then the algorithm is * dependent upon the key type (especially Ed25519 and Ed448). * * If `key` is not a [`KeyObject`][], this function behaves as if `key` had been * passed to [`crypto.createPublicKey()`][]. */ function verify(algorithm: string | null | undefined, data: NodeJS.ArrayBufferView, key: KeyLike | VerifyKeyWithOptions, signature: NodeJS.ArrayBufferView): boolean; }
{ "content_hash": "f61e3acdff2f8fdaa03b742691775011", "timestamp": "", "source": "github", "line_count": 615, "max_line_length": 176, "avg_line_length": 49.77235772357724, "alnum_prop": 0.6743547860176413, "repo_name": "henryhe1/henryhe1.github.io", "id": "3238dcab7adc2dd6b64875e06ca7e04f348a0f59", "size": "30610", "binary": false, "copies": "3", "ref": "refs/heads/master", "path": "node_modules/@types/node/crypto.d.ts", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "CSS", "bytes": "44557" }, { "name": "HTML", "bytes": "41077" }, { "name": "JavaScript", "bytes": "17363" } ], "symlink_target": "" }
// Copyright 2016 The Bazel Authors. All rights reserved. // // Licensed under the Apache License, Version 2.0 (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.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package com.google.devtools.build.lib.bazel.repository.skylark; import com.google.common.collect.ImmutableList; import com.google.devtools.build.lib.concurrent.ThreadSafety.Immutable; import com.google.devtools.build.lib.skylarkinterface.SkylarkCallable; import com.google.devtools.build.lib.skylarkinterface.SkylarkModule; import com.google.devtools.build.lib.vfs.Path; import java.io.IOException; import java.util.List; /** * A Path object to be used into Skylark remote repository. * * <p>This path object enable non-hermetic operations from Skylark and should not be returned by * something other than a SkylarkRepositoryContext. */ @Immutable @SkylarkModule(name = "path", doc = "A structure representing a file to be used inside a repository" ) final class SkylarkPath { final Path path; public SkylarkPath(Path path) { this.path = path; } public Path getPath() { return path; } @Override public boolean equals(Object obj) { return (obj instanceof SkylarkPath) && path.equals(((SkylarkPath) obj).path); } @Override public int hashCode() { return path.hashCode(); } @SkylarkCallable( name = "basename", structField = true, doc = "A string giving the basename of the file." ) public String getBasename() { return path.getBaseName(); } @SkylarkCallable( name = "readdir", structField = false, doc = "The list of entries in the directory denoted by this path." ) public List<SkylarkPath> readdir() throws IOException { ImmutableList.Builder<SkylarkPath> builder = ImmutableList.builder(); for (Path p : path.getDirectoryEntries()) { builder.add(new SkylarkPath(p)); } return builder.build(); } @SkylarkCallable( name = "dirname", structField = true, doc = "The parent directory of this file, or None if this file does not have a parent." ) public SkylarkPath getDirname() { Path parentPath = path.getParentDirectory(); return parentPath == null ? null : new SkylarkPath(parentPath); } @SkylarkCallable( name = "get_child", doc = "Append the given path to this path and return the resulted path." ) public SkylarkPath getChild(String childPath) { return new SkylarkPath(path.getChild(childPath)); } @SkylarkCallable( name = "exists", structField = true, doc = "Returns true if the file denoted by this path exists." ) public boolean exists() { return path.exists(); } @Override public String toString() { return path.toString(); } }
{ "content_hash": "f04ea32add28f0601d2578a418aef35a", "timestamp": "", "source": "github", "line_count": 109, "max_line_length": 100, "avg_line_length": 29, "alnum_prop": 0.7095855741853844, "repo_name": "whuwxl/bazel", "id": "328fa74e94f062485315f14cfe3a55c33bf80488", "size": "3161", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "src/main/java/com/google/devtools/build/lib/bazel/repository/skylark/SkylarkPath.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "C", "bytes": "46850" }, { "name": "C++", "bytes": "285741" }, { "name": "HTML", "bytes": "16217" }, { "name": "Java", "bytes": "15326662" }, { "name": "Objective-C", "bytes": "5306" }, { "name": "Protocol Buffer", "bytes": "76315" }, { "name": "Python", "bytes": "220690" }, { "name": "Shell", "bytes": "417468" } ], "symlink_target": "" }
<?xml version="1.0" encoding="utf-8"?> <shape xmlns:android="http://schemas.android.com/apk/res/android" android:shape="rectangle" > <corners android:radius="5px" /> <solid android:color="@color/button_color_press" /> </shape>
{ "content_hash": "c021fe064b579e426c0943acf39c9ce1", "timestamp": "", "source": "github", "line_count": 10, "max_line_length": 65, "avg_line_length": 24.2, "alnum_prop": 0.6694214876033058, "repo_name": "HussainDerry/quick-notes", "id": "259884e6f6d7e8d448d198726ef5e96d561aacbe", "size": "242", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "app/src/main/res/drawable/btn_custom_pressed.xml", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Java", "bytes": "55860" } ], "symlink_target": "" }
package guest import ( "flag" "io" "context" "os" "github.com/vmware/govmomi/govc/cli" "github.com/vmware/govmomi/vim25/soap" ) type download struct { *GuestFlag overwrite bool } func init() { cli.Register("guest.download", &download{}) } func (cmd *download) Register(ctx context.Context, f *flag.FlagSet) { cmd.GuestFlag, ctx = newGuestFlag(ctx) cmd.GuestFlag.Register(ctx, f) f.BoolVar(&cmd.overwrite, "f", false, "If set, the local destination file is clobbered") } func (cmd *download) Usage() string { return "SOURCE DEST" } func (cmd *download) Description() string { return `Copy SOURCE from the guest VM to DEST on the local system. If DEST name is "-", source is written to stdout. ` } func (cmd *download) Process(ctx context.Context) error { if err := cmd.GuestFlag.Process(ctx); err != nil { return err } return nil } func (cmd *download) Run(ctx context.Context, f *flag.FlagSet) error { if f.NArg() != 2 { return flag.ErrHelp } m, err := cmd.FileManager() if err != nil { return err } src := f.Arg(0) dst := f.Arg(1) _, err = os.Stat(dst) if err == nil && !cmd.overwrite { return os.ErrExist } info, err := m.InitiateFileTransferFromGuest(ctx, cmd.Auth(), src) if err != nil { return err } u, err := cmd.ParseURL(info.Url) if err != nil { return err } c, err := cmd.Client() if err != nil { return nil } p := soap.DefaultDownload if dst == "-" { f, _, err := c.Client.Download(u, &p) if err != nil { return err } _, err = io.Copy(os.Stdout, f) return err } if cmd.OutputFlag.TTY { logger := cmd.ProgressLogger("Downloading... ") p.Progress = logger defer logger.Wait() } return c.Client.DownloadFile(dst, u, &p) }
{ "content_hash": "678c0468a9a491b359091e7edaa87d53", "timestamp": "", "source": "github", "line_count": 102, "max_line_length": 89, "avg_line_length": 16.95098039215686, "alnum_prop": 0.6443030653556969, "repo_name": "frapposelli/govmomi", "id": "516603df1a0cdb50be5f8327f7098283bafaa3de", "size": "2317", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "govc/vm/guest/download.go", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Emacs Lisp", "bytes": "55523" }, { "name": "Go", "bytes": "3444887" }, { "name": "Makefile", "bytes": "831" }, { "name": "Ruby", "bytes": "25147" }, { "name": "Shell", "bytes": "81435" } ], "symlink_target": "" }
namespace g{ namespace Android{ namespace Base{ namespace Primitives{ // public extern struct ujbyte :1978 // { uStructType* ujbyte_typeof(); struct ujbyte { }; // } }}}} // ::g::Android::Base::Primitives
{ "content_hash": "f5bff28961950894447d2f7c4cc5477d", "timestamp": "", "source": "github", "line_count": 15, "max_line_length": 38, "avg_line_length": 13.866666666666667, "alnum_prop": 0.6875, "repo_name": "blyk/BlackCode-Fuse", "id": "5da4702b72f231a5927c2e2bec2db55c8dbaa75a", "size": "456", "binary": false, "copies": "6", "ref": "refs/heads/master", "path": "AddfromApp/.build/Simulator/Android/include/Android.Base.Primitives.ujbyte.h", "mode": "33188", "license": "mit", "language": [ { "name": "Batchfile", "bytes": "31111" }, { "name": "C", "bytes": "22885804" }, { "name": "C++", "bytes": "197750292" }, { "name": "Java", "bytes": "951083" }, { "name": "JavaScript", "bytes": "578555" }, { "name": "Logos", "bytes": "48297" }, { "name": "Makefile", "bytes": "6592573" }, { "name": "Shell", "bytes": "19985" } ], "symlink_target": "" }
using System.Runtime.InteropServices; namespace System { [Flags] // [ComVisible (false)] public enum StringSplitOptions { None = 0, RemoveEmptyEntries = 1 } }
{ "content_hash": "4837191e502976b69578702bb0460080", "timestamp": "", "source": "github", "line_count": 12, "max_line_length": 37, "avg_line_length": 14.083333333333334, "alnum_prop": 0.7100591715976331, "repo_name": "ncave/dotnet-js", "id": "98f2b88be93757332b0c5d37cfa94f9633ce37cf", "size": "1350", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/DNA/corlib/System/StringSplitOptions.cs", "mode": "33188", "license": "mit", "language": [ { "name": "Batchfile", "bytes": "1329" }, { "name": "C", "bytes": "577162" }, { "name": "C#", "bytes": "887687" }, { "name": "C++", "bytes": "109430" }, { "name": "CMake", "bytes": "1266" }, { "name": "F#", "bytes": "2327493" }, { "name": "HTML", "bytes": "211" }, { "name": "JavaScript", "bytes": "873954" }, { "name": "Objective-C", "bytes": "69891" }, { "name": "QMake", "bytes": "2759" }, { "name": "TypeScript", "bytes": "6398" } ], "symlink_target": "" }
/** * @author mrdoob / http://mrdoob.com/ */ import { BufferAttribute, BufferGeometry, InterleavedBuffer, InterleavedBufferAttribute, Vector2, Vector3 } from "../../../build/three.module.js"; var BufferGeometryUtils = { computeTangents: function ( geometry ) { var index = geometry.index; var attributes = geometry.attributes; // based on http://www.terathon.com/code/tangent.html // (per vertex tangents) if ( index === null || attributes.position === undefined || attributes.normal === undefined || attributes.uv === undefined ) { console.warn( 'THREE.BufferGeometry: Missing required attributes (index, position, normal or uv) in BufferGeometry.computeTangents()' ); return; } var indices = index.array; var positions = attributes.position.array; var normals = attributes.normal.array; var uvs = attributes.uv.array; var nVertices = positions.length / 3; if ( attributes.tangent === undefined ) { geometry.addAttribute( 'tangent', new BufferAttribute( new Float32Array( 4 * nVertices ), 4 ) ); } var tangents = attributes.tangent.array; var tan1 = [], tan2 = []; for ( var i = 0; i < nVertices; i ++ ) { tan1[ i ] = new Vector3(); tan2[ i ] = new Vector3(); } var vA = new Vector3(), vB = new Vector3(), vC = new Vector3(), uvA = new Vector2(), uvB = new Vector2(), uvC = new Vector2(), sdir = new Vector3(), tdir = new Vector3(); function handleTriangle( a, b, c ) { vA.fromArray( positions, a * 3 ); vB.fromArray( positions, b * 3 ); vC.fromArray( positions, c * 3 ); uvA.fromArray( uvs, a * 2 ); uvB.fromArray( uvs, b * 2 ); uvC.fromArray( uvs, c * 2 ); var x1 = vB.x - vA.x; var x2 = vC.x - vA.x; var y1 = vB.y - vA.y; var y2 = vC.y - vA.y; var z1 = vB.z - vA.z; var z2 = vC.z - vA.z; var s1 = uvB.x - uvA.x; var s2 = uvC.x - uvA.x; var t1 = uvB.y - uvA.y; var t2 = uvC.y - uvA.y; var r = 1.0 / ( s1 * t2 - s2 * t1 ); sdir.set( ( t2 * x1 - t1 * x2 ) * r, ( t2 * y1 - t1 * y2 ) * r, ( t2 * z1 - t1 * z2 ) * r ); tdir.set( ( s1 * x2 - s2 * x1 ) * r, ( s1 * y2 - s2 * y1 ) * r, ( s1 * z2 - s2 * z1 ) * r ); tan1[ a ].add( sdir ); tan1[ b ].add( sdir ); tan1[ c ].add( sdir ); tan2[ a ].add( tdir ); tan2[ b ].add( tdir ); tan2[ c ].add( tdir ); } var groups = geometry.groups; if ( groups.length === 0 ) { groups = [ { start: 0, count: indices.length } ]; } for ( var i = 0, il = groups.length; i < il; ++ i ) { var group = groups[ i ]; var start = group.start; var count = group.count; for ( var j = start, jl = start + count; j < jl; j += 3 ) { handleTriangle( indices[ j + 0 ], indices[ j + 1 ], indices[ j + 2 ] ); } } var tmp = new Vector3(), tmp2 = new Vector3(); var n = new Vector3(), n2 = new Vector3(); var w, t, test; function handleVertex( v ) { n.fromArray( normals, v * 3 ); n2.copy( n ); t = tan1[ v ]; // Gram-Schmidt orthogonalize tmp.copy( t ); tmp.sub( n.multiplyScalar( n.dot( t ) ) ).normalize(); // Calculate handedness tmp2.crossVectors( n2, t ); test = tmp2.dot( tan2[ v ] ); w = ( test < 0.0 ) ? - 1.0 : 1.0; tangents[ v * 4 ] = tmp.x; tangents[ v * 4 + 1 ] = tmp.y; tangents[ v * 4 + 2 ] = tmp.z; tangents[ v * 4 + 3 ] = w; } for ( var i = 0, il = groups.length; i < il; ++ i ) { var group = groups[ i ]; var start = group.start; var count = group.count; for ( var j = start, jl = start + count; j < jl; j += 3 ) { handleVertex( indices[ j + 0 ] ); handleVertex( indices[ j + 1 ] ); handleVertex( indices[ j + 2 ] ); } } }, /** * @param {Array<BufferGeometry>} geometries * @param {Boolean} useGroups * @return {BufferGeometry} */ mergeBufferGeometries: function ( geometries, useGroups ) { var isIndexed = geometries[ 0 ].index !== null; var attributesUsed = new Set( Object.keys( geometries[ 0 ].attributes ) ); var morphAttributesUsed = new Set( Object.keys( geometries[ 0 ].morphAttributes ) ); var attributes = {}; var morphAttributes = {}; var mergedGeometry = new BufferGeometry(); var offset = 0; for ( var i = 0; i < geometries.length; ++ i ) { var geometry = geometries[ i ]; // ensure that all geometries are indexed, or none if ( isIndexed !== ( geometry.index !== null ) ) return null; // gather attributes, exit early if they're different for ( var name in geometry.attributes ) { if ( ! attributesUsed.has( name ) ) return null; if ( attributes[ name ] === undefined ) attributes[ name ] = []; attributes[ name ].push( geometry.attributes[ name ] ); } // gather morph attributes, exit early if they're different for ( var name in geometry.morphAttributes ) { if ( ! morphAttributesUsed.has( name ) ) return null; if ( morphAttributes[ name ] === undefined ) morphAttributes[ name ] = []; morphAttributes[ name ].push( geometry.morphAttributes[ name ] ); } // gather .userData mergedGeometry.userData.mergedUserData = mergedGeometry.userData.mergedUserData || []; mergedGeometry.userData.mergedUserData.push( geometry.userData ); if ( useGroups ) { var count; if ( isIndexed ) { count = geometry.index.count; } else if ( geometry.attributes.position !== undefined ) { count = geometry.attributes.position.count; } else { return null; } mergedGeometry.addGroup( offset, count, i ); offset += count; } } // merge indices if ( isIndexed ) { var indexOffset = 0; var mergedIndex = []; for ( var i = 0; i < geometries.length; ++ i ) { var index = geometries[ i ].index; for ( var j = 0; j < index.count; ++ j ) { mergedIndex.push( index.getX( j ) + indexOffset ); } indexOffset += geometries[ i ].attributes.position.count; } mergedGeometry.setIndex( mergedIndex ); } // merge attributes for ( var name in attributes ) { var mergedAttribute = this.mergeBufferAttributes( attributes[ name ] ); if ( ! mergedAttribute ) return null; mergedGeometry.addAttribute( name, mergedAttribute ); } // merge morph attributes for ( var name in morphAttributes ) { var numMorphTargets = morphAttributes[ name ][ 0 ].length; if ( numMorphTargets === 0 ) break; mergedGeometry.morphAttributes = mergedGeometry.morphAttributes || {}; mergedGeometry.morphAttributes[ name ] = []; for ( var i = 0; i < numMorphTargets; ++ i ) { var morphAttributesToMerge = []; for ( var j = 0; j < morphAttributes[ name ].length; ++ j ) { morphAttributesToMerge.push( morphAttributes[ name ][ j ][ i ] ); } var mergedMorphAttribute = this.mergeBufferAttributes( morphAttributesToMerge ); if ( ! mergedMorphAttribute ) return null; mergedGeometry.morphAttributes[ name ].push( mergedMorphAttribute ); } } return mergedGeometry; }, /** * @param {Array<BufferAttribute>} attributes * @return {BufferAttribute} */ mergeBufferAttributes: function ( attributes ) { var TypedArray; var itemSize; var normalized; var arrayLength = 0; for ( var i = 0; i < attributes.length; ++ i ) { var attribute = attributes[ i ]; if ( attribute.isInterleavedBufferAttribute ) return null; if ( TypedArray === undefined ) TypedArray = attribute.array.constructor; if ( TypedArray !== attribute.array.constructor ) return null; if ( itemSize === undefined ) itemSize = attribute.itemSize; if ( itemSize !== attribute.itemSize ) return null; if ( normalized === undefined ) normalized = attribute.normalized; if ( normalized !== attribute.normalized ) return null; arrayLength += attribute.array.length; } var array = new TypedArray( arrayLength ); var offset = 0; for ( var i = 0; i < attributes.length; ++ i ) { array.set( attributes[ i ].array, offset ); offset += attributes[ i ].array.length; } return new BufferAttribute( array, itemSize, normalized ); }, /** * @param {Array<BufferAttribute>} attributes * @return {Array<InterleavedBufferAttribute>} */ interleaveAttributes: function ( attributes ) { // Interleaves the provided attributes into an InterleavedBuffer and returns // a set of InterleavedBufferAttributes for each attribute var TypedArray; var arrayLength = 0; var stride = 0; // calculate the the length and type of the interleavedBuffer for ( var i = 0, l = attributes.length; i < l; ++ i ) { var attribute = attributes[ i ]; if ( TypedArray === undefined ) TypedArray = attribute.array.constructor; if ( TypedArray !== attribute.array.constructor ) { console.warn( 'AttributeBuffers of different types cannot be interleaved' ); return null; } arrayLength += attribute.array.length; stride += attribute.itemSize; } // Create the set of buffer attributes var interleavedBuffer = new InterleavedBuffer( new TypedArray( arrayLength ), stride ); var offset = 0; var res = []; var getters = [ 'getX', 'getY', 'getZ', 'getW' ]; var setters = [ 'setX', 'setY', 'setZ', 'setW' ]; for ( var j = 0, l = attributes.length; j < l; j ++ ) { var attribute = attributes[ j ]; var itemSize = attribute.itemSize; var count = attribute.count; var iba = new InterleavedBufferAttribute( interleavedBuffer, itemSize, offset, attribute.normalized ); res.push( iba ); offset += itemSize; // Move the data for each attribute into the new interleavedBuffer // at the appropriate offset for ( var c = 0; c < count; c ++ ) { for ( var k = 0; k < itemSize; k ++ ) { iba[ setters[ k ] ]( c, attribute[ getters[ k ] ]( c ) ); } } } return res; }, /** * @param {Array<BufferGeometry>} geometry * @return {number} */ estimateBytesUsed: function ( geometry ) { // Return the estimated memory used by this geometry in bytes // Calculate using itemSize, count, and BYTES_PER_ELEMENT to account // for InterleavedBufferAttributes. var mem = 0; for ( var name in geometry.attributes ) { var attr = geometry.getAttribute( name ); mem += attr.count * attr.itemSize * attr.array.BYTES_PER_ELEMENT; } var indices = geometry.getIndex(); mem += indices ? indices.count * indices.itemSize * indices.array.BYTES_PER_ELEMENT : 0; return mem; }, /** * @param {BufferGeometry} geometry * @param {number} tolerance * @return {BufferGeometry>} */ mergeVertices: function ( geometry, tolerance = 1e-4 ) { tolerance = Math.max( tolerance, Number.EPSILON ); // Generate an index buffer if the geometry doesn't have one, or optimize it // if it's already available. var hashToIndex = {}; var indices = geometry.getIndex(); var positions = geometry.getAttribute( 'position' ); var vertexCount = indices ? indices.count : positions.count; // next value for triangle indices var nextIndex = 0; // attributes and new attribute arrays var attributeNames = Object.keys( geometry.attributes ); var attrArrays = {}; var morphAttrsArrays = {}; var newIndices = []; var getters = [ 'getX', 'getY', 'getZ', 'getW' ]; // initialize the arrays for ( var i = 0, l = attributeNames.length; i < l; i ++ ) { var name = attributeNames[ i ]; attrArrays[ name ] = []; var morphAttr = geometry.morphAttributes[ name ]; if ( morphAttr ) { morphAttrsArrays[ name ] = new Array( morphAttr.length ).fill().map( () => [] ); } } // convert the error tolerance to an amount of decimal places to truncate to var decimalShift = Math.log10( 1 / tolerance ); var shiftMultiplier = Math.pow( 10, decimalShift ); for ( var i = 0; i < vertexCount; i ++ ) { var index = indices ? indices.getX( i ) : i; // Generate a hash for the vertex attributes at the current index 'i' var hash = ''; for ( var j = 0, l = attributeNames.length; j < l; j ++ ) { var name = attributeNames[ j ]; var attribute = geometry.getAttribute( name ); var itemSize = attribute.itemSize; for ( var k = 0; k < itemSize; k ++ ) { // double tilde truncates the decimal value hash += `${ ~ ~ ( attribute[ getters[ k ] ]( index ) * shiftMultiplier ) },`; } } // Add another reference to the vertex if it's already // used by another index if ( hash in hashToIndex ) { newIndices.push( hashToIndex[ hash ] ); } else { // copy data to the new index in the attribute arrays for ( var j = 0, l = attributeNames.length; j < l; j ++ ) { var name = attributeNames[ j ]; var attribute = geometry.getAttribute( name ); var morphAttr = geometry.morphAttributes[ name ]; var itemSize = attribute.itemSize; var newarray = attrArrays[ name ]; var newMorphArrays = morphAttrsArrays[ name ]; for ( var k = 0; k < itemSize; k ++ ) { var getterFunc = getters[ k ]; newarray.push( attribute[ getterFunc ]( index ) ); if ( morphAttr ) { for ( var m = 0, ml = morphAttr.length; m < ml; m ++ ) { newMorphArrays[ m ].push( morphAttr[ m ][ getterFunc ]( index ) ); } } } } hashToIndex[ hash ] = nextIndex; newIndices.push( nextIndex ); nextIndex ++; } } // Generate typed arrays from new attribute arrays and update // the attributeBuffers const result = geometry.clone(); for ( var i = 0, l = attributeNames.length; i < l; i ++ ) { var name = attributeNames[ i ]; var oldAttribute = geometry.getAttribute( name ); var attribute; var buffer = new oldAttribute.array.constructor( attrArrays[ name ] ); if ( oldAttribute.isInterleavedBufferAttribute ) { attribute = new BufferAttribute( buffer, oldAttribute.itemSize, oldAttribute.itemSize ); } else { attribute = geometry.getAttribute( name ).clone(); attribute.setArray( buffer ); } result.addAttribute( name, attribute ); // Update the attribute arrays if ( name in morphAttrsArrays ) { for ( var j = 0; j < morphAttrsArrays[ name ].length; j ++ ) { var morphAttribute = geometry.morphAttributes[ name ][ j ].clone(); morphAttribute.setArray( new morphAttribute.array.constructor( morphAttrsArrays[ name ][ j ] ) ); result.morphAttributes[ name ][ j ] = morphAttribute; } } } // Generate an index buffer typed array var cons = Uint8Array; if ( newIndices.length >= Math.pow( 2, 8 ) ) cons = Uint16Array; if ( newIndices.length >= Math.pow( 2, 16 ) ) cons = Uint32Array; var newIndexBuffer = new cons( newIndices ); var newIndices = null; if ( indices === null ) { newIndices = new BufferAttribute( newIndexBuffer, 1 ); } else { newIndices = geometry.getIndex().clone(); newIndices.setArray( newIndexBuffer ); } result.setIndex( newIndices ); return result; } }; export { BufferGeometryUtils };
{ "content_hash": "4ac62786f5812daa067835dddea7900e", "timestamp": "", "source": "github", "line_count": 658, "max_line_length": 139, "avg_line_length": 22.814589665653497, "alnum_prop": 0.6176392219557687, "repo_name": "skycolor/study", "id": "3b3d8f954f8da6fa8f3a0e229010f737b0ef639f", "size": "15012", "binary": false, "copies": "6", "ref": "refs/heads/master", "path": "frontWeb/three/official/examples/jsm/utils/BufferGeometryUtils.js", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "87749" }, { "name": "G-code", "bytes": "1940664" }, { "name": "GLSL", "bytes": "3228" }, { "name": "HTML", "bytes": "2524224" }, { "name": "Java", "bytes": "36690" }, { "name": "JavaScript", "bytes": "21773716" }, { "name": "Vue", "bytes": "82873" } ], "symlink_target": "" }
import React from 'react'; import { Heading, HeadingCaption } from 'cf-component-heading'; const HeadingComponent = () => ( <Heading size={2}> Look at this nice heading! <HeadingCaption> It even has a nice HeadingCaption </HeadingCaption> </Heading> ); export default HeadingComponent;
{ "content_hash": "c96a98beb0b30e2926863118552c992f", "timestamp": "", "source": "github", "line_count": 13, "max_line_length": 63, "avg_line_length": 23.846153846153847, "alnum_prop": 0.6935483870967742, "repo_name": "koddsson/cf-ui", "id": "3ee08f0f90a3c8885ca476f10d6ecf39214ae4b2", "size": "310", "binary": false, "copies": "4", "ref": "refs/heads/master", "path": "packages/cf-component-heading/example/basic/component.js", "mode": "33188", "license": "bsd-3-clause", "language": [ { "name": "HTML", "bytes": "252" }, { "name": "JavaScript", "bytes": "310503" }, { "name": "Shell", "bytes": "625" } ], "symlink_target": "" }
* fib.c: Contains fib function's code * fib.h: Contains decleration of fib function * fib_test.c: fib function test program * runtest: Bash script for compiling and runing test ## Runing test You need to have gcc compiler and bash interpreter installed on your machine in order to run the test. For running the test you have to execute ./runtest script from your command line: ```Bash $ ./runtest 30 ``` The optional argument to ./runtest determines the nth fibonacci number to find (The default is: 30) The output shows the algorithm's execution time in seconds.
{ "content_hash": "ec686572d3425be7cd79b785dfbf6dd3", "timestamp": "", "source": "github", "line_count": 15, "max_line_length": 102, "avg_line_length": 38.93333333333333, "alnum_prop": 0.7448630136986302, "repo_name": "mahdavipanah/AlgorithmDesign", "id": "20dac46b24910a7719a909762c994b58bcb300bd", "size": "740", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "Fibonacci/DivideAndConquer/C/README.md", "mode": "33188", "license": "mit", "language": [ { "name": "C", "bytes": "16961" }, { "name": "Go", "bytes": "10399" }, { "name": "Shell", "bytes": "797" } ], "symlink_target": "" }
import datetime from south.db import db from south.v2 import SchemaMigration from django.db import models class Migration(SchemaMigration): def forwards(self, orm): # Adding field 'Stream.running' db.add_column(u'twitter_stream', 'running', self.gf('django.db.models.fields.BooleanField')(default=False), keep_default=False) def backwards(self, orm): # Deleting field 'Stream.running' db.delete_column(u'twitter_stream', 'running') models = { u'twitter.followedlocation': { 'Meta': {'object_name': 'FollowedLocation'}, 'bounding_box': ('django.db.models.fields.CharField', [], {'max_length': '1000'}), u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'stream': ('django.db.models.fields.related.ForeignKey', [], {'related_name': "'followed_locations'", 'to': u"orm['twitter.Stream']"}) }, u'twitter.followeduser': { 'Meta': {'object_name': 'FollowedUser'}, u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'stream': ('django.db.models.fields.related.ForeignKey', [], {'related_name': "'followed_users'", 'to': u"orm['twitter.Stream']"}), 'user_id': ('django.db.models.fields.CharField', [], {'max_length': '500', 'null': 'True'}), 'username': ('django.db.models.fields.CharField', [], {'max_length': '500'}) }, u'twitter.stream': { 'Meta': {'object_name': 'Stream'}, u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'name': ('django.db.models.fields.CharField', [], {'max_length': '255'}), 'running': ('django.db.models.fields.BooleanField', [], {'default': 'False'}), 'slug': ('autoslug.fields.AutoSlugField', [], {'unique_with': '()', 'max_length': '50', 'populate_from': "'name'"}) }, u'twitter.trackedterm': { 'Meta': {'object_name': 'TrackedTerm'}, u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'phrase': ('django.db.models.fields.CharField', [], {'max_length': '60'}), 'stream': ('django.db.models.fields.related.ForeignKey', [], {'related_name': "'tracked_terms'", 'to': u"orm['twitter.Stream']"}) }, u'twitter.tweet': { 'Meta': {'object_name': 'Tweet'}, 'coordinates': ('jsonfield.fields.JSONField', [], {'null': 'True'}), 'created_at': ('django.db.models.fields.DateTimeField', [], {}), 'entities': ('jsonfield.fields.JSONField', [], {}), 'favorite_count': ('django.db.models.fields.IntegerField', [], {'default': '0', 'null': 'True'}), 'id': ('django.db.models.fields.CharField', [], {'max_length': '255', 'primary_key': 'True'}), 'in_reply_to_screen_name': ('django.db.models.fields.CharField', [], {'default': "''", 'max_length': '255', 'null': 'True'}), 'in_reply_to_status_id': ('django.db.models.fields.CharField', [], {'default': "''", 'max_length': '255', 'null': 'True'}), 'in_reply_to_user_id': ('django.db.models.fields.CharField', [], {'default': "''", 'max_length': '255', 'null': 'True'}), 'place': ('jsonfield.fields.JSONField', [], {'null': 'True'}), 'possibly_sensitive': ('django.db.models.fields.BooleanField', [], {'default': 'False'}), 'raw_data': ('jsonfield.fields.JSONField', [], {'default': '{}'}), 'retweet_count': ('django.db.models.fields.IntegerField', [], {'default': '0', 'null': 'True'}), 'stream': ('django.db.models.fields.related.ForeignKey', [], {'to': u"orm['twitter.Stream']"}), 'text': ('django.db.models.fields.CharField', [], {'max_length': '400'}), 'user': ('django.db.models.fields.related.ForeignKey', [], {'to': u"orm['twitter.TwitterUser']"}) }, u'twitter.twitteruser': { 'Meta': {'object_name': 'TwitterUser'}, 'description': ('django.db.models.fields.CharField', [], {'default': "''", 'max_length': '500'}), 'favourites_count': ('django.db.models.fields.IntegerField', [], {'default': '0'}), 'followers_count': ('django.db.models.fields.IntegerField', [], {'default': '0'}), 'friends_count': ('django.db.models.fields.IntegerField', [], {'default': '0'}), 'id': ('django.db.models.fields.CharField', [], {'max_length': '255', 'primary_key': 'True'}), 'name': ('django.db.models.fields.CharField', [], {'default': "''", 'max_length': '255'}), 'profile_image_url': ('django.db.models.fields.CharField', [], {'default': "''", 'max_length': '1000'}), 'raw_data': ('jsonfield.fields.JSONField', [], {'default': '{}'}), 'screen_name': ('django.db.models.fields.CharField', [], {'default': "''", 'max_length': '100'}), 'verified': ('django.db.models.fields.BooleanField', [], {'default': 'False'}) } } complete_apps = ['twitter']
{ "content_hash": "ee019928cdcc5885b56a84c57ef50ce8", "timestamp": "", "source": "github", "line_count": 81, "max_line_length": 146, "avg_line_length": 63.28395061728395, "alnum_prop": 0.5446742099102614, "repo_name": "chalkchisel/django-social-stream", "id": "44efd4696f7af4a64849bdc8d0c1e2996c8c4c3e", "size": "5150", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "social_stream/twitter/migrations/0003_auto__add_field_stream_running.py", "mode": "33188", "license": "mit", "language": [ { "name": "Python", "bytes": "99116" } ], "symlink_target": "" }
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <!-- NewPage --> <html lang="en"> <head> <!-- Generated by javadoc (version 1.7.0-google-v6) on Sat Nov 22 14:21:57 GMT 2014 --> <title>NotCapException (CAP Library)</title> <meta name="date" content="2014-11-22"> <link rel="stylesheet" type="text/css" href="../../../../stylesheet.css" title="Style"> </head> <body> <script type="text/javascript"><!-- if (location.href.indexOf('is-external=true') == -1) { parent.document.title="NotCapException (CAP Library)"; } //--> </script> <noscript> <div>JavaScript is disabled on your browser.</div> </noscript> <!-- ========= START OF TOP NAVBAR ======= --> <div class="topNav"><a name="navbar_top"> <!-- --> </a><a href="#skip-navbar_top" title="Skip navigation links"></a><a name="navbar_top_firstrow"> <!-- --> </a> <ul class="navList" title="Navigation"> <li><a href="../../../../overview-summary.html">Overview</a></li> <li><a href="package-summary.html">Package</a></li> <li class="navBarCell1Rev">Class</li> <li><a href="class-use/NotCapException.html">Use</a></li> <li><a href="package-tree.html">Tree</a></li> <li><a href="../../../../deprecated-list.html">Deprecated</a></li> <li><a href="../../../../index-all.html">Index</a></li> <li><a href="../../../../help-doc.html">Help</a></li> </ul> </div> <div class="subNav"> <ul class="navList"> <li><a href="../../../../com/google/publicalerts/cap/InfoOrBuilder.html" title="interface in com.google.publicalerts.cap"><span class="strong">Prev Class</span></a></li> <li><a href="../../../../com/google/publicalerts/cap/Point.html" title="class in com.google.publicalerts.cap"><span class="strong">Next Class</span></a></li> </ul> <ul class="navList"> <li><a href="../../../../index.html?com/google/publicalerts/cap/NotCapException.html" target="_top">Frames</a></li> <li><a href="NotCapException.html" target="_top">No Frames</a></li> </ul> <ul class="navList" id="allclasses_navbar_top"> <li><a href="../../../../allclasses-noframe.html">All Classes</a></li> </ul> <div> <script type="text/javascript"><!-- allClassesLink = document.getElementById("allclasses_navbar_top"); if(window==top) { allClassesLink.style.display = "block"; } else { allClassesLink.style.display = "none"; } //--> </script> </div> <div> <ul class="subNavList"> <li>Summary:&nbsp;</li> <li>Nested&nbsp;|&nbsp;</li> <li>Field&nbsp;|&nbsp;</li> <li><a href="#constructor_summary">Constr</a>&nbsp;|&nbsp;</li> <li><a href="#methods_inherited_from_class_java.lang.Throwable">Method</a></li> </ul> <ul class="subNavList"> <li>Detail:&nbsp;</li> <li>Field&nbsp;|&nbsp;</li> <li><a href="#constructor_detail">Constr</a>&nbsp;|&nbsp;</li> <li>Method</li> </ul> </div> <a name="skip-navbar_top"> <!-- --> </a></div> <!-- ========= END OF TOP NAVBAR ========= --> <!-- ======== START OF CLASS DATA ======== --> <div class="header"> <div class="subTitle">com.google.publicalerts.cap</div> <h2 title="Class NotCapException" class="title">Class NotCapException</h2> </div> <div class="contentContainer"> <ul class="inheritance"> <li>java.lang.Object</li> <li> <ul class="inheritance"> <li>java.lang.Throwable</li> <li> <ul class="inheritance"> <li>java.lang.Exception</li> <li> <ul class="inheritance"> <li>java.lang.RuntimeException</li> <li> <ul class="inheritance"> <li>com.google.publicalerts.cap.NotCapException</li> </ul> </li> </ul> </li> </ul> </li> </ul> </li> </ul> <div class="description"> <ul class="blockList"> <li class="blockList"> <dl> <dt>All Implemented Interfaces:</dt> <dd>java.io.Serializable</dd> </dl> <hr> <br> <pre>public class <span class="strong">NotCapException</span> extends java.lang.RuntimeException</pre> <div class="block">An exception for when data is not in the CAP format.</div> <dl><dt><span class="strong">See Also:</span></dt><dd><a href="../../../../serialized-form.html#com.google.publicalerts.cap.NotCapException">Serialized Form</a></dd></dl> </li> </ul> </div> <div class="summary"> <ul class="blockList"> <li class="blockList"> <!-- ======== CONSTRUCTOR SUMMARY ======== --> <ul class="blockList"> <li class="blockList"><a name="constructor_summary"> <!-- --> </a> <h3>Constructor Summary</h3> <table class="overviewSummary" border="0" cellpadding="3" cellspacing="0" summary="Constructor Summary table, listing constructors, and an explanation"> <caption><span>Constructors</span><span class="tabEnd">&nbsp;</span></caption> <tr> <th class="colOne" scope="col">Constructor and Description</th> </tr> <tr class="altColor"> <td class="colOne"><code><strong><a href="../../../../com/google/publicalerts/cap/NotCapException.html#NotCapException()">NotCapException</a></strong>()</code>&nbsp;</td> </tr> <tr class="rowColor"> <td class="colOne"><code><strong><a href="../../../../com/google/publicalerts/cap/NotCapException.html#NotCapException(java.lang.String)">NotCapException</a></strong>(java.lang.String&nbsp;message)</code>&nbsp;</td> </tr> <tr class="altColor"> <td class="colOne"><code><strong><a href="../../../../com/google/publicalerts/cap/NotCapException.html#NotCapException(java.lang.String,%20java.lang.Throwable)">NotCapException</a></strong>(java.lang.String&nbsp;message, java.lang.Throwable&nbsp;cause)</code>&nbsp;</td> </tr> </table> </li> </ul> <!-- ========== METHOD SUMMARY =========== --> <ul class="blockList"> <li class="blockList"><a name="method_summary"> <!-- --> </a> <h3>Method Summary</h3> <ul class="blockList"> <li class="blockList"><a name="methods_inherited_from_class_java.lang.Throwable"> <!-- --> </a> <h3>Methods inherited from class&nbsp;java.lang.Throwable</h3> <code>addSuppressed, fillInStackTrace, getCause, getLocalizedMessage, getMessage, getStackTrace, getSuppressed, initCause, printStackTrace, printStackTrace, printStackTrace, setStackTrace, toString</code></li> </ul> <ul class="blockList"> <li class="blockList"><a name="methods_inherited_from_class_java.lang.Object"> <!-- --> </a> <h3>Methods inherited from class&nbsp;java.lang.Object</h3> <code>clone, equals, finalize, getClass, hashCode, notify, notifyAll, wait, wait, wait</code></li> </ul> </li> </ul> </li> </ul> </div> <div class="details"> <ul class="blockList"> <li class="blockList"> <!-- ========= CONSTRUCTOR DETAIL ======== --> <ul class="blockList"> <li class="blockList"><a name="constructor_detail"> <!-- --> </a> <h3>Constructor Detail</h3> <a name="NotCapException()"> <!-- --> </a> <ul class="blockList"> <li class="blockList"> <h4>NotCapException</h4> <pre>public&nbsp;NotCapException()</pre> </li> </ul> <a name="NotCapException(java.lang.String)"> <!-- --> </a> <ul class="blockList"> <li class="blockList"> <h4>NotCapException</h4> <pre>public&nbsp;NotCapException(java.lang.String&nbsp;message)</pre> </li> </ul> <a name="NotCapException(java.lang.String, java.lang.Throwable)"> <!-- --> </a> <ul class="blockListLast"> <li class="blockList"> <h4>NotCapException</h4> <pre>public&nbsp;NotCapException(java.lang.String&nbsp;message, java.lang.Throwable&nbsp;cause)</pre> </li> </ul> </li> </ul> </li> </ul> </div> </div> <!-- ========= END OF CLASS DATA ========= --> <!-- ======= START OF BOTTOM NAVBAR ====== --> <div class="bottomNav"><a name="navbar_bottom"> <!-- --> </a><a href="#skip-navbar_bottom" title="Skip navigation links"></a><a name="navbar_bottom_firstrow"> <!-- --> </a> <ul class="navList" title="Navigation"> <li><a href="../../../../overview-summary.html">Overview</a></li> <li><a href="package-summary.html">Package</a></li> <li class="navBarCell1Rev">Class</li> <li><a href="class-use/NotCapException.html">Use</a></li> <li><a href="package-tree.html">Tree</a></li> <li><a href="../../../../deprecated-list.html">Deprecated</a></li> <li><a href="../../../../index-all.html">Index</a></li> <li><a href="../../../../help-doc.html">Help</a></li> </ul> </div> <div class="subNav"> <ul class="navList"> <li><a href="../../../../com/google/publicalerts/cap/InfoOrBuilder.html" title="interface in com.google.publicalerts.cap"><span class="strong">Prev Class</span></a></li> <li><a href="../../../../com/google/publicalerts/cap/Point.html" title="class in com.google.publicalerts.cap"><span class="strong">Next Class</span></a></li> </ul> <ul class="navList"> <li><a href="../../../../index.html?com/google/publicalerts/cap/NotCapException.html" target="_top">Frames</a></li> <li><a href="NotCapException.html" target="_top">No Frames</a></li> </ul> <ul class="navList" id="allclasses_navbar_bottom"> <li><a href="../../../../allclasses-noframe.html">All Classes</a></li> </ul> <div> <script type="text/javascript"><!-- allClassesLink = document.getElementById("allclasses_navbar_bottom"); if(window==top) { allClassesLink.style.display = "block"; } else { allClassesLink.style.display = "none"; } //--> </script> </div> <div> <ul class="subNavList"> <li>Summary:&nbsp;</li> <li>Nested&nbsp;|&nbsp;</li> <li>Field&nbsp;|&nbsp;</li> <li><a href="#constructor_summary">Constr</a>&nbsp;|&nbsp;</li> <li><a href="#methods_inherited_from_class_java.lang.Throwable">Method</a></li> </ul> <ul class="subNavList"> <li>Detail:&nbsp;</li> <li>Field&nbsp;|&nbsp;</li> <li><a href="#constructor_detail">Constr</a>&nbsp;|&nbsp;</li> <li>Method</li> </ul> </div> <a name="skip-navbar_bottom"> <!-- --> </a></div> <!-- ======== END OF BOTTOM NAVBAR ======= --> </body> </html>
{ "content_hash": "c10b7d5c460532085f54c6d2bd7f188d", "timestamp": "", "source": "github", "line_count": 282, "max_line_length": 220, "avg_line_length": 33.43262411347518, "alnum_prop": 0.6456300381841323, "repo_name": "google/cap-library", "id": "cbfb26db788abf2b218af4e5a7fa9ab03f4b4eb0", "size": "9428", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "java/docs/com/google/publicalerts/cap/NotCapException.html", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "CSS", "bytes": "2672" }, { "name": "HTML", "bytes": "4327692" }, { "name": "Java", "bytes": "596732" }, { "name": "JavaScript", "bytes": "4472" } ], "symlink_target": "" }
package com.frameworkset.platform.cms.documentmanager.bean; public class ToAuditDocument implements java.io.Serializable { private int docid; //待审核文档id private String docName; //待审核文档名称 private String submitTime; //文档提交时间 private int submitUserid; //呈送人id private String submitUserName; //呈送人姓名 private int docChannelid; //文档所处频道id private String docChannelName; //文档所处频道名 public int getDocChannelid() { return docChannelid; } public void setDocChannelid(int docChannelid) { this.docChannelid = docChannelid; } public String getDocChannelName() { return docChannelName; } public void setDocChannelName(String docChannelName) { this.docChannelName = docChannelName; } public int getDocid() { return docid; } public void setDocid(int docid) { this.docid = docid; } public String getDocName() { return docName; } public void setDocName(String docName) { this.docName = docName; } public String getSubmitTime() { return submitTime; } public void setSubmitTime(String submitTime) { this.submitTime = submitTime; } public int getSubmitUserid() { return submitUserid; } public void setSubmitUserid(int submitUserid) { this.submitUserid = submitUserid; } public String getSubmitUserName() { return submitUserName; } public void setSubmitUserName(String submitUserName) { this.submitUserName = submitUserName; } }
{ "content_hash": "782c126b3710c2e7872e1367ac60845d", "timestamp": "", "source": "github", "line_count": 54, "max_line_length": 62, "avg_line_length": 26.537037037037038, "alnum_prop": 0.7264480111653873, "repo_name": "tzou24/BPS", "id": "9547841e565eeadf2703052f1eb85054d6227695", "size": "1511", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "BPS/src/com/frameworkset/platform/cms/documentmanager/bean/ToAuditDocument.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "ASP", "bytes": "32778" }, { "name": "C#", "bytes": "16603" }, { "name": "CSS", "bytes": "1938634" }, { "name": "Groff", "bytes": "2353" }, { "name": "HTML", "bytes": "2622575" }, { "name": "Java", "bytes": "22195778" }, { "name": "JavaScript", "bytes": "13876786" }, { "name": "PHP", "bytes": "40188" }, { "name": "Ruby", "bytes": "5020" } ], "symlink_target": "" }
<!DOCTYPE html> <html lang="" xml:lang=""> <head> <title>Métodos de otimização</title> <meta charset="utf-8" /> <meta name="author" content="Bruno Santos" /> <meta name="date" content="2021-03-28" /> <script src="libs/fabric/fabric.min.js"></script> <link href="libs/xaringanExtra-scribble/scribble.css" rel="stylesheet" /> <script src="libs/xaringanExtra-scribble/scribble.js"></script> <script>document.addEventListener('DOMContentLoaded', function() { window.xeScribble = new Scribble({"pen_color":["#FF0000"],"pen_size":3,"eraser_size":30}) })</script> <link rel="stylesheet" href="xaringan-themer.css" type="text/css" /> </head> <body> <textarea id="source"> class: middle ## Métodos de otimização ***** ### Prof. Bruno Santos - email: bruno.santos.31@ufes.br --- class: center, middle, inverse # Sobre integração estocástica --- # Sobre integração estocástica - No último exemplo estudado, consideramos um exemplo de um caso bivariado. -- - Ao utilizarmos o algoritmo SIR para gerarmos valores aleatórios de `\(\pi(\alpha, \beta | x)\)`, podemos utilizar esses valores para calcular integrais do tipo `$$\int_\mathbb{R} \int_\mathbb{R} h(\alpha, \beta) \pi(\alpha, \beta|x) d\alpha d\beta$$` -- - Além disso, o exemplo tratou de falar sobre um problema do ponto de vista bayesiano de forma mais sucinta. -- - Poderíamos discutir algumas medidas que podem ser importantes para avaliar em algoritmos do tipo MCMC. --- class: inverse, middle, center # Métodos de otimização --- # Um exemplo anterior - Na aula sobre o método de aceitação e rejeição para variáveis contínuas tínhamos a seguinte situação. -- `$$f(x) = 20 x (1-x)^3, \quad 0 &lt; x &lt; 1.$$` `$$g(x) = 1, \quad 0 &lt; x &lt; 1.$$` - Precisávamos encontrar `\(c\)` tal que a linha vermelha fique acima da linha preta &lt;img src="index_files/figure-html/unnamed-chunk-1-1.png" width="30%" style="display: block; margin: auto;" /&gt; --- # Método força bruta - Utilizamos o cálculo para encontrar de `\(x\)` considerando a derivada. `$$\frac{d}{dx} \left( \frac{f(x)}{g(x)} \right) = 20[(1-x)^3 + 3x(1-x)^2]$$` -- - Como resposta, encontramos o valor de `\(x = 1/4\)`. -- - Poderíamos encontrar um valor próximo considerando uma sequência de valores `\(x\)` onde podemos calcular o valor da razão `\(\frac{f(x)}{g(x)}\)`. -- ```r x &lt;- seq(0, 1, length.out = 1e3 + 1) valores_razao &lt;- dbeta(x, 2, 4)/1 ind_x_max &lt;- which(valores_razao == max(valores_razao)) x[ind_x_max] ``` ``` ## [1] 0.25 ``` --- class: inverse, middle, center # Método de Newton-Raphson --- # Método de Newton-Raphson - Para descrever o método, precisamos lembrar do teorema do valor médio. -- De forma simplificada, podemos escrever que existe um `\(c\)` `$$f'(c) = \frac{f(b) - f(a)}{b - a}$$` para `\(f\)` contínua em `\([a,b]\)`, diferenciável em `\((a, b)\)`. -- - Se estivermos interessados em encontrar o ponto `\(x_R\)`, em que `\(f(x_R) = 0\)`, logo `\(x_R\)` é uma raiz da equação, podemos utilizar o teorema para escrever `$$f(x_n) = f'(z)[x_n - x_R]$$` -- - Reorganizando e considerando que não conhecemos `\(x_R\)` ou `\(z\)`, podemos fazer `$$x_{n+1} = x_n - \frac{f(x_n)}{f'(x_n)} = x_n - [f'(x_n)]^{-1}f(x_n)$$` --- # Função de verossimilhança - Considerando um modelo estatístico, estamos sempre interessar em obter estimativas dos parâmetros associados a esse modelo. -- - Caso Normal `$$X \sim N(\mu, \sigma^2), \quad \theta = (\mu, \sigma^2)$$` -- - Caso Poisson `$$X \sim P(\lambda), \quad \theta = \lambda$$` -- - Para ambos os casos, podemos escrever a função de verossimilhança `$$L(\theta) = f(x | \theta) \quad \mbox{ ou } \quad L(\theta) = P(X = x| \theta)$$` -- - Se temos uma amostra aleatória, ou seja, as observações são independentes. `$$L(\theta) = f(x_1, \ldots, x_n | \theta) = \prod_{i=1}^n f(x_i | \theta)$$` --- # Estimador de máxima verossimilhança - Podemos tentar encontrar `\(\theta\)` que maximiza a função de verossimilhança. -- - Esse valor também chamado de Estimador de máxima verossimilhança (EMV): - **é o valor do espaço paramétrico que maximiza a probabilidade de termos observado aquela amostra.** -- ```r set.seed(3456); amostra &lt;- rpois(50, lambda = 5) vero &lt;- function(theta) sapply(theta, function(a) prod(dpois(amostra, lambda = a))) curve(vero(x), 3, 7); abline(v = 5, lty = 2) ``` &lt;img src="index_files/figure-html/unnamed-chunk-3-1.png" width="25%" style="display: block; margin: auto;" /&gt; --- # Obtenção do máximo - É comum considerarmos o logaritmo da função de verossimilhança. `$$l(\theta) = \log(L(\theta))$$` -- - Porque é equivalente encontrar o máximo de `\(l(\theta)\)` ou `\(L(\theta)\)`. -- - Dessa forma, podemos utilizar o método de Newton para encontrar o máximo de `\(l(\theta)\)`, que é encontrar a raiz de `\(l'(\theta)\)`. -- - Reescrevendo o algoritmo, temos `$$\theta_{n+1} = \theta_n - [l''(\theta_n)]^{-1}l'(\theta_n)$$` -- - Dessa forma, podemos utilizar esse algoritmo de forma iterativa para encontrar o máximo do logaritmo da verossimilhança. -- - Um cuidado especial deve ser considerado no caso multivariado, pois `\(l''(\theta)\)` vai ser uma matriz. --- class: inverse, middle, center # Exemplo --- # Exemplo: Poisson - A função de probabilidade de `\(X \sim P(\theta)\)` `$$P(X = x) = \frac{e^{-\theta} \theta^x}{x!}, \quad x = 0, 1, 2, \ldots$$` -- - Se consideramos uma amostra aleatória `\(X_1,\ldots,X_n\)` `$$L(\theta) = \prod_{i=1}^n \frac{e^{-\theta} \theta^{x_i}}{x_i!} = \frac{1}{\prod_{i=1}^n x_i!} e^{-{n\theta}} \theta^{\sum_{i=1}^n x_i}$$` -- - Podemos escrever o logaritmo dessa função como `$$l(\theta) = - \sum_{i=1}^n \log(x_i!) - n\theta + \sum_{i=1}^n x_i \log(\theta)$$` -- - A primeira derivada de `\(l'(\theta)\)` também é fácil de ser obtida `$$l'(\theta) = \frac{\sum_{i=1}^n x_i}{\theta} - n$$` --- ### Método de Newton - Para utilizarmos o método de Newton precisamos também da segunda derivada `$$l''(\theta) = - \frac{\sum_{i=1}^n x_i}{\theta^2} = - \frac{n \bar{x}}{\theta^2}$$` -- - Podemos fazer o gráfico de `\(l'(\theta)\)` ```r escore &lt;- function(theta, amostra, n = length(amostra)) n * mean(amostra) / theta - n curve(escore(x, amostra), 1, 9, xlab = "theta", ylab = "escore(theta)"); abline(h = 0, lty = 2) ``` &lt;img src="index_files/figure-html/unnamed-chunk-4-1.png" width="30%" style="display: block; margin: auto;" /&gt; --- ### Método de Newton (cont.) - Podemos escrever um algoritmo para atualizar os valores de `\(\theta\)` a partir de um valor inicial. -- - O algoritmo deve considerar a seguinte relação `$$\begin{align*} \theta_{n+1} &amp;= \theta_n - \left[- \frac{n \bar{x}}{\theta^2} \right]^{-1} \left(\frac{n \bar{x}}{\theta} - n \right) \\ &amp;= 2\theta_n - \frac{\theta_n^2}{\bar{x}} \end{align*}$$` -- ```r met_newton_poisson &lt;- function(x, ponto_inicial, tolerancia = 0.01){ seq_theta &lt;- ponto_inicial seq_theta[2] &lt;- 2 * seq_theta[1] - seq_theta[1]^2/mean(x) dif &lt;- abs(seq_theta[2] - seq_theta[1]) while(dif &gt; tolerancia){ n &lt;- length(seq_theta) seq_theta[n + 1] &lt;- 2 * seq_theta[n] - seq_theta[n]^2/mean(x) dif &lt;- abs(seq_theta[n + 1] - seq_theta[n]) } seq_theta } ``` --- # Testando a função - Sabemos que o estimador de `\(\theta\)` é igual a média amostral. -- Então, podemos comparar o método quando começamos longe da média amostral e perto. -- ```r met_newton_poisson(x = amostra, ponto_inicial = 8) ``` ``` ## [1] 8.000000 3.200000 4.352000 4.916019 4.998589 5.000000 ``` ```r met_newton_poisson(x = amostra, ponto_inicial = 9, tolerancia = 0.0001) ``` ``` ## [1] 9.000000 1.800000 2.952000 4.161139 4.859263 4.996039 4.999997 5.000000 ``` ```r met_newton_poisson(x = amostra, ponto_inicial = 0.01, tolerancia = 0.0001) ``` ``` ## [1] 0.01000000 0.01998000 0.03988016 0.07944223 0.15762226 0.31027556 ## [7] 0.60129693 1.13028225 2.00505691 3.20606318 4.35635814 4.91714503 ## [13] 4.99862701 4.99999962 5.00000000 ``` --- ## Fazendo uma animação para mostrar os passos - Para mostrar os passos do algoritmo, podemos gerar um gif para poder comparar diferentes valores de amostra, valores iniciais ```r library(gganimate) faz_gif &lt;- function(n, lambda, p_inic, tol = 0.0001, seed = 42, min_fun = 0, max_fun = 10, nome_gif = "gif_newton.gif"){ set.seed(seed) x &lt;- rpois(n, lambda) palp &lt;- met_newton_poisson(x, p_inic, tol) dados_alg &lt;- data.frame(val_p = palp, it = 1:length(palp)) g &lt;- ggplot() + theme_classic() + geom_function(fun = escore, args = list(amostra = x), xlim = c(min_fun, max_fun)) + geom_vline(data = dados_alg, aes(xintercept = val_p), linetype = 2, size = 0.5, color = 'gray50') + geom_vline(aes(xintercept = mean(x)), color = 'darkviolet') + transition_states(states = it, wrap = TRUE) + labs(title = paste0("Iteração = ", "{closest_state}"), x = "x", y = "") anim_save(nome_gif, g) } ``` --- ```r faz_gif(50, 10, p_inic = 0.001, max_fun = 20) ``` .center[ ![](gif_newton.gif)] --- ```r faz_gif(20, 10, p_inic = 0.001, max_fun = 20, nome_gif = "gif2.gif") ``` .center[ ![](gif2.gif)] --- class: inverse, middle, center # Método de Fisher --- # Método de Fisher ou Método de Escore -- - Lembre que no método de Newton, nós precisávamos calcular `$$l''(\theta)$$` para inserir no método: `$$\theta_{n+1} = \theta_n - [l''(\theta_n)]^{-1}l'(\theta_n)$$` -- - Principalmente no caso em que `\(\theta\)` é um vetor, pode ser não tão simples obter a inversa da segunda derivada de `\(l(\theta)\)`. -- - Lembre que $$I(\theta) = E\left(-\frac{\partial^2 \log f(x|\theta)}{\partial \theta}\right) = E(-l''(\theta)) $$ -- - Então, poderíamos reescrever o método Newton considerando esse valor esperado `$$\theta_{n+1} = \theta_n + [I(\theta)]^{-1}l'(\theta_n)$$` --- class: middle, center, inverse # Fim! </textarea> <style data-target="print-only">@media screen {.remark-slide-container{display:block;}.remark-slide-scaler{box-shadow:none;}}</style> <script src="https://remarkjs.com/downloads/remark-latest.min.js"></script> <script>var slideshow = remark.create({ "highlightStyle": "github", "highlightLines": true, "countIncrementalSlides": false, "ratio": "16:9" }); if (window.HTMLWidgets) slideshow.on('afterShowSlide', function (slide) { window.dispatchEvent(new Event('resize')); }); (function(d) { var s = d.createElement("style"), r = d.querySelector(".remark-slide-scaler"); if (!r) return; s.type = "text/css"; s.innerHTML = "@page {size: " + r.style.width + " " + r.style.height +"; }"; d.head.appendChild(s); })(document); (function(d) { var el = d.getElementsByClassName("remark-slides-area"); if (!el) return; var slide, slides = slideshow.getSlides(), els = el[0].children; for (var i = 1; i < slides.length; i++) { slide = slides[i]; if (slide.properties.continued === "true" || slide.properties.count === "false") { els[i - 1].className += ' has-continuation'; } } var s = d.createElement("style"); s.type = "text/css"; s.innerHTML = "@media print { .has-continuation { display: none; } }"; d.head.appendChild(s); })(document); // delete the temporary CSS (for displaying all slides initially) when the user // starts to view slides (function() { var deleted = false; slideshow.on('beforeShowSlide', function(slide) { if (deleted) return; var sheets = document.styleSheets, node; for (var i = 0; i < sheets.length; i++) { node = sheets[i].ownerNode; if (node.dataset["target"] !== "print-only") continue; node.parentNode.removeChild(node); } deleted = true; }); })(); (function() { "use strict" // Replace <script> tags in slides area to make them executable var scripts = document.querySelectorAll( '.remark-slides-area .remark-slide-container script' ); if (!scripts.length) return; for (var i = 0; i < scripts.length; i++) { var s = document.createElement('script'); var code = document.createTextNode(scripts[i].textContent); s.appendChild(code); var scriptAttrs = scripts[i].attributes; for (var j = 0; j < scriptAttrs.length; j++) { s.setAttribute(scriptAttrs[j].name, scriptAttrs[j].value); } scripts[i].parentElement.replaceChild(s, scripts[i]); } })(); (function() { var links = document.getElementsByTagName('a'); for (var i = 0; i < links.length; i++) { if (/^(https?:)?\/\//.test(links[i].getAttribute('href'))) { links[i].target = '_blank'; } } })(); // adds .remark-code-has-line-highlighted class to <pre> parent elements // of code chunks containing highlighted lines with class .remark-code-line-highlighted (function(d) { const hlines = d.querySelectorAll('.remark-code-line-highlighted'); const preParents = []; const findPreParent = function(line, p = 0) { if (p > 1) return null; // traverse up no further than grandparent const el = line.parentElement; return el.tagName === "PRE" ? el : findPreParent(el, ++p); }; for (let line of hlines) { let pre = findPreParent(line); if (pre && !preParents.includes(pre)) preParents.push(pre); } preParents.forEach(p => p.classList.add("remark-code-has-line-highlighted")); })(document);</script> <script> slideshow._releaseMath = function(el) { var i, text, code, codes = el.getElementsByTagName('code'); for (i = 0; i < codes.length;) { code = codes[i]; if (code.parentNode.tagName !== 'PRE' && code.childElementCount === 0) { text = code.textContent; if (/^\\\((.|\s)+\\\)$/.test(text) || /^\\\[(.|\s)+\\\]$/.test(text) || /^\$\$(.|\s)+\$\$$/.test(text) || /^\\begin\{([^}]+)\}(.|\s)+\\end\{[^}]+\}$/.test(text)) { code.outerHTML = code.innerHTML; // remove <code></code> continue; } } i++; } }; slideshow._releaseMath(document); </script> <!-- dynamically load mathjax for compatibility with self-contained --> <script> (function () { var script = document.createElement('script'); script.type = 'text/javascript'; script.src = 'https://mathjax.rstudio.com/latest/MathJax.js?config=TeX-MML-AM_CHTML'; if (location.protocol !== 'file:' && /^https?:/.test(script.src)) script.src = script.src.replace(/^https?:/, ''); document.getElementsByTagName('head')[0].appendChild(script); })(); </script> </body> </html>
{ "content_hash": "3d0b1d8997c8571230b020bf7a8b3c2f", "timestamp": "", "source": "github", "line_count": 541, "max_line_length": 172, "avg_line_length": 26.817005545286506, "alnum_prop": 0.6277915632754343, "repo_name": "brsantos/brsantos.github.io", "id": "bd5aa2a916c740e336f5aa7cfe8afd9220cdf25d", "size": "14632", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "comp_slides/aula11/index.html", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "855894" }, { "name": "Dockerfile", "bytes": "1101" }, { "name": "HTML", "bytes": "28819953" }, { "name": "JavaScript", "bytes": "4903882" }, { "name": "R", "bytes": "78930" }, { "name": "Ruby", "bytes": "1109" }, { "name": "TeX", "bytes": "69825" } ], "symlink_target": "" }
void handleRequest39 ( UdpSlot *slot , int32_t netnice ) ; class Msg39Request { public: Msg39Request () { reset(); }; void reset() { m_docsToGet = 10; m_niceness = MAX_NICENESS; m_maxAge = 0; m_maxQueryTerms = 9999; //m_compoundListMaxSize = 20000000; m_boolFlag = 2; m_language = 0; m_queryExpansion = false; m_debug = 0; m_getDocIdScoringInfo = true; m_doSiteClustering = true; m_hideAllClustered = false; //m_doIpClustering = true; m_doDupContentRemoval = true; m_restrictPosdbForQuery = false; m_addToCache = false; m_familyFilter = false; m_timeout = -1; // -1 means auto-compute //m_useMinAlgo = false; //m_fastIntersection = -1; m_stripe = 0; m_collnum = -1; m_useQueryStopWords = true; //m_useNewAlgo = true; m_doMaxScoreAlgo = true; m_seoDebug = false; m_useSeoResultsCache = false; ptr_readSizes = NULL; ptr_query = NULL; // in utf8? ptr_whiteList = NULL; //ptr_coll = NULL; m_forSectionStats = false; size_readSizes = 0; size_query = 0; size_whiteList = 0; m_sameLangWeight = 20.0; m_maxFacets = -1; //size_coll = 0; m_getDocIdScoringInfo = 1; // -1 means to not to docid range restriction m_minDocId = -1LL; m_maxDocId = -1LL; m_numDocIdSplits = 1; // for widget, to only get results to append to last docid m_maxSerpScore = 0.0; m_minSerpDocId = 0LL; m_makeReply = true; // . search results knobs // . accumulate the top 10 term pairs from inlink text. lower // it down from 10 here. m_realMaxTop = MAX_TOP; }; // we are requesting that this many docids be returned. Msg40 requests // of Msg3a a little more docids than it needs because it assumes // some will be de-duped at summary gen time. int32_t m_docsToGet; int32_t m_maxFacets; int32_t m_nqt; // # of query terms char m_niceness; int32_t m_maxAge; int32_t m_maxQueryTerms; int32_t m_numDocIdSplits; float m_sameLangWeight; //int32_t m_compoundListMaxSize; char m_boolFlag; uint8_t m_language; // flags char m_queryExpansion; char m_debug; char m_seoDebug; char m_useSeoResultsCache; char m_doSiteClustering; char m_hideAllClustered; //char m_doIpClustering; char m_doDupContentRemoval; char m_restrictPosdbForQuery; char m_addToCache; char m_familyFilter; char m_getDocIdScoringInfo; char m_realMaxTop; char m_stripe; char m_useQueryStopWords; //char m_useNewAlgo; char m_doMaxScoreAlgo; char m_forSectionStats; // Msg3a still uses this //int32_t m_myFacetVal32; // for gbfacet:xpathsite really sectionstats //char m_useMinAlgo; //char m_fastIntersection; collnum_t m_collnum; int64_t m_minDocId; int64_t m_maxDocId; bool m_makeReply; // for widget, to only get results to append to last docid double m_maxSerpScore; int64_t m_minSerpDocId; // msg3a stuff int32_t m_timeout; // in seconds time_t m_nowUTC; // do not add new string parms before ptr_readSizes or // after ptr_whiteList so serializeMsg() calls still work char *ptr_readSizes; char *ptr_termFreqWeights; char *ptr_query; // in utf8? char *ptr_whiteList; //char *ptr_coll; // do not add new string parms before size_readSizes or // after size_whiteList so serializeMsg() calls still work int32_t size_readSizes; int32_t size_termFreqWeights; int32_t size_query; int32_t size_whiteList; //int32_t size_coll; char m_buf[0]; }; class Msg39Reply { public: // zero ourselves out void reset() { memset ( (char *)this,0,sizeof(Msg39Reply) ); }; int32_t m_numDocIds; // # of "unignored" query terms int32_t m_nqt; // # of estimated hits we had int32_t m_estimatedHits; // error code int32_t m_errno; // do not add new string parms before ptr_docIds or // after ptr_clusterRecs so serializeMsg() calls still work char *ptr_docIds ; // the results, int64_t char *ptr_scores; ; // now doubles! so we can have intScores char *ptr_scoreInfo ; // transparency info char *ptr_pairScoreBuf ; // transparency info char *ptr_singleScoreBuf ; // transparency info // this is now 1-1 with # of query terms! char *ptr_facetHashList ; // list of all the facet values in serps char *ptr_clusterRecs ; // key_t (might be empty) // do not add new string parms before size_docIds or // after size_clusterRecs so serializeMsg() calls still work int32_t size_docIds; int32_t size_scores; int32_t size_scoreInfo; int32_t size_pairScoreBuf ; int32_t size_singleScoreBuf; int32_t size_facetHashList; int32_t size_clusterRecs; // . this is the "string buffer" and it is a variable size // . this whole class is cast to a udp reply, so the size of "buf" // depends on the size of that udp reply char m_buf[0]; }; class Msg39 { public: Msg39(); void reset(); void reset2(); // register our request handler for Msg39's bool registerHandler ( ); // called by handler when a request for docids arrives void getDocIds ( UdpSlot *slot ) ; // XmlDoc.cpp seo pipeline uses this call void getDocIds2 ( class Msg39Request *req ) ; // retrieves the lists needed as specified by termIds and PosdbTable bool getLists () ; // called when lists have been retrieved, uses PosdbTable to hash lists bool intersectLists ( );//bool updateReadInfo ) ; // this is called after thread exits, or if thread creation failed bool addedLists(); // incoming parameters passed to Msg39::getDocIds() function //void *m_state; //void (* m_callback ) ( void *state ); // . this is used by handler to reconstruct the incoming Query class // . TODO: have a serialize/deserialize for Query class Query m_tmpq; int64_t m_docIdStart ; int64_t m_docIdEnd ; // used to get IndexLists all at once Msg2 m_msg2; // holds slot after we create this Msg39 to handle a request for docIds UdpSlot *m_slot; // . used for getting IndexList startKey/endKey/minNumRecs for each // termId we got from the query // . used for hashing our retrieved IndexLists PosdbTable m_posdbTable; // keep a ptr to the request Msg39Request *m_r; char m_debug; //int32_t m_numDocIdSplits; bool m_allocedTree; int64_t m_ddd; int64_t m_dddEnd; bool doDocIdSplitLoop(); // . we hold our IndexLists here for passing to PosdbTable // . one array for each of the tiers IndexList m_lists [ MAX_QUERY_TERMS ]; // used for timing int64_t m_startTime; // this is set if PosdbTable::addLists() had an error int32_t m_errno; // always use top tree now TopTree m_tt; char m_boolFlag; int32_t m_firstResultNum; int64_t m_numTotalHits; int32_t m_numCensored; // for indexdb splitting char m_paritySplit; int32_t m_bufSize; char *m_buf; int64_t *m_clusterDocIds; char *m_clusterLevels; key_t *m_clusterRecs; int32_t m_numClusterDocIds; int32_t m_numVisible; int32_t m_numDocIds; Msg51 m_msg51; bool m_gotClusterRecs; bool controlLoop(); int32_t m_phase; void estimateHitsAndSendReply (); bool setClusterRecs (); bool gotClusterRecs (); // hack stuff void *m_tmp; int32_t m_tmp2; bool m_blocked; void (*m_callback)( void *state ); void *m_state; int64_t m_topDocId; float m_topScore; int64_t m_topDocId2; float m_topScore2; // . for the top 50 algo in seo.cpp // . will be the score of the last result if < 50 results float m_topScore50; int64_t m_topDocId50; bool m_inUse; }; #endif
{ "content_hash": "bde2fc5a08d908f17752a0fc0a236ee3", "timestamp": "", "source": "github", "line_count": 303, "max_line_length": 74, "avg_line_length": 26.554455445544555, "alnum_prop": 0.6327367636092468, "repo_name": "kalatestimine/open-source-search-engine", "id": "515666cfb55eadd98f69b98f3112ee6b931c8e03", "size": "8618", "binary": false, "copies": "5", "ref": "refs/heads/master", "path": "Msg39.h", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "C", "bytes": "1788423" }, { "name": "C++", "bytes": "25516807" }, { "name": "HTML", "bytes": "376299" }, { "name": "Makefile", "bytes": "25194" }, { "name": "Objective-C", "bytes": "7505" }, { "name": "PHP", "bytes": "8039" }, { "name": "Perl", "bytes": "7481" }, { "name": "Shell", "bytes": "542" } ], "symlink_target": "" }
<div ng-controller="NavCtrl"> <div class="alert {{ msg.type }} fade-in" ng-repeat="msg in messages"> <span class="close" data-dismiss="alert" aria-label="close" ng-click="close($index)">&times;</span> {{ msg.text }} </div> </div>
{ "content_hash": "dc6902a1c516a5d9f51de79f93f80283", "timestamp": "", "source": "github", "line_count": 12, "max_line_length": 66, "avg_line_length": 21.833333333333332, "alnum_prop": 0.5801526717557252, "repo_name": "Shura16/contatosjs", "id": "4bfbdbdab8823768ce907e273bd1e2689c907981", "size": "262", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "dist/views/alertsDirective.html", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "384921" }, { "name": "HTML", "bytes": "137587" }, { "name": "JavaScript", "bytes": "4668491" }, { "name": "PowerShell", "bytes": "468" }, { "name": "Ruby", "bytes": "869" }, { "name": "Shell", "bytes": "1204" } ], "symlink_target": "" }
class ppIO{ public: std::string ReadFile(const char *filename); }; #endif
{ "content_hash": "c00d587684e444666b21ab0e9911d423", "timestamp": "", "source": "github", "line_count": 6, "max_line_length": 44, "avg_line_length": 12.666666666666666, "alnum_prop": 0.7105263157894737, "repo_name": "spywhere/Legacy-ParticlePlay", "id": "5da59b6b92dc8ef0e377df6d4e962d235f402873", "size": "169", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "ParticlePlay/Core/IO.hpp", "mode": "33188", "license": "bsd-3-clause", "language": [ { "name": "Batchfile", "bytes": "130" }, { "name": "C++", "bytes": "355654" }, { "name": "CMake", "bytes": "11837" }, { "name": "Makefile", "bytes": "444" }, { "name": "Shell", "bytes": "396" } ], "symlink_target": "" }
<?php namespace Mage\Widget\Test\Block\Adminhtml\Widget; use Magento\Mtf\Client\Locator; use Magento\Mtf\Client\Element\SimpleElement; /** * Widget Chosen Option. */ class ChosenOption extends SimpleElement { /** * Select page button selector. * * @var string */ protected $selectButton = '//ancestor::body//button[contains(@class,"btn-chooser")]'; /** * Select block selector. * * @var string */ protected $selectBlock = "//ancestor::body/div[@id='widget-chooser']"; /** * Entity chooser block class mapping. * * @var array */ protected $chooserClasses = [ 'page' => '\Mage\Adminhtml\Test\Block\Cms\Page\Widget\Chooser', ]; /** * Select widget options. * * @param array $value * @return void */ public function setValue($value) { $this->clickSelectButton(); if (isset($value['filter_url_key'])) { $grid = $this->getClassBlock($this->chooserClasses['page']); $grid->searchAndOpen(['chooser_identifier' => $value['filter_url_key']]); } } /** * Clicking to select button. * * @return void */ protected function clickSelectButton() { $this->find($this->selectButton, Locator::SELECTOR_XPATH)->click(); } /** * Get block by class. * * @param string $class * @return mixed */ protected function getClassBlock($class) { return \Magento\Mtf\ObjectManager::getInstance()->create( $class, ['element' => $this->driver->find($this->selectBlock, Locator::SELECTOR_XPATH)] ); } }
{ "content_hash": "6df8771a243bfcf39568c25875938a1f", "timestamp": "", "source": "github", "line_count": 75, "max_line_length": 91, "avg_line_length": 22.506666666666668, "alnum_prop": 0.5657582938388626, "repo_name": "tuminitumina/magentobasic", "id": "4f54e02faffe9bcd695bb38761a098fec74febc8", "size": "2647", "binary": false, "copies": "6", "ref": "refs/heads/master", "path": "dev/tests/functional/tests/app/Mage/Widget/Test/Block/Adminhtml/Widget/ChosenOption.php", "mode": "33188", "license": "mit", "language": [ { "name": "ApacheConf", "bytes": "95" }, { "name": "CSS", "bytes": "757556" }, { "name": "HTML", "bytes": "5126501" }, { "name": "JavaScript", "bytes": "1126889" }, { "name": "PHP", "bytes": "28512323" }, { "name": "Ruby", "bytes": "288" } ], "symlink_target": "" }
package io.github.stormcloud_dev.stormcloud.frame.clientbound; public class DisPlayerClientBoundFrame extends ClientBoundFrame { public DisPlayerClientBoundFrame(double objectIndex, double multiplayerId) { super((byte) 17, objectIndex, multiplayerId); } @Override public int getLength() { return 17; } }
{ "content_hash": "9bd5f27d63fb4329f62392655ac2e4f4", "timestamp": "", "source": "github", "line_count": 15, "max_line_length": 80, "avg_line_length": 23, "alnum_prop": 0.7217391304347827, "repo_name": "stormcloud-dev/stormcloud", "id": "cee671eb0c38fd182e3213f0f277ed16891572be", "size": "976", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/main/java/io/github/stormcloud_dev/stormcloud/frame/clientbound/DisPlayerClientBoundFrame.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Java", "bytes": "392312" } ], "symlink_target": "" }
export interface WishList { name?: string; title?: string; description?: string; users?: UserShare[]; owners?: UserShare[] | null; picture?: string; pictures?: string[]; type?: WishListType; date?: number | null; privacy?: WishListPrivacy; forceAnonymous?: boolean; state?: string; owner?: boolean; canSuggest?: boolean; counts?: { ACTIVE: number; ARCHIVED: number; [key: string]: number; }; } export interface UserShare { email?: string; name?: string; type?: "SHARED" | "OWNER" | string; photoURL?: string; } export type WishListPrivacy = "PRIVATE" | "OPEN" | "PUBLIC"; export type WishListType = | "OTHER" | "CHRISTMAS" | "BIRTHDAY" | "BIRTH" | "WEDDING" | "LEAVING" | "HOUSE_WARMING" | "RETIREMENT" | "CEREMONY" | "SPECIAL_OCCASION";
{ "content_hash": "3b1cae911484e3318029a391bc65df61", "timestamp": "", "source": "github", "line_count": 42, "max_line_length": 60, "avg_line_length": 19.38095238095238, "alnum_prop": 0.6277641277641277, "repo_name": "patou/liste-envies", "id": "5adbc71f669f7c2398ac12e6f0097ae26aea1f8c", "size": "816", "binary": false, "copies": "1", "ref": "refs/heads/develop", "path": "liste-envies-front/src/app/models/WishList.d.ts", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "CSS", "bytes": "33746" }, { "name": "HTML", "bytes": "344836" }, { "name": "Java", "bytes": "157546" }, { "name": "JavaScript", "bytes": "5794" }, { "name": "SCSS", "bytes": "222400" }, { "name": "TypeScript", "bytes": "232123" } ], "symlink_target": "" }
require './handlers/gif_limiter' Lita.configure do |config| # Bot name config.robot.name = ENV.fetch('BOT_NAME', 'unbot') # Also use the '$' alias config.robot.alias = ENV['BOT_ALIAS'] if ENV.has_key? 'BOT_ALIAS' # The severity of messages to log. Options are: # :debug, :info, :warn, :error, :fatal # Messages at the selected level and above will be logged. config.robot.log_level = :info # An array of user IDs that are considered administrators. These users # the ability to add and remove other users from authorization groups. # What is considered a user ID will change depending on which adapter you use. config.robot.admins = ['U025V5AC3'] # Use the Slack adapter config.robot.adapter = :slack config.adapters.slack.token = ENV['SLACK_TOKEN'] # Configure redis using Redis To Go if on Heroku config.redis[:url] = ENV['REDIS_URL'] if ENV.has_key? 'REDIS_URL' # Set port if available config.http.port = ENV['PORT'] if ENV.has_key? 'PORT' # Configure Giphy API key config.handlers.giphy.api_key = ENV['GIPHY_API_KEY'] # Configure forecast.io API key config.handlers.forecast.api_key = ENV['FORECAST_API_KEY'] end
{ "content_hash": "2031bf23fc5259329820f00e6b02ff04", "timestamp": "", "source": "github", "line_count": 35, "max_line_length": 80, "avg_line_length": 33.48571428571429, "alnum_prop": 0.7039249146757679, "repo_name": "unhaltable/unbot", "id": "3dcddd4ae7ac24bab4b9c1420eb55868fc476c3c", "size": "1172", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "lita_config.rb", "mode": "33188", "license": "mit", "language": [ { "name": "Ruby", "bytes": "3887" } ], "symlink_target": "" }
$.fn.yarp = function(options) { var options = options || {}; this.options = { colors: ['gray'], // Array. Colors to be used randomly duration: 750 // Integer. Duration of the ripple animation }; this.options = $.extend({}, this.options, options); $(this).each(function(i, e) { // No overflow for the selected set of elements $(e).css({ overflow: 'hidden' }); $(e).on('click', function(ev) { // Create the ripple element var ripple = $('<div></div>').appendTo($(e)); // Set some initial CSS ripple.css({ width: 1, height: 1, borderRadius: '50%', opacity: 1, background: this.options.colors[Math.floor(Math.random() * this.options.colors.length)], top: ev.clientY - ($(e).offset().top - $(window).scrollTop()), left: ev.clientX - ($(e).offset().left - $(window).scrollLeft()), position: 'absolute' }); // Additional CSS to be set at the end of the browser's execution queue setTimeout(function() { ripple.css({ transform: 'scale(1000)', opacity: 0, transition: 'all ' + this.options.duration + 'ms linear' }); }.bind(this), 0); // Remove ripple after it finished animating setTimeout(function() { ripple.remove(); }, this.options.duration); }.bind(this)); }.bind(this)); };
{ "content_hash": "7e72809755fbcdb772b990451f03c4cc", "timestamp": "", "source": "github", "line_count": 50, "max_line_length": 104, "avg_line_length": 34.14, "alnum_prop": 0.45987111892208554, "repo_name": "Ardethian/yet-another-ripple-plugin", "id": "d2af8a3fba962bf093051b314321cdb4aadc88bb", "size": "1707", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/yarp.js", "mode": "33188", "license": "mit", "language": [ { "name": "JavaScript", "bytes": "1707" } ], "symlink_target": "" }
package com.hazelcast.client.impl.protocol.codec; import com.hazelcast.client.impl.protocol.ClientMessage; import com.hazelcast.client.impl.protocol.Generated; import com.hazelcast.client.impl.protocol.codec.builtin.*; import com.hazelcast.client.impl.protocol.codec.custom.*; import javax.annotation.Nullable; import static com.hazelcast.client.impl.protocol.ClientMessage.*; import static com.hazelcast.client.impl.protocol.codec.builtin.FixedSizeTypesCodec.*; /* * This file is auto-generated by the Hazelcast Client Protocol Code Generator. * To change this file, edit the templates or the protocol * definitions on the https://github.com/hazelcast/hazelcast-client-protocol * and regenerate it. */ /** * Retrieves the mapped value of the given key using a custom javax.cache.expiry.ExpiryPolicy. If no mapping exists * null is returned. If the cache is configured for read-through operation mode, the underlying configured * javax.cache.integration.CacheLoader might be called to retrieve the value of the key from any kind of external resource. */ @Generated("525bdb91b8230a96e62c3d9c0c3d4144") public final class CacheGetCodec { //hex: 0x130D00 public static final int REQUEST_MESSAGE_TYPE = 1248512; //hex: 0x130D01 public static final int RESPONSE_MESSAGE_TYPE = 1248513; private static final int REQUEST_INITIAL_FRAME_SIZE = PARTITION_ID_FIELD_OFFSET + INT_SIZE_IN_BYTES; private static final int RESPONSE_INITIAL_FRAME_SIZE = RESPONSE_BACKUP_ACKS_FIELD_OFFSET + BYTE_SIZE_IN_BYTES; private CacheGetCodec() { } @edu.umd.cs.findbugs.annotations.SuppressFBWarnings({"URF_UNREAD_PUBLIC_OR_PROTECTED_FIELD"}) public static class RequestParameters { /** * Name of the cache. */ public java.lang.String name; /** * The key whose mapped value is to be returned. */ public com.hazelcast.internal.serialization.Data key; /** * Expiry policy for the entry. Byte-array which is serialized from an object implementing * javax.cache.expiry.ExpiryPolicy interface. */ public @Nullable com.hazelcast.internal.serialization.Data expiryPolicy; } public static ClientMessage encodeRequest(java.lang.String name, com.hazelcast.internal.serialization.Data key, @Nullable com.hazelcast.internal.serialization.Data expiryPolicy) { ClientMessage clientMessage = ClientMessage.createForEncode(); clientMessage.setRetryable(true); clientMessage.setOperationName("Cache.Get"); ClientMessage.Frame initialFrame = new ClientMessage.Frame(new byte[REQUEST_INITIAL_FRAME_SIZE], UNFRAGMENTED_MESSAGE); encodeInt(initialFrame.content, TYPE_FIELD_OFFSET, REQUEST_MESSAGE_TYPE); encodeInt(initialFrame.content, PARTITION_ID_FIELD_OFFSET, -1); clientMessage.add(initialFrame); StringCodec.encode(clientMessage, name); DataCodec.encode(clientMessage, key); CodecUtil.encodeNullable(clientMessage, expiryPolicy, DataCodec::encode); return clientMessage; } public static CacheGetCodec.RequestParameters decodeRequest(ClientMessage clientMessage) { ClientMessage.ForwardFrameIterator iterator = clientMessage.frameIterator(); RequestParameters request = new RequestParameters(); //empty initial frame iterator.next(); request.name = StringCodec.decode(iterator); request.key = DataCodec.decode(iterator); request.expiryPolicy = CodecUtil.decodeNullable(iterator, DataCodec::decode); return request; } public static ClientMessage encodeResponse(@Nullable com.hazelcast.internal.serialization.Data response) { ClientMessage clientMessage = ClientMessage.createForEncode(); ClientMessage.Frame initialFrame = new ClientMessage.Frame(new byte[RESPONSE_INITIAL_FRAME_SIZE], UNFRAGMENTED_MESSAGE); encodeInt(initialFrame.content, TYPE_FIELD_OFFSET, RESPONSE_MESSAGE_TYPE); clientMessage.add(initialFrame); CodecUtil.encodeNullable(clientMessage, response, DataCodec::encode); return clientMessage; } /** * The value assigned to the given key, or null if not assigned. */ public static com.hazelcast.internal.serialization.Data decodeResponse(ClientMessage clientMessage) { ClientMessage.ForwardFrameIterator iterator = clientMessage.frameIterator(); //empty initial frame iterator.next(); return CodecUtil.decodeNullable(iterator, DataCodec::decode); } }
{ "content_hash": "f93e13b80efcdf3dcae0b60b8a78e1d9", "timestamp": "", "source": "github", "line_count": 104, "max_line_length": 183, "avg_line_length": 44.03846153846154, "alnum_prop": 0.7327510917030567, "repo_name": "emre-aydin/hazelcast", "id": "361f792922ca17a5e80ecc6578b66445597c2649", "size": "5205", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "hazelcast/src/main/java/com/hazelcast/client/impl/protocol/codec/CacheGetCodec.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Batchfile", "bytes": "1261" }, { "name": "C", "bytes": "353" }, { "name": "Java", "bytes": "39634758" }, { "name": "Shell", "bytes": "29479" } ], "symlink_target": "" }
require 'spec_helper' require 'pp' require 'stringio' describe RSpec::Core::Example, :parent_metadata => 'sample' do let(:example_group) do RSpec::Core::ExampleGroup.describe('group description') end let(:example_instance) do example_group.example('example description') { } end it_behaves_like "metadata hash builder" do def metadata_hash(*args) example = example_group.example('example description', *args) example.metadata end end def capture_stdout orig_stdout = $stdout $stdout = StringIO.new yield $stdout.string ensure $stdout = orig_stdout end it "can be pretty printed" do output = ignoring_warnings { capture_stdout { pp example_instance } } expect(output).to include("RSpec::Core::Example") end describe "#exception" do it "supplies the first exception raised, if any" do RSpec.configuration.output_stream = StringIO.new example = example_group.example { raise "first" } example_group.after { raise "second" } example_group.run expect(example.exception.message).to eq("first") end it "returns nil if there is no exception" do example = example_group.example('example') { } example_group.run expect(example.exception).to be_nil end end describe "when there is an explicit description" do context "when RSpec.configuration.format_docstrings is set to a block" do it "formats the description using the block" do RSpec.configuration.format_docstrings { |s| s.strip } example = example_group.example(' an example with whitespace ') {} example_group.run expect(example.description).to eql('an example with whitespace') end end end describe "when there is no explicit description" do def expect_with(*frameworks) RSpec.configuration.stub(:expecting_with_rspec?).and_return(frameworks.include?(:rspec)) if frameworks.include?(:stdlib) example_group.class_eval do def assert(val) raise "Expected #{val} to be true" unless val end end end end context "when RSpec.configuration.format_docstrings is set to a block" do it "formats the description using the block" do RSpec.configuration.format_docstrings { |s| s.upcase } example_group.example { expect(5).to eq(5) } example_group.run pattern = /EXAMPLE AT #{relative_path(__FILE__).upcase}:#{__LINE__ - 2}/ expect(example_group.examples.first.description).to match(pattern) end end context "when `expect_with :rspec` is configured" do before(:each) { expect_with :rspec } it "uses the matcher-generated description" do example_group.example { expect(5).to eq(5) } example_group.run expect(example_group.examples.first.description).to eq("should eq 5") end it "uses the matcher-generated description in the full description" do example_group.example { expect(5).to eq(5) } example_group.run expect(example_group.examples.first.full_description).to eq("group description should eq 5") end it "uses the file and line number if there is no matcher-generated description" do example = example_group.example {} example_group.run expect(example.description).to match(/example at #{relative_path(__FILE__)}:#{__LINE__ - 2}/) end it "uses the file and line number if there is an error before the matcher" do example = example_group.example { expect(5).to eq(5) } example_group.before { raise } example_group.run expect(example.description).to match(/example at #{relative_path(__FILE__)}:#{__LINE__ - 3}/) end end context "when `expect_with :rspec, :stdlib` is configured" do before(:each) { expect_with :rspec, :stdlib } it "uses the matcher-generated description" do example_group.example { expect(5).to eq(5) } example_group.run expect(example_group.examples.first.description).to eq("should eq 5") end it "uses the file and line number if there is no matcher-generated description" do example = example_group.example {} example_group.run expect(example.description).to match(/example at #{relative_path(__FILE__)}:#{__LINE__ - 2}/) end it "uses the file and line number if there is an error before the matcher" do example = example_group.example { expect(5).to eq(5) } example_group.before { raise } example_group.run expect(example.description).to match(/example at #{relative_path(__FILE__)}:#{__LINE__ - 3}/) end end context "when `expect_with :stdlib` is configured" do before(:each) { expect_with :stdlib } it "does not attempt to get the generated description from RSpec::Matchers" do RSpec::Matchers.should_not_receive(:generated_description) example_group.example { assert 5 == 5 } example_group.run end it "uses the file and line number" do example = example_group.example { assert 5 == 5 } example_group.run expect(example.description).to match(/example at #{relative_path(__FILE__)}:#{__LINE__ - 2}/) end end end describe "#described_class" do it "returns the class (if any) of the outermost example group" do expect(described_class).to eq(RSpec::Core::Example) end end describe "accessing metadata within a running example" do it "has a reference to itself when running" do |ex| expect(ex.description).to eq("has a reference to itself when running") end it "can access the example group's top level metadata as if it were its own" do |ex| expect(ex.example_group.metadata).to include(:parent_metadata => 'sample') expect(ex.metadata).to include(:parent_metadata => 'sample') end end describe "accessing options within a running example" do it "can look up option values by key", :demo => :data do |ex| expect(ex.metadata[:demo]).to eq(:data) end end describe "#run" do it "sets its reference to the example group instance to nil" do group = RSpec::Core::ExampleGroup.describe do example('example') { expect(1).to eq(1) } end group.run expect(group.examples.first.instance_variable_get("@example_group_instance")).to be_nil end it "runs after(:each) when the example passes" do after_run = false group = RSpec::Core::ExampleGroup.describe do after(:each) { after_run = true } example('example') { expect(1).to eq(1) } end group.run expect(after_run).to be_truthy, "expected after(:each) to be run" end it "runs after(:each) when the example fails" do after_run = false group = RSpec::Core::ExampleGroup.describe do after(:each) { after_run = true } example('example') { expect(1).to eq(2) } end group.run expect(after_run).to be_truthy, "expected after(:each) to be run" end it "runs after(:each) when the example raises an Exception" do after_run = false group = RSpec::Core::ExampleGroup.describe do after(:each) { after_run = true } example('example') { raise "this error" } end group.run expect(after_run).to be_truthy, "expected after(:each) to be run" end context "with an after(:each) that raises" do it "runs subsequent after(:each)'s" do after_run = false group = RSpec::Core::ExampleGroup.describe do after(:each) { after_run = true } after(:each) { raise "FOO" } example('example') { expect(1).to eq(1) } end group.run expect(after_run).to be_truthy, "expected after(:each) to be run" end it "stores the exception" do group = RSpec::Core::ExampleGroup.describe group.after(:each) { raise "FOO" } example = group.example('example') { expect(1).to eq(1) } group.run expect(example.metadata[:execution_result][:exception].message).to eq("FOO") end end it "wraps before/after(:each) inside around" do results = [] group = RSpec::Core::ExampleGroup.describe do around(:each) do |e| results << "around (before)" e.run results << "around (after)" end before(:each) { results << "before" } after(:each) { results << "after" } example { results << "example" } end group.run expect(results).to eq([ "around (before)", "before", "example", "after", "around (after)" ]) end context "clearing ivars" do it "sets ivars to nil to prep them for GC" do group = RSpec::Core::ExampleGroup.describe do before(:all) { @before_all = :before_all } before(:each) { @before_each = :before_each } after(:each) { @after_each = :after_each } after(:all) { @after_all = :after_all } end group.example("does something") do expect(@before_all).to eq(:before_all) expect(@before_each).to eq(:before_each) end expect(group.run(double.as_null_object)).to be_truthy group.new do |example| %w[@before_all @before_each @after_each @after_all].each do |ivar| expect(example.instance_variable_get(ivar)).to be_nil end end end it "does not impact the before_all_ivars which are copied to each example" do group = RSpec::Core::ExampleGroup.describe do before(:all) { @before_all = "abc" } example("first") { expect(@before_all).not_to be_nil } example("second") { expect(@before_all).not_to be_nil } end expect(group.run).to be_truthy end end context 'when the example raises an error' do def run_and_capture_reported_message(group) reported_msg = nil # We can't use should_receive(:message).with(/.../) here, # because if that fails, it would fail within our example-under-test, # and since there's already two errors, it would just be reported again. RSpec.configuration.reporter.stub(:message) { |msg| reported_msg = msg } group.run reported_msg end it "prints any around hook errors rather than silencing them" do group = RSpec::Core::ExampleGroup.describe do around(:each) { |e| e.run; raise "around" } example("e") { raise "example" } end message = run_and_capture_reported_message(group) expect(message).to match(/An error occurred in an around.* hook/i) end it "prints any after hook errors rather than silencing them" do group = RSpec::Core::ExampleGroup.describe do after(:each) { raise "after" } example("e") { raise "example" } end message = run_and_capture_reported_message(group) expect(message).to match(/An error occurred in an after.* hook/i) end it "does not print mock expectation errors" do group = RSpec::Core::ExampleGroup.describe do example do foo = double foo.should_receive(:bar) raise "boom" end end message = run_and_capture_reported_message(group) expect(message).to be_nil end it "leaves a raised exception unmodified (GH-1103)" do # set the backtrace, otherwise MRI will build a whole new object, # and thus mess with our expectations. Rubinius and JRuby are not # affected. exception = StandardError.new exception.set_backtrace([]) group = RSpec::Core::ExampleGroup.describe do example { raise exception.freeze } end group.run actual = group.examples.first.metadata[:execution_result][:exception] expect(actual.__id__).to eq(exception.__id__) end end end describe "#pending" do context "in the example" do it "sets the example to pending" do group = RSpec::Core::ExampleGroup.describe do example { pending } end group.run expect(group.examples.first).to be_pending end it "allows post-example processing in around hooks (see https://github.com/rspec/rspec-core/issues/322)" do blah = nil group = RSpec::Core::ExampleGroup.describe do around do |example| example.run blah = :success end example { pending } end group.run expect(blah).to be(:success) end context "with a block" do it "sets the example to pending if block fails" do group = RSpec::Core::ExampleGroup.describe do example do pending { expect(1).to eq(2) } end end group.run expect(group.examples.first.metadata[:execution_result][:status]).to eq('pending') expect(group.examples.first.metadata[:execution_result][:pending_fixed]).to eq(false) end it "fails if block is fixed, i.e. does not raise" do group = RSpec::Core::ExampleGroup.describe do example do pending {} end end group.run expect(group.examples.first.metadata[:execution_result][:status]).to eq('failed') expect(group.examples.first.metadata[:execution_result][:pending_fixed]).to eq(true) end end end context "in before(:each)" do it "sets each example to pending" do group = RSpec::Core::ExampleGroup.describe do before(:each) { pending } example {} example {} end group.run expect(group.examples.first).to be_pending expect(group.examples.last).to be_pending end end context "in before(:all)" do it "sets each example to pending" do group = RSpec::Core::ExampleGroup.describe do before(:all) { pending } example {} example {} end group.run expect(group.examples.first).to be_pending expect(group.examples.last).to be_pending end end context "in around(:each)" do it "sets the example to pending" do group = RSpec::Core::ExampleGroup.describe do around(:each) { pending } example {} end group.run expect(group.examples.first).to be_pending end end end describe "timing" do it "uses RSpec::Core::Time as to not be affected by changes to time in examples" do reporter = double(:reporter).as_null_object group = RSpec::Core::ExampleGroup.describe example = group.example example.__send__ :start, reporter Time.stub(:now => Time.utc(2012, 10, 1)) example.__send__ :finish, reporter expect(example.metadata[:execution_result][:run_time]).to be < 0.2 end end it "does not interfere with per-example randomness when running examples in a random order" do values = [] RSpec.configuration.order = :random RSpec::Core::ExampleGroup.describe do # The bug was only triggered when the examples # were in nested contexts; see https://github.com/rspec/rspec-core/pull/837 context { example { values << rand } } context { example { values << rand } } end.run expect(values.uniq).to have(2).values end describe "optional block argument" do it "contains the example" do |ex| expect(ex).to be_an(RSpec::Core::Example) expect(ex.description).to match(/contains the example/) end end %w[example running_example].each do |accessor| describe accessor do before { allow_deprecation } it "is deprecated" do expect_warn_deprecation_with_call_site(__FILE__, __LINE__ + 1, /#{accessor}/) send(accessor) end it "returns the current running example" do |ex| expect(send(accessor)).to eq ex end end end describe "setting the current example" do it "sets RSpec.current_example to the example that is currently running" do group = RSpec::Core::ExampleGroup.describe("an example group") current_examples = [] example1 = group.example("example 1") { current_examples << RSpec.current_example } example2 = group.example("example 2") { current_examples << RSpec.current_example } group.run expect(current_examples).to eq([example1, example2]) end end end
{ "content_hash": "9fc44170a7cfc10a59baaebdbc389ba4", "timestamp": "", "source": "github", "line_count": 502, "max_line_length": 113, "avg_line_length": 33.48207171314741, "alnum_prop": 0.6109590671108995, "repo_name": "sghill/gocd", "id": "3fc4c982c20f12982eb70af94e68377fc1d68abb", "size": "16808", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "server/webapp/WEB-INF/rails.new/vendor/bundle/jruby/1.9/gems/rspec-core-2.99.2/spec/rspec/core/example_spec.rb", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Batchfile", "bytes": "8229" }, { "name": "CSS", "bytes": "527466" }, { "name": "FreeMarker", "bytes": "182" }, { "name": "HTML", "bytes": "642918" }, { "name": "Java", "bytes": "15199526" }, { "name": "JavaScript", "bytes": "2736266" }, { "name": "NSIS", "bytes": "19022" }, { "name": "PowerShell", "bytes": "743" }, { "name": "Ruby", "bytes": "2661293" }, { "name": "SQLPL", "bytes": "9050" }, { "name": "Shell", "bytes": "239120" }, { "name": "XSLT", "bytes": "147495" } ], "symlink_target": "" }
package org.terracotta.offheapresource.management; import org.terracotta.management.service.monitoring.registry.provider.AliasBinding; import org.terracotta.offheapresource.OffHeapResource; public class OffHeapResourceBinding extends AliasBinding { public OffHeapResourceBinding(String identifier, OffHeapResource offHeapResource) { super(identifier, offHeapResource); } @Override public OffHeapResource getValue() { return (OffHeapResource) super.getValue(); } }
{ "content_hash": "ae900143175fd5cd63a34b9536e8b80a", "timestamp": "", "source": "github", "line_count": 18, "max_line_length": 85, "avg_line_length": 27.11111111111111, "alnum_prop": 0.8094262295081968, "repo_name": "jd0-sag/terracotta-platform", "id": "1b5f6d8c17dbf43c559b0416bec0b5e7e049d830", "size": "1082", "binary": false, "copies": "9", "ref": "refs/heads/master", "path": "offheap-resource/src/main/java/org/terracotta/offheapresource/management/OffHeapResourceBinding.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Java", "bytes": "1182422" } ], "symlink_target": "" }
using System; namespace SharpDX.Direct3D10 { /// <summary> /// Defines possible character sets for fonts. /// </summary> /// <unmanaged>CHARSET</unmanaged> public enum FontCharacterSet : byte { /// <summary> /// The ANSI character set. /// </summary> Ansi = 0, /// <summary> /// The Arabic character set. /// </summary> Arabic = 0xb2, /// <summary> /// The Baltic character set. /// </summary> Baltic = 0xba, /// <summary> /// The Chinese character set. /// </summary> ChineseBig5 = 0x88, /// <summary> /// The default system character set. /// </summary> Default = 1, /// <summary> /// The East Europe character set. /// </summary> EastEurope = 0xee, /// <summary> /// The GB2312 character set. /// </summary> GB2312 = 0x86, /// <summary> /// The Greek character set. /// </summary> Greek = 0xa1, /// <summary> /// The Hangul character set. /// </summary> Hangul = 0x81, /// <summary> /// The Hebrew character set. /// </summary> Hebrew = 0xb1, /// <summary> /// The Johab character set. /// </summary> Johab = 130, /// <summary> /// The Mac character set. /// </summary> Mac = 0x4d, /// <summary> /// The OEM character set. /// </summary> Oem = 0xff, /// <summary> /// The Russian character set. /// </summary> Russian = 0xcc, /// <summary> /// The ShiftJIS character set. /// </summary> ShiftJIS = 0x80, /// <summary> /// The symbol character set. /// </summary> Symbol = 2, /// <summary> /// The Thai character set. /// </summary> Thai = 0xde, /// <summary> /// The Turkish character set. /// </summary> Turkish = 0xa2, /// <summary> /// The Vietnamese character set. /// </summary> Vietnamese = 0xa3 } }
{ "content_hash": "9cc1a285bb9c34cf9eacaafed625b92b", "timestamp": "", "source": "github", "line_count": 88, "max_line_length": 50, "avg_line_length": 25.511363636363637, "alnum_prop": 0.44587973273942094, "repo_name": "sharpdx/SharpDX", "id": "e32d94e128a3a19ee0a6f94d5086b8060ac0336a", "size": "3376", "binary": false, "copies": "7", "ref": "refs/heads/master", "path": "Source/SharpDX.Direct3D10/FontCharacterSet.cs", "mode": "33188", "license": "mit", "language": [ { "name": "Batchfile", "bytes": "166" }, { "name": "C", "bytes": "68666" }, { "name": "C#", "bytes": "13812632" }, { "name": "C++", "bytes": "728545" }, { "name": "Rich Text Format", "bytes": "21390" } ], "symlink_target": "" }
package org.jdal.logic; import java.sql.SQLException; import java.sql.Statement; import javax.sql.DataSource; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.springframework.dao.DataAccessException; import org.springframework.jdbc.core.JdbcTemplate; import org.springframework.jdbc.core.SqlProvider; import org.springframework.jdbc.core.StatementCallback; /** * @author Jose Luis Martin - (jlm@joseluismartin.info) * */ public class DbAdminManagerSupport { private static final Log log = LogFactory.getLog(DbAdminManagerSupport.class); private DataSource dataSource; private JdbcTemplate template; public boolean execute(final String sql) throws DataAccessException { if (log.isDebugEnabled()) { log.debug("Executing SQL statement [" + sql + "]"); } class ExecuteStatementCallback implements StatementCallback<Boolean>, SqlProvider { public Boolean doInStatement(Statement stmt) throws SQLException { return stmt.execute(sql); } public String getSql() { return sql; } } return template.execute(new ExecuteStatementCallback()); } /** * @return the dataSource */ public DataSource getDataSource() { return dataSource; } /** * @param dataSource the dataSource to set */ public void setDataSource(DataSource dataSource) { this.dataSource = dataSource; } /** * @return the template */ public JdbcTemplate getTemplate() { return template; } /** * @param template the template to set */ public void setTemplate(JdbcTemplate template) { this.template = template; } }
{ "content_hash": "16012f2aabddf6cdb8f37ee574ba280f", "timestamp": "", "source": "github", "line_count": 71, "max_line_length": 85, "avg_line_length": 22.577464788732396, "alnum_prop": 0.7398627573300063, "repo_name": "chelu/jdal", "id": "0505e05347f26403f3a261eb5889cde68fe8d4e7", "size": "2223", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "core/src/main/java/org/jdal/logic/DbAdminManagerSupport.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "AspectJ", "bytes": "4370" }, { "name": "Java", "bytes": "1337330" }, { "name": "JavaScript", "bytes": "1503" } ], "symlink_target": "" }
package com.amazonaws.services.lookoutforvision.model.transform; import java.math.*; import javax.annotation.Generated; import com.amazonaws.services.lookoutforvision.model.*; import com.amazonaws.transform.SimpleTypeJsonUnmarshallers.*; import com.amazonaws.transform.*; import com.fasterxml.jackson.core.JsonToken; import static com.fasterxml.jackson.core.JsonToken.*; /** * CreateDatasetResult JSON Unmarshaller */ @Generated("com.amazonaws:aws-java-sdk-code-generator") public class CreateDatasetResultJsonUnmarshaller implements Unmarshaller<CreateDatasetResult, JsonUnmarshallerContext> { public CreateDatasetResult unmarshall(JsonUnmarshallerContext context) throws Exception { CreateDatasetResult createDatasetResult = new CreateDatasetResult(); int originalDepth = context.getCurrentDepth(); String currentParentElement = context.getCurrentParentElement(); int targetDepth = originalDepth + 1; JsonToken token = context.getCurrentToken(); if (token == null) token = context.nextToken(); if (token == VALUE_NULL) { return createDatasetResult; } while (true) { if (token == null) break; if (token == FIELD_NAME || token == START_OBJECT) { if (context.testExpression("DatasetMetadata", targetDepth)) { context.nextToken(); createDatasetResult.setDatasetMetadata(DatasetMetadataJsonUnmarshaller.getInstance().unmarshall(context)); } } else if (token == END_ARRAY || token == END_OBJECT) { if (context.getLastParsedParentElement() == null || context.getLastParsedParentElement().equals(currentParentElement)) { if (context.getCurrentDepth() <= originalDepth) break; } } token = context.nextToken(); } return createDatasetResult; } private static CreateDatasetResultJsonUnmarshaller instance; public static CreateDatasetResultJsonUnmarshaller getInstance() { if (instance == null) instance = new CreateDatasetResultJsonUnmarshaller(); return instance; } }
{ "content_hash": "88bfc704426b6a9200e6d30d4aa9a4ae", "timestamp": "", "source": "github", "line_count": 63, "max_line_length": 136, "avg_line_length": 35.857142857142854, "alnum_prop": 0.6622399291722001, "repo_name": "aws/aws-sdk-java", "id": "efa62a1e579dc802bc807c11d6febb105aac390e", "size": "2839", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "aws-java-sdk-lookoutforvision/src/main/java/com/amazonaws/services/lookoutforvision/model/transform/CreateDatasetResultJsonUnmarshaller.java", "mode": "33188", "license": "apache-2.0", "language": [], "symlink_target": "" }
module Smartcoin class SmartcoinError < StandardError attr_reader :http_status, :json_message, :http_message, :message def initialize(http_status=nil, json_message=nil, http_message=nil, message=nil) @http_status = http_status @json_message = json_message @http_message = http_message @message = message end end end
{ "content_hash": "31d17dd1da4494f02ac7d7281293f75b", "timestamp": "", "source": "github", "line_count": 12, "max_line_length": 84, "avg_line_length": 29.666666666666668, "alnum_prop": 0.6938202247191011, "repo_name": "smartcoinpayments/smartcoin-ruby", "id": "8090120aba4e12d387de0d8607e4a52996debc91", "size": "356", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "lib/smartcoin/errors/smartcoin_error.rb", "mode": "33188", "license": "mit", "language": [ { "name": "Ruby", "bytes": "31318" } ], "symlink_target": "" }
using System; using System.IO; using System.Diagnostics; namespace SteamBot { public class Log : IDisposable { public enum LogLevel { Debug, Info, Success, Warn, Error, Interface, // if the user needs to input something Nothing // not recommended; it basically silences // the console output because nothing is // greater than it. even if the bot needs // input, it won't be shown in the console. } protected StreamWriter _FileStream; protected string _Bot; public LogLevel OutputToConsole; public ConsoleColor DefaultConsoleColor = ConsoleColor.White; public Log (string logFile, string botName = "", LogLevel output = LogLevel.Info) { _FileStream = File.AppendText (logFile); _FileStream.AutoFlush = true; _Bot = botName; OutputToConsole = output; Console.ForegroundColor = DefaultConsoleColor; } public void Dispose() { _FileStream.Dispose(); } // This outputs a log entry of the level info. public void Info (string data) { _OutputLine (LogLevel.Info, data); } // This outputs a log entry of the level debug. public void Debug (string data) { _OutputLine (LogLevel.Debug, data); } // This outputs a log entry of the level success. public void Success (string data) { _OutputLine (LogLevel.Success, data); } // This outputs a log entry of the level warn. public void Warn (string data) { _OutputLine (LogLevel.Warn, data); } // This outputs a log entry of the level error. public void Error (string data) { _OutputLine (LogLevel.Error, data); } // This outputs a log entry of the level interface; // normally, this means that some sort of user interaction // is required. public void Interface (string data) { _OutputLine (LogLevel.Interface, data); } // Outputs a line to both the log and the console, if // applicable. protected void _OutputLine (LogLevel level, string line) { string formattedString = String.Format ( "[{0} {1}] {2}: {3}", (_Bot == null ? "(System)" : _Bot), DateTime.Now.ToString ("yyyy-MM-dd HH:mm:ss"), _LogLevel (level).ToUpper (), line ); _FileStream.WriteLine (formattedString); if (level >= OutputToConsole) _OutputLineToConsole (level, formattedString); } // Outputs a line to the console, with the correct color // formatting. protected void _OutputLineToConsole (LogLevel level, string line) { Console.ForegroundColor = _LogColor (level); System.Diagnostics.Debug.WriteLine(line); Console.ForegroundColor = DefaultConsoleColor; } // Determine the string equivalent of the LogLevel. protected string _LogLevel (LogLevel level) { switch (level) { case LogLevel.Info: return "info"; case LogLevel.Debug: return "debug"; case LogLevel.Success: return "success"; case LogLevel.Warn: return "warn"; case LogLevel.Error: return "error"; case LogLevel.Interface: return "interface"; case LogLevel.Nothing: return "nothing"; default: return "undef"; } } // Determine the color to be used when outputting to the // console. protected ConsoleColor _LogColor (LogLevel level) { switch (level) { case LogLevel.Info: case LogLevel.Debug: return ConsoleColor.White; case LogLevel.Success: return ConsoleColor.Green; case LogLevel.Warn: return ConsoleColor.Yellow; case LogLevel.Error: return ConsoleColor.Red; case LogLevel.Interface: return ConsoleColor.DarkCyan; default: return DefaultConsoleColor; } } } }
{ "content_hash": "0ecdff722e4df5d8af52614fda6bb0df", "timestamp": "", "source": "github", "line_count": 153, "max_line_length": 89, "avg_line_length": 30.49673202614379, "alnum_prop": 0.5222888984140591, "repo_name": "narugo/PonyBot", "id": "5ead4a88b5723dab2543896ee72adef2440709d9", "size": "4666", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "SteamBot/Log.cs", "mode": "33188", "license": "mit", "language": [], "symlink_target": "" }
require 'rubygems' require 'bundler/setup' require 'faye/websocket' require 'eventmachine' EM.run { url = ARGV[0] headers = {'Origin' => 'http://faye.jcoglan.com'} proxy = {:origin => ARGV[1], :headers => {'User-Agent' => 'Echo'}} ws = Faye::WebSocket::Client.new(url, nil, :headers => headers, :proxy => proxy) ws.onopen = lambda do |event| p [:open, ws.headers] ws.send('mic check') end ws.onclose = lambda do |close| p [:close, close.code, close.reason] EM.stop end ws.onerror = lambda do |error| p [:error, error.message] end ws.onmessage = lambda do |message| p [:message, message.data] end }
{ "content_hash": "42d67e538c9381af1170c474999fbc84", "timestamp": "", "source": "github", "line_count": 29, "max_line_length": 87, "avg_line_length": 22.82758620689655, "alnum_prop": 0.6148036253776435, "repo_name": "rogerheykoop/RailsParallelDomainChecker", "id": "bcab0229bdf5a1852799bcb902b7962d6d7ce781", "size": "662", "binary": false, "copies": "3", "ref": "refs/heads/master", "path": "vendor/cache/ruby/2.1.0/gems/faye-websocket-0.9.2/examples/client.rb", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "1173" }, { "name": "CoffeeScript", "bytes": "422" }, { "name": "JavaScript", "bytes": "16060" }, { "name": "Ruby", "bytes": "50895" } ], "symlink_target": "" }
<p> <?php echo link_to('プライバシーポリシー', 'default/privacyPolicy', array('target' => '_blank')); ?> <?php echo link_to('利用規約', 'default/userAgreement', array('target' => '_blank')); ?> <?php $snsConfigSettings = sfConfig::get('openpne_sns_config'); ?> <?php if (opToolkit::isSecurePage()) : ?> <?php echo Doctrine::getTable('SnsConfig')->get('footer_after', $snsConfigSettings['footer_after']['Default']); ?> <?php else: ?> <?php echo Doctrine::getTable('SnsConfig')->get('footer_before', $snsConfigSettings['footer_before']['Default']); ?> <?php endif; ?> </p>
{ "content_hash": "22b35797b68fd54054fb4fd85b4948c0", "timestamp": "", "source": "github", "line_count": 10, "max_line_length": 116, "avg_line_length": 55.9, "alnum_prop": 0.6547406082289803, "repo_name": "tejimaya/OpenPNE3", "id": "d7f2b965ed9ba035720e2fb1843ec9dd2f98cdf3", "size": "587", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "apps/pc_frontend/templates/_footer.php", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "CSS", "bytes": "115036" }, { "name": "JavaScript", "bytes": "99989" }, { "name": "PHP", "bytes": "1611460" } ], "symlink_target": "" }
mitlru ====== Simple thread-safe sizeable LRU cache (maps interface{} to interface{}). Simple, small, 100% test coverage, MIT licensed. [Documentation](http://godoc.org/github.com/robmccoll/mitlru)
{ "content_hash": "569c745969f6f2b65ff439ed0a863e50", "timestamp": "", "source": "github", "line_count": 8, "max_line_length": 72, "avg_line_length": 25.125, "alnum_prop": 0.736318407960199, "repo_name": "robmccoll/mitlru", "id": "fc9d3ecfb1494ea22a78ddc9d743b963c3c10c8c", "size": "201", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "README.md", "mode": "33188", "license": "mit", "language": [ { "name": "Go", "bytes": "24401" } ], "symlink_target": "" }
package terrastore.communication.protocol; import java.io.IOException; import java.util.Collections; import java.util.HashMap; import java.util.HashSet; import java.util.Map; import java.util.Set; import org.msgpack.MessageTypeException; import org.msgpack.Packer; import org.msgpack.Unpacker; import terrastore.communication.CommunicationException; import terrastore.communication.Node; import terrastore.communication.ProcessingException; import terrastore.router.MissingRouteException; import terrastore.router.Router; import terrastore.store.Bucket; import terrastore.store.Key; import terrastore.store.Store; import terrastore.store.StoreOperationException; import terrastore.store.Value; import terrastore.store.features.Predicate; import terrastore.util.collect.Maps; import terrastore.util.io.MsgPackUtils; /** * @author Sergio Bossa */ public class PutValuesCommand extends AbstractCommand<Set<Key>> { private String bucketName; private Map<Key, Value> values; public PutValuesCommand(String bucketName, Map<Key, Value> values) { this.bucketName = bucketName; this.values = values; } public PutValuesCommand() { } @Override public Response<Set<Key>> executeOn(Router router) throws CommunicationException, MissingRouteException, ProcessingException { Map<Node, Set<Key>> nodeToKeys = router.routeToNodesFor(bucketName, values.keySet()); Set<Key> result = new HashSet<Key>(); for (Map.Entry<Node, Set<Key>> nodeToKeysEntry : nodeToKeys.entrySet()) { Node node = nodeToKeysEntry.getKey(); Set<Key> nodeKeys = nodeToKeysEntry.getValue(); PutValuesCommand command = new PutValuesCommand(bucketName, Maps.slice(values, nodeKeys)); result.addAll(node.<Set<Key>>send(command)); } return new KeysResponse(id, result); } public Response<Set<Key>> executeOn(Store store) throws StoreOperationException { Bucket bucket = store.getOrCreate(bucketName); Set<Key> insertedKeys = new HashSet<Key>(); for (Map.Entry<Key, Value> entry : values.entrySet()) { bucket.put(entry.getKey(), entry.getValue()); insertedKeys.add(entry.getKey()); } return new KeysResponse(id, insertedKeys); } @Override protected void doSerialize(Packer packer) throws IOException { MsgPackUtils.packString(packer, bucketName); MsgPackUtils.packValues(packer, values); } @Override protected void doDeserialize(Unpacker unpacker) throws IOException, MessageTypeException { bucketName = MsgPackUtils.unpackString(unpacker); values = MsgPackUtils.unpackValues(unpacker); } }
{ "content_hash": "7fd19ede75ea4b642fe016dfdfe5dc3c", "timestamp": "", "source": "github", "line_count": 77, "max_line_length": 130, "avg_line_length": 35.311688311688314, "alnum_prop": 0.7234277307833762, "repo_name": "xingh/terrastore", "id": "88ad77654a5a683d668d3b2ea70f040c2fb7675c", "size": "3374", "binary": false, "copies": "3", "ref": "refs/heads/master", "path": "src/main/java/terrastore/communication/protocol/PutValuesCommand.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "HTML", "bytes": "9116" }, { "name": "Java", "bytes": "1239945" }, { "name": "JavaScript", "bytes": "17488" }, { "name": "Shell", "bytes": "1134" } ], "symlink_target": "" }
<?xml version="1.0" encoding="utf-8"?> <android.support.v7.widget.CardView android:id="@+id/card_view" xmlns:android="http://schemas.android.com/apk/res/android" xmlns:card_view="http://schemas.android.com/apk/res-auto" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_margin="4dp" android:clipChildren="false" android:clipToPadding="false" android:elevation="4dp" card_view:cardCornerRadius="4dp"> <RelativeLayout android:layout_width="match_parent" android:layout_height="wrap_content" android:clipChildren="false" android:clipToPadding="false" android:padding="8dp" android:translationZ="100dp"> <TextView android:id="@+id/faction_name_text" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_centerHorizontal="true" android:fontFamily="serif" android:gravity="center" android:text="Faction" android:textAlignment="center" android:textColor="@color/colorPrimaryText" android:textSize="19sp" android:textStyle="bold"/> <TextView android:id="@+id/faction_description_text" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_below="@+id/faction_name_text" android:layout_centerHorizontal="true" android:layout_marginBottom="8dp" android:layout_marginTop="8dp" android:fontFamily="sans-serif-condensed" android:gravity="center" android:paddingEnd="8dp" android:paddingStart="8dp" android:text="Description" android:textAlignment="center" android:textColor="@color/colorSecondaryText" android:textSize="16sp"/> <RelativeLayout android:layout_width="300dp" android:layout_height="wrap_content" android:layout_below="@+id/faction_description_text" android:layout_centerHorizontal="true" android:clipChildren="false" android:clipToPadding="false" android:translationZ="100dp"> <ImageView android:id="@+id/leader1_image" android:layout_width="90dp" android:layout_height="wrap_content" android:layout_alignParentStart="true" android:layout_marginEnd="22dp" android:elevation="10dp" android:focusable="true" android:focusableInTouchMode="true" android:tag="0" android:translationZ="100dp"/> <ImageView android:id="@+id/leader2_image" android:layout_width="90dp" android:layout_height="wrap_content" android:layout_centerHorizontal="true" android:layout_marginEnd="22dp" android:layout_marginStart="22dp" android:elevation="10dp" android:focusable="true" android:focusableInTouchMode="true" android:tag="1" android:translationZ="100dp"/> <ImageView android:id="@+id/leader3_image" android:layout_width="90dp" android:layout_height="wrap_content" android:layout_alignParentEnd="true" android:layout_marginStart="22dp" android:elevation="10dp" android:focusable="true" android:focusableInTouchMode="true" android:tag="2" android:translationZ="100dp"/> </RelativeLayout> </RelativeLayout> </android.support.v7.widget.CardView>
{ "content_hash": "4d4aa1cea16a72c661f88d44717e88f3", "timestamp": "", "source": "github", "line_count": 100, "max_line_length": 64, "avg_line_length": 38.93, "alnum_prop": 0.5810428975083484, "repo_name": "bachhuberdesign/deck-builder-gwent", "id": "4977ccd4e6504293cba2d5df0f3d7120345ed6af", "size": "3893", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "app/src/main/res/layout/item_faction.xml", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Java", "bytes": "61966" }, { "name": "Kotlin", "bytes": "173997" } ], "symlink_target": "" }
package examples.stateless; import java.util.Collection; import examples.model.Employee; public interface EmployeeService { public Employee createEmployee(String name, long salary); public Employee addEmployeeNickname(int empId, String nickname); public Collection<Employee> findAllEmployees(); }
{ "content_hash": "85b8214fb1bb30cc5690e7ba5f7fed24", "timestamp": "", "source": "github", "line_count": 11, "max_line_length": 68, "avg_line_length": 28.363636363636363, "alnum_prop": 0.7948717948717948, "repo_name": "velmuruganvelayutham/jpa", "id": "a333a14b92425f6feca0aa52102d5dbde591e602", "size": "312", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "examples/Chapter5/2-overrideCollectionTableColumn/src/model/examples/stateless/EmployeeService.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Java", "bytes": "831359" }, { "name": "Shell", "bytes": "8424" } ], "symlink_target": "" }
using System; using System.Collections.Generic; namespace Hydra.HydraCommon.Abstract { /// <summary> /// HydraMonoBehaviourChild provides methods similar to ScriptableObject. /// </summary> public class HydraMonoBehaviourChild { private List<HydraMonoBehaviourChild> m_MonoBehaviourChildren; public enum Message { OnUpdate, OnEnable, OnDisable, OnDestroy, OnReset } #region Methods /// <summary> /// Calls OnUpdate(). /// </summary> /// <param name="parent">Parent.</param> public void Update(HydraMonoBehaviour parent) { OnUpdate(parent); } /// <summary> /// Calls OnReset(). /// </summary> /// <param name="parent">Parent.</param> public void Reset(HydraMonoBehaviour parent) { OnReset(parent); } /// <summary> /// Calls OnEnable(). /// </summary> /// <param name="parent">Parent.</param> public void Enable(HydraMonoBehaviour parent) { OnEnable(parent); } /// <summary> /// Calls OnDisable(). /// </summary> /// <param name="parent">Parent.</param> public void Disable(HydraMonoBehaviour parent) { OnDisable(parent); } /// <summary> /// Calls OnDestroy(). /// </summary> /// <param name="parent">Parent.</param> public void Destroy(HydraMonoBehaviour parent) { OnDestroy(parent); } #endregion #region Protected Methods /// <summary> /// Called when the parent updates. /// </summary> protected virtual void OnUpdate(HydraMonoBehaviour parent) { ProcessMessage(parent, Message.OnUpdate); } /// <summary> /// Called to reset the instance to default values. /// </summary> protected virtual void OnReset(HydraMonoBehaviour parent) { ProcessMessage(parent, Message.OnReset); } /// <summary> /// Called when the parent is about to be destroyed. /// </summary> protected virtual void OnDestroy(HydraMonoBehaviour parent) { ProcessMessage(parent, Message.OnDestroy); } /// <summary> /// Called when the parent is enabled. /// </summary> protected virtual void OnEnable(HydraMonoBehaviour parent) { ProcessMessage(parent, Message.OnEnable); } /// <summary> /// Called when the parent is disabled. /// </summary> protected virtual void OnDisable(HydraMonoBehaviour parent) { ProcessMessage(parent, Message.OnDisable); } /// <summary> /// Override this method to return any HydraMonoBehaviourChild instances. /// </summary> /// <returns>The mono behaviour children.</returns> protected virtual List<HydraMonoBehaviourChild> GetMonoBehaviourChildren() { if (m_MonoBehaviourChildren == null) m_MonoBehaviourChildren = new List<HydraMonoBehaviourChild>(); m_MonoBehaviourChildren.Clear(); return m_MonoBehaviourChildren; } /// <summary> /// Processes the message. /// </summary> /// <param name="message">Message.</param> private void ProcessMessage(HydraMonoBehaviour parent, Message message) { ProcessMessage(GetMonoBehaviourChildren(), parent, message); } #endregion /// <summary> /// Creates the instance. /// </summary> /// <returns>The instance.</returns> /// <param name="parent">Parent.</param> /// <typeparam name="T">The instance type.</typeparam> public static T CreateInstance<T>(HydraMonoBehaviour parent) where T : HydraMonoBehaviourChild, new() { T output = new T(); output.Enable(parent); return output; } /// <summary> /// Processes the message. /// </summary> /// <param name="children">Children.</param> /// <param name="parent">Parent.</param> /// <param name="message">Message.</param> public static void ProcessMessage(List<HydraMonoBehaviourChild> children, HydraMonoBehaviour parent, Message message) { for (int index = 0; index < children.Count; index++) { HydraMonoBehaviourChild child = children[index]; if (child == null) continue; switch (message) { case Message.OnUpdate: child.Update(parent); break; case Message.OnDestroy: child.Destroy(parent); break; case Message.OnDisable: child.Disable(parent); break; case Message.OnEnable: child.Enable(parent); break; case Message.OnReset: child.Reset(parent); break; default: throw new ArgumentOutOfRangeException(); } } } } }
{ "content_hash": "5f3a45de951c947c0f46f1eafef34873", "timestamp": "", "source": "github", "line_count": 190, "max_line_length": 119, "avg_line_length": 22.878947368421052, "alnum_prop": 0.6602254428341385, "repo_name": "TeamSpatch/EndoWars", "id": "ca61bb3a9df10d2e3052554917bacaed8026f370", "size": "4504", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "Assets/Hydra/HydraCommon/Scripts/Abstract/HydraMonoBehaviourChild.cs", "mode": "33188", "license": "bsd-3-clause", "language": [ { "name": "C#", "bytes": "541822" } ], "symlink_target": "" }
 (function() { /** * Represents a list os CKEDITOR.dom.range objects, which can be easily * iterated sequentially. * @constructor * @param {CKEDITOR.dom.range|Array} [ranges] The ranges contained on this list. * Note that, if an array of ranges is specified, the range sequence * should match its DOM order. This class will not help to sort them. */ CKEDITOR.dom.rangeList = function( ranges ) { if ( ranges instanceof CKEDITOR.dom.rangeList ) return ranges; if ( !ranges ) ranges = []; else if ( ranges instanceof CKEDITOR.dom.range ) ranges = [ ranges ]; return CKEDITOR.tools.extend( ranges, mixins ); }; var mixins = /** @lends CKEDITOR.dom.rangeList.prototype */ { /** * Creates an instance of the rangeList iterator, it should be used * only when the ranges processing could be DOM intrusive, which * means it may pollute and break other ranges in this list. * Otherwise, it's enough to just iterate over this array in a for loop. * @returns {CKEDITOR.dom.rangeListIterator} */ createIterator : function() { var rangeList = this, bookmarks = [], current; /** * @lends CKEDITOR.dom.rangeListIterator.prototype */ return { /** * Retrieves the next range in the list. */ getNextRange : function() { current = current == undefined ? 0 : current + 1; var range = rangeList[ current ]; // Multiple ranges might be mangled by each other. if ( range && rangeList.length > 1 ) { // Bookmarking all other ranges on the first iteration, // the range correctness after it doesn't matter since we'll // restore them before the next iteration. if ( !current ) { // Make sure bookmark correctness by reverse processing. for ( var i = rangeList.length - 1; i > 0; i-- ) bookmarks.unshift( rangeList[ i ].createBookmark( true ) ); } else range.moveToBookmark( bookmarks.shift() ); } return range; } }; }, createBookmarks : function( serializable ) { var retval = [], bookmark; for ( var i = 0; i < this.length ; i++ ) { retval.push( bookmark = this[ i ].createBookmark( serializable, true) ); // Updating the container & offset values for ranges // that have been touched. for ( var j = i + 1; j < this.length; j++ ) { this[ j ] = updateDirtyRange( bookmark, this[ j ] ); this[ j ] = updateDirtyRange( bookmark, this[ j ], true ); } } return retval; }, createBookmarks2 : function( normalized ) { var bookmarks = []; for ( var i = 0 ; i < this.length ; i++ ) bookmarks.push( this[ i ].createBookmark2( normalized ) ); return bookmarks; }, /** * Move each range in the list to the position specified by a list of bookmarks. * @param {Array} bookmarks The list of bookmarks, each one matching a range in the list. */ moveToBookmarks : function( bookmarks ) { for ( var i = 0 ; i < this.length ; i++ ) this[ i ].moveToBookmark( bookmarks[ i ] ); } }; // Update the specified range which has been mangled by previous insertion of // range bookmark nodes.(#3256) function updateDirtyRange( bookmark, dirtyRange, checkEnd ) { var serializable = bookmark.serializable, container = dirtyRange[ checkEnd ? 'endContainer' : 'startContainer' ], offset = checkEnd ? 'endOffset' : 'startOffset'; var bookmarkStart = serializable ? dirtyRange.document.getById( bookmark.startNode ) : bookmark.startNode; var bookmarkEnd = serializable ? dirtyRange.document.getById( bookmark.endNode ) : bookmark.endNode; if ( container.equals( bookmarkStart.getPrevious() ) ) { dirtyRange.startOffset = dirtyRange.startOffset - container.getLength() - bookmarkEnd.getPrevious().getLength(); container = bookmarkEnd.getNext(); } else if ( container.equals( bookmarkEnd.getPrevious() ) ) { dirtyRange.startOffset = dirtyRange.startOffset - container.getLength(); container = bookmarkEnd.getNext(); } container.equals( bookmarkStart.getParent() ) && dirtyRange[ offset ]++; container.equals( bookmarkEnd.getParent() ) && dirtyRange[ offset ]++; // Update and return this range. dirtyRange[ checkEnd ? 'endContainer' : 'startContainer' ] = container; return dirtyRange; } })(); /** * (Virtual Class) Do not call this constructor. This class is not really part * of the API. It just describes the return type of {@link CKEDITOR.dom.rangeList#createIterator}. * @name CKEDITOR.dom.rangeListIterator * @constructor * @example */
{ "content_hash": "59ae5e97b09c6157b68a11f22fc11194", "timestamp": "", "source": "github", "line_count": 160, "max_line_length": 98, "avg_line_length": 29.29375, "alnum_prop": 0.6430552592276509, "repo_name": "hgabka/KunstmaanBundlesCMS", "id": "f85cc7de46c5075cd0b1e3b1e0181424e7489b5e", "size": "4833", "binary": false, "copies": "12", "ref": "refs/heads/master", "path": "src/Kunstmaan/AdminBundle/Resources/public/default-theme/ckeditor/_source/core/dom/rangelist.js", "mode": "33188", "license": "mit", "language": [ { "name": "ASP", "bytes": "46244" }, { "name": "CSS", "bytes": "468600" }, { "name": "Gherkin", "bytes": "22178" }, { "name": "HTML", "bytes": "934141" }, { "name": "Hack", "bytes": "20" }, { "name": "JavaScript", "bytes": "4087160" }, { "name": "PHP", "bytes": "2946789" }, { "name": "Ruby", "bytes": "2363" }, { "name": "Shell", "bytes": "235" } ], "symlink_target": "" }
package com.commonsware.android.wakecast; import android.app.AlarmManager; import android.app.PendingIntent; import android.content.Context; import android.content.Intent; import android.os.SystemClock; import android.support.v4.content.WakefulBroadcastReceiver; public class PollReceiver extends WakefulBroadcastReceiver { private static final int PERIOD=900000; // 15 minutes private static final int INITIAL_DELAY=5000; // 5 seconds @Override public void onReceive(Context ctxt, Intent i) { if (i.getAction() == null) { startWakefulService(ctxt, new Intent(ctxt, ScheduledService.class)); } else { scheduleAlarms(ctxt); } } static void scheduleAlarms(Context ctxt) { AlarmManager mgr= (AlarmManager)ctxt.getSystemService(Context.ALARM_SERVICE); Intent i=new Intent(ctxt, PollReceiver.class); PendingIntent pi=PendingIntent.getBroadcast(ctxt, 0, i, 0); mgr.setRepeating(AlarmManager.ELAPSED_REALTIME_WAKEUP, SystemClock.elapsedRealtime() + INITIAL_DELAY, PERIOD, pi); } }
{ "content_hash": "4ed5bd7e742f01446d93fd7d72fa2b09", "timestamp": "", "source": "github", "line_count": 38, "max_line_length": 68, "avg_line_length": 29.36842105263158, "alnum_prop": 0.703405017921147, "repo_name": "krovs/cw-omnibus", "id": "737fcb7da92577098484b8452c6455cd0f8bcd61", "size": "1788", "binary": false, "copies": "7", "ref": "refs/heads/master", "path": "AlarmManager/WakeCast/src/com/commonsware/android/wakecast/PollReceiver.java", "mode": "33188", "license": "apache-2.0", "language": [], "symlink_target": "" }
/* * Constraint.java * * Created on 8. August 2005, 22:08 */ package de.tub.eyes.apps.PS; /** * * @author Till Wimmer */ public class Constraint implements java.io.Serializable { int attributeID; int operationID; long value; public Constraint() { } public Constraint(int attributeID, int operationID, long value) { this.attributeID = attributeID; this.operationID = operationID; this.value = value; } public int getAttributeID() { return attributeID; } public int getOperationID() { return operationID; } public long getValue() { return value; } public String toString() { return new String("Constraint{ AttributeID = " + attributeID + " OperatorID = " + operationID + " Value = " + value + " }"); } }
{ "content_hash": "b158c755ee8949361d6c5da52ef3fde0", "timestamp": "", "source": "github", "line_count": 44, "max_line_length": 132, "avg_line_length": 20.068181818181817, "alnum_prop": 0.5707814269535674, "repo_name": "fresskarma/tinyos-1.x", "id": "50f8b90e48f29bc8ed58946ba1b118c05894b58f", "size": "883", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "contrib/eyes/tools/java/de/tub/eyes/apps/PS/Constraint.java", "mode": "33188", "license": "bsd-3-clause", "language": [ { "name": "Assembly", "bytes": "137296" }, { "name": "Awk", "bytes": "2286" }, { "name": "C", "bytes": "10268716" }, { "name": "C#", "bytes": "140791" }, { "name": "C++", "bytes": "2931461" }, { "name": "CSS", "bytes": "19694" }, { "name": "Forth", "bytes": "101" }, { "name": "Groff", "bytes": "3149" }, { "name": "HTML", "bytes": "1387492" }, { "name": "Inno Setup", "bytes": "16361" }, { "name": "Java", "bytes": "7496416" }, { "name": "Lex", "bytes": "16806" }, { "name": "Logos", "bytes": "10058" }, { "name": "M", "bytes": "2148" }, { "name": "Makefile", "bytes": "871469" }, { "name": "Mathematica", "bytes": "164375" }, { "name": "Matlab", "bytes": "760094" }, { "name": "OCaml", "bytes": "34306" }, { "name": "Objective-C", "bytes": "1149978" }, { "name": "PHP", "bytes": "79339" }, { "name": "Perl", "bytes": "649566" }, { "name": "Perl6", "bytes": "13417" }, { "name": "PostScript", "bytes": "476077" }, { "name": "Python", "bytes": "884036" }, { "name": "Shell", "bytes": "91087" }, { "name": "Smarty", "bytes": "1515" }, { "name": "SourcePawn", "bytes": "29314" }, { "name": "Standard ML", "bytes": "2129" }, { "name": "Tcl", "bytes": "168362" }, { "name": "TeX", "bytes": "213012" }, { "name": "TypeScript", "bytes": "3834" }, { "name": "Visual Basic", "bytes": "274161" }, { "name": "Yacc", "bytes": "43956" }, { "name": "nesC", "bytes": "46659836" } ], "symlink_target": "" }
#include "XnErrorLogger.h" namespace xnl { #if XN_PLATFORM != XN_PLATFORM_WIN32 XN_THREAD_STATIC char ErrorLogger::m_errorBuffer[ms_bufferSize] = ""; XN_THREAD_STATIC int ErrorLogger::m_currentEnd = 0; #endif ErrorLogger& ErrorLogger::GetInstance() { static ErrorLogger el; return el; } void ErrorLogger::Clear() { SingleBuffer* pBuffer = getBuffer(); pBuffer->m_currentEnd = 0; pBuffer->m_errorBuffer[0] = '\0'; } void ErrorLogger::Append(const XnChar* cpFormat, ...) { #if XN_PLATFORM != XN_PLATFORM_WIN32 SingleBuffer* pBuffer = getBuffer(); if (pBuffer->m_currentEnd > ms_bufferSize) return; pBuffer->m_errorBuffer[pBuffer->m_currentEnd++] = '\t'; unsigned int charsWritten; va_list args; va_start(args, cpFormat); xnOSStrFormatV(pBuffer->m_errorBuffer+pBuffer->m_currentEnd, ms_bufferSize-pBuffer->m_currentEnd, &charsWritten, cpFormat, args); va_end(args); pBuffer->m_currentEnd += charsWritten; pBuffer->m_errorBuffer[pBuffer->m_currentEnd++] = '\n'; pBuffer->m_errorBuffer[pBuffer->m_currentEnd] = '\0'; #endif } void ErrorLogger::AppendV(const XnChar* cpFormat, va_list args) { #if XN_PLATFORM != XN_PLATFORM_WIN32 SingleBuffer* pBuffer = getBuffer(); if (pBuffer->m_currentEnd > ms_bufferSize) return; pBuffer->m_errorBuffer[pBuffer->m_currentEnd++] = '\t'; unsigned int charsWritten; xnOSStrFormatV(pBuffer->m_errorBuffer+pBuffer->m_currentEnd, ms_bufferSize-pBuffer->m_currentEnd, &charsWritten, cpFormat, args); pBuffer->m_currentEnd += charsWritten; pBuffer->m_errorBuffer[pBuffer->m_currentEnd++] = '\n'; pBuffer->m_errorBuffer[pBuffer->m_currentEnd] = '\0'; #endif } ErrorLogger::ErrorLogger() { SingleBuffer* pBuffer = getBuffer(); xnOSMemSet(pBuffer->m_errorBuffer, 0, ms_bufferSize); pBuffer->m_currentEnd = 0; } ErrorLogger::~ErrorLogger() { #if XN_PLATFORM == XN_PLATFORM_WIN32 while (!m_buffers.IsEmpty()) { SingleBuffer* pBuffer = m_buffers.Begin()->Value(); XN_DELETE(pBuffer); m_buffers.Remove(m_buffers.Begin()); } #endif } #if XN_PLATFORM == XN_PLATFORM_WIN32 ErrorLogger::SingleBuffer* ErrorLogger::getBuffer() { m_bufferLock.Lock(); XN_THREAD_ID threadId; xnOSGetCurrentThreadID(&threadId); // Check if we already have a buffer for this thread xnl::Hash<XN_THREAD_ID, SingleBuffer*>::ConstIterator buffer = m_buffers.Find(threadId); if (buffer != m_buffers.End()) { SingleBuffer* pBuffer = buffer->Value(); m_bufferLock.Unlock(); return pBuffer; } // Go over list and remove any buffer for which the thread no longer exists xnl::List<XN_THREAD_ID> deadThreads; for (xnl::Hash<XN_THREAD_ID, SingleBuffer*>::ConstIterator iter = m_buffers.Begin(); iter != m_buffers.End(); ++iter) { if (xnOSDoesThreadExistByID(iter->Key()) != TRUE) { deadThreads.AddLast(iter->Key()); } } for (xnl::List<XN_THREAD_ID>::ConstIterator deadIter = deadThreads.Begin(); deadIter != deadThreads.End(); ++deadIter) { SingleBuffer* pBuffer = m_buffers[*deadIter]; XN_DELETE(pBuffer); m_buffers.Remove(*deadIter); } // Create a buffer for this thread SingleBuffer* pNewBuffer = XN_NEW(SingleBuffer); m_buffers[threadId] = pNewBuffer; m_bufferLock.Unlock(); return pNewBuffer; } #else ErrorLogger::SingleBuffer* ErrorLogger::getBuffer() { return this; } #endif }
{ "content_hash": "ddb940c9aa9610e99b7abedf4e70c4c8", "timestamp": "", "source": "github", "line_count": 133, "max_line_length": 131, "avg_line_length": 25.30075187969925, "alnum_prop": 0.6933135215453194, "repo_name": "PersonifyInc/OpenNI2", "id": "e2f03dd53f0a6f5f71aced68419de2de6cdcdea7", "size": "4944", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "ThirdParty/PSCommon/XnLib/Source/XnErrorLogger.cpp", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "C", "bytes": "210283" }, { "name": "C++", "bytes": "1983712" }, { "name": "CMake", "bytes": "9549" }, { "name": "Makefile", "bytes": "10029" }, { "name": "Objective-C", "bytes": "111617" }, { "name": "Python", "bytes": "46519" }, { "name": "Shell", "bytes": "3423" } ], "symlink_target": "" }
// // This file was pubmed.openAccess.jaxb.generated by the JavaTM Architecture for XML Binding(JAXB) Reference Implementation, vJAXB 2.1.10 in JDK 6 // See <a href="http://java.sun.com/xml/jaxb">http://java.sun.com/xml/jaxb</a> // Any modifications to this file will be lost upon recompilation of the source schema. // Generated on: 2011.06.04 at 07:58:30 PM BST // package elsevier.jaxb.math.mathml; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import javax.xml.bind.annotation.XmlAccessType; import javax.xml.bind.annotation.XmlAccessorType; import javax.xml.bind.annotation.XmlAnyAttribute; import javax.xml.bind.annotation.XmlAttribute; import javax.xml.bind.annotation.XmlID; import javax.xml.bind.annotation.XmlIDREF; import javax.xml.bind.annotation.XmlRootElement; import javax.xml.bind.annotation.XmlSchemaType; import javax.xml.bind.annotation.XmlType; import javax.xml.bind.annotation.adapters.CollapsedStringAdapter; import javax.xml.bind.annotation.adapters.XmlJavaTypeAdapter; import javax.xml.namespace.QName; /** * <p>Java class for in.type complex type. * * <p>The following schema fragment specifies the expected content contained within this class. * * <pre> * &lt;complexType name="in.type"> * &lt;complexContent> * &lt;restriction base="{http://www.w3.org/2001/XMLSchema}anyType"> * &lt;attGroup ref="{http://www.w3.org/1998/Math/MathML}in.attlist"/> * &lt;/restriction> * &lt;/complexContent> * &lt;/complexType> * </pre> * * */ @XmlAccessorType(XmlAccessType.FIELD) @XmlType(name = "in.type") @XmlRootElement(name = "in") public class In { @XmlAttribute(name = "class") @XmlSchemaType(name = "NMTOKENS") protected List<String> clazzs; @XmlAttribute protected String style; @XmlAttribute @XmlIDREF @XmlSchemaType(name = "IDREF") protected Object xref; @XmlAttribute @XmlJavaTypeAdapter(CollapsedStringAdapter.class) @XmlID @XmlSchemaType(name = "ID") protected String id; @XmlAttribute(namespace = "http://www.w3.org/1999/xlink") @XmlSchemaType(name = "anyURI") protected String href; @XmlAttribute protected String encoding; @XmlAttribute @XmlSchemaType(name = "anyURI") protected String definitionURL; @XmlAnyAttribute private Map<QName, String> otherAttributes = new HashMap<QName, String>(); /** * Gets the value of the clazzs property. * * <p> * This accessor method returns a reference to the live list, * not a snapshot. Therefore any modification you make to the * returned list will be present inside the JAXB object. * This is why there is not a <CODE>set</CODE> method for the clazzs property. * * <p> * For example, to add a new item, do as follows: * <pre> * getClazzs().add(newItem); * </pre> * * * <p> * Objects of the following type(s) are allowed in the list * {@link String } * * */ public List<String> getClazzs() { if (clazzs == null) { clazzs = new ArrayList<String>(); } return this.clazzs; } /** * Gets the value of the style property. * * @return * possible object is * {@link String } * */ public String getStyle() { return style; } /** * Sets the value of the style property. * * @param value * allowed object is * {@link String } * */ public void setStyle(String value) { this.style = value; } /** * Gets the value of the xref property. * * @return * possible object is * {@link Object } * */ public Object getXref() { return xref; } /** * Sets the value of the xref property. * * @param value * allowed object is * {@link Object } * */ public void setXref(Object value) { this.xref = value; } /** * Gets the value of the id property. * * @return * possible object is * {@link String } * */ public String getId() { return id; } /** * Sets the value of the id property. * * @param value * allowed object is * {@link String } * */ public void setId(String value) { this.id = value; } /** * Gets the value of the href property. * * @return * possible object is * {@link String } * */ public String getHref() { return href; } /** * Sets the value of the href property. * * @param value * allowed object is * {@link String } * */ public void setHref(String value) { this.href = value; } /** * Gets the value of the encoding property. * * @return * possible object is * {@link String } * */ public String getEncoding() { return encoding; } /** * Sets the value of the encoding property. * * @param value * allowed object is * {@link String } * */ public void setEncoding(String value) { this.encoding = value; } /** * Gets the value of the definitionURL property. * * @return * possible object is * {@link String } * */ public String getDefinitionURL() { return definitionURL; } /** * Sets the value of the definitionURL property. * * @param value * allowed object is * {@link String } * */ public void setDefinitionURL(String value) { this.definitionURL = value; } /** * Gets a map that contains attributes that aren't bound to any typed property on this class. * * <p> * the map is keyed by the name of the attribute and * the value is the string value of the attribute. * * the map returned by this method is live, and you can add new attribute * by updating the map directly. Because of this design, there's no setter. * * * @return * always non-null */ public Map<QName, String> getOtherAttributes() { return otherAttributes; } }
{ "content_hash": "c0b264540cf0c317ebde0a43d581a95d", "timestamp": "", "source": "github", "line_count": 267, "max_line_length": 147, "avg_line_length": 24.254681647940075, "alnum_prop": 0.5821494749845584, "repo_name": "alexgarciac/testbiotea", "id": "b7220f24e74cb579180bfecf5a7fb75eddf8512b", "size": "6476", "binary": false, "copies": "3", "ref": "refs/heads/master", "path": "src/elsevier/jaxb/math/mathml/In.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "HTML", "bytes": "77386" }, { "name": "Java", "bytes": "7379391" } ], "symlink_target": "" }
<?php namespace PrestataireDeServices\prestataireBundle\Entity; use Doctrine\ORM\Mapping as ORM; /** * Notification * * @ORM\Table(name="notification", indexes={@ORM\Index(name="IDX_BF5476CA97AF9ABE", columns={"IdDeal"}), @ORM\Index(name="IDX_BF5476CA804A36C4", columns={"IdFromUser"}), @ORM\Index(name="IDX_BF5476CAAC91624F", columns={"IdToUser"})}) * @ORM\Entity */ class Notification { /** * @var string * * @ORM\Column(name="DateNotification", type="string", length=100, nullable=true) */ private $datenotification; /** * @var string * * @ORM\Column(name="TypeNotification", type="string", length=254, nullable=true) */ private $typenotification; /** * @var string * * @ORM\Column(name="Message", type="string", length=254, nullable=true) */ private $message; /** * @var integer * * @ORM\Column(name="IdNotification", type="integer") * @ORM\Id * @ORM\GeneratedValue(strategy="IDENTITY") */ private $idnotification; /** * @var \PrestataireDeServices\prestataireBundle\Entity\Deal * * @ORM\ManyToOne(targetEntity="PrestataireDeServices\prestataireBundle\Entity\Deal") * @ORM\JoinColumns({ * @ORM\JoinColumn(name="IdDeal", referencedColumnName="IdDeal") * }) */ private $iddeal; /** * @var \PrestataireDeServices\prestataireBundle\Entity\User * * @ORM\ManyToOne(targetEntity="PrestataireDeServices\prestataireBundle\Entity\User") * @ORM\JoinColumns({ * @ORM\JoinColumn(name="IdFromUser", referencedColumnName="IdUser") * }) */ private $idfromuser; /** * @var \PrestataireDeServices\prestataireBundle\Entity\User * * @ORM\ManyToOne(targetEntity="PrestataireDeServices\prestataireBundle\Entity\User") * @ORM\JoinColumns({ * @ORM\JoinColumn(name="IdToUser", referencedColumnName="IdUser") * }) */ private $idtouser; }
{ "content_hash": "cc473025dc77b8e81163fd02975a4a75", "timestamp": "", "source": "github", "line_count": 76, "max_line_length": 233, "avg_line_length": 26.17105263157895, "alnum_prop": 0.6349924585218703, "repo_name": "rafaelAres/BestDeal", "id": "d9adf620af21f774650465b4edc8a486b4c5025d", "size": "1989", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "src/PrestataireDeServices/prestataireBundle/Entity/Notification.php", "mode": "33188", "license": "mit", "language": [ { "name": "ApacheConf", "bytes": "2907" }, { "name": "CSS", "bytes": "132638" }, { "name": "HTML", "bytes": "507100" }, { "name": "JavaScript", "bytes": "867100" }, { "name": "Liquid", "bytes": "38454" }, { "name": "PHP", "bytes": "135794" } ], "symlink_target": "" }
/* ** Car.java ** Author: Sushil Parti * This program is written to understand the concepts of Inheritance in Java */ public class Car { public int speed; public String color; public String brand; public Car(int startSpeed, String color, String brand) { this.speed = startSpeed; this.color = color; this.brand = brand; } public void setSpeed(int increment) { speed += increment; } public void changeColor(String newColor) { color = newColor; } public void displayAll() { System.out.println("Speed: " + speed +" Color: "+color+" Brand: "+brand); } public static void main(String[] args) { Car civic = new Car(20, "Black", "Honda"); civic.displayAll(); civic.changeColor("White"); civic.displayAll(); } }
{ "content_hash": "e6d645bc28fa585df105bdb545871bfc", "timestamp": "", "source": "github", "line_count": 45, "max_line_length": 76, "avg_line_length": 16.733333333333334, "alnum_prop": 0.6693227091633466, "repo_name": "sushilparti/leisure", "id": "0d943e1bd2ba5cbe0ec8d8d6be832ebf8b298a81", "size": "753", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "General/Car.java", "mode": "33188", "license": "mit", "language": [ { "name": "C++", "bytes": "1974" }, { "name": "HTML", "bytes": "449" }, { "name": "Java", "bytes": "88047" }, { "name": "JavaScript", "bytes": "3924" } ], "symlink_target": "" }
/* TEMPLATE GENERATED TESTCASE FILE Filename: CWE190_Integer_Overflow__int_connect_socket_preinc_13.c Label Definition File: CWE190_Integer_Overflow__int.label.xml Template File: sources-sinks-13.tmpl.c */ /* * @description * CWE: 190 Integer Overflow * BadSource: connect_socket Read data using a connect socket (client side) * GoodSource: Set data to a small, non-zero number (two) * Sinks: increment * GoodSink: Ensure there will not be an overflow before incrementing data * BadSink : Increment data, which can cause an overflow * Flow Variant: 13 Control flow: if(GLOBAL_CONST_FIVE==5) and if(GLOBAL_CONST_FIVE!=5) * * */ #include "std_testcase.h" #ifdef _WIN32 #include <winsock2.h> #include <windows.h> #include <direct.h> #pragma comment(lib, "ws2_32") /* include ws2_32.lib when linking */ #define CLOSE_SOCKET closesocket #else /* NOT _WIN32 */ #include <sys/types.h> #include <sys/socket.h> #include <netinet/in.h> #include <arpa/inet.h> #include <unistd.h> #define INVALID_SOCKET -1 #define SOCKET_ERROR -1 #define CLOSE_SOCKET close #define SOCKET int #endif #define TCP_PORT 27015 #define IP_ADDRESS "127.0.0.1" #define CHAR_ARRAY_SIZE (3 * sizeof(data) + 2) #ifndef OMITBAD void CWE190_Integer_Overflow__int_connect_socket_preinc_13_bad() { int data; /* Initialize data */ data = 0; if(GLOBAL_CONST_FIVE==5) { { #ifdef _WIN32 WSADATA wsaData; int wsaDataInit = 0; #endif int recvResult; struct sockaddr_in service; SOCKET connectSocket = INVALID_SOCKET; char inputBuffer[CHAR_ARRAY_SIZE]; do { #ifdef _WIN32 if (WSAStartup(MAKEWORD(2,2), &wsaData) != NO_ERROR) { break; } wsaDataInit = 1; #endif /* POTENTIAL FLAW: Read data using a connect socket */ connectSocket = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP); if (connectSocket == INVALID_SOCKET) { break; } memset(&service, 0, sizeof(service)); service.sin_family = AF_INET; service.sin_addr.s_addr = inet_addr(IP_ADDRESS); service.sin_port = htons(TCP_PORT); if (connect(connectSocket, (struct sockaddr*)&service, sizeof(service)) == SOCKET_ERROR) { break; } /* Abort on error or the connection was closed, make sure to recv one * less char than is in the recv_buf in order to append a terminator */ recvResult = recv(connectSocket, inputBuffer, CHAR_ARRAY_SIZE - 1, 0); if (recvResult == SOCKET_ERROR || recvResult == 0) { break; } /* NUL-terminate the string */ inputBuffer[recvResult] = '\0'; /* Convert to int */ data = atoi(inputBuffer); } while (0); if (connectSocket != INVALID_SOCKET) { CLOSE_SOCKET(connectSocket); } #ifdef _WIN32 if (wsaDataInit) { WSACleanup(); } #endif } } if(GLOBAL_CONST_FIVE==5) { { /* POTENTIAL FLAW: Incrementing data could cause an overflow */ ++data; int result = data; printIntLine(result); } } } #endif /* OMITBAD */ #ifndef OMITGOOD /* goodB2G1() - use badsource and goodsink by changing the second GLOBAL_CONST_FIVE==5 to GLOBAL_CONST_FIVE!=5 */ static void goodB2G1() { int data; /* Initialize data */ data = 0; if(GLOBAL_CONST_FIVE==5) { { #ifdef _WIN32 WSADATA wsaData; int wsaDataInit = 0; #endif int recvResult; struct sockaddr_in service; SOCKET connectSocket = INVALID_SOCKET; char inputBuffer[CHAR_ARRAY_SIZE]; do { #ifdef _WIN32 if (WSAStartup(MAKEWORD(2,2), &wsaData) != NO_ERROR) { break; } wsaDataInit = 1; #endif /* POTENTIAL FLAW: Read data using a connect socket */ connectSocket = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP); if (connectSocket == INVALID_SOCKET) { break; } memset(&service, 0, sizeof(service)); service.sin_family = AF_INET; service.sin_addr.s_addr = inet_addr(IP_ADDRESS); service.sin_port = htons(TCP_PORT); if (connect(connectSocket, (struct sockaddr*)&service, sizeof(service)) == SOCKET_ERROR) { break; } /* Abort on error or the connection was closed, make sure to recv one * less char than is in the recv_buf in order to append a terminator */ recvResult = recv(connectSocket, inputBuffer, CHAR_ARRAY_SIZE - 1, 0); if (recvResult == SOCKET_ERROR || recvResult == 0) { break; } /* NUL-terminate the string */ inputBuffer[recvResult] = '\0'; /* Convert to int */ data = atoi(inputBuffer); } while (0); if (connectSocket != INVALID_SOCKET) { CLOSE_SOCKET(connectSocket); } #ifdef _WIN32 if (wsaDataInit) { WSACleanup(); } #endif } } if(GLOBAL_CONST_FIVE!=5) { /* INCIDENTAL: CWE 561 Dead Code, the code below will never run */ printLine("Benign, fixed string"); } else { /* FIX: Add a check to prevent an overflow from occurring */ if (data < INT_MAX) { ++data; int result = data; printIntLine(result); } else { printLine("data value is too large to perform arithmetic safely."); } } } /* goodB2G2() - use badsource and goodsink by reversing the blocks in the second if */ static void goodB2G2() { int data; /* Initialize data */ data = 0; if(GLOBAL_CONST_FIVE==5) { { #ifdef _WIN32 WSADATA wsaData; int wsaDataInit = 0; #endif int recvResult; struct sockaddr_in service; SOCKET connectSocket = INVALID_SOCKET; char inputBuffer[CHAR_ARRAY_SIZE]; do { #ifdef _WIN32 if (WSAStartup(MAKEWORD(2,2), &wsaData) != NO_ERROR) { break; } wsaDataInit = 1; #endif /* POTENTIAL FLAW: Read data using a connect socket */ connectSocket = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP); if (connectSocket == INVALID_SOCKET) { break; } memset(&service, 0, sizeof(service)); service.sin_family = AF_INET; service.sin_addr.s_addr = inet_addr(IP_ADDRESS); service.sin_port = htons(TCP_PORT); if (connect(connectSocket, (struct sockaddr*)&service, sizeof(service)) == SOCKET_ERROR) { break; } /* Abort on error or the connection was closed, make sure to recv one * less char than is in the recv_buf in order to append a terminator */ recvResult = recv(connectSocket, inputBuffer, CHAR_ARRAY_SIZE - 1, 0); if (recvResult == SOCKET_ERROR || recvResult == 0) { break; } /* NUL-terminate the string */ inputBuffer[recvResult] = '\0'; /* Convert to int */ data = atoi(inputBuffer); } while (0); if (connectSocket != INVALID_SOCKET) { CLOSE_SOCKET(connectSocket); } #ifdef _WIN32 if (wsaDataInit) { WSACleanup(); } #endif } } if(GLOBAL_CONST_FIVE==5) { /* FIX: Add a check to prevent an overflow from occurring */ if (data < INT_MAX) { ++data; int result = data; printIntLine(result); } else { printLine("data value is too large to perform arithmetic safely."); } } } /* goodG2B1() - use goodsource and badsink by changing the first GLOBAL_CONST_FIVE==5 to GLOBAL_CONST_FIVE!=5 */ static void goodG2B1() { int data; /* Initialize data */ data = 0; if(GLOBAL_CONST_FIVE!=5) { /* INCIDENTAL: CWE 561 Dead Code, the code below will never run */ printLine("Benign, fixed string"); } else { /* FIX: Use a small, non-zero value that will not cause an integer overflow in the sinks */ data = 2; } if(GLOBAL_CONST_FIVE==5) { { /* POTENTIAL FLAW: Incrementing data could cause an overflow */ ++data; int result = data; printIntLine(result); } } } /* goodG2B2() - use goodsource and badsink by reversing the blocks in the first if */ static void goodG2B2() { int data; /* Initialize data */ data = 0; if(GLOBAL_CONST_FIVE==5) { /* FIX: Use a small, non-zero value that will not cause an integer overflow in the sinks */ data = 2; } if(GLOBAL_CONST_FIVE==5) { { /* POTENTIAL FLAW: Incrementing data could cause an overflow */ ++data; int result = data; printIntLine(result); } } } void CWE190_Integer_Overflow__int_connect_socket_preinc_13_good() { goodB2G1(); goodB2G2(); goodG2B1(); goodG2B2(); } #endif /* OMITGOOD */ /* Below is the main(). It is only used when building this testcase on its own for testing or for building a binary to use in testing binary analysis tools. It is not used when compiling all the testcases as one application, which is how source code analysis tools are tested. */ #ifdef INCLUDEMAIN int main(int argc, char * argv[]) { /* seed randomness */ srand( (unsigned)time(NULL) ); #ifndef OMITGOOD printLine("Calling good()..."); CWE190_Integer_Overflow__int_connect_socket_preinc_13_good(); printLine("Finished good()"); #endif /* OMITGOOD */ #ifndef OMITBAD printLine("Calling bad()..."); CWE190_Integer_Overflow__int_connect_socket_preinc_13_bad(); printLine("Finished bad()"); #endif /* OMITBAD */ return 0; } #endif
{ "content_hash": "d4f2ee760c373c41f96cff1f1e984279", "timestamp": "", "source": "github", "line_count": 373, "max_line_length": 113, "avg_line_length": 30.536193029490615, "alnum_prop": 0.5045654082528533, "repo_name": "JianpingZeng/xcc", "id": "68dfdb488d5b66466b23b46341223a38f4a5116d", "size": "11390", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "xcc/test/juliet/testcases/CWE190_Integer_Overflow/s07/CWE190_Integer_Overflow__int_connect_socket_preinc_13.c", "mode": "33188", "license": "bsd-3-clause", "language": [], "symlink_target": "" }
package org.uberfire.java.nio.file; import java.net.URI; import java.util.Map; import java.util.ServiceConfigurationError; import org.uberfire.java.nio.IOException; import org.uberfire.java.nio.file.api.FileSystemProviders; import static java.util.Collections.emptyMap; import static org.kie.soup.commons.validation.Preconditions.checkNotNull; /** * Back port of JSR-203 from Java Platform, Standard Edition 7. * * @see <a href="http://docs.oracle.com/javase/7/docs/api/java/nio/file/FileSystems.html">Original JavaDoc</a> */ public final class FileSystems { private FileSystems() { } /** * @see <a href="http://docs.oracle.com/javase/7/docs/api/java/nio/file/FileSystems.html#getDefault()">Original JavaDoc</a> */ public static FileSystem getDefault() { return DefaultFileSystemHolder.defaultFileSystem; } /** * @throws IllegalArgumentException * @throws FileSystemNotFoundException * @throws ProviderNotFoundException * @throws SecurityException * @see <a href="http://docs.oracle.com/javase/7/docs/api/java/nio/file/FileSystems.html#getFileSystem(java.net.URI)">Original JavaDoc</a> */ public static FileSystem getFileSystem(final URI uri) throws IllegalArgumentException, FileSystemNotFoundException, ProviderNotFoundException, SecurityException { checkNotNull("uri", uri); return FileSystemProviders.resolveProvider(uri).getFileSystem(uri); } /** * @throws IllegalArgumentException * @throws FileSystemAlreadyExistsException * @throws ProviderNotFoundException * @throws IOException * @throws SecurityException * @see <a href="http://docs.oracle.com/javase/7/docs/api/java/nio/file/FileSystems.html#newFileSystem(java.net.URI, java.util.Map)">Original JavaDoc</a> */ public static FileSystem newFileSystem(final URI uri, final Map<String, ?> env) throws IllegalArgumentException, FileSystemAlreadyExistsException, ProviderNotFoundException, IOException, SecurityException { checkNotNull("uri", uri); checkNotNull("env", env); return newFileSystem(uri, env, null); } /** * @throws IllegalArgumentException * @throws ProviderNotFoundException * @throws ServiceConfigurationError * @throws IOException * @throws SecurityException * @see <a href="http://docs.oracle.com/javase/7/docs/api/java/nio/file/FileSystems.html#newFileSystem(java.nio.file.Path, java.lang.ClassLoader)">Original JavaDoc</a> */ public static FileSystem newFileSystem(final Path path, final ClassLoader loader) throws IllegalArgumentException, ProviderNotFoundException, ServiceConfigurationError, IOException, SecurityException { checkNotNull("path", path); final Map<String, ?> env = emptyMap(); return newFileSystem(path.toUri(), env, null); } /** * @throws IllegalArgumentException * @throws FileSystemAlreadyExistsException * @throws ProviderNotFoundException * @throws ServiceConfigurationError * @throws IOException * @throws SecurityException * @see <a href="http://docs.oracle.com/javase/7/docs/api/java/nio/file/FileSystems.html#newFileSystem(java.net.URI, java.util.Map, java.lang.ClassLoader)">Original JavaDoc</a> */ public static FileSystem newFileSystem(final URI uri, final Map<String, ?> env, final ClassLoader loader) throws IllegalArgumentException, FileSystemAlreadyExistsException, ProviderNotFoundException, ServiceConfigurationError, IOException, SecurityException { checkNotNull("uri", uri); checkNotNull("env", env); return FileSystemProviders.resolveProvider(uri).newFileSystem(uri, env); } // for lazy init private static class DefaultFileSystemHolder { static final FileSystem defaultFileSystem = getDefaultFileSystem(); private static FileSystem getDefaultFileSystem() { return FileSystemProviders.getDefaultProvider().getFileSystem(URI.create("default:///")); } } }
{ "content_hash": "09b4d90eac9e5552994df2de6e99bd6a", "timestamp": "", "source": "github", "line_count": 121, "max_line_length": 180, "avg_line_length": 38.09090909090909, "alnum_prop": 0.6383163376003471, "repo_name": "karreiro/uberfire", "id": "8080b34479365b8309fa510bfe3554138ece2602", "size": "5230", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "uberfire-nio2-backport/uberfire-nio2-api/src/main/java/org/uberfire/java/nio/file/FileSystems.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "CSS", "bytes": "80257" }, { "name": "FreeMarker", "bytes": "46611" }, { "name": "HTML", "bytes": "106890" }, { "name": "Java", "bytes": "15858867" }, { "name": "JavaScript", "bytes": "86367" }, { "name": "Shell", "bytes": "5994" } ], "symlink_target": "" }
package org.n52.iceland.exception.ows.concrete; import static org.n52.iceland.util.http.HTTPStatus.INTERNAL_SERVER_ERROR; import org.n52.iceland.exception.ows.NoApplicableCodeException; /** * @author <a href="mailto:c.autermann@52north.org">Christian Autermann</a> * @author <a href="mailto:e.h.juerrens@52north.org">Eike Hinderk * J&uuml;rrens</a> * * @since 1.0.0 */ public class NoEncoderForResponseException extends NoApplicableCodeException { private static final long serialVersionUID = -6155794217269036717L; public NoEncoderForResponseException() { withMessage("Error while getting encoder for response!"); setStatus(INTERNAL_SERVER_ERROR); } }
{ "content_hash": "6804238c90d8c847d5582f50e79475d6", "timestamp": "", "source": "github", "line_count": 23, "max_line_length": 78, "avg_line_length": 30.47826086956522, "alnum_prop": 0.7417974322396577, "repo_name": "nuest/iceland", "id": "35d2cc280d74c7d467df8068bd9a09666ff79905", "size": "1347", "binary": false, "copies": "1", "ref": "refs/heads/develop", "path": "core/src/main/java/org/n52/iceland/exception/ows/concrete/NoEncoderForResponseException.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Groovy", "bytes": "672" }, { "name": "Java", "bytes": "1500420" }, { "name": "Shell", "bytes": "517" } ], "symlink_target": "" }
This is a multiplayer UNO card game based on the client-server architecture written in C++ and JavaScript. The following keywords are related in the current state of the project: C++, JavaScript, node.js, HTML5, CSS3, Socket.IO, publish-subscribe. A few may follow later: Java, Andriod, OpenGL. Currently there are no easily accessible working versions of the game, however, there are such versions buried deep in the history. ##Directory Structure The v0.2 branch has a brand new structure as follows: - docs - server - acts as a separate npm module - lib - server related js files and link to the compiled addon - addon - C++ resources - client-browser - acts as separate npm module, files related to the client are here
{ "content_hash": "4a2a4b5cc16be3f68ac57551522ddc8a", "timestamp": "", "source": "github", "line_count": 12, "max_line_length": 294, "avg_line_length": 60.833333333333336, "alnum_prop": 0.7684931506849315, "repo_name": "erenon/casino", "id": "525b5202739faa48038c45e53e886810d7ed26dc", "size": "744", "binary": false, "copies": "1", "ref": "refs/heads/v0.2", "path": "README.md", "mode": "33188", "license": "mit", "language": [ { "name": "JavaScript", "bytes": "148119" } ], "symlink_target": "" }
<?php namespace Oro\Component\MessageQueue\Tests\Unit\Transport\Dbal; use Doctrine\Common\Persistence\ManagerRegistry; use Doctrine\DBAL\Connection; use Doctrine\DBAL\Schema\AbstractSchemaManager; use Oro\Component\MessageQueue\Transport\Dbal\DbalConnection; use Oro\Component\MessageQueue\Transport\Dbal\DbalLazyConnection; use Oro\Component\Testing\ClassExtensionTrait; class DbalLazyConnectionTest extends \PHPUnit\Framework\TestCase { use ClassExtensionTrait; public function testShouldImplementConnectionInterface() { self::assertClassExtends(DbalConnection::class, DbalLazyConnection::class); } public function testCouldBeConstructedWithRequiredArguments() { new DbalLazyConnection($this->createManagerRegistryStub(), 'connection', 'table'); } public function testShouldNotBeInitOnConstruct() { $connection = new DbalLazyConnection($this->createManagerRegistryStub(), 'connection', 'table'); self::assertConnectionIsNotInit($connection); } public function testShouldInitDBALConnectionUsingRegistryAndConnectionName() { $dbalConnection = $this->createDBALConnectionMock(); $registry = $this->createManagerRegistryMock(); $registry ->expects(self::once()) ->method('getConnection') ->with('theConnection') ->willReturn($dbalConnection) ; $connection = new DbalLazyConnection($registry, 'theConnection', 'table'); //guard self::assertConnectionIsNotInit($connection); self::assertSame($dbalConnection, $connection->getDBALConnection()); self::assertConnectionIsInit($connection); } public function testShouldNotInitOnCreateSessionMethodCall() { $connection = new DbalLazyConnection($this->createManagerRegistryStub(), 'connection', 'table'); //guard self::assertConnectionIsNotInit($connection); $session = $connection->createSession(); self::assertAttributeInstanceOf(DbalLazyConnection::class, 'connection', $session); self::assertConnectionIsNotInit($connection); } public function testShouldNotInitOnGetTableNameCall() { $connection = new DbalLazyConnection($this->createManagerRegistryStub(), 'connection', 'theTable'); //guard self::assertConnectionIsNotInit($connection); self::assertEquals('theTable', $connection->getTableName()); self::assertConnectionIsNotInit($connection); } public function testShouldNotInitOnGetOptionsCall() { $options = ['foo' => 'fooVal', 'bar' => 'barVal']; $connection = new DbalLazyConnection($this->createManagerRegistryStub(), 'connection', 'table', $options); //guard self::assertConnectionIsNotInit($connection); self::assertEquals($options, $connection->getOptions()); self::assertConnectionIsNotInit($connection); } public function testShouldNotInitOnCloseIfNotInit() { $dbalConnection = $this->createDBALConnectionMock(); $dbalConnection ->expects(self::never()) ->method('close') ; $registry = $this->createManagerRegistryStub($dbalConnection); $connection = new DbalLazyConnection($registry, 'connection', 'table'); //guard self::assertConnectionIsNotInit($connection); $connection->close(); self::assertConnectionIsNotInit($connection); } public function testShouldCallCloseInitOnCloseIfNotInit() { $dbalConnection = $this->createDBALConnectionMock(); $dbalConnection ->expects(self::once()) ->method('close') ; $registry = $this->createManagerRegistryStub($dbalConnection); $connection = new DbalLazyConnection($registry, 'connection', 'table'); $connection->getDBALConnection(); //guard self::assertConnectionIsInit($connection); $connection->close(); } private static function assertConnectionIsNotInit(DbalLazyConnection $connection) { self::assertAttributeSame(false, 'isInit', $connection); } private static function assertConnectionIsInit(DbalLazyConnection $connection) { self::assertAttributeSame(true, 'isInit', $connection); } /** * @return \PHPUnit\Framework\MockObject\MockObject|ManagerRegistry */ private function createManagerRegistryMock() { return $this->createMock(ManagerRegistry::class); } /** * @return \PHPUnit\Framework\MockObject\MockObject|ManagerRegistry */ private function createManagerRegistryStub($connection = null) { $registryMock = $this->createManagerRegistryMock(); $registryMock ->expects(self::any()) ->method('getConnection') ->willReturn($connection) ; return $registryMock; } /** * @return \PHPUnit\Framework\MockObject\MockObject|Connection */ private function createDBALConnectionMock() { $schemaManager = $this->createMock(AbstractSchemaManager::class); $dbalConnection = $this->createMock(Connection::class); $dbalConnection ->expects($this->any()) ->method('getSchemaManager') ->will($this->returnValue($schemaManager)) ; return $dbalConnection; } }
{ "content_hash": "e8268aec28ad97e9aafbff1a2c6ee380", "timestamp": "", "source": "github", "line_count": 181, "max_line_length": 114, "avg_line_length": 30.14364640883978, "alnum_prop": 0.6636730205278593, "repo_name": "orocrm/platform", "id": "4fd8abb2d054f56e29309c5febb2f079897a5535", "size": "5456", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/Oro/Component/MessageQueue/Tests/Unit/Transport/Dbal/DbalLazyConnectionTest.php", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "618485" }, { "name": "Gherkin", "bytes": "158217" }, { "name": "HTML", "bytes": "1648915" }, { "name": "JavaScript", "bytes": "3326127" }, { "name": "PHP", "bytes": "37828618" } ], "symlink_target": "" }
#pragma once #include "BluetoothObject.hpp" #include "BluetoothManager.hpp" #include "BluetoothUUID.hpp" #include <vector> /* Forward declaration of types */ struct _Object; typedef struct _Object Object; struct _Adapter1; typedef struct _Adapter1 Adapter1; /** * Provides access to Bluetooth adapters. Follows the BlueZ adapter API * available at: http://git.kernel.org/cgit/bluetooth/bluez.git/tree/doc/adapter-api.txt */ class tinyb::BluetoothAdapter: public BluetoothObject { friend class tinyb::BluetoothManager; friend class tinyb::BluetoothEventManager; friend class tinyb::BluetoothDevice; friend class tinyb::BluetoothNotificationHandler; private: Adapter1 *object; protected: BluetoothAdapter(Adapter1 *object); static std::unique_ptr<BluetoothAdapter> make(Object *object, BluetoothType type = BluetoothType::ADAPTER, std::string *name = nullptr, std::string *identifier = nullptr, BluetoothObject *parent = nullptr); std::function<void(bool)> powered_callback; std::function<void(bool)> discoverable_callback; std::function<void(bool)> pairable_callback; std::function<void(bool)> discovering_callback; public: static std::string java_class() { return std::string(JAVA_PACKAGE "/BluetoothAdapter"); } static BluetoothType class_type() { return BluetoothType::ADAPTER; } virtual std::string get_java_class() const; virtual std::string get_class_name() const; virtual std::string get_object_path() const; virtual BluetoothType get_bluetooth_type() const; BluetoothAdapter(const BluetoothAdapter &object); ~BluetoothAdapter(); virtual BluetoothAdapter *clone() const; std::unique_ptr<BluetoothDevice> find(std::string *name, std::string *identifier, std::chrono::milliseconds timeout = std::chrono::milliseconds::zero()) { BluetoothManager *manager = BluetoothManager::get_bluetooth_manager(); return manager->find<BluetoothDevice>(name, identifier, this, timeout); } /* D-Bus method calls: */ /** Removes a device from the list of devices available on this adapter. * @param[in] arg_device The path of the device on DBus * @return TRUE if device was successfully removed */ bool remove_device ( const std::string &arg_device ); /** Turns on device discovery if it is disabled. * @return TRUE if discovery was successfully enabled */ bool start_discovery ( ); /** Turns off device discovery if it is enabled. * @return TRUE if discovery was successfully disabled */ bool stop_discovery ( ); /** Sets the device discovery filter for the caller. If all fields are empty, * filter is removed. * @param uuids Vector of UUIDs to filter on * @param rssi RSSI low bounded threshold * @param pathloss Pathloss threshold value * @param transport Type of scan to run */ bool set_discovery_filter (std::vector<BluetoothUUID> uuids, int16_t rssi, uint16_t pathloss, const TransportType &transport); /** Returns a list of BluetoothDevices visible from this adapter. * @return A list of BluetoothDevices visible on this adapter, * NULL if an error occurred */ std::vector<std::unique_ptr<BluetoothDevice>> get_devices ( ); /* D-Bus property accessors: */ /** Returns the hardware address of this adapter. * @return The hardware address of this adapter. */ std::string get_address (); /** Returns the system name of this adapter. * @return The system name of this adapter. */ std::string get_name (); /** Returns the friendly name of this adapter. * @return The friendly name of this adapter. */ std::string get_alias (); /** Sets the friendly name of this adapter. */ void set_alias (const std::string &value); /** Returns the Bluetooth class of the adapter. * @return The Bluetooth class of the adapter. */ unsigned int get_class (); /** Returns the power state the adapter. * @return The power state of the adapter. */ bool get_powered (); /** Sets the power state the adapter. */ void set_powered (bool value); /** * Enables notifications for changes of the powered status of the adapter * and triggers the callback when the value changes. * Uninstalls the previous powered callback, if any was installed. * @param callback A function of the form void(BluetoothAdapter&, bool, void *), where * BluetoothAdapter& is the adapter for which the callback was set, bool will contain the * new value of the powered property and void * contains optional, user set data * @param userdata The data which will be delivered to the callback when it is triggered. * Memory must be managed by user. */ void enable_powered_notifications( std::function<void(BluetoothAdapter &adapter, bool powered, void *userdata)> callback, void *userdata); /** * Enables notifications for changes of the powered status of the adapter * and triggers the callback when the value changes. * Uninstalls the previous powered callback, if any was installed. * @param callback A function of the form void(bool), where * bool will contain the new value of the powered property */ void enable_powered_notifications(std::function<void(bool powered)> callback); /** * Disables notifications for changes of the powered status of the adapter * and uninstalls any callback. */ void disable_powered_notifications(); /** Returns the discoverable state the adapter. * @return The discoverable state of the adapter. */ bool get_discoverable (); /** Sets the discoverable state the adapter. */ void set_discoverable (bool value); /** * Enables notifications for changes of the discoverable status of the adapter * and triggers the callback when the value changes. * Uninstalls the previous discoverable callback, if any was installed. * @param callback A function of the form void(BluetoothAdapter&, bool, void *), where * BluetoothAdapter& is the adapter for which the callback was set, bool will contain the * new value of the discoverable property and void * contains optional, user set data * @param userdata The data which will be delivered to the callback when it is triggered. * Memory must be managed by user. */ void enable_discoverable_notifications( std::function<void(BluetoothAdapter &adapter, bool discoverable, void *userdata)> callback, void *userdata); /** * Enables notifications for changes of the discoverable status of the adapter * and triggers the callback when the value changes. * Uninstalls the previous discoverable callback, if any was installed. * @param callback A function of the form void(bool), where * bool will contain the new value of the discoverable property */ void enable_discoverable_notifications(std::function<void(bool discoverable)> callback); /** * Disables notifications for changes of the discoverable status of the adapter and uninstalls any callback; */ void disable_discoverable_notifications(); /** Returns the discoverable timeout the adapter. * @return The discoverable timeout of the adapter. */ unsigned int get_discoverable_timeout (); /** Sets the discoverable timeout the adapter. A value of 0 disables * the timeout. */ void set_discoverable_timeout (unsigned int value); /** Returns the pairable state the adapter. * @return The pairable state of the adapter. */ bool get_pairable (); /** Sets the discoverable state the adapter. */ void set_pairable (bool value); /** * Enables notifications for changes of the pairable status of the adapter * and triggers the callback when the value changes. * Uninstalls the previous pairable callback, if any was installed. * @param callback A function of the form void(BluetoothAdapter&, bool, void *), where * BluetoothAdapter& is the adapter for which the callback was set, bool will contain the * new value of the pairable property and void * contains optional, user set data * @param userdata The data which will be delivered to the callback when it is triggered. * Memory must be managed by user. */ void enable_pairable_notifications( std::function<void(BluetoothAdapter &adapter, bool pairable, void *userdata)> callback, void *userdata); /** * Enables notifications for changes of the pairable status of the adapter * and triggers the callback when the value changes. * Uninstalls the previous pairable callback, if any was installed. * @param callback A function of the form void(bool), where * bool will contain the new value of the pairable property */ void enable_pairable_notifications(std::function<void(bool pairable)> callback); /** * Disables notifications for changes of the pairable status of the adapter and uninstalls any callback; */ void disable_pairable_notifications(); /** Returns the timeout in seconds after which pairable state turns off * automatically, 0 means never. * @return The pairable timeout of the adapter. */ unsigned int get_pairable_timeout (); /** Sets the timeout after which pairable state turns off automatically, 0 means never. */ void set_pairable_timeout (unsigned int value); /** Returns the discovering state the adapter. It can be modified through * start_discovery/stop_discovery functions. * @return The discovering state of the adapter. */ bool get_discovering (); /** * Enables notifications for changes of the discovering status of the adapter * and triggers the callback when the value changes. * Uninstalls the previous discovering callback, if any was installed. * @param callback A function of the form void(BluetoothAdapter&, bool, void *), where * BluetoothAdapter& is the adapter for which the callback was set, bool will contain the * new value of the discovering property and void * contains optional, user set data * @param userdata The data which will be delivered to the callback when it is triggered. * Memory must be managed by user. */ void enable_discovering_notifications( std::function<void(BluetoothAdapter &adapter, bool discovering, void *userdata)> callback, void *userdata); /** * Enables notifications for changes of the discovering status of the adapter * and triggers the callback when the value changes. * Uninstalls the previous discovering callback, if any was installed. * @param callback A function of the form void(bool), where * bool will contain the new value of the discovering property */ void enable_discovering_notifications(std::function<void(bool discovering)> callback); /** * Disables notifications for changes of the discovering status of the adapter and uninstalls any callback; */ void disable_discovering_notifications(); /** Returns the UUIDs of the adapter. * @return Array containing the UUIDs of the adapter, ends with NULL. */ std::vector<std::string> get_uuids (); /** Returns the local ID of the adapter. * @return The local ID of the adapter. */ std::unique_ptr<std::string> get_modalias (); };
{ "content_hash": "9ef953b419393cc80062587ed06e0d9d", "timestamp": "", "source": "github", "line_count": 302, "max_line_length": 112, "avg_line_length": 38.688741721854306, "alnum_prop": 0.6886340294419719, "repo_name": "intel-iot-devkit/tinyb", "id": "43000e452def46a5d2ff9b83b439a7b793d22021", "size": "12860", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "api/tinyb/BluetoothAdapter.hpp", "mode": "33188", "license": "mit", "language": [ { "name": "C", "bytes": "493193" }, { "name": "C++", "bytes": "294418" }, { "name": "CMake", "bytes": "33322" }, { "name": "Java", "bytes": "68690" } ], "symlink_target": "" }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Collections.Generic; using System.ComponentModel.Composition; using System.Linq; using Microsoft.CodeAnalysis.Editor.Shared.Utilities; using Microsoft.CodeAnalysis.Host.Mef; using Microsoft.VisualStudio.Shell; using Microsoft.VisualStudio.Shell.Interop; using Roslyn.Utilities; namespace Microsoft.VisualStudio.LanguageServices.Implementation.ProjectSystem.Legacy { /// <summary> /// Creates batch scopes for projects based on IVsSolutionEvents. This is useful for projects types that don't otherwise have /// good batching concepts. /// </summary> /// <remarks>All members of this class are affinitized to the UI thread.</remarks> [Export(typeof(SolutionEventsBatchScopeCreator))] internal sealed class SolutionEventsBatchScopeCreator : ForegroundThreadAffinitizedObject { private readonly List<(VisualStudioProject project, IVsHierarchy hierarchy, VisualStudioProject.BatchScope batchScope)> _fullSolutionLoadScopes = new List<(VisualStudioProject, IVsHierarchy, VisualStudioProject.BatchScope)>(); private uint? _runningDocumentTableEventsCookie; private readonly IServiceProvider _serviceProvider; private bool _isSubscribedToSolutionEvents = false; private bool _solutionLoaded = false; [ImportingConstructor] [Obsolete(MefConstruction.ImportingConstructorMessage, error: true)] public SolutionEventsBatchScopeCreator(IThreadingContext threadingContext, [Import(typeof(SVsServiceProvider))] IServiceProvider serviceProvider) : base(threadingContext, assertIsForeground: false) { _serviceProvider = serviceProvider; } public void StartTrackingProject(VisualStudioProject project, IVsHierarchy hierarchy) { AssertIsForeground(); EnsureSubscribedToSolutionEvents(); if (!_solutionLoaded) { _fullSolutionLoadScopes.Add((project, hierarchy, project.CreateBatchScope())); EnsureSubscribedToRunningDocumentTableEvents(); } } public void StopTrackingProject(VisualStudioProject project) { AssertIsForeground(); foreach (var scope in _fullSolutionLoadScopes) { if (scope.project == project) { scope.batchScope.Dispose(); _fullSolutionLoadScopes.Remove(scope); break; } } EnsureUnsubscribedFromRunningDocumentTableEventsIfNoLongerNeeded(); } private void StopTrackingAllProjects() { AssertIsForeground(); foreach (var (_, _, batchScope) in _fullSolutionLoadScopes) { batchScope.Dispose(); } _fullSolutionLoadScopes.Clear(); EnsureUnsubscribedFromRunningDocumentTableEventsIfNoLongerNeeded(); } private void StopTrackingAllProjectsMatchingHierarchy(IVsHierarchy hierarchy) { AssertIsForeground(); for (var i = 0; i < _fullSolutionLoadScopes.Count; i++) { if (_fullSolutionLoadScopes[i].hierarchy == hierarchy) { _fullSolutionLoadScopes[i].batchScope.Dispose(); _fullSolutionLoadScopes.RemoveAt(i); // Go back by one so we re-check the same index i--; } } EnsureUnsubscribedFromRunningDocumentTableEventsIfNoLongerNeeded(); } private void EnsureSubscribedToSolutionEvents() { AssertIsForeground(); if (_isSubscribedToSolutionEvents) { return; } var solution = (IVsSolution)_serviceProvider.GetService(typeof(SVsSolution)); // We never unsubscribe from these, so we just throw out the cookie. We could consider unsubscribing if/when all our // projects are unloaded, but it seems fairly unnecessary -- it'd only be useful if somebody closed one solution but then // opened other solutions in entirely different languages from there. if (ErrorHandler.Succeeded(solution.AdviseSolutionEvents(new SolutionEventsEventSink(this), out _))) { _isSubscribedToSolutionEvents = true; } // It's possible that we're loading after the solution has already fully loaded, so see if we missed the event var shellMonitorSelection = (IVsMonitorSelection)_serviceProvider.GetService(typeof(SVsShellMonitorSelection)); if (ErrorHandler.Succeeded(shellMonitorSelection.GetCmdUIContextCookie(VSConstants.UICONTEXT.SolutionExistsAndFullyLoaded_guid, out var fullyLoadedContextCookie))) { if (ErrorHandler.Succeeded(shellMonitorSelection.IsCmdUIContextActive(fullyLoadedContextCookie, out var fActive)) && fActive != 0) { _solutionLoaded = true; } } } private void EnsureSubscribedToRunningDocumentTableEvents() { AssertIsForeground(); if (_runningDocumentTableEventsCookie.HasValue) { return; } var runningDocumentTable = (IVsRunningDocumentTable)_serviceProvider.GetService(typeof(SVsRunningDocumentTable)); if (ErrorHandler.Succeeded(runningDocumentTable.AdviseRunningDocTableEvents(new RunningDocumentTableEventSink(this, runningDocumentTable), out var runningDocumentTableEventsCookie))) { _runningDocumentTableEventsCookie = runningDocumentTableEventsCookie; } } private void EnsureUnsubscribedFromRunningDocumentTableEventsIfNoLongerNeeded() { AssertIsForeground(); if (!_runningDocumentTableEventsCookie.HasValue) { return; } // If we don't have any scopes left, then there is no reason to be subscribed to Running Document Table events, because // there won't be any scopes to complete. if (_fullSolutionLoadScopes.Count > 0) { return; } var runningDocumentTable = (IVsRunningDocumentTable)_serviceProvider.GetService(typeof(SVsRunningDocumentTable)); runningDocumentTable.UnadviseRunningDocTableEvents(_runningDocumentTableEventsCookie.Value); _runningDocumentTableEventsCookie = null; } private class SolutionEventsEventSink : IVsSolutionEvents, IVsSolutionLoadEvents { private readonly SolutionEventsBatchScopeCreator _scopeCreator; public SolutionEventsEventSink(SolutionEventsBatchScopeCreator scopeCreator) => _scopeCreator = scopeCreator; int IVsSolutionLoadEvents.OnBeforeOpenSolution(string pszSolutionFilename) { Contract.ThrowIfTrue(_scopeCreator._fullSolutionLoadScopes.Any()); _scopeCreator._solutionLoaded = false; return VSConstants.S_OK; } int IVsSolutionEvents.OnBeforeCloseSolution(object pUnkReserved) { _scopeCreator._solutionLoaded = false; return VSConstants.S_OK; } int IVsSolutionEvents.OnAfterOpenSolution(object pUnkReserved, int fNewSolution) { _scopeCreator._solutionLoaded = true; _scopeCreator.StopTrackingAllProjects(); return VSConstants.S_OK; } #region Unimplemented Members int IVsSolutionLoadEvents.OnAfterBackgroundSolutionLoadComplete() => VSConstants.E_NOTIMPL; int IVsSolutionEvents.OnAfterOpenProject(IVsHierarchy pHierarchy, int fAdded) => VSConstants.E_NOTIMPL; int IVsSolutionEvents.OnQueryCloseProject(IVsHierarchy pHierarchy, int fRemoving, ref int pfCancel) => VSConstants.E_NOTIMPL; int IVsSolutionEvents.OnBeforeCloseProject(IVsHierarchy pHierarchy, int fRemoved) => VSConstants.E_NOTIMPL; int IVsSolutionEvents.OnAfterLoadProject(IVsHierarchy pStubHierarchy, IVsHierarchy pRealHierarchy) => VSConstants.E_NOTIMPL; int IVsSolutionEvents.OnQueryUnloadProject(IVsHierarchy pRealHierarchy, ref int pfCancel) => VSConstants.E_NOTIMPL; int IVsSolutionEvents.OnBeforeUnloadProject(IVsHierarchy pRealHierarchy, IVsHierarchy pStubHierarchy) => VSConstants.E_NOTIMPL; int IVsSolutionEvents.OnQueryCloseSolution(object pUnkReserved, ref int pfCancel) => VSConstants.E_NOTIMPL; int IVsSolutionEvents.OnAfterCloseSolution(object pUnkReserved) => VSConstants.E_NOTIMPL; int IVsSolutionLoadEvents.OnBeforeBackgroundSolutionLoadBegins() => VSConstants.E_NOTIMPL; int IVsSolutionLoadEvents.OnQueryBackgroundLoadProjectBatch(out bool pfShouldDelayLoadToNextIdle) { pfShouldDelayLoadToNextIdle = false; return VSConstants.E_NOTIMPL; } int IVsSolutionLoadEvents.OnBeforeLoadProjectBatch(bool fIsBackgroundIdleBatch) => VSConstants.E_NOTIMPL; int IVsSolutionLoadEvents.OnAfterLoadProjectBatch(bool fIsBackgroundIdleBatch) => VSConstants.E_NOTIMPL; #endregion } private class RunningDocumentTableEventSink : IVsRunningDocTableEvents { private readonly SolutionEventsBatchScopeCreator _scopeCreator; private readonly IVsRunningDocumentTable4 _runningDocumentTable; public RunningDocumentTableEventSink(SolutionEventsBatchScopeCreator scopeCreator, IVsRunningDocumentTable runningDocumentTable) { _scopeCreator = scopeCreator; _runningDocumentTable = (IVsRunningDocumentTable4)runningDocumentTable; } int IVsRunningDocTableEvents.OnAfterFirstDocumentLock(uint docCookie, uint dwRDTLockType, uint dwReadLocksRemaining, uint dwEditLocksRemaining) { _runningDocumentTable.GetDocumentHierarchyItem(docCookie, out var hierarchy, out _); // Some document is being opened in this project; we need to ensure the project is fully updated so any requests // for CodeModel or the workspace are successful. _scopeCreator.StopTrackingAllProjectsMatchingHierarchy(hierarchy); return VSConstants.S_OK; } #region Unimplemented Members int IVsRunningDocTableEvents.OnBeforeLastDocumentUnlock(uint docCookie, uint dwRDTLockType, uint dwReadLocksRemaining, uint dwEditLocksRemaining) => VSConstants.E_NOTIMPL; int IVsRunningDocTableEvents.OnAfterSave(uint docCookie) => VSConstants.E_NOTIMPL; int IVsRunningDocTableEvents.OnAfterAttributeChange(uint docCookie, uint grfAttribs) => VSConstants.E_NOTIMPL; int IVsRunningDocTableEvents.OnBeforeDocumentWindowShow(uint docCookie, int fFirstShow, IVsWindowFrame pFrame) => VSConstants.E_NOTIMPL; int IVsRunningDocTableEvents.OnAfterDocumentWindowHide(uint docCookie, IVsWindowFrame pFrame) => VSConstants.E_NOTIMPL; #endregion } } }
{ "content_hash": "832d4729475c3bb86cda95bd62b6ade0", "timestamp": "", "source": "github", "line_count": 295, "max_line_length": 234, "avg_line_length": 40.43728813559322, "alnum_prop": 0.6542040405733925, "repo_name": "genlu/roslyn", "id": "83ca08b51eda55ff4182fa93c03881bc0726d368", "size": "11931", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "src/VisualStudio/Core/Def/Implementation/ProjectSystem/Legacy/SolutionEventsBatchScopeCreator.cs", "mode": "33188", "license": "mit", "language": [ { "name": "1C Enterprise", "bytes": "257760" }, { "name": "Batchfile", "bytes": "9059" }, { "name": "C#", "bytes": "139228314" }, { "name": "C++", "bytes": "5602" }, { "name": "CMake", "bytes": "9153" }, { "name": "Dockerfile", "bytes": "2450" }, { "name": "F#", "bytes": "549" }, { "name": "PowerShell", "bytes": "242675" }, { "name": "Shell", "bytes": "92965" }, { "name": "Visual Basic .NET", "bytes": "71735255" } ], "symlink_target": "" }
FROM netengine/base:0.1.1 MAINTAINER team@netengine.com.au # Install postgresql RUN echo "deb http://apt.postgresql.org/pub/repos/apt/ trusty-pgdg main" >> /etc/apt/sources.list RUN ansible local --connection=local -m apt_key -a "url=https://www.postgresql.org/media/keys/ACCC4CF8.asc state=present" RUN apt-get update RUN ansible local --connection=local -m apt -a "pkg=postgresql-9.3 state=present" RUN ansible local --connection=local -m apt -a "pkg=postgresql-contrib-9.3 state=present" # Configure postgresql ADD files /config RUN cp /config/postgresql_service.json /consul/config/postgresql_service.json RUN chown -R netengine:netengine /config RUN ansible local --connection=local -m file -a "state=directory path=/etc/service/postgres owner=root group=root" RUN ansible local --connection=local -m copy -a "src=/config/run dest=/etc/service/postgres/run owner=root group=root mode=0555" # Install bootstrapping script for new /shared-data volumes RUN ansible local --connection=local -m file -a "path=/config/prepare_shared_data_volume owner=netengine group=netengine mode=0555" # Clean up RUN apt-get clean && rm -rf /var/lib/apt/lists/* /tmp/* /var/tmp/* # Start Runit CMD ["/sbin/my_init"]
{ "content_hash": "19b084fd7fee7e90be7b29b1d249a172", "timestamp": "", "source": "github", "line_count": 25, "max_line_length": 131, "avg_line_length": 48.24, "alnum_prop": 0.7645107794361525, "repo_name": "net-engine/docker-postgresql", "id": "663f09149faaad11a5ac76ea7ce94ba9574b4475", "size": "1206", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "Dockerfile", "mode": "33188", "license": "mit", "language": [ { "name": "Shell", "bytes": "1206" } ], "symlink_target": "" }
using System; using Assets.Common.StandardAssets.CrossPlatformInput.Scripts; using UnityEngine; namespace Assets.Common.StandardAssets.Characters.FirstPersonCharacter.Scripts { [RequireComponent(typeof (Rigidbody))] [RequireComponent(typeof (CapsuleCollider))] [AddComponentMenu("Scripts/Standard Assets/Characters/First Person/Rigidbody First Person Controller")] public class RigidbodyFirstPersonController : MonoBehaviour { [Serializable] public class MovementSettings { public float ForwardSpeed = 8.0f; // Speed when walking forward public float BackwardSpeed = 4.0f; // Speed when walking backwards public float StrafeSpeed = 4.0f; // Speed when walking sideways public float RunMultiplier = 2.0f; // Speed when sprinting public KeyCode RunKey = KeyCode.LeftShift; public float JumpForce = 30f; public AnimationCurve SlopeCurveModifier = new AnimationCurve(new Keyframe(-90.0f, 1.0f), new Keyframe(0.0f, 1.0f), new Keyframe(90.0f, 0.0f)); [HideInInspector] public float CurrentTargetSpeed = 8f; #if !MOBILE_INPUT private bool m_Running; #endif public void UpdateDesiredTargetSpeed(Vector2 input) { if (input == Vector2.zero) return; if (input.x > 0 || input.x < 0) { // strafe CurrentTargetSpeed = StrafeSpeed; } if (input.y < 0) { // backwards CurrentTargetSpeed = BackwardSpeed; } if (input.y > 0) { // forwards // handled last as if strafing and moving forward at the same time forwards speed should take precedence CurrentTargetSpeed = ForwardSpeed; } #if !MOBILE_INPUT if (Input.GetKey(RunKey)) { CurrentTargetSpeed *= RunMultiplier; m_Running = true; } else { m_Running = false; } #endif } #if !MOBILE_INPUT public bool Running { get { return m_Running; } } #endif } [Serializable] public class AdvancedSettings { public float groundCheckDistance = 0.01f; // distance for checking if the controller is grounded ( 0.01f seems to work best for this ) public float stickToGroundHelperDistance = 0.5f; // stops the character public float slowDownRate = 20f; // rate at which the controller comes to a stop when there is no input public bool airControl; // can the user control the direction that is being moved in the air [Tooltip("set it to 0.1 or more if you get stuck in wall")] public float shellOffset; // reduce the radius by that ratio to avoid getting stuck in wall (a value of 0.1f is nice) } public Camera cam; public MovementSettings movementSettings = new MovementSettings(); public MouseLook mouseLook = new MouseLook(); public AdvancedSettings advancedSettings = new AdvancedSettings(); private Rigidbody m_RigidBody; private CapsuleCollider m_Capsule; private float m_YRotation; private Vector3 m_GroundContactNormal; private bool m_Jump; private bool m_PreviouslyGrounded; private bool m_Jumping; private bool m_IsGrounded; public Vector3 Velocity { get { return m_RigidBody.velocity; } } public bool Grounded { get { return m_IsGrounded; } } public bool Jumping { get { return m_Jumping; } } public bool Running { get { #if !MOBILE_INPUT return movementSettings.Running; #else return false; #endif } } private void Start() { m_RigidBody = GetComponent<Rigidbody>(); m_Capsule = GetComponent<CapsuleCollider>(); mouseLook.Init (transform, cam.transform); } private void Update() { RotateView(); if (CrossPlatformInputManager.GetButtonDown("Jump") && !m_Jump) { m_Jump = true; } } private void FixedUpdate() { GroundCheck(); Vector2 input = GetInput(); if ((Mathf.Abs(input.x) > float.Epsilon || Mathf.Abs(input.y) > float.Epsilon) && (advancedSettings.airControl || m_IsGrounded)) { // always move along the camera forward as it is the direction that it being aimed at Vector3 desiredMove = cam.transform.forward*input.y + cam.transform.right*input.x; desiredMove = Vector3.ProjectOnPlane(desiredMove, m_GroundContactNormal).normalized; desiredMove.x = desiredMove.x*movementSettings.CurrentTargetSpeed; desiredMove.z = desiredMove.z*movementSettings.CurrentTargetSpeed; desiredMove.y = desiredMove.y*movementSettings.CurrentTargetSpeed; if (m_RigidBody.velocity.sqrMagnitude < (movementSettings.CurrentTargetSpeed*movementSettings.CurrentTargetSpeed)) { m_RigidBody.AddForce(desiredMove*SlopeMultiplier(), ForceMode.Impulse); } } if (m_IsGrounded) { m_RigidBody.drag = 5f; if (m_Jump) { m_RigidBody.drag = 0f; m_RigidBody.velocity = new Vector3(m_RigidBody.velocity.x, 0f, m_RigidBody.velocity.z); m_RigidBody.AddForce(new Vector3(0f, movementSettings.JumpForce, 0f), ForceMode.Impulse); m_Jumping = true; } if (!m_Jumping && Mathf.Abs(input.x) < float.Epsilon && Mathf.Abs(input.y) < float.Epsilon && m_RigidBody.velocity.magnitude < 1f) { m_RigidBody.Sleep(); } } else { m_RigidBody.drag = 0f; if (m_PreviouslyGrounded && !m_Jumping) { StickToGroundHelper(); } } m_Jump = false; } private float SlopeMultiplier() { float angle = Vector3.Angle(m_GroundContactNormal, Vector3.up); return movementSettings.SlopeCurveModifier.Evaluate(angle); } private void StickToGroundHelper() { RaycastHit hitInfo; if (Physics.SphereCast(transform.position, m_Capsule.radius * (1.0f - advancedSettings.shellOffset), Vector3.down, out hitInfo, ((m_Capsule.height/2f) - m_Capsule.radius) + advancedSettings.stickToGroundHelperDistance, Physics.AllLayers, QueryTriggerInteraction.Ignore)) { if (Mathf.Abs(Vector3.Angle(hitInfo.normal, Vector3.up)) < 85f) { m_RigidBody.velocity = Vector3.ProjectOnPlane(m_RigidBody.velocity, hitInfo.normal); } } } private Vector2 GetInput() { Vector2 input = new Vector2 { x = CrossPlatformInputManager.GetAxis("Horizontal"), y = CrossPlatformInputManager.GetAxis("Vertical") }; movementSettings.UpdateDesiredTargetSpeed(input); return input; } private void RotateView() { // avoids the mouse looking if the game is effectively paused if (Mathf.Abs(Time.timeScale) < float.Epsilon) return; // get the rotation before it's changed float oldYRotation = transform.eulerAngles.y; mouseLook.LookRotation (transform, cam.transform); if (m_IsGrounded || advancedSettings.airControl) { // Rotate the rigidbody velocity to match the new direction that the character is looking Quaternion velRotation = Quaternion.AngleAxis(transform.eulerAngles.y - oldYRotation, Vector3.up); m_RigidBody.velocity = velRotation*m_RigidBody.velocity; } } /// sphere cast down just beyond the bottom of the capsule to see if the capsule is colliding round the bottom private void GroundCheck() { m_PreviouslyGrounded = m_IsGrounded; RaycastHit hitInfo; if (Physics.SphereCast(transform.position, m_Capsule.radius * (1.0f - advancedSettings.shellOffset), Vector3.down, out hitInfo, ((m_Capsule.height/2f) - m_Capsule.radius) + advancedSettings.groundCheckDistance, Physics.AllLayers, QueryTriggerInteraction.Ignore)) { m_IsGrounded = true; m_GroundContactNormal = hitInfo.normal; } else { m_IsGrounded = false; m_GroundContactNormal = Vector3.up; } if (!m_PreviouslyGrounded && m_IsGrounded && m_Jumping) { m_Jumping = false; } } } }
{ "content_hash": "f485ca845e8abd48ef78a2eeda7ebebd", "timestamp": "", "source": "github", "line_count": 274, "max_line_length": 169, "avg_line_length": 34.21167883211679, "alnum_prop": 0.565500320034137, "repo_name": "LewisJohnson/unity-ui-examples", "id": "a83176e7c93c4288b263791418ee925aeab1e1f0", "size": "9374", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "Assets/Common/StandardAssets/Characters/FirstPersonCharacter/Scripts/RigidbodyFirstPersonController.cs", "mode": "33188", "license": "mit", "language": [ { "name": "C#", "bytes": "243982" }, { "name": "Python", "bytes": "1748" }, { "name": "ShaderLab", "bytes": "1013" } ], "symlink_target": "" }
package com.intellij.codeInsight; import com.intellij.core.JavaPsiBundle; import com.intellij.icons.AllIcons; import com.intellij.ide.util.ClassFilter; import com.intellij.ide.util.TreeClassChooser; import com.intellij.ide.util.TreeClassChooserFactory; import com.intellij.java.JavaBundle; import com.intellij.openapi.actionSystem.AnActionEvent; import com.intellij.openapi.project.Project; import com.intellij.psi.PsiClass; import com.intellij.psi.search.GlobalSearchScope; import com.intellij.ui.*; import com.intellij.ui.table.JBTable; import com.intellij.util.ui.EmptyIcon; import com.intellij.util.ui.JBDimension; import com.intellij.util.ui.JBUI; import org.jetbrains.annotations.NonNls; import org.jetbrains.annotations.NotNull; import javax.swing.*; import javax.swing.table.DefaultTableColumnModel; import javax.swing.table.DefaultTableModel; import javax.swing.table.TableCellRenderer; import javax.swing.table.TableColumn; import java.awt.*; import java.util.ArrayList; import java.util.HashSet; import java.util.List; import java.util.Set; public class AnnotationsPanel { private final Project myProject; private String myDefaultAnnotation; private final Set<String> myDefaultAnnotations; private final JBTable myTable; private final JPanel myComponent; protected final DefaultTableModel myTableModel; public AnnotationsPanel(Project project, @NonNls String name, String defaultAnnotation, List<String> annotations, List<String> defaultAnnotations, Set<String> checkedAnnotations, boolean showInstrumentationOptions, boolean showDefaultActions) { myProject = project; myDefaultAnnotation = defaultAnnotation; myDefaultAnnotations = new HashSet<>(defaultAnnotations); myTableModel = new DefaultTableModel() { @Override public boolean isCellEditable(int row, int column) { return column == 1; } }; myTableModel.setColumnCount(showInstrumentationOptions ? 2 : 1); for (String annotation : annotations) { addRow(annotation, checkedAnnotations.contains(annotation)); } DefaultTableColumnModel columnModel = new DefaultTableColumnModel(); columnModel.addColumn(new TableColumn(0, 100, new ColoredTableCellRenderer() { @Override public void acquireState(JTable table, boolean isSelected, boolean hasFocus, int row, int column) { super.acquireState(table, isSelected, false, row, column); } @Override protected void customizeCellRenderer(@NotNull JTable table, Object value, boolean selected, boolean hasFocus, int row, int column) { append((String)value, SimpleTextAttributes.REGULAR_ATTRIBUTES); if (value.equals(myDefaultAnnotation)) { setIcon(AllIcons.Actions.Forward); } else { setIcon(EmptyIcon.ICON_16); } } }, null)); myTable = new JBTable(myTableModel, columnModel); if (showInstrumentationOptions) { columnModel.getColumn(0).setHeaderValue(JavaPsiBundle.message("node.annotation.tooltip")); TableColumn checkColumn = new TableColumn(1, 100, new BooleanTableCellRenderer(), new BooleanTableCellEditor()); columnModel.addColumn(checkColumn); checkColumn.setHeaderValue(" Instrument "); TableCellRenderer defaultRenderer = myTable.getTableHeader().getDefaultRenderer(); TableCellRenderer headerRenderer = new TableCellRenderer() { @Override public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int column) { Component component = defaultRenderer.getTableCellRendererComponent(table, value, isSelected, hasFocus, row, column); if (component instanceof JComponent) { ((JComponent)component) .setToolTipText(column == 1 ? JavaBundle.message("nullable.notnull.annotations.runtime.instrumentation.tooltip") : null); } return component; } }; myTable.getTableHeader().setDefaultRenderer(headerRenderer); checkColumn.setHeaderRenderer(headerRenderer); checkColumn.sizeWidthToFit(); } final AnActionButton selectButton = new AnActionButton(JavaBundle.messagePointer("action.AnActionButton.text.select.annotation.used.for.code.generation"), AllIcons.Actions.Checked) { @Override public void actionPerformed(@NotNull AnActionEvent e) { String selectedValue = getSelectedAnnotation(); if (selectedValue == null) return; myDefaultAnnotation = selectedValue; // to show the new default value in the ui myTableModel.fireTableRowsUpdated(myTable.getSelectedRow(), myTable.getSelectedRow()); } @Override public void updateButton(@NotNull AnActionEvent e) { String selectedValue = getSelectedAnnotation(); e.getPresentation().setEnabled(selectedValue != null && !selectedValue.equals(myDefaultAnnotation)); } }; final ToolbarDecorator toolbarDecorator = ToolbarDecorator.createDecorator(myTable).disableUpDownActions() .setAddAction(b -> chooseAnnotation(name)) .setRemoveAction(new AnActionButtonRunnable() { @Override public void run(AnActionButton anActionButton) { String selectedValue = getSelectedAnnotation(); if (selectedValue == null) return; if (myDefaultAnnotation.equals(selectedValue)) myDefaultAnnotation = (String)myTable.getValueAt(0, 0); myTableModel.removeRow(myTable.getSelectedRow()); } }) .setRemoveActionUpdater(e -> !myDefaultAnnotations.contains(getSelectedAnnotation())); if (showDefaultActions) { toolbarDecorator.addExtraAction(selectButton); } final JPanel panel = toolbarDecorator.createPanel(); myComponent = new JPanel(new BorderLayout()); myComponent.setBorder(IdeBorderFactory.createTitledBorder(JavaBundle.message("nullable.notnull.annotations.panel.title", name), false, JBUI.insetsTop(10))); myComponent.add(panel); myComponent.setPreferredSize(new JBDimension(myComponent.getPreferredSize().width, 200)); myTable.setSelectionMode(ListSelectionModel.SINGLE_SELECTION); myTable.setRowSelectionAllowed(true); myTable.setShowGrid(false); selectAnnotation(myDefaultAnnotation); } private void addRow(String annotation, boolean checked) { myTableModel.addRow(new Object[]{annotation, checked}); } private Integer selectAnnotation(String annotation) { for (int i = 0; i < myTable.getRowCount(); i++) { if (annotation.equals(myTable.getValueAt(i, 0))) { myTable.setRowSelectionInterval(i, i); return i; } } return null; } private String getSelectedAnnotation() { int selectedRow = myTable.getSelectedRow(); return selectedRow < 0 ? null : (String)myTable.getValueAt(selectedRow, 0); } private void chooseAnnotation(String title) { final TreeClassChooser chooser = TreeClassChooserFactory.getInstance(myProject) .createNoInnerClassesScopeChooser(JavaBundle.message("dialog.title.choose.annotation", title), GlobalSearchScope.allScope(myProject), new ClassFilter() { @Override public boolean isAccepted(PsiClass aClass) { return aClass.isAnnotationType(); } }, null); chooser.showDialog(); final PsiClass selected = chooser.getSelected(); if (selected == null) { return; } final String qualifiedName = selected.getQualifiedName(); if (selectAnnotation(qualifiedName) == null) { addRow(qualifiedName, false); } } public JComponent getComponent() { return myComponent; } String getDefaultAnnotation() { return myDefaultAnnotation; } public String[] getAnnotations() { int size = myTable.getRowCount(); String[] result = new String[size]; for (int i = 0; i < size; i++) { result[i] = (String)myTable.getValueAt(i, 0); } return result; } List<String> getCheckedAnnotations() { List<String> result = new ArrayList<>(); for (int i = 0; i < myTable.getRowCount(); i++) { if (Boolean.TRUE.equals(myTable.getValueAt(i, 1))) { result.add((String)myTable.getValueAt(i, 0)); } } return result; } }
{ "content_hash": "6f48705ce0e8594a0d824a913ade7c5c", "timestamp": "", "source": "github", "line_count": 231, "max_line_length": 160, "avg_line_length": 38.85281385281385, "alnum_prop": 0.6620612813370473, "repo_name": "allotria/intellij-community", "id": "801abb6503ccf48633321a47c41a589afc2fefcb", "size": "9116", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "java/openapi/src/com/intellij/codeInsight/AnnotationsPanel.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "AMPL", "bytes": "20665" }, { "name": "AspectJ", "bytes": "182" }, { "name": "Batchfile", "bytes": "60580" }, { "name": "C", "bytes": "195249" }, { "name": "C#", "bytes": "1264" }, { "name": "C++", "bytes": "195810" }, { "name": "CMake", "bytes": "1675" }, { "name": "CSS", "bytes": "201445" }, { "name": "CoffeeScript", "bytes": "1759" }, { "name": "Erlang", "bytes": "10" }, { "name": "Groovy", "bytes": "3197810" }, { "name": "HLSL", "bytes": "57" }, { "name": "HTML", "bytes": "1891055" }, { "name": "J", "bytes": "5050" }, { "name": "Java", "bytes": "164463076" }, { "name": "JavaScript", "bytes": "570364" }, { "name": "Jupyter Notebook", "bytes": "93222" }, { "name": "Kotlin", "bytes": "4240307" }, { "name": "Lex", "bytes": "147047" }, { "name": "Makefile", "bytes": "2352" }, { "name": "NSIS", "bytes": "51270" }, { "name": "Objective-C", "bytes": "27941" }, { "name": "Perl", "bytes": "903" }, { "name": "Perl6", "bytes": "26" }, { "name": "Protocol Buffer", "bytes": "6680" }, { "name": "Python", "bytes": "25385564" }, { "name": "Roff", "bytes": "37534" }, { "name": "Ruby", "bytes": "1217" }, { "name": "Scala", "bytes": "11698" }, { "name": "Shell", "bytes": "65705" }, { "name": "Smalltalk", "bytes": "338" }, { "name": "TeX", "bytes": "25473" }, { "name": "Thrift", "bytes": "1846" }, { "name": "TypeScript", "bytes": "9469" }, { "name": "Visual Basic", "bytes": "77" }, { "name": "XSLT", "bytes": "113040" } ], "symlink_target": "" }
My Site ====== My Site is the personal website of Michael Mello. This project is an ongoing effort to strengthen my knowledge of web development and software in general. Technologies ------------------ * ASP.NET MVC 4 * C# * HTML5 * CSS3 * LESS * jQuery * Bootstrap License ------------------ The MIT License (MIT) Copyright (c) 2013 Michael Mello 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.
{ "content_hash": "615b77bce7631a1fd832479f58a7fcf5", "timestamp": "", "source": "github", "line_count": 40, "max_line_length": 80, "avg_line_length": 34.575, "alnum_prop": 0.7657266811279827, "repo_name": "michaelmello/mysite", "id": "eb0930f5359a998689b509b6a563c7b08dd6e7f4", "size": "1383", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "README.md", "mode": "33188", "license": "mit", "language": [ { "name": "ASP", "bytes": "103" }, { "name": "C#", "bytes": "4324" }, { "name": "CSS", "bytes": "157708" }, { "name": "JavaScript", "bytes": "221608" } ], "symlink_target": "" }
package br.usp.each.saeg.code.forest.primitive; import br.usp.each.saeg.code.forest.metaphor.*; public interface CodeInformation { CodeGeometry getGeometry(); }
{ "content_hash": "04a74a4a3a71297408ce745546c9eef7", "timestamp": "", "source": "github", "line_count": 8, "max_line_length": 47, "avg_line_length": 22, "alnum_prop": 0.7329545454545454, "repo_name": "saeg/code-forest", "id": "533d570653a902fe3d55b9e869f77ca9ee4b3a46", "size": "176", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "code-forest-standalone/src/br/usp/each/saeg/code/forest/primitive/CodeInformation.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Java", "bytes": "392443" } ], "symlink_target": "" }
$(document).ready(function (){ var scanner = new Scanner(); scanner.init('#test0'); scanner.controllerDivStyle=''; scanner.controlBarStyle='background-color:#999;'; //Set control bar at bottom of page //scanner.setControlBar("bottom"); scanner.setControlBar("top"); //Insert scanPanel before #test0 div scanner.setScanPanel("#test0",'before'); //set actions to each buttons in #test0 for (var j = 0, len = 5; j < len; j+=1) { scanner.actions[j]=[]; for (var i = 0, slen = 5; i < slen; i+=1) { scanner.actions[j].push(function(){ var elem=scanner.getElem(); var col = scanner.getSelCol(); var row = scanner.getSelRow(); var val = $(elem +' tr:eq('+row+') td:eq('+col+')').children().first().prop('id'); alert(val); } ); } } scanner.toggleButtonDisable('#stop_test0',true); $('#txtPB').click(function (){ }); $('#stop_test0').click(function (){ scanner.stopTimer(); scanner.toggleButtonDisable('#start_test0',false); scanner.toggleButtonDisable('#select_test0',true); scanner.toggleButtonDisable('#stop_test0',true); }); $('#start_test0').on('click',function(){ scanner.startTimer('row',scanner.scanSpeed); scanner.toggleButtonDisable('#start_test0',true); scanner.toggleButtonDisable('#changeScanSpeed_test0',true); scanner.toggleButtonDisable('#select_test0',false); scanner.toggleButtonDisable('#stop_test0',false); }); scanner.toggleButtonDisable('#start_test0',false); $('#select_test0').on('click',function(){ scanner.selectItem(); scanner.toggleButtonDisable('#start_test0',true); }); $('#scanModeOnOff_test0').on('click',function(){ scanner.toggleScanOnOff(); }); $('#scanModeOnOff_test0').mouseenter(function(){ $('#test0').css('background-color','red'); }).mouseleave(function(){ $('#test0').css('background-color',''); }); $('#changeScanSpeed_test0').on('click',function(){ scanner.setSpeedScan($('#scanSpeed_test0').val()); }); $('#scanSpeed_test0').keyup(function(){ if (($(this).val().length>0 && !isNaN(parseInt($(this).val())))) { scanner.toggleButtonDisable('#changeScanSpeed_test0',false); }else{ scanner.toggleButtonDisable('#changeScanSpeed_test0',true); } }); }); $(document).ready(function (){ //Set click event to each buttons in #test0 $('#test0 :button').on('click',function(){ alert($(this).val()+' is clicked.'); }); }); $(document).ready(function (){ var scanner = new Scanner(); scanner.init('#test'); scanner.controllerDivStyle='background-color: yellow; width: 200px;'; scanner.selectColor='green'; //control bar is already set, so item will only append to control bar scanner.setControlBar(); //Insert scanPanel after #test3 div scanner.setScanPanel("#test3"); scanner.toggleButtonDisable('#stop_test',true); $('#txtPB').click(function (){ }); $('#stop_test').click(function (){ scanner.stopTimer(); scanner.toggleButtonDisable('#start_test',false); scanner.toggleButtonDisable('#select_test',true); scanner.toggleButtonDisable('#stop_test',true); }); $('#start_test').on('click',function(){ scanner.startTimer('row',scanner.scanSpeed); scanner.toggleButtonDisable('#start_test',true); scanner.toggleButtonDisable('#changeScanSpeed_test',true); scanner.toggleButtonDisable('#select_test',false); scanner.toggleButtonDisable('#stop_test',false); }); scanner.toggleButtonDisable('#start_test',false); $('#select_test').on('click',function(){ scanner.selectItem(); scanner.toggleButtonDisable('#start_test',true); }); $('#scanModeOnOff_test').on('click',function(){ scanner.toggleScanOnOff(); }); $('#scanModeOnOff_test').mouseenter(function(){ $('#test').css('background-color','red'); }).mouseleave(function(){ $('#test').css('background-color',''); }); $('#changeScanSpeed_test').on('click',function(){ scanner.setSpeedScan($('#scanSpeed_test').val()); }); $('#scanSpeed_test').keyup(function(){ if (($(this).val().length>0 && !isNaN(parseInt($(this).val())))) { scanner.toggleButtonDisable('#changeScanSpeed_test',false); }else{ scanner.toggleButtonDisable('#changeScanSpeed_test',true); } }); });
{ "content_hash": "c51b1c74f315ac2759d9318451873470", "timestamp": "", "source": "github", "line_count": 128, "max_line_length": 91, "avg_line_length": 35.0234375, "alnum_prop": 0.6163283515503012, "repo_name": "eronde/Scanner-js", "id": "c56b8af9a10d05e056eb88d45913193aa64a493b", "size": "4483", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "libs/js/init.js", "mode": "33188", "license": "mit", "language": [ { "name": "HTML", "bytes": "3909" }, { "name": "JavaScript", "bytes": "13502" } ], "symlink_target": "" }
struct CvCascadeBoostParams : CvBoostParams { float minHitRate; float maxFalseAlarm; CvCascadeBoostParams(); CvCascadeBoostParams( int _boostType, float _minHitRate, float _maxFalseAlarm, double _weightTrimRate, int _maxDepth, int _maxWeakCount ); virtual ~CvCascadeBoostParams() {} void write( FileStorage &fs ) const; bool read( const FileNode &node ); virtual void printDefaults() const; virtual void printAttrs() const; virtual bool scanAttr( const String prmName, const String val); }; struct CvCascadeBoostTrainData : CvDTreeTrainData { CvCascadeBoostTrainData( const CvFeatureEvaluator* _featureEvaluator, const CvDTreeParams& _params ); CvCascadeBoostTrainData( const CvFeatureEvaluator* _featureEvaluator, int _numSamples, int _precalcValBufSize, int _precalcIdxBufSize, const CvDTreeParams& _params = CvDTreeParams() ); virtual void setData( const CvFeatureEvaluator* _featureEvaluator, int _numSamples, int _precalcValBufSize, int _precalcIdxBufSize, const CvDTreeParams& _params=CvDTreeParams() ); void precalculate(); virtual const int* get_class_labels( CvDTreeNode* n, int* labelsBuf ); virtual const int* get_cv_labels( CvDTreeNode* n, int* labelsBuf); virtual const int* get_sample_indices( CvDTreeNode* n, int* indicesBuf ); virtual void get_ord_var_data( CvDTreeNode* n, int vi, float* ordValuesBuf, int* sortedIndicesBuf, const float** ordValues, const int** sortedIndices, int* sampleIndicesBuf ); virtual const int* get_cat_var_data( CvDTreeNode* n, int vi, int* catValuesBuf ); virtual float getVarValue( int vi, int si ); virtual void free_train_data(); const CvFeatureEvaluator* featureEvaluator; Mat valCache; // precalculated feature values (CV_32FC1) CvMat _resp; // for casting int numPrecalcVal, numPrecalcIdx; }; class CvCascadeBoostTree : public CvBoostTree { public: virtual CvDTreeNode* predict( int sampleIdx ) const; void write( FileStorage &fs, const Mat& featureMap ); void read( const FileNode &node, CvBoost* _ensemble, CvDTreeTrainData* _data ); void markFeaturesInMap( Mat& featureMap ); protected: virtual void split_node_data( CvDTreeNode* n ); }; class CvCascadeBoost : public CvBoost { public: virtual bool train( const CvFeatureEvaluator* _featureEvaluator, int _numSamples, int _precalcValBufSize, int _precalcIdxBufSize, const CvCascadeBoostParams& _params=CvCascadeBoostParams() ); virtual float predict( int sampleIdx, bool returnSum = false ) const; float getThreshold() const { return threshold; }; void write( FileStorage &fs, const Mat& featureMap ) const; bool read( const FileNode &node, const CvFeatureEvaluator* _featureEvaluator, const CvCascadeBoostParams& _params ); void markUsedFeaturesInMap( Mat& featureMap ); protected: virtual bool set_params( const CvBoostParams& _params ); virtual void update_weights( CvBoostTree* tree ); virtual bool isErrDesired(); float threshold; float minHitRate, maxFalseAlarm; }; #endif
{ "content_hash": "7916c35b55f509efae65ad36c7f2cecf", "timestamp": "", "source": "github", "line_count": 78, "max_line_length": 110, "avg_line_length": 42.666666666666664, "alnum_prop": 0.6826923076923077, "repo_name": "eirTony/INDI1", "id": "d4c36898fcf04f38321a9ecbb4b42404d0ab6d8c", "size": "3431", "binary": false, "copies": "5", "ref": "refs/heads/develop", "path": "to/lang/OpenCV-2.2.0/modules/traincascade/boost.h", "mode": "33188", "license": "mit", "language": [ { "name": "Batchfile", "bytes": "2182" }, { "name": "C", "bytes": "987751" }, { "name": "C++", "bytes": "25614243" }, { "name": "CMake", "bytes": "723934" }, { "name": "CSS", "bytes": "175949" }, { "name": "Cuda", "bytes": "311879" }, { "name": "HTML", "bytes": "839417" }, { "name": "Java", "bytes": "127925" }, { "name": "JavaScript", "bytes": "199216" }, { "name": "M4", "bytes": "200" }, { "name": "Makefile", "bytes": "6245411" }, { "name": "Mathematica", "bytes": "284" }, { "name": "Objective-C++", "bytes": "53970" }, { "name": "Prolog", "bytes": "2474" }, { "name": "Python", "bytes": "415039" }, { "name": "QMake", "bytes": "173988" }, { "name": "Shell", "bytes": "3748" }, { "name": "TeX", "bytes": "1530252" } ], "symlink_target": "" }
#include "QmitkDicomPreferencePage.h" #include "QmitkDicomEditor.h" #include <berryIPreferencesService.h> #include <berryIBerryPreferences.h> #include <berryPlatform.h> QmitkDicomPreferencePage::QmitkDicomPreferencePage() : m_MainControl(0) { } QmitkDicomPreferencePage::~QmitkDicomPreferencePage() { } void QmitkDicomPreferencePage::Init(berry::IWorkbench::Pointer ) { } void QmitkDicomPreferencePage::CreateQtControl(QWidget* parent) { berry::IPreferencesService::Pointer prefService= berry::Platform::GetServiceRegistry().GetServiceById<berry::IPreferencesService>(berry::IPreferencesService::ID); m_DicomPreferencesNode = prefService->GetSystemPreferences()->Node(QmitkDicomEditor::EDITOR_ID).Cast<berry::IBerryPreferences>();; assert( m_DicomPreferencesNode ); m_MainControl = new QWidget(parent); m_MainControl->setWindowTitle(QApplication::translate("DicomPreferencePage", "Form", 0, QApplication::UnicodeUTF8)); formLayout = new QFormLayout(m_MainControl); formLayout->setObjectName(QString::fromUtf8("formLayout")); formLayout->setFieldGrowthPolicy(QFormLayout::AllNonFixedFieldsGrow); label = new QLabel(m_MainControl); label->setObjectName(QString::fromUtf8("label")); label->setText(QApplication::translate("DicomPreferencePage", "Database directory:", 0, QApplication::UnicodeUTF8)); formLayout->setWidget(0, QFormLayout::LabelRole, label); DatabaseLineEdit = new QLineEdit(m_MainControl); DatabaseLineEdit->setObjectName(QString::fromUtf8("DatabaseLineEdit")); formLayout->setWidget(0, QFormLayout::FieldRole, DatabaseLineEdit); label_2 = new QLabel(m_MainControl); label_2->setObjectName(QString::fromUtf8("label_2")); label_2->setText(QApplication::translate("DicomPreferencePage", "Dicom listener directory:", 0, QApplication::UnicodeUTF8)); formLayout->setWidget(1, QFormLayout::LabelRole, label_2); ListenerLineEdit = new QLineEdit(m_MainControl); ListenerLineEdit->setObjectName(QString::fromUtf8("ListenerLineEdit")); formLayout->setWidget(1, QFormLayout::FieldRole, ListenerLineEdit); frame = new QFrame(m_MainControl); frame->setObjectName(QString::fromUtf8("frame")); frame->setFrameShape(QFrame::StyledPanel); frame->setFrameShadow(QFrame::Raised); formLayout->setWidget(3, QFormLayout::FieldRole, frame); } QWidget* QmitkDicomPreferencePage::GetQtControl() const { return m_MainControl; } void QmitkDicomPreferencePage::PerformCancel() { } bool QmitkDicomPreferencePage::PerformOk() { return true; } void QmitkDicomPreferencePage::Update() { }
{ "content_hash": "e23c0755482cc56b163fd5d63aa2df0d", "timestamp": "", "source": "github", "line_count": 87, "max_line_length": 134, "avg_line_length": 30.114942528735632, "alnum_prop": 0.7576335877862596, "repo_name": "lsanzdiaz/MITK-BiiG", "id": "6ae67305008e4de97e09e07e85216faf3191810e", "size": "3118", "binary": false, "copies": "3", "ref": "refs/heads/master", "path": "Plugins/org.mitk.gui.qt.dicom/src/internal/QmitkDicomPreferencePage.cpp", "mode": "33188", "license": "bsd-3-clause", "language": [ { "name": "C", "bytes": "2597854" }, { "name": "C++", "bytes": "25201686" }, { "name": "CMake", "bytes": "839468" }, { "name": "CSS", "bytes": "12562" }, { "name": "HTML", "bytes": "6322" }, { "name": "Java", "bytes": "350330" }, { "name": "JavaScript", "bytes": "47660" }, { "name": "Makefile", "bytes": "742" }, { "name": "Objective-C", "bytes": "476189" }, { "name": "Perl", "bytes": "982" }, { "name": "Python", "bytes": "7545" }, { "name": "QML", "bytes": "4829" }, { "name": "QMake", "bytes": "5583" }, { "name": "Shell", "bytes": "5433" }, { "name": "XSLT", "bytes": "30684" } ], "symlink_target": "" }
ES.next examples for better understanding. - [External links](#Links) - [Arrow Functions](#Arrow-Functions) - [Classes](#Classes) - [Enhanced Object Literals](#Enhanced-Object-Literals) - [Template Strings](#Template-Strings) - [Destructuring](#Destructuring) - [Default](#Default) - [Rest](#Rest) - [Spread](#Spread) - [Let + Const](#Let-Const) - [Iterators + For..Of](#Iterators-For-Of) - [Generators](#Generators) - [Comprehensions](#Comprehensions) - [Unicode](#Unicode) - [Modules](#Modules) - [Module Loaders](#Module-Loaders) - [Map + Set + WeakMap + WeakSet](#Map-Set-WeakMap-WeakSet) - [Proxies](#Proxies) - [Symbols](#Symbols) - [Subclassable Built-ins](#Subclassable-Built-ins) - [Math + Number + String + Object APIs](#Math-Number-String-Object-APIs) - [Binary and Octal Literals](#Binary-and-Octal-Literals) - [Promises](#Promises) - [Reflect API](#Reflect-API) - [Tail Calls](#Tail-Calls) <h2 name="Links">External links</h2> * [Airbnb JavaScript Style Guide](https://github.com/airbnb/javascript) (Very good resource with do's and don'ts and why's) <h2 name="Arrow-Functions">Arrow Functions</h2> `(x, y) => {}` is a shorter form for `function (x, y) {}`. But the big difference is that the `this` in the function body is what you most likely expect it to be: that of the outer scope. So for example, this won’t log the name: ```js this.name = 'Jack'; … setTimeout(function(){ console.log(this.name); }, 100); ``` But with the usage of the ES.next arrows, this will work: ```js this.name = 'Jack'; … setTimeout(() => { console.log(this.name); }, 200); ``` A single expression, however, requires no braces: ```js setTimeout(() => console.log(this.name), 300); ``` Single parameter case needs no parentheses around parameter list. ```js let yell = x => x.toUpperCase(); yell("Avast"); // AVAST ``` ### Short forms The following functions all do the same. ```js function(x) { return x * x; }; // old school (x) => { return x * x; }; // ES6 arrow function x => { return x * x; }; // skip parentheses for single args x => x * x; // skip {return …} for simple calls ``` ### Examples ```js var numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]; var index = numbers.map((v, i) => i); // [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] var odds = numbers.filter(v => v % 2); // [1, 3, 5, 7, 9] var evens = odds.map(v => v + 1); // [2, 4, 6, 8, 10] ``` Statement body needs braces, must use `return` explicitly if not void: ```js // Statement bodies var squares = numbers.filter(v => { var root = Math.sqrt(v); return root == Math.floor(root); }); ``` Parenthesize the body to return an object literal expression: ```js var pairs = numbers.map((v, i) => ({value: v, index: i})); ``` ([Run examples above](http://jsbin.com/povipu/edit?js,console)); <h2 name="Classes">Classes</h2> The new `class` in ES.Next offers nice syntax sugar to get started with classes way easier. ```js class Pirate { constructor(name){ this.name = name; this.grogs = 0; } drink(){ this.grogs++; } isDrunk(){ return this.grogs > 10; } } var bill = new Pirate('Bill'); bill.isDrunk(); // returns false ``` ([Run code above](http://jsbin.com/lutalabalu/edit?js,console)) ### Extend classes Classes can `extend` other classes and call their `super` functions. ```js class Pirate { constructor(name){ this.name = name; this.grogs = 0; } drink(){ this.grogs++; } isDrunk(){ return this.grogs > 10; } } class Captain extends Pirate { constructor(name){ super(name); } isDrunk(){ return this.grogs > 50; } } var bill = new Pirate('Bill'), jack = new Captain('Jack'), rounds = 20; while (rounds--) { bill.drink(); jack.drink(); } bill.isDrunk(); // returns true jack.isDrunk(); // returns false ``` ([Run code above](http://jsbin.com/xerefo/edit?js,console)) ### Getter and Setters Also, there are getters and setters: ```js class Treasure { constructor(){ this.coins = 0; } get weight() { return this.coins * 50; } set weight(value) { if (value <= 0) { throw new Error('Avast: weight must be greater than 0!!') } this.coins = value / 50; } } var booty = new Treasure(); console.log(booty.coins, booty.weight); // 0, 0 booty.coins = 10; console.log(booty.weight); // 500 gramm booty.coins++; console.log(booty.weight); // 550 gramm booty.weight = 2000; console.log(booty.coins); // 40 coins booty.weight = -77; // throws an error ``` ([Run code above](http://jsbin.com/qusafi/edit?js,console)) Classes can have static members. Like other languages with static class members, the static keyword will create a method associated with the class, and not with an instance of the class. In other words, you can only reach a static method using the name of the class. Static methods have no access to the fields, properties, and methods defined on an instance of the class using this. ### Examples <h2 name="Enhanced-Object-Literals">Enhanced Object Literals</h2> ### Examples <h2 name="Template-Strings">Template Strings</h2> As there is no *sprintf* or something similar, composing strings in ES5 is a bit painful: ```js var name = 'Jack', greeting = 'Ahoy ' + name + ', welcome on board'; ``` In ES6, template strings got introduced which allow the usage of template variables (`${variable}`) available in the scope and support strings on multiple lines: ```js var name = 'Jack', greeting = `Ahoy ${name}, welcome on board! `; ``` ### Examples ```js // Basic literal string creation `In JavaScript "\n" is a line-feed.` ``` ```js // Multiline strings `In old school JavaScript (ES5) this was not valid but works in ES6. Make sure to use backticks instead of single or double quotes. Yarr!` ``` ```js // Interpolate variable bindings var name = "Jack", drink = "grog", message = `${name} wants another ${drink}!` ``` ```js class Pirate { constructor(name){ this.name = name; } yell(){ console.log(`I am ${this.name}!`); } } var jack = new Pirate('Bill'); jack.yell(); ``` ([Run examples above](http://jsbin.com/faqeci/edit?js,console)) <h2 name="Default">Default</h2> Often a parameter in a function has to be defined. To catch not defined parameters, a check is the first thing that happens in a function: ```js function yell(message) { message = message || 'Arrr'; console.log(message.toUpperCase() + '!'); } yell(); ``` In ES.next, it is possible, to define defaults for parameters, so that check is unnecessary: ```js function yell(message = 'Arrr') { console.log(message.toUpperCase() + '!'); } yell(); // "ARRR!" yell('Avast'); // AVAST! ``` ([Run example above](http://jsbin.com/wuvoso/edit?js,console)) <h2 name="Destructuring">Destructuring</h2> When passing a lot of data to a function it is often done via an `options` object: ```js ajax(‘/todo’, { method: ‘POST’, body: 'Some content') }); ``` Then, to acces these params in ES5, one would assign them manually: ```js function ajax(url, options) { options = options || {}; var body = options.body || '', method = options.method || 'GET'; } ``` In ES.next, we can define these directly: ```js function ajax(url, {body='', method='GET'}) { console.log(method); } ``` This can also be used in assignments: ```js var [a, , b] = [1, 2, 3]; console.log(a, b); // logs: 1, 3 ``` ### Examples ```js function getData() { return { name: 'Jack', age: 33, location: { region: 'Bermuda', island: 'Isle of Devils' } } } var {age, name, location: { region }} = getData(); console.log(age, name, region); // logs: 33, 'Jack', 'Bermuda' ``` ```js var [a] = []; console.log(a); // logs: undefined; // Using a default: var [a = 1] = []; console.log(a); // logs: 1 ``` <h2 name="Rest">Rest</h2> ### Examples <h2 name="Spread">Spread</h2> ### Examples <h2 name="Let-Const">Let + Const</h2> ### Examples <h2 name="Iterators-For-Of">Iterators + For..Of</h2> ### Examples <h2 name="Generators">Generators</h2> ### Examples <h2 name="Comprehensions">Comprehensions</h2> ### Examples <h2 name="Unicode">Unicode</h2> ### Examples <h2 name="Modules">Modules</h2> ES.next introduces module support to prevent filling up the global scope. The syntax is a bit different than the NPM module syntax. When exporting a `default`, it can be imported via giving some name on import: ```js // header.js export default function(){} // app.js import header from ‘header’; ``` But when importing named exports, they have to defined via `{ }` or can be imported with a wildcard: ```js // header.js export function init(){} // app.js import { init } from ‘header’; init(); // or import * as header from ‘header’; header.init(); ``` To just import a module, but not naming it can be done, too: ```js import 'picturefill'; ``` ### Examples ```js // lib/math.js export var pi = 3.141593; // lib/mathplusplus.js export * from "lib/math"; export var e = 2.71828182846; export default function(x) { return Math.exp(x); } // app.js import exp, {pi, e} from "lib/mathplusplus"; alert("2π = " + exp(pi, e)); ``` <h2 name="Module-Loaders">Module Loaders</h2> ### Examples <h2 name="Map-Set-WeakMap-WeakSet">Map + Set + WeakMap + WeakSet</h2> ### Examples <h2 name="Proxies">Proxies</h2> ### Examples <h2 name="Symbols">Symbols</h2> ### Examples <h2 name="Subclassable-Built-ins">Subclassable Built-ins</h2> ### Examples <h2 name="Math-Number-String-Object-APIs">Math + Number + String + Object APIs</h2> ### Examples <h2 name="Binary-and-Octal-Literals">Binary and Octal Literals</h2> ### Examples <h2 name="Promises">Promises</h2> To avoid callback hell, Promises are here for a rescue! Instead of passing in a callback to a function, the function returns a Promise instead. A promise then gets resolved or rejected. See this function: ```js function loadSomething(url) { return new Promise(function(resolve, reject) { request.get(url, function(error, response, body) { if (error) { return reject(error); } resolve(body); }); }); } loadSomething('http://ubilabs.net/') .then(function(body) { console.log(body); return loadSomething('http://ubilabs.net/en'); }) .then(function(body) { console.log(body); }) .catch(function(error) { // Catches any error in the calls above console.error(error); }); ``` ### Promise.all The example above executes the `loadSomething` calls one after the other. To execute them in parallel and get all the results, there is `Promise.all`. We have the same `loadSomething` function available as above. ```js Promise.all([ loadSomething('http://ubilabs.net/'), loadSomething('http://ubilabs.net/en') ]) .then(function(data) { // This is an array with all the data returned by the promises console.log(data); }) .catch(function(error) { // Catches any error in the calls above console.error(error); }) ``` There is a small polyfill library called [lie](https://www.npmjs.com/package/lie). <h2 name="Reflect API">Reflect-API</h2> ### Examples <h2 name="Tail Calls">Tail-Calls</h2> ### Examples
{ "content_hash": "cf2efb619596c95fe8a79ed488821996", "timestamp": "", "source": "github", "line_count": 533, "max_line_length": 383, "avg_line_length": 20.96060037523452, "alnum_prop": 0.6515395631936985, "repo_name": "ubilabs/es-next", "id": "444e01d3ab59eb503dfc75aef3fe1acb0efab054", "size": "11213", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "README.md", "mode": "33188", "license": "mit", "language": [], "symlink_target": "" }
<?php namespace Symfony\Component\OptionsResolver\Tests; use Symfony\Component\OptionsResolver\Options; class OptionsTest extends \PHPUnit_Framework_TestCase { /** * @var Options */ private $options; protected function setUp() { $this->options = new Options(); } public function testArrayAccess() { $this->assertFalse(isset($this->options['foo'])); $this->assertFalse(isset($this->options['bar'])); $this->options['foo'] = 0; $this->options['bar'] = 1; $this->assertTrue(isset($this->options['foo'])); $this->assertTrue(isset($this->options['bar'])); unset($this->options['bar']); $this->assertTrue(isset($this->options['foo'])); $this->assertFalse(isset($this->options['bar'])); $this->assertEquals(0, $this->options['foo']); } public function testCountable() { $this->options->set('foo', 0); $this->options->set('bar', 1); $this->assertCount(2, $this->options); } /** * @expectedException \OutOfBoundsException */ public function testGetNonExisting() { $this->options->get('foo'); } /** * @expectedException Symfony\Component\OptionsResolver\Exception\OptionDefinitionException */ public function testSetNotSupportedAfterGet() { $this->options->set('foo', 'bar'); $this->options->get('foo'); $this->options->set('foo', 'baz'); } /** * @expectedException Symfony\Component\OptionsResolver\Exception\OptionDefinitionException */ public function testRemoveNotSupportedAfterGet() { $this->options->set('foo', 'bar'); $this->options->get('foo'); $this->options->remove('foo'); } public function testSetLazyOption() { $test = $this; $this->options->set('foo', function (Options $options) use ($test) { return 'dynamic'; }); $this->assertEquals('dynamic', $this->options->get('foo')); } public function testSetDiscardsPreviousValue() { $test = $this; // defined by superclass $this->options->set('foo', 'bar'); // defined by subclass $this->options->set('foo', function (Options $options, $previousValue) use ($test) { /* @var \PHPUnit_Framework_TestCase $test */ $test->assertNull($previousValue); return 'dynamic'; }); $this->assertEquals('dynamic', $this->options->get('foo')); } public function testOverloadKeepsPreviousValue() { $test = $this; // defined by superclass $this->options->set('foo', 'bar'); // defined by subclass $this->options->overload('foo', function (Options $options, $previousValue) use ($test) { /* @var \PHPUnit_Framework_TestCase $test */ $test->assertEquals('bar', $previousValue); return 'dynamic'; }); $this->assertEquals('dynamic', $this->options->get('foo')); } public function testPreviousValueIsEvaluatedIfLazy() { $test = $this; // defined by superclass $this->options->set('foo', function (Options $options) { return 'bar'; }); // defined by subclass $this->options->overload('foo', function (Options $options, $previousValue) use ($test) { /* @var \PHPUnit_Framework_TestCase $test */ $test->assertEquals('bar', $previousValue); return 'dynamic'; }); $this->assertEquals('dynamic', $this->options->get('foo')); } public function testLazyOptionCanAccessOtherOptions() { $test = $this; $this->options->set('foo', 'bar'); $this->options->set('bam', function (Options $options) use ($test) { /* @var \PHPUnit_Framework_TestCase $test */ $test->assertEquals('bar', $options->get('foo')); return 'dynamic'; }); $this->assertEquals('bar', $this->options->get('foo')); $this->assertEquals('dynamic', $this->options->get('bam')); } public function testLazyOptionCanAccessOtherLazyOptions() { $test = $this; $this->options->set('foo', function (Options $options) { return 'bar'; }); $this->options->set('bam', function (Options $options) use ($test) { /* @var \PHPUnit_Framework_TestCase $test */ $test->assertEquals('bar', $options->get('foo')); return 'dynamic'; }); $this->assertEquals('bar', $this->options->get('foo')); $this->assertEquals('dynamic', $this->options->get('bam')); } /** * @expectedException Symfony\Component\OptionsResolver\Exception\OptionDefinitionException */ public function testFailForCyclicDependencies() { $this->options->set('foo', function (Options $options) { $options->get('bam'); }); $this->options->set('bam', function (Options $options) { $options->get('foo'); }); $this->options->get('foo'); } public function testReplaceClearsAndSets() { $this->options->set('one', '1'); $this->options->replace(array( 'two' => '2', 'three' => function (Options $options) { return '2' === $options['two'] ? '3' : 'foo'; } )); $this->assertEquals(array( 'two' => '2', 'three' => '3', ), $this->options->all()); } public function testClearRemovesAllOptions() { $this->options->set('one', 1); $this->options->set('two', 2); $this->options->clear(); $this->assertEmpty($this->options->all()); } /** * @covers Symfony\Component\OptionsResolver\Options::replace * @expectedException Symfony\Component\OptionsResolver\Exception\OptionDefinitionException */ public function testCannotReplaceAfterOptionWasRead() { $this->options->set('one', 1); $this->options->all(); $this->options->replace(array( 'two' => '2', )); } /** * @covers Symfony\Component\OptionsResolver\Options::overload * @expectedException Symfony\Component\OptionsResolver\Exception\OptionDefinitionException */ public function testCannotOverloadAfterOptionWasRead() { $this->options->set('one', 1); $this->options->all(); $this->options->overload('one', 2); } /** * @covers Symfony\Component\OptionsResolver\Options::clear * @expectedException Symfony\Component\OptionsResolver\Exception\OptionDefinitionException */ public function testCannotClearAfterOptionWasRead() { $this->options->set('one', 1); $this->options->all(); $this->options->clear(); } public function testOverloadCannotBeEvaluatedLazilyWithoutExpectedClousureParams() { $this->options->set('foo', 'bar'); $this->options->overload('foo', function () { return 'test'; }); $this->assertNotEquals('test', $this->options->get('foo')); $this->assertTrue(is_callable($this->options->get('foo'))); } public function testOverloadCannotBeEvaluatedLazilyWithoutFirstParamTypeHint() { $this->options->set('foo', 'bar'); $this->options->overload('foo', function ($object) { return 'test'; }); $this->assertNotEquals('test', $this->options->get('foo')); $this->assertTrue(is_callable($this->options->get('foo'))); } public function testOptionsIteration() { $this->options->set('foo', 'bar'); $this->options->set('foo1', 'bar1'); $expectedResult = array('foo' => 'bar', 'foo1' => 'bar1'); $this->assertEquals($expectedResult, iterator_to_array($this->options, true)); } }
{ "content_hash": "fc98c1e1000f3f63d930c386a6e31932", "timestamp": "", "source": "github", "line_count": 292, "max_line_length": 97, "avg_line_length": 27.445205479452056, "alnum_prop": 0.5632642874968805, "repo_name": "mehulsbhatt/cdr", "id": "ca0872feb8c3693ffc2c785bd16ff57875bcd962", "size": "8243", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "vendor/symfony/symfony/src/Symfony/Component/OptionsResolver/Tests/OptionsTest.php", "mode": "33188", "license": "mit", "language": [], "symlink_target": "" }
package com.haru.write; import com.haru.JsonEncodable; public interface Operation extends JsonEncodable { public abstract String getMethod(); public abstract String getRequestDataKey(); public abstract void mergeFromPrevious(Operation other); }
{ "content_hash": "45adc90d27326d8fb598554fbc403f95", "timestamp": "", "source": "github", "line_count": 12, "max_line_length": 60, "avg_line_length": 21.833333333333332, "alnum_prop": 0.7786259541984732, "repo_name": "haruio/haru-sdk-android", "id": "428a4ad71009b482616d00a0e68a147756a142a5", "size": "262", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "core/src/main/java/com/haru/write/Operation.java", "mode": "33188", "license": "mit", "language": [ { "name": "Java", "bytes": "815865" } ], "symlink_target": "" }
import json import requests url = 'https://api.github.com/search/issues?q=is:issue+label:official-cve-feed+\ state:closed+repo:kubernetes/kubernetes&per_page=100' headers = {'Accept': 'application/vnd.github.v3+json'} res = requests.get(url, headers=headers) gh_items = res.json()['items'] # Use link header to iterate over pages # https://docs.github.com/en/rest/overview/resources-in-the-rest-api#pagination # https://datatracker.ietf.org/doc/html/rfc5988 # Please note that if there is a great number of pages, this unauthenticated # request may be subject to rate limits and fail. # https://docs.github.com/en/rest/overview/resources-in-the-rest-api#rate-limiting while 'next' in res.links: res = requests.get(res.links['next']['url'], headers=headers) gh_items.extend(res.json()['items']) cve_list = [] for item in gh_items: cve = {"issue_url": None, "number": None, "cve_id": None, "summary": None, "cve_url": None, "google_group_url": None} cve['issue_url'] = item['html_url'] cve['number'] = item['number'] title = item['title'].replace(" -", ":") title = title.split(": ") if len(title) == 1: cve_id = None cve['cve_id'] = None cve['cve_url'] = None cve['summary'] = title[0] cve['google_group_url'] = None else: cve_id = title[0] cve['cve_id'] = title[0] if len(title) == 3: cve['summary'] = title[2] else: cve['summary'] = title[1] cve['cve_url'] = f"https://www.cve.org/cverecord?id={cve_id}" cve['google_group_url'] = \ f"https://groups.google.com/g/kubernetes-announce/search?q={cve_id}" cve_list.append(cve) cves = json.dumps(cve_list, sort_keys=True, indent=4) print(cves) # write the final cve list to official_cve_feed.json with open("official-cve-feed.json", "w") as cvejson: cvejson.write(cves)
{ "content_hash": "e6f56ee4e166d8fd7f4cf3153343c75b", "timestamp": "", "source": "github", "line_count": 50, "max_line_length": 82, "avg_line_length": 37.88, "alnum_prop": 0.6325237592397043, "repo_name": "kubernetes/sig-security", "id": "f51733b61e4826f5463031c0a6a684886c0388cc", "size": "2506", "binary": false, "copies": "1", "ref": "refs/heads/main", "path": "sig-security-tooling/cve-feed/hack/fetch-official-cve-feed.py", "mode": "33261", "license": "apache-2.0", "language": [ { "name": "Makefile", "bytes": "193" }, { "name": "Python", "bytes": "6176" }, { "name": "Shell", "bytes": "2564" } ], "symlink_target": "" }
A library that generates EPUB previews from full publications. The output is based on the upcoming specification dedicated to previews published by the [IDPF](http://www.idpf.org). Created by [Feedbooks](http://www.feedbooks.com) with the support of [Centre National du Livre](http://www.centrenationaldulivre.fr/). Released under the MIT license. ## Requirements Ruby 1.9 or a more recent version. Install bundler with gem. In the directory run "bundle install". Required Ruby gems: * zipruby * nokogiri * mime-types * uuid * thor * workers EPUB Preview Factory is based on a fork of [Peregrin](https://github.com/joseph/peregrin) to handle the EPUB side of things. ## Using EPUB Preview Factory You can list all the available options for EPUB Preview Factory using the command-line: $ bundle exec ruby main.rb Usage: main.rb extract -d, --destination=DESTINATION -s, --source=SOURCE Options: -s, --source=SOURCE # Source file or directory -d, --destination=DESTINATION # destination file or directory -i, [--identifier=IDENTIFIER] # force preview identifier -p, [--percent=PERCENT] # change percent, default 5% -w, [--pool-size=POOL_SIZE] # change pool size for directory mode, default 5 -v, [--verbose=VERBOSE] # verbose mode -c, [--max-char=MAX_CHAR] # calcul the size of the extract by char count instead of percent -m, [--move-finish-files=MOVE_FINISH_FILES] # move finished file to the following directory EPUB Preview Factory has two main modes: single file or batch. In single file mode (-s pointing to an EPUB), you just need to specify two options: the source file and the destination file. The default option for a preview is to include 5% of the total publication. $ bundle exec ruby main.rb extract -s test.epub -d test_preview.epub In batch mode (-s pointing to a directory), you can specify the number of workers (default option is 5 workers) that you'd like to use to process books faster using the -w option. ## Upcoming features * Detect FXL EPUB and use a page mode for them * Add specific support for navigation documents in EPUB 3 * Detect cover pages, introduction, toc etc. and exclude them from count * Better support for relative URLs for links that are modified in HTML * Support for EPUB 3.0.1 collections and the preview role ## History * 0.1 - Initial release - Generate preview based on % of the book or total number of characters - Use metadata recommendations from the AHL spec (different identifier, link back to original identifier with dc:source, dc:type set to preview) - Updates the container, OPF and NCX to only include the content documents that we need - Detect images used in content files of the preview and remove other images
{ "content_hash": "9832a61ce3fe5f4e5b48c5404d9ebe83", "timestamp": "", "source": "github", "line_count": 71, "max_line_length": 201, "avg_line_length": 41.014084507042256, "alnum_prop": 0.7057005494505495, "repo_name": "Feedbooks/epub_preview_factory", "id": "a2ee0f3b327640e769d777345ae1a9f4d7253419", "size": "2936", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "README.md", "mode": "33188", "license": "mit", "language": [ { "name": "Ruby", "bytes": "14245" } ], "symlink_target": "" }
// // KNBUtilExtend.h // KenuoTraining // // Created by Robert on 16/2/22. // Copyright © 2016年 Robert. All rights reserved. // #ifndef KNBUtilExtend_h #define KNBUtilExtend_h //通知相关 CG_INLINE void KNB_ADD_NOTIFICATION(NSString *name, id target, SEL action, id object) { [[NSNotificationCenter defaultCenter] addObserver:target selector:action name:name object:object]; } CG_INLINE void KNB_REMOVE_NOTIFICATION(NSString *name, id target, id object) { [[NSNotificationCenter defaultCenter] removeObserver:target name:name object:object]; } CG_INLINE void KNB_POST_NOTIFICATION(NSString *name, id object, NSDictionary *userInfo) { [[NSNotificationCenter defaultCenter] postNotificationName:name object:object userInfo:userInfo]; } CG_INLINE BOOL isNullStr(NSString *str) { return (str.length == 0 || [str isKindOfClass:[NSNull class]]); } //Alert提示 CG_INLINE void KNB_AlertlogError (NSString* message) { static UIAlertView *alertView = nil; if (!alertView) { alertView = [[UIAlertView alloc] initWithTitle: @"" message: message delegate: nil cancelButtonTitle: @"好的" otherButtonTitles: nil, nil]; [alertView show]; } else { [alertView dismissWithClickedButtonIndex:0 animated:NO]; alertView = nil; alertView = [[UIAlertView alloc] initWithTitle: @"" message: message delegate: nil cancelButtonTitle: @"好的" otherButtonTitles: nil, nil]; [alertView show]; } } //多线程相关 CG_INLINE void KNB_PerformAsynchronous (void(^block)(void)) { dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0); dispatch_async(queue, block); } CG_INLINE void KNB_PerformOnMainThread (void(^block)(void)) { dispatch_async(dispatch_get_main_queue(), block); } typedef NS_ENUM(NSUInteger, KNBRecorderType) { KNBRecorderPhoto = 2, //照片 KNBRecorderVideo //视频 }; CG_INLINE NSURL *resourceSaveDirectory(NSString *userName, KNBRecorderType type) { NSString *dirPath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES)[0] stringByAppendingPathComponent:userName]; BOOL isDir; if (![[NSFileManager defaultManager] fileExistsAtPath:dirPath isDirectory:&isDir] || !isDir) { [[NSFileManager defaultManager] createDirectoryAtPath:dirPath withIntermediateDirectories:YES attributes:nil error:nil]; } if (type == KNBRecorderVideo){ dirPath = [dirPath stringByAppendingPathComponent:@"Video"]; }else if (type == KNBRecorderPhoto) { dirPath = [dirPath stringByAppendingPathComponent:@"Photo"]; } if (![[NSFileManager defaultManager] fileExistsAtPath:dirPath isDirectory:&isDir] || !isDir) { [[NSFileManager defaultManager] createDirectoryAtPath:dirPath withIntermediateDirectories:YES attributes:nil error:nil]; } NSURL *dirUrl = [NSURL fileURLWithPath:dirPath];; return dirUrl; } CG_INLINE NSURL *resourceAbsolutePath(NSString *userName, NSString *resourceName, KNBRecorderType type) { NSURL *dirUrl = resourceSaveDirectory(userName, type); NSURL *fileUrl = nil; if (type == KNBRecorderVideo) { fileUrl = [[dirUrl URLByAppendingPathComponent:resourceName] URLByAppendingPathExtension:@"mp4"]; }else if (type == KNBRecorderPhoto) { fileUrl = [[dirUrl URLByAppendingPathComponent:resourceName] URLByAppendingPathExtension:@"jpg"]; } return fileUrl; } CG_INLINE void removeResources(NSString *userName) { NSString *dirPath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES)[0] stringByAppendingPathComponent:userName]; NSString *videoDirPath = [dirPath stringByAppendingPathComponent:@"Video"]; NSString *photoDirPath = [dirPath stringByAppendingPathComponent:@"Photo"]; [[NSFileManager defaultManager] removeItemAtPath:videoDirPath error:nil]; [[NSFileManager defaultManager] removeItemAtPath:photoDirPath error:nil]; } CG_INLINE NSString *combineResourceUrl(NSString *url) { // NSString *complteString = [NSString stringWithFormat:@"%@%@", [[KNBMainConfigModel shareInstance] getRequestUrlWithKey:KNBResourceUrl], url]; // return complteString; return url; } CG_INLINE BOOL isPhoneNumber(NSString *number){ //* 普通 NSString *MB=@"^1[3-9]\\d{9}$"; //* 移动 NSString *CM=@"^1(34[0-8]|(3[5-9]|5[017-9]|8[278])\\d)\\d{7}$"; //* 联通 NSString *CU=@"^1(3[0-2]|5[256]|8[56])\\d{8}$"; //* 电信 NSString *CT=@"^1((33|53|8[09])[0-9]|349)\\d{7}$"; NSPredicate *regextestmb = [NSPredicate predicateWithFormat:@"SELF MATCHES %@",MB]; NSPredicate *regextestcm = [NSPredicate predicateWithFormat:@"SELF MATCHES %@",CM]; NSPredicate *regextestcu = [NSPredicate predicateWithFormat:@"SELF MATCHES %@",CU]; NSPredicate *regextestct = [NSPredicate predicateWithFormat:@"SELF MATCHES %@",CT]; if(([regextestmb evaluateWithObject:number] ==YES) || ([regextestcm evaluateWithObject:number] ==YES) || ([regextestct evaluateWithObject:number] ==YES) || ([regextestcu evaluateWithObject:number] ==YES)) { return YES; } else { return NO; } } #endif /* KNBUtilExtend_h */
{ "content_hash": "98313b1663b2e1fb2b0ee275b6ec5f71", "timestamp": "", "source": "github", "line_count": 155, "max_line_length": 149, "avg_line_length": 36.08387096774194, "alnum_prop": 0.6567137493295191, "repo_name": "atbj505/KNBKit", "id": "f18a0648b78d643d8ba14e1fc49f0b624a3f1d79", "size": "5650", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "KNBKit/KNBKit/Source/KNBUtilExtend.h", "mode": "33188", "license": "mit", "language": [ { "name": "C", "bytes": "30543" }, { "name": "Objective-C", "bytes": "306067" }, { "name": "Ruby", "bytes": "802" } ], "symlink_target": "" }
def extractWanderingtranslationsWordpressCom(item): ''' Parser for 'wanderingtranslations.wordpress.com' ''' vol, chp, frag, postfix = extractVolChapterFragmentPostfix(item['title']) if not (chp or vol) or "preview" in item['title'].lower(): return None if "WATTT" in item['tags']: return buildReleaseMessageWithType(item, "WATTT", vol, chp, frag=frag, postfix=postfix) return False
{ "content_hash": "1d960d35dd35b75571e008f562915fb9", "timestamp": "", "source": "github", "line_count": 14, "max_line_length": 89, "avg_line_length": 28.428571428571427, "alnum_prop": 0.7361809045226131, "repo_name": "fake-name/ReadableWebProxy", "id": "6d7696bf0dc80fff4610cb4c847477f951ac83fe", "size": "399", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "WebMirror/management/rss_parser_funcs/feed_parse_extractWanderingtranslationsWordpressCom.py", "mode": "33188", "license": "bsd-3-clause", "language": [ { "name": "CSS", "bytes": "105811" }, { "name": "Dockerfile", "bytes": "1178" }, { "name": "HTML", "bytes": "119737" }, { "name": "JavaScript", "bytes": "3006524" }, { "name": "Jupyter Notebook", "bytes": "148075" }, { "name": "Mako", "bytes": "1454" }, { "name": "Python", "bytes": "5264346" }, { "name": "Shell", "bytes": "1059" } ], "symlink_target": "" }
(function( factory ) { "use strict"; var interValId; var intervalIndex = 0; var run = function(){ if ( window.respimage ) { factory( window.respimage ); } if(window.respimage || intervalIndex > 9999){ clearInterval(interValId); } intervalIndex++; }; interValId = setInterval(run, 8); run(); }( function( respimage ) { "use strict"; var document = window.document; var Element = window.Element; var MutationObserver = window.MutationObserver; var noop = function() {}; var riobserver = { disconnect: noop, take: noop, observe: noop, start: noop, stop: noop, connected: false }; var isReady = /^loade|^c|^i/.test(document.readyState || ""); var ri = respimage._; ri.mutationSupport = false; ri.observer = riobserver; if ( !Object.keys || !window.HTMLSourceElement || !document.addEventListener) { return; } var matches, observer, allowConnect, addMutation; var observeProps = { src: 1, srcset: 1, sizes: 1, media: 1 }; var attrFilter = Object.keys( observeProps ); var config = { attributes: true, childList: true, subtree: true, attributeFilter: attrFilter }; var elemProto = Element && Element.prototype; var sup = {}; var monkeyPatch = function( name, fn ) { sup[ name ] = ri[ name ]; ri[ name ] = fn; }; if ( elemProto && !elemProto.matches ) { elemProto.matches = elemProto.matchesSelector || elemProto.mozMatchesSelector || elemProto.webkitMatchesSelector || elemProto.msMatchesSelector; } if ( elemProto && elemProto.matches ) { matches = function( elem, sel ) { return elem.matches( sel ); }; ri.mutationSupport = !!( Object.create && Object.defineProperties ); } if ( !ri.mutationSupport ) { return; } riobserver.observe = function() { if ( allowConnect ) { riobserver.connected = true; if ( observer ) { observer.observe( document.documentElement, config ); } } }; riobserver.disconnect = function() { riobserver.connected = false; if ( observer ) { observer.disconnect(); } }; riobserver.take = function() { if ( observer ) { ri.onMutations( observer.takeRecords() ); } else if ( addMutation ) { addMutation.take(); } }; riobserver.start = function() { allowConnect = true; riobserver.observe(); }; riobserver.stop = function() { allowConnect = false; riobserver.disconnect(); }; monkeyPatch( "setupRun", function() { riobserver.disconnect(); return sup.setupRun.apply( this, arguments ); }); monkeyPatch( "teardownRun", function() { var ret = sup.setupRun.apply( this, arguments ); riobserver.observe(); return ret; }); monkeyPatch( "setSrc", function() { var ret; var wasConnected = riobserver.connected; riobserver.disconnect(); ret = sup.setSrc.apply( this, arguments ); if ( wasConnected ) { riobserver.observe(); } return ret; }); ri.onMutations = function( mutations ) { var i, len; var modifiedImgs = []; for (i = 0, len = mutations.length; i < len; i++) { if ( isReady && mutations[i].type === "childList" ) { ri.onSubtreeChange( mutations[i], modifiedImgs ); } else if ( mutations[i].type === "attributes" ) { ri.onAttrChange( mutations[i], modifiedImgs ); } } if ( modifiedImgs.length ) { ri.fillImgs({ elements: modifiedImgs, reevaluate: true }); } }; ri.onSubtreeChange = function( mutations, imgs ) { ri.findAddedMutations( mutations.addedNodes, imgs ); ri.findRemovedMutations( mutations.removedNodes, mutations.target, imgs ); }; ri.findAddedMutations = function( nodes, imgs ) { var i, len, node, nodeName; for ( i = 0, len = nodes.length; i < len; i++ ){ node = nodes[i]; if ( node.nodeType !== 1 ) {continue;} nodeName = node.nodeName.toUpperCase(); if ( nodeName === "PICTURE" ) { ri.addToElements( node.getElementsByTagName( "img" )[0], imgs ); } else if ( nodeName === "IMG" && matches( node, ri.selShort ) ){ ri.addToElements( node, imgs ); } else if ( nodeName === "SOURCE" ) { ri.addImgForSource( node, node.parentNode, imgs ); } else { ri.addToElements( ri.qsa( node, ri.selShort ), imgs ); } } }; ri.findRemovedMutations = function( nodes, target, imgs ) { var i, len, node; for ( i = 0, len = nodes.length; i < len; i++ ) { node = nodes[i]; if ( node.nodeType !== 1 ) {continue;} if ( node.nodeName.toUpperCase() === "SOURCE" ) { ri.addImgForSource( node, target, imgs ); } } }; ri.addImgForSource = function( node, parent, imgs ) { if ( parent && ( parent.nodeName || "" ).toUpperCase() !== "PICTURE" ) { parent = parent.parentNode; if(!parent || ( parent.nodeName || "" ).toUpperCase() !== "PICTURE" ) { parent = null; } } if(parent){ ri.addToElements( parent.getElementsByTagName( "img" )[0], imgs ); } }; ri.addToElements = function( img, imgs ) { var i, len; if ( img ) { if ( ("length" in img) && !img.nodeType ){ for ( i = 0, len = img.length; i < len; i++ ) { ri.addToElements( img[i], imgs ); } } else if ( img.parentNode && imgs.indexOf(img) === -1 ) { imgs.push( img ); } } }; ri.onAttrChange = function( mutation, modifiedImgs ) { var nodeName; var riData = mutation.target[ ri.ns ]; if ( !riData && mutation.attributeName === "srcset" && (nodeName = mutation.target.nodeName.toUpperCase()) === "IMG" ) { ri.addToElements( mutation.target, modifiedImgs ); } else if ( riData ) { if(!nodeName){ nodeName = mutation.target.nodeName.toUpperCase(); } if ( nodeName === "IMG" ) { if ( mutation.attributeName in riData ) { riData[ mutation.attributeName ] = undefined; } ri.addToElements( mutation.target, modifiedImgs ); } else if ( nodeName === "SOURCE" ) { ri.addImgForSource( mutation.target, mutation.target.parentNode, modifiedImgs ); } } }; if ( !ri.supPicture ) { if ( MutationObserver && !ri.testMutationEvents ) { observer = new MutationObserver( ri.onMutations ); } else { addMutation = (function() { var running = false; var mutations = []; var setImmediate = window.setImmediate || window.setTimeout; return function(mutation) { if ( !running ) { running = true; if ( !addMutation.take ) { addMutation.take = function() { if ( mutations.length ) { ri.onMutations( mutations ); mutations = []; } running = false; }; } setImmediate( addMutation.take ); } mutations.push( mutation ); }; })(); document.documentElement.addEventListener( "DOMNodeInserted", function( e ) { if ( riobserver.connected && isReady ) { addMutation( { type: "childList", addedNodes: [ e.target ], removedNodes: [] } ); } }, true); document.documentElement.addEventListener( "DOMNodeRemoved", function( e ) { if ( riobserver.connected && isReady && (e.target || {}).nodeName == 'SOURCE') { addMutation( { type: "childList", addedNodes: [], removedNodes: [ e.target ], target: e.target.parentNode } ); } }, true); document.documentElement.addEventListener( "DOMAttrModified", function( e ) { if ( riobserver.connected && observeProps[e.attrName] ) { addMutation( { type: "attributes", target: e.target, attributeName: e.attrName } ); } }, true); } if ( window.HTMLImageElement && Object.defineProperties ) { (function() { var image = document.createElement( "img" ); var imgIdls = []; var getImgAttr = image.getAttribute; var setImgAttr = image.setAttribute; var GETIMGATTRS = { src: 1 }; if ( ri.supSrcset && !ri.supSizes ) { GETIMGATTRS.srcset = 1; } Object.defineProperties(HTMLImageElement.prototype, { getAttribute: { value: function( attr ) { var internal; if ( GETIMGATTRS[ attr ] && (internal = this[ ri.ns ]) && ( internal[attr] !== undefined ) ) { return internal[ attr ]; } return getImgAttr.apply( this, arguments ); }, writeable: true, enumerable: true, configurable: true } }); if(!ri.supSrcset){ imgIdls.push('srcset'); } if(!ri.supSizes){ imgIdls.push('sizes'); } imgIdls.forEach(function(idl){ Object.defineProperty(HTMLImageElement.prototype, idl, { set: function( value ) { setImgAttr.call( this, idl, value ); }, get: function() { return getImgAttr.call( this, idl ) || ''; }, enumerable: true, configurable: true }); }); if(!('currentSrc' in image)){ (function(){ var ascendingSort; var updateCurSrc = function(elem, src) { if(src == null){ src = elem.src || ''; } Object.defineProperty(elem, 'riCurrentSrc', { value: src, writable: true }); }; var baseUpdateCurSrc = updateCurSrc; if(ri.supSrcset && window.devicePixelRatio){ ascendingSort = function( a, b ) { var aRes = a.res || a.d || a.x || a.w; var bRes = b.res || b.d || b.x || a.w; return aRes - bRes; }; updateCurSrc = function(elem) { var i, cands, length, ret; var imageData = elem[ ri.ns ]; if ( imageData && imageData.supported && imageData.srcset && imageData.sets && (cands = ri.parseSet(imageData.sets[0])) && cands.sort) { cands.sort( ascendingSort ); length = cands.length; ret = cands[ length - 1 ]; for(i = 0; i < length; i++){ if(cands[i].x >= window.devicePixelRatio){ ret = cands[i]; break; } } if(ret){ ret = ri.makeUrl(ret.url); } } baseUpdateCurSrc(elem, ret); }; } document.addEventListener('load', function(e){ if(e.target.nodeName.toUpperCase() == 'IMG'){ updateCurSrc(e.target); } }, true); Object.defineProperty(HTMLImageElement.prototype, 'currentSrc', { set: function() { if(window.console && console.warn){ console.warn('currentSrc can\'t be set on img element'); } }, get: function(){ if(this.complete){ updateCurSrc(this); } return (!this.src && !this.srcset) ? '' : this.riCurrentSrc || ''; }, enumerable: true, configurable: true }); })(); } if(window.HTMLSourceElement && !('srcset' in document.createElement('source'))){ ['srcset', 'sizes'].forEach(function(idl){ Object.defineProperty(HTMLSourceElement.prototype, idl, { set: function( value ) { this.setAttribute( idl, value ); }, get: function() { return this.getAttribute( idl ) || ''; }, enumerable: true, configurable: true }); }); } })(); } riobserver.start(); } if ( !isReady ) { document.addEventListener("DOMContentLoaded", function(event) { isReady = true; }); } }));
{ "content_hash": "2b903e6622314741fd5b65cf5369fb6d", "timestamp": "", "source": "github", "line_count": 428, "max_line_length": 146, "avg_line_length": 25.740654205607477, "alnum_prop": 0.5927203412907325, "repo_name": "aFarkas/respimage", "id": "fce541ec07c50140652723c2eba187eddb87be2f", "size": "11017", "binary": false, "copies": "4", "ref": "refs/heads/gh-pages", "path": "plugins/mutation/ri.mutation.js", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "4356" }, { "name": "HTML", "bytes": "28926" }, { "name": "JavaScript", "bytes": "182335" } ], "symlink_target": "" }
<?php /** * @category Mad * @package Mad_Model * @subpackage Exceptions * @copyright (c) 2007-2009 Maintainable Software, LLC * @license http://opensource.org/licenses/bsd-license.php BSD */ class Mad_Model_Association_Exception extends Mad_Model_Exception {}
{ "content_hash": "72589c5589e27e84cee235d7a15354bf", "timestamp": "", "source": "github", "line_count": 12, "max_line_length": 66, "avg_line_length": 23.166666666666668, "alnum_prop": 0.7014388489208633, "repo_name": "williamn/framework", "id": "430b3a3f6268ee6ade2707a0f5e3f9189298f6f1", "size": "477", "binary": false, "copies": "3", "ref": "refs/heads/master", "path": "vendor/Mad/Model/Association/Exception.php", "mode": "33188", "license": "bsd-3-clause", "language": [ { "name": "HTML", "bytes": "4884" }, { "name": "JavaScript", "bytes": "16" }, { "name": "PHP", "bytes": "683520" }, { "name": "Ruby", "bytes": "744" } ], "symlink_target": "" }
.class Landroid/animation/PropertyValuesHolder$FloatPropertyValuesHolder; .super Landroid/animation/PropertyValuesHolder; .source "PropertyValuesHolder.java" # annotations .annotation system Ldalvik/annotation/EnclosingClass; value = Landroid/animation/PropertyValuesHolder; .end annotation .annotation system Ldalvik/annotation/InnerClass; accessFlags = 0x8 name = "FloatPropertyValuesHolder" .end annotation # static fields .field private static final sJNISetterPropertyMap:Ljava/util/HashMap; .annotation system Ldalvik/annotation/Signature; value = { "Ljava/util/HashMap", "<", "Ljava/lang/Class;", "Ljava/util/HashMap", "<", "Ljava/lang/String;", "Ljava/lang/Integer;", ">;>;" } .end annotation .end field # instance fields .field mFloatAnimatedValue:F .field mFloatKeyframeSet:Landroid/animation/FloatKeyframeSet; .field private mFloatProperty:Landroid/util/FloatProperty; .field mJniSetter:I # direct methods .method static constructor <clinit>()V .locals 1 .prologue .line 883 new-instance v0, Ljava/util/HashMap; invoke-direct {v0}, Ljava/util/HashMap;-><init>()V sput-object v0, Landroid/animation/PropertyValuesHolder$FloatPropertyValuesHolder;->sJNISetterPropertyMap:Ljava/util/HashMap; return-void .end method .method public constructor <init>(Landroid/util/Property;Landroid/animation/FloatKeyframeSet;)V .locals 1 .parameter "property" .parameter "keyframeSet" .prologue .line 899 const/4 v0, 0x0 invoke-direct {p0, p1, v0}, Landroid/animation/PropertyValuesHolder;-><init>(Landroid/util/Property;Landroid/animation/PropertyValuesHolder$1;)V .line 900 sget-object v0, Ljava/lang/Float;->TYPE:Ljava/lang/Class; iput-object v0, p0, Landroid/animation/PropertyValuesHolder;->mValueType:Ljava/lang/Class; .line 901 iput-object p2, p0, Landroid/animation/PropertyValuesHolder;->mKeyframeSet:Landroid/animation/KeyframeSet; .line 902 iget-object v0, p0, Landroid/animation/PropertyValuesHolder;->mKeyframeSet:Landroid/animation/KeyframeSet; check-cast v0, Landroid/animation/FloatKeyframeSet; iput-object v0, p0, Landroid/animation/PropertyValuesHolder$FloatPropertyValuesHolder;->mFloatKeyframeSet:Landroid/animation/FloatKeyframeSet; .line 903 instance-of v0, p1, Landroid/util/FloatProperty; if-eqz v0, :cond_0 .line 904 iget-object v0, p0, Landroid/animation/PropertyValuesHolder;->mProperty:Landroid/util/Property; check-cast v0, Landroid/util/FloatProperty; iput-object v0, p0, Landroid/animation/PropertyValuesHolder$FloatPropertyValuesHolder;->mFloatProperty:Landroid/util/FloatProperty; .line 906 :cond_0 return-void .end method .method public varargs constructor <init>(Landroid/util/Property;[F)V .locals 1 .parameter "property" .parameter "values" .prologue .line 914 const/4 v0, 0x0 invoke-direct {p0, p1, v0}, Landroid/animation/PropertyValuesHolder;-><init>(Landroid/util/Property;Landroid/animation/PropertyValuesHolder$1;)V .line 915 invoke-virtual {p0, p2}, Landroid/animation/PropertyValuesHolder$FloatPropertyValuesHolder;->setFloatValues([F)V .line 916 instance-of v0, p1, Landroid/util/FloatProperty; if-eqz v0, :cond_0 .line 917 iget-object v0, p0, Landroid/animation/PropertyValuesHolder;->mProperty:Landroid/util/Property; check-cast v0, Landroid/util/FloatProperty; iput-object v0, p0, Landroid/animation/PropertyValuesHolder$FloatPropertyValuesHolder;->mFloatProperty:Landroid/util/FloatProperty; .line 919 :cond_0 return-void .end method .method public constructor <init>(Ljava/lang/String;Landroid/animation/FloatKeyframeSet;)V .locals 1 .parameter "propertyName" .parameter "keyframeSet" .prologue .line 892 const/4 v0, 0x0 invoke-direct {p0, p1, v0}, Landroid/animation/PropertyValuesHolder;-><init>(Ljava/lang/String;Landroid/animation/PropertyValuesHolder$1;)V .line 893 sget-object v0, Ljava/lang/Float;->TYPE:Ljava/lang/Class; iput-object v0, p0, Landroid/animation/PropertyValuesHolder;->mValueType:Ljava/lang/Class; .line 894 iput-object p2, p0, Landroid/animation/PropertyValuesHolder;->mKeyframeSet:Landroid/animation/KeyframeSet; .line 895 iget-object v0, p0, Landroid/animation/PropertyValuesHolder;->mKeyframeSet:Landroid/animation/KeyframeSet; check-cast v0, Landroid/animation/FloatKeyframeSet; iput-object v0, p0, Landroid/animation/PropertyValuesHolder$FloatPropertyValuesHolder;->mFloatKeyframeSet:Landroid/animation/FloatKeyframeSet; .line 896 return-void .end method .method public varargs constructor <init>(Ljava/lang/String;[F)V .locals 1 .parameter "propertyName" .parameter "values" .prologue .line 909 const/4 v0, 0x0 invoke-direct {p0, p1, v0}, Landroid/animation/PropertyValuesHolder;-><init>(Ljava/lang/String;Landroid/animation/PropertyValuesHolder$1;)V .line 910 invoke-virtual {p0, p2}, Landroid/animation/PropertyValuesHolder$FloatPropertyValuesHolder;->setFloatValues([F)V .line 911 return-void .end method # virtual methods .method calculateValue(F)V .locals 1 .parameter "fraction" .prologue .line 929 iget-object v0, p0, Landroid/animation/PropertyValuesHolder$FloatPropertyValuesHolder;->mFloatKeyframeSet:Landroid/animation/FloatKeyframeSet; invoke-virtual {v0, p1}, Landroid/animation/FloatKeyframeSet;->getFloatValue(F)F move-result v0 iput v0, p0, Landroid/animation/PropertyValuesHolder$FloatPropertyValuesHolder;->mFloatAnimatedValue:F .line 930 return-void .end method .method public clone()Landroid/animation/PropertyValuesHolder$FloatPropertyValuesHolder; .locals 2 .prologue .line 939 invoke-super {p0}, Landroid/animation/PropertyValuesHolder;->clone()Landroid/animation/PropertyValuesHolder; move-result-object v0 check-cast v0, Landroid/animation/PropertyValuesHolder$FloatPropertyValuesHolder; .line 940 .local v0, newPVH:Landroid/animation/PropertyValuesHolder$FloatPropertyValuesHolder; iget-object v1, v0, Landroid/animation/PropertyValuesHolder;->mKeyframeSet:Landroid/animation/KeyframeSet; check-cast v1, Landroid/animation/FloatKeyframeSet; iput-object v1, v0, Landroid/animation/PropertyValuesHolder$FloatPropertyValuesHolder;->mFloatKeyframeSet:Landroid/animation/FloatKeyframeSet; .line 941 return-object v0 .end method .method public bridge synthetic clone()Landroid/animation/PropertyValuesHolder; .locals 1 .prologue .line 880 invoke-virtual {p0}, Landroid/animation/PropertyValuesHolder$FloatPropertyValuesHolder;->clone()Landroid/animation/PropertyValuesHolder$FloatPropertyValuesHolder; move-result-object v0 return-object v0 .end method .method public bridge synthetic clone()Ljava/lang/Object; .locals 1 .annotation system Ldalvik/annotation/Throws; value = { Ljava/lang/CloneNotSupportedException; } .end annotation .prologue .line 880 invoke-virtual {p0}, Landroid/animation/PropertyValuesHolder$FloatPropertyValuesHolder;->clone()Landroid/animation/PropertyValuesHolder$FloatPropertyValuesHolder; move-result-object v0 return-object v0 .end method .method getAnimatedValue()Ljava/lang/Object; .locals 1 .prologue .line 934 iget v0, p0, Landroid/animation/PropertyValuesHolder$FloatPropertyValuesHolder;->mFloatAnimatedValue:F invoke-static {v0}, Ljava/lang/Float;->valueOf(F)Ljava/lang/Float; move-result-object v0 return-object v0 .end method .method setAnimatedValue(Ljava/lang/Object;)V .locals 4 .parameter "target" .prologue .line 953 iget-object v1, p0, Landroid/animation/PropertyValuesHolder$FloatPropertyValuesHolder;->mFloatProperty:Landroid/util/FloatProperty; if-eqz v1, :cond_1 .line 954 iget-object v1, p0, Landroid/animation/PropertyValuesHolder$FloatPropertyValuesHolder;->mFloatProperty:Landroid/util/FloatProperty; iget v2, p0, Landroid/animation/PropertyValuesHolder$FloatPropertyValuesHolder;->mFloatAnimatedValue:F invoke-virtual {v1, p1, v2}, Landroid/util/FloatProperty;->setValue(Ljava/lang/Object;F)V .line 975 :cond_0 :goto_0 return-void .line 957 :cond_1 iget-object v1, p0, Landroid/animation/PropertyValuesHolder;->mProperty:Landroid/util/Property; if-eqz v1, :cond_2 .line 958 iget-object v1, p0, Landroid/animation/PropertyValuesHolder;->mProperty:Landroid/util/Property; iget v2, p0, Landroid/animation/PropertyValuesHolder$FloatPropertyValuesHolder;->mFloatAnimatedValue:F invoke-static {v2}, Ljava/lang/Float;->valueOf(F)Ljava/lang/Float; move-result-object v2 invoke-virtual {v1, p1, v2}, Landroid/util/Property;->set(Ljava/lang/Object;Ljava/lang/Object;)V goto :goto_0 .line 961 :cond_2 iget v1, p0, Landroid/animation/PropertyValuesHolder$FloatPropertyValuesHolder;->mJniSetter:I if-eqz v1, :cond_3 .line 962 iget v1, p0, Landroid/animation/PropertyValuesHolder$FloatPropertyValuesHolder;->mJniSetter:I iget v2, p0, Landroid/animation/PropertyValuesHolder$FloatPropertyValuesHolder;->mFloatAnimatedValue:F #calls: Landroid/animation/PropertyValuesHolder;->nCallFloatMethod(Ljava/lang/Object;IF)V invoke-static {p1, v1, v2}, Landroid/animation/PropertyValuesHolder;->access$400(Ljava/lang/Object;IF)V goto :goto_0 .line 965 :cond_3 iget-object v1, p0, Landroid/animation/PropertyValuesHolder;->mSetter:Ljava/lang/reflect/Method; if-eqz v1, :cond_0 .line 967 :try_start_0 iget-object v1, p0, Landroid/animation/PropertyValuesHolder;->mTmpValueArray:[Ljava/lang/Object; const/4 v2, 0x0 iget v3, p0, Landroid/animation/PropertyValuesHolder$FloatPropertyValuesHolder;->mFloatAnimatedValue:F invoke-static {v3}, Ljava/lang/Float;->valueOf(F)Ljava/lang/Float; move-result-object v3 aput-object v3, v1, v2 .line 968 iget-object v1, p0, Landroid/animation/PropertyValuesHolder;->mSetter:Ljava/lang/reflect/Method; iget-object v2, p0, Landroid/animation/PropertyValuesHolder;->mTmpValueArray:[Ljava/lang/Object; invoke-virtual {v1, p1, v2}, Ljava/lang/reflect/Method;->invoke(Ljava/lang/Object;[Ljava/lang/Object;)Ljava/lang/Object; :try_end_0 .catch Ljava/lang/reflect/InvocationTargetException; {:try_start_0 .. :try_end_0} :catch_0 .catch Ljava/lang/IllegalAccessException; {:try_start_0 .. :try_end_0} :catch_1 goto :goto_0 .line 969 :catch_0 move-exception v0 .line 970 .local v0, e:Ljava/lang/reflect/InvocationTargetException; const-string v1, "PropertyValuesHolder" invoke-virtual {v0}, Ljava/lang/reflect/InvocationTargetException;->toString()Ljava/lang/String; move-result-object v2 invoke-static {v1, v2}, Landroid/util/Log;->e(Ljava/lang/String;Ljava/lang/String;)I goto :goto_0 .line 971 .end local v0 #e:Ljava/lang/reflect/InvocationTargetException; :catch_1 move-exception v0 .line 972 .local v0, e:Ljava/lang/IllegalAccessException; const-string v1, "PropertyValuesHolder" invoke-virtual {v0}, Ljava/lang/IllegalAccessException;->toString()Ljava/lang/String; move-result-object v2 invoke-static {v1, v2}, Landroid/util/Log;->e(Ljava/lang/String;Ljava/lang/String;)I goto :goto_0 .end method .method public varargs setFloatValues([F)V .locals 1 .parameter "values" .prologue .line 923 invoke-super {p0, p1}, Landroid/animation/PropertyValuesHolder;->setFloatValues([F)V .line 924 iget-object v0, p0, Landroid/animation/PropertyValuesHolder;->mKeyframeSet:Landroid/animation/KeyframeSet; check-cast v0, Landroid/animation/FloatKeyframeSet; iput-object v0, p0, Landroid/animation/PropertyValuesHolder$FloatPropertyValuesHolder;->mFloatKeyframeSet:Landroid/animation/FloatKeyframeSet; .line 925 return-void .end method .method setupSetter(Ljava/lang/Class;)V .locals 5 .parameter "targetClass" .prologue .line 979 iget-object v3, p0, Landroid/animation/PropertyValuesHolder;->mProperty:Landroid/util/Property; if-eqz v3, :cond_1 .line 1014 :cond_0 :goto_0 return-void .line 984 :cond_1 :try_start_0 iget-object v3, p0, Landroid/animation/PropertyValuesHolder;->mPropertyMapLock:Ljava/util/concurrent/locks/ReentrantReadWriteLock; invoke-virtual {v3}, Ljava/util/concurrent/locks/ReentrantReadWriteLock;->writeLock()Ljava/util/concurrent/locks/ReentrantReadWriteLock$WriteLock; move-result-object v3 invoke-virtual {v3}, Ljava/util/concurrent/locks/ReentrantReadWriteLock$WriteLock;->lock()V .line 985 sget-object v3, Landroid/animation/PropertyValuesHolder$FloatPropertyValuesHolder;->sJNISetterPropertyMap:Ljava/util/HashMap; invoke-virtual {v3, p1}, Ljava/util/HashMap;->get(Ljava/lang/Object;)Ljava/lang/Object; move-result-object v2 check-cast v2, Ljava/util/HashMap; .line 986 .local v2, propertyMap:Ljava/util/HashMap;,"Ljava/util/HashMap<Ljava/lang/String;Ljava/lang/Integer;>;" if-eqz v2, :cond_2 .line 987 iget-object v3, p0, Landroid/animation/PropertyValuesHolder;->mPropertyName:Ljava/lang/String; invoke-virtual {v2, v3}, Ljava/util/HashMap;->get(Ljava/lang/Object;)Ljava/lang/Object; move-result-object v0 check-cast v0, Ljava/lang/Integer; .line 988 .local v0, mJniSetterInteger:Ljava/lang/Integer; if-eqz v0, :cond_2 .line 989 invoke-virtual {v0}, Ljava/lang/Integer;->intValue()I move-result v3 iput v3, p0, Landroid/animation/PropertyValuesHolder$FloatPropertyValuesHolder;->mJniSetter:I .line 992 .end local v0 #mJniSetterInteger:Ljava/lang/Integer; :cond_2 iget v3, p0, Landroid/animation/PropertyValuesHolder$FloatPropertyValuesHolder;->mJniSetter:I if-nez v3, :cond_4 .line 993 const-string/jumbo v3, "set" iget-object v4, p0, Landroid/animation/PropertyValuesHolder;->mPropertyName:Ljava/lang/String; invoke-static {v3, v4}, Landroid/animation/PropertyValuesHolder$FloatPropertyValuesHolder;->getMethodName(Ljava/lang/String;Ljava/lang/String;)Ljava/lang/String; move-result-object v1 .line 994 .local v1, methodName:Ljava/lang/String; #calls: Landroid/animation/PropertyValuesHolder;->nGetFloatMethod(Ljava/lang/Class;Ljava/lang/String;)I invoke-static {p1, v1}, Landroid/animation/PropertyValuesHolder;->access$500(Ljava/lang/Class;Ljava/lang/String;)I move-result v3 iput v3, p0, Landroid/animation/PropertyValuesHolder$FloatPropertyValuesHolder;->mJniSetter:I .line 995 iget v3, p0, Landroid/animation/PropertyValuesHolder$FloatPropertyValuesHolder;->mJniSetter:I if-eqz v3, :cond_4 .line 996 if-nez v2, :cond_3 .line 997 new-instance v2, Ljava/util/HashMap; .end local v2 #propertyMap:Ljava/util/HashMap;,"Ljava/util/HashMap<Ljava/lang/String;Ljava/lang/Integer;>;" invoke-direct {v2}, Ljava/util/HashMap;-><init>()V .line 998 .restart local v2 #propertyMap:Ljava/util/HashMap;,"Ljava/util/HashMap<Ljava/lang/String;Ljava/lang/Integer;>;" sget-object v3, Landroid/animation/PropertyValuesHolder$FloatPropertyValuesHolder;->sJNISetterPropertyMap:Ljava/util/HashMap; invoke-virtual {v3, p1, v2}, Ljava/util/HashMap;->put(Ljava/lang/Object;Ljava/lang/Object;)Ljava/lang/Object; .line 1000 :cond_3 iget-object v3, p0, Landroid/animation/PropertyValuesHolder;->mPropertyName:Ljava/lang/String; iget v4, p0, Landroid/animation/PropertyValuesHolder$FloatPropertyValuesHolder;->mJniSetter:I invoke-static {v4}, Ljava/lang/Integer;->valueOf(I)Ljava/lang/Integer; move-result-object v4 invoke-virtual {v2, v3, v4}, Ljava/util/HashMap;->put(Ljava/lang/Object;Ljava/lang/Object;)Ljava/lang/Object; :try_end_0 .catchall {:try_start_0 .. :try_end_0} :catchall_0 .catch Ljava/lang/NoSuchMethodError; {:try_start_0 .. :try_end_0} :catch_0 .line 1008 .end local v1 #methodName:Ljava/lang/String; :cond_4 iget-object v3, p0, Landroid/animation/PropertyValuesHolder;->mPropertyMapLock:Ljava/util/concurrent/locks/ReentrantReadWriteLock; invoke-virtual {v3}, Ljava/util/concurrent/locks/ReentrantReadWriteLock;->writeLock()Ljava/util/concurrent/locks/ReentrantReadWriteLock$WriteLock; move-result-object v3 invoke-virtual {v3}, Ljava/util/concurrent/locks/ReentrantReadWriteLock$WriteLock;->unlock()V .line 1010 .end local v2 #propertyMap:Ljava/util/HashMap;,"Ljava/util/HashMap<Ljava/lang/String;Ljava/lang/Integer;>;" :goto_1 iget v3, p0, Landroid/animation/PropertyValuesHolder$FloatPropertyValuesHolder;->mJniSetter:I if-nez v3, :cond_0 .line 1012 invoke-super {p0, p1}, Landroid/animation/PropertyValuesHolder;->setupSetter(Ljava/lang/Class;)V goto :goto_0 .line 1003 :catch_0 move-exception v3 .line 1008 iget-object v3, p0, Landroid/animation/PropertyValuesHolder;->mPropertyMapLock:Ljava/util/concurrent/locks/ReentrantReadWriteLock; invoke-virtual {v3}, Ljava/util/concurrent/locks/ReentrantReadWriteLock;->writeLock()Ljava/util/concurrent/locks/ReentrantReadWriteLock$WriteLock; move-result-object v3 invoke-virtual {v3}, Ljava/util/concurrent/locks/ReentrantReadWriteLock$WriteLock;->unlock()V goto :goto_1 :catchall_0 move-exception v3 iget-object v4, p0, Landroid/animation/PropertyValuesHolder;->mPropertyMapLock:Ljava/util/concurrent/locks/ReentrantReadWriteLock; invoke-virtual {v4}, Ljava/util/concurrent/locks/ReentrantReadWriteLock;->writeLock()Ljava/util/concurrent/locks/ReentrantReadWriteLock$WriteLock; move-result-object v4 invoke-virtual {v4}, Ljava/util/concurrent/locks/ReentrantReadWriteLock$WriteLock;->unlock()V throw v3 .end method
{ "content_hash": "e27397fc6200c5c2748929148fbeff55", "timestamp": "", "source": "github", "line_count": 578, "max_line_length": 166, "avg_line_length": 31.505190311418684, "alnum_prop": 0.7367380560131795, "repo_name": "baidurom/devices-n7108", "id": "1659d9c5d5b20d7ea0176b119fa9ea13a56c3274", "size": "18210", "binary": false, "copies": "6", "ref": "refs/heads/coron-4.1", "path": "framework.jar.out/smali/android/animation/PropertyValuesHolder$FloatPropertyValuesHolder.smali", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Makefile", "bytes": "12697" }, { "name": "Shell", "bytes": "1974" } ], "symlink_target": "" }
flagfile=${1?} if [ -f "$flagfile" ]; then log "Error: $flagfile exists, which indicates it's already initialized" exit 1 fi su -s /bin/bash hdfs -c "hdfs namenode -format" touch "$flagfile" ## File : format_hdfs.sh ends
{ "content_hash": "390306f3334a16b3be68ce1387428133", "timestamp": "", "source": "github", "line_count": 11, "max_line_length": 75, "avg_line_length": 21.09090909090909, "alnum_prop": 0.6637931034482759, "repo_name": "DennyZhang/devops_public", "id": "a143df0804ab7f461dc96518a748d043520f7635", "size": "686", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "data_layer/hadoop/format_hdfs.sh", "mode": "33261", "license": "mit", "language": [ { "name": "HTML", "bytes": "264" }, { "name": "Python", "bytes": "87986" }, { "name": "Ruby", "bytes": "11207" }, { "name": "Shell", "bytes": "401264" } ], "symlink_target": "" }
var arr = Int32Array.of(101, 99, 77, 67, 4); var iter; // 1. Go for keys() var keys = arr.keys(); while (!(iter = keys.next ()).done) console.log (iter.value); console.log(); // 2. Go for values() var values = arr.values(); while (!(iter = values.next ()).done) console.log (iter.value);
{ "content_hash": "9c2267913ec6d91b9dd76e8131a44bb5", "timestamp": "", "source": "github", "line_count": 15, "max_line_length": 44, "avg_line_length": 20, "alnum_prop": 0.6033333333333334, "repo_name": "toshok/echojs", "id": "a1264cddad16a56c63417f806ddacf770df46220", "size": "320", "binary": false, "copies": "1", "ref": "refs/heads/main", "path": "test/typedarray10.js", "mode": "33188", "license": "mit", "language": [ { "name": "C", "bytes": "38259" }, { "name": "C++", "bytes": "1572039" }, { "name": "CMake", "bytes": "9614" }, { "name": "CoffeeScript", "bytes": "2129" }, { "name": "EJS", "bytes": "1422" }, { "name": "GLSL", "bytes": "14763" }, { "name": "HTML", "bytes": "53474" }, { "name": "Java", "bytes": "4231" }, { "name": "JavaScript", "bytes": "7494689" }, { "name": "LLVM", "bytes": "4930" }, { "name": "Makefile", "bytes": "46677" }, { "name": "Objective-C", "bytes": "7276" }, { "name": "Perl", "bytes": "90633" }, { "name": "Python", "bytes": "519" }, { "name": "Shell", "bytes": "2200" } ], "symlink_target": "" }
package org.apache.falcon.extensions.mirroring.hdfs; import org.apache.commons.lang3.StringUtils; import org.apache.falcon.FalconException; import org.apache.falcon.entity.ClusterHelper; import org.apache.falcon.entity.v0.cluster.Cluster; import org.apache.falcon.extensions.AbstractExtension; import java.util.Properties; /** * Hdfs mirroring extension. */ public class HdfsMirroringExtension extends AbstractExtension { private static final String COMMA_SEPARATOR = ","; private static final String EXTENSION_NAME = "HDFS-MIRRORING"; @Override public String getName() { return EXTENSION_NAME; } @Override public void validate(final Properties extensionProperties) throws FalconException { for (HdfsMirroringExtensionProperties option : HdfsMirroringExtensionProperties.values()) { if (extensionProperties.getProperty(option.getName()) == null && option.isRequired()) { throw new FalconException("Missing extension property: " + option.getName()); } } } @Override public Properties getAdditionalProperties(final Properties extensionProperties) throws FalconException { Properties additionalProperties = new Properties(); // Add default properties if not passed String distcpMaxMaps = extensionProperties.getProperty( HdfsMirroringExtensionProperties.DISTCP_MAX_MAPS.getName()); if (StringUtils.isBlank(distcpMaxMaps)) { additionalProperties.put(HdfsMirroringExtensionProperties.DISTCP_MAX_MAPS.getName(), "1"); } String distcpMapBandwidth = extensionProperties.getProperty( HdfsMirroringExtensionProperties.DISTCP_MAP_BANDWIDTH_IN_MB.getName()); if (StringUtils.isBlank(distcpMapBandwidth)) { additionalProperties.put(HdfsMirroringExtensionProperties.DISTCP_MAP_BANDWIDTH_IN_MB.getName(), "100"); } // Construct fully qualified hdfs src path String srcPaths = extensionProperties.getProperty(HdfsMirroringExtensionProperties .SOURCE_DIR.getName()); StringBuilder absoluteSrcPaths = new StringBuilder(); String sourceClusterName = extensionProperties.getProperty( HdfsMirroringExtensionProperties.SOURCE_CLUSTER.getName()); // Since source cluster get read interface Cluster srcCluster = ClusterHelper.getCluster(sourceClusterName); if (srcCluster == null) { throw new FalconException("Cluster entity " + sourceClusterName + " not found"); } String srcClusterEndPoint = ClusterHelper.getReadOnlyStorageUrl(srcCluster); if (StringUtils.isNotBlank(srcPaths)) { String[] paths = srcPaths.split(COMMA_SEPARATOR); for (String path : paths) { StringBuilder srcpath = new StringBuilder(srcClusterEndPoint); srcpath.append(path.trim()); srcpath.append(COMMA_SEPARATOR); absoluteSrcPaths.append(srcpath); } } additionalProperties.put(HdfsMirroringExtensionProperties.SOURCE_DIR.getName(), StringUtils.removeEnd(absoluteSrcPaths.toString(), COMMA_SEPARATOR)); // add sourceClusterFS and targetClusterFS additionalProperties.put(HdfsMirroringExtensionProperties.SOURCE_CLUSTER_FS_WRITE_ENDPOINT.getName(), ClusterHelper.getStorageUrl(srcCluster)); String targetClusterName = extensionProperties.getProperty( HdfsMirroringExtensionProperties.TARGET_CLUSTER.getName()); Cluster targetCluster = ClusterHelper.getCluster(targetClusterName); if (targetCluster == null) { throw new FalconException("Cluster entity " + targetClusterName + " not found"); } additionalProperties.put(HdfsMirroringExtensionProperties.TARGET_CLUSTER_FS_WRITE_ENDPOINT.getName(), ClusterHelper.getStorageUrl(targetCluster)); if (StringUtils.isBlank( extensionProperties.getProperty(HdfsMirroringExtensionProperties.TDE_ENCRYPTION_ENABLED.getName()))) { additionalProperties.put(HdfsMirroringExtensionProperties.TDE_ENCRYPTION_ENABLED.getName(), "false"); } addAdditionalDistCPProperties(extensionProperties, additionalProperties); return additionalProperties; } }
{ "content_hash": "f843b41bdbfbbcb35386ff2cea2a4f7c", "timestamp": "", "source": "github", "line_count": 103, "max_line_length": 118, "avg_line_length": 42.79611650485437, "alnum_prop": 0.699410163339383, "repo_name": "sriksun/falcon", "id": "ef26d81f895b04e77f73f676fed52fbf11ecdcb5", "size": "5214", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "extensions/src/main/java/org/apache/falcon/extensions/mirroring/hdfs/HdfsMirroringExtension.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "CSS", "bytes": "119841" }, { "name": "HTML", "bytes": "224589" }, { "name": "Java", "bytes": "7480382" }, { "name": "JavaScript", "bytes": "743100" }, { "name": "Perl", "bytes": "19690" }, { "name": "PigLatin", "bytes": "4826" }, { "name": "Python", "bytes": "20124" }, { "name": "Shell", "bytes": "29149" }, { "name": "XSLT", "bytes": "16792" } ], "symlink_target": "" }
<?php namespace Cheetahmail\Campaigns\SmsUnit; class ListCustom { /** * @var ListUnitSmsParam $unitSMSParam */ protected $unitSMSParam = null; /** * @param ListUnitSmsParam $unitSMSParam */ public function __construct($unitSMSParam) { $this->unitSMSParam = $unitSMSParam; } /** * @return ListUnitSmsParam */ public function getUnitSMSParam() { return $this->unitSMSParam; } /** * @param ListUnitSmsParam $unitSMSParam * @return \Cheetahmail\Campaigns\SmsUnit\List */ public function setUnitSMSParam($unitSMSParam) { $this->unitSMSParam = $unitSMSParam; return $this; } }
{ "content_hash": "2a92efbdc550449453bed92d964cf720", "timestamp": "", "source": "github", "line_count": 37, "max_line_length": 50, "avg_line_length": 19.16216216216216, "alnum_prop": 0.6036671368124118, "repo_name": "pgrimaud/cheetahmail-sdk", "id": "ed63425a6534e6f0c62e63e4d2c4eaf0308c57ff", "size": "709", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/Campaigns/SmsUnit/ListCustom.php", "mode": "33188", "license": "mit", "language": [ { "name": "PHP", "bytes": "746810" } ], "symlink_target": "" }
namespace Castle.Facilities.NHibernate { using System; using System.Diagnostics.Contracts; using global::NHibernate; [ContractClassFor(typeof(ISessionManager))] internal abstract class ISessionManagerContract : ISessionManager { ISession ISessionManager.OpenSession() { Contract.Ensures(Contract.Result<ISession>() != null); throw new NotImplementedException(); } } }
{ "content_hash": "760c2fc4705dd119e924e1e2b3a2213d", "timestamp": "", "source": "github", "line_count": 18, "max_line_length": 66, "avg_line_length": 22.555555555555557, "alnum_prop": 0.7389162561576355, "repo_name": "n054/Castle.Facilities.NHibernate", "id": "203037305de02f4b32fc6e95b2571122492b918a", "size": "1050", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "src/Castle.Facilities.NHibernate/ISessionManagerContract.cs", "mode": "33188", "license": "apache-2.0", "language": [], "symlink_target": "" }
package ms.safi.btsync; import java.io.File; import java.io.IOException; import java.io.InputStream; import java.net.URL; import java.nio.file.Files; import org.apache.commons.io.FileUtils; import org.apache.commons.lang3.SystemUtils; import org.codehaus.jackson.JsonEncoding; import org.codehaus.jackson.JsonFactory; import org.codehaus.jackson.JsonGenerationException; import org.codehaus.jackson.JsonGenerator; /** * BTSyncApp is used for starting an instance of BitTorrent Sync. A BitTorrent Sync v1.3.105 * executable for linux and windows platforms are bundled with this library. * * @author Omeed Safi */ public class BTSyncApp implements AutoCloseable { private String deviceName; private int listeningPort; private boolean useUpnp; private String storagePath; private boolean useGui; private String listen; private String login; private String password; private String apiKey; private File btSyncTmpFolder = new File(System.getProperty("java.io.tmpdir"), "BTSyncJava"); private File btSyncExecutable; private File btSyncConf = new File(btSyncTmpFolder, "sync.conf"); private Process runningAppProcess; /** * Constructs a new BTSyncApp used to start a BitTorrent Sync instance with default * settings. * * <p>Default Settings: * <ul> * <li>device_name = "BTSync-Java" * <li>listening_port = 0 (Meaning random port assignment) * <li>use_upnp = false * <li>storage_path = ./ * <li>use_gui = false * <li>listen = 127.0.0.1:18080 * <li>login = user * <li>password = password * </ul> * * @param apiKey the BitTorrent Sync API Key */ public BTSyncApp(String apiKey) { this.deviceName = "BTSyncJava"; this.listeningPort = 0; this.useUpnp = false; this.storagePath = "./"; this.useGui = false; this.listen = "127.0.0.1:18080"; this.login = "user"; this.password = "password"; this.apiKey = apiKey; try { FileUtils.deleteDirectory(btSyncTmpFolder); Files.createDirectory(btSyncTmpFolder.toPath()); } catch (Exception e) { e.printStackTrace(); } } /** * Sets the device_name for BitTorrent Sync to use. The default is <code>BTSync-Java</code> * * @param deviceName the deviceName to set * @return the updated BTSyncApp instance */ public BTSyncApp setDeviceName(String deviceName) { this.deviceName = deviceName; return this; } /** * Sets the listening_port for BitTorrent Sync to use. The default is <code>0</code> which * means a port is randomly assigned * * @param listeningPort the listeningPort to set * @return the updated BTSyncApp instance */ public BTSyncApp setListeningPort(int listeningPort) { this.listeningPort = listeningPort; return this; } /** * Sets the use_upnp flag for BitTorrent Sync. The default is <code>false</code>. * Need more research to understand what this flag actually is for better description. * * @param useUpnp whether BitTorrent Sync will use UPNP or not * @return the updated BTSyncApp instance */ public BTSyncApp setUseUpnp(boolean useUpnp) { this.useUpnp = useUpnp; return this; } /** * Sets the storage_path for BitTorrent Sync to use. The default is <code>./</code> * * @param storagePath the storagePath to set * @return the updated BTSyncApp instance */ public BTSyncApp setStoragePath(String storagePath) { this.storagePath = storagePath; return this; } /** * Sets the use_gui for BitTorrent Sync. The default is <code>false</code>. * The use_gui option sets whether or not BitTorrent Sync should be shown when running. * Effects of setting the use_gui value to <code>true</code> on linux is unknown as linux only has webui * * @param useGui whether the BT Sync GUI is shown or not * @return the updated BTSyncApp instance */ public BTSyncApp setUseGui(boolean useGui) { this.useGui = useGui; return this; } /** * Sets the address:port that BitTorrent Sync will listen on. The default is <code>127.0.0.1:18080</code>. * * @param listen the address:port * @return the updated BTSyncApp instance */ public BTSyncApp setListen(String listen) { this.listen = listen; return this; } /** * Sets the username for clients to use to accessing BitTorrent Sync API methods. * The default is <code>user</code>. * * @param login the username * @return the updated BTSyncApp instance */ public BTSyncApp setLogin(String login) { this.login = login; return this; } /** * Sets the password for clients to use to accessing BitTorrent Sync API methods. * The default is <code>password</code>. * * @param password the password * @return the updated BTSyncApp instance */ public BTSyncApp setPassword(String password) { this.password = password; return this; } /** * Starts BitTorrent Sync and returns an instance of BTSyncClient for accessing * the BitTorrent Sync API. * * <p>See the class description for the current limitations of this method. * * @return a BTSyncClient preconfigured for accessing the BitTorrent Sync started */ public BTSyncClient startBtSync() { if(SystemUtils.IS_OS_WINDOWS) { btSyncExecutable = new File(btSyncTmpFolder, "btsync.exe"); return this.startBtSyncWindows(); } else if(SystemUtils.IS_OS_UNIX) { btSyncExecutable = new File(btSyncTmpFolder, "btsync"); return this.startBtSyncLinux(); } else if(SystemUtils.IS_OS_MAC_OSX) { return this.startBtSyncMacOsx(); } else { return null; } } private BTSyncClient startBtSyncWindows() { this.extractWinBtSync(); this.buildConf(); try { //Print this line using logging api //System.out.println(btSyncExecutable.getCanonicalPath() + " /config " + btSyncConf.getCanonicalPath()); runningAppProcess = Runtime.getRuntime().exec(btSyncExecutable.getCanonicalPath() + " /config " + btSyncConf.getCanonicalPath()); } catch (IOException e) { e.printStackTrace(); } return new BTSyncClient(this.listen, this.login, this.password); } private BTSyncClient startBtSyncLinux() { this.extractLinuxBtSync(); this.buildConf(); try { //Print this line using logging api //System.out.println(btSyncExecutable.getCanonicalPath() + " --config " + btSyncConf.getCanonicalPath()); runningAppProcess = Runtime.getRuntime().exec(btSyncExecutable.getCanonicalPath() + " --config " + btSyncConf.getCanonicalPath()); } catch (IOException e) { e.printStackTrace(); } return new BTSyncClient(this.listen, this.login, this.password); } private BTSyncClient startBtSyncMacOsx() { return null; } private void buildConf() { try { Files.createFile(btSyncConf.toPath()); btSyncConf.setReadable(true, false); btSyncConf.setWritable(true, false); JsonFactory jFactory = new JsonFactory(); JsonGenerator jGenerator = jFactory.createJsonGenerator(btSyncConf, JsonEncoding.UTF8); jGenerator.useDefaultPrettyPrinter(); jGenerator.writeStartObject(); // { jGenerator.writeStringField("device_name", this.deviceName); jGenerator.writeNumberField("listening_port", this.listeningPort); jGenerator.writeBooleanField("check_for_updates", false); // NEVER CHECK FOR UPDATES jGenerator.writeBooleanField("use_upnp", useUpnp); jGenerator.writeStringField("storage_path", this.storagePath); jGenerator.writeBooleanField("use_gui", this.useGui); jGenerator.writeFieldName("webui"); jGenerator.writeStartObject(); // { jGenerator.writeStringField("listen", this.listen); jGenerator.writeStringField("login", this.login); jGenerator.writeStringField("password", this.password); jGenerator.writeStringField("api_key", this.apiKey); jGenerator.writeEndObject(); // } jGenerator.writeEndObject(); // } jGenerator.close(); } catch (JsonGenerationException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } } private void extractWinBtSync() { try { URL url = getClass().getClassLoader().getResource("btsync-win.exe"); InputStream in = url.openStream(); Files.copy(in, btSyncExecutable.toPath()); btSyncExecutable.setExecutable(true, false); btSyncExecutable.setReadable(true, false); btSyncExecutable.setWritable(true, false); } catch (IOException e) { e.printStackTrace(); } } private void extractLinuxBtSync() { try { URL url = getClass().getClassLoader().getResource("btsync-linux-i386"); InputStream in = url.openStream(); Files.copy(in, btSyncExecutable.toPath()); btSyncExecutable.setExecutable(true, false); btSyncExecutable.setReadable(true, false); btSyncExecutable.setWritable(true, false); } catch (IOException e) { e.printStackTrace(); } } @Override public void close() { // Close BTSync if running if(isAlive(runningAppProcess)) { runningAppProcess.destroy(); try { runningAppProcess.waitFor(); } catch (InterruptedException e) { System.out.println("Exception while waiting for the BTSync process to end"); e.printStackTrace(); } } // Cleanup files try { FileUtils.deleteDirectory(btSyncTmpFolder); } catch (IOException e) { e.printStackTrace(); } } public boolean isAlive(Process p) { try { p.exitValue(); return false; } catch (IllegalThreadStateException e) { return true; } } }
{ "content_hash": "011e23358beecb2557f3025683c3c7a0", "timestamp": "", "source": "github", "line_count": 321, "max_line_length": 133, "avg_line_length": 29.018691588785046, "alnum_prop": 0.7113258185721953, "repo_name": "osafi/BTSync-Java", "id": "fc535c50c02b6e5b714d0a849b108bb91e7d7320", "size": "9907", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "BTSync-Java/src/main/java/ms/safi/btsync/BTSyncApp.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Groovy", "bytes": "2024" }, { "name": "Java", "bytes": "64776" } ], "symlink_target": "" }
<?php defined('JPATH_BASE') or die; $data = $displayData; // Receive overridable options $data['options'] = !empty($data['options']) ? $data['options'] : array(); if ($data['view'] instanceof MenusViewItems) { $doc = JFactory::getDocument(); $doc->addStyleDeclaration(" /* Fixed filter field in search bar */ .js-stools .js-stools-menutype { float: left; margin-right: 10px; min-width: 220px; } html[dir=rtl] .js-stools .js-stools-menutype { float: right; margin-left: 10px margin-right: 0; } .js-stools .js-stools-container-bar .js-stools-field-filter .chzn-container { padding: 3px 0; } "); // Menutype filter doesn't have to activate the filter bar unset($data['view']->activeFilters['menutype']); } // Display the main joomla layout echo JLayoutHelper::render('joomla.searchtools.default', $data, null, array('component' => 'none'));
{ "content_hash": "4be6abe2758ce17fd14235c9a93b6cb3", "timestamp": "", "source": "github", "line_count": 37, "max_line_length": 100, "avg_line_length": 23.945945945945947, "alnum_prop": 0.6693002257336343, "repo_name": "yaelduckwen/libriastore", "id": "2be8cef926ab54538315a908546fa0b9a9873356", "size": "1124", "binary": false, "copies": "105", "ref": "refs/heads/master", "path": "joomla/administrator/components/com_menus/layouts/joomla/searchtools/default.php", "mode": "33188", "license": "mit", "language": [ { "name": "ApacheConf", "bytes": "44" }, { "name": "CSS", "bytes": "2779463" }, { "name": "HTML", "bytes": "26380" }, { "name": "JavaScript", "bytes": "2813038" }, { "name": "PHP", "bytes": "24821947" }, { "name": "PLpgSQL", "bytes": "2393" }, { "name": "SQLPL", "bytes": "17688" } ], "symlink_target": "" }
<?php // Get the PHP helper library from twilio.com/docs/php/install require_once '/path/to/vendor/autoload.php'; // Loads the library use Twilio\Rest\Client; // Your Account Sid and Auth Token from twilio.com/user/account $accountSid = "ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX"; $authToken = "your_auth_token"; $workspaceSid = "WSXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX"; $workerSid = "WKXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX"; $client = new Client($accountSid, $authToken); $statistics = $client->taskrouter ->workspaces($workspaceSid) ->workers($workerSid) ->statistics() ->fetch( array('minutes' => 60) ); echo $statistics->cumulative["reservations_accepted"];
{ "content_hash": "60bf05bc5cf552ae83ea8c0dc5926eaa", "timestamp": "", "source": "github", "line_count": 23, "max_line_length": 65, "avg_line_length": 29.608695652173914, "alnum_prop": 0.7283406754772394, "repo_name": "teoreteetik/api-snippets", "id": "5da8c0c22b9ca5e0b8b64296e9cd848b3d8183b6", "size": "681", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "rest/taskrouter/statistics/workers/example-1/example-1.5.x.php", "mode": "33188", "license": "mit", "language": [ { "name": "C#", "bytes": "643369" }, { "name": "HTML", "bytes": "335" }, { "name": "Java", "bytes": "943336" }, { "name": "JavaScript", "bytes": "539577" }, { "name": "M", "bytes": "117" }, { "name": "Mathematica", "bytes": "93" }, { "name": "Objective-C", "bytes": "46198" }, { "name": "PHP", "bytes": "538312" }, { "name": "Python", "bytes": "467248" }, { "name": "Ruby", "bytes": "470316" }, { "name": "Shell", "bytes": "1564" }, { "name": "Swift", "bytes": "36563" } ], "symlink_target": "" }
<?xml version="1.0" encoding="utf-8"?> <manifest xmlns:android="http://schemas.android.com/apk/res/android" package="com.rndetectnavbarandroid" > </manifest>
{ "content_hash": "14b41b2bdd491177599755147cac5b67", "timestamp": "", "source": "github", "line_count": 4, "max_line_length": 68, "avg_line_length": 40.5, "alnum_prop": 0.7222222222222222, "repo_name": "lequanghuylc/react-native-detect-navbar-android", "id": "cf557cd5e8f70befc4714618a71a3da9c222336d", "size": "162", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "android/src/main/AndroidManifest.xml", "mode": "33188", "license": "mit", "language": [ { "name": "Java", "bytes": "3245" }, { "name": "JavaScript", "bytes": "445" } ], "symlink_target": "" }
docker build -t asn1_codec_dev:latest -f Dockerfile.dev .
{ "content_hash": "c2afb3c6e75a21f6589812b7e08304ed", "timestamp": "", "source": "github", "line_count": 1, "max_line_length": 57, "avg_line_length": 57, "alnum_prop": 0.7719298245614035, "repo_name": "usdot-jpo-ode/asn1_codec", "id": "b50093abc7c4571d4720e79935bf5f63c080dbf0", "size": "57", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "docker_dev_build.cmd", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Batchfile", "bytes": "332" }, { "name": "C", "bytes": "30710" }, { "name": "C++", "bytes": "1447521" }, { "name": "CMake", "bytes": "6941" }, { "name": "Python", "bytes": "1175" }, { "name": "Shell", "bytes": "5793" } ], "symlink_target": "" }
Rails.application.configure do # Settings specified here will take precedence over those in config/application.rb. # Code is not reloaded between requests. config.cache_classes = true # Eager load code on boot. This eager loads most of Rails and # your application in memory, allowing both threaded web servers # and those relying on copy on write to perform better. # Rake tasks automatically ignore this option for performance. config.eager_load = true # Full error reports are disabled and caching is turned on. config.consider_all_requests_local = false config.action_controller.perform_caching = true # Attempt to read encrypted secrets from `config/secrets.yml.enc`. # Requires an encryption key in `ENV["RAILS_MASTER_KEY"]` or # `config/secrets.yml.key`. config.read_encrypted_secrets = true # Disable serving static files from the `/public` folder by default since # Apache or NGINX already handles this. config.public_file_server.enabled = ENV['RAILS_SERVE_STATIC_FILES'].present? # Compress JavaScripts and CSS. config.assets.js_compressor = :uglifier # config.assets.css_compressor = :sass # Do not fallback to assets pipeline if a precompiled asset is missed. config.assets.compile = false # `config.assets.precompile` and `config.assets.version` have moved to config/initializers/assets.rb # Enable serving of images, stylesheets, and JavaScripts from an asset server. # config.action_controller.asset_host = 'http://assets.example.com' # Specifies the header that your server uses for sending files. # config.action_dispatch.x_sendfile_header = 'X-Sendfile' # for Apache # config.action_dispatch.x_sendfile_header = 'X-Accel-Redirect' # for NGINX # Mount Action Cable outside main process or domain # config.action_cable.mount_path = nil # config.action_cable.url = 'wss://example.com/cable' # config.action_cable.allowed_request_origins = [ 'http://example.com', /http:\/\/example.*/ ] # Force all access to the app over SSL, use Strict-Transport-Security, and use secure cookies. # config.force_ssl = true # Use the lowest log level to ensure availability of diagnostic information # when problems arise. config.log_level = :debug # Prepend all log lines with the following tags. config.log_tags = [ :request_id ] # Use a different cache store in production. # config.cache_store = :mem_cache_store # Use a real queuing backend for Active Job (and separate queues per environment) # config.active_job.queue_adapter = :resque # config.active_job.queue_name_prefix = "hawk_set_#{Rails.env}" config.action_mailer.perform_caching = false # Ignore bad email addresses and do not raise email delivery errors. # Set this to true and configure the email server for immediate delivery to raise delivery errors. # config.action_mailer.raise_delivery_errors = false # Enable locale fallbacks for I18n (makes lookups for any locale fall back to # the I18n.default_locale when a translation cannot be found). config.i18n.fallbacks = true # Send deprecation notices to registered listeners. config.active_support.deprecation = :notify # Use default logging formatter so that PID and timestamp are not suppressed. config.log_formatter = ::Logger::Formatter.new # Use a different logger for distributed setups. # require 'syslog/logger' # config.logger = ActiveSupport::TaggedLogging.new(Syslog::Logger.new 'app-name') if ENV["RAILS_LOG_TO_STDOUT"].present? logger = ActiveSupport::Logger.new(STDOUT) logger.formatter = config.log_formatter config.logger = ActiveSupport::TaggedLogging.new(logger) end # Do not dump schema after migrations. config.active_record.dump_schema_after_migration = false end
{ "content_hash": "3032a8c03c4270eab66a0e78f755e867", "timestamp": "", "source": "github", "line_count": 91, "max_line_length": 102, "avg_line_length": 41.604395604395606, "alnum_prop": 0.7406233491811939, "repo_name": "jshopsin/Hawk_Set", "id": "575652db2ed6b1eeed52acec63a8f947a8e28ab5", "size": "3786", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "config/environments/production.rb", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "3997" }, { "name": "HTML", "bytes": "16685" }, { "name": "JavaScript", "bytes": "3973" }, { "name": "Ruby", "bytes": "70973" } ], "symlink_target": "" }
namespace TMDbLib.Objects.Movies { public enum ReleaseDateType { Premiere = 1, TheatricalLimited = 2, Theatrical = 3, Digital = 4, Physical = 5, TV = 6 } }
{ "content_hash": "cd78441e70d5fcb40e2d755bae61c92b", "timestamp": "", "source": "github", "line_count": 12, "max_line_length": 33, "avg_line_length": 18, "alnum_prop": 0.5185185185185185, "repo_name": "LordMike/TMDbLib", "id": "1ae882b254b8ea0a56eeb6a0c2504159138cffd5", "size": "218", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "TMDbLib/Objects/Movies/ReleaseDateType.cs", "mode": "33188", "license": "mit", "language": [ { "name": "C#", "bytes": "479153" } ], "symlink_target": "" }
import { exposeGlobally, normalizeFlag } from '@flopflip/adapter-utilities'; import { type TAdapterEventHandlers, type TAdapterStatus, type TAdapterStatusChange, type TFlagName, type TFlags, type TFlagsChange, type TFlagVariation, type TMemoryAdapterArgs, type TMemoryAdapterInterface, type TUpdateFlagsOptions, type TUser, AdapterConfigurationStatus, adapterIdentifiers, AdapterInitializationStatus, AdapterSubscriptionStatus, } from '@flopflip/types'; import mitt, { type Emitter } from 'mitt'; import warning from 'tiny-warning'; type TInternalStatusChange = '__internalConfiguredStatusChange__'; type TEmitterEvents = { __internalConfiguredStatusChange__: undefined; flagsStateChange: TFlags; statusStateChange: Partial<TAdapterStatus>; }; type TMemoryAdapterState = { flags: TFlags; lockedFlags: Set<TFlagName>; user?: TUser; emitter: Emitter<TEmitterEvents>; }; const intialAdapterState: TAdapterStatus & TMemoryAdapterState = { configurationStatus: AdapterConfigurationStatus.Unconfigured, subscriptionStatus: AdapterSubscriptionStatus.Subscribed, flags: {}, lockedFlags: new Set<TFlagName>(), user: {}, emitter: mitt(), }; class MemoryAdapter implements TMemoryAdapterInterface { #__internalConfiguredStatusChange__: TInternalStatusChange = '__internalConfiguredStatusChange__'; #adapterState: TAdapterStatus & TMemoryAdapterState; id: typeof adapterIdentifiers.memory; constructor() { this.#adapterState = { ...intialAdapterState, }; this.id = adapterIdentifiers.memory; } #getIsAdapterUnsubscribed = () => this.#adapterState.subscriptionStatus === AdapterSubscriptionStatus.Unsubscribed; #getIsFlagLocked = (flagName: TFlagName) => this.#adapterState.lockedFlags.has(flagName); #updateUser = (user: TUser) => { this.#adapterState.user = user; }; getUser = () => this.#adapterState.user; updateFlags = (flags: TFlags, options?: TUpdateFlagsOptions) => { const isAdapterConfigured = this.getIsConfigurationStatus( AdapterConfigurationStatus.Configured ); warning( isAdapterConfigured, '@flopflip/memory-adapter: adapter is not configured. Flags can not be updated before.' ); if (!isAdapterConfigured) return; Object.entries(flags).forEach(([flagName, flagValue]) => { const [normalizedFlagName, normalizedFlagValue] = normalizeFlag( flagName, flagValue ); if (this.#getIsFlagLocked(normalizedFlagName)) return; if (options?.lockFlags) { this.#adapterState.lockedFlags.add(normalizedFlagName); } this.#adapterState.flags = { ...this.#adapterState.flags, [normalizedFlagName]: normalizedFlagValue, }; }); this.#adapterState.emitter.emit( 'flagsStateChange', this.#adapterState.flags ); }; async configure( adapterArgs: TMemoryAdapterArgs, adapterEventHandlers: TAdapterEventHandlers ) { const handleFlagsChange = (nextFlags: TFlagsChange['flags']) => { if (this.#getIsAdapterUnsubscribed()) return; adapterEventHandlers.onFlagsStateChange({ flags: nextFlags, id: this.id, }); }; const handleStatusChange = (nextStatus: TAdapterStatusChange['status']) => { if (this.#getIsAdapterUnsubscribed()) return; adapterEventHandlers.onStatusStateChange({ status: nextStatus, id: this.id, }); }; this.#adapterState.emitter.on('flagsStateChange', handleFlagsChange); this.#adapterState.emitter.on('statusStateChange', handleStatusChange); this.setConfigurationStatus(AdapterConfigurationStatus.Configuring); const { user } = adapterArgs; this.#adapterState.user = user; return Promise.resolve().then(() => { this.#adapterState.flags = {}; this.#updateUser(user); this.setConfigurationStatus(AdapterConfigurationStatus.Configured); this.#adapterState.emitter.emit( 'flagsStateChange', this.#adapterState.flags ); this.#adapterState.emitter.emit(this.#__internalConfiguredStatusChange__); return { initializationStatus: AdapterInitializationStatus.Succeeded, }; }); } async reconfigure( adapterArgs: TMemoryAdapterArgs, _adapterEventHandlers: TAdapterEventHandlers ) { this.setConfigurationStatus(AdapterConfigurationStatus.Configuring); this.#updateUser(adapterArgs.user); this.#adapterState.flags = {}; this.setConfigurationStatus(AdapterConfigurationStatus.Configured); this.#adapterState.emitter.emit( 'flagsStateChange', this.#adapterState.flags ); return Promise.resolve({ initializationStatus: AdapterInitializationStatus.Succeeded, }); } getIsConfigurationStatus(configurationStatus: AdapterConfigurationStatus) { return this.#adapterState.configurationStatus === configurationStatus; } setConfigurationStatus(nextConfigurationStatus: AdapterConfigurationStatus) { this.#adapterState.configurationStatus = nextConfigurationStatus; this.#adapterState.emitter.emit('statusStateChange', { configurationStatus: this.#adapterState.configurationStatus, }); } reset = () => { this.#adapterState = { ...intialAdapterState, }; }; async waitUntilConfigured() { return new Promise<void>((resolve) => { if (this.getIsConfigurationStatus(AdapterConfigurationStatus.Configured)) resolve(); else this.#adapterState.emitter.on( this.#__internalConfiguredStatusChange__, resolve ); }); } getFlag(flagName: TFlagName): TFlagVariation { return this.#adapterState?.flags[flagName]; } unsubscribe = () => { this.#adapterState.subscriptionStatus = AdapterSubscriptionStatus.Unsubscribed; }; subscribe = () => { this.#adapterState.subscriptionStatus = AdapterSubscriptionStatus.Subscribed; }; } const adapter = new MemoryAdapter(); exposeGlobally(adapter); export default adapter;
{ "content_hash": "8fb2f9bee0c7fa9cbaed687bb8c56d2e", "timestamp": "", "source": "github", "line_count": 230, "max_line_length": 93, "avg_line_length": 26.469565217391306, "alnum_prop": 0.7030223390275953, "repo_name": "tdeekens/flopflip", "id": "0269627f73dbab2028578193d286bc173f1924ad", "size": "6088", "binary": false, "copies": "1", "ref": "refs/heads/main", "path": "packages/memory-adapter/src/adapter/adapter.ts", "mode": "33188", "license": "mit", "language": [ { "name": "JavaScript", "bytes": "181809" }, { "name": "Prolog", "bytes": "1702" }, { "name": "Shell", "bytes": "893" }, { "name": "TypeScript", "bytes": "146840" } ], "symlink_target": "" }
UNIX_ElementInPolicyRoleCollectionFixture::UNIX_ElementInPolicyRoleCollectionFixture() { } UNIX_ElementInPolicyRoleCollectionFixture::~UNIX_ElementInPolicyRoleCollectionFixture() { } void UNIX_ElementInPolicyRoleCollectionFixture::Run() { CIMName className("UNIX_ElementInPolicyRoleCollection"); CIMNamespaceName nameSpace("root/cimv2"); UNIX_ElementInPolicyRoleCollection _p; UNIX_ElementInPolicyRoleCollectionProvider _provider; Uint32 propertyCount; CIMOMHandle omHandle; _provider.initialize(omHandle); _p.initialize(); for(int pIndex = 0; _p.load(pIndex); pIndex++) { CIMInstance instance = _provider.constructInstance(className, nameSpace, _p); CIMObjectPath path = instance.getPath(); cout << path.toString() << endl; propertyCount = instance.getPropertyCount(); for(Uint32 i = 0; i < propertyCount; i++) { CIMProperty propertyItem = instance.getProperty(i); cout << " Name: " << propertyItem.getName().getString() << " - Value: " << propertyItem.getValue().toString() << endl; } cout << "------------------------------------" << endl; cout << endl; } _p.finalize(); }
{ "content_hash": "e7e0a3f2d074704432ee5f6135dde416", "timestamp": "", "source": "github", "line_count": 41, "max_line_length": 121, "avg_line_length": 27.536585365853657, "alnum_prop": 0.7059344552701505, "repo_name": "brunolauze/openpegasus-providers-old", "id": "a249583194685050ac8fba2d5b2c68d091cc2d76", "size": "2961", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "src/Providers/UNIXProviders/tests/UNIXProviders.Tests/UNIX_ElementInPolicyRoleCollectionFixture.cpp", "mode": "33188", "license": "mit", "language": [ { "name": "C", "bytes": "2631164" }, { "name": "C++", "bytes": "120884401" }, { "name": "Objective-C", "bytes": "64" }, { "name": "Shell", "bytes": "17094" } ], "symlink_target": "" }
""" [env] # Conda Environment conda create --name automate_po_job python=3.9.7 conda info --envs source activate automate_po_job conda deactivate # if needed to remove conda env remove -n [NAME_OF_THE_CONDA_ENVIRONMENT] [path] cd /Users/brunoflaven/Documents/03_git/BlogArticlesExamples/automate_po_job_demo_support/002_pythonspot/ [file] python pythonspot_dummy.py [source] https://pythonspot.com/orm-with-sqlalchemy/ [required] # install pip install streamlit pip install watchdog pip install sqlalchemy pip install -r requirements.txt CREATE TABLE student ( id INTEGER NOT NULL, username VARCHAR, firstname VARCHAR, lastname VARCHAR, university VARCHAR, PRIMARY KEY (id) ) """ import datetime from sqlalchemy import create_engine from sqlalchemy.orm import sessionmaker # required check schema_pythonspot_tabledef.py from schema_pythonspot_tabledef import * # personal configuration import config_values.values_conf as conf ### 2. VALUES ### URI_SQLITE_DB_PYTHONSPOT = conf.URI_SQLITE_DB_PYTHONSPOT # engine = create_engine(f'sqlite:///{URI_SQLITE_DB_PYTHONSPOT}', echo=True) engine = create_engine(f'sqlite:///{URI_SQLITE_DB_PYTHONSPOT}', echo=False) # create a Session Session = sessionmaker(bind=engine) session = Session() # Create objects user = Student("james", "James", "Boogie", "MIT") session.add(user) user = Student("lara", "Lara", "Miami", "UU") session.add(user) user = Student("eric", "Eric", "York", "Stanford") session.add(user) user = Student("bruno", "Bruno", "Bentolila", "IUOO") session.add(user) user = Student("prisca", "Prisca", "Jore", "Heidelberg University") session.add(user) # commit the record the database session.commit() # DEBUG print(f'2. ROWS INSERTED IN :: {URI_SQLITE_DB_PYTHONSPOT}')
{ "content_hash": "7d36e388e34683e746fc5d3fe3fd1dbd", "timestamp": "", "source": "github", "line_count": 90, "max_line_length": 104, "avg_line_length": 19.633333333333333, "alnum_prop": 0.7357102433503112, "repo_name": "bflaven/BlogArticlesExamples", "id": "8e61a111db1fa7c2d50f953236b0747feb048f90", "size": "1810", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "automate_po_job_demo_support/002_pythonspot/pythonspot_dummy.py", "mode": "33188", "license": "mit", "language": [ { "name": "AppleScript", "bytes": "2756" }, { "name": "CSS", "bytes": "3497" }, { "name": "CoffeeScript", "bytes": "1785" }, { "name": "Dockerfile", "bytes": "993" }, { "name": "HTML", "bytes": "23687927" }, { "name": "JavaScript", "bytes": "12838" }, { "name": "Jupyter Notebook", "bytes": "2918640" }, { "name": "Makefile", "bytes": "4058" }, { "name": "PHP", "bytes": "223161" }, { "name": "Python", "bytes": "1461699" }, { "name": "Shell", "bytes": "12291" } ], "symlink_target": "" }
PDI=GEN006460 #Start-Lockdown # Couldn't find any reference to this in the documentation or scripts. Until # more or updated info can be provided I'm moving this to a manual check.
{ "content_hash": "f98f7d990745da966b72abca7b34639c", "timestamp": "", "source": "github", "line_count": 6, "max_line_length": 77, "avg_line_length": 30.666666666666668, "alnum_prop": 0.7717391304347826, "repo_name": "tomhurd/clip", "id": "9a5a7accf82110aa48e88f68484447c90e73178e", "size": "2727", "binary": false, "copies": "4", "ref": "refs/heads/master", "path": "packages/aqueduct/aqueduct/compliance/Bash/STIG/rhel-5-beta/manual-checks/GEN006460.sh", "mode": "33261", "license": "apache-2.0", "language": [ { "name": "Augeas", "bytes": "1413" }, { "name": "Awk", "bytes": "209" }, { "name": "C", "bytes": "13623" }, { "name": "CSS", "bytes": "11752" }, { "name": "JavaScript", "bytes": "4586" }, { "name": "Makefile", "bytes": "27100" }, { "name": "Pascal", "bytes": "91645" }, { "name": "Perl", "bytes": "8268" }, { "name": "Puppet", "bytes": "18738" }, { "name": "Python", "bytes": "263618" }, { "name": "Ruby", "bytes": "4278" }, { "name": "Shell", "bytes": "5489710" }, { "name": "XSLT", "bytes": "171062" } ], "symlink_target": "" }
ACCEPTED #### According to Index Fungorum #### Published in Bull. natn. Sci. Mus. , Tokyo, B 2(4): 129 (1976) #### Original name Protocreopsis musicola Yoshim. Doi ### Remarks null
{ "content_hash": "1144b221b419e25dae387465552448d8", "timestamp": "", "source": "github", "line_count": 13, "max_line_length": 49, "avg_line_length": 14.153846153846153, "alnum_prop": 0.6793478260869565, "repo_name": "mdoering/backbone", "id": "44d66dbc2a8a2c0aa642b7953b76d2a82a18083a", "size": "242", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "life/Fungi/Ascomycota/Sordariomycetes/Hypocreales/Bionectriaceae/Protocreopsis/Protocreopsis musicola/README.md", "mode": "33188", "license": "apache-2.0", "language": [], "symlink_target": "" }
// Copyright (c) Microsoft Technologies, Inc. All rights reserved. // Licensed under the Apache License, Version 2.0. // See License.txt in the project root for license information. using System; using System.Net; using System.Net.Security; using System.Security.Cryptography.X509Certificates; using CompatCheckAndMigrate.Controls; using CompatCheckAndMigrate.Helpers; using CompatCheckAndMigrate.ObjectModel; using System.Collections.Generic; using System.Windows.Forms; using System.Diagnostics; using System.IO; namespace CompatCheckAndMigrate { public partial class MainForm : Form { private Control _previousControl = null; private Dictionary<WizardSteps, IWizardStep> _steps = new Dictionary<WizardSteps, IWizardStep>() { {WizardSteps.FeedbackPage, new SendFeedbackControl()}, { WizardSteps.MigrationCandidates, new MigrationCandidatesControl() }, { WizardSteps.ReadinessReport, new ReadinessReportControl() }, { WizardSteps.SaveReadinessReport, new SaveReadinessReportControl() }, { WizardSteps.Confirmation, new ConfirmationControl() }, {WizardSteps.ContentAndDbMigration, new ContentAndDbMigrationControl()}, {WizardSteps.SiteStep,new MigrationSite()}, {WizardSteps.InstallWebDeploy, new InstallerControl()}, {WizardSteps.SiteNotMigrated, new SiteStatusControl()}, {WizardSteps.RemoteComputerInfo, new RemoteServerControl()}, {WizardSteps.AddRemoteServers, new AddRemoteServers()}, {WizardSteps.PickPublishSettings, new PickPublishSettingsControl()}, }; private void InitializeTrace() { TraceHelper.Tracer = new Tracer(); } public MainForm() { InitializeComponent(); InitializeTrace(); CheckAndSetBrowserEmulation(); this.WindowState = FormWindowState.Maximized; } public static void WriteTrace(string format, params object[] args) { TraceHelper.Tracer.WriteTrace(format, args); } private static void CheckAndSetBrowserEmulation() { // Get highest iE installed var ieVersion = Helper.InstalledIEVersion; if (ieVersion < 8 || ieVersion > 13) { Helper.ShowErrorMessageAndExit("The application needs IE 8 or higher installed. Please install the latest IE supported for this system and restart the application. The application will now exit"); } Helper.SetEmulationVersion(ieVersion); } static MainForm() { ServicePointManager.ServerCertificateValidationCallback += ServerCertificateValidationCallback; } private static bool ServerCertificateValidationCallback(object sender, X509Certificate cert, X509Chain chain, SslPolicyErrors errors) { return true; } private void MainForm_Load(object sender, System.EventArgs e) { InitializeWizardSteps(); } private void InitializeWizardSteps() { // Subscribe to wizard steps notifications foreach (var step in _steps) { step.Value.GoTo += OnGoToStep; } if (Helper.IsWebDeployInstalled && !Helper.IsIISComponentNeeded) { // Go to first step GoToStep(WizardSteps.RemoteComputerInfo, null); } else { var result = MessageBox.Show("Web Deploy is needed for migrating your site content and database to azure. Would you like to install it?", "Web Deploy For Publish", MessageBoxButtons.YesNo); if (result == DialogResult.Yes) { GoToStep(WizardSteps.InstallWebDeploy, null); } else { GoToStep(WizardSteps.RemoteComputerInfo, null); } } } private void OnGoToStep(object sender, GoToWizardStepEventArgs e) { GoToStep(e.GoTo, e.State, e.IsNavigatingBack); } private void GoToStep(WizardSteps step, object state, bool isNavigatingBack = false) { this.SuspendLayout(); if (_previousControl != null) { this.contentPanel.Controls.Remove(_previousControl); } IWizardStep wizardStep = _steps[step]; wizardStep.SetState(state, isNavigatingBack); Control wizardStepControl = (Control)wizardStep; wizardStepControl.Dock = DockStyle.Fill; this.contentPanel.Controls.Add(wizardStepControl); this.contentPanel.ResumeLayout(false); this.contentPanel.PerformLayout(); this.ResumeLayout(false); _previousControl = wizardStepControl; } private void MainForm_FormClosing(object sender, FormClosingEventArgs e) { } } }
{ "content_hash": "24928209ca328bc1c3185f1896094d63", "timestamp": "", "source": "github", "line_count": 147, "max_line_length": 212, "avg_line_length": 35.61224489795919, "alnum_prop": 0.6061127029608405, "repo_name": "Azure/Azure-Websites-Migration-Tool", "id": "f0a98514317d7d34d2c61ce2aaf69b015cb32f39", "size": "5237", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "MainForm.cs", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Batchfile", "bytes": "12875" }, { "name": "C#", "bytes": "309793" } ], "symlink_target": "" }
import MemoizedFieldCmd from '../classes/MemoizedFieldCmd'; export function memoized(computeFn) { return new MemoizedFieldCmd(computeFn); } export default memoized;
{ "content_hash": "5295d1e60c4ba5bc0839738d8dd67553", "timestamp": "", "source": "github", "line_count": 8, "max_line_length": 59, "avg_line_length": 21.25, "alnum_prop": 0.7941176470588235, "repo_name": "mangojuicejs/mangojuice", "id": "71bafbf4fa37d8476824b7377614d3dfd706f630", "size": "170", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "packages/mangojuice-core/src/core/memoized.js", "mode": "33188", "license": "mit", "language": [ { "name": "JavaScript", "bytes": "147875" } ], "symlink_target": "" }
package main import ( "encoding/json" "strings" "github.com/aws/aws-sdk-go/aws" "github.com/aws/aws-sdk-go/service/lambda" ) func addPermissionToLambdaFromCloudWatchEvents(lc *lambda.Lambda, rules []Rule) error { for _, rule := range rules { for _, target := range rule.Targets { if !IsLambdaFunction(target.Arn) { continue } if result, err := isAlreadyAddPermission(lc, rule, target); err != nil { return err } else if result { // do nothing (already granted permission) continue } else { _, errL := lc.AddPermission(&lambda.AddPermissionInput{ Action: aws.String("lambda:InvokeFunction"), FunctionName: aws.String(LambdaFunctionNameFromArn(target.Arn)), Principal: aws.String("events.amazonaws.com"), SourceArn: rule.ActualRule.Arn, StatementId: aws.String(target.ID), }) if errL != nil { return errL } } } } return nil } func removePermissonFromLambda(lc *lambda.Lambda, rules []Rule) error { for _, rule := range rules { for _, target := range rule.Targets { if target.NeedDelete && IsLambdaFunction(*target.ActualTarget.Arn) { _, err := lc.RemovePermission(&lambda.RemovePermissionInput{ FunctionName: target.ActualTarget.Arn, StatementId: target.ActualTarget.Id, }) if err != nil { return err } } } } return nil } func isAlreadyAddPermission(lc *lambda.Lambda, rule Rule, target Target) (bool, error) { var policy LambdaPolicy policyOutput, err := lc.GetPolicy(&lambda.GetPolicyInput{ FunctionName: &target.Arn, }) if err != nil { return false, err } errJ := json.Unmarshal([]byte(*policyOutput.Policy), &policy) if errJ != nil { return false, errJ } for _, statement := range *policy.Statement { if (statement.Resource == target.Arn && strings.HasSuffix(statement.Condition.ArnLike.AwsSourceArn, rule.Name) && statement.Effect == "Allow" && statement.Principal.Service == "events.amazonaws.com" && statement.Action == "lambda:InvokeFunction") || statement.StatementID == target.ID { return true, nil } } return false, nil } // IsLambdaFunction return true if passed arn is lambda func IsLambdaFunction(arn string) bool { return strings.HasPrefix(arn, "arn:aws:lambda") } // LambdaFunctionNameFromArn return lambda function name from arn string func LambdaFunctionNameFromArn(arn string) string { return strings.Split(arn, ":")[6] }
{ "content_hash": "16024ce07fdb0622850efe5a890c390f", "timestamp": "", "source": "github", "line_count": 98, "max_line_length": 88, "avg_line_length": 24.948979591836736, "alnum_prop": 0.681799591002045, "repo_name": "unasuke/maekawa", "id": "ae520bdb9144ac3cbcd16d5650e7b9f504d4a007", "size": "2445", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "lambda.go", "mode": "33188", "license": "mit", "language": [ { "name": "Go", "bytes": "49482" } ], "symlink_target": "" }
using System; namespace Braintree { public class SearchNode<T> { protected string Name; protected T Parent; public SearchNode(string name, T parent) { Name = name; Parent = parent; } } }
{ "content_hash": "bbff43b694dff6fda7e82a386561d75e", "timestamp": "", "source": "github", "line_count": 16, "max_line_length": 48, "avg_line_length": 16.5625, "alnum_prop": 0.5245283018867924, "repo_name": "scottmeyer/braintree_dotnet", "id": "c63cb5093dab6b96b8b5780b2bc126a3a445e9d8", "size": "295", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "Braintree/SearchNode.cs", "mode": "33188", "license": "mit", "language": [ { "name": "Batchfile", "bytes": "2864" }, { "name": "C#", "bytes": "1117740" }, { "name": "HTML", "bytes": "6020" }, { "name": "Ruby", "bytes": "1571" }, { "name": "Shell", "bytes": "26" } ], "symlink_target": "" }
package com.opencredo.concursus.domain.events.batching; import com.opencredo.concursus.domain.events.Event; import com.opencredo.concursus.domain.events.channels.EventsOutChannel; import java.util.LinkedList; import java.util.List; import java.util.UUID; final class BufferingEventBatch implements EventBatch { static EventBatch buffering(EventBatch eventBatch, EventsOutChannel outChannel) { return new BufferingEventBatch(eventBatch, outChannel); } private final EventBatch eventBatch; private final EventsOutChannel outChannel; private final List<Event> buffer = new LinkedList<>(); private BufferingEventBatch(EventBatch eventBatch, EventsOutChannel outChannel) { this.eventBatch = eventBatch; this.outChannel = outChannel; } @Override public void accept(Event event) { eventBatch.accept(event); buffer.add(event); } @Override public UUID getId() { return eventBatch.getId(); } @Override public void complete() { eventBatch.complete(); outChannel.accept(buffer); } }
{ "content_hash": "eafa338d2f5c7c788a17b495b0e38671", "timestamp": "", "source": "github", "line_count": 41, "max_line_length": 85, "avg_line_length": 27.024390243902438, "alnum_prop": 0.7148014440433214, "repo_name": "opencredo/concursus", "id": "65c2794bcc7c9332038ef73a86d9c3a19f1e4e76", "size": "1108", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "concursus-domain/src/main/java/com/opencredo/concursus/domain/events/batching/BufferingEventBatch.java", "mode": "33188", "license": "mit", "language": [ { "name": "Java", "bytes": "644126" }, { "name": "Kotlin", "bytes": "22700" } ], "symlink_target": "" }
namespace chrono { namespace vehicle { // ----------------------------------------------------------------------------- ChTrackShoeDoublePin::ChTrackShoeDoublePin(const std::string& name, DoublePinTrackShoeType topology) : ChTrackShoeSegmented(name), m_topology(topology) {} ChTrackShoeDoublePin::~ChTrackShoeDoublePin() { if (!m_shoe) return; auto sys = m_shoe->GetSystem(); if (sys) { switch (m_topology) { case DoublePinTrackShoeType::TWO_CONNECTORS: sys->Remove(m_connector_L); sys->Remove(m_connector_R); ChChassis::RemoveJoint(m_joint_L); ChChassis::RemoveJoint(m_joint_R); if (m_rsda_L) { sys->Remove(m_rsda_L); sys->Remove(m_rsda_R); } ChChassis::RemoveJoint(m_connection_joint_L); ChChassis::RemoveJoint(m_connection_joint_R); if (m_connection_rsda_L) { sys->Remove(m_connection_rsda_L); sys->Remove(m_connection_rsda_R); } break; case DoublePinTrackShoeType::ONE_CONNECTOR: sys->Remove(m_connector_L); ChChassis::RemoveJoint(m_joint_L); if (m_rsda_L) { sys->Remove(m_rsda_L); } ChChassis::RemoveJoint(m_connection_joint_L); if (m_connection_rsda_L) { sys->Remove(m_connection_rsda_L); } break; } } } // ----------------------------------------------------------------------------- void ChTrackShoeDoublePin::Initialize(std::shared_ptr<ChBodyAuxRef> chassis, const ChVector<>& location, const ChQuaternion<>& rotation) { ChTrackShoeSegmented::Initialize(chassis, location, rotation); ChSystem* sys = chassis->GetSystem(); // Express the track shoe location and orientation in global frame. ChVector<> loc = chassis->TransformPointLocalToParent(location); ChQuaternion<> rot = chassis->GetRot() * rotation; ChVector<> xdir = rot.GetXaxis(); ChVector<> ydir = rot.GetYaxis(); // Create the shoe body m_shoe = std::shared_ptr<ChBody>(sys->NewBody()); m_shoe->SetNameString(m_name + "_shoe"); m_shoe->SetIdentifier(BodyID::SHOE_BODY); m_shoe->SetPos(loc - (0.5 * GetConnectorLength()) * xdir); m_shoe->SetRot(rot); m_shoe->SetMass(GetShoeMass()); m_shoe->SetInertiaXX(GetShoeInertia()); m_shoe->SetCollide(true); chassis->GetSystem()->AddBody(m_shoe); // Create the connector bodies. switch (m_topology) { case DoublePinTrackShoeType::TWO_CONNECTORS: { m_connector_L = std::shared_ptr<ChBody>(sys->NewBody()); m_connector_L->SetNameString(m_name + "_connector_L"); m_connector_L->SetPos(loc + (0.5 * GetShoeLength()) * xdir + (0.5 * GetShoeWidth()) * ydir); m_connector_L->SetRot(rot); m_connector_L->SetMass(GetConnectorMass()); m_connector_L->SetInertiaXX(GetConnectorInertia()); chassis->GetSystem()->AddBody(m_connector_L); m_connector_R = std::shared_ptr<ChBody>(chassis->GetSystem()->NewBody()); m_connector_R->SetNameString(m_name + "_connector_R"); m_connector_R->SetPos(loc + (0.5 * GetShoeLength()) * xdir - (0.5 * GetShoeWidth()) * ydir); m_connector_R->SetRot(rot); m_connector_R->SetMass(GetConnectorMass()); m_connector_R->SetInertiaXX(GetConnectorInertia()); chassis->GetSystem()->AddBody(m_connector_R); } break; case DoublePinTrackShoeType::ONE_CONNECTOR: { // Set mass and inertia corresponding to two separate connector bodies. double mass_connector = 2.0 * GetConnectorMass(); ChVector<> inertia_connector = 2.0 * GetConnectorInertia(); inertia_connector.y() += 2.0 * GetConnectorMass() * (0.5 * GetShoeWidth()) * (0.5 * GetShoeWidth()); m_connector_L = std::shared_ptr<ChBody>(sys->NewBody()); m_connector_L->SetNameString(m_name + "_connector"); m_connector_L->SetPos(loc + (0.5 * GetShoeLength()) * xdir); m_connector_L->SetRot(rot); m_connector_L->SetMass(mass_connector); m_connector_L->SetInertiaXX(inertia_connector); chassis->GetSystem()->AddBody(m_connector_L); } break; } // Add contact geometry on shoe body m_geometry.CreateCollisionShapes(m_shoe, TrackedCollisionFamily::SHOES, sys->GetContactMethod()); m_shoe->GetCollisionModel()->SetFamilyMaskNoCollisionWithFamily(TrackedCollisionFamily::SHOES); } void ChTrackShoeDoublePin::Initialize(std::shared_ptr<ChBodyAuxRef> chassis, const ChVector<>& loc_shoe, const ChQuaternion<>& rot_shoe, const ChVector<>& loc_connector_L, const ChVector<>& loc_connector_R, const ChQuaternion<>& rot_connector) { // Initialize at origin. Initialize(chassis, VNULL, QUNIT); // Overwrite absolute body locations and orientations. m_shoe->SetPos(chassis->TransformPointLocalToParent(loc_shoe)); m_shoe->SetRot(chassis->GetRot() * rot_shoe); switch (m_topology) { case DoublePinTrackShoeType::TWO_CONNECTORS: m_connector_L->SetPos(chassis->TransformPointLocalToParent(loc_connector_L)); m_connector_L->SetRot(chassis->GetRot() * rot_connector); m_connector_R->SetPos(chassis->TransformPointLocalToParent(loc_connector_R)); m_connector_R->SetRot(chassis->GetRot() * rot_connector); break; case DoublePinTrackShoeType::ONE_CONNECTOR: m_connector_L->SetPos(chassis->TransformPointLocalToParent(0.5 * (loc_connector_L + loc_connector_R))); m_connector_L->SetRot(chassis->GetRot() * rot_connector); break; } } void ChTrackShoeDoublePin::InitializeInertiaProperties() { m_mass = GetShoeMass() + 2 * GetConnectorMass(); } void ChTrackShoeDoublePin::UpdateInertiaProperties() { m_xform = m_shoe->GetFrame_REF_to_abs(); // Calculate COM and inertia expressed in global frame utils::CompositeInertia composite; composite.AddComponent(m_shoe->GetFrame_COG_to_abs(), m_shoe->GetMass(), m_shoe->GetInertia()); switch (m_topology) { case DoublePinTrackShoeType::TWO_CONNECTORS: composite.AddComponent(m_connector_L->GetFrame_COG_to_abs(), m_connector_L->GetMass(), m_connector_L->GetInertia()); composite.AddComponent(m_connector_R->GetFrame_COG_to_abs(), m_connector_R->GetMass(), m_connector_R->GetInertia()); break; case DoublePinTrackShoeType::ONE_CONNECTOR: composite.AddComponent(m_connector_L->GetFrame_COG_to_abs(), m_connector_L->GetMass(), m_connector_L->GetInertia()); break; } // Express COM and inertia in subsystem reference frame m_com.coord.pos = m_xform.TransformPointParentToLocal(composite.GetCOM()); m_com.coord.rot = QUNIT; m_inertia = m_xform.GetA().transpose() * composite.GetInertia() * m_xform.GetA(); } double ChTrackShoeDoublePin::GetPitch() const { return GetShoeLength() + GetConnectorLength(); } // ----------------------------------------------------------------------------- void ChTrackShoeDoublePin::AddVisualizationAssets(VisualizationType vis) { ChTrackShoeSegmented::AddVisualizationAssets(vis); switch (m_topology) { case DoublePinTrackShoeType::TWO_CONNECTORS: AddConnectorVisualization2(m_connector_L, vis); AddConnectorVisualization2(m_connector_R, vis); break; case DoublePinTrackShoeType::ONE_CONNECTOR: AddConnectorVisualization1(m_connector_L, vis); break; } } void ChTrackShoeDoublePin::RemoveVisualizationAssets() { switch (m_topology) { case DoublePinTrackShoeType::TWO_CONNECTORS: ChPart::RemoveVisualizationAssets(m_connector_L); ChPart::RemoveVisualizationAssets(m_connector_R); break; case DoublePinTrackShoeType::ONE_CONNECTOR: ChPart::RemoveVisualizationAssets(m_connector_L); break; } ChTrackShoeSegmented::RemoveVisualizationAssets(); } void ChTrackShoeDoublePin::AddConnectorVisualization2(std::shared_ptr<ChBody> connector, VisualizationType vis) { assert(m_topology == DoublePinTrackShoeType::TWO_CONNECTORS); if (vis == VisualizationType::NONE) return; double c_length = GetConnectorLength(); double c_width = GetConnectorWidth(); double c_radius = GetConnectorRadius(); auto cyl_rear = chrono_types::make_shared<ChCylinderShape>(); cyl_rear->GetCylinderGeometry().p1 = ChVector<>(-0.5 * c_length, -0.5 * c_width, 0); cyl_rear->GetCylinderGeometry().p2 = ChVector<>(-0.5 * c_length, +0.5 * c_width, 0); cyl_rear->GetCylinderGeometry().rad = c_radius; connector->AddVisualShape(cyl_rear); auto cyl_front = chrono_types::make_shared<ChCylinderShape>(); cyl_front->GetCylinderGeometry().p1 = ChVector<>(0.5 * c_length, -0.5 * c_width, 0); cyl_front->GetCylinderGeometry().p2 = ChVector<>(0.5 * c_length, +0.5 * c_width, 0); cyl_front->GetCylinderGeometry().rad = c_radius; connector->AddVisualShape(cyl_front); auto box = chrono_types::make_shared<ChBoxShape>(); box->GetBoxGeometry().SetLengths(ChVector<>(c_length, c_width, 2 * c_radius)); connector->AddVisualShape(box, ChFrame<>()); } void ChTrackShoeDoublePin::AddConnectorVisualization1(std::shared_ptr<ChBody> connector, VisualizationType vis) { assert(m_topology == DoublePinTrackShoeType::ONE_CONNECTOR); if (vis == VisualizationType::NONE) return; auto mat = chrono_types::make_shared<ChVisualMaterial>(); mat->SetDiffuseColor(ChColor(1.0f, 0.68f, 0.2f)); double offset = 0.5 * GetShoeWidth(); double c_length = GetConnectorLength(); double c_width = GetConnectorWidth(); double c_radius = GetConnectorRadius(); { auto cyl_rear = chrono_types::make_shared<ChCylinderShape>(); cyl_rear->GetCylinderGeometry().p1 = ChVector<>(-0.5 * c_length, +offset - 0.5 * c_width, 0); cyl_rear->GetCylinderGeometry().p2 = ChVector<>(-0.5 * c_length, +offset + 0.5 * c_width, 0); cyl_rear->GetCylinderGeometry().rad = c_radius; cyl_rear->AddMaterial(mat); connector->AddVisualShape(cyl_rear); auto cyl_front = chrono_types::make_shared<ChCylinderShape>(); cyl_front->GetCylinderGeometry().p1 = ChVector<>(0.5 * c_length, +offset - 0.5 * c_width, 0); cyl_front->GetCylinderGeometry().p2 = ChVector<>(0.5 * c_length, +offset + 0.5 * c_width, 0); cyl_front->GetCylinderGeometry().rad = c_radius; cyl_front->AddMaterial(mat); connector->AddVisualShape(cyl_front); auto box = chrono_types::make_shared<ChBoxShape>(); box->GetBoxGeometry().SetLengths(ChVector<>(c_length, c_width, 2 * c_radius)); box->AddMaterial(mat); connector->AddVisualShape(box, ChFrame<>(ChVector<>(0, +offset, 0))); } { auto cyl_rear = chrono_types::make_shared<ChCylinderShape>(); cyl_rear->GetCylinderGeometry().p1 = ChVector<>(-0.5 * c_length, -offset - 0.5 * c_width, 0); cyl_rear->GetCylinderGeometry().p2 = ChVector<>(-0.5 * c_length, -offset + 0.5 * c_width, 0); cyl_rear->GetCylinderGeometry().rad = c_radius; cyl_rear->AddMaterial(mat); connector->AddVisualShape(cyl_rear); auto cyl_front = chrono_types::make_shared<ChCylinderShape>(); cyl_front->GetCylinderGeometry().p1 = ChVector<>(0.5 * c_length, -offset - 0.5 * c_width, 0); cyl_front->GetCylinderGeometry().p2 = ChVector<>(0.5 * c_length, -offset + 0.5 * c_width, 0); cyl_front->GetCylinderGeometry().rad = c_radius; cyl_front->AddMaterial(mat); connector->AddVisualShape(cyl_front); auto box = chrono_types::make_shared<ChBoxShape>(); box->GetBoxGeometry().SetLengths(ChVector<>(c_length, c_width, 2 * c_radius)); box->AddMaterial(mat); connector->AddVisualShape(box, ChFrame<>(ChVector<>(0, -offset, 0))); } } // ----------------------------------------------------------------------------- void ChTrackShoeDoublePin::EnableTrackBendingStiffness(bool val) { switch (m_topology) { case DoublePinTrackShoeType::TWO_CONNECTORS: m_rsda_L->SetDisabled(val); m_rsda_R->SetDisabled(val); m_connection_rsda_L->SetDisabled(val); m_connection_rsda_R->SetDisabled(val); break; case DoublePinTrackShoeType::ONE_CONNECTOR: m_rsda_L->SetDisabled(val); m_connection_rsda_L->SetDisabled(val); break; } } void ChTrackShoeDoublePin::Connect(std::shared_ptr<ChTrackShoe> next, ChTrackAssembly* assembly, ChChassis* chassis, bool ccw) { switch (m_topology) { case DoublePinTrackShoeType::TWO_CONNECTORS: Connect2(next, assembly, chassis, ccw); break; case DoublePinTrackShoeType::ONE_CONNECTOR: Connect1(next, assembly, chassis, ccw); break; } } void ChTrackShoeDoublePin::Connect2(std::shared_ptr<ChTrackShoe> next, ChTrackAssembly* assembly, ChChassis* chassis, bool ccw) { assert(m_topology == DoublePinTrackShoeType::TWO_CONNECTORS); auto track = static_cast<ChTrackAssemblyDoublePin*>(assembly); assert(track->GetBushingData()); ChSystem* system = m_shoe->GetSystem(); double sign = ccw ? +1 : -1; ChVector<> pShoe_L; // local point on shoe (left) ChVector<> pShoe_R; // local point on shoe (right) ChVector<> pConnector; // local point on connector ChVector<> loc_L; // left point (expressed in absolute frame) ChVector<> loc_R; // right point (expressed in absolute frame) ChQuaternion<> rot; // orientation (expressed in absolute frame) // 1. Connections between this shoe body and connector bodies // Create and initialize the revolute joints/bushings between shoe body and connector bodies. pShoe_L = ChVector<>(sign * GetShoeLength() / 2, +GetShoeWidth() / 2, 0); pShoe_R = ChVector<>(sign * GetShoeLength() / 2, -GetShoeWidth() / 2, 0); pConnector = ChVector<>(-sign * GetConnectorLength() / 2, 0, 0); loc_L = m_shoe->TransformPointLocalToParent(pShoe_L); loc_R = m_shoe->TransformPointLocalToParent(pShoe_R); rot = m_shoe->GetRot() * Q_from_AngX(CH_C_PI_2); m_joint_L = chrono_types::make_shared<ChVehicleJoint>(ChVehicleJoint::Type::REVOLUTE, m_name + "_pin_L", m_connector_L, m_shoe, ChCoordsys<>(loc_L, rot), track->GetBushingData()); chassis->AddJoint(m_joint_L); m_joint_R = chrono_types::make_shared<ChVehicleJoint>(ChVehicleJoint::Type::REVOLUTE, m_name + "_pin_R", m_connector_R, m_shoe, ChCoordsys<>(loc_R, rot), track->GetBushingData()); chassis->AddJoint(m_joint_R); // Optionally, include rotational spring-dampers to model track bending stiffness. // The RSDA frames are aligned with the corresponding body frames and the springs have a default zero rest angle. if (track->GetTorqueFunctor()) { ChQuaternion<> z2y = Q_from_AngX(-CH_C_PI_2); m_rsda_L = chrono_types::make_shared<ChLinkRSDA>(); m_rsda_L->SetNameString(m_name + "_rsda_pin_L"); m_rsda_L->Initialize(m_shoe, m_connector_L, true, ChCoordsys<>(pShoe_L, z2y), ChCoordsys<>(pConnector, z2y)); m_rsda_L->RegisterTorqueFunctor(track->GetTorqueFunctor()); system->AddLink(m_rsda_L); m_rsda_R = chrono_types::make_shared<ChLinkRSDA>(); m_rsda_R->SetNameString(m_name + "_rsda_pin_R"); m_rsda_R->Initialize(m_shoe, m_connector_R, true, ChCoordsys<>(pShoe_R, z2y), ChCoordsys<>(pConnector, z2y)); m_rsda_R->RegisterTorqueFunctor(track->GetTorqueFunctor()); system->AddLink(m_rsda_R); } // 2. Connections between connector bodies and next shoe body pShoe_L = ChVector<>(-sign * GetShoeLength() / 2, +GetShoeWidth() / 2, 0); pShoe_R = ChVector<>(-sign * GetShoeLength() / 2, -GetShoeWidth() / 2, 0); pConnector = ChVector<>(sign * GetConnectorLength() / 2, 0, 0); loc_L = m_connector_L->TransformPointLocalToParent(pConnector); loc_R = m_connector_R->TransformPointLocalToParent(pConnector); // Create and initialize revolute bushings between connector bodies and next shoe body. rot = m_connector_L->GetRot() * Q_from_AngX(CH_C_PI_2); m_connection_joint_L = chrono_types::make_shared<ChVehicleJoint>(ChVehicleJoint::Type::REVOLUTE, m_name + "_cpin_L", next->GetShoeBody(), m_connector_L, ChCoordsys<>(loc_L, rot), track->GetBushingData()); chassis->AddJoint(m_connection_joint_L); rot = m_connector_R->GetRot() * Q_from_AngX(CH_C_PI_2); m_connection_joint_R = chrono_types::make_shared<ChVehicleJoint>(ChVehicleJoint::Type::REVOLUTE, m_name + "_cpin_R", next->GetShoeBody(), m_connector_R, ChCoordsys<>(loc_R, rot), track->GetBushingData()); chassis->AddJoint(m_connection_joint_R); // Optionally, include rotational spring-dampers to model track bending stiffness // The RSDA frames are aligned with the corresponding body frames and the springs have a default zero rest angle. if (track->GetTorqueFunctor()) { ChQuaternion<> z2y = Q_from_AngX(-CH_C_PI_2); m_connection_rsda_L = chrono_types::make_shared<ChLinkRSDA>(); m_connection_rsda_L->SetNameString(m_name + "_rsda_cpin_L"); m_connection_rsda_L->Initialize(m_connector_L, next->GetShoeBody(), true, ChCoordsys<>(pConnector, z2y), ChCoordsys<>(pShoe_L, z2y)); m_connection_rsda_L->RegisterTorqueFunctor(track->GetTorqueFunctor()); system->AddLink(m_connection_rsda_L); m_connection_rsda_R = chrono_types::make_shared<ChLinkRSDA>(); m_connection_rsda_R->SetNameString(m_name + "_rsda_cpin_R"); m_connection_rsda_R->Initialize(m_connector_R, next->GetShoeBody(), true, ChCoordsys<>(pConnector, z2y), ChCoordsys<>(pShoe_R, z2y)); m_connection_rsda_R->RegisterTorqueFunctor(track->GetTorqueFunctor()); system->AddLink(m_connection_rsda_R); } } void ChTrackShoeDoublePin::Connect1(std::shared_ptr<ChTrackShoe> next, ChTrackAssembly* assembly, ChChassis* chassis, bool ccw) { assert(m_topology == DoublePinTrackShoeType::ONE_CONNECTOR); auto track = static_cast<ChTrackAssemblyDoublePin*>(assembly); ChSystem* system = m_shoe->GetSystem(); double sign = ccw ? +1 : -1; ChVector<> pShoe; // local point on shoe ChVector<> pConnector; // local point on connector ChVector<> loc; // point (expressed in absolute frame) ChQuaternion<> rot; // orientation (expressed in absolute frame) // 1. Connections between this shoe body and connector body // Create and initialize the joint/bushing between shoe body and connector body. pShoe = ChVector<>(sign * GetShoeLength() / 2, 0, 0); pConnector = ChVector<>(-sign * GetConnectorLength() / 2, 0, 0); loc = m_shoe->TransformPointLocalToParent(pShoe); if (track->GetBushingData() || m_index != 0) { rot = m_shoe->GetRot() * Q_from_AngX(CH_C_PI_2); m_joint_L = chrono_types::make_shared<ChVehicleJoint>(ChVehicleJoint::Type::REVOLUTE, m_name + "_pin", m_connector_L, m_shoe, ChCoordsys<>(loc, rot), track->GetBushingData()); chassis->AddJoint(m_joint_L); } else { m_joint_L = chrono_types::make_shared<ChVehicleJoint>(ChVehicleJoint::Type::SPHERICAL, m_name + "_sph", m_connector_L, m_shoe, ChCoordsys<>(loc, QUNIT)); chassis->AddJoint(m_joint_L); } // Optionally, include rotational spring-damper to model track bending stiffness. // The RSDA frame is aligned with the corresponding body frame and the spring has a default zero rest angle. if (track->GetTorqueFunctor()) { ChQuaternion<> z2y = Q_from_AngX(-CH_C_PI_2); m_rsda_L = chrono_types::make_shared<ChLinkRSDA>(); m_rsda_L->SetNameString(m_name + "_rsda_pin"); m_rsda_L->Initialize(m_shoe, m_connector_L, true, ChCoordsys<>(pShoe, z2y), ChCoordsys<>(pConnector, z2y)); m_rsda_L->RegisterTorqueFunctor(track->GetTorqueFunctor()); system->AddLink(m_rsda_L); } // 2. Connection between connector body and next shoe body pShoe = ChVector<>(-sign * GetShoeLength() / 2, 0, 0); pConnector = ChVector<>(sign * GetConnectorLength() / 2, 0, 0); loc = m_connector_L->TransformPointLocalToParent(pConnector); if (track->GetBushingData() || m_index != 0) { rot = m_connector_L->GetRot() * Q_from_AngX(CH_C_PI_2); m_connection_joint_L = chrono_types::make_shared<ChVehicleJoint>( ChVehicleJoint::Type::REVOLUTE, m_name + "_cpin", next->GetShoeBody(), m_connector_L, ChCoordsys<>(loc, rot), track->GetBushingData()); chassis->AddJoint(m_connection_joint_L); } else { rot = m_connector_L->GetRot() * Q_from_AngY(-CH_C_PI_2); m_connection_joint_L = chrono_types::make_shared<ChVehicleJoint>(ChVehicleJoint::Type::UNIVERSAL, m_name + "_cuniv", next->GetShoeBody(), m_connector_L, ChCoordsys<>(loc, rot)); chassis->AddJoint(m_connection_joint_L); } // Optionally, include rotational spring-dampers to model track bending stiffness // The RSDA frame is aligned with the corresponding body frame and the spring has a default zero rest angle. if (track->GetTorqueFunctor()) { ChQuaternion<> z2y = Q_from_AngX(-CH_C_PI_2); m_connection_rsda_L = chrono_types::make_shared<ChLinkRSDA>(); m_connection_rsda_L->SetNameString(m_name + "_rsda_cpin_L"); m_connection_rsda_L->Initialize(m_connector_L, next->GetShoeBody(), true, ChCoordsys<>(pConnector, z2y), ChCoordsys<>(pShoe, z2y)); m_connection_rsda_L->RegisterTorqueFunctor(track->GetTorqueFunctor()); system->AddLink(m_connection_rsda_L); } } ChVector<> ChTrackShoeDoublePin::GetTension() const { switch (m_topology) { case DoublePinTrackShoeType::TWO_CONNECTORS: return m_joint_L->GetForce() + m_joint_R->GetForce(); case DoublePinTrackShoeType::ONE_CONNECTOR: return m_joint_L->GetForce(); } return ChVector<>(0); } // ----------------------------------------------------------------------------- void ChTrackShoeDoublePin::ExportComponentList(rapidjson::Document& jsonDocument) const { ChPart::ExportComponentList(jsonDocument); std::vector<std::shared_ptr<ChBody>> bodies; std::vector<std::shared_ptr<ChLink>> joints; std::vector<std::shared_ptr<ChLoadBodyBody>> bushings; bodies.push_back(m_shoe); switch (m_topology) { case DoublePinTrackShoeType::TWO_CONNECTORS: bodies.push_back(m_connector_L); bodies.push_back(m_connector_R); m_joint_L->IsKinematic() ? joints.push_back(m_joint_L->GetAsLink()) : bushings.push_back(m_joint_L->GetAsBushing()); m_joint_R->IsKinematic() ? joints.push_back(m_joint_R->GetAsLink()) : bushings.push_back(m_joint_R->GetAsBushing()); m_connection_joint_L->IsKinematic() ? joints.push_back(m_connection_joint_L->GetAsLink()) : bushings.push_back(m_connection_joint_L->GetAsBushing()); m_connection_joint_R->IsKinematic() ? joints.push_back(m_connection_joint_R->GetAsLink()) : bushings.push_back(m_connection_joint_R->GetAsBushing()); break; case DoublePinTrackShoeType::ONE_CONNECTOR: bodies.push_back(m_connector_L); m_joint_L->IsKinematic() ? joints.push_back(m_joint_L->GetAsLink()) : bushings.push_back(m_joint_L->GetAsBushing()); m_connection_joint_L->IsKinematic() ? joints.push_back(m_connection_joint_L->GetAsLink()) : bushings.push_back(m_connection_joint_L->GetAsBushing()); break; } ChPart::ExportBodyList(jsonDocument, bodies); ChPart::ExportJointList(jsonDocument, joints); ChPart::ExportBodyLoadList(jsonDocument, bushings); } void ChTrackShoeDoublePin::Output(ChVehicleOutput& database) const { if (!m_output) return; std::vector<std::shared_ptr<ChBody>> bodies; std::vector<std::shared_ptr<ChLink>> joints; std::vector<std::shared_ptr<ChLoadBodyBody>> bushings; bodies.push_back(m_shoe); switch (m_topology) { case DoublePinTrackShoeType::TWO_CONNECTORS: bodies.push_back(m_connector_L); bodies.push_back(m_connector_R); m_joint_L->IsKinematic() ? joints.push_back(m_joint_L->GetAsLink()) : bushings.push_back(m_joint_L->GetAsBushing()); m_joint_R->IsKinematic() ? joints.push_back(m_joint_R->GetAsLink()) : bushings.push_back(m_joint_R->GetAsBushing()); m_connection_joint_L->IsKinematic() ? joints.push_back(m_connection_joint_L->GetAsLink()) : bushings.push_back(m_connection_joint_L->GetAsBushing()); m_connection_joint_R->IsKinematic() ? joints.push_back(m_connection_joint_R->GetAsLink()) : bushings.push_back(m_connection_joint_R->GetAsBushing()); break; case DoublePinTrackShoeType::ONE_CONNECTOR: bodies.push_back(m_connector_L); m_joint_L->IsKinematic() ? joints.push_back(m_joint_L->GetAsLink()) : bushings.push_back(m_joint_L->GetAsBushing()); m_connection_joint_L->IsKinematic() ? joints.push_back(m_connection_joint_L->GetAsLink()) : bushings.push_back(m_connection_joint_L->GetAsBushing()); break; } database.WriteBodies(bodies); database.WriteJoints(joints); database.WriteBodyLoads(bushings); } } // end namespace vehicle } // end namespace chrono
{ "content_hash": "8949dae1cdf395767c1ff81a06f2300a", "timestamp": "", "source": "github", "line_count": 594, "max_line_length": 120, "avg_line_length": 46.6986531986532, "alnum_prop": 0.5959479433288871, "repo_name": "projectchrono/chrono", "id": "fc3d465c629bb66153a5f7cf34d1e6f46be3a58c", "size": "28827", "binary": false, "copies": "1", "ref": "refs/heads/main", "path": "src/chrono_vehicle/tracked_vehicle/track_shoe/ChTrackShoeDoublePin.cpp", "mode": "33188", "license": "bsd-3-clause", "language": [ { "name": "Batchfile", "bytes": "7614" }, { "name": "C", "bytes": "2409870" }, { "name": "C++", "bytes": "26511084" }, { "name": "CMake", "bytes": "645492" }, { "name": "CSS", "bytes": "170326" }, { "name": "Cuda", "bytes": "1226094" }, { "name": "Dockerfile", "bytes": "3279" }, { "name": "GLSL", "bytes": "4925" }, { "name": "HTML", "bytes": "7922" }, { "name": "Inno Setup", "bytes": "24125" }, { "name": "JavaScript", "bytes": "4731" }, { "name": "Lex", "bytes": "3433" }, { "name": "Lua", "bytes": "651" }, { "name": "POV-Ray SDL", "bytes": "25421" }, { "name": "PowerShell", "bytes": "142" }, { "name": "Python", "bytes": "645743" }, { "name": "SWIG", "bytes": "317316" }, { "name": "Shell", "bytes": "4827" } ], "symlink_target": "" }
layout: default title: "Consumer Credit And Debt" --- {% include interests/consumer-credit-and-debt.md %} ### Who is interested in Consumer Credit And Debt? * [Yvonne Fovargue]({{ site.baseurl }}/members/yvonne-fovargue.html)
{ "content_hash": "30b5e4971aeecf99f94fdf47e89aaafa", "timestamp": "", "source": "github", "line_count": 11, "max_line_length": 68, "avg_line_length": 21, "alnum_prop": 0.7186147186147186, "repo_name": "JeniT/childs-guide-to-parliament", "id": "0da736f9f2a55bc00419eee819bf8c32cdc968fc", "size": "351", "binary": false, "copies": "1", "ref": "refs/heads/gh-pages", "path": "interests/consumer-credit-and-debt.md", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "210544" }, { "name": "JavaScript", "bytes": "6242" }, { "name": "Python", "bytes": "11600" }, { "name": "Ruby", "bytes": "48" } ], "symlink_target": "" }
var util = require('util'); var TEMPLATE = '' + 'window.__html__ = window.__html__ || {};\n' + 'window.__html__[\'%s\'] = \'%s\''; var escapeContent = function(content) { return content.replace(/'/g, '\\\'').replace(/\r?\n/g, ''); }; var createHtml2JsPreprocessor = function(logger, basePath) { var log = logger.create('preprocessor.html2js'); return function(content, file, done) { log.debug('Processing "%s".', file.originalPath); var htmlPath = file.originalPath.replace(basePath + '/', ''); file.path = file.path + '.js'; done(util.format(TEMPLATE, htmlPath, escapeContent(content))); }; }; createHtml2JsPreprocessor.$inject = ['logger', 'config.basePath']; module.exports = createHtml2JsPreprocessor;
{ "content_hash": "088ce8b107ae93a4646a3fdc08bd211f", "timestamp": "", "source": "github", "line_count": 27, "max_line_length": 66, "avg_line_length": 27.51851851851852, "alnum_prop": 0.6379542395693136, "repo_name": "Agilefreaks/karma-html2js-preprocessor", "id": "32533517b9103a9183fc7fb4b5b8f95b3ded022f", "size": "743", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "lib/html2js.js", "mode": "33188", "license": "mit", "language": [ { "name": "CoffeeScript", "bytes": "2356" }, { "name": "HTML", "bytes": "5266730" }, { "name": "JavaScript", "bytes": "2835" } ], "symlink_target": "" }
using System; using System.Collections.Generic; using System.Web; using ServiceStack.Common; using ServiceStack; using GatecoinServiceInterface.Response; namespace GatecoinServiceInterface.Request{ [Route("/Bank/Accounts/{Currency}/{Location}", "GET", Summary = @"Get internal bank account for deposit", Notes = @"")] public class GetInternalBankAccount : IReturn<InternalBankAccountResponse> { [ApiMember(Name = "Currency", Description = "Currency of bank account", ParameterType = "path", DataType = "string", IsRequired = false)] public System.String Currency {get; set; } [ApiMember(Name = "Location", Description = "Location of bank account", ParameterType = "path", DataType = "string", IsRequired = false)] public System.String Location {get; set; } } }
{ "content_hash": "4e7b98276290beca1a680b0082b147fa", "timestamp": "", "source": "github", "line_count": 18, "max_line_length": 137, "avg_line_length": 42.5, "alnum_prop": 0.7581699346405228, "repo_name": "Gatecoin/api-gatecoin-dotnet", "id": "d5b038dcf0b47e927c31a6ecf12a5762badf0011", "size": "765", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "Request/GetInternalBankAccount.cs", "mode": "33188", "license": "mit", "language": [ { "name": "C#", "bytes": "247535" }, { "name": "Shell", "bytes": "3060" } ], "symlink_target": "" }
package org.kie.dmn.feel.runtime.functions; import java.time.ZonedDateTime; import java.time.temporal.TemporalAccessor; import org.kie.dmn.api.feel.runtime.events.FEELEvent; import org.kie.dmn.feel.runtime.functions.FEELFnResult; public class NowFunction extends BaseFEELFunction { public NowFunction() { super( "now" ); } public FEELFnResult<TemporalAccessor> invoke() { return FEELFnResult.ofResult( ZonedDateTime.now() ); } }
{ "content_hash": "14756bd206b7ef18c120eb0dd7b29cea", "timestamp": "", "source": "github", "line_count": 22, "max_line_length": 60, "avg_line_length": 21.681818181818183, "alnum_prop": 0.7211740041928721, "repo_name": "sutaakar/drools", "id": "33bdeeb578ae539df10de098318c3d806c070087", "size": "1098", "binary": false, "copies": "3", "ref": "refs/heads/master", "path": "kie-dmn/kie-dmn-feel/src/main/java/org/kie/dmn/feel/runtime/functions/NowFunction.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "ANTLR", "bytes": "14216" }, { "name": "Batchfile", "bytes": "2554" }, { "name": "CSS", "bytes": "1412" }, { "name": "GAP", "bytes": "197080" }, { "name": "HTML", "bytes": "9298" }, { "name": "Java", "bytes": "28490800" }, { "name": "Protocol Buffer", "bytes": "13855" }, { "name": "Python", "bytes": "4555" }, { "name": "Ruby", "bytes": "491" }, { "name": "Shell", "bytes": "1120" }, { "name": "Standard ML", "bytes": "82260" }, { "name": "XSLT", "bytes": "24302" } ], "symlink_target": "" }