text
stringlengths
2
1.04M
meta
dict
package com.github.davidcarboni.dylan.filesystem; import com.github.davidcarboni.cryptolite.Crypto; import com.github.davidcarboni.cryptolite.Keys; import com.github.davidcarboni.cryptolite.Random; import org.junit.After; import org.junit.Before; import org.junit.Test; import javax.crypto.SecretKey; import java.io.IOException; import java.nio.ByteBuffer; import java.nio.channels.SeekableByteChannel; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.StandardOpenOption; import static java.nio.file.StandardOpenOption.READ; import static java.nio.file.StandardOpenOption.WRITE; import static org.junit.Assert.*; /** * Test for {@link CipherChannel}. */ public class CipherChannelTest { SecretKey key; Path path; SeekableByteChannel seekableByteChannel; @Before public void setUp() throws Exception { // Key key = Keys.newSecretKey(); // New file path = Files.createTempFile(CipherChannelTest.class.getSimpleName(), ".test"); // Open a channel that can be read or written seekableByteChannel = Files.newByteChannel(path, READ, WRITE); } @After public void tearDown() throws Exception { seekableByteChannel.close(); Files.delete(path); } private void createContent(int size) throws IOException { try (CipherChannel cipherChannel = CipherChannel.wrap(Files.newByteChannel(path, WRITE), key)) { byte[] content = Random.bytes(size); ByteBuffer buffer = ByteBuffer.wrap(content); int count = 0; do { cipherChannel.write(buffer); } while (buffer.remaining() > 0); } } @Test(expected = IllegalStateException.class) public void shouldSetEncryptMode() throws IOException { // Given // A Cipher Channel CipherChannel cipherChannel = CipherChannel.wrap(seekableByteChannel, key); // When // We write to the channel cipherChannel.write(ByteBuffer.allocate(1)); // Then // It should not be possible to read from the channel cipherChannel.read(ByteBuffer.allocate(1)); } @Test(expected = IllegalStateException.class) public void shouldSetDecryptMode() throws IOException { // Given // A Cipher Channel CipherChannel cipherChannel = CipherChannel.wrap(seekableByteChannel, key); createContent(1); // When // We write to the channel cipherChannel.read(ByteBuffer.allocate(1)); // Then // It should not be possible to read from the channel cipherChannel.write(ByteBuffer.allocate(1)); } @Test public void shouldDiscountIvWhenCalculatingSize() throws IOException { for (int i = 0; i < 100; i++) { // Given // A Cipher Channel with no content createContent(i); CipherChannel cipherChannel = CipherChannel.wrap(Files.newByteChannel(path), key); // When // We ask for the size long size = cipherChannel.size(); // Then // The channel size should exclude the iv assertEquals(i, size); // To confirm, the size of the file should be the CipherChannel size, plus the iv size: assertEquals(i + new Crypto().getIvSize(), Files.size(path)); } } @Test public void shouldBeOpen() throws IOException { // Given // Uninitialised, read and write channels createContent(10); CipherChannel uninitialised = CipherChannel.wrap(Files.newByteChannel(path), key); CipherChannel write = CipherChannel.wrap(Files.newByteChannel(path, StandardOpenOption.WRITE), key); CipherChannel read = CipherChannel.wrap(Files.newByteChannel(path), key); write.write(ByteBuffer.allocate(1)); read.read(ByteBuffer.allocate(1)); // When // We ask if they are open boolean uninitialisedOpen = uninitialised.isOpen(); boolean writeOpen = write.isOpen(); boolean readOpen = read.isOpen(); // Then // They should all be open assertTrue(uninitialisedOpen); assertTrue(writeOpen); assertTrue(readOpen); } @Test public void shouldClose() throws IOException { // Given // Uninitialised, read and write channels createContent(10); CipherChannel uninitialised = CipherChannel.wrap(Files.newByteChannel(path), key); CipherChannel write = CipherChannel.wrap(Files.newByteChannel(path, StandardOpenOption.WRITE), key); CipherChannel read = CipherChannel.wrap(Files.newByteChannel(path), key); write.write(ByteBuffer.allocate(1)); read.read(ByteBuffer.allocate(1)); // When // We ask if they are open uninitialised.close(); write.close(); read.close(); // Then // They should all be open assertFalse(uninitialised.isOpen()); assertFalse(write.isOpen()); assertFalse(read.isOpen()); } @Test (expected = UnsupportedOperationException.class) public void shouldNotSeek() throws IOException { // Given // Uninitialised, read and write channels createContent(10); CipherChannel uninitialised = CipherChannel.wrap(Files.newByteChannel(path), key); CipherChannel write = CipherChannel.wrap(Files.newByteChannel(path, StandardOpenOption.WRITE), key); CipherChannel read = CipherChannel.wrap(Files.newByteChannel(path), key); write.write(ByteBuffer.allocate(1)); read.read(ByteBuffer.allocate(1)); // When // We try to set the position uninitialised.position(1); write.position(1); read.position(1); // Then // We should get an exception } }
{ "content_hash": "735e47adb72ed1b11a1d577e75b6ed99", "timestamp": "", "source": "github", "line_count": 193, "max_line_length": 108, "avg_line_length": 30.683937823834196, "alnum_prop": 0.6430260047281324, "repo_name": "ONSdigital/Dylan", "id": "5f4de880c33415a0604101a5e22cc6c240b1798b", "size": "5922", "binary": false, "copies": "1", "ref": "refs/heads/develop", "path": "src/test/java/com/github/davidcarboni/dylan/filesystem/CipherChannelTest.java", "mode": "33188", "license": "mit", "language": [ { "name": "Java", "bytes": "80856" }, { "name": "Shell", "bytes": "2916" } ], "symlink_target": "" }
<?xml version="1.0" encoding="UTF-8"?> <!-- Norwegian bokmål FBReaderJ resources, by Haakon Meland Eriksen --> <resources> <node name="library" value="FBReader bibliotek"> <node name="unknownAuthor" value="Ukjent forfatter"/> <node name="booksWithNoTags" value="Bøker uten merkelapper"/> <node name="demo" value="smakebit"/> <node name="byAuthor" value="Etter forfatter"> <node name="summary" value="Bøker sortert etter forfatter"/> </node> <node name="byTitle" value="Etter tittel"> <node name="summary" value="Bøker sortert etter tittel"/> </node> <node name="bySeries" value="Etter serie"> <node name="summary" value="Bøker sortert etter serie"/> </node> <node name="byTag" value="Etter merkelapp"> <node name="summary" value="Bøker sortert etter merkelapp"/> </node> <node name="recent" value="Nylig"> <node name="summary" value="Nylig åpnede bøker"/> </node> <node name="favorites" value="Favoritter"> <node name="summary" value="Mine utvalgte bøker"/> </node> <node name="found" value="Funnet"> <node name="summary" value="Søkeresultat for: %s"/> </node> <node name="fileTree" value="Filtre"> <node name="summary" value="Utforsk filsystemet"/> </node> <node name="fileTreeRoot" value="Enhet"> <node name="summary" value="Hele filsystemet til enheten"/> </node> <node name="fileTreeCard" value="Minnekort"> <node name="summary" value="Minnekort i enheten"/> </node> <node name="fileTreeLibrary" value="FBReader bibliotek"> <node name="summary" value="FBReader bokkatalog"/> </node> <node name="menu"> <node name="localSearch" value="Søk"/> <node name="rescan" value="Rescan" toBeTranslated="true"/> </node> <node name="openBook" value="Åpne book"/> <node name="showBookInfo" value="Bokinformasjon"/> <node name="shareBook" value="Del bok"/> <node name="deleteBook" value="Slett bok"/> <node name="addToFavorites" value="Legg til i favoritter"/> <node name="removeFromFavorites" value="Fjern fra favoritter"/> <node name="markAsRead" value="Mark as read" toBeTranslated="true"/> <node name="markAsUnread" value="Mark as unread" toBeTranslated="true"/> </node> <node name="networkLibrary" value="FBReader nettverksbibliotek"> <node name="byAuthor" value="Etter forfatter"> <node name="summary" value="Bøker sortert på forfatter"/> </node> <node name="byTitle" value="Etter tittel"> <node name="summary" value="Bøker sortert på tittel"/> </node> <node name="byDate" value="Etter dato"> <node name="summary" value="Bøker sortert etter anskaffelsesdato"/> </node> <node name="bySeries" value="Etter serie"> <node name="summary" value="Bøker sortert etter serie"/> </node> <node name="search" value="Søk"> <node name="summary" value="Søk etter bøker hos %s"/> <node name="summaryAllCatalogs" value="Søk etter bøker i alle kataloger"/> <node name="summaryInProgress" value="Søk pågår"/> </node> <node name="found" value="Funnet"> <node name="summary" value="Søkeresultat for: %s"/> </node> <node name="openCatalog" value="Åpne katalog"/> <node name="networkSearch" value="Søk"/> <node name="showResults" value="Vis resultat"/> <node name="showBooks" value="Vis bøker"/> <node name="download" value="Last ned"/> <node name="read" value="Les lokal kopi"/> <node name="delete" value="Slett lokal kopi"/> <node name="readDemo" value="Les smakebit"/> <node name="deleteDemo" value="Slett smakebit"/> <node name="downloadDemo" value="Last ned smakebit"/> <node name="buy" value="Kjøp (%s)"/> <node name="addToBasket" value="Legg i kurven"/> <node name="removeFromBasket" value="Fjern fra kurven"/> <node name="openBasket" value="Åpne kurv"/> <node name="clearBasket" value="Tøm kurv"/> <node name="buyAllBooks" value="Kjøp alle bøker"/> <node name="openInBrowser" value="Åpne i nettleser"/> <node name="stopLoading" value="Stopp lasting"/> <node name="stopSearching" value="Stopp søking"/> <node name="signIn" value="Logg inn"/> <node name="signOut" value="Logg ut (%s)"/> <node name="topup" value="Topp opp konto (for øyeblikket: %s)"/> <node name="topupTitle" value="Topp opp konto"/> <node name="topupViaBrowser" value="Åpne side i nettleser"/> <node name="authorizationMenuTitle" value="Velg handling"/> <node name="topupSummary" value="For øyeblikket: %s"/> <node name="basket" value="Kurv"/> <node name="basketSummaryEmpty" value="Ingen bøker"/> <node name="basketSummaryCountOnly" value="%0 bøker"> <node condition="value 1" value="%0 bok"/> </node> <node name="basketSummary" value="%0 bøker (%1)"> <node condition="value 1" value="%0 bok (%1)"/> </node> <node name="alreadyDownloading" value="Boken lastes ned"/> <node name="alreadyDownloadingDemo" value="Prøven lastes ned"/> <node name="stoppingCatalogLoading" value="Stopper lasting"/> <node name="stoppingNetworkSearch" value="Stopper søk"/> <node name="editCustomCatalog" value="Endre katalog"/> <node name="removeCustomCatalog" value="Fjern katalog"/> <node name="addCustomCatalog" value="Legg til katalog"/> <node name="addCustomCatalogSummary" value="Legg til egen OPDS-katalog manuelt"/> <node name="confirmQuestions"> <node name="read" value="Ønsker du å lese lokal kopi?"/> <node name="download" value="Ønsker du å laste ned denne boken?"/> <node name="readDemo" value="Ønsker du å lese en smakebit?"/> <node name="downloadDemo" value="Ønsker du å laste ned en smakebit?"/> <node name="buy" value="Ønsker du å kjøpe denne boken? (%s)"/> <node name="openInBrowser" value="Ønsker du å åpne denne katalogen i nettleseren?"/> </node> <node name="downloadingCatalogs" value="Laster ned kataloger"/> <!-- used as notification title --> <node name="searchingNetwork" value="Søker etter bøker i nettverket"/> <!-- used as notification title --> <node name="addCatalog"> <node name="title" value="Legg til katalog"/> <node name="editUrl" value="Skriv URL manuelt"/> </node> <node name="menu"> <node name="networkSearch" value="Søk"/> <node name="reload" value="Last på nytt"/> <node name="signIn" value="Logg inn"/> <node name="signUp" value="Registrer deg"/> <node name="signOut" value="Logg ut (%s)"/> <node name="topup" value="Topp opp konto"/> <node name="addCustomCatalog" value="Legg til katalog"/> <node name="refreshCatalogsList" value="Oppdater katalogene"/> <node name="languages" value="Språkfilter"/> <node name="clearBasket" value="Tøm kurv"/> <node name="buyAllBooks" value="Kjøp alle bøkene"/> </node> </node> <node name="buyBook"> <node name="title" value="Kjøp bok"/> <node name="titleSeveralBooks" value="Kjøp bøker"/> <node name="confirm" value="Er du sikker på at du ønsker å kjøpe &#10;“%s”?"/> <node name="confirmSeveralBooks" value="Er du sikker på at du ønsker å kjøpe %s bøker?"/> <node name="alreadyBought" value="Boken er allerede kjøpt"/> <node name="notAuthorized" value="Tillatelse kreves"/> <node name="noAccountInformation" value="Kan ikke laste kontotilstand"/> <node name="unsufficientFunds" value="Dette kjøpet koster %0 og du har bare %1"/> <node name="zeroFunds" value="Dette kjøpet koster %0"/> </node> <node name="bookInfo"> <node name="bookInfo" value="Bokinformasjon"/> <node name="fileInfo" value="Filinformasjon"/> <node name="description" value="Beskrivelse"/> <node name="noDescription" value="Ingen beskrivelse tilgjengelig."/> <node name="annotation" value="Merknad"/> <node name="title" value="Tittel:"/> <node name="authors" value="Forfattere:"> <node condition="value 1" value="Forfatter:"/> </node> <node name="series" value="Serie:"/> <node name="indexInSeries" value="Nummer i serie:"/> <node name="tags" value="Merkelapper:"> <node condition="value 1" value="Merkelapp:"/> </node> <node name="language" value="Språk:"/> <node name="name" value="Navn:"/> <node name="type" value="Type:"/> <node name="size" value="Størrelse:"/> <node name="time" value="Sist endret:"/> <node name="sizeInBytes" value="%s bytes"> <node condition="value 1" value="%s byte"/> </node> <node name="sizeInKiloBytes" value="%s kB"/> <node name="catalog" value="Katalog:"/> <node name="extraLinks" value="Relaterte lenker"/> <node name="menu"> <node name="edit" value="Endre"/> </node> </node> <node name="bookDownloader"> <node name="tickerSuccess" value="Boken er lastet ned"/> <node name="tickerError" value="Feil ved nedlasting av bok"/> <node name="contentSuccess" value="Nedlasting ferdig"/> <node name="contentError" value="Nedlasting mislyktes"/> <node name="downloadingStarted" value="Nedlasting av bok har begynt"/> <node name="alreadyDownloading" value="Boken lastes allerede ned"/> <node name="cannotCreateDirectory" value="Kan ikke lage katalogen %s"/> <node name="cannotCreateFile" value="Kan ikke lage filen %s"/> </node> <node name="tocView"> <node name="expandTree" value="Utvid tre"/> <node name="collapseTree" value="Trekk sammen tre"/> <node name="readText" value="Les boktekst"/> </node> <node name="bookmarksView"> <node name="thisBook" value="Denne boken"/> <node name="allBooks" value="Alle bøker"/> <node name="found" value="Funnet"/> <node name="new" value="Nytt bokmerke"/> <node name="open" value="Åpne"/> <node name="edit" value="Endre bokmerke"/> <node name="delete" value="Slett bokmerke"/> <node name="menu"> <node name="search" value="Søk"/> </node> </node> <node name="cancelMenu"> <node name="library" value="Åpne bibliotek"/> <node name="networkLibrary" value="Åpne nettverksbibliotek"/> <node name="previousBook" value="Åpne forrige bok"/> <node name="returnTo" value="Gå tilbake til …"/> <node name="back" value="Tilbake"/> <node name="forward" value="Fram"/> <node name="close" value="Lukk FBReader"/> </node> <node name="style" value="Style %s" toBeTranslated="true"/> <node name="highlightingStyleMenu"> <node name="editStyle" value="Edit style…" toBeTranslated="true"/> <node name="deleteBookmark" value="Slett bokmerke"/> </node> <node name="editStyle"> <node name="name" value="Style name" toBeTranslated="true"/> <node name="invisible" value="Invisible" toBeTranslated="true"> <node name="summaryOn" value="Do not highlight bookmarks" toBeTranslated="true"/> <node name="summaryOff" value="Highlight bookmarks" toBeTranslated="true"/> </node> <node name="bgColor" value="Background color" toBeTranslated="true"/> </node> <node name="selection" value="Utvalg"> <node name="copyToClipboard" value="Kopier til utklippstavle"/> <node name="openInDictionary" value="Åpne i ordbok"/> <node name="quoteFrom" value="Sitér fra %s"/> <node name="textInBuffer" value="Kopiert til utklippstavle:&#10;%s"/> <node name="bookmarkCreated" value="Bokmerke laget:&#10;%s"/> <node name="clearSelection" value="Tøm"/> </node> <node name="sharing"> <node name="sharedFrom" value="Delt fra &lt;a href=&quot;http://www.fbreader.org/&quot;&gt;FBReader&lt;/a&gt;"/> </node> <node name="menu"> <node name="preferences" value="Innstillinger"/> <node name="bookInfo" value="Bokinformasjon"/> <node name="library" value="Bibliotek"/> <node name="toc" value="Innhold"/> <node name="day" value="Dag"/> <node name="night" value="Natt"/> <node name="networkLibrary" value="Nettverksbibliotek"/> <node name="navigate" value="Navigér"> <node name="toc" value="Innholdsfortegnelse"/> <node name="gotoHome" value="Gå til begynnelsen av dokumentet"/> <node name="gotoPageNumber" value="Gå til side…"/> <node name="gotoSectionStart" value="Gå til starten av tekstdelen"/> <node name="gotoSectionEnd" value="Gå til slutten av tekstdelen"/> <node name="nextTOCSection" value="Gå til neste punkt i innholdsfortegnelsen"/> <node name="previousTOCSection" value="Gå til forrige punkt i innholdsfortegnelsen"/> <node name="undo" value="Gå tilbake"/> <node name="redo" value="Gå framover"/> </node> <node name="shareBook" value="Del bok"/> <node name="search" value="Søk"/> <node name="rotate" value="Rotér visning"/> <node name="screenOrientation" value="Visningsretning"/> <node name="screenOrientationSystem" value="System"/> <node name="screenOrientationSensor" value="Følger retningen til enheten"/> <node name="screenOrientationPortrait" value="Portrett"/> <node name="screenOrientationLandscape" value="Landskap"/> <node name="screenOrientationReversePortrait" value="Motsatt portrett"/> <node name="screenOrientationReverseLandscape" value="Motsatt landskap"/> <node name="increaseFont" value="Zoom inn"/> <node name="decreaseFont" value="Zoom ut"/> <node name="toggleFullscreen" value="Full skjerm"/> <node name="bookmarks" value="Bokmerker"/> </node> <node name="BookInfo"> <node name="fileName" value="Filnavn"/> <node name="title" value="Tittel"/> <node name="language" value="Språk"/> <node name="encoding" value="Koding"/> <node name="authors" value="Forfatter(-e)"/> <node name="tags" value="Merkelapp(-er)"/> <node name="series" value="Serie"/> </node> <node name="Preferences"> <node name="directories" value="Kataloger"> <node name="summary" value="Kataloger å se etter filer i"/> <node name="books" value="Bokkatalog"/> <node name="fonts" value="Skrifttypekatalog"/> <node name="wallpapers" value="Bakgrunnskatalog"/> </node> <node name="appearance" value="Utseende"> <node name="summary" value="Visningsinnstillinger, statuslinje, knappelys"/> <node name="language" value="Språk"/> <node name="screenOrientation" value="Visningsretning"> <node name="system" value="System"/> <node name="sensor" value="Følger retningen til enhet"/> <node name="portrait" value="Portrett"/> <node name="landscape" value="Landskap"/> <node name="reversePortrait" value="Motsatt portrett"/> <node name="reverseLandscape" value="Mottsatt landskap"/> </node> <node name="autoOrientation" value="Automatisk rotering"> <node name="summaryOn" value="Visningen vil rotere når brukeren beveger enheten"/> <node name="summaryOff" value="Visningen vil ikke rotere når brukeren beveger enheten"/> </node> <node name="showStatusBar" value="Vis statuslinje"> <node name="summaryOn" value="Vis statuslinjen ved lesing"/> <node name="summaryOff" value="Skjul statuslinjen ved lesing"/> </node> <node name="showActionBar" value="Vis handlingslinjen"> <node name="summaryOn" value="Vis handlingslinjen ved lesing"/> <node name="summaryOff" value="Skjul handlingslinjen ved lesing"/> </node> <node name="showStatusBarWhenMenuIsActive" value="Vis statuslinjen når menyen er aktiv"> <node name="summaryOn" value="Vis statuslinjen når menyen blir aktiv"/> <node name="summaryOff" value="Ikke vis statuslinjen når menyen blir aktiv"/> </node> <node name="disableButtonLights" value="Skru av knappelys under lesing"> <node name="summaryOn" value="Skru av knappelys (virker ikke på alle enheter)"/> <node name="summaryOff" value="Ikke prøv å skru av knappelys"/> </node> <node name="twoColumnView" value="Two column view" toBeTranslated="true"> <node name="summaryOn" value="Display text in two columns when device is held horizontally" toBeTranslated="true"/> <node name="summaryOff" value="Always display text in one column" toBeTranslated="true"/> </node> <node name="allowScreenBrightnessAdjustment" value="Juster skjermens lysstyrke"> <node name="summaryOn" value="Ved å dra fingeren opp/ned langs venstre side av skjermen"/> <node name="summaryOff" value="Av"/> </node> <node name="dontTurnScreenOff" value="Stopp skjermen fra å gå i dvale"> <node name="0" value="Alltid"/> <node name="25" value="Når batterinivået er høyere enn 25 prosent"/> <node name="50" value="Når betterinivået er høyere enn 50 prosent"/> <node name="100" value="Aldri"/> </node> <node name="dontTurnScreenOffDuringCharging" value="Stopp skjermen fra å gå i dvale under lading"> <node name="summaryOn" value="Stopp skjermen fra å gå i dvale hvis enheten lader"/> <node name="summaryOff" value="Skru av skjermen selv om enheten lader"/> </node> </node> <node name="text" value="Tekst"> <node name="summary" value="Skrifttype, bindestrek, osv."/> <node name="fontProperties" value="Egenskaper ved skrift"> <node name="summary" value="Valg for glattere skrift"/> <node name="antiAlias" value="Antialiasing"> <node name="summaryOn" value="Antialiasing er på"/> <node name="summaryOff" value="Antialiasing er av"/> </node> <node name="deviceKerning" value="Enhet kniping"> <node name="summaryOn" value="Enhet kniping er på"/> <node name="summaryOff" value="Enhet kniping er av"/> </node> <node name="dithering" value="Fargeutjamning"> <node name="summaryOn" value="Fargeutjamning er på"/> <node name="summaryOff" value="Fargeutjamning er av"/> </node> <node name="hinting" value="Antydning"> <node name="summaryOn" value="Skriftantydning er på"/> <node name="summaryOff" value="Skriftantydning er av"/> </node> <node name="subpixel" value="Subpixel-glatting"> <node name="summaryOn" value="Subpixel-glatting er på"/> <node name="summaryOff" value="Subpixel-glatting er av"/> </node> </node> <node name="font" value="Skrifttype"> <node name="unchanged" value="&lt;uforandret&gt;"/> </node> <node name="fontSize" value="Skriftstørrelse"/> <node name="fontSizeDifference" value="Skriftstørrelse-forskjell"/> <node name="fontStyle" value="Skriftstil"> <node name="regular" value="Vanlig"/> <node name="bold" value="Uthevet"/> <node name="italic" value="Kursiv"/> <node name="boldItalic" value="Uthevet kursiv"/> </node> <node name="bold" value="Uthevet"> <node name="summaryOn" value="uthevet"/> <node name="summaryOff" value="vanlig"/> <node name="unchanged" value="&lt;uforandret&gt;"/> </node> <node name="italic" value="Kursiv"> <node name="summaryOn" value="kursiv"/> <node name="summaryOff" value="vanlig"/> <node name="unchanged" value="&lt;uforandret&gt;"/> </node> <node name="underlined" value="Understreket"> <node name="summaryOn" value="understreket"/> <node name="summaryOff" value="vanlig"/> <node name="unchanged" value="&lt;uforandret&gt;"/> </node> <node name="strikedThrough" value="Gjennomstreket"> <node name="summaryOn" value="gjennomstreket"/> <node name="summaryOff" value="vanlig"/> <node name="unchanged" value="&lt;uforandret&gt;"/> </node> <node name="lineSpacing" value="Linjeavstand"> <node name="unchanged" value="&lt;uforandret&gt;"/> </node> <node name="alignment" value="Justering"> <node name="left" value="Venstre"/> <node name="right" value="Høyre"/> <node name="center" value="Midtstilt"/> <node name="justify" value="Blokkjustert"/> <node name="unchanged" value="&lt;uforandret&gt;"/> </node> <node name="autoHyphenations" value="Auto-bindestrek"> <node name="summaryOn" value="Lag bindestrek i ord automatisk"/> <node name="summaryOff" value="Ikke lag bindestrek i ord automatisk"/> </node> <node name="allowHyphenations" value="Tillat bindestrek"> <node name="summaryOn" value="lag bindestrek i ord"/> <node name="summaryOff" value="ikke lag bindestrek i ord"/> <node name="unchanged" value="&lt;uforandret&gt;"/> </node> <node name="firstLineIndent" value="Innrykk første linje"/> <node name="spaceBefore" value="Mellomrom foran"/> <node name="spaceAfter" value="Mellomrom etter"/> <node name="leftIndent" value="Venstre innrykk"/> <node name="rightIndent" value="Høyre innrykk"/> <node name="more" value="Flere stiler"> <node name="summary" value="Egne innstillinger for titler, epigrafer, osv."/> <node name="Regular Paragraph" value="Vanlig avsnitt"> <node name="summary" value=""/> </node> <node name="Title" value="Tittel"> <node name="summary" value=""/> </node> <node name="Section Title" value="Seksjonstittel"> <node name="summary" value=""/> </node> <node name="Poem Title" value="Dikttittel"> <node name="summary" value=""/> </node> <node name="Subtitle" value="Underoverskrift"> <node name="summary" value=""/> </node> <node name="Annotation" value="Kommentar"> <node name="summary" value=""/> </node> <node name="Epigraph" value="Epigraf"> <node name="summary" value=""/> </node> <node name="Stanza" value="Strofe"> <node name="summary" value=""/> </node> <node name="Verse" value="Vers"> <node name="summary" value=""/> </node> <node name="Preformatted text" value="Forhåndsformatert tekst"> <node name="summary" value=""/> </node> <node name="Image" value="Bilde"> <node name="summary" value=""/> </node> <node name="Cite" value="Sitere"> <node name="summary" value=""/> </node> <node name="Author" value="Forfatter"> <node name="summary" value=""/> </node> <node name="Date" value="Dato"> <node name="summary" value=""/> </node> <node name="Internal Hyperlink" value="Intern hyperlenke"> <node name="summary" value=""/> </node> <node name="Footnote" value="Fotnote"> <node name="summary" value=""/> </node> <node name="Emphasis" value="Trykk"> <node name="summary" value=""/> </node> <node name="Strong" value="Sterk"> <node name="summary" value=""/> </node> <node name="Subscript" value="Senket skrift"> <node name="summary" value=""/> </node> <node name="Superscript" value="Hevet skrift"> <node name="summary" value=""/> </node> <node name="Code" value="Kode"> <node name="summary" value=""/> </node> <node name="StrikeThrough" value="Gjennomstrek"> <node name="summary" value=""/> </node> <node name="Italic" value="Kursiv"> <node name="summary" value=""/> </node> <node name="Bold" value="Uthevet"> <node name="summary" value=""/> </node> <node name="Definition" value="Definisjon"> <node name="summary" value=""/> </node> <node name="Definition Description" value="Definisjonsbeskrivelse"> <node name="summary" value=""/> </node> <node name="Header 1" value="Overskrift 1"> <node name="summary" value=""/> </node> <node name="Header 2" value="Overskrift 2"> <node name="summary" value=""/> </node> <node name="Header 3" value="Overskrift 3"> <node name="summary" value=""/> </node> <node name="Header 4" value="Overskrift 4"> <node name="summary" value=""/> </node> <node name="Header 5" value="Overskrift 5"> <node name="summary" value=""/> </node> <node name="Header 6" value="Overskrift 6"> <node name="summary" value=""/> </node> <node name="External Hyperlink" value="Ekstern hyperlenke"> <node name="summary" value=""/> </node> </node> </node> <node name="css" value="CSS"> <node name="summary" value="Bruk/ignorer verdier definert i CSS-stilark"/> <node name="fontSize" value="Skriftstørrelse"> <node name="summaryOn" value="Bruk skriftstørrelse definert i CSS"/> <node name="summaryOff" value="Ignorer skriftstørrelse definert i CSS"/> </node> <node name="textAlignment" value="Tekstjustering"> <node name="summaryOn" value="Bruk tekstjustering definert i CSS"/> <node name="summaryOff" value="Ignorer tekstjustering definert i CSS"/> </node> </node> <node name="colors" value="Farger og bakgrunnsbilder"> <node name="summary" value="Fargeinnstillinger"/> <node name="background" value="Bakgrunn"> <node name="solidColor" value="Ensfarget"/> <node name="leather" value="Lær"/> <node name="sepia" value="Sepia"/> <node name="wood" value="Tre"/> </node> <node name="backgroundColor" value="Bakgrunnsfarge"/> <node name="selectionBackground" value="Utvalgsbakgrunn"/> <node name="selectionForeground" value="Valgt tekst"/> <node name="text" value="Vanlig tekst"/> <node name="hyperlink" value="Hyperlenketekst"/> <node name="hyperlinkVisited" value="Besøkt hyperlenketekst"/> <node name="highlighting" value="Bakgrunn søkeresultat"/> <node name="footer" value="Bunntekst"/> </node> <node name="margins" value="Marger"> <node name="summary" value="Tekstmarger"/> <node name="left" value="Venstre marg"/> <node name="right" value="Høyre marg"/> <node name="top" value="Toppmarg"/> <node name="bottom" value="Bunnmarg"/> <node name="spaceBetweenColumns" value="Space between columns" toBeTranslated="true"/> </node> <node name="scrollBar" value="Fremgangsindikator"> <node name="summary" value="Innstillinger for rullefelt og bunntekst"/> <node name="scrollbarType" value="Rullefelttype"> <node name="hide" value="Skjul"/> <node name="show" value="Loddrett glidebryter"/> <node name="showAsProgress" value="Loddrett fremgangsfelt"/> <node name="showAsFooter" value="Vannrett bunntekst"/> </node> <node name="footerHeight" value="Bunntekstens høyde"/> <node name="footerColor" value="Bunntekstens farge"/> <node name="tocMarks" value="Vis merkene i innholdsfortegnelsen"> <node name="summaryOn" value="Vis merkene i innholdsfortegnelsen i bunntekstlinjen"/> <node name="summaryOff" value="Ikke vis merkene i innholdsfortegnelsen i bunntekstlinjen"/> </node> <node name="showProgress" value="Vis sidetall"> <node name="summaryOn" value="Vis sidetall i bunnteksten"/> <node name="summaryOff" value="Ikke vis sidetall i bunnteksten"/> </node> <node name="showBattery" value="Vis batterinivå"> <node name="summaryOn" value="Vis batterinivået i bunnteksten"/> <node name="summaryOff" value="Ikke vis batterinivået i bunnteksten"/> </node> <node name="showClock" value="Vis klokke"> <node name="summaryOn" value="Vis klokken i bunnteksten"/> <node name="summaryOff" value="Ikke vis klokken i bunnteksten"/> </node> <node name="font" value="Skrifttype"/> </node> <node name="scrolling" value="Bla sider"> <node name="summary" value="Hvordan bla om sidene"/> <node name="fingerScrolling" value="Berør skjermen for å bla"> <node name="byTap" value="Bla om sidene ved å trykke med fingeren"/> <node name="byFlick" value="Bla om sidene ved å dra fingeren over"/> <node name="byTapAndFlick" value="Bla om sidene enten ved å trykke eller dra"/> </node> <node name="enableDoubleTapDetection" value="Oppdag dobbeltrykk"> <node name="summaryOn" value="Dobbeltrykk for å åpne navigasjonsdialog/meny"/> <node name="summaryOff" value="Ignorer dobbeltrykk"/> </node> <node name="volumeKeys" value="Bla om med volumknappene"> <node name="summaryOn" value="Bruk volumknappene til å bla om sidene"/> <node name="summaryOff" value="Behold volumknappene til lyd"/> </node> <node name="invertVolumeKeys" value="Snu om på volumknappenes retning"> <node name="summaryOn" value="Høyere- (lavere-) knappen blar sidene til forrige (neste) side"/> <node name="summaryOff" value="Lavere- (høyere-) knappen blar sidene til neste (forrige) side"/> </node> <node name="animation" value="Animasjon"> <node name="none" value="Bla sidene uten animasjon"/> <node name="curl" value="Krølleanimasjon"/> <node name="slide" value="Skyveanimasjon"/> <node name="shift" value="Skifteanimasjon"/> </node> <node name="animationSpeed" value="Animasjonshastighet"> <node name="fast" value="rask"/> <node name="slow" value="sakte"/> </node> <node name="horizontal" value="Vannrett rulling"> <node name="summaryOn" value="Rull sidene vannrett"/> <node name="summaryOff" value="Rull sidene loddrett"/> </node> </node> <node name="tapZones" value="Trykksoner"> <node name="summary" value="Handlinger ved fingertrykk"/> <node name="tapZonesScheme" value="Oppsett for trykksoner"> <node name="left_to_right" value="Venstre til høyre siderulling"/> <node name="right_to_left" value="Høyre til venstre siderulling"/> <node name="up" value="Ned til opp siderulling"/> <node name="down" value="Opp til ned siderulling"/> <node name="custom" value="Egendefinert…"/> </node> </node> <node name="dictionary" value="Ordbok"> <node name="summary" value="Innstillinger for ordbok"/> <node name="dictionary" value="Ordbok"/> <node name="translator" value="Oversetter"/> <node name="tappingAction" value="Handling ved langvarig trykk"> <node name="doNothing" value="Langvarig trykk gjør ingenting"/> <node name="selectSingleWord" value="Langvarig trykk velger enkeltord"/> <node name="startSelecting" value="Langvarig trykk starter velging"/> <node name="openDictionary" value="Langvarig trykk velger enkeltord, slipp trykk for å åpne ordbok"/> </node> <node name="navigateOverAllWords" value="Naviger over alle ord"> <node name="summaryOn" value="Key navigation visits all words" toBeTranslated="true"/> <node name="summaryOff" value="Tastenavigasjon besøker bare hyperlenker"/> </node> </node> <node name="images" value="Bilder"> <node name="summary" value="Valg for bildevisning"/> <node name="backgroundColor" value="Bakgrunnsfarge ved bildevisning"/> <node name="tappingAction" value="Handling ved langvarig trykk"> <node name="doNothing" value="Langvarig trykk gjør ingenting"/> <node name="selectImage" value="Langvarig trykk velger bildet"/> <node name="openImageView" value="Langvarig trykk åpner bildevisning"/> </node> <node name="fitImagesToScreen" value="Tilpass bilder til skjerm"> <node name="none" value="Ingen"/> <node name="covers" value="Bare forsider"/> <node name="all" value="Alle"/> </node> </node> <node name="cancelMenu" value="Avbryt meny"> <node name="summary" value="Handlingsliste for tilbakeknappen"/> <node name="library" value="Bibliotek"> <node name="summaryOn" value="Vis elementer i 'open library' "/> <node name="summaryOff" value="Ikke vis elementer i 'open library'"/> </node> <node name="networkLibrary" value="Nettverksbibliotek"> <node name="summaryOn" value="Vis elementer i 'open network library'"/> <node name="summaryOff" value="Ikke vis elementer i 'open network library'"/> </node> <node name="previousBook" value="Forrige bok"> <node name="summaryOn" value="Vis elementet 'return to previous book'"/> <node name="summaryOff" value="Ikke vis 'return to previous book'"/> </node> <node name="positions" value="Siste tre posisjoner"> <node name="summaryOn" value="Vis elementer for de siste tre posisjonene i boken"/> <node name="summaryOff" value="Ikke vis elementer for de siste tre posisjonene i boken"/> </node> <node name="backKeyAction" value="Tilbakeknapp handling"> <node name="exit" value="Lukk FBReader"/> <node name="goBack" value="Naviger tilbake"/> <node name="cancelMenu" value="Vis avbryt meny"/> </node> <node name="backKeyLongPressAction" value="Tilbakeknapp - handling ved langvarig trykk"> <node name="exit" value="Lukk FBReader"/> <node name="goBack" value="Naviger tilbake"/> <node name="cancelMenu" value="Vis avbryt meny"/> <node name="none" value="Ingen handling"/> </node> </node> <node name="tips" value="Tips"> <node name="summary" value="Innstillinger for daglige tips"/> <node name="showTips" value="Vis tips"> <node name="summaryOn" value="Vis daglige tips"/> <node name="summaryOff" value="Ikke vis"/> </node> </node> <node name="about" value="Om FBReader"> <node name="summary" value="Versjonsinfo, kontakter"/> <node name="version" value="Versjon"/> <node name="site" value="Besøk nettstedet vårt"> <node name="url" value="http://www.fbreader.org/"/> </node> <node name="email" value="Send oss en e-post"> <node name="url" value="mailto:contact@geometerplus.com"/> </node> <node name="twitter" value="Følg oss på Twitter"> <node name="url" value="http://twitter.com/fbreader"/> </node> </node> </node> <node name="dialog"> <node name="button"> <node name="install" value="Installer"/> <node name="update" value="Oppdater"/> <node name="skip" value="Hopp over"/> <node name="buy" value="Kjøp"/> <node name="buyAndDownload" value="Kjøp og last ned"/> <node name="continue" value="Fortsett"/> <node name="editUrl" value="Endre URL"/> <node name="tryAgain" value="Prøv igjen"/> <node name="openBook" value="Les"/> <node name="editInfo" value="Endre"/> <node name="reloadInfo" value="Oppfrisk"/> <node name="shareBook" value="Del"/> <node name="topup" value="Fyll opp"/> <node name="pay" value="Betal"/> <node name="refresh" value="Oppfrisk"/> <node name="authorize" value="Autoriser"/> <node name="resetPosition" value="Tilbakestill posisjon"/> <node name="sendReport" value="Send rapport"/> <node name="addToFavorites" value="Legg til i favoritter"/> <node name="removeFromFavorites" value="Fjern fra favoritter"/> <node name="markAsRead" value="Mark as read" toBeTranslated="true"/> <node name="markAsUnread" value="Mark as unread" toBeTranslated="true"/> </node> <node name="plugin"> <node name="installTitle" value="Installer tillegg"/> <node name="updateTitle" value="Oppdater tillegg"/> <node name="dontAskAgain" value="Ikke spør igjen"/> </node> <node name="installDictionary"> <node name="title" value="Installer ordbok"/> <node name="message" value="Vil du installere %s?"/> </node> <node name="deleteBookBox"> <node name="message" value="Filen med boken vil bli slettet uten mulighet for å angre. Er du sikker på at du vil slette boken?"/> </node> <node name="redownloadFileBox"> <node name="message" value="Filen finnes allerede. Last ned på nytt?"/> </node> <node name="waitMessage"> <node name="downloadingFile" value="Laster ned boken %s"/> <node name="search" value="Søker. Vennligst vent…"/> <node name="loadInfo" value="Laster informasjon. Vennligst vent…"/> <node name="loadingBook" value="Åpner bok. Vennligst vent…"/> <node name="loadingBookList" value="Åpner bibliotek. Vennligst vent…"/> <node name="creatingBooksDatabase" value="Lager bokdatabase. Vennligst vent…"/> <node name="updatingBooksDatabase" value="Oppdater bokdatabasen. Vennligst vent…"/> <node name="loadingNetworkLibrary" value="Åpner bibliotek. Vennligst vent…"/> <node name="authentication" value="Auteniserer. Vennligst vent…"/> <node name="signOut" value="Logger ut. Vennligst vent…"/> <node name="purchaseBook" value="Kjøper bok. Vennligst vent…"/> <node name="loadingCatalogInfo" value="Laster kataloginformasjon. Vennligst vent…"/> <node name="loadingNetworkBookInfo" value="Laster bokinformasjon. Vennligst vent…"/> <node name="updatingCatalogsList" value="Oppdaterer kataloglister. Vennligst vent…"/> <node name="updatingAccountInformation" value="Oppdaterer kontorinformasjon. Vennligst vent…"/> </node> <node name="networkError"> <node name="internalError" value="Intern feil i tjenesten"/> <node name="purchaseNotEnoughMoney" value="Ikke nok penger"/> <node name="purchaseMissingBook" value="Manglende bok"/> <node name="purchaseAlreadyPurchased" value="Allerede kjøpt"/> <node name="bookNotPurchased" value="Boken ble ikke kjøpt"/> <node name="downloadLimitExceeded" value="Nedlastingsgrensen er overskredet"/> <node name="noUserEmail" value="Ingen bruker var registrert&#10;med oppgitte e-postadresse"/> <node name="unsupportedOperation" value="Handlingen er ikke støttet"/> <node name="notAnOPDS" value="Dette er ikke en OPDS-katalog"/> <node name="noRequiredInformation" value="Påkrevet informasjon er ikke oppgitt i katalogen"/> <node name="cacheDirectoryError" value="Kan ikke lage mellomlagringskatalog"/> </node> <node name="AuthenticationDialog"> <node name="title" value="Autentisering"/> <node name="unencryptedWarning" value="Passordet ditt vil bli sent ukryptert"/> <node name="login" value="Brukernavn"/> <node name="password" value="Passord"/> <node name="loginIsEmpty" value="Brukernavn kan ikke stå tomt"/> <node name="register" value="Registrer deg"/> </node> <node name="CustomCatalogDialog"> <node name="title" value="FBReader: legg til katalog selv"/> <node name="catalogTitle" value="Tittel"/> <node name="catalogUrl" value="URL"/> <node name="catalogSummary" value="Sammendrag"/> <node name="catalogTitleExample" value="For eksempel: Prosjekt Gutenberg-katalogen"/> <node name="catalogUrlExample" value="For eksempel: http://m.gutenberg.org/"/> <node name="catalogSummaryExample" value="For eksempel: Frie bøker"/> <node name="titleIsEmpty" value="Tittel kan ikke stå tomt"/> <node name="urlIsEmpty" value="URL kan ikke stå tomt"/> <node name="invalidUrl" value="Ugyldig URL"/> <node name="titleAlreadyExists" value="Oppgitt tittel er allerede i bruk"/> <node name="siteAlreadyExists" value="Oppgitt nettsted er allerede i bruk"/> </node> <node name="languageFilterDialog"> <node name="title" value="Språkfilter"/> </node> <node name="tips"> <node name="title" value="Dagens tips"/> <node name="initializationText" value="Ønsker du å lese daglige tips i FBReader? Nye tips vil bli lastet ned fra nettstedet til FBReader. Forventet nettverkstrafikk er 1-2 kilobytes per uke.&#10;&#10;Skru på tips?"/> <node name="dontShowAgain" value="Ikke vis igjen"/> <node name="more" value="Neste tips"/> </node> </node> <node name="errorMessage"> <node name="cannotRunAndroidMarket" value="Ikke tilgang til Android Market. Vennligst installer %s manuelt"/> <node name="textNotFound" value="Det er ingen passende tekst i boken, beklager"/> <node name="bookNotFound" value="Det er ingen passende bøker i biblioteket, beklager"/> <node name="bookmarkNotFound" value="Det er ingen passende bokmerker, beklager"/> <node name="cannotOpenBook" value="Kan for øyeblikket ikke åpne denne boken, beklager"/> <node name="dictionaryIsNotInstalled" value="Ordbok er ikke installert, beklager"/> <node name="permissionDenied" value="Mangler tillatelse, beklager"/> <node name="noFavorites" value="Favorittlisten din er tom, beklager"/> <node name="noSeries" value="There are no books in series, sorry" toBeTranslated="true"/> <node name="emptyCatalog" value="Katalogen er tom, beklager"/> <node name="emptyBasket" value="Kurven din er tom, beklager"/> <node name="emptyNetworkSearchResults" value="Ingen bøker ble funnet, beklager"/> </node> <node name="external"> <node name="browser" value="Nettleser"/> <node name="defaultBrowser" value="Standard nettleser"/> </node> <node name="mobipocketPlugin"> <node name="unknown" value="Ukjent feil"/> <node name="unsupportedCompressionMethod" value="Kompresjonsmetoden er ikke støttet"/> <node name="encryptedFile" value="Filen inneholder Digitale RestriksjonsMekanismer (DRM)"/> </node> <node name="crash"> <node name="fixBooksDirectory"> <node name="title" value="FBReader problem"/> <node name="text" value="Mellomlagringskatalogen til FBReader er ikke tilgjengelig for skriving. Kanskje du glemte å sette inn eller har koblet fra minnekortet ditt. Vennligst fiks dette problemet eller skriv inn et annet katalognavn nedenfor."/> </node> <node name="missingNativeLibrary"> <node name="title" value="FBReader problem"/> <node name="text" value="FBReader kan ikke laste innebygget bibliotek. Kanskje det ikke ble installert skikkelig. Hvis problemet vedvarer, så prøv å installere FBReader på nytt."/> </node> </node> <node name="error"> <node name="bookReading"> <node name="title" value="FBReader problem"/> </node> </node> <node name="bookReadingException"> <node name="errorReadingFile" value="Feilen oppstod under lesing '%s'"/> <node name="errorReadingZip" value="Feilen oppstod under utpakking '%s'"/> <node name="pluginNotFound" value="Ingen tillegg for '%s'"/> <node name="unknownPluginType" value="Ukjent tilleggstype: %s"/> <node name="fileNotFound" value="Filen ble ikke funnet: %s"/> <node name="opfFileNotFound" value="OPF er ikke funnet i %s"/> <node name="unsupportedFileFormat" value="Filformatet er ikke støttet for '%s'"/> <node name="errorParsingRtf" value="Rtf analysingsfeil i: %s"/> </node> </resources>
{ "content_hash": "4799e246102530dd01d51c322b3483f7", "timestamp": "", "source": "github", "line_count": 869, "max_line_length": 249, "avg_line_length": 46.81472957422324, "alnum_prop": 0.683643871982695, "repo_name": "liufeiit/itmarry", "id": "a0cacc37c7236c6b67dc9ed4fa6d9ea214cebc21", "size": "40934", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "reader/android-reader/assets/resources/application/nb.xml", "mode": "33188", "license": "mit", "language": [ { "name": "C", "bytes": "676835" }, { "name": "C++", "bytes": "811681" }, { "name": "CSS", "bytes": "27002" }, { "name": "Groovy", "bytes": "7626" }, { "name": "Java", "bytes": "9589143" }, { "name": "JavaScript", "bytes": "1158018" }, { "name": "Perl", "bytes": "1710" }, { "name": "Shell", "bytes": "400802" } ], "symlink_target": "" }
// Copyright (c) Microsoft Open Technologies, Inc. All rights reserved. See License.txt in the project root for license information. #if !NO_TPL using System; using System.Collections.Generic; using System.Linq; using System.Text; using Microsoft.VisualStudio.TestTools.UnitTesting; using System.Collections; using System.Threading; using System.Threading.Tasks; using System.Diagnostics; //using System.Reactive.Linq; //using System.Reactive.Concurrency; namespace Tests { public partial class AsyncTests { [TestInitialize] public void InitTests() { TaskScheduler.UnobservedTaskException += (o, e) => { }; } /* [TestMethod] public void TestPushPopAsync() { var stack = new Stack<int>(); var count = 10; var observable = Observable.Generate( 0, i => i < count, i => i + 1, i => i, i => TimeSpan.FromMilliseconds(1), // change this to 0 to avoid the problem [1] Scheduler.ThreadPool); var task = DoSomethingAsync(observable, stack); // we give it a timeout so the test can fail instead of hang task.Wait(TimeSpan.FromSeconds(2)); Assert.AreEqual(10, stack.Count); } private Task DoSomethingAsync(IObservable<int> observable, Stack<int> stack) { var ae = observable .ToAsyncEnumerable() //.Do(i => Debug.WriteLine("Bug-fixing side effect: " + i)) // [2] .GetEnumerator(); var tcs = new TaskCompletionSource<object>(); var a = default(Action); a = new Action(() => { ae.MoveNext().ContinueWith(t => { if (t.Result) { var i = ae.Current; Debug.WriteLine("Doing something with " + i); Thread.Sleep(50); stack.Push(i); a(); } else tcs.TrySetResult(null); }); }); a(); return tcs.Task; } */ static IEnumerable<int> Xs(Action a) { try { var rnd = new Random(); while (true) { yield return rnd.Next(0, 43); Thread.Sleep(rnd.Next(0, 500)); } } finally { a(); } } [TestMethod] public void CorrectDispose() { var disposed = false; var xs = new[] { 1, 2, 3 }.WithDispose(() => { disposed = true; }).ToAsyncEnumerable(); var ys = xs.Select(x => x + 1); var e = ys.GetEnumerator(); e.Dispose(); Assert.IsTrue(disposed); Assert.IsFalse(e.MoveNext().Result); } [TestMethod] public void DisposesUponError() { var disposed = false; var xs = new[] { 1, 2, 3 }.WithDispose(() => { disposed = true; }).ToAsyncEnumerable(); var ex = new Exception("Bang!"); var ys = xs.Select(x => { if (x == 1) throw ex; return x; }); var e = ys.GetEnumerator(); AssertThrows<Exception>(() => e.MoveNext()); Assert.IsTrue(disposed); } [TestMethod] public void CorrectCancel() { var disposed = false; var xs = new[] { 1, 2, 3 }.WithDispose(() => { disposed = true; }).ToAsyncEnumerable(); var ys = xs.Select(x => x + 1).Where(x => true); var e = ys.GetEnumerator(); var cts = new CancellationTokenSource(); var t = e.MoveNext(cts.Token); cts.Cancel(); try { t.Wait(); } catch { // Don't care about the outcome; we could have made it to element 1 // but we could also have cancelled the MoveNext-calling task. Either // way, we want to wait for the task to be completed and check that } finally { // the cancellation bubbled all the way up to the source to dispose // it. This design is chosen because cancelling a MoveNext call leaves // the enumerator in an indeterminate state. Further interactions with // it should be forbidden. Assert.IsTrue(disposed); } Assert.IsFalse(e.MoveNext().Result); } [TestMethod] public void CanCancelMoveNext() { var evt = new ManualResetEvent(false); var xs = Blocking(evt).ToAsyncEnumerable().Select(x => x).Where(x => true); var e = xs.GetEnumerator(); var cts = new CancellationTokenSource(); var t = e.MoveNext(cts.Token); cts.Cancel(); try { t.Wait(); Assert.Fail(); } catch { Assert.IsTrue(t.IsCanceled); } evt.Set(); } static IEnumerable<int> Blocking(ManualResetEvent evt) { evt.WaitOne(); yield return 42; } } static class MyExt { public static IEnumerable<T> WithDispose<T>(this IEnumerable<T> source, Action a) { return EnumerableEx.Create(() => { var e = source.GetEnumerator(); return new Enumerator<T>(e.MoveNext, () => e.Current, () => { e.Dispose(); a(); }); }); } class Enumerator<T> : IEnumerator<T> { private readonly Func<bool> _moveNext; private readonly Func<T> _current; private readonly Action _dispose; public Enumerator(Func<bool> moveNext, Func<T> current, Action dispose) { _moveNext = moveNext; _current = current; _dispose = dispose; } public T Current { get { return _current(); } } public void Dispose() { _dispose(); } object IEnumerator.Current { get { return Current; } } public bool MoveNext() { return _moveNext(); } public void Reset() { throw new NotImplementedException(); } } } } #endif
{ "content_hash": "7d6c5abae4379760ae8aa1eac4ca5c31", "timestamp": "", "source": "github", "line_count": 265, "max_line_length": 133, "avg_line_length": 26.577358490566038, "alnum_prop": 0.45165412466278576, "repo_name": "airbreather/RandomFireplace", "id": "7fc85301380ed0e9fe0415b18cc73c2b87daf026", "size": "7045", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "External/Rx/Ix.NET/Source/Tests/AsyncTests.Bugs.cs", "mode": "33188", "license": "bsd-3-clause", "language": [ { "name": "C#", "bytes": "10894888" }, { "name": "PowerShell", "bytes": "5066" }, { "name": "Shell", "bytes": "979" }, { "name": "Smalltalk", "bytes": "383113" } ], "symlink_target": "" }
using base::Time; namespace history { namespace { static const char* kHistoryThreadName = "Chrome_HistoryThread"; void RunWithFaviconResults( const favicon_base::FaviconResultsCallback& callback, std::vector<favicon_base::FaviconRawBitmapResult>* bitmap_results) { callback.Run(*bitmap_results); } void RunWithFaviconResult( const favicon_base::FaviconRawBitmapCallback& callback, favicon_base::FaviconRawBitmapResult* bitmap_result) { callback.Run(*bitmap_result); } void RunWithQueryURLResult(const HistoryService::QueryURLCallback& callback, const QueryURLResult* result) { callback.Run(result->success, result->row, result->visits); } void RunWithVisibleVisitCountToHostResult( const HistoryService::GetVisibleVisitCountToHostCallback& callback, const VisibleVisitCountToHostResult* result) { callback.Run(result->success, result->count, result->first_visit); } // Callback from WebHistoryService::ExpireWebHistory(). void ExpireWebHistoryComplete(bool success) { // Ignore the result. // // TODO(davidben): ExpireLocalAndRemoteHistoryBetween callback should not fire // until this completes. } } // namespace // Sends messages from the backend to us on the main thread. This must be a // separate class from the history service so that it can hold a reference to // the history service (otherwise we would have to manually AddRef and // Release when the Backend has a reference to us). class HistoryService::BackendDelegate : public HistoryBackend::Delegate { public: BackendDelegate( const base::WeakPtr<HistoryService>& history_service, const scoped_refptr<base::SequencedTaskRunner>& service_task_runner) : history_service_(history_service), service_task_runner_(service_task_runner) {} void NotifyProfileError(sql::InitStatus init_status) override { // Send to the history service on the main thread. service_task_runner_->PostTask( FROM_HERE, base::Bind(&HistoryService::NotifyProfileError, history_service_, init_status)); } void SetInMemoryBackend(scoped_ptr<InMemoryHistoryBackend> backend) override { // Send the backend to the history service on the main thread. service_task_runner_->PostTask( FROM_HERE, base::Bind(&HistoryService::SetInMemoryBackend, history_service_, base::Passed(&backend))); } void NotifyFaviconsChanged(const std::set<GURL>& page_urls, const GURL& icon_url) override { // Send the notification to the history service on the main thread. service_task_runner_->PostTask( FROM_HERE, base::Bind(&HistoryService::NotifyFaviconsChanged, history_service_, page_urls, icon_url)); } void NotifyURLVisited(ui::PageTransition transition, const URLRow& row, const RedirectList& redirects, base::Time visit_time) override { service_task_runner_->PostTask( FROM_HERE, base::Bind(&HistoryService::NotifyURLVisited, history_service_, transition, row, redirects, visit_time)); } void NotifyURLsModified(const URLRows& changed_urls) override { service_task_runner_->PostTask( FROM_HERE, base::Bind(&HistoryService::NotifyURLsModified, history_service_, changed_urls)); } void NotifyURLsDeleted(bool all_history, bool expired, const URLRows& deleted_rows, const std::set<GURL>& favicon_urls) override { service_task_runner_->PostTask( FROM_HERE, base::Bind(&HistoryService::NotifyURLsDeleted, history_service_, all_history, expired, deleted_rows, favicon_urls)); } void NotifyKeywordSearchTermUpdated(const URLRow& row, KeywordID keyword_id, const base::string16& term) override { service_task_runner_->PostTask( FROM_HERE, base::Bind(&HistoryService::NotifyKeywordSearchTermUpdated, history_service_, row, keyword_id, term)); } void NotifyKeywordSearchTermDeleted(URLID url_id) override { service_task_runner_->PostTask( FROM_HERE, base::Bind(&HistoryService::NotifyKeywordSearchTermDeleted, history_service_, url_id)); } void DBLoaded() override { service_task_runner_->PostTask( FROM_HERE, base::Bind(&HistoryService::OnDBLoaded, history_service_)); } private: const base::WeakPtr<HistoryService> history_service_; const scoped_refptr<base::SequencedTaskRunner> service_task_runner_; }; // The history thread is intentionally not a BrowserThread because the // sync integration unit tests depend on being able to create more than one // history thread. HistoryService::HistoryService() : thread_(new base::Thread(kHistoryThreadName)), history_client_(nullptr), backend_loaded_(false), weak_ptr_factory_(this) { } HistoryService::HistoryService(scoped_ptr<HistoryClient> history_client, scoped_ptr<VisitDelegate> visit_delegate) : thread_(new base::Thread(kHistoryThreadName)), history_client_(std::move(history_client)), visit_delegate_(std::move(visit_delegate)), backend_loaded_(false), weak_ptr_factory_(this) {} HistoryService::~HistoryService() { DCHECK(thread_checker_.CalledOnValidThread()); // Shutdown the backend. This does nothing if Cleanup was already invoked. Cleanup(); } bool HistoryService::BackendLoaded() { DCHECK(thread_checker_.CalledOnValidThread()); return backend_loaded_; } #if defined(OS_IOS) void HistoryService::HandleBackgrounding() { if (!thread_ || !history_backend_.get()) return; ScheduleTask(PRIORITY_NORMAL, base::MakeCriticalClosure(base::Bind( &HistoryBackend::PersistState, history_backend_.get()))); } #endif void HistoryService::ClearCachedDataForContextID(ContextID context_id) { DCHECK(thread_) << "History service being called after cleanup"; DCHECK(thread_checker_.CalledOnValidThread()); ScheduleTask(PRIORITY_NORMAL, base::Bind(&HistoryBackend::ClearCachedDataForContextID, history_backend_.get(), context_id)); } URLDatabase* HistoryService::InMemoryDatabase() { DCHECK(thread_checker_.CalledOnValidThread()); return in_memory_backend_ ? in_memory_backend_->db() : nullptr; } bool HistoryService::GetTypedCountForURL(const GURL& url, int* typed_count) { DCHECK(thread_checker_.CalledOnValidThread()); URLRow url_row; if (!GetRowForURL(url, &url_row)) return false; *typed_count = url_row.typed_count(); return true; } bool HistoryService::GetLastVisitTimeForURL(const GURL& url, base::Time* last_visit) { DCHECK(thread_checker_.CalledOnValidThread()); URLRow url_row; if (!GetRowForURL(url, &url_row)) return false; *last_visit = url_row.last_visit(); return true; } bool HistoryService::GetVisitCountForURL(const GURL& url, int* visit_count) { DCHECK(thread_checker_.CalledOnValidThread()); URLRow url_row; if (!GetRowForURL(url, &url_row)) return false; *visit_count = url_row.visit_count(); return true; } TypedUrlSyncableService* HistoryService::GetTypedUrlSyncableService() const { return history_backend_->GetTypedUrlSyncableService(); } void HistoryService::Shutdown() { DCHECK(thread_checker_.CalledOnValidThread()); Cleanup(); } void HistoryService::SetKeywordSearchTermsForURL(const GURL& url, KeywordID keyword_id, const base::string16& term) { DCHECK(thread_) << "History service being called after cleanup"; DCHECK(thread_checker_.CalledOnValidThread()); ScheduleTask(PRIORITY_UI, base::Bind(&HistoryBackend::SetKeywordSearchTermsForURL, history_backend_.get(), url, keyword_id, term)); } void HistoryService::DeleteAllSearchTermsForKeyword(KeywordID keyword_id) { DCHECK(thread_) << "History service being called after cleanup"; DCHECK(thread_checker_.CalledOnValidThread()); if (in_memory_backend_) in_memory_backend_->DeleteAllSearchTermsForKeyword(keyword_id); ScheduleTask(PRIORITY_UI, base::Bind(&HistoryBackend::DeleteAllSearchTermsForKeyword, history_backend_.get(), keyword_id)); } void HistoryService::DeleteKeywordSearchTermForURL(const GURL& url) { DCHECK(thread_) << "History service being called after cleanup"; DCHECK(thread_checker_.CalledOnValidThread()); ScheduleTask(PRIORITY_UI, base::Bind(&HistoryBackend::DeleteKeywordSearchTermForURL, history_backend_.get(), url)); } void HistoryService::DeleteMatchingURLsForKeyword(KeywordID keyword_id, const base::string16& term) { DCHECK(thread_) << "History service being called after cleanup"; DCHECK(thread_checker_.CalledOnValidThread()); ScheduleTask(PRIORITY_UI, base::Bind(&HistoryBackend::DeleteMatchingURLsForKeyword, history_backend_.get(), keyword_id, term)); } void HistoryService::URLsNoLongerBookmarked(const std::set<GURL>& urls) { DCHECK(thread_) << "History service being called after cleanup"; DCHECK(thread_checker_.CalledOnValidThread()); ScheduleTask(PRIORITY_NORMAL, base::Bind(&HistoryBackend::URLsNoLongerBookmarked, history_backend_.get(), urls)); } void HistoryService::AddObserver(HistoryServiceObserver* observer) { DCHECK(thread_checker_.CalledOnValidThread()); observers_.AddObserver(observer); } void HistoryService::RemoveObserver(HistoryServiceObserver* observer) { DCHECK(thread_checker_.CalledOnValidThread()); observers_.RemoveObserver(observer); } base::CancelableTaskTracker::TaskId HistoryService::ScheduleDBTask( scoped_ptr<HistoryDBTask> task, base::CancelableTaskTracker* tracker) { DCHECK(thread_) << "History service being called after cleanup"; DCHECK(thread_checker_.CalledOnValidThread()); base::CancelableTaskTracker::IsCanceledCallback is_canceled; base::CancelableTaskTracker::TaskId task_id = tracker->NewTrackedTaskId(&is_canceled); // Use base::ThreadTaskRunnerHandler::Get() to get a message loop proxy to // the current message loop so that we can forward the call to the method // HistoryDBTask::DoneRunOnMainThread() in the correct thread. thread_->task_runner()->PostTask( FROM_HERE, base::Bind(&HistoryBackend::ProcessDBTask, history_backend_.get(), base::Passed(&task), base::ThreadTaskRunnerHandle::Get(), is_canceled)); return task_id; } void HistoryService::FlushForTest(const base::Closure& flushed) { thread_->task_runner()->PostTaskAndReply( FROM_HERE, base::Bind(&base::DoNothing), flushed); } void HistoryService::SetOnBackendDestroyTask(const base::Closure& task) { DCHECK(thread_) << "History service being called after cleanup"; DCHECK(thread_checker_.CalledOnValidThread()); ScheduleTask( PRIORITY_NORMAL, base::Bind(&HistoryBackend::SetOnBackendDestroyTask, history_backend_.get(), base::MessageLoop::current(), task)); } void HistoryService::TopHosts(size_t num_hosts, const TopHostsCallback& callback) const { DCHECK(thread_) << "History service being called after cleanup"; DCHECK(thread_checker_.CalledOnValidThread()); PostTaskAndReplyWithResult( thread_->task_runner().get(), FROM_HERE, base::Bind(&HistoryBackend::TopHosts, history_backend_.get(), num_hosts), callback); } void HistoryService::GetCountsAndLastVisitForOrigins( const std::set<GURL>& origins, const GetCountsAndLastVisitForOriginsCallback& callback) const { DCHECK(thread_) << "History service being called after cleanup"; DCHECK(thread_checker_.CalledOnValidThread()); PostTaskAndReplyWithResult( thread_->task_runner().get(), FROM_HERE, base::Bind(&HistoryBackend::GetCountsAndLastVisitForOrigins, history_backend_.get(), origins), callback); } void HistoryService::HostRankIfAvailable( const GURL& url, const base::Callback<void(int)>& callback) const { DCHECK(thread_) << "History service being called after cleanup"; DCHECK(thread_checker_.CalledOnValidThread()); PostTaskAndReplyWithResult(thread_->task_runner().get(), FROM_HERE, base::Bind(&HistoryBackend::HostRankIfAvailable, history_backend_.get(), url), callback); } void HistoryService::AddPage(const GURL& url, Time time, ContextID context_id, int nav_entry_id, const GURL& referrer, const RedirectList& redirects, ui::PageTransition transition, VisitSource visit_source, bool did_replace_entry) { DCHECK(thread_checker_.CalledOnValidThread()); AddPage(HistoryAddPageArgs(url, time, context_id, nav_entry_id, referrer, redirects, transition, visit_source, did_replace_entry)); } void HistoryService::AddPage(const GURL& url, base::Time time, VisitSource visit_source) { DCHECK(thread_checker_.CalledOnValidThread()); AddPage(HistoryAddPageArgs(url, time, nullptr, 0, GURL(), RedirectList(), ui::PAGE_TRANSITION_LINK, visit_source, false)); } void HistoryService::AddPage(const HistoryAddPageArgs& add_page_args) { DCHECK(thread_) << "History service being called after cleanup"; DCHECK(thread_checker_.CalledOnValidThread()); // Filter out unwanted URLs. We don't add auto-subframe URLs. They are a // large part of history (think iframes for ads) and we never display them in // history UI. We will still add manual subframes, which are ones the user // has clicked on to get. if (history_client_ && !history_client_->CanAddURL(add_page_args.url)) return; // Inform VisitedDelegate of all links and redirects. if (visit_delegate_) { if (!add_page_args.redirects.empty()) { // We should not be asked to add a page in the middle of a redirect chain, // and thus add_page_args.url should be the last element in the array // add_page_args.redirects which mean we can use VisitDelegate::AddURLs() // with the whole array. DCHECK_EQ(add_page_args.url, add_page_args.redirects.back()); visit_delegate_->AddURLs(add_page_args.redirects); } else { visit_delegate_->AddURL(add_page_args.url); } } ScheduleTask(PRIORITY_NORMAL, base::Bind(&HistoryBackend::AddPage, history_backend_.get(), add_page_args)); } void HistoryService::AddPageNoVisitForBookmark(const GURL& url, const base::string16& title) { DCHECK(thread_) << "History service being called after cleanup"; DCHECK(thread_checker_.CalledOnValidThread()); if (history_client_ && !history_client_->CanAddURL(url)) return; ScheduleTask(PRIORITY_NORMAL, base::Bind(&HistoryBackend::AddPageNoVisitForBookmark, history_backend_.get(), url, title)); } void HistoryService::SetPageTitle(const GURL& url, const base::string16& title) { DCHECK(thread_) << "History service being called after cleanup"; DCHECK(thread_checker_.CalledOnValidThread()); ScheduleTask(PRIORITY_NORMAL, base::Bind(&HistoryBackend::SetPageTitle, history_backend_.get(), url, title)); } void HistoryService::UpdateWithPageEndTime(ContextID context_id, int nav_entry_id, const GURL& url, Time end_ts) { DCHECK(thread_) << "History service being called after cleanup"; DCHECK(thread_checker_.CalledOnValidThread()); ScheduleTask( PRIORITY_NORMAL, base::Bind(&HistoryBackend::UpdateWithPageEndTime, history_backend_.get(), context_id, nav_entry_id, url, end_ts)); } void HistoryService::AddPageWithDetails(const GURL& url, const base::string16& title, int visit_count, int typed_count, Time last_visit, bool hidden, VisitSource visit_source) { DCHECK(thread_) << "History service being called after cleanup"; DCHECK(thread_checker_.CalledOnValidThread()); // Filter out unwanted URLs. if (history_client_ && !history_client_->CanAddURL(url)) return; // Inform VisitDelegate of the URL. if (visit_delegate_) visit_delegate_->AddURL(url); URLRow row(url); row.set_title(title); row.set_visit_count(visit_count); row.set_typed_count(typed_count); row.set_last_visit(last_visit); row.set_hidden(hidden); URLRows rows; rows.push_back(row); ScheduleTask(PRIORITY_NORMAL, base::Bind(&HistoryBackend::AddPagesWithDetails, history_backend_.get(), rows, visit_source)); } void HistoryService::AddPagesWithDetails(const URLRows& info, VisitSource visit_source) { DCHECK(thread_) << "History service being called after cleanup"; DCHECK(thread_checker_.CalledOnValidThread()); // Inform the VisitDelegate of the URLs if (!info.empty() && visit_delegate_) { std::vector<GURL> urls; urls.reserve(info.size()); for (const auto& row : info) urls.push_back(row.url()); visit_delegate_->AddURLs(urls); } ScheduleTask(PRIORITY_NORMAL, base::Bind(&HistoryBackend::AddPagesWithDetails, history_backend_.get(), info, visit_source)); } base::CancelableTaskTracker::TaskId HistoryService::GetFavicons( const std::vector<GURL>& icon_urls, int icon_types, const std::vector<int>& desired_sizes, const favicon_base::FaviconResultsCallback& callback, base::CancelableTaskTracker* tracker) { DCHECK(thread_) << "History service being called after cleanup"; DCHECK(thread_checker_.CalledOnValidThread()); std::vector<favicon_base::FaviconRawBitmapResult>* results = new std::vector<favicon_base::FaviconRawBitmapResult>(); return tracker->PostTaskAndReply( thread_->task_runner().get(), FROM_HERE, base::Bind(&HistoryBackend::GetFavicons, history_backend_.get(), icon_urls, icon_types, desired_sizes, results), base::Bind(&RunWithFaviconResults, callback, base::Owned(results))); } base::CancelableTaskTracker::TaskId HistoryService::GetFaviconsForURL( const GURL& page_url, int icon_types, const std::vector<int>& desired_sizes, const favicon_base::FaviconResultsCallback& callback, base::CancelableTaskTracker* tracker) { DCHECK(thread_) << "History service being called after cleanup"; DCHECK(thread_checker_.CalledOnValidThread()); std::vector<favicon_base::FaviconRawBitmapResult>* results = new std::vector<favicon_base::FaviconRawBitmapResult>(); return tracker->PostTaskAndReply( thread_->task_runner().get(), FROM_HERE, base::Bind(&HistoryBackend::GetFaviconsForURL, history_backend_.get(), page_url, icon_types, desired_sizes, results), base::Bind(&RunWithFaviconResults, callback, base::Owned(results))); } base::CancelableTaskTracker::TaskId HistoryService::GetLargestFaviconForURL( const GURL& page_url, const std::vector<int>& icon_types, int minimum_size_in_pixels, const favicon_base::FaviconRawBitmapCallback& callback, base::CancelableTaskTracker* tracker) { DCHECK(thread_) << "History service being called after cleanup"; DCHECK(thread_checker_.CalledOnValidThread()); favicon_base::FaviconRawBitmapResult* result = new favicon_base::FaviconRawBitmapResult(); return tracker->PostTaskAndReply( thread_->task_runner().get(), FROM_HERE, base::Bind(&HistoryBackend::GetLargestFaviconForURL, history_backend_.get(), page_url, icon_types, minimum_size_in_pixels, result), base::Bind(&RunWithFaviconResult, callback, base::Owned(result))); } base::CancelableTaskTracker::TaskId HistoryService::GetFaviconForID( favicon_base::FaviconID favicon_id, int desired_size, const favicon_base::FaviconResultsCallback& callback, base::CancelableTaskTracker* tracker) { DCHECK(thread_) << "History service being called after cleanup"; DCHECK(thread_checker_.CalledOnValidThread()); std::vector<favicon_base::FaviconRawBitmapResult>* results = new std::vector<favicon_base::FaviconRawBitmapResult>(); return tracker->PostTaskAndReply( thread_->task_runner().get(), FROM_HERE, base::Bind(&HistoryBackend::GetFaviconForID, history_backend_.get(), favicon_id, desired_size, results), base::Bind(&RunWithFaviconResults, callback, base::Owned(results))); } base::CancelableTaskTracker::TaskId HistoryService::UpdateFaviconMappingsAndFetch( const GURL& page_url, const std::vector<GURL>& icon_urls, int icon_types, const std::vector<int>& desired_sizes, const favicon_base::FaviconResultsCallback& callback, base::CancelableTaskTracker* tracker) { DCHECK(thread_) << "History service being called after cleanup"; DCHECK(thread_checker_.CalledOnValidThread()); std::vector<favicon_base::FaviconRawBitmapResult>* results = new std::vector<favicon_base::FaviconRawBitmapResult>(); return tracker->PostTaskAndReply( thread_->task_runner().get(), FROM_HERE, base::Bind(&HistoryBackend::UpdateFaviconMappingsAndFetch, history_backend_.get(), page_url, icon_urls, icon_types, desired_sizes, results), base::Bind(&RunWithFaviconResults, callback, base::Owned(results))); } void HistoryService::MergeFavicon( const GURL& page_url, const GURL& icon_url, favicon_base::IconType icon_type, scoped_refptr<base::RefCountedMemory> bitmap_data, const gfx::Size& pixel_size) { DCHECK(thread_) << "History service being called after cleanup"; DCHECK(thread_checker_.CalledOnValidThread()); if (history_client_ && !history_client_->CanAddURL(page_url)) return; ScheduleTask( PRIORITY_NORMAL, base::Bind(&HistoryBackend::MergeFavicon, history_backend_.get(), page_url, icon_url, icon_type, bitmap_data, pixel_size)); } void HistoryService::SetFavicons(const GURL& page_url, favicon_base::IconType icon_type, const GURL& icon_url, const std::vector<SkBitmap>& bitmaps) { DCHECK(thread_) << "History service being called after cleanup"; DCHECK(thread_checker_.CalledOnValidThread()); if (history_client_ && !history_client_->CanAddURL(page_url)) return; ScheduleTask(PRIORITY_NORMAL, base::Bind(&HistoryBackend::SetFavicons, history_backend_.get(), page_url, icon_type, icon_url, bitmaps)); } void HistoryService::SetFaviconsOutOfDateForPage(const GURL& page_url) { DCHECK(thread_) << "History service being called after cleanup"; DCHECK(thread_checker_.CalledOnValidThread()); ScheduleTask(PRIORITY_NORMAL, base::Bind(&HistoryBackend::SetFaviconsOutOfDateForPage, history_backend_.get(), page_url)); } void HistoryService::SetImportedFavicons( const favicon_base::FaviconUsageDataList& favicon_usage) { DCHECK(thread_) << "History service being called after cleanup"; DCHECK(thread_checker_.CalledOnValidThread()); ScheduleTask(PRIORITY_NORMAL, base::Bind(&HistoryBackend::SetImportedFavicons, history_backend_.get(), favicon_usage)); } base::CancelableTaskTracker::TaskId HistoryService::QueryURL( const GURL& url, bool want_visits, const QueryURLCallback& callback, base::CancelableTaskTracker* tracker) { DCHECK(thread_) << "History service being called after cleanup"; DCHECK(thread_checker_.CalledOnValidThread()); QueryURLResult* query_url_result = new QueryURLResult(); return tracker->PostTaskAndReply( thread_->task_runner().get(), FROM_HERE, base::Bind(&HistoryBackend::QueryURL, history_backend_.get(), url, want_visits, base::Unretained(query_url_result)), base::Bind(&RunWithQueryURLResult, callback, base::Owned(query_url_result))); } // Statistics ------------------------------------------------------------------ base::CancelableTaskTracker::TaskId HistoryService::GetHistoryCount( const Time& begin_time, const Time& end_time, const GetHistoryCountCallback& callback, base::CancelableTaskTracker* tracker) { DCHECK(thread_) << "History service being called after cleanup"; DCHECK(thread_checker_.CalledOnValidThread()); return tracker->PostTaskAndReplyWithResult( thread_->task_runner().get(), FROM_HERE, base::Bind(&HistoryBackend::GetHistoryCount, history_backend_.get(), begin_time, end_time), callback); } // Downloads ------------------------------------------------------------------- // Handle creation of a download by creating an entry in the history service's // 'downloads' table. void HistoryService::CreateDownload( const DownloadRow& create_info, const HistoryService::DownloadCreateCallback& callback) { DCHECK(thread_) << "History service being called after cleanup"; DCHECK(thread_checker_.CalledOnValidThread()); PostTaskAndReplyWithResult(thread_->task_runner().get(), FROM_HERE, base::Bind(&HistoryBackend::CreateDownload, history_backend_.get(), create_info), callback); } void HistoryService::GetNextDownloadId(const DownloadIdCallback& callback) { DCHECK(thread_) << "History service being called after cleanup"; DCHECK(thread_checker_.CalledOnValidThread()); PostTaskAndReplyWithResult( thread_->task_runner().get(), FROM_HERE, base::Bind(&HistoryBackend::GetNextDownloadId, history_backend_.get()), callback); } // Handle queries for a list of all downloads in the history database's // 'downloads' table. void HistoryService::QueryDownloads(const DownloadQueryCallback& callback) { DCHECK(thread_) << "History service being called after cleanup"; DCHECK(thread_checker_.CalledOnValidThread()); std::vector<DownloadRow>* rows = new std::vector<DownloadRow>(); scoped_ptr<std::vector<DownloadRow>> scoped_rows(rows); // Beware! The first Bind() does not simply |scoped_rows.get()| because // base::Passed(&scoped_rows) nullifies |scoped_rows|, and compilers do not // guarantee that the first Bind's arguments are evaluated before the second // Bind's arguments. thread_->task_runner()->PostTaskAndReply( FROM_HERE, base::Bind(&HistoryBackend::QueryDownloads, history_backend_.get(), rows), base::Bind(callback, base::Passed(&scoped_rows))); } // Handle updates for a particular download. This is a 'fire and forget' // operation, so we don't need to be called back. void HistoryService::UpdateDownload(const DownloadRow& data) { DCHECK(thread_) << "History service being called after cleanup"; DCHECK(thread_checker_.CalledOnValidThread()); ScheduleTask(PRIORITY_NORMAL, base::Bind(&HistoryBackend::UpdateDownload, history_backend_.get(), data)); } void HistoryService::RemoveDownloads(const std::set<uint32_t>& ids) { DCHECK(thread_) << "History service being called after cleanup"; DCHECK(thread_checker_.CalledOnValidThread()); ScheduleTask(PRIORITY_NORMAL, base::Bind(&HistoryBackend::RemoveDownloads, history_backend_.get(), ids)); } base::CancelableTaskTracker::TaskId HistoryService::QueryHistory( const base::string16& text_query, const QueryOptions& options, const QueryHistoryCallback& callback, base::CancelableTaskTracker* tracker) { DCHECK(thread_) << "History service being called after cleanup"; DCHECK(thread_checker_.CalledOnValidThread()); QueryResults* query_results = new QueryResults(); return tracker->PostTaskAndReply( thread_->task_runner().get(), FROM_HERE, base::Bind(&HistoryBackend::QueryHistory, history_backend_.get(), text_query, options, base::Unretained(query_results)), base::Bind(callback, base::Owned(query_results))); } base::CancelableTaskTracker::TaskId HistoryService::QueryRedirectsFrom( const GURL& from_url, const QueryRedirectsCallback& callback, base::CancelableTaskTracker* tracker) { DCHECK(thread_) << "History service being called after cleanup"; DCHECK(thread_checker_.CalledOnValidThread()); RedirectList* result = new RedirectList(); return tracker->PostTaskAndReply( thread_->task_runner().get(), FROM_HERE, base::Bind(&HistoryBackend::QueryRedirectsFrom, history_backend_.get(), from_url, base::Unretained(result)), base::Bind(callback, base::Owned(result))); } base::CancelableTaskTracker::TaskId HistoryService::QueryRedirectsTo( const GURL& to_url, const QueryRedirectsCallback& callback, base::CancelableTaskTracker* tracker) { DCHECK(thread_) << "History service being called after cleanup"; DCHECK(thread_checker_.CalledOnValidThread()); RedirectList* result = new RedirectList(); return tracker->PostTaskAndReply( thread_->task_runner().get(), FROM_HERE, base::Bind(&HistoryBackend::QueryRedirectsTo, history_backend_.get(), to_url, base::Unretained(result)), base::Bind(callback, base::Owned(result))); } base::CancelableTaskTracker::TaskId HistoryService::GetVisibleVisitCountToHost( const GURL& url, const GetVisibleVisitCountToHostCallback& callback, base::CancelableTaskTracker* tracker) { DCHECK(thread_) << "History service being called after cleanup"; DCHECK(thread_checker_.CalledOnValidThread()); VisibleVisitCountToHostResult* result = new VisibleVisitCountToHostResult(); return tracker->PostTaskAndReply( thread_->task_runner().get(), FROM_HERE, base::Bind(&HistoryBackend::GetVisibleVisitCountToHost, history_backend_.get(), url, base::Unretained(result)), base::Bind(&RunWithVisibleVisitCountToHostResult, callback, base::Owned(result))); } base::CancelableTaskTracker::TaskId HistoryService::QueryMostVisitedURLs( int result_count, int days_back, const QueryMostVisitedURLsCallback& callback, base::CancelableTaskTracker* tracker) { DCHECK(thread_) << "History service being called after cleanup"; DCHECK(thread_checker_.CalledOnValidThread()); MostVisitedURLList* result = new MostVisitedURLList(); return tracker->PostTaskAndReply( thread_->task_runner().get(), FROM_HERE, base::Bind(&HistoryBackend::QueryMostVisitedURLs, history_backend_.get(), result_count, days_back, base::Unretained(result)), base::Bind(callback, base::Owned(result))); } void HistoryService::Cleanup() { DCHECK(thread_checker_.CalledOnValidThread()); if (!thread_) { // We've already cleaned up. return; } NotifyHistoryServiceBeingDeleted(); weak_ptr_factory_.InvalidateWeakPtrs(); // Inform the HistoryClient that we are shuting down. if (history_client_) history_client_->Shutdown(); // Unload the backend. if (history_backend_.get()) { // Get rid of the in-memory backend. in_memory_backend_.reset(); // The backend's destructor must run on the history thread since it is not // threadsafe. So this thread must not be the last thread holding a // reference to the backend, or a crash could happen. // // We have a reference to the history backend. There is also an extra // reference held by our delegate installed in the backend, which // HistoryBackend::Closing will release. This means if we scheduled a call // to HistoryBackend::Closing and *then* released our backend reference, // there will be a race between us and the backend's Closing function to see // who is the last holder of a reference. If the backend thread's Closing // manages to run before we release our backend refptr, the last reference // will be held by this thread and the destructor will be called from here. // // Therefore, we create a closure to run the Closing operation first. This // holds a reference to the backend. Then we release our reference, then we // schedule the task to run. After the task runs, it will delete its // reference from the history thread, ensuring everything works properly. // // TODO(ajwong): Cleanup HistoryBackend lifetime issues. // See http://crbug.com/99767. history_backend_->AddRef(); base::Closure closing_task = base::Bind(&HistoryBackend::Closing, history_backend_.get()); ScheduleTask(PRIORITY_NORMAL, closing_task); closing_task.Reset(); HistoryBackend* raw_ptr = history_backend_.get(); history_backend_ = nullptr; thread_->message_loop()->ReleaseSoon(FROM_HERE, raw_ptr); } // Delete the thread, which joins with the background thread. We defensively // nullptr the pointer before deleting it in case somebody tries to use it // during shutdown, but this shouldn't happen. base::Thread* thread = thread_; thread_ = nullptr; delete thread; } bool HistoryService::Init( bool no_db, const HistoryDatabaseParams& history_database_params) { TRACE_EVENT0("browser,startup", "HistoryService::Init") SCOPED_UMA_HISTOGRAM_TIMER("History.HistoryServiceInitTime"); DCHECK(thread_) << "History service being called after cleanup"; DCHECK(thread_checker_.CalledOnValidThread()); base::Thread::Options options; options.timer_slack = base::TIMER_SLACK_MAXIMUM; if (!thread_->StartWithOptions(options)) { Cleanup(); return false; } // Create the history backend. scoped_refptr<HistoryBackend> backend(new HistoryBackend( new BackendDelegate(weak_ptr_factory_.GetWeakPtr(), base::ThreadTaskRunnerHandle::Get()), history_client_ ? history_client_->CreateBackendClient() : nullptr, thread_->task_runner())); history_backend_.swap(backend); ScheduleTask(PRIORITY_UI, base::Bind(&HistoryBackend::Init, history_backend_.get(), no_db, history_database_params)); if (visit_delegate_ && !visit_delegate_->Init(this)) return false; if (history_client_) history_client_->OnHistoryServiceCreated(this); return true; } void HistoryService::ScheduleAutocomplete( const base::Callback<void(HistoryBackend*, URLDatabase*)>& callback) { DCHECK(thread_checker_.CalledOnValidThread()); ScheduleTask(PRIORITY_UI, base::Bind(&HistoryBackend::ScheduleAutocomplete, history_backend_.get(), callback)); } void HistoryService::ScheduleTask(SchedulePriority priority, const base::Closure& task) { DCHECK(thread_checker_.CalledOnValidThread()); CHECK(thread_); CHECK(thread_->message_loop()); // TODO(brettw): Do prioritization. thread_->task_runner()->PostTask(FROM_HERE, task); } base::WeakPtr<HistoryService> HistoryService::AsWeakPtr() { DCHECK(thread_checker_.CalledOnValidThread()); return weak_ptr_factory_.GetWeakPtr(); } syncer::SyncMergeResult HistoryService::MergeDataAndStartSyncing( syncer::ModelType type, const syncer::SyncDataList& initial_sync_data, scoped_ptr<syncer::SyncChangeProcessor> sync_processor, scoped_ptr<syncer::SyncErrorFactory> error_handler) { DCHECK(thread_checker_.CalledOnValidThread()); DCHECK_EQ(type, syncer::HISTORY_DELETE_DIRECTIVES); delete_directive_handler_.Start(this, initial_sync_data, std::move(sync_processor)); return syncer::SyncMergeResult(type); } void HistoryService::StopSyncing(syncer::ModelType type) { DCHECK(thread_checker_.CalledOnValidThread()); DCHECK_EQ(type, syncer::HISTORY_DELETE_DIRECTIVES); delete_directive_handler_.Stop(); } syncer::SyncDataList HistoryService::GetAllSyncData( syncer::ModelType type) const { DCHECK(thread_checker_.CalledOnValidThread()); DCHECK_EQ(type, syncer::HISTORY_DELETE_DIRECTIVES); // TODO(akalin): Keep track of existing delete directives. return syncer::SyncDataList(); } syncer::SyncError HistoryService::ProcessSyncChanges( const tracked_objects::Location& from_here, const syncer::SyncChangeList& change_list) { delete_directive_handler_.ProcessSyncChanges(this, change_list); return syncer::SyncError(); } syncer::SyncError HistoryService::ProcessLocalDeleteDirective( const sync_pb::HistoryDeleteDirectiveSpecifics& delete_directive) { DCHECK(thread_checker_.CalledOnValidThread()); return delete_directive_handler_.ProcessLocalDeleteDirective( delete_directive); } void HistoryService::SetInMemoryBackend( scoped_ptr<InMemoryHistoryBackend> mem_backend) { DCHECK(thread_checker_.CalledOnValidThread()); DCHECK(!in_memory_backend_) << "Setting mem DB twice"; in_memory_backend_.reset(mem_backend.release()); // The database requires additional initialization once we own it. in_memory_backend_->AttachToHistoryService(this); } void HistoryService::NotifyProfileError(sql::InitStatus init_status) { DCHECK(thread_checker_.CalledOnValidThread()); if (history_client_) history_client_->NotifyProfileError(init_status); } void HistoryService::DeleteURL(const GURL& url) { DCHECK(thread_) << "History service being called after cleanup"; DCHECK(thread_checker_.CalledOnValidThread()); // We will update the visited links when we observe the delete notifications. ScheduleTask(PRIORITY_NORMAL, base::Bind(&HistoryBackend::DeleteURL, history_backend_.get(), url)); } void HistoryService::DeleteURLsForTest(const std::vector<GURL>& urls) { DCHECK(thread_) << "History service being called after cleanup"; DCHECK(thread_checker_.CalledOnValidThread()); // We will update the visited links when we observe the delete // notifications. ScheduleTask(PRIORITY_NORMAL, base::Bind(&HistoryBackend::DeleteURLs, history_backend_.get(), urls)); } void HistoryService::ExpireHistoryBetween( const std::set<GURL>& restrict_urls, Time begin_time, Time end_time, const base::Closure& callback, base::CancelableTaskTracker* tracker) { DCHECK(thread_) << "History service being called after cleanup"; DCHECK(thread_checker_.CalledOnValidThread()); tracker->PostTaskAndReply( thread_->task_runner().get(), FROM_HERE, base::Bind(&HistoryBackend::ExpireHistoryBetween, history_backend_, restrict_urls, begin_time, end_time), callback); } void HistoryService::ExpireHistory( const std::vector<ExpireHistoryArgs>& expire_list, const base::Closure& callback, base::CancelableTaskTracker* tracker) { DCHECK(thread_) << "History service being called after cleanup"; DCHECK(thread_checker_.CalledOnValidThread()); tracker->PostTaskAndReply( thread_->task_runner().get(), FROM_HERE, base::Bind(&HistoryBackend::ExpireHistory, history_backend_, expire_list), callback); } void HistoryService::ExpireLocalAndRemoteHistoryBetween( WebHistoryService* web_history, const std::set<GURL>& restrict_urls, Time begin_time, Time end_time, const base::Closure& callback, base::CancelableTaskTracker* tracker) { // TODO(dubroy): This should be factored out into a separate class that // dispatches deletions to the proper places. if (web_history) { // TODO(dubroy): This API does not yet support deletion of specific URLs. DCHECK(restrict_urls.empty()); delete_directive_handler_.CreateDeleteDirectives(std::set<int64_t>(), begin_time, end_time); // Attempt online deletion from the history server, but ignore the result. // Deletion directives ensure that the results will eventually be deleted. // // TODO(davidben): |callback| should not run until this operation completes // too. web_history->ExpireHistoryBetween(restrict_urls, begin_time, end_time, base::Bind(&ExpireWebHistoryComplete)); } ExpireHistoryBetween(restrict_urls, begin_time, end_time, callback, tracker); } void HistoryService::OnDBLoaded() { DCHECK(thread_checker_.CalledOnValidThread()); backend_loaded_ = true; NotifyHistoryServiceLoaded(); } bool HistoryService::GetRowForURL(const GURL& url, URLRow* url_row) { DCHECK(thread_checker_.CalledOnValidThread()); URLDatabase* db = InMemoryDatabase(); return db && (db->GetRowForURL(url, url_row) != 0); } void HistoryService::NotifyURLVisited(ui::PageTransition transition, const URLRow& row, const RedirectList& redirects, base::Time visit_time) { DCHECK(thread_checker_.CalledOnValidThread()); FOR_EACH_OBSERVER(HistoryServiceObserver, observers_, OnURLVisited(this, transition, row, redirects, visit_time)); } void HistoryService::NotifyURLsModified(const URLRows& changed_urls) { DCHECK(thread_checker_.CalledOnValidThread()); FOR_EACH_OBSERVER(HistoryServiceObserver, observers_, OnURLsModified(this, changed_urls)); } void HistoryService::NotifyURLsDeleted(bool all_history, bool expired, const URLRows& deleted_rows, const std::set<GURL>& favicon_urls) { DCHECK(thread_checker_.CalledOnValidThread()); if (!thread_) return; // Inform the VisitDelegate of the deleted URLs. We will inform the delegate // of added URLs as soon as we get the add notification (we don't have to wait // for the backend, which allows us to be faster to update the state). // // For deleted URLs, we don't typically know what will be deleted since // delete notifications are by time. We would also like to be more // respectful of privacy and never tell the user something is gone when it // isn't. Therefore, we update the delete URLs after the fact. if (visit_delegate_) { if (all_history) { visit_delegate_->DeleteAllURLs(); } else { std::vector<GURL> urls; urls.reserve(deleted_rows.size()); for (const auto& row : deleted_rows) urls.push_back(row.url()); visit_delegate_->DeleteURLs(urls); } } FOR_EACH_OBSERVER( HistoryServiceObserver, observers_, OnURLsDeleted(this, all_history, expired, deleted_rows, favicon_urls)); } void HistoryService::NotifyHistoryServiceLoaded() { DCHECK(thread_checker_.CalledOnValidThread()); FOR_EACH_OBSERVER(HistoryServiceObserver, observers_, OnHistoryServiceLoaded(this)); } void HistoryService::NotifyHistoryServiceBeingDeleted() { DCHECK(thread_checker_.CalledOnValidThread()); FOR_EACH_OBSERVER(HistoryServiceObserver, observers_, HistoryServiceBeingDeleted(this)); } void HistoryService::NotifyKeywordSearchTermUpdated( const URLRow& row, KeywordID keyword_id, const base::string16& term) { DCHECK(thread_checker_.CalledOnValidThread()); FOR_EACH_OBSERVER(HistoryServiceObserver, observers_, OnKeywordSearchTermUpdated(this, row, keyword_id, term)); } void HistoryService::NotifyKeywordSearchTermDeleted(URLID url_id) { DCHECK(thread_checker_.CalledOnValidThread()); FOR_EACH_OBSERVER(HistoryServiceObserver, observers_, OnKeywordSearchTermDeleted(this, url_id)); } scoped_ptr<base::CallbackList<void(const std::set<GURL>&, const GURL&)>::Subscription> HistoryService::AddFaviconsChangedCallback( const HistoryService::OnFaviconsChangedCallback& callback) { DCHECK(thread_checker_.CalledOnValidThread()); return favicon_changed_callback_list_.Add(callback); } void HistoryService::NotifyFaviconsChanged(const std::set<GURL>& page_urls, const GURL& icon_url) { DCHECK(thread_checker_.CalledOnValidThread()); favicon_changed_callback_list_.Notify(page_urls, icon_url); } } // namespace history
{ "content_hash": "13dcd0e3cd8108ecf38b109638e3580f", "timestamp": "", "source": "github", "line_count": 1117, "max_line_length": 80, "avg_line_length": 40.630259623992835, "alnum_prop": 0.6734091309712674, "repo_name": "was4444/chromium.src", "id": "557a1693c0b450705bc1cd45eaddf6c503076515", "size": "47923", "binary": false, "copies": "1", "ref": "refs/heads/nw15", "path": "components/history/core/browser/history_service.cc", "mode": "33188", "license": "bsd-3-clause", "language": [], "symlink_target": "" }
package org.apache.causeway.extensions.secman.applib.user.dom; import java.util.Collection; import java.util.Collections; import java.util.Objects; import java.util.Optional; import java.util.function.Consumer; import javax.inject.Inject; import javax.inject.Provider; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Qualifier; import org.springframework.lang.Nullable; import org.springframework.security.crypto.password.PasswordEncoder; import org.apache.causeway.applib.query.Query; import org.apache.causeway.applib.services.eventbus.EventBusService; import org.apache.causeway.applib.services.factory.FactoryService; import org.apache.causeway.applib.services.queryresultscache.QueryResultsCache; import org.apache.causeway.applib.services.repository.RepositoryService; import org.apache.causeway.commons.internal.base._Casts; import org.apache.causeway.commons.internal.base._NullSafe; import org.apache.causeway.commons.internal.collections._Sets; import org.apache.causeway.core.config.CausewayConfiguration; import org.apache.causeway.extensions.secman.applib.role.dom.ApplicationRole; import org.apache.causeway.extensions.secman.applib.tenancy.dom.ApplicationTenancy; import org.apache.causeway.extensions.secman.applib.user.dom.mixins.ApplicationUser_lock; import org.apache.causeway.extensions.secman.applib.user.dom.mixins.ApplicationUser_unlock; import org.apache.causeway.extensions.secman.applib.user.events.UserCreatedEvent; import org.apache.causeway.extensions.secman.applib.util.RegexReplacer; import lombok.NonNull; import lombok.val; /** * * @since 2.0 {@index} */ public class ApplicationUserRepositoryAbstract<U extends ApplicationUser> implements ApplicationUserRepository { @Inject private FactoryService factoryService; @Inject private RepositoryService repository; @Inject protected CausewayConfiguration config; @Inject private EventBusService eventBusService; @Inject private RegexReplacer regexReplacer; @Inject private Provider<QueryResultsCache> queryResultsCacheProvider; // empty if no candidate is available @Autowired(required = false) @Qualifier("secman") PasswordEncoder passwordEncoder; private final Class<U> applicationUserClass; protected ApplicationUserRepositoryAbstract(final Class<U> applicationUserClass) { this.applicationUserClass = applicationUserClass; } @Override public ApplicationUser newApplicationUser() { return factoryService.detachedEntity(this.applicationUserClass); } // -- findOrCreateUserByUsername (programmatic) /** * Uses the {@link QueryResultsCache} in order to support * multiple lookups from <code>org.apache.causeway.extensions.secman.jdo.app.user.UserPermissionViewModel</code>. * <p> * <p> * If the user does not exist, it will be automatically created. * </p> */ @Override public ApplicationUser findOrCreateUserByUsername( final String username) { // slightly unusual to cache a function that modifies state, but safe because this is idempotent return queryResultsCacheProvider.get().execute(()-> findByUsername(username).orElseGet(()->newDelegateUser(username, null)), ApplicationUserRepositoryAbstract.class, "findOrCreateUserByUsername", username); } // -- findByUsername public Optional<ApplicationUser> findByUsernameCached(final String username) { return queryResultsCacheProvider.get().execute(this::findByUsername, ApplicationUserRepositoryAbstract.class, "findByUsernameCached", username); } @Override public Optional<ApplicationUser> findByUsername(final String username) { return _Casts.uncheckedCast( repository.uniqueMatch(Query.named(this.applicationUserClass, ApplicationUser.Nq.FIND_BY_USERNAME) .withParameter("username", username)) ); } // -- findByEmailAddress (programmatic) public Optional<ApplicationUser> findByEmailAddressCached(final String emailAddress) { return queryResultsCacheProvider.get().execute(this::findByEmailAddress, ApplicationUserRepositoryAbstract.class, "findByEmailAddressCached", emailAddress); } @Override public Optional<ApplicationUser> findByEmailAddress(final String emailAddress) { return _Casts.uncheckedCast( repository.uniqueMatch(Query.named(this.applicationUserClass, ApplicationUser.Nq.FIND_BY_EMAIL_ADDRESS) .withParameter("emailAddress", emailAddress)) ); } // -- findByName @Override public Collection<ApplicationUser> find(final @Nullable String _search) { val regex = regexReplacer.asRegex(_search); return repository.allMatches(Query.named(this.applicationUserClass, ApplicationUser.Nq.FIND) .withParameter("regex", regex)) .stream() .collect(_Sets.toUnmodifiableSorted()); } // -- allUsers @Override public Collection<ApplicationUser> findByAtPath(final String atPath) { return repository.allMatches(Query.named(this.applicationUserClass, ApplicationUser.Nq.FIND_BY_ATPATH) .withParameter("atPath", atPath)) .stream() .collect(_Sets.toUnmodifiableSorted()); } @Override public Collection<ApplicationUser> findByRole(final ApplicationRole role) { return _NullSafe.stream(role.getUsers()) .collect(_Sets.toUnmodifiableSorted()); } @Override public Collection<ApplicationUser> findByTenancy( final @NonNull ApplicationTenancy genericTenancy) { return findByAtPath(genericTenancy.getPath()) .stream() .collect(_Sets.toUnmodifiableSorted()); } // -- allUsers @Override public Collection<ApplicationUser> allUsers() { return repository.allInstances(this.applicationUserClass) .stream() .collect(_Sets.toUnmodifiableSorted()); } @Override public Collection<ApplicationUser> findMatching(final String search) { if (search != null && search.length() > 0) { return find(search); } return Collections.emptySortedSet(); } // -- UPDATE USER STATE @Override public void enable(final ApplicationUser user) { if(user.getStatus() != ApplicationUserStatus.UNLOCKED) { factoryService.mixin(ApplicationUser_unlock.class, user) .act(); } } @Override public void disable(final ApplicationUser user) { if(user.getStatus() != ApplicationUserStatus.LOCKED) { factoryService.mixin(ApplicationUser_lock.class, user) .act(); } } @Override public boolean isAdminUser(final ApplicationUser user) { return Objects.equals( config.getExtensions().getSecman().getSeed().getAdmin().getUserName(), user.getName()); } @Override public ApplicationUser newUser( @NonNull final String username, @Nullable final AccountType accountType, final Consumer<ApplicationUser> beforePersist) { val user = newApplicationUser(); user.setUsername(username); user.setAccountType(accountType); beforePersist.accept(user); if(user.getAccountType().equals(AccountType.LOCAL)) { // keep null when is set for status in accept() call above } else { user.setStatus(ApplicationUserStatus.LOCKED); } repository.persistAndFlush(user); eventBusService.post(UserCreatedEvent.of(user)); return user; } @Override public boolean updatePassword( final ApplicationUser user, final String password) { // in case called programmatically if(!isPasswordFeatureEnabled(user)) { return false; } user.setEncryptedPassword(passwordEncoder.encode(password)); repository.persistAndFlush(user); return true; } @Override public boolean isPasswordFeatureEnabled(final ApplicationUser user) { return user.isLocalAccount() && passwordEncoder != null; } }
{ "content_hash": "4b625c7c13ac34f4d90ac22a21444fe3", "timestamp": "", "source": "github", "line_count": 234, "max_line_length": 119, "avg_line_length": 35.81196581196581, "alnum_prop": 0.701073985680191, "repo_name": "apache/isis", "id": "7357c760eeb38878f73b4f3a2531ca94962fe8ab", "size": "9205", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "extensions/security/secman/applib/src/main/java/org/apache/causeway/extensions/secman/applib/user/dom/ApplicationUserRepositoryAbstract.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "CSS", "bytes": "152495" }, { "name": "Clean", "bytes": "8063" }, { "name": "Gherkin", "bytes": "412" }, { "name": "Groovy", "bytes": "15585" }, { "name": "HTML", "bytes": "268010" }, { "name": "Handlebars", "bytes": "337" }, { "name": "Java", "bytes": "17242597" }, { "name": "JavaScript", "bytes": "271368" }, { "name": "Kotlin", "bytes": "1913258" }, { "name": "Rich Text Format", "bytes": "2150674" }, { "name": "Shell", "bytes": "102821" }, { "name": "TypeScript", "bytes": "275" } ], "symlink_target": "" }
Yet another jQuery HTML WYSIWYG plugin As the following image shows, Htmle has the a set of most common editing functions. Htmle can be customized to show only the required controls. It doesn't have a heavy design theme, so that you can easily alter its css to fit into the theme of your website. ![Htmle Print Screen](https://raw.githubusercontent.com/mhsallam/htmle/master/htmle.jpg) ## Prerequisites 1. font-awesome: for Htmle icons 2. bootstrap: for add-link modal 3. jQuery ## Example Add a <textarea id="editing-area"></textarea> element in you htmle page, and then execute the following javascript code: ```javascript $(document).ready(function () { $('#editing-area').htmle(); }); ``` ## Note More ways to utilize this plugin will be published soon..
{ "content_hash": "9ff50c6266bb757ed07762bb40b266f8", "timestamp": "", "source": "github", "line_count": 28, "max_line_length": 257, "avg_line_length": 27.714285714285715, "alnum_prop": 0.7422680412371134, "repo_name": "mhsallam/htmle", "id": "dc1a4e667ba8eff7ceb02844ae4c8d936606dcdf", "size": "784", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "README.md", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "3757" }, { "name": "HTML", "bytes": "995" }, { "name": "JavaScript", "bytes": "30853" } ], "symlink_target": "" }
<!-- HTML header for doxygen 1.8.6--> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv="Content-Type" content="text/xhtml;charset=UTF-8"/> <meta http-equiv="X-UA-Compatible" content="IE=9"/> <meta name="generator" content="Doxygen 1.8.12"/> <title>OpenCV: Member List</title> <link href="../../opencv.ico" rel="shortcut icon" type="image/x-icon" /> <link href="../../tabs.css" rel="stylesheet" type="text/css"/> <script type="text/javascript" src="../../jquery.js"></script> <script type="text/javascript" src="../../dynsections.js"></script> <link href="../../search/search.css" rel="stylesheet" type="text/css"/> <script type="text/javascript" src="../../search/searchdata.js"></script> <script type="text/javascript" src="../../search/search.js"></script> <script type="text/x-mathjax-config"> MathJax.Hub.Config({ extensions: ["tex2jax.js", "TeX/AMSmath.js", "TeX/AMSsymbols.js"], jax: ["input/TeX","output/HTML-CSS"], }); //<![CDATA[ MathJax.Hub.Config( { TeX: { Macros: { matTT: [ "\\[ \\left|\\begin{array}{ccc} #1 & #2 & #3\\\\ #4 & #5 & #6\\\\ #7 & #8 & #9 \\end{array}\\right| \\]", 9], fork: ["\\left\\{ \\begin{array}{l l} #1 & \\mbox{#2}\\\\ #3 & \\mbox{#4}\\\\ \\end{array} \\right.", 4], forkthree: ["\\left\\{ \\begin{array}{l l} #1 & \\mbox{#2}\\\\ #3 & \\mbox{#4}\\\\ #5 & \\mbox{#6}\\\\ \\end{array} \\right.", 6], vecthree: ["\\begin{bmatrix} #1\\\\ #2\\\\ #3 \\end{bmatrix}", 3], vecthreethree: ["\\begin{bmatrix} #1 & #2 & #3\\\\ #4 & #5 & #6\\\\ #7 & #8 & #9 \\end{bmatrix}", 9], hdotsfor: ["\\dots", 1], mathbbm: ["\\mathbb{#1}", 1], bordermatrix: ["\\matrix{#1}", 1] } } } ); //]]> </script><script type="text/javascript" src="http://cdn.mathjax.org/mathjax/latest/MathJax.js"></script> <link href="../../doxygen.css" rel="stylesheet" type="text/css" /> <link href="../../stylesheet.css" rel="stylesheet" type="text/css"/> </head> <body> <div id="top"><!-- do not remove this div, it is closed by doxygen! --> <div id="titlearea"> <!--#include virtual="/google-search.html"--> <table cellspacing="0" cellpadding="0"> <tbody> <tr style="height: 56px;"> <td id="projectlogo"><img alt="Logo" src="../../opencv-logo-small.png"/></td> <td style="padding-left: 0.5em;"> <div id="projectname">OpenCV &#160;<span id="projectnumber">3.2.0</span> </div> <div id="projectbrief">Open Source Computer Vision</div> </td> </tr> </tbody> </table> </div> <script type="text/javascript"> //<![CDATA[ function getLabelName(innerHTML) { var str = innerHTML.toLowerCase(); // Replace all '+' with 'p' str = str.split('+').join('p'); // Replace all ' ' with '_' str = str.split(' ').join('_'); // Replace all '#' with 'sharp' str = str.split('#').join('sharp'); // Replace other special characters with 'ascii' + code for (var i = 0; i < str.length; i++) { var charCode = str.charCodeAt(i); if (!(charCode == 95 || (charCode > 96 && charCode < 123) || (charCode > 47 && charCode < 58))) str = str.substr(0, i) + 'ascii' + charCode + str.substr(i + 1); } return str; } function addToggle() { var $getDiv = $('div.newInnerHTML').last(); var buttonName = $getDiv.html(); var label = getLabelName(buttonName.trim()); $getDiv.attr("title", label); $getDiv.hide(); $getDiv = $getDiv.next(); $getDiv.attr("class", "toggleable_div label_" + label); $getDiv.hide(); } //]]> </script> <!-- end header part --> <!-- Generated by Doxygen 1.8.12 --> <script type="text/javascript"> var searchBox = new SearchBox("searchBox", "../../search",false,'Search'); </script> <script type="text/javascript" src="../../menudata.js"></script> <script type="text/javascript" src="../../menu.js"></script> <script type="text/javascript"> $(function() { initMenu('../../',true,false,'search.php','Search'); $(document).ready(function() { init_search(); }); }); </script> <div id="main-nav"></div> <!-- window showing the filter options --> <div id="MSearchSelectWindow" onmouseover="return searchBox.OnSearchSelectShow()" onmouseout="return searchBox.OnSearchSelectHide()" onkeydown="return searchBox.OnSearchSelectKey(event)"> </div> <!-- iframe showing the search results (closed by default) --> <div id="MSearchResultsWindow"> <iframe src="javascript:void(0)" frameborder="0" name="MSearchResults" id="MSearchResults"> </iframe> </div> <div id="nav-path" class="navpath"> <ul> <li class="navelem"><a class="el" href="../../d2/d75/namespacecv.html">cv</a></li><li class="navelem"><a class="el" href="../../df/d1d/namespacecv_1_1cudev.html">cudev</a></li><li class="navelem"><a class="el" href="../../de/dfa/structcv_1_1cudev_1_1minimum_3_01ushort_01_4.html">minimum&lt; ushort &gt;</a></li> </ul> </div> </div><!-- top --> <div class="header"> <div class="headertitle"> <div class="title">cv::cudev::minimum&lt; ushort &gt; Member List</div> </div> </div><!--header--> <div class="contents"> <p>This is the complete list of members for <a class="el" href="../../de/dfa/structcv_1_1cudev_1_1minimum_3_01ushort_01_4.html">cv::cudev::minimum&lt; ushort &gt;</a>, including all inherited members.</p> <table class="directory"> <tr class="even"><td class="entry"><a class="el" href="../../d6/ddf/structcv_1_1cudev_1_1binary__function.html#af7e0b87fad00c320d7b2e271b4798e45">first_argument_type</a> typedef</td><td class="entry"><a class="el" href="../../d6/ddf/structcv_1_1cudev_1_1binary__function.html">cv::cudev::binary_function&lt; ushort, ushort, ushort &gt;</a></td><td class="entry"></td></tr> <tr><td class="entry"><a class="el" href="../../de/dfa/structcv_1_1cudev_1_1minimum_3_01ushort_01_4.html#ac33cd62d0c0ebbeed517eab9d577517d">operator()</a>(ushort a, ushort b) const</td><td class="entry"><a class="el" href="../../de/dfa/structcv_1_1cudev_1_1minimum_3_01ushort_01_4.html">cv::cudev::minimum&lt; ushort &gt;</a></td><td class="entry"></td></tr> <tr class="even"><td class="entry"><a class="el" href="../../d6/ddf/structcv_1_1cudev_1_1binary__function.html#ae95433e072c626bc13222df9ed5124af">result_type</a> typedef</td><td class="entry"><a class="el" href="../../d6/ddf/structcv_1_1cudev_1_1binary__function.html">cv::cudev::binary_function&lt; ushort, ushort, ushort &gt;</a></td><td class="entry"></td></tr> <tr><td class="entry"><a class="el" href="../../d6/ddf/structcv_1_1cudev_1_1binary__function.html#af7915bb2d619d3eb441b231edc33d704">second_argument_type</a> typedef</td><td class="entry"><a class="el" href="../../d6/ddf/structcv_1_1cudev_1_1binary__function.html">cv::cudev::binary_function&lt; ushort, ushort, ushort &gt;</a></td><td class="entry"></td></tr> </table></div><!-- contents --> <!-- HTML footer for doxygen 1.8.6--> <!-- start footer part --> <hr class="footer"/><address class="footer"><small> Generated on Fri Dec 23 2016 13:00:28 for OpenCV by &#160;<a href="http://www.doxygen.org/index.html"> <img class="footer" src="../../doxygen.png" alt="doxygen"/> </a> 1.8.12 </small></address> <script type="text/javascript"> //<![CDATA[ function addButton(label, buttonName) { var b = document.createElement("BUTTON"); b.innerHTML = buttonName; b.setAttribute('class', 'toggleable_button label_' + label); b.onclick = function() { $('.toggleable_button').css({ border: '2px outset', 'border-radius': '4px' }); $('.toggleable_button.label_' + label).css({ border: '2px inset', 'border-radius': '4px' }); $('.toggleable_div').css('display', 'none'); $('.toggleable_div.label_' + label).css('display', 'block'); }; b.style.border = '2px outset'; b.style.borderRadius = '4px'; b.style.margin = '2px'; return b; } function buttonsToAdd($elements, $heading, $type) { if ($elements.length === 0) { $elements = $("" + $type + ":contains(" + $heading.html() + ")").parent().prev("div.newInnerHTML"); } var arr = jQuery.makeArray($elements); var seen = {}; arr.forEach(function(e) { var txt = e.innerHTML; if (!seen[txt]) { $button = addButton(e.title, txt); if (Object.keys(seen).length == 0) { var linebreak1 = document.createElement("br"); var linebreak2 = document.createElement("br"); ($heading).append(linebreak1); ($heading).append(linebreak2); } ($heading).append($button); seen[txt] = true; } }); return; } $("h2").each(function() { $heading = $(this); $smallerHeadings = $(this).nextUntil("h2").filter("h3").add($(this).nextUntil("h2").find("h3")); if ($smallerHeadings.length) { $smallerHeadings.each(function() { var $elements = $(this).nextUntil("h3").filter("div.newInnerHTML"); buttonsToAdd($elements, $(this), "h3"); }); } else { var $elements = $(this).nextUntil("h2").filter("div.newInnerHTML"); buttonsToAdd($elements, $heading, "h2"); } }); $(".toggleable_button").first().click(); var $clickDefault = $('.toggleable_button.label_python').first(); if ($clickDefault.length) { $clickDefault.click(); } $clickDefault = $('.toggleable_button.label_cpp').first(); if ($clickDefault.length) { $clickDefault.click(); } //]]> </script> </body> </html>
{ "content_hash": "9603a7751171c1b45559153178b21d79", "timestamp": "", "source": "github", "line_count": 214, "max_line_length": 374, "avg_line_length": 44.77570093457944, "alnum_prop": 0.604049259027343, "repo_name": "lucasbrsa/OpenCV-3.2", "id": "9d79cc6686971cddefde65a52ab99442fc7d7358", "size": "9582", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "docs/3.2/dd/d19/structcv_1_1cudev_1_1minimum_3_01ushort_01_4-members.html", "mode": "33261", "license": "mit", "language": [ { "name": "C", "bytes": "320592" }, { "name": "C#", "bytes": "12756" }, { "name": "C++", "bytes": "499322" }, { "name": "CMake", "bytes": "244871" }, { "name": "Makefile", "bytes": "344335" }, { "name": "Python", "bytes": "7735" }, { "name": "Visual Basic", "bytes": "13139" } ], "symlink_target": "" }
module MnoEnterprise class Jpi::V1::Impac::DashboardsController < Jpi::V1::BaseResourceController include MnoEnterprise::Concerns::Controllers::Jpi::V1::Impac::DashboardsController end end
{ "content_hash": "cb1597a132b8583d4501800d3df2828a", "timestamp": "", "source": "github", "line_count": 5, "max_line_length": 86, "avg_line_length": 39.4, "alnum_prop": 0.7918781725888325, "repo_name": "maestrano/mno-enterprise", "id": "14e667dbbcad89adb1a3db22358110fa304e8ff0", "size": "197", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "api/app/controllers/mno_enterprise/jpi/v1/impac/dashboards_controller.rb", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "CSS", "bytes": "277763" }, { "name": "CoffeeScript", "bytes": "101017" }, { "name": "HTML", "bytes": "136566" }, { "name": "JavaScript", "bytes": "280731" }, { "name": "Ruby", "bytes": "790255" }, { "name": "Shell", "bytes": "1569" } ], "symlink_target": "" }
execute "set vagrant password" do command "echo 'vagrant:duckduckhack' | sudo chpasswd" action :run end
{ "content_hash": "00938d3981ab9f0999644b74b6772adf", "timestamp": "", "source": "github", "line_count": 4, "max_line_length": 55, "avg_line_length": 27, "alnum_prop": 0.75, "repo_name": "mikedep333/duckpan-vagrant", "id": "0dee298425953ebfe3e71b3804dbff108419b304", "size": "170", "binary": false, "copies": "1", "ref": "refs/heads/duckduckhack-vm", "path": "cookbooks/duckduckhack-vm/recipes/setpassword.rb", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "CSS", "bytes": "2658" }, { "name": "JavaScript", "bytes": "336188" }, { "name": "Ruby", "bytes": "22556" }, { "name": "Shell", "bytes": "3120" }, { "name": "VimL", "bytes": "82" } ], "symlink_target": "" }
<!doctype html> <html lang="en"> <head> <title>Code coverage report for client/model/shared/superclasses/GenericProcess.js</title> <meta charset="utf-8"> <link rel="stylesheet" href="../../../../prettify.css"> <style> body, html { margin:0; padding: 0; } body { font-family: Helvetica Neue, Helvetica,Arial; font-size: 10pt; } div.header, div.footer { background: #eee; padding: 1em; } div.header { z-index: 100; position: fixed; top: 0; border-bottom: 1px solid #666; width: 100%; } div.footer { border-top: 1px solid #666; } div.body { margin-top: 10em; } div.meta { font-size: 90%; text-align: center; } h1, h2, h3 { font-weight: normal; } h1 { font-size: 12pt; } h2 { font-size: 10pt; } pre { font-family: Consolas, Menlo, Monaco, monospace; margin: 0; padding: 0; line-height: 14px; font-size: 14px; -moz-tab-size: 2; -o-tab-size: 2; tab-size: 2; } div.path { font-size: 110%; } div.path a:link, div.path a:visited { color: #000; } table.coverage { border-collapse: collapse; margin:0; padding: 0 } table.coverage td { margin: 0; padding: 0; color: #111; vertical-align: top; } table.coverage td.line-count { width: 50px; text-align: right; padding-right: 5px; } table.coverage td.line-coverage { color: #777 !important; text-align: right; border-left: 1px solid #666; border-right: 1px solid #666; } table.coverage td.text { } table.coverage td span.cline-any { display: inline-block; padding: 0 5px; width: 40px; } table.coverage td span.cline-neutral { background: #eee; } table.coverage td span.cline-yes { background: #b5d592; color: #999; } table.coverage td span.cline-no { background: #fc8c84; } .cstat-yes { color: #111; } .cstat-no { background: #fc8c84; color: #111; } .fstat-no { background: #ffc520; color: #111 !important; } .cbranch-no { background: yellow !important; color: #111; } .cstat-skip { background: #ddd; color: #111; } .fstat-skip { background: #ddd; color: #111 !important; } .cbranch-skip { background: #ddd !important; color: #111; } .missing-if-branch { display: inline-block; margin-right: 10px; position: relative; padding: 0 4px; background: black; color: yellow; } .skip-if-branch { display: none; margin-right: 10px; position: relative; padding: 0 4px; background: #ccc; color: white; } .missing-if-branch .typ, .skip-if-branch .typ { color: inherit !important; } .entity, .metric { font-weight: bold; } .metric { display: inline-block; border: 1px solid #333; padding: 0.3em; background: white; } .metric small { font-size: 80%; font-weight: normal; color: #666; } div.coverage-summary table { border-collapse: collapse; margin: 3em; font-size: 110%; } div.coverage-summary td, div.coverage-summary table th { margin: 0; padding: 0.25em 1em; border-top: 1px solid #666; border-bottom: 1px solid #666; } div.coverage-summary th { text-align: left; border: 1px solid #666; background: #eee; font-weight: normal; } div.coverage-summary th.file { border-right: none !important; } div.coverage-summary th.pic { border-left: none !important; text-align: right; } div.coverage-summary th.pct { border-right: none !important; } div.coverage-summary th.abs { border-left: none !important; text-align: right; } div.coverage-summary td.pct { text-align: right; border-left: 1px solid #666; } div.coverage-summary td.abs { text-align: right; font-size: 90%; color: #444; border-right: 1px solid #666; } div.coverage-summary td.file { text-align: right; border-left: 1px solid #666; white-space: nowrap; } div.coverage-summary td.pic { min-width: 120px !important; } div.coverage-summary a:link { text-decoration: none; color: #000; } div.coverage-summary a:visited { text-decoration: none; color: #333; } div.coverage-summary a:hover { text-decoration: underline; } div.coverage-summary tfoot td { border-top: 1px solid #666; } div.coverage-summary .yui3-datatable-sort-indicator, div.coverage-summary .dummy-sort-indicator { height: 10px; width: 7px; display: inline-block; margin-left: 0.5em; } div.coverage-summary .yui3-datatable-sort-indicator { background: url("http://yui.yahooapis.com/3.6.0/build/datatable-sort/assets/skins/sam/sort-arrow-sprite.png") no-repeat scroll 0 0 transparent; } div.coverage-summary .yui3-datatable-sorted .yui3-datatable-sort-indicator { background-position: 0 -20px; } div.coverage-summary .yui3-datatable-sorted-desc .yui3-datatable-sort-indicator { background-position: 0 -10px; } .high { background: #b5d592 !important; } .medium { background: #ffe87c !important; } .low { background: #fc8c84 !important; } span.cover-fill, span.cover-empty { display:inline-block; border:1px solid #444; background: white; height: 12px; } span.cover-fill { background: #ccc; border-right: 1px solid #444; } span.cover-empty { background: white; border-left: none; } span.cover-full { border-right: none !important; } pre.prettyprint { border: none !important; padding: 0 !important; margin: 0 !important; } .com { color: #999 !important; } .ignore-none { color: #999; font-weight: normal; } </style> </head> <body> <div class="header high"> <h1>Code coverage report for <span class="entity">client/model/shared/superclasses/GenericProcess.js</span></h1> <h2> Statements: <span class="metric">95.24% <small>(40 / 42)</small></span> &nbsp;&nbsp;&nbsp;&nbsp; Branches: <span class="metric">100% <small>(0 / 0)</small></span> &nbsp;&nbsp;&nbsp;&nbsp; Functions: <span class="metric">88.24% <small>(15 / 17)</small></span> &nbsp;&nbsp;&nbsp;&nbsp; Lines: <span class="metric">95.24% <small>(40 / 42)</small></span> &nbsp;&nbsp;&nbsp;&nbsp; Ignored: <span class="metric"><span class="ignore-none">none</span></span> &nbsp;&nbsp;&nbsp;&nbsp; </h2> <div class="path"><a href="../../../../index.html">All files</a> &#187; <a href="index.html">client/model/shared/superclasses/</a> &#187; GenericProcess.js</div> </div> <div class="body"> <pre><table class="coverage"> <tr><td class="line-count">1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129</td><td class="line-coverage"><span class="cline-any cline-neutral">&nbsp;</span> <span class="cline-any cline-neutral">&nbsp;</span> <span class="cline-any cline-neutral">&nbsp;</span> <span class="cline-any cline-neutral">&nbsp;</span> <span class="cline-any cline-neutral">&nbsp;</span> <span class="cline-any cline-neutral">&nbsp;</span> <span class="cline-any cline-neutral">&nbsp;</span> <span class="cline-any cline-neutral">&nbsp;</span> <span class="cline-any cline-neutral">&nbsp;</span> <span class="cline-any cline-neutral">&nbsp;</span> <span class="cline-any cline-neutral">&nbsp;</span> <span class="cline-any cline-neutral">&nbsp;</span> <span class="cline-any cline-neutral">&nbsp;</span> <span class="cline-any cline-neutral">&nbsp;</span> <span class="cline-any cline-neutral">&nbsp;</span> <span class="cline-any cline-neutral">&nbsp;</span> <span class="cline-any cline-neutral">&nbsp;</span> <span class="cline-any cline-neutral">&nbsp;</span> <span class="cline-any cline-neutral">&nbsp;</span> <span class="cline-any cline-neutral">&nbsp;</span> <span class="cline-any cline-neutral">&nbsp;</span> <span class="cline-any cline-neutral">&nbsp;</span> <span class="cline-any cline-neutral">&nbsp;</span> <span class="cline-any cline-neutral">&nbsp;</span> <span class="cline-any cline-neutral">&nbsp;</span> <span class="cline-any cline-neutral">&nbsp;</span> <span class="cline-any cline-neutral">&nbsp;</span> <span class="cline-any cline-neutral">&nbsp;</span> <span class="cline-any cline-neutral">&nbsp;</span> <span class="cline-any cline-neutral">&nbsp;</span> <span class="cline-any cline-neutral">&nbsp;</span> <span class="cline-any cline-yes">1</span> <span class="cline-any cline-neutral">&nbsp;</span> <span class="cline-any cline-yes">7</span> <span class="cline-any cline-yes">7</span> <span class="cline-any cline-yes">7</span> <span class="cline-any cline-yes">7</span> <span class="cline-any cline-yes">7</span> <span class="cline-any cline-yes">7</span> <span class="cline-any cline-yes">7</span> <span class="cline-any cline-yes">7</span> <span class="cline-any cline-neutral">&nbsp;</span> <span class="cline-any cline-yes">1</span> <span class="cline-any cline-yes">1</span> <span class="cline-any cline-neutral">&nbsp;</span> <span class="cline-any cline-neutral">&nbsp;</span> <span class="cline-any cline-yes">1</span> <span class="cline-any cline-yes">1</span> <span class="cline-any cline-neutral">&nbsp;</span> <span class="cline-any cline-neutral">&nbsp;</span> <span class="cline-any cline-yes">1</span> <span class="cline-any cline-yes">1</span> <span class="cline-any cline-neutral">&nbsp;</span> <span class="cline-any cline-neutral">&nbsp;</span> <span class="cline-any cline-yes">1</span> <span class="cline-any cline-yes">1</span> <span class="cline-any cline-neutral">&nbsp;</span> <span class="cline-any cline-neutral">&nbsp;</span> <span class="cline-any cline-yes">1</span> <span class="cline-any cline-yes">1</span> <span class="cline-any cline-neutral">&nbsp;</span> <span class="cline-any cline-neutral">&nbsp;</span> <span class="cline-any cline-yes">1</span> <span class="cline-any cline-yes">1</span> <span class="cline-any cline-neutral">&nbsp;</span> <span class="cline-any cline-neutral">&nbsp;</span> <span class="cline-any cline-yes">1</span> <span class="cline-any cline-yes">1</span> <span class="cline-any cline-neutral">&nbsp;</span> <span class="cline-any cline-neutral">&nbsp;</span> <span class="cline-any cline-yes">1</span> <span class="cline-any cline-yes">1</span> <span class="cline-any cline-neutral">&nbsp;</span> <span class="cline-any cline-neutral">&nbsp;</span> <span class="cline-any cline-yes">1</span> <span class="cline-any cline-yes">1</span> <span class="cline-any cline-neutral">&nbsp;</span> <span class="cline-any cline-neutral">&nbsp;</span> <span class="cline-any cline-yes">1</span> <span class="cline-any cline-yes">1</span> <span class="cline-any cline-neutral">&nbsp;</span> <span class="cline-any cline-neutral">&nbsp;</span> <span class="cline-any cline-yes">1</span> <span class="cline-any cline-yes">1</span> <span class="cline-any cline-neutral">&nbsp;</span> <span class="cline-any cline-neutral">&nbsp;</span> <span class="cline-any cline-yes">1</span> <span class="cline-any cline-yes">1</span> <span class="cline-any cline-neutral">&nbsp;</span> <span class="cline-any cline-neutral">&nbsp;</span> <span class="cline-any cline-neutral">&nbsp;</span> <span class="cline-any cline-neutral">&nbsp;</span> <span class="cline-any cline-yes">1</span> <span class="cline-any cline-yes">1</span> <span class="cline-any cline-neutral">&nbsp;</span> <span class="cline-any cline-neutral">&nbsp;</span> <span class="cline-any cline-yes">1</span> <span class="cline-any cline-yes">1</span> <span class="cline-any cline-neutral">&nbsp;</span> <span class="cline-any cline-neutral">&nbsp;</span> <span class="cline-any cline-yes">1</span> <span class="cline-any cline-no">&nbsp;</span> <span class="cline-any cline-neutral">&nbsp;</span> <span class="cline-any cline-neutral">&nbsp;</span> <span class="cline-any cline-yes">1</span> <span class="cline-any cline-no">&nbsp;</span> <span class="cline-any cline-neutral">&nbsp;</span> <span class="cline-any cline-neutral">&nbsp;</span> <span class="cline-any cline-neutral">&nbsp;</span> <span class="cline-any cline-yes">7</span> <span class="cline-any cline-neutral">&nbsp;</span> <span class="cline-any cline-neutral">&nbsp;</span> <span class="cline-any cline-neutral">&nbsp;</span> <span class="cline-any cline-neutral">&nbsp;</span> <span class="cline-any cline-neutral">&nbsp;</span> <span class="cline-any cline-neutral">&nbsp;</span> <span class="cline-any cline-neutral">&nbsp;</span> <span class="cline-any cline-neutral">&nbsp;</span> <span class="cline-any cline-neutral">&nbsp;</span> <span class="cline-any cline-neutral">&nbsp;</span> <span class="cline-any cline-neutral">&nbsp;</span> <span class="cline-any cline-neutral">&nbsp;</span> <span class="cline-any cline-neutral">&nbsp;</span> <span class="cline-any cline-neutral">&nbsp;</span> <span class="cline-any cline-neutral">&nbsp;</span> <span class="cline-any cline-neutral">&nbsp;</span> <span class="cline-any cline-neutral">&nbsp;</span> <span class="cline-any cline-neutral">&nbsp;</span> <span class="cline-any cline-neutral">&nbsp;</span></td><td class="text"><pre class="prettyprint lang-js"> &nbsp; var GenericProcess = function(){ &nbsp; var isAvailable = undefined; var description = undefined; var publicationDate = undefined; var closingDate = undefined; var name = undefined; var totalSteps = undefined; var idAdminOwner = undefined; var stepsList = undefined; &nbsp; function getIsAvailable(){ return isAvailable; }; function setIsAvailable(newIsAvailable){ isAvailable = newIsAvailable; }; &nbsp; function getDescription(){ return description; }; function setDescription(newDescription){ description = newDescription; }; &nbsp; function getPublicationDate(){ return publicationDate; }; function setPublicationDate(newPublicationDate){ publicationDate = newPublicationDate; }; &nbsp; function getClosingDate(){ return closingDate; }; function setClosingDate(newClosingDate){ closingDate = newClosingDate; }; &nbsp; function getName(){ return name; }; function setName(newName){ name = newName; }; &nbsp; function getTotalSteps(){ return totalSteps; }; function setTotalSteps(newTotalSteps){ totalSteps = newTotalSteps; }; //IdAdminOwner function getIdAdminOwner(){ return idAdminOwner; }; function setIdAdminOwner(newIdAdminOwner){ idAdminOwner = newIdAdminOwner; }; &nbsp; <span class="fstat-no" title="function not covered" > function getStepsList(){</span> <span class="cstat-no" title="statement not covered" > return stepsList;</span> }; <span class="fstat-no" title="function not covered" > function setStepsList(newStepsList){</span> <span class="cstat-no" title="statement not covered" > stepsList = newStepsList;</span> }; &nbsp; // Ritorno solo ciò che voglio rendere pubblico return{ getIsAvailable: getIsAvailable, setIsAvailable: setIsAvailable, getDescription: getDescription, setDescription: setDescription, getPublicationDate: getPublicationDate, setPublicationDate: setPublicationDate, getClosingDate: getClosingDate, setClosingDate: setClosingDate, getName: getName, setName: setName, getTotalSteps: getTotalSteps, setTotalSteps: setTotalSteps, getIdAdminOwner: getIdAdminOwner, setIdAdminOwner: setIdAdminOwner, getStepsList: getStepsList, setStepsList: setStepsList }; }; &nbsp;</pre></td></tr> </table></pre> </div> <div class="footer"> <div class="meta">Generated by <a href="http://istanbul-js.org/" target="_blank">istanbul</a> at Wed Jul 02 2014 13:11:48 GMT+0200 (CEST)</div> </div> <script src="../../../../prettify.js"></script> <script src="http://yui.yahooapis.com/3.6.0/build/yui/yui-min.js"></script> <script> YUI().use('datatable', function (Y) { var formatters = { pct: function (o) { o.className += o.record.get('classes')[o.column.key]; try { return o.value.toFixed(2) + '%'; } catch (ex) { return o.value + '%'; } }, html: function (o) { o.className += o.record.get('classes')[o.column.key]; return o.record.get(o.column.key + '_html'); } }, defaultFormatter = function (o) { o.className += o.record.get('classes')[o.column.key]; return o.value; }; function getColumns(theadNode) { var colNodes = theadNode.all('tr th'), cols = [], col; colNodes.each(function (colNode) { col = { key: colNode.getAttribute('data-col'), label: colNode.get('innerHTML') || ' ', sortable: !colNode.getAttribute('data-nosort'), className: colNode.getAttribute('class'), type: colNode.getAttribute('data-type'), allowHTML: colNode.getAttribute('data-html') === 'true' || colNode.getAttribute('data-fmt') === 'html' }; col.formatter = formatters[colNode.getAttribute('data-fmt')] || defaultFormatter; cols.push(col); }); return cols; } function getRowData(trNode, cols) { var tdNodes = trNode.all('td'), i, row = { classes: {} }, node, name; for (i = 0; i < cols.length; i += 1) { name = cols[i].key; node = tdNodes.item(i); row[name] = node.getAttribute('data-value') || node.get('innerHTML'); row[name + '_html'] = node.get('innerHTML'); row.classes[name] = node.getAttribute('class'); //Y.log('Name: ' + name + '; Value: ' + row[name]); if (cols[i].type === 'number') { row[name] = row[name] * 1; } } //Y.log(row); return row; } function getData(tbodyNode, cols) { var data = []; tbodyNode.all('tr').each(function (trNode) { data.push(getRowData(trNode, cols)); }); return data; } function replaceTable(node) { if (!node) { return; } var cols = getColumns(node.one('thead')), data = getData(node.one('tbody'), cols), table, parent = node.get('parentNode'); table = new Y.DataTable({ columns: cols, data: data, sortBy: 'file' }); parent.set('innerHTML', ''); table.render(parent); } Y.on('domready', function () { replaceTable(Y.one('div.coverage-summary table')); if (typeof prettyPrint === 'function') { prettyPrint(); } }); }); </script> </body> </html>
{ "content_hash": "1b865ddd0e5bb04a5dd8b200ffd22562", "timestamp": "", "source": "github", "line_count": 677, "max_line_length": 165, "avg_line_length": 29.997045790251107, "alnum_prop": 0.6028166239905456, "repo_name": "MDaino/Seq", "id": "b35feb7638b4a0e6064b8fcb020a234c20a7ec30", "size": "21371", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "src/test/java/com/sequenziatore/client/coverage/Chrome 35.0.1916 (Mac OS X 10.9.3)/client/model/shared/superclasses/GenericProcess.js.html", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "CSS", "bytes": "49576" }, { "name": "Java", "bytes": "696208" }, { "name": "JavaScript", "bytes": "993362" } ], "symlink_target": "" }
(function() { 'use strict'; angular .module('cupid') .config(routerConfig); /** @ngInject */ /* $urlRouterProvider 路由重定向 $stateProvider 路由状态配置 */ function routerConfig($stateProvider, $urlRouterProvider) { // For unmatched route $stateProvider .state('app', { abstract: true, templateUrl: 'app/components/common/layout.html', resolve: { deps: ['$ocLazyLoad', function($ocLazyLoad) { return $ocLazyLoad.load({ insertBefore: '#ng_load_plugins_before', // load the above css files before '#ng_load_plugins_before' files: [ '../../assets/scripts/profile/app.min.js', '../../assets/styles/profile/components.min.css' ] }); }] } }) .state('admin', { abstract: true, templateUrl: 'app/components/common/admin-layout.html', resolve: { deps: ['$ocLazyLoad', function($ocLazyLoad) { return $ocLazyLoad.load({ insertBefore: '#ng_load_plugins_before', // load the above css files before '#ng_load_plugins_before' files: [ '../../assets/scripts/profile/app.min.js', '../../assets/styles/profile/components.min.css' ] }); }] } }) .state('app.dashboard', { url: '/dashboard', templateUrl: 'app/components/dashboard/dashboard.html', resolve: { deps: ['$ocLazyLoad', function ($ocLazyLoad) { return $ocLazyLoad.load([ { insertBefore: '#load_styles_before', files: [ 'assets/styles/climacons-font.css', '../bower_components/rickshaw/rickshaw.min.css' ] }, { serie: true, files: [ '../bower_components/d3/d3.min.js', '../bower_components/rickshaw/rickshaw.min.js', '../bower_components/Flot/jquery.flot.js', '../bower_components/Flot/jquery.flot.resize.js', '../bower_components/Flot/jquery.flot.pie.js', '../bower_components/Flot/jquery.flot.categories.js' ] }, { name: 'angular-flot', files: [ '../bower_components/angular-flot/angular-flot.js' ] }]).then(function () { return $ocLazyLoad.load('app/components/dashboard/dashboard.controller.js'); }); }] }, data: { title: 'Dashboard' } }) .state('admin.dashboard', { url: '/admin/dashboard', templateUrl: 'app/components/admin/dashboard/dashboard.html', resolve: { deps: ['$ocLazyLoad', function ($ocLazyLoad) { return $ocLazyLoad.load([ { insertBefore: '#load_styles_before', files: [ 'assets/styles/climacons-font.css', '../bower_components/rickshaw/rickshaw.min.css' ] }, { serie: true, files: [ '../bower_components/d3/d3.min.js', '../bower_components/rickshaw/rickshaw.min.js', '../bower_components/Flot/jquery.flot.js', '../bower_components/Flot/jquery.flot.resize.js', '../bower_components/Flot/jquery.flot.pie.js', '../bower_components/Flot/jquery.flot.categories.js' ] }, { name: 'angular-flot', files: [ '../bower_components/angular-flot/angular-flot.js' ] }]).then(function () { return $ocLazyLoad.load('app/components/admin/dashboard/dashboard.controller.js'); }); }] }, data: { title: 'Admin Dashboard' } }) .state('admin.table', { url: '/admin/table', templateUrl: 'app/components/admin/table.html', resolve: { deps: ['$ocLazyLoad', function ($ocLazyLoad) { return $ocLazyLoad.load([ ] ).then(function () { return $ocLazyLoad.load('app/components/admin/table.controller.js'); }); }] }, data: { title: 'Admin Dashboard' } }) .state('admin.account', { url: '/admin/account', templateUrl: 'app/components/admin/account/account.html', resolve: { deps: ['$ocLazyLoad', function ($ocLazyLoad) { return $ocLazyLoad.load([ { insertBefore: '#load_styles_before', files: [ 'app/components/admin/user/style.css', ] } ] ).then(function () { return $ocLazyLoad.load('app/components/admin/account/account.controller.js'); }); }] }, data: { title: 'Admin Account Dashboard' } }) .state('admin.user', { url: '/admin/user', templateUrl: 'app/components/admin/user/user.html', resolve: { deps: ['$ocLazyLoad', function ($ocLazyLoad) { return $ocLazyLoad.load([ '../../assets/styles/profile/layout.min.css', '../bower_components/bootstrap/dist/js/bootstrap.min.js', '../bower_components/bootstrap-hover-dropdown/bootstrap-hover-dropdown.min.js', ] ).then(function () { return $ocLazyLoad.load('app/components/admin/user/user.controller.js'); }); }] }, data: { title: 'Admin User Dashboard' } }) .state('user', { templateUrl: 'app/components/common/session.html' }) .state('user.signin', { url: '/signin', templateUrl: 'app/components/user/extras-signin.html', resolve: { deps: ['$ocLazyLoad', function ($ocLazyLoad) { return $ocLazyLoad.load('app/components/user/session.controller.js'); }] }, data: { appClasses: 'bg-white usersession', contentClasses: 'full-height' } }) .state('user.adminsignin', { url: '/admin/signin', templateUrl: 'app/components/user/admin-signin.html', resolve: { deps: ['$ocLazyLoad', function ($ocLazyLoad) { return $ocLazyLoad.load('app/components/user/session.controller.js'); }] }, data: { appClasses: 'bg-white usersession', contentClasses: 'full-height' } }) .state('user.signup', { url: '/signup', templateUrl: 'app/components/user/extras-signup.html', resolve: { deps: ['$ocLazyLoad', function ($ocLazyLoad) { return $ocLazyLoad.load('app/components/user/session.controller.js'); }] }, data: { appClasses: 'bg-white usersession', contentClasses: 'full-height' } }) .state('user.forgot', { url: '/forgot', templateUrl: 'app/components/user/extras-forgot.html', resolve: { deps: ['$ocLazyLoad', function ($ocLazyLoad) { return $ocLazyLoad.load('app/components/user/session.controller.js'); }] }, data: { appClasses: 'bg-white usersession', contentClasses: 'full-height' } }) // UI Routes .state('app.ui', { template: '<div ui-view></div>', abstract: true, url: '/ui' }) // Todo .state('app.todo', { url: "/todo", templateUrl: "app/components/task/task-todo.html", data: {pageTitle: 'Todo'}, controller: "TodoController", resolve: { deps: ['$ocLazyLoad', function($ocLazyLoad) { return $ocLazyLoad.load({ insertBefore: '#ng_load_plugins_before', // load the above css files before '#ng_load_plugins_before' files: [ '../bower_components/bootstrap-datepicker/dist/css/bootstrap-datepicker3.min.css', '../bower_components/bootstrap-datepicker/dist/js/bootstrap-datepicker.min.js', '../../assets/styles/todo/todo-2.css', '../bower_components/select2/dist/css/select2.min.css', '../bower_components/select2/dist/js/select2.full.min.js', '../../assets/scripts/todo/todo-2.min.js', 'app/components/task/todo.controller.js' ] }); }] } }) // Profile .state("app.profile", { url: "/profile", templateUrl: "app/components/profile/profile-main.html", resolve: { deps: ['$ocLazyLoad', function($ocLazyLoad) { return $ocLazyLoad.load({ insertBefore: '#ng_load_plugins_before', // load the above css files before '#ng_load_plugins_before' files: [ '../bower_components/font-awesome/css/font-awesome.min.css', '../bower_components/bootstrap/dist/css/bootstrap.min.css', '../bower_components/simple-line-icons/css/simple-line-icons.css', '../bower_components/jquery.uniform/themes/default/css/uniform.default.css', '../bower_components/bootstrap-switch/dist/css/bootstrap3/bootstrap-switch.min.css', '../bower_components/bootstrap-fileinput/css/fileinput.min.css', '../../assets/styles/profile/layout.min.css', '../../assets/styles/profile/plugins-md.css', '../../assets/styles/profile/profile.min.css', '../../assets/styles/profile/darkblue.min.css', '../../assets/styles/profile/custom.min.css', '../../assets/scripts/profile/demo.min.js', '../../assets/scripts/profile/excanvas.min.js', '../../assets/scripts/profile/jquery.sparkline.min.js', '../../assets/scripts/profile/layout.min.js', '../../assets/scripts/profile/profile.min.js', '../../assets/scripts/profile/quick-sidebar.min.js', '../../assets/scripts/profile/respond.min.js', '../../assets/scripts/profile/timeline.min.js', '../bower_components/bootstrap/dist/js/bootstrap.min.js', '../bower_components/bootstrap-hover-dropdown/bootstrap-hover-dropdown.min.js', '../bower_components/jquery-slimscroll/jquery.slimscroll.min.js', '../bower_components/jquery.uniform/jquery.uniform.min.js', '../bower_components/jquery-slimscroll/jquery.slimscroll.min.js', '../bower_components/malsup.github.com/min/jquery.blockUI.min.js', '../bower_components/bootstrap-switch/dist/js/bootstrap-switch.min.js', '../bower_components/bootstrap-switch/dist/js/bootstrap-switch.min.js', '../bower_components/bootstrap-fileinput/js/fileinput.min.js' ] }); }] }, data: {pageTitle: 'User Profile'} }) // User Profile Help .state("app.profile.help", { url: "/help", templateUrl: "app/components/profile/profile-help.html", data: {pageTitle: 'Profile Help'} }) // User Profile Dashboard .state("app.profile.dashboard", { url: "/dashboard", templateUrl: "app/components/profile/profile-dashboard.html", data: {pageTitle: 'Profile Dashboard'} }) // User Profile Account .state("app.profile.account", { url: "/account", templateUrl: "app/components/profile/profile-account.html", data: {pageTitle: 'Account'} }); $urlRouterProvider.otherwise('/signin'); } })();
{ "content_hash": "a47b001d7e73a6a953dbb600e1151800", "timestamp": "", "source": "github", "line_count": 335, "max_line_length": 115, "avg_line_length": 36.30746268656716, "alnum_prop": 0.5110581271067993, "repo_name": "weilewantieba/swiip", "id": "820b82d72d81de8e2cf3d1e853fb70517a1e64a4", "size": "12185", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/app/index.route.js", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "CSS", "bytes": "1349518" }, { "name": "HTML", "bytes": "222230" }, { "name": "JavaScript", "bytes": "174525" } ], "symlink_target": "" }
var go = {}; go; go.app = function() { var vumigo = require('vumigo_v02'); var App = vumigo.App; var MenuState = vumigo.states.MenuState; var Choice = vumigo.states.Choice; var ChoiceState = vumigo.states.ChoiceState; var EndState = vumigo.states.EndState; var FreeText = vumigo.states.FreeText; var GoApp = App.extend(function(self) { App.call(self, 'states:language'); self.states.add('states:language', function(name) { return new MenuState(name, { question: 'Choose Language', choices: [ new Choice('states:main', 'English'), new Choice('states:notsupported', 'Sesotho'), new Choice('states:notsupported', 'Isizulu'), new Choice('states:exit', 'Exit')], }); }); self.states.add('states:notsupported', function(name) { return new ChoiceState(name, { question: 'Sesotho & Isizulu menus are currently not active. Please user english version.', choices: [ new Choice('states:join', 'English'), new Choice('states:exit', 'Exit')], next: function(choice) { return choice.value; } }); }); self.states.add('states:main', function(name) { return new ChoiceState(name, { question: 'TLHOLO - VICTORY', choices: [ new Choice('states:join', 'Join Tlholo'), new Choice('states:covers', 'Covers'), new Choice('states:status','Policy Status'), new Choice('states:claim', 'Claim Documents'), new Choice('states:rules', 'Motjha-O-Tjhele'), new Choice('states:contact','Our Offices'), new Choice('states:about', 'About Tlholo'), new Choice('states:terms', 'T & C'), new Choice('states:exit', 'Exit')], next: function(choice) { return choice.value; } }); }); self.states.add('states:join', function(name){ return new FreeText(name,{ question: 'Enter your name and Tlholo representative will call you back shortly:', next: function(content){ self.contact.extra.join = content; return self.im.contacts.save(self.contact).then(function(){ return "states:exit"; }); } }); }); self.states.add('states:status', function(name){ return new ChoiceState(name,{ question: 'Your policy is in good standing.', choices: [ new Choice('states:main', 'Main menu'), new Choice('states:exit', 'Exit')], next: function(choice) { return choice.value; } }); }); self.states.add('states:covers', function(name){ return new ChoiceState(name,{ question: 'Types of Covers:', choices: [ new Choice('states:single_cover', 'Single Cover'), new Choice('states:family_cover', 'Family Cover'), new Choice('states:main', 'Main menu'), new Choice('states:exit', 'Exit')], next: function(choice) { return choice.value; } }); }); self.states.add('states:single_cover', function(name){ return new EndState(name,{ text: 'Age: [18-64] cover[5000 - 20 000] premium[R80-R180]\nAge: [65-74] cover[5000 - 10 000] premium[R100-R170]\nAge: [75-84] cover[5000] premium[R190]', next: 'states:language' }); }); self.states.add('states:family_cover', function(name){ return new EndState(name,{ text: 'Our family covers premium\nranges from R80 to R280\ndepending on how many family\nmembers you would like to include\nConsultant will call you shortly', next: 'states:language' }); }); self.states.add('states:claim', function(name){ return new EndState(name,{ text: 'Required documents(certified) at claim stage:\nDeath Certificate\nDeaceased ID\nClaimant ID\nOne Month Bank Statement', next: 'states:language' }); }); self.states.add('states:rules', function(name){ return new EndState(name,{ text: 'Motjha-O-Tjhele premiums ranges between R200-R250\nThere are conditions for Motjha-O-Tjhele\nA consultant will call you shortly', next: 'states:language' }); }); self.states.add('states:contact', function(name){ return new EndState(name,{ text: 'Our Offices\nQwaqwa\nABSA Building\n071 908 2988\n\nBotshabelo\nReahola Complex\n083 669 5913\n\nBloemfontein\n154 Maitland Str\n\n083 669 5913', next: 'states:language' }); }); self.states.add('states:about', function(name){ return new EndState(name,{ text: 'Tlholo Victory Financial Services is an authorised\nFinancial services provider\nThe benefits are currently underwritten by Liberty Life', next: 'states:language' }); }); self.states.add('states:terms', function(name){ return new EndState(name,{ text: 'Six months WAITING period, excerpt suicide 24 Months\n & accidental death 1 month\nR50 Once off Joining fee\nPolicy lapses upon non payment of two premiums', next: 'states:language' }); }); self.states.add('states:exit', function(name) { return new EndState(name, { text: 'Tlholo - Victory\nVictors Not Victims\nDemo by Textily(Pty) Ltd', next: 'states:language' }); }); }); return { GoApp: GoApp }; }(); go.init = function() { var vumigo = require('vumigo_v02'); var InteractionMachine = vumigo.InteractionMachine; var GoApp = go.app.GoApp; return { im: new InteractionMachine(api, new GoApp()) }; }();
{ "content_hash": "4bbb0e9547835cc7d7399ffe0a4e2a82", "timestamp": "", "source": "github", "line_count": 179, "max_line_length": 180, "avg_line_length": 36.62011173184357, "alnum_prop": 0.5208237986270023, "repo_name": "Textily/tlokotsi-ussd-demo", "id": "8c824f2ae0626f1c050af67cdc2c7cd64d0717bb", "size": "6675", "binary": false, "copies": "1", "ref": "refs/heads/develop", "path": "go-app.js", "mode": "33188", "license": "bsd-3-clause", "language": [ { "name": "JavaScript", "bytes": "25437" } ], "symlink_target": "" }
using Should; using Xunit; namespace Cassette.Utilities { public class ByteArrayExtensions_ToHexString_Tests { [Fact] public void Empty_array_returns_empty_string() { new byte[] { }.ToHexString().ShouldEqual(""); } [Fact] public void _1_returns_01_as_string() { new byte[] { 1 }.ToHexString().ShouldEqual("01"); } [Fact] public void _10_returns_0a_as_string() { new byte[] { 10 }.ToHexString().ShouldEqual("0a"); } [Fact] public void _255_returns_ff_as_string() { new byte[] { 255 }.ToHexString().ShouldEqual("ff"); } } public class ByteArrayExtensions_FromHexString_Tests { [Fact] public void _01_returns_1() { ByteArrayExtensions.FromHexString("01").ShouldEqual(new byte[] { 1 }); } [Fact] public void _01ff_returns_1_255() { ByteArrayExtensions.FromHexString("01ff").ShouldEqual(new byte[] { 1, 255 }); } [Fact] public void _01FF_returns_1_255() { ByteArrayExtensions.FromHexString("01FF").ShouldEqual(new byte[] { 1, 255 }); } } }
{ "content_hash": "b97125c753f88088e842bfdad44aadb5", "timestamp": "", "source": "github", "line_count": 54, "max_line_length": 101, "avg_line_length": 24.85185185185185, "alnum_prop": 0.49254843517138597, "repo_name": "honestegg/cassette", "id": "459ea36dfa2b72bebe72d5d3f015b6bea4b65343", "size": "1344", "binary": false, "copies": "5", "ref": "refs/heads/master", "path": "src/Cassette.UnitTests/Utilities/ByteArrayExtensions.cs", "mode": "33188", "license": "mit", "language": [ { "name": "ASP", "bytes": "3709" }, { "name": "C#", "bytes": "1742742" }, { "name": "CSS", "bytes": "144588" }, { "name": "CoffeeScript", "bytes": "15" }, { "name": "JavaScript", "bytes": "801532" }, { "name": "Pascal", "bytes": "1463" }, { "name": "PowerShell", "bytes": "4083" }, { "name": "Shell", "bytes": "310" } ], "symlink_target": "" }
#include <stdexcept> #include "FileInput.h" #include "IOBase.h" #include "LexiconManager.h" #include "PhoneSet.h" #include "LogMessage.h" namespace Bavieca { // constructor LexiconManager::LexiconManager(const char *strFile, PhoneSet *phoneSet) { assert(phoneSet); m_strFile = strFile; m_phoneSet = phoneSet; m_mLexUnit = new MLexUnit; // number of lexical units of each kind m_iLexicalUnitsStandard = 0; m_iLexicalUnitsFiller = 0; m_iLexicalUnitsSentenceDelimiter = 0; m_iLexicalUnitsUnknown = 0; m_iLexicalUnitsUnique = 0; // number of lexical units regardless alternative pronunciations // these lexical units are allways defined (needed by the decoder) m_lexUnitBegSentence = NULL; m_lexUnitEndSentence = NULL; m_lexUnitUnknown = NULL; } // destructor LexiconManager::~LexiconManager() { destroy(); } // load the lexicon from a file void LexiconManager::load() { try { int iLexUnitId = 0; FileInput file(m_strFile.c_str(),false); file.open(); // (1) insert the sentence delimiters and the unknown symbol (if not in the language model they will be removed later) // unknown (before the word identity is known) m_lexUnitUnknown = new LexUnit; m_lexUnitUnknown->iType = LEX_UNIT_TYPE_UNKNOWN; m_lexUnitUnknown->iLexUnit = iLexUnitId; m_lexUnitUnknown->iPronunciation = 0; m_lexUnitUnknown->fProbability = 1.0; m_lexUnitUnknown->fInsertionPenalty = 0.0; LexUnitX *lexUnitX = new LexUnitX; lexUnitX->iLexUnit = iLexUnitId++; lexUnitX->strLexUnit = LEX_UNIT_UNKNOWN; lexUnitX->vLexUnitPronunciations.push_back(m_lexUnitUnknown); m_lexiconX.push_back(lexUnitX); m_lexicon.push_back(m_lexUnitUnknown); m_mLexUnit->insert(MLexUnit::value_type(lexUnitX->strLexUnit,lexUnitX)); ++m_iLexicalUnitsUnknown; // end of sentence "</s>" (must be created before the beginning of sentence to preserve alphabetical order) m_lexUnitEndSentence = new LexUnit; m_lexUnitEndSentence->iType = LEX_UNIT_TYPE_SENTENCE_DELIMITER; m_lexUnitEndSentence->iLexUnit = iLexUnitId; m_lexUnitEndSentence->iPronunciation = 0; m_lexUnitEndSentence->fProbability = 1.0; m_lexUnitEndSentence->fInsertionPenalty = 0.0; lexUnitX = new LexUnitX; lexUnitX->iLexUnit = iLexUnitId++; lexUnitX->strLexUnit = LEX_UNIT_END_SENTENCE; lexUnitX->vLexUnitPronunciations.push_back(m_lexUnitEndSentence); m_lexiconX.push_back(lexUnitX); m_lexicon.push_back(m_lexUnitEndSentence); m_mLexUnit->insert(MLexUnit::value_type(lexUnitX->strLexUnit,lexUnitX)); ++m_iLexicalUnitsSentenceDelimiter; // beginning of sentence "<s>" m_lexUnitBegSentence = new LexUnit; m_lexUnitBegSentence->iType = LEX_UNIT_TYPE_SENTENCE_DELIMITER; m_lexUnitBegSentence->iLexUnit = iLexUnitId; m_lexUnitBegSentence->iPronunciation = 0; m_lexUnitBegSentence->fProbability = 1.0; m_lexUnitBegSentence->fInsertionPenalty = 0.0; lexUnitX = new LexUnitX; lexUnitX->iLexUnit = iLexUnitId++; lexUnitX->strLexUnit = LEX_UNIT_BEG_SENTENCE; lexUnitX->vLexUnitPronunciations.push_back(m_lexUnitBegSentence); m_lexiconX.push_back(lexUnitX); m_lexicon.push_back(m_lexUnitBegSentence); m_mLexUnit->insert(MLexUnit::value_type(lexUnitX->strLexUnit,lexUnitX)); ++m_iLexicalUnitsSentenceDelimiter; // (2) insert lexical units read from the file char strLexUnit[MAX_LEXUNIT_LENGTH+1]; int iLine = 0; string strLine; while(std::getline(file.getStream(),strLine)) { ++iLine; // skip comments and blank lines if (strLine.empty() || ((strLine.c_str()[0] == '#') && (strLine.c_str()[1] == '#')) || ((strLine.length() >= 3) && (strLine.c_str()[0] == ';') && (strLine.c_str()[1] == ';') && (strLine.c_str()[2] == ';'))) { continue; } LexUnit *lexUnit = processLine(strLine.c_str(),iLine,strLexUnit); assert(lexUnit); lexUnit->fProbability = 1.0; // insert it into the lexicon map MLexUnit::iterator it = m_mLexUnit->find(strLexUnit); if (it == m_mLexUnit->end()) { // insert the lexical unit into the lexicon LexUnitX *lexUnitX = new LexUnitX; lexUnitX->iLexUnit = iLexUnitId++; lexUnitX->vLexUnitPronunciations.push_back(lexUnit); char *strLexUnitFit = new char[strlen(strLexUnit)+1]; strcpy(strLexUnitFit,strLexUnit); pair<MLexUnit::iterator, bool> pair = m_mLexUnit->insert(MLexUnit::value_type(strLexUnitFit,lexUnitX)); lexUnitX->strLexUnit = strLexUnitFit; lexUnit->iLexUnit = lexUnitX->iLexUnit; m_lexiconX.push_back(lexUnitX); } else { // insert the lexical unit into the lexicon lexUnit->iLexUnit = it->second->iLexUnit; it->second->vLexUnitPronunciations.push_back(lexUnit); } // insert it into the lexicon m_lexicon.push_back(lexUnit); attachIndex(lexUnit); } file.close(); // attach an index to those units that are not in the lexicon file attachIndex(m_lexUnitUnknown); attachIndex(m_lexUnitEndSentence); attachIndex(m_lexUnitBegSentence); // create lexical unit ids including pronunciations int iLexUnitPron = 0; for(VLexUnitX::iterator it = m_lexiconX.begin() ; it != m_lexiconX.end() ; ++it) { for(VLexUnit::iterator jt = (*it)->vLexUnitPronunciations.begin() ; jt != (*it)->vLexUnitPronunciations.end() ; ++jt) { (*jt)->iLexUnitPron = iLexUnitPron; ++iLexUnitPron; } } assert((int)m_lexicon.size() == iLexUnitPron); // sanity check for(VLexUnitX::iterator it = m_lexiconX.begin() ; it != m_lexiconX.end() ; ++it) { int j = 0; for(VLexUnit::iterator jt = (*it)->vLexUnitPronunciations.begin() ; jt != (*it)->vLexUnitPronunciations.end() ; ++jt, ++j) { assert((*jt)->iPronunciation == j); } } } catch(std::runtime_error) { BVC_ERROR << "unable to load the lexicon file: " << m_strFile; } } // process a line in the lexicon and extract the lexical unit and its phonetic transcription LexUnit *LexiconManager::processLine(const char *strLine, int iLine, char *strLexUnit) { int i = 0; int iCharacters = 0; int iTokens = 0; char strBuffer[MAX_LEXUNIT_LENGTH+1]; unsigned char iType = UCHAR_MAX; float fPronunciationProbability = 1.0; LexUnit *lexUnit = new LexUnit; // process characters until the end of line while((strLine[i] != '\0') && (strLine[i] != '\r') && (strLine[i] != '\n')) { // if a separator is found then if ((strLine[i] == ' ') || (strLine[i] == '\t')) { if (iCharacters > 0) { // the first token is the lexical unit if (iTokens == 0) { ++iTokens; strBuffer[iCharacters] = '\0'; // keep the lexical unit strcpy(strLexUnit,strBuffer); iCharacters = 0; } // the rest of the tokens are the pronunciation probability (optional) or part of the phonetic transcription else { // check if it is the pronunciation probability if ((iTokens == 1) && (iCharacters == 6) && ((strBuffer[0] == '0') || (strBuffer[0] == '1')) && (strBuffer[1] == '.')) { ++iTokens; strBuffer[iCharacters] = '\0'; // check correctness for(int j=0 ; j < iCharacters ; ++j) { // skip the '.' if (j == 1) { continue; } if (isdigit(strBuffer[j]) == 0) { BVC_ERROR << "pronunciation probability " << strBuffer << " is not in the right format: line " << iLine; } } // convert the string to a probability fPronunciationProbability = (float)atof(strBuffer+1); if ((fPronunciationProbability > 1.0) || (fPronunciationProbability < 0.0)) { BVC_ERROR << "non probabilistic value found \"" << strBuffer+1 << "\": line " << iLine; } iCharacters = 0; } // read the phone else { ++iTokens; strBuffer[iCharacters] = '\0'; //get the phone index int iPhoneIndex = m_phoneSet->getPhoneIndex(strBuffer); if (iPhoneIndex == -1) { BVC_ERROR << "unknown phonetic symbol: \"" << strBuffer << "\", it is not defined in the phonetic symbol set: line " << iLine; } lexUnit->vPhones.push_back(iPhoneIndex); iCharacters = 0; } } } } else { if (iTokens == 0) { if (iCharacters+1 >= MAX_LEXUNIT_LENGTH) { BVC_ERROR << "lexical unit defined in line " << iLine << " of the lexicon exceeds the maximum length (" << MAX_LEXUNIT_LENGTH << " characters)"; } } else { if (iCharacters+1 >= MAX_PHONETIC_SYMBOL_LENGTH) { BVC_ERROR << "phonetic symbol defined in line " << iLine << " of the lexicon exceeds the maximum length (" << MAX_PHONETIC_SYMBOL_LENGTH << " characters)"; } } strBuffer[iCharacters++] = strLine[i]; } ++i; } if (iCharacters > 0) { ++iTokens; strBuffer[iCharacters] = '\0'; //get the phone index int iPhoneIndex = m_phoneSet->getPhoneIndex(strBuffer); if (iPhoneIndex == -1) { BVC_ERROR << "unknown phonetic symbol: \"" << strBuffer << "\", it is not defined in the phonetic symbol set: line " << iLine; } lexUnit->vPhones.push_back(iPhoneIndex); iCharacters = 0; } // check completeness if (iTokens == 0) { BVC_ERROR << "no lexical unit defined at line " << iLine << " of the lexicon"; } else if (iTokens < 2) { BVC_ERROR << "no phonetic symbol defined for lexical unit " << strLexUnit << " at line " << iLine << " of the lexicon"; } // check redundancy if (isRedundant(lexUnit,strLexUnit)) { BVC_ERROR << "redundant lexical unit \"" << strLexUnit << "\" at line " << iLine << " of the lexicon (same word and sequence of phonemes)"; } // extract the pronunciation number from the lexical unit int iPronunciation = 0; char *cAlternative = strrchr(strLexUnit,'('); if (strLexUnit[strlen(strLexUnit)-1] != ')') cAlternative = NULL; if (cAlternative) { for(int i = 1 ; cAlternative[i] != ')' ; ++i) { // make sure it is a number (by the way this checks that the end of string is not reached before the ')') if ((cAlternative[i] > 57) || (cAlternative[i] < 48)) { BVC_ERROR << "lexicon file is not in a valid format: line " + iLine; } iPronunciation = iPronunciation*10; iPronunciation += cAlternative[i]-48; } iPronunciation--; *cAlternative = '\0'; // get the lexical unit type and check its correctness iType = getLexicalUnitType(strLexUnit); if ((iType != LEX_UNIT_TYPE_STANDARD) && (iType != LEX_UNIT_TYPE_FILLER)) { BVC_ERROR << "lexical unit \"" << strLexUnit << "\" at line " << iLine << " cannot be included in the lexicon"; } // make sure alternative pronunciations of this lexical unit were already seen bool bCorrectId = false; int iSize = 0; MLexUnit::iterator it = m_mLexUnit->find(strLexUnit); if (it != m_mLexUnit->end()) { iSize = (int)it->second->vLexUnitPronunciations.size(); if (iSize == iPronunciation) { bCorrectId = true; } } if (bCorrectId == false) { int iPronunciationOld = iPronunciation+1; iPronunciation = iSize; BVC_WARNING << "lexical unit \"" << strLexUnit << "(" << iPronunciationOld << ")\" at line " << iLine << " has an incorrect pronunciation id, renamed to: \"" << strLexUnit << "(" << iPronunciation+1 << ")\""; } } else { // get the lexical unit type and check its correctness iType = getLexicalUnitType(strLexUnit); if ((iType != LEX_UNIT_TYPE_STANDARD) && (iType != LEX_UNIT_TYPE_FILLER)) { BVC_ERROR << "lexical unit \"" << strLexUnit << "\" at line " << iLine << " cannot be included in the lexicon"; } // in case the lexical unit does not have an alternative pronunciation id and was already seen in the lexicon, create a pronunciation id and report a warning MLexUnit::iterator it = m_mLexUnit->find(strLexUnit); if (it != m_mLexUnit->end()) { // get the next available pronunciation id iPronunciation = (int)it->second->vLexUnitPronunciations.size(); BVC_WARNING << "lexical unit \"" << strLexUnit << "\" at line " << iLine << " was previously defined in the lexicon, renamed to: \"" << strLexUnit << "(" << iPronunciation+1 << ")\""; } } lexUnit->iPronunciation = iPronunciation; lexUnit->fProbability = fPronunciationProbability; lexUnit->iType = iType; lexUnit->fInsertionPenalty = 0.0; // accumulate type statistics switch(lexUnit->iType) { case LEX_UNIT_TYPE_STANDARD: { ++m_iLexicalUnitsStandard; break; } case LEX_UNIT_TYPE_FILLER: { ++m_iLexicalUnitsFiller; break; } case LEX_UNIT_TYPE_SENTENCE_DELIMITER: { ++m_iLexicalUnitsSentenceDelimiter; break; } case LEX_UNIT_TYPE_UNKNOWN: { ++m_iLexicalUnitsUnknown; break; } default: { assert(0); } } // accumulate pronunciation statistics if (lexUnit->iPronunciation == 0) { m_iLexicalUnitsUnique++; } return lexUnit; } // return whether the lexical unit is redundant bool LexiconManager::isRedundant(LexUnit *lexUnit, const char *strLexUnit) { assert(strLexUnit); assert(lexUnit->vPhones.empty() == false); MLexUnit::iterator it = m_mLexUnit->find(strLexUnit); if (it != m_mLexUnit->end()) { assert(strcmp(strLexUnit,it->second->strLexUnit) == 0); for(VLexUnit::iterator jt = it->second->vLexUnitPronunciations.begin() ; jt != it->second->vLexUnitPronunciations.end() ; ++jt) { if ((*jt)->vPhones.size() != lexUnit->vPhones.size()) { continue; } bool bEqual = true; vector<int>::iterator lt = (*jt)->vPhones.begin(); for(vector<int>::iterator kt = lexUnit->vPhones.begin() ; kt != lexUnit->vPhones.end() ; ++kt, ++lt) { if (*kt != *lt) { bEqual = false; break; } } if (bEqual) { return true; } } } return false; } // attach insertion-penalties to lexical units in the lexicon (needed for decoding) void LexiconManager::attachLexUnitPenalties(float fInsertionPenaltyStandard, float fInsertionPenaltyFiller) { for(VLexUnit::iterator it = m_lexicon.begin() ; it != m_lexicon.end() ; ++it) { if ((*it)->iType == LEX_UNIT_TYPE_STANDARD) { (*it)->fInsertionPenalty = fInsertionPenaltyStandard; } else if ((*it)->iType == LEX_UNIT_TYPE_FILLER) { (*it)->fInsertionPenalty = fInsertionPenaltyFiller; } else { assert(((*it)->iType == LEX_UNIT_TYPE_SENTENCE_DELIMITER) || ((*it)->iType == LEX_UNIT_TYPE_UNKNOWN)); } } } // return the lexical-unit type unsigned char LexiconManager::getLexicalUnitType(const char *strLexUnit) { unsigned int iLength = (unsigned int)strlen(strLexUnit); assert(iLength > 0); // beginning/end of sentence if ((strcmp(strLexUnit,LEX_UNIT_BEG_SENTENCE) == 0) || (strcmp(strLexUnit,LEX_UNIT_END_SENTENCE) == 0)) { return LEX_UNIT_TYPE_SENTENCE_DELIMITER; } // unknown else if (strcmp(strLexUnit,LEX_UNIT_UNKNOWN) == 0) { return LEX_UNIT_TYPE_UNKNOWN; } // filler else if ((strLexUnit[0] == '<') && (strLexUnit[iLength-1] == '>')) { return LEX_UNIT_TYPE_FILLER; } // standard else { return LEX_UNIT_TYPE_STANDARD; } } // clean-up void LexiconManager::destroy() { for(VLexUnitX::iterator it = m_lexiconX.begin() ; it != m_lexiconX.end() ; ++it) { if ((strcmp((*it)->strLexUnit,LEX_UNIT_UNKNOWN) != 0) && (strcmp((*it)->strLexUnit,LEX_UNIT_BEG_SENTENCE) != 0) && (strcmp((*it)->strLexUnit,LEX_UNIT_END_SENTENCE) != 0)) { delete [] (*it)->strLexUnit; } for(VLexUnit::iterator jt = (*it)->vLexUnitPronunciations.begin() ; jt != (*it)->vLexUnitPronunciations.end() ; ++jt) { delete *jt; } delete *it; } m_lexicon.clear(); m_lexiconX.clear(); if (m_mLexUnit != NULL) { /*for(MLexUnit::iterator it = m_mLexUnit->begin() ; it != m_mLexUnit->end() ; ++it) { delete [] it->first; }*/ m_mLexUnit->clear(); delete m_mLexUnit; } } // prints the lexicon void LexiconManager::print(bool bPrintLexUnits) { printf("VLexUnit:\n"); printf(" ## lexical units (standard): %8d \n",m_iLexicalUnitsStandard); printf(" ## lexical units (filler): %8d\n",m_iLexicalUnitsFiller); printf(" alt. pronunciation ratio: %8.2f\n",((float)m_iLexicalUnitsStandard)/((float)m_iLexicalUnitsUnique)); if (bPrintLexUnits) { for(VLexUnit::iterator it = m_lexicon.begin() ; it != m_lexicon.end() ; ++it) { const char *str = LexiconManager::getStrLexUnit((*it)->iLexUnit); printf("%10d[%10d]: %s(%d)",(*it)->iLexUnit,(*it)->iLexUnitPron,str,(*it)->iPronunciation); for(vector<int>::iterator jt = (*it)->vPhones.begin() ; jt != (*it)->vPhones.end() ; ++jt) { printf(" %s",m_phoneSet->getStrPhone(*jt)); } printf("\n"); } } } // return a vector containing all the filler lexical units (special-optional lexical units) void LexiconManager::getVLexUnitFiller(VLexUnit &vLexUnit) { // iterate through all the lexical units for(VLexUnitX::iterator it = m_lexiconX.begin() ; it != m_lexiconX.end() ; ++it) { if (isFiller((*it)->iLexUnit)) { assert((*it)->vLexUnitPronunciations.size() == 1); vLexUnit.push_back((*it)->vLexUnitPronunciations.front()); } } } // compute the average number of alternative pronunciations in the lexicon float LexiconManager::computeAveragePronunciationVariations() { return ((float)m_iLexicalUnitsStandard)/((float)m_iLexicalUnitsUnique); } // return the silence lexical unit LexUnit *LexiconManager::getLexUnitSilence() { // find the silence lexical unit LexUnitX *lexUnitXSilence = getLexUnit(LEX_UNIT_SILENCE_SYMBOL); if ((!lexUnitXSilence) || (lexUnitXSilence->vLexUnitPronunciations.size() != 1)) { BVC_ERROR << "no lexical unit for silence was defined in the lexicon, " << LEX_UNIT_SILENCE_SYMBOL << " must be defined"; } return lexUnitXSilence->vLexUnitPronunciations.front(); } // tranform a sequence of lexical units from text format to object format bool LexiconManager::getLexUnits(const char *strText, VLexUnit &vLexUnit, bool &bAllKnown) { bAllKnown = true; // process the text character by character int iLength = (int)strlen(strText); char strLexUnit[MAX_LEXUNIT_LENGTH+1]; int iCharacters = 0; for(int i=0 ; i<iLength ; ++i) { if (isspace(strText[i]) != 0) { if (iCharacters > 0) { strLexUnit[iCharacters] = 0; LexUnit *lexUnit = getLexUnitPronunciation(strLexUnit); if (lexUnit == NULL) { // the lexical unit is not in the lexicon, replace it by the <UNK> lexical unit lexUnit = m_lexUnitUnknown; bAllKnown = false; } vLexUnit.push_back(lexUnit); iCharacters = 0; } } else { // check if the lexical units exceeds the maximum length if (iCharacters >= MAX_LEXUNIT_LENGTH) { return false; } strLexUnit[iCharacters] = strText[i]; ++iCharacters; } } if (iCharacters > 0) { strLexUnit[iCharacters] = 0; LexUnit *lexUnit = getLexUnitPronunciation(strLexUnit); if (lexUnit == NULL) { // the lexical unit is not in the lexicon, replace it by the <UNK> lexical unit lexUnit = m_lexUnitUnknown; } vLexUnit.push_back(lexUnit); } return true; } // tranform a sequence of lexical units from text format to object format bool LexiconManager::getLexUnits(const char *strText, VLexUnitX &vLexUnitX, bool &bAllKnown) { bAllKnown = true; // process the text character by character int iLength = (int)strlen(strText); char strLexUnit[MAX_LEXUNIT_LENGTH+1]; int iCharacters = 0; for(int i=0 ; i<iLength ; ++i) { if (isspace(strText[i]) != 0) { if (iCharacters > 0) { strLexUnit[iCharacters] = 0; LexUnitX *lexUnitX = getLexUnit(strLexUnit); if (lexUnitX == NULL) { // the lexical unit is not in the lexicon, replace it by the <UNK> lexical unit lexUnitX = getLexUnit(m_lexUnitUnknown->iLexUnit); bAllKnown = false; } vLexUnitX.push_back(lexUnitX); iCharacters = 0; } } else { // check if the lexical units exceed the maximum length if (iCharacters >= MAX_LEXUNIT_LENGTH) { return false; } strLexUnit[iCharacters] = strText[i]; ++iCharacters; } } if (iCharacters > 0) { strLexUnit[iCharacters] = 0; LexUnitX *lexUnitX = getLexUnit(strLexUnit); if (lexUnitX == NULL) { // the lexical unit is not in the lexicon, replace it by the <UNK> lexical unit lexUnitX = getLexUnit(m_lexUnitUnknown->iLexUnit); } vLexUnitX.push_back(lexUnitX); } return true; } // map lexical units from pronunciation format to non-pron format void LexiconManager::map(VLexUnit &vLexUnitInput, VLexUnitX &vLexUnitOutput) { for(VLexUnit::iterator it = vLexUnitInput.begin() ; it != vLexUnitInput.end() ; ++it) { vLexUnitOutput.push_back(getLexUnit((*it)->iLexUnit)); } } // remove non-standard lexical units void LexiconManager::removeNonStandardLexUnits(VLexUnit &vLexUnit) { for(VLexUnit::iterator it = vLexUnit.begin() ; it != vLexUnit.end() ; ) { if (isStandard(*it) == false) { it = vLexUnit.erase(it); } else { ++it; } } } }; // end-of-namespace
{ "content_hash": "555b8e16c55a36439aec34f3cd7cc83f", "timestamp": "", "source": "github", "line_count": 623, "max_line_length": 160, "avg_line_length": 33.22953451043339, "alnum_prop": 0.6593565839049367, "repo_name": "nlphacker/bavieca", "id": "1dbc27e08929b2009db95d8fcec1306d9472a8c2", "size": "22352", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/common/base/LexiconManager.cpp", "mode": "33261", "license": "apache-2.0", "language": [ { "name": "C", "bytes": "28835" }, { "name": "C++", "bytes": "2029463" }, { "name": "Java", "bytes": "9826" }, { "name": "Perl", "bytes": "92109" }, { "name": "Shell", "bytes": "11464" } ], "symlink_target": "" }
package unfiltered.server import javax.servlet.http.HttpServletResponse import org.specs2.mutable._ import unfiltered.response._ import unfiltered.request._ import unfiltered.request.{Path => UFPath} import unfiltered.filter.WritableServletResponse object WriterSafetySpec extends Specification with unfiltered.specs2.jetty.Served { case class WriteString(text: String) extends Responder[HttpServletResponse] { override def respond(res: HttpResponse[HttpServletResponse]): Unit = { val writer = WritableServletResponse(res).getWriter writer.print(text) writer.close() } } def setup = _.plan(unfiltered.filter.Planify { case GET(UFPath("/writer")) => WriteString("written") ~> Ok }) "An Responder[HttpServletResponse]" should { "have reliable access to the underlying writer" in { http(host / "writer").as_string must_== "written" } } }
{ "content_hash": "61a473bbdda6f4e045da30580a6dcef5", "timestamp": "", "source": "github", "line_count": 30, "max_line_length": 83, "avg_line_length": 29.933333333333334, "alnum_prop": 0.7338530066815144, "repo_name": "omarkilani/unfiltered", "id": "0c707d0ce08d1daf21cae4b48b20b43a190d7058", "size": "898", "binary": false, "copies": "3", "ref": "refs/heads/0.10.x", "path": "filter/src/test/scala/WriterSafetySpec.scala", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "15" }, { "name": "HTML", "bytes": "52" }, { "name": "JavaScript", "bytes": "14" }, { "name": "Scala", "bytes": "821438" } ], "symlink_target": "" }
mod acpi; pub(crate) mod bat; pub(crate) mod serial_device; pub(crate) use acpi::acpi_event_run; pub(crate) use acpi::get_acpi_event_sock;
{ "content_hash": "70f283e4a4349a7d296a30843b621482", "timestamp": "", "source": "github", "line_count": 6, "max_line_length": 41, "avg_line_length": 23.333333333333332, "alnum_prop": 0.7285714285714285, "repo_name": "google/crosvm", "id": "65a64175b1d41406a2efd960d63497485eea0fc2", "size": "286", "binary": false, "copies": "2", "ref": "refs/heads/main", "path": "devices/src/sys/unix.rs", "mode": "33188", "license": "bsd-3-clause", "language": [ { "name": "Assembly", "bytes": "1648" }, { "name": "Batchfile", "bytes": "108" }, { "name": "C", "bytes": "217997" }, { "name": "Dockerfile", "bytes": "4659" }, { "name": "Makefile", "bytes": "7446" }, { "name": "Python", "bytes": "205322" }, { "name": "Rust", "bytes": "12683982" }, { "name": "Shell", "bytes": "57495" }, { "name": "Starlark", "bytes": "10836" } ], "symlink_target": "" }
*Design and print wheel encoder discs for robotics and more. Cross platform, open source!* ## Introduction WheelEncoderGenerator is a cross-platform desktop JavaFX app used to design and print wheel encoder discs for use in robotics. It supports printing of quadrature, binary, gray-code binary, and basic single-track encoder disc patterns with resolutions from 1 bit (2 positions) to 11 bit (2048 positions). You can adjust outer diameter of the encoder disc, as well as minimum diameter of the innermost track, and the diameter of the axle/shaft hole of the encoder. An index track with a single stripe can be enabled on quadrature and basic discs. The disc can also be inverted, exchange foreground and background colors. Finally, you can adjust the encoder for clockwise or counter-clockwise rotation. The encoder disc settings can be saved and loaded and, of course, the final design can be printed from the application. [Latest Release](https://github.com/shimniok/WheelEncoderGenerator/releases) ## Directions * Download the archive file from the [Latest Release](https://github.com/shimniok/WheelEncoderGenerator/releases) for your operating system * Extract archive to a location of your choosing * Open the extracted folder and open the ```bin``` folder/directory * Linux/Mac: open/run the file ```weg``` * Windows: open/run the file ```weg.bat``` Refer to the [User Guide](https://shimniok.github.io/WheelEncoderGenerator/) for more help. ## Feature List * Supports Mac, Windows, Linux with completely self-contained application * Design wheel coder with adjustable encoder tracks' outer and inner diameters, and axle/shaft diameter * Print encoder design to a printer * Save or Open configuration files or create new encoder. * Four encoder types: basic, quadrature, binary, and gray-coded binary * Index track available on quadrature and simple encoders (n/a for binary or gray encoders) * Adjust resolution up to 2048 positions (11-bit) * Invert color scheme (black on white vs white on black) * Clockwise or Counter-clockwise rotation (n/a for simple encoder) ## Original Application The original Java Swing application repository can be found [here](https://code.google.com/archive/p/wheel-encoder-generator/).
{ "content_hash": "ce97914e21a4d00846d6188b04ac9341", "timestamp": "", "source": "github", "line_count": 47, "max_line_length": 140, "avg_line_length": 48.02127659574468, "alnum_prop": 0.7815684536996013, "repo_name": "shimniok/WheelEncoderGenerator", "id": "00b1a610894b567e1c48c17a411ad87d8c8d9aef", "size": "2283", "binary": false, "copies": "1", "ref": "refs/heads/0.3.3", "path": "README.md", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Python", "bytes": "27669" } ], "symlink_target": "" }
package org.codegist.crest.serializer; import org.codegist.common.io.IOs; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.nio.charset.Charset; /** * @author laurent.gilles@codegist.org */ public class InputStreamSerializer implements Serializer<InputStream> { /** * @inheritDoc */ public void serialize(InputStream value, Charset charset, OutputStream out) throws IOException { IOs.copy(value, out, true); } }
{ "content_hash": "4ccb60712c7d4ec2c97e1779201b2148", "timestamp": "", "source": "github", "line_count": 22, "max_line_length": 100, "avg_line_length": 22.545454545454547, "alnum_prop": 0.7278225806451613, "repo_name": "codegist/crest", "id": "f750153510cf55b69e520f3af42727d710dacf7c", "size": "1254", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "core/src/main/java/org/codegist/crest/serializer/InputStreamSerializer.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Java", "bytes": "2235596" } ], "symlink_target": "" }
/** * @author Anton Avtamonov * @version $Revision$ */ package javax.swing.event; import java.awt.event.MouseEvent; public abstract class MouseInputAdapter implements MouseInputListener { public void mouseReleased(final MouseEvent e) { return; } public void mousePressed(final MouseEvent e) { return; } public void mouseMoved(final MouseEvent e) { return; } public void mouseExited(final MouseEvent e) { return; } public void mouseEntered(final MouseEvent e) { return; } public void mouseDragged(final MouseEvent e) { return; } public void mouseClicked(final MouseEvent e) { return; } }
{ "content_hash": "4ca0079f61477f8bcfa588c707fa9ab2", "timestamp": "", "source": "github", "line_count": 42, "max_line_length": 71, "avg_line_length": 17.023809523809526, "alnum_prop": 0.6363636363636364, "repo_name": "freeVM/freeVM", "id": "ab7c7ce6c020cae0f4c683defa458485d71bc736", "size": "1527", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "enhanced/archive/classlib/java6/modules/swing/src/main/java/common/javax/swing/event/MouseInputAdapter.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Assembly", "bytes": "116828" }, { "name": "C", "bytes": "17860389" }, { "name": "C++", "bytes": "19007206" }, { "name": "CSS", "bytes": "217777" }, { "name": "Java", "bytes": "152108632" }, { "name": "Objective-C", "bytes": "106412" }, { "name": "Objective-J", "bytes": "11029421" }, { "name": "Perl", "bytes": "305690" }, { "name": "Scilab", "bytes": "34" }, { "name": "Shell", "bytes": "153821" }, { "name": "XSLT", "bytes": "152859" } ], "symlink_target": "" }
#ifndef GLINK_INTERNAL_H #define GLINK_INTERNAL_H /*=========================================================================== GLink Core Internal Header File ===========================================================================*/ /*=========================================================================== INCLUDE FILES ===========================================================================*/ #include "smem_list.h" #include "glink.h" #include "glink_os_utils.h" #include "glink_core_if.h" #ifdef __cplusplus extern "C" { #endif /*=========================================================================== FEATURE DEFINITIONS ===========================================================================*/ #define GLINK_VERSION 0 #define GLINK_FEATURE_FLAGS 0 #define GLINK_NUM_HOSTS 7 /*=========================================================================== MACRO DEFINITIONS ===========================================================================*/ #define GLINK_LOG_EVENT(type, ch_name, xport, remote_ss, param) \ glink_mem_log(__FUNCTION__, __LINE__, type, ch_name, xport, remote_ss, param); #define GLINK_MEM_LOG_SIZE 128 /*=========================================================================== TYPE DEFINITIONS ===========================================================================*/ typedef enum { GLINK_EVENT_INIT, GLINK_EVENT_REGISTER_XPORT, GLINK_EVENT_CH_OPEN, GLINK_EVENT_CH_CLOSE, GLINK_EVENT_CH_TX, GLINK_EVENT_CH_Q_RX_INTENT, GLINK_EVENT_CH_RX_DONE, GLINK_EVENT_LINK_UP, GLINK_EVENT_RX_CMD_VER, GLINK_EVENT_RM_CH_OPEN, GLINK_EVENT_CH_OPEN_ACK, GLINK_EVENT_CH_CLOSE_ACK, GLINK_EVENT_CH_REMOTE_CLOSE, GLINK_EVENT_CH_STATE_TRANS, GLINK_EVENT_CH_INTENT_PUT, GLINK_EVENT_CH_RX_DATA, GLINK_EVENT_CH_RX_DATA_FRAG, GLINK_EVENT_CH_GET_PKT_CTX, GLINK_EVENT_CH_PUT_PKT_CTX, GLINK_EVENT_CH_TX_DONE, GLINK_EVENT_CH_SIG_SET, GLINK_EVENT_CH_SIG_L_GET, GLINK_EVENT_CH_SIG_R_GET, GLINK_EVENT_CH_NO_MIGRATION, GLINK_EVENT_CH_MIGRATION_IN_PROGRESS, GLINK_EVENT_XPORT_INTERNAL, GLINK_EVENT_TRACER_PKT_FAILURE, GLINK_EVENT_TXV_INVALID_BUFFER }glink_log_event_type; typedef struct _glink_channel_intents_type { /* Link for a channel in Tx queue */ struct _glink_channel_intents_type* next; /* Critical section to protest access to intent queues */ os_cs_type intent_q_cs; /* Event that glink_tx waits on and blocks until remote rx_intents * are available */ os_event_type rm_intent_avail_evt; /* Size of requested intent that this channel wait on */ size_t rm_intent_req_size; /* Linked list of remote Rx intents. Data can be transmitted only when * remote intents are available */ smem_list_type remote_intent_q; /* Linked list of remote Rx intents which local GLink core has used to * transmit data, and are pending Tx complete */ smem_list_type remote_intent_pending_tx_q; /* Linked list of local Rx intents. Data can be received only when * local intents are available */ smem_list_type local_intent_q; /* Linked list of remote Rx intents held by the clients */ smem_list_type local_intent_client_q; /* Read intent being gathered */ glink_rx_intent_type *cur_read_intent; /* Linked list of Tx packets in the order they where submitted by * the channel owner */ smem_list_type tx_pkt_q; } glink_channel_intents_type; struct glink_channel_ctx { /* Link needed for use with list APIs. Must be at the head of the struct */ smem_list_link_type link; /* Channel name */ char name[GLINK_CH_NAME_LEN]; /* Local channel ID */ uint32 lcid; /* Remote Channel ID */ uint32 rcid; /* Local Channel state */ glink_local_state_type local_state; /* Remote channel state */ glink_remote_state_type remote_state; /* Critical section to protect channel states */ os_cs_type ch_state_cs; /* Channel local control signal state */ uint32 local_sigs; /* Channel remote control signal state */ uint32 remote_sigs; /* Critical section to protect tx operations */ os_cs_type tx_cs; /* channel intent collection */ glink_channel_intents_type *pintents; /* Interface pointer with with this channel is registered */ glink_transport_if_type *if_ptr; /** Private data for client to maintain context. This data is passed back * to client in the notification callbacks */ const void *priv; /** Data receive notification callback */ glink_rx_notification_cb notify_rx; /** Tracer Packet data receive notification callback */ glink_rx_tracer_pkt_notification_cb notify_rx_tracer_pkt; /** Vector receive notification callback */ glink_rxv_notification_cb notify_rxv; /** Data transmit notification callback */ glink_tx_notification_cb notify_tx_done; /** GLink channel state notification callback */ glink_state_notification_cb notify_state; /** Intent request from the remote side */ glink_notify_rx_intent_req_cb notify_rx_intent_req; /** New intent arrival from the remote side */ glink_notify_rx_intent_cb notify_rx_intent; /** Control signal change notification - Invoked when remote side * alters its control signals */ glink_notify_rx_sigs_cb notify_rx_sigs; /** rx_intent abort notification. This callback would be invoked for * every rx_intent that is queued with GLink core at the time the * remote side or local side decides to close the port. Optional */ glink_notify_rx_abort_cb notify_rx_abort; /** tx abort notification. This callback would be invoked if client * had queued a tx buffer with glink and it had not been transmitted i.e. * tx_done callback has not been called for this buffer and remote side * or local side closed the port. Optional */ glink_notify_tx_abort_cb notify_tx_abort; /* glink transport if pointer for preferred channel */ glink_transport_if_type *req_if_ptr; /* flag to check if channel is marked for deletion * This is workaround to prevent channel migration algorithm from finding channel * which should be closed but has not been closed yet. This case occurs when glink_close * is called for closing channel on initial xport and it is being opened on other xport. * This may lead to remote side opening channel on neogitated xport from which local side * will get remote open again. In this case channel to be closed will be found for negotiation * on initial xport again and channel migration algorithm will be triggered(again) */ boolean tag_ch_for_close; /* save glink open config options */ uint32 ch_open_options; }; typedef struct _glink_mem_log_entry_type { const char *func; uint32 line; glink_log_event_type type; const char *msg; const char *xport; const char *remote_ss; uint32 param; } glink_mem_log_entry_type; /* Structure to store link notification callbacks */ typedef struct { /* Link needed for use with list APIs. Must be at the head of the struct */ smem_list_link_type link; const char* xport; /* NULL = any transport */ const char* remote_ss; /* NULL = any subsystem */ glink_link_state_notif_cb link_notifier; /* Notification callback */ void *priv; /* Notification priv ptr */ } glink_link_notif_data_type; /*=========================================================================== GLOBAL DATA DECLARATIONS ===========================================================================*/ extern os_cs_type *glink_transport_q_cs; extern const char *glink_hosts_supported[GLINK_NUM_HOSTS]; extern smem_list_type glink_registered_transports[]; /*=========================================================================== LOCAL FUNCTION DEFINITIONS ===========================================================================*/ /*=========================================================================== EXTERNAL FUNCTION DEFINITIONS ===========================================================================*/ /*=========================================================================== FUNCTION glink_link_up DESCRIPTION Indicates that transport is now ready to start negotiation using the v0 configuration ARGUMENTS *if_ptr Pointer to interface instance; must be unique for each edge RETURN VALUE None. SIDE EFFECTS None ===========================================================================*/ void glink_link_up ( glink_transport_if_type *if_ptr ); /*=========================================================================== FUNCTION glink_rx_cmd_version DESCRIPTION Receive transport version for remote-initiated version negotiation ARGUMENTS *if_ptr Pointer to interface instance; must be unique for each edge version Remote Version features Remote Features RETURN VALUE None. SIDE EFFECTS None ===========================================================================*/ void glink_rx_cmd_version ( glink_transport_if_type *if_ptr, uint32 version, uint32 features ); /*=========================================================================== FUNCTION glink_rx_cmd_version_ack DESCRIPTION Receive ACK to previous glink_transport_if::tx_cmd_version command ARGUMENTS *if_ptr Pointer to interface instance; must be unique for each edge version Remote Version features Remote Features RETURN VALUE None. SIDE EFFECTS None ===========================================================================*/ void glink_rx_cmd_version_ack ( glink_transport_if_type *if_ptr, uint32 version, uint32 features ); /*=========================================================================== FUNCTION glink_rx_cmd_ch_remote_open DESCRIPTION Receive remote channel open request; Calls glink_transport_if:: tx_cmd_ch_remote_open_ack as a result ARGUMENTS *if_ptr Pointer to interface instance; must be unique for each edge rcid Remote Channel ID *name String name for logical channel prio requested xport priority from remote side RETURN VALUE None. SIDE EFFECTS None ===========================================================================*/ void glink_rx_cmd_ch_remote_open ( glink_transport_if_type *if_ptr, uint32 rcid, const char *name, glink_xport_priority prio ); /*=========================================================================== FUNCTION glink_rx_cmd_ch_open_ack DESCRIPTION This function is invoked by the transport in response to glink_transport_if:: tx_cmd_ch_open ARGUMENTS *if_ptr Pointer to interface instance; must be unique for each edge lcid Local Channel ID prio Negotiated xport priority obtained from remote side after negotiation happened on remote side RETURN VALUE None. SIDE EFFECTS None ===========================================================================*/ void glink_rx_cmd_ch_open_ack ( glink_transport_if_type *if_ptr, uint32 lcid, glink_xport_priority prio ); /*=========================================================================== FUNCTION glink_rx_cmd_ch_close_ack DESCRIPTION This function is invoked by the transport in response to glink_transport_if_type:: tx_cmd_ch_close ARGUMENTS *if_ptr Pointer to interface instance; must be unique for each edge lcid Local Channel ID RETURN VALUE None. SIDE EFFECTS None ===========================================================================*/ void glink_rx_cmd_ch_close_ack ( glink_transport_if_type *if_ptr, /* Pointer to the interface instance */ uint32 lcid /* Local channel ID */ ); /*=========================================================================== FUNCTION glink_rx_cmd_ch_remote_close DESCRIPTION Remote channel close request; will result in sending glink_transport_if_type:: tx_cmd_ch_remote_close_ack ARGUMENTS *if_ptr Pointer to interface instance; must be unique for each edge rcid Remote Channel ID RETURN VALUE None. SIDE EFFECTS None ===========================================================================*/ void glink_rx_cmd_ch_remote_close ( glink_transport_if_type *if_ptr, /* Pointer to the interface instance */ uint32 rcid /* Remote channel ID */ ); /*=========================================================================== FUNCTION glink_rx_put_pkt_ctx DESCRIPTION Transport invokes this call to receive a packet fragment (must have previously received an rx_cmd_rx_data packet) ARGUMENTS *if_ptr Pointer to interface instance; must be unique for each edge rcid Remote Channel ID *intent_ptr Pointer to the intent fragment complete True if pkt is complete RETURN VALUE None SIDE EFFECTS None ===========================================================================*/ void glink_rx_put_pkt_ctx ( glink_transport_if_type *if_ptr, /* Pointer to the interface instance */ uint32 rcid, /* Remote channel ID */ glink_rx_intent_type *intent_ptr, /* Fragment ptr */ boolean complete /* True if pkt is complete */ ); /*=========================================================================== FUNCTION glink_rx_cmd_remote_sigs DESCRIPTION Transport invokes this call to inform GLink of remote side changing its control signals ARGUMENTS *if_ptr Pointer to interface instance; must be unique for each edge rcid Remote Channel ID remote_sigs Remote signal state. RETURN VALUE None. SIDE EFFECTS None ===========================================================================*/ void glink_rx_cmd_remote_sigs ( glink_transport_if_type *if_ptr, /* Pointer to the interface instance */ uint32 rcid, /* Remote channel ID */ uint32 remote_sigs /* Remote control signals */ ); /*=========================================================================== FUNCTION glink_set_core_version DESCRIPTION Sets the core version used by the transport; called after completing negotiation. ARGUMENTS *if_ptr Pointer to interface instance; must be unique for each edge version Negotiated transport version RETURN VALUE None. SIDE EFFECTS None ===========================================================================*/ void glink_set_core_version ( glink_transport_if_type *if_ptr, /* Pointer to the interface instance */ uint32 version /* Version */ ); /*=========================================================================== CHANNEL CONTEXT APIS ===========================================================================*/ /*=========================================================================== FUNCTION glinki_ch_is_fully_opened DESCRIPTION Determine if both the local and remote channel state is fully open ARGUMENTS *cfg_ptr - Pointer to channel context RETURN VALUE True if fully opened, false otherwise. SIDE EFFECTS None ===========================================================================*/ boolean glinki_ch_is_fully_opened ( glink_channel_ctx_type *ctx ); /*=========================================================================== FUNCTION glinki_ch_push_local_rx_intent DESCRIPTION Create and push a local receive intent to internal list ARGUMENTS *cfg_ptr - Pointer to channel context *pkt_priv - Client-provided opaque data size - Size of Receive Intent RETURN VALUE Pointer to the new intent SIDE EFFECTS None ===========================================================================*/ glink_rx_intent_type* glinki_ch_push_local_rx_intent ( glink_channel_ctx_type *ctx, const void *pkt_priv, size_t size ); /*=========================================================================== FUNCTION glinki_ch_get_local_rx_intent DESCRIPTION Lookup a local receive intent ARGUMENTS *cfg_ptr - Pointer to channel context liid - Local Receive Intent ID RETURN VALUE Pointer to the intent or NULL if not match is found. SIDE EFFECTS None ===========================================================================*/ glink_rx_intent_type* glinki_ch_get_local_rx_intent ( glink_channel_ctx_type *ctx, uint32 liid ); /*=========================================================================== FUNCTION glinki_ch_remove_local_rx_intent DESCRIPTION Removes Local Receive Intent ID ARGUMENTS *cfg_ptr - Pointer to channel context liid - Local Receive Intent ID RETURN VALUE None SIDE EFFECTS None ===========================================================================*/ void glinki_ch_remove_local_rx_intent ( glink_channel_ctx_type *ctx, uint32 liid ); /*=========================================================================== FUNCTION glinki_ch_set_local_rx_intent_notified DESCRIPTION Sets the state of the intent as client-notified ARGUMENTS *cfg_ptr - Pointer to channel context *intent_ptr - Pointer to the receive intent RETURN VALUE None SIDE EFFECTS None ===========================================================================*/ void glinki_ch_set_local_rx_intent_notified ( glink_channel_ctx_type *ctx, glink_rx_intent_type *intent_ptr ); /*=========================================================================== FUNCTION glinki_ch_get_local_rx_intent_notified DESCRIPTION Lookup a Local Receive Intent ID that is in the client-notified state ARGUMENTS *cfg_ptr - Pointer to channel context *ptr - Data pointer of receive buffer from client (passed in through glink_rx_done) RETURN VALUE Pointer to the intent or NULL if not match is found. SIDE EFFECTS None ===========================================================================*/ glink_rx_intent_type* glinki_ch_get_local_rx_intent_notified ( glink_channel_ctx_type *ctx, void *ptr ); /*=========================================================================== FUNCTION glinki_ch_remove_local_rx_intent_notified DESCRIPTION Removes the Local Receive Intent ARGUMENTS *cfg_ptr - Pointer to channel context *intent_ptr - Pointer to the receive intent RETURN VALUE New channel context or NULL SIDE EFFECTS None ===========================================================================*/ glink_channel_ctx_type* glinki_ch_remove_local_rx_intent_notified ( glink_channel_ctx_type *ctx, glink_rx_intent_type *intent_ptr ); /*=========================================================================== FUNCTION glinki_ch_push_remote_rx_intent DESCRIPTION Adds a new Remote Receive Intent ARGUMENTS *cfg_ptr - Pointer to channel context size - Size of the Remote Receive Intent RETURN VALUE None SIDE EFFECTS None ===========================================================================*/ void glinki_ch_push_remote_rx_intent ( glink_channel_ctx_type *ctx, size_t size ); /*=========================================================================== FUNCTION glinki_ch_pop_remote_rx_intent DESCRIPTION Removes a Remote Receive Intent ARGUMENTS *cfg_ptr - Pointer to channel context size - Size of the Remote Receive Intent *riid_ptr - Pointer to the Remote Receive Intent RETURN VALUE Standard GLink Err code. SIDE EFFECTS None ===========================================================================*/ glink_err_type glinki_ch_pop_remote_rx_intent ( glink_channel_ctx_type *ctx, size_t size, uint32 *riid_ptr ); /*=========================================================================== FUNCTION glinki_ch_get_tx_pending_remote_done DESCRIPTION Lookup packet transmit context for a packet that is waiting for the remote-done notification. ARGUMENTS *cfg_ptr - Pointer to channel context riid - Remote Receive Intent ID RETURN VALUE Pointer to the transmit packet context or NULL if not match is found. SIDE EFFECTS None ===========================================================================*/ glink_core_tx_pkt_type* glinki_ch_get_tx_pending_remote_done ( glink_channel_ctx_type *ctx, uint32 riid ); /*=========================================================================== FUNCTION glinki_ch_remove_tx_pending_remote_done DESCRIPTION Removes a packet transmit context for a packet that is waiting for the remote-done notification. ARGUMENTS *cfg_ptr - Pointer to channel context *tx_pkt - Pointer to the packet context to remove RETURN VALUE None SIDE EFFECTS None ===========================================================================*/ void glinki_ch_remove_tx_pending_remote_done ( glink_channel_ctx_type *ctx, glink_core_tx_pkt_type *tx_pkt ); /*=========================================================================== FUNCTION glinki_add_ch_to_xport ===========================================================================*/ /** * Add remote/local channel context to xport open channel queue * * @param[in] if_ptr Pointer to xport if on which channel is to * be opened * @param[in] req_if_ptr Pointer to xport if on which channel * actually wants to open * @param[in] ch_ctx channel context * @param[out] allocated_ch_ctx Pointer to channel context pointer * @param[in] local_open flag to determine if channel is opened * locally or remotely * @param[in] prio negotiated xport priority * (used to send priority via remote_open_ack to * remote side) * * @return pointer to glink_transport_if_type struct * * @sideeffects NONE */ /*=========================================================================*/ glink_err_type glinki_add_ch_to_xport ( glink_transport_if_type *if_ptr, glink_transport_if_type *req_if_ptr, glink_channel_ctx_type *ch_ctx, glink_channel_ctx_type **allocated_ch_ctx, unsigned int local_open, glink_xport_priority prio ); void glink_mem_log ( const char *func, uint32 line, glink_log_event_type type, const char *msg, const char *xport, const char *remote_ss, uint32 param ); /*=========================================================================== FUNCTION glink_core_setup ===========================================================================*/ /** Initializes internal core functions based on the transport capabilities. @param[in] if_ptr The Pointer to the interface instance. @return None. @sideeffects None. */ /*=========================================================================*/ void glink_core_setup(glink_transport_if_type *if_ptr); /*=========================================================================== FUNCTION glink_core_get_default_interface ===========================================================================*/ /** Provides default core interface. @return Pointer to the default core interface. @sideeffects None. */ /*=========================================================================*/ glink_core_if_type* glink_core_get_default_interface(void); /*=========================================================================== FUNCTION glink_core_setup_full_xport ===========================================================================*/ /** Initializes internal core functions for the full-featured transport. @param[in] if_ptr The Pointer to the interface instance. @return None. @sideeffects None. */ /*=========================================================================*/ void glink_core_setup_full_xport(glink_transport_if_type *if_ptr); /*=========================================================================== FUNCTION glink_core_setup_intentless_xport ===========================================================================*/ /** Initializes internal core functions for the intentless transport. @param[in] if_ptr The Pointer to the interface instance. @return None. @sideeffects None. */ /*=========================================================================*/ void glink_core_setup_intentless_xport(glink_transport_if_type *if_ptr); #endif /* GLINK_INTERNAL_H */
{ "content_hash": "8ff0e6dac0758d0c93e60893537b0f46", "timestamp": "", "source": "github", "line_count": 804, "max_line_length": 96, "avg_line_length": 32.6952736318408, "alnum_prop": 0.4987636474302887, "repo_name": "jaehyek/lk", "id": "bdd434c6c9804e21795cb9cc327a139cfb1ecc5c", "size": "27802", "binary": false, "copies": "3", "ref": "refs/heads/master", "path": "platform/msm_shared/include/glink_internal.h", "mode": "33188", "license": "mit", "language": [ { "name": "Assembly", "bytes": "550333" }, { "name": "Batchfile", "bytes": "2356" }, { "name": "C", "bytes": "21547634" }, { "name": "C++", "bytes": "351682" }, { "name": "DIGITAL Command Language", "bytes": "113105" }, { "name": "Makefile", "bytes": "230074" }, { "name": "Objective-C", "bytes": "4534" }, { "name": "Perl", "bytes": "911757" }, { "name": "Python", "bytes": "10626" }, { "name": "Shell", "bytes": "24220" }, { "name": "XS", "bytes": "4319" }, { "name": "eC", "bytes": "3710" } ], "symlink_target": "" }
package com.ai.alg; import com.ai.Policy; import com.ai.Racetrack; import com.ai.model.Action; import com.ai.model.Position; import com.ai.model.State; import com.ai.model.Velocity; import com.ai.sim.CollisionModel; import com.ai.sim.MDPActionSimulator; import com.ai.sim.RacetrackMDP; import org.apache.log4j.Logger; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; public class QLearning extends RacetrackLearner { private static final double LEARNING_RATE = .7; private static final double DISCOUNT_FACTOR = .8; private static int ITERATION_LIMIT; private static final double TIMES_TO_VISIT = 10D; private static final Logger logger = Logger.getLogger(QLearning.class); public int iterationCount = 0; private Map<State, Map<Action, Double>> qTable = new HashMap<>(); private Map<State, Integer> timesVisited = new HashMap<>(); MDPActionSimulator mdpActionSimulator; QLearningPolicy policy; public QLearning(Racetrack racetrack, CollisionModel collisionModel) { super(racetrack, collisionModel); mdpActionSimulator = new MDPActionSimulator(new RacetrackMDP(racetrack, collisionModel)); policy = new QLearningPolicy(); ITERATION_LIMIT = racetrack.getWidth()*racetrack.getHeight()*121*9*2; } @Override public String toString() { return "QLearning"; } private class QLearningPolicy implements Policy { /** * Returns an action based on a given state, using epsilon greedy * * @param state the state to act within * @return the action to take in the given state */ @Override public Action getAction(State state) { // get epsilon if (!timesVisited.containsKey(state)) { timesVisited.put(state, 1); } if (Math.random() > timesVisited.get(state)/TIMES_TO_VISIT) { return getRandomAction(); } double bestCost = Double.MAX_VALUE; Action argMax = null; if (!qTable.containsKey(state)) { qTable.put(state, new HashMap<>()); } Map<Action, Double> actions = qTable.get(state); for(Action action : actions.keySet()) { if(actions.get(action) < bestCost) { argMax = action; bestCost = actions.get(action); } } if (argMax == null) { argMax = getRandomAction(); } //logger.info("Policy... State: " + state + " Action:" +argMax + " "+ qTable.get(state).get(argMax)); return argMax; } /** * Returns a random valid action * * @return The randomly chosen action to take */ public Action getRandomAction() { return new Action(-1+ (int)(Math.random()*3), -1+ (int)(Math.random()*3)); } } @Override public void next() { Position curPos; Velocity curVel; State currentState; Action currentAction = policy.getRandomAction(); List<Action> actions; List<State> states; int xPos; int yPos; do { xPos = (int) (Math.random() * racetrack.getWidth()); yPos = (int) (Math.random() * racetrack.getHeight()); curPos = new Position(xPos, yPos); } while (!racetrack.isSafe(curPos) || racetrack.finishLine().contains(curPos)); int xVel = -5 + (int)(Math.random()*12); int yVel = -5 + (int)(Math.random()*12); dowhile: do { states = new ArrayList<>(); actions = new ArrayList<>(); curPos = new Position(xPos, yPos); curVel = new Velocity(xVel, yVel); currentState = new State(curPos, curVel); for (int i = 0; i<ITERATION_LIMIT; i++) { states.add(currentState); actions.add(currentAction); currentAction = policy.getAction(currentState); currentState = mdpActionSimulator.getNextState(currentState, currentAction); if (currentState == null) { logger.info("QLearning reached the finish line..."); break dowhile; } } logger.debug("QLearning reached iteration limit, trying again..."); } while (true); for (int i = 0; i < states.size(); i++) { State state = states.get(i); Action action = actions.get(i); double nextStateActionUtility = currentState == null ? 0 : -1000; if (i < states.size() - 1) { State nextState = states.get(i + 1); Action nextAction = actions.get(i + 1); if (!qTable.containsKey(nextState)) { qTable.put(nextState, new HashMap<>()); } if (!qTable.get(nextState).containsKey(nextAction)) { qTable.get(nextState).put(nextAction, Math.random()); } nextStateActionUtility = qTable.get(nextState).get(nextAction); } int reward = -1; if (currentState == null) { reward = 0; } if (!qTable.containsKey(state)) { qTable.put(state, new HashMap<>()); } if (!qTable.get(state).containsKey(action)) { qTable.get(state).put(action, Math.random()); } //logger.info("Next... State: " + state + " Action:" +action +" " + qTable.get(state).get(action)); qTable.get(state).put(action, (state!=null? qTable.get(state).get(action): 1) + (LEARNING_RATE * (reward + (DISCOUNT_FACTOR * nextStateActionUtility) - (state!=null ? qTable.get(state).get(action) : 0)))); if (!timesVisited.containsKey(state)){ timesVisited.put(state, timesVisited.get(state)+1); } } iterationCount += states.size(); } @Override public int getIterationCount() { return iterationCount; } @Override public boolean finished() { return iterationCount >= ITERATION_LIMIT; } @Override public Policy getPolicy() { return policy; } }
{ "content_hash": "37f9aea652882b77bfa89ec32052f686", "timestamp": "", "source": "github", "line_count": 196, "max_line_length": 217, "avg_line_length": 32.75, "alnum_prop": 0.5577192709144727, "repo_name": "sagersmith8/racetrack_ai", "id": "868b09b6d692142945931193bc9bfd8586946f2b", "size": "6419", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/main/java/com.ai/alg/QLearning.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Java", "bytes": "79037" } ], "symlink_target": "" }
bool FASTAParser::isValidPeptide(AASequence& pep) { String p = pep.toString(); if (p.hasSubstring("U") || p.hasSubstring("B") || p.hasSubstring("Z") || p.hasSubstring("J") || p.hasSubstring("X")) { return false; } return true; } void FASTAParser::digestProtein(FASTAFile::FASTAEntry& protein, EnzymaticDigestion& digestor) { std::vector<AASequence> peptides; digestor.digest(AASequence::fromString(protein.sequence), peptides); for (Size j = 0; j < peptides.size(); ++j) { if (peptides[j].size() >= MIN_PEPTIDE_LENGTH && peptides[j].size() <= MAX_PEPTIDE_LENGTH && peptides[j].getAverageWeight() <= MAX_MASS && isValidPeptide(peptides[j]) && unique_peptides.find(peptides[j]) == unique_peptides.end()) { unique_peptides.insert(peptides[j]); } } } void FASTAParser::digestFASTA() { std::vector<FASTAFile::FASTAEntry> proteins; FASTAFile().load(fasta_path, proteins); EnzymaticDigestion digestor; // default parameters are fully tryptic with 0 missed cleavages for (Size i = 0; i < proteins.size(); ++i) { digestProtein(proteins[i], digestor); } }
{ "content_hash": "32af173a72b3a4de137deaccc0d599b6", "timestamp": "", "source": "github", "line_count": 35, "max_line_length": 142, "avg_line_length": 33.628571428571426, "alnum_prop": 0.6380628717077316, "repo_name": "UNC-Major-Lab/Fragment-Isotope-Distribution-Paper", "id": "3e588794ea5e61b4ef079b6cff170d8c736ddef7", "size": "1251", "binary": false, "copies": "1", "ref": "refs/heads/Publication", "path": "FASTAParser.cpp", "mode": "33188", "license": "mit", "language": [ { "name": "C++", "bytes": "144455" }, { "name": "CMake", "bytes": "3229" }, { "name": "Java", "bytes": "13089" }, { "name": "Matlab", "bytes": "7293" }, { "name": "Python", "bytes": "7419" }, { "name": "R", "bytes": "15002" }, { "name": "Shell", "bytes": "15542" } ], "symlink_target": "" }
package com.hazelcast.multimap.impl; import com.hazelcast.cluster.Address; import com.hazelcast.core.EntryEventType; import com.hazelcast.map.impl.event.EntryEventData; import com.hazelcast.map.impl.event.MapEventData; import com.hazelcast.internal.serialization.Data; import com.hazelcast.spi.impl.NodeEngine; import com.hazelcast.spi.impl.eventservice.EventRegistration; import com.hazelcast.spi.impl.eventservice.EventService; import java.util.Collection; /** * Publishes multimap entry and map events through eventService */ public class MultiMapEventsPublisher { private final NodeEngine nodeEngine; public MultiMapEventsPublisher(NodeEngine nodeEngine) { this.nodeEngine = nodeEngine; } public void publishMultiMapEvent(String mapName, EntryEventType eventType, int numberOfEntriesAffected) { EventService eventService = nodeEngine.getEventService(); Collection<EventRegistration> registrations = eventService.getRegistrations(MultiMapService.SERVICE_NAME, mapName); if (registrations.isEmpty()) { return; } Address caller = nodeEngine.getThisAddress(); String source = caller.toString(); MapEventData mapEventData = new MapEventData(source, mapName, caller, eventType.getType(), numberOfEntriesAffected); eventService.publishEvent(MultiMapService.SERVICE_NAME, registrations, mapEventData, mapName.hashCode()); } public final void publishEntryEvent(String multiMapName, EntryEventType eventType, Data key, Object newValue, Object oldValue) { EventService eventService = nodeEngine.getEventService(); Collection<EventRegistration> registrations = eventService.getRegistrations(MultiMapService.SERVICE_NAME, multiMapName); for (EventRegistration registration : registrations) { MultiMapEventFilter filter = (MultiMapEventFilter) registration.getFilter(); if (filter.getKey() == null || filter.getKey().equals(key)) { Data dataNewValue = filter.isIncludeValue() ? nodeEngine.toData(newValue) : null; Data dataOldValue = filter.isIncludeValue() ? nodeEngine.toData(oldValue) : null; Address caller = nodeEngine.getThisAddress(); String source = caller.toString(); EntryEventData event = new EntryEventData(source, multiMapName, caller, key, dataNewValue, dataOldValue, eventType.getType()); eventService.publishEvent(MultiMapService.SERVICE_NAME, registration, event, multiMapName.hashCode()); } } } }
{ "content_hash": "f3432aa355b1689c4cf6fb76b7f6f6f5", "timestamp": "", "source": "github", "line_count": 56, "max_line_length": 128, "avg_line_length": 47.42857142857143, "alnum_prop": 0.7134789156626506, "repo_name": "emre-aydin/hazelcast", "id": "95d58cbc5b284b49725ddfdd55e5400176d6913d", "size": "3281", "binary": false, "copies": "4", "ref": "refs/heads/master", "path": "hazelcast/src/main/java/com/hazelcast/multimap/impl/MultiMapEventsPublisher.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": "" }
<!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> <title>lesniewski-mereology: Not compatible 👼</title> <link rel="shortcut icon" type="image/png" href="../../../../../favicon.png" /> <link href="../../../../../bootstrap.min.css" rel="stylesheet"> <link href="../../../../../bootstrap-custom.css" rel="stylesheet"> <link href="//maxcdn.bootstrapcdn.com/font-awesome/4.2.0/css/font-awesome.min.css" rel="stylesheet"> <script src="../../../../../moment.min.js"></script> <!-- HTML5 Shim and Respond.js IE8 support of HTML5 elements and media queries --> <!-- WARNING: Respond.js doesn't work if you view the page via file:// --> <!--[if lt IE 9]> <script src="https://oss.maxcdn.com/html5shiv/3.7.2/html5shiv.min.js"></script> <script src="https://oss.maxcdn.com/respond/1.4.2/respond.min.js"></script> <![endif]--> </head> <body> <div class="container"> <div class="navbar navbar-default" role="navigation"> <div class="container-fluid"> <div class="navbar-header"> <a class="navbar-brand" href="../../../../.."><i class="fa fa-lg fa-flag-checkered"></i> Coq bench</a> </div> <div id="navbar" class="collapse navbar-collapse"> <ul class="nav navbar-nav"> <li><a href="../..">clean / released</a></li> <li class="active"><a href="">8.13.2 / lesniewski-mereology - 8.8.0</a></li> </ul> </div> </div> </div> <div class="article"> <div class="row"> <div class="col-md-12"> <a href="../..">« Up</a> <h1> lesniewski-mereology <small> 8.8.0 <span class="label label-info">Not compatible 👼</span> </small> </h1> <p>📅 <em><script>document.write(moment("2022-10-06 17:21:09 +0000", "YYYY-MM-DD HH:mm:ss Z").fromNow());</script> (2022-10-06 17:21:09 UTC)</em><p> <h2>Context</h2> <pre># Packages matching: installed # Name # Installed # Synopsis base-bigarray base base-num base Num library distributed with the OCaml compiler base-threads base base-unix base conf-findutils 1 Virtual package relying on findutils conf-gmp 4 Virtual package relying on a GMP lib system installation coq 8.13.2 Formal proof management system num 0 The Num library for arbitrary-precision integer and rational arithmetic ocaml 4.05.0 The OCaml compiler (virtual package) ocaml-base-compiler 4.05.0 Official 4.05.0 release ocaml-config 1 OCaml Switch Configuration ocamlfind 1.9.5 A library manager for OCaml zarith 1.12 Implements arithmetic and logical operations over arbitrary-precision integers # opam file: opam-version: &quot;2.0&quot; maintainer: &quot;Hugo.Herbelin@inria.fr&quot; homepage: &quot;https://github.com/coq-contribs/lesniewski-mereology&quot; license: &quot;LGPL&quot; build: [make &quot;-j%{jobs}%&quot;] install: [make &quot;install&quot;] remove: [&quot;rm&quot; &quot;-R&quot; &quot;%{lib}%/coq/user-contrib/LesniewskiMereology&quot;] depends: [ &quot;ocaml&quot; &quot;coq&quot; {&gt;= &quot;8.8&quot; &amp; &lt; &quot;8.9~&quot;} ] tags: [ &quot;keyword: mereology&quot; &quot;keyword: protothetic&quot; &quot;keyword: ontology&quot; &quot;keyword: nominalist theory&quot; &quot;keyword: extensionality&quot; &quot;category: Mathematics/Logic/Foundations&quot; ] authors: [ &quot;Richard Dapoigny &lt;richard.dapoigny@univ-savoie.fr&gt; [https://www.researchgate.net/profile/Richard_Dapoigny]&quot; &quot;Patrick Barlatier &lt;patrick.barlatier@univ-savoie.fr&gt; [https://www.researchgate.net/profile/Patrick_Barlatier]&quot; ] bug-reports: &quot;https://github.com/coq-contribs/lesniewski-mereology/issues&quot; dev-repo: &quot;git+https://github.com/coq-contribs/lesniewski-mereology.git&quot; synopsis: &quot;Knowledge-based Dependently Typed Language (KDTL)&quot; description: &quot;&quot;&quot; http://www.polytech.univ-savoie.fr/index.php?id=listic-logiciels-coq&amp;L=1 LesniewskiMereology is a Coq library created by R. Dapoigny and P. Barlatier whose purpose is to implement the alternative to Set Theory of Stanislaw Lesniewski. It is part of an on-going project using the Coq language and called KDTL (Knowledge-based Dependently Typed Language) to build an alternative to Description Logics. The developed theory is close to the analysis of Denis Mieville (1984) in his book &quot;Un developpement des systemes logiques de Stanislaw Lesniewski&quot;. It is a theoretical construct which relies on three dependent levels, logic (a.k.a. Protothetic), the Lesniewski Ontologie (LO) and mereology. Each level incorporates a minimal collection of axioms, protothetic and ontologic definitions and a set of theorems together with their intuitionist proofs.&quot;&quot;&quot; flags: light-uninstall url { src: &quot;https://github.com/coq-contribs/lesniewski-mereology/archive/v8.8.0.tar.gz&quot; checksum: &quot;md5=24ca05ae88c1a992e3191ad0558f6e62&quot; } </pre> <h2>Lint</h2> <dl class="dl-horizontal"> <dt>Command</dt> <dd><code>true</code></dd> <dt>Return code</dt> <dd>0</dd> </dl> <h2>Dry install 🏜️</h2> <p>Dry install with the current Coq version:</p> <dl class="dl-horizontal"> <dt>Command</dt> <dd><code>opam install -y --show-action coq-lesniewski-mereology.8.8.0 coq.8.13.2</code></dd> <dt>Return code</dt> <dd>5120</dd> <dt>Output</dt> <dd><pre>[NOTE] Package coq is already installed (current version is 8.13.2). The following dependencies couldn&#39;t be met: - coq-lesniewski-mereology -&gt; coq &lt; 8.9~ -&gt; ocaml &lt; 4.03.0 base of this switch (use `--unlock-base&#39; to force) Your request can&#39;t be satisfied: - No available version of coq satisfies the constraints No solution found, exiting </pre></dd> </dl> <p>Dry install without Coq/switch base, to test if the problem was incompatibility with the current Coq/OCaml version:</p> <dl class="dl-horizontal"> <dt>Command</dt> <dd><code>opam remove -y coq; opam install -y --show-action --unlock-base coq-lesniewski-mereology.8.8.0</code></dd> <dt>Return code</dt> <dd>0</dd> </dl> <h2>Install dependencies</h2> <dl class="dl-horizontal"> <dt>Command</dt> <dd><code>true</code></dd> <dt>Return code</dt> <dd>0</dd> <dt>Duration</dt> <dd>0 s</dd> </dl> <h2>Install 🚀</h2> <dl class="dl-horizontal"> <dt>Command</dt> <dd><code>true</code></dd> <dt>Return code</dt> <dd>0</dd> <dt>Duration</dt> <dd>0 s</dd> </dl> <h2>Installation size</h2> <p>No files were installed.</p> <h2>Uninstall 🧹</h2> <dl class="dl-horizontal"> <dt>Command</dt> <dd><code>true</code></dd> <dt>Return code</dt> <dd>0</dd> <dt>Missing removes</dt> <dd> none </dd> <dt>Wrong removes</dt> <dd> none </dd> </dl> </div> </div> </div> <hr/> <div class="footer"> <p class="text-center"> Sources are on <a href="https://github.com/coq-bench">GitHub</a> © Guillaume Claret 🐣 </p> </div> </div> <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script> <script src="../../../../../bootstrap.min.js"></script> </body> </html>
{ "content_hash": "723310fb4b5ccf8b4523e3d296d25b28", "timestamp": "", "source": "github", "line_count": 168, "max_line_length": 803, "avg_line_length": 49.17261904761905, "alnum_prop": 0.5857644352983901, "repo_name": "coq-bench/coq-bench.github.io", "id": "63b7342197b5ca3fb0495741c4cf4db4d50492a3", "size": "8286", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "clean/Linux-x86_64-4.05.0-2.0.1/released/8.13.2/lesniewski-mereology/8.8.0.html", "mode": "33188", "license": "mit", "language": [], "symlink_target": "" }
module ActsAsLimitable VERSION = 0.2 end
{ "content_hash": "d4b2f09e85402b604e2e916ef202bc3b", "timestamp": "", "source": "github", "line_count": 3, "max_line_length": 22, "avg_line_length": 14.333333333333334, "alnum_prop": 0.7674418604651163, "repo_name": "deevis/acts_as_limitable", "id": "293dc936fd7ccd71dcdc716766c97916bee259a4", "size": "43", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "lib/acts_as_limitable/version.rb", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "CSS", "bytes": "686" }, { "name": "HTML", "bytes": "4883" }, { "name": "JavaScript", "bytes": "596" }, { "name": "Ruby", "bytes": "52388" } ], "symlink_target": "" }
from swgpy.object import * def create(kernel): result = Intangible() result.template = "object/draft_schematic/clothing/shared_clothing_bikini_casual_02.iff" result.attribute_template_id = -1 result.stfName("string_id_table","") #### BEGIN MODIFICATIONS #### #### END MODIFICATIONS #### return result
{ "content_hash": "3dd6431b76cea7e42ff5618dc4b42e81", "timestamp": "", "source": "github", "line_count": 13, "max_line_length": 89, "avg_line_length": 24.46153846153846, "alnum_prop": 0.7012578616352201, "repo_name": "obi-two/Rebelion", "id": "94148e70573324969e9bb7e89284a53507cdc556", "size": "463", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "data/scripts/templates/object/draft_schematic/clothing/shared_clothing_bikini_casual_02.py", "mode": "33188", "license": "mit", "language": [ { "name": "Batchfile", "bytes": "11818" }, { "name": "C", "bytes": "7699" }, { "name": "C++", "bytes": "2293610" }, { "name": "CMake", "bytes": "39727" }, { "name": "PLSQL", "bytes": "42065" }, { "name": "Python", "bytes": "7499185" }, { "name": "SQLPL", "bytes": "41864" } ], "symlink_target": "" }
require_relative '../helper' describe Dalli::Protocol::ValueSerializer do describe 'options' do subject { Dalli::Protocol::ValueSerializer.new(options) } describe 'serializer' do describe 'when the serializer option is unspecified' do let(:options) { {} } it 'defaults to Marshal' do assert_equal subject.serializer, ::Marshal end end describe 'when the serializer option is explicitly specified' do let(:dummy_serializer) { Object.new } let(:options) { { serializer: dummy_serializer } } it 'uses the explicit option' do assert_equal subject.serializer, dummy_serializer end end end end describe 'store' do let(:bitflags) { rand(32) } let(:serializer) { Minitest::Mock.new } let(:serialized_dummy) { SecureRandom.hex(8) } let(:serializer_options) { { serializer: serializer } } let(:vs) { Dalli::Protocol::ValueSerializer.new(vs_options) } let(:vs_options) { { serializer: serializer } } let(:raw_value) { Object.new } describe 'when the request options are nil' do let(:req_options) { nil } it 'serializes the value' do serializer.expect :dump, serialized_dummy, [raw_value] val, newbitflags = vs.store(raw_value, req_options, bitflags) assert_equal val, serialized_dummy assert_equal newbitflags, (bitflags | 0x1) serializer.verify end end describe 'when the request options do not specify a value for the :raw key' do let(:req_options) { { other: SecureRandom.hex(4) } } it 'serializes the value' do serializer.expect :dump, serialized_dummy, [raw_value] val, newbitflags = vs.store(raw_value, req_options, bitflags) assert_equal val, serialized_dummy assert_equal newbitflags, (bitflags | 0x1) serializer.verify end end describe 'when the request options value for the :raw key is false' do let(:req_options) { { raw: false } } it 'serializes the value' do serializer.expect :dump, serialized_dummy, [raw_value] val, newbitflags = vs.store(raw_value, req_options, bitflags) assert_equal val, serialized_dummy assert_equal newbitflags, (bitflags | 0x1) serializer.verify end end describe 'when the request options value for the :raw key is true' do let(:req_options) { { raw: true } } it 'does not call the serializer and just converts the input value to a string' do val, newbitflags = vs.store(raw_value, req_options, bitflags) assert_equal val, raw_value.to_s assert_equal newbitflags, bitflags serializer.verify end end describe 'when serialization raises a TimeoutError' do let(:error_message) { SecureRandom.hex(10) } let(:serializer) { Marshal } let(:req_options) { {} } it 'reraises the Timeout::Error' do error = ->(_arg) { raise Timeout::Error, error_message } serializer.stub :dump, error do exception = assert_raises Timeout::Error do vs.store(raw_value, req_options, bitflags) end assert_equal exception.message, error_message end end end describe 'when serialization raises an Error that is not a TimeoutError' do let(:error_message) { SecureRandom.hex(10) } let(:serializer) { Marshal } let(:req_options) { {} } it 'translates that into a MarshalError' do error = ->(_arg) { raise StandardError, error_message } serializer.stub :dump, error do exception = assert_raises Dalli::MarshalError do vs.store(raw_value, req_options, bitflags) end assert_equal exception.message, error_message end end end describe 'when serialization raises an Error that is not a TimeoutError' do let(:error_message) { SecureRandom.hex(10) } let(:serializer) { Marshal } let(:req_options) { {} } it 'translates that into a MarshalError' do error = ->(_arg) { raise StandardError, error_message } serializer.stub :dump, error do exception = assert_raises Dalli::MarshalError do vs.store(raw_value, req_options, bitflags) end assert_equal exception.message, error_message end end end end describe 'retrieve' do let(:raw_value) { SecureRandom.hex(8) } let(:deserialized_dummy) { SecureRandom.hex(8) } let(:serializer) { Minitest::Mock.new } let(:vs_options) { { serializer: serializer } } let(:vs) { Dalli::Protocol::ValueSerializer.new(vs_options) } describe 'when the bitflags do not specify serialization' do it 'should return the value without deserializing' do bitflags = rand(32) bitflags &= 0xFFFE assert_equal(0, bitflags & 0x1) assert_equal vs.retrieve(raw_value, bitflags), raw_value serializer.verify end end describe 'when the bitflags specify serialization' do it 'should deserialize the value' do serializer.expect :load, deserialized_dummy, [raw_value] bitflags = rand(32) bitflags |= 0x1 assert_equal(0x1, bitflags & 0x1) assert_equal vs.retrieve(raw_value, bitflags), deserialized_dummy serializer.verify end end describe 'when deserialization raises a TypeError for needs to have method `_load' do let(:error_message) { "needs to have method `_load'" } let(:serializer) { Marshal } # TODO: Determine what scenario causes this error it 'raises UnmarshalError on uninitialized constant' do error = ->(_arg) { raise TypeError, error_message } exception = serializer.stub :load, error do assert_raises Dalli::UnmarshalError do vs.retrieve(raw_value, Dalli::Protocol::ValueSerializer::FLAG_SERIALIZED) end end assert_equal exception.message, "Unable to unmarshal value: #{error_message}" end end describe 'when deserialization raises a TypeError for exception class/object expected' do let(:error_message) { 'exception class/object expected' } let(:serializer) { Marshal } # TODO: Determine what scenario causes this error it 'raises UnmarshalError on uninitialized constant' do error = ->(_arg) { raise TypeError, error_message } exception = serializer.stub :load, error do assert_raises Dalli::UnmarshalError do vs.retrieve(raw_value, Dalli::Protocol::ValueSerializer::FLAG_SERIALIZED) end end assert_equal exception.message, "Unable to unmarshal value: #{error_message}" end end describe 'when deserialization raises an TypeError for an instance of IO needed' do let(:error_message) { 'instance of IO needed' } let(:serializer) { Marshal } let(:raw_value) { Object.new } it 'raises UnmarshalError on uninitialized constant' do exception = assert_raises Dalli::UnmarshalError do vs.retrieve(raw_value, Dalli::Protocol::ValueSerializer::FLAG_SERIALIZED) end assert_equal exception.message, "Unable to unmarshal value: #{error_message}" end end describe "when deserialization raises an TypeError for an incompatible marshal file format (can't be read)" do let(:error_message) { "incompatible marshal file format (can't be read)" } let(:serializer) { Marshal } let(:raw_value) { '{"a":"b"}' } it 'raises UnmarshalError on uninitialized constant' do exception = assert_raises Dalli::UnmarshalError do vs.retrieve(raw_value, Dalli::Protocol::ValueSerializer::FLAG_SERIALIZED) end assert exception.message.start_with?("Unable to unmarshal value: #{error_message}") end end describe 'when deserialization raises a TypeError with a non-matching message' do let(:error_message) { SecureRandom.hex(10) } let(:serializer) { Marshal } it 're-raises TypeError' do error = ->(_arg) { raise TypeError, error_message } exception = serializer.stub :load, error do assert_raises TypeError do vs.retrieve(raw_value, Dalli::Protocol::ValueSerializer::FLAG_SERIALIZED) end end assert_equal error_message, exception.message end end describe 'when deserialization raises a NameError for an uninitialized constant' do let(:error_message) { 'uninitialized constant Ddd' } let(:serializer) { Marshal } # TODO: Determine what scenario causes this error it 'raises UnmarshalError on uninitialized constant' do error = ->(_arg) { raise NameError, error_message } exception = serializer.stub :load, error do assert_raises Dalli::UnmarshalError do vs.retrieve(raw_value, Dalli::Protocol::ValueSerializer::FLAG_SERIALIZED) end end assert exception.message.start_with?("Unable to unmarshal value: #{error_message}") end end describe 'when deserialization raises a NameError with a non-matching message' do let(:error_message) { SecureRandom.hex(10) } let(:serializer) { Marshal } it 're-raises NameError' do error = ->(_arg) { raise NameError, error_message } exception = serializer.stub :load, error do assert_raises NameError do vs.retrieve(raw_value, Dalli::Protocol::ValueSerializer::FLAG_SERIALIZED) end end assert exception.message.start_with?(error_message) end end describe 'when deserialization raises an ArgumentError for an undefined class' do let(:error_message) { 'undefined class/module NonexistentClass' } let(:serializer) { Marshal } let(:raw_value) { "\x04\bo:\x15NonexistentClass\x00" } it 'raises UnmarshalError on uninitialized constant' do exception = assert_raises Dalli::UnmarshalError do vs.retrieve(raw_value, Dalli::Protocol::ValueSerializer::FLAG_SERIALIZED) end assert_equal exception.message, "Unable to unmarshal value: #{error_message}" end end describe 'when deserialization raises an ArgumentError for marshal data too short' do let(:error_message) { 'marshal data too short' } let(:serializer) { Marshal } let(:raw_value) { "\x04\bo:\vObj" } it 'raises UnmarshalError on uninitialized constant' do exception = assert_raises Dalli::UnmarshalError do vs.retrieve(raw_value, Dalli::Protocol::ValueSerializer::FLAG_SERIALIZED) end assert_equal exception.message, "Unable to unmarshal value: #{error_message}" end end describe 'when deserialization raises an ArgumentError with a non-matching message' do let(:error_message) { SecureRandom.hex(10) } let(:serializer) { Marshal } it 're-raises ArgumentError' do error = ->(_arg) { raise ArgumentError, error_message } exception = serializer.stub :load, error do assert_raises ArgumentError do vs.retrieve(raw_value, Dalli::Protocol::ValueSerializer::FLAG_SERIALIZED) end end assert_equal exception.message, error_message end end describe 'when using the default serializer' do let(:deserialized_value) { SecureRandom.hex(1024) } let(:serialized_value) { Marshal.dump(deserialized_value) } let(:vs_options) { {} } let(:vs) { Dalli::Protocol::ValueSerializer.new(vs_options) } it 'properly deserializes the serialized value' do assert_equal vs.retrieve(serialized_value, Dalli::Protocol::ValueSerializer::FLAG_SERIALIZED), deserialized_value end it 'raises UnmarshalError for non-seriaized data' do assert_raises Dalli::UnmarshalError do vs.retrieve(:not_serialized_value, Dalli::Protocol::ValueSerializer::FLAG_SERIALIZED) end end end end end
{ "content_hash": "803c992bcfa48c75eba92105f2993775", "timestamp": "", "source": "github", "line_count": 323, "max_line_length": 114, "avg_line_length": 37.46749226006192, "alnum_prop": 0.6478268054866965, "repo_name": "mperham/dalli", "id": "0127c180fd97921e84451f0b78f299c0f80d0dc6", "size": "12133", "binary": false, "copies": "1", "ref": "refs/heads/main", "path": "test/protocol/test_value_serializer.rb", "mode": "33188", "license": "mit", "language": [ { "name": "Ruby", "bytes": "143020" } ], "symlink_target": "" }
require 'test/unit' require File.join(File.expand_path(File.dirname(__FILE__)), 'gemutilities') require 'rubygems/commands/pristine_command' class TestGemCommandsPristineCommand < RubyGemTestCase def setup super @cmd = Gem::Commands::PristineCommand.new end def test_execute a = quick_gem 'a' do |s| s.executables = %w[foo] end FileUtils.mkdir_p File.join(@tempdir, 'bin') File.open File.join(@tempdir, 'bin', 'foo'), 'w' do |fp| fp.puts "#!/usr/bin/ruby" end install_gem a @cmd.options[:args] = %w[a] use_ui @ui do @cmd.execute end out = @ui.output.split "\n" assert_equal "Restoring gem(s) to pristine condition...", out.shift assert_equal "#{a.full_name} is in pristine condition", out.shift assert out.empty?, out.inspect end def test_execute_all a = quick_gem 'a' do |s| s.executables = %w[foo] end FileUtils.mkdir_p File.join(@tempdir, 'bin') File.open File.join(@tempdir, 'bin', 'foo'), 'w' do |fp| fp.puts "#!/usr/bin/ruby" end install_gem a gem_bin = File.join @gemhome, 'gems', "#{a.full_name}", 'bin', 'foo' FileUtils.rm gem_bin @cmd.handle_options %w[--all] use_ui @ui do @cmd.execute end out = @ui.output.split "\n" assert_equal "Restoring gem(s) to pristine condition...", out.shift assert_equal "Restoring 1 file to #{a.full_name}...", out.shift assert_equal " #{gem_bin}", out.shift assert out.empty?, out.inspect end def test_execute_missing_cache_gem a = quick_gem 'a' do |s| s.executables = %w[foo] end FileUtils.mkdir_p File.join(@tempdir, 'bin') File.open File.join(@tempdir, 'bin', 'foo'), 'w' do |fp| fp.puts "#!/usr/bin/ruby" end install_gem a FileUtils.rm File.join(@gemhome, 'cache', "#{a.full_name}.gem") @cmd.options[:args] = %w[a] use_ui @ui do @cmd.execute end out = @ui.output.split "\n" assert_equal "Restoring gem\(s\) to pristine condition...", out.shift assert out.empty?, out.inspect assert_equal "ERROR: Cached gem for #{a.full_name} not found, use `gem install` to restore\n", @ui.error end def test_execute_no_gem @cmd.options[:args] = %w[] e = assert_raise Gem::CommandLineError do use_ui @ui do @cmd.execute end end assert_match %r|specify a gem name|, e.message end end
{ "content_hash": "61f9a944f88b243a7120222d5e80751a", "timestamp": "", "source": "github", "line_count": 100, "max_line_length": 99, "avg_line_length": 24.2, "alnum_prop": 0.6128099173553719, "repo_name": "thewoolleyman/geminstaller", "id": "cd1d3500aeead20af5301bb5d1496808e0835a39", "size": "2420", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "spec/fixture/rubygems_dist/rubygems-1.1.1/test/test_gem_commands_pristine_command.rb", "mode": "33188", "license": "mit", "language": [ { "name": "JavaScript", "bytes": "148" }, { "name": "Ruby", "bytes": "2285563" }, { "name": "Shell", "bytes": "1466" } ], "symlink_target": "" }
<?xml version="1.0" ?><!DOCTYPE TS><TS language="ca_ES" version="2.0"> <defaultcodec>UTF-8</defaultcodec> <context> <name>AboutDialog</name> <message> <location filename="../forms/aboutdialog.ui" line="+14"/> <source>About TielnetCoin</source> <translation>Sobre TielnetCoin</translation> </message> <message> <location line="+39"/> <source>&lt;b&gt;TielnetCoin&lt;/b&gt; version</source> <translation>&lt;b&gt;TielnetCoin&lt;/b&gt; versió</translation> </message> <message> <location line="+57"/> <source> This is experimental software. Distributed under the MIT/X11 software license, see the accompanying file COPYING or http://www.opensource.org/licenses/mit-license.php. This product includes software developed by the OpenSSL Project for use in the OpenSSL Toolkit (http://www.openssl.org/) and cryptographic software written by Eric Young (eay@cryptsoft.com) and UPnP software written by Thomas Bernard.</source> <translation>\n Aquest és software experimental.\n\n Distribuït sota llicència de software MIT/11, veure l&apos;arxiu COPYING o http://www.opensource.org/licenses/mit-license.php.\n\nAquest producte inclou software desarrollat pel projecte OpenSSL per a l&apos;ús de OppenSSL Toolkit (http://www.openssl.org/) i de softwqre criptogràfic escrit per l&apos;Eric Young (eay@cryptsoft.com) i software UPnP escrit per en Thomas Bernard.</translation> </message> <message> <location filename="../aboutdialog.cpp" line="+14"/> <source>Copyright</source> <translation>Copyright</translation> </message> <message> <location line="+0"/> <source>The TielnetCoin developers</source> <translation type="unfinished"/> </message> </context> <context> <name>AddressBookPage</name> <message> <location filename="../forms/addressbookpage.ui" line="+14"/> <source>Address Book</source> <translation>Llibreta d&apos;adreces</translation> </message> <message> <location line="+19"/> <source>Double-click to edit address or label</source> <translation>Feu doble clic per editar l&apos;adreça o l&apos;etiqueta</translation> </message> <message> <location line="+27"/> <source>Create a new address</source> <translation>Crear una nova adreça</translation> </message> <message> <location line="+14"/> <source>Copy the currently selected address to the system clipboard</source> <translation>Copiar l&apos;adreça seleccionada al porta-retalls del sistema</translation> </message> <message> <location line="-11"/> <source>&amp;New Address</source> <translation>&amp;Nova adreça</translation> </message> <message> <location filename="../addressbookpage.cpp" line="+63"/> <source>These are your TielnetCoin addresses for receiving payments. You may want to give a different one to each sender so you can keep track of who is paying you.</source> <translation>Aquestes són les teves adreces TielnetCoin per a rebre pagaments. Pot interesar-te proveïr diferents adreces a cadascun dels enviadors així pots identificar qui et va pagant.</translation> </message> <message> <location filename="../forms/addressbookpage.ui" line="+14"/> <source>&amp;Copy Address</source> <translation>&amp;Copiar adreça</translation> </message> <message> <location line="+11"/> <source>Show &amp;QR Code</source> <translation>Mostrar codi &amp;QR</translation> </message> <message> <location line="+11"/> <source>Sign a message to prove you own a TielnetCoin address</source> <translation>Signa el missatge per provar que ets propietari de l&apos;adreça TielnetCoin</translation> </message> <message> <location line="+3"/> <source>Sign &amp;Message</source> <translation>Signar &amp;Missatge</translation> </message> <message> <location line="+25"/> <source>Delete the currently selected address from the list</source> <translation>Esborrar l&apos;adreça sel·leccionada</translation> </message> <message> <location line="+27"/> <source>Export the data in the current tab to a file</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>&amp;Export</source> <translation type="unfinished"/> </message> <message> <location line="-44"/> <source>Verify a message to ensure it was signed with a specified TielnetCoin address</source> <translation>Verificar un missatge per asegurar-se que ha estat signat amb una adreça TielnetCoin específica</translation> </message> <message> <location line="+3"/> <source>&amp;Verify Message</source> <translation>&amp;Verificar el missatge</translation> </message> <message> <location line="+14"/> <source>&amp;Delete</source> <translation>&amp;Esborrar</translation> </message> <message> <location filename="../addressbookpage.cpp" line="-5"/> <source>These are your TielnetCoin addresses for sending payments. Always check the amount and the receiving address before sending coins.</source> <translation>Aquestes són la seva adreça de TielnetCoin per enviar els pagaments. Sempre revisi la quantitat i l&apos;adreça del destinatari abans transferència de monedes.</translation> </message> <message> <location line="+13"/> <source>Copy &amp;Label</source> <translation>Copiar &amp;Etiqueta</translation> </message> <message> <location line="+1"/> <source>&amp;Edit</source> <translation>&amp;Editar</translation> </message> <message> <location line="+1"/> <source>Send &amp;Coins</source> <translation>Enviar &amp;Monedes</translation> </message> <message> <location line="+260"/> <source>Export Address Book Data</source> <translation>Exporta llibreta d&apos;adreces</translation> </message> <message> <location line="+1"/> <source>Comma separated file (*.csv)</source> <translation>Arxiu de separació per comes (*.csv)</translation> </message> <message> <location line="+13"/> <source>Error exporting</source> <translation>Error en l&apos;exportació</translation> </message> <message> <location line="+0"/> <source>Could not write to file %1.</source> <translation>No s&apos;ha pogut escriure a l&apos;arxiu %1.</translation> </message> </context> <context> <name>AddressTableModel</name> <message> <location filename="../addresstablemodel.cpp" line="+144"/> <source>Label</source> <translation>Etiqueta</translation> </message> <message> <location line="+0"/> <source>Address</source> <translation>Adreça</translation> </message> <message> <location line="+36"/> <source>(no label)</source> <translation>(sense etiqueta)</translation> </message> </context> <context> <name>AskPassphraseDialog</name> <message> <location filename="../forms/askpassphrasedialog.ui" line="+26"/> <source>Passphrase Dialog</source> <translation>Dialeg de contrasenya</translation> </message> <message> <location line="+21"/> <source>Enter passphrase</source> <translation>Introdueix contrasenya</translation> </message> <message> <location line="+14"/> <source>New passphrase</source> <translation>Nova contrasenya</translation> </message> <message> <location line="+14"/> <source>Repeat new passphrase</source> <translation>Repeteix la nova contrasenya</translation> </message> <message> <location filename="../askpassphrasedialog.cpp" line="+33"/> <source>Enter the new passphrase to the wallet.&lt;br/&gt;Please use a passphrase of &lt;b&gt;10 or more random characters&lt;/b&gt;, or &lt;b&gt;eight or more words&lt;/b&gt;.</source> <translation>Introdueixi la nova contrasenya al moneder&lt;br/&gt;Si us plau useu una contrasenya de &lt;b&gt;10 o més caracters aleatoris&lt;/b&gt;, o &lt;b&gt;vuit o més paraules&lt;/b&gt;.</translation> </message> <message> <location line="+1"/> <source>Encrypt wallet</source> <translation>Xifrar la cartera</translation> </message> <message> <location line="+3"/> <source>This operation needs your wallet passphrase to unlock the wallet.</source> <translation>Aquesta operació requereix la seva contrasenya del moneder per a desbloquejar-lo.</translation> </message> <message> <location line="+5"/> <source>Unlock wallet</source> <translation>Desbloqueja el moneder</translation> </message> <message> <location line="+3"/> <source>This operation needs your wallet passphrase to decrypt the wallet.</source> <translation>Aquesta operació requereix la seva contrasenya del moneder per a desencriptar-lo.</translation> </message> <message> <location line="+5"/> <source>Decrypt wallet</source> <translation>Desencripta el moneder</translation> </message> <message> <location line="+3"/> <source>Change passphrase</source> <translation>Canviar la contrasenya</translation> </message> <message> <location line="+1"/> <source>Enter the old and new passphrase to the wallet.</source> <translation>Introdueixi tant l&apos;antiga com la nova contrasenya de moneder.</translation> </message> <message> <location line="+46"/> <source>Confirm wallet encryption</source> <translation>Confirmar l&apos;encriptació del moneder</translation> </message> <message> <location line="+1"/> <source>Warning: If you encrypt your wallet and lose your passphrase, you will &lt;b&gt;LOSE ALL OF YOUR LITECOINS&lt;/b&gt;!</source> <translation>Advertència: Si encripteu el vostre moneder i perdeu la constrasenya, &lt;b&gt;PERDREU TOTS ELS VOSTRES LITECOINS&lt;/b&gt;!</translation> </message> <message> <location line="+0"/> <source>Are you sure you wish to encrypt your wallet?</source> <translation>Esteu segur que voleu encriptar el vostre moneder?</translation> </message> <message> <location line="+15"/> <source>IMPORTANT: Any previous backups you have made of your wallet file should be replaced with the newly generated, encrypted wallet file. For security reasons, previous backups of the unencrypted wallet file will become useless as soon as you start using the new, encrypted wallet.</source> <translation>IMPORTANT: Tota copia de seguretat que hagis realitzat hauria de ser reemplaçada pel, recentment generat, arxiu encriptat del moneder.</translation> </message> <message> <location line="+100"/> <location line="+24"/> <source>Warning: The Caps Lock key is on!</source> <translation>Advertència: Les lletres majúscules estàn activades!</translation> </message> <message> <location line="-130"/> <location line="+58"/> <source>Wallet encrypted</source> <translation>Moneder encriptat</translation> </message> <message> <location line="-56"/> <source>TielnetCoin will close now to finish the encryption process. Remember that encrypting your wallet cannot fully protect your tielnetcoins from being stolen by malware infecting your computer.</source> <translation>TielnetCoin es tancarà ara per acabar el procés d&apos;encriptació. Recorda que encriptar el teu moneder no protegeix completament els teus tielnetcoins de ser robades per programari maliciós instal·lat al teu ordinador.</translation> </message> <message> <location line="+13"/> <location line="+7"/> <location line="+42"/> <location line="+6"/> <source>Wallet encryption failed</source> <translation>L&apos;encriptació del moneder ha fallat</translation> </message> <message> <location line="-54"/> <source>Wallet encryption failed due to an internal error. Your wallet was not encrypted.</source> <translation>L&apos;encriptació del moneder ha fallat per un error intern. El seu moneder no ha estat encriptat.</translation> </message> <message> <location line="+7"/> <location line="+48"/> <source>The supplied passphrases do not match.</source> <translation>La contrasenya introduïda no coincideix.</translation> </message> <message> <location line="-37"/> <source>Wallet unlock failed</source> <translation>El desbloqueig del moneder ha fallat</translation> </message> <message> <location line="+1"/> <location line="+11"/> <location line="+19"/> <source>The passphrase entered for the wallet decryption was incorrect.</source> <translation>La contrasenya introduïda per a desencriptar el moneder és incorrecte.</translation> </message> <message> <location line="-20"/> <source>Wallet decryption failed</source> <translation>La desencriptació del moneder ha fallat</translation> </message> <message> <location line="+14"/> <source>Wallet passphrase was successfully changed.</source> <translation>La contrasenya del moneder ha estat modificada correctament.</translation> </message> </context> <context> <name>BitcoinGUI</name> <message> <location filename="../bitcoingui.cpp" line="+233"/> <source>Sign &amp;message...</source> <translation>Signar &amp;missatge...</translation> </message> <message> <location line="+280"/> <source>Synchronizing with network...</source> <translation>Sincronitzant amb la xarxa ...</translation> </message> <message> <location line="-349"/> <source>&amp;Overview</source> <translation>&amp;Panorama general</translation> </message> <message> <location line="+1"/> <source>Show general overview of wallet</source> <translation>Mostra panorama general del moneder</translation> </message> <message> <location line="+20"/> <source>&amp;Transactions</source> <translation>&amp;Transaccions</translation> </message> <message> <location line="+1"/> <source>Browse transaction history</source> <translation>Cerca a l&apos;historial de transaccions</translation> </message> <message> <location line="+7"/> <source>Edit the list of stored addresses and labels</source> <translation>Edita la llista d&apos;adreces emmagatzemada i etiquetes</translation> </message> <message> <location line="-14"/> <source>Show the list of addresses for receiving payments</source> <translation>Mostra el llistat d&apos;adreces per rebre pagaments</translation> </message> <message> <location line="+31"/> <source>E&amp;xit</source> <translation>S&amp;ortir</translation> </message> <message> <location line="+1"/> <source>Quit application</source> <translation>Sortir de l&apos;aplicació</translation> </message> <message> <location line="+4"/> <source>Show information about TielnetCoin</source> <translation>Mostra informació sobre TielnetCoin</translation> </message> <message> <location line="+2"/> <source>About &amp;Qt</source> <translation>Sobre &amp;Qt</translation> </message> <message> <location line="+1"/> <source>Show information about Qt</source> <translation>Mostra informació sobre Qt</translation> </message> <message> <location line="+2"/> <source>&amp;Options...</source> <translation>&amp;Opcions...</translation> </message> <message> <location line="+6"/> <source>&amp;Encrypt Wallet...</source> <translation>&amp;Xifrar moneder</translation> </message> <message> <location line="+3"/> <source>&amp;Backup Wallet...</source> <translation>&amp;Realitzant copia de seguretat del moneder...</translation> </message> <message> <location line="+2"/> <source>&amp;Change Passphrase...</source> <translation>&amp;Canviar contrasenya...</translation> </message> <message> <location line="+285"/> <source>Importing blocks from disk...</source> <translation>Important blocs del disc..</translation> </message> <message> <location line="+3"/> <source>Reindexing blocks on disk...</source> <translation>Re-indexant blocs al disc...</translation> </message> <message> <location line="-347"/> <source>Send coins to a TielnetCoin address</source> <translation>Enviar monedes a una adreça TielnetCoin</translation> </message> <message> <location line="+49"/> <source>Modify configuration options for TielnetCoin</source> <translation>Modificar les opcions de configuració per tielnetcoin</translation> </message> <message> <location line="+9"/> <source>Backup wallet to another location</source> <translation>Realitzar còpia de seguretat del moneder a un altre directori</translation> </message> <message> <location line="+2"/> <source>Change the passphrase used for wallet encryption</source> <translation>Canviar la constrasenya d&apos;encriptació del moneder</translation> </message> <message> <location line="+6"/> <source>&amp;Debug window</source> <translation>&amp;Finestra de debug</translation> </message> <message> <location line="+1"/> <source>Open debugging and diagnostic console</source> <translation>Obrir la consola de diagnòstic i debugging</translation> </message> <message> <location line="-4"/> <source>&amp;Verify message...</source> <translation>&amp;Verifica el missatge..</translation> </message> <message> <location line="-165"/> <location line="+530"/> <source>TielnetCoin</source> <translation>TielnetCoin</translation> </message> <message> <location line="-530"/> <source>Wallet</source> <translation>Moneder</translation> </message> <message> <location line="+101"/> <source>&amp;Send</source> <translation>&amp;Enviar</translation> </message> <message> <location line="+7"/> <source>&amp;Receive</source> <translation>&amp;Rebre</translation> </message> <message> <location line="+14"/> <source>&amp;Addresses</source> <translation>&amp;Adreces</translation> </message> <message> <location line="+22"/> <source>&amp;About TielnetCoin</source> <translation>&amp;Sobre TielnetCoin</translation> </message> <message> <location line="+9"/> <source>&amp;Show / Hide</source> <translation>&amp;Mostrar / Amagar</translation> </message> <message> <location line="+1"/> <source>Show or hide the main Window</source> <translation>Mostrar o amagar la finestra principal</translation> </message> <message> <location line="+3"/> <source>Encrypt the private keys that belong to your wallet</source> <translation>Xifrar les claus privades pertanyents al seu moneder</translation> </message> <message> <location line="+7"/> <source>Sign messages with your TielnetCoin addresses to prove you own them</source> <translation>Signa el missatges amb la seva adreça de TielnetCoin per provar que les poseeixes</translation> </message> <message> <location line="+2"/> <source>Verify messages to ensure they were signed with specified TielnetCoin addresses</source> <translation>Verificar els missatges per assegurar-te que han estat signades amb una adreça TielnetCoin específica.</translation> </message> <message> <location line="+28"/> <source>&amp;File</source> <translation>&amp;Arxiu</translation> </message> <message> <location line="+7"/> <source>&amp;Settings</source> <translation>&amp;Configuració</translation> </message> <message> <location line="+6"/> <source>&amp;Help</source> <translation>&amp;Ajuda</translation> </message> <message> <location line="+9"/> <source>Tabs toolbar</source> <translation>Barra d&apos;eines de seccions</translation> </message> <message> <location line="+17"/> <location line="+10"/> <source>[testnet]</source> <translation>[testnet]</translation> </message> <message> <location line="+47"/> <source>TielnetCoin client</source> <translation>Client TielnetCoin</translation> </message> <message numerus="yes"> <location line="+141"/> <source>%n active connection(s) to TielnetCoin network</source> <translation><numerusform>%n connexió activa a la xarxa TielnetCoin</numerusform><numerusform>%n connexions actives a la xarxa TielnetCoin</numerusform></translation> </message> <message> <location line="+22"/> <source>No block source available...</source> <translation type="unfinished"/> </message> <message> <location line="+12"/> <source>Processed %1 of %2 (estimated) blocks of transaction history.</source> <translation>Processat el %1 de %2 (estimat) dels blocs del històric de transaccions.</translation> </message> <message> <location line="+4"/> <source>Processed %1 blocks of transaction history.</source> <translation>Proccessats %1 blocs del històric de transaccions.</translation> </message> <message numerus="yes"> <location line="+20"/> <source>%n hour(s)</source> <translation><numerusform>%n hora</numerusform><numerusform>%n hores</numerusform></translation> </message> <message numerus="yes"> <location line="+4"/> <source>%n day(s)</source> <translation><numerusform>%n dia</numerusform><numerusform>%n dies</numerusform></translation> </message> <message numerus="yes"> <location line="+4"/> <source>%n week(s)</source> <translation><numerusform>%n setmana</numerusform><numerusform>%n setmanes</numerusform></translation> </message> <message> <location line="+4"/> <source>%1 behind</source> <translation>%1 radera</translation> </message> <message> <location line="+14"/> <source>Last received block was generated %1 ago.</source> <translation>Lúltim bloc rebut ha estat generat fa %1.</translation> </message> <message> <location line="+2"/> <source>Transactions after this will not yet be visible.</source> <translation>Les transaccions a partir d&apos;això no seràn visibles.</translation> </message> <message> <location line="+22"/> <source>Error</source> <translation>Error</translation> </message> <message> <location line="+3"/> <source>Warning</source> <translation>Avís</translation> </message> <message> <location line="+3"/> <source>Information</source> <translation>Informació</translation> </message> <message> <location line="+70"/> <source>This transaction is over the size limit. You can still send it for a fee of %1, which goes to the nodes that process your transaction and helps to support the network. Do you want to pay the fee?</source> <translation>Aquesta transacció supera el límit de tamany. Tot i així pots enviar-la amb una comissió de %1, que es destinen als nodes que processen la seva transacció i ajuda a donar suport a la xarxa. Vols pagar la comissió?</translation> </message> <message> <location line="-140"/> <source>Up to date</source> <translation>Al dia</translation> </message> <message> <location line="+31"/> <source>Catching up...</source> <translation>Posar-se al dia ...</translation> </message> <message> <location line="+113"/> <source>Confirm transaction fee</source> <translation>Confirmar comisió de transacció</translation> </message> <message> <location line="+8"/> <source>Sent transaction</source> <translation>Transacció enviada</translation> </message> <message> <location line="+0"/> <source>Incoming transaction</source> <translation>Transacció entrant</translation> </message> <message> <location line="+1"/> <source>Date: %1 Amount: %2 Type: %3 Address: %4 </source> <translation>Data: %1\nQuantitat %2\n Tipus: %3\n Adreça: %4\n</translation> </message> <message> <location line="+33"/> <location line="+23"/> <source>URI handling</source> <translation>Manejant URI</translation> </message> <message> <location line="-23"/> <location line="+23"/> <source>URI can not be parsed! This can be caused by an invalid TielnetCoin address or malformed URI parameters.</source> <translation>la URI no pot ser processada! Això es pot ser causat per una adreça TielnetCoin invalida o paràmetres URI malformats.</translation> </message> <message> <location line="+17"/> <source>Wallet is &lt;b&gt;encrypted&lt;/b&gt; and currently &lt;b&gt;unlocked&lt;/b&gt;</source> <translation>El moneder està &lt;b&gt;encriptat&lt;/b&gt; i actualment &lt;b&gt;desbloquejat&lt;/b&gt;</translation> </message> <message> <location line="+8"/> <source>Wallet is &lt;b&gt;encrypted&lt;/b&gt; and currently &lt;b&gt;locked&lt;/b&gt;</source> <translation>El moneder està &lt;b&gt;encriptat&lt;/b&gt; i actualment &lt;b&gt;bloquejat&lt;/b&gt;</translation> </message> <message> <location filename="../bitcoin.cpp" line="+111"/> <source>A fatal error occurred. TielnetCoin can no longer continue safely and will quit.</source> <translation>Ha tingut lloc un error fatal. TielnetCoin no pot continuar executant-se de manera segura i es tancará.</translation> </message> </context> <context> <name>ClientModel</name> <message> <location filename="../clientmodel.cpp" line="+104"/> <source>Network Alert</source> <translation>Alerta de xarxa</translation> </message> </context> <context> <name>EditAddressDialog</name> <message> <location filename="../forms/editaddressdialog.ui" line="+14"/> <source>Edit Address</source> <translation>Editar Adreça</translation> </message> <message> <location line="+11"/> <source>&amp;Label</source> <translation>&amp;Etiqueta</translation> </message> <message> <location line="+10"/> <source>The label associated with this address book entry</source> <translation>Etiqueta associada amb aquesta entrada de la llibreta d&apos;adreces</translation> </message> <message> <location line="+7"/> <source>&amp;Address</source> <translation>&amp;Direcció</translation> </message> <message> <location line="+10"/> <source>The address associated with this address book entry. This can only be modified for sending addresses.</source> <translation>Adreça associada amb aquesta entrada de la llibreta d&apos;adreces. Només pot ser modificat per a enviar adreces.</translation> </message> <message> <location filename="../editaddressdialog.cpp" line="+21"/> <source>New receiving address</source> <translation>Nova adreça de recepció.</translation> </message> <message> <location line="+4"/> <source>New sending address</source> <translation>Nova adreça d&apos;enviament</translation> </message> <message> <location line="+3"/> <source>Edit receiving address</source> <translation>Editar adreces de recepció</translation> </message> <message> <location line="+4"/> <source>Edit sending address</source> <translation>Editar adreces d&apos;enviament</translation> </message> <message> <location line="+76"/> <source>The entered address &quot;%1&quot; is already in the address book.</source> <translation>L&apos;adreça introduïda &quot;%1&quot; ja és present a la llibreta d&apos;adreces.</translation> </message> <message> <location line="-5"/> <source>The entered address &quot;%1&quot; is not a valid TielnetCoin address.</source> <translation>L&apos;adreça introduida &quot;%1&quot; no és una adreça TielnetCoin valida.</translation> </message> <message> <location line="+10"/> <source>Could not unlock wallet.</source> <translation>No s&apos;ha pogut desbloquejar el moneder.</translation> </message> <message> <location line="+5"/> <source>New key generation failed.</source> <translation>Ha fallat la generació d&apos;una nova clau.</translation> </message> </context> <context> <name>GUIUtil::HelpMessageBox</name> <message> <location filename="../guiutil.cpp" line="+424"/> <location line="+12"/> <source>TielnetCoin-Qt</source> <translation>TielnetCoin-Qt</translation> </message> <message> <location line="-12"/> <source>version</source> <translation>versió</translation> </message> <message> <location line="+2"/> <source>Usage:</source> <translation>Ús:</translation> </message> <message> <location line="+1"/> <source>command-line options</source> <translation>Opcions de la línia d&apos;ordres</translation> </message> <message> <location line="+4"/> <source>UI options</source> <translation>Opcions de IU</translation> </message> <message> <location line="+1"/> <source>Set language, for example &quot;de_DE&quot; (default: system locale)</source> <translation>Definir llenguatge, per exemple &quot;de_DE&quot; (per defecte: Preferències locals de sistema)</translation> </message> <message> <location line="+1"/> <source>Start minimized</source> <translation>Iniciar minimitzat</translation> </message> <message> <location line="+1"/> <source>Show splash screen on startup (default: 1)</source> <translation>Mostrar finestra de benvinguda a l&apos;inici (per defecte: 1)</translation> </message> </context> <context> <name>OptionsDialog</name> <message> <location filename="../forms/optionsdialog.ui" line="+14"/> <source>Options</source> <translation>Opcions</translation> </message> <message> <location line="+16"/> <source>&amp;Main</source> <translation>&amp;Principal</translation> </message> <message> <location line="+6"/> <source>Optional transaction fee per kB that helps make sure your transactions are processed quickly. Most transactions are 1 kB.</source> <translation type="unfinished"/> </message> <message> <location line="+15"/> <source>Pay transaction &amp;fee</source> <translation>Pagar &amp;comisió de transacció</translation> </message> <message> <location line="+31"/> <source>Automatically start TielnetCoin after logging in to the system.</source> <translation>Iniciar automàticament TielnetCoin després de l&apos;inici de sessió del sistema.</translation> </message> <message> <location line="+3"/> <source>&amp;Start TielnetCoin on system login</source> <translation>&amp;Iniciar TielnetCoin al inici de sessió del sistema.</translation> </message> <message> <location line="+35"/> <source>Reset all client options to default.</source> <translation>Reestablir totes les opcions del client.</translation> </message> <message> <location line="+3"/> <source>&amp;Reset Options</source> <translation>&amp;Reestablir Opcions</translation> </message> <message> <location line="+13"/> <source>&amp;Network</source> <translation>&amp;Xarxa</translation> </message> <message> <location line="+6"/> <source>Automatically open the TielnetCoin client port on the router. This only works when your router supports UPnP and it is enabled.</source> <translation>Obrir el port del client de TielnetCoin al router de forma automàtica. Això només funciona quan el teu router implementa UPnP i l&apos;opció està activada.</translation> </message> <message> <location line="+3"/> <source>Map port using &amp;UPnP</source> <translation>Port obert amb &amp;UPnP</translation> </message> <message> <location line="+7"/> <source>Connect to the TielnetCoin network through a SOCKS proxy (e.g. when connecting through Tor).</source> <translation>Connectar a la xarxa TielnetCoin a través de un SOCKS proxy (per exemple connectant a través de Tor).</translation> </message> <message> <location line="+3"/> <source>&amp;Connect through SOCKS proxy:</source> <translation>&amp;Connecta a través de un proxy SOCKS:</translation> </message> <message> <location line="+9"/> <source>Proxy &amp;IP:</source> <translation>&amp;IP del proxy:</translation> </message> <message> <location line="+19"/> <source>IP address of the proxy (e.g. 127.0.0.1)</source> <translation>Adreça IP del proxy (per exemple 127.0.0.1)</translation> </message> <message> <location line="+7"/> <source>&amp;Port:</source> <translation>&amp;Port:</translation> </message> <message> <location line="+19"/> <source>Port of the proxy (e.g. 9050)</source> <translation>Port del proxy (per exemple 9050)</translation> </message> <message> <location line="+7"/> <source>SOCKS &amp;Version:</source> <translation>&amp;Versió de SOCKS:</translation> </message> <message> <location line="+13"/> <source>SOCKS version of the proxy (e.g. 5)</source> <translation>Versió SOCKS del proxy (per exemple 5)</translation> </message> <message> <location line="+36"/> <source>&amp;Window</source> <translation>&amp;Finestra</translation> </message> <message> <location line="+6"/> <source>Show only a tray icon after minimizing the window.</source> <translation>Mostrar només l&apos;icona de la barra al minimitzar l&apos;aplicació.</translation> </message> <message> <location line="+3"/> <source>&amp;Minimize to the tray instead of the taskbar</source> <translation>&amp;Minimitzar a la barra d&apos;aplicacions</translation> </message> <message> <location line="+7"/> <source>Minimize instead of exit the application when the window is closed. When this option is enabled, the application will be closed only after selecting Quit in the menu.</source> <translation>Minimitza en comptes de sortir de la aplicació al tancar la finestra. Quan aquesta opció està activa, la aplicació només es tancarà al seleccionar Sortir al menú.</translation> </message> <message> <location line="+3"/> <source>M&amp;inimize on close</source> <translation>M&amp;inimitzar al tancar</translation> </message> <message> <location line="+21"/> <source>&amp;Display</source> <translation>&amp;Pantalla</translation> </message> <message> <location line="+8"/> <source>User Interface &amp;language:</source> <translation>Llenguatge de la Interfície d&apos;Usuari:</translation> </message> <message> <location line="+13"/> <source>The user interface language can be set here. This setting will take effect after restarting TielnetCoin.</source> <translation>Aquí pots definir el llenguatge de l&apos;aplicatiu. Aquesta configuració tindrà efecte un cop es reiniciï TielnetCoin.</translation> </message> <message> <location line="+11"/> <source>&amp;Unit to show amounts in:</source> <translation>&amp;Unitats per mostrar les quantitats en:</translation> </message> <message> <location line="+13"/> <source>Choose the default subdivision unit to show in the interface and when sending coins.</source> <translation>Sel·lecciona la unitat de subdivisió per defecte per mostrar en la interficie quan s&apos;envien monedes.</translation> </message> <message> <location line="+9"/> <source>Whether to show TielnetCoin addresses in the transaction list or not.</source> <translation>Mostrar adreces TielnetCoin als llistats de transaccions o no.</translation> </message> <message> <location line="+3"/> <source>&amp;Display addresses in transaction list</source> <translation>&amp;Mostrar adreces al llistat de transaccions</translation> </message> <message> <location line="+71"/> <source>&amp;OK</source> <translation>&amp;OK</translation> </message> <message> <location line="+7"/> <source>&amp;Cancel</source> <translation>&amp;Cancel·la</translation> </message> <message> <location line="+10"/> <source>&amp;Apply</source> <translation>&amp;Aplicar</translation> </message> <message> <location filename="../optionsdialog.cpp" line="+53"/> <source>default</source> <translation>Per defecte</translation> </message> <message> <location line="+130"/> <source>Confirm options reset</source> <translation>Confirmi el reestabliment de les opcions</translation> </message> <message> <location line="+1"/> <source>Some settings may require a client restart to take effect.</source> <translation>Algunes configuracions poden requerir reiniciar el client per a que tinguin efecte.</translation> </message> <message> <location line="+0"/> <source>Do you want to proceed?</source> <translation>Vols procedir?</translation> </message> <message> <location line="+42"/> <location line="+9"/> <source>Warning</source> <translation>Avís</translation> </message> <message> <location line="-9"/> <location line="+9"/> <source>This setting will take effect after restarting TielnetCoin.</source> <translation>Aquesta configuració tindrà efecte un cop es reiniciï TielnetCoin.</translation> </message> <message> <location line="+29"/> <source>The supplied proxy address is invalid.</source> <translation>L&apos;adreça proxy introduïda és invalida.</translation> </message> </context> <context> <name>OverviewPage</name> <message> <location filename="../forms/overviewpage.ui" line="+14"/> <source>Form</source> <translation>Formulari</translation> </message> <message> <location line="+50"/> <location line="+166"/> <source>The displayed information may be out of date. Your wallet automatically synchronizes with the TielnetCoin network after a connection is established, but this process has not completed yet.</source> <translation>La informació mostrada pot no estar al día. El teu moneder es sincronitza automàticament amb la xarxa TielnetCoin un cop s&apos;ha establert connexió, però aquest proces no s&apos;ha completat encara.</translation> </message> <message> <location line="-124"/> <source>Balance:</source> <translation>Balanç:</translation> </message> <message> <location line="+29"/> <source>Unconfirmed:</source> <translation>Sense confirmar:</translation> </message> <message> <location line="-78"/> <source>Wallet</source> <translation>Moneder</translation> </message> <message> <location line="+107"/> <source>Immature:</source> <translation>Immatur:</translation> </message> <message> <location line="+13"/> <source>Mined balance that has not yet matured</source> <translation>Balanç minat que encara no ha madurat</translation> </message> <message> <location line="+46"/> <source>&lt;b&gt;Recent transactions&lt;/b&gt;</source> <translation>&lt;b&gt;Transaccions recents&lt;/b&gt;</translation> </message> <message> <location line="-101"/> <source>Your current balance</source> <translation>El seu balanç actual</translation> </message> <message> <location line="+29"/> <source>Total of transactions that have yet to be confirmed, and do not yet count toward the current balance</source> <translation>Total de transaccions encara sense confirmar, que encara no es content en el balanç actual</translation> </message> <message> <location filename="../overviewpage.cpp" line="+116"/> <location line="+1"/> <source>out of sync</source> <translation>Fora de sincronia</translation> </message> </context> <context> <name>PaymentServer</name> <message> <location filename="../paymentserver.cpp" line="+107"/> <source>Cannot start tielnetcoin: click-to-pay handler</source> <translation>No es pot iniciar tielnetcoin: manejador clicla-per-pagar</translation> </message> </context> <context> <name>QRCodeDialog</name> <message> <location filename="../forms/qrcodedialog.ui" line="+14"/> <source>QR Code Dialog</source> <translation>Dialeg del codi QR</translation> </message> <message> <location line="+59"/> <source>Request Payment</source> <translation>Reclamar pagament</translation> </message> <message> <location line="+56"/> <source>Amount:</source> <translation>Quantitat:</translation> </message> <message> <location line="-44"/> <source>Label:</source> <translation>Etiqueta:</translation> </message> <message> <location line="+19"/> <source>Message:</source> <translation>Missatge:</translation> </message> <message> <location line="+71"/> <source>&amp;Save As...</source> <translation>&amp;Desar com...</translation> </message> <message> <location filename="../qrcodedialog.cpp" line="+62"/> <source>Error encoding URI into QR Code.</source> <translation>Error codificant la URI en un codi QR.</translation> </message> <message> <location line="+40"/> <source>The entered amount is invalid, please check.</source> <translation>La quantitat introduïda és invalida, si us plau comprovi-la.</translation> </message> <message> <location line="+23"/> <source>Resulting URI too long, try to reduce the text for label / message.</source> <translation>URI resultant massa llarga, intenta reduir el text per a la etiqueta / missatge</translation> </message> <message> <location line="+25"/> <source>Save QR Code</source> <translation>Desar codi QR</translation> </message> <message> <location line="+0"/> <source>PNG Images (*.png)</source> <translation>Imatges PNG (*.png)</translation> </message> </context> <context> <name>RPCConsole</name> <message> <location filename="../forms/rpcconsole.ui" line="+46"/> <source>Client name</source> <translation>Nom del client</translation> </message> <message> <location line="+10"/> <location line="+23"/> <location line="+26"/> <location line="+23"/> <location line="+23"/> <location line="+36"/> <location line="+53"/> <location line="+23"/> <location line="+23"/> <location filename="../rpcconsole.cpp" line="+339"/> <source>N/A</source> <translation>N/A</translation> </message> <message> <location line="-217"/> <source>Client version</source> <translation>Versió del client</translation> </message> <message> <location line="-45"/> <source>&amp;Information</source> <translation>&amp;Informació</translation> </message> <message> <location line="+68"/> <source>Using OpenSSL version</source> <translation>Utilitzant OpenSSL versió</translation> </message> <message> <location line="+49"/> <source>Startup time</source> <translation>&amp;Temps d&apos;inici</translation> </message> <message> <location line="+29"/> <source>Network</source> <translation>Xarxa</translation> </message> <message> <location line="+7"/> <source>Number of connections</source> <translation>Nombre de connexions</translation> </message> <message> <location line="+23"/> <source>On testnet</source> <translation>A testnet</translation> </message> <message> <location line="+23"/> <source>Block chain</source> <translation>Bloquejar cadena</translation> </message> <message> <location line="+7"/> <source>Current number of blocks</source> <translation>Nombre de blocs actuals</translation> </message> <message> <location line="+23"/> <source>Estimated total blocks</source> <translation>Total estimat de blocs</translation> </message> <message> <location line="+23"/> <source>Last block time</source> <translation>Últim temps de bloc</translation> </message> <message> <location line="+52"/> <source>&amp;Open</source> <translation>&amp;Obrir</translation> </message> <message> <location line="+16"/> <source>Command-line options</source> <translation>Opcions de línia d&apos;ordres</translation> </message> <message> <location line="+7"/> <source>Show the TielnetCoin-Qt help message to get a list with possible TielnetCoin command-line options.</source> <translation>Mostrar el missatge d&apos;ajuda de TielnetCoin-Qt per a obtenir un llistat de possibles ordres per a la línia d&apos;ordres de TielnetCoin.</translation> </message> <message> <location line="+3"/> <source>&amp;Show</source> <translation>&amp;Mostrar</translation> </message> <message> <location line="+24"/> <source>&amp;Console</source> <translation>&amp;Consola</translation> </message> <message> <location line="-260"/> <source>Build date</source> <translation>Data de compilació</translation> </message> <message> <location line="-104"/> <source>TielnetCoin - Debug window</source> <translation>TielnetCoin -Finestra de debug</translation> </message> <message> <location line="+25"/> <source>TielnetCoin Core</source> <translation>Nucli de TielnetCoin</translation> </message> <message> <location line="+279"/> <source>Debug log file</source> <translation>Dietàri de debug</translation> </message> <message> <location line="+7"/> <source>Open the TielnetCoin debug log file from the current data directory. This can take a few seconds for large log files.</source> <translation>Obrir el dietari de debug de TielnetCoin del directori de dades actual. Aixó pot trigar uns quants segons per a dietàris grossos.</translation> </message> <message> <location line="+102"/> <source>Clear console</source> <translation>Netejar consola</translation> </message> <message> <location filename="../rpcconsole.cpp" line="-30"/> <source>Welcome to the TielnetCoin RPC console.</source> <translation>Benvingut a la consola RPC de TielnetCoin</translation> </message> <message> <location line="+1"/> <source>Use up and down arrows to navigate history, and &lt;b&gt;Ctrl-L&lt;/b&gt; to clear screen.</source> <translation>Utilitza les fletxes d&apos;amunt i avall per navegar per l&apos;històric, i &lt;b&gt;Ctrl-L&lt;\b&gt; per netejar la pantalla.</translation> </message> <message> <location line="+1"/> <source>Type &lt;b&gt;help&lt;/b&gt; for an overview of available commands.</source> <translation>Escriu &lt;b&gt;help&lt;\b&gt; per a obtenir una llistat de les ordres disponibles.</translation> </message> </context> <context> <name>SendCoinsDialog</name> <message> <location filename="../forms/sendcoinsdialog.ui" line="+14"/> <location filename="../sendcoinsdialog.cpp" line="+124"/> <location line="+5"/> <location line="+5"/> <location line="+5"/> <location line="+6"/> <location line="+5"/> <location line="+5"/> <source>Send Coins</source> <translation>Enviar monedes</translation> </message> <message> <location line="+50"/> <source>Send to multiple recipients at once</source> <translation>Enviar a multiples destinataris al mateix temps</translation> </message> <message> <location line="+3"/> <source>Add &amp;Recipient</source> <translation>Affegir &amp;Destinatari</translation> </message> <message> <location line="+20"/> <source>Remove all transaction fields</source> <translation>Netejar tots els camps de la transacció</translation> </message> <message> <location line="+3"/> <source>Clear &amp;All</source> <translation>Esborrar &amp;Tot</translation> </message> <message> <location line="+22"/> <source>Balance:</source> <translation>Balanç:</translation> </message> <message> <location line="+10"/> <source>123.456 BTC</source> <translation>123.456 BTC</translation> </message> <message> <location line="+31"/> <source>Confirm the send action</source> <translation>Confirmi l&apos;acció d&apos;enviament</translation> </message> <message> <location line="+3"/> <source>S&amp;end</source> <translation>E&amp;nviar</translation> </message> <message> <location filename="../sendcoinsdialog.cpp" line="-59"/> <source>&lt;b&gt;%1&lt;/b&gt; to %2 (%3)</source> <translation>&lt;b&gt;%1&lt;/b&gt; to %2 (%3)</translation> </message> <message> <location line="+5"/> <source>Confirm send coins</source> <translation>Confirmar l&apos;enviament de monedes</translation> </message> <message> <location line="+1"/> <source>Are you sure you want to send %1?</source> <translation>Estas segur que vols enviar %1?</translation> </message> <message> <location line="+0"/> <source> and </source> <translation>i</translation> </message> <message> <location line="+23"/> <source>The recipient address is not valid, please recheck.</source> <translation>L&apos;adreça remetent no és vàlida, si us plau comprovi-la.</translation> </message> <message> <location line="+5"/> <source>The amount to pay must be larger than 0.</source> <translation>La quantitat a pagar ha de ser major que 0.</translation> </message> <message> <location line="+5"/> <source>The amount exceeds your balance.</source> <translation>Import superi el saldo de la seva compte.</translation> </message> <message> <location line="+5"/> <source>The total exceeds your balance when the %1 transaction fee is included.</source> <translation>El total excedeix el teu balanç quan s&apos;afegeix la comisió a la transacció %1.</translation> </message> <message> <location line="+6"/> <source>Duplicate address found, can only send to each address once per send operation.</source> <translation>S&apos;ha trobat una adreça duplicada, tan sols es pot enviar a cada adreça un cop per ordre de enviament.</translation> </message> <message> <location line="+5"/> <source>Error: Transaction creation failed!</source> <translation>Error: La ceació de la transacció ha fallat!</translation> </message> <message> <location line="+5"/> <source>Error: The transaction was rejected. This might happen if some of the coins in your wallet were already spent, such as if you used a copy of wallet.dat and coins were spent in the copy but not marked as spent here.</source> <translation>Error: La transacció ha estat rebutjada. Això pot passar si alguna de les monedes del teu moneder ja s&apos;han gastat, com si haguesis usat una copia de l&apos;arxiu wallet.dat i s&apos;haguessin gastat monedes de la copia però sense marcar com gastades en aquest.</translation> </message> </context> <context> <name>SendCoinsEntry</name> <message> <location filename="../forms/sendcoinsentry.ui" line="+14"/> <source>Form</source> <translation>Formulari</translation> </message> <message> <location line="+15"/> <source>A&amp;mount:</source> <translation>Q&amp;uantitat:</translation> </message> <message> <location line="+13"/> <source>Pay &amp;To:</source> <translation>Pagar &amp;A:</translation> </message> <message> <location line="+34"/> <source>The address to send the payment to (e.g. Ler4HNAEfwYhBmGXcFP2Po1NpRUEiK8km2)</source> <translation>La adreça a on envia el pagament (per exemple: Ler4HNAEfwYhBmGXcFP2Po1NpRUEiK8km2)</translation> </message> <message> <location line="+60"/> <location filename="../sendcoinsentry.cpp" line="+26"/> <source>Enter a label for this address to add it to your address book</source> <translation>Introdueixi una etiquera per a aquesta adreça per afegir-la a la llibreta d&apos;adreces</translation> </message> <message> <location line="-78"/> <source>&amp;Label:</source> <translation>&amp;Etiqueta:</translation> </message> <message> <location line="+28"/> <source>Choose address from address book</source> <translation>Escollir adreça del llibre d&apos;adreces</translation> </message> <message> <location line="+10"/> <source>Alt+A</source> <translation>Alta+A</translation> </message> <message> <location line="+7"/> <source>Paste address from clipboard</source> <translation>Enganxar adreça del porta-retalls</translation> </message> <message> <location line="+10"/> <source>Alt+P</source> <translation>Alt+P</translation> </message> <message> <location line="+7"/> <source>Remove this recipient</source> <translation>Eliminar aquest destinatari</translation> </message> <message> <location filename="../sendcoinsentry.cpp" line="+1"/> <source>Enter a TielnetCoin address (e.g. Ler4HNAEfwYhBmGXcFP2Po1NpRUEiK8km2)</source> <translation>Introdueixi una adreça de TielnetCoin (per exemple Ler4HNAEfwYhBmGXcFP2Po1NpRUEiK8km2)</translation> </message> </context> <context> <name>SignVerifyMessageDialog</name> <message> <location filename="../forms/signverifymessagedialog.ui" line="+14"/> <source>Signatures - Sign / Verify a Message</source> <translation>Signatures .Signar/Verificar un Missatge</translation> </message> <message> <location line="+13"/> <source>&amp;Sign Message</source> <translation>&amp;Signar Missatge</translation> </message> <message> <location line="+6"/> <source>You can sign messages with your addresses to prove you own them. Be careful not to sign anything vague, as phishing attacks may try to trick you into signing your identity over to them. Only sign fully-detailed statements you agree to.</source> <translation>Pots signar missatges amb la teva adreça per provar que són teus. Sigues cautelòs al signar qualsevol cosa, ja que els atacs phising poden intentar confondre&apos;t per a que els hi signis amb la teva identitat. Tan sols signa als documents completament detallats amb els que hi estàs d&apos;acord.</translation> </message> <message> <location line="+18"/> <source>The address to sign the message with (e.g. Ler4HNAEfwYhBmGXcFP2Po1NpRUEiK8km2)</source> <translation>La adreça amb la que signat els missatges (per exemple Ler4HNAEfwYhBmGXcFP2Po1NpRUEiK8km2)</translation> </message> <message> <location line="+10"/> <location line="+213"/> <source>Choose an address from the address book</source> <translation>Escollir una adreça de la llibreta de direccions</translation> </message> <message> <location line="-203"/> <location line="+213"/> <source>Alt+A</source> <translation>Alta+A</translation> </message> <message> <location line="-203"/> <source>Paste address from clipboard</source> <translation>Enganxar adreça del porta-retalls</translation> </message> <message> <location line="+10"/> <source>Alt+P</source> <translation>Alt+P</translation> </message> <message> <location line="+12"/> <source>Enter the message you want to sign here</source> <translation>Introdueix aqui el missatge que vols signar</translation> </message> <message> <location line="+7"/> <source>Signature</source> <translation>Signatura</translation> </message> <message> <location line="+27"/> <source>Copy the current signature to the system clipboard</source> <translation>Copiar la signatura actual al porta-retalls del sistema</translation> </message> <message> <location line="+21"/> <source>Sign the message to prove you own this TielnetCoin address</source> <translation>Signa el missatge per provar que ets propietari d&apos;aquesta adreça TielnetCoin</translation> </message> <message> <location line="+3"/> <source>Sign &amp;Message</source> <translation>Signar &amp;Missatge</translation> </message> <message> <location line="+14"/> <source>Reset all sign message fields</source> <translation>Neteja tots els camps de clau</translation> </message> <message> <location line="+3"/> <location line="+146"/> <source>Clear &amp;All</source> <translation>Esborrar &amp;Tot</translation> </message> <message> <location line="-87"/> <source>&amp;Verify Message</source> <translation>&amp;Verificar el missatge</translation> </message> <message> <location line="+6"/> <source>Enter the signing address, message (ensure you copy line breaks, spaces, tabs, etc. exactly) and signature below to verify the message. Be careful not to read more into the signature than what is in the signed message itself, to avoid being tricked by a man-in-the-middle attack.</source> <translation>Introdueixi l&apos;adreça signant, missatge (assegura&apos;t que copies salts de línia, espais, tabuladors, etc excactament tot el text) i la signatura a sota per verificar el missatge. Per evitar ser enganyat per un atac home-entre-mig, vés amb compte de no llegir més en la signatura del que hi ha al missatge signat mateix.</translation> </message> <message> <location line="+21"/> <source>The address the message was signed with (e.g. Ler4HNAEfwYhBmGXcFP2Po1NpRUEiK8km2)</source> <translation>La adreça amb el que el missatge va ser signat (per exemple Ler4HNAEfwYhBmGXcFP2Po1NpRUEiK8km2)</translation> </message> <message> <location line="+40"/> <source>Verify the message to ensure it was signed with the specified TielnetCoin address</source> <translation>Verificar el missatge per assegurar-se que ha estat signat amb una adreça TielnetCoin específica</translation> </message> <message> <location line="+3"/> <source>Verify &amp;Message</source> <translation>Verificar &amp;Missatge</translation> </message> <message> <location line="+14"/> <source>Reset all verify message fields</source> <translation>Neteja tots els camps de verificació de missatge</translation> </message> <message> <location filename="../signverifymessagedialog.cpp" line="+27"/> <location line="+3"/> <source>Enter a TielnetCoin address (e.g. Ler4HNAEfwYhBmGXcFP2Po1NpRUEiK8km2)</source> <translation>Introdueixi una adreça de TielnetCoin (per exemple Ler4HNAEfwYhBmGXcFP2Po1NpRUEiK8km2)</translation> </message> <message> <location line="-2"/> <source>Click &quot;Sign Message&quot; to generate signature</source> <translation>Clica &quot;Signar Missatge&quot; per a generar una signatura</translation> </message> <message> <location line="+3"/> <source>Enter TielnetCoin signature</source> <translation>Introduïr una clau TielnetCoin</translation> </message> <message> <location line="+82"/> <location line="+81"/> <source>The entered address is invalid.</source> <translation>L&apos;adreça intoduïda és invàlida.</translation> </message> <message> <location line="-81"/> <location line="+8"/> <location line="+73"/> <location line="+8"/> <source>Please check the address and try again.</source> <translation>Siu us plau, comprovi l&apos;adreça i provi de nou.</translation> </message> <message> <location line="-81"/> <location line="+81"/> <source>The entered address does not refer to a key.</source> <translation>L&apos;adreça introduïda no referencia a cap clau.</translation> </message> <message> <location line="-73"/> <source>Wallet unlock was cancelled.</source> <translation>El desbloqueig del moneder ha estat cancelat.</translation> </message> <message> <location line="+8"/> <source>Private key for the entered address is not available.</source> <translation>La clau privada per a la adreça introduïda no està disponible.</translation> </message> <message> <location line="+12"/> <source>Message signing failed.</source> <translation>El signat del missatge ha fallat.</translation> </message> <message> <location line="+5"/> <source>Message signed.</source> <translation>Missatge signat.</translation> </message> <message> <location line="+59"/> <source>The signature could not be decoded.</source> <translation>La signatura no s&apos;ha pogut decodificar .</translation> </message> <message> <location line="+0"/> <location line="+13"/> <source>Please check the signature and try again.</source> <translation>Su us plau, comprovi la signatura i provi de nou.</translation> </message> <message> <location line="+0"/> <source>The signature did not match the message digest.</source> <translation>La signatura no coincideix amb el resum del missatge.</translation> </message> <message> <location line="+7"/> <source>Message verification failed.</source> <translation>Ha fallat la verificació del missatge.</translation> </message> <message> <location line="+5"/> <source>Message verified.</source> <translation>Missatge verificat.</translation> </message> </context> <context> <name>SplashScreen</name> <message> <location filename="../splashscreen.cpp" line="+22"/> <source>The TielnetCoin developers</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>[testnet]</source> <translation type="unfinished"/> </message> </context> <context> <name>TransactionDesc</name> <message> <location filename="../transactiondesc.cpp" line="+20"/> <source>Open until %1</source> <translation>Obert fins %1</translation> </message> <message> <location line="+6"/> <source>%1/offline</source> <translation>%1/offline</translation> </message> <message> <location line="+2"/> <source>%1/unconfirmed</source> <translation>%1/sense confirmar</translation> </message> <message> <location line="+2"/> <source>%1 confirmations</source> <translation>%1 confrimacions</translation> </message> <message> <location line="+18"/> <source>Status</source> <translation>Estat</translation> </message> <message numerus="yes"> <location line="+7"/> <source>, broadcast through %n node(s)</source> <translation><numerusform>, difusió a través de %n node</numerusform><numerusform>, difusió a través de %n nodes</numerusform></translation> </message> <message> <location line="+4"/> <source>Date</source> <translation>Data</translation> </message> <message> <location line="+7"/> <source>Source</source> <translation>Font</translation> </message> <message> <location line="+0"/> <source>Generated</source> <translation>Generat</translation> </message> <message> <location line="+5"/> <location line="+17"/> <source>From</source> <translation>Des de</translation> </message> <message> <location line="+1"/> <location line="+22"/> <location line="+58"/> <source>To</source> <translation>A</translation> </message> <message> <location line="-77"/> <location line="+2"/> <source>own address</source> <translation>Adreça pròpia</translation> </message> <message> <location line="-2"/> <source>label</source> <translation>etiqueta</translation> </message> <message> <location line="+37"/> <location line="+12"/> <location line="+45"/> <location line="+17"/> <location line="+30"/> <source>Credit</source> <translation>Crèdit</translation> </message> <message numerus="yes"> <location line="-102"/> <source>matures in %n more block(s)</source> <translation><numerusform>disponible en %n bloc més</numerusform><numerusform>disponibles en %n blocs més</numerusform></translation> </message> <message> <location line="+2"/> <source>not accepted</source> <translation>no acceptat</translation> </message> <message> <location line="+44"/> <location line="+8"/> <location line="+15"/> <location line="+30"/> <source>Debit</source> <translation>Dèbit</translation> </message> <message> <location line="-39"/> <source>Transaction fee</source> <translation>Comissió de transacció</translation> </message> <message> <location line="+16"/> <source>Net amount</source> <translation>Quantitat neta</translation> </message> <message> <location line="+6"/> <source>Message</source> <translation>Missatge</translation> </message> <message> <location line="+2"/> <source>Comment</source> <translation>Comentar</translation> </message> <message> <location line="+2"/> <source>Transaction ID</source> <translation>ID de transacció</translation> </message> <message> <location line="+3"/> <source>Generated coins must mature 120 blocks before they can be spent. When you generated this block, it was broadcast to the network to be added to the block chain. If it fails to get into the chain, its state will change to &quot;not accepted&quot; and it won&apos;t be spendable. This may occasionally happen if another node generates a block within a few seconds of yours.</source> <translation>Les monedes generades han de madurar 120 blocs abans de poder ser gastades. Quan has generat aquest bloc, aquest ha estat transmés a la xarxa per a ser afegit a la cadena de blocs. Si no arriba a ser acceptat a la cadena, el seu estat passará a &quot;no acceptat&quot; i no podrá ser gastat. Això pot ocòrrer ocasionalment si un altre node genera un bloc a pocs segons del teu.</translation> </message> <message> <location line="+7"/> <source>Debug information</source> <translation>Informació de debug</translation> </message> <message> <location line="+8"/> <source>Transaction</source> <translation>Transacció</translation> </message> <message> <location line="+3"/> <source>Inputs</source> <translation>Entrades</translation> </message> <message> <location line="+23"/> <source>Amount</source> <translation>Quantitat</translation> </message> <message> <location line="+1"/> <source>true</source> <translation>cert</translation> </message> <message> <location line="+0"/> <source>false</source> <translation>fals</translation> </message> <message> <location line="-209"/> <source>, has not been successfully broadcast yet</source> <translation>, encara no ha estat emès correctement</translation> </message> <message numerus="yes"> <location line="-35"/> <source>Open for %n more block(s)</source> <translation><numerusform>Obre per %n bloc més</numerusform><numerusform>Obre per %n blocs més</numerusform></translation> </message> <message> <location line="+70"/> <source>unknown</source> <translation>desconegut</translation> </message> </context> <context> <name>TransactionDescDialog</name> <message> <location filename="../forms/transactiondescdialog.ui" line="+14"/> <source>Transaction details</source> <translation>Detall de la transacció</translation> </message> <message> <location line="+6"/> <source>This pane shows a detailed description of the transaction</source> <translation>Aquest panell mostra una descripció detallada de la transacció</translation> </message> </context> <context> <name>TransactionTableModel</name> <message> <location filename="../transactiontablemodel.cpp" line="+225"/> <source>Date</source> <translation>Data</translation> </message> <message> <location line="+0"/> <source>Type</source> <translation>Tipus</translation> </message> <message> <location line="+0"/> <source>Address</source> <translation>Direcció</translation> </message> <message> <location line="+0"/> <source>Amount</source> <translation>Quantitat</translation> </message> <message numerus="yes"> <location line="+57"/> <source>Open for %n more block(s)</source> <translation><numerusform>Obre per %n bloc més</numerusform><numerusform>Obre per %n blocs més</numerusform></translation> </message> <message> <location line="+3"/> <source>Open until %1</source> <translation>Obert fins %1</translation> </message> <message> <location line="+3"/> <source>Offline (%1 confirmations)</source> <translation>Sense connexió (%1 confirmacions)</translation> </message> <message> <location line="+3"/> <source>Unconfirmed (%1 of %2 confirmations)</source> <translation>Sense confirmar (%1 de %2 confirmacions)</translation> </message> <message> <location line="+3"/> <source>Confirmed (%1 confirmations)</source> <translation>Confirmat (%1 confirmacions)</translation> </message> <message numerus="yes"> <location line="+8"/> <source>Mined balance will be available when it matures in %n more block(s)</source> <translation><numerusform>El saldo recent minat estarà disponible quan venci el termini en %n bloc més</numerusform><numerusform>El saldo recent minat estarà disponible quan venci el termini en %n blocs més</numerusform></translation> </message> <message> <location line="+5"/> <source>This block was not received by any other nodes and will probably not be accepted!</source> <translation>Aquest bloc no ha estat rebut per cap altre node i probablement no serà acceptat!</translation> </message> <message> <location line="+3"/> <source>Generated but not accepted</source> <translation>Generat però no acceptat</translation> </message> <message> <location line="+43"/> <source>Received with</source> <translation>Rebut amb</translation> </message> <message> <location line="+2"/> <source>Received from</source> <translation>Rebut de</translation> </message> <message> <location line="+3"/> <source>Sent to</source> <translation>Enviat a</translation> </message> <message> <location line="+2"/> <source>Payment to yourself</source> <translation>Pagament a un mateix</translation> </message> <message> <location line="+2"/> <source>Mined</source> <translation>Minat</translation> </message> <message> <location line="+38"/> <source>(n/a)</source> <translation>(n/a)</translation> </message> <message> <location line="+199"/> <source>Transaction status. Hover over this field to show number of confirmations.</source> <translation>Estat de la transacció. Desplaça&apos;t per aquí sobre per mostrar el nombre de confirmacions.</translation> </message> <message> <location line="+2"/> <source>Date and time that the transaction was received.</source> <translation>Data i hora en que la transacció va ser rebuda.</translation> </message> <message> <location line="+2"/> <source>Type of transaction.</source> <translation>Tipus de transacció.</translation> </message> <message> <location line="+2"/> <source>Destination address of transaction.</source> <translation>Adreça del destinatari de la transacció.</translation> </message> <message> <location line="+2"/> <source>Amount removed from or added to balance.</source> <translation>Quantitat extreta o afegida del balanç.</translation> </message> </context> <context> <name>TransactionView</name> <message> <location filename="../transactionview.cpp" line="+52"/> <location line="+16"/> <source>All</source> <translation>Tot</translation> </message> <message> <location line="-15"/> <source>Today</source> <translation>Avui</translation> </message> <message> <location line="+1"/> <source>This week</source> <translation>Aquesta setmana</translation> </message> <message> <location line="+1"/> <source>This month</source> <translation>Aquest mes</translation> </message> <message> <location line="+1"/> <source>Last month</source> <translation>El mes passat</translation> </message> <message> <location line="+1"/> <source>This year</source> <translation>Enguany</translation> </message> <message> <location line="+1"/> <source>Range...</source> <translation>Rang...</translation> </message> <message> <location line="+11"/> <source>Received with</source> <translation>Rebut amb</translation> </message> <message> <location line="+2"/> <source>Sent to</source> <translation>Enviat a</translation> </message> <message> <location line="+2"/> <source>To yourself</source> <translation>A tu mateix</translation> </message> <message> <location line="+1"/> <source>Mined</source> <translation>Minat</translation> </message> <message> <location line="+1"/> <source>Other</source> <translation>Altres</translation> </message> <message> <location line="+7"/> <source>Enter address or label to search</source> <translation>Introdueix una adreça o una etiqueta per cercar</translation> </message> <message> <location line="+7"/> <source>Min amount</source> <translation>Quantitat mínima</translation> </message> <message> <location line="+34"/> <source>Copy address</source> <translation>Copiar adreça </translation> </message> <message> <location line="+1"/> <source>Copy label</source> <translation>Copiar etiqueta</translation> </message> <message> <location line="+1"/> <source>Copy amount</source> <translation>Copiar quantitat</translation> </message> <message> <location line="+1"/> <source>Copy transaction ID</source> <translation>Copiar ID de transacció</translation> </message> <message> <location line="+1"/> <source>Edit label</source> <translation>Editar etiqueta</translation> </message> <message> <location line="+1"/> <source>Show transaction details</source> <translation>Mostra detalls de la transacció</translation> </message> <message> <location line="+139"/> <source>Export Transaction Data</source> <translation>Exportar detalls de la transacció </translation> </message> <message> <location line="+1"/> <source>Comma separated file (*.csv)</source> <translation>Arxiu de separació per comes (*.csv)</translation> </message> <message> <location line="+8"/> <source>Confirmed</source> <translation>Confirmat</translation> </message> <message> <location line="+1"/> <source>Date</source> <translation>Data</translation> </message> <message> <location line="+1"/> <source>Type</source> <translation>Tipus</translation> </message> <message> <location line="+1"/> <source>Label</source> <translation>Etiqueta</translation> </message> <message> <location line="+1"/> <source>Address</source> <translation>Direcció</translation> </message> <message> <location line="+1"/> <source>Amount</source> <translation>Quantitat</translation> </message> <message> <location line="+1"/> <source>ID</source> <translation>ID</translation> </message> <message> <location line="+4"/> <source>Error exporting</source> <translation>Error en l&apos;exportació</translation> </message> <message> <location line="+0"/> <source>Could not write to file %1.</source> <translation>No s&apos;ha pogut escriure a l&apos;arxiu %1.</translation> </message> <message> <location line="+100"/> <source>Range:</source> <translation>Rang:</translation> </message> <message> <location line="+8"/> <source>to</source> <translation>a</translation> </message> </context> <context> <name>WalletModel</name> <message> <location filename="../walletmodel.cpp" line="+193"/> <source>Send Coins</source> <translation>Enviar monedes</translation> </message> </context> <context> <name>WalletView</name> <message> <location filename="../walletview.cpp" line="+42"/> <source>&amp;Export</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Export the data in the current tab to a file</source> <translation type="unfinished"/> </message> <message> <location line="+193"/> <source>Backup Wallet</source> <translation>Realitzar còpia de seguretat del moneder</translation> </message> <message> <location line="+0"/> <source>Wallet Data (*.dat)</source> <translation>Dades del moneder (*.dat)</translation> </message> <message> <location line="+3"/> <source>Backup Failed</source> <translation>Còpia de seguretat faillida</translation> </message> <message> <location line="+0"/> <source>There was an error trying to save the wallet data to the new location.</source> <translation>Hi ha hagut un error intentant desar les dades del moneder al nou directori</translation> </message> <message> <location line="+4"/> <source>Backup Successful</source> <translation>Copia de seguretat realitzada correctament</translation> </message> <message> <location line="+0"/> <source>The wallet data was successfully saved to the new location.</source> <translation>Les dades del moneder han estat desades cirrectament al nou emplaçament.</translation> </message> </context> <context> <name>bitcoin-core</name> <message> <location filename="../bitcoinstrings.cpp" line="+94"/> <source>TielnetCoin version</source> <translation>Versió de TielnetCoin</translation> </message> <message> <location line="+102"/> <source>Usage:</source> <translation>Ús:</translation> </message> <message> <location line="-29"/> <source>Send command to -server or tielnetcoind</source> <translation>Enviar comanda a -servidor o tielnetcoind</translation> </message> <message> <location line="-23"/> <source>List commands</source> <translation>Llista d&apos;ordres</translation> </message> <message> <location line="-12"/> <source>Get help for a command</source> <translation>Obtenir ajuda per a un ordre.</translation> </message> <message> <location line="+24"/> <source>Options:</source> <translation>Opcions:</translation> </message> <message> <location line="+24"/> <source>Specify configuration file (default: tielnetcoin.conf)</source> <translation>Especificat arxiu de configuració (per defecte: tielnetcoin.conf)</translation> </message> <message> <location line="+3"/> <source>Specify pid file (default: tielnetcoind.pid)</source> <translation>Especificar arxiu pid (per defecte: tielnetcoind.pid)</translation> </message> <message> <location line="-1"/> <source>Specify data directory</source> <translation>Especificar directori de dades</translation> </message> <message> <location line="-9"/> <source>Set database cache size in megabytes (default: 25)</source> <translation>Establir tamany de la memoria cau en megabytes (per defecte: 25)</translation> </message> <message> <location line="-28"/> <source>Listen for connections on &lt;port&gt; (default: 9333 or testnet: 19333)</source> <translation>Escoltar connexions a &lt;port&gt; (per defecte: 9333 o testnet: 19333)</translation> </message> <message> <location line="+5"/> <source>Maintain at most &lt;n&gt; connections to peers (default: 125)</source> <translation>Mantenir com a molt &lt;n&gt; connexions a peers (per defecte: 125)</translation> </message> <message> <location line="-48"/> <source>Connect to a node to retrieve peer addresses, and disconnect</source> <translation>Connectar al node per obtenir les adreces de les connexions, i desconectar</translation> </message> <message> <location line="+82"/> <source>Specify your own public address</source> <translation>Especificar la teva adreça pública</translation> </message> <message> <location line="+3"/> <source>Threshold for disconnecting misbehaving peers (default: 100)</source> <translation>Límit per a desconectar connexions errònies (per defecte: 100)</translation> </message> <message> <location line="-134"/> <source>Number of seconds to keep misbehaving peers from reconnecting (default: 86400)</source> <translation>Nombre de segons abans de reconectar amb connexions errònies (per defecte: 86400)</translation> </message> <message> <location line="-29"/> <source>An error occurred while setting up the RPC port %u for listening on IPv4: %s</source> <translation>Ha sorgit un error al configurar el port RPC %u escoltant a IPv4: %s</translation> </message> <message> <location line="+27"/> <source>Listen for JSON-RPC connections on &lt;port&gt; (default: 9332 or testnet: 19332)</source> <translation>Escoltar connexions JSON-RPC al port &lt;port&gt; (per defecte: 9332 o testnet:19332)</translation> </message> <message> <location line="+37"/> <source>Accept command line and JSON-RPC commands</source> <translation>Acceptar línia d&apos;ordres i ordres JSON-RPC </translation> </message> <message> <location line="+76"/> <source>Run in the background as a daemon and accept commands</source> <translation>Executar en segon pla com a programa dimoni i acceptar ordres</translation> </message> <message> <location line="+37"/> <source>Use the test network</source> <translation>Usar la xarxa de prova</translation> </message> <message> <location line="-112"/> <source>Accept connections from outside (default: 1 if no -proxy or -connect)</source> <translation>Aceptar connexions d&apos;afora (per defecte: 1 si no -proxy o -connect)</translation> </message> <message> <location line="-80"/> <source>%s, you must set a rpcpassword in the configuration file: %s It is recommended you use the following random password: rpcuser=tielnetcoinrpc rpcpassword=%s (you do not need to remember this password) The username and password MUST NOT be the same. If the file does not exist, create it with owner-readable-only file permissions. It is also recommended to set alertnotify so you are notified of problems; for example: alertnotify=echo %%s | mail -s &quot;TielnetCoin Alert&quot; admin@foo.com </source> <translation>%s has de establir una contrasenya RPC a l&apos;arxiu de configuració:\n%s\nEs recomana que useu la següent constrasenya aleatòria:\nrpcuser=tielnetcoinrpc\nrpcpassword=%s\n(no necesiteu recordar aquesta contrsenya)\nEl nom d&apos;usuari i contrasenya NO HAN de ser els mateixos.\nSi l&apos;arxiu no existeix, crea&apos;l amb els permisos d&apos;arxiu de només lectura per al propietari.\nTambé es recomana establir la notificació d&apos;alertes i així seràs notificat de les incidències;\nper exemple: alertnotify=echo %%s | mail -s &quot;TielnetCoin Alert&quot; admin@foo.com</translation> </message> <message> <location line="+17"/> <source>An error occurred while setting up the RPC port %u for listening on IPv6, falling back to IPv4: %s</source> <translation>Ha sorgit un error al configurar el port RPC %u escoltant a IPv6, retrocedint a IPv4: %s</translation> </message> <message> <location line="+3"/> <source>Bind to given address and always listen on it. Use [host]:port notation for IPv6</source> <translation>Vincular a una adreça específica i sempre escoltar-hi. Utilitza la notació [host]:port per IPv6</translation> </message> <message> <location line="+3"/> <source>Cannot obtain a lock on data directory %s. TielnetCoin is probably already running.</source> <translation>No es pot bloquejar el directori de dades %s. Probablement TielnetCoin ja estigui en execució.</translation> </message> <message> <location line="+3"/> <source>Error: The transaction was rejected! This might happen if some of the coins in your wallet were already spent, such as if you used a copy of wallet.dat and coins were spent in the copy but not marked as spent here.</source> <translation>Error: La transacció ha estat rebutjada. Això pot passar si alguna de les monedes del teu moneder ja s&apos;han gastat, com si haguesis usat una copia de l&apos;arxiu wallet.dat i s&apos;haguessin gastat monedes de la copia però sense marcar com gastades en aquest.</translation> </message> <message> <location line="+4"/> <source>Error: This transaction requires a transaction fee of at least %s because of its amount, complexity, or use of recently received funds!</source> <translation>Error: Aquesta transacció requereix una comissió d&apos;almenys %s degut al seu import, complexitat o per l&apos;ús de fons recentment rebuts!</translation> </message> <message> <location line="+3"/> <source>Execute command when a relevant alert is received (%s in cmd is replaced by message)</source> <translation>Executar ordre al rebre una alerta rellevant (%s al cmd es reemplaça per message)</translation> </message> <message> <location line="+3"/> <source>Execute command when a wallet transaction changes (%s in cmd is replaced by TxID)</source> <translation>Executar una ordre quan una transacció del moneder canviï (%s in cmd es canvia per TxID)</translation> </message> <message> <location line="+11"/> <source>Set maximum size of high-priority/low-fee transactions in bytes (default: 27000)</source> <translation>Establir una mida màxima de transaccions d&apos;alta prioritat/baixa comisió en bytes (per defecte: 27000)</translation> </message> <message> <location line="+6"/> <source>This is a pre-release test build - use at your own risk - do not use for mining or merchant applications</source> <translation>Aquesta és una versió de pre-llançament - utilitza-la sota la teva responsabilitat - No usar per a minería o aplicacions de compra-venda</translation> </message> <message> <location line="+5"/> <source>Warning: -paytxfee is set very high! This is the transaction fee you will pay if you send a transaction.</source> <translation>Advertència: el -paytxfee és molt elevat! Aquesta és la comissió de transacció que pagaràs quan enviis una transacció.</translation> </message> <message> <location line="+3"/> <source>Warning: Displayed transactions may not be correct! You may need to upgrade, or other nodes may need to upgrade.</source> <translation>Advertència: Les transaccions mostrades poden no ser correctes! Pot esser que necessitis actualitzar, o bé que altres nodes ho necessitin.</translation> </message> <message> <location line="+3"/> <source>Warning: Please check that your computer&apos;s date and time are correct! If your clock is wrong TielnetCoin will not work properly.</source> <translation>Advertència: Si us plau comprovi que la data i hora del seu computador siguin correctes! Si el seu rellotge està mal configurat, TielnetCoin no funcionará de manera apropiada.</translation> </message> <message> <location line="+3"/> <source>Warning: error reading wallet.dat! All keys read correctly, but transaction data or address book entries might be missing or incorrect.</source> <translation>Advertència: Error llegint l&apos;arxiu wallet.dat!! Totes les claus es llegeixen correctament, però hi ha dades de transaccions o entrades del llibre d&apos;adreces absents o bé son incorrectes.</translation> </message> <message> <location line="+3"/> <source>Warning: wallet.dat corrupt, data salvaged! Original wallet.dat saved as wallet.{timestamp}.bak in %s; if your balance or transactions are incorrect you should restore from a backup.</source> <translation>Advertència: L&apos;arxiu wallet.dat és corrupte, dades rescatades! L&apos;arxiu wallet.dat original ha estat desat com wallet.{estampa_temporal}.bak al directori %s; si el teu balanç o transaccions son incorrectes hauries de restaurar-lo de un backup.</translation> </message> <message> <location line="+14"/> <source>Attempt to recover private keys from a corrupt wallet.dat</source> <translation>Intentar recuperar les claus privades d&apos;un arxiu wallet.dat corrupte</translation> </message> <message> <location line="+2"/> <source>Block creation options:</source> <translation>Opcions de la creació de blocs:</translation> </message> <message> <location line="+5"/> <source>Connect only to the specified node(s)</source> <translation>Connectar només al(s) node(s) especificats</translation> </message> <message> <location line="+3"/> <source>Corrupted block database detected</source> <translation>S&apos;ha detectat una base de dades de blocs corrupta</translation> </message> <message> <location line="+1"/> <source>Discover own IP address (default: 1 when listening and no -externalip)</source> <translation>Descobrir la pròpia adreça IP (per defecte: 1 quan escoltant i no -externalip)</translation> </message> <message> <location line="+1"/> <source>Do you want to rebuild the block database now?</source> <translation>Vols reconstruir la base de dades de blocs ara?</translation> </message> <message> <location line="+2"/> <source>Error initializing block database</source> <translation>Error carregant la base de dades de blocs</translation> </message> <message> <location line="+1"/> <source>Error initializing wallet database environment %s!</source> <translation>Error inicialitzant l&apos;entorn de la base de dades del moneder %s!</translation> </message> <message> <location line="+1"/> <source>Error loading block database</source> <translation>Error carregant la base de dades del bloc</translation> </message> <message> <location line="+4"/> <source>Error opening block database</source> <translation>Error obrint la base de dades de blocs</translation> </message> <message> <location line="+2"/> <source>Error: Disk space is low!</source> <translation>Error: Espai al disc baix!</translation> </message> <message> <location line="+1"/> <source>Error: Wallet locked, unable to create transaction!</source> <translation>Error: El moneder està blocat, no és possible crear la transacció!</translation> </message> <message> <location line="+1"/> <source>Error: system error: </source> <translation>Error: error de sistema:</translation> </message> <message> <location line="+1"/> <source>Failed to listen on any port. Use -listen=0 if you want this.</source> <translation>Error al escoltar a qualsevol port. Utilitza -listen=0 si vols això.</translation> </message> <message> <location line="+1"/> <source>Failed to read block info</source> <translation>Ha fallat la lectura de la informació del bloc</translation> </message> <message> <location line="+1"/> <source>Failed to read block</source> <translation>Ha fallat la lectura del bloc</translation> </message> <message> <location line="+1"/> <source>Failed to sync block index</source> <translation>Ha fallat la sincronització de l&apos;índex de bloc</translation> </message> <message> <location line="+1"/> <source>Failed to write block index</source> <translation>Ha fallat la escriptura de l&apos;índex de blocs</translation> </message> <message> <location line="+1"/> <source>Failed to write block info</source> <translation>Ha fallat la escriptura de la informació de bloc</translation> </message> <message> <location line="+1"/> <source>Failed to write block</source> <translation>Ha fallat l&apos;escriptura del bloc</translation> </message> <message> <location line="+1"/> <source>Failed to write file info</source> <translation>Ha fallat l&apos;escriptura de l&apos;arxiu info</translation> </message> <message> <location line="+1"/> <source>Failed to write to coin database</source> <translation>Ha fallat l&apos;escriptura de la basse de dades de monedes</translation> </message> <message> <location line="+1"/> <source>Failed to write transaction index</source> <translation>Ha fallat l&apos;escriptura de l&apos;índex de transaccions</translation> </message> <message> <location line="+1"/> <source>Failed to write undo data</source> <translation>Ha fallat el desfer de dades</translation> </message> <message> <location line="+2"/> <source>Find peers using DNS lookup (default: 1 unless -connect)</source> <translation>Cerca punts de connexió usant rastreig de DNS (per defecte: 1 tret d&apos;usar -connect)</translation> </message> <message> <location line="+1"/> <source>Generate coins (default: 0)</source> <translation type="unfinished"/> </message> <message> <location line="+2"/> <source>How many blocks to check at startup (default: 288, 0 = all)</source> <translation>Quants blocs s&apos;han de confirmar a l&apos;inici (per defecte: 288, 0 = tots)</translation> </message> <message> <location line="+1"/> <source>How thorough the block verification is (0-4, default: 3)</source> <translation>Com verificar el bloc (0-4, per defecte 3)</translation> </message> <message> <location line="+19"/> <source>Not enough file descriptors available.</source> <translation type="unfinished"/> </message> <message> <location line="+8"/> <source>Rebuild block chain index from current blk000??.dat files</source> <translation>Reconstruir l&apos;índex de la cadena de blocs dels arxius actuals blk000??.dat</translation> </message> <message> <location line="+16"/> <source>Set the number of threads to service RPC calls (default: 4)</source> <translation>Estableix el nombre de fils per atendre trucades RPC (per defecte: 4)</translation> </message> <message> <location line="+26"/> <source>Verifying blocks...</source> <translation>Verificant blocs...</translation> </message> <message> <location line="+1"/> <source>Verifying wallet...</source> <translation>Verificant moneder...</translation> </message> <message> <location line="-69"/> <source>Imports blocks from external blk000??.dat file</source> <translation>Importa blocs de un fitxer blk000??.dat extern</translation> </message> <message> <location line="-76"/> <source>Set the number of script verification threads (up to 16, 0 = auto, &lt;0 = leave that many cores free, default: 0)</source> <translation type="unfinished"/> </message> <message> <location line="+77"/> <source>Information</source> <translation>&amp;Informació</translation> </message> <message> <location line="+3"/> <source>Invalid -tor address: &apos;%s&apos;</source> <translation>Adreça -tor invàlida: &apos;%s&apos;</translation> </message> <message> <location line="+1"/> <source>Invalid amount for -minrelaytxfee=&lt;amount&gt;: &apos;%s&apos;</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Invalid amount for -mintxfee=&lt;amount&gt;: &apos;%s&apos;</source> <translation type="unfinished"/> </message> <message> <location line="+8"/> <source>Maintain a full transaction index (default: 0)</source> <translation>Mantenir tot l&apos;índex de transaccions (per defecte: 0)</translation> </message> <message> <location line="+2"/> <source>Maximum per-connection receive buffer, &lt;n&gt;*1000 bytes (default: 5000)</source> <translation>Mida màxima del buffer de recepció per a cada connexió, &lt;n&gt;*1000 bytes (default: 5000)</translation> </message> <message> <location line="+1"/> <source>Maximum per-connection send buffer, &lt;n&gt;*1000 bytes (default: 1000)</source> <translation>Mida màxima del buffer d&apos;enviament per a cada connexió, &lt;n&gt;*1000 bytes (default: 5000)</translation> </message> <message> <location line="+2"/> <source>Only accept block chain matching built-in checkpoints (default: 1)</source> <translation>Tan sols acceptar cadenes de blocs que coincideixin amb els punts de prova (per defecte: 1)</translation> </message> <message> <location line="+1"/> <source>Only connect to nodes in network &lt;net&gt; (IPv4, IPv6 or Tor)</source> <translation>Només connectar als nodes de la xarxa &lt;net&gt; (IPv4, IPv6 o Tor)</translation> </message> <message> <location line="+2"/> <source>Output extra debugging information. Implies all other -debug* options</source> <translation>Sortida de la informació extra de debugging. Implica totes les demés opcions -debug*</translation> </message> <message> <location line="+1"/> <source>Output extra network debugging information</source> <translation>Sortida de la informació extra de debugging de xarxa.</translation> </message> <message> <location line="+2"/> <source>Prepend debug output with timestamp</source> <translation>Anteposar estampa temporal a les dades de debug</translation> </message> <message> <location line="+5"/> <source>SSL options: (see the TielnetCoin Wiki for SSL setup instructions)</source> <translation>Opcions SSL: (veure la Wiki de TielnetCoin per a instruccions de configuració SSL)</translation> </message> <message> <location line="+1"/> <source>Select the version of socks proxy to use (4-5, default: 5)</source> <translation>Selecciona la versió de socks proxy a utilitzar (4-5, per defecte: 5)</translation> </message> <message> <location line="+3"/> <source>Send trace/debug info to console instead of debug.log file</source> <translation>Enviar informació de traça/debug a la consola en comptes del arxiu debug.log</translation> </message> <message> <location line="+1"/> <source>Send trace/debug info to debugger</source> <translation>Enviar informació de traça/debug a un debugger</translation> </message> <message> <location line="+5"/> <source>Set maximum block size in bytes (default: 250000)</source> <translation>Establir una mida màxima de bloc en bytes (per defecte: 250000)</translation> </message> <message> <location line="+1"/> <source>Set minimum block size in bytes (default: 0)</source> <translation>Establir una mida mínima de bloc en bytes (per defecte: 0)</translation> </message> <message> <location line="+2"/> <source>Shrink debug.log file on client startup (default: 1 when no -debug)</source> <translation>Reduir l&apos;arxiu debug.log al iniciar el client (per defecte 1 quan no -debug)</translation> </message> <message> <location line="+1"/> <source>Signing transaction failed</source> <translation type="unfinished"/> </message> <message> <location line="+2"/> <source>Specify connection timeout in milliseconds (default: 5000)</source> <translation>Especificar el temps limit per a un intent de connexió en milisegons (per defecte: 5000)</translation> </message> <message> <location line="+4"/> <source>System error: </source> <translation>Error de sistema:</translation> </message> <message> <location line="+4"/> <source>Transaction amount too small</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Transaction amounts must be positive</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Transaction too large</source> <translation type="unfinished"/> </message> <message> <location line="+7"/> <source>Use UPnP to map the listening port (default: 0)</source> <translation>Utilitza UPnP per a mapejar els ports d&apos;escolta (per defecte: 0)</translation> </message> <message> <location line="+1"/> <source>Use UPnP to map the listening port (default: 1 when listening)</source> <translation>Utilitza UPnP per a mapejar els ports d&apos;escolta (per defecte: 1 quan s&apos;escolta)</translation> </message> <message> <location line="+1"/> <source>Use proxy to reach tor hidden services (default: same as -proxy)</source> <translation>Utilitzar proxy per arribar als serveis tor amagats (per defecte: el mateix que -proxy)</translation> </message> <message> <location line="+2"/> <source>Username for JSON-RPC connections</source> <translation>Nom d&apos;usuari per a connexions JSON-RPC</translation> </message> <message> <location line="+4"/> <source>Warning</source> <translation>Avís</translation> </message> <message> <location line="+1"/> <source>Warning: This version is obsolete, upgrade required!</source> <translation>Advertència: Aquetsa versió està obsoleta, és necessari actualitzar!</translation> </message> <message> <location line="+1"/> <source>You need to rebuild the databases using -reindex to change -txindex</source> <translation>Necessiteu reconstruir les bases de dades usant -reindex per canviar -txindex</translation> </message> <message> <location line="+1"/> <source>wallet.dat corrupt, salvage failed</source> <translation>L&apos;arxiu wallet.data és corrupte, el rescat de les dades ha fallat</translation> </message> <message> <location line="-50"/> <source>Password for JSON-RPC connections</source> <translation>Contrasenya per a connexions JSON-RPC</translation> </message> <message> <location line="-67"/> <source>Allow JSON-RPC connections from specified IP address</source> <translation>Permetre connexions JSON-RPC d&apos;adreces IP específiques</translation> </message> <message> <location line="+76"/> <source>Send commands to node running on &lt;ip&gt; (default: 127.0.0.1)</source> <translation>Enviar ordre al node en execució a &lt;ip&gt; (per defecte: 127.0.0.1)</translation> </message> <message> <location line="-120"/> <source>Execute command when the best block changes (%s in cmd is replaced by block hash)</source> <translation>Executar orde quan el millor bloc canviï (%s al cmd es reemplaça per un bloc de hash)</translation> </message> <message> <location line="+147"/> <source>Upgrade wallet to latest format</source> <translation>Actualitzar moneder a l&apos;últim format</translation> </message> <message> <location line="-21"/> <source>Set key pool size to &lt;n&gt; (default: 100)</source> <translation>Establir límit de nombre de claus a &lt;n&gt; (per defecte: 100)</translation> </message> <message> <location line="-12"/> <source>Rescan the block chain for missing wallet transactions</source> <translation>Re-escanejar cadena de blocs en cerca de transaccions de moneder perdudes</translation> </message> <message> <location line="+35"/> <source>Use OpenSSL (https) for JSON-RPC connections</source> <translation>Utilitzar OpenSSL (https) per a connexions JSON-RPC</translation> </message> <message> <location line="-26"/> <source>Server certificate file (default: server.cert)</source> <translation>Arxiu del certificat de servidor (per defecte: server.cert)</translation> </message> <message> <location line="+1"/> <source>Server private key (default: server.pem)</source> <translation>Clau privada del servidor (per defecte: server.pem)</translation> </message> <message> <location line="-151"/> <source>Acceptable ciphers (default: TLSv1+HIGH:!SSLv2:!aNULL:!eNULL:!AH:!3DES:@STRENGTH)</source> <translation>Xifrats acceptats (per defecte: TLSv1+HIGH:!SSLv2:!aNULL:!eNULL:!AH:!3DES:@STRENGTH)</translation> </message> <message> <location line="+165"/> <source>This help message</source> <translation>Aquest misatge d&apos;ajuda</translation> </message> <message> <location line="+6"/> <source>Unable to bind to %s on this computer (bind returned error %d, %s)</source> <translation>Impossible d&apos;unir %s a aquest ordinador (s&apos;ha retornat l&apos;error %d, %s)</translation> </message> <message> <location line="-91"/> <source>Connect through socks proxy</source> <translation>Connectar a través de socks proxy</translation> </message> <message> <location line="-10"/> <source>Allow DNS lookups for -addnode, -seednode and -connect</source> <translation>Permetre consultes DNS per a -addnode, -seednode i -connect</translation> </message> <message> <location line="+55"/> <source>Loading addresses...</source> <translation>Carregant adreces...</translation> </message> <message> <location line="-35"/> <source>Error loading wallet.dat: Wallet corrupted</source> <translation>Error carregant wallet.dat: Moneder corrupte</translation> </message> <message> <location line="+1"/> <source>Error loading wallet.dat: Wallet requires newer version of TielnetCoin</source> <translation>Error carregant wallet.dat: El moneder requereix una versió de TielnetCoin més moderna</translation> </message> <message> <location line="+93"/> <source>Wallet needed to be rewritten: restart TielnetCoin to complete</source> <translation>El moneder necesita ser re-escrit: re-inicia TielnetCoin per a completar la tasca</translation> </message> <message> <location line="-95"/> <source>Error loading wallet.dat</source> <translation>Error carregant wallet.dat</translation> </message> <message> <location line="+28"/> <source>Invalid -proxy address: &apos;%s&apos;</source> <translation>Adreça -proxy invalida: &apos;%s&apos;</translation> </message> <message> <location line="+56"/> <source>Unknown network specified in -onlynet: &apos;%s&apos;</source> <translation>Xarxa desconeguda especificada a -onlynet: &apos;%s&apos;</translation> </message> <message> <location line="-1"/> <source>Unknown -socks proxy version requested: %i</source> <translation>S&apos;ha demanat una versió desconeguda de -socks proxy: %i</translation> </message> <message> <location line="-96"/> <source>Cannot resolve -bind address: &apos;%s&apos;</source> <translation>No es pot resoldre l&apos;adreça -bind: &apos;%s&apos;</translation> </message> <message> <location line="+1"/> <source>Cannot resolve -externalip address: &apos;%s&apos;</source> <translation>No es pot resoldre l&apos;adreça -externalip: &apos;%s&apos;</translation> </message> <message> <location line="+44"/> <source>Invalid amount for -paytxfee=&lt;amount&gt;: &apos;%s&apos;</source> <translation>Quantitat invalida per a -paytxfee=&lt;amount&gt;: &apos;%s&apos;</translation> </message> <message> <location line="+1"/> <source>Invalid amount</source> <translation>Quanitat invalida</translation> </message> <message> <location line="-6"/> <source>Insufficient funds</source> <translation>Balanç insuficient</translation> </message> <message> <location line="+10"/> <source>Loading block index...</source> <translation>Carregant índex de blocs...</translation> </message> <message> <location line="-57"/> <source>Add a node to connect to and attempt to keep the connection open</source> <translation>Afegir un node per a connectar&apos;s-hi i intentar mantenir la connexió oberta</translation> </message> <message> <location line="-25"/> <source>Unable to bind to %s on this computer. TielnetCoin is probably already running.</source> <translation>Impossible d&apos;unir %s en aquest ordinador. Probablement TielnetCoin ja estigui en execució.</translation> </message> <message> <location line="+64"/> <source>Fee per KB to add to transactions you send</source> <translation>Comisió a afegir per cada KB de transaccions que enviïs</translation> </message> <message> <location line="+19"/> <source>Loading wallet...</source> <translation>Carregant moneder...</translation> </message> <message> <location line="-52"/> <source>Cannot downgrade wallet</source> <translation>No es pot reduir la versió del moneder</translation> </message> <message> <location line="+3"/> <source>Cannot write default address</source> <translation>No es pot escriure l&apos;adreça per defecte</translation> </message> <message> <location line="+64"/> <source>Rescanning...</source> <translation>Re-escanejant...</translation> </message> <message> <location line="-57"/> <source>Done loading</source> <translation>Càrrega acabada</translation> </message> <message> <location line="+82"/> <source>To use the %s option</source> <translation>Utilitza la opció %s</translation> </message> <message> <location line="-74"/> <source>Error</source> <translation>Error</translation> </message> <message> <location line="-31"/> <source>You must set rpcpassword=&lt;password&gt; in the configuration file: %s If the file does not exist, create it with owner-readable-only file permissions.</source> <translation>Has de configurar el rpcpassword=&lt;password&gt; a l&apos;arxiu de configuració:\n %s\n Si l&apos;arxiu no existeix, crea&apos;l amb els permís owner-readable-only.</translation> </message> </context> </TS>
{ "content_hash": "9015ede274a600b04207c1ff277e6fea", "timestamp": "", "source": "github", "line_count": 2917, "max_line_length": 612, "avg_line_length": 40.65855330819335, "alnum_prop": 0.6340840296456185, "repo_name": "BuzzPrograms/tielnetcoin", "id": "5700a54d320953e4a1ca50b8068d709dbcf423e9", "size": "118997", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/qt/locale/bitcoin_ca_ES.ts", "mode": "33188", "license": "mit", "language": [ { "name": "C", "bytes": "31208" }, { "name": "C++", "bytes": "2496978" }, { "name": "CSS", "bytes": "1127" }, { "name": "Groff", "bytes": "18284" }, { "name": "HTML", "bytes": "50615" }, { "name": "Makefile", "bytes": "5122" }, { "name": "NSIS", "bytes": "6016" }, { "name": "Objective-C", "bytes": "858" }, { "name": "Objective-C++", "bytes": "5711" }, { "name": "Python", "bytes": "69712" }, { "name": "QMake", "bytes": "14116" }, { "name": "Shell", "bytes": "9737" } ], "symlink_target": "" }
import { KeyChord, KeyCode, KeyMod } from 'vs/base/common/keyCodes'; import { Mimes } from 'vs/base/common/mime'; import { IBulkEditService, ResourceTextEdit } from 'vs/editor/browser/services/bulkEditService'; import { localize } from 'vs/nls'; import { MenuId, registerAction2 } from 'vs/platform/actions/common/actions'; import { ContextKeyExpr } from 'vs/platform/contextkey/common/contextkey'; import { InputFocusedContext, InputFocusedContextKey } from 'vs/platform/contextkey/common/contextkeys'; import { ServicesAccessor } from 'vs/platform/instantiation/common/instantiation'; import { KeybindingWeight } from 'vs/platform/keybinding/common/keybindingsRegistry'; import { ResourceNotebookCellEdit } from 'vs/workbench/contrib/bulkEdit/browser/bulkCellEdits'; import { changeCellToKind, computeCellLinesContents, copyCellRange, joinCellsWithSurrounds, moveCellRange } from 'vs/workbench/contrib/notebook/browser/controller/cellOperations'; import { cellExecutionArgs, CellOverflowToolbarGroups, CellToolbarOrder, CELL_TITLE_CELL_GROUP_ID, INotebookCellActionContext, INotebookCellToolbarActionContext, INotebookCommandContext, NotebookCellAction, NotebookMultiCellAction, parseMultiCellExecutionArgs } from 'vs/workbench/contrib/notebook/browser/controller/coreActions'; import { CellFocusMode, EXPAND_CELL_INPUT_COMMAND_ID, EXPAND_CELL_OUTPUT_COMMAND_ID, ICellViewModel, INotebookEditor } from 'vs/workbench/contrib/notebook/browser/notebookBrowser'; import { NOTEBOOK_CELL_EDITABLE, NOTEBOOK_CELL_HAS_OUTPUTS, NOTEBOOK_CELL_INPUT_COLLAPSED, NOTEBOOK_CELL_LIST_FOCUSED, NOTEBOOK_CELL_OUTPUT_COLLAPSED, NOTEBOOK_CELL_TYPE, NOTEBOOK_EDITOR_EDITABLE, NOTEBOOK_EDITOR_FOCUSED, NOTEBOOK_IS_ACTIVE_EDITOR } from 'vs/workbench/contrib/notebook/common/notebookContextKeys'; import * as icons from 'vs/workbench/contrib/notebook/browser/notebookIcons'; import { CellEditType, CellKind } from 'vs/workbench/contrib/notebook/common/notebookCommon'; //#region Move/Copy cells const MOVE_CELL_UP_COMMAND_ID = 'notebook.cell.moveUp'; const MOVE_CELL_DOWN_COMMAND_ID = 'notebook.cell.moveDown'; const COPY_CELL_UP_COMMAND_ID = 'notebook.cell.copyUp'; const COPY_CELL_DOWN_COMMAND_ID = 'notebook.cell.copyDown'; registerAction2(class extends NotebookCellAction { constructor() { super( { id: MOVE_CELL_UP_COMMAND_ID, title: { value: localize('notebookActions.moveCellUp', "Move Cell Up"), original: 'Move Cell Up' }, icon: icons.moveUpIcon, keybinding: { primary: KeyMod.Alt | KeyCode.UpArrow, when: ContextKeyExpr.and(NOTEBOOK_EDITOR_FOCUSED, InputFocusedContext.toNegated()), weight: KeybindingWeight.WorkbenchContrib }, menu: { id: MenuId.NotebookCellTitle, when: ContextKeyExpr.equals('config.notebook.dragAndDropEnabled', false), group: CellOverflowToolbarGroups.Edit, order: 13 } }); } async runWithContext(accessor: ServicesAccessor, context: INotebookCellActionContext) { return moveCellRange(context, 'up'); } }); registerAction2(class extends NotebookCellAction { constructor() { super( { id: MOVE_CELL_DOWN_COMMAND_ID, title: { value: localize('notebookActions.moveCellDown', "Move Cell Down"), original: 'Move Cell Down' }, icon: icons.moveDownIcon, keybinding: { primary: KeyMod.Alt | KeyCode.DownArrow, when: ContextKeyExpr.and(NOTEBOOK_EDITOR_FOCUSED, InputFocusedContext.toNegated()), weight: KeybindingWeight.WorkbenchContrib }, menu: { id: MenuId.NotebookCellTitle, when: ContextKeyExpr.equals('config.notebook.dragAndDropEnabled', false), group: CellOverflowToolbarGroups.Edit, order: 14 } }); } async runWithContext(accessor: ServicesAccessor, context: INotebookCellActionContext) { return moveCellRange(context, 'down'); } }); registerAction2(class extends NotebookCellAction { constructor() { super( { id: COPY_CELL_UP_COMMAND_ID, title: { value: localize('notebookActions.copyCellUp', "Copy Cell Up"), original: 'Copy Cell Up' }, keybinding: { primary: KeyMod.Alt | KeyMod.Shift | KeyCode.UpArrow, when: ContextKeyExpr.and(NOTEBOOK_EDITOR_FOCUSED, InputFocusedContext.toNegated()), weight: KeybindingWeight.WorkbenchContrib } }); } async runWithContext(accessor: ServicesAccessor, context: INotebookCellActionContext) { return copyCellRange(context, 'up'); } }); registerAction2(class extends NotebookCellAction { constructor() { super( { id: COPY_CELL_DOWN_COMMAND_ID, title: { value: localize('notebookActions.copyCellDown', "Copy Cell Down"), original: 'Copy Cell Down' }, keybinding: { primary: KeyMod.Alt | KeyMod.Shift | KeyCode.DownArrow, when: ContextKeyExpr.and(NOTEBOOK_EDITOR_FOCUSED, InputFocusedContext.toNegated()), weight: KeybindingWeight.WorkbenchContrib }, menu: { id: MenuId.NotebookCellTitle, when: ContextKeyExpr.and(NOTEBOOK_EDITOR_FOCUSED, NOTEBOOK_EDITOR_EDITABLE, NOTEBOOK_CELL_EDITABLE), group: CellOverflowToolbarGroups.Edit, order: 12 } }); } async runWithContext(accessor: ServicesAccessor, context: INotebookCellActionContext) { return copyCellRange(context, 'down'); } }); //#endregion //#region Join/Split const SPLIT_CELL_COMMAND_ID = 'notebook.cell.split'; const JOIN_CELL_ABOVE_COMMAND_ID = 'notebook.cell.joinAbove'; const JOIN_CELL_BELOW_COMMAND_ID = 'notebook.cell.joinBelow'; registerAction2(class extends NotebookCellAction { constructor() { super( { id: SPLIT_CELL_COMMAND_ID, title: { value: localize('notebookActions.splitCell', "Split Cell"), original: 'Split Cell' }, menu: { id: MenuId.NotebookCellTitle, when: ContextKeyExpr.and( NOTEBOOK_EDITOR_EDITABLE, NOTEBOOK_CELL_EDITABLE, NOTEBOOK_CELL_INPUT_COLLAPSED.toNegated() ), order: CellToolbarOrder.SplitCell, group: CELL_TITLE_CELL_GROUP_ID }, icon: icons.splitCellIcon, keybinding: { when: ContextKeyExpr.and(NOTEBOOK_EDITOR_FOCUSED, NOTEBOOK_EDITOR_EDITABLE, NOTEBOOK_CELL_EDITABLE), primary: KeyChord(KeyMod.CtrlCmd | KeyCode.KeyK, KeyMod.CtrlCmd | KeyMod.Shift | KeyCode.Backslash), weight: KeybindingWeight.WorkbenchContrib }, }); } async runWithContext(accessor: ServicesAccessor, context: INotebookCellActionContext) { if (context.notebookEditor.isReadOnly) { return; } const bulkEditService = accessor.get(IBulkEditService); const cell = context.cell; const index = context.notebookEditor.getCellIndex(cell); const splitPoints = cell.focusMode === CellFocusMode.Container ? [{ lineNumber: 1, column: 1 }] : cell.getSelectionsStartPosition(); if (splitPoints && splitPoints.length > 0) { await cell.resolveTextModel(); if (!cell.hasModel()) { return; } const newLinesContents = computeCellLinesContents(cell, splitPoints); if (newLinesContents) { const language = cell.language; const kind = cell.cellKind; const mime = cell.mime; const textModel = await cell.resolveTextModel(); await bulkEditService.apply( [ new ResourceTextEdit(cell.uri, { range: textModel.getFullModelRange(), text: newLinesContents[0] }), new ResourceNotebookCellEdit(context.notebookEditor.textModel.uri, { editType: CellEditType.Replace, index: index + 1, count: 0, cells: newLinesContents.slice(1).map(line => ({ cellKind: kind, language, mime, source: line, outputs: [], metadata: {} })) } ) ], { quotableLabel: 'Split Notebook Cell' } ); } } } }); registerAction2(class extends NotebookCellAction { constructor() { super( { id: JOIN_CELL_ABOVE_COMMAND_ID, title: { value: localize('notebookActions.joinCellAbove', "Join With Previous Cell"), original: 'Join With Previous Cell' }, keybinding: { when: NOTEBOOK_EDITOR_FOCUSED, primary: KeyMod.WinCtrl | KeyMod.Alt | KeyMod.Shift | KeyCode.KeyJ, weight: KeybindingWeight.WorkbenchContrib }, menu: { id: MenuId.NotebookCellTitle, when: ContextKeyExpr.and(NOTEBOOK_EDITOR_FOCUSED, NOTEBOOK_EDITOR_EDITABLE), group: CellOverflowToolbarGroups.Edit, order: 10 } }); } async runWithContext(accessor: ServicesAccessor, context: INotebookCellActionContext) { const bulkEditService = accessor.get(IBulkEditService); return joinCellsWithSurrounds(bulkEditService, context, 'above'); } }); registerAction2(class extends NotebookCellAction { constructor() { super( { id: JOIN_CELL_BELOW_COMMAND_ID, title: { value: localize('notebookActions.joinCellBelow', "Join With Next Cell"), original: 'Join With Next Cell' }, keybinding: { when: NOTEBOOK_EDITOR_FOCUSED, primary: KeyMod.WinCtrl | KeyMod.Alt | KeyCode.KeyJ, weight: KeybindingWeight.WorkbenchContrib }, menu: { id: MenuId.NotebookCellTitle, when: ContextKeyExpr.and(NOTEBOOK_EDITOR_FOCUSED, NOTEBOOK_EDITOR_EDITABLE), group: CellOverflowToolbarGroups.Edit, order: 11 } }); } async runWithContext(accessor: ServicesAccessor, context: INotebookCellActionContext) { const bulkEditService = accessor.get(IBulkEditService); return joinCellsWithSurrounds(bulkEditService, context, 'below'); } }); //#endregion //#region Change Cell Type const CHANGE_CELL_TO_CODE_COMMAND_ID = 'notebook.cell.changeToCode'; const CHANGE_CELL_TO_MARKDOWN_COMMAND_ID = 'notebook.cell.changeToMarkdown'; registerAction2(class ChangeCellToCodeAction extends NotebookMultiCellAction { constructor() { super({ id: CHANGE_CELL_TO_CODE_COMMAND_ID, title: { value: localize('notebookActions.changeCellToCode', "Change Cell to Code"), original: 'Change Cell to Code' }, keybinding: { when: ContextKeyExpr.and(NOTEBOOK_EDITOR_FOCUSED, ContextKeyExpr.not(InputFocusedContextKey)), primary: KeyCode.KeyY, weight: KeybindingWeight.WorkbenchContrib }, precondition: ContextKeyExpr.and(NOTEBOOK_IS_ACTIVE_EDITOR, NOTEBOOK_CELL_TYPE.isEqualTo('markup')), menu: { id: MenuId.NotebookCellTitle, when: ContextKeyExpr.and(NOTEBOOK_EDITOR_FOCUSED, NOTEBOOK_EDITOR_EDITABLE, NOTEBOOK_CELL_EDITABLE, NOTEBOOK_CELL_TYPE.isEqualTo('markup')), group: CellOverflowToolbarGroups.Edit, } }); } async runWithContext(accessor: ServicesAccessor, context: INotebookCommandContext | INotebookCellToolbarActionContext): Promise<void> { await changeCellToKind(CellKind.Code, context); } }); registerAction2(class ChangeCellToMarkdownAction extends NotebookMultiCellAction { constructor() { super({ id: CHANGE_CELL_TO_MARKDOWN_COMMAND_ID, title: { value: localize('notebookActions.changeCellToMarkdown', "Change Cell to Markdown"), original: 'Change Cell to Markdown' }, keybinding: { when: ContextKeyExpr.and(NOTEBOOK_EDITOR_FOCUSED, ContextKeyExpr.not(InputFocusedContextKey)), primary: KeyCode.KeyM, weight: KeybindingWeight.WorkbenchContrib }, precondition: ContextKeyExpr.and(NOTEBOOK_IS_ACTIVE_EDITOR, NOTEBOOK_CELL_TYPE.isEqualTo('code')), menu: { id: MenuId.NotebookCellTitle, when: ContextKeyExpr.and(NOTEBOOK_EDITOR_FOCUSED, NOTEBOOK_EDITOR_EDITABLE, NOTEBOOK_CELL_EDITABLE, NOTEBOOK_CELL_TYPE.isEqualTo('code')), group: CellOverflowToolbarGroups.Edit, } }); } async runWithContext(accessor: ServicesAccessor, context: INotebookCommandContext | INotebookCellToolbarActionContext): Promise<void> { await changeCellToKind(CellKind.Markup, context, 'markdown', Mimes.markdown); } }); //#endregion //#region Collapse Cell const COLLAPSE_CELL_INPUT_COMMAND_ID = 'notebook.cell.collapseCellInput'; const COLLAPSE_CELL_OUTPUT_COMMAND_ID = 'notebook.cell.collapseCellOutput'; const COLLAPSE_ALL_CELL_INPUTS_COMMAND_ID = 'notebook.cell.collapseAllCellInputs'; const EXPAND_ALL_CELL_INPUTS_COMMAND_ID = 'notebook.cell.expandAllCellInputs'; const COLLAPSE_ALL_CELL_OUTPUTS_COMMAND_ID = 'notebook.cell.collapseAllCellOutputs'; const EXPAND_ALL_CELL_OUTPUTS_COMMAND_ID = 'notebook.cell.expandAllCellOutputs'; const TOGGLE_CELL_OUTPUTS_COMMAND_ID = 'notebook.cell.toggleOutputs'; registerAction2(class CollapseCellInputAction extends NotebookMultiCellAction { constructor() { super({ id: COLLAPSE_CELL_INPUT_COMMAND_ID, title: { value: localize('notebookActions.collapseCellInput', "Collapse Cell Input"), original: 'Collapse Cell Input' }, keybinding: { when: ContextKeyExpr.and(NOTEBOOK_CELL_LIST_FOCUSED, NOTEBOOK_CELL_INPUT_COLLAPSED.toNegated(), InputFocusedContext.toNegated()), primary: KeyChord(KeyMod.CtrlCmd | KeyCode.KeyK, KeyMod.CtrlCmd | KeyCode.KeyC), weight: KeybindingWeight.WorkbenchContrib } }); } override parseArgs(accessor: ServicesAccessor, ...args: any[]): INotebookCommandContext | undefined { return parseMultiCellExecutionArgs(accessor, ...args); } async runWithContext(accessor: ServicesAccessor, context: INotebookCommandContext | INotebookCellToolbarActionContext): Promise<void> { if (context.ui) { context.cell.isInputCollapsed = true; } else { context.selectedCells.forEach(cell => cell.isInputCollapsed = true); } } }); registerAction2(class ExpandCellInputAction extends NotebookMultiCellAction { constructor() { super({ id: EXPAND_CELL_INPUT_COMMAND_ID, title: { value: localize('notebookActions.expandCellInput', "Expand Cell Input"), original: 'Expand Cell Input' }, keybinding: { when: ContextKeyExpr.and(NOTEBOOK_CELL_LIST_FOCUSED, NOTEBOOK_CELL_INPUT_COLLAPSED), primary: KeyChord(KeyMod.CtrlCmd | KeyCode.KeyK, KeyMod.CtrlCmd | KeyCode.KeyC), weight: KeybindingWeight.WorkbenchContrib } }); } override parseArgs(accessor: ServicesAccessor, ...args: any[]): INotebookCommandContext | undefined { return parseMultiCellExecutionArgs(accessor, ...args); } async runWithContext(accessor: ServicesAccessor, context: INotebookCommandContext | INotebookCellToolbarActionContext): Promise<void> { if (context.ui) { context.cell.isInputCollapsed = false; } else { context.selectedCells.forEach(cell => cell.isInputCollapsed = false); } } }); registerAction2(class CollapseCellOutputAction extends NotebookMultiCellAction { constructor() { super({ id: COLLAPSE_CELL_OUTPUT_COMMAND_ID, title: { value: localize('notebookActions.collapseCellOutput', "Collapse Cell Output"), original: 'Collapse Cell Output' }, keybinding: { when: ContextKeyExpr.and(NOTEBOOK_CELL_LIST_FOCUSED, NOTEBOOK_CELL_OUTPUT_COLLAPSED.toNegated(), InputFocusedContext.toNegated(), NOTEBOOK_CELL_HAS_OUTPUTS), primary: KeyChord(KeyMod.CtrlCmd | KeyCode.KeyK, KeyCode.KeyT), weight: KeybindingWeight.WorkbenchContrib } }); } async runWithContext(accessor: ServicesAccessor, context: INotebookCommandContext | INotebookCellToolbarActionContext): Promise<void> { if (context.ui) { context.cell.isOutputCollapsed = true; } else { context.selectedCells.forEach(cell => cell.isOutputCollapsed = true); } } }); registerAction2(class ExpandCellOuputAction extends NotebookMultiCellAction { constructor() { super({ id: EXPAND_CELL_OUTPUT_COMMAND_ID, title: { value: localize('notebookActions.expandCellOutput', "Expand Cell Output"), original: 'Expand Cell Output' }, keybinding: { when: ContextKeyExpr.and(NOTEBOOK_CELL_LIST_FOCUSED, NOTEBOOK_CELL_OUTPUT_COLLAPSED), primary: KeyChord(KeyMod.CtrlCmd | KeyCode.KeyK, KeyCode.KeyT), weight: KeybindingWeight.WorkbenchContrib } }); } async runWithContext(accessor: ServicesAccessor, context: INotebookCommandContext | INotebookCellToolbarActionContext): Promise<void> { if (context.ui) { context.cell.isOutputCollapsed = false; } else { context.selectedCells.forEach(cell => cell.isOutputCollapsed = false); } } }); registerAction2(class extends NotebookMultiCellAction { constructor() { super({ id: TOGGLE_CELL_OUTPUTS_COMMAND_ID, precondition: NOTEBOOK_CELL_LIST_FOCUSED, title: { value: localize('notebookActions.toggleOutputs', "Toggle Outputs"), original: 'Toggle Outputs' }, description: { description: localize('notebookActions.toggleOutputs', "Toggle Outputs"), args: cellExecutionArgs } }); } override parseArgs(accessor: ServicesAccessor, ...args: any[]): INotebookCommandContext | undefined { return parseMultiCellExecutionArgs(accessor, ...args); } async runWithContext(accessor: ServicesAccessor, context: INotebookCommandContext | INotebookCellToolbarActionContext): Promise<void> { let cells: readonly ICellViewModel[] = []; if (context.ui) { cells = [context.cell]; } else if (context.selectedCells) { cells = context.selectedCells; } for (const cell of cells) { cell.isOutputCollapsed = !cell.isOutputCollapsed; } } }); registerAction2(class CollapseAllCellInputsAction extends NotebookMultiCellAction { constructor() { super({ id: COLLAPSE_ALL_CELL_INPUTS_COMMAND_ID, title: { value: localize('notebookActions.collapseAllCellInput', "Collapse All Cell Inputs"), original: 'Collapse All Cell Inputs' }, f1: true, }); } async runWithContext(accessor: ServicesAccessor, context: INotebookCommandContext | INotebookCellToolbarActionContext): Promise<void> { forEachCell(context.notebookEditor, cell => cell.isInputCollapsed = true); } }); registerAction2(class ExpandAllCellInputsAction extends NotebookMultiCellAction { constructor() { super({ id: EXPAND_ALL_CELL_INPUTS_COMMAND_ID, title: { value: localize('notebookActions.expandAllCellInput', "Expand All Cell Inputs"), original: 'Expand All Cell Inputs' }, f1: true }); } async runWithContext(accessor: ServicesAccessor, context: INotebookCommandContext | INotebookCellToolbarActionContext): Promise<void> { forEachCell(context.notebookEditor, cell => cell.isInputCollapsed = false); } }); registerAction2(class CollapseAllCellOutputsAction extends NotebookMultiCellAction { constructor() { super({ id: COLLAPSE_ALL_CELL_OUTPUTS_COMMAND_ID, title: { value: localize('notebookActions.collapseAllCellOutput', "Collapse All Cell Outputs"), original: 'Collapse All Cell Outputs' }, f1: true, }); } async runWithContext(accessor: ServicesAccessor, context: INotebookCommandContext | INotebookCellToolbarActionContext): Promise<void> { forEachCell(context.notebookEditor, cell => cell.isOutputCollapsed = true); } }); registerAction2(class ExpandAllCellOutputsAction extends NotebookMultiCellAction { constructor() { super({ id: EXPAND_ALL_CELL_OUTPUTS_COMMAND_ID, title: { value: localize('notebookActions.expandAllCellOutput', "Expand All Cell Outputs"), original: 'Expand All Cell Outputs' }, f1: true }); } async runWithContext(accessor: ServicesAccessor, context: INotebookCommandContext | INotebookCellToolbarActionContext): Promise<void> { forEachCell(context.notebookEditor, cell => cell.isOutputCollapsed = false); } }); //#endregion function forEachCell(editor: INotebookEditor, callback: (cell: ICellViewModel, index: number) => void) { for (let i = 0; i < editor.getLength(); i++) { const cell = editor.cellAt(i); callback(cell!, i); } }
{ "content_hash": "d4c442dda2df5108528706ac947e8c55", "timestamp": "", "source": "github", "line_count": 570, "max_line_length": 330, "avg_line_length": 34.064912280701755, "alnum_prop": 0.7317299273832208, "repo_name": "eamodio/vscode", "id": "5074d759b06508419d30c35d4b15e9eabbc2165f", "size": "19768", "binary": false, "copies": "2", "ref": "refs/heads/main", "path": "src/vs/workbench/contrib/notebook/browser/contrib/cellCommands/cellCommands.ts", "mode": "33188", "license": "mit", "language": [ { "name": "Batchfile", "bytes": "19196" }, { "name": "C", "bytes": "818" }, { "name": "C#", "bytes": "709" }, { "name": "C++", "bytes": "2745" }, { "name": "CSS", "bytes": "620323" }, { "name": "Clojure", "bytes": "1206" }, { "name": "CoffeeScript", "bytes": "590" }, { "name": "Cuda", "bytes": "3634" }, { "name": "Dart", "bytes": "324" }, { "name": "Dockerfile", "bytes": "475" }, { "name": "F#", "bytes": "634" }, { "name": "Go", "bytes": "652" }, { "name": "Groovy", "bytes": "3928" }, { "name": "HLSL", "bytes": "184" }, { "name": "HTML", "bytes": "380999" }, { "name": "Hack", "bytes": "16" }, { "name": "Handlebars", "bytes": "1064" }, { "name": "Inno Setup", "bytes": "304239" }, { "name": "Java", "bytes": "599" }, { "name": "JavaScript", "bytes": "1413253" }, { "name": "Julia", "bytes": "940" }, { "name": "Jupyter Notebook", "bytes": "929" }, { "name": "Less", "bytes": "1029" }, { "name": "Lua", "bytes": "252" }, { "name": "Makefile", "bytes": "2252" }, { "name": "Objective-C", "bytes": "1387" }, { "name": "Objective-C++", "bytes": "1387" }, { "name": "PHP", "bytes": "998" }, { "name": "Perl", "bytes": "1922" }, { "name": "PowerShell", "bytes": "12409" }, { "name": "Pug", "bytes": "654" }, { "name": "Python", "bytes": "2405" }, { "name": "R", "bytes": "362" }, { "name": "Roff", "bytes": "351" }, { "name": "Ruby", "bytes": "1703" }, { "name": "Rust", "bytes": "532" }, { "name": "SCSS", "bytes": "6732" }, { "name": "ShaderLab", "bytes": "330" }, { "name": "Shell", "bytes": "57256" }, { "name": "Swift", "bytes": "284" }, { "name": "TeX", "bytes": "1602" }, { "name": "TypeScript", "bytes": "41954506" }, { "name": "Visual Basic .NET", "bytes": "893" } ], "symlink_target": "" }
<?php namespace fXmlRpc\Client\Tests\Exception; use fXmlRpc\Client\Exception\InvalidArgumentException; /** * @author Lars Strojny <lstrojny@php.net> */ class InvalidArgumentExceptionTest extends \PHPUnit_Framework_TestCase { public function testExceptionImplementsExceptionInterface() { $this->assertInstanceOf('fXmlRpc\Exception', new InvalidArgumentException()); } public function testInvalidExpectedParameter() { $e = InvalidArgumentException::expectedParameter(1, 'string', false); $this->assertEquals( 'Expected parameter 1 to be of type "string", "boolean" given', $e->getMessage() ); } public function testInvalidExpectedObjectParameter() { $e = InvalidArgumentException::expectedParameter(1, 'string', new \stdClass); $this->assertEquals( 'Expected parameter 1 to be of type "string", "object" of type "stdClass" given', $e->getMessage() ); } }
{ "content_hash": "6482051218fb189bbd0196fb964d6655", "timestamp": "", "source": "github", "line_count": 38, "max_line_length": 93, "avg_line_length": 26.42105263157895, "alnum_prop": 0.6613545816733067, "repo_name": "fxmlrpc/fxmlrpc", "id": "7b584cf054186ee91829cafddf0c99fbb310851a", "size": "1234", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "tests/Exception/InvalidArgumentExceptionTest.php", "mode": "33188", "license": "mit", "language": [ { "name": "PHP", "bytes": "3711" } ], "symlink_target": "" }
package de.chrgroth.generictypesystem.validation.impl; import java.util.ArrayList; import java.util.List; import java.util.Set; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.junit.runners.Parameterized; import org.junit.runners.Parameterized.Parameter; import org.junit.runners.Parameterized.Parameters; import de.chrgroth.generictypesystem.model.DefaultGenericAttributeType; import de.chrgroth.generictypesystem.model.GenericAttribute; import de.chrgroth.generictypesystem.model.GenericStructure; import de.chrgroth.generictypesystem.model.GenericType; import de.chrgroth.generictypesystem.model.GenericUnits; import de.chrgroth.generictypesystem.model.GenericValue; import de.chrgroth.generictypesystem.validation.BaseValidationServiceTypeAndItemTest; import de.chrgroth.generictypesystem.validation.ValidationError; @RunWith(Parameterized.class) public class DefaultValidationServiceTypeAttributeTypeTest extends BaseValidationServiceTypeAndItemTest { private static final String ATTRIBUTE_NAME = "dummy"; private UnitsLookupTestHelper unitsLookupTestHelper; @Before public void setup() { unitsLookupTestHelper = new UnitsLookupTestHelper(); service = new DefaultValidationService(unitsLookupTestHelper, null); type = new GenericType(0l, "testType", "testGroup", null, null, null, null); } @Parameters(name = "attribute type {0} value type {1}") public static Iterable<DefaultGenericAttributeType[]> data() { List<DefaultGenericAttributeType[]> data = new ArrayList<>(); for (DefaultGenericAttributeType type : DefaultGenericAttributeType.values()) { for (DefaultGenericAttributeType valueType : DefaultGenericAttributeType.values()) { data.add(new DefaultGenericAttributeType[] { type, valueType }); } } return data; } @Parameter(value = 0) public DefaultGenericAttributeType testType; @Parameter(value = 1) public DefaultGenericAttributeType testValueType; @Test public void attributeTypeTest() { // create attribute with type only createAttribute(null, false, false, null, null, null, null, null, null, null, null, null); // define expected error message keys List<ValidationError> errorKeys = new ArrayList<>(); if (testType.isEnum()) { errorKeys.add(new ValidationError(ATTRIBUTE_NAME, DefaultValidationServiceMessageKey.TYPE_ATTRIBUTE_ENUM_VALUE_NOT_AVAILABLE)); } else if (testType.isList()) { errorKeys.add(new ValidationError(ATTRIBUTE_NAME, DefaultValidationServiceMessageKey.TYPE_ATTRIBUTE_LIST_VALUE_TYPE_MANDATORY)); } else if (testType.isStructure()) { errorKeys.add(new ValidationError(ATTRIBUTE_NAME, DefaultValidationServiceMessageKey.TYPE_ATTRIBUTE_STRUCTURE_STRUCTURE_MANDATORY)); } // validate type validateType(errorKeys.toArray(new ValidationError[errorKeys.size()])); // create attribute with value type clearAttributes(); createAttribute(testValueType, false, false, null, null, null, null, null, null, null, null, null); // define expected error message keys errorKeys = new ArrayList<>(); if (testType.isEnum()) { errorKeys.add(new ValidationError(ATTRIBUTE_NAME, DefaultValidationServiceMessageKey.TYPE_ATTRIBUTE_ENUM_VALUE_NOT_AVAILABLE)); } if (testType.isList()) { if (testValueType.isList()) { errorKeys.add(new ValidationError(ATTRIBUTE_NAME, DefaultValidationServiceMessageKey.TYPE_ATTRIBUTE_LIST_NESTED_LISTS_NOT_ALLOWED)); } else if (testValueType.isStructure()) { errorKeys.add(new ValidationError(ATTRIBUTE_NAME, DefaultValidationServiceMessageKey.TYPE_ATTRIBUTE_LIST_STRUCTURE_MANDATORY)); } } else { if (testType.isStructure()) { errorKeys.add(new ValidationError(ATTRIBUTE_NAME, DefaultValidationServiceMessageKey.TYPE_ATTRIBUTE_STRUCTURE_STRUCTURE_MANDATORY)); errorKeys.add(new ValidationError(ATTRIBUTE_NAME, DefaultValidationServiceMessageKey.TYPE_ATTRIBUTE_STRUCTURE_VALUE_TYPE_NOT_ALLOWED)); } else { errorKeys.add(new ValidationError(ATTRIBUTE_NAME, DefaultValidationServiceMessageKey.TYPE_ATTRIBUTE_VALUE_TYPE_NOT_ALLOWED)); } } // validate type validateType(errorKeys.toArray(new ValidationError[errorKeys.size()])); // create attribute with structure clearAttributes(); createAttribute(null, false, false, new GenericStructure(), null, null, null, null, null, null, null, null); // define expected error message keys errorKeys = new ArrayList<>(); if (testType.isEnum()) { errorKeys.add(new ValidationError(ATTRIBUTE_NAME, DefaultValidationServiceMessageKey.TYPE_ATTRIBUTE_ENUM_VALUE_NOT_AVAILABLE)); } if (testType.isList()) { errorKeys.add(new ValidationError(ATTRIBUTE_NAME, DefaultValidationServiceMessageKey.TYPE_ATTRIBUTE_LIST_VALUE_TYPE_MANDATORY)); } else if (!testType.isStructure()) { errorKeys.add(new ValidationError(ATTRIBUTE_NAME, DefaultValidationServiceMessageKey.TYPE_ATTRIBUTE_STRUCTURE_NOT_ALLOWED)); } // validate type validateType(errorKeys.toArray(new ValidationError[errorKeys.size()])); // create attribute with value type and structure clearAttributes(); createAttribute(testValueType, false, false, new GenericStructure(), null, null, null, null, null, null, null, null); // define expected error message keys errorKeys = new ArrayList<>(); if (testType.isEnum()) { errorKeys.add(new ValidationError(ATTRIBUTE_NAME, DefaultValidationServiceMessageKey.TYPE_ATTRIBUTE_ENUM_VALUE_NOT_AVAILABLE)); } if (testType.isList()) { if (testValueType.isList()) { errorKeys.add(new ValidationError(ATTRIBUTE_NAME, DefaultValidationServiceMessageKey.TYPE_ATTRIBUTE_LIST_NESTED_LISTS_NOT_ALLOWED)); } if (!testValueType.isStructure()) { errorKeys.add(new ValidationError(ATTRIBUTE_NAME, DefaultValidationServiceMessageKey.TYPE_ATTRIBUTE_LIST_STRUCTURE_NOT_ALLOWED, testValueType.toString())); } } else if (testType.isStructure()) { errorKeys.add(new ValidationError(ATTRIBUTE_NAME, DefaultValidationServiceMessageKey.TYPE_ATTRIBUTE_STRUCTURE_VALUE_TYPE_NOT_ALLOWED)); } else { errorKeys.add(new ValidationError(ATTRIBUTE_NAME, DefaultValidationServiceMessageKey.TYPE_ATTRIBUTE_VALUE_TYPE_NOT_ALLOWED)); errorKeys.add(new ValidationError(ATTRIBUTE_NAME, DefaultValidationServiceMessageKey.TYPE_ATTRIBUTE_STRUCTURE_NOT_ALLOWED)); } // validate type validateType(errorKeys.toArray(new ValidationError[errorKeys.size()])); } public void createAttribute(DefaultGenericAttributeType valueType, boolean unique, boolean mandatory, GenericStructure structure, Double min, Double max, Double step, String pattern, GenericValue<?> defaultValue, String defaultValueCallback, Set<Long> valueProposalDependencies, GenericUnits units) { attribute = new GenericAttribute(0l, ATTRIBUTE_NAME, testType, valueType, unique, mandatory, structure, min, max, step, pattern, defaultValue, defaultValueCallback, valueProposalDependencies, units != null ? units.getId() : null, null); if (units != null) { unitsLookupTestHelper.register(units); } type.getAttributes().add(attribute); } private void clearAttributes() { type.getAttributes().clear(); } }
{ "content_hash": "e496ad5f58e4e122ab0a6d77f5df7765", "timestamp": "", "source": "github", "line_count": 158, "max_line_length": 172, "avg_line_length": 49.70886075949367, "alnum_prop": 0.7079195314489433, "repo_name": "christiangroth/generic-typesystem", "id": "fec027732d6ff8de5b3019473132e533c7f9af4c", "size": "7854", "binary": false, "copies": "1", "ref": "refs/heads/develop", "path": "src/test/java/de/chrgroth/generictypesystem/validation/impl/DefaultValidationServiceTypeAttributeTypeTest.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Java", "bytes": "291095" } ], "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 model 'Category' db.create_table(u'faq_category', ( (u'id', self.gf('django.db.models.fields.AutoField')(primary_key=True)), ('name', self.gf('django.db.models.fields.CharField')(max_length=150)), ('slug', self.gf('django.db.models.fields.SlugField')(max_length=75)), ('display_order', self.gf('django.db.models.fields.PositiveIntegerField')(default=1, db_index=True)), )) db.send_create_signal(u'faq', ['Category']) # Adding model 'Question' db.create_table(u'faq_question', ( (u'id', self.gf('django.db.models.fields.AutoField')(primary_key=True)), ('question', self.gf('django.db.models.fields.TextField')()), ('answer', self.gf('django.db.models.fields.TextField')()), ('display_order', self.gf('django.db.models.fields.PositiveIntegerField')(default=1, db_index=True)), ('category', self.gf('django.db.models.fields.related.ForeignKey')(related_name='questions', null=True, on_delete=models.SET_NULL, to=orm['faq.Category'])), )) db.send_create_signal(u'faq', ['Question']) def backwards(self, orm): # Deleting model 'Category' db.delete_table(u'faq_category') # Deleting model 'Question' db.delete_table(u'faq_question') models = { u'faq.category': { 'Meta': {'ordering': "('display_order',)", 'object_name': 'Category'}, 'display_order': ('django.db.models.fields.PositiveIntegerField', [], {'default': '1', 'db_index': 'True'}), u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'name': ('django.db.models.fields.CharField', [], {'max_length': '150'}), 'slug': ('django.db.models.fields.SlugField', [], {'max_length': '75'}) }, u'faq.question': { 'Meta': {'ordering': "('display_order',)", 'object_name': 'Question'}, 'answer': ('django.db.models.fields.TextField', [], {}), 'category': ('django.db.models.fields.related.ForeignKey', [], {'related_name': "'questions'", 'null': 'True', 'on_delete': 'models.SET_NULL', 'to': u"orm['faq.Category']"}), 'display_order': ('django.db.models.fields.PositiveIntegerField', [], {'default': '1', 'db_index': 'True'}), u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'question': ('django.db.models.fields.TextField', [], {}) } } complete_apps = ['faq']
{ "content_hash": "f706360920c1b8dfcbe32303041dcfb2", "timestamp": "", "source": "github", "line_count": 56, "max_line_length": 186, "avg_line_length": 48.642857142857146, "alnum_prop": 0.5833333333333334, "repo_name": "waustin/django-simple-faq", "id": "698a141bd1c51ac2a161a2b3cc2733cbd5a0e1de", "size": "2748", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "faq/migrations/0001_initial.py", "mode": "33188", "license": "bsd-3-clause", "language": [ { "name": "Python", "bytes": "12509" } ], "symlink_target": "" }
using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; // General Information about an assembly is controlled through the following // set of attributes. Change these attribute values to modify the information // associated with an assembly. [assembly: AssemblyTitle("01.BlankReceipt")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("01.BlankReceipt")] [assembly: AssemblyCopyright("Copyright © 2017")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. [assembly: ComVisible(false)] // The following GUID is for the ID of the typelib if this project is exposed to COM [assembly: Guid("a498d4d4-56b8-4a6c-97f2-185da83dc042")] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Build and Revision Numbers // by using the '*' as shown below: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("1.0.0.0")] [assembly: AssemblyFileVersion("1.0.0.0")]
{ "content_hash": "de633c0d98f4cb81c056d0758e877220", "timestamp": "", "source": "github", "line_count": 36, "max_line_length": 84, "avg_line_length": 38.97222222222222, "alnum_prop": 0.744832501781896, "repo_name": "GerganaRibarova/Programming-Fundamentals-Extended", "id": "5f950b7b9567eae66d5df899c137ce292c695a25", "size": "1406", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "Methods-Lab/01.BlankReceipt/Properties/AssemblyInfo.cs", "mode": "33188", "license": "mit", "language": [ { "name": "C#", "bytes": "166118" } ], "symlink_target": "" }
<?xml version="1.0" encoding="utf-8"?> <!-- Copyright (C) 2010 The Android Open Source Project 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. --> <!-- **** **** THIS FILE WAS GENERATED BY tools/get_search_engines.py **** Each value in the string-array is the name of a value in all_search_engines.xml --> <resources xmlns:xliff="urn:oasis:names:tc:xliff:document:1.2"> <string-array name="search_engines" translatable="false"> <item>google</item> <item>bing_nl_BE</item> <item>yahoo</item> <item>bing_fr_BE</item> </string-array> </resources>
{ "content_hash": "9832d3dffefe390fe29d9c6e1582be95", "timestamp": "", "source": "github", "line_count": 30, "max_line_length": 79, "avg_line_length": 36.266666666666666, "alnum_prop": 0.7003676470588235, "repo_name": "xjwangliang/android_source_note", "id": "d743fc095dfde830f1ba3a11d3cde96ff5f40777", "size": "1088", "binary": false, "copies": "14", "ref": "refs/heads/master", "path": "Browser_2.3/BrowserActivity/res/values-nl-rBE/donottranslate-search_engines.xml", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Java", "bytes": "1598341" }, { "name": "Python", "bytes": "9928" } ], "symlink_target": "" }
import stix from stix.common import StructuredTextList # bindings import stix.bindings.ttp as ttp_binding from mixbox import fields class Exploit(stix.Entity): _binding = ttp_binding _binding_class = _binding.ExploitType _namespace = "http://stix.mitre.org/TTP-1" id_ = fields.IdField("id") idref = fields.IdrefField("idref") title = fields.TypedField("Title") descriptions = fields.TypedField("Description", type_="stix.common.StructuredTextList") short_descriptions = fields.TypedField("Short_Description", type_="stix.common.StructuredTextList") def __init__(self, id_=None, idref=None, title=None, description=None, short_description=None): super(Exploit, self).__init__() self.id_ = id_ self.idref = idref self.title = title self.description = StructuredTextList(description) self.short_description = StructuredTextList(short_description) @property def description(self): """A single description about the contents or purpose of this object. Default Value: ``None`` Note: If this object has more than one description set, this will return the description with the lowest ordinality value. Returns: An instance of :class:`.StructuredText` """ if self.descriptions is None: self.descriptions = StructuredTextList() return next(iter(self.descriptions), None) @description.setter def description(self, value): self.descriptions = value def add_description(self, description): """Adds a description to the ``descriptions`` collection. This is the same as calling "foo.descriptions.add(bar)". """ self.descriptions.add(description) @property def short_description(self): """A single short description about the contents or purpose of this object. Default Value: ``None`` Note: If this object has more than one short description set, this will return the description with the lowest ordinality value. Returns: An instance of :class:`.StructuredText` """ if self.short_descriptions is None: self.short_descriptions = StructuredTextList() return next(iter(self.short_descriptions), None) @short_description.setter def short_description(self, value): self.short_descriptions = value def add_short_description(self, description): """Adds a description to the ``short_descriptions`` collection. This is the same as calling "foo.short_descriptions.add(bar)". """ self.short_descriptions.add(description)
{ "content_hash": "be6090c33b5f2b8c0f72b66a38b92512", "timestamp": "", "source": "github", "line_count": 83, "max_line_length": 103, "avg_line_length": 32.95180722891566, "alnum_prop": 0.6548446069469835, "repo_name": "STIXProject/python-stix", "id": "ebdbb5a7d2d51733918a5f1b47ee1b422a2e6fe3", "size": "2851", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "stix/ttp/exploit.py", "mode": "33188", "license": "bsd-3-clause", "language": [ { "name": "Python", "bytes": "1422974" } ], "symlink_target": "" }
var StructReference = require('./types/reference') exports.methodsFor = function(obj, prop, get, set) { obj[get] = function(parent) { if (!this[prop]) return 0 if (this[prop] instanceof StructReference) return parent[this[prop].prop] else if (typeof this[prop] === 'function') return this[prop].call(parent) return this[prop] } if (!set) return obj[set] = function(value, parent) { if (this[prop] instanceof StructReference) parent[this[prop].prop] = value else this[prop] = value } } exports.options = function(opts) { if (typeof opts === 'object') { this._offset = opts.offset this._length = opts.length this._size = opts.size this.$unpacked = opts.$unpacked this.$packing = opts.$packing this.external = opts.external === true this.storage = opts.storage this.littleEndian = opts.littleEndian === true } else { this._length = opts } }
{ "content_hash": "2bf170006101becfda27af92f535ac18", "timestamp": "", "source": "github", "line_count": 33, "max_line_length": 52, "avg_line_length": 29.303030303030305, "alnum_prop": 0.6204756980351603, "repo_name": "sapit/whiteboard", "id": "ec90a9c325115ee3f00c880d1646f3c3f2e3c77f", "size": "967", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "node_modules/pdfjs/node_modules/ttfjs/node_modules/structjs/lib/utils.js", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Batchfile", "bytes": "14" }, { "name": "CSS", "bytes": "15031" }, { "name": "HTML", "bytes": "16244" }, { "name": "JavaScript", "bytes": "618112" }, { "name": "Shell", "bytes": "4719" } ], "symlink_target": "" }
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed'); class Home_model extends CI_Model{ public function insert_data($array){ $this->db->insert('formdata',$array); } public function check_exit_values($field_name,$field_value) { return $this->db->select('formdata_id') ->from('formdata') ->where($field_name,$field_value) ->get() ->result(); } } ?>
{ "content_hash": "c2aa5dc03734790f30d2cec5597333ea", "timestamp": "", "source": "github", "line_count": 16, "max_line_length": 76, "avg_line_length": 33.4375, "alnum_prop": 0.4747663551401869, "repo_name": "vinupatidar/testlookup", "id": "e73667eded3c0e30b3fc178938ed7e7e70c1a797", "size": "535", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "application/models/home_model.php", "mode": "33188", "license": "mit", "language": [ { "name": "ApacheConf", "bytes": "424" }, { "name": "HTML", "bytes": "4830" }, { "name": "PHP", "bytes": "1706591" } ], "symlink_target": "" }
<?php namespace Neutrino\Repositories\Exceptions; use Phalcon\Exception; class TransactionException extends Exception { }
{ "content_hash": "d4d4ff70a9949e51004a140541d4954d", "timestamp": "", "source": "github", "line_count": 10, "max_line_length": 44, "avg_line_length": 12.5, "alnum_prop": 0.816, "repo_name": "phalcon-nucleon/framework", "id": "87e812bbbc32490253f794765a79e336a3c6fde6", "size": "125", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/Neutrino/Repositories/Exceptions/TransactionException.php", "mode": "33188", "license": "mit", "language": [ { "name": "PHP", "bytes": "1445318" } ], "symlink_target": "" }
<?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE mbean PUBLIC "-//JBoss//DTD JBOSS XMBEAN 1.1//EN" "http://www.jboss.org/j2ee/dtd/jboss_xmbean_1_1.dtd"> <!-- Version $Revision:$ $Date:$ --> <server> <mbean code="org.jboss.jms.server.destination.QueueService" name="dcm4chee.web:service=Queue,name=IANSCU_web" xmbean-dd="xmdesc/Queue-xmbean.xml"> <depends optional-attribute-name="ServerPeer">jboss.messaging:service=ServerPeer</depends> <depends>jboss.messaging:service=PostOffice</depends> </mbean> <mbean code="org.dcm4chee.web.service.ian.IANScuService" name="dcm4chee.web:service=IANSCU" xmbean-dd=""> <depends optional-attribute-name="JMSServiceName">dcm4chee.archive:service=JMS</depends> <depends>dcm4chee.web:service=Queue,name=IANSCU_web</depends> <depends optional-attribute-name="TlsCfgServiceName">dcm4chee.web:service=TlsConfig</depends> <xmbean> <description><![CDATA[<b>Instance Availability Notification (IAN) SCU Service</b> ]]> </description> <descriptors> <persistence persistPolicy="OnUpdate"/> <persistence-manager value="org.jboss.mx.persistence.DelegatingPersistenceManager" /> </descriptors> <class>org.dcm4chee.web.service.ian.IANScuService</class> <constructor> <description>The default constructor</description> <name>IANScuService</name> </constructor> <attribute access="read-write" getMethod="getCallingAET" setMethod="setCallingAET"> <description>Calling AE title of the Store SCU to send Rejection Note Key Object Selection. </description> <name>CallingAETitle</name> <type>java.lang.String</type> <descriptors> <value value="DCM4CHEE" /> </descriptors> </attribute> <attribute access="read-write" getMethod="getCalledAETs" setMethod="setCalledAETs"> <description>AE title(s) of Store SCPs. </description> <name>CalledAETitles</name> <type>java.lang.String</type> <descriptors> <value value="NONE" /> </descriptors> </attribute> <attribute access="read-write" getMethod="isOfferStudyContentNotification" setMethod="setOfferStudyContentNotification"> <description>Offer also retired Study Content Notification. </description> <name>OfferStudyContentNotification</name> <type>boolean</type> <descriptors> <value value="false" /> </descriptors> </attribute> <attribute access="read-write" getMethod="getPriority" setMethod="setPriority"> <description>Priority used in C-MOVE requests. Enumerated Values: LOW, MEDIUM, HIGH. </description> <name>Priority</name> <type>java.lang.String</type> <descriptors> <value value="MEDIUM"/> </descriptors> </attribute> <attribute access="read-write" getMethod="getConnectTimeout" setMethod="setConnectTimeout"> <description>Connection timeout in ms. 0 = no timeout</description> <name>ConnectTimeout</name> <type>int</type> <descriptors> <value value="0"/> </descriptors> </attribute> <attribute access="read-write" getMethod="getAcceptTimeout" setMethod="setAcceptTimeout"> <description>A-Associate accept timeout in milliseconds. 0 = no timeout.</description> <name>AcceptTimeout</name> <type>int</type> <descriptors> <value value="10000"/> </descriptors> </attribute> <attribute access="read-write" getMethod="getRetrieveRspTimeout" setMethod="setRetrieveRspTimeout"> <description>Timeout in milliseconds for receiving DIMSE-RSP for an open C-MOVE request. 0 = no timeout. </description> <name>RetrieveRspTimeout</name> <type>int</type> <descriptors> <value value="60000"/> </descriptors> </attribute> <attribute access="read-write" getMethod="getReleaseTimeout" setMethod="setReleaseTimeout"> <description>Timeout in ms for receiving A-RELEASE-RP. </description> <name>ReleaseTimeout</name> <type>int</type> <descriptors> <value value="5000"/> </descriptors> </attribute> <attribute access="read-write" getMethod="getSocketCloseDelay" setMethod="setSocketCloseDelay"> <description>Delay in ms for Socket close after sending A-ABORT. </description> <name>SocketCloseDelay</name> <type>int</type> <descriptors> <value value="50"/> </descriptors> </attribute> <attribute access="read-write" getMethod="getMaxPDULengthReceive" setMethod="setMaxPDULengthReceive"> <description>Maximum protocol data unit (PDU) package length for receiving PDUs. </description> <name>MaximumPDULengthReceive</name> <type>int</type> <descriptors> <value value="16352"/> </descriptors> </attribute> <attribute access="read-write" getMethod="getMaxOpsInvoked" setMethod="setMaxOpsInvoked"> <description>Maximum number of outstanding operations this MOVE SCU will invoke on one Association. 0 = no limit </description> <name>getMaxOpsInvoked</name> <type>int</type> <descriptors> <value value="0"/> </descriptors> </attribute> <attribute access="read-write" getMethod="isTcpNoDelay" setMethod="setTcpNoDelay"> <description>Send packets as quickly as possible (Disable Nagle's algorithmn). </description> <name>TcpNoDelay</name> <type>boolean</type> <descriptors> <value value="true" /> </descriptors> </attribute> <attribute access="read-write" getMethod="getRetryIntervalls" setMethod="setRetryIntervalls"> <description>Number and intervals of retries for failed Instance Available or Study Content Notification requests. &lt;br&gt;Format: &lt;br&gt;Comma separated list of &lt;i&gt;number&lt;/I&gt; x &lt;i&gt;interval&lt;/I&gt; pairs. &lt;br&gt;The interval can be specified in seconds (##s), minutes (##m), hours (##h) or days (##d). &lt;br&gt;Example: &lt;br&gt;5x1m,10x10m means retry a total of 5 times, one minute apart for each retry; then retry a total of 10 times, 10 minutes apart for each retry. </description> <name>RetryIntervals</name> <type>java.lang.String</type> <descriptors> <value value="5x1m,12x5m,24x1h,7x1d"/> </descriptors> </attribute> <attribute access="read-write" getMethod="getQueueName" setMethod="setQueueName"> <description>Used internally. Do not modify.</description> <name>QueueName</name> <type>java.lang.String</type> <descriptors> <value value="IANSCU_web" /> </descriptors> </attribute> <attribute access="read-write" getMethod="getTlsCfgServiceName" setMethod="setTlsCfgServiceName"> <description>Used internally. Do NOT modify. </description> <name>TlsCfgServiceName</name> <type>javax.management.ObjectName</type> </attribute> <attribute access="read-write" getMethod="getJmsServiceName" setMethod="setJmsServiceName"> <description>Used internally. Do NOT modify. </description> <name>JMSServiceName</name> <type>javax.management.ObjectName</type> </attribute> <attribute access="read-write" getMethod="getConcurrency" setMethod="setConcurrency"> <description>Maximum number of concurrent sent notifications. </description> <name>Concurrency</name> <type>int</type> <descriptors> <value value="1"/> </descriptors> </attribute> &defaultAttributes; <!-- Operations --> &defaultOperations; <operation impact="ACTION"> <description><![CDATA[ Schedule Instance Availability Notification to configured calledAETs. ]]> </description> <name>scheduleIAN</name> <parameter> <description>DicomObject with IAN attributes</description> <name>ian</name> <type>org.dcm4che2.data.DicomObject</type> </parameter> <return-type>void</return-type> </operation> </xmbean> </mbean> </server>
{ "content_hash": "4307480353b8badca7b58006afb2e311", "timestamp": "", "source": "github", "line_count": 241, "max_line_length": 118, "avg_line_length": 34.46058091286307, "alnum_prop": 0.6573148705599037, "repo_name": "medicayun/medicayundicom", "id": "f8026ceca5be7618d9db4bb19271865e038ea215", "size": "8305", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "dcm4chee-web/tags/DCM4CHEE_WEB_3_0_0_TEST1/dcm4chee-web-sar/dcm4chee-web-sar-ianscu/src/main/resources/META-INF/jboss-service.xml", "mode": "33188", "license": "apache-2.0", "language": [], "symlink_target": "" }
export { default } from './UserAutoComplete';
{ "content_hash": "e95e46a7ac6fd7d85065ecad3a44f429", "timestamp": "", "source": "github", "line_count": 1, "max_line_length": 45, "avg_line_length": 46, "alnum_prop": 0.717391304347826, "repo_name": "VoiSmart/Rocket.Chat", "id": "4fb4f7b54f1b44aa6455e7cca32a8ed2564d4ca0", "size": "46", "binary": false, "copies": "5", "ref": "refs/heads/ng_integration", "path": "client/components/UserAutoComplete/index.js", "mode": "33188", "license": "mit", "language": [ { "name": "Batchfile", "bytes": "549" }, { "name": "CSS", "bytes": "818469" }, { "name": "Dockerfile", "bytes": "1895" }, { "name": "HTML", "bytes": "701096" }, { "name": "JavaScript", "bytes": "5470868" }, { "name": "Shell", "bytes": "25172" }, { "name": "Smarty", "bytes": "1052" }, { "name": "Standard ML", "bytes": "1843" } ], "symlink_target": "" }
using System.Collections; using System.Collections.Generic; using System; using UnityEngine; public class GridSpot { protected Vector3 coord; //Coordinates of this gridspot on the map protected GameObject gameObject; //Hides the fact that this gridspot is also a gameobject (GUI) protected Unit[] unit; //Units that are currently in this gridspot public bool Changeable{ get; protected set; } //If the tile can be changed public GridSpot ( Vector3 coord, GameObject obj, bool changeable ) { this.coord = coord; this.gameObject = obj; this.Changeable = changeable; } public Unit getUnit() { return unit[0]; } public Vector3 Coord() { return coord; } public GameObject initSpot() { return this.gameObject; } override public String ToString() { return "X: " + this.coord.x + "\tY: " + this.coord.y; } }
{ "content_hash": "259813abed3853cc24aeced3a21dcca1", "timestamp": "", "source": "github", "line_count": 35, "max_line_length": 96, "avg_line_length": 23.914285714285715, "alnum_prop": 0.7192353643966547, "repo_name": "tolae/SpellCasters", "id": "3d9249336c70614532223d17a2cc2c8df9258670", "size": "839", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "Assets/Scripts/Board Control/FloorSpots/GridSpot.cs", "mode": "33188", "license": "mit", "language": [ { "name": "C#", "bytes": "43072" } ], "symlink_target": "" }
package com.strobel.decompiler.languages.java.ast; import com.strobel.decompiler.languages.EntityType; import com.strobel.decompiler.patterns.INode; import com.strobel.decompiler.patterns.Match; public class ConstructorDeclaration extends EntityDeclaration { public final static TokenRole THROWS_KEYWORD = MethodDeclaration.THROWS_KEYWORD; public final AstNodeCollection<TypeParameterDeclaration> getTypeParameters() { return getChildrenByRole(Roles.TYPE_PARAMETER); } public final AstNodeCollection<ParameterDeclaration> getParameters() { return getChildrenByRole(Roles.PARAMETER); } public final AstNodeCollection<AstType> getThrownTypes() { return getChildrenByRole(Roles.THROWN_TYPE); } public final BlockStatement getBody() { return getChildByRole(Roles.BODY); } public final void setBody(final BlockStatement value) { setChildByRole(Roles.BODY, value); } public final JavaTokenNode getLeftParenthesisToken() { return getChildByRole(Roles.LEFT_PARENTHESIS); } public final JavaTokenNode getRightParenthesisToken() { return getChildByRole(Roles.RIGHT_PARENTHESIS); } @Override public EntityType getEntityType() { return EntityType.CONSTRUCTOR; } @Override public <T, R> R acceptVisitor(final IAstVisitor<? super T, ? extends R> visitor, final T data) { return visitor.visitConstructorDeclaration(this, data); } @Override public boolean matches(final INode other, final Match match) { if (other instanceof MethodDeclaration) { final MethodDeclaration otherDeclaration = (MethodDeclaration) other; return !otherDeclaration.isNull() && matchString(getName(), otherDeclaration.getName()) && matchAnnotationsAndModifiers(otherDeclaration, match) && getTypeParameters().matches(otherDeclaration.getTypeParameters(), match) && getParameters().matches(otherDeclaration.getParameters(), match) && getBody().matches(otherDeclaration.getBody(), match); } return false; } }
{ "content_hash": "57972d2056613a3accecfc84d5a1e0a7", "timestamp": "", "source": "github", "line_count": 65, "max_line_length": 100, "avg_line_length": 34.738461538461536, "alnum_prop": 0.6758193091231178, "repo_name": "Thog/Procyon", "id": "a7c849c9c49a7e8363d3a6ff92def2b71e030181", "size": "2897", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "Procyon.CompilerTools/src/main/java/com/strobel/decompiler/languages/java/ast/ConstructorDeclaration.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Jasmin", "bytes": "13156" }, { "name": "Java", "bytes": "5879289" } ], "symlink_target": "" }
using Sqloogle.Libs.Rhino.Etl.Core.Operations; using Sqloogle.Operations; using Sqloogle.Operations.Support; namespace Sqloogle.Processes { /// <summary> /// A ServerProcess queries cached sql, sql agent jobs, /// reporting services commands, and object definitions from /// a single SQL Server. /// </summary> public class ServerCrawlProcess : PartialProcessOperation { public ServerCrawlProcess(string connectionString, string server) { var union = new ParallelUnionAllOperation( new DefinitionProcess(connectionString), new CachedSqlProcess(connectionString), new SqlAgentJobExtract(connectionString), new ReportingServicesProcess(connectionString) ); Register(union); RegisterLast(new AppendToRowOperation("server", server)); } } }
{ "content_hash": "063a0506e5d5b59baf593804b1063964", "timestamp": "", "source": "github", "line_count": 30, "max_line_length": 75, "avg_line_length": 30.033333333333335, "alnum_prop": 0.6614872364039955, "repo_name": "dineshkummarc/SQLoogle", "id": "0ad5e0966f36ff412ff361dcdce43e6ff8efec5e", "size": "1488", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "Sqloogle/Processes/ServerCrawlProcess.cs", "mode": "33188", "license": "apache-2.0", "language": [], "symlink_target": "" }
package net.sf.mmm.util.file.base; import java.io.File; import java.io.FileFilter; import java.io.FileInputStream; import java.io.IOException; import java.util.ArrayList; import java.util.List; import java.util.Properties; import java.util.UUID; import org.junit.Test; import net.sf.mmm.test.TestResourceHelper; import net.sf.mmm.util.file.api.FileType; import net.sf.mmm.util.file.api.FileUtil; /** * This is the test-case for {@link FileUtilImpl}. * * @author Joerg Hohwiller (hohwille at users.sourceforge.net) */ @SuppressWarnings("all") public class FileUtilTest extends FileUtilLimitedTest { @Override protected FileUtil getFileUtil() { return FileUtilImpl.getInstance(); } protected void checkTestdata(File originalFile, File copyFile) throws IOException { assertThat(originalFile.length()).isEqualTo(copyFile.length()); Properties copyProperties = new Properties(); FileInputStream in = new FileInputStream(copyFile); copyProperties.load(in); in.close(); assertThat(copyProperties.get("Message1")).isEqualTo("This is only a test"); assertThat(copyProperties.get("Message2")).isEqualTo("The second test"); } /** * Tests {@link FileUtil#copyFile(File, File)}. */ @Test public void testCopyFile() throws IOException { FileUtil util = getFileUtil(); File originalFile = new File(TestResourceHelper.getTestPath("net/sf/mmm/util/file/testdata.properties")); File copyFile = File.createTempFile("testdata", ".properties"); util.copyFile(originalFile, copyFile); checkTestdata(originalFile, copyFile); copyFile.delete(); } /** Tests {@link FileUtil#copyFile(File, File)}. */ @Test public void testDirectoryTree() throws IOException { FileUtil util = getFileUtil(); File tempDir = util.getTemporaryDirectory(); String uidName = "mmm-" + UUID.randomUUID(); File subdir = new File(tempDir, uidName); assertThat(subdir.mkdir()).isTrue(); assertThat(subdir.isDirectory()).isTrue(); File originalFile = new File(TestResourceHelper.getTestPath("net/sf/mmm/util/file/testdata.properties")); File copyFile = new File(subdir, originalFile.getName()); util.copyFile(originalFile, copyFile); checkTestdata(originalFile, copyFile); File testFile = new File(subdir, "test.properties"); assertThat(testFile.createNewFile()).isTrue(); File subsubdir = new File(subdir, "folder"); assertThat(subsubdir.mkdir()).isTrue(); File fooFile = new File(subsubdir, "foo.properties"); assertThat(fooFile.createNewFile()).isTrue(); // test matching files File[] matchingFiles = util.getMatchingFiles(subdir, "*/*.properties", FileType.FILE); assertThat(1).isEqualTo(matchingFiles.length); assertThat(matchingFiles[0]).isEqualTo(fooFile); matchingFiles = util.getMatchingFiles(subdir, "**/*.properties", FileType.FILE); assertThat(matchingFiles.length).isEqualTo(3); int magic = 0; for (File file : matchingFiles) { if (file.equals(fooFile)) { magic += 1; } else if (file.equals(testFile)) { magic += 2; } else if (file.equals(copyFile)) { magic += 4; } } assertThat(7).isEqualTo(magic); matchingFiles = util.getMatchingFiles(subdir, "**/fo*", null); magic = 0; for (File file : matchingFiles) { if (file.equals(fooFile)) { magic += 1; } else if (file.equals(subsubdir)) { magic += 2; } } assertThat(3).isEqualTo(magic); // copy recursive File copyDir = new File(tempDir, uidName + "-copy"); util.copyRecursive(subdir, copyDir, false); // collect matching files of copy matchingFiles = util.getMatchingFiles(copyDir, "*/*.properties", FileType.FILE); assertThat(matchingFiles.length).isEqualTo(1); assertThat(matchingFiles[0].getName()).isEqualTo(fooFile.getName()); matchingFiles = util.getMatchingFiles(copyDir, "**/*.properties", FileType.FILE); assertThat(matchingFiles.length).isEqualTo(3); assertThat(new String[] { matchingFiles[0].getName(), matchingFiles[1].getName(), matchingFiles[2].getName() }) .containsOnly(new String[] { fooFile.getName(), testFile.getName(), copyFile.getName() }); // delete recursive FileFilter filter = new FileFilter() { @Override public boolean accept(File pathname) { return pathname.getName().endsWith(".properties"); } }; int deleteCount = util.deleteRecursive(subdir, filter); assertThat(subdir.exists()).isFalse(); assertThat(deleteCount).isEqualTo(3); deleteCount = util.deleteRecursive(copyDir); assertThat(copyDir.exists()).isFalse(); assertThat(deleteCount).isEqualTo(3); } /** Test of {@link FileUtil#touch(File)}. */ @Test public void testTouch() throws Exception { FileUtil util = getFileUtil(); File tmpFile = File.createTempFile("test-", "-touch"); assertThat(tmpFile).isFile(); assertThat(util.ensureFileExists(tmpFile)).isFalse(); long before = System.currentTimeMillis(); assertThat(util.touch(tmpFile)).isFalse(); long after = System.currentTimeMillis(); long delta = 5000; // precision of filesystem is quite low... assertThat(tmpFile.lastModified()).isBetween(before - delta, after + delta); assertThat(tmpFile.delete()).isTrue(); assertThat(tmpFile).doesNotExist(); assertThat(util.touch(tmpFile)).isTrue(); assertThat(tmpFile).isFile(); tmpFile.delete(); File tmpFile2 = new File(tmpFile, "sub1/sub2/test-file"); assertThat(tmpFile2).doesNotExist(); assertThat(tmpFile).doesNotExist(); assertThat(util.touch(tmpFile2)).isTrue(); assertThat(tmpFile2).isFile(); util.deleteRecursive(tmpFile); } /** Tests {@link FileUtil#collectMatchingFiles(File, String, FileType, java.util.List)}. */ @Test public void testCollectMatchingFiles() { // given FileUtil util = getFileUtil(); List<File> list = new ArrayList<File>(); String testPath = TestResourceHelper.getTestPath() + "../../main/java"; // when boolean hasPattern = util.collectMatchingFiles(new File(testPath), "net/sf/mmm/ut?l/**/impl/*.java", FileType.FILE, list); // then assertThat(hasPattern).isTrue(); assertThat(list).contains(create(testPath, net.sf.mmm.util.io.impl.BufferInputStream.class, net.sf.mmm.util.pool.impl.ByteArrayPoolImpl.class, net.sf.mmm.util.io.impl.DetectorStreamProviderImpl.class)); assertThat(list).doesNotContain(create(testPath, net.sf.mmm.util.file.impl.spring.UtilFileSpringConfig.class)); } private File[] create(String testPath, Class<?>... classes) { File[] files = new File[classes.length]; int i = 0; for (Class<?> c : classes) { files[i++] = new File(testPath, c.getName().replace('.', '/') + ".java"); } return files; } }
{ "content_hash": "fc7e6eeec711a1cb3061099592ff8b61", "timestamp": "", "source": "github", "line_count": 189, "max_line_length": 146, "avg_line_length": 37.23809523809524, "alnum_prop": 0.6686558681443592, "repo_name": "m-m-m/util", "id": "6d3699988f778779ed94982b9af86b035c67f55c", "size": "7167", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "io/src/test/java/net/sf/mmm/util/file/base/FileUtilTest.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Batchfile", "bytes": "116" }, { "name": "HTML", "bytes": "57" }, { "name": "Java", "bytes": "4988376" } ], "symlink_target": "" }
An easy way to add a stereoscopic ARKit SceneView to your project. The MixedRealityKit class extends ARSCNView and splits camera in two stereoscopic SceneViews. Works with Google Cardboard or any VR Viewer that supports non-barrel distorted VR. **Virtual Reality Demo (enclosed room scene)** ![Virtual Reality Example](demo1.gif) **Mixed Reality Demo (viewing virtual objects in the real world)** ![Virtual Reality Example](demo2.gif) ## Setting up a new Project to use MixedRealityKit 1. Add to your podfile: `pod 'MixedRealityKit'` 2. In Terminal, navigate to your project folder, then: `pod update` `pod install` 3. Make sure the **Camera Usage Description** key is set in your info.plist. 4. For best results, uncheck **Portrait** under Device Orientation. Due to some weirdness with the scene flipping upside down, you need both **Landscape Left** and **Landscape Right** checked. Change your ViewController class to look like the following ```swift import UIKit import SceneKit import ARKit import MixedRealityKit class ViewController: UIViewController, MixedRealityDelegate { var sceneView:MixedRealityKit? override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view, typically from a nib. sceneView=MixedRealityKit(frame: view.frame) sceneView?.mixedRealityDelegate = self let scene=SCNScene() sceneView?.scene=scene view.addSubview(sceneView!) } override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) sceneView?.runSession() } override func viewWillDisappear(_ animated: Bool) { super.viewWillDisappear(animated) sceneView?.pauseSession() } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } // MixedRealityDelegate Methods - These are passed from ARSCNViewDelegate and ARSCNSessionDelegate by way of the MixedRealityDelegate, allowing you to subscribe only to MixedRealityDelegate func renderer(_ renderer: SCNSceneRenderer, updateAtTime time: TimeInterval) { } func renderer(_ renderer: SCNSceneRenderer, didAdd node: SCNNode, for anchor: ARAnchor) { } func renderer(_ renderer: SCNSceneRenderer, willUpdate node: SCNNode, for anchor: ARAnchor) { } func renderer(_ renderer: SCNSceneRenderer, didRemove node: SCNNode, for anchor: ARAnchor) { } func session(_ session: ARSession, didUpdate frame: ARFrame) { } func session(_ session: ARSession, didFailWithError error: Error) { } func sessionWasInterrupted(_ session: ARSession) { } func sessionInterruptionEnded(_ session: ARSession) { } } ``` You can use the Room.scn file provided in this repo, or create an empty SCNScene(), adding your own nodes to it. If you are adding a floor to your scene, you will need to play with the y-axis positioning so it matches the relative eye level. I found that -1.7 worked well. ## Delegates I added a new delegate to the MixedRealityKit class called **mixedRealityDelegate** which allows you to optionally override the ARSCNViewDelegate methods in your ViewController as you normally would, passing them to the MixedRealityKit class. While you don't need to override these delegates, you will need to implement them in your ViewController. The Error Message "Fix" button will do this for you if you are lazy :) I'm hoping to fix this requirement in a future release. ## Options **disableSleepMode** - (default: _true_): When set to _true_ your device will not go turn off when idle. This can be overridden, but since your device will likely be in a Google Cardboard, you will not want it to go to sleep. The **runSession()** method takes the optional parameter **detectPlanes** (default: _false_). As of now, only horizontal plane detection is available out of the box. ## Author Scott Finkelstein [Twitter](https://twitter.com/sbf02) Available as open source under the terms of the [MIT License](http://opensource.org/licenses/MIT).
{ "content_hash": "520297c8ac5cbd04dc318001f9342c9e", "timestamp": "", "source": "github", "line_count": 124, "max_line_length": 475, "avg_line_length": 33.38709677419355, "alnum_prop": 0.7357487922705314, "repo_name": "scottfinkelstein/MixedRealityKit", "id": "183b4465690748dcdd6cf28acb86122a389fabcf", "size": "4161", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "README.md", "mode": "33188", "license": "mit", "language": [ { "name": "Ruby", "bytes": "831" }, { "name": "Swift", "bytes": "11402" } ], "symlink_target": "" }
using System; using System.Collections.Generic; using System.Data; using System.Data.SqlClient; using Csla; using Csla.Data; using SelfLoadSoftDelete.DataAccess; using SelfLoadSoftDelete.DataAccess.ERLevel; namespace SelfLoadSoftDelete.DataAccess.Sql.ERLevel { /// <summary> /// DAL SQL Server implementation of <see cref="IG08_RegionDal"/> /// </summary> public partial class G08_RegionDal : IG08_RegionDal { /// <summary> /// Inserts a new G08_Region object in the database. /// </summary> /// <param name="g08_Region">The G08 Region DTO.</param> /// <returns>The new <see cref="G08_RegionDto"/>.</returns> public G08_RegionDto Insert(G08_RegionDto g08_Region) { using (var ctx = ConnectionManager<SqlConnection>.GetManager("DeepLoad")) { using (var cmd = new SqlCommand("AddG08_Region", ctx.Connection)) { cmd.CommandType = CommandType.StoredProcedure; cmd.Parameters.AddWithValue("@Parent_Country_ID", g08_Region.Parent_Country_ID).DbType = DbType.Int32; cmd.Parameters.AddWithValue("@Region_ID", g08_Region.Region_ID).Direction = ParameterDirection.Output; cmd.Parameters.AddWithValue("@Region_Name", g08_Region.Region_Name).DbType = DbType.String; cmd.ExecuteNonQuery(); g08_Region.Region_ID = (int)cmd.Parameters["@Region_ID"].Value; } } return g08_Region; } /// <summary> /// Updates in the database all changes made to the G08_Region object. /// </summary> /// <param name="g08_Region">The G08 Region DTO.</param> /// <returns>The updated <see cref="G08_RegionDto"/>.</returns> public G08_RegionDto Update(G08_RegionDto g08_Region) { using (var ctx = ConnectionManager<SqlConnection>.GetManager("DeepLoad")) { using (var cmd = new SqlCommand("UpdateG08_Region", ctx.Connection)) { cmd.CommandType = CommandType.StoredProcedure; cmd.Parameters.AddWithValue("@Region_ID", g08_Region.Region_ID).DbType = DbType.Int32; cmd.Parameters.AddWithValue("@Region_Name", g08_Region.Region_Name).DbType = DbType.String; var rowsAffected = cmd.ExecuteNonQuery(); if (rowsAffected == 0) throw new DataNotFoundException("G08_Region"); } } return g08_Region; } /// <summary> /// Deletes the G08_Region object from database. /// </summary> /// <param name="region_ID">The Region ID.</param> public void Delete(int region_ID) { using (var ctx = ConnectionManager<SqlConnection>.GetManager("DeepLoad")) { using (var cmd = new SqlCommand("DeleteG08_Region", ctx.Connection)) { cmd.CommandType = CommandType.StoredProcedure; cmd.Parameters.AddWithValue("@Region_ID", region_ID).DbType = DbType.Int32; cmd.ExecuteNonQuery(); } } } } }
{ "content_hash": "4d5fe591550917a546c6484d08827858", "timestamp": "", "source": "github", "line_count": 78, "max_line_length": 122, "avg_line_length": 43.46153846153846, "alnum_prop": 0.5566371681415929, "repo_name": "CslaGenFork/CslaGenFork", "id": "e31d22de53a7828a74b8f224c2f775482a128488", "size": "3390", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "trunk/Samples/DeepLoad/DAL-DTO/SelfLoadSoftDelete.DataAccess.Sql/ERLevel/G08_RegionDal.Designer.cs", "mode": "33188", "license": "mit", "language": [ { "name": "ASP", "bytes": "4816094" }, { "name": "Assembly", "bytes": "73066" }, { "name": "C#", "bytes": "12314305" }, { "name": "C++", "bytes": "313681" }, { "name": "HTML", "bytes": "30950" }, { "name": "PHP", "bytes": "35716" }, { "name": "PLpgSQL", "bytes": "2164471" }, { "name": "Pascal", "bytes": "1244" }, { "name": "PowerShell", "bytes": "1687" }, { "name": "SourcePawn", "bytes": "500196" }, { "name": "Visual Basic", "bytes": "3027224" } ], "symlink_target": "" }
package stuartw_at_umich_dot_edu.MindstormRobot; import lejos.nxt.Button; import lejos.nxt.LightSensor; import lejos.nxt.SensorPort; import lejos.robotics.localization.OdometryPoseProvider; import lejos.robotics.navigation.DifferentialPilot; import lejos.robotics.subsumption.Behavior; public class LineBehavior implements Behavior { private boolean suppressed = false; private LightSensor ls; private DifferentialPilot pilot; private OdometryPoseProvider poseProvider; private boolean sensed; LineBehavior(DifferentialPilot pilot, OdometryPoseProvider poseProvider) { ls = new LightSensor(SensorPort.S1); this.pilot = pilot; this.poseProvider = poseProvider; } @Override public boolean takeControl() { // Experience tells me 50 is a decent number to detect the tape line int reading = ls.readValue(); if (reading > 50) { sensed = true; } return sensed; } @Override public void action() { suppressed = false; System.out.println("Found Line!"); // First rotate to face initial direction float heading = poseProvider.getPose().getHeading(); pilot.rotate(90-heading, true); while (pilot.isMoving() && !suppressed) { Thread.yield(); } // Now travel 12" after finish line pilot.travel(12.0, true); while (pilot.isMoving() && !suppressed) { Thread.yield(); } // Now stop pilot.stop(); Button.waitForAnyPress(); //System.exit(0); } @Override public void suppress() { suppressed = true; } public void calibrate() { System.out.println("Calibrate over floor"); Button.waitForAnyPress(); calibrateFloor(); System.out.println("Calibrate over line"); Button.waitForAnyPress(); calibrateLine(); } public void calibrateFloor() { ls.calibrateLow(); } public void calibrateLine() { ls.calibrateHigh(); } }
{ "content_hash": "cc333df78d7bc1fcc742965aa76e5a70", "timestamp": "", "source": "github", "line_count": 84, "max_line_length": 73, "avg_line_length": 21.595238095238095, "alnum_prop": 0.717199558985667, "repo_name": "swheaton/MindstormRobot", "id": "ee040c5b81bb5202bb8db7c0c89bdf64f7a095d2", "size": "1814", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/stuartw_at_umich_dot_edu/MindstormRobot/LineBehavior.java", "mode": "33188", "license": "mit", "language": [ { "name": "Java", "bytes": "10908" } ], "symlink_target": "" }
package main import ( "fmt" "log" "os" "strconv" "./src/hlt" ) // golang starter kit with logging and basic pathfinding // Arjun Viswanathan 2017 / github arjunvis func main() { logging := true botName := "GoBot" conn := hlt.NewConnection(botName) // set up logging if logging { fname := strconv.Itoa(conn.PlayerTag) + "_gamelog.log" f, err := os.OpenFile(fname, os.O_RDWR|os.O_CREATE|os.O_APPEND, 0666) if err != nil { fmt.Printf("error opening file: %v\n", err) } defer f.Close() log.SetOutput(f) } gameMap := conn.UpdateMap() gameturn := 1 for true { gameMap = conn.UpdateMap() commandQueue := []string{} myPlayer := gameMap.Players[gameMap.MyID] myShips := myPlayer.Ships for i := 0; i < len(myShips); i++ { ship := myShips[i] if ship.DockingStatus == hlt.UNDOCKED { commandQueue = append(commandQueue, hlt.StrategyBasicBot(ship, gameMap)) } } log.Printf("Turn %v\n", gameturn) conn.SubmitCommands(commandQueue) gameturn++ } }
{ "content_hash": "365ff9a20b12e417d3a2a250d036489c", "timestamp": "", "source": "github", "line_count": 50, "max_line_length": 76, "avg_line_length": 20, "alnum_prop": 0.653, "repo_name": "lanyudhy/Halite-II", "id": "10709aeac4f2c62d302e754b32dec869b3452104", "size": "1000", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "airesources/Go/MyBot.go", "mode": "33188", "license": "mit", "language": [ { "name": "Batchfile", "bytes": "8116" }, { "name": "C", "bytes": "1908128" }, { "name": "C#", "bytes": "30809" }, { "name": "C++", "bytes": "796200" }, { "name": "CMake", "bytes": "2548" }, { "name": "CSS", "bytes": "402475" }, { "name": "Go", "bytes": "14446" }, { "name": "HTML", "bytes": "61424" }, { "name": "Java", "bytes": "27904" }, { "name": "JavaScript", "bytes": "8321266" }, { "name": "Makefile", "bytes": "32949" }, { "name": "Mako", "bytes": "532" }, { "name": "Python", "bytes": "367681" }, { "name": "Ruby", "bytes": "156268" }, { "name": "Rust", "bytes": "17292" }, { "name": "Scala", "bytes": "21512" }, { "name": "Shell", "bytes": "24822" }, { "name": "Vue", "bytes": "284601" } ], "symlink_target": "" }
uint64 FxTime2TSec(uint fxTime); uint TSec2FxTime(uint64 tSec);
{ "content_hash": "58b1cd4015a2f7dfd225f9b2d3b7e3d2", "timestamp": "", "source": "github", "line_count": 2, "max_line_length": 32, "avg_line_length": 32, "alnum_prop": 0.8125, "repo_name": "stackprobe/Factory", "id": "68ebc59e16a875345f7deee8ad20cab61e5f1a8a", "size": "64", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "Labo/Fx/libs/FxTime.h", "mode": "33188", "license": "mit", "language": [ { "name": "Batchfile", "bytes": "24175" }, { "name": "C", "bytes": "2523559" }, { "name": "C++", "bytes": "66761" }, { "name": "JavaScript", "bytes": "514" }, { "name": "Objective-C", "bytes": "5072" } ], "symlink_target": "" }
package com.tle.webtests.pageobject.generic.component; import com.tle.webtests.framework.PageContext; import com.tle.webtests.pageobject.AbstractPage; import com.tle.webtests.pageobject.PageObject; import com.tle.webtests.pageobject.WaitingPageObject; import org.openqa.selenium.By; import org.openqa.selenium.WebElement; import org.openqa.selenium.support.ui.ExpectedCondition; import org.openqa.selenium.support.ui.ExpectedConditions; public class SelectCourseDialog extends AbstractPage<SelectCourseDialog> { private final String baseId; private ExpectedCondition<WebElement> fieldAvailable = ExpectedConditions.visibilityOfElementLocated(By.className("select2-search__field")); public SelectCourseDialog(PageContext context, String baseId) { super(context); this.baseId = baseId; } public String getBaseid() { return baseId; } public WebElement getBaseElement() { return driver.findElement(By.id("select2-" + baseId + "-container")); } @Override public WebElement findLoadedElement() { return getBaseElement(); } public <T extends PageObject> T searchSelectAndFinish( String course, WaitingPageObject<T> returnTo) { WebElement baseElement = getBaseElement(); baseElement.click(); WebElement searchField = getWaiter().until(fieldAvailable); searchField.sendKeys(course); WebElement entries = waiter.until( ExpectedConditions.visibilityOfElementLocated( By.xpath("//div[contains(text(), " + quoteXPath(course) + ")]"))); entries.click(); return returnTo.get(); } }
{ "content_hash": "e74f06e9a4af6d9cba4ba2b2400f817d", "timestamp": "", "source": "github", "line_count": 48, "max_line_length": 91, "avg_line_length": 33.25, "alnum_prop": 0.743734335839599, "repo_name": "equella/Equella", "id": "9f8f6698141ca29ec9f599908c54a99048a1efab", "size": "1596", "binary": false, "copies": "1", "ref": "refs/heads/develop", "path": "autotest/Tests/src/main/java/com/tle/webtests/pageobject/generic/component/SelectCourseDialog.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Awk", "bytes": "402" }, { "name": "Batchfile", "bytes": "38432" }, { "name": "CSS", "bytes": "648823" }, { "name": "Dockerfile", "bytes": "2055" }, { "name": "FreeMarker", "bytes": "370046" }, { "name": "HTML", "bytes": "865667" }, { "name": "Java", "bytes": "27081020" }, { "name": "JavaScript", "bytes": "1673995" }, { "name": "PHP", "bytes": "821" }, { "name": "PLpgSQL", "bytes": "1363" }, { "name": "PureScript", "bytes": "307610" }, { "name": "Python", "bytes": "79871" }, { "name": "Scala", "bytes": "765981" }, { "name": "Shell", "bytes": "64170" }, { "name": "TypeScript", "bytes": "146564" }, { "name": "XSLT", "bytes": "510113" } ], "symlink_target": "" }
package com.flectosystems.morphiasparkapi.dao; import com.flectosystems.morphiasparkapi.config.MongoDB; import com.flectosystems.morphiasparkapi.models.Venue; import com.mongodb.BasicDBObject; import org.bson.types.ObjectId; import javax.inject.Named; import java.util.List; /** * Class designed to access to the DB for the {@link Venue} entity. * <p> * Created by Ernesto Mancebo T on 1/6/15. */ @Named public class VenueDAO extends ExtendedBasicDAO<Venue, ObjectId> { public VenueDAO() { super(MongoDB.getInstance().getDatastore()); } public List<Venue> getVenueNear(double[] location) { return getDatastore() .find(getEntityClass()) .field("loc").near(location[0], location[1]) .asList(); } public void deleteAllVenues() { getDatastore().getCollection(Venue.class).remove(new BasicDBObject()); } }
{ "content_hash": "d0f2716a55bb93cd16c9bcc0cd492ad8", "timestamp": "", "source": "github", "line_count": 33, "max_line_length": 78, "avg_line_length": 27.484848484848484, "alnum_prop": 0.681367144432194, "repo_name": "ernestomancebo/MorphiaSparkAPI", "id": "69af0d9a0301b13f11c93a1ecee00a2cbaddfef7", "size": "907", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/main/java/com/flectosystems/morphiasparkapi/dao/VenueDAO.java", "mode": "33188", "license": "mit", "language": [ { "name": "Java", "bytes": "29738" } ], "symlink_target": "" }
/** * @module Ajax客户端[AjaxClient] * @description Ajax客户端 * * @author: * @date: 2013-08-29 下午1:48 */ define([ "core/js/Class", "core/js/rpc/AjaxRequest", "core/js/rpc/JsonResponse", "jquery.fileDownload"], function (Class, AjaxRequest, JsonResponse) { var AjaxClient = Class.extend({ /** * 服务地址 */ serverUrl: null, ctor: function (serverUrl) { this.serverUrl = serverUrl; }, buildClientRequest: function (methodName, methodVersion, ignoreNull) { return new AjaxRequest(this, methodName, methodVersion, ignoreNull); }, buildJsonResponse: function (transport, callback, responseData) { return new JsonResponse(transport, callback, responseData); }, getServerUrl: function () { return this.serverUrl; }, setServerUrl: function (serverUrl) { this.serverUrl = serverUrl; }, /** * 导出文件 * * @param methodName * @param methodVersion * @param attachParams */ exportFile: function (methodName, methodVersion, attachParams) { if (typeof methodName == "object") { attachParams = methodName; methodName = attachParams["methodName"]; methodVersion = attachParams["methodVersion"]; $.fileDownload(methodName, { prepareCallback:attachParams["prepareCallback"], successCallback:attachParams["successCallback"], failCallback:attachParams["failCallback"] //preparingMessageHtml: "We are preparing your report, please wait...", //failMessageHtml: "There was a problem generating your report, please try again." }); }else{ $.fileDownload(methodName); } }, get: function (methodName, methodVersion, data, callback, ajaxResponse, async, dataType, cache, contentType, timeout, interceptSystemException, ignoreNull) { return this.method("get", methodName, methodVersion, data, callback, ajaxResponse, async, dataType, cache, contentType, timeout, interceptSystemException, ignoreNull); }, post: function (methodName, methodVersion, data, callback, ajaxResponse, async, dataType, cache, contentType, timeout, interceptSystemException, ignoreNull) { return this.method("post", methodName, methodVersion, data, callback, ajaxResponse, async, dataType, cache, contentType, timeout, interceptSystemException, ignoreNull); }, method: function (ajaxMethod, methodName, methodVersion, data, callback, ajaxResponse, async, dataType, cache, contentType, timeout, interceptSystemException, ignoreNull) { if (typeof methodName == "object") { var opts = methodName; methodName = opts["methodName"]; methodVersion = opts["methodVersion"]; ignoreNull = opts["ignoreNull"]; data = opts["data"]; dataType = opts["dataType"]; //add by cw 2013.12.25 callback = opts; } var options = this._getOptions(callback, ajaxResponse, async, dataType, cache, contentType, timeout, interceptSystemException); return this.buildClientRequest(methodName, methodVersion, ignoreNull) .addParams(data) .method(ajaxMethod, options); }, _getOptions: function (callback, ajaxResponse, async, dataType, cache, contentType, timeout, interceptSystemException) { if (typeof callback == "object") { var opts = callback; callback = opts["complete"]; ajaxResponse = opts["ajaxResponse"]; async = opts["async"]; dataType = opts["dataType"]; cache = opts["cache"]; contentType = opts["contentType"]; timeout = opts["timeout"]; interceptSystemException = opts["interceptSystemException"]; } var result = { complete: callback, ajaxResponse: ajaxResponse, async: async, dataType: dataType, cache: cache, contentType: contentType, timeout: timeout, interceptSystemException: interceptSystemException } return result; }, }); return AjaxClient; });
{ "content_hash": "a8fa20639361cbc67abea332d5b1e454", "timestamp": "", "source": "github", "line_count": 113, "max_line_length": 180, "avg_line_length": 40.88495575221239, "alnum_prop": 0.5744588744588744, "repo_name": "huangfeng19820712/hfast", "id": "cd101ca81d99067f4b96b659d7e7ea04f93f326d", "size": "4652", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "core/js/rpc/AjaxClient.js", "mode": "33188", "license": "mit", "language": [ { "name": "Batchfile", "bytes": "837" }, { "name": "CSS", "bytes": "6104134" }, { "name": "HTML", "bytes": "459347" }, { "name": "JavaScript", "bytes": "19919100" }, { "name": "PHP", "bytes": "20370" }, { "name": "Python", "bytes": "16281" }, { "name": "Ruby", "bytes": "1123" }, { "name": "Shell", "bytes": "1061" } ], "symlink_target": "" }
<!doctype html> <html lang="en-us"> <head> <meta charset="utf-8"> <meta http-equiv="Content-Type" content="text/html; charset=utf-8"> <title>Emscripten-Generated Code</title> <style> .emscripten { padding-right: 0; margin-left: auto; margin-right: auto; display: block; } textarea.emscripten { font-family: monospace; width: 80%; } div.emscripten { text-align: center; } div.emscripten_border { border: 1px solid black; } /* the canvas *must not* have any border or padding, or mouse coords will be wrong */ canvas.emscripten { border: 0px none; } .spinner { height: 50px; width: 50px; margin: 0px auto; -webkit-animation: rotation .8s linear infinite; -moz-animation: rotation .8s linear infinite; -o-animation: rotation .8s linear infinite; animation: rotation 0.8s linear infinite; border-left: 5px solid rgb(235, 235, 235); border-right: 5px solid rgb(235, 235, 235); border-bottom: 5px solid rgb(235, 235, 235); border-top: 5px solid rgb(120, 120, 120); border-radius: 100%; background-color: rgb(189, 215, 46); } @-webkit-keyframes rotation { from {-webkit-transform: rotate(0deg);} to {-webkit-transform: rotate(360deg);} } @-moz-keyframes rotation { from {-moz-transform: rotate(0deg);} to {-moz-transform: rotate(360deg);} } @-o-keyframes rotation { from {-o-transform: rotate(0deg);} to {-o-transform: rotate(360deg);} } @keyframes rotation { from {transform: rotate(0deg);} to {transform: rotate(360deg);} } #status { display: inline-block; vertical-align: top; margin-top: 30px; margin-left: 20px; font-weight: bold; color: rgb(120, 120, 120); } #progress { height: 20px; width: 30px; } #controls { display: inline-block; float: right; vertical-align: top; margin-top: 30px; margin-right: 20px; } #output { width: 100%; height: 200px; margin: 0 auto; margin-top: 10px; border-left: 0px; border-right: 0px; padding-left: 0px; padding-right: 0px; display: block; background-color: black; color: white; font-family: 'Lucida Console', Monaco, monospace; outline: none; } </style> </head> <body> <div class="emscripten"> <input type="button" title="View the main canvas in fullscreen mode" value="Fullscreen" onclick="Module.requestFullScreen(false,false)"> <input type="file" title="Add local files to the browsable file system" multiple id="fileSelection_id" onchange="fileSelectionCallback();"/> </div> <figure style="overflow:visible;" id="spinner"><div class="spinner"></div><center style="margin-top:0.5em"><strong>emscripten</strong></center></figure> <div class="emscripten" id="status">Downloading...</div> <div class="emscripten"> <progress value="0" max="100" id="progress" hidden=1></progress> </div> <div class="emscripten_border"> <canvas class="emscripten" id="canvas" oncontextmenu="event.preventDefault()"></canvas> </div> <textarea class="emscripten" id="output" rows="8"></textarea> <script type='text/javascript'> var statusElement = document.getElementById('status'); var progressElement = document.getElementById('progress'); var spinnerElement = document.getElementById('spinner'); var Module = { preRun: [], postRun: [], print: (function() { var element = document.getElementById('output'); if (element) element.value = ''; // clear browser cache return function(text) { if (arguments.length > 1) text = Array.prototype.slice.call(arguments).join(' '); // These replacements are necessary if you render to raw HTML //text = text.replace(/&/g, "&amp;"); //text = text.replace(/</g, "&lt;"); //text = text.replace(/>/g, "&gt;"); //text = text.replace('\n', '<br>', 'g'); console.log(text); if (element) { element.value += text + "\n"; element.scrollTop = element.scrollHeight; // focus on bottom } }; })(), printErr: function(text) { if (arguments.length > 1) text = Array.prototype.slice.call(arguments).join(' '); if (0) { // XXX disabled for safety typeof dump == 'function') { dump(text + '\n'); // fast, straight to the real console } else { console.error(text); } }, canvas: (function() { var canvas = document.getElementById('canvas'); // As a default initial behavior, pop up an alert when webgl context is lost. To make your // application robust, you may want to override this behavior before shipping! // See http://www.khronos.org/registry/webgl/specs/latest/1.0/#5.15.2 canvas.addEventListener("webglcontextlost", function(e) { alert('WebGL context lost. You will need to reload the page.'); e.preventDefault(); }, false); return canvas; })(), setStatus: function(text) { if (!Module.setStatus.last) Module.setStatus.last = { time: Date.now(), text: '' }; if (text === Module.setStatus.text) return; var m = text.match(/([^(]+)\((\d+(\.\d+)?)\/(\d+)\)/); var now = Date.now(); if (m && now - Date.now() < 30) return; // if this is a progress update, skip it if too soon if (m) { text = m[1]; progressElement.value = parseInt(m[2])*100; progressElement.max = parseInt(m[4])*100; progressElement.hidden = false; spinnerElement.hidden = false; } else { progressElement.value = null; progressElement.max = null; progressElement.hidden = true; if (!text) spinnerElement.hidden = true; } statusElement.innerHTML = text; }, totalDependencies: 0, monitorRunDependencies: function(left) { this.totalDependencies = Math.max(this.totalDependencies, left); Module.setStatus(left ? 'Preparing... (' + (this.totalDependencies-left) + '/' + this.totalDependencies + ')' : 'All downloads complete.'); } }; Module.setStatus('Downloading...'); window.onerror = function() { Module.setStatus('Exception thrown, see JavaScript console'); spinnerElement.style.display = 'none'; Module.setStatus = function(text) { if (text) Module.printErr('[post-exception status] ' + text); }; }; </script> <script> function fileExistsInMemoryFS(path) { var statbuf = FS.stat(path); if (!statbuf) return false; return FS.isFile(statbuf.mode); } function saveFileToMemoryFS(e) { try { if (fileExistsInMemoryFS('/'+e.target.current_file_name)) FS.unlink('/'+e.target.current_file_name); } catch(err) { //document.getElementById("saveFileToMemoryFS").innerHTML = err.message; } var data=e.target.result; FS.createDataFile( '/', // thr root folder can be changed here e.target.current_file_name, data, true, true, true ); //Module.ccall('file_system_changed_callback'); // This function should be exposed by the C++ code } function fileSelectionCallback() { var files = document.getElementById("fileSelection_id").files, nFiles = files.length; for (var nFileId = 0; nFileId < nFiles; nFileId++) { var file=files[nFileId]; var reader = new FileReader(); reader.current_file_name = file.name; reader.onload = saveFileToMemoryFS; reader.readAsBinaryString(file); } } </script> <script src="FileSaver.js"> </script> <script> function saveFileFromMemoryFSToDisk(memoryFSname,localFSname) // This can be called by C++ code { var data=FS.readFile(memoryFSname); var blob; var isSafari = /^((?!chrome|android).)*safari/i.test(navigator.userAgent); if(isSafari) { blob = new Blob([data.buffer], {type: "application/octet-stream"}); } else { blob = new Blob([data.buffer], {type: "application/octet-binary"}); } saveAs(blob, localFSname); } </script> <script> var ASSERTIONS = 0; // Prefix of data URIs emitted by SINGLE_FILE and related options. var dataURIPrefix = 'data:application/octet-stream;base64,'; // Indicates whether filename is a base64 data URI. function isDataURI(filename) { return String.prototype.startsWith ? filename.startsWith(dataURIPrefix) : filename.indexOf(dataURIPrefix) === 0; } // Copied from https://github.com/strophe/strophejs/blob/e06d027/src/polyfills.js#L149 // This code was written by Tyler Akins and has been placed in the // public domain. It would be nice if you left this header intact. // Base64 code from Tyler Akins -- http://rumkin.com /** * Decodes a base64 string. * @param {String} input The string to decode. */ var decodeBase64 = typeof atob === 'function' ? atob : function (input) { var keyStr = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/='; var output = ''; var chr1, chr2, chr3; var enc1, enc2, enc3, enc4; var i = 0; // remove all characters that are not A-Z, a-z, 0-9, +, /, or = input = input.replace(/[^A-Za-z0-9\+\/\=]/g, ''); do { enc1 = keyStr.indexOf(input.charAt(i++)); enc2 = keyStr.indexOf(input.charAt(i++)); enc3 = keyStr.indexOf(input.charAt(i++)); enc4 = keyStr.indexOf(input.charAt(i++)); chr1 = (enc1 << 2) | (enc2 >> 4); chr2 = ((enc2 & 15) << 4) | (enc3 >> 2); chr3 = ((enc3 & 3) << 6) | enc4; output = output + String.fromCharCode(chr1); if (enc3 !== 64) { output = output + String.fromCharCode(chr2); } if (enc4 !== 64) { output = output + String.fromCharCode(chr3); } } while (i < input.length); return output; }; // Converts a string of base64 into a byte array. // Throws error on invalid input. function intArrayFromBase64(s) { if (typeof ENVIRONMENT_IS_NODE === 'boolean' && ENVIRONMENT_IS_NODE) { var buf; try { buf = Buffer.from(s, 'base64'); } catch (_) { buf = new Buffer(s, 'base64'); } return new Uint8Array(buf.buffer, buf.byteOffset, buf.byteLength); } try { var decoded = decodeBase64(s); var bytes = new Uint8Array(decoded.length); for (var i = 0 ; i < decoded.length ; ++i) { bytes[i] = decoded.charCodeAt(i); } return bytes; } catch (_) { throw new Error('Converting base64 string to bytes failed.'); } } // If filename is a base64 data URI, parses and returns data (Buffer on node, // Uint8Array otherwise). If filename is not a base64 data URI, returns undefined. function tryParseAsDataURI(filename) { if (!isDataURI(filename)) { return; } return intArrayFromBase64(filename.slice(dataURIPrefix.length)); } /** @type {function(string, boolean=, number=)} */ function intArrayFromString(stringy, dontAddNull, length) { var len = length > 0 ? length : lengthBytesUTF8(stringy)+1; var u8array = new Array(len); var numBytesWritten = stringToUTF8Array(stringy, u8array, 0, u8array.length); if (dontAddNull) u8array.length = numBytesWritten; return u8array; } function intArrayToString(array) { var ret = []; for (var i = 0; i < array.length; i++) { var chr = array[i]; if (chr > 0xFF) { if (ASSERTIONS) { assert(false, 'Character code ' + chr + ' (' + String.fromCharCode(chr) + ') at offset ' + i + ' not in 0x00-0xFF.'); } chr &= 0xFF; } ret.push(String.fromCharCode(chr)); } return ret.join(''); } var memoryInitializer = 'main.html.mem'; if (typeof Module['locateFile'] === 'function') { memoryInitializer = Module['locateFile'](memoryInitializer); } else if (Module['memoryInitializerPrefixURL']) { memoryInitializer = Module['memoryInitializerPrefixURL'] + memoryInitializer; } Module['memoryInitializerRequestURL'] = memoryInitializer; var meminitXHR = Module['memoryInitializerRequest'] = new XMLHttpRequest(); meminitXHR.open('GET', memoryInitializer, true); meminitXHR.responseType = 'arraybuffer'; meminitXHR.send(null); var script = document.createElement('script'); script.src = "main.js"; document.body.appendChild(script); </script> </body> </html>
{ "content_hash": "7498155e27f0205bd0d54b0ff38f4211", "timestamp": "", "source": "github", "line_count": 365, "max_line_length": 162, "avg_line_length": 35.58082191780822, "alnum_prop": 0.5952105952105952, "repo_name": "wflohry/imgui-addons", "id": "b34ab3929b37e94631cb9bf6748a713213a732df", "size": "12987", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "examples/addons_examples/html/main.html", "mode": "33188", "license": "mit", "language": [ { "name": "C", "bytes": "1263783" }, { "name": "C++", "bytes": "5830239" } ], "symlink_target": "" }
using Fortune_Teller_UI.Services; using Microsoft.AspNetCore.Mvc; using System.Threading.Tasks; namespace Fortune_Teller_UI.Controllers { [Route("/")] public class HomeController : Controller { IFortuneService _fortunes; public HomeController(IFortuneService fortunes) { _fortunes = fortunes; } [HttpGet] public IActionResult Index() { return View(); } [HttpGet("random")] public async Task<string> Random() { return await _fortunes.RandomFortuneAsync(); } } }
{ "content_hash": "7f62d25ffc1615c23d78aca1496b3188", "timestamp": "", "source": "github", "line_count": 29, "max_line_length": 56, "avg_line_length": 21.17241379310345, "alnum_prop": 0.5781758957654723, "repo_name": "SteelToeOSS/Samples", "id": "a90ca857a8071d2d4d1e1c3f51e64474290b6897", "size": "616", "binary": false, "copies": "1", "ref": "refs/heads/2.x", "path": "Discovery/src/AspDotNetCore/Fortune-Teller-UI/Controllers/HomeController.cs", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "ASP", "bytes": "210" }, { "name": "Batchfile", "bytes": "2137" }, { "name": "C#", "bytes": "546165" }, { "name": "CSS", "bytes": "8760" }, { "name": "HTML", "bytes": "107853" }, { "name": "JavaScript", "bytes": "72677" }, { "name": "Shell", "bytes": "2091" } ], "symlink_target": "" }
<?php namespace phpOlap\Tests\Xmla\Metadata; use phpOlap\Xmla\Metadata\Catalog; class CatalogTest extends \PHPUnit_Framework_TestCase { public function testHydrate() { $resultSoap = '<root> <row> <CATALOG_NAME>FoodMart</CATALOG_NAME> <DESCRIPTION>No description available</DESCRIPTION> <ROLES>California manager,No HR Cube</ROLES> </row> </root>'; $document = new \DOMDocument(); $document->loadXML($resultSoap); $node = $document->getElementsByTagName('row')->item(0); $connection = $this->getMock('phpOlap\Xmla\Connection\Connection', array(), array(), '', FALSE); $connection->expects($this->any()) ->method('findSchemas') ->will($this->onConsecutiveCalls('schema1', 'schema2')); $catalog = new Catalog(); $catalog->hydrate($node, $connection); $this->assertEquals($catalog->getConnection(), $connection); $this->assertEquals($catalog->getName(), 'FoodMart'); $this->assertEquals($catalog->getDescription(), 'No description available'); $this->assertEquals($catalog->getRoles(), array('California manager', 'No HR Cube')); $this->assertEquals($catalog->getSchemas(), 'schema1'); $this->assertEquals($catalog->getSchemas(), 'schema1'); } }
{ "content_hash": "c07f6603ba03444ad25e80c6d80cf717", "timestamp": "", "source": "github", "line_count": 43, "max_line_length": 98, "avg_line_length": 28.88372093023256, "alnum_prop": 0.6714975845410628, "repo_name": "instaclick/phpOlap", "id": "f06200eee177b72f3c4a6569365a0d686563441d", "size": "1452", "binary": false, "copies": "4", "ref": "refs/heads/master", "path": "tests/phpOlap/Tests/Xmla/Metadata/CatalogTest.php", "mode": "33188", "license": "mit", "language": [ { "name": "PHP", "bytes": "186544" } ], "symlink_target": "" }
{% extends "layout.html" %} {% from "macros/project.html" import render_project %} {% from "macros/pagination.html" import render_pagination %} {% block title %}{{ bag('translation', this.alt, 'projects') }}{% endblock %} {% block content %} {% for child in this.pagination.items %} {{ render_project(child, from_index=true) }} <hr> {% endfor %} {{ render_pagination(this.pagination, this.alt) }} {% endblock %}
{ "content_hash": "6d9df6766e64fb00001809b912f337a0", "timestamp": "", "source": "github", "line_count": 15, "max_line_length": 77, "avg_line_length": 28.666666666666668, "alnum_prop": 0.6395348837209303, "repo_name": "humrochagf/humrochagf.github.io", "id": "9ee57cc96d864baf4ba30c44634072772588557b", "size": "430", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "templates/projects.html", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "6884" }, { "name": "HTML", "bytes": "18314" }, { "name": "JavaScript", "bytes": "2409" } ], "symlink_target": "" }
import os import re import time import select import subprocess import sys import json from requests.exceptions import ConnectionError sys.path.insert(0, '/srv/newsblur') os.environ['DJANGO_SETTINGS_MODULE'] = 'newsblur_web.settings' NEWSBLUR_USERNAME = 'nb' IGNORE_HOSTS = [ 'app-push', ] # Use this to count the number of times each user shows up in the logs. Good for finding abusive accounts. # tail -n20000 logs/newsblur.log | sed 's/\x1b\[[0-9;]*m//g' | sed -En 's/.*?[0-9]s\] \[([a-zA-Z0-9]+\*?)\].*/\1/p' | sort | uniq -c | sort def main(roles=None, command=None, path=None): delay = 1 hosts = subprocess.check_output(['ansible-inventory', '--list']) if not hosts: print(" ***> Could not load ansible-inventory!") return hosts = json.loads(hosts) if not roles: roles = ['app'] if not isinstance(roles, list): roles = [roles] while True: try: streams = create_streams_for_roles(hosts, roles, command=command, path=path) print(" --- Loading %s %s Log Tails ---" % (len(streams), roles)) read_streams(streams) # except UnicodeDecodeError: # unexpected end of data # print " --- Lost connections - Retrying... ---" # time.sleep(1) # continue except ConnectionError: print(" --- Retrying in %s seconds... ---" % delay) time.sleep(delay) delay += 1 continue except KeyboardInterrupt: print(" --- End of Logging ---") break def create_streams_for_roles(hosts, roles, command=None, path=None): streams = list() found = set() print(path) if not path: path = "/srv/newsblur/logs/newsblur.log" if not command: command = "tail -f" for role in roles: if role in hosts: for hostname in hosts[role]['hosts']: if any(h in hostname for h in IGNORE_HOSTS) and role != 'push': continue follow_host(hosts, streams, found, hostname, command, path) else: host = role follow_host(hosts, streams, found, host, command) return streams def follow_host(hosts, streams, found, hostname, command=None, path=None): if isinstance(hostname, dict): address = hostname['address'] hostname = hostname['name'] elif ':' in hostname: hostname, address = hostname.split(':', 1) elif isinstance(hostname, tuple): hostname, address = hostname[0], hostname[1] else: address = hosts['_meta']['hostvars'][hostname]['ansible_host'] print(" ---> Following %s \t[%s]" % (hostname, address)) if hostname in found: return s = subprocess.Popen(["ssh", "-l", NEWSBLUR_USERNAME, "-i", os.path.expanduser("/srv/secrets-newsblur/keys/docker.key"), address, "%s %s" % (command, path)], stdout=subprocess.PIPE) s.name = hostname streams.append(s) found.add(hostname) def read_streams(streams): while True: r, _, _ = select.select( [stream.stdout.fileno() for stream in streams], [], []) for fileno in r: for stream in streams: if stream.stdout.fileno() != fileno: continue data = os.read(fileno, 4096) if not data: streams.remove(stream) break try: combination_message = "[%-13s] %s" % (stream.name[:13], data.decode()) except UnicodeDecodeError: continue sys.stdout.write(combination_message) sys.stdout.flush() break if __name__ == "__main__": main(*sys.argv[1:])
{ "content_hash": "567aaae658ff88e5bf8514d46e8f5934", "timestamp": "", "source": "github", "line_count": 112, "max_line_length": 139, "avg_line_length": 34.0625, "alnum_prop": 0.5559633027522936, "repo_name": "samuelclay/NewsBlur", "id": "4118e64a7b1dbdf1a28b5ae93f66adfcd0ab3b41", "size": "3838", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "utils/tlnb.py", "mode": "33261", "license": "mit", "language": [ { "name": "C", "bytes": "454" }, { "name": "CSS", "bytes": "776813" }, { "name": "CoffeeScript", "bytes": "13093" }, { "name": "Dockerfile", "bytes": "3704" }, { "name": "HCL", "bytes": "29303" }, { "name": "HTML", "bytes": "1921563" }, { "name": "Java", "bytes": "853216" }, { "name": "JavaScript", "bytes": "1803770" }, { "name": "Jinja", "bytes": "89121" }, { "name": "Kotlin", "bytes": "298281" }, { "name": "Makefile", "bytes": "8909" }, { "name": "Objective-C", "bytes": "2565934" }, { "name": "Perl", "bytes": "55606" }, { "name": "Python", "bytes": "2067295" }, { "name": "R", "bytes": "527" }, { "name": "Ruby", "bytes": "2094" }, { "name": "SCSS", "bytes": "47069" }, { "name": "Shell", "bytes": "51526" }, { "name": "Swift", "bytes": "136021" } ], "symlink_target": "" }
// Indirect Eval, Not Strict Mode, VariableEnvironment=GlobalEnv, LexicalEnvironment=not GlobalEnv const { assertTrue, assertFalse, assertSame, assertUndefined, assertNotUndefined, } = Assert; const global = this; let obj; with (obj = {}) { (1,eval)("function v1(){}"); assertSame("function", typeof v1); assertTrue("v1" in global); assertNotUndefined(global["v1"]); assertFalse("v1" in obj); assertUndefined(obj["v1"]); } with (obj = {}) { (1,eval)("function* v2(){}"); assertSame("function", typeof v2); assertTrue("v2" in global); assertNotUndefined(global["v2"]); assertFalse("v2" in obj); assertUndefined(obj["v2"]); } with (obj = {}) { (1,eval)("class v3{}"); assertSame("function", typeof v3); assertFalse("v3" in global); assertUndefined(global["v3"]); assertFalse("v3" in obj); assertUndefined(obj["v3"]); } with (obj = {}) { (1,eval)("var v4"); assertSame("undefined", typeof v4); assertTrue("v4" in global); assertUndefined(global["v4"]); assertFalse("v4" in obj); assertUndefined(obj["v4"]); } with (obj = {}) { (1,eval)("var v5 = 0"); assertSame("number", typeof v5); assertTrue("v5" in global); assertNotUndefined(global["v5"]); assertFalse("v5" in obj); assertUndefined(obj["v5"]); } with (obj = {}) { (1,eval)("let v6"); assertSame("undefined", typeof v6); assertFalse("v6" in global); assertUndefined(global["v6"]); assertFalse("v6" in obj); assertUndefined(obj["v6"]); } with (obj = {}) { (1,eval)("let v7 = 0"); assertSame("number", typeof v7); assertFalse("v7" in global); assertUndefined(global["v7"]); assertFalse("v7" in obj); assertUndefined(obj["v7"]); } with (obj = {}) { (1,eval)("const v8 = 0"); assertSame("number", typeof v8); assertFalse("v8" in global); assertUndefined(global["v8"]); assertFalse("v8" in obj); assertUndefined(obj["v8"]); }
{ "content_hash": "463978b06e94d8f6f075ed02533b25b2", "timestamp": "", "source": "github", "line_count": 79, "max_line_length": 98, "avg_line_length": 22.632911392405063, "alnum_prop": 0.6694630872483222, "repo_name": "rwaldron/es6draft", "id": "5b0fe0521949e8cfb96361389fc7363a30a9e297", "size": "1961", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/test/scripts/suite/objects/GlobalObject/eval/indirect_nonstrict_global_local2.js", "mode": "33261", "license": "mit", "language": [], "symlink_target": "" }
<div id="footer"> <?php require TEMPLATEPATH . '/includes/instagram-cosenary.php'; use MetzWeb\Instagram\Instagram; ?> <?php if(is_page('the-bean-fights-back')) { } else { ?> <div id="footerWrap"> <div class="container"> <div id="coffeewarning"></div> <?php $instagram = new Instagram('0a072efb2f9d45b5b2b47b6ce0db7eb6'); $result = $instagram->getUserMedia(29447247, 8); ?> <div class="beangrams"> <div id="instabean" class="instabean"> <?php $ii = 1; foreach ($result->data as $data) { $getimg = $data->images->low_resolution->url; $getlink = $data->link; echo '<div class="instabox instabox' . $ii . '"><a target="_blank" href="' . $getlink . '"><img src="' . get_bloginfo('template_url') . '/images/transimg.png"/><div style="background-image: url(' . $getimg . ');"></div></a></div>'; $ii++; } ?> </div> </div> </div> </div><!-- / #footerWrap --> <?php } ?> <div id="credits"> <div class="container"> <div class="findbean"> <p class="one"> <span class="loco"><span class="dot"></span> <span class="highlight">54 2nd Ave (corner of East 3rd) East Village NYC</span> <span class="dot mob"></span></span> <span class="loco"><span class="dot"></span> <span class="highlight">824 Broadway (corner of East 12th) Union Square NYC</span> <span class="dot"></span></span> <span class="loco"><span class="dot"></span> <span class="highlight">147 1st Ave (corner of East 9th) East Village, NYC</span> <span class="dot mob"></span></span> <span class="loco"><span class="dot"></span> <span class="highlight">101 Bedford Ave (corner of North 11th) Williamsburg, Brooklyn NY</span> <span class="dot"></span></span> </p> <p class="two">Tell us about an experience you had at one of our shops: <a href="mailto:letusknow@thebeannyc.com">letusknow@thebeannyc.com</a></p> </div> <div class="copyrights"> <p class="one">Copyright &copy; <?php echo date('Y'); ?> <a href="<?php bloginfo('url'); ?>">The Bean</a>. All rights reserved.</p> <p class="two">Baked And Frosted By<a class="misfit-inc" href="http://misfit-inc.com" target="_blank"></a></p> </div> </div> </div> </div><!-- / #footer --> <?php wp_footer(); ?> <?php if ( get_option('woo_google_analytics') <> "" ) { echo stripslashes(get_option('woo_google_analytics')); } ?> </body> </html>
{ "content_hash": "07d50a1a39a9874739f3c8f5049d3485", "timestamp": "", "source": "github", "line_count": 68, "max_line_length": 239, "avg_line_length": 36.94117647058823, "alnum_prop": 0.5812101910828026, "repo_name": "misfit-inc/thebeannyc.com", "id": "170d1b368ece20af4d74b0ca7af98aea56fffb94", "size": "2512", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "wp-content/themes/irresistible/footer.php", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "2183533" }, { "name": "HTML", "bytes": "285538" }, { "name": "JavaScript", "bytes": "3048541" }, { "name": "PHP", "bytes": "11847785" } ], "symlink_target": "" }
'use strict'; const ReduktComponent = require('./ReduktComponent'); const Imagemin = require('../loaders/Imagemin'); const Merge = require('../tools/Merge'); /** * @class */ class Assets extends ReduktComponent { /** * @inheritDoc */ init(config) { this.folderImages = config.folder.images; this.folderFonts = config.folder.fonts; } /** * Generates the filename of the asset. * * @private * @param {String} path * @param {String} folder * @return {string} */ getName(path, folder) { let name = '[name]'; if (/node_modules/.test(path)) { name = path .replace(/\\/g, '/') .replace(/((.*(node_modules))|fonts|font|images|image|img|assets)\//g, '') .replace('@', '') .replace(/\.[^/.]+$/, ''); } return `${folder}/${name}${this.hash()}[ext]`; } /** * Generates the rule for the given test. * * @private * @param {RegExp} test * @param {String} folder * @param {{}} extra * @return {{}} */ getRule(test, folder, extra = {}) { return Merge.webpack({ test: test, type: 'asset/resource', generator: { filename: module => this.getName(module.filename, folder), }, }, extra); } /** * Returns the rules for the assets. * * @private * @return {{}[]} */ rules() { const imagemin = new Imagemin(this); return [ this.getRule(/(\.(eot|[ot]tf|woff2?)$|font.*\.svg$)/, this.folderFonts, { use: imagemin.svgoLoader(), }), this.getRule(/^((?!font).)*\.svg$/, this.folderImages, { use: imagemin.svgoLoader(), }), this.getRule(/\.(gif|jpe?g|png|webp)$/, this.folderImages, { use: imagemin.rasterLoader(), }), ]; } /** * @inheritDoc */ config() { return { module: { rules: this.rules(), }, }; } } module.exports = Assets;
{ "content_hash": "b3f348f2d8c950d3abe00292d920146f", "timestamp": "", "source": "github", "line_count": 94, "max_line_length": 78, "avg_line_length": 18.882978723404257, "alnum_prop": 0.5673239436619718, "repo_name": "inerciacreativa/redukt", "id": "2eea13431545c7ac464236f7da823c32e1fa5c41", "size": "1775", "binary": false, "copies": "1", "ref": "refs/heads/main", "path": "src/components/Assets.js", "mode": "33188", "license": "mit", "language": [ { "name": "JavaScript", "bytes": "53419" } ], "symlink_target": "" }
#ifndef _H_CASPER_SET_GOAL #define _H_CASPER_SET_GOAL #include <casper/cp/goal/labeling.h> namespace Casper { namespace CP { namespace Detail { template<class ElemEval> struct MinDomEvaluator<Set<ElemEval> > { typedef int Eval; template<class Dom> Eval operator()(const Dom& d) const { return d.possSize(); } }; template<class ElemEval> struct MaxDomEvaluator<Set<ElemEval> > { typedef int Eval; template<class Dom> Eval operator()(const Dom& d) const { return -d.possSize(); } }; template<class ElemEval> struct MinMinElemEvaluator<Set<ElemEval> > { typedef ElemEval Eval; template<class Dom> Eval operator()(const Dom& d) const { assert(!d.poss().empty()); return *d.poss().begin(); } }; template<class ElemEval> struct MaxMaxElemEvaluator<Set<ElemEval> > { typedef ElemEval Eval; template<class Dom> Eval operator()(const Dom& d) const { assert(!d.poss().empty()); return -*--d.poss().end(); } }; template<class ElemEval> struct MinDomOverDegreeEvaluator<Set<ElemEval> > { typedef double Eval; template<class Dom> Eval operator()(const Dom& d) const { return d.possSize()/static_cast<double>(d.getNbSuspFilters()); } }; template<class ElemEval> struct MaxDomOverDegreeEvaluator<Set<ElemEval> > { typedef double Eval; template<class Dom> Eval operator()(const Dom& d) const { return -d.possSize()/static_cast<double>(d.getNbSuspFilters()); } }; template<class ElemEval> struct MinDomOverWeightedDegreeEvaluator<Set<ElemEval> > { typedef double Eval; template<class Dom> Eval operator()(const Dom& d) const { return d.possSize()/static_cast<double>(d.getAFC()); } }; template<class ElemEval> struct MaxDomOverWeightedDegreeEvaluator<Set<ElemEval> > { typedef double Eval; template<class Dom> Eval operator()(const Dom& d) const { return -d.possSize()/static_cast<double>(d.getAFC()); } }; } template<class T,class View> struct InsertElem : IGoal { typedef typename DomView<Set<T>,View>::Dom Dom; typedef typename Dom::PIterator PIterator; InsertElem(Store& s, const View& v,PIterator it) : IGoal(),store(s),v(s,v),it(it) {} Goal execute(IExplorer& s) { assert(v->findInPoss(*it) != v->endPoss()); if (v->insert(it) and store.valid()) return succeed(); return fail(); } Store& store; DomView<Set<T>,View> v; PIterator it; }; template<class T,class View> Goal insertElem(Store& s,const View& v,typename DomView<Set<T>,View>::Dom::PIterator it) { return new (s) InsertElem<T,View>(s,v,it); } template<class T,class View> struct EraseElem : IGoal { typedef typename DomView<Set<T>,View>::Dom Dom; typedef typename Dom::PIterator PIterator; EraseElem(Store& s,const View& v,PIterator it) : IGoal(),store(s),v(s,v),it(it) {} Goal execute(IExplorer& s) { assert(v->findInPoss(*it) != v->endPoss()); if (v->erase(it) and store.valid()) return succeed(); return fail(); } Store& store; DomView<Set<T>,View> v; PIterator it; }; template<class T,class View> Goal eraseElem(Store& s,const View& v,typename DomView<Set<T>,View>::Dom::PIterator it) { return new (s) EraseElem<T,View>(s,v,it); } namespace Detail { /** * Goal for selecting a set variable. Attempts to assign a value * to the variable trying all possible values in ascending order on backtracking. */ template<class Eval,class Obj> struct SelectValsMin<Seq<Set<Eval> >,Obj> : IValSelector { SelectValsMin(Store& store, const Obj& obj) : store(store),doms(store,obj) {} Goal select(uint idx) { if (doms[idx]->ground()) return succeed(); return Goal(store, (insertElem<Eval>(store,doms[idx].getObj(),doms[idx]->beginPoss()) or eraseElem<Eval>(store,doms[idx].getObj(),doms[idx]->beginPoss())) and callValSelector(store,this,idx)); } Store& store; DomArrayView<Set<Eval>,Obj> doms; }; /** * Goal for selecting a set variable. Attempts to assign a value * to the variable trying all possible values in random order on backtracking. */ template<class Eval,class Obj> struct SelectValsRand<Seq<Set<Eval> >,Obj> : IValSelector { SelectValsRand(Store& store,const Obj& obj) : store(store),doms(store,obj) {} Goal select(uint idx) { if (doms[idx]->ground()) return succeed(); uint r = static_cast<uint>(rand()/(double)RAND_MAX * doms[idx]->possSize()); auto it = doms[idx]->beginPoss(); while (r-- > 0) ++it; return Goal(store, (insertElem<Eval>(store,doms[idx].getObj(),it) or eraseElem<Eval>(store,doms[idx].getObj(),it)) and callValSelector(store,this,idx)); } Store& store; DomArrayView<Set<Eval>,Obj> doms; }; /** * Goal for bisecting a set variable. Attempts to assign a value * to the variable trying all possible values in ascending order on backtracking. */ template<class Eval, class Obj> struct SelectValMin<Seq<Set<Eval> >,Obj > : IValSelector { SelectValMin(Store& store, const Obj& obj) : store(store),doms(store,obj) {} Goal select(uint idx) { if (doms[idx]->ground()) return succeed(); return Goal(store, insertElem<Eval>(store,doms[idx].getObj(),doms[idx]->beginPoss()) or eraseElem<Eval>(store,doms[idx].getObj(),doms[idx]->beginPoss())); } Store& store; DomArrayView<Set<Eval>,Obj> doms; }; /** * Goal for bisecting a set variable. Attempts to assign a value * to the variable trying all possible values in descending order on backtracking. */ template<class Eval, class Obj> struct SelectValMax<Seq<Set<Eval> >,Obj > : IValSelector { SelectValMax(Store& store, const Obj& obj) : store(store),doms(store,obj) {} Goal select(uint idx) { if (doms[idx]->ground()) return succeed(); return Goal(store, insertElem<Eval>(store,doms[idx].getObj(),--doms[idx]->endPoss()) or eraseElem<Eval>(store,doms[idx].getObj(),--doms[idx]->endPoss())); } Store& store; DomArrayView<Set<Eval>,Obj> doms; }; }; } // CP } // Casper #endif /*_H_CASPER_INT_GOAL*/
{ "content_hash": "a37ced9ee7cc95a771e8c23362394ec0", "timestamp": "", "source": "github", "line_count": 248, "max_line_length": 88, "avg_line_length": 23.717741935483872, "alnum_prop": 0.6892213532811968, "repo_name": "marcovc/casper", "id": "cdbca9ecce15238607dd3dafbe2a702adbbbaeca", "size": "6538", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "casper/cp/set/goal.h", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "C", "bytes": "581144" }, { "name": "C++", "bytes": "1771099" }, { "name": "Objective-C", "bytes": "81787" }, { "name": "Python", "bytes": "96279" }, { "name": "Shell", "bytes": "83" } ], "symlink_target": "" }
shared_examples_for "currency inputs" do |attributes| attributes.each do |attribute| it "#{attribute} accepts strings" do subject.public_send("#{attribute}=", "1000") expect(subject.public_send("#{attribute}")).to eq(1000) end it "#{attribute} accepts strings with commas" do subject.public_send("#{attribute}=", "1,000,000.01") expect(subject.public_send("#{attribute}")).to eq(1000000.01) end it "#{attribute} accepts integers" do subject.public_send("#{attribute}=", 1000) expect(subject.public_send("#{attribute}")).to eq(1000) end it "#{attribute} accepts floats" do subject.public_send("#{attribute}=", 1000.01) expect(subject.public_send("#{attribute}")).to eq(1000.01) end end end
{ "content_hash": "f49b06f100b25a9cb69a2d6ca06e0926", "timestamp": "", "source": "github", "line_count": 24, "max_line_length": 67, "avg_line_length": 32.375, "alnum_prop": 0.640926640926641, "repo_name": "moneyadviceservice/mortgage_calculator", "id": "537ed9d4efc3c2f43e355e4424f603e3bf05b304", "size": "777", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "spec/support/shared_currency_inputs.rb", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "546" }, { "name": "Dockerfile", "bytes": "300" }, { "name": "Gherkin", "bytes": "41395" }, { "name": "HTML", "bytes": "114420" }, { "name": "JavaScript", "bytes": "25139" }, { "name": "Ruby", "bytes": "167890" }, { "name": "SCSS", "bytes": "66521" }, { "name": "Shell", "bytes": "1633" } ], "symlink_target": "" }
using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; // General Information about an assembly is controlled through the following // set of attributes. Change these attribute values to modify the information // associated with an assembly. [assembly: AssemblyTitle("AdminApp")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("AdminApp")] [assembly: AssemblyCopyright("Copyright © 2015")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. [assembly: ComVisible(false)] // The following GUID is for the ID of the typelib if this project is exposed to COM [assembly: Guid("c597227f-0863-4392-9ddd-5eb3abe56006")] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Build and Revision Numbers // by using the '*' as shown below: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("1.0.0.0")] [assembly: AssemblyFileVersion("1.0.0.0")]
{ "content_hash": "7acb1c07aaeaa642e8200a84b4f4a4cf", "timestamp": "", "source": "github", "line_count": 36, "max_line_length": 84, "avg_line_length": 38.583333333333336, "alnum_prop": 0.7437005039596832, "repo_name": "Narvalex/LexUx", "id": "da69d6a2b0d687f6203dde0d60f454a51b099d81", "size": "1392", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "LexUx/AdminApp/Properties/AssemblyInfo.cs", "mode": "33188", "license": "mit", "language": [ { "name": "ASP", "bytes": "95" }, { "name": "C#", "bytes": "12281" }, { "name": "CSS", "bytes": "242576" }, { "name": "HTML", "bytes": "25723" }, { "name": "JavaScript", "bytes": "287029" } ], "symlink_target": "" }
rabbit ====== Rabbit stream cipher implementation in Java Iurii Sergiichuk, BIKSm-14-1, Kharkiv National University of Radioelectronics, Ukraine, Kharkiv. useful links: http://cr.yp.to/streamciphers/rabbit/desc.pdf https://tools.ietf.org/html/rfc4503 http://en.wikipedia.org/wiki/Rabbit_%28cipher%29
{ "content_hash": "b60a6a9cfd81556a1a5292ea89f33d45", "timestamp": "", "source": "github", "line_count": 11, "max_line_length": 96, "avg_line_length": 27.545454545454547, "alnum_prop": 0.7821782178217822, "repo_name": "xSAVIKx/RABBIT-cipher", "id": "a34c53b018aa6d4890dce6cbd5bb1c278902427b", "size": "303", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "README.md", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Java", "bytes": "20885" } ], "symlink_target": "" }
// Copyright (c) 2009-2010 Satoshi Nakamoto // Copyright (c) 2009-2014 The Bitcoin developers // Distributed under the MIT software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #ifndef GREENCOIN_CHAINPARAMS_H #define GREENCOIN_CHAINPARAMS_H #include "chainparamsbase.h" #include "checkpoints.h" #include "primitives/block.h" #include "protocol.h" #include "uint256.h" #include <vector> typedef unsigned char MessageStartChars[MESSAGE_START_SIZE]; struct CDNSSeedData { std::string name, host; CDNSSeedData(const std::string &strName, const std::string &strHost) : name(strName), host(strHost) {} }; /** * CChainParams defines various tweakable parameters of a given instance of the * Greencoin system. There are three: the main network on which people trade goods * and services, the public test network which gets reset from time to time and * a regression test mode which is intended for private networks only. It has * minimal difficulty to ensure that blocks can be found instantly. */ class CChainParams { public: enum Base58Type { PUBKEY_ADDRESS, SCRIPT_ADDRESS, SECRET_KEY, EXT_PUBLIC_KEY, EXT_SECRET_KEY, MAX_BASE58_TYPES }; const uint256& HashGenesisBlock() const { return hashGenesisBlock; } const MessageStartChars& MessageStart() const { return pchMessageStart; } const std::vector<unsigned char>& AlertKey() const { return vAlertPubKey; } int GetDefaultPort() const { return nDefaultPort; } const uint256& ProofOfWorkLimit() const { return bnProofOfWorkLimit; } int SubsidyHalvingInterval() const { return nSubsidyHalvingInterval; } /** Used to check majorities for block version upgrade */ int EnforceBlockUpgradeMajority() const { return nEnforceBlockUpgradeMajority; } int RejectBlockOutdatedMajority() const { return nRejectBlockOutdatedMajority; } int ToCheckBlockUpgradeMajority() const { return nToCheckBlockUpgradeMajority; } /** Used if GenerateGreencoins is called with a negative number of threads */ int DefaultMinerThreads() const { return nMinerThreads; } const CBlock& GenesisBlock() const { return genesis; } bool RequireRPCPassword() const { return fRequireRPCPassword; } /** Make miner wait to have peers to avoid wasting work */ bool MiningRequiresPeers() const { return fMiningRequiresPeers; } /** Default value for -checkmempool argument */ bool DefaultCheckMemPool() const { return fDefaultCheckMemPool; } /** Allow mining of a min-difficulty block */ bool AllowMinDifficultyBlocks() const { return fAllowMinDifficultyBlocks; } /** Skip proof-of-work check: allow mining of any difficulty block */ bool SkipProofOfWorkCheck() const { return fSkipProofOfWorkCheck; } /** Make standard checks */ bool RequireStandard() const { return fRequireStandard; } int64_t TargetTimespan() const { return nTargetTimespan; } int64_t TargetSpacing() const { return nTargetSpacing; } int64_t Interval() const { return nTargetTimespan / nTargetSpacing; } /** Make miner stop after a block is found. In RPC, don't return until nGenProcLimit blocks are generated */ bool MineBlocksOnDemand() const { return fMineBlocksOnDemand; } /** In the future use NetworkIDString() for RPC fields */ bool TestnetToBeDeprecatedFieldRPC() const { return fTestnetToBeDeprecatedFieldRPC; } /** Return the BIP70 network string (main, test or regtest) */ std::string NetworkIDString() const { return strNetworkID; } const std::vector<CDNSSeedData>& DNSSeeds() const { return vSeeds; } const std::vector<unsigned char>& Base58Prefix(Base58Type type) const { return base58Prefixes[type]; } const std::vector<CAddress>& FixedSeeds() const { return vFixedSeeds; } virtual const Checkpoints::CCheckpointData& Checkpoints() const = 0; protected: CChainParams() {} uint256 hashGenesisBlock; MessageStartChars pchMessageStart; //! Raw pub key bytes for the broadcast alert signing key. std::vector<unsigned char> vAlertPubKey; int nDefaultPort; uint256 bnProofOfWorkLimit; int nSubsidyHalvingInterval; int nEnforceBlockUpgradeMajority; int nRejectBlockOutdatedMajority; int nToCheckBlockUpgradeMajority; int64_t nTargetTimespan; int64_t nTargetSpacing; int nMinerThreads; std::vector<CDNSSeedData> vSeeds; std::vector<unsigned char> base58Prefixes[MAX_BASE58_TYPES]; CBaseChainParams::Network networkID; std::string strNetworkID; CBlock genesis; std::vector<CAddress> vFixedSeeds; bool fRequireRPCPassword; bool fMiningRequiresPeers; bool fDefaultCheckMemPool; bool fAllowMinDifficultyBlocks; bool fRequireStandard; bool fMineBlocksOnDemand; bool fSkipProofOfWorkCheck; bool fTestnetToBeDeprecatedFieldRPC; }; /** * Modifiable parameters interface is used by test cases to adapt the parameters in order * to test specific features more easily. Test cases should always restore the previous * values after finalization. */ class CModifiableParams { public: //! Published setters to allow changing values in unit test cases virtual void setSubsidyHalvingInterval(int anSubsidyHalvingInterval) =0; virtual void setEnforceBlockUpgradeMajority(int anEnforceBlockUpgradeMajority)=0; virtual void setRejectBlockOutdatedMajority(int anRejectBlockOutdatedMajority)=0; virtual void setToCheckBlockUpgradeMajority(int anToCheckBlockUpgradeMajority)=0; virtual void setDefaultCheckMemPool(bool aDefaultCheckMemPool)=0; virtual void setAllowMinDifficultyBlocks(bool aAllowMinDifficultyBlocks)=0; virtual void setSkipProofOfWorkCheck(bool aSkipProofOfWorkCheck)=0; }; /** * Return the currently selected parameters. This won't change after app startup * outside of the unit tests. */ const CChainParams &Params(); /** Return parameters for the given network. */ CChainParams &Params(CBaseChainParams::Network network); /** Get modifiable network parameters (UNITTEST only) */ CModifiableParams *ModifiableParams(); /** Sets the params returned by Params() to those for the given network. */ void SelectParams(CBaseChainParams::Network network); /** * Looks for -regtest or -testnet and then calls SelectParams as appropriate. * Returns false if an invalid combination is given. */ bool SelectParamsFromCommandLine(); #endif // GREENCOIN_CHAINPARAMS_H
{ "content_hash": "331d9a72058e28c77a91c7b8d6508dc5", "timestamp": "", "source": "github", "line_count": 154, "max_line_length": 112, "avg_line_length": 42.04545454545455, "alnum_prop": 0.751042471042471, "repo_name": "CavityGap/greencoin", "id": "3d5926b0e4c49ee1cdfd6b862fc37e76f3ac593e", "size": "6475", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/chainparams.h", "mode": "33188", "license": "mit", "language": [ { "name": "Assembly", "bytes": "7639" }, { "name": "C", "bytes": "318383" }, { "name": "C++", "bytes": "3548413" }, { "name": "CSS", "bytes": "1127" }, { "name": "HTML", "bytes": "50621" }, { "name": "Java", "bytes": "2102" }, { "name": "M4", "bytes": "138611" }, { "name": "Makefile", "bytes": "81748" }, { "name": "Objective-C", "bytes": "4381" }, { "name": "Objective-C++", "bytes": "7186" }, { "name": "Protocol Buffer", "bytes": "2316" }, { "name": "Python", "bytes": "207943" }, { "name": "QMake", "bytes": "2021" }, { "name": "Roff", "bytes": "18163" }, { "name": "Shell", "bytes": "45054" } ], "symlink_target": "" }
from .base import FunctionalTest class AuthenticationTest(FunctionalTest): def test_anon_user_redirected_to_authentication(self): # Try to go to the System Maintenance homepage self.browser.get(self.system_maintenance_url()) # Not logged in, so get redirected to the SysAdmin Authentication page self.assertIn('System Maintenance', self.browser.title) header_text = self.browser.find_element_by_tag_name('h1').text self.assertIn('SysAdmin Authentication', header_text) # See input boxes for username & password self.find_authentication_elements() self.assertEqual( self.username_inputbox.get_attribute('placeholder'), 'Enter username') self.assertEqual( self.password_inputbox.get_attribute('placeholder'), 'Enter password') self.assertEqual(self.login_button.text, 'Login') def test_username_and_password_required(self): # Go to the authentication page self.browser.get(self.system_maintenance_url('authentication')) # Accidentally click 'Login' button without entering credentials self.find_authentication_elements() self.login_button.click() # See two error messages about required fields form_errors = self.browser.find_elements_by_class_name('has-error') self.assertEqual(len(form_errors), 2) for error in form_errors: self.assertIn('This field is required.', error.text) def test_incorrect_credentials_raise_error(self): # Go to the authentication page self.browser.get(self.system_maintenance_url('authentication')) # Enter incorrect credentials self.login_as('nobody') # See error message about entering correct username and password self.assertIn( 'Please enter a correct username and password. Note that both ' + 'fields may be case-sensitive.', self.browser.find_element_by_class_name('alert-danger').text) def test_nonsysadmin_is_denied_access_and_can_logout(self): # Go to the authentication page self.browser.get(self.system_maintenance_url('authentication')) # Enter non-sysadmin credentials self.login_as('nonsysadmin') # See 'Access denied.' message about not being a sys admin self.assertIn( 'Access denied.', self.browser.find_element_by_tag_name('h1').text) self.assertIn( 'Hello nonsysadmin. You are not a system administrator.', self.browser.find_element_by_tag_name('p').text) # Click 'Logout' button and get redirected to authentication page. self.logout_button = self.browser.find_element_by_tag_name('a') self.logout_button.click() def test_can_login_as_sysadmin_and_can_logout(self): # Go to the authentication page self.browser.get(self.system_maintenance_url('authentication')) # Enter sysadmin credentials self.login_as('sysadmin') # Check that redirected to System Maintenance home page self.assertIn('System Maintenance', self.browser.title) self.assertEqual( self.browser.find_element_by_tag_name('p').text, 'System maintenance records and other important system ' 'administration information is accessible via the buttons below.') self.assertEqual( len(self.browser.find_elements_by_css_selector( '.btn.full-width-on-mobile')), 7) self.assertEqual( len(self.browser.find_elements_by_css_selector( '.btn-group.hide-on-mobile > .btn')), 7) # Logout and get redirected to SysAdmin Authentication page self.browser.get(self.system_maintenance_url('logout')) header_text = self.browser.find_element_by_tag_name('h1').text self.assertIn('SysAdmin Authentication', header_text) def test_can_login_as_super_sysadmin(self): # Go to the authentication page self.browser.get(self.system_maintenance_url('authentication')) # Enter superuser sysadmin credentials self.login_as('supersysadmin') # Check that redirected to System Maintenance home page w/ admin access self.assertIn('System Maintenance', self.browser.title) paragraphs = self.browser.find_elements_by_tag_name('p') self.assertIn('System maintenance records and ', paragraphs[0].text) self.assertIn('To add or change system ', paragraphs[1].text) self.assertEqual( len(self.browser.find_elements_by_css_selector( '.btn.full-width-on-mobile')), 7) self.assertEqual( len(self.browser.find_elements_by_css_selector( '.btn-group.hide-on-mobile > .btn')), 14)
{ "content_hash": "9d9adc3c1d17db9e435e35b5cb2ed2a3", "timestamp": "", "source": "github", "line_count": 117, "max_line_length": 79, "avg_line_length": 41.452991452991455, "alnum_prop": 0.654020618556701, "repo_name": "mfcovington/django-system-maintenance", "id": "c77cc61cdd4046f57e3a983cc6f34a260f1a302e", "size": "4850", "binary": false, "copies": "1", "ref": "refs/heads/develop", "path": "system_maintenance/tests/functional/test_authentication.py", "mode": "33188", "license": "bsd-3-clause", "language": [ { "name": "CSS", "bytes": "2047" }, { "name": "HTML", "bytes": "23058" }, { "name": "JavaScript", "bytes": "83" }, { "name": "Python", "bytes": "53998" } ], "symlink_target": "" }
<?php // include class.secure.php to protect this file and the whole CMS! if (defined('WB_PATH')) { if (defined('LEPTON_VERSION')) include(WB_PATH.'/framework/class.secure.php'); } else { $oneback = "../"; $root = $oneback; $level = 1; while (($level < 10) && (!file_exists($root.'/framework/class.secure.php'))) { $root .= $oneback; $level += 1; } if (file_exists($root.'/framework/class.secure.php')) { include($root.'/framework/class.secure.php'); } else { trigger_error(sprintf("[ <b>%s</b> ] Can't include class.secure.php!", $_SERVER['SCRIPT_NAME']), E_USER_ERROR); } } // end include class.secure.php // Checking Requirements $PRECHECK['PHP_VERSION'] = array('VERSION' => '5.2.0', 'OPERATOR' => '>='); $PRECHECK['WB_ADDONS'] = array( 'dwoo' => array('VERSION' => '0.17', 'OPERATOR' => '>='), 'kit_tools' => array('VERSION' => '0.18', 'OPRATOR' => '>='), 'droplets_extension' => array('VERSION' => '0.25', 'OPERATOR' => '>=') ); // check utf-8 global $database; $sql = "SELECT `value` FROM `".TABLE_PREFIX."settings` WHERE `name`='default_charset'"; $result = $database->query($sql); // check allow_url_open and cURL $url_status = (ini_get('allow_url_fopen') == 1) ? 'enabled' : 'disabled'; $curl_status = function_exists('curl_init') ? 'loaded' : 'missing'; $json_status = function_exists('json_decode') ? 'loaded' : 'missing'; if ($result) { $data = $result->fetchRow(MYSQL_ASSOC); $PRECHECK['CUSTOM_CHECKS'] = array( 'Default Charset' => array( 'REQUIRED' => 'utf-8', 'ACTUAL' => $data['value'], 'STATUS' => ($data['value'] === 'utf-8')), 'allow_url_open' => array( 'REQUIRED' => 'enabled', 'ACTUAL' => $url_status, 'STATUS' => ($url_status == 'enabled')), 'cURL extension' => array( 'REQUIRED' => 'loaded', 'ACTUAL' => $curl_status, 'STATUS' => ($curl_status == 'loaded') ), 'JSON extension' => array( 'REQUIRED' => 'loaded', 'ACTUAL' => $json_status, 'STATUS' => ($json_status == 'loaded') ) ); } ?>
{ "content_hash": "0f77d5247b9d7ede34dca9168f1d478a", "timestamp": "", "source": "github", "line_count": 71, "max_line_length": 115, "avg_line_length": 28.971830985915492, "alnum_prop": 0.5712202236266407, "repo_name": "phpManufaktur/manufakturGallery", "id": "5480800c8106a4ad86333f214577f2be5f91750d", "size": "2272", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "precheck.php", "mode": "33188", "license": "mit", "language": [ { "name": "PHP", "bytes": "110758" } ], "symlink_target": "" }
external help file: Microsoft.WindowsAzure.Commands.Storage.dll-Help.xml ms.assetid: CF3B6E3B-3FC1-4871-AFE0-366B17A9E4F8 online version: schema: 2.0.0 --- # New-AzureStorageTableStoredAccessPolicy ## SYNOPSIS Creates a stored access policy for an Azure storage table. ## SYNTAX ``` New-AzureStorageTableStoredAccessPolicy [-Table] <String> [-Policy] <String> [-Permission <String>] [-StartTime <DateTime>] [-ExpiryTime <DateTime>] [-Context <AzureStorageContext>] [<CommonParameters>] ``` ## DESCRIPTION The **New-AzureStorageTableStoredAccessPolicy** cmdlet creates a stored access policy for an Azure storage table. ## EXAMPLES ### Example 1: Create a stored access policy in a table ``` PS C:\>New-AzureStorageTableStoredAccessPolicy -Table "MyTable" -Policy "Policy02" ``` This command creates an access policy named Policy02 in the storage table named MyTable. ## PARAMETERS ### -Context Specifies an Azure storage context. To obtain a storage context, use the New-AzureStorageContext cmdlet. ```yaml Type: AzureStorageContext Parameter Sets: (All) Aliases: Required: False Position: Named Default value: None Accept pipeline input: True (ByPropertyName, ByValue) Accept wildcard characters: False ``` ### -ExpiryTime Specifies the time at which the stored access policy becomes invalid. ```yaml Type: DateTime Parameter Sets: (All) Aliases: Required: False Position: Named Default value: None Accept pipeline input: False Accept wildcard characters: False ``` ### -Permission Specifies permissions in the stored access policy to access the storage table. ```yaml Type: String Parameter Sets: (All) Aliases: Required: False Position: Named Default value: None Accept pipeline input: False Accept wildcard characters: False ``` ### -Policy Specifies a name for the stored access policy. ```yaml Type: String Parameter Sets: (All) Aliases: Required: True Position: 1 Default value: None Accept pipeline input: False Accept wildcard characters: False ``` ### -StartTime Specifies the time at which the stored access policy becomes valid. ```yaml Type: DateTime Parameter Sets: (All) Aliases: Required: False Position: Named Default value: None Accept pipeline input: False Accept wildcard characters: False ``` ### -Table Specifies the Azure storage table name. ```yaml Type: String Parameter Sets: (All) Aliases: N, Name Required: True Position: 0 Default value: None Accept pipeline input: True (ByPropertyName, ByValue) Accept wildcard characters: False ``` ### CommonParameters This cmdlet supports the common parameters: -Debug, -ErrorAction, -ErrorVariable, -InformationAction, -InformationVariable, -OutVariable, -OutBuffer, -PipelineVariable, -Verbose, -WarningAction, and -WarningVariable. For more information, see about_CommonParameters (http://go.microsoft.com/fwlink/?LinkID=113216). ## INPUTS ## OUTPUTS ## NOTES ## RELATED LINKS [Get-AzureStorageTableStoredAccessPolicy](./Get-AzureStorageTableStoredAccessPolicy.md) [New-AzureStorageContext](./New-AzureStorageContext.md) [Remove-AzureStorageTableStoredAccessPolicy](./Remove-AzureStorageTableStoredAccessPolicy.md) [Set-AzureStorageTableStoredAccessPolicy](./Set-AzureStorageTableStoredAccessPolicy.md)
{ "content_hash": "59bd6be946784166868fc2d8c61b1d6d", "timestamp": "", "source": "github", "line_count": 143, "max_line_length": 314, "avg_line_length": 22.503496503496503, "alnum_prop": 0.7768800497203232, "repo_name": "krkhan/azure-powershell", "id": "bd9c29cd9ec5749147a68ef9c29d82d96d295403", "size": "3222", "binary": false, "copies": "1", "ref": "refs/heads/dev", "path": "src/Storage/Commands.Storage/help/New-AzureStorageTableStoredAccessPolicy.md", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Batchfile", "bytes": "16509" }, { "name": "C#", "bytes": "38709434" }, { "name": "HTML", "bytes": "209" }, { "name": "JavaScript", "bytes": "4979" }, { "name": "PHP", "bytes": "41" }, { "name": "PowerShell", "bytes": "3828428" }, { "name": "Ruby", "bytes": "265" }, { "name": "Shell", "bytes": "50" }, { "name": "XSLT", "bytes": "6114" } ], "symlink_target": "" }
<?php /** * Created by IntelliJ IDEA. * User: gerk * Date: 11.04.17 * Time: 15:48 */ declare(strict_types=1); namespace PeekAndPoke\Aviator\Mvc\Exception; /** * @author Karsten J. Gerber <kontakt@karsten-gerber.de> */ class HttpMethodNotAllowed extends HttpException { /** * HttpForbidden constructor. * * @param \Throwable|null $previous */ public function __construct(\Throwable $previous = null) { parent::__construct('Method Not Allowed', 405, $previous); } }
{ "content_hash": "55f0fb61d39572cb8993a6e9e6653144", "timestamp": "", "source": "github", "line_count": 27, "max_line_length": 66, "avg_line_length": 19.185185185185187, "alnum_prop": 0.638996138996139, "repo_name": "PeekAndPoke/aviator", "id": "437446d3a63b6a2a0da9284e394d31f62ca5154d", "size": "518", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/PeekAndPoke/Aviator/Mvc/Exception/HttpMethodNotAllowed.php", "mode": "33188", "license": "bsd-3-clause", "language": [ { "name": "HTML", "bytes": "14327" }, { "name": "JavaScript", "bytes": "2188" }, { "name": "PHP", "bytes": "472915" }, { "name": "Shell", "bytes": "3793" } ], "symlink_target": "" }
<!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> <title>cfgv: Not compatible 👼</title> <link rel="shortcut icon" type="image/png" href="../../../../../favicon.png" /> <link href="../../../../../bootstrap.min.css" rel="stylesheet"> <link href="../../../../../bootstrap-custom.css" rel="stylesheet"> <link href="//maxcdn.bootstrapcdn.com/font-awesome/4.2.0/css/font-awesome.min.css" rel="stylesheet"> <script src="../../../../../moment.min.js"></script> <!-- HTML5 Shim and Respond.js IE8 support of HTML5 elements and media queries --> <!-- WARNING: Respond.js doesn't work if you view the page via file:// --> <!--[if lt IE 9]> <script src="https://oss.maxcdn.com/html5shiv/3.7.2/html5shiv.min.js"></script> <script src="https://oss.maxcdn.com/respond/1.4.2/respond.min.js"></script> <![endif]--> </head> <body> <div class="container"> <div class="navbar navbar-default" role="navigation"> <div class="container-fluid"> <div class="navbar-header"> <a class="navbar-brand" href="../../../../.."><i class="fa fa-lg fa-flag-checkered"></i> Coq bench</a> </div> <div id="navbar" class="collapse navbar-collapse"> <ul class="nav navbar-nav"> <li><a href="../..">clean / released</a></li> <li class="active"><a href="">8.11.1 / cfgv - 8.7.0</a></li> </ul> </div> </div> </div> <div class="article"> <div class="row"> <div class="col-md-12"> <a href="../..">« Up</a> <h1> cfgv <small> 8.7.0 <span class="label label-info">Not compatible 👼</span> </small> </h1> <p>📅 <em><script>document.write(moment("2022-03-25 11:16:21 +0000", "YYYY-MM-DD HH:mm:ss Z").fromNow());</script> (2022-03-25 11:16:21 UTC)</em><p> <h2>Context</h2> <pre># Packages matching: installed # Name # Installed # Synopsis base-bigarray base base-threads base base-unix base conf-findutils 1 Virtual package relying on findutils coq 8.11.1 Formal proof management system num 1.4 The legacy Num library for arbitrary-precision integer and rational arithmetic ocaml 4.08.1 The OCaml compiler (virtual package) ocaml-base-compiler 4.08.1 Official release 4.08.1 ocaml-config 1 OCaml Switch Configuration ocamlfind 1.9.3 A library manager for OCaml # opam file: opam-version: &quot;2.0&quot; maintainer: &quot;Hugo.Herbelin@inria.fr&quot; homepage: &quot;https://github.com/coq-contribs/cfgv&quot; license: &quot;LGPL&quot; build: [make &quot;-j%{jobs}%&quot;] install: [make &quot;install&quot;] remove: [&quot;rm&quot; &quot;-R&quot; &quot;%{lib}%/coq/user-contrib/CFGV&quot;] depends: [ &quot;ocaml&quot; &quot;coq&quot; {&gt;= &quot;8.7&quot; &amp; &lt; &quot;8.8~&quot;} ] tags: [ &quot;keyword: generic programming&quot; &quot;keyword: variable bindings&quot; &quot;keyword: context free grammars&quot; &quot;keyword: substitution&quot; &quot;keyword: alpha equality&quot; &quot;keyword: equivariance&quot; &quot;category: Computer Science/Lambda Calculi&quot; ] authors: [ &quot;Abhishek &lt;abhishek.anand.iitg@gmail.com&gt; [http://www.cs.cornell.edu/~aa755/]&quot; &quot;Vincent Rahli &lt;vincent.rahli@gmail.com&gt; [http://www.cs.cornell.edu/~rahli/]&quot; ] bug-reports: &quot;https://github.com/coq-contribs/cfgv/issues&quot; dev-repo: &quot;git+https://github.com/coq-contribs/cfgv.git&quot; synopsis: &quot;Generic Proofs about Alpha Equality and Substitution&quot; description: &quot;&quot;&quot; http://www.nuprl.org/html/CFGVLFMTP2014/ Please read the following paper&quot;&quot;&quot; flags: light-uninstall url { src: &quot;https://github.com/coq-contribs/cfgv/archive/v8.7.0.tar.gz&quot; checksum: &quot;md5=59a29ea2c3114e007451171d9de147d8&quot; } </pre> <h2>Lint</h2> <dl class="dl-horizontal"> <dt>Command</dt> <dd><code>true</code></dd> <dt>Return code</dt> <dd>0</dd> </dl> <h2>Dry install 🏜️</h2> <p>Dry install with the current Coq version:</p> <dl class="dl-horizontal"> <dt>Command</dt> <dd><code>opam install -y --show-action coq-cfgv.8.7.0 coq.8.11.1</code></dd> <dt>Return code</dt> <dd>5120</dd> <dt>Output</dt> <dd><pre>[NOTE] Package coq is already installed (current version is 8.11.1). The following dependencies couldn&#39;t be met: - coq-cfgv -&gt; coq &lt; 8.8~ -&gt; ocaml &lt; 4.06.0 base of this switch (use `--unlock-base&#39; to force) Your request can&#39;t be satisfied: - No available version of coq satisfies the constraints No solution found, exiting </pre></dd> </dl> <p>Dry install without Coq/switch base, to test if the problem was incompatibility with the current Coq/OCaml version:</p> <dl class="dl-horizontal"> <dt>Command</dt> <dd><code>opam remove -y coq; opam install -y --show-action --unlock-base coq-cfgv.8.7.0</code></dd> <dt>Return code</dt> <dd>0</dd> </dl> <h2>Install dependencies</h2> <dl class="dl-horizontal"> <dt>Command</dt> <dd><code>true</code></dd> <dt>Return code</dt> <dd>0</dd> <dt>Duration</dt> <dd>0 s</dd> </dl> <h2>Install 🚀</h2> <dl class="dl-horizontal"> <dt>Command</dt> <dd><code>true</code></dd> <dt>Return code</dt> <dd>0</dd> <dt>Duration</dt> <dd>0 s</dd> </dl> <h2>Installation size</h2> <p>No files were installed.</p> <h2>Uninstall 🧹</h2> <dl class="dl-horizontal"> <dt>Command</dt> <dd><code>true</code></dd> <dt>Return code</dt> <dd>0</dd> <dt>Missing removes</dt> <dd> none </dd> <dt>Wrong removes</dt> <dd> none </dd> </dl> </div> </div> </div> <hr/> <div class="footer"> <p class="text-center"> Sources are on <a href="https://github.com/coq-bench">GitHub</a> © Guillaume Claret 🐣 </p> </div> </div> <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script> <script src="../../../../../bootstrap.min.js"></script> </body> </html>
{ "content_hash": "d52e309220ad6d8c5d2887ea6679aaf9", "timestamp": "", "source": "github", "line_count": 164, "max_line_length": 290, "avg_line_length": 42.792682926829265, "alnum_prop": 0.5467369620974637, "repo_name": "coq-bench/coq-bench.github.io", "id": "680e661a28cdc39270cf4c24639e1fe7664aa32b", "size": "7043", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "clean/Linux-x86_64-4.08.1-2.0.5/released/8.11.1/cfgv/8.7.0.html", "mode": "33188", "license": "mit", "language": [], "symlink_target": "" }
<?php /** * This file is part of file-fixture. * * (c) Noritaka Horio <holy.shared.design@gmail.com> * * This source file is subject to the MIT license that is bundled * with this source code in the file LICENSE. */ namespace holyshared\fixture\container; use Collections\Map; use holyshared\fixture\Container; final class FixtureContainer implements Container { /** * @var \Collections\Map */ private $fixtures; /** * @param array $fixtures */ public function __construct(array $fixtures = []) { $this->fixtures = Map::fromArray($fixtures); } /** * Get the path of fixture file * * @param string $name * @return string */ public function get($name) { return $this->fixtures->get($name); } /** * @param string $name * @return bool */ public function has($name) { return $this->fixtures->containsKey($name); } }
{ "content_hash": "7ae23141857c76b22b4d7ff304db8b9e", "timestamp": "", "source": "github", "line_count": 55, "max_line_length": 65, "avg_line_length": 17.618181818181817, "alnum_prop": 0.5902992776057792, "repo_name": "holyshared/file-fixture", "id": "535f72697757da5dd5c22b222a8ef41036155640", "size": "969", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/container/FixtureContainer.php", "mode": "33188", "license": "mit", "language": [ { "name": "MAXScript", "bytes": "30" }, { "name": "PHP", "bytes": "30272" } ], "symlink_target": "" }
drop procedure sptest.getnames if exists go drop procedure sptest.getname if exists go drop procedure sptest.adder if exists go drop procedure sptest.arraytest if exists go drop table sptest.names if exists go drop table sptest.items if exists go drop schema sptest if exists go create schema sptest go create procedure sptest.adder(in addend1 integer, in addend2 integer, out theSum integer) begin atomic set theSum = addend1 + addend2; end go create table sptest.names ( id integer generated by default as identity not null, first_name varchar(20), last_name varchar(20), primary key(id) ) go insert into sptest.names (first_name, last_name) values('Fred', 'Flintstone') go insert into sptest.names (first_name, last_name) values('Wilma', 'Flintstone') go insert into sptest.names (first_name, last_name) values('Barney', 'Rubble') go insert into sptest.names (first_name, last_name) values('Betty', 'Rubble') go create table sptest.items ( id integer generated by default as identity not null, item varchar(20), primary key(id) ) go insert into sptest.items (item) values('Brontosaurus Burger') go insert into sptest.items (item) values('Lunch Box') go insert into sptest.items (item) values('Helmet') go -- note that these create procedure statements will fail until hsqldb 2.0.1 create procedure sptest.getname(in nameId integer) modifies sql data dynamic result sets 1 BEGIN ATOMIC declare cur cursor for select * from sptest.names where id = nameId; open cur; END go create procedure sptest.getnamesanditems() modifies sql data dynamic result sets 2 BEGIN ATOMIC declare cur1 cursor for select * from sptest.names; declare cur2 cursor for select * from sptest.items; open cur1; open cur2; END go create procedure sptest.getnames(in lowestId int, out totalrows integer) modifies sql data dynamic result sets 1 BEGIN ATOMIC declare cur cursor for select * from sptest.names where id >= lowestId; select count(*) into totalrows from sptest.names where id >= lowestId; open cur; END go create procedure sptest.arraytest(in ids int array, out rowsrequested integer, out returnedids int array) modifies sql data dynamic result sets 1 begin atomic declare cur cursor for select * from sptest.names where id in (unnest(ids)); set rowsrequested = cardinality(ids); set returnedids = array [7, 8, 9, 10]; open cur; end go
{ "content_hash": "c0855c113b64098478ea37a3bfe78b48", "timestamp": "", "source": "github", "line_count": 107, "max_line_length": 105, "avg_line_length": 22.27102803738318, "alnum_prop": 0.7624842635333613, "repo_name": "c340c340/mybatis-3.2.22", "id": "bda384370fd22da271cafd31a37578706889c722", "size": "3017", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/test/java/org/apache/ibatis/submitted/sptests/CreateDB.sql", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "CSS", "bytes": "730" }, { "name": "Java", "bytes": "2728460" }, { "name": "PLSQL", "bytes": "3259" }, { "name": "SQLPL", "bytes": "3017" } ], "symlink_target": "" }
'use strict'; // Include Gulp & Tools We'll Use var gulp = require('gulp'); var $ = require('gulp-load-plugins')(); var del = require('del'); var runSequence = require('run-sequence'); var browserSync = require('browser-sync'); var pagespeed = require('psi'); var reload = browserSync.reload; var AUTOPREFIXER_BROWSERS = [ 'ie >= 10', 'ie_mob >= 10', 'ff >= 30', 'chrome >= 34', 'safari >= 7', 'opera >= 23', 'ios >= 7', 'android >= 4.4', 'bb >= 10' ]; // Lint JavaScript gulp.task('jshint', function () { return gulp.src(['app/scripts/**/*.js', '!app/scripts/bower_components/**']) .pipe(reload({stream: true, once: true})) .pipe($.jshint()) .pipe($.jshint.reporter('jshint-stylish')) .pipe($.if(!browserSync.active, $.jshint.reporter('fail'))); }); // Optimize Images gulp.task('images', function () { return gulp.src('app/images/**/*') .pipe($.cache($.imagemin({ progressive: true, interlaced: true }))) .pipe(gulp.dest('dist/images')) .pipe($.size({title: 'images'})); }); // Copy All Files At The Root Level (app) gulp.task('copy', function () { return gulp.src([ 'app/*', '!app/*.html', 'node_modules/apache-server-configs/dist/.htaccess' ], { dot: true }).pipe(gulp.dest('dist')) .pipe($.size({title: 'copy'})); }); // Copy Web Fonts To Dist gulp.task('fonts', function () { return gulp.src(['app/fonts/**']) .pipe(gulp.dest('dist/fonts')) .pipe($.size({title: 'fonts'})); }); // Compile and Automatically Prefix Stylesheets gulp.task('styles', function () { // For best performance, don't add Sass partials to `gulp.src` return gulp.src([ 'app/styles/*.scss', 'app/styles/**/*.css', 'app/styles/components/components.scss' ]) .pipe($.changed('styles', {extension: '.scss'})) .pipe($.rubySass({ style: 'expanded', precision: 10 }) .on('error', console.error.bind(console)) ) .pipe($.autoprefixer(AUTOPREFIXER_BROWSERS)) .pipe(gulp.dest('.tmp/styles')) // Concatenate And Minify Styles .pipe($.if('*.css', $.csso())) .pipe(gulp.dest('dist/styles')) .pipe($.size({title: 'styles'})); }); // Scan Your HTML For Assets & Optimize Them gulp.task('html', function () { var assets = $.useref.assets({searchPath: '{.tmp,app}'}); return gulp.src('app/**/*.html') .pipe(assets) // Concatenate And Minify JavaScript .pipe($.if('*.js', $.uglify({preserveComments: 'some'}))) // Remove Any Unused CSS // Note: If not using the Style Guide, you can delete it from // the next line to only include styles your project uses. .pipe($.if('*.css', $.uncss({ html: [ 'app/index.html', 'app/styleguide.html' ], // CSS Selectors for UnCSS to ignore ignore: [ /.navdrawer-container.open/, /.app-bar.open/ ] }))) // Concatenate And Minify Styles // In case you are still using useref build blocks .pipe($.if('*.css', $.csso())) .pipe(assets.restore()) .pipe($.useref()) // Update Production Style Guide Paths .pipe($.replace('components/components.css', 'components/main.min.css')) // Minify Any HTML .pipe($.if('*.html', $.minifyHtml())) // Output Files .pipe(gulp.dest('dist')) .pipe($.size({title: 'html'})); }); // Clean Output Directory gulp.task('clean', del.bind(null, ['.tmp', 'dist'])); // Watch Files For Changes & Reload gulp.task('serve', ['styles'], function () { browserSync({ notify: false, // Run as an https by uncommenting 'https: true' // Note: this uses an unsigned certificate which on first access // will present a certificate warning in the browser. // https: true, server: ['.tmp', 'app'] }); gulp.watch(['app/**/*.html'], reload); gulp.watch(['app/styles/**/*.{scss,css}'], ['styles', reload]); gulp.watch(['app/scripts/**/*.js'], ['jshint']); gulp.watch(['app/images/**/*'], reload); }); // Build and serve the output from the dist build gulp.task('serve:dist', ['default'], function () { browserSync({ notify: false, // Run as an https by uncommenting 'https: true' // Note: this uses an unsigned certificate which on first access // will present a certificate warning in the browser. // https: true, server: 'dist' }); }); // Build Production Files, the Default Task gulp.task('default', ['clean'], function (cb) { runSequence('styles', ['jshint', 'html', 'images', 'fonts', 'copy'], cb); }); // Run PageSpeed Insights // Update `url` below to the public URL for your site gulp.task('pagespeed', pagespeed.bind(null, { // By default, we use the PageSpeed Insights // free (no API key) tier. You can use a Google // Developer API key if you have one. See // http://goo.gl/RkN0vE for info key: 'YOUR_API_KEY' url: 'https://example.com', strategy: 'mobile' })); // Load custom tasks from the `tasks` directory try { require('require-dir')('tasks'); } catch (err) {}
{ "content_hash": "83dc49a5741b747b6faf7790877121ad", "timestamp": "", "source": "github", "line_count": 173, "max_line_length": 78, "avg_line_length": 29.023121387283236, "alnum_prop": 0.6004779924317865, "repo_name": "ronatgithub/angular-web-starter", "id": "be05f39128e7dc002745aab0374907bb69cb4fe0", "size": "5672", "binary": false, "copies": "1", "ref": "refs/heads/stable", "path": "gulpfile.js", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "88114" }, { "name": "HTML", "bytes": "62639" }, { "name": "JavaScript", "bytes": "12371" } ], "symlink_target": "" }
using System; using System.Collections.Generic; using System.Data.Entity; using System.Data.Entity.Infrastructure; using System.Linq; using System.Text; using System.Threading.Tasks; namespace InventoryManager.Data { public interface IInventoryManagerDbContext { DbSet<TEntity> Set<TEntity>() where TEntity : class; DbEntityEntry<TEntity> Entry<TEntity>(TEntity entity) where TEntity : class; void Dispose(); int SaveChanges(); } }
{ "content_hash": "2eb4ee569457f8874b630ea3584d2264", "timestamp": "", "source": "github", "line_count": 21, "max_line_length": 84, "avg_line_length": 22.904761904761905, "alnum_prop": 0.7214137214137214, "repo_name": "todor-enikov/InventoryManager-ASP.NET-MVC-Project", "id": "0ee4f488ac8ca61c3e8867ecbe96212086410444", "size": "483", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "Source/InventoryManager.Data/IInventoryManagerDbContext.cs", "mode": "33188", "license": "mit", "language": [ { "name": "ASP", "bytes": "118" }, { "name": "C#", "bytes": "155481" }, { "name": "CSS", "bytes": "513" }, { "name": "HTML", "bytes": "5127" }, { "name": "JavaScript", "bytes": "11032" } ], "symlink_target": "" }
(function (WjsProto) { 'use strict'; /** * Returns name of css transition event, * used to detect when a CSS animation ends. */ WjsProto.register('JsMethod', 'eventTransitionName', function () { var t, fakeElement = this.window.document.createElement('fakeElement'), transitions = { 'WebkitTransition': 'webkitAnimationEnd', 'OTransition': 'oAnimationEnd', 'MozTransition': 'animationend', 'transition': 'animationend' }; for (t in transitions) { if (transitions.hasOwnProperty(t) && fakeElement.style[t] !== undefined) { return transitions[t]; } } return false; }); }(WjsProto));
{ "content_hash": "fc7e09b682f7d4d059b1568bcf874304", "timestamp": "", "source": "github", "line_count": 23, "max_line_length": 80, "avg_line_length": 29.73913043478261, "alnum_prop": 0.6154970760233918, "repo_name": "weeger/wjs", "id": "ab70e41f51c1f813075ff6a10d4379549e550481", "size": "684", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "extension/JsMethod/eventTransitionName.js", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "440" }, { "name": "HTML", "bytes": "211" }, { "name": "JavaScript", "bytes": "279467" }, { "name": "PHP", "bytes": "90681" } ], "symlink_target": "" }
var validation = require("./validation.js"); var validationSchema = require("./collection-config-validation/validation-schema.js"); var cfg = require("./constraint-type"); // check validate model MenuConfig Parse.Cloud.beforeSave("MenuConfig", function(req, res) { validation.validateMenu({modelName:"MenuConfig",req:req,res:res}); }); // check validate model StyleConfig Parse.Cloud.beforeSave("StyleConfig", function(req, res) { validation.validateStyle({modelName:"StyleConfig",req:req,res:res}); }); // check validate model SettingConfig Parse.Cloud.beforeSave("SettingConfig", function(req, res) { validation.validateSetting({modelName:"SettingConfig",req:req,res:res}); }); // check validate model ItemConfig Parse.Cloud.beforeSave("ItemConfig", function(req, res) { validation.validateItem({modelName:"ItemConfig",req:req,res:res}); }); var cacheConstraint = require("./constraint"); var constraint = require('./constraint-type'); Parse.Cloud.beforeSave(cfg.collectionName, function(req,res) { if(!req.object.get("constraintType")){ res.error("constraintType is required"); return; } if(!constraint.constraintType[req.object.get("constraintType")]){ res.error("constraintType is invalid"); return; } var json ={}; if(req.object.id){ json.objectId =req.object.id; } if(req.object.get("constraintType")){ json.constraintType =req.object.get("constraintType"); } //check from memory var existed = cacheConstraint.isExisted(json); if(existed){ res.error("constraintType is duplicated"); }else{ validationSchema.validateSchema({req:req,res:res},req.object.get("constraintType")); // res.success(); } /*// check duplicate var query = new Parse.Query(cfg.collectionName); query.equalTo("constraintType", req.object.get("constraintType")); if(req.object.id){ query.notEqualTo("objectId", req.object.id); } query.first().then(function(results){ if(results){ res.error("constraintType is duplicated"); }else{ res.success(); } }).catch(function(error){ res.error(error); });*/ }); Parse.Cloud.afterSave(cfg.collectionName, function(req) { //the req contains the latest ParseObject. var parseObjArr = [req.object]; cacheConstraint.notifySaved(parseObjArr); /*// save history var query = new Parse.Query(cfg.collectionName); query.get(req.object.id, { success: function(objectDataBase) { if(objectDataBase){ console.log("AfterSave: " + cfg.collectionName + "Ok"); var parseObjArr = [objectDataBase]; cacheConstraint.notifySaved(parseObjArr); } }, error: function(object, error) { console.log("AfterSave: " + cfg.collectionName , error); } });*/ }); Parse.Cloud.define('getAllConstraints', function(req, res) { res.success(cacheConstraint.getConstraint(null)); }); Parse.Cloud.afterDelete(cfg.collectionName, function(req) { //the req contains db record had been deleted. cacheConstraint.removeItems({objectId:req.object.id, constraintType: req.object.toJSON().constraintType}); });
{ "content_hash": "d8a62c2d8d333217ef1dbbb21ec358ed", "timestamp": "", "source": "github", "line_count": 108, "max_line_length": 110, "avg_line_length": 29.12037037037037, "alnum_prop": 0.6883942766295708, "repo_name": "huynhtankhanh1988/parse-server-terralogic", "id": "ddb130564bb57ca6de62e4e26b305e3a75f1a11b", "size": "3145", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "spec/cloud-terra/main.js", "mode": "33188", "license": "bsd-3-clause", "language": [ { "name": "HTML", "bytes": "2796" }, { "name": "JavaScript", "bytes": "1551172" }, { "name": "Shell", "bytes": "4067" } ], "symlink_target": "" }
"""Copyright 2022 Google LLC 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 https://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. """ # Lint as: python3 """Examine variance for GLOVE embeddings. """ from __future__ import absolute_import # Not necessary in a Python 3-only module from __future__ import division # Not necessary in a Python 3-only module from __future__ import google_type_annotations # Not necessary in a Python 3-only module from __future__ import print_function # Not necessary in a Python 3-only module from absl import app from absl import flags from google3.sstable.python import sstable from google3.learning.dist_belief.experimental.embedding_client import embedding_pb2 import numpy as np import sys import pickle FLAGS = flags.FLAGS flags.DEFINE_string( 'embedding_sstable', '', 'SSTable containing static word embeddings.' ) def get_embedding(word, embedding_table): table = sstable.SSTable( embedding_table, # Proto2 wrapper=sstable.TableWrapper(embedding_pb2.TokenEmbedding.FromString)) print('table', table.items()) word = word.encode('utf-8') print('word', word) if word in table: return table[word] def get_average(embedding_table, embedding_dim): norms = [] table = sstable.SSTable( embedding_table, # Proto2 wrapper=sstable.TableWrapper(embedding_pb2.TokenEmbedding.FromString)) keys = set(table.iterkeys()) sum_embedding = np.zeros(embedding_dim) for key in keys: embedding = table[key] embedding = np.array(embedding.vector.values) norms.append(norm(embedding)) sum_embedding += embedding mean_embedding = sum_embedding / len(keys) print('mean_embedding', mean_embedding) return mean_embedding, norms def main(argv): embedding_table = FLAGS.embedding_sstable table = sstable.SSTable( embedding_table, # Proto2 wrapper=sstable.TableWrapper(embedding_pb2.TokenEmbedding.FromString)) keys = set(table.iterkeys()) embeddings = [] for i, key in enumerate(keys): embedding = table[key] embedding = np.array(embedding.vector.values) embeddings.append(embedding) embeddings = np.array(embeddings) mean_embeddings = list(np.mean(embeddings, axis=0)) np.set_printoptions(threshold=sys.maxsize) print('mean', mean_embeddings) std_embeddings = list(np.std(embeddings, axis=0)) np.set_printoptions(threshold=sys.maxsize) print('std', std_embeddings) min_embeddings = list(np.amin(embeddings, axis=0)) np.set_printoptions(threshold=sys.maxsize) print('min', min_embeddings) max_embeddings = list(np.amax(embeddings, axis=0)) np.set_printoptions(threshold=sys.maxsize) print('max', max_embeddings) stats_file = '/usr/local/google/home/agoldie/data/glove/stats.txt' stats = {} with open(stats_file, 'r') as f: for line in f: line = line.strip().strip(']') category, data = line.split(' [') embedding = [float(t) for t in data.split(', ')] print(category) print(type(embedding), embedding) stats[category] = embedding print(stats.keys()) for k in stats.keys(): print(k, len(stats[k])) mean_embedding = np.array(stats['mean']) std_embedding = np.array(stats['std']) num_stds = 1.5 lower_bound = mean_embedding - num_stds * std_embedding upper_bound = mean_embedding + num_stds * std_embedding print(lower_bound) print(upper_bound) embedding_table = FLAGS.embedding_sstable table = sstable.SSTable( embedding_table, # Proto2 wrapper=sstable.TableWrapper(embedding_pb2.TokenEmbedding.FromString)) keys = set(table.iterkeys()) for i, key in enumerate(keys): print(i) embedding = table[key] embedding = np.array(embedding.vector.values) if (embedding > lower_bound).all() and (embedding < upper_bound).all(): print(key) break embedding_table = FLAGS.embedding_sstable table = sstable.SSTable( embedding_table, # Proto2 wrapper=sstable.TableWrapper(embedding_pb2.TokenEmbedding.FromString)) distance_to_words = [] for word in table: embedding = table[word] embedding = np.array(embedding.vector.values) euclidean_dist = np.linalg.norm(embedding) distance_to_words.append((euclidean_dist, word)) distance_to_words.sort() import pickle distance_to_words_file = '/usr/local/google/home/agoldie/data/glove/distance_to_words.pkl' with open(distance_to_words_file, 'wb') as f: pickle.dump(distance_to_words, f) print(distance_to_words) with open(distance_to_words_file, 'rb') as f: distance_to_words = pickle.load(f) n = 5000 vocab = set([pair[1].decode() for pair in distance_to_words[:n]]) print(vocab) if __name__ == '__main__': app.run(main)
{ "content_hash": "fa864e47f125c41f71f161801a043801", "timestamp": "", "source": "github", "line_count": 148, "max_line_length": 92, "avg_line_length": 34.57432432432432, "alnum_prop": 0.7123314442055892, "repo_name": "google/one-weird-trick", "id": "6fe175fe510df567a9cbe6cbf366cc1dfd51d577", "size": "5117", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/examine_variance_for_glove_embeddings.py", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Jupyter Notebook", "bytes": "3655866" }, { "name": "Python", "bytes": "280706" }, { "name": "Starlark", "bytes": "15214" } ], "symlink_target": "" }
<menu xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res-auto" xmlns:tools="http://schemas.android.com/tools" tools:context="com.example.elias.androidbuzzer.GameShowActivity"> </menu>
{ "content_hash": "12563a9f8cc4cb00cce949a4173eac15", "timestamp": "", "source": "github", "line_count": 5, "max_line_length": 69, "avg_line_length": 50, "alnum_prop": 0.74, "repo_name": "edcarter/AndroidBuzzer", "id": "8e37028850e9d79ed2cc9df9efd5965eac2bf5c5", "size": "250", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "app/src/main/res/menu/menu_game_show.xml", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Java", "bytes": "81130" } ], "symlink_target": "" }
<?xml version="1.0" encoding="UTF-8"?> <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> <modelVersion>4.0.0</modelVersion> <groupId>de.spinscale.netty</groupId> <artifactId>netty4-http-pipelining</artifactId> <version>1.0-SNAPSHOT</version> <dependencies> <dependency> <groupId>io.netty</groupId> <artifactId>netty-all</artifactId> <version>4.1.0.Beta8</version> </dependency> <dependency> <groupId>junit</groupId> <artifactId>junit</artifactId> <version>4.12</version> <scope>test</scope> </dependency> <dependency> <groupId>org.hamcrest</groupId> <artifactId>hamcrest-all</artifactId> <version>1.3</version> </dependency> </dependencies> <build> <plugins> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-compiler-plugin</artifactId> <version>3.1</version> <configuration> <source>1.7</source> <target>1.7</target> </configuration> </plugin> </plugins> </build> </project>
{ "content_hash": "10d9986f74883749bebb869ec0efd844", "timestamp": "", "source": "github", "line_count": 43, "max_line_length": 108, "avg_line_length": 33.348837209302324, "alnum_prop": 0.5467224546722455, "repo_name": "spinscale/netty4-http-pipelining", "id": "f4b75cfbb7b94384360a004a3767fe1865917762", "size": "1434", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "pom.xml", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Java", "bytes": "13110" } ], "symlink_target": "" }
<?php namespace JHWEB\SeguridadVialBundle\Controller; use JHWEB\SeguridadVialBundle\Entity\SvCfgIluminacion; use Sensio\Bundle\FrameworkExtraBundle\Configuration\Method; use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route; use Symfony\Bundle\FrameworkBundle\Controller\Controller; use Symfony\Component\HttpFoundation\Request; /** * Svcfgiluminacion controller. * * @Route("svcfgiluminacion") */ class SvCfgIluminacionController extends Controller { /** * Lists all svCfgIluminacion entities. * * @Route("/", name="svcfgiluminacion_index") * @Method("GET") */ public function indexAction() { $helpers = $this->get("app.helpers"); $em = $this->getDoctrine()->getManager(); $iluminaciones = $em->getRepository('JHWEBSeguridadVialBundle:SvCfgIluminacion')->findBy( array('activo' => true) ); $response['data'] = array(); if ($iluminaciones) { $response = array( 'status' => 'success', 'code' => 200, 'message' => count($iluminaciones) . " registros encontrados", 'data' => $iluminaciones, ); } return $helpers->json($response); } /** * Creates a new svCfgIluminacion entity. * * @Route("/new", name="svcfgiluminacion_new") * @Method({"GET", "POST"}) */ public function newAction(Request $request) { $helpers = $this->get("app.helpers"); $hash = $request->get("authorization", null); $authCheck = $helpers->authCheck($hash); if ($authCheck == true) { $json = $request->get("json", null); $params = json_decode($json); $iluminacion = new SvCfgIluminacion(); $em = $this->getDoctrine()->getManager(); $iluminacion->setNombre(strtoupper($params->nombre)); $iluminacion->setActivo(true); $em->persist($iluminacion); $em->flush(); $response = array( 'status' => 'success', 'code' => 200, 'message' => "Los datos han sido registrados exitosamente.", ); } else { $response = array( 'status' => 'error', 'code' => 400, 'message' => "Autorización no válida", ); } return $helpers->json($response); } /** * Finds and displays a svCfgIluminacion entity. * * @Route("/{id}/show", name="svcfgiluminacion_show") * @Method("GET") */ public function showAction(SvCfgIluminacion $svCfgIluminacion) { $deleteForm = $this->createDeleteForm($svCfgIluminacion); return $this->render('svCfgIluminacion/show.html.twig', array( 'svCfgIluminacion' => $svCfgIluminacion, 'delete_form' => $deleteForm->createView(), )); } /** * Displays a form to edit an existing svCfgIluminacion entity. * * @Route("/edit", name="svcfgiluminacion_edit") * @Method({"GET", "POST"}) */ public function editAction(Request $request) { $helpers = $this->get("app.helpers"); $hash = $request->get("authorization", null); $authCheck = $helpers->authCheck($hash); if ($authCheck == true) { $json = $request->get("json", null); $params = json_decode($json); $em = $this->getDoctrine()->getManager(); $iluminacion = $em->getRepository('JHWEBSeguridadVialBundle:SvCfgIluminacion')->find($params->id); if ($iluminacion != null) { $iluminacion->setNombre(strtoupper($params->nombre)); $em->persist($iluminacion); $em->flush(); $response = array( 'status' => 'success', 'code' => 200, 'message' => "Registro actualizado con éxito", 'data' => $iluminacion, ); } else { $response = array( 'status' => 'error', 'code' => 400, 'message' => "El registro no se encuentra en la base de datos", ); } } else { $response = array( 'status' => 'error', 'code' => 400, 'message' => "Autorización no válida para editar", ); } return $helpers->json($response); } /** * Deletes a svCfgIluminacion entity. * @Route("/delete", name="svcfgiluminacion_delete") * @Method({"GET", "POST"}) */ public function deleteAction(Request $request) { $helpers = $this->get("app.helpers"); $hash = $request->get("authorization", true); $authCheck = $helpers->authCheck($hash); if ($authCheck == true) { $em = $this->getDoctrine()->getManager(); $json = $request->get("json", null); $params = json_decode($json); $iluminacion = $em->getRepository('JHWEBSeguridadVialBundle:SvCfgIluminacion')->find($params->id); $iluminacion->setActivo(false); $em->persist($iluminacion); $em->flush(); $response = array( 'status' => 'success', 'code' => 200, 'message' => "Registro eliminado con éxito.", ); } else { $response = array( 'status' => 'error', 'code' => 400, 'message' => "Autorizacion no válida", ); } return $helpers->json($response); } /** * Creates a form to delete a svCfgIluminacion entity. * * @param SvCfgIluminacion $svCfgIluminacion The svCfgIluminacion entity * * @return \Symfony\Component\Form\Form The form */ private function createDeleteForm(SvCfgIluminacion $svCfgIluminacion) { return $this->createFormBuilder() ->setAction($this->generateUrl('svcfgiluminacion_delete', array('id' => $svCfgIluminacion->getId()))) ->setMethod('DELETE') ->getForm(); } /** * datos para select 2 * * @Route("/select", name="iluminacion_select") * @Method({"GET", "POST"}) */ public function selectAction() { $helpers = $this->get("app.helpers"); $em = $this->getDoctrine()->getManager(); $iluminaciones = $em->getRepository('JHWEBSeguridadVialBundle:SvCfgIluminacion')->findBy( array('activo' => 1) ); $response = null; foreach ($iluminaciones as $key => $iluminacion) { $response[$key] = array( 'value' => $iluminacion->getId(), 'label' => $iluminacion->getNombre(), ); } return $helpers->json($response); } }
{ "content_hash": "79ab9a3ea225b9683e464fda7447a2ed", "timestamp": "", "source": "github", "line_count": 226, "max_line_length": 113, "avg_line_length": 30.911504424778762, "alnum_prop": 0.518894932722588, "repo_name": "edosgn/colossus-sit", "id": "cdd7ca5ea93cfa5934a2e8b5866b0f4a6ffd7a51", "size": "6993", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/JHWEB/SeguridadVialBundle/Controller/SvCfgIluminacionController.php", "mode": "33188", "license": "mit", "language": [ { "name": "HTML", "bytes": "326601" }, { "name": "PHP", "bytes": "6284297" } ], "symlink_target": "" }
class Array def compact select{|x| !x.nil? } end end
{ "content_hash": "5ba5259edf8e20afc7b6cf2d7d00aa2e", "timestamp": "", "source": "github", "line_count": 5, "max_line_length": 24, "avg_line_length": 12.2, "alnum_prop": 0.6065573770491803, "repo_name": "jkutner/mjruby", "id": "6f4c31c05aeb156bcad2fe5177ae34169b40bd5b", "size": "61", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "mrblib/array.rb", "mode": "33188", "license": "mit", "language": [ { "name": "C", "bytes": "2100" }, { "name": "Ruby", "bytes": "27488" } ], "symlink_target": "" }
(function() { var models, nconf, passport_oauth, strategy, users; passport_oauth = require('passport-google-oauth'); nconf = require('nconf'); models = require("./models"); console.log("[auth] loading..."); nconf.env().file({ file: 'config.json' }); users = { serialize: function(user, done) { return models.user.update(user.email, user, function(err) { return done(err, user.email); }); }, deserialize: function(email, done) { return models.user.read(email, function(err, entity) { return done(err, typeof entity.toObject === "function" ? entity.toObject() : void 0); }); }, authenticated: function(accessToken, refreshToken, profile, done) { var email; email = profile.emails[0].value; console.log("[auth] user '" + email + "' authenticated..."); return models.user.read(email, function(err, user) { if (err) { console.error("[auth] error '" + err + "' while authenticating user '" + email + "'!"); return done(err); } else if (!user) { console.log("[auth] '" + email + "' is a new user..."); return models.user.update(email, {}, function(err, entity) { return done(err, typeof entity.toObject === "function" ? entity.toObject() : void 0); }); } else { console.log("[auth] '" + email + "' is an existing user..."); return done(null, typeof user.toObject === "function" ? user.toObject() : void 0); } }); } }; console.log("[auth] creating strategy..."); console.log("[auth] using host: '" + (nconf.get("host")) + "'"); strategy = new passport_oauth.OAuth2Strategy({ clientID: "" + (nconf.get("oauth_client_id")), clientSecret: "" + (nconf.get("oauth_client_secret")), callbackURL: "" + (nconf.get("oauth_protocol")) + "://" + (nconf.get("host")) + "/oauth2callback" }, users.authenticated); exports.configure = function(passport, express) { passport.serializeUser = users.serialize; passport.deserializeUser = users.deserialize; passport.use(strategy); express.get('/auth/google', passport.authenticate('google', { scope: 'email' })); express.get('/oauth2callback', passport.authenticate('google', { scope: 'email', successRedirect: '/core.html#/careers', failureRedirect: '/core.html#/user' })); express.get('/auth/logout', function(req, res) { req.logout(); return res.redirect('/core.html#/user'); }); return express.get('/user/me', function(req, res) { if (req.user) { return res.json(req.user); } else { return res.send(404); } }); }; console.log("[auth] loaded."); }).call(this);
{ "content_hash": "3b16bef1bf73f6775b5a0c7fe1192bbd", "timestamp": "", "source": "github", "line_count": 85, "max_line_length": 101, "avg_line_length": 32.576470588235296, "alnum_prop": 0.5796316359696642, "repo_name": "fitzmont/pigeonfireman", "id": "839d38440453ae9f4646d93ff899ac9b94810cda", "size": "2804", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "auth.js", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "317273" }, { "name": "CoffeeScript", "bytes": "56143" }, { "name": "JavaScript", "bytes": "29163" } ], "symlink_target": "" }
<div class="commune_descr limited"> <p> Corbreuse est une commune localisée dans le département de l'Essonne en Île-de-France. Elle comptait 1&nbsp;643 habitants en 2008.</p> <p>À coté de Corbreuse sont situées les villes de <a href="{{VLROOT}}/immobilier/granges-le-roi_91284/">Les&nbsp;Granges-le-Roi</a> localisée à 4&nbsp;km, 949 habitants, <a href="{{VLROOT}}/immobilier/ponthevrard_78499/">Ponthévrard</a> située à 6&nbsp;km, 542 habitants, <a href="{{VLROOT}}/immobilier/richarville_91519/">Richarville</a> à 4&nbsp;km, 432 habitants, <a href="{{VLROOT}}/immobilier/saint-martin-de-brethencourt_78564/">Saint-Martin-de-Bréthencourt</a> à 2&nbsp;km, 591 habitants, <a href="{{VLROOT}}/immobilier/boinville-le-gaillard_78071/">Boinville-le-Gaillard</a> localisée à 6&nbsp;km, 572 habitants, <a href="{{VLROOT}}/immobilier/dourdan_91200/">Dourdan</a> située à 5&nbsp;km, 9&nbsp;518 habitants, entre autres. De plus, Corbreuse est située à seulement 18&nbsp;km de <a href="{{VLROOT}}/immobilier/rambouillet_78517/">Rambouillet</a>.</p> <p>La ville propose quelques équipements sportifs, elle propose entre autres un terrain de tennis, un centre d'équitation et un terrain de sport.</p> <p>À Corbreuse, la valeur moyenne à l'achat d'un appartement se situe à 3&nbsp;174 &euro; du m² en vente. La valeur moyenne d'une maison à l'achat se situe à 2&nbsp;259 &euro; du m². À la location la valeur moyenne se situe à 8,26 &euro; du m² par mois.</p> <p>Le nombre d'habitations, à Corbreuse, était réparti en 2011 en 127 appartements et 543 maisons soit un marché relativement équilibré.</p> </div>
{ "content_hash": "7a5b00c016bcf3623c7aebf22b21f123", "timestamp": "", "source": "github", "line_count": 17, "max_line_length": 257, "avg_line_length": 94.47058823529412, "alnum_prop": 0.7434620174346201, "repo_name": "donaldinou/frontend", "id": "13bacf1d2d9cac8bf4ced78ccb5aef17a871928b", "size": "1644", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/Viteloge/CoreBundle/Resources/descriptions/91175.html", "mode": "33188", "license": "mit", "language": [ { "name": "ApacheConf", "bytes": "3073" }, { "name": "CSS", "bytes": "111338" }, { "name": "HTML", "bytes": "58634405" }, { "name": "JavaScript", "bytes": "88564" }, { "name": "PHP", "bytes": "841919" } ], "symlink_target": "" }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using ArcGIS.Core.CIM; using ArcGIS.Desktop.Core; using ArcGIS.Desktop.Framework.Threading.Tasks; using ArcGIS.Desktop.Mapping; using Renderer.Helpers; namespace Renderer { internal static class ProportionalRenderers { #region Snippet Proportional symbols renderer. /// <summary> /// Renders a feature layer using proportional symbols to draw quantities. /// ![Proportional Symbols renderer](http://Esri.github.io/arcgis-pro-sdk/images/Renderers/proportional-renderer.png) /// </summary> /// <remarks></remarks> /// <param name="featureLayer"></param> /// <returns></returns> internal static Task ProportionalRenderer(FeatureLayer featureLayer) { return QueuedTask.Run(() => { //Gets the first numeric field of the feature layer var firstNumericFieldOfFeatureLayer = SDKHelpers.GetNumericField(featureLayer); //Gets the min and max value of the field var sizes = SDKHelpers.GetFieldMinMax(featureLayer, firstNumericFieldOfFeatureLayer); ProportionalRendererDefinition prDef = new ProportionalRendererDefinition() { Field = firstNumericFieldOfFeatureLayer, MinimumSymbolSize = 4, MaximumSymbolSize = 50, LowerSizeStop = Convert.ToDouble(sizes.Item1), UpperSizeStop = Convert.ToDouble(sizes.Item2) }; CIMProportionalRenderer propRndr = (CIMProportionalRenderer)featureLayer.CreateRenderer(prDef); featureLayer.SetRenderer(propRndr); }); } #endregion } }
{ "content_hash": "3ad187c7410e21f9dedf07b3e2105845", "timestamp": "", "source": "github", "line_count": 47, "max_line_length": 125, "avg_line_length": 39.93617021276596, "alnum_prop": 0.6286627597229622, "repo_name": "SoJourned/arcgis-pro-sdk-community-samples-1", "id": "74cb1e005bd96293cff0e29f70533cd8676fb921", "size": "2460", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "Map-Authoring/Renderer/ProportionalRenderers.cs", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "C#", "bytes": "4040148" }, { "name": "HTML", "bytes": "330608" }, { "name": "Python", "bytes": "2934" }, { "name": "Visual Basic", "bytes": "37873" }, { "name": "XSLT", "bytes": "11612" } ], "symlink_target": "" }
package com.morgan.server.util.stat; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; /** * Annotation to mark which methods should have statistics measured for them. * * @author mark@mark-morgan.net (Mark Morgan) */ @Retention(RetentionPolicy.RUNTIME) @Target({ ElementType.METHOD }) public @interface MeasureStatistics { }
{ "content_hash": "a352a577ccfb9a2df800ae182bd1e2b7", "timestamp": "", "source": "github", "line_count": 15, "max_line_length": 77, "avg_line_length": 29.533333333333335, "alnum_prop": 0.7878103837471784, "repo_name": "mmm2a/game-center", "id": "199c5a49407a11d3cde5da3dfa609e15e8d19850", "size": "443", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/com/morgan/server/util/stat/MeasureStatistics.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Batchfile", "bytes": "67" }, { "name": "CSS", "bytes": "24714" }, { "name": "HTML", "bytes": "593642" }, { "name": "Java", "bytes": "733815" }, { "name": "JavaScript", "bytes": "1724557" }, { "name": "Shell", "bytes": "626" } ], "symlink_target": "" }
package gov.nasa.jpf; import gov.nasa.jpf.report.Publisher; import gov.nasa.jpf.report.PublisherExtension; import gov.nasa.jpf.report.Reporter; import gov.nasa.jpf.search.Search; import gov.nasa.jpf.search.SearchListener; import gov.nasa.jpf.tool.RunJPF; import gov.nasa.jpf.util.JPFLogger; import gov.nasa.jpf.util.LogManager; import gov.nasa.jpf.util.Misc; import gov.nasa.jpf.util.RunRegistry; import gov.nasa.jpf.vm.VM; import gov.nasa.jpf.vm.NoOutOfMemoryErrorProperty; import gov.nasa.jpf.vm.VMListener; import java.io.File; import java.util.ArrayList; import java.util.List; import java.util.logging.Logger; /** * main class of the JPF verification framework. This reads the configuration, * instantiates the Search and VM objects, and kicks off the Search */ public class JPF implements Runnable { public static String VERSION = "8.0"; // the major version number static Logger logger = null; // initially public enum Status { NEW, RUNNING, DONE }; class ConfigListener implements ConfigChangeListener { /** * check for new listeners that are dynamically configured */ @Override public void propertyChanged(Config config, String key, String oldValue, String newValue) { if ("listener".equals(key)) { if (oldValue == null) oldValue = ""; String[] nv = config.asStringArray(newValue); String[] ov = config.asStringArray(oldValue); String[] newListeners = Misc.getAddedElements(ov, nv); Class<?>[] argTypes = { Config.class, JPF.class }; // Many listeners have 2 parameter constructors Object[] args = {config, JPF.this }; if (newListeners != null) { for (String clsName : newListeners) { try { JPFListener newListener = config.getInstance("listener", clsName, JPFListener.class, argTypes, args); addListener(newListener); logger.info("config changed, added listener " + clsName); } catch (JPFConfigException cfx) { logger.warning("listener change failed: " + cfx.getMessage()); } } } } } /** * clean up to avoid a sublte but serious memory leak when using the * same config for multiple JPF objects/runs - this listener is an inner * class object that keeps its encapsulating JPF instance alive */ @Override public void jpfRunTerminated(Config config){ config.removeChangeListener(this); } } /** this is the backbone of all JPF configuration */ Config config; /** The search policy used to explore the state space */ Search search; /** Reference to the virtual machine used by the search */ VM vm; /** the report generator */ Reporter reporter; Status status = Status.NEW; /** a list of listeners that get automatically added from VM, Search or Reporter initialization */ List<VMListener> pendingVMListeners; List<SearchListener> pendingSearchListeners; /** we use this as safety margin, to be released upon OutOfMemoryErrors */ byte[] memoryReserve; private static Logger initLogging(Config conf) { LogManager.init(conf); return getLogger("gov.nasa.jpf"); } /** * use this one to get a Logger that is initialized via our Config mechanism. Note that * our own Loggers do NOT pass */ public static JPFLogger getLogger (String name) { return LogManager.getLogger( name); } public static void main(String[] args){ int options = RunJPF.getOptions(args); if (args.length == 0 || RunJPF.isOptionEnabled( RunJPF.HELP,options)) { RunJPF.showUsage(); return; } if (RunJPF.isOptionEnabled( RunJPF.ADD_PROJECT,options)){ RunJPF.addProject(args); return; } if (RunJPF.isOptionEnabled( RunJPF.BUILD_INFO,options)){ RunJPF.showBuild(RunJPF.class.getClassLoader()); } if (RunJPF.isOptionEnabled( RunJPF.LOG,options)){ Config.enableLogging(true); } Config conf = createConfig(args); if (RunJPF.isOptionEnabled( RunJPF.SHOW, options)) { conf.printEntries(); } start(conf, args); } public static void start(Config conf, String[] args){ // this is redundant to jpf.report.<publisher>.start=..config.. // but nobody can remember this (it's only used to produce complete reports) if (logger == null) { logger = initLogging(conf); } if (!checkArgs(args)){ return; } setNativeClassPath(conf); // in case we have to find a shell // check if there is a shell class specification, in which case we just delegate JPFShell shell = conf.getInstance("shell", JPFShell.class); if (shell != null) { shell.start(args); // responsible for exception handling itself } else { // no shell, we start JPF directly LogManager.printStatus(logger); conf.printStatus(logger); // this has to be done after we checked&consumed all "-.." arguments // this is NOT about checking properties! checkUnknownArgs(args); try { JPF jpf = new JPF(conf); jpf.run(); } catch (ExitException x) { logger.severe( "JPF terminated"); // this is how we get most runtime config exceptions if (x.shouldReport()) { x.printStackTrace(); } /** Throwable cause = x.getCause(); if ((cause != null) && conf.getBoolean("pass_exceptions", false)) { cause.fillInStackTrace(); throw cause; } **/ } catch (JPFException jx) { logger.severe( "JPF exception, terminating: " + jx.getMessage()); if (conf.getBoolean("jpf.print_exception_stack")) { Throwable cause = jx.getCause(); if (cause != null && cause != jx){ cause.printStackTrace(); } else { jx.printStackTrace(); } } // pass this on, caller has to handle throw jx; } } } static void setNativeClassPath(Config config) { if (!config.hasSetClassLoader()) { config.initClassLoader( JPF.class.getClassLoader()); } } protected JPF (){ // just to support unit test mockups } /** * create new JPF object. Note this is always guaranteed to return, but the * Search and/or VM object instantiation might have failed (i.e. the JPF * object might not be really usable). If you directly use getSearch() / getVM(), * check for null */ public JPF(Config conf) { config = conf; setNativeClassPath(config); // before we do anything else if (logger == null) { // maybe somebody created a JPF object explicitly logger = initLogging(config); } initialize(); } /** * convenience method if caller doesn't care about Config */ public JPF (String ... args) { this( createConfig(args)); } private void initialize() { VERSION = config.getString("jpf.version", VERSION); memoryReserve = new byte[config.getInt("jpf.memory_reserve", 64 * 1024)]; // in bytes try { Class<?>[] vmArgTypes = { JPF.class, Config.class }; Object[] vmArgs = { this, config }; vm = config.getEssentialInstance(ConfigConstants.VM_CLASS, VM.class, vmArgTypes, vmArgs); Class<?>[] searchArgTypes = { Config.class, VM.class }; Object[] searchArgs = { config, vm }; search = config.getEssentialInstance("search.class", Search.class, searchArgTypes, searchArgs); // although the Reporter will always be notified last, this has to be set // first so that it can register utility listeners like Statistics that // can be used by configured listeners Class<?>[] reporterArgTypes = { Config.class, JPF.class }; Object[] reporterArgs = { config, this }; reporter = config.getInstance("report.class", Reporter.class, reporterArgTypes, reporterArgs); if (reporter != null){ search.setReporter(reporter); } addListeners(); config.addChangeListener(new ConfigListener()); } catch (JPFConfigException cx) { logger.severe(cx.toString()); //cx.getCause().printStackTrace(); throw new ExitException(false, cx); } } public Status getStatus() { return status; } public boolean isRunnable () { return ((vm != null) && (search != null)); } public void addPropertyListener (PropertyListenerAdapter pl) { if (vm != null) { vm.addListener( pl); } if (search != null) { search.addListener( pl); search.addProperty(pl); } } public void addSearchListener (SearchListener l) { if (search != null) { search.addListener(l); } } protected void addPendingVMListener (VMListener l){ if (pendingVMListeners == null){ pendingVMListeners = new ArrayList<VMListener>(); } pendingVMListeners.add(l); } protected void addPendingSearchListener (SearchListener l){ if (pendingSearchListeners == null){ pendingSearchListeners = new ArrayList<SearchListener>(); } pendingSearchListeners.add(l); } public void addListener (JPFListener l) { // the VM is instantiated first if (l instanceof VMListener) { if (vm != null) { vm.addListener( (VMListener) l); } else { // no VM yet, we are in VM initialization addPendingVMListener((VMListener)l); } } if (l instanceof SearchListener) { if (search != null) { search.addListener( (SearchListener) l); } else { // no search yet, we are in Search initialization addPendingSearchListener((SearchListener)l); } } } public <T> T getListenerOfType( Class<T> type){ if (search != null){ T listener = search.getNextListenerOfType(type, null); if (listener != null){ return listener; } } if (vm != null){ T listener = vm.getNextListenerOfType(type, null); if (listener != null){ return listener; } } return null; } public boolean addUniqueTypeListener (JPFListener l) { boolean addedListener = false; Class<?> cls = l.getClass(); if (l instanceof VMListener) { if (vm != null) { if (!vm.hasListenerOfType(cls)) { vm.addListener( (VMListener) l); addedListener = true; } } } if (l instanceof SearchListener) { if (search != null) { if (!search.hasListenerOfType(cls)) { search.addListener( (SearchListener) l); addedListener = true; } } } return addedListener; } public void removeListener (JPFListener l){ if (l instanceof VMListener) { if (vm != null) { vm.removeListener( (VMListener) l); } } if (l instanceof SearchListener) { if (search != null) { search.removeListener( (SearchListener) l); } } } public void addVMListener (VMListener l) { if (vm != null) { vm.addListener(l); } } public void addSearchProperty (Property p) { if (search != null) { search.addProperty(p); } } /** * this is called after vm, search and reporter got instantiated */ void addListeners () { Class<?>[] argTypes = { Config.class, JPF.class }; Object[] args = { config, this }; // first listeners that were automatically added from VM, Search and Reporter initialization if (pendingVMListeners != null){ for (VMListener l : pendingVMListeners) { vm.addListener(l); } pendingVMListeners = null; } if (pendingSearchListeners != null){ for (SearchListener l : pendingSearchListeners) { search.addListener(l); } pendingSearchListeners = null; } // and finally everything that's user configured List<JPFListener> listeners = config.getInstances("listener", JPFListener.class, argTypes, args); if (listeners != null) { for (JPFListener l : listeners) { addListener(l); } } } public Reporter getReporter () { return reporter; } public <T extends Publisher> boolean addPublisherExtension (Class<T> pCls, PublisherExtension e) { if (reporter != null) { return reporter.addPublisherExtension(pCls, e); } return false; } public <T extends Publisher> void setPublisherItems (Class<T> pCls, int category, String[] topics) { if (reporter != null) { reporter.setPublisherItems(pCls, category, topics); } } public Config getConfig() { return config; } /** * return the search object. This can be null if the initialization has failed */ public Search getSearch() { return search; } /** * return the VM object. This can be null if the initialization has failed */ public VM getVM() { return vm; } public static void exit() { // Hmm, exception as non local return. But we might be called from a // context we don't want to kill throw new ExitException(); } public boolean foundErrors() { return !(search.getErrors().isEmpty()); } /** * this assumes that we have checked and 'consumed' (nullified) all known * options, so we just have to check for any '-' option prior to the * target class name */ static void checkUnknownArgs (String[] args) { for ( int i=0; i<args.length; i++) { if (args[i] != null) { if (args[i].charAt(0) == '-') { logger.warning("unknown command line option: " + args[i]); } else { // this is supposed to be the target class name - everything that follows // is supposed to be processed by the program under test break; } } } } public static void printBanner (Config config) { System.out.println("Java Pathfinder core system v" + config.getString("jpf.version", VERSION) + " - (C) 2005-2014 United States Government. All rights reserved."); } /** * find the value of an arg that is either specific as * "-key=value" or as "-key value". If not found, the supplied * defValue is returned */ static String getArg(String[] args, String pattern, String defValue, boolean consume) { String s = defValue; if (args != null){ for (int i = 0; i < args.length; i++) { String arg = args[i]; if (arg != null) { if (arg.matches(pattern)) { int idx=arg.indexOf('='); if (idx > 0) { s = arg.substring(idx+1); if (consume) { args[i]=null; } } else if (i < args.length-1) { s = args[i+1]; if (consume) { args[i] = null; args[i+1] = null; } } break; } } } } return s; } /** * what property file to look for */ static String getConfigFileName (String[] args) { if (args.length > 0) { // check if the last arg is a mode property file // if yes, it has to include a 'target' spec int idx = args.length-1; String lastArg = args[idx]; if (lastArg.endsWith(".jpf") || lastArg.endsWith(".properties")) { if (lastArg.startsWith("-c")) { int i = lastArg.indexOf('='); if (i > 0) { lastArg = lastArg.substring(i+1); } } args[idx] = null; return lastArg; } } return getArg(args, "-c(onfig)?(=.+)?", "jpf.properties", true); } /** * return a Config object that holds the JPF options. This first * loads the properties from a (potentially configured) properties file, and * then overlays all command line arguments that are key/value pairs */ public static Config createConfig (String[] args) { return new Config(args); } /** * runs the verification. */ @Override public void run() { Runtime rt = Runtime.getRuntime(); // this might be executed consecutively, so notify everybody RunRegistry.getDefaultRegistry().reset(); if (isRunnable()) { try { if (vm.initialize()) { status = Status.RUNNING; search.search(); } } catch (OutOfMemoryError oom) { // try to get memory back before we do anything that makes it worse // (note that we even try to avoid calls here, we are on thin ice) // NOTE - we don't try to recover at this point (that is what we do // if we fall below search.min_free within search()), we only want to // terminate gracefully (incl. report) memoryReserve = null; // release something long m0 = rt.freeMemory(); long d = 10000; // see if we can reclaim some memory before logging or printing statistics for (int i=0; i<10; i++) { rt.gc(); long m1 = rt.freeMemory(); if ((m1 <= m0) || ((m1 - m0) < d)) { break; } m0 = m1; } logger.severe("JPF out of memory"); // that's questionable, but we might want to see statistics / coverage // to know how far we got. We don't inform any other listeners though // if it throws an exception we bail - we can't handle it w/o memory try { search.notifySearchConstraintHit("JPF out of memory"); search.error(new NoOutOfMemoryErrorProperty()); // JUnit tests will succeed if OOM isn't flagged. reporter.searchFinished(search); } catch (Throwable t){ throw new JPFListenerException("exception during out-of-memory termination", t); } // NOTE - this is not an exception firewall anymore } finally { status = Status.DONE; config.jpfRunTerminated(); cleanUp(); } } } protected void cleanUp(){ search.cleanUp(); vm.cleanUp(); reporter.cleanUp(); } public List<Error> getSearchErrors () { if (search != null) { return search.getErrors(); } return null; } public Error getLastError () { if (search != null) { return search.getLastError(); } return null; } // some minimal sanity checks static boolean checkArgs (String[] args){ String lastArg = args[args.length-1]; if (lastArg != null && lastArg.endsWith(".jpf")){ if (!new File(lastArg).isFile()){ logger.severe("application property file not found: " + lastArg); return false; } } return true; } public static void handleException(JPFException e) { logger.severe(e.getMessage()); exit(); } /** * private helper class for local termination of JPF (without killing the * whole Java process via System.exit). * While this is basically a bad non-local goto exception, it seems to be the * least of evils given the current JPF structure, and the need to terminate * w/o exiting the whole Java process. If we just do a System.exit(), we couldn't * use JPF in an embedded context */ @SuppressWarnings("serial") public static class ExitException extends RuntimeException { boolean report = true; ExitException() {} ExitException (boolean report, Throwable cause){ super(cause); this.report = report; } ExitException(String msg) { super(msg); } public boolean shouldReport() { return report; } } }
{ "content_hash": "1a56fd45b2bfc684c875874071bd437b", "timestamp": "", "source": "github", "line_count": 715, "max_line_length": 118, "avg_line_length": 27.66993006993007, "alnum_prop": 0.6006368782854832, "repo_name": "grzesuav/gjpf-core", "id": "5fa12cda453a25617958b692448c51187ba70319", "size": "20569", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "main/src/main/java/gov/nasa/jpf/JPF.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Batchfile", "bytes": "611" }, { "name": "Java", "bytes": "5194287" }, { "name": "Shell", "bytes": "982" } ], "symlink_target": "" }
"use strict" var keys = require('keys'); var actionTypes = keys({ CHANGE_PAGE: null, START_ADD_TASK: null, STOP_ADD_TASK: null, SET_ADDITION_TASK_PRIORITY: null, SET_ADDITION_TASK_DATE: null, SET_ADDITION_TASK_TITLE: null, CHANGE_QUICK_ADD_BLOCK: null, SAVING_ADDITION_TASK: null, SAVED_TASK: null, PUT_TASKS_PACK: null, TASK_UPDATED: null }); module.exports = actionTypes;
{ "content_hash": "978c506b12ae177e6c5fa7a444b31294", "timestamp": "", "source": "github", "line_count": 19, "max_line_length": 37, "avg_line_length": 22.157894736842106, "alnum_prop": 0.6579572446555819, "repo_name": "atomiomi/clavy", "id": "3304bb4a5f6942cb7141462f0c336e9f0716abd4", "size": "421", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "client/js/constants/actionTypes.js", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "32128" }, { "name": "HTML", "bytes": "206" }, { "name": "JavaScript", "bytes": "1050595" } ], "symlink_target": "" }
from .reactors import get_reactor from .protocols import StreamProtocol, ProcessProtocol from .utils import Deferred, monadic from . import utils
{ "content_hash": "4c0ce67a5b3f7b9e9a1723f49d9b898e", "timestamp": "", "source": "github", "line_count": 5, "max_line_length": 54, "avg_line_length": 29.4, "alnum_prop": 0.8231292517006803, "repo_name": "tomerfiliba/tangled", "id": "4bed2c0088095e509d59c376c5ae3bff8d222ad2", "size": "147", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "__init__.py", "mode": "33188", "license": "mit", "language": [ { "name": "Python", "bytes": "36178" } ], "symlink_target": "" }
//fs is to manage file from the fileSystem var fs = require('fs'); /* Tasty code will contains a map of instructions with their parameters and corresponding code line. its is mapped by the full instruction line example : { 'my instructions with $oneParame or $moreParameters' : { parameters : [ '$oneParame', '$moreParameters'], codeLines : [ 'driver.doSomething(), 'myOtherCustom instruction $oneParam', 'driver.doSomethingElse($moreParameters)' ] } } */ var tastyCode = []; exports.addPluginFile=function(filePath, callback){ fs.readFile(filePath, 'utf8', function (err,data) { if (err) { console.log(err); }else { tastyCode = _extractTastyCode(data.split('\n')); } callback(); }); }; exports.getTastyCode=function(){ return tastyCode; }; exports.toSeleniumCode=function(tastyScriptLinesArray){ var seleniumCode = []; for(var i=0;i<tastyScriptLinesArray.length;i++){ var tastyLine = tastyScriptLinesArray[i].trim(); seleniumCode = seleniumCode.concat( _getSeleniumCodeFrom(tastyLine)); } return seleniumCode.join('\n'); }; _getSeleniumCodeFrom=function(tastyLine){ for (var instruction in tastyCode) { var isMatching = tastyLine.match(new RegExp(tastyCode[instruction].regexMatcher)); if(isMatching){ var seleniumCode = []; var codeLines = tastyCode[instruction].codeLines; for(var i=0;i<codeLines.length;i++){ var codeLine = _replaceTastyParameters(codeLines[i], tastyCode[instruction].parameters ,isMatching); seleniumCode.push(codeLine); } return seleniumCode; } } }; _replaceTastyParameters=function(codeLine, parametersArray, matcherArray){ for(var i=0;i<parametersArray.length;i++){ codeLine = codeLine.replace(parametersArray[i], "'"+matcherArray[i+1]+"'"); } return codeLine; }; _extractTastyCode=function(fileLinesArray){ var instructions = []; var currentInstruction; var currentParameters; var currentCodeLines = []; var currentRegexMatcher; var instructionStarted for(var i=0;i<fileLinesArray.length;i++){ var line = fileLinesArray[i].trim(); if(line.endsWith('*{')){ currentInstruction = line.substring(0, line.length-2).trim(); currentParameters = currentInstruction.match(/\$\w*/gi); currentRegexMatcher = '^' + currentInstruction.replace(new RegExp('\\'+currentParameters.join('|\\'), 'g'), '(.*)'); currentCodeLines = []; }else if(line.startsWith('}*')){ instructions[currentInstruction] = { 'parameters' : currentParameters, 'codeLines' : currentCodeLines, 'regexMatcher' : currentRegexMatcher }; }else if(line){ currentCodeLines.push(line); } } return instructions; }; // console.log("instructions ->"+ instructions[currentInstruction].parameters); // instructions[currentInstruction].codeLines.map(function(value){ // console.log("value ->"+value); // }); // for (var key in instructions) { // console.log("key ->"+key); // }
{ "content_hash": "5bb097a3116113abf2b4fd86d221fcdc", "timestamp": "", "source": "github", "line_count": 103, "max_line_length": 128, "avg_line_length": 32.1747572815534, "alnum_prop": 0.616173808086904, "repo_name": "stalina/tasty", "id": "7016bfcf89d3022ff32915923e98eef30c1b0122", "size": "3314", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "app/lib/tasty-analyser.js", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "CSS", "bytes": "592" }, { "name": "HTML", "bytes": "457" }, { "name": "JavaScript", "bytes": "10725" } ], "symlink_target": "" }
import re from abc import abstractmethod, ABC from itertools import groupby, zip_longest from functools import reduce from contextlib import closing from django.db.models import Q from django.db import transaction MONTH_TYPE_RE = re.compile(r"^M\d{2}$") PERIOD_CODE_RE = re.compile( r"^(?P<year>\d{4})" r"(?P<type>IBY1|IBY2|ADJB|ORGB|AUDA|PAUD|ITY1|ITY2|TABB|TRFR|SCHD)?" r"(M(?P<month>\d{2}))?$" ) def group_rows(rows, size): args = [iter(rows)] * size return zip_longest(*args) def period_code_details(code): match = PERIOD_CODE_RE.match(code) if match: details = match.groupdict() return ( details["year"], details["type"] or "ACT", "month" if details["month"] else "year", details["month"] or details["year"], ) else: return None def all_to_code_dict(model): return dict(map( lambda o: (o.code, o), model.objects.all(), )) def build_unique_query_params_with_period(rows): keys = set( map( lambda o: o[0], groupby( filter(None, rows), lambda o: (o.demarcation_code, o.period_code) ), ) ) query_params = map( lambda k: Q(demarcation_code=k[0]) & Q(period_code=k[1]), keys, ) query_params = reduce( lambda r, q: r | q, query_params, Q(), ) return query_params def build_unique_query_params_with_year(rows): keys = set( map( lambda o: o[0], groupby( filter(None, rows), lambda o: (o.demarcation_code, o.financial_year) ), ) ) query_params = map( lambda k: Q(demarcation_code=k[0]) & Q(financial_year=k[1]), keys, ) query_params = reduce( lambda r, q: r | q, query_params, Q(), ) return query_params def build_unique_query_params_with_role(rows): keys = set( map( lambda o: o[0], groupby( filter(None, rows), lambda o: (o.demarcation_code, o.role) ), ) ) query_params = map( lambda k: Q(demarcation_code=k[0]) & Q(role=k[1]), keys, ) query_params = reduce( lambda r, q: r | q, query_params, Q(), ) return query_params class Updater(ABC): facts_cls = None reader_cls = None references_cls = {} def __init__(self, update_obj, batch_size): cls = self.__class__ self.update_obj = update_obj self.batch_size = batch_size self.references = dict( map( lambda o: (o[0], all_to_code_dict(o[1])), cls.references_cls.items(), ) ) @abstractmethod def row_to_obj(self, row): pass @abstractmethod def build_unique_query(self, rows): pass def update(self): cls = self.__class__ with transaction.atomic(): # Delete the existing matching records self.update_obj.deleted = 0 self.update_obj.file.open('r') with closing(self.update_obj.file) as file: lines = iter(file) next(lines) # Skip header reader = cls.reader_cls(lines) for rows in group_rows(reader, self.batch_size): count, _ = cls.facts_cls.objects.filter( self.build_unique_query(rows) ).delete() self.update_obj.deleted += count # Add the records from the dataset self.update_obj.inserted = 0 self.update_obj.file.open('r') with closing(self.update_obj.file) as file: lines = iter(file) next(lines) # Skip header reader = cls.reader_cls(lines) for rows in group_rows(reader, self.batch_size): objects = map( self.row_to_obj, filter(None, rows), ) objects = cls.facts_cls.objects.bulk_create(objects) self.update_obj.inserted += len(objects) # Save the status of the update self.update_obj.save()
{ "content_hash": "1cfd75d4993959b8e21b5734080ed2c2", "timestamp": "", "source": "github", "line_count": 167, "max_line_length": 72, "avg_line_length": 26.221556886227546, "alnum_prop": 0.5060516099566111, "repo_name": "Code4SA/municipal-data", "id": "64da6b7d6817cc91b25ea45fe41b61920bf1538a", "size": "4379", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "municipal_finance/update/utils.py", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "172224" }, { "name": "HTML", "bytes": "166174" }, { "name": "JavaScript", "bytes": "466942" }, { "name": "PLpgSQL", "bytes": "23056" }, { "name": "Python", "bytes": "215064" }, { "name": "Shell", "bytes": "905" } ], "symlink_target": "" }
var crypto = require('crypto'); var config = require('./../appconfig').Config; /** * Sign taobao api for JSSDK`. * * @param {appkey} Key * @param {appsecret} Secret * @api public */ var Sign = function (appkey,appsecret) { var timestamp = new Date().getTime(); var message = appsecret + "app_key" + appkey + "timestamp" + timestamp + appsecret; var sign = SignByHmacMd5(message, appsecret); return{ timestamp:timestamp, sign:sign } } var SignByHmacMd5 = function (message, secret) { var hmac = crypto.createHmac("md5", secret); var result= hmac.update(message).digest('hex'); result=result.toUpperCase(); return result; } exports.SignTaobao=Sign; exports.SignByHmacMd5=SignByHmacMd5;
{ "content_hash": "fd528111e6308bd2a284ba518744cef4", "timestamp": "", "source": "github", "line_count": 30, "max_line_length": 87, "avg_line_length": 24.833333333333332, "alnum_prop": 0.6604026845637584, "repo_name": "JerroldLee/tbCusMkt", "id": "92eb003089872d3b6292d6c6c54b938a01e018b9", "size": "745", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "backup/util/sign.js", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "108320" }, { "name": "JavaScript", "bytes": "659669" } ], "symlink_target": "" }
ACCEPTED #### According to International Plant Names Index #### Published in null #### Original name null ### Remarks null
{ "content_hash": "11d1a355f94a337b1bf427b6b2fb2301", "timestamp": "", "source": "github", "line_count": 13, "max_line_length": 31, "avg_line_length": 9.692307692307692, "alnum_prop": 0.7063492063492064, "repo_name": "mdoering/backbone", "id": "594e5d1cb85d32d7ceee3c0fb1fa417328fa820f", "size": "179", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "life/Plantae/Magnoliophyta/Magnoliopsida/Malvales/Thymelaeaceae/Struthiola/Struthiola albersii/README.md", "mode": "33188", "license": "apache-2.0", "language": [], "symlink_target": "" }
<?php namespace Google\Service\CloudSearch; class PrivateMessageInfo extends \Google\Collection { protected $collection_key = 'gsuiteIntegrationMetadata'; protected $annotationsType = Annotation::class; protected $annotationsDataType = 'array'; protected $attachmentsType = Attachment::class; protected $attachmentsDataType = 'array'; protected $contextualAddOnMarkupType = GoogleChatV1ContextualAddOnMarkup::class; protected $contextualAddOnMarkupDataType = 'array'; protected $gsuiteIntegrationMetadataType = GsuiteIntegrationMetadata::class; protected $gsuiteIntegrationMetadataDataType = 'array'; /** * @var string */ public $text; protected $userIdType = UserId::class; protected $userIdDataType = ''; /** * @param Annotation[] */ public function setAnnotations($annotations) { $this->annotations = $annotations; } /** * @return Annotation[] */ public function getAnnotations() { return $this->annotations; } /** * @param Attachment[] */ public function setAttachments($attachments) { $this->attachments = $attachments; } /** * @return Attachment[] */ public function getAttachments() { return $this->attachments; } /** * @param GoogleChatV1ContextualAddOnMarkup[] */ public function setContextualAddOnMarkup($contextualAddOnMarkup) { $this->contextualAddOnMarkup = $contextualAddOnMarkup; } /** * @return GoogleChatV1ContextualAddOnMarkup[] */ public function getContextualAddOnMarkup() { return $this->contextualAddOnMarkup; } /** * @param GsuiteIntegrationMetadata[] */ public function setGsuiteIntegrationMetadata($gsuiteIntegrationMetadata) { $this->gsuiteIntegrationMetadata = $gsuiteIntegrationMetadata; } /** * @return GsuiteIntegrationMetadata[] */ public function getGsuiteIntegrationMetadata() { return $this->gsuiteIntegrationMetadata; } /** * @param string */ public function setText($text) { $this->text = $text; } /** * @return string */ public function getText() { return $this->text; } /** * @param UserId */ public function setUserId(UserId $userId) { $this->userId = $userId; } /** * @return UserId */ public function getUserId() { return $this->userId; } } // Adding a class alias for backwards compatibility with the previous class name. class_alias(PrivateMessageInfo::class, 'Google_Service_CloudSearch_PrivateMessageInfo');
{ "content_hash": "b19234ca59175992c3a0db5ef398403d", "timestamp": "", "source": "github", "line_count": 111, "max_line_length": 88, "avg_line_length": 22.576576576576578, "alnum_prop": 0.6879489225857941, "repo_name": "googleapis/google-api-php-client-services", "id": "ca297a1e082d1b15c1a37812b81e1e997b732ff2", "size": "3096", "binary": false, "copies": "2", "ref": "refs/heads/main", "path": "src/CloudSearch/PrivateMessageInfo.php", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "PHP", "bytes": "55414116" }, { "name": "Python", "bytes": "427325" }, { "name": "Shell", "bytes": "787" } ], "symlink_target": "" }
const Backbone = require('backbone') const buttonModel = Backbone.Model.extend({ url: "", initialize:function(){ }, }) const buttonCollection = Backbone.Collection.extend({ model: buttonModel, url: "" , initialize:function(theToken){ this.url = "https://api.meetup.com/2/concierge/?access_token=" + theToken + "" }, sync:function(method, collection, options){ options.dataType="jsonp"; return Backbone.sync(method,collection,options); } }) const button3Coll = Backbone.Collection.extend({ model: buttonModel, url: "" , initialize:function(theToken){ this.url = "https://api.meetup.com/2/categories/?access_token=" + theToken + "" }, sync:function(method, collection, options){ options.dataType="jsonp"; return Backbone.sync(method,collection,options); } }) const button4Coll = Backbone.Collection.extend({ model: buttonModel, url: "" , initialize:function(theToken){ this.url = "https://api.meetup.com/find/events/?access_token=" + theToken + "" }, sync:function(method, collection, options){ options.dataType="jsonp"; return Backbone.sync(method,collection,options); } }) module.exports = {buttonModel, buttonCollection, button3Coll, button4Coll}
{ "content_hash": "2b3de9a0e957295a24e9e66a0c79d422", "timestamp": "", "source": "github", "line_count": 53, "max_line_length": 85, "avg_line_length": 24.28301886792453, "alnum_prop": 0.6635586635586636, "repo_name": "Vicula/CliqueUp", "id": "4b2de3698165bff41fea1d7ae30f17e84600e3a5", "size": "1287", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "src-client/scripts/Button-Colls.js", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "6550" }, { "name": "HTML", "bytes": "2357" }, { "name": "Java", "bytes": "38290" }, { "name": "JavaScript", "bytes": "3140241" }, { "name": "Shell", "bytes": "133" } ], "symlink_target": "" }
module OandaAPI module Streaming # Resource URI templates BASE_URI = { live: "https://stream-fxtrade.oanda.com/[API_VERSION]", practice: "https://stream-fxpractice.oanda.com/[API_VERSION]" } # @example Example Usage # client = OandaAPI::Streaming::Client.new :practice, ENV.fetch("ONADA_PRACTICE_TOKEN") # # # IMPORTANT # # This code will block indefinitely because streaming executes as an infinite loop. # prices = client.prices(account_id: 1234, instruments: %w[AUD_CAD AUD_CHF]) # prices.stream do |price| # # # The code in this block should handle the price as efficently # # as possible, otherwise the connection could timeout. # # For example, you could publish the tick on a queue to be handled # # by some other thread or process. # price # => OandaAPI::Resource::Price # end # # client.events.stream do |transaction| # transaction # => OandaAPI::Resource::Transaction # end # # # -- Stopping the stream -- # # You may add a second argument to the block to yield the client itself. # # You can use it to issue a client.stop! to terminate streaming. # @prices = [] # prices = client.prices(account_id: 1234, instruments: %w[AUD_CAD AUD_CHF]) # prices.stream do |price, client| # @prices << price # client.stop! if @prices.size == 10 # end # # @!attribute [r] auth_token # @return [String] Oanda personal access token. # # @!attribute [r] streaming_request # @return [OandaAPI::Streaming::Request] # # @!attribute [rw] domain # @return [Symbol] identifies the Oanda subdomain (`:practice` or `:live`) # accessed by the client. # # @!attribute [rw] headers # @return [Hash] parameters that are included with every API request # as HTTP headers. class Client attr_reader :auth_token, :streaming_request attr_accessor :domain, :headers # @param [Symbol] domain see {#domain} # @param [String] auth_token see {#auth_token} def initialize(domain, auth_token) super() @auth_token = auth_token self.domain = domain @headers = auth @streaming_request = nil end # Returns an absolute URI for a resource request. # # @param [String] path the path portion of the URI. # # @return [String] a URI. def api_uri(path) uri = "#{BASE_URI[domain]}#{path}" uri.sub "[API_VERSION]", OandaAPI.configuration.rest_api_version end # Parameters used for authentication. # @return [Hash] def auth { "Authorization" => "Bearer #{auth_token}" } end # @private # Sets the domain the client can access. # @return [void] def domain=(value) fail ArgumentError, "Invalid domain" unless OandaAPI::DOMAINS.include? value @domain = value end # Determines whether emitted resources should include heartbeats. # @param [boolean] value def emit_heartbeats=(value) @emit_heartbeats = value streaming_request.emit_heartbeats = value if streaming_request end # Returns `true` if emitted resources include heartbeats. Defaults to false. # @return [boolean] def emit_heartbeats? !!@emit_heartbeats end # Signals the streaming request to disconnect and terminates streaming. # @return [void] def stop! streaming_request.stop! if running? end # Returns `true` if the client is currently streaming. # @return [boolean] def running? !!(streaming_request && streaming_request.running?) end # @private # Executes a streaming http request. # # @param [Symbol] _method Ignored. # # @param [String] path the path of an Oanda resource request. # # @param [Hash] conditions optional parameters that are converted into query parameters. # # @yield [OandaAPI:ResourceBase, OandaAPI::Streaming::Client] See {OandaAPI::Streaming::Request.stream} # # @return [void] # # @raise [OandaAPI::RequestError] if the API return code is not 2xx. # @raise [OandaAPI::StreamingDisconnect] if the API disconnects. def execute_request(_method, path, conditions = {}, &block) Http::Exceptions.wrap_and_check do @streaming_request = OandaAPI::Streaming::Request.new client: self, uri: api_uri(path), query: Utils.stringify_keys(conditions), headers: OandaAPI.configuration.headers.merge(headers) @streaming_request.stream(&block) return nil end rescue Http::Exceptions::HttpException => e raise OandaAPI::RequestError, e.message end private # @private # Enables method-chaining. # @return [OandaAPI::Client::NamespaceProxy] def method_missing(sym, *args) OandaAPI::Client::NamespaceProxy.new self, sym, args.first end end end end
{ "content_hash": "b5bb326c39f3e1bee222c30a2586a45d", "timestamp": "", "source": "github", "line_count": 153, "max_line_length": 118, "avg_line_length": 34.72549019607843, "alnum_prop": 0.5928853754940712, "repo_name": "bewon/oanda_api", "id": "db0e5bb6a04cfb1aa169b1f8e769dd03e7bcfa57", "size": "5313", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "lib/oanda_api/streaming/client.rb", "mode": "33188", "license": "mit", "language": [ { "name": "Ruby", "bytes": "114186" } ], "symlink_target": "" }
/* * pmembench.c -- main source file for benchmark framework */ #include <stdio.h> #include <string.h> #include <err.h> #include <assert.h> #include <getopt.h> #include <unistd.h> #include <math.h> #include <float.h> #include <sys/queue.h> #include <linux/limits.h> #include <dirent.h> #include "benchmark.h" #include "benchmark_worker.h" #include "scenario.h" #include "clo_vec.h" #include "clo.h" #include "config_reader.h" /* * struct pmembench -- main context */ struct pmembench { int argc; char **argv; struct scenario *scenario; struct clo_vec *clovec; bool override_clos; }; /* * struct benchmark -- benchmark's context */ struct benchmark { LIST_ENTRY(benchmark) next; struct benchmark_info *info; void *priv; struct benchmark_clo *clos; size_t nclos; size_t args_size; }; /* * struct results -- statistics for total measurements */ struct results { double min; double max; double avg; double std_dev; double med; }; /* * struct latency -- statistics for latency measurements */ struct latency { uint64_t max; uint64_t min; uint64_t avg; double std_dev; }; /* * struct bench_list -- list of available benchmarks */ struct bench_list { LIST_HEAD(benchmarks_head, benchmark) head; bool initialized; }; /* * struct benchmark_opts -- arguments for pmembench */ struct benchmark_opts { bool help; bool version; const char *file_name; }; static struct version_s { unsigned int major; unsigned int minor; } version = {1, 0}; /* benchmarks list initialization */ static struct bench_list benchmarks = { .initialized = false, }; /* list of arguments for pmembench */ static struct benchmark_clo pmembench_opts[] = { { .opt_short = 'h', .opt_long = "help", .descr = "Print help", .type = CLO_TYPE_FLAG, .off = clo_field_offset(struct benchmark_opts, help), .ignore_in_res = true, }, { .opt_short = 'v', .opt_long = "version", .descr = "Print version", .type = CLO_TYPE_FLAG, .off = clo_field_offset(struct benchmark_opts, version), .ignore_in_res = true, }, }; /* common arguments for benchmarks */ static struct benchmark_clo pmembench_clos[] = { { .opt_short = 'h', .opt_long = "help", .descr = "Print help for single benchmark", .type = CLO_TYPE_FLAG, .off = clo_field_offset(struct benchmark_args, help), .ignore_in_res = true, }, { .opt_short = 't', .opt_long = "threads", .type = CLO_TYPE_UINT, .descr = "Number of working threads", .off = clo_field_offset(struct benchmark_args, n_threads), .def = "1", .type_uint = { .size = clo_field_size(struct benchmark_args, n_threads), .base = CLO_INT_BASE_DEC, .min = 1, .max = 32, }, }, { .opt_short = 'n', .opt_long = "ops-per-thread", .type = CLO_TYPE_UINT, .descr = "Number of operations per thread", .off = clo_field_offset(struct benchmark_args, n_ops_per_thread), .def = "1", .type_uint = { .size = clo_field_size(struct benchmark_args, n_ops_per_thread), .base = CLO_INT_BASE_DEC, .min = 1, .max = ULLONG_MAX, }, }, { .opt_short = 'd', .opt_long = "data-size", .type = CLO_TYPE_UINT, .descr = "IO data size", .off = clo_field_offset(struct benchmark_args, dsize), .def = "1", .type_uint = { .size = clo_field_size(struct benchmark_args, dsize), .base = CLO_INT_BASE_DEC|CLO_INT_BASE_HEX, .min = 1, .max = ULONG_MAX, }, }, { .opt_short = 'f', .opt_long = "file", .type = CLO_TYPE_STR, .descr = "File name", .off = clo_field_offset(struct benchmark_args, fname), .def = "/mnt/pmem/testfile", .ignore_in_res = true, }, { .opt_short = 'm', .opt_long = "fmode", .type = CLO_TYPE_UINT, .descr = "File mode", .off = clo_field_offset(struct benchmark_args, fmode), .def = "0666", .ignore_in_res = true, .type_uint = { .size = clo_field_size(struct benchmark_args, fmode), .base = CLO_INT_BASE_OCT, .min = 0, .max = ULONG_MAX, }, }, { .opt_short = 's', .opt_long = "seed", .type = CLO_TYPE_UINT, .descr = "PRNG seed", .off = clo_field_offset(struct benchmark_args, seed), .def = "0", .type_uint = { .size = clo_field_size(struct benchmark_args, seed), .base = CLO_INT_BASE_DEC, .min = 0, .max = ~0, }, }, { .opt_short = 'r', .opt_long = "repeats", .type = CLO_TYPE_UINT, .descr = "Number of repeats of scenario", .off = clo_field_offset(struct benchmark_args, repeats), .def = "1", .type_uint = { .size = clo_field_size(struct benchmark_args, repeats), .base = CLO_INT_BASE_DEC|CLO_INT_BASE_HEX, .min = 1, .max = ULONG_MAX, }, }, }; /* * pmembench_get_priv -- return private structure of benchmark */ void * pmembench_get_priv(struct benchmark *bench) { return bench->priv; } /* * pmembench_set_priv -- set private structure of benchmark */ void pmembench_set_priv(struct benchmark *bench, void *priv) { bench->priv = priv; } /* * pmembench_register -- register benchmark */ int pmembench_register(struct benchmark_info *bench_info) { struct benchmark *bench = calloc(1, sizeof (*bench)); assert(bench != NULL); bench->info = bench_info; if (!benchmarks.initialized) { LIST_INIT(&benchmarks.head); benchmarks.initialized = true; } LIST_INSERT_HEAD(&benchmarks.head, bench, next); return 0; } /* * pmembench_get_info -- return structure with information about benchmark */ struct benchmark_info * pmembench_get_info(struct benchmark *bench) { return bench->info; } /* * pmembench_release_clos -- release CLO structure */ static void pmembench_release_clos(struct benchmark *bench) { free(bench->clos); } /* * pmembench_merge_clos -- merge benchmark's CLOs with common CLOs */ static void pmembench_merge_clos(struct benchmark *bench) { size_t size = sizeof (struct benchmark_args); size_t pb_nclos = ARRAY_SIZE(pmembench_clos); size_t nclos = pb_nclos; size_t i; if (bench->info->clos) { size += bench->info->opts_size; nclos += bench->info->nclos; } struct benchmark_clo *clos = calloc(nclos, sizeof (struct benchmark_clo)); assert(clos != NULL); memcpy(clos, pmembench_clos, pb_nclos * sizeof (struct benchmark_clo)); if (bench->info->clos) { memcpy(&clos[pb_nclos], bench->info->clos, bench->info->nclos * sizeof (struct benchmark_clo)); for (i = 0; i < bench->info->nclos; i++) { clos[pb_nclos + i].off += sizeof (struct benchmark_args); } } bench->clos = clos; bench->nclos = nclos; bench->args_size = size; } /* * pmembench_run_worker -- run worker with benchmark operation */ static int pmembench_run_worker(struct benchmark *bench, struct worker_info *winfo) { uint64_t i; uint64_t ops = winfo->nops; benchmark_time_t start, stop; for (i = 0; i < ops; i++) { if (bench->info->op_init) { if (bench->info->op_init(bench, &winfo->opinfo[i])) return -1; } benchmark_time_get(&start); if (bench->info->operation(bench, &winfo->opinfo[i])) return -1; benchmark_time_get(&stop); benchmark_time_diff(&winfo->opinfo[i].t_diff, &start, &stop); if (bench->info->op_exit) { if (bench->info->op_exit(bench, &winfo->opinfo[i])) return -1; } } return 0; } /* * pmembench_print_header -- print header of benchmark's results */ static void pmembench_print_header(struct pmembench *pb, struct benchmark *bench, struct clo_vec *clovec) { if (pb->scenario) { printf("%s: %s [%ld]\n", pb->scenario->name, bench->info->name, clovec->nargs); } else { printf("%s [%ld]\n", bench->info->name, clovec->nargs); } printf("total-avg;" "ops-per-second;" "total-max;" "total-min;" "total-median;" "total-std-dev;" "latency-avg;" "latency-min;" "latency-max;" "latency-std-dev"); size_t i; for (i = 0; i < bench->nclos; i++) { if (!bench->clos[i].ignore_in_res) { printf(";%s", bench->clos[i].opt_long); } } printf("\n"); } /* * pmembench_print_results -- print benchmark's results */ static void pmembench_print_results(struct benchmark *bench, struct benchmark_args *args, size_t n_threads, size_t n_ops, struct results *stats, struct latency *latency) { double opsps = n_threads * n_ops / stats->avg; printf("%f;%f;%f;%f;%f;%f;%ld;%ld;%ld;%f", stats->avg, opsps, stats->max, stats->min, stats->med, stats->std_dev, latency->avg, latency->min, latency->max, latency->std_dev); size_t i; for (i = 0; i < bench->nclos; i++) { if (!bench->clos[i].ignore_in_res) printf(";%s", benchmark_clo_str(&bench->clos[i], args, bench->args_size)); } printf("\n"); } /* * pmembench_parse_clos -- parse command line arguments for benchmark */ static int pmembench_parse_clo(struct pmembench *pb, struct benchmark *bench, struct clo_vec *clovec) { if (!pb->scenario) { return benchmark_clo_parse(pb->argc, pb->argv, bench->clos, bench->nclos, clovec); } if (pb->override_clos) { /* * Use only ARRAY_SIZE(pmembench_clos) clos - these are the * general clos and are placed at the beginning of the * clos array. */ int ret = benchmark_override_clos_in_scenario(pb->scenario, pb->argc, pb->argv, bench->clos, ARRAY_SIZE(pmembench_clos)); /* reset for the next benchmark in the config file */ optind = 1; if (ret) return ret; } return benchmark_clo_parse_scenario(pb->scenario, bench->clos, bench->nclos, clovec); } /* * pmembench_init_workers -- init benchmark's workers */ static int pmembench_init_workers(struct benchmark_worker **workers, size_t nworkers, size_t n_ops, struct benchmark *bench, struct benchmark_args *args) { size_t i; for (i = 0; i < nworkers; i++) { workers[i] = benchmark_worker_alloc(); workers[i]->info.index = i; workers[i]->info.nops = n_ops; workers[i]->info.opinfo = calloc(n_ops, sizeof (struct operation_info)); size_t j; for (j = 0; j < n_ops; j++) { workers[i]->info.opinfo[j].worker = &workers[i]->info; workers[i]->info.opinfo[j].args = args; workers[i]->info.opinfo[j].index = j; } workers[i]->bench = bench; workers[i]->args = args; workers[i]->func = pmembench_run_worker; workers[i]->init = bench->info->init_worker; workers[i]->exit = bench->info->free_worker; benchmark_worker_init(workers[i]); } return 0; } /* * pmembench_dummy_op -- dummy operation */ static int pmembench_dummy_op() { return 0; } /* * compare_doubles -- comparing function used for sorting */ static int compare_doubles(const void *a1, const void *b1) { const double *a = (const double *)a1; const double *b = (const double *)b1; return (*a > *b) - (*a < *b); } /* * pmembench_get_results -- return results of one repeat */ static void pmembench_get_results(struct benchmark_worker **workers, size_t nworkers, struct latency *stats, double *workers_times) { memset(stats, 0, sizeof (*stats)); stats->min = ~0; uint64_t i; uint64_t j; uint64_t d; uint64_t nsecs = 0; uint64_t nsecs_dummy = 0; double secs_dummy = 0; uint64_t count = 0; benchmark_time_t start, stop, dummy; benchmark_time_get(&start); pmembench_dummy_op(); benchmark_time_get(&stop); benchmark_time_diff(&dummy, &start, &stop); nsecs_dummy = benchmark_time_get_nsecs(&dummy); secs_dummy = benchmark_time_get_secs(&dummy); for (i = 0; i < nworkers; i++) { for (j = 0; j < workers[i]->info.nops; j++) { nsecs = benchmark_time_get_nsecs( &workers[i]->info.opinfo[j].t_diff); if (nsecs > nsecs_dummy) nsecs -= nsecs_dummy; workers_times[i] += benchmark_time_get_secs( &workers[i]->info.opinfo[j].t_diff); if (workers_times[i] > secs_dummy) workers_times[i] -= secs_dummy; if (nsecs > stats->max) stats->max = nsecs; if (nsecs < stats->min) stats->min = nsecs; stats->avg += nsecs; count++; } } assert(count != 0); if (count > 0) stats->avg /= count; for (i = 0; i < nworkers; i++) { for (j = 0; j < workers[i]->info.nops; j++) { nsecs = benchmark_time_get_nsecs( &workers[i]->info.opinfo[j].t_diff) - nsecs_dummy; d = nsecs > stats->avg ? nsecs - stats->avg : stats->avg - nsecs; stats->std_dev += d * d; } } stats->std_dev = sqrt(stats->std_dev / count); } /* * pmembench_get_total_results -- return results of all repeats of scenario */ static void pmembench_get_total_results(struct latency *stats, double *workers_times, struct results *total, struct latency *latency, size_t repeats, size_t nworkers) { memset(total, 0, sizeof (*total)); memset(latency, 0, sizeof (*latency)); total->min = DBL_MAX; latency->min = ~0; size_t nresults = repeats * nworkers; size_t i; size_t j; size_t d; double df; for (i = 0; i < repeats; i++) { /* latency */ if (stats[i].max > latency->max) latency->max = stats[i].max; if (stats[i].min < latency->min) latency->min = stats[i].min; latency->avg += stats[i].avg; /* total time */ for (j = 0; j < nworkers; j++) { int idx = i * nworkers + j; total->avg += workers_times[idx]; } } latency->avg /= repeats; total->avg /= nresults; qsort(workers_times, nresults, sizeof (double), compare_doubles); total->min = workers_times[0]; total->max = workers_times[nresults - 1]; total->med = nresults % 2 ? (workers_times[nresults / 2] + workers_times[nresults / 2 + 1]) / 2: workers_times[nresults / 2]; for (i = 0; i < repeats; i++) { d = stats[i].std_dev > latency->avg ? stats[i].std_dev - latency->avg : latency->avg - stats[i].std_dev; latency->std_dev += d * d; for (j = 0; j < nworkers; j++) { int idx = i * nworkers + j; df = workers_times[idx] > total->avg ? workers_times[idx] - total->avg : total->avg - workers_times[idx]; total->std_dev += df * df; } } latency->std_dev = sqrt(latency->std_dev / repeats); total->std_dev = sqrt(total->std_dev / nresults); } /* * pmembench_print_args -- print arguments for one benchmark */ static void pmembench_print_args(struct benchmark_clo *clos, size_t nclos) { struct benchmark_clo clo; for (size_t i = 0; i < nclos; i++) { clo = clos[i]; if (clo.opt_short != 0) printf("\t-%c,", clo.opt_short); else printf("\t"); printf("\t--%-15s\t\t%s", clo.opt_long, clo.descr); if (clo.type != CLO_TYPE_FLAG) printf(" [default: %s]", clo.def); if (clo.type == CLO_TYPE_INT) { if (clo.type_int.min != LONG_MIN) printf(" [min: %jd]", clo.type_int.min); if (clo.type_int.max != LONG_MAX) printf(" [max: %jd]", clo.type_int.max); } else if (clo.type == CLO_TYPE_UINT) { if (clo.type_uint.min != 0) printf(" [min: %ju]", clo.type_uint.min); if (clo.type_uint.max != ULONG_MAX) printf(" [max: %ju]", clo.type_uint.max); } printf("\n"); } } /* * pmembench_print_help_single -- prints help for single benchmark */ static void pmembench_print_help_single(struct benchmark *bench) { struct benchmark_info *info = bench->info; printf("%s\n%s\n", info->name, info->brief); printf("\nArguments:\n"); size_t nclos = sizeof (pmembench_clos) / sizeof (struct benchmark_clo); pmembench_print_args(pmembench_clos, nclos); if (info->clos == NULL) return; pmembench_print_args(info->clos, info->nclos); } /* * pmembench_print_usage -- print usage of framework */ static void pmembench_print_usage() { printf("Usage: $ pmembench [-h|--help] [-v|--version]" "\t[<benchmark>[<args>]]\n"); printf("\t\t\t\t\t\t[<config>[<scenario>]]\n"); printf("\t\t\t\t\t\t[<config>[<scenario>[<common_args>]]]\n"); } /* * pmembench_print_version -- print version of framework */ static void pmembench_print_version() { printf("Benchmark framework - version %d.%d\n", version.major, version.minor); } /* * pmembench_print_examples() -- print examples of using framework */ static void pmembench_print_examples() { printf("\nExamples:\n"); printf("$ pmembench <benchmark_name> <args>\n"); printf(" # runs benchmark of name <benchmark> with arguments <args>\n"); printf("or\n"); printf("$ pmembench <config_file>\n"); printf(" # runs all scenarios from config file\n"); printf("or\n"); printf("$ pmembench [<benchmark_name>] [-h|--help [-v|--version]\n"); printf(" # prints help\n"); printf("or\n"); printf("$ pmembench <config_file> <name_of_scenario>\n"); printf(" # runs the specified scenario from config file\n"); printf("$ pmembench <config_file> <name_of_scenario_1> " "<name_of_scenario_2> <common_args>\n"); printf(" # runs the specified scenarios from config file and overwrites" " the given common_args from the config file\n"); } /* * pmembench_print_help -- print help for framework */ static void pmembench_print_help() { pmembench_print_version(); pmembench_print_usage(); printf("\nCommon arguments:\n"); size_t nclos = sizeof (pmembench_opts) / sizeof (struct benchmark_clo); pmembench_print_args(pmembench_opts, nclos); printf("\nAvaliable benchmarks:\n"); struct benchmark *bench = NULL; LIST_FOREACH(bench, &benchmarks.head, next) printf("\t%-20s\t\t%s\n", bench->info->name, bench->info->brief); printf("\n$ pmembench <benchmark> --help to print detailed information" " about benchmark arguments\n"); pmembench_print_examples(); } /* * pmembench_get_bench -- searching benchmarks by name */ static struct benchmark * pmembench_get_bench(const char *name) { struct benchmark *bench; LIST_FOREACH(bench, &benchmarks.head, next) { if (strcmp(name, bench->info->name) == 0) return bench; } return NULL; } /* * pmembench_parse_opts -- parse arguments for framework */ static int pmembench_parse_opts(struct pmembench *pb) { int ret = 0; int argc = ++pb->argc; char **argv = --pb->argv; struct benchmark_opts *opts = NULL; struct clo_vec *clovec; size_t size, n_clos; size = sizeof (struct benchmark_opts); n_clos = ARRAY_SIZE(pmembench_opts); clovec = clo_vec_alloc(size); assert(clovec != NULL); if (benchmark_clo_parse(argc, argv, pmembench_opts, n_clos, clovec)) { ret = -1; goto out; } opts = clo_vec_get_args(clovec, 0); if (opts->help) pmembench_print_help(); if (opts->version) pmembench_print_version(); out: clo_vec_free(clovec); free(opts); return ret; } /* * pmembench_remove_file -- remove file or directory if exists */ static int pmembench_remove_file(const char *dname) { int ret = 0; DIR *dir; struct dirent *d; char *tmp; dir = opendir(dname); if (dir == NULL) { if (access(dname, F_OK) == 0) remove(dname); return ret; } while ((d = readdir(dir)) != NULL) { if (strcmp(d->d_name, ".") == 0 || strcmp(d->d_name, "..") == 0) continue; tmp = malloc(strlen(dname) + strlen(d->d_name) + 2); sprintf(tmp, "%s/%s", dname, d->d_name); ret = (d->d_type == DT_DIR) ? pmembench_remove_file(tmp) : remove(tmp); free(tmp); if (ret != 0) return ret; } ret = rmdir(dname); return ret; } /* * pmembench_run -- runs one benchmark. Parses arguments and performs * specific functions. */ static int pmembench_run(struct pmembench *pb, struct benchmark *bench) { char old_wd[PATH_MAX]; int ret = 0; assert(bench->info != NULL); pmembench_merge_clos(bench); /* * Check if PMEMBENCH_DIR env var is set and change * the working directory accordingly. */ char *wd = getenv("PMEMBENCH_DIR"); if (wd != NULL) { /* get current dir name */ if (getcwd(old_wd, PATH_MAX) == NULL) { perror("getcwd"); ret = -1; goto out_release_clos; } if (chdir(wd)) { perror("chdir(wd)"); ret = -1; goto out_release_clos; } } if (bench->info->pre_init) { if (bench->info->pre_init(bench)) { warn("%s: pre-init failed", bench->info->name); ret = -1; goto out_old_wd; } } struct benchmark_args *args = NULL; struct clo_vec *clovec = clo_vec_alloc(bench->args_size); assert(clovec != NULL); if (pmembench_parse_clo(pb, bench, clovec)) { warn("%s: parsing command line arguments failed", bench->info->name); ret = -1; goto out_release_args; } args = clo_vec_get_args(clovec, 0); if (args->help) { pmembench_print_help_single(bench); goto out; } pmembench_print_header(pb, bench, clovec); size_t args_i; for (args_i = 0; args_i < clovec->nargs; args_i++) { args = clo_vec_get_args(clovec, args_i); args->opts = (void *)((uintptr_t)args + sizeof (struct benchmark_args)); size_t n_threads = !bench->info->multithread ? 1 : args->n_threads; size_t n_ops = !bench->info->multiops ? 1 : args->n_ops_per_thread; struct latency *stats = calloc(args->repeats, sizeof (struct latency)); assert(stats != NULL); double *workers_times = calloc(n_threads * args->repeats, sizeof (double)); assert(workers_times != NULL); for (unsigned int i = 0; i < args->repeats; i++) { if (bench->info->rm_file) { ret = pmembench_remove_file(args->fname); if (ret != 0) { perror("removing file failed"); goto out; } } if (bench->info->init) { if (bench->info->init(bench, args)) { warn("%s: initialization failed", bench->info->name); ret = -1; goto out; } } assert(bench->info->operation != NULL); struct benchmark_worker **workers; workers = malloc(args->n_threads * sizeof (struct benchmark_worker *)); assert(workers != NULL); if ((ret = pmembench_init_workers(workers, n_threads, n_ops, bench, args)) != 0) { if (bench->info->exit) bench->info->exit(bench, args); goto out; } unsigned int j; for (j = 0; j < args->n_threads; j++) { benchmark_worker_run(workers[j]); } for (j = 0; j < args->n_threads; j++) { benchmark_worker_join(workers[j]); if (workers[j]->ret != 0) { ret = workers[j]->ret; fprintf(stderr, "thread number %d failed \n", j); } } if (ret == 0) pmembench_get_results(workers, n_threads, &stats[i], &workers_times[i * n_threads]); for (j = 0; j < args->n_threads; j++) { benchmark_worker_exit(workers[j]); free(workers[j]->info.opinfo); benchmark_worker_free(workers[j]); } free(workers); if (bench->info->exit) bench->info->exit(bench, args); } struct results total; struct latency latency; pmembench_get_total_results(stats, workers_times, &total, &latency, args->repeats, n_threads); pmembench_print_results(bench, args, n_threads, n_ops, &total, &latency); free(stats); free(workers_times); } out: out_release_args: clo_vec_free(clovec); out_old_wd: /* restore the original working directory */ if (wd != NULL) { /* Only if PMEMBENCH_DIR env var was defined */ if (chdir(old_wd)) { perror("chdir(old_wd)"); ret = -1; } } out_release_clos: pmembench_release_clos(bench); return ret; } /* * pmembench_free_benchmarks -- release all benchmarks */ static void __attribute__((destructor)) pmembench_free_benchmarks(void) { while (!LIST_EMPTY(&benchmarks.head)) { struct benchmark *bench = LIST_FIRST(&benchmarks.head); LIST_REMOVE(bench, next); free(bench); } } /* * pmembench_run_scenario -- run single benchmark's scenario */ static int pmembench_run_scenario(struct pmembench *pb, struct scenario *scenario) { struct benchmark *bench = pmembench_get_bench(scenario->benchmark); if (NULL == bench) { fprintf(stderr, "unknown benchmark: %s\n", scenario->benchmark); return -1; } pb->scenario = scenario; return pmembench_run(pb, bench); } /* * pmembench_run_scenarios -- run all scenarios */ static int pmembench_run_scenarios(struct pmembench *pb, struct scenarios *ss) { struct scenario *scenario; FOREACH_SCENARIO(scenario, ss) { if (pmembench_run_scenario(pb, scenario) != 0) return -1; } return 0; } /* * pmembench_run_config -- run one or all scenarios from config file */ static int pmembench_run_config(struct pmembench *pb, const char *config) { struct config_reader *cr = config_reader_alloc(); assert(cr != NULL); int ret = 0; if ((ret = config_reader_read(cr, config))) goto out; struct scenarios *ss = NULL; if ((ret = config_reader_get_scenarios(cr, &ss))) goto out; assert(ss != NULL); if (pb->argc == 1) { if ((ret = pmembench_run_scenarios(pb, ss)) != 0) goto out_scenarios; } else { /* Skip the config file name in cmd line params */ int tmp_argc = pb->argc - 1; char **tmp_argv = pb->argv + 1; if (!contains_scenarios(tmp_argc, tmp_argv, ss)) { /* no scenarios in cmd line arguments - parse params */ pb->override_clos = true; if ((ret = pmembench_run_scenarios(pb, ss)) != 0) goto out_scenarios; } else { /* scenarios in cmd line */ struct scenarios *cmd_ss = scenarios_alloc(); assert(cmd_ss != NULL); int parsed_scenarios = clo_get_scenarios(tmp_argc, tmp_argv, ss, cmd_ss); if (parsed_scenarios < 0) goto out_cmd; /* * If there are any cmd line args left, treat * them as config file params override. */ if (tmp_argc - parsed_scenarios) pb->override_clos = true; /* * Skip the scenarios in the cmd line, * pmembench_run_scenarios does not expect them and will * fail otherwise. */ pb->argc -= parsed_scenarios; pb->argv += parsed_scenarios; if ((ret = pmembench_run_scenarios(pb, cmd_ss)) != 0) { goto out_cmd; } out_cmd: scenarios_free(cmd_ss); } } out_scenarios: scenarios_free(ss); out: config_reader_free(cr); return ret; } int main(int argc, char *argv[]) { int ret = 0; struct pmembench *pb = calloc(1, sizeof (*pb)); assert(pb != NULL); /* * Parse common command line arguments and * benchmark's specific ones. */ if (argc < 2) { pmembench_print_usage(); exit(EXIT_FAILURE); return -1; } pb->argc = --argc; pb->argv = ++argv; char *bench_name = pb->argv[0]; if (NULL == bench_name) { ret = -1; goto out; } int fexists = access(bench_name, R_OK) == 0; struct benchmark *bench = pmembench_get_bench(bench_name); if (NULL != bench) ret = pmembench_run(pb, bench); else if (fexists) ret = pmembench_run_config(pb, bench_name); else if ((ret = pmembench_parse_opts(pb)) != 0) { pmembench_print_usage(); goto out; } out: free(pb); return ret; }
{ "content_hash": "64e08c08b1221165585eb3d90efd6d4a", "timestamp": "", "source": "github", "line_count": 1148, "max_line_length": 77, "avg_line_length": 22.729965156794425, "alnum_prop": 0.6286119414424772, "repo_name": "amaliujia/peloton", "id": "1d461b36b25d81550768d54fdfa7b4389367e14e", "size": "27690", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "third_party/nvml/src/benchmarks/pmembench.c", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Assembly", "bytes": "3265" }, { "name": "C", "bytes": "2626904" }, { "name": "C++", "bytes": "26153026" }, { "name": "DTrace", "bytes": "3480" }, { "name": "Groff", "bytes": "28217" }, { "name": "Java", "bytes": "8582" }, { "name": "Lex", "bytes": "35658" }, { "name": "Makefile", "bytes": "78628" }, { "name": "Objective-C", "bytes": "2795" }, { "name": "PLpgSQL", "bytes": "108662" }, { "name": "Perl", "bytes": "76475" }, { "name": "Python", "bytes": "7744" }, { "name": "Ruby", "bytes": "1027" }, { "name": "SQLPL", "bytes": "32868" }, { "name": "Shell", "bytes": "8978" }, { "name": "Yacc", "bytes": "17418" } ], "symlink_target": "" }
require 'spec_helper' require 'component_helper' require 'java_buildpack/container/play_framework' require 'java_buildpack/util/play/factory' describe JavaBuildpack::Container::PlayFramework do include_context 'with component help' let(:delegate) { instance_double('delegate') } context do before do allow(JavaBuildpack::Util::Play::Factory).to receive(:create).with(droplet).and_return(delegate) end it 'delegates detect' do allow(delegate).to receive(:version).and_return('0.0.0') expect(component.detect).to eq('play-framework=0.0.0') end it 'delegates compile' do allow(delegate).to receive(:compile) component.compile end it 'delegates release' do allow(delegate).to receive(:release) component.release end end context do before do allow(JavaBuildpack::Util::Play::Factory).to receive(:create).with(droplet).and_return(nil) end it 'does not delegate detect' do expect(component.detect).to be_nil end it 'does not delegate compile' do component.compile end it 'does not delegate release' do component.release end end end
{ "content_hash": "f5c991c91e4c18f4749eb2c781a28820", "timestamp": "", "source": "github", "line_count": 57, "max_line_length": 102, "avg_line_length": 20.789473684210527, "alnum_prop": 0.6810126582278481, "repo_name": "rakutentech/java-buildpack", "id": "fac718692e51babe355c9ee843e61e567e343eb9", "size": "1849", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "spec/java_buildpack/container/play_framework_spec.rb", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Dockerfile", "bytes": "1092" }, { "name": "Ruby", "bytes": "776371" }, { "name": "Shell", "bytes": "6764" } ], "symlink_target": "" }
a VideoView with gestures
{ "content_hash": "f8254766ac6e617612e3ffaf8f941dad", "timestamp": "", "source": "github", "line_count": 1, "max_line_length": 25, "avg_line_length": 26, "alnum_prop": 0.8461538461538461, "repo_name": "SethWen/GestureVideoView", "id": "3a9651c314a95b9bcfcce0bd39a0f53e9b65dccc", "size": "45", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "README.md", "mode": "33188", "license": "mit", "language": [ { "name": "Java", "bytes": "117581" } ], "symlink_target": "" }
fiddle-20150402-UnBufferedColumnFiltering ====== ![Screenshot](screenshot.png) ### Title UnBuffered Column Filtering ### Creation Date 04-02-15 ### Description This fiddle is a response to [fiddle-20150401-BufferedColumnFiltering](../fiddle-20150401-BufferedColumnFiltering/index.html). It illustrates how to enable column filter on a grid panel bound to a vanilla data store--i.e. Ext.data.Store. ### Published Version Link [Sencha Fiddle](https://fiddle.sencha.com/#fiddle/ko5) ### Tags EXTJS-5-1, grid, panel, plugins, gridfilters, bufferedrender, data, store, toolbar, paging
{ "content_hash": "a32b030ef971e643c4a8900c7e21ec93", "timestamp": "", "source": "github", "line_count": 29, "max_line_length": 238, "avg_line_length": 20.586206896551722, "alnum_prop": 0.7504187604690117, "repo_name": "bradyhouse/house", "id": "878c45844e5006ae3ecfca55f8fb286a19051d3b", "size": "597", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "fiddles/extjs5/fiddle-20150402-UnBufferedColumnFiltering/README.markdown", "mode": "33188", "license": "mit", "language": [ { "name": "C", "bytes": "26015" }, { "name": "CSS", "bytes": "3541537" }, { "name": "HTML", "bytes": "3275889" }, { "name": "Handlebars", "bytes": "1593" }, { "name": "Java", "bytes": "90609" }, { "name": "JavaScript", "bytes": "9249816" }, { "name": "Less", "bytes": "3364" }, { "name": "PHP", "bytes": "125609" }, { "name": "Pug", "bytes": "1758" }, { "name": "Python", "bytes": "20858" }, { "name": "Ruby", "bytes": "11317" }, { "name": "SCSS", "bytes": "37673" }, { "name": "Shell", "bytes": "1095755" }, { "name": "TypeScript", "bytes": "779887" } ], "symlink_target": "" }