text
stringlengths
4
5.48M
meta
stringlengths
14
6.54k
local require = require local rawget = rawget local pairs = pairs local table = require "loop.table" module "loop.simple" -------------------------------------------------------------------------------- local ObjectCache = require "loop.collection.ObjectCache" local base = require "loop.base" -------------------------------------------------------------------------------- table.copy(base, _M) -------------------------------------------------------------------------------- local DerivedClass = ObjectCache { retrieve = function(self, super) return base.class { __index = super, __call = new } end, } function class(class, super) if super then return DerivedClass[super](initclass(class)) else return base.class(class) end end -------------------------------------------------------------------------------- function isclass(class) local metaclass = classof(class) if metaclass then return metaclass == rawget(DerivedClass, metaclass.__index) or base.isclass(class) end end -------------------------------------------------------------------------------- function superclass(class) local metaclass = classof(class) if metaclass then return metaclass.__index end end -------------------------------------------------------------------------------- function subclassof(class, super) while class do if class == super then return true end class = superclass(class) end return false end -------------------------------------------------------------------------------- function instanceof(object, class) return subclassof(classof(object), class) end
{'content_hash': '92c9464c88325b9093a2d18d6d8a1997', 'timestamp': '', 'source': 'github', 'line_count': 49, 'max_line_length': 80, 'avg_line_length': 32.51020408163265, 'alnum_prop': 0.4783427495291902, 'repo_name': 'ld-test/oil', 'id': '860cc17ce076c7b8731a1509b1b938499d445657', 'size': '3619', 'binary': False, 'copies': '13', 'ref': 'refs/heads/master', 'path': 'lua/loop/simple.lua', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'C', 'bytes': '159816'}, {'name': 'Lua', 'bytes': '1003003'}, {'name': 'Makefile', 'bytes': '13314'}, {'name': 'Shell', 'bytes': '6060'}]}
namespace tpp { /*! \file assert.hpp \brief Implements a better 'Assert' */ #ifndef REVIVER_ASSERT_HPP #define REVIVER_ASSERT_HPP /*! \def MyAssertFunction \brief Function used by 'Assert' function in _DEBUG mode. Details. */ //Fix for Visual Studio C++ needing full definition of MyAssertFunction #if defined _MSC_VER extern bool MyAssertFunction( bool b, char* desc, int line, char* file) {return 1;}; #else extern bool MyAssertFunction( bool b, char* desc, int line, char* file); #endif #if defined( _DEBUG ) #define Assert( exp, description ) tpp::MyAssertFunction( (int)(exp), description, __LINE__, __FILE__ ) #else #define Assert( exp, description ) #endif #endif }
{'content_hash': 'eceac01f903f7e9daf6addf84a373a83', 'timestamp': '', 'source': 'github', 'line_count': 33, 'max_line_length': 103, 'avg_line_length': 21.363636363636363, 'alnum_prop': 0.6921985815602837, 'repo_name': 'HellicarAndLewis/Stripes', 'id': '45bb0a006ca4f7a7ca641634f5cd59a865485f42', 'size': '705', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'addons/ofxContourAnalysis/triangle/assert.hpp', 'mode': '33261', 'license': 'mit', 'language': [{'name': 'C', 'bytes': '52546'}, {'name': 'C++', 'bytes': '809884'}]}
struct TripAlight { edgepayload_t type; long external_id; State* (*walk)(struct EdgePayload*, struct State*, struct WalkOptions*); State* (*walkBack)(struct EdgePayload*, struct State*, struct WalkOptions*); int n; int* arrivals; char** trip_ids; int* stop_sequences; ServiceCalendar* calendar; Timezone* timezone; int agency; ServiceId service_id; int overage; //number of seconds schedules past midnight of the last departure. If it's at 12:00:00, the overage is 0. } ; TripAlight* alNew( ServiceId service_id, ServiceCalendar* calendar, Timezone* timezone, int agency ); void alDestroy(TripAlight* this); ServiceCalendar* alGetCalendar( TripAlight* this ); Timezone* alGetTimezone( TripAlight* this ); int alGetAgency( TripAlight* this ); ServiceId alGetServiceId( TripAlight* this ); int alGetNumAlightings(TripAlight* this); void alAddAlighting(TripAlight* this, char* trip_id, int arrival, int stop_sequence); char* alGetAlightingTripId(TripAlight* this, int i); int alGetAlightingArrival(TripAlight* this, int i); int alGetAlightingStopSequence(TripAlight* this, int i); int alSearchAlightingsList(TripAlight* this, int time); int alGetLastAlightingIndex(TripAlight* this, int time); int alGetOverage(TripAlight* this); int alGetAlightingIndexByTripId(TripAlight* this, char* trip_id); inline State* alWalk(EdgePayload* this, State* state, WalkOptions* options); inline State* alWalkBack(EdgePayload* this, State* state, WalkOptions* options); #endif
{'content_hash': 'bbbd05b15f5d4e44d24a877f66fe0ae6', 'timestamp': '', 'source': 'github', 'line_count': 71, 'max_line_length': 122, 'avg_line_length': 21.732394366197184, 'alnum_prop': 0.7414128321451717, 'repo_name': 'bmander/graphserver', 'id': '524859f6a63259fe3437164cb8b3ac3074a2bc9a', 'size': '1675', 'binary': False, 'copies': '2', 'ref': 'refs/heads/master', 'path': 'core/edgetypes/tripalight.h', 'mode': '33188', 'license': 'bsd-3-clause', 'language': [{'name': 'C', 'bytes': '200078'}, {'name': 'Python', 'bytes': '428337'}]}
<?xml version="1.0" ?><!DOCTYPE TS><TS language="fi" version="2.0"> <defaultcodec>UTF-8</defaultcodec> <context> <name>AboutDialog</name> <message> <location filename="../forms/aboutdialog.ui" line="14"/> <source>About Bitcoin</source> <translation>Tietoa Bitcoinista</translation> </message> <message> <location filename="../forms/aboutdialog.ui" line="53"/> <source>&lt;b&gt;Bitcoin&lt;/b&gt; version</source> <translation>&lt;b&gt;Bitcoin&lt;/b&gt; versio</translation> </message> <message> <location filename="../forms/aboutdialog.ui" line="97"/> <source>Copyright © 2009-2012 Bitcoin Developers This is experimental software. Distributed under the MIT/X11 software license, see the accompanying file license.txt 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 ([email protected]) and UPnP software written by Thomas Bernard.</source> <translation>Copyright © 2009-2012 Bitcoin Developers This is experimental software. Distributed under the MIT/X11 software license, see the accompanying file license.txt 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 ([email protected]) and UPnP software written by Thomas Bernard.</translation> </message> </context> <context> <name>AddressBookPage</name> <message> <location filename="../forms/addressbookpage.ui" line="14"/> <source>Address Book</source> <translation>Osoitekirja</translation> </message> <message> <location filename="../forms/addressbookpage.ui" line="20"/> <source>These are your Bitcoin 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>Nämä ovat sinun Bitcoin-osoitteesi suoritusten vastaanottamiseen. Voit halutessasi antaa kullekin lähettäjälle eri osoitteen, jotta voit seurata kuka sinulle maksaa.</translation> </message> <message> <location filename="../forms/addressbookpage.ui" line="36"/> <source>Double-click to edit address or label</source> <translation>Kaksoisnapauta muokataksesi osoitetta tai nimeä</translation> </message> <message> <location filename="../forms/addressbookpage.ui" line="63"/> <source>Create a new address</source> <translation>Luo uusi osoite</translation> </message> <message> <location filename="../forms/addressbookpage.ui" line="77"/> <source>Copy the currently selected address to the system clipboard</source> <translation>Kopioi valittu osoite leikepöydälle</translation> </message> <message> <location filename="../forms/addressbookpage.ui" line="66"/> <source>&amp;New Address</source> <translation type="unfinished"/> </message> <message> <location filename="../forms/addressbookpage.ui" line="80"/> <source>&amp;Copy Address</source> <translation type="unfinished"/> </message> <message> <location filename="../forms/addressbookpage.ui" line="91"/> <source>Show &amp;QR Code</source> <translation>Näytä &amp;QR-koodi</translation> </message> <message> <location filename="../forms/addressbookpage.ui" line="102"/> <source>Sign a message to prove you own this address</source> <translation>Allekirjoita viesti millä todistat omistavasi tämän osoitteen</translation> </message> <message> <location filename="../forms/addressbookpage.ui" line="105"/> <source>&amp;Sign Message</source> <translation>&amp;Allekirjoita viesti</translation> </message> <message> <location filename="../forms/addressbookpage.ui" line="116"/> <source>Delete the currently selected address from the list. Only sending addresses can be deleted.</source> <translation>Poista valittuna oleva osoite listasta. Vain lähettämiseen käytettäviä osoitteita voi poistaa.</translation> </message> <message> <location filename="../forms/addressbookpage.ui" line="119"/> <source>&amp;Delete</source> <translation>&amp;Poista</translation> </message> <message> <location filename="../addressbookpage.cpp" line="63"/> <source>Copy &amp;Label</source> <translation type="unfinished"/> </message> <message> <location filename="../addressbookpage.cpp" line="65"/> <source>&amp;Edit</source> <translation type="unfinished"/> </message> <message> <location filename="../addressbookpage.cpp" line="292"/> <source>Export Address Book Data</source> <translation>Vie osoitekirja</translation> </message> <message> <location filename="../addressbookpage.cpp" line="293"/> <source>Comma separated file (*.csv)</source> <translation>Comma separated file (*.csv)</translation> </message> <message> <location filename="../addressbookpage.cpp" line="306"/> <source>Error exporting</source> <translation>Virhe viedessä osoitekirjaa</translation> </message> <message> <location filename="../addressbookpage.cpp" line="306"/> <source>Could not write to file %1.</source> <translation>Ei voida kirjoittaa tiedostoon %1.</translation> </message> </context> <context> <name>AddressTableModel</name> <message> <location filename="../addresstablemodel.cpp" line="142"/> <source>Label</source> <translation>Nimi</translation> </message> <message> <location filename="../addresstablemodel.cpp" line="142"/> <source>Address</source> <translation>Osoite</translation> </message> <message> <location filename="../addresstablemodel.cpp" line="178"/> <source>(no label)</source> <translation>(ei nimeä)</translation> </message> </context> <context> <name>AskPassphraseDialog</name> <message> <location filename="../forms/askpassphrasedialog.ui" line="26"/> <source>Passphrase Dialog</source> <translation type="unfinished"/> </message> <message> <location filename="../forms/askpassphrasedialog.ui" line="47"/> <source>Enter passphrase</source> <translation>Anna tunnuslause</translation> </message> <message> <location filename="../forms/askpassphrasedialog.ui" line="61"/> <source>New passphrase</source> <translation>Uusi tunnuslause</translation> </message> <message> <location filename="../forms/askpassphrasedialog.ui" line="75"/> <source>Repeat new passphrase</source> <translation>Toista uusi tunnuslause</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>Anna lompakolle uusi tunnuslause.&lt;br/&gt;Käytä tunnuslausetta, jossa on ainakin &lt;b&gt;10 satunnaista mekkiä&lt;/b&gt; tai &lt;b&gt;kahdeksan sanaa&lt;/b&gt;.</translation> </message> <message> <location filename="../askpassphrasedialog.cpp" line="34"/> <source>Encrypt wallet</source> <translation>Salaa lompakko</translation> </message> <message> <location filename="../askpassphrasedialog.cpp" line="37"/> <source>This operation needs your wallet passphrase to unlock the wallet.</source> <translation>Tätä toimintoa varten sinun täytyy antaa lompakon tunnuslause sen avaamiseksi.</translation> </message> <message> <location filename="../askpassphrasedialog.cpp" line="42"/> <source>Unlock wallet</source> <translation>Avaa lompakko</translation> </message> <message> <location filename="../askpassphrasedialog.cpp" line="45"/> <source>This operation needs your wallet passphrase to decrypt the wallet.</source> <translation>Tätä toimintoa varten sinun täytyy antaa lompakon tunnuslause salauksen purkuun.</translation> </message> <message> <location filename="../askpassphrasedialog.cpp" line="50"/> <source>Decrypt wallet</source> <translation>Pura lompakon salaus</translation> </message> <message> <location filename="../askpassphrasedialog.cpp" line="53"/> <source>Change passphrase</source> <translation>Vaihda tunnuslause</translation> </message> <message> <location filename="../askpassphrasedialog.cpp" line="54"/> <source>Enter the old and new passphrase to the wallet.</source> <translation>Anna vanha ja uusi tunnuslause.</translation> </message> <message> <location filename="../askpassphrasedialog.cpp" line="100"/> <source>Confirm wallet encryption</source> <translation>Hyväksy lompakon salaus</translation> </message> <message> <location filename="../askpassphrasedialog.cpp" line="101"/> <source>WARNING: If you encrypt your wallet and lose your passphrase, you will &lt;b&gt;LOSE ALL OF YOUR BITCOINS&lt;/b&gt;! Are you sure you wish to encrypt your wallet?</source> <translation>VAROITUS: Mikäli salaat lompakkosi ja unohdat tunnuslauseen, &lt;b&gt;MENETÄT LOMPAKON KOKO SISÄLLÖN&lt;/b&gt;! Tahdotko varmasti salata lompakon?</translation> </message> <message> <location filename="../askpassphrasedialog.cpp" line="110"/> <location filename="../askpassphrasedialog.cpp" line="159"/> <source>Wallet encrypted</source> <translation>Lompakko salattu</translation> </message> <message> <location filename="../askpassphrasedialog.cpp" line="111"/> <source>Bitcoin will close now to finish the encryption process. Remember that encrypting your wallet cannot fully protect your bitcoins from being stolen by malware infecting your computer.</source> <translation>Bitcoin sulkeutuu lopettaakseen salausprosessin. Muista, että salattu lompakko ei täysin suojaa sitä haittaohjelmien aiheuttamilta varkauksilta.</translation> </message> <message> <location filename="../askpassphrasedialog.cpp" line="207"/> <location filename="../askpassphrasedialog.cpp" line="231"/> <source>Warning: The Caps Lock key is on.</source> <translation>Varoitus: Caps Lock on päällä.</translation> </message> <message> <location filename="../askpassphrasedialog.cpp" line="116"/> <location filename="../askpassphrasedialog.cpp" line="123"/> <location filename="../askpassphrasedialog.cpp" line="165"/> <location filename="../askpassphrasedialog.cpp" line="171"/> <source>Wallet encryption failed</source> <translation>Lompakon salaus epäonnistui</translation> </message> <message> <location filename="../askpassphrasedialog.cpp" line="117"/> <source>Wallet encryption failed due to an internal error. Your wallet was not encrypted.</source> <translation>Lompakon salaaminen epäonnistui sisäisen virheen vuoksi. Lompakkoa ei salattu.</translation> </message> <message> <location filename="../askpassphrasedialog.cpp" line="124"/> <location filename="../askpassphrasedialog.cpp" line="172"/> <source>The supplied passphrases do not match.</source> <translation>Annetut tunnuslauseet eivät täsmää.</translation> </message> <message> <location filename="../askpassphrasedialog.cpp" line="135"/> <source>Wallet unlock failed</source> <translation>Lompakon avaaminen epäonnistui.</translation> </message> <message> <location filename="../askpassphrasedialog.cpp" line="136"/> <location filename="../askpassphrasedialog.cpp" line="147"/> <location filename="../askpassphrasedialog.cpp" line="166"/> <source>The passphrase entered for the wallet decryption was incorrect.</source> <translation>Annettu tunnuslause oli väärä.</translation> </message> <message> <location filename="../askpassphrasedialog.cpp" line="146"/> <source>Wallet decryption failed</source> <translation>Lompakon salauksen purku epäonnistui.</translation> </message> <message> <location filename="../askpassphrasedialog.cpp" line="160"/> <source>Wallet passphrase was succesfully changed.</source> <translation>Lompakon tunnuslause on vaihdettu.</translation> </message> </context> <context> <name>BitcoinGUI</name> <message> <location filename="../bitcoingui.cpp" line="73"/> <source>Bitcoin Wallet</source> <translation>Bitcoin-lompakko</translation> </message> <message> <location filename="../bitcoingui.cpp" line="215"/> <source>Sign &amp;message...</source> <translation type="unfinished"/> </message> <message> <location filename="../bitcoingui.cpp" line="248"/> <source>Show/Hide &amp;Bitcoin</source> <translation>Näytä/Kätke &amp;Bitcoin</translation> </message> <message> <location filename="../bitcoingui.cpp" line="515"/> <source>Synchronizing with network...</source> <translation>Synkronoidaan verkon kanssa...</translation> </message> <message> <location filename="../bitcoingui.cpp" line="185"/> <source>&amp;Overview</source> <translation>&amp;Yleisnäkymä</translation> </message> <message> <location filename="../bitcoingui.cpp" line="186"/> <source>Show general overview of wallet</source> <translation>Näyttää kokonaiskatsauksen lompakon tilanteesta</translation> </message> <message> <location filename="../bitcoingui.cpp" line="191"/> <source>&amp;Transactions</source> <translation>&amp;Rahansiirrot</translation> </message> <message> <location filename="../bitcoingui.cpp" line="192"/> <source>Browse transaction history</source> <translation>Selaa rahansiirtohistoriaa</translation> </message> <message> <location filename="../bitcoingui.cpp" line="197"/> <source>&amp;Address Book</source> <translation>&amp;Osoitekirja</translation> </message> <message> <location filename="../bitcoingui.cpp" line="198"/> <source>Edit the list of stored addresses and labels</source> <translation>Muokkaa tallennettujen nimien ja osoitteiden listaa</translation> </message> <message> <location filename="../bitcoingui.cpp" line="203"/> <source>&amp;Receive coins</source> <translation>&amp;Vastaanota Bitcoineja</translation> </message> <message> <location filename="../bitcoingui.cpp" line="204"/> <source>Show the list of addresses for receiving payments</source> <translation>Näytä Bitcoinien vastaanottamiseen käytetyt osoitteet</translation> </message> <message> <location filename="../bitcoingui.cpp" line="209"/> <source>&amp;Send coins</source> <translation>&amp;Lähetä Bitcoineja</translation> </message> <message> <location filename="../bitcoingui.cpp" line="216"/> <source>Prove you control an address</source> <translation>Todista että hallitset osoitetta</translation> </message> <message> <location filename="../bitcoingui.cpp" line="235"/> <source>E&amp;xit</source> <translation>L&amp;opeta</translation> </message> <message> <location filename="../bitcoingui.cpp" line="236"/> <source>Quit application</source> <translation>Lopeta ohjelma</translation> </message> <message> <location filename="../bitcoingui.cpp" line="239"/> <source>&amp;About %1</source> <translation>&amp;Tietoja %1</translation> </message> <message> <location filename="../bitcoingui.cpp" line="240"/> <source>Show information about Bitcoin</source> <translation>Näytä tietoa Bitcoin-projektista</translation> </message> <message> <location filename="../bitcoingui.cpp" line="242"/> <source>About &amp;Qt</source> <translation>Tietoja &amp;Qt</translation> </message> <message> <location filename="../bitcoingui.cpp" line="243"/> <source>Show information about Qt</source> <translation>Näytä tietoja QT:ta</translation> </message> <message> <location filename="../bitcoingui.cpp" line="245"/> <source>&amp;Options...</source> <translation>&amp;Asetukset...</translation> </message> <message> <location filename="../bitcoingui.cpp" line="252"/> <source>&amp;Encrypt Wallet...</source> <translation type="unfinished"/> </message> <message> <location filename="../bitcoingui.cpp" line="255"/> <source>&amp;Backup Wallet...</source> <translation type="unfinished"/> </message> <message> <location filename="../bitcoingui.cpp" line="257"/> <source>&amp;Change Passphrase...</source> <translation type="unfinished"/> </message> <message numerus="yes"> <location filename="../bitcoingui.cpp" line="517"/> <source>~%n block(s) remaining</source> <translation><numerusform>~%n lohko jäljellä</numerusform><numerusform>~%n lohkoja jäljellä</numerusform></translation> </message> <message> <location filename="../bitcoingui.cpp" line="528"/> <source>Downloaded %1 of %2 blocks of transaction history (%3% done).</source> <translation>Ladattu %1 / %2 lohkoista rahansiirtohistoriasta (%3% suoritettu).</translation> </message> <message> <location filename="../bitcoingui.cpp" line="250"/> <source>&amp;Export...</source> <translation>&amp;Vie...</translation> </message> <message> <location filename="../bitcoingui.cpp" line="210"/> <source>Send coins to a Bitcoin address</source> <translation type="unfinished"/> </message> <message> <location filename="../bitcoingui.cpp" line="246"/> <source>Modify configuration options for Bitcoin</source> <translation type="unfinished"/> </message> <message> <location filename="../bitcoingui.cpp" line="249"/> <source>Show or hide the Bitcoin window</source> <translation>Näytä tai piillota Bitcoin-ikkuna</translation> </message> <message> <location filename="../bitcoingui.cpp" line="251"/> <source>Export the data in the current tab to a file</source> <translation>Vie auki olevan välilehden tiedot tiedostoon</translation> </message> <message> <location filename="../bitcoingui.cpp" line="253"/> <source>Encrypt or decrypt wallet</source> <translation>Salaa tai poista salaus lompakosta</translation> </message> <message> <location filename="../bitcoingui.cpp" line="256"/> <source>Backup wallet to another location</source> <translation>Varmuuskopioi lompakko toiseen sijaintiin</translation> </message> <message> <location filename="../bitcoingui.cpp" line="258"/> <source>Change the passphrase used for wallet encryption</source> <translation>Vaihda lompakon salaukseen käytettävä tunnuslause</translation> </message> <message> <location filename="../bitcoingui.cpp" line="259"/> <source>&amp;Debug window</source> <translation type="unfinished"/> </message> <message> <location filename="../bitcoingui.cpp" line="260"/> <source>Open debugging and diagnostic console</source> <translation type="unfinished"/> </message> <message> <location filename="../bitcoingui.cpp" line="261"/> <source>&amp;Verify message...</source> <translation type="unfinished"/> </message> <message> <location filename="../bitcoingui.cpp" line="262"/> <source>Verify a message signature</source> <translation type="unfinished"/> </message> <message> <location filename="../bitcoingui.cpp" line="286"/> <source>&amp;File</source> <translation>&amp;Tiedosto</translation> </message> <message> <location filename="../bitcoingui.cpp" line="296"/> <source>&amp;Settings</source> <translation>&amp;Asetukset</translation> </message> <message> <location filename="../bitcoingui.cpp" line="302"/> <source>&amp;Help</source> <translation>&amp;Apua</translation> </message> <message> <location filename="../bitcoingui.cpp" line="311"/> <source>Tabs toolBHC</source> <translation>Välilehtipalkki</translation> </message> <message> <location filename="../bitcoingui.cpp" line="322"/> <source>Actions toolBHC</source> <translation>Toimintopalkki</translation> </message> <message> <location filename="../bitcoingui.cpp" line="334"/> <location filename="../bitcoingui.cpp" line="343"/> <source>[testnet]</source> <translation>[testnet]</translation> </message> <message> <location filename="../bitcoingui.cpp" line="343"/> <location filename="../bitcoingui.cpp" line="399"/> <source>Bitcoin client</source> <translation>Bitcoin-asiakas</translation> </message> <message numerus="yes"> <location filename="../bitcoingui.cpp" line="492"/> <source>%n active connection(s) to Bitcoin network</source> <translation><numerusform>%n aktiivinen yhteys Bitcoin-verkkoon</numerusform><numerusform>%n aktiivista yhteyttä Bitcoin-verkkoon</numerusform></translation> </message> <message> <location filename="../bitcoingui.cpp" line="540"/> <source>Downloaded %1 blocks of transaction history.</source> <translation>Ladattu %1 lohkoa rahansiirron historiasta.</translation> </message> <message numerus="yes"> <location filename="../bitcoingui.cpp" line="555"/> <source>%n second(s) ago</source> <translation><numerusform>%n sekunti sitten</numerusform><numerusform>%n sekuntia sitten</numerusform></translation> </message> <message numerus="yes"> <location filename="../bitcoingui.cpp" line="559"/> <source>%n minute(s) ago</source> <translation><numerusform>%n minuutti sitten</numerusform><numerusform>%n minuuttia sitten</numerusform></translation> </message> <message numerus="yes"> <location filename="../bitcoingui.cpp" line="563"/> <source>%n hour(s) ago</source> <translation><numerusform>%n tunti sitten</numerusform><numerusform>%n tuntia sitten</numerusform></translation> </message> <message numerus="yes"> <location filename="../bitcoingui.cpp" line="567"/> <source>%n day(s) ago</source> <translation><numerusform>%n päivä sitten</numerusform><numerusform>%n päivää sitten</numerusform></translation> </message> <message> <location filename="../bitcoingui.cpp" line="573"/> <source>Up to date</source> <translation>Rahansiirtohistoria on ajan tasalla</translation> </message> <message> <location filename="../bitcoingui.cpp" line="580"/> <source>Catching up...</source> <translation>Kurotaan kiinni...</translation> </message> <message> <location filename="../bitcoingui.cpp" line="590"/> <source>Last received block was generated %1.</source> <translation>Viimeisin vastaanotettu lohko tuotettu %1.</translation> </message> <message> <location filename="../bitcoingui.cpp" line="649"/> <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>Tämä rahansiirto ylittää kokorajoituksen. Voit siitä huolimatta lähettää sen %1 siirtopalkkion mikä menee solmuille jotka käsittelevät rahansiirtosi tämä auttaa myös verkostoa. Haluatko maksaa siirtopalkkion? </translation> </message> <message> <location filename="../bitcoingui.cpp" line="654"/> <source>Confirm transaction fee</source> <translation type="unfinished"/> </message> <message> <location filename="../bitcoingui.cpp" line="681"/> <source>Sent transaction</source> <translation>Lähetetyt rahansiirrot</translation> </message> <message> <location filename="../bitcoingui.cpp" line="682"/> <source>Incoming transaction</source> <translation>Saapuva rahansiirto</translation> </message> <message> <location filename="../bitcoingui.cpp" line="683"/> <source>Date: %1 Amount: %2 Type: %3 Address: %4 </source> <translation>Päivä: %1 Määrä: %2 Tyyppi: %3 Osoite: %4</translation> </message> <message> <location filename="../bitcoingui.cpp" line="804"/> <source>Wallet is &lt;b&gt;encrypted&lt;/b&gt; and currently &lt;b&gt;unlocked&lt;/b&gt;</source> <translation>Lompakko on &lt;b&gt;salattu&lt;/b&gt; ja tällä hetkellä &lt;b&gt;avoinna&lt;/b&gt;</translation> </message> <message> <location filename="../bitcoingui.cpp" line="812"/> <source>Wallet is &lt;b&gt;encrypted&lt;/b&gt; and currently &lt;b&gt;locked&lt;/b&gt;</source> <translation>Lompakko on &lt;b&gt;salattu&lt;/b&gt; ja tällä hetkellä &lt;b&gt;lukittuna&lt;/b&gt;</translation> </message> <message> <location filename="../bitcoingui.cpp" line="835"/> <source>Backup Wallet</source> <translation>Varmuuskopioi lompakko</translation> </message> <message> <location filename="../bitcoingui.cpp" line="835"/> <source>Wallet Data (*.dat)</source> <translation>Lompakkodata (*.dat)</translation> </message> <message> <location filename="../bitcoingui.cpp" line="838"/> <source>Backup Failed</source> <translation>Varmuuskopio epäonnistui</translation> </message> <message> <location filename="../bitcoingui.cpp" line="838"/> <source>There was an error trying to save the wallet data to the new location.</source> <translation>Virhe tallennettaessa lompakkodataa uuteen sijaintiin.</translation> </message> <message> <location filename="../bitcoin.cpp" line="112"/> <source>A fatal error occured. Bitcoin can no longer continue safely and will quit.</source> <translation type="unfinished"/> </message> </context> <context> <name>ClientModel</name> <message> <location filename="../clientmodel.cpp" line="84"/> <source>Network Alert</source> <translation type="unfinished"/> </message> </context> <context> <name>DisplayOptionsPage</name> <message> <location filename="../optionsdialog.cpp" line="246"/> <source>Display</source> <translation>Näyttö</translation> </message> <message> <location filename="../optionsdialog.cpp" line="257"/> <source>default</source> <translation type="unfinished"/> </message> <message> <location filename="../optionsdialog.cpp" line="263"/> <source>The user interface language can be set here. This setting will only take effect after restarting Bitcoin.</source> <translation type="unfinished"/> </message> <message> <location filename="../optionsdialog.cpp" line="252"/> <source>User Interface &amp;Language:</source> <translation type="unfinished"/> </message> <message> <location filename="../optionsdialog.cpp" line="273"/> <source>&amp;Unit to show amounts in:</source> <translation type="unfinished"/> </message> <message> <location filename="../optionsdialog.cpp" line="277"/> <source>Choose the default subdivision unit to show in the interface, and when sending coins</source> <translation>Valitse oletus lisämääre mikä näkyy käyttöliittymässä ja kun lähetät kolikoita</translation> </message> <message> <location filename="../optionsdialog.cpp" line="284"/> <source>&amp;Display addresses in transaction list</source> <translation type="unfinished"/> </message> <message> <location filename="../optionsdialog.cpp" line="285"/> <source>Whether to show Bitcoin addresses in the transaction list</source> <translation type="unfinished"/> </message> <message> <location filename="../optionsdialog.cpp" line="303"/> <source>Warning</source> <translation type="unfinished"/> </message> <message> <location filename="../optionsdialog.cpp" line="303"/> <source>This setting will take effect after restarting Bitcoin.</source> <translation type="unfinished"/> </message> </context> <context> <name>EditAddressDialog</name> <message> <location filename="../forms/editaddressdialog.ui" line="14"/> <source>Edit Address</source> <translation>Muokkaa osoitetta</translation> </message> <message> <location filename="../forms/editaddressdialog.ui" line="25"/> <source>&amp;Label</source> <translation>&amp;Nimi</translation> </message> <message> <location filename="../forms/editaddressdialog.ui" line="35"/> <source>The label associated with this address book entry</source> <translation>Tähän osoitteeseen liitetty nimi</translation> </message> <message> <location filename="../forms/editaddressdialog.ui" line="42"/> <source>&amp;Address</source> <translation>&amp;Osoite</translation> </message> <message> <location filename="../forms/editaddressdialog.ui" line="52"/> <source>The address associated with this address book entry. This can only be modified for sending addresses.</source> <translation>Osoite, joka liittyy tämän osoitekirjan merkintään. Tätä voidaan muuttaa vain lähtevissä osoitteissa.</translation> </message> <message> <location filename="../editaddressdialog.cpp" line="20"/> <source>New receiving address</source> <translation>Uusi vastaanottava osoite</translation> </message> <message> <location filename="../editaddressdialog.cpp" line="24"/> <source>New sending address</source> <translation>Uusi lähettävä osoite</translation> </message> <message> <location filename="../editaddressdialog.cpp" line="27"/> <source>Edit receiving address</source> <translation>Muokkaa vastaanottajan osoitetta</translation> </message> <message> <location filename="../editaddressdialog.cpp" line="31"/> <source>Edit sending address</source> <translation>Muokkaa lähtevää osoitetta</translation> </message> <message> <location filename="../editaddressdialog.cpp" line="91"/> <source>The entered address &quot;%1&quot; is already in the address book.</source> <translation>Osoite &quot;%1&quot; on jo osoitekirjassa.</translation> </message> <message> <location filename="../editaddressdialog.cpp" line="96"/> <source>The entered address &quot;%1&quot; is not a valid Bitcoin address.</source> <translation type="unfinished"/> </message> <message> <location filename="../editaddressdialog.cpp" line="101"/> <source>Could not unlock wallet.</source> <translation>Lompakkoa ei voitu avata.</translation> </message> <message> <location filename="../editaddressdialog.cpp" line="106"/> <source>New key generation failed.</source> <translation>Uuden avaimen luonti epäonnistui.</translation> </message> </context> <context> <name>HelpMessageBox</name> <message> <location filename="../bitcoin.cpp" line="133"/> <location filename="../bitcoin.cpp" line="143"/> <source>Bitcoin-Qt</source> <translation type="unfinished"/> </message> <message> <location filename="../bitcoin.cpp" line="133"/> <source>version</source> <translation type="unfinished"/> </message> <message> <location filename="../bitcoin.cpp" line="135"/> <source>Usage:</source> <translation>Käyttö:</translation> </message> <message> <location filename="../bitcoin.cpp" line="136"/> <source>options</source> <translation type="unfinished"/> </message> <message> <location filename="../bitcoin.cpp" line="138"/> <source>UI options</source> <translation type="unfinished"/> </message> <message> <location filename="../bitcoin.cpp" line="139"/> <source>Set language, for example &quot;de_DE&quot; (default: system locale)</source> <translation>Set language, for example &quot;de_DE&quot; (default: system locale)</translation> </message> <message> <location filename="../bitcoin.cpp" line="140"/> <source>Start minimized</source> <translation>Käynnistä pienennettynä</translation> </message> <message> <location filename="../bitcoin.cpp" line="141"/> <source>Show splash screen on startup (default: 1)</source> <translation>Näytä aloitusruutu käynnistettäessä (oletus: 1)</translation> </message> </context> <context> <name>MainOptionsPage</name> <message> <location filename="../optionsdialog.cpp" line="227"/> <source>Detach block and address databases at shutdown. This means they can be moved to another data directory, but it slows down shutdown. The wallet is always detached.</source> <translation type="unfinished"/> </message> <message> <location filename="../optionsdialog.cpp" line="212"/> <source>Pay transaction &amp;fee</source> <translation>Maksa rahansiirtopalkkio</translation> </message> <message> <location filename="../optionsdialog.cpp" line="204"/> <source>Main</source> <translation>Yleiset</translation> </message> <message> <location filename="../optionsdialog.cpp" line="206"/> <source>Optional transaction fee per kB that helps make sure your transactions are processed quickly. Most transactions are 1 kB. Fee 0.01 recommended.</source> <translation>Vapaaehtoinen rahansiirtopalkkio per kB auttaa nopeuttamaan siirtoja. Useimmat rahansiirrot ovat 1 kB. 0.01 palkkio on suositeltava.</translation> </message> <message> <location filename="../optionsdialog.cpp" line="222"/> <source>&amp;Start Bitcoin on system login</source> <translation type="unfinished"/> </message> <message> <location filename="../optionsdialog.cpp" line="223"/> <source>Automatically start Bitcoin after logging in to the system</source> <translation type="unfinished"/> </message> <message> <location filename="../optionsdialog.cpp" line="226"/> <source>&amp;Detach databases at shutdown</source> <translation type="unfinished"/> </message> </context> <context> <name>MessagePage</name> <message> <location filename="../forms/messagepage.ui" line="14"/> <source>Sign Message</source> <translation type="unfinished"/> </message> <message> <location filename="../forms/messagepage.ui" line="20"/> <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>Voit allekirjoittaa viestit omalla osoitteellasi todistaaksesi että omistat ne. Ole huolellinen, että et allekirjoita mitään epämääräistä, phishing-hyökkääjät voivat huijata sinua allekirjoittamaan luovuttamalla henkilöllisyytesi. Allekirjoita selvitys täysin yksityiskohtaisesti mihin olet sitoutunut.</translation> </message> <message> <location filename="../forms/messagepage.ui" line="38"/> <source>The address to sign the message with (e.g. 1NS17iag9jJgTHD1VXjvLCEnZuQ3rJDE9L)</source> <translation>Osoite millä viesti allekirjoitetaan (esim. 1NS17iag9jJgTHD1VXjvLCEnZuQ3rJDE9L)</translation> </message> <message> <location filename="../forms/messagepage.ui" line="48"/> <source>Choose adress from address book</source> <translation>Valitse osoite osoitekirjasta</translation> </message> <message> <location filename="../forms/messagepage.ui" line="58"/> <source>Alt+A</source> <translation>Alt+A</translation> </message> <message> <location filename="../forms/messagepage.ui" line="71"/> <source>Paste address from clipboard</source> <translation>Liitä osoite leikepöydältä</translation> </message> <message> <location filename="../forms/messagepage.ui" line="81"/> <source>Alt+P</source> <translation>Alt+P</translation> </message> <message> <location filename="../forms/messagepage.ui" line="93"/> <source>Enter the message you want to sign here</source> <translation>Kirjoita tähän viesti minkä haluat allekirjoittaa</translation> </message> <message> <location filename="../forms/messagepage.ui" line="128"/> <source>Copy the current signature to the system clipboard</source> <translation type="unfinished"/> </message> <message> <location filename="../forms/messagepage.ui" line="131"/> <source>&amp;Copy Signature</source> <translation type="unfinished"/> </message> <message> <location filename="../forms/messagepage.ui" line="142"/> <source>Reset all sign message fields</source> <translation type="unfinished"/> </message> <message> <location filename="../forms/messagepage.ui" line="145"/> <source>Clear &amp;All</source> <translation type="unfinished"/> </message> <message> <location filename="../messagepage.cpp" line="31"/> <source>Click &quot;Sign Message&quot; to get signature</source> <translation>Klikkaa &quot;Allekirjoita viesti&quot; saadaksesi allekirjoituksen</translation> </message> <message> <location filename="../forms/messagepage.ui" line="114"/> <source>Sign a message to prove you own this address</source> <translation>Allekirjoita viesti millä todistat omistavasi tämän osoitteen</translation> </message> <message> <location filename="../forms/messagepage.ui" line="117"/> <source>&amp;Sign Message</source> <translation>&amp;Allekirjoita viesti</translation> </message> <message> <location filename="../messagepage.cpp" line="30"/> <source>Enter a Bitcoin address (e.g. 1NS17iag9jJgTHD1VXjvLCEnZuQ3rJDE9L)</source> <translation>Anna Bitcoin-osoite (esim. 1NS17iag9jJgTHD1VXjvLCEnZuQ3rJDE9L)</translation> </message> <message> <location filename="../messagepage.cpp" line="83"/> <location filename="../messagepage.cpp" line="90"/> <location filename="../messagepage.cpp" line="105"/> <location filename="../messagepage.cpp" line="117"/> <source>Error signing</source> <translation>Virhe allekirjoitettaessa</translation> </message> <message> <location filename="../messagepage.cpp" line="83"/> <source>%1 is not a valid address.</source> <translation>%1 ei ole kelvollinen osoite.</translation> </message> <message> <location filename="../messagepage.cpp" line="90"/> <source>%1 does not refer to a key.</source> <translation type="unfinished"/> </message> <message> <location filename="../messagepage.cpp" line="105"/> <source>Private key for %1 is not available.</source> <translation>Yksityisavain %1 :lle ei ole saatavilla.</translation> </message> <message> <location filename="../messagepage.cpp" line="117"/> <source>Sign failed</source> <translation>Allekirjoittaminen epäonnistui</translation> </message> </context> <context> <name>NetworkOptionsPage</name> <message> <location filename="../optionsdialog.cpp" line="345"/> <source>Network</source> <translation type="unfinished"/> </message> <message> <location filename="../optionsdialog.cpp" line="347"/> <source>Map port using &amp;UPnP</source> <translation>Portin uudelleenohjaus &amp;UPnP:llä</translation> </message> <message> <location filename="../optionsdialog.cpp" line="348"/> <source>Automatically open the Bitcoin client port on the router. This only works when your router supports UPnP and it is enabled.</source> <translation>Avaa Bitcoin-asiakasohjelman portti reitittimellä automaattisesti. Tämä toimii vain, jos reitittimesi tukee UPnP:tä ja se on käytössä.</translation> </message> <message> <location filename="../optionsdialog.cpp" line="351"/> <source>&amp;Connect through SOCKS4 proxy:</source> <translation>&amp;Yhdistä SOCKS4-välityspalvelimen kautta:</translation> </message> <message> <location filename="../optionsdialog.cpp" line="352"/> <source>Connect to the Bitcon network through a SOCKS4 proxy (e.g. when connecting through Tor)</source> <translation>Yhdistä Bitcoin-verkkoon SOCKS4-välityspalvelimen kautta (esimerkiksi käyttäessä Tor:ia)</translation> </message> <message> <location filename="../optionsdialog.cpp" line="357"/> <source>Proxy &amp;IP:</source> <translation type="unfinished"/> </message> <message> <location filename="../optionsdialog.cpp" line="366"/> <source>&amp;Port:</source> <translation type="unfinished"/> </message> <message> <location filename="../optionsdialog.cpp" line="363"/> <source>IP address of the proxy (e.g. 127.0.0.1)</source> <translation>Välityspalvelimen IP-osoite (esim. 127.0.0.1)</translation> </message> <message> <location filename="../optionsdialog.cpp" line="372"/> <source>Port of the proxy (e.g. 1234)</source> <translation>Portti, johon Bitcoin-asiakasohjelma yhdistää (esim. 1234)</translation> </message> </context> <context> <name>OptionsDialog</name> <message> <location filename="../optionsdialog.cpp" line="135"/> <source>Options</source> <translation>Asetukset</translation> </message> </context> <context> <name>OverviewPage</name> <message> <location filename="../forms/overviewpage.ui" line="14"/> <source>Form</source> <translation>Lomake</translation> </message> <message> <location filename="../forms/overviewpage.ui" line="47"/> <location filename="../forms/overviewpage.ui" line="204"/> <source>The displayed information may be out of date. Your wallet automatically synchronizes with the Bitcoin network after a connection is established, but this process has not completed yet.</source> <translation type="unfinished"/> </message> <message> <location filename="../forms/overviewpage.ui" line="89"/> <source>Balance:</source> <translation>Saldo:</translation> </message> <message> <location filename="../forms/overviewpage.ui" line="147"/> <source>Number of transactions:</source> <translation>Rahansiirtojen lukumäärä:</translation> </message> <message> <location filename="../forms/overviewpage.ui" line="118"/> <source>Unconfirmed:</source> <translation>Vahvistamatta:</translation> </message> <message> <location filename="../forms/overviewpage.ui" line="40"/> <source>Wallet</source> <translation>Lompakko</translation> </message> <message> <location filename="../forms/overviewpage.ui" line="197"/> <source>&lt;b&gt;Recent transactions&lt;/b&gt;</source> <translation>&lt;b&gt;Viimeisimmät rahansiirrot&lt;/b&gt;</translation> </message> <message> <location filename="../forms/overviewpage.ui" line="105"/> <source>Your current balance</source> <translation>Tililläsi tällä hetkellä olevien Bitcoinien määrä</translation> </message> <message> <location filename="../forms/overviewpage.ui" line="134"/> <source>Total of transactions that have yet to be confirmed, and do not yet count toward the current balance</source> <translation>Niiden saapuvien rahansiirtojen määrä, joita Bitcoin-verkko ei vielä ole ehtinyt vahvistaa ja siten eivät vielä näy saldossa.</translation> </message> <message> <location filename="../forms/overviewpage.ui" line="154"/> <source>Total number of transactions in wallet</source> <translation>Lompakolla tehtyjen rahansiirtojen yhteismäärä</translation> </message> <message> <location filename="../overviewpage.cpp" line="110"/> <location filename="../overviewpage.cpp" line="111"/> <source>out of sync</source> <translation type="unfinished"/> </message> </context> <context> <name>QRCodeDialog</name> <message> <location filename="../forms/qrcodedialog.ui" line="14"/> <source>QR Code Dialog</source> <translation type="unfinished"/> </message> <message> <location filename="../forms/qrcodedialog.ui" line="32"/> <source>QR Code</source> <translation>QR-koodi</translation> </message> <message> <location filename="../forms/qrcodedialog.ui" line="55"/> <source>Request Payment</source> <translation>Vastaanota maksu</translation> </message> <message> <location filename="../forms/qrcodedialog.ui" line="70"/> <source>Amount:</source> <translation>Määrä:</translation> </message> <message> <location filename="../forms/qrcodedialog.ui" line="105"/> <source>BTC</source> <translation>BTC</translation> </message> <message> <location filename="../forms/qrcodedialog.ui" line="121"/> <source>Label:</source> <translation>Tunniste:</translation> </message> <message> <location filename="../forms/qrcodedialog.ui" line="144"/> <source>Message:</source> <translation>Viesti:</translation> </message> <message> <location filename="../forms/qrcodedialog.ui" line="186"/> <source>&amp;Save As...</source> <translation>&amp;Tallenna nimellä...</translation> </message> <message> <location filename="../qrcodedialog.cpp" line="45"/> <source>Error encoding URI into QR Code.</source> <translation type="unfinished"/> </message> <message> <location filename="../qrcodedialog.cpp" line="63"/> <source>Resulting URI too long, try to reduce the text for label / message.</source> <translation>Tuloksen URI liian pitkä, yritä lyhentää otsikon tekstiä / viestiä.</translation> </message> <message> <location filename="../qrcodedialog.cpp" line="120"/> <source>Save QR Code</source> <translation type="unfinished"/> </message> <message> <location filename="../qrcodedialog.cpp" line="120"/> <source>PNG Images (*.png)</source> <translation>PNG kuvat (*png)</translation> </message> </context> <context> <name>RPCConsole</name> <message> <location filename="../forms/rpcconsole.ui" line="14"/> <source>Bitcoin debug window</source> <translation type="unfinished"/> </message> <message> <location filename="../forms/rpcconsole.ui" line="46"/> <source>Client name</source> <translation type="unfinished"/> </message> <message> <location filename="../forms/rpcconsole.ui" line="56"/> <location filename="../forms/rpcconsole.ui" line="79"/> <location filename="../forms/rpcconsole.ui" line="102"/> <location filename="../forms/rpcconsole.ui" line="125"/> <location filename="../forms/rpcconsole.ui" line="161"/> <location filename="../forms/rpcconsole.ui" line="214"/> <location filename="../forms/rpcconsole.ui" line="237"/> <location filename="../forms/rpcconsole.ui" line="260"/> <location filename="../rpcconsole.cpp" line="245"/> <source>N/A</source> <translation type="unfinished"/> </message> <message> <location filename="../forms/rpcconsole.ui" line="69"/> <source>Client version</source> <translation type="unfinished"/> </message> <message> <location filename="../forms/rpcconsole.ui" line="24"/> <source>&amp;Information</source> <translation type="unfinished"/> </message> <message> <location filename="../forms/rpcconsole.ui" line="39"/> <source>Client</source> <translation type="unfinished"/> </message> <message> <location filename="../forms/rpcconsole.ui" line="115"/> <source>Startup time</source> <translation type="unfinished"/> </message> <message> <location filename="../forms/rpcconsole.ui" line="144"/> <source>Network</source> <translation type="unfinished"/> </message> <message> <location filename="../forms/rpcconsole.ui" line="151"/> <source>Number of connections</source> <translation type="unfinished"/> </message> <message> <location filename="../forms/rpcconsole.ui" line="174"/> <source>On testnet</source> <translation type="unfinished"/> </message> <message> <location filename="../forms/rpcconsole.ui" line="197"/> <source>Block chain</source> <translation type="unfinished"/> </message> <message> <location filename="../forms/rpcconsole.ui" line="204"/> <source>Current number of blocks</source> <translation type="unfinished"/> </message> <message> <location filename="../forms/rpcconsole.ui" line="227"/> <source>Estimated total blocks</source> <translation type="unfinished"/> </message> <message> <location filename="../forms/rpcconsole.ui" line="250"/> <source>Last block time</source> <translation type="unfinished"/> </message> <message> <location filename="../forms/rpcconsole.ui" line="292"/> <source>Debug logfile</source> <translation type="unfinished"/> </message> <message> <location filename="../forms/rpcconsole.ui" line="299"/> <source>Open the Bitcoin debug logfile from the current data directory. This can take a few seconds for large logfiles.</source> <translation type="unfinished"/> </message> <message> <location filename="../forms/rpcconsole.ui" line="302"/> <source>&amp;Open</source> <translation type="unfinished"/> </message> <message> <location filename="../forms/rpcconsole.ui" line="323"/> <source>&amp;Console</source> <translation type="unfinished"/> </message> <message> <location filename="../forms/rpcconsole.ui" line="92"/> <source>Build date</source> <translation type="unfinished"/> </message> <message> <location filename="../forms/rpcconsole.ui" line="372"/> <source>Clear console</source> <translation type="unfinished"/> </message> <message> <location filename="../rpcconsole.cpp" line="212"/> <source>Welcome to the Bitcoin RPC console.</source> <translation type="unfinished"/> </message> <message> <location filename="../rpcconsole.cpp" line="213"/> <source>Use up and down arrows to navigate history, and &lt;b&gt;Ctrl-L&lt;/b&gt; to clear screen.</source> <translation type="unfinished"/> </message> <message> <location filename="../rpcconsole.cpp" line="214"/> <source>Type &lt;b&gt;help&lt;/b&gt; for an overview of available commands.</source> <translation type="unfinished"/> </message> </context> <context> <name>SendCoinsDialog</name> <message> <location filename="../forms/sendcoinsdialog.ui" line="14"/> <location filename="../sendcoinsdialog.cpp" line="122"/> <location filename="../sendcoinsdialog.cpp" line="127"/> <location filename="../sendcoinsdialog.cpp" line="132"/> <location filename="../sendcoinsdialog.cpp" line="137"/> <location filename="../sendcoinsdialog.cpp" line="143"/> <location filename="../sendcoinsdialog.cpp" line="148"/> <location filename="../sendcoinsdialog.cpp" line="153"/> <source>Send Coins</source> <translation>Lähetä Bitcoineja</translation> </message> <message> <location filename="../forms/sendcoinsdialog.ui" line="64"/> <source>Send to multiple recipients at once</source> <translation>Lähetä monelle vastaanottajalle</translation> </message> <message> <location filename="../forms/sendcoinsdialog.ui" line="67"/> <source>&amp;Add Recipient</source> <translation type="unfinished"/> </message> <message> <location filename="../forms/sendcoinsdialog.ui" line="84"/> <source>Remove all transaction fields</source> <translation>Poista kaikki rahansiirtokentät</translation> </message> <message> <location filename="../forms/sendcoinsdialog.ui" line="87"/> <source>Clear &amp;All</source> <translation type="unfinished"/> </message> <message> <location filename="../forms/sendcoinsdialog.ui" line="106"/> <source>Balance:</source> <translation>Saldo:</translation> </message> <message> <location filename="../forms/sendcoinsdialog.ui" line="113"/> <source>123.456 BTC</source> <translation>123,456 BTC</translation> </message> <message> <location filename="../forms/sendcoinsdialog.ui" line="144"/> <source>Confirm the send action</source> <translation>Vahvista lähetys</translation> </message> <message> <location filename="../forms/sendcoinsdialog.ui" line="147"/> <source>&amp;Send</source> <translation>&amp;Lähetä</translation> </message> <message> <location filename="../sendcoinsdialog.cpp" line="94"/> <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 filename="../sendcoinsdialog.cpp" line="99"/> <source>Confirm send coins</source> <translation>Hyväksy Bitcoinien lähettäminen</translation> </message> <message> <location filename="../sendcoinsdialog.cpp" line="100"/> <source>Are you sure you want to send %1?</source> <translation>Haluatko varmasti lähettää %1?</translation> </message> <message> <location filename="../sendcoinsdialog.cpp" line="100"/> <source> and </source> <translation> ja </translation> </message> <message> <location filename="../sendcoinsdialog.cpp" line="123"/> <source>The recepient address is not valid, please recheck.</source> <translation>Vastaanottajan osoite ei kelpaa, ole hyvä ja tarkista</translation> </message> <message> <location filename="../sendcoinsdialog.cpp" line="128"/> <source>The amount to pay must be larger than 0.</source> <translation>Maksettavan summan tulee olla suurempi kuin 0 Bitcoinia.</translation> </message> <message> <location filename="../sendcoinsdialog.cpp" line="133"/> <source>The amount exceeds your balance.</source> <translation type="unfinished"/> </message> <message> <location filename="../sendcoinsdialog.cpp" line="138"/> <source>The total exceeds your balance when the %1 transaction fee is included.</source> <translation type="unfinished"/> </message> <message> <location filename="../sendcoinsdialog.cpp" line="144"/> <source>Duplicate address found, can only send to each address once per send operation.</source> <translation type="unfinished"/> </message> <message> <location filename="../sendcoinsdialog.cpp" line="149"/> <source>Error: Transaction creation failed.</source> <translation type="unfinished"/> </message> <message> <location filename="../sendcoinsdialog.cpp" line="154"/> <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 type="unfinished"/> </message> </context> <context> <name>SendCoinsEntry</name> <message> <location filename="../forms/sendcoinsentry.ui" line="14"/> <source>Form</source> <translation>Lomake</translation> </message> <message> <location filename="../forms/sendcoinsentry.ui" line="29"/> <source>A&amp;mount:</source> <translation>M&amp;äärä:</translation> </message> <message> <location filename="../forms/sendcoinsentry.ui" line="42"/> <source>Pay &amp;To:</source> <translation>Maksun saaja:</translation> </message> <message> <location filename="../forms/sendcoinsentry.ui" line="66"/> <location filename="../sendcoinsentry.cpp" line="25"/> <source>Enter a label for this address to add it to your address book</source> <translation>Anna nimi tälle osoitteelle, jos haluat lisätä sen osoitekirjaan</translation> </message> <message> <location filename="../forms/sendcoinsentry.ui" line="75"/> <source>&amp;Label:</source> <translation>&amp;Nimi:</translation> </message> <message> <location filename="../forms/sendcoinsentry.ui" line="93"/> <source>The address to send the payment to (e.g. 1NS17iag9jJgTHD1VXjvLCEnZuQ3rJDE9L)</source> <translation>Osoite, johon Bitcoinit lähetetään (esim. 1NS17iag9jJgTHD1VXjvLCEnZuQ3rJDE9L)</translation> </message> <message> <location filename="../forms/sendcoinsentry.ui" line="103"/> <source>Choose address from address book</source> <translation>Valitse osoite osoitekirjasta</translation> </message> <message> <location filename="../forms/sendcoinsentry.ui" line="113"/> <source>Alt+A</source> <translation>Alt+A</translation> </message> <message> <location filename="../forms/sendcoinsentry.ui" line="120"/> <source>Paste address from clipboard</source> <translation>Liitä osoite leikepöydältä</translation> </message> <message> <location filename="../forms/sendcoinsentry.ui" line="130"/> <source>Alt+P</source> <translation>Alt+P</translation> </message> <message> <location filename="../forms/sendcoinsentry.ui" line="137"/> <source>Remove this recipient</source> <translation>Poista </translation> </message> <message> <location filename="../sendcoinsentry.cpp" line="26"/> <source>Enter a Bitcoin address (e.g. 1NS17iag9jJgTHD1VXjvLCEnZuQ3rJDE9L)</source> <translation>Anna Bitcoin-osoite (esim. 1NS17iag9jJgTHD1VXjvLCEnZuQ3rJDE9L)</translation> </message> </context> <context> <name>TransactionDesc</name> <message> <location filename="../transactiondesc.cpp" line="21"/> <source>Open for %1 blocks</source> <translation>Avoinna %1 lohkolle</translation> </message> <message> <location filename="../transactiondesc.cpp" line="23"/> <source>Open until %1</source> <translation>Avoinna %1 asti</translation> </message> <message> <location filename="../transactiondesc.cpp" line="29"/> <source>%1/offline?</source> <translation>%1/ei linjalla?</translation> </message> <message> <location filename="../transactiondesc.cpp" line="31"/> <source>%1/unconfirmed</source> <translation>%1/vahvistamaton</translation> </message> <message> <location filename="../transactiondesc.cpp" line="33"/> <source>%1 confirmations</source> <translation>%1 vahvistusta</translation> </message> <message> <location filename="../transactiondesc.cpp" line="51"/> <source>&lt;b&gt;Status:&lt;/b&gt; </source> <translation>&lt;b&gt;Tila:&lt;/b&gt; </translation> </message> <message> <location filename="../transactiondesc.cpp" line="56"/> <source>, has not been successfully broadcast yet</source> <translation>, ei ole vielä onnistuneesti lähetetty</translation> </message> <message> <location filename="../transactiondesc.cpp" line="58"/> <source>, broadcast through %1 node</source> <translation>, lähetetään %1 solmun kautta</translation> </message> <message> <location filename="../transactiondesc.cpp" line="60"/> <source>, broadcast through %1 nodes</source> <translation>, lähetetään %1 solmun kautta</translation> </message> <message> <location filename="../transactiondesc.cpp" line="64"/> <source>&lt;b&gt;Date:&lt;/b&gt; </source> <translation>&lt;b&gt;Päivä:&lt;/b&gt; </translation> </message> <message> <location filename="../transactiondesc.cpp" line="71"/> <source>&lt;b&gt;Source:&lt;/b&gt; Generated&lt;br&gt;</source> <translation>&lt;b&gt;Lähde:&lt;/b&gt; Generoitu&lt;br&gt;</translation> </message> <message> <location filename="../transactiondesc.cpp" line="77"/> <location filename="../transactiondesc.cpp" line="94"/> <source>&lt;b&gt;From:&lt;/b&gt; </source> <translation>&lt;b&gt;Lähettäjä:&lt;/b&gt; </translation> </message> <message> <location filename="../transactiondesc.cpp" line="94"/> <source>unknown</source> <translation>tuntematon</translation> </message> <message> <location filename="../transactiondesc.cpp" line="95"/> <location filename="../transactiondesc.cpp" line="118"/> <location filename="../transactiondesc.cpp" line="178"/> <source>&lt;b&gt;To:&lt;/b&gt; </source> <translation>&lt;b&gt;Vast. ott.:&lt;/b&gt;</translation> </message> <message> <location filename="../transactiondesc.cpp" line="98"/> <source> (yours, label: </source> <translation>(sinun, tunniste: </translation> </message> <message> <location filename="../transactiondesc.cpp" line="100"/> <source> (yours)</source> <translation>(sinun)</translation> </message> <message> <location filename="../transactiondesc.cpp" line="136"/> <location filename="../transactiondesc.cpp" line="150"/> <location filename="../transactiondesc.cpp" line="195"/> <location filename="../transactiondesc.cpp" line="212"/> <source>&lt;b&gt;Credit:&lt;/b&gt; </source> <translation>&lt;b&gt;Krediitti:&lt;/b&gt; </translation> </message> <message> <location filename="../transactiondesc.cpp" line="138"/> <source>(%1 matures in %2 more blocks)</source> <translation>(%1 erääntyy %2 useammassa lohkossa)</translation> </message> <message> <location filename="../transactiondesc.cpp" line="142"/> <source>(not accepted)</source> <translation>(ei hyväksytty)</translation> </message> <message> <location filename="../transactiondesc.cpp" line="186"/> <location filename="../transactiondesc.cpp" line="194"/> <location filename="../transactiondesc.cpp" line="209"/> <source>&lt;b&gt;Debit:&lt;/b&gt; </source> <translation>&lt;b&gt;Debit:&lt;/b&gt; </translation> </message> <message> <location filename="../transactiondesc.cpp" line="200"/> <source>&lt;b&gt;Transaction fee:&lt;/b&gt; </source> <translation>&lt;b&gt;Rahansiirtomaksu:&lt;/b&gt; </translation> </message> <message> <location filename="../transactiondesc.cpp" line="216"/> <source>&lt;b&gt;Net amount:&lt;/b&gt; </source> <translation>&lt;b&gt;Nettomäärä:&lt;/b&gt; </translation> </message> <message> <location filename="../transactiondesc.cpp" line="222"/> <source>Message:</source> <translation>Viesti:</translation> </message> <message> <location filename="../transactiondesc.cpp" line="224"/> <source>Comment:</source> <translation>Kommentti:</translation> </message> <message> <location filename="../transactiondesc.cpp" line="226"/> <source>Transaction ID:</source> <translation>Rahansiirron ID:</translation> </message> <message> <location filename="../transactiondesc.cpp" line="229"/> <source>Generated coins must wait 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, it will change to &quot;not accepted&quot; and not be spendable. This may occasionally happen if another node generates a block within a few seconds of yours.</source> <translation>Luotujen kolikoiden on odotettava 120 lohkoa ennen kuin ne voidaan käyttää. Kun loit tämän lohkon, se lähetettiin verkkoon lisättäväksi lohkoketjuun. Jos se epäonnistuu ketjuun liittymisessä, sen tila muuttuu &quot;ei hyväksytty&quot; eikä sitä voi käyttää. Tätä voi silloin tällöin esiintyä jos toinen solmu luo lohkon muutamia sekunteja omastasi.</translation> </message> </context> <context> <name>TransactionDescDialog</name> <message> <location filename="../forms/transactiondescdialog.ui" line="14"/> <source>Transaction details</source> <translation>Rahansiirron yksityiskohdat</translation> </message> <message> <location filename="../forms/transactiondescdialog.ui" line="20"/> <source>This pane shows a detailed description of the transaction</source> <translation>Tämä ruutu näyttää yksityiskohtaisen tiedon rahansiirrosta</translation> </message> </context> <context> <name>TransactionTableModel</name> <message> <location filename="../transactiontablemodel.cpp" line="226"/> <source>Date</source> <translation>Päivämäärä</translation> </message> <message> <location filename="../transactiontablemodel.cpp" line="226"/> <source>Type</source> <translation>Laatu</translation> </message> <message> <location filename="../transactiontablemodel.cpp" line="226"/> <source>Address</source> <translation>Osoite</translation> </message> <message> <location filename="../transactiontablemodel.cpp" line="226"/> <source>Amount</source> <translation>Määrä</translation> </message> <message numerus="yes"> <location filename="../transactiontablemodel.cpp" line="281"/> <source>Open for %n block(s)</source> <translation><numerusform>Auki %n lohkolle</numerusform><numerusform>Auki %n lohkoille</numerusform></translation> </message> <message> <location filename="../transactiontablemodel.cpp" line="284"/> <source>Open until %1</source> <translation>Avoinna %1 asti</translation> </message> <message> <location filename="../transactiontablemodel.cpp" line="287"/> <source>Offline (%1 confirmations)</source> <translation>Ei yhteyttä verkkoon (%1 vahvistusta)</translation> </message> <message> <location filename="../transactiontablemodel.cpp" line="290"/> <source>Unconfirmed (%1 of %2 confirmations)</source> <translation>Vahvistamatta (%1/%2 vahvistusta)</translation> </message> <message> <location filename="../transactiontablemodel.cpp" line="293"/> <source>Confirmed (%1 confirmations)</source> <translation>Vahvistettu (%1 vahvistusta)</translation> </message> <message numerus="yes"> <location filename="../transactiontablemodel.cpp" line="301"/> <source>Mined balance will be available in %n more blocks</source> <translation><numerusform>Louhittu saldo tulee saataville %n lohkossa</numerusform><numerusform>Louhittu saldo tulee saataville %n lohkossa</numerusform></translation> </message> <message> <location filename="../transactiontablemodel.cpp" line="307"/> <source>This block was not received by any other nodes and will probably not be accepted!</source> <translation>Tätä lohkoa ei vastaanotettu mistään muusta solmusta ja sitä ei mahdollisesti hyväksytä!</translation> </message> <message> <location filename="../transactiontablemodel.cpp" line="310"/> <source>Generated but not accepted</source> <translation>Generoitu mutta ei hyväksytty</translation> </message> <message> <location filename="../transactiontablemodel.cpp" line="353"/> <source>Received with</source> <translation>Vastaanotettu osoitteella</translation> </message> <message> <location filename="../transactiontablemodel.cpp" line="355"/> <source>Received from</source> <translation>Vastaanotettu</translation> </message> <message> <location filename="../transactiontablemodel.cpp" line="358"/> <source>Sent to</source> <translation>Saaja</translation> </message> <message> <location filename="../transactiontablemodel.cpp" line="360"/> <source>Payment to yourself</source> <translation>Maksu itsellesi</translation> </message> <message> <location filename="../transactiontablemodel.cpp" line="362"/> <source>Mined</source> <translation>Louhittu</translation> </message> <message> <location filename="../transactiontablemodel.cpp" line="400"/> <source>(n/a)</source> <translation>(ei saatavilla)</translation> </message> <message> <location filename="../transactiontablemodel.cpp" line="599"/> <source>Transaction status. Hover over this field to show number of confirmations.</source> <translation>Rahansiirron tila. Siirrä osoitin kentän päälle nähdäksesi vahvistusten lukumäärä.</translation> </message> <message> <location filename="../transactiontablemodel.cpp" line="601"/> <source>Date and time that the transaction was received.</source> <translation>Rahansiirron vastaanottamisen päivämäärä ja aika.</translation> </message> <message> <location filename="../transactiontablemodel.cpp" line="603"/> <source>Type of transaction.</source> <translation>Rahansiirron laatu.</translation> </message> <message> <location filename="../transactiontablemodel.cpp" line="605"/> <source>Destination address of transaction.</source> <translation>Rahansiirron kohteen Bitcoin-osoite</translation> </message> <message> <location filename="../transactiontablemodel.cpp" line="607"/> <source>Amount removed from or added to balance.</source> <translation>Saldoon lisätty tai siitä vähennetty määrä.</translation> </message> </context> <context> <name>TransactionView</name> <message> <location filename="../transactionview.cpp" line="55"/> <location filename="../transactionview.cpp" line="71"/> <source>All</source> <translation>Kaikki</translation> </message> <message> <location filename="../transactionview.cpp" line="56"/> <source>Today</source> <translation>Tänään</translation> </message> <message> <location filename="../transactionview.cpp" line="57"/> <source>This week</source> <translation>Tällä viikolla</translation> </message> <message> <location filename="../transactionview.cpp" line="58"/> <source>This month</source> <translation>Tässä kuussa</translation> </message> <message> <location filename="../transactionview.cpp" line="59"/> <source>Last month</source> <translation>Viime kuussa</translation> </message> <message> <location filename="../transactionview.cpp" line="60"/> <source>This year</source> <translation>Tänä vuonna</translation> </message> <message> <location filename="../transactionview.cpp" line="61"/> <source>Range...</source> <translation>Alue...</translation> </message> <message> <location filename="../transactionview.cpp" line="72"/> <source>Received with</source> <translation>Vastaanotettu osoitteella</translation> </message> <message> <location filename="../transactionview.cpp" line="74"/> <source>Sent to</source> <translation>Saaja</translation> </message> <message> <location filename="../transactionview.cpp" line="76"/> <source>To yourself</source> <translation>Itsellesi</translation> </message> <message> <location filename="../transactionview.cpp" line="77"/> <source>Mined</source> <translation>Louhittu</translation> </message> <message> <location filename="../transactionview.cpp" line="78"/> <source>Other</source> <translation>Muu</translation> </message> <message> <location filename="../transactionview.cpp" line="85"/> <source>Enter address or label to search</source> <translation>Anna etsittävä osoite tai tunniste</translation> </message> <message> <location filename="../transactionview.cpp" line="92"/> <source>Min amount</source> <translation>Minimimäärä</translation> </message> <message> <location filename="../transactionview.cpp" line="126"/> <source>Copy address</source> <translation>Kopioi osoite</translation> </message> <message> <location filename="../transactionview.cpp" line="127"/> <source>Copy label</source> <translation>Kopioi nimi</translation> </message> <message> <location filename="../transactionview.cpp" line="128"/> <source>Copy amount</source> <translation>Kopioi määrä</translation> </message> <message> <location filename="../transactionview.cpp" line="129"/> <source>Edit label</source> <translation>Muokkaa nimeä</translation> </message> <message> <location filename="../transactionview.cpp" line="130"/> <source>Show transaction details</source> <translation type="unfinished"/> </message> <message> <location filename="../transactionview.cpp" line="270"/> <source>Export Transaction Data</source> <translation>Vie rahansiirron tiedot</translation> </message> <message> <location filename="../transactionview.cpp" line="271"/> <source>Comma separated file (*.csv)</source> <translation>Comma separated file (*.csv)</translation> </message> <message> <location filename="../transactionview.cpp" line="279"/> <source>Confirmed</source> <translation>Vahvistettu</translation> </message> <message> <location filename="../transactionview.cpp" line="280"/> <source>Date</source> <translation>Aika</translation> </message> <message> <location filename="../transactionview.cpp" line="281"/> <source>Type</source> <translation>Laatu</translation> </message> <message> <location filename="../transactionview.cpp" line="282"/> <source>Label</source> <translation>Nimi</translation> </message> <message> <location filename="../transactionview.cpp" line="283"/> <source>Address</source> <translation>Osoite</translation> </message> <message> <location filename="../transactionview.cpp" line="284"/> <source>Amount</source> <translation>Määrä</translation> </message> <message> <location filename="../transactionview.cpp" line="285"/> <source>ID</source> <translation>ID</translation> </message> <message> <location filename="../transactionview.cpp" line="289"/> <source>Error exporting</source> <translation>Virhe tietojen viennissä</translation> </message> <message> <location filename="../transactionview.cpp" line="289"/> <source>Could not write to file %1.</source> <translation>Ei voida kirjoittaa tiedostoon %1.</translation> </message> <message> <location filename="../transactionview.cpp" line="384"/> <source>Range:</source> <translation>Alue:</translation> </message> <message> <location filename="../transactionview.cpp" line="392"/> <source>to</source> <translation>kenelle</translation> </message> </context> <context> <name>VerifyMessageDialog</name> <message> <location filename="../forms/verifymessagedialog.ui" line="14"/> <source>Verify Signed Message</source> <translation type="unfinished"/> </message> <message> <location filename="../forms/verifymessagedialog.ui" line="20"/> <source>Enter the message and signature below (be careful to correctly copy newlines, spaces, tabs and other invisible characters) to obtain the Bitcoin address used to sign the message.</source> <translation type="unfinished"/> </message> <message> <location filename="../forms/verifymessagedialog.ui" line="62"/> <source>Verify a message and obtain the Bitcoin address used to sign the message</source> <translation type="unfinished"/> </message> <message> <location filename="../forms/verifymessagedialog.ui" line="65"/> <source>&amp;Verify Message</source> <translation type="unfinished"/> </message> <message> <location filename="../forms/verifymessagedialog.ui" line="79"/> <source>Copy the currently selected address to the system clipboard</source> <translation>Kopioi valittu osoite leikepöydälle</translation> </message> <message> <location filename="../forms/verifymessagedialog.ui" line="82"/> <source>&amp;Copy Address</source> <translation type="unfinished"/> </message> <message> <location filename="../forms/verifymessagedialog.ui" line="93"/> <source>Reset all verify message fields</source> <translation type="unfinished"/> </message> <message> <location filename="../forms/verifymessagedialog.ui" line="96"/> <source>Clear &amp;All</source> <translation type="unfinished"/> </message> <message> <location filename="../verifymessagedialog.cpp" line="28"/> <source>Enter Bitcoin signature</source> <translation type="unfinished"/> </message> <message> <location filename="../verifymessagedialog.cpp" line="29"/> <source>Click &quot;Verify Message&quot; to obtain address</source> <translation type="unfinished"/> </message> <message> <location filename="../verifymessagedialog.cpp" line="55"/> <location filename="../verifymessagedialog.cpp" line="62"/> <source>Invalid Signature</source> <translation type="unfinished"/> </message> <message> <location filename="../verifymessagedialog.cpp" line="55"/> <source>The signature could not be decoded. Please check the signature and try again.</source> <translation type="unfinished"/> </message> <message> <location filename="../verifymessagedialog.cpp" line="62"/> <source>The signature did not match the message digest. Please check the signature and try again.</source> <translation type="unfinished"/> </message> <message> <location filename="../verifymessagedialog.cpp" line="72"/> <source>Address not found in address book.</source> <translation type="unfinished"/> </message> <message> <location filename="../verifymessagedialog.cpp" line="72"/> <source>Address found in address book: %1</source> <translation type="unfinished"/> </message> </context> <context> <name>WalletModel</name> <message> <location filename="../walletmodel.cpp" line="158"/> <source>Sending...</source> <translation>Lähetetään...</translation> </message> </context> <context> <name>WindowOptionsPage</name> <message> <location filename="../optionsdialog.cpp" line="313"/> <source>Window</source> <translation type="unfinished"/> </message> <message> <location filename="../optionsdialog.cpp" line="316"/> <source>&amp;Minimize to the tray instead of the taskBHC</source> <translation>&amp;Pienennä ilmaisinalueelle työkalurivin sijasta</translation> </message> <message> <location filename="../optionsdialog.cpp" line="317"/> <source>Show only a tray icon after minimizing the window</source> <translation>Näytä ainoastaan pikkukuvake ikkunan pienentämisen jälkeen</translation> </message> <message> <location filename="../optionsdialog.cpp" line="320"/> <source>M&amp;inimize on close</source> <translation type="unfinished"/> </message> <message> <location filename="../optionsdialog.cpp" line="321"/> <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>Ikkunaa suljettaessa vain pienentää Bitcoin-ohjelman ikkunan lopettamatta itse ohjelmaa. Kun tämä asetus on valittuna, ohjelman voi sulkea vain valitsemalla Lopeta ohjelman valikosta.</translation> </message> </context> <context> <name>bitcoin-core</name> <message> <location filename="../bitcoinstrings.cpp" line="43"/> <source>Bitcoin version</source> <translation>Bitcoinin versio</translation> </message> <message> <location filename="../bitcoinstrings.cpp" line="44"/> <source>Usage:</source> <translation>Käyttö:</translation> </message> <message> <location filename="../bitcoinstrings.cpp" line="45"/> <source>Send command to -server or bitcoind</source> <translation>Lähetä käsky palvelimelle tai bitcoind:lle</translation> </message> <message> <location filename="../bitcoinstrings.cpp" line="46"/> <source>List commands</source> <translation>Lista komennoista</translation> </message> <message> <location filename="../bitcoinstrings.cpp" line="47"/> <source>Get help for a command</source> <translation>Hanki apua käskyyn</translation> </message> <message> <location filename="../bitcoinstrings.cpp" line="49"/> <source>Options:</source> <translation>Asetukset:</translation> </message> <message> <location filename="../bitcoinstrings.cpp" line="50"/> <source>Specify configuration file (default: bitcoin.conf)</source> <translation>Määritä asetustiedosto (oletus: bitcoin.conf)</translation> </message> <message> <location filename="../bitcoinstrings.cpp" line="51"/> <source>Specify pid file (default: bitcoind.pid)</source> <translation>Määritä pid-tiedosto (oletus: bitcoin.pid)</translation> </message> <message> <location filename="../bitcoinstrings.cpp" line="52"/> <source>Generate coins</source> <translation>Generoi kolikoita</translation> </message> <message> <location filename="../bitcoinstrings.cpp" line="53"/> <source>Don&apos;t generate coins</source> <translation>Älä generoi kolikoita</translation> </message> <message> <location filename="../bitcoinstrings.cpp" line="54"/> <source>Specify data directory</source> <translation>Määritä data-hakemisto</translation> </message> <message> <location filename="../bitcoinstrings.cpp" line="55"/> <source>Set database cache size in megabytes (default: 25)</source> <translation>Aseta tietokannan välimuistin koko megatavuina (oletus: 25)</translation> </message> <message> <location filename="../bitcoinstrings.cpp" line="56"/> <source>Set database disk log size in megabytes (default: 100)</source> <translation>Aseta tietokannan lokitiedoston koko megatavuina (oletus: 100)</translation> </message> <message> <location filename="../bitcoinstrings.cpp" line="57"/> <source>Specify connection timeout (in milliseconds)</source> <translation>Määritä yhteyden aikakatkaisu (millisekunneissa)</translation> </message> <message> <location filename="../bitcoinstrings.cpp" line="63"/> <source>Listen for connections on &lt;port&gt; (default: 8333 or testnet: 18333)</source> <translation>Kuuntele yhteyksiä portista &lt;port&gt; (oletus: 8333 tai testnet: 18333)</translation> </message> <message> <location filename="../bitcoinstrings.cpp" line="64"/> <source>Maintain at most &lt;n&gt; connections to peers (default: 125)</source> <translation>Pidä enintään &lt;n&gt; yhteyttä verkkoihin (oletus: 125)</translation> </message> <message> <location filename="../bitcoinstrings.cpp" line="66"/> <source>Connect only to the specified node</source> <translation>Muodosta yhteys vain tiettyyn solmuun</translation> </message> <message> <location filename="../bitcoinstrings.cpp" line="67"/> <source>Connect to a node to retrieve peer addresses, and disconnect</source> <translation type="unfinished"/> </message> <message> <location filename="../bitcoinstrings.cpp" line="68"/> <source>Specify your own public address</source> <translation type="unfinished"/> </message> <message> <location filename="../bitcoinstrings.cpp" line="69"/> <source>Only connect to nodes in network &lt;net&gt; (IPv4 or IPv6)</source> <translation type="unfinished"/> </message> <message> <location filename="../bitcoinstrings.cpp" line="70"/> <source>Try to discover public IP address (default: 1)</source> <translation type="unfinished"/> </message> <message> <location filename="../bitcoinstrings.cpp" line="73"/> <source>Bind to given address. Use [host]:port notation for IPv6</source> <translation type="unfinished"/> </message> <message> <location filename="../bitcoinstrings.cpp" line="75"/> <source>Threshold for disconnecting misbehaving peers (default: 100)</source> <translation>Kynnysarvo aikakatkaisulle heikosti toimiville verkoille (oletus: 100)</translation> </message> <message> <location filename="../bitcoinstrings.cpp" line="76"/> <source>Number of seconds to keep misbehaving peers from reconnecting (default: 86400)</source> <translation>Sekuntien määrä, kuinka kauan uudelleenkytkeydytään verkkoihin (oletus: 86400)</translation> </message> <message> <location filename="../bitcoinstrings.cpp" line="79"/> <source>Maximum per-connection receive buffer, &lt;n&gt;*1000 bytes (default: 10000)</source> <translation>Maksimi verkkoyhteyden vastaanottopuskuri, &lt;n&gt;*1000 tavua (oletus: 10000)</translation> </message> <message> <location filename="../bitcoinstrings.cpp" line="80"/> <source>Maximum per-connection send buffer, &lt;n&gt;*1000 bytes (default: 10000)</source> <translation>Maksimi verkkoyhteyden lähetyspuskuri, &lt;n&gt;*1000 tavua (oletus: 10000)</translation> </message> <message> <location filename="../bitcoinstrings.cpp" line="83"/> <source>Detach block and address databases. Increases shutdown time (default: 0)</source> <translation type="unfinished"/> </message> <message> <location filename="../bitcoinstrings.cpp" line="86"/> <source>Accept command line and JSON-RPC commands</source> <translation>Hyväksy merkkipohjaiset- ja JSON-RPC-käskyt</translation> </message> <message> <location filename="../bitcoinstrings.cpp" line="87"/> <source>Run in the background as a daemon and accept commands</source> <translation>Aja taustalla daemonina ja hyväksy komennot</translation> </message> <message> <location filename="../bitcoinstrings.cpp" line="88"/> <source>Use the test network</source> <translation>Käytä test -verkkoa</translation> </message> <message> <location filename="../bitcoinstrings.cpp" line="89"/> <source>Output extra debugging information</source> <translation>Tulosta ylimääräistä debuggaustietoa</translation> </message> <message> <location filename="../bitcoinstrings.cpp" line="90"/> <source>Prepend debug output with timestamp</source> <translation>Lisää debuggaustiedon tulostukseen aikaleima</translation> </message> <message> <location filename="../bitcoinstrings.cpp" line="91"/> <source>Send trace/debug info to console instead of debug.log file</source> <translation>Lähetä jäljitys/debug-tieto konsoliin, debug.log-tiedoston sijaan</translation> </message> <message> <location filename="../bitcoinstrings.cpp" line="92"/> <source>Send trace/debug info to debugger</source> <translation>Lähetä jäljitys/debug-tieto debuggeriin</translation> </message> <message> <location filename="../bitcoinstrings.cpp" line="93"/> <source>Username for JSON-RPC connections</source> <translation>Käyttäjätunnus JSON-RPC-yhteyksille</translation> </message> <message> <location filename="../bitcoinstrings.cpp" line="94"/> <source>Password for JSON-RPC connections</source> <translation>Salasana JSON-RPC-yhteyksille</translation> </message> <message> <location filename="../bitcoinstrings.cpp" line="95"/> <source>Listen for JSON-RPC connections on &lt;port&gt; (default: 8332)</source> <translation>Kuuntele JSON-RPC -yhteyksiä portista &lt;port&gt; (oletus: 8332)</translation> </message> <message> <location filename="../bitcoinstrings.cpp" line="96"/> <source>Allow JSON-RPC connections from specified IP address</source> <translation>Salli JSON-RPC yhteydet tietystä ip-osoitteesta</translation> </message> <message> <location filename="../bitcoinstrings.cpp" line="97"/> <source>Send commands to node running on &lt;ip&gt; (default: 127.0.0.1)</source> <translation>Lähetä käskyjä solmuun osoitteessa &lt;ip&gt; (oletus: 127.0.0.1)</translation> </message> <message> <location filename="../bitcoinstrings.cpp" line="98"/> <source>Execute command when the best block changes (%s in cmd is replaced by block hash)</source> <translation>Suorita käsky kun paras lohko muuttuu (%s cmd on vaihdettu block hashin kanssa)</translation> </message> <message> <location filename="../bitcoinstrings.cpp" line="101"/> <source>Upgrade wallet to latest format</source> <translation>Päivitä lompakko uusimpaan formaattiin</translation> </message> <message> <location filename="../bitcoinstrings.cpp" line="102"/> <source>Set key pool size to &lt;n&gt; (default: 100)</source> <translation>Aseta avainpoolin koko arvoon &lt;n&gt; (oletus: 100)</translation> </message> <message> <location filename="../bitcoinstrings.cpp" line="103"/> <source>Rescan the block chain for missing wallet transactions</source> <translation>Skannaa uudelleen lohkoketju lompakon puuttuvien rahasiirtojen vuoksi</translation> </message> <message> <location filename="../bitcoinstrings.cpp" line="104"/> <source>How many blocks to check at startup (default: 2500, 0 = all)</source> <translation>Kuinka monta lohkoa tarkistetaan käynnistettäessä (oletus: 2500, 0 = kaikki)</translation> </message> <message> <location filename="../bitcoinstrings.cpp" line="105"/> <source>How thorough the block verification is (0-6, default: 1)</source> <translation>Kuinka tiukka lohkovarmistus on (0-6, oletus: 1)</translation> </message> <message> <location filename="../bitcoinstrings.cpp" line="106"/> <source>Imports blocks from external blk000?.dat file</source> <translation type="unfinished"/> </message> <message> <location filename="../bitcoinstrings.cpp" line="108"/> <source> SSL options: (see the Bitcoin Wiki for SSL setup instructions)</source> <translation>SSL-asetukset: (lisätietoja Bitcoin-Wikistä)</translation> </message> <message> <location filename="../bitcoinstrings.cpp" line="111"/> <source>Use OpenSSL (https) for JSON-RPC connections</source> <translation>Käytä OpenSSL:ää (https) JSON-RPC-yhteyksille</translation> </message> <message> <location filename="../bitcoinstrings.cpp" line="112"/> <source>Server certificate file (default: server.cert)</source> <translation>Palvelimen sertifikaatti-tiedosto (oletus: server.cert)</translation> </message> <message> <location filename="../bitcoinstrings.cpp" line="113"/> <source>Server private key (default: server.pem)</source> <translation>Palvelimen yksityisavain (oletus: server.pem)</translation> </message> <message> <location filename="../bitcoinstrings.cpp" line="114"/> <source>Acceptable ciphers (default: TLSv1+HIGH:!SSLv2:!aNULL:!eNULL:!AH:!3DES:@STRENGTH)</source> <translation>Hyväksyttävä salaus (oletus: TLSv1+HIGH:!SSLv2:!aNULL:!eNULL:!AH:!3DES:@STRENGTH)</translation> </message> <message> <location filename="../bitcoinstrings.cpp" line="145"/> <source>Warning: Disk space is low</source> <translation type="unfinished"/> </message> <message> <location filename="../bitcoinstrings.cpp" line="107"/> <source>This help message</source> <translation>Tämä ohjeviesti</translation> </message> <message> <location filename="../bitcoinstrings.cpp" line="121"/> <source>Cannot obtain a lock on data directory %s. Bitcoin is probably already running.</source> <translation>En pääse käsiksi data-hakemiston lukitukseen %s. Bitcoin on todennäköisesti jo käynnistetty.</translation> </message> <message> <location filename="../bitcoinstrings.cpp" line="48"/> <source>Bitcoin</source> <translation>Bitcoin</translation> </message> <message> <location filename="../bitcoinstrings.cpp" line="30"/> <source>Unable to bind to %s on this computer (bind returned error %d, %s)</source> <translation type="unfinished"/> </message> <message> <location filename="../bitcoinstrings.cpp" line="58"/> <source>Connect through socks proxy</source> <translation type="unfinished"/> </message> <message> <location filename="../bitcoinstrings.cpp" line="59"/> <source>Select the version of socks proxy to use (4 or 5, 5 is default)</source> <translation type="unfinished"/> </message> <message> <location filename="../bitcoinstrings.cpp" line="60"/> <source>Do not use proxy for connections to network &lt;net&gt; (IPv4 or IPv6)</source> <translation type="unfinished"/> </message> <message> <location filename="../bitcoinstrings.cpp" line="61"/> <source>Allow DNS lookups for -addnode, -seednode and -connect</source> <translation type="unfinished"/> </message> <message> <location filename="../bitcoinstrings.cpp" line="62"/> <source>Pass DNS requests to (SOCKS5) proxy</source> <translation type="unfinished"/> </message> <message> <location filename="../bitcoinstrings.cpp" line="142"/> <source>Loading addresses...</source> <translation>Ladataan osoitteita...</translation> </message> <message> <location filename="../bitcoinstrings.cpp" line="132"/> <source>Error loading blkindex.dat</source> <translation>Virhe ladattaessa blkindex.dat-tiedostoa</translation> </message> <message> <location filename="../bitcoinstrings.cpp" line="134"/> <source>Error loading wallet.dat: Wallet corrupted</source> <translation>Virhe ladattaessa wallet.dat-tiedostoa: Lompakko vioittunut</translation> </message> <message> <location filename="../bitcoinstrings.cpp" line="135"/> <source>Error loading wallet.dat: Wallet requires newer version of Bitcoin</source> <translation>Virhe ladattaessa wallet.dat-tiedostoa: Tarvitset uudemman version Bitcoinista</translation> </message> <message> <location filename="../bitcoinstrings.cpp" line="136"/> <source>Wallet needed to be rewritten: restart Bitcoin to complete</source> <translation>Lompakko tarvitsee uudelleenkirjoittaa: käynnistä Bitcoin uudelleen</translation> </message> <message> <location filename="../bitcoinstrings.cpp" line="137"/> <source>Error loading wallet.dat</source> <translation>Virhe ladattaessa wallet.dat-tiedostoa</translation> </message> <message> <location filename="../bitcoinstrings.cpp" line="124"/> <source>Invalid -proxy address: &apos;%s&apos;</source> <translation type="unfinished"/> </message> <message> <location filename="../bitcoinstrings.cpp" line="125"/> <source>Unknown network specified in -noproxy: &apos;%s&apos;</source> <translation type="unfinished"/> </message> <message> <location filename="../bitcoinstrings.cpp" line="127"/> <source>Unknown network specified in -onlynet: &apos;%s&apos;</source> <translation type="unfinished"/> </message> <message> <location filename="../bitcoinstrings.cpp" line="126"/> <source>Unknown -socks proxy version requested: %i</source> <translation type="unfinished"/> </message> <message> <location filename="../bitcoinstrings.cpp" line="128"/> <source>Cannot resolve -bind address: &apos;%s&apos;</source> <translation type="unfinished"/> </message> <message> <location filename="../bitcoinstrings.cpp" line="129"/> <source>Not listening on any port</source> <translation type="unfinished"/> </message> <message> <location filename="../bitcoinstrings.cpp" line="130"/> <source>Cannot resolve -externalip address: &apos;%s&apos;</source> <translation type="unfinished"/> </message> <message> <location filename="../bitcoinstrings.cpp" line="117"/> <source>Invalid amount for -paytxfee=&lt;amount&gt;: &apos;%s&apos;</source> <translation type="unfinished"/> </message> <message> <location filename="../bitcoinstrings.cpp" line="143"/> <source>Error: could not start node</source> <translation type="unfinished"/> </message> <message> <location filename="../bitcoinstrings.cpp" line="31"/> <source>Error: Wallet locked, unable to create transaction </source> <translation>Virhe: Lompakko on lukittu, rahansiirtoa ei voida luoda</translation> </message> <message> <location filename="../bitcoinstrings.cpp" line="32"/> <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>Virhe: Tämä rahansiirto vaatii rahansiirtopalkkion vähintään %s johtuen sen määrästä, monimutkaisuudesta tai hiljattain vastaanotettujen summien käytöstä</translation> </message> <message> <location filename="../bitcoinstrings.cpp" line="35"/> <source>Error: Transaction creation failed </source> <translation>Virhe: Rahansiirron luonti epäonnistui</translation> </message> <message> <location filename="../bitcoinstrings.cpp" line="36"/> <source>Sending...</source> <translation>Lähetetään...</translation> </message> <message> <location filename="../bitcoinstrings.cpp" line="37"/> <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>Virhe: Rahansiirto hylättiin. Tämä voi tapahtua jos jotkin bitcoineistasi on jo käytetty, esimerkiksi jos olet käyttänyt kopiota wallet.dat-lompakkotiedostosta ja bitcoinit on merkitty käytetyksi vain kopiossa.</translation> </message> <message> <location filename="../bitcoinstrings.cpp" line="41"/> <source>Invalid amount</source> <translation>Virheellinen määrä</translation> </message> <message> <location filename="../bitcoinstrings.cpp" line="42"/> <source>Insufficient funds</source> <translation>Lompakon saldo ei riitä</translation> </message> <message> <location filename="../bitcoinstrings.cpp" line="131"/> <source>Loading block index...</source> <translation>Ladataan lohkoindeksiä...</translation> </message> <message> <location filename="../bitcoinstrings.cpp" line="65"/> <source>Add a node to connect to and attempt to keep the connection open</source> <translation>Linää solmu mihin liittyä pitääksesi yhteyden auki</translation> </message> <message> <location filename="../bitcoinstrings.cpp" line="28"/> <source>Unable to bind to %s on this computer. Bitcoin is probably already running.</source> <translation type="unfinished"/> </message> <message> <location filename="../bitcoinstrings.cpp" line="71"/> <source>Find peers using internet relay chat (default: 0)</source> <translation>Etsi solmuja käyttäen internet relay chatia (oletus: 0)</translation> </message> <message> <location filename="../bitcoinstrings.cpp" line="72"/> <source>Accept connections from outside (default: 1)</source> <translation>Hyväksytään ulkopuoliset yhteydet (oletus: 1)</translation> </message> <message> <location filename="../bitcoinstrings.cpp" line="74"/> <source>Find peers using DNS lookup (default: 1)</source> <translation>Etsi solmuja käyttämällä DNS hakua (oletus: 1)</translation> </message> <message> <location filename="../bitcoinstrings.cpp" line="81"/> <source>Use Universal Plug and Play to map the listening port (default: 1)</source> <translation>Käytä Plug and Play kartoitusta kuunnellaksesi porttia (oletus: 1)</translation> </message> <message> <location filename="../bitcoinstrings.cpp" line="82"/> <source>Use Universal Plug and Play to map the listening port (default: 0)</source> <translation>Käytä Plug and Play kartoitusta kuunnellaksesi porttia (oletus: 0)</translation> </message> <message> <location filename="../bitcoinstrings.cpp" line="85"/> <source>Fee per KB to add to transactions you send</source> <translation>Rahansiirtopalkkio per KB lisätään lähettämääsi rahansiirtoon</translation> </message> <message> <location filename="../bitcoinstrings.cpp" line="118"/> <source>Warning: -paytxfee is set very high. This is the transaction fee you will pay if you send a transaction.</source> <translation type="unfinished"/> </message> <message> <location filename="../bitcoinstrings.cpp" line="133"/> <source>Loading wallet...</source> <translation>Ladataan lompakkoa...</translation> </message> <message> <location filename="../bitcoinstrings.cpp" line="138"/> <source>Cannot downgrade wallet</source> <translation>Et voi päivittää lompakkoasi vanhempaan versioon</translation> </message> <message> <location filename="../bitcoinstrings.cpp" line="139"/> <source>Cannot initialize keypool</source> <translation>Avainvarastoa ei voi alustaa</translation> </message> <message> <location filename="../bitcoinstrings.cpp" line="140"/> <source>Cannot write default address</source> <translation>Oletusosoitetta ei voi kirjoittaa</translation> </message> <message> <location filename="../bitcoinstrings.cpp" line="141"/> <source>Rescanning...</source> <translation>Skannataan uudelleen...</translation> </message> <message> <location filename="../bitcoinstrings.cpp" line="144"/> <source>Done loading</source> <translation>Lataus on valmis</translation> </message> <message> <location filename="../bitcoinstrings.cpp" line="8"/> <source>To use the %s option</source> <translation>Käytä %s optiota</translation> </message> <message> <location filename="../bitcoinstrings.cpp" line="9"/> <source>%s, you must set a rpcpassword in the configuration file: %s It is recommended you use the following random password: rpcuser=bitcoinrpc rpcpassword=%s (you do not need to remember this password) If the file does not exist, create it with owner-readable-only file permissions. </source> <translation>%s, sinun täytyy asettaa rpcpassword asetustiedostoon: %s On suositeltavaa käyttää seuraavaan satunnaista salasanaa: rpcuser=bitcoinrpc rpcpassword=%s (sinun ei tarvitse muistaa tätä salasanaa) Jos tiedostoa ei ole, niin luo se ainoastaan omistajan kirjoitusoikeuksin. </translation> </message> <message> <location filename="../bitcoinstrings.cpp" line="18"/> <source>Error</source> <translation>Virhe</translation> </message> <message> <location filename="../bitcoinstrings.cpp" line="19"/> <source>An error occured while setting up the RPC port %i for listening: %s</source> <translation>Virhe asetettaessa RCP-porttia %i kuunteluun: %s</translation> </message> <message> <location filename="../bitcoinstrings.cpp" line="20"/> <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>Sinun täytyy asettaa rpcpassword=&lt;password&gt; asetustiedostoon: %s Jos tiedostoa ei ole, niin luo se ainoastaan omistajan kirjoitusoikeuksin.</translation> </message> <message> <location filename="../bitcoinstrings.cpp" line="25"/> <source>Warning: Please check that your computer&apos;s date and time are correct. If your clock is wrong Bitcoin will not work properly.</source> <translation>Varoitus: Tarkista, ovatko tietokoneesi päivämäärä ja aika oikein. Mikäli aika on väärin, Bitcoin-ohjelma ei toimi oikein.</translation> </message> </context> </TS>
{'content_hash': '9d19f82a369d9fc9870815d3fb970aa3', 'timestamp': '', 'source': 'github', 'line_count': 2520, 'max_line_length': 383, 'avg_line_length': 43.58015873015873, 'alnum_prop': 0.6466737083644443, 'repo_name': 'IeuanG/BHC', 'id': '9008c1e3b5004ce446d6ca674ab85e7de1315c92', 'size': '110359', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'src/qt/locale/bitcoin_fi.ts', 'mode': '33261', 'license': 'mit', 'language': [{'name': 'C', 'bytes': '14758'}, {'name': 'C++', 'bytes': '1432339'}, {'name': 'Erlang', 'bytes': '6839'}, {'name': 'JavaScript', 'bytes': '12'}, {'name': 'Makefile', 'bytes': '79169'}, {'name': 'Objective-C++', 'bytes': '2463'}, {'name': 'PHP', 'bytes': '1948'}, {'name': 'Perl', 'bytes': '16929'}, {'name': 'Python', 'bytes': '47538'}, {'name': 'Shell', 'bytes': '2615'}]}
<?xml version="1.0"?> <!DOCTYPE resource-action-mapping PUBLIC "-//Liferay//DTD Resource Action Mapping 6.2.0//EN" "http://www.liferay.com/dtd/liferay-resource-action-mapping_6_2_0.dtd"> <resource-action-mapping> <model-resource> <model-name>org.oep.dossiermgt.model.PaymentFile</model-name> <portlet-ref> <portlet-name>oep-core-dossiermgt</portlet-name> </portlet-ref> <weight>2</weight> <permissions> <supports> <action-key>CREATE_PAYMENTFILE</action-key> <action-key>PERMISSIONS</action-key> <action-key>UPDATE_PAYMENTFILE</action-key> </supports> <site-member-defaults> <action-key>CREATE_PAYMENTFILE</action-key> </site-member-defaults> <guest-defaults /> <guest-unsupported> <action-key>PERMISSIONS</action-key> <action-key>UPDATE_PAYMENTFILE</action-key> </guest-unsupported> </permissions> </model-resource> </resource-action-mapping>
{'content_hash': '02252013d43c2c9c5b20a71b33db9d63', 'timestamp': '', 'source': 'github', 'line_count': 27, 'max_line_length': 164, 'avg_line_length': 33.51851851851852, 'alnum_prop': 0.7104972375690608, 'repo_name': 'openegovplatform/OEPv2', 'id': '716a8f0e5568373e411e3cfd99858f2a9edf919e', 'size': '905', 'binary': False, 'copies': '2', 'ref': 'refs/heads/master', 'path': 'oep-dossier-portlet/docroot/WEB-INF/src/resource-actions/paymentfile.xml', 'mode': '33188', 'license': 'apache-2.0', 'language': [{'name': 'CSS', 'bytes': '5166'}, {'name': 'Java', 'bytes': '45541534'}]}
package com.tutorialspoint.abstraction; public class AbstractDemo { public static void main(String[] args) { /* Following is not allowed and would raise error */ // Employee e = new Employee("George W.", "Houston, TX", 43); // Compile time error Salary s = new Salary("Mohd Mohtashim", "Ambehta, UP", 3, 3600.00); Employee e = new Salary("John Adams", "Boston, MA", 2, 2400.00); System.out.println("Call mailCheck using Salary reference --"); s.mailCheck(); System.out.println("\nCall mailCheck using Employee reference--"); e.mailCheck(); } }
{'content_hash': '80d5c9815131d8a2c7aa85e80bd0ed61', 'timestamp': '', 'source': 'github', 'line_count': 16, 'max_line_length': 87, 'avg_line_length': 37.4375, 'alnum_prop': 0.6494156928213689, 'repo_name': 'antalpeti/Java-Tutorial', 'id': 'cb1a626739250ab543710691a5f0585ff9890a70', 'size': '599', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'src/com/tutorialspoint/abstraction/AbstractDemo.java', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'CSS', 'bytes': '549'}, {'name': 'HTML', 'bytes': '1147'}, {'name': 'Java', 'bytes': '409438'}]}
using System; using System.Net; using System.Net.Fakes; using System.Net.Http; using System.Net.Http.Fakes; using System.Threading.Tasks; using Microsoft.QualityTools.Testing.Fakes; using Microsoft.VisualStudio.TestTools.UnitTesting; using Newtonsoft.Json; using Xciles.Uncommon.Net; namespace Xciles.Uncommon.Tests.Net { [TestClass] public class UncommonRequestHelperExceptionTests { private readonly Person _person = new Person { DateOfBirth = DateTime.Now.Subtract(new TimeSpan(800, 1, 1, 1)), Firstname = "First", Lastname = "Person", PhoneNumber = "0123456789", SomeString = "This is just a string" }; [TestMethod] public void ProcessGetRequestWebExceptionTest() { ProcessGetRequestWebExceptionTestAsync().Wait(); } private async Task ProcessGetRequestWebExceptionTestAsync() { var exceptionObject = new ExceptionObject() { Description = "This is a test Exception Description", Message = "This is a test Exception Message", Type = EType.WrongHeaders }; using (ShimsContext.Create()) { ShimHttpClient.AllInstances.SendAsyncHttpRequestMessageCancellationToken = (client, message, arg3) => { return Task.FromResult(new HttpResponseMessage() { Content = new StringContent(JsonConvert.SerializeObject(exceptionObject)), StatusCode = HttpStatusCode.BadRequest }); }; try { var result = await UncommonRequestHelper.ProcessGetRequestAsync<Person>("http://www.xciles.com/"); Assert.Fail("Should not be able to be here..."); } catch (UncommonRequestException ex) { Assert.IsTrue(ex.RequestExceptionStatus == EUncommonRequestExceptionStatus.ServiceError); Assert.IsTrue(ex.StatusCode == HttpStatusCode.BadRequest); var responseResult = ex.ConvertExceptionResponseToObject<ExceptionObject>(); Assert.IsTrue(responseResult != null); Assert.IsTrue(responseResult.Description == exceptionObject.Description); Assert.IsTrue(responseResult.Message == exceptionObject.Message); Assert.IsTrue(responseResult.Type == exceptionObject.Type); } } } [TestMethod] public void ProcessGetRequestHttpRequestExceptionTest() { ProcessGetRequestHttpRequestExceptionTestAsync().Wait(); } private async Task ProcessGetRequestHttpRequestExceptionTestAsync() { var exceptionObject = new ExceptionObject() { Description = "This is a test Exception Description", Message = "This is a test Exception Message", Type = EType.WrongHeaders }; using (ShimsContext.Create()) { ShimHttpClient.AllInstances.SendAsyncHttpRequestMessageCancellationToken = (client, message, arg3) => { //var webEx = new WebException("", WebExceptionStatus.UnknownError, ) throw new HttpRequestException(); }; ShimHttpWebResponse.AllInstances.ResponseStreamGet = (response) => { return ShimsContext.ExecuteWithoutShims(() => response.GetResponseStream()); }; try { var result = await UncommonRequestHelper.ProcessGetRequestAsync<Person>("http://www.xciles.com/"); Assert.Fail("Should not be able to be here..."); } catch (UncommonRequestException ex) { Assert.IsTrue(ex.RequestExceptionStatus == EUncommonRequestExceptionStatus.ServiceError); Assert.IsTrue(ex.StatusCode == HttpStatusCode.BadRequest); //var responseResult = ex.ConvertExceptionResponseToObject<ExceptionObject>(); //Assert.IsTrue(responseResult != null); //Assert.IsTrue(responseResult.Description == exceptionObject.Description); //Assert.IsTrue(responseResult.Message == exceptionObject.Message); //Assert.IsTrue(responseResult.Type == exceptionObject.Type); } } } } }
{'content_hash': 'e0f5a5e28a0b96215ea75c8f58fcba13', 'timestamp': '', 'source': 'github', 'line_count': 122, 'max_line_length': 118, 'avg_line_length': 38.80327868852459, 'alnum_prop': 0.5701309674693705, 'repo_name': 'Xciles/Uncommon', 'id': '599c1d78c23361960cd716ebf69cb66d00433506', 'size': '4736', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'Uncommon.Tests/Net/UncommonRequestHelperExceptionTests.cs', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'ASP', 'bytes': '109'}, {'name': 'C#', 'bytes': '146892'}, {'name': 'CSS', 'bytes': '315'}, {'name': 'HTML', 'bytes': '5125'}, {'name': 'JavaScript', 'bytes': '19032'}, {'name': 'Pascal', 'bytes': '525'}]}
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:layout_width="fill_parent" android:layout_height="fill_parent" android:padding="20dp" android:gravity="center" android:background="#333" android:orientation="vertical"> <TextView android:id="@+id/textview_alias_input" android:layout_marginTop="10dp" android:layout_width="200dp" android:layout_height="wrap_content" android:text="@string/alias" android:textColor="#fff" android:textSize="18dp" /> <EditText android:id="@+id/edittext_alias_input" android:layout_marginTop="10dp" android:layout_width="200dp" android:layout_height="44dp" /> </LinearLayout>
{'content_hash': 'a5e928b2b29f2548ce086e3527b3f0bb', 'timestamp': '', 'source': 'github', 'line_count': 26, 'max_line_length': 72, 'avg_line_length': 31.384615384615383, 'alnum_prop': 0.6519607843137255, 'repo_name': 'p2plab/Nxt-Client-For-Android', 'id': '9718894353d3d5ce987d2d2ff7677a5897fbd02c', 'size': '816', 'binary': False, 'copies': '2', 'ref': 'refs/heads/master', 'path': 'res/layout/alias_input.xml', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'Java', 'bytes': '531831'}]}
<!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> <title>jQuery UI Datepicker Demos</title> <link rel="stylesheet" href="../demos.css"> </head> <body> <div class="demos-nav"> <h4>Examples</h4> <ul> <li class="demo-config-on"><a href="default.html">Default functionality</a></li> <li><a href="date-formats.html">Format date</a></li> <li><a href="min-max.html">Restrict date range</a></li> <li><a href="localization.html">Localize calendar</a></li> <li><a href="alt-field.html">Populate alternate field</a></li> <li><a href="inline.html">Display inline</a></li> <li><a href="buttonbar.html">Display button bar</a></li> <li><a href="dropdown-month-year.html">Display month &amp; year menus</a></li> <li><a href="other-months.html">Dates in other months</a></li> <li><a href="show-week.html">Show week of the year</a></li> <li><a href="multiple-calendars.html">Display multiple months</a></li> <li><a href="icon-trigger.html">Icon trigger</a></li> <li><a href="animation.html">Animations</a></li> <li><a href="event-search.html">Event Search</a></li> </ul> </div> </body> </html>
{'content_hash': '011e5fa1504454cdbee214ef0cdcefd2', 'timestamp': '', 'source': 'github', 'line_count': 31, 'max_line_length': 82, 'avg_line_length': 36.54838709677419, 'alnum_prop': 0.6487202118270079, 'repo_name': 'PhillyPUG/phillypug', 'id': '37c8ef7148c7d46d3a6b916355ee6d0566bbf534', 'size': '1133', 'binary': False, 'copies': '34', 'ref': 'refs/heads/master', 'path': 'media/development-bundle/demos/datepicker/index.html', 'mode': '33188', 'license': 'bsd-3-clause', 'language': []}
package dilawar type Type string const ( TypeCredit Type = "credit" TypeDebit Type = "debit" ) type Storable interface { Create(*Transaction) error Read(int) *Transaction List() []Transaction }
{'content_hash': '8bf48ee2048fbe4af9d0dfa38a110c95', 'timestamp': '', 'source': 'github', 'line_count': 14, 'max_line_length': 27, 'avg_line_length': 14.5, 'alnum_prop': 0.7241379310344828, 'repo_name': 'umayr/dilawar', 'id': '31ea7e27bc18ed5652752d47e84a35bcf92ff53c', 'size': '203', 'binary': False, 'copies': '2', 'ref': 'refs/heads/master', 'path': 'dilawar.go', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'Go', 'bytes': '6636'}, {'name': 'Makefile', 'bytes': '1874'}]}
extern "C" { #include "third_party/py/scipy/optimize/Zeros/zeros.h" } namespace logistic_hd { // Integrands for the equations defined in Eq. 5 from Sur and Candès // (PNAS, 2019). These are called by the bivariate integration over Z1 and Z2 // in `asymp_system_solve.py`. double integrand(double Z1, double Z2, double kappa, double gamma, double b0, double alpha, double lambda, double sigma, double beta0, int eq_num); // Computes the derivative of the objective that defines the proximal operator. // The prox operator is the value of z that makes this zero. double prox_deriv(double z, void *args); double sigmoid(double z); // Computes the derivative of the prox operator for the logistic regression // log likelihood. double prox_impl(double lambda, double x, double xtol = 1e-8, double rtol = 1e-8, int maxiters = 1000); // Computes the pdf of the bivariate normal without any input validation // because this is called many times during optimization. double pdf(double x1, double x2); // Helper function to pass values between our code and the scipy.optimize API. double scipy_zeros_functions_func(double x, void *params); typedef struct prox_params { double lambda; double x; } prox_params; } // namespace logistic_hd #endif // MLE_PARAM_INTEGRANDS_H_
{'content_hash': '591be7b34b1395ac2119351a1f2e218f', 'timestamp': '', 'source': 'github', 'line_count': 39, 'max_line_length': 79, 'avg_line_length': 34.02564102564103, 'alnum_prop': 0.720422004521477, 'repo_name': 'google-research/sloe-logistic', 'id': 'f3d13ad1d3b57092c932b7a4ba6143cec5890cae', 'size': '2016', 'binary': False, 'copies': '1', 'ref': 'refs/heads/main', 'path': 'mle_param_integrands.h', 'mode': '33188', 'license': 'apache-2.0', 'language': []}
// Protocol Buffers - Google's data interchange format // Copyright 2008 Google Inc. All rights reserved. // http://github.com/jskeet/dotnet-protobufs/ // Original C++/Java/Python code: // http://code.google.com/p/protobuf/ // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are // met: // // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above // copyright notice, this list of conditions and the following disclaimer // in the documentation and/or other materials provided with the // distribution. // * Neither the name of Google Inc. nor the names of its // contributors may be used to endorse or promote products derived from // this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. #endregion using System; using System.Collections; using System.Collections.Generic; using Google.ProtocolBuffers.Descriptors; //Disable warning CS3010: CLS-compliant interfaces must have only CLS-compliant members #pragma warning disable 3010 namespace Google.ProtocolBuffers { /// <summary> /// Provides an interface that is used write a message. Most often proto buffers are written /// in their binary form by creating a instance via the CodedOutputStream.CreateInstance /// static factory. /// </summary> public interface ICodedOutputStream { /// <summary> /// Writes any message initialization data needed to the output stream /// </summary> /// <remarks> /// This is primarily used by text formats and unnecessary for protobuffers' own /// binary format. The API for MessageStart/End was added for consistent handling /// of output streams regardless of the actual writer implementation. /// </remarks> void WriteMessageStart(); /// <summary> /// Writes any message finalization data needed to the output stream /// </summary> /// <remarks> /// This is primarily used by text formats and unnecessary for protobuffers' own /// binary format. The API for MessageStart/End was added for consistent handling /// of output streams regardless of the actual writer implementation. /// </remarks> void WriteMessageEnd(); /// <summary> /// Indicates that all temporary buffers be written to the final output. /// </summary> void Flush(); /// <summary> /// Writes an unknown message as a group /// </summary> [Obsolete] void WriteUnknownGroup(int fieldNumber, IMessageLite value); /// <summary> /// Writes an unknown field value of bytes /// </summary> void WriteUnknownBytes(int fieldNumber, ByteString value); /// <summary> /// Writes an unknown field of a primitive type /// </summary> [CLSCompliant(false)] void WriteUnknownField(int fieldNumber, WireFormat.WireType wireType, ulong value); /// <summary> /// Writes an extension as a message-set group /// </summary> void WriteMessageSetExtension(int fieldNumber, string fieldName, IMessageLite value); /// <summary> /// Writes an unknown extension as a message-set group /// </summary> void WriteMessageSetExtension(int fieldNumber, string fieldName, ByteString value); /// <summary> /// Writes a field value, including tag, to the stream. /// </summary> void WriteField(FieldType fieldType, int fieldNumber, string fieldName, object value); /// <summary> /// Writes a double field value, including tag, to the stream. /// </summary> void WriteDouble(int fieldNumber, string fieldName, double value); /// <summary> /// Writes a float field value, including tag, to the stream. /// </summary> void WriteFloat(int fieldNumber, string fieldName, float value); /// <summary> /// Writes a uint64 field value, including tag, to the stream. /// </summary> [CLSCompliant(false)] void WriteUInt64(int fieldNumber, string fieldName, ulong value); /// <summary> /// Writes an int64 field value, including tag, to the stream. /// </summary> void WriteInt64(int fieldNumber, string fieldName, long value); /// <summary> /// Writes an int32 field value, including tag, to the stream. /// </summary> void WriteInt32(int fieldNumber, string fieldName, int value); /// <summary> /// Writes a fixed64 field value, including tag, to the stream. /// </summary> [CLSCompliant(false)] void WriteFixed64(int fieldNumber, string fieldName, ulong value); /// <summary> /// Writes a fixed32 field value, including tag, to the stream. /// </summary> [CLSCompliant(false)] void WriteFixed32(int fieldNumber, string fieldName, uint value); /// <summary> /// Writes a bool field value, including tag, to the stream. /// </summary> void WriteBool(int fieldNumber, string fieldName, bool value); /// <summary> /// Writes a string field value, including tag, to the stream. /// </summary> void WriteString(int fieldNumber, string fieldName, string value); /// <summary> /// Writes a group field value, including tag, to the stream. /// </summary> void WriteGroup(int fieldNumber, string fieldName, IMessageLite value); /// <summary> /// Writes a message field value, including tag, to the stream. /// </summary> void WriteMessage(int fieldNumber, string fieldName, IMessageLite value); /// <summary> /// Writes a byte array field value, including tag, to the stream. /// </summary> void WriteBytes(int fieldNumber, string fieldName, ByteString value); /// <summary> /// Writes a UInt32 field value, including tag, to the stream. /// </summary> [CLSCompliant(false)] void WriteUInt32(int fieldNumber, string fieldName, uint value); /// <summary> /// Writes an enum field value, including tag, to the stream. /// </summary> void WriteEnum(int fieldNumber, string fieldName, int value, object rawValue); /// <summary> /// Writes a fixed 32-bit field value, including tag, to the stream. /// </summary> void WriteSFixed32(int fieldNumber, string fieldName, int value); /// <summary> /// Writes a signed fixed 64-bit field value, including tag, to the stream. /// </summary> void WriteSFixed64(int fieldNumber, string fieldName, long value); /// <summary> /// Writes a signed 32-bit field value, including tag, to the stream. /// </summary> void WriteSInt32(int fieldNumber, string fieldName, int value); /// <summary> /// Writes a signed 64-bit field value, including tag, to the stream. /// </summary> void WriteSInt64(int fieldNumber, string fieldName, long value); /// <summary> /// Writes a repeated field value, including tag(s), to the stream. /// </summary> void WriteArray(FieldType fieldType, int fieldNumber, string fieldName, IEnumerable list); /// <summary> /// Writes a repeated group value, including tag(s), to the stream. /// </summary> void WriteGroupArray<T>(int fieldNumber, string fieldName, IEnumerable<T> list) where T : IMessageLite; /// <summary> /// Writes a repeated message value, including tag(s), to the stream. /// </summary> void WriteMessageArray<T>(int fieldNumber, string fieldName, IEnumerable<T> list) where T : IMessageLite; /// <summary> /// Writes a repeated string value, including tag(s), to the stream. /// </summary> void WriteStringArray(int fieldNumber, string fieldName, IEnumerable<string> list); /// <summary> /// Writes a repeated ByteString value, including tag(s), to the stream. /// </summary> void WriteBytesArray(int fieldNumber, string fieldName, IEnumerable<ByteString> list); /// <summary> /// Writes a repeated boolean value, including tag(s), to the stream. /// </summary> void WriteBoolArray(int fieldNumber, string fieldName, IEnumerable<bool> list); /// <summary> /// Writes a repeated Int32 value, including tag(s), to the stream. /// </summary> void WriteInt32Array(int fieldNumber, string fieldName, IEnumerable<int> list); /// <summary> /// Writes a repeated SInt32 value, including tag(s), to the stream. /// </summary> void WriteSInt32Array(int fieldNumber, string fieldName, IEnumerable<int> list); /// <summary> /// Writes a repeated UInt32 value, including tag(s), to the stream. /// </summary> void WriteUInt32Array(int fieldNumber, string fieldName, IEnumerable<uint> list); /// <summary> /// Writes a repeated Fixed32 value, including tag(s), to the stream. /// </summary> void WriteFixed32Array(int fieldNumber, string fieldName, IEnumerable<uint> list); /// <summary> /// Writes a repeated SFixed32 value, including tag(s), to the stream. /// </summary> void WriteSFixed32Array(int fieldNumber, string fieldName, IEnumerable<int> list); /// <summary> /// Writes a repeated Int64 value, including tag(s), to the stream. /// </summary> void WriteInt64Array(int fieldNumber, string fieldName, IEnumerable<long> list); /// <summary> /// Writes a repeated SInt64 value, including tag(s), to the stream. /// </summary> void WriteSInt64Array(int fieldNumber, string fieldName, IEnumerable<long> list); /// <summary> /// Writes a repeated UInt64 value, including tag(s), to the stream. /// </summary> void WriteUInt64Array(int fieldNumber, string fieldName, IEnumerable<ulong> list); /// <summary> /// Writes a repeated Fixed64 value, including tag(s), to the stream. /// </summary> void WriteFixed64Array(int fieldNumber, string fieldName, IEnumerable<ulong> list); /// <summary> /// Writes a repeated SFixed64 value, including tag(s), to the stream. /// </summary> void WriteSFixed64Array(int fieldNumber, string fieldName, IEnumerable<long> list); /// <summary> /// Writes a repeated Double value, including tag(s), to the stream. /// </summary> void WriteDoubleArray(int fieldNumber, string fieldName, IEnumerable<double> list); /// <summary> /// Writes a repeated Float value, including tag(s), to the stream. /// </summary> void WriteFloatArray(int fieldNumber, string fieldName, IEnumerable<float> list); /// <summary> /// Writes a repeated enumeration value of type T, including tag(s), to the stream. /// </summary> [CLSCompliant(false)] void WriteEnumArray<T>(int fieldNumber, string fieldName, IEnumerable<T> list) where T : struct, IComparable, IFormattable; /// <summary> /// Writes a packed repeated primitive, including tag and length, to the stream. /// </summary> void WritePackedArray(FieldType fieldType, int fieldNumber, string fieldName, IEnumerable list); /// <summary> /// Writes a packed repeated boolean, including tag and length, to the stream. /// </summary> void WritePackedBoolArray(int fieldNumber, string fieldName, int calculatedSize, IEnumerable<bool> list); /// <summary> /// Writes a packed repeated Int32, including tag and length, to the stream. /// </summary> void WritePackedInt32Array(int fieldNumber, string fieldName, int calculatedSize, IEnumerable<int> list); /// <summary> /// Writes a packed repeated SInt32, including tag and length, to the stream. /// </summary> void WritePackedSInt32Array(int fieldNumber, string fieldName, int calculatedSize, IEnumerable<int> list); /// <summary> /// Writes a packed repeated UInt32, including tag and length, to the stream. /// </summary> void WritePackedUInt32Array(int fieldNumber, string fieldName, int calculatedSize, IEnumerable<uint> list); /// <summary> /// Writes a packed repeated Fixed32, including tag and length, to the stream. /// </summary> void WritePackedFixed32Array(int fieldNumber, string fieldName, int calculatedSize, IEnumerable<uint> list); /// <summary> /// Writes a packed repeated SFixed32, including tag and length, to the stream. /// </summary> void WritePackedSFixed32Array(int fieldNumber, string fieldName, int calculatedSize, IEnumerable<int> list); /// <summary> /// Writes a packed repeated Int64, including tag and length, to the stream. /// </summary> void WritePackedInt64Array(int fieldNumber, string fieldName, int calculatedSize, IEnumerable<long> list); /// <summary> /// Writes a packed repeated SInt64, including tag and length, to the stream. /// </summary> void WritePackedSInt64Array(int fieldNumber, string fieldName, int calculatedSize, IEnumerable<long> list); /// <summary> /// Writes a packed repeated UInt64, including tag and length, to the stream. /// </summary> void WritePackedUInt64Array(int fieldNumber, string fieldName, int calculatedSize, IEnumerable<ulong> list); /// <summary> /// Writes a packed repeated Fixed64, including tag and length, to the stream. /// </summary> void WritePackedFixed64Array(int fieldNumber, string fieldName, int calculatedSize, IEnumerable<ulong> list); /// <summary> /// Writes a packed repeated SFixed64, including tag and length, to the stream. /// </summary> void WritePackedSFixed64Array(int fieldNumber, string fieldName, int calculatedSize, IEnumerable<long> list); /// <summary> /// Writes a packed repeated Double, including tag and length, to the stream. /// </summary> void WritePackedDoubleArray(int fieldNumber, string fieldName, int calculatedSize, IEnumerable<double> list); /// <summary> /// Writes a packed repeated Float, including tag and length, to the stream. /// </summary> void WritePackedFloatArray(int fieldNumber, string fieldName, int calculatedSize, IEnumerable<float> list); /// <summary> /// Writes a packed repeated enumeration of type T, including tag and length, to the stream. /// </summary> [CLSCompliant(false)] void WritePackedEnumArray<T>(int fieldNumber, string fieldName, int calculatedSize, IEnumerable<T> list) where T : struct, IComparable, IFormattable; } }
{'content_hash': '28a175106a29d8ad5a090d313dcec3d0', 'timestamp': '', 'source': 'github', 'line_count': 373, 'max_line_length': 117, 'avg_line_length': 44.49061662198391, 'alnum_prop': 0.6294667068394094, 'repo_name': 'plutoo/protobuf-csharp-port', 'id': '64c8065321ff09d8602f07ced65b1c176b33458e', 'size': '16633', 'binary': False, 'copies': '7', 'ref': 'refs/heads/master', 'path': 'src/ProtocolBuffers/ICodedOutputStream.cs', 'mode': '33188', 'license': 'bsd-3-clause', 'language': [{'name': 'ApacheConf', 'bytes': '1911'}, {'name': 'C#', 'bytes': '7562639'}, {'name': 'HTML', 'bytes': '6297'}, {'name': 'Protocol Buffer', 'bytes': '395806'}, {'name': 'Python', 'bytes': '8912'}, {'name': 'Shell', 'bytes': '4628'}]}
#include <linux/firmware.h> #include <linux/module.h> #include <linux/bitrev.h> #include <linux/kernel.h> #include "firmware.h" #include "chip.h" MODULE_FIRMWARE("6fire/dmx6firel2.ihx"); MODULE_FIRMWARE("6fire/dmx6fireap.ihx"); MODULE_FIRMWARE("6fire/dmx6firecf.bin"); enum { FPGA_BUFSIZE = 512, FPGA_EP = 2 }; /* * wMaxPacketSize of pcm endpoints. * keep synced with rates_in_packet_size and rates_out_packet_size in pcm.c * fpp: frames per isopacket * * CAUTION: keep sizeof <= buffer[] in usb6fire_fw_init */ static const u8 ep_w_max_packet_size[] = { 0xe4, 0x00, 0xe4, 0x00, /* alt 1: 228 EP2 and EP6 (7 fpp) */ 0xa4, 0x01, 0xa4, 0x01, /* alt 2: 420 EP2 and EP6 (13 fpp)*/ 0x94, 0x01, 0x5c, 0x02 /* alt 3: 404 EP2 and 604 EP6 (25 fpp) */ }; static const u8 known_fw_versions[][2] = { { 0x03, 0x01 } }; struct ihex_record { u16 address; u8 len; u8 data[256]; char error; /* true if an error occurred parsing this record */ u8 max_len; /* maximum record length in whole ihex */ /* private */ const char *txt_data; unsigned int txt_length; unsigned int txt_offset; /* current position in txt_data */ }; static u8 usb6fire_fw_ihex_hex(const u8 *data, u8 *crc) { u8 val = 0; int hval; hval = hex_to_bin(data[0]); if (hval >= 0) val |= (hval << 4); hval = hex_to_bin(data[1]); if (hval >= 0) val |= hval; *crc += val; return val; } /* * returns true if record is available, false otherwise. * iff an error occurred, false will be returned and record->error will be true. */ static bool usb6fire_fw_ihex_next_record(struct ihex_record *record) { u8 crc = 0; u8 type; int i; record->error = false; /* find begin of record (marked by a colon) */ while (record->txt_offset < record->txt_length && record->txt_data[record->txt_offset] != ':') record->txt_offset++; if (record->txt_offset == record->txt_length) return false; /* number of characters needed for len, addr and type entries */ record->txt_offset++; if (record->txt_offset + 8 > record->txt_length) { record->error = true; return false; } record->len = usb6fire_fw_ihex_hex(record->txt_data + record->txt_offset, &crc); record->txt_offset += 2; record->address = usb6fire_fw_ihex_hex(record->txt_data + record->txt_offset, &crc) << 8; record->txt_offset += 2; record->address |= usb6fire_fw_ihex_hex(record->txt_data + record->txt_offset, &crc); record->txt_offset += 2; type = usb6fire_fw_ihex_hex(record->txt_data + record->txt_offset, &crc); record->txt_offset += 2; /* number of characters needed for data and crc entries */ if (record->txt_offset + 2 * (record->len + 1) > record->txt_length) { record->error = true; return false; } for (i = 0; i < record->len; i++) { record->data[i] = usb6fire_fw_ihex_hex(record->txt_data + record->txt_offset, &crc); record->txt_offset += 2; } usb6fire_fw_ihex_hex(record->txt_data + record->txt_offset, &crc); if (crc) { record->error = true; return false; } if (type == 1 || !record->len) /* eof */ return false; else if (type == 0) return true; else { record->error = true; return false; } } static int usb6fire_fw_ihex_init(const struct firmware *fw, struct ihex_record *record) { record->txt_data = fw->data; record->txt_length = fw->size; record->txt_offset = 0; record->max_len = 0; /* read all records, if loop ends, record->error indicates, * whether ihex is valid. */ while (usb6fire_fw_ihex_next_record(record)) record->max_len = max(record->len, record->max_len); if (record->error) return -EINVAL; record->txt_offset = 0; return 0; } static int usb6fire_fw_ezusb_write(struct usb_device *device, int type, int value, char *data, int len) { int ret; ret = usb_control_msg(device, usb_sndctrlpipe(device, 0), type, USB_DIR_OUT | USB_TYPE_VENDOR | USB_RECIP_DEVICE, value, 0, data, len, HZ); if (ret < 0) return ret; else if (ret != len) return -EIO; return 0; } static int usb6fire_fw_ezusb_read(struct usb_device *device, int type, int value, char *data, int len) { int ret = usb_control_msg(device, usb_rcvctrlpipe(device, 0), type, USB_DIR_IN | USB_TYPE_VENDOR | USB_RECIP_DEVICE, value, 0, data, len, HZ); if (ret < 0) return ret; else if (ret != len) return -EIO; return 0; } static int usb6fire_fw_fpga_write(struct usb_device *device, char *data, int len) { int actual_len; int ret; ret = usb_bulk_msg(device, usb_sndbulkpipe(device, FPGA_EP), data, len, &actual_len, HZ); if (ret < 0) return ret; else if (actual_len != len) return -EIO; return 0; } static int usb6fire_fw_ezusb_upload( struct usb_interface *intf, const char *fwname, unsigned int postaddr, u8 *postdata, unsigned int postlen) { int ret; u8 data; struct usb_device *device = interface_to_usbdev(intf); const struct firmware *fw = NULL; struct ihex_record *rec = kmalloc(sizeof(struct ihex_record), GFP_KERNEL); if (!rec) return -ENOMEM; ret = request_firmware(&fw, fwname, &device->dev); if (ret < 0) { kfree(rec); snd_printk(KERN_ERR PREFIX "error requesting ezusb " "firmware %s.\n", fwname); return ret; } ret = usb6fire_fw_ihex_init(fw, rec); if (ret < 0) { kfree(rec); release_firmware(fw); snd_printk(KERN_ERR PREFIX "error validating ezusb " "firmware %s.\n", fwname); return ret; } /* upload firmware image */ data = 0x01; /* stop ezusb cpu */ ret = usb6fire_fw_ezusb_write(device, 0xa0, 0xe600, &data, 1); if (ret < 0) { kfree(rec); release_firmware(fw); snd_printk(KERN_ERR PREFIX "unable to upload ezusb " "firmware %s: begin message.\n", fwname); return ret; } while (usb6fire_fw_ihex_next_record(rec)) { /* write firmware */ ret = usb6fire_fw_ezusb_write(device, 0xa0, rec->address, rec->data, rec->len); if (ret < 0) { kfree(rec); release_firmware(fw); snd_printk(KERN_ERR PREFIX "unable to upload ezusb " "firmware %s: data urb.\n", fwname); return ret; } } release_firmware(fw); kfree(rec); if (postdata) { /* write data after firmware has been uploaded */ ret = usb6fire_fw_ezusb_write(device, 0xa0, postaddr, postdata, postlen); if (ret < 0) { snd_printk(KERN_ERR PREFIX "unable to upload ezusb " "firmware %s: post urb.\n", fwname); return ret; } } data = 0x00; /* resume ezusb cpu */ ret = usb6fire_fw_ezusb_write(device, 0xa0, 0xe600, &data, 1); if (ret < 0) { snd_printk(KERN_ERR PREFIX "unable to upload ezusb " "firmware %s: end message.\n", fwname); return ret; } return 0; } static int usb6fire_fw_fpga_upload( struct usb_interface *intf, const char *fwname) { int ret; int i; struct usb_device *device = interface_to_usbdev(intf); u8 *buffer = kmalloc(FPGA_BUFSIZE, GFP_KERNEL); const char *c; const char *end; const struct firmware *fw; if (!buffer) return -ENOMEM; ret = request_firmware(&fw, fwname, &device->dev); if (ret < 0) { snd_printk(KERN_ERR PREFIX "unable to get fpga firmware %s.\n", fwname); kfree(buffer); return -EIO; } c = fw->data; end = fw->data + fw->size; ret = usb6fire_fw_ezusb_write(device, 8, 0, NULL, 0); if (ret < 0) { kfree(buffer); release_firmware(fw); snd_printk(KERN_ERR PREFIX "unable to upload fpga firmware: " "begin urb.\n"); return ret; } while (c != end) { for (i = 0; c != end && i < FPGA_BUFSIZE; i++, c++) buffer[i] = byte_rev_table[(u8) *c]; ret = usb6fire_fw_fpga_write(device, buffer, i); if (ret < 0) { release_firmware(fw); kfree(buffer); snd_printk(KERN_ERR PREFIX "unable to upload fpga " "firmware: fw urb.\n"); return ret; } } release_firmware(fw); kfree(buffer); ret = usb6fire_fw_ezusb_write(device, 9, 0, NULL, 0); if (ret < 0) { snd_printk(KERN_ERR PREFIX "unable to upload fpga firmware: " "end urb.\n"); return ret; } return 0; } /* check, if the firmware version the devices has currently loaded * is known by this driver. 'version' needs to have 4 bytes version * info data. */ static int usb6fire_fw_check(u8 *version) { int i; for (i = 0; i < ARRAY_SIZE(known_fw_versions); i++) if (!memcmp(version, known_fw_versions + i, 2)) return 0; snd_printk(KERN_ERR PREFIX "invalid fimware version in device: %*ph. " "please reconnect to power. if this failure " "still happens, check your firmware installation.", 4, version); return -EINVAL; } int usb6fire_fw_init(struct usb_interface *intf) { int i; int ret; struct usb_device *device = interface_to_usbdev(intf); /* buffer: 8 receiving bytes from device and * sizeof(EP_W_MAX_PACKET_SIZE) bytes for non-const copy */ u8 buffer[12]; ret = usb6fire_fw_ezusb_read(device, 1, 0, buffer, 8); if (ret < 0) { snd_printk(KERN_ERR PREFIX "unable to receive device " "firmware state.\n"); return ret; } if (buffer[0] != 0xeb || buffer[1] != 0xaa || buffer[2] != 0x55) { snd_printk(KERN_ERR PREFIX "unknown device firmware state " "received from device: "); for (i = 0; i < 8; i++) snd_printk("%02x ", buffer[i]); snd_printk("\n"); return -EIO; } /* do we need fpga loader ezusb firmware? */ if (buffer[3] == 0x01) { ret = usb6fire_fw_ezusb_upload(intf, "6fire/dmx6firel2.ihx", 0, NULL, 0); if (ret < 0) return ret; return FW_NOT_READY; } /* do we need fpga firmware and application ezusb firmware? */ else if (buffer[3] == 0x02) { ret = usb6fire_fw_check(buffer + 4); if (ret < 0) return ret; ret = usb6fire_fw_fpga_upload(intf, "6fire/dmx6firecf.bin"); if (ret < 0) return ret; memcpy(buffer, ep_w_max_packet_size, sizeof(ep_w_max_packet_size)); ret = usb6fire_fw_ezusb_upload(intf, "6fire/dmx6fireap.ihx", 0x0003, buffer, sizeof(ep_w_max_packet_size)); if (ret < 0) return ret; return FW_NOT_READY; } /* all fw loaded? */ else if (buffer[3] == 0x03) return usb6fire_fw_check(buffer + 4); /* unknown data? */ else { snd_printk(KERN_ERR PREFIX "unknown device firmware state " "received from device: "); for (i = 0; i < 8; i++) snd_printk("%02x ", buffer[i]); snd_printk("\n"); return -EIO; } return 0; }
{'content_hash': '15d745cdbedbb969c8d9c35a1595961a', 'timestamp': '', 'source': 'github', 'line_count': 404, 'max_line_length': 80, 'avg_line_length': 24.95049504950495, 'alnum_prop': 0.645436507936508, 'repo_name': 'Ant-OS/android_kernel_moto_shamu', 'id': 'b9defcdeb7ef805af05a6453ce309a2eb64bdb18', 'size': '10519', 'binary': False, 'copies': '2121', 'ref': 'refs/heads/master', 'path': 'sound/usb/6fire/firmware.c', 'mode': '33188', 'license': 'apache-2.0', 'language': [{'name': 'ASP', 'bytes': '4528'}, {'name': 'Assembly', 'bytes': '9738337'}, {'name': 'Awk', 'bytes': '18681'}, {'name': 'C', 'bytes': '467488098'}, {'name': 'C++', 'bytes': '3473858'}, {'name': 'Clojure', 'bytes': '547'}, {'name': 'Groff', 'bytes': '22012'}, {'name': 'Lex', 'bytes': '40805'}, {'name': 'Makefile', 'bytes': '1342678'}, {'name': 'Objective-C', 'bytes': '1121986'}, {'name': 'Perl', 'bytes': '461504'}, {'name': 'Python', 'bytes': '33978'}, {'name': 'Scilab', 'bytes': '21433'}, {'name': 'Shell', 'bytes': '138789'}, {'name': 'SourcePawn', 'bytes': '4687'}, {'name': 'UnrealScript', 'bytes': '6113'}, {'name': 'Yacc', 'bytes': '83091'}]}
/** * @file * @brief * This file defines the OpenThread crypto C APIs. */ #ifndef OPENTHREAD_CRYPTO_H_ #define OPENTHREAD_CRYPTO_H_ #include <stdbool.h> #include <stdint.h> #ifdef __cplusplus extern "C" { #endif /** * @addtogroup api-crypto * * @brief * This module includes cryptographic functions. * * @{ * */ #define OT_CRYPTO_HMAC_SHA_HASH_SIZE 32 ///< Length of HMAC SHA (in bytes). /** * This function performs HMAC computation. * * @param[in] aKey A pointer to the key. * @param[in] aKeyLength The key length in bytes. * @param[in] aBuf A pointer to the input buffer. * @param[in] aBufLength The length of @p aBuf in bytes. * @param[out] aHash A pointer to the output hash buffer. * */ void otCryptoHmacSha256( const uint8_t *aKey, uint16_t aKeyLength, const uint8_t *aBuf, uint16_t aBufLength, uint8_t *aHash); /** * This method performs AES CCM computation. * * @param[in] aKey A pointer to the key. * @param[in] aKeyLength Length of the key in bytes. * @param[in] aTagLength Length of tag in bytes. * @param[in] aNonce A pointer to the nonce. * @param[in] aNonceLength Length of nonce in bytes. * * @param[in] aHeader A pointer to the header. * @param[in] aHeaderLength Length of header in bytes. * * @param[inout] aPlainText A pointer to the plaintext. * @param[inout] aCipherText A pointer to the ciphertext. * @param[in] aLength Plaintext length in bytes. * @param[in] aEncrypt `true` on encrypt and `false` on decrypt. * * @param[out] aTag A pointer to the tag. * */ void otCryptoAesCcm( const uint8_t *aKey, uint16_t aKeyLength, uint8_t aTagLength, const void *aNonce, uint8_t aNonceLength, const void *aHeader, uint32_t aHeaderLength, void *aPlainText, void *aCipherText, uint32_t aLength, bool aEncrypt, void *aTag); /** * @} * */ #ifdef __cplusplus } // extern "C" #endif #endif // OPENTHREAD_CRYPTO_H_
{'content_hash': 'e9706e9d8632e56471be3249fed671f8', 'timestamp': '', 'source': 'github', 'line_count': 83, 'max_line_length': 79, 'avg_line_length': 25.10843373493976, 'alnum_prop': 0.6228406909788867, 'repo_name': 'fbsder/openthread', 'id': 'd80a45af879bf664b492b6300da0961dd367f192', 'size': '3692', 'binary': False, 'copies': '5', 'ref': 'refs/heads/master', 'path': 'include/openthread/crypto.h', 'mode': '33188', 'license': 'bsd-3-clause', 'language': [{'name': 'Batchfile', 'bytes': '10128'}, {'name': 'C', 'bytes': '574131'}, {'name': 'C#', 'bytes': '18077'}, {'name': 'C++', 'bytes': '3369485'}, {'name': 'M4', 'bytes': '47539'}, {'name': 'Makefile', 'bytes': '81726'}, {'name': 'Python', 'bytes': '1050179'}, {'name': 'Ruby', 'bytes': '3397'}, {'name': 'Shell', 'bytes': '26917'}]}
<!DOCTYPE html> <html lang="en-us" dir="ltr" itemscope itemtype="http://schema.org/Article"> <head> <meta charset="utf-8" /> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1"/> <title>Eterno Amor</title> <meta name="author" content="" /> <meta name="description" content="Um misto de remorso pelas agruras da guerra com a energia de uma investigação guiada unicamente pela fé (ou pelo amor). A beleza da fotografia fria e triste do front se contrapõe aos horizontes..."/> <meta name="yandex-verification" content="48a8210fc043c5e8" /> <meta name="generator" content="Hugo 0.54.0" /> <meta itemprop="name" content="Eterno Amor"/> <meta itemprop="description" content="Um misto de remorso pelas agruras da guerra com a energia de uma investigação guiada unicamente pela fé (ou pelo amor). A beleza da fotografia fria e triste do front se contrapõe aos horizontes..."/> <meta itemprop="image" content="/img/logo.svg"/> <meta property="og:title" content="Eterno Amor"/> <meta property="og:type" content="article"/> <meta property="og:url" content="http://www.cinetenisverde.com.br/eterno-amor/"/> <meta property="og:image" content="/img/logo.svg"/> <meta property="og:description" content="Um misto de remorso pelas agruras da guerra com a energia de uma investigação guiada unicamente pela fé (ou pelo amor). A beleza da fotografia fria e triste do front se contrapõe aos horizontes..."/> <meta property="og:site_name" content="Cine Tênis Verde"/> <meta property="article:published_time" content="2016-01-06T00:00:00&#43;00:00"/> <meta property="article:section" content="post"/> <meta name="twitter:card" content="summary"/> <meta name="twitter:site" content=""/> <meta name="twitter:title" content="Eterno Amor"/> <meta name="twitter:description" content="Um misto de remorso pelas agruras da guerra com a energia de uma investigação guiada unicamente pela fé (ou pelo amor). A beleza da fotografia fria e triste do front se contrapõe aos horizontes..."/> <meta name="twitter:creator" content=""/> <meta name="twitter:image:src" content="/img/logo.svg"/> <link rel="stylesheet" type="text/css" href="/css/capsule.min.css"/> <link rel="stylesheet" type="text/css" href="/css/custom.css"/> <script> (function(i,s,o,g,r,a,m){i['GoogleAnalyticsObject']=r;i[r]=i[r]||function(){ (i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o), m=s.getElementsByTagName(o)[0];a.async=1;a.src=g;m.parentNode.insertBefore(a,m) })(window,document,'script','https://www.google-analytics.com/analytics.js','ga'); ga('create', 'UA-50557403-1', 'auto'); ga('send', 'pageview'); </script> <link rel="apple-touch-icon" href="/img/apple-touch-icon.png"/> <link rel="icon" href="/img/favicon.ico"/> </head> <body style="min-height:100vh;display:flex;flex-direction:column"> <nav class="navbar has-shadow is-white" role="navigation" aria-label="main navigation"> <div class="container"> <div class="navbar-brand"> <a class="navbar-item" href="/"> <img alt="Brand" src="/img/brand.svg"> <div class="title is-4">&nbsp;Cine Tênis Verde</div> </a> <label class="button navbar-burger is-white" for="navbar-burger-state"> <span></span> <span></span> <span></span> </label> </div> <input type="checkbox" id="navbar-burger-state"/> <div class="navbar-menu"> <div class="navbar-end"> <a href="/post" class="navbar-item ">search </a> <a href="https://twitter.com/cinetenisverde" class="navbar-item ">twitter </a> <a href="/index.xml" class="navbar-item ">rss </a> </div> </div> </div> </nav> <section class="section" style="flex:1"> <div class="container"> <p class="title">Eterno Amor</p> <p class="subtitle"><span class="entry-sidebar-stars"> &#x2605;&#x2605;&#x2605;&#x2605;&#x2606; </span> Wanderley Caloni, <a href="https://github.com/Caloni/cinetenisverde/commits/master/content/post/eterno-amor.md">January 6, 2016</a></p> <p><p> <div class="content"> <p>Um misto de remorso pelas agruras da guerra com a energia de uma investigação guiada unicamente pela fé (ou pelo amor). A beleza da fotografia fria e triste do front se contrapõe aos horizontes oníricos do presente nostálgico, que clama pela elucidação completa de um passado nebuloso que separou um casal apaixonado prestes a se casar. Eterno Amor é pura poesia na forma de criatividade narrativa. Um Pierre Jeunet que retrabalha sua Amélie Poulain em traços mais cruéis e menos esperançosos, e que tenta soar como um romance épico em torno de personagens com pouca alma e muita persistência.</p> <p>Utilizando novamente Audrey Tautou, a namoradinha da França, o diretor Jean-Pierre Jeunet mais uma vez aplica a belíssima fotografia de seu colaborador Bruno Delbonnel (Harry Potter e o Enigma do Príncipe, Inside Llewyn Davis: Balada de um Homem Comum, Amélie Poulain) e a dinâmica e inventiva montagem de seu editor Hervé Schneid (Micmacs - Um Plano Complicado) para contar uma história cheia de poder criativo, mas que encontra em seu núcleo um drama intransponível para o estilo do diretor.</p> <p>Sua busca incessante, no entanto, em tentar juntar todas as pistas que a bela mas manca Mathilde (Tatou) vai acumulando, testemunho após testemunho, em busca da verdade definitiva a respeito do paradeiro de seu amor, Manech (Gaspard Ulliel), é tão contagiante que o mundo que se cria em torno acaba compensando a total falta de realismo nesse conto quase-surrealista.</p> <p>Com aspectos técnicos impressionantes a cada cena &ndash; exceto talvez pela música de Angelo Badalamenti, repetitiva e monótona, mas ainda assim condizente com a proposta do filme &ndash; e com um ritmo que vai se formando pela repetição (a insistência do carteiro em espalhar o cascalho da entrada da casa de Mathilde, só pelo bem da &ldquo;entrada triunfal&rdquo;), o roteiro da dupla Guillaume Laurant e do próprio Pierre Jeunet, baseados no romance de Sébastien Japrisot, não consegue se desvencilhar da sua complexidade em utilizar diferentes personagens que se parecem em situações que se embaralham, o que se por um lado acaba contribuindo para a atmosfera de desorientação de Mathilde, vai aos poucos se tornando uma distração incômoda para o espectador, que já não espera encontrar qualquer conexão memorável entre as pistas.</p> <p>Até mesmo a dualidade de cores frias da guerra com as cores sempre aquecidas do presente da protagonista, fascinante no começo, também vai se esvaecendo com a cada vez mais distante capacidade de atribuir significado naquele emaranhado de símbolos. Jeunet se deixa sabotar pela sua própria obsessão de detalhes, e assim como seu mais recente trabalho, Uma Viagem Extraordinária, se esquece das emoções primárias de seus personagens para focar unicamente nas idiossincrasias de sua complexa história.</p> <p>O que acaba por fim em tornar tudo aquilo uma imensa espiral de eventos que revela uma estrutura tal qual as escadas do farol onde o casal se encontrava: aparentemente infinita, mas se encarada com dedicação e empenho, alcançável até por uma manca que deseja enxergar além de suas limitações físicas. É o metafísico celebrado em vida. A mágica de usar o cinema como cornucópia de simbolismos visuais.</p> <a href="https://www.imdb.com/title/tt0344510/mediaviewer/" target="ctvimg">Imagens</a> e créditos no <a title="IMDB: Internet Movie DataBase" href="http://www.imdb.com/title/tt0344510">IMDB</a>. </div> <span class="entry-sidebar-stars"> &#x2605;&#x2605;&#x2605;&#x2605;&#x2606; </span> Eterno Amor &#9679; Eterno Amor. Un long dimanche de fiançailles (France, 2004). Dirigido por Jean-Pierre Jeunet. Escrito por Sébastien Japrisot, Jean-Pierre Jeunet, Guillaume Laurant, Guillaume Laurant. Com Audrey Tautou, Gaspard Ulliel, Dominique Pinon, Chantal Neuwirth, André Dussollier, Ticky Holgado, Marion Cotillard, Dominique Bettenfeld, Jodie Foster. &#9679; Nota: 4/5. Categoria: movies. Publicado em 2016-01-06. Texto escrito por Wanderley Caloni. <p><br>Quer <a href="https://twitter.com/search?q=@cinetenisverde Eterno%20Amor">comentar</a>?<br></p> </div> </section> <section class="section"> <br> <div class="container"> <div class="is-flex"> <span> <a class="button">Share</a> </span> &nbsp; <span> <a class="button" href="https://www.facebook.com/sharer/sharer.php?u=http%3a%2f%2fwww.cinetenisverde.com.br%2feterno-amor%2f"> <span class="icon"><i class="fa fa-facebook"></i></span> </a> <a class="button" href="https://twitter.com/intent/tweet?url=http%3a%2f%2fwww.cinetenisverde.com.br%2feterno-amor%2f&text=Eterno%20Amor"> <span class="icon"><i class="fa fa-twitter"></i></span> </a> <a class="button" href="https://news.ycombinator.com/submitlink?u=http%3a%2f%2fwww.cinetenisverde.com.br%2feterno-amor%2f"> <span class="icon"><i class="fa fa-hacker-news"></i></span> </a> <a class="button" href="https://reddit.com/submit?url=http%3a%2f%2fwww.cinetenisverde.com.br%2feterno-amor%2f&title=Eterno%20Amor"> <span class="icon"><i class="fa fa-reddit"></i></span> </a> <a class="button" href="https://plus.google.com/share?url=http%3a%2f%2fwww.cinetenisverde.com.br%2feterno-amor%2f"> <span class="icon"><i class="fa fa-google-plus"></i></span> </a> <a class="button" href="https://www.linkedin.com/shareArticle?url=http%3a%2f%2fwww.cinetenisverde.com.br%2feterno-amor%2f&title=Eterno%20Amor"> <span class="icon"><i class="fa fa-linkedin"></i></span> </a> <a class="button" href="https://www.tumblr.com/widgets/share/tool?canonicalUrl=http%3a%2f%2fwww.cinetenisverde.com.br%2feterno-amor%2f&title=Eterno%20Amor&caption="> <span class="icon"><i class="fa fa-tumblr"></i></span> </a> <a class="button" href="https://pinterest.com/pin/create/bookmarklet/?media=%2fimg%2flogo.svg&url=http%3a%2f%2fwww.cinetenisverde.com.br%2feterno-amor%2f&description=Eterno%20Amor"> <span class="icon"><i class="fa fa-pinterest"></i></span> </a> <a class="button" href="whatsapp://send?text=http%3a%2f%2fwww.cinetenisverde.com.br%2feterno-amor%2f"> <span class="icon"><i class="fa fa-whatsapp"></i></span> </a> <a class="button" href="https://web.skype.com/share?url=http%3a%2f%2fwww.cinetenisverde.com.br%2feterno-amor%2f"> <span class="icon"><i class="fa fa-skype"></i></span> </a> </span> </div> </div> <br> </section> <footer class="footer"> <div class="container"> <nav class="level"> <div class="level-right has-text-centered"> <div class="level-item"> <a class="button" href="http://www.cinetenisverde.com.br/"> <span class="icon"><i class="fa fa-home"></i></span> </a> &nbsp; <a class="button" href="/post"> <span class="icon"><i class="fa fa-search"></i></span> </a> &nbsp; <a class="button" href="https://twitter.com/cinetenisverde"> <span class="icon"><i class="fa fa-twitter"></i></span> </a> &nbsp; <a class="button" href="/index.xml"> <span class="icon"><i class="fa fa-rss"></i></span> </a> &nbsp; </div> </div> </nav> </div> </footer> </body> </html>
{'content_hash': '5750f5fb43c3be1ac0ed645741172b4e', 'timestamp': '', 'source': 'github', 'line_count': 296, 'max_line_length': 842, 'avg_line_length': 41.986486486486484, 'alnum_prop': 0.6437882201480528, 'repo_name': 'cinetenisverde/cinetenisverde.github.io', 'id': '50eb0e0d692d60f0129f5cd086d6384190bc5365', 'size': '12522', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'eterno-amor/index.html', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'CSS', 'bytes': '533'}, {'name': 'HTML', 'bytes': '31113501'}, {'name': 'JavaScript', 'bytes': '3266'}, {'name': 'Python', 'bytes': '2943'}]}
function toggle_visibility(id) { var e = document.getElementById(id); if(e.style.display == 'block') e.style.display = 'none'; else e.style.display = 'block'; } jQuery(document).ready(function($) { $(".scroll").click(function(event){ event.preventDefault(); $('body').animate({scrollTop:$(this.hash).offset().top}, 1500); }); });
{'content_hash': '7d199aa600dde168b96b11fead6cf842', 'timestamp': '', 'source': 'github', 'line_count': 16, 'max_line_length': 91, 'avg_line_length': 33.1875, 'alnum_prop': 0.4218455743879473, 'repo_name': 'regravity/ThreadCSS', 'id': '65450d0d0e315646c520802a73cde60b56721649', 'size': '531', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'js/function.js', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'CSS', 'bytes': '42847'}, {'name': 'HTML', 'bytes': '5902'}, {'name': 'JavaScript', 'bytes': '531'}]}
package com.intellij.refactoring.move.moveInstanceMethod; import com.intellij.openapi.actionSystem.DataContext; import com.intellij.openapi.editor.Editor; import com.intellij.openapi.project.Project; import com.intellij.psi.*; import com.intellij.refactoring.move.MoveCallback; import com.intellij.refactoring.move.MoveHandlerDelegate; import com.intellij.refactoring.move.moveClassesOrPackages.JavaMoveClassesOrPackagesHandler; import org.jetbrains.annotations.Nullable; public class MoveInstanceMethodHandlerDelegate extends MoveHandlerDelegate { @Override public boolean canMove(final PsiElement[] elements, @Nullable final PsiElement targetContainer) { if (elements.length != 1) return false; PsiElement element = elements [0]; if (!(element instanceof PsiMethod)) return false; if (element instanceof SyntheticElement) return false; PsiMethod method = (PsiMethod) element; if (method.hasModifierProperty(PsiModifier.STATIC)) return false; return targetContainer == null || super.canMove(elements, targetContainer); } @Override public boolean isValidTarget(final PsiElement targetElement, PsiElement[] sources) { for (PsiElement source : sources) { if (JavaMoveClassesOrPackagesHandler.invalid4Move(source)) return false; } return targetElement instanceof PsiClass && !(targetElement instanceof PsiAnonymousClass); } @Override public boolean tryToMove(final PsiElement element, final Project project, final DataContext dataContext, final PsiReference reference, final Editor editor) { if (element instanceof PsiMethod) { PsiMethod method = (PsiMethod) element; if (!method.hasModifierProperty(PsiModifier.STATIC)) { new MoveInstanceMethodHandler().invoke(project, new PsiElement[]{method}, dataContext); return true; } } return false; } @Override public void doMove(final Project project, final PsiElement[] elements, final PsiElement targetContainer, final MoveCallback callback) { new MoveInstanceMethodHandler().invoke(project, elements, null); } }
{'content_hash': '258b6a6fd63e3565e06b0802904c7518', 'timestamp': '', 'source': 'github', 'line_count': 50, 'max_line_length': 137, 'avg_line_length': 42.2, 'alnum_prop': 0.762085308056872, 'repo_name': 'xfournet/intellij-community', 'id': 'baeb4deb8b2b865eafb7fa19f7003296554b0a91', 'size': '2710', 'binary': False, 'copies': '10', 'ref': 'refs/heads/master', 'path': 'java/java-impl/src/com/intellij/refactoring/move/moveInstanceMethod/MoveInstanceMethodHandlerDelegate.java', 'mode': '33188', 'license': 'apache-2.0', 'language': [{'name': 'AMPL', 'bytes': '20665'}, {'name': 'AspectJ', 'bytes': '182'}, {'name': 'Batchfile', 'bytes': '60827'}, {'name': 'C', 'bytes': '211454'}, {'name': 'C#', 'bytes': '1264'}, {'name': 'C++', 'bytes': '199030'}, {'name': 'CMake', 'bytes': '1675'}, {'name': 'CSS', 'bytes': '201445'}, {'name': 'CoffeeScript', 'bytes': '1759'}, {'name': 'Erlang', 'bytes': '10'}, {'name': 'Groovy', 'bytes': '3289024'}, {'name': 'HLSL', 'bytes': '57'}, {'name': 'HTML', 'bytes': '1901772'}, {'name': 'J', 'bytes': '5050'}, {'name': 'Java', 'bytes': '166392304'}, {'name': 'JavaScript', 'bytes': '570364'}, {'name': 'Jupyter Notebook', 'bytes': '93222'}, {'name': 'Kotlin', 'bytes': '4720744'}, {'name': 'Lex', 'bytes': '147486'}, {'name': 'Makefile', 'bytes': '2352'}, {'name': 'NSIS', 'bytes': '51061'}, {'name': 'Objective-C', 'bytes': '27861'}, {'name': 'Perl', 'bytes': '903'}, {'name': 'Perl 6', 'bytes': '26'}, {'name': 'Protocol Buffer', 'bytes': '6680'}, {'name': 'Python', 'bytes': '25477371'}, {'name': 'Roff', 'bytes': '37534'}, {'name': 'Ruby', 'bytes': '1217'}, {'name': 'Shell', 'bytes': '64141'}, {'name': 'Smalltalk', 'bytes': '338'}, {'name': 'TeX', 'bytes': '25473'}, {'name': 'Thrift', 'bytes': '1846'}, {'name': 'TypeScript', 'bytes': '9469'}, {'name': 'Visual Basic', 'bytes': '77'}, {'name': 'XSLT', 'bytes': '113040'}]}
/* A Bison parser, made by GNU Bison 3.0.4. */ /* Bison interface for Yacc-like parsers in C Copyright (C) 1984, 1989-1990, 2000-2015 Free Software Foundation, Inc. This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. */ /* As a special exception, you may create a larger work that contains part or all of the Bison parser skeleton and distribute that work under terms of your choice, so long as that work isn't itself a parser generator using the skeleton or a modified version thereof as a parser skeleton. Alternatively, if you modify or redistribute the parser skeleton itself, you may (at your option) remove this special exception, which will cause the skeleton and the resulting Bison output files to be licensed under the GNU General Public License without this special exception. This special exception was added by the Free Software Foundation in version 2.2 of Bison. */ #ifndef YY_YY_PARSE_H_INCLUDED # define YY_YY_PARSE_H_INCLUDED /* Debug traces. */ #ifndef YYDEBUG # define YYDEBUG 0 #endif #if YYDEBUG extern int yydebug; #endif /* Token type. */ #ifndef YYTOKENTYPE # define YYTOKENTYPE enum yytokentype { CHAR = 258, NUMBER = 259, SECTEND = 260, SCDECL = 261, XSCDECL = 262, NAME = 263, PREVCCL = 264, EOF_OP = 265, OPTION_OP = 266, OPT_OUTFILE = 267, OPT_PREFIX = 268, OPT_YYCLASS = 269, OPT_HEADER = 270, OPT_EXTRA_TYPE = 271, OPT_TABLES = 272, CCE_ALNUM = 273, CCE_ALPHA = 274, CCE_BLANK = 275, CCE_CNTRL = 276, CCE_DIGIT = 277, CCE_GRAPH = 278, CCE_LOWER = 279, CCE_PRINT = 280, CCE_PUNCT = 281, CCE_SPACE = 282, CCE_UPPER = 283, CCE_XDIGIT = 284, CCE_NEG_ALNUM = 285, CCE_NEG_ALPHA = 286, CCE_NEG_BLANK = 287, CCE_NEG_CNTRL = 288, CCE_NEG_DIGIT = 289, CCE_NEG_GRAPH = 290, CCE_NEG_LOWER = 291, CCE_NEG_PRINT = 292, CCE_NEG_PUNCT = 293, CCE_NEG_SPACE = 294, CCE_NEG_UPPER = 295, CCE_NEG_XDIGIT = 296, CCL_OP_DIFF = 297, CCL_OP_UNION = 298, BEGIN_REPEAT_POSIX = 299, END_REPEAT_POSIX = 300, BEGIN_REPEAT_FLEX = 301, END_REPEAT_FLEX = 302 }; #endif /* Tokens. */ #define CHAR 258 #define NUMBER 259 #define SECTEND 260 #define SCDECL 261 #define XSCDECL 262 #define NAME 263 #define PREVCCL 264 #define EOF_OP 265 #define OPTION_OP 266 #define OPT_OUTFILE 267 #define OPT_PREFIX 268 #define OPT_YYCLASS 269 #define OPT_HEADER 270 #define OPT_EXTRA_TYPE 271 #define OPT_TABLES 272 #define CCE_ALNUM 273 #define CCE_ALPHA 274 #define CCE_BLANK 275 #define CCE_CNTRL 276 #define CCE_DIGIT 277 #define CCE_GRAPH 278 #define CCE_LOWER 279 #define CCE_PRINT 280 #define CCE_PUNCT 281 #define CCE_SPACE 282 #define CCE_UPPER 283 #define CCE_XDIGIT 284 #define CCE_NEG_ALNUM 285 #define CCE_NEG_ALPHA 286 #define CCE_NEG_BLANK 287 #define CCE_NEG_CNTRL 288 #define CCE_NEG_DIGIT 289 #define CCE_NEG_GRAPH 290 #define CCE_NEG_LOWER 291 #define CCE_NEG_PRINT 292 #define CCE_NEG_PUNCT 293 #define CCE_NEG_SPACE 294 #define CCE_NEG_UPPER 295 #define CCE_NEG_XDIGIT 296 #define CCL_OP_DIFF 297 #define CCL_OP_UNION 298 #define BEGIN_REPEAT_POSIX 299 #define END_REPEAT_POSIX 300 #define BEGIN_REPEAT_FLEX 301 #define END_REPEAT_FLEX 302 /* Value type. */ #if ! defined YYSTYPE && ! defined YYSTYPE_IS_DECLARED typedef int YYSTYPE; # define YYSTYPE_IS_TRIVIAL 1 # define YYSTYPE_IS_DECLARED 1 #endif extern YYSTYPE yylval; int yyparse (void); #endif /* !YY_YY_PARSE_H_INCLUDED */
{'content_hash': '42ea53de0b18b9312c7c7ce32521c551', 'timestamp': '', 'source': 'github', 'line_count': 154, 'max_line_length': 76, 'avg_line_length': 26.733766233766232, 'alnum_prop': 0.7002671848433325, 'repo_name': 'loki04/csibe', 'id': '033f91974e11261d03432c8861554b8c22759016', 'size': '4117', 'binary': False, 'copies': '3', 'ref': 'refs/heads/master', 'path': 'src/flex-2.6.0/src/parse.h', 'mode': '33188', 'license': 'bsd-3-clause', 'language': [{'name': 'Awk', 'bytes': '2800'}, {'name': 'C', 'bytes': '1097132'}, {'name': 'C++', 'bytes': '8474'}, {'name': 'CMake', 'bytes': '15006'}, {'name': 'CSS', 'bytes': '1746'}, {'name': 'Groff', 'bytes': '26612'}, {'name': 'HTML', 'bytes': '128005'}, {'name': 'LLVM', 'bytes': '5737'}, {'name': 'Lex', 'bytes': '136350'}, {'name': 'M4', 'bytes': '99282'}, {'name': 'Makefile', 'bytes': '325456'}, {'name': 'PHP', 'bytes': '3703'}, {'name': 'Perl', 'bytes': '12320'}, {'name': 'Prolog', 'bytes': '430'}, {'name': 'Python', 'bytes': '17647'}, {'name': 'Shell', 'bytes': '427842'}, {'name': 'TeX', 'bytes': '323102'}, {'name': 'XSLT', 'bytes': '12288'}, {'name': 'Yacc', 'bytes': '34188'}]}
class CreateBodyParts < ActiveRecord::Migration def change create_table :body_parts do |t| t.string :name t.string :slug t.timestamps end end end
{'content_hash': 'bcbb25f0fca33b6b77f093ac63fc8a3c', 'timestamp': '', 'source': 'github', 'line_count': 10, 'max_line_length': 47, 'avg_line_length': 17.7, 'alnum_prop': 0.6497175141242938, 'repo_name': 'ericallfesta/kirarirenew', 'id': '2c5397417d461fc527311a5c819eb20986940424', 'size': '177', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'proto.git 2/db/migrate/20140103132455_create_body_parts.rb', 'mode': '33261', 'license': 'apache-2.0', 'language': [{'name': 'CSS', 'bytes': '170444'}, {'name': 'CoffeeScript', 'bytes': '2178'}, {'name': 'JavaScript', 'bytes': '99649'}, {'name': 'Ruby', 'bytes': '234345'}]}
Making a formula is easy. Just `brew create URL` and then `brew install $FORMULA` (perhaps with `--debug --verbose`). Basically, a formula is a Ruby file. You can place it anywhere you want (local or remote) and install it by pointing to the file or URL. We want your formula to be awesome, and the cookbook will tell you how. ## Terminology - Homebrew speak <table> <tbody> <tr> <th>Formula</th> <td>The package definition</td> <td><code>/usr/local/Library/Formula/foo.rb</code></td> </tr> <tr> <th>Keg</th> <td>The installation prefix of a Formula</td> <td><code>/usr/local/Cellar/foo/0.1</code></td> </tr> <tr> <th>opt prefix</th> <td>A symlink to the active version of a keg</td> <td><code>/usr/local/opt/foo</code></td> </tr> <tr> <th>Cellar</th> <td>All kegs are installed here</td> <td><code>/usr/local/Cellar</code></td> </tr> <tr> <th>Tap</th> <td>An optional repository (git) of Formulae</td> <td><code>/usr/local/Library/Taps</code></td> </tr> <tr> <th>Bottle</th> <td>Pre-built (binary) Keg that can be unpacked</td> <td><code>qt-4.8.4.mountain_lion.bottle.1.tar.gz</code></td> </tr> </tbody> </table> _More general: `brew --prefix` and `brew --repository` instead of `/usr/local` but lets KISS._ ## An Introduction Did you see `/usr/local/.git`? Homebrew is built on Git. This means you can just do your work in `/usr/local` and merge in upstream changes as you go. Homebrew installs to the `Cellar`, it then symlinks some of the installation into `/usr/local` so that other programs can see what's going on. We suggest you `brew ls` a few of the kegs in your Cellar to see how it is all arranged. Packages are installed according to their formulae, which live in `$(brew --repository)/Library/Formula`. Check some out. You can view any formula at anytime; e.g. `brew edit wget`. # Basic Instructions Make sure you run `brew update` before you start. This turns your Homebrew installation into a Git repository. Before contributing, make sure your package: * meets all our [Acceptable Formulae](Acceptable-Formulae.md) requirements * isn't already in Homebrew (check `brew search $FORMULA`) * isn't in another [Homebrew tap](https://github.com/Homebrew) * isn't already waiting to be merged (check the [issue tracker](https://github.com/Homebrew/homebrew/issues)) * is still supported by upstream * has a stable, tagged version (i.e. not just a GitHub repository with no versions). See [Interesting-Taps-&-Branches](Interesting-Taps-&-Branches.md) for where pre-release and head-only versions belong. Make sure you search thoroughly (all aliases!). We don’t want you to waste your time. Be sure to look over the [contributing guidelines](https://github.com/Homebrew/homebrew/blob/master/CONTRIBUTING.md) as well. ## Will we merge your formula? Probably. But we have rules to keep the quality and goals of Homebrew intact: Please read [Acceptable Formulae](Acceptable-Formulae.md). ## Some Quick Examples Before You Get Started Formulae aren’t that complicated. [etl](https://github.com/Homebrew/homebrew/blob/master/Library/Formula/etl.rb) is as simple as it gets. And then [Git](https://github.com/Homebrew/homebrew/tree/master/Library/Formula/git.rb) and [flac](https://github.com/Homebrew/homebrew/tree/master/Library/Formula/flac.rb) show more advanced functionality. A more complete example-formula [cheat-sheet](https://github.com/Homebrew/homebrew/blob/master/Library/Contributions/example-formula.rb) shows almost all the stuff you can use in a Formula. ## Grab the URL All you need to make a formula is a URL to the tarball. brew create http://example.com/foo-0.1.tar.gz This creates: `$HOMEBREW_REPOSITORY/Library/Formula/foo.rb` And opens it in your `$EDITOR`. It'll look like: ```ruby class Foo < Formula url "http://example.com/foo-0.1.tar.gz" homepage "" sha256 "85cc828a96735bdafcf29eb6291ca91bac846579bcef7308536e0c875d6c81d7" # depends_on "cmake" => :build def install system "./configure", "--prefix=#{prefix}", "--disable-debug", "--disable-dependency-tracking" # system "cmake", ".", *std_cmake_args system "make", "install" end end ``` **Note:** If `brew` said `Warning: Version cannot be determined from URL` when doing the `create` step, you’ll need to explicitly add the correct version to the formula with `version "foo"` **and then save the formula**. `brew install` should then proceed without any trouble. **Note:** If `brew` said `No formula found for "php54-timezonedb". Searching open pull requests...` and you are writing a Tap, you should run `brew tap --repair`. ## Fill in the Homepage **We don’t accept formulae without homepages!** Homebrew now has a description field (`desc`). Try and summarize this from the homepage. ## Check the build system brew install -i foo You’re now at new prompt with the tarball extracted to a temporary sandbox. Check the package’s `README`. Does the package install with `autotools`, `cmake`, or something else? Delete the commented out cmake lines if the package uses autotools (i.e. if it has a `configure` script). ## Check for dependencies The `README` probably tells you about dependencies. Homebrew or OS X probably already has them. You can check for Homebrew deps with `brew search`. These are the common deps that OS X comes with: * `libexpat` * `libGL` * `libiconv` * `libpcap` * `libxml2` * `Python` * `Ruby` There are plenty of others. Check `/usr/lib` to see. We try to not duplicate libraries and complicated tools in core Homebrew. We dupe some common tools though. But generally, we avoid dupes because it’s one of Homebrew’s foundations. (And it causes build and usage problems!) The one special exception is OpenSSL. Anything that uses OpenSSL *should* be built using Homebrew’s shipped OpenSSL and our test bot's post-install audit will warn of this when it is detected. (*Of course, there are exceptions to the exception. Not everything can be forced onto our OpenSSL)*. Because Homebrew’s OpenSSL is `keg_only` to avoid conflicting with the system sometimes formulae need to have environmental variables set or special configuration flags passed to locate our preferred OpenSSL; you can see this mechanism in the [clamav](https://github.com/Homebrew/homebrew/blob/master/Library/Formula/clamav.rb#L28) formula. Usually this is unnecessary because when OpenSSL is specified as a dependency Homebrew temporarily prepends the $PATH with that prefix. Homebrew maintains a special [tap that provides other useful dupes](https://github.com/Homebrew/homebrew-dupes). *Important:* Since the introduction of `superenv`, `brew --prefix`/bin is NOT on the `$PATH` during formula installation. If you have dependencies at build time, you must specify them and brew will add them to the `$PATH`. You can test around this with `--env=std`. ## Specifying other formulae as dependencies ```ruby class Foo < Formula depends_on "jpeg" depends_on "gtk+" => :optional depends_on "readline" => :recommended depends_on "boost" => "with-icu" depends_on :x11 => :optional end ``` A String specifies a formula dependency. A Symbol specifies a special conditional dependency, such as X11. A Hash specifies a formula dependency with some additional information. Given a single string key, the value can take several forms: * a Symbol (currently one of `:build`, `:optional`, `:recommended`). - `:build` tags that dependency as a build-time only dependency, meaning it can be safely ignored when installing from a bottle and when listing missing dependencies using `brew missing`. - `:optional` generates an implicit `with-foo` option for the formula. This means that, given `depends_on "foo" => :optional`, the user must pass `--with-foo` in order to enable the dependency. - `:recommended` generates an implicit `without-foo` option, meaning that the dependency is enabled by default and the user must pass `--without-foo` to disable this dependency. The default description can be overridden using the normal option syntax (in this case, the option declaration must precede the dependency): ```ruby option "with-foo", "Compile with foo bindings" # This overrides the generated description if you want to depends_on "foo" => :optional # Generated description is "Build with foo support" ``` * a String or an Array String values are interpreted as options to be passed to the dependency. You can also pass an array of strings, or an array of symbols and strings, in which case the symbols are interpreted as described above, and the strings are passed to the dependency as options. ```ruby depends_on "foo" => "with-bar" depends_on "foo" => %w{with-bar with-baz} depends_on "foo" => [:optional, "with-bar"] ``` ## Specifying other formulae as conflicts Sometimes there’s hard conflict between formulae, and it can’t be avoided or circumvented with `keg_only`. PolarSSL is a good [example](https://github.com/Homebrew/homebrew/blob/master/Library/Formula/polarssl.rb#L36-L37) formula for minor conflict. PolarSSL ship GNU’s Hello, and compiles a `hello` binary. This is obviously non-essential to PolarSSL’s functionality, and conflict with the `hello` formula would be overkill, so we just remove it. However, also in the PolarSSL formulae is a [firm conflict](https://github.com/Homebrew/homebrew/blob/master/Library/Formula/polarssl.rb#L19) with `md5sha1sum`, because both `md5sha1sum` and `polarssl` compile identically-named binaries that *are* important for core functionality. As a general rule, `conflicts_with` should be a last-resort option. It’s a fairly blunt instrument. The syntax for conflict that can’t be worked around is ```ruby conflicts_with "blueduck", :because => "yellowduck also ships a duck binary" ``` ## Formulae Revisions In Homebrew we sometimes accept formulae updates that don’t include a version bump. These include homepage changes, resource updates, new patches or fixing a security issue with a formula. Occasionally, these updates require a forced-recompile of the formula itself or its dependents to either ensure formulae continue to function as expected or to close a security issue. This forced-recompile is known as a `revision` and inserted underneath the homepage/url/sha block. Where a dependent of a formula fails against a new version of that dependency it must receive a `revision`. An example of such failure can be seen [here](https://github.com/Homebrew/homebrew/issues/31195) and the fix [here](https://github.com/Homebrew/homebrew/pull/31207). `Revisions` are also used for formulae that move from the system OpenSSL to the Homebrew-shipped OpenSSL without any other changes to that formula. This ensures users aren’t left exposed to the potential security issues of the outdated OpenSSL. An example of this can be seen in [this commit](https://github.com/Homebrew/homebrew/commit/6b9d60d474d72b1848304297d91adc6120ea6f96). ## Double-check for dependencies When you already have a lot of brews installed, its easy to miss a common dependency like `glib` or `gettext`. You can double-check which libraries a binary links to with the `otool` command (perhaps you need to use `xcrun otool`): $ otool -L /usr/local/bin/ldapvi /usr/local/bin/ldapvi: /usr/local/opt/openssl/lib/libssl.1.0.0.dylib (compatibility version 1.0.0, current version 1.0.0) /usr/local/opt/openssl/lib/libcrypto.1.0.0.dylib (compatibility version 1.0.0, current version 1.0.0) /usr/local/lib/libglib-2.0.0.dylib (compatibility version 4201.0.0, current version 4201.0.0) /usr/local/opt/gettext/lib/libintl.8.dylib (compatibility version 10.0.0, current version 10.2.0) /usr/local/opt/readline/lib/libreadline.6.dylib (compatibility version 6.0.0, current version 6.3.0) /usr/local/lib/libpopt.0.dylib (compatibility version 1.0.0, current version 1.0.0) /usr/lib/libncurses.5.4.dylib (compatibility version 5.4.0, current version 5.4.0) /System/Library/Frameworks/LDAP.framework/Versions/A/LDAP (compatibility version 1.0.0, current version 2.4.0) /usr/lib/libresolv.9.dylib (compatibility version 1.0.0, current version 1.0.0) /usr/lib/libSystem.B.dylib (compatibility version 1.0.0, current version 1213.0.0) ## Specifying gems, Python modules, Go projects, etc. as dependencies Homebrew doesn’t package already packaged language-specific libraries. These should be installed directly from `gem`/`cpan`/`pip` etc. If you're installing an application then please locally vendor all the language-specific dependencies: ```ruby class Foo < Formula resource "pycrypto" do url "https://pypi.python.org/packages/source/p/pycrypto/pycrypto-2.6.tar.gz" sha256 "85cc828a96735bdafcf29eb6291ca91bac846579bcef7308536e0c875d6c81d7" end def install resource("pycrypto").stage { system "python", *Language::Python.setup_install_args(libexec/"vendor") } end end ``` [jrnl](https://github.com/Homebrew/homebrew/blob/master/Library/Formula/jrnl.rb) is an example of a formula that does this well. The end-result means the user doesn't have to faff with `pip` or Python and can just run `jrnl`. [homebrew-pypi-poet](https://github.com/tdsmith/homebrew-pypi-poet) can help you generate resource stanzas for the dependencies of your Python application. Similarly, [homebrew-go-resources](https://github.com/samertm/homebrew-go-resources) can help you generate go\_resource stanzas for the dependencies of your go application. If your formula needs a gem or python module and it can't be made into a resource you’ll need to check for these external dependencies: ```ruby class Foo < Formula depends_on "mg" => :ruby depends_on "json" => :python depends_on "Authen::NTLM" => :perl end ``` Note that we probably won't accept the formulae in this case; it's a far worse user experience than vendoring libraries with resources. ## Test the formula Exit out of the interactive shell. brew install --verbose --debug foo Debug will ask you to open an interactive shell when the build fails so you can try to figure out what went wrong. Check the top of the `./configure` output (if applicable)! Some configure scripts do not recognize `--disable-debug`. If you see a warning about it, remove the option from the formula. ## Add a test to the formula Please add a `test do` block to the formula. This will be run by `brew test foo` and the [Brew Test Bot](Brew-Test-Bot.md). The `test do` block automatically creates and changes to a temporary directory which is deleted after run. You can access this Pathname with the `testpath` function. We want tests that don't require any user input and test the basic functionality of the application. For example `foo build-foo input.foo` is a good test and (despite their widespread use) `foo --version` and `foo --help` are bad tests. However, a bad test is better than no test at all. See [cmake](https://github.com/Homebrew/homebrew/blob/master/Library/Formula/cmake.rb) for an example of a formula with a good test. A basic `CMakeLists.txt` file is written CMake uses it to generate Makefiles. This test checks that CMake doesn't e.g. segfault during basic operation. ## Manuals Homebrew expects to find man pages in `[prefix]/share/man/...`, and not in `[prefix]/man/...`. Some software installs to man instead of `share/man`, so check the output and add a `"--mandir=#{man}"` to the `./configure` line if needed. ## A Quick Word on Naming **THE NAME IS VERY IMPORTANT!** Name the formula like the project markets the product. So it’s `pkg-config`, not `pkgconfig`; `sdl_mixer`, not `sdl-mixer` or `sdlmixer`. The only exception is stuff like “Apache Ant”. Apache sticks “Apache” in front of everything, but we use the formula name `ant`. We only include the prefix in cases like *GNUplot* (because it’s part of the name) and *GNU Go* (because everyone calls it “GNU go”—nobody just calls it “Go”). The word “Go” is too common and there are too many implementations of it. If you’re not sure about the name check the homepage, and check the Wikipedia page. [ALSO CHECK WHAT DEBIAN CALLS IT!](https://www.debian.org/distrib/packages) Where Homebrew already has a formula called `foo` we typically do not accept requests to replace that formula with something else also named `foo`. This is to avoid both confusing and surprising users’ expectation. When two formulae share an upstream name, e.g. [`AESCrypt`](https://github.com/Homebrew/homebrew/blob/master/Library/Formula/aescrypt.rb) and [`AESCrypt`](https://github.com/Homebrew/homebrew/blob/master/Library/Formula/aescrypt-packetizer.rb) the newer formula must typically adapt the name to avoid conflict with the current formula. If you’re *still* not sure, just commit. We’ll apply some arbitrary rule and make a decision ;) When importing classes, Homebrew will require the formula and then create an instance of the class. It does this by assuming the formula name can be directly converted to the class name using a `regexp`. The rules are simple: * `foo-bar.rb` => `FooBar` * `foobar.rb` => `Foobar` Thus, if you change the name of the class, you must also rename the file. Filenames should be all lowercase. Add aliases by creating symlinks in `Library/Aliases`. ## Audit the formula You can run `brew audit` to test formulae for adherence to Homebrew house style. This includes warnings for trailing whitespace, preferred URLs for certain source hosts, and a lot of other style issues. Fixing these warnings before committing will make the process a lot smoother for us. Use `brew info` and check if the version guessed by Homebrew from the URL is correct. Add an explicit `version` if not. ## Commit Everything is built on Git, so contribution is easy: brew install git # if you already have git installed, skip this command brew update # required in more ways than you think (initializes the brew git repository if you don't already have it) cd `brew --repository` # Create a new git branch for your formula so your pull request is easy to # modify if any changes come up during review. git checkout -b <some-descriptive-name> git add Library/Formula/foo.rb git commit The established standard for Git commit messages is: * the first line is a commit summary of *50 characters or less*, then * two (2) newlines, then * explain the commit throughly At Homebrew, we like to put the name of the formula upfront like so "foobar 7.3 (new formula)". This may seem crazy short, but you’ll find that forcing yourself to summarise the commit encourages you to be atomic and concise. If you can’t summarise it in 50-80 characters, you’re probably trying to commit two commits as one. For a more thorough explanation, please read Tim Pope’s excellent blog post, [A Note About Git Commit Messages](http://tbaggery.com/2008/04/19/a-note-about-git-commit-messages.html). The preferred commit message format for simple version updates is "foobar 7.3". Ensure you reference any relevant GitHub issue `#12345` in the commit message. Homebrew’s history is the first thing future contributors will look to when trying to understand the current state of formulae they’re interested in. ## Push Now you just need to push back to GitHub. If you haven’t forked Homebrew yet, [go to the repo and hit the fork button](https://github.com/Homebrew/homebrew). If you have already forked Homebrew on GitHub, then you can manually push (just make sure you have been pulling from the Homebrew/homebrew master): git push [email protected]:myname/homebrew.git <what-you-called-your-branch> Now, please open a Pull Request (on your GitHub repo page) for new and updated brews. * One formula per commit; one commit per formula * Keep merge commits out of the request * If you have any merge or mixup commits, please [squash](http://gitready.com/advanced/2009/02/10/squashing-commits-with-rebase.html) them. If a commit touches multiple files, or isn’t one logical bug fix, or a file is touched in multiple commits, we’ll probably ask you to `rebase` and `squash` your commits. For this reason, you should avoid pushing to your `master` branch. Note, after rebase and/or squash, you'll need to push with `--force` to your remote. # Overview of the Formula Install Process <!-- TODO rewrite this. It is outdated, there are more layers now, and the implementation details discussed here are not relevant or useful to most users anyway. --> * The result of `Formula.download_strategy` is instantiated. * `DownloadStrategy.fetch` is called (downloads tarball, checks out git repository, etc.) * A temporary sandbox is created in `/tmp/$formulaname` * `DownloadStrategy.stage` is called (extracts tarball to above sandbox, exports git repository to sandbox, etc.) * Patches are applied * Current directory is changed to the stage root (so when you `system make`, it works) * `Formula.install` is called * Anything installed to the keg is cleaned (see later) * The keg is symlinked into Homebrew’s prefix * Caveats are displayed # Convenience Tools ## Messaging Three commands are provided for displaying informational messages to the user: * `ohai` for general info * `opoo` for warning messages * `onoe` for error messages In particular, when a test needs to be performed before installation use `onoe` to bail out gracefully. For example: ```ruby if some_test? system "make", "install" else onoe "Error! Something is wrong." end ``` ## bin.install "foo" You’ll see stuff like that in other formulae. This installs the file foo into the Formula’s `bin` directory (`/usr/local/Cellar/pkg/0.1/bin`) and makes it executable (`chmod 0555 foo`). ## inreplace A convenience function that can edit files in-place. For example: `inreplace "path", before, after` `before` and `after` can be strings or regexps. You can also use the block form: ```ruby inreplace "path" do |s| s.gsub! /foo/, "bar" end ``` Make sure you modify `s`! This block ignores the returned value. `inreplace` should be used instead of patches when it is patching something that will never be accepted upstream e.g. make the software’s build system respect Homebrew’s installation hierarchy. If it's Homebrew and MacPorts or OS X specific it should be turned into a patch instead. If you need modify variables in a Makefile, rather than using `inreplace`, pass them as arguments to make: ```rb system "make", "target", "VAR2=value1", "VAR2=value2", "VAR3=values can have spaces" ``` ```rb args = %W[ CC=#{ENV.cc} PREFIX=#{prefix} ] system "make", *args ``` Note that values *can* contain unescaped spaces if you use the multiple-argument form of `system`. ## Patches While patches should generally be avoided, sometimes they are necessary. When patching (i.e. fixing header file inclusion, fixing compiler warnings, etc.) the first thing to do is check whether or not the upstream project is aware of the issue. If not, file a bug report and/or submit your patch for inclusion. We may sometimes still accept your patch before it was submitted upstream but by getting the ball rolling on fixing the upstream issue you reduce the length of time we have to carry the patch around. *Always, always, always justify a patch with a code comment!* Otherwise, nobody will know when it is safe to remove the patch, or safe to leave it in when updating the formula. The comment should include a link to the relevant upstream issue(s). External patches can be declared using resource-style blocks: ```rb patch do url "https://example.com/example_patch.diff" sha256 "85cc828a96735bdafcf29eb6291ca91bac846579bcef7308536e0c875d6c81d7" end ``` A strip level of -p1 is assumed. It can be overridden using a symbol argument: ```rb patch :p0 do url "https://example.com/example_patch.diff" sha256 "85cc828a96735bdafcf29eb6291ca91bac846579bcef7308536e0c875d6c81d7" end ``` Patches can be declared in stable, devel, and head blocks. NOTE: always use a block instead of a conditional, i.e. `stable do ... end` instead of `if build.stable? then ... end`. ```rb stable do # some other things... patch do url "https://example.com/example_patch.diff" sha256 "85cc828a96735bdafcf29eb6291ca91bac846579bcef7308536e0c875d6c81d7" end end ``` Embedded (__END__) patches can be declared like so: ```rb patch :DATA patch :p0, :DATA ``` with the patch data included at the end of the file: ``` __END__ diff --git a/foo/showfigfonts b/foo/showfigfonts index 643c60b..543379c 100644 --- a/foo/showfigfonts +++ b/foo/showfigfonts @@ -14,6 +14,7 @@ … ``` Patches can also be embedded by passing a string. This makes it possible to provide multiple embedded patches while making only some of them conditional. ```rb patch :p0, "..." ``` In embedded patches, the string `HOMEBREW_PREFIX` is replaced with the value of the constant `HOMEBREW_PREFIX` before the patch is applied. ## Creating the diff brew install --interactive --git foo … (make some edits) … git diff | pbcopy brew edit foo Now just paste into the formula after `__END__`. Instead of `git diff | pbcopy`, for some editors `git diff >> path/to/your/formula/foo.rb` might help you that the diff is not touched (e.g. white space removal, indentation, etc.) # Advanced Formula Tricks If anything isn’t clear, you can usually figure it out with some `grep` and the `Library/Formula` directory. Please amend this document if you think it will help! ## Unstable versions (`HEAD`, `devel`) Formulae can specify alternate downloads for the upstream project’s `devel` release (unstable but not `trunk`) or `HEAD` (`master/trunk`). ### HEAD HEAD URLs (activated by passing `--HEAD`) build the development cutting edge. Specifying it is easy: ```ruby class Foo < Formula head "https://github.com/mxcl/lastfm-cocoa.git" end ``` Homebrew understands `git`, `svn`, and `hg` URLs, and has a way to specify `cvs` repositories as a URL as well. You can test whether the `HEAD` is being built with `build.head?`. To use a specific commit, tag, or branch from a repository, specify head with the `:tag` and `:revision`, `:revision`, or `:branch` option, like so: ```ruby class Foo < Formula head "https://github.com/some/package.git", :revision => "090930930295adslfknsdfsdaffnasd13" # or :branch => "develop" # or :tag => "1_0_release", # :revision => "090930930295adslfknsdfsdaffnasd13" end ``` Formulae that only have `head` versions should be submitted to [homebrew/headonly](https://github.com/Homebrew/homebrew-headonly) instead of Homebrew/homebrew. ### devel The "devel" spec (activated by passing `--devel`) is used for a project’s unstable releases. It is specified in a block: ```ruby devel do url "https://foo.com/foo-0.1.tar.gz" sha256 "85cc828a96735bdafcf29eb6291ca91bac846579bcef7308536e0c875d6c81d7" end ``` You can test if the "devel" spec is in use with `build.devel?`. ## Compiler selection Sometimes a package fails to build when using a certain compiler. Since recent Xcode no longer includes a GCC compiler, we cannot simply force the use of GCC. Instead, the correct way to declare this is the `fails_with` DSL method. A properly constructed `fails_with` block documents the latest compiler build version known to cause compilation to fail, and the cause of the failure. For example: ```ruby fails_with :llvm do build 2335 cause <<-EOS.undent The "cause" field should include a short summary of the error. Include the URLs of any relevant information, such as upstream bug reports. Wrap the text at a sensible boundary (~72-80 characters), but do not break URLs over multiple lines. EOS end ``` `build` takes a Fixnum (you can find this number in your `brew --config` output). `cause` takes a string, and the use of heredocs is encouraged to improve readability and allow for more comprehensive documentation. `fails_with` declarations can be used with any of `:gcc`, `:llvm`, and `:clang`. Homebrew will use this information to select a working compiler (if one is available). ## Specifying the Download Strategy explicitly To use one of Homebrew’s built-in download strategies, specify the `:using =>` flag on a `url` or `head`. For example: ```ruby class Sip < Formula url "http://www.riverbankcomputing.co.uk/hg/sip/archive/4.11" md5 "dbafd7101a4e7caee6f529912a1356e5" head "http://www.riverbankcomputing.co.uk/hg/sip", :using => :hg homepage "http://www.riverbankcomputing.co.uk/software/sip" ``` The downloaders offered by Homebrew are: <table> <thead> <tr> <th>Value of <code>:using</code></th> <th>Corresponds To</th> </tr> </thead> <tbody> <tr> <td><code>:bzr</code></td> <td><code>BazaarDownloadStrategy</code></td> </tr> <tr> <td><code>:curl</code></td> <td><code>CurlDownloadStrategy</code></td> </tr> <tr> <td><code>:cvs</code></td> <td><code>CVSDownloadStrategy</code></td> </tr> <tr> <td><code>:git</code></td> <td><code>GitDownloadStrategy</code></td> </tr> <tr> <td><code>:hg</code></td> <td><code>MercurialDownloadStrategy</code></td> </tr> <tr> <td><code>:nounzip</code></td> <td><code>NoUnzipCurlDownloadStrategy</code></td> </tr> <tr> <td><code>:post</code></td> <td><code>CurlPostDownloadStrategy</code></td> </tr> <tr> <td><code>:svn</code></td> <td><code>SubversionDownloadStrategy</code></td> </tr> </tbody> </table> If you need more control over the way files are downloaded and staged, you can create a custom download strategy and specify it using the `url` method's `:using` option: ```ruby class MyDownloadStrategy < SomeHomebrewDownloadStrategy # Does something cool end class Foo < Formula url "something", :using => MyDownloadStrategy end ``` Specifying download strategies can be useful when used with a local repo, where a plain URL would not let you specify how to access it. For example: ```ruby class Bar < Formula head "/users/abc/src/git.git", :using => :git end ``` ## Just copying some files When your code in the install function is run, the current working directory is set to the extracted tarball. So it is easy to just copy some files: ```ruby prefix.install "file1", "file2" ``` Or everything: ```ruby prefix.install Dir["output/*"] ``` Generally we'd rather you were specific about what files or directories need to be installed rather than installing everything. ### Variables for directory locations <table> <thead> <tr> <th>Name</th> <th>Default</th> <th>Example</th> </tr> </thead> <tbody> <tr> <th><code>HOMEBREW_PREFIX</code></th> <td><code>/usr/local</code></td> <td></td> </tr> <tr> <th><code>prefix</code></th> <td><code>#{HOMEBREW_PREFIX}/Cellar/#{name}/#{version}</code></td> <td><code>/usr/local/Cellar/foo/0.1</code></td> </tr> <tr> <th><code>opt_prefix</code></th> <td><code>#{HOMEBREW_PREFIX}/opt/#{name}</code></td> <td><code>/usr/local/opt/foo</code></td> </tr> <tr> <th><code>bin</code></th> <td><code>#{prefix}/bin</code></td> <td><code>/usr/local/Cellar/foo/0.1/bin</code></td> </tr> <tr> <th><code>doc</code></th> <td><code>#{prefix}/share/doc/foo</code></td> <td><code>/usr/local/Cellar/foo/0.1/share/doc/foo</code></td> </tr> <tr> <th><code>include</code></th> <td><code>#{prefix}/include</code></td> <td><code>/usr/local/Cellar/foo/0.1/include</code></td> </tr> <tr> <th><code>info</code></th> <td><code>#{prefix}/share/info</code></td> <td><code>/usr/local/Cellar/foo/0.1/share/info</code></td> </tr> <tr> <th><code>lib</code></th> <td><code>#{prefix}/lib</code></td> <td><code>/usr/local/Cellar/foo/0.1/lib</code></td> </tr> <tr> <th><code>libexec</code></th> <td><code>#{prefix}/libexec</code></td> <td><code>/usr/local/Cellar/foo/0.1/libexec</code></td> </tr> <tr> <th><code>man</code></th> <td><code>#{prefix}/share/man</code></td> <td><code>/usr/local/Cellar/foo/0.1/share/man</code></td> </tr> <tr> <th><code>man[1-8]</code></th> <td><code>#{prefix}/share/man/man[1-8]</code></td> <td><code>/usr/local/Cellar/foo/0.1/share/man/man[1-8]</code></td> </tr> <tr> <th><code>sbin</code></th> <td><code>#{prefix}/sbin</code></td> <td><code>/usr/local/Cellar/foo/0.1/sbin</code></td> </tr> <tr> <th><code>share</code></th> <td><code>#{prefix}/share</code></td> <td><code>/usr/local/Cellar/foo/0.1/share</code></td> </tr> <tr> <th><code>etc</code></th> <td><code>#{HOMEBREW_PREFIX}/etc</code></td> <td><code>/usr/local/etc</code></td> </tr> <tr> <th><code>var</code></th> <td><code>#{HOMEBREW_PREFIX}/var</code></td> <td><code>/usr/local/var</code></td> </tr> <tr> <th><code>buildpath</code></th> <td>A temporary dir somewhere on your system</td> <td><code>/private/tmp/[formula-name]-0q2b/[formula-name]</code></td> </tr> </tbody> </table> These can be used, for instance, in code such as ```ruby bin.install Dir["output/*"] ``` to install binaries into their correct location into the cellar, and ```ruby man.mkpath ``` to create the directory structure to the man location. To install man pages into specific locations, use `man1.install "foo.1", "bar.1"`, `man2.install "foo.2"`, etc. Note that in the context of Homebrew, `libexec` is reserved for private use by the formula and therefore is not symlinked into `HOMEBREW_PREFIX`. ### Installation without linking into `/usr/local` (keg-only) If you only need a program for a dependency and it does not need to be linked for public use in `/usr/local`, specify ```ruby keg_only "This is my rationale." ``` in the Formula class. ## Adding optional steps If you want to add an option: ```ruby class Yourformula < Formula ... option "with-ham", "Description of the option" option "without-spam", "Another description" depends_on "foo" => :optional # will automatically add a with-foo option ... ``` And then to define the effects the options have: ```ruby if build.with? "ham" # note, no "with" in the option name (it is added by the build.with? method) end if build.without? "ham" # works as you'd expect. True if `--without-ham` was given. end if build.include? "enable-ham" # the deprecated style, only useful for options other than `with`/`without` style end ``` Option names should be prefixed with one of the words `with`, `without`, `no`, or a verb in the imperative tense describing the action to be taken. For example, an option to run a test suite should be named `--with-test` or `--with-check` rather than `--test`, and an option to enable a shared library should be named `--enable-shared` rather than `--shared`. Note that options that aren’t ` build.with? ` or ` build.without? ` should be actively deprecated where possible. See [wget](https://github.com/Homebrew/homebrew/blob/master/Library/Formula/wget.rb#L27-L31) for an example. See the [graphviz](https://github.com/Homebrew/homebrew/blob/master/Library/Formula/graphviz.rb) formula for an example. ## File level operations You can use the file utilities provided by Ruby (`FileUtils`). These are included in the `Formula` class, so you do not need the `FileUtils.` prefix to use them. They are documented [here](http://www.ruby-doc.org/stdlib/libdoc/fileutils/rdoc/index.html). When creating symlinks, take special care to ensure they are *relative* symlinks. This makes it easier to create a relocatable bottle. For example, to create a symlink in `bin` to an executable in `libexec`, use ```rb bin.install_symlink libexec/"name" ``` *not* ```rb ln_s libexec/"name", bin ``` The symlinks created by `install_symlink` are guaranteed to be relative. `ln_s` will only produce a relative symlink when given a relative path. ## Handling files that should persist over formula upgrades For example, Ruby 1.9’s gems should be installed to `var/lib/ruby/` so that gems don’t need to be reinstalled when upgrading Ruby. You can usually do this with symlink trickery, or *better* a configure option. ### launchd plist files Homebrew provides two Formula methods for launchd plist files. `plist_name` will return `homebrew.mxcl.<formula>`, and `plist_path` will return, for example, `/usr/local/Cellar/foo/0.1/homebrew.mxcl.foo.plist`. ## Updating formulae Eventually a new version of the software will be released. In this case you should update the `url` and `sha256`. Please leave the `bottle do ... end` block as-is; our CI system will update it when we pull your change. Check if the formula you are updating is a dependency for any other formulae by running `brew uses UPDATED_FORMULA`. If it is a dependency please `brew reinstall` all the dependencies after it is installed and verify they work correctly. # Style guide Homebrew wants to maintain a consistent Ruby style across all formulae based on [Ruby Style Guide](https://github.com/styleguide/ruby). Other formulae may not have been updated to match this guide yet but all new ones should. Also: * The order of methods in a formula should be consistent with other formulae (e.g.: `def patches` goes before `def install`) * An empty line is required before the `__END__` line # Troubleshooting for people writing new formulae ### Version detection fails Homebrew tries to automatically determine the version from the URL in order to save on duplication. If the tarball has a funny name though, you may have to assign the version number: ```ruby class Foobar version "0.7" end ``` ## Bad Makefiles Not all projects have makefiles that will run in parallel so try to deparallelize: brew edit foo Add all this to the formula (so there will already be a class line, don’t add another or change that, and there’s already an install function, don't add another one, add the lines in the install function below to the top of the problem formula’s install function). ```ruby class Foo < Formula skip_clean :all def install ENV.deparallelize ENV.no_optimization system "make" # separate make and make install steps system "make", "install" end end ``` If that fixes it, please open an [issue](https://github.com/Homebrew/homebrew/issues) so that we can fix it for everyone. ## Still won’t work? Check out what MacPorts and Fink do: `brew -S --macports foo` `brew -S --fink foo` # Superenv Notes `superenv` is a "super" environment that tries to improve reliability for the general case. But it does make making formula harder. To not use `superenv`, install with `--env=std`. Superenv isolates builds by removing `/usr/local/bin` and all user-PATHs that are not determined to be essential to the build. It does this because other PATHs are full of stuff that breaks builds. (We have 15,000 tickets as testament!) `superenv` tries to remove bad-flags from the commands passed to `clang`/`gcc` and injects others (for example all `keg_only` dependencies are added to the `-I` and `-L` flags. If superenv troubles you, try to `brew install --env=std` and report to us if that fixes it. # Fortran Some software requires a Fortran compiler. This can be declared by adding `depends_on :fortran` to a formula. `:fortran` is a special dependency that does several things. First, it looks to see if you have set the `FC` environment variable. If it is set, Homebrew will use this value during compilation. If it is not set, it will check to see if `gfortran` is found in `PATH`. If it is, Homebrew will use its location as the value of `FC`. Otherwise, the `gcc` formula will be treated as a dependency and installed prior to compilation. If you have set `FC` to a custom Fortran compiler, you may additionally set `FCFLAGS` and `FFLAGS`. Alternatively, you can pass `--default-fortran-flags` to `brew install` to use Homebrew's standard `CFLAGS`. When using Homebrew's own gfortran compiler, the standard `CFLAGS` are used and user-supplied values of `FCFLAGS` and `FFLAGS` are ignored for consistency and reproducibility reasons. # How to start over (reset to `master`)? Have you created a real mess in git which paralyzes you to create the commit you just want to push? Then you might consider start from scratch. Your changes will be discarded in favour of the `master` branch: `git checkout master` `git reset --hard FETCH_HEAD`
{'content_hash': '8d53a5d3ee66b814a3acde6349ddb05c', 'timestamp': '', 'source': 'github', 'line_count': 987, 'max_line_length': 476, 'avg_line_length': 41.4822695035461, 'alnum_prop': 0.7218816403292382, 'repo_name': 'tylerball/homebrew', 'id': 'ca05738ca5b42bfeaae355e1ddbf5fd7b6a3e0b1', 'size': '41092', 'binary': False, 'copies': '5', 'ref': 'refs/heads/master', 'path': 'share/doc/homebrew/Formula-Cookbook.md', 'mode': '33188', 'license': 'bsd-2-clause', 'language': [{'name': 'C++', 'bytes': '5889'}, {'name': 'Groff', 'bytes': '26137'}, {'name': 'JavaScript', 'bytes': '18'}, {'name': 'Perl', 'bytes': '547'}, {'name': 'PostScript', 'bytes': '485'}, {'name': 'Ruby', 'bytes': '4617578'}, {'name': 'Shell', 'bytes': '19080'}]}
package gr.demokritos.iit.ydsapi.model; import com.google.gson.Gson; import com.google.gson.GsonBuilder; import com.google.gson.JsonArray; import com.google.gson.JsonDeserializationContext; import com.google.gson.JsonDeserializer; import com.google.gson.JsonElement; import com.google.gson.JsonObject; import com.google.gson.JsonParseException; import com.google.gson.JsonSerializationContext; import com.google.gson.JsonSerializer; import java.lang.reflect.Type; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.LinkedHashSet; import java.util.List; import java.util.Objects; import java.util.Set; import org.bson.types.ObjectId; /** * * @author George K. <[email protected]> */ public class BasketItem { private final String userID; private final String componentParentUUID; private final String title; private final ObjectId basketItemID; private final Set<String> tags; private final Set<BFilter> filters; private final String compType; private final String contentType; private final BasketType type; private final boolean priv; private final String lang; private BasketItem(Builder builder) { this.userID = builder.user_id; this.componentParentUUID = builder.component_parent_UUID; this.title = builder.title; this.basketItemID = builder.basket_item_id; this.tags = builder.tags; this.filters = builder.filters; this.compType = builder.component_type; this.contentType = builder.content_type; this.type = builder.type; this.priv = builder.isPrivate; this.lang = builder.lang; } /** * obtain json request, utilizes {@link Builder} for safety * * @param jsonBasketItem */ public BasketItem(String jsonBasketItem) { BasketItem bi = new GsonBuilder() .registerTypeAdapter(BasketItem.class, new BasketItemDeserializer()) .create() .fromJson(jsonBasketItem, getClass()); this.userID = bi.userID; this.componentParentUUID = bi.componentParentUUID; this.title = bi.title; this.basketItemID = bi.basketItemID; this.tags = bi.tags; this.filters = bi.filters; this.compType = bi.compType; this.contentType = bi.contentType; this.type = bi.type; this.priv = bi.priv; this.lang = bi.lang; } public String getUserID() { return userID; } public String getComponentParentUUID() { return componentParentUUID; } public String getTitle() { return title; } public ObjectId getBasketItemID() { return basketItemID; } public Set<String> getTags() { return tags; } public Set<BFilter> getFilters() { return filters; } public String getComponentType() { return compType; } public String getContentType() { return contentType; } public BasketType getType() { return type; } public boolean isPrivate() { return priv; } public String getLang() { return lang; } @Override public String toString() { return "BasketItem{" + "user_id=" + userID + ", component_parent_UUID=" + componentParentUUID + ", title=" + title + ", basket_item_id=" + basketItemID + ", tags=" + tags + ", filters=" + filters + ", component_type=" + compType + ", content_type=" + contentType + ", type=" + type + ", priv=" + priv + ", lang=" + lang + '}'; } public String toJSON() { GsonBuilder gsonBuilder = new GsonBuilder(); gsonBuilder .registerTypeAdapter(BasketItem.class, new BasketItemSerializer()) .disableHtmlEscaping() .setPrettyPrinting(); Gson gson = gsonBuilder.create(); return gson.toJson(this); } public JsonElement toJSONElement() { GsonBuilder gsonBuilder = new GsonBuilder(); gsonBuilder .registerTypeAdapter(BasketItem.class, new BasketItemSerializer()) .disableHtmlEscaping() .setPrettyPrinting(); Gson gson = gsonBuilder.create(); return gson.toJsonTree(this); } /** * we want only these specific fields to uniquely identify a * {@link BasketItem} * * @return */ @Override public int hashCode() { int hash = 3; hash = 17 * hash + Objects.hashCode(this.componentParentUUID); hash = 17 * hash + Objects.hashCode(this.title); hash = 17 * hash + Objects.hashCode(this.compType); hash = 17 * hash + Objects.hashCode(this.contentType); hash = 17 * hash + Objects.hashCode(this.type); hash = 17 * hash + Objects.hashCode(this.lang); return hash; } @Override public boolean equals(Object obj) { if (obj == null) { return false; } if (getClass() != obj.getClass()) { return false; } final BasketItem other = (BasketItem) obj; if (!Objects.equals(this.componentParentUUID, other.componentParentUUID)) { return false; } if (!Objects.equals(this.title, other.title)) { return false; } if (!Objects.equals(this.compType, other.compType)) { return false; } if (!Objects.equals(this.contentType, other.contentType)) { return false; } if (this.type != other.type) { return false; } return Objects.equals(this.lang, other.lang); } /** * custom builder class for {@link BasketItem} */ public static class Builder { private final String user_id; private final String component_parent_UUID; private final String title; private ObjectId basket_item_id; private Set<String> tags; private Set<BFilter> filters; private String component_type; private String content_type; private BasketType type; private Boolean isPrivate;// private String lang; public Builder(String userIDArg, String compParentUUIDArg, String titleArg) { this.user_id = userIDArg; this.component_parent_UUID = compParentUUIDArg; this.title = titleArg; } /** * * @param lang * @return */ public Builder withLang(String lang) { this.lang = lang; return this; } /** * * @param tagsArg * @return */ public Builder withTags(Collection<String> tagsArg) { if (tagsArg == null) { this.tags = new LinkedHashSet(0); } else { this.tags = new LinkedHashSet(tagsArg); } return this; } /** * * @param filtersArg * @return */ public Builder withFilters(Collection<BFilter> filtersArg) { if (filtersArg == null) { this.filters = new LinkedHashSet(0); } else { this.filters = new LinkedHashSet(filtersArg); } return this; } /** * * @param compTarg * @return */ public Builder withComponentType(String compTarg) { String compTargLower = compTarg.toLowerCase(); if (!ComponentType.ACCEPTED.contains(compTargLower)) { throw new IllegalArgumentException(String.format("'%s' not accepted as a valid component type", compTarg)); } else { this.component_type = compTargLower; } return this; } /** * * @param contTarg * @return */ public Builder withContentType(String contTarg) { this.content_type = contTarg; return this; } /** * * @param id * @return */ public Builder withID(ObjectId id) { this.basket_item_id = id; return this; } /** * * @param typeArg * @return */ public Builder withType(BasketType typeArg) { this.type = typeArg; return this; } /** * * @param typeArg * @return */ public Builder withType(String typeArg) throws IllegalArgumentException { if (typeArg.equalsIgnoreCase(BasketType.DATASET.getDecl())) { this.type = BasketType.DATASET; } else if (typeArg.equalsIgnoreCase(BasketType.VISUALISATION.getDecl())) { this.type = BasketType.VISUALISATION; } else { throw new IllegalArgumentException("type must be one of " + Arrays.asList( new String[]{ BasketType.DATASET.getDecl(), BasketType.VISUALISATION.getDecl() } ).toString()); } return this; } /** * * @param isPrivateArg * @return */ public Builder withIsPrivate(boolean isPrivateArg) { this.isPrivate = isPrivateArg; return this; } public BasketItem build() { if (this.lang == null || this.lang.trim().isEmpty()) { this.lang = "en"; } // default is 'private' if (this.isPrivate == null) { this.isPrivate = Boolean.TRUE; } // mandatory fields if (this.type == null) { throw new IllegalArgumentException("declare basket type"); } if (this.content_type == null) { throw new IllegalArgumentException("declare content type"); } if (this.component_type == null) { throw new IllegalArgumentException("declare component type"); } return new BasketItem(this); } } /** * basket types: dataset/visualization, 'ALL' is used to override call */ public enum BasketType { DATASET("dataset"), VISUALISATION("visualisation"), ALL("all"); private final String type; private BasketType(String type) { this.type = type; } public String getDecl() { return type; } } public static final String FLD_USERID = "user_id"; public static final String FLD_BASKET_ITEM_ID = "basket_item_id"; public static final String FLD_OBJ_ID = "_id"; public static final String FLD_COMPONENT_PARENT_UUID = "component_parent_uuid"; public static final String FLD_TITLE = "title"; public static final String FLD_TAGS = "tags"; public static final String FLD_FILTERS = "filters"; public static final String FLD_COMPONENT_TYPE = "component_type"; public static final String FLD_CONTENT_TYPE = "content_type"; public static final String FLD_TYPE = "type"; public static final String FLD_IS_PRIVATE = "is_private"; public static final String FLD_LANG = "lang"; /** * Helper class to serialize as needed in the API */ class BasketItemSerializer implements JsonSerializer<BasketItem> { @Override public JsonElement serialize(BasketItem t, Type type, JsonSerializationContext jsc) { final JsonObject jsonObject = new JsonObject(); jsonObject.addProperty(BasketItem.FLD_USERID, t.getUserID()); if (t.getBasketItemID() != null) { jsonObject.addProperty(BasketItem.FLD_BASKET_ITEM_ID, t.getBasketItemID().toString()); } jsonObject.addProperty(BasketItem.FLD_COMPONENT_PARENT_UUID, t.getComponentParentUUID()); jsonObject.addProperty(BasketItem.FLD_TITLE, t.getTitle()); jsonObject.addProperty(BasketItem.FLD_COMPONENT_TYPE, t.getComponentType()); jsonObject.addProperty(BasketItem.FLD_CONTENT_TYPE, t.getContentType()); jsonObject.addProperty(BasketItem.FLD_TYPE, t.getType().getDecl()); jsonObject.addProperty(BasketItem.FLD_IS_PRIVATE, t.isPrivate()); jsonObject.addProperty(BasketItem.FLD_LANG, t.getLang()); final JsonElement jsonTags = jsc.serialize(t.getTags()); jsonObject.add(BasketItem.FLD_TAGS, jsonTags); // add filters final JsonArray jsonFilters = new JsonArray(); for (final BFilter filt : t.getFilters()) { final JsonElement jsonfil = filt.toJSONElement(); jsonFilters.add(jsonfil); } jsonObject.add(BasketItem.FLD_FILTERS, jsonFilters); return jsonObject; } } class BasketItemDeserializer implements JsonDeserializer<BasketItem> { @Override public BasketItem deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) throws JsonParseException { final JsonObject jsonObject = json.getAsJsonObject(); // initial final String user_id = jsonObject.get(BasketItem.FLD_USERID).getAsString(); final String component_parent_uuid = jsonObject.get(BasketItem.FLD_COMPONENT_PARENT_UUID).getAsString(); final String title = jsonObject.get(BasketItem.FLD_TITLE).getAsString(); // init builder object Builder b = new Builder(user_id, component_parent_uuid, title); // other JsonElement jsonbitemID = jsonObject.get(BasketItem.FLD_OBJ_ID); if (jsonbitemID != null) { ObjectId id = new ObjectId(jsonbitemID.getAsString()); b = b.withID(id); } // tags final JsonArray jsonTags = jsonObject.get(BasketItem.FLD_TAGS).getAsJsonArray(); final List<String> lTags = new ArrayList(jsonTags.size()); for (int i = 0; i < jsonTags.size(); i++) { final JsonElement jsonTag = jsonTags.get(i); lTags.add(jsonTag.getAsString()); } // add tags b = b.withTags(lTags); // filters final JsonArray jsonFilters = jsonObject.get(BasketItem.FLD_FILTERS).getAsJsonArray(); final List<BFilter> lFilters = new ArrayList(jsonFilters.size()); for (int i = 0; i < jsonFilters.size(); i++) { final JsonElement jsonFilt = jsonFilters.get(i); BFilter bf = new Gson().fromJson(jsonFilt, BFilter.class); lFilters.add(bf); } // add filters b = b.withFilters(lFilters); // add rest items final String component_type = jsonObject.get(BasketItem.FLD_COMPONENT_TYPE).getAsString(); final String content_type = jsonObject.get(BasketItem.FLD_CONTENT_TYPE).getAsString(); final String type = jsonObject.get(BasketItem.FLD_TYPE).getAsString(); final boolean isPrivate = jsonObject.get(BasketItem.FLD_IS_PRIVATE).getAsBoolean(); final String lang = jsonObject.get(BasketItem.FLD_LANG).getAsString(); b = b.withComponentType(component_type) .withContentType(content_type) .withType(type) .withIsPrivate(isPrivate) .withLang(lang); return b.build(); } } }
{'content_hash': 'ff8352d76a1d05d222bfa1cf7aa871a5', 'timestamp': '', 'source': 'github', 'line_count': 479, 'max_line_length': 133, 'avg_line_length': 33.292275574112736, 'alnum_prop': 0.5690098451119333, 'repo_name': 'YourDataStories/components-visualisation', 'id': 'd6b2924d122ec177734768bbab917638cd5222c2', 'size': '15947', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'BackendUtilities/src/main/java/gr/demokritos/iit/ydsapi/model/BasketItem.java', 'mode': '33188', 'license': 'apache-2.0', 'language': [{'name': 'CSS', 'bytes': '42030'}, {'name': 'HTML', 'bytes': '353801'}, {'name': 'Java', 'bytes': '164739'}, {'name': 'JavaScript', 'bytes': '881627'}]}
#!/usr/bin/env node var sys = require('sys') , fs = require('fs') , M = require('./Mustache') , compressor = require('node-minify'); var package = require('../package.json'); var code = ''; var docs = {}; docs.main = ''; docs.API = ''; docs.copyrightYear = new Date().getFullYear(); // read in the the main.js file as our main boilerplate code code += fs.readFileSync('./main.js', encoding = 'utf8'); code = M.Mustache.to_html(code, {'today': new Date().getTime(), 'version': package.version}); docs.main += fs.readFileSync('./docs.js', encoding = 'utf8'); // parse entire lib directory and concat it into one file for the browser var lib = paths('./lib'); var faker = require('../index'); // generate bundle for code on the browser for (var module in faker) { code += ( '\n' + 'faker.' + module + ' = {};'); for (var method in faker[module]) { code += ( '\n' + 'faker.' + module); code += ( '.' + method + ' = '); // serialize arrays as JSON, otherwise use simple string conversion var methodValue = faker[module][method]; if (Array.isArray(methodValue)) { code += JSON.stringify(methodValue) + ';\n'; } else { code += (methodValue.toString() + ';\n'); } } } // generate nice tree of api for docs docs.API += '<ul>'; for (var module in faker) { docs.API += '<li>' + module; docs.API += '<ul>'; for (var method in faker[module]) { docs.API += '<li>' + method + '</li>'; } docs.API += '</ul>'; docs.API += '</li>'; } docs.API += '</ul>'; // definitions hack code += 'var definitions = faker.definitions;\n'; code += 'var Helpers = faker.Helpers;\n'; // if we are running in a CommonJS env, export everything out code +=["\nif (typeof define == 'function'){", " define(function(){", " return faker;", " });", "}", "else if(typeof module !== 'undefined' && module.exports) {", " module.exports = faker;", "}", "else {", " window.faker = faker;", "}", "", "}()); // end faker closure"].join('\n'); // generate core library fs.writeFile('../faker.js', code, function() { sys.puts("faker.js generated successfully!"); }); // generate example js file as well fs.writeFile('../examples/js/faker.js', code, function() { sys.puts("faker.js generated successfully!"); }); var docOutput = M.Mustache.to_html(docs.main, {"API": docs.API, "copyrightYear": docs.copyrightYear}); // generate some samples sets (move this code to another section) fs.writeFile('../Readme.md', docOutput, function() { sys.puts("Docs generated successfully!"); }); // generates minified version Using Google Closure new compressor.minify({ type: 'gcc', fileIn: '../faker.js', fileOut: '../minfaker.js', callback: function(err){ if(err) { console.log(err); } else sys.puts("Minified version generated successfully!"); } }); /*********************** BUILD HELPER METHODS *********************/ // Recursively traverse a hierarchy, returning a list of all relevant .js files. function paths(dir) { var paths = []; try { fs.statSync(dir); } catch (e) { return e; } (function traverse(dir, stack) { stack.push(dir); fs.readdirSync(stack.join('/')).forEach(function(file) { var path = stack.concat([file]).join('/'), stat = fs.statSync(path); if (file[0] == '.' || file === 'vendor') { return; } else if (stat.isFile() && /\.js$/.test(file)) { paths.push(path); } else if (stat.isDirectory()) { paths.push(path); traverse(file, stack); } }); stack.pop(); })(dir || '.', []); return paths; }
{'content_hash': '76dc6e97bafea63b4e7ab27aa325fcb2', 'timestamp': '', 'source': 'github', 'line_count': 139, 'max_line_length': 102, 'avg_line_length': 25.280575539568346, 'alnum_prop': 0.601593625498008, 'repo_name': 'kentcdodds/kcd-angular', 'id': '08a408fea1ded05047142521e3df8106504dd89e', 'size': '3514', 'binary': False, 'copies': '4', 'ref': 'refs/heads/main', 'path': 'resources/bower_components/Faker/BUILD/BUILD.js', 'mode': '33261', 'license': 'mit', 'language': [{'name': 'CSS', 'bytes': '9738'}, {'name': 'HTML', 'bytes': '37638'}, {'name': 'JavaScript', 'bytes': '37691'}]}
class GroupList { public: GroupList(void); ~GroupList(void); GroupData *AddGroup(const char *name); void RemoveGroup(GroupData *data); bool HasGroup(const char *item); GroupData *FindGroup(const char *name); GroupItem *ItemForGroup(const char *name); GroupItem *ItemForGroup(GroupData *data); }; #endif
{'content_hash': '8e7fe41f8a29b2686eb7e0795e42f2fe', 'timestamp': '', 'source': 'github', 'line_count': 17, 'max_line_length': 43, 'avg_line_length': 18.529411764705884, 'alnum_prop': 0.7396825396825397, 'repo_name': 'HaikuArchives/MrPeeps', 'id': 'b439962109fd869b64676a5cf89d1db7822481ae', 'size': '402', 'binary': False, 'copies': '2', 'ref': 'refs/heads/master', 'path': 'src/GroupList.h', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'C', 'bytes': '9728'}, {'name': 'C++', 'bytes': '245568'}, {'name': 'Makefile', 'bytes': '5308'}]}
package org.cgfalcon.myprolang.antlr.graphics;// Generated from Graphics.g4 by ANTLR 4.1 import org.antlr.v4.runtime.misc.NotNull; import org.antlr.v4.runtime.tree.ParseTreeListener; /** * This interface defines a complete listener for a parse tree produced by * {@link GraphicsParser}. */ public interface GraphicsListener extends ParseTreeListener { /** * Enter a parse tree produced by {@link GraphicsParser#point}. * @param ctx the parse tree */ void enterPoint(@NotNull GraphicsParser.PointContext ctx); /** * Exit a parse tree produced by {@link GraphicsParser#point}. * @param ctx the parse tree */ void exitPoint(@NotNull GraphicsParser.PointContext ctx); /** * Enter a parse tree produced by {@link GraphicsParser#file}. * @param ctx the parse tree */ void enterFile(@NotNull GraphicsParser.FileContext ctx); /** * Exit a parse tree produced by {@link GraphicsParser#file}. * @param ctx the parse tree */ void exitFile(@NotNull GraphicsParser.FileContext ctx); /** * Enter a parse tree produced by {@link GraphicsParser#command}. * @param ctx the parse tree */ void enterCommand(@NotNull GraphicsParser.CommandContext ctx); /** * Exit a parse tree produced by {@link GraphicsParser#command}. * @param ctx the parse tree */ void exitCommand(@NotNull GraphicsParser.CommandContext ctx); }
{'content_hash': '87223a5ec1d56c43446b988da0d71696', 'timestamp': '', 'source': 'github', 'line_count': 42, 'max_line_length': 88, 'avg_line_length': 32.11904761904762, 'alnum_prop': 0.7346182357301705, 'repo_name': 'cgfalcon/myprolang', 'id': 'aafe2f0572f6db9325e9b005570456535f134cc4', 'size': '1349', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'src/main/java/org/cgfalcon/myprolang/antlr/graphics/GraphicsListener.java', 'mode': '33188', 'license': 'apache-2.0', 'language': [{'name': 'ANTLR', 'bytes': '385'}, {'name': 'Java', 'bytes': '30673'}]}
<# Suppress PSAvoidUsingConvertToSecureStringWithPlainText since SecureString objects are used for test passwords. #> [Diagnostics.CodeAnalysis.SuppressMessageAttribute('PSAvoidUsingConvertToSecureStringWithPlainText', '')] param () $testJobPrefix = 'MsiPackageTestJob' <# .SYNOPSIS Tests if the package with the given Id is installed. .PARAMETER ProductId The ID of the package to test for. #> function Test-PackageInstalledById { [OutputType([System.Boolean])] [CmdletBinding()] param ( [Parameter()] [System.String] $ProductId ) $uninstallRegistryKey = 'HKLM:\SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall' $uninstallRegistryKeyWow64 = 'HKLM:\SOFTWARE\Wow6432Node\Microsoft\Windows\CurrentVersion\Uninstall' $productEntry = $null if (-not [System.String]::IsNullOrEmpty($ProductId)) { $productEntryKeyLocation = Join-Path -Path $uninstallRegistryKey -ChildPath $ProductId $productEntry = Get-Item -Path $productEntryKeyLocation -ErrorAction 'SilentlyContinue' if ($null -eq $productEntry) { $productEntryKeyLocation = Join-Path -Path $uninstallRegistryKeyWow64 -ChildPath $ProductId $productEntry = Get-Item $productEntryKeyLocation -ErrorAction 'SilentlyContinue' } } return ($null -ne $productEntry) } <# .SYNOPSIS Starts a simple mock http or https file server. Server will stay on and continue to be able to receive requests until the client calls Stop-Server. The server returns the job object and an EventWaitHandle object that the client will need to dispose of (by calling Stop-Server) once it is done sending requests. .PARAMETER FilePath The path to the file to add on to the mock file server. Should be an MSI file. .PARAMETER LogPath The path to the log file to write output to. This is important for debugging since most of the work of this function is done within a separate process. Default value will be in PSScriptRoot. .PARAMETER Https Indicates whether the server should use Https. If True then the file server will use Https and listen on port 'https://localhost:HttpsPort'. Otherwise the file server will use Http and listen on port 'http://localhost:HttpPort' Default value is False (Http). .PARAMETER HttpPort Specifies the TCP port to register an Http based HttpListener on. .PARAMETER HttspPort Specifies the TCP port to register an Https based HttpListener on. #> function Start-Server { [OutputType([System.Collections.Hashtable])] [CmdletBinding()] param ( [Parameter(Mandatory = $true)] [ValidateNotNullOrEmpty()] [System.String] $FilePath, [Parameter()] [System.String] $LogPath = (Join-Path -Path $PSScriptRoot -ChildPath 'PackageTestLogFile.txt'), [Parameter()] [System.Boolean] $Https = $false, [Parameter(Mandatory = $true)] [ValidateScript({$_ -gt 0})] [System.UInt16] $HttpPort, [Parameter(Mandatory = $true)] [ValidateScript({$_ -gt 0})] [System.UInt16] $HttpsPort ) # Create an event object to let the client know when the server is ready to begin receiving requests. $fileServerStarted = New-Object -TypeName 'System.Threading.EventWaitHandle' -ArgumentList @($false, [System.Threading.EventResetMode]::ManualReset, 'HttpIntegrationTest.FileServerStarted') $null = $fileServerStarted.Reset() <# The server is run on a separate process so that it can receive requests while the tests continue to run. It takes in the same parameterss that are passed in to this function. All helper functions that the server uses have to be defined within the scope of this script. #> $server = { param ( [Parameter()] $FilePath, [Parameter()] $LogPath, [Parameter()] $Https, [Parameter()] $HttpPort, [Parameter()] $HttpsPort ) <# .SYNOPSIS Stops the listener, removes the SSL binding if applicable, and closes the listener. .PARAMETER HttpListener The listner to stop and close. .PARAMETER Https Indicates whether https was used and if so, removes the SSL binding. .PARAMETER HttspPort Specifies the TCP port to de-register an Https based HttpListener from. #> function Stop-Listener { [CmdletBinding()] param ( [Parameter(Mandatory = $true)] [System.Net.HttpListener] $HttpListener, [Parameter(Mandatory = $true)] [System.Boolean] $Https, [Parameter(Mandatory = $true)] [ValidateScript({$_ -gt 0})] [System.UInt16] $HttpsPort ) Write-Log -LogFile $LogPath -Message 'Finished listening for requests. Shutting down HTTP server.' $ipPort = "0.0.0.0:$HttpsPort" if ($null -eq $HttpListener) { $errorMessage = 'HttpListener was null when trying to close' Write-Log -LogFile $LogPath -Message $errorMessage if ($Https) { Invoke-ConsoleCommand -Target $ipPort -Action 'removing SSL certificate binding' -ScriptBlock { netsh http delete sslcert ipPort="$ipPort" } } throw $errorMessage } if ($HttpListener.IsListening) { Write-Log -LogFile $LogPath -Message 'HttpListener is about to be stopped' $HttpListener.Stop() } if ($Https) { Write-Log -LogFile $LogPath -Message 'Removing SSL binding' # Remove SSL Binding Invoke-ConsoleCommand -Target $ipPort -Action 'removing SSL certificate binding' -ScriptBlock { netsh http delete sslcert ipPort="$ipPort" } } Write-Log -LogFile $LogPath -Message 'Closing listener' $HttpListener.Close() $null = netsh advfirewall set allprofiles state on } <# .SYNOPSIS Creates and registers an SSL certificate for Https connections. .PARAMETER HttspPort Specifies the TCP port to register an Https based HttpListener on. #> function Register-Ssl { [CmdletBinding()] param ( [Parameter(Mandatory = $true)] [ValidateScript({$_ -gt 0})] [System.UInt16] $HttpsPort ) # Create certificate $certificate = New-SelfSignedCertificate -CertStoreLocation 'Cert:\LocalMachine\My' -DnsName localhost Write-Log -LogFile $LogPath -Message 'Created certificate' $hash = $certificate.Thumbprint $certPassword = ConvertTo-SecureString -String 'password12345' -AsPlainText -Force $tempPath = 'C:\certForTesting' $null = Export-PfxCertificate -Cert $certificate -FilePath $tempPath -Password $certPassword $null = Import-PfxCertificate -CertStoreLocation 'Cert:\LocalMachine\Root' -FilePath 'C:\certForTesting' -Password $certPassword Remove-Item -Path $tempPath Write-Log -LogFile $LogPath -Message 'Finished importing certificate into root. About to bind it to port.' # Use net shell command to directly bind certificate to designated testing port $null = netsh http add sslcert ipport=0.0.0.0:$HttpsPort certhash=$hash appid='{833f13c2-319a-4799-9d1a-5b267a0c3593}' clientcertnegotiation=enable } <# .SYNOPSIS Defines the callback function required for BeginGetContext. .PARAMETER Callback The callback script - in this case the requestListener script defined below. #> function New-ScriptBlockCallback { [CmdletBinding()] param ( [Parameter(Mandatory = $true)] [ValidateNotNullOrEmpty()] [System.Management.Automation.ScriptBlock] $Callback ) # Add the CallbackEventBridge type if it's not already defined if (-not ('CallbackEventBridge' -as [System.Type])) { Add-Type @' using System; public sealed class CallbackEventBridge { public event AsyncCallback CallbackComplete = delegate { }; private CallbackEventBridge() {} private void CallbackInternal(IAsyncResult result) { CallbackComplete(result); } public AsyncCallback Callback { get { return new AsyncCallback(CallbackInternal); } } public static CallbackEventBridge Create() { return new CallbackEventBridge(); } } '@ } $bridge = [CallbackEventBridge]::Create() Register-ObjectEvent -InputObject $bridge -EventName 'CallbackComplete' -Action $Callback -MessageData $args > $null $bridge.Callback Write-Log -LogFile $LogPath -Message 'Finished callback function' } <# .SYNOPSIS Invokes a console command and captures the exit code. .PARAMETER Target Where the command is being executed. .PARAMETER Action A description of the action being performed. .PARAMETER ScriptBlock The code to execute. #> function Invoke-ConsoleCommand { [CmdletBinding()] param ( [Parameter(Mandatory = $true)] [System.String] $Target, [Parameter(Mandatory = $true)] [System.String] $Action, [Parameter(Mandatory = $true)] [System.Management.Automation.ScriptBlock] $ScriptBlock ) $output = Invoke-Command -ScriptBlock $ScriptBlock if ($LASTEXITCODE) { $output = $output -join [Environment]::NewLine $message = ('Failed action ''{0}'' on target ''{1}'' (exit code {2}): {3}' -f $Action,$Target,$LASTEXITCODE,$output) Write-Error -Message $message Write-Log -LogFile $LogPath -Message "Error from Invoke-ConsoleCommand: $message" } else { $nonNullOutput = $output | Where-Object { $_ -ne $null } Write-Log -LogFile $LogPath -Message "Output from Invoke-ConsoleCommand: $nonNullOutput" } } <# .SYNOPSIS Writes the specified message to the specified log file. Does NOT overwrite what is already written there. .PARAMETER LogFile The path to the file to write to. .PARAMETER Message The message to write to the file. #> function Write-Log { [CmdletBinding()] param ( [Parameter(Mandatory = $true)] [System.String] $LogFile, [Parameter(Mandatory = $true)] [System.String] $Message ) $Message >> $LogFile } # End of function declarations - Beginning of function execution if ($null -eq (Get-NetFirewallRule -DisplayName 'UnitTestRule' -ErrorAction 'SilentlyContinue')) { $null = New-NetFirewallRule -DisplayName 'UnitTestRule' -Direction 'Inbound' -Program "$PSHome\powershell.exe" -Authentication 'NotRequired' -Action 'Allow' } $null = netsh advfirewall set allprofiles state off Write-Log -LogFile $LogPath -Message (Get-Date) $HttpListener = New-Object 'System.Net.HttpListener' $fileServerStarted = $null try { # Set up the listener if ($Https) { $HttpListener.Prefixes.Add([Uri] "https://localhost:$HttpsPort") try { Register-SSL -HttpsPort $HttpsPort } catch { $errorMessage = "Unable to bind SSL certificate to port. Error: $_" Write-Log -LogFile $LogPath -Message $errorMessage throw $errorMessage } Write-Log -LogFile $LogPath -Message 'Certificate is registered' } else { $HttpListener.Prefixes.Add([Uri] "http://localhost:$HttpPort") } Write-Log -LogFile $LogPath -Message 'Finished listener setup - about to start listener' $HttpListener.Start() # Cue the tests that the listener is started and can begin receiving requests $fileServerStarted = New-Object -TypeName 'System.Threading.EventWaitHandle' ` -ArgumentList @($false, [System.Threading.EventResetMode]::AutoReset, 'HttpIntegrationTest.FileServerStarted' ) $fileServerStarted.Set() Write-Log -LogFile $LogPath -Message 'Listener is started' <# .SYNOPSIS Script block called by the callback function for BeginGetContext. Ends the current BeginGetContext, copies the response, and calls BeginGetContext again to continue receiving requests. .PARAMETER Result th IAsyncResult containing the listener object and path to the MSI file. #> $requestListener = { [CmdletBinding()] param ( [Parameter()] [IAsyncResult] $Result ) Write-Log -LogFile $LogPath -Message 'Starting request listener' $asyncState = $Result.AsyncState [System.Net.HttpListener] $listener = $asyncState.Listener $filepath = $asyncState.FilePath Write-Log -LogFile $LogPath -Message (ConvertTo-Json $asyncState) # Call EndGetContext to complete the asynchronous operation. $context = $listener.EndGetContext($Result) $response = $null try { # Prepare binary buffer for http/https response $fileInfo = New-Object -TypeName 'System.IO.FileInfo' -ArgumentList @( $filePath ) $numBytes = $fileInfo.Length $fileStream = New-Object -TypeName 'System.IO.FileStream' -ArgumentList @( $filePath, 'Open' ) $binaryReader = New-Object -TypeName 'System.IO.BinaryReader' -ArgumentList @( $fileStream ) [System.Byte[]] $buf = $binaryReader.ReadBytes($numBytes) $fileStream.Close() Write-Log -LogFile $LogPath -Message 'Buffer prepared for response' $response = $context.Response $response.ContentType = 'application/octet-stream' $response.ContentLength64 = $buf.Length $response.OutputStream.Write($buf, 0, $buf.Length) Write-Log -LogFile $LogPath -Message 'Response written' $response.OutputStream.Flush() # Open the response stream again to receive more requests $listener.BeginGetContext((New-ScriptBlockCallback -Callback $requestListener), $asyncState) } catch { $errorMessage = "error writing response: $_" Write-Log -LogFile $LogPath -Message $errorMessage throw $errorMessage } finally { if ($null -ne $response) { $response.Dispose() } } } # Register the request listener scriptblock as the async callback $HttpListener.BeginGetContext((New-ScriptBlockCallback -Callback $requestListener), @{ Listener = $Httplistener FilePath = $FilePath }) | Out-Null Write-Log -LogFile $LogPath -Message 'First BeginGetContext called' # Ensure that the request listener stays on until the server is done receiving responses - client is responsible for stopping the server. while ($true) { Start-Sleep -Milliseconds 100 } } catch { $errorMessage = "There were problems setting up the HTTP(s) listener. Error: $_" Write-Log -LogFile $LogPath -Message $errorMessage 'Error Record Info' >> $LogPath $_ | ConvertTo-Xml -As String >> $LogPath 'Exception Info' >> $LogPath $_.Exception | ConvertTo-Xml -As String >> $LogPath 'Running Process Info' >> $LogPath Get-Process | Format-List | Out-String >> $LogPath 'Open TCP Connections Info' >> $LogPath Get-NetTCPConnection | Format-List | Out-String >> $LogPath throw $_ } finally { if ($fileServerStarted) { $fileServerStarted.Dispose() } Write-Log -LogFile $LogPath -Message 'Stopping the Server' Stop-Listener -HttpListener $HttpListener -Https $Https -HttpsPort $HttpsPort } } if ($Https) { $jobName = $testJobPrefix + 'Https' } else { $jobName = $testJobPrefix + 'Http' } $job = Start-Job -ScriptBlock $server -Name $jobName -ArgumentList @( $FilePath, $LogPath, $Https, $HttpPort, $HttpsPort ) # Verify that the job is receivable and does not contain an exception. If it does, re-throw it. try { $null = $job | Receive-Job } catch { Write-Error -Message 'Failed to setup HTTP(S) listener for MsiPackage Tests' throw $_ } <# Return the event object so that client knows when it can start sending requests and the job object so that the client can stop the job once it is done sending requests. #> return @{ FileServerStarted = $fileServerStarted Job = $job } } <# .SYNOPSIS Disposes the EventWaitHandle object and stops and removes the job to ensure that proper cleanup is done for the listener. If this function is not called after Start-Server then the listening port will remain open until the job is stopped or the machine is rebooted. .PARAMETER FileServerStarted The EventWaitHandle object returned by Start-Server to let the client know that it is ready to receive requests. The client is responsible for calling this function to ensure that this object is disposed of once the client is done sending requests. .PARAMETER Job The job object returned by Start-Server that needs to be stopped so that the server will close the listening port. #> function Stop-Server { [CmdletBinding()] param ( [Parameter()] [System.Threading.EventWaitHandle] $FileServerStarted, [Parameter()] [System.Management.Automation.Job] $Job ) if ($null -ne $FileServerStarted) { $FileServerStarted.Dispose() } if ($null -ne $Job) { Stop-Job -Job $Job Remove-Job -Job $Job } } <# .SYNOPSIS Removes any jobs associated with HTTP(S) servers that were created for MsiPackage tests. #> function Stop-EveryTestServerInstance { [CmdletBinding()] param () Get-Job -Name "$($testJobPrefix)*" | Stop-Job Get-Job -Name "$($testJobPrefix)*" | Remove-Job } <# .SYNOPSIS Creates a new MSI package for testing. .PARAMETER DestinationPath The path at which to create the test msi file. #> function New-TestMsi { [CmdletBinding()] param ( [Parameter(Mandatory = $true)] [ValidateNotNullOrEmpty()] [System.String] $DestinationPath ) #region msiContentInBase64 $msiContentInBase64 = '0M8R4KGxGuEAAAAAAAAAAAAAAAAAAAAAPgAEAP7/DAAGAAAAAAAAAAEAAAABAAAAAQA' + ` 'AAAAAAAAAEAAAAgAAAAEAAAD+////AAAAAAAAAAD/////////////////////////////////////////////' + ` '/////////////////////////////////////////////////////////////////////////////////////' + ` '/////////////////////////////////////////////////////////////////////////////////////' + ` '/////////////////////////////////////////////////////////////////////////////////////' + ` '/////////////////////////////////////////////////////////////////////////////////////' + ` '/////////////////////////////////////////////////////////////////////////////////////' + ` '/////////////////////////////////////////////////////////////////////////////////////' + ` '////////////////////8AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA' + ` 'AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA' + ` 'AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA' + ` 'AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA' + ` 'AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA' + ` 'AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA' + ` 'AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA' + ` 'AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA' + ` 'AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA' + ` 'AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA' + ` 'AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA' + ` 'AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA' + ` 'AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA' + ` 'AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA' + ` 'AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA' + ` 'AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA' + ` 'AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA' + ` 'AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA' + ` 'AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA' + ` 'AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA' + ` 'AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA' + ` 'AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA' + ` 'AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA' + ` 'AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA' + ` 'AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA' + ` 'AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA' + ` 'AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA' + ` 'AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA' + ` 'AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA' + ` 'AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA' + ` 'AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA' + ` 'AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA' + ` 'AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA' + ` 'AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA' + ` 'AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA' + ` 'AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA' + ` 'AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA' + ` 'AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA' + ` 'AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA' + ` 'AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA' + ` 'AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA' + ` 'AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA' + ` 'AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA' + ` 'AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA' + ` 'AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA' + ` 'AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA' + ` 'AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA' + ` 'AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA' + ` 'AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA' + ` 'AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA' + ` 'AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA' + ` 'AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA' + ` 'AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA' + ` 'AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA' + ` 'AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA' + ` 'AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA' + ` 'AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAP3////+/////v///wYAAAD+////BAAAAP7////////////' + ` '/////////////////////////////////////////////////////////////////////////////////////' + ` '/////////////////////////////////////////////////////////////////////////////////////' + ` '/////////////////////////////////////////////////////////////////////////////////////' + ` '/////////////////////////////////////////////////////////////////////////////////////' + ` '/////////////////////////////////////////////////////////////////////////////////////' + ` '/////////////////////////////////////////////////////////////////////////////////////' + ` '/////////////////////////////////////////////////////////////////////////////////////' + ` '/////////////////////////////////////////////////////////////////////////////////////' + ` '/////////////////////////////////////////////////////////////////////////////////////' + ` '/////////////////////////////////////////////////////////////////////////////////////' + ` '/////////////////////////////////////////////////////////////////////////////////////' + ` '/////////////////////////////////////////////////////////////////////////////////////' + ` '/////////////////////////////////////////////////////////////////////////////////////' + ` '/////////////////////////////////////////////////////////////////////////////////////' + ` '/////////////////////////////////////////////////////////////////////////////////////' + ` '/////////////////////////////////////////////////////////////////////////////////////' + ` '/////////////////////////////////////////////////////////////////////////////////////' + ` '/////////////////////////////////////////////////////////////////////////////////////' + ` '/////////////////////////////////////////////////////////////////////////////////////' + ` '/////////////////////////////////////////////////////////////////////////////////////' + ` '/////////////////////////////////////////////////////////////////////////////////////' + ` '/////////////////////////////////////////////////////////////////////////////////////' + ` '/////////////////////////////////////////////////////////////////////////////////////' + ` '/////////////////////////////////////////////////////////////////////////////////////' + ` '/////////////////////////////////////////////////////////////////////////////////////' + ` '/////////////////////////////////////////////////////////////////////////////////////' + ` '/////////////////////////////////////////////////////////////////////////////////////' + ` '/////////////////////////////////////////////////////////////////////////////////////' + ` '/////////////////////////////////////////////////////////////////////////////////////' + ` '/////////////////////////////////////////////////////////////////////////////////////' + ` '/////////////////////////////////////////////////////////////////////////////////////' + ` '/////////////////////////////////////////////////////////////////////////////////////' + ` '/////////////////////////////////////////////////////////////////////////////////////' + ` '/////////////////////////////////////////////////////////////////////////////////////' + ` '/////////////////////////////////////////////////////////////////////////////////////' + ` '/////////////////////////////////////////////////////////////////////////////////////' + ` '/////////////////////////////////////////////////////////////////////////////////////' + ` '/////////////////////////////////////////////////////////////////////////////////////' + ` '/////////////////////////////////////////////////////////////////////////////////////' + ` '/////////////////////////////////////////////////////////////////////////////////////' + ` '/////////////////////////////////////////////////////////////////////////////////////' + ` '/////////////////////////////////////////////////////////////////////////////////////' + ` '/////////////////////////////////////////////////////////////////////////////////////' + ` '/////////////////////////////////////////////////////////////////////////////////////' + ` '/////////////////////////////////////////////////////////////////////////////////////' + ` '/////////////////////////////////////////////////////////////////////////////////////' + ` '/////////////////////////////////////////////////////////////////////////////////////' + ` '/////////////////////////////////////////////////////////////////////////////////////' + ` '/////////////////////////////////////////////////////////////////////////////////////' + ` '/////////////////////////////////////////////////////////////////////////////////////' + ` '/////////////////////////////////////////////////////////////////////////////////////' + ` '/////////////////////////////////////////////////////////////////////////////////////' + ` '/////////////////////////////////////////////////////////////////////////////////////' + ` '/////////////////////////////////////////////////////////////////////////////////////' + ` '/////////////////////////////////////////////////////////////////////////////////////' + ` '/////////////////////////////////////////////////////////////////////////////////////' + ` '/////////////////////////////////////////////////////////////////////////////////////' + ` '/////////////////////////////////////////////////////////////////////////////////////' + ` '/////////////////////////////////////////////////////////////////////////////////////' + ` '/////////////////////////////////////////////////////////////////////////////////////' + ` '/////////////////////////////////////////////////////////////////////////////////////' + ` '/////////////////////////////////////////////////////////////////////////////////////' + ` '/////////////////////////////////////////////////////////////////////////////////////' + ` '////////////////////////////////////////////////////////////9SAG8AbwB0ACAARQBuAHQAcgB' + ` '5AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAFgAFAP//////////CQAAAIQQ' + ` 'DAAAAAAAwAAAAAAAAEYAAAAAAAAAAAAAAADwRqG1qh/OAQMAAAAAEwAAAAAAAAUAUwB1AG0AbQBhAHIAeQBJA' + ` 'G4AZgBvAHIAbQBhAHQAaQBvAG4AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAoAAIA////////////////AA' + ` 'AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAADwCAAAAAAAAQEj/P+RD7EHkRaxEMUgAAAA' + ` 'AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAABAAAgETAAAABAAAAP////8A' + ` 'AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAJAAAAOAcAAAAAAABASMpBMEOxOztCJkY3QhxCN' + ` 'EZoRCZCAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAGAACAQsAAAAKAAAA/////w' + ` 'AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAACYAAAAwAAAAAAAAAEBIykEwQ7E/Ej8oRThCsUE' + ` 'oSAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAUAAIBDAAAAP//////////' + ` 'AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAJwAAABgAAAAAAAAAQEjKQflFzkaoQfhFKD8oR' + ` 'ThCsUEoSAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAABgAAgD///////////////' + ` '8AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAoAAAAKgAAAAAAAABASIxE8ERyRGhEN0gAAAA' + ` 'AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAADgACAP//////////////' + ` '/wAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAACkAAAAMAAAAAAAAAEBIDUM1QuZFckU8SAAAA' + ` 'AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAOAAIADgAAAAIAAAD///' + ` '//AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAKgAAABIAAAAAAAAAQEgPQuRFeEUoSAAAAAA' + ` 'AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAwAAgD/////////////' + ` '//8AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAArAAAAEAAAAAAAAABASA9C5EV4RSg7MkSzR' + ` 'DFC8UU2SAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAFgACAQcAAAADAAAA//' + ` '///wAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAACwAAAAEAAAAAAAAAEBIUkT2ReRDrzs7QiZ' + ` 'GN0IcQjRGaEQmQgAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAaAAIBBQAAAAEAAAD/' + ` '////AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAALQAAAHIAAAAAAAAAQEhSRPZF5EOvPxI/K' + ` 'EU4QrFBKEgAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAABYAAgH///////////' + ` '////8AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAvAAAAMAAAAAAAAABASBVBeETmQoxE8UH' + ` 'sRaxEMUgAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAFAACAP//////////' + ` '/////wAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAADAAAAAEAAAAAAAAAEBIWUXyRGhFN0cAA' + ` 'AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAMAAIBDwAAAP////' + ` '//////AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAMQAAACQAAAAAAAAAQEgbQipD9kU1RwA' + ` 'AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAwAAgEQAAAADQAA' + ` 'AP////8AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAyAAAADAAAAAAAAABASN5EakXkQShIA' + ` 'AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAADAACAP////////' + ` '///////wAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAADMAAAAgAAAAAAAAAEBIfz9kQS9CNkg' + ` 'AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAMAAIBEQAAAAgA' + ` 'AAD/////AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAANAAAACAAAAAAAAAAQEg/O/JDOESxR' + ` 'QAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAwAAgD///////' + ` '////////8AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA1AAAAWAIAAAAAAABASD8/d0VsRGo' + ` '+skQvSAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAEAACAP//////' + ` '/////////wAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAD8AAAAYAwAAAAAAAEBIPz93RWxEa' + ` 'jvkRSRIAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAQAAIBBgAAAB' + ` 'IAAAD/////AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAABQAAAFAaAAAAAAAAAAAAAAAAAAA' + ` 'AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAD/////' + ` '//////////8AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA' + ` 'AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAP////' + ` '///////////wAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA' + ` 'AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA////' + ` '////////////AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA' + ` 'AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAD///' + ` '////////////8AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA' + ` 'AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAP//' + ` '/////////////wAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA' + ` 'AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA//' + ` '//////////////AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA' + ` 'AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAD/' + ` '//////////////8AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA' + ` 'AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAP' + ` '///////////////wAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA' + ` 'AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA' + ` '////////////////AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA' + ` 'AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA' + ` 'D///////////////8AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA' + ` 'AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA' + ` 'AP///////////////wAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA' + ` 'AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA' + ` 'AA////////////////AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAQA' + ` 'AAAIAAAADAAAABAAAAAUAAAAGAAAABwAAAAgAAAD+////CgAAAAsAAAAMAAAADQAAAA4AAAAPAAAAEAAAABEA' + ` 'AAASAAAAEwAAABQAAAAVAAAAFgAAABcAAAAYAAAAGQAAABoAAAAbAAAAHAAAAB0AAAAeAAAAHwAAACAAAAAhA' + ` 'AAAIgAAACMAAAAkAAAAJQAAAP7////+/////v////7////+/////v////7////+////LgAAAP7////+/////v' + ` '////7////+/////v////7///82AAAANwAAADgAAAA5AAAAOgAAADsAAAA8AAAAPQAAAD4AAAD+////QAAAAEE' + ` 'AAABCAAAAQwAAAEQAAABFAAAARgAAAEcAAABIAAAASQAAAEoAAABLAAAA/v//////////////////////////' + ` '/////////////////////////////////////////////////////////////////////////////////////' + ` '/////////////////////////////////////////////////////////////////////////////////////' + ` '/////////////////////////////////////////////////////////////////////////////////////' + ` '/////////////////////////////////////////////////////////////////////////////////////' + ` '/////////////////////////////////////////////////////////////////////////////////////' + ` '/////////////////////////////////////////////////////////////////////////////////////' + ` '/////////////////////////////////////////////////////////////////////////////////////' + ` '/////////////////////////////////////////////////////////////////////////////////////' + ` '/////////////////////////////////////////////////////////////////////////////////////' + ` '/////////////////////////////////////////////////////////////////////////////////////' + ` '/////////////////////////////////////////////////////////////////////////////////////' + ` '/////////////////////////////////////////////////////////////////////////////////////' + ` '/////////////////////////////////////////////////////////////////////////////////////' + ` '/////////////////////////////////////////////////////////////////////////////////////' + ` '/////////////////////////////////////////////////////////////////////////////////////' + ` '/////////////////////////////////////////////////////////////////////////////////////' + ` '/////////////////////////////////////////////////////////////////////////////////////' + ` '/////////////////////////////////////////////////////////////////////////////////////' + ` '/////////////////////////////////////////////////////////////////////////////////////' + ` '/////////////////////////////////////////////////////////////////////////////////////' + ` '/////////////////////////////////////////////////////////////////////////////////////' + ` '/////////////////////////////////////////////////////////////////////////////////////' + ` '/////////////////////////////////////////////////////////////////////////////////////' + ` '/////////////////////////////////////////////////////////////////////////////////////' + ` '/////////////////////////////////////////////////////////////////////////////////////' + ` '/////////////////////////////////////////////////////////////////////////////////////' + ` '/////////////////////////////////////////////////////////////////////////////////////' + ` '/////////////////////////////////////////////////////////////////////////////////////' + ` '/////////////////////////////////////////////////////////////////////////////////////' + ` '/////////////////////////////////////////////////////////////////////////////////////' + ` '/////////////////////////////////////////////////////////////////////////////////////' + ` '/////////////////////////////////////////////////////////////////////////////////////' + ` '/////////////////////////////////////////////////////////////////////////////////////' + ` '/////////////////////////////////////////////////////////////////////////////////////' + ` '/////////////////////////////////////////////////////////////////////////////////////' + ` '/////////////////////////////////////////////////////////////////////////////////////' + ` '/////////////////////////////////////////////////////////////////////////////////////' + ` '/////////////////////////////////////////////////////////////////////////////////////' + ` '/////////////////////////////////////////////////////////////////////////////////////' + ` '/////////////////////////////////////////////////////////////////////////////////////' + ` '/////////////////////////////////////////////////////////////////////////////////////' + ` '/////////////////////////////////////////////////////////////////////////////////////' + ` '/////////////////////////////////////////////////////////////////////////////////////' + ` '/////////////////////////////////////////////////////////////////////////////////////' + ` '/////////////////////////////////////////////////////////////////////////////////////' + ` '/////////////////////////////////////////////////////////////////////////////////////' + ` '/////////////////////////////////////////////////////////////////////////////////////' + ` '/////////////////////////////////////////////////////////////////////////////////////' + ` '/////////////////////////////////////////////////////////////////////////////////////' + ` '/////////////////////////////////////////////////////////////////////////////////////' + ` '/////////////////////////////////////////////////////////////////////////////////////' + ` '/////////////////////////////////////////////////////////////////////////////////////' + ` '/////////////////////////////////////////////////////////////////////////////////////' + ` '/////////////////////////////////////////////////////////////////////////////////////' + ` '/////////////////////////////////////////////////////////////////////////////////////' + ` '/////////////////////////////////////////////////////////////////////////////////////' + ` '/////////////////////////////////////////////////////////////////////////////////////' + ` '/////////////////////////////////////////////////////////////////////////////////////' + ` '/////////////////////////////////////////////////////////////////////////////////////' + ` '///////////////////7/AAAGAQIAAAAAAAAAAAAAAAAAAAAAAAEAAADghZ/y+U9oEKuRCAArJ7PZMAAAAAwC' + ` 'AAAOAAAAAQAAAHgAAAACAAAAgAAAAAMAAACgAAAABAAAAMQAAAAFAAAA9AAAAAYAAAAIAQAABwAAAGwBAAAJA' + ` 'AAAgAEAAAwAAACwAQAADQAAALwBAAAOAAAAyAEAAA8AAADQAQAAEgAAANgBAAATAAAABAIAAAIAAADkBAAAHg' + ` 'AAABYAAABJbnN0YWxsYXRpb24gRGF0YWJhc2UAAAAeAAAAGwAAAEEgcGFja2FnZSBmb3IgdW5pdCB0ZXN0aW5' + ` 'nAAAeAAAAKAAAAE1pY3Jvc29mdCBVbml0IFRlc3RpbmcgR3VpbGQgb2YgQW1lcmljYQAeAAAACgAAAEluc3Rh' + ` 'bGxlcgAAAB4AAABcAAAAVGhpcyBpbnN0YWxsZXIgZGF0YWJhc2UgY29udGFpbnMgdGhlIGxvZ2ljIGFuZCBkY' + ` 'XRhIHJlcXVpcmVkIHRvIGluc3RhbGwgRFNDVW5pdFRlc3RQYWNrYWdlLgAeAAAACwAAAEludGVsOzEwMzMAAB' + ` '4AAAAnAAAAe0YxN0FGREExLUREMEItNDRFNi1CNDczLTlFQkUyREJEOUVBOX0AAEAAAAAAAOO0qh/OAUAAAAA' + ` 'AAOO0qh/OAQMAAADIAAAAAwAAAAIAAAAeAAAAIwAAAFdpbmRvd3MgSW5zdGFsbGVyIFhNTCAoMy43LjEyMDQu' + ` 'MCkAAAMAAAACAAAAAAAAAAYABgAGAAYABgAGAAYABgAGAAYACgAKACIAIgAiACkAKQApACoAKgAqACsAKwArA' + ` 'CsAKwArADEAMQAxAD4APgA+AD4APgA+AD4APgBNAE0AUgBSAFIAUgBSAFIAUgBSAGAAYABgAGEAYQBhAGIAYg' + ` 'BmAGYAZgBmAGYAZgByAHIAdgB2AHYAdgB2AHYAgACAAIAAgACAAIAAgAACAAUACwAMAA0ADgAPABAAEQASAAc' + ` 'ACQAjACUAJwAjACUAJwAjACUAJwAlACsALQAwADMANgAxADoAPAALADAAMwA+AEAAQgBFAEcATgBQACcAMwBQ' + ` 'AFIAVQBYAFoAXAAjACUAJwAjACUAJwALACUAZwBpAGsAbQBvAHEABwByAAEABwBQAHYAeAB6ADMAXACBAIMAh' + ` 'QCJAIsACAAIABgAGAAYABgAGAAIABgAGAAIAAgACAAYABgACAAYABgACAAYABgAGAAIABgACAAIABgACAAYAA' + ` 'gAGAAYAAgACAAYABgAGAAIAAgACAAIABgACAAIAAgACAAYABgACAAYABgACAAYABgACAAIAAgACAAYABgAGAA' + ` 'YAAgACAAYABgACAAIAAgACAAIABgACAAYABgAGAAIAAAAAAAAAAAAAAAAAAAAAAAAAAAAAQAAgAEAAAAAAAAA' + ` 'AAAAAAEAAAAAAAAAAAAAAAAAAAAAAAAA/P//fwAAAAAAAAAA/P//fwAAAAAAAAAA/P//fwAAAAAAAAAAAAAAA' + ` 'AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAIAAAACAAAAAAAAAAA' + ` 'ABAACAAAAAgAAAAAAAAAAAAAAAAAAAAIAAAAAAAAAAAAAAAAAAAAAA/P//fwAAAAAAAAAA/P//fwAAAAAAAAA' + ` 'AAQAAgAAAAIAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA////fwAAAAAAAACAAAAA' + ` 'AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAgAACA/////wAAAAAAAAAA/////wAAA' + ` 'AAAAAAAAAAAAAAAAAD/fwCAAAAAAAAAAAD/fwCAAAAAAAAAAAD/fwCAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA' + ` 'AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA/38AgP9/AIAAAAAAAAAAAP//////fwCAAAA' + ` 'AAAAAAAAAAAAA/////wAAAAAAAAAAAAAAAAAAAAD/fwCAAAAAAAAAAAD/fwCAAAAAAAAAAAD/fwCA/////wAA' + ` 'AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAADAACAAAAAAP////8AAAAAAAAAAAAAAAAAA' + ` 'AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAxAAAANw' + ` 'AAADEAAAAAADEAAAAAAD4AAAAAAAAAPgArAAAAAAArAAAAAAAAAFIAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA' + ` 'AAAAAAAAAAAAAAAAAAAArAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA' + ` 'AAAAAAAAAAAAAAAAAAAAAAAAAAAAAYAAAAGAAAABgAAAAAABgAAAAAABgAAAAAAAAAGAAYAAAAAAAYAAAAAAA' + ` 'AABgAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAYAAAAAAAAAAAAAAAAAAAAAAAAAAAB' + ` 'MAEwAfAB8AAAAAAAAAAAATAAAAAAAAABMAJQAAABMAJQAAABMAJQAAACUAEwAuABMAAAATABMAEwA8AB8ASQA' + ` 'AABMAEwAfAAAAAAATABMAAAAAABMAEwBWAAAAWgBcABMAJQAAABMAJQAAAGQAJQAAAAAAHwBtAB8AcgAfABMA' + ` 'ZABkABMAEwAAAHsAAABcAC4AHwAfAGQASQAAAAAAAAAAAB0AAAAAABYAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA' + ` 'AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAASwAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA' + ` 'AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAFAAVACEAIAAeABw' + ` 'AGgAXABsAGQAAAAAAJAAmACgAJAAmACgAJAAmACgANQAsAC8AMgA0ADgAOQA7AD0ARABKAEwAPwBBAEMARgBI' + ` 'AE8AUQBfAF4AVABTAFcAWQBbAF0AJAAmACgAJAAmACgAZQBjAGgAagBsAG4AcABzAHUAdAB9AH4AfwB3AHkAf' + ` 'ACIAIcAggCEAIYAigCMAAAAAAAAAAAAjQCOAI8AkACRAJIAkwCUAAAAAAAAAAAAAAAAAAAAAAAgg4SD6IN4hd' + ` 'yFPI+gj8iZAAAAAAAAAAAAAAAAAAAAAI0AjgCPAJUAAAAAAAAAAAAgg4SD6IMUhQAAAAAAAAAAAAAAAAAAAAA' + ` 'AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAACNAI8AkACRAJQAlgCXAAAAAAAAAAAAAAAAAAAAIIPog3iF3IXImZyY' + ` 'AJkAAAAAAAAAAAAAAAAAAAAAAAAAAAAAmACZAJoABIAAAJsAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA' + ` 'AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAJoAnACeAJwAngAAAJ0AnwCgAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA' + ` 'AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAChAAAAogAAAAKAAYAAAACAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA' + ` 'AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAoQCYAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA' + ` 'AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAI0AjgCPAJAAkQCUAJYAlwCjAKQApQCmAKcAqACpAKoAqwCsAK0AA' + ` 'AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAgg4SD6IN4hdyFyJmcmACZGYBkgLyCsIRAhg' + ` 'iHKIqIk3CX1Jd5hQAAAAAAAAAAAAAAAAAAjQCOAI8AlQCjAKQApQCmAAAAAAAAAAAAAAAAAAAAAAAgg4SD6IM' + ` 'UhRmAZIC8grCEAAAAAAAAAAAAAAAAAAAAAK4ArwAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA' + ` 'AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAACBALAAsgC0ALYAuAC6AL0AvwC8ALEAswC1ALcAuQC7AL4AwAAAA' + ` 'AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAmwACgMEAwgDDAJgAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA' + ` 'AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAALwAvAAAALsAuwAAAAAAAAABAACAAgAAgAAAAADEAMUAAAAAAAA' + ` 'AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAGACIAKQAqACsAMQA+AE0AUgBgAGEAYgBmAHIAdgCAAAAAAAAA' + ` 'AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAABgAGAAYABgAGAAYABgAGAAYABgAiACIAIgApACkAKQAqACoAK' + ` 'gArACsAKwArACsAKwAxADEAMQA+AD4APgA+AD4APgA+AD4ATQBNAFIAUgBSAFIAUgBSAFIAUgBgAGAAYABhAG' + ` 'EAYQBiAGIAZgBmAGYAZgBmAGYAcgByAHYAdgB2AHYAdgB2AIAAgACAAIAAgACAAIAAAYACgAOABIAFgAaAB4A' + ` 'IgAmACoABgAKAA4ABgAKAA4ABgAKAA4ABgAKAA4AEgAWABoABgAKAA4ABgAKAA4AEgAWABoAHgAiAAYACgAGA' + ` 'AoADgASABYAGgAeACIABgAKAA4ABgAKAA4ABgAKAAYACgAOABIAFgAaAAYACgAGAAoADgASABYAGgAGAAoADg' + ` 'ASABYAGgAeAAgAFABAAEgAPABEADgANAAwACwAjACUAJwAjACUAJwAjACUAJwArAC0AMAAzACUANgAxADoAPA' + ` 'A+AEAAQgALAEUARwAwADMATgBQAFIAUABVAFgAWgBcADMAJwAjACUAJwAjACUAJwAlAAsAZwBpAGsAbQBvAHE' + ` 'AcgAHAHYAeAB6AAEABwBQAIEAgwCFAFwAMwCJAIsAIK0grQSNBJEEkf+dApUgnf+d/51Irf+dApVIrf+dApVI' + ` 'rf+dApVIrSadSI0Chf+dSJ1IrUid/48mrSadQJ//nwKVAoVInQKFJq1IrUitSI3/jwSBSJ0UnQKVBIFIrf+dA' + ` 'pVIrf+dApX/rf+PAqUEgUCf/50gnUidSK0Aj0itAoX/j/+fAJ9IjSatFL0Uvf+9BKH/nUiNAAAAAAAAAAAAAA' + ` 'AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAEAAIABQACAAAAAAAAAAAABgACAAsAFQAFAAUAAQA' + ` 'mAAoAAQATAAIACwAGAAMAAgAIAAIACQACAAgAAgBudGVnZXIgdG8gZGV0ZXJtaW5lIHNvcnQgb3JkZXIgZm9y' + ` 'IHRhYmxlLkxhc3RTZXF1ZW5jZUZpbGUgc2VxdWVuY2UgbnVtYmVyIGZvciB0aGUgbGFzdCBmaWxlIGZvciB0a' + ` 'GlzIG1lZGlhLkRpc2tQcm9tcHREaXNrIG5hbWU6IHRoZSB2aXNpYmxlIHRleHQgYWN0dWFsbHkgcHJpbnRlZC' + ` 'BvbiB0aGUgZGlzay4gIFRoaXMgd2lsbCBiZSB1c2VkIHRvIHByb21wdCB0aGUgdXNlciB3aGVuIHRoaXMgZGl' + ` 'zayBuZWVkcyB0byBiZSBpbnNlcnRlZC5DYWJpbmV0SWYgc29tZSBvciBhbGwgb2YgdGhlIGZpbGVzIHN0b3Jl' + ` 'ZCBvbiB0aGUgbWVkaWEgYXJlIGNvbXByZXNzZWQgaW4gYSBjYWJpbmV0LCB0aGUgbmFtZSBvZiB0aGF0IGNhY' + ` 'mluZXQuVm9sdW1lTGFiZWxUaGUgbGFiZWwgYXR0cmlidXRlZCB0byB0aGUgdm9sdW1lLlNvdXJjZVByb3Blcn' + ` 'R5VGhlIHByb3BlcnR5IGRlZmluaW5nIHRoZSBsb2NhdGlvbiBvZiB0aGUgY2FiaW5ldCBmaWxlLk5hbWUgb2Y' + ` 'gcHJvcGVydHksIHVwcGVyY2FzZSBpZiBzZXR0YWJsZSBieSBsYXVuY2hlciBvciBsb2FkZXIuU3RyaW5nIHZh' + ` 'bHVlIGZvciBwcm9wZXJ0eS4gIE5ldmVyIG51bGwgb3IgZW1wdHkuUmVnaXN0cnlQcmltYXJ5IGtleSwgbm9uL' + ` 'WxvY2FsaXplZCB0b2tlbi5Sb290VGhlIHByZWRlZmluZWQgcm9vdCBrZXkgZm9yIHRoZSByZWdpc3RyeSB2YW' + ` 'x1ZSwgb25lIG9mIHJya0VudW0uS2V5UmVnUGF0aFRoZSBrZXkgZm9yIHRoZSByZWdpc3RyeSB2YWx1ZS5UaGU' + ` 'gcmVnaXN0cnkgdmFsdWUgbmFtZS5UaGUgcmVnaXN0cnkgdmFsdWUuRm9yZWlnbiBrZXkgaW50byB0aGUgQ29t' + ` 'cG9uZW50IHRhYmxlIHJlZmVyZW5jaW5nIGNvbXBvbmVudCB0aGF0IGNvbnRyb2xzIHRoZSBpbnN0YWxsaW5nI' + ` 'G9mIHRoZSByZWdpc3RyeSB2YWx1ZS5VcGdyYWRlVXBncmFkZUNvZGVUaGUgVXBncmFkZUNvZGUgR1VJRCBiZW' + ` 'xvbmdpbmcgdG8gdGhlIHByb2R1Y3RzIGluIHRoaXMgc2V0LlZlcnNpb25NaW5UaGUgbWluaW11bSBQcm9kdWN' + ` '0VmVyc2lvbiBvZiB0aGUgcHJvZHVjdHMgaW4gdGhpcyBzZXQuICBUaGUgc2V0IG1heSBvciBtYXkgbm90IGlu' + ` 'Y2x1ZGUgcHJvZHVjdHMgd2l0aCB0aGlzIHBhcnRpY3VsYXIgdmVyc2lvbi5WZXJzaW9uTWF4VGhlIG1heGltd' + ` 'W0gUHJvZHVjdFZlcnNpb24gb2YgdGhlIHByb2R1Y3RzIGluIHRoaXMgc2V0LiAgVGhlIHNldCBtYXkgb3IgbW' + ` 'F5IG5vdCBpbmNsdWRlIHByb2R1Y3RzIHdpdGggdGhpcyBwYXJ0aWN1bGFyIHZlcnNpb24uQSBjb21tYS1zZXB' + ` 'hcmF0ZWQgbGlzdCBvZiBsYW5ndWFnZXMgZm9yIGVpdGhlciBwcm9kdWN0cyBpbiB0aGlzIHNldCBvciBwcm9k' + ` 'dWN0cyBub3QgaW4gdGhpcyBzZXQuVGhlIGF0dHJpYnV0ZXMgb2YgdGhpcyBwcm9kdWN0IHNldC5SZW1vdmVUa' + ` 'GUgbGlzdCBvZiBmZWF0dXJlcyB0byByZW1vdmUgd2hlbiB1bmluc3RhbGxpbmcgYSBwcm9kdWN0IGZyb20gdG' + ` 'hpcyBzZXQuICBUaGUgZGVmYXVsdCBpcyAiQUxMIi5BY3Rpb25Qcm9wZXJ0eVRoZSBwcm9wZXJ0eSB0byBzZXQ' + ` 'gd2hlbiBhIHByb2R1Y3QgaW4gdGhpcyBzZXQgaXMgZm91bmQuQ29zdEluaXRpYWxpemVGaWxlQ29zdENvc3RG' + ` 'aW5hbGl6ZUluc3RhbGxWYWxpZGF0ZUluc3RhbGxJbml0aWFsaXplSW5zdGFsbEFkbWluUGFja2FnZUluc3Rhb' + ` 'GxGaWxlc0luc3RhbGxGaW5hbGl6ZUV4ZWN1dGVBY3Rpb25QdWJsaXNoRmVhdHVyZXNQdWJsaXNoUHJvZHVjdF' + ` 'Byb2R1Y3RDb21wb25lbnR7OTg5QjBFRDgtREVBRC01MjhELUI4RTMtN0NBRTQxODYyNEQ1fUlOU1RBTExGT0x' + ` 'ERVJEdW1teUZsYWdWYWx1ZVByb2dyYW1GaWxlc0ZvbGRlcnE0cGZqNHo3fERTQ1NldHVwUHJvamVjdFRBUkdF' + ` 'VERJUi5Tb3VyY2VEaXJQcm9kdWN0RmVhdHVyZURTQ1NldHVwUHJvamVjdEZpbmRSZWxhdGVkUHJvZHVjdHNMY' + ` 'XVuY2hDb25kaXRpb25zVmFsaWRhdGVQcm9kdWN0SURNaWdyYXRlRmVhdHVyZVN0YXRlc1Byb2Nlc3NDb21wb2' + ` '5lbnRzVW5wdWJsaXNoRmVhdHVyZXNSZW1vdmVSZWdpc3RyeVZhbHVlc1dyaXRlUmVnaXN0cnlWYWx1ZXNSZWd' + ` 'pc3RlclVzZXJSZWdpc3RlclByb2R1Y3RSZW1vdmVFeGlzdGluZ1Byb2R1Y3RzTk9UIFdJWF9ET1dOR1JBREVf' + ` 'REVURUNURURBIG5ld2VyIHZlcnNpb24gb2YgW1Byb2R1Y3ROYW1lXSBpcyBhbHJlYWR5IGluc3RhbGxlZC5BT' + ` 'ExVU0VSUzFNYW51ZmFjdHVyZXJNaWNyb3NvZnQgVW5pdCBUZXN0aW5nIEd1aWxkIG9mIEFtZXJpY2FQcm9kdW' + ` 'N0Q29kZXtERUFEQkVFRi04MEM2LTQxRTYtQTFCOS04QkRCOEEwNTAyN0Z9UHJvZHVjdExhbmd1YWdlMTAzM1B' + ` 'yb2R1Y3ROYW1lRFNDVW5pdFRlc3RQYWNrYWdlUHJvZHVjdFZlcnNpb24xLjIuMy40ezgzQkMzNzkyLTgwQzYt' + ` 'NDFFNi1BMUI5LThCREI4QTA1MDI3Rn1TZWN1cmVDdXN0b21Qcm9wZXJ0aWVzV0lYX0RPV05HUkFERV9ERVRFQ' + ` '1RFRDtXSVhfVVBHUkFERV9ERVRFQ1RFRFdpeFBkYlBhdGhDOlxVc2Vyc1xiZWNhcnJcRG9jdW1lbnRzXFZpc3' + ` 'VhbCBTdHVkaW8gMjAxMFxQcm9qZWN0c1xEU0NTZXR1cFByb2plY3RcRFNDU2V0dXBQcm9qZWN0XGJpblxEZWJ' + ` '1Z1xEU0NTZXR1cFByb2plY3Qud2l4cGRiU29mdHdhcmVcRFNDVGVzdERlYnVnRW50cnlbfl1EVU1NWUZMQUc9' + ` 'W0RVTU1ZRkxBR11bfl1XSVhfVVBHUkFERV9ERVRFQ1RFRFdJWF9ET1dOR1JBREVfREVURUNURURzZWQgdG8gZ' + ` 'm9yY2UgYSBzcGVjaWZpYyBkaXNwbGF5IG9yZGVyaW5nLkxldmVsVGhlIGluc3RhbGwgbGV2ZWwgYXQgd2hpY2' + ` 'ggcmVjb3JkIHdpbGwgYmUgaW5pdGlhbGx5IHNlbGVjdGVkLiBBbiBpbnN0YWxsIGxldmVsIG9mIDAgd2lsbCB' + ` 'kaXNhYmxlIGFuIGl0ZW0gYW5kIHByZXZlbnQgaXRzIGRpc3BsYXkuVXBwZXJDYXNlVGhlIG5hbWUgb2YgdGhl' + ` 'IERpcmVjdG9yeSB0aGF0IGNhbiBiZSBjb25maWd1cmVkIGJ5IHRoZSBVSS4gQSBub24tbnVsbCB2YWx1ZSB3a' + ` 'WxsIGVuYWJsZSB0aGUgYnJvd3NlIGJ1dHRvbi4wOzE7Mjs0OzU7Njs4Ozk7MTA7MTY7MTc7MTg7MjA7MjE7Mj' + ` 'I7MjQ7MjU7MjY7MzI7MzM7MzQ7MzY7Mzc7Mzg7NDg7NDk7NTA7NTI7NQAAAAAAAAAAAAAAAAAAAAAAAAAAAAA' + ` 'AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA' + ` 'AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA' + ` 'AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA' + ` 'AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA' + ` 'AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA' + ` 'AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA' + ` 'AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA' + ` 'AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA' + ` 'AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA' + ` 'AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA' + ` 'AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA' + ` 'AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA' + ` 'AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA' + ` 'AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA' + ` 'AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA' + ` 'AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA' + ` 'AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAATmFtZVRhYmxlQ29sdW1uX1Zh' + ` 'bGlkYXRpb25WYWx1ZU5Qcm9wZXJ0eUlkX1N1bW1hcnlJbmZvcm1hdGlvbkRlc2NyaXB0aW9uU2V0Q2F0ZWdvc' + ` 'nlLZXlDb2x1bW5NYXhWYWx1ZU51bGxhYmxlS2V5VGFibGVNaW5WYWx1ZUlkZW50aWZpZXJOYW1lIG9mIHRhYm' + ` 'xlTmFtZSBvZiBjb2x1bW5ZO05XaGV0aGVyIHRoZSBjb2x1bW4gaXMgbnVsbGFibGVZTWluaW11bSB2YWx1ZSB' + ` 'hbGxvd2VkTWF4aW11bSB2YWx1ZSBhbGxvd2VkRm9yIGZvcmVpZ24ga2V5LCBOYW1lIG9mIHRhYmxlIHRvIHdo' + ` 'aWNoIGRhdGEgbXVzdCBsaW5rQ29sdW1uIHRvIHdoaWNoIGZvcmVpZ24ga2V5IGNvbm5lY3RzVGV4dDtGb3JtY' + ` 'XR0ZWQ7VGVtcGxhdGU7Q29uZGl0aW9uO0d1aWQ7UGF0aDtWZXJzaW9uO0xhbmd1YWdlO0lkZW50aWZpZXI7Qm' + ` 'luYXJ5O1VwcGVyQ2FzZTtMb3dlckNhc2U7RmlsZW5hbWU7UGF0aHM7QW55UGF0aDtXaWxkQ2FyZEZpbGVuYW1' + ` 'lO1JlZ1BhdGg7Q3VzdG9tU291cmNlO1Byb3BlcnR5O0NhYmluZXQ7U2hvcnRjdXQ7Rm9ybWF0dGVkU0RETFRl' + ` 'eHQ7SW50ZWdlcjtEb3VibGVJbnRlZ2VyO1RpbWVEYXRlO0RlZmF1bHREaXJTdHJpbmcgY2F0ZWdvcnlUZXh0U' + ` '2V0IG9mIHZhbHVlcyB0aGF0IGFyZSBwZXJtaXR0ZWREZXNjcmlwdGlvbiBvZiBjb2x1bW5BZG1pbkV4ZWN1dG' + ` 'VTZXF1ZW5jZUFjdGlvbk5hbWUgb2YgYWN0aW9uIHRvIGludm9rZSwgZWl0aGVyIGluIHRoZSBlbmdpbmUgb3I' + ` 'gdGhlIGhhbmRsZXIgRExMLkNvbmRpdGlvbk9wdGlvbmFsIGV4cHJlc3Npb24gd2hpY2ggc2tpcHMgdGhlIGFj' + ` 'dGlvbiBpZiBldmFsdWF0ZXMgdG8gZXhwRmFsc2UuSWYgdGhlIGV4cHJlc3Npb24gc3ludGF4IGlzIGludmFsa' + ` 'WQsIHRoZSBlbmdpbmUgd2lsbCB0ZXJtaW5hdGUsIHJldHVybmluZyBpZXNCYWRBY3Rpb25EYXRhLlNlcXVlbm' + ` 'NlTnVtYmVyIHRoYXQgZGV0ZXJtaW5lcyB0aGUgc29ydCBvcmRlciBpbiB3aGljaCB0aGUgYWN0aW9ucyBhcmU' + ` 'gdG8gYmUgZXhlY3V0ZWQuICBMZWF2ZSBibGFuayB0byBzdXBwcmVzcyBhY3Rpb24uQWRtaW5VSVNlcXVlbmNl' + ` 'QWR2dEV4ZWN1dGVTZXF1ZW5jZUNvbXBvbmVudFByaW1hcnkga2V5IHVzZWQgdG8gaWRlbnRpZnkgYSBwYXJ0a' + ` 'WN1bGFyIGNvbXBvbmVudCByZWNvcmQuQ29tcG9uZW50SWRHdWlkQSBzdHJpbmcgR1VJRCB1bmlxdWUgdG8gdG' + ` 'hpcyBjb21wb25lbnQsIHZlcnNpb24sIGFuZCBsYW5ndWFnZS5EaXJlY3RvcnlfRGlyZWN0b3J5UmVxdWlyZWQ' + ` 'ga2V5IG9mIGEgRGlyZWN0b3J5IHRhYmxlIHJlY29yZC4gVGhpcyBpcyBhY3R1YWxseSBhIHByb3BlcnR5IG5h' + ` 'bWUgd2hvc2UgdmFsdWUgY29udGFpbnMgdGhlIGFjdHVhbCBwYXRoLCBzZXQgZWl0aGVyIGJ5IHRoZSBBcHBTZ' + ` 'WFyY2ggYWN0aW9uIG9yIHdpdGggdGhlIGRlZmF1bHQgc2V0dGluZyBvYnRhaW5lZCBmcm9tIHRoZSBEaXJlY3' + ` 'RvcnkgdGFibGUuQXR0cmlidXRlc1JlbW90ZSBleGVjdXRpb24gb3B0aW9uLCBvbmUgb2YgaXJzRW51bUEgY29' + ` 'uZGl0aW9uYWwgc3RhdGVtZW50IHRoYXQgd2lsbCBkaXNhYmxlIHRoaXMgY29tcG9uZW50IGlmIHRoZSBzcGVj' + ` 'aWZpZWQgY29uZGl0aW9uIGV2YWx1YXRlcyB0byB0aGUgJ1RydWUnIHN0YXRlLiBJZiBhIGNvbXBvbmVudCBpc' + ` 'yBkaXNhYmxlZCwgaXQgd2lsbCBub3QgYmUgaW5zdGFsbGVkLCByZWdhcmRsZXNzIG9mIHRoZSAnQWN0aW9uJy' + ` 'BzdGF0ZSBhc3NvY2lhdGVkIHdpdGggdGhlIGNvbXBvbmVudC5LZXlQYXRoRmlsZTtSZWdpc3RyeTtPREJDRGF' + ` '0YVNvdXJjZUVpdGhlciB0aGUgcHJpbWFyeSBrZXkgaW50byB0aGUgRmlsZSB0YWJsZSwgUmVnaXN0cnkgdGFi' + ` 'bGUsIG9yIE9EQkNEYXRhU291cmNlIHRhYmxlLiBUaGlzIGV4dHJhY3QgcGF0aCBpcyBzdG9yZWQgd2hlbiB0a' + ` 'GUgY29tcG9uZW50IGlzIGluc3RhbGxlZCwgYW5kIGlzIHVzZWQgdG8gZGV0ZWN0IHRoZSBwcmVzZW5jZSBvZi' + ` 'B0aGUgY29tcG9uZW50IGFuZCB0byByZXR1cm4gdGhlIHBhdGggdG8gaXQuVW5pcXVlIGlkZW50aWZpZXIgZm9' + ` 'yIGRpcmVjdG9yeSBlbnRyeSwgcHJpbWFyeSBrZXkuIElmIGEgcHJvcGVydHkgYnkgdGhpcyBuYW1lIGlzIGRl' + ` 'ZmluZWQsIGl0IGNvbnRhaW5zIHRoZSBmdWxsIHBhdGggdG8gdGhlIGRpcmVjdG9yeS5EaXJlY3RvcnlfUGFyZ' + ` 'W50UmVmZXJlbmNlIHRvIHRoZSBlbnRyeSBpbiB0aGlzIHRhYmxlIHNwZWNpZnlpbmcgdGhlIGRlZmF1bHQgcG' + ` 'FyZW50IGRpcmVjdG9yeS4gQSByZWNvcmQgcGFyZW50ZWQgdG8gaXRzZWxmIG9yIHdpdGggYSBOdWxsIHBhcmV' + ` 'udCByZXByZXNlbnRzIGEgcm9vdCBvZiB0aGUgaW5zdGFsbCB0cmVlLkRlZmF1bHREaXJUaGUgZGVmYXVsdCBz' + ` 'dWItcGF0aCB1bmRlciBwYXJlbnQncyBwYXRoLkZlYXR1cmVQcmltYXJ5IGtleSB1c2VkIHRvIGlkZW50aWZ5I' + ` 'GEgcGFydGljdWxhciBmZWF0dXJlIHJlY29yZC5GZWF0dXJlX1BhcmVudE9wdGlvbmFsIGtleSBvZiBhIHBhcm' + ` 'VudCByZWNvcmQgaW4gdGhlIHNhbWUgdGFibGUuIElmIHRoZSBwYXJlbnQgaXMgbm90IHNlbGVjdGVkLCB0aGV' + ` 'uIHRoZSByZWNvcmQgd2lsbCBub3QgYmUgaW5zdGFsbGVkLiBOdWxsIGluZGljYXRlcyBhIHJvb3QgaXRlbS5U' + ` 'aXRsZVNob3J0IHRleHQgaWRlbnRpZnlpbmcgYSB2aXNpYmxlIGZlYXR1cmUgaXRlbS5Mb25nZXIgZGVzY3Jpc' + ` 'HRpdmUgdGV4dCBkZXNjcmliaW5nIGEgdmlzaWJsZSBmZWF0dXJlIGl0ZW0uRGlzcGxheU51bWVyaWMgc29ydC' + ` 'BvcmRlciwgdXNlZCB0byBmb3JjZSBhIHNwZWNpZmljIGRpc3BsYXkgb3JkZXJpbmcuTGV2ZWxUaGUgaW5zdGF' + ` 'sbCBsZXZlbCBhdCB3aGljaCByZWNvcmQgd2lsbCBiZSBpbml0aWFsbHkgc2VsZWN0ZWQuIEFuIGluc3RhbGwg' + ` 'bGV2ZWwgb2YgMCB3aWxsIGRpc2FibGUgYW4gaXRlbSBhbmQgcHJldmVudCBpdHMgZGlzcGxheS5VcHBlckNhc' + ` '2VUaGUgbmFtZSBvZiB0aGUgRGlyZWN0b3J5IHRoYXQgY2FuIGJlIGNvbmZpZ3VyZWQgYnkgdGhlIFVJLiBBIG' + ` '5vbi1udWxsIHZhbHVlIHdpbGwgZW5hYmxlIHRoZSBicm93c2UgYnV0dG9uLjA7MTsyOzQ7NTs2Ozg7OTsxMDs' + ` 'xNjsxNzsxODsyMDsyMTsyMjsyNDsyNTsyNjszMjszMzszNDszNjszNzszODs0ODs0OTs1MDs1Mjs1Mzs1NEZl' + ` 'YXR1cmUgYXR0cmlidXRlc0ZlYXR1cmVDb21wb25lbnRzRmVhdHVyZV9Gb3JlaWduIGtleSBpbnRvIEZlYXR1c' + ` 'mUgdGFibGUuQ29tcG9uZW50X0ZvcmVpZ24ga2V5IGludG8gQ29tcG9uZW50IHRhYmxlLkZpbGVQcmltYXJ5IG' + ` 'tleSwgbm9uLWxvY2FsaXplZCB0b2tlbiwgbXVzdCBtYXRjaCBpZGVudGlmaWVyIGluIGNhYmluZXQuICBGb3I' + ` 'gdW5jb21wcmVzc2VkIGZpbGVzLCB0aGlzIGZpZWxkIGlzIGlnbm9yZWQuRm9yZWlnbiBrZXkgcmVmZXJlbmNp' + ` 'bmcgQ29tcG9uZW50IHRoYXQgY29udHJvbHMgdGhlIGZpbGUuRmlsZU5hbWVGaWxlbmFtZUZpbGUgbmFtZSB1c' + ` '2VkIGZvciBpbnN0YWxsYXRpb24sIG1heSBiZSBsb2NhbGl6ZWQuICBUaGlzIG1heSBjb250YWluIGEgInNob3' + ` 'J0IG5hbWV8bG9uZyBuYW1lIiBwYWlyLkZpbGVTaXplU2l6ZSBvZiBmaWxlIGluIGJ5dGVzIChsb25nIGludGV' + ` 'nZXIpLlZlcnNpb25WZXJzaW9uIHN0cmluZyBmb3IgdmVyc2lvbmVkIGZpbGVzOyAgQmxhbmsgZm9yIHVudmVy' + ` 'c2lvbmVkIGZpbGVzLkxhbmd1YWdlTGlzdCBvZiBkZWNpbWFsIGxhbmd1YWdlIElkcywgY29tbWEtc2VwYXJhd' + ` 'GVkIGlmIG1vcmUgdGhhbiBvbmUuSW50ZWdlciBjb250YWluaW5nIGJpdCBmbGFncyByZXByZXNlbnRpbmcgZm' + ` 'lsZSBhdHRyaWJ1dGVzICh3aXRoIHRoZSBkZWNpbWFsIHZhbHVlIG9mIGVhY2ggYml0IHBvc2l0aW9uIGluIHB' + ` 'hcmVudGhlc2VzKVNlcXVlbmNlIHdpdGggcmVzcGVjdCB0byB0aGUgbWVkaWEgaW1hZ2VzOyBvcmRlciBtdXN0' + ` 'IHRyYWNrIGNhYmluZXQgb3JkZXIuSW5zdGFsbEV4ZWN1dGVTZXF1ZW5jZUluc3RhbGxVSVNlcXVlbmNlTGF1b' + ` 'mNoQ29uZGl0aW9uRXhwcmVzc2lvbiB3aGljaCBtdXN0IGV2YWx1YXRlIHRvIFRSVUUgaW4gb3JkZXIgZm9yIG' + ` 'luc3RhbGwgdG8gY29tbWVuY2UuRm9ybWF0dGVkTG9jYWxpemFibGUgdGV4dCB0byBkaXNwbGF5IHdoZW4gY29' + ` 'uZGl0aW9uIGZhaWxzIGFuZCBpbnN0YWxsIG11c3QgYWJvcnQuTWVkaWFEaXNrSWRQcmltYXJ5IGtleSwgaQgA' + ` 'AgAIAAIACAACAAoAFgANAAEADgABAAMAAQAeAAEAAQAnABUAAQAVAAEANgABACQAAQD1AAEADwABAAQACQAgA' + ` 'AEAFQABABQABwAGAAoAQgAFAAkAFQCfAAUACAAMAG8ABQAPAAcAEwAHAAkAEgA7AAEACwACAAQAAgA+AAEACg' + ` 'AEAAkADADSAAEACgAIACcAAQDoAAEABwACABwAAQDjAAEAhgABABAAAgCmAAEACgADACkAAQAHABUAOQABAA4' + ` 'AAgCUAAEABQACAC4AAQA6AAEABwACAD4AAQAFAAIAgQABAAkAAgBrAAEAUQABABIAAQARAAUACAACAB8AAQAK' + ` 'AAYAIQABAAQAFABzAAEAOQABAAgAAgAIAAEAYwABAAgAAgAlAAEABwADAEEAAQAIAAYAPwABAHYAAQBKAAEAF' + ` 'gAHABEABwAPAAUASAABAAkABABIAAEABQANAAYAAgA3AAEADAACADYAAQAKAAIAhAABAAcAAwBmAAEACwACAC' + ` 'MAAQAGAAIACAAIADcAAQA+AAEAMAABAAgADwAhAAEABAACAD8AAQADAAIABwABAB8AAQAYAAEAEwABAG4AAQA' + ` 'HAA8ACwADADsAAQAKAAIAfgABAAoAAgB+AAEAYAABACMAAQAGAAIAYAABAA4AAgA4AAEADgAFAAgABAAMAAUA' + ` 'DwADABEAAwATAAEADAABAA8AAwANAAIADwACAA4AAgAQAAMAJgABAA0AAgAOAAIAEgACABgAAQAJAAIAAQABA' + ` 'AkAAQAOAAIADwABABMAAgAQAAIAEQACABQAAgARAAEAEQABABQAAQATAAEADAABAA8AAQAWAAEAGgABADYAAQ' + ` 'AIAAEAAQABAAwAAQAnAAEACwABACYAAQAPAAEABAABAAsAAQASAAEADgABAAcAAwAmAAMAFgABACsAAQAKAAE' + ` 'AdgABABAAAQAKAAEAGwABABQAAQAWAAEAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA' + ` 'AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA' + ` 'AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA' + ` 'AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA' + ` 'AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA' + ` 'AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA' + ` 'AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA' + ` 'AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA' + ` 'AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA' + ` 'AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA' + ` 'AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA' + ` 'AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA' + ` 'AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA' + ` 'AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA' + ` 'AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA' + ` 'AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA' + ` 'AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA' + ` 'AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA' + ` 'AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA' + ` 'AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA' + ` 'AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA' + ` 'AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA' + ` 'AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA' + ` 'AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA' + ` 'AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA' + ` 'AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA' + ` 'AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA' + ` 'AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA' + ` 'AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA' + ` 'AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA' + ` 'AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA' + ` 'AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA' + ` 'AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA' + ` 'AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA' + ` 'AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA' + ` 'AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA' + ` 'AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA' + ` 'AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA' + ` 'AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA' + ` 'AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA' + ` 'AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA' + ` 'AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA' + ` 'AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA' + ` 'AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA' + ` 'AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA' + ` 'AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA' + ` 'AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA' + ` 'AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA' + ` 'AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA' + ` 'AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA' + ` 'AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA' + ` 'AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA' + ` 'AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA' + ` 'AAAAAAAAAAAAAAAAAAA=' #endregion $msiContentInBytes = [System.Convert]::FromBase64String($msiContentInBase64) Set-Content -Path $DestinationPath -Value $msiContentInBytes -Encoding 'Byte' | Out-Null } <# .SYNOPSIS Clears the Package cache where files are downloaded from the file server when applicable. #> function Clear-PackageCache { [CmdletBinding()] param () $packageCacheLocation = "$env:ProgramData\Microsoft\Windows\PowerShell\Configuration\" + ` 'BuiltinProvCache\MSFT_xPackageResource' Remove-Item -Path $packageCacheLocation -ErrorAction 'SilentlyContinue' -Recurse } <# .SYNOPSIS Tests if the package with the given name is installed. .PARAMETER Name The name of the package to test for. #> function Test-PackageInstalledByName { [OutputType([System.Boolean])] [CmdletBinding()] param ( [Parameter()] [System.String] $Name ) $uninstallRegistryKey = 'HKLM:\SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall' $uninstallRegistryKeyWow64 = 'HKLM:\SOFTWARE\Wow6432Node\Microsoft\Windows\CurrentVersion\Uninstall' $productEntry = $null foreach ($registryKeyEntry in (Get-ChildItem -Path @( $uninstallRegistryKey, $uninstallRegistryKeyWow64) -ErrorAction 'Ignore' )) { if ($Name -eq (Get-LocalizedRegistryKeyValue -RegistryKey $registryKeyEntry -ValueName 'DisplayName')) { $productEntry = $registryKeyEntry break } } return ($null -ne $productEntry) } <# .SYNOPSIS Retrieves a localized registry key value. .PARAMETER RegistryKey The registry key to retrieve the value from. .PARAMETER ValueName The name of the value to retrieve. #> function Get-LocalizedRegistryKeyValue { [CmdletBinding()] param ( [Parameter()] [System.Object] $RegistryKey, [Parameter(Mandatory = $true)] [ValidateNotNullOrEmpty()] [System.String] $ValueName ) $localizedRegistryKeyValue = $RegistryKey.GetValue('{0}_Localized' -f $ValueName) if ($null -eq $localizedRegistryKeyValue) { $localizedRegistryKeyValue = $RegistryKey.GetValue($ValueName) } return $localizedRegistryKeyValue } <# .SYNOPSIS Creates a new test executable. .PARAMETER DestinationPath The path at which to create the test executable. #> function New-TestExecutable { [CmdletBinding()] param ( [Parameter(Mandatory = $true)] [ValidateNotNullOrEmpty()] [System.String] $DestinationPath ) if (Test-Path -Path $DestinationPath) { Write-Verbose -Message "Removing old executable at $DestinationPath..." Remove-Item -Path $DestinationPath -Force } $testExecutableCode = @' using System; using System.Collections.Generic; using System.Linq; using System.Management; using System.Text; using System.Threading.Tasks; using System.Management.Automation; using System.Management.Automation.Runspaces; using System.Runtime.InteropServices; namespace Providers.Package.UnitTests.MySuite { class ExeTestClass { public static void Main(string[] args) { string cmdline = System.Environment.CommandLine; Console.WriteLine("Cmdline was " + cmdline); int endIndex = cmdline.IndexOf("\"", 1); string self = cmdline.Substring(0, endIndex); string other = cmdline.Substring(self.Length + 1); string msiexecpath = System.IO.Path.Combine(System.Environment.SystemDirectory, "msiexec.exe"); self = self.Replace("\"", ""); string packagePath = System.IO.Path.Combine(System.IO.Path.GetDirectoryName(self), "DSCSetupProject.msi"); string msiexecargs = String.Format("/i \"{0}\" {1}", packagePath, other); System.Diagnostics.Process.Start(msiexecpath, msiexecargs).WaitForExit(); } } } '@ Add-Type -TypeDefinition $testExecutableCode -OutputAssembly $DestinationPath -OutputType 'ConsoleApplication' } Export-ModuleMember -Function ` New-TestMsi, ` Clear-PackageCache, ` New-TestExecutable, ` Start-Server, ` Stop-Server, ` Test-PackageInstalledByName, ` Test-PackageInstalledById, ` Stop-EveryTestServerInstance
{'content_hash': '85d124a5a34af959d579a0150b1aa61a', 'timestamp': '', 'source': 'github', 'line_count': 1324, 'max_line_length': 168, 'avg_line_length': 58.58459214501511, 'alnum_prop': 0.6052265167728128, 'repo_name': 'PowerShell/xPSDesiredStateConfiguration', 'id': 'e340a9674f367714b38aef81eb9ad5725d0b06ac', 'size': '77566', 'binary': False, 'copies': '1', 'ref': 'refs/heads/Issue-729', 'path': 'tests/TestHelpers/DSC_xPackageResource.TestHelper.psm1', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'C#', 'bytes': '7766'}, {'name': 'PowerShell', 'bytes': '2735024'}]}
local GUI = { -- GUI Survival {type = 'header', text = 'Survival', align = 'center'}, {type = 'checkbox', text = 'Enable Lay on Hands', key = 'S_LOHE', default = true}, {type = 'spinner', text = '', key = 'S_LOH', default = 10}, {type = 'checkbox', text = 'Enable Flash of Light', key = 'S_FOLE', default = true}, {type = 'spinner', text = '', key = 'S_FOL', default = 40}, {type = 'checkbox', text = 'Enable Shield of Vengeance', key = 'S_SOVE', default = true}, {type = 'spinner', text = '', key = 'S_SOV', default = 75}, {type = 'checkbox', text = 'Enable Eye for an Eye', key = 'S_EFAEE', default = true}, {type = 'spinner', text = '', key = 'S_EFAE', default = 90}, --{type = 'checkbox', text = 'Enable Every Man for Himself (Stun)', key = 'S_EMFHSE', default = true}, --{type = 'checkbox', text = 'Enable Blessing of Freedom (Root)', key = 'S_BOFRE', default = true}, --{type = 'checkbox', text = 'Enable Blessing of Freedom (Snare)', key = 'S_BOFSE', default = true}, {type = 'checkbox', text = 'Enable Gift of the Naaru', key = 'S_GOTNE', default = true}, {type = 'spinner', text = '', key = 'S_GOTN', default = 40}, {type = 'checkbox', text = 'Enable Healthstone', key = 'S_HSE', default = true}, {type = 'spinner', text = '', key = 'S_HS', default = 20}, {type = 'checkbox', text = 'Enable Ancient Healing Potion', key = 'S_AHPE', default = true}, {type = 'spinner', text = '', key = 'S_AHP', default = 20}, {type = 'ruler'},{type = 'spacer'}, -- GUI Emergency Group Assistance {type = 'header', text = 'Emergency Group Assistance', align = 'center'}, {type = 'checkbox', text = 'Enable Emergency Group Assistance', key = 'E_GAE', default = false}, {type = 'text', text = 'Flash of Light'}, {type = 'spinner', text = '', key = 'E_FOL', default = 35}, {type = 'text', text = 'Lay on Hands'}, {type = 'spinner', text = '', key = 'E_LOH', default = 10}, {type = 'text', text = 'Blessing of Protection'}, {type = 'spinner', text = '', key = 'E_BOP', default = 10}, {type = 'ruler'},{type = 'spacer'}, -- GUI Blessings {type = 'header', text = 'Blessings', align = 'center'}, {type = 'text', text = 'Check to enable blessings on yourself'}, {type = 'checkbox', text = 'Blessing of Kings', key = 'B_BOKP', default = false}, {type = 'checkbox', text = 'Blessing of Wisdom', key = 'B_BOWP', default = false}, {type = 'ruler'},{type = 'spacer'}, } local exeOnLoad = function() -- Rotation loaded message. print('|cfff58cba ----------------------------------------------------------------------|r') print('|cfff58cba --- |rPaladin: |cfff58cbaRETRIBUTION|r') print('|cfff58cba --- |rTalents: 1/2 - 2/2 - 3/1 - 4/2 - 5/2 - 6/1 - 7/2|r') print('|cfff58cba --- |rNo Multitarget (AoE) enabled settings|r') print('|cfff58cba ----------------------------------------------------------------------|r') print('|cffff0000 Configuration: |rRight-click the MasterToggle and go to Combat Routines Settings|r') NeP.Interface:AddToggle({ -- Cleanse Toxin key = 'yuCT', name = 'Cleanse Toxin', text = 'Enable/Disable: Automatic removal of Poison and Diseases', icon = 'Interface\\ICONS\\spell_holy_renew', }) NeP.Interface:AddToggle({ -- Emergency Group Assistance key = 'yuEGA', name = 'Emergency Group Assistance', text = 'Enable/Disable: Automatic LoH/BoP/FoL on group members', icon = 'Interface\\ICONS\\ability_fiegndead', }) end local Survival = { -- Lay on Hands usage if enabled in UI. {'&Lay on Hands', 'UI(S_LOHE)&{!player.debuff(Ignite Soul)}&player.health<=UI(S_LOH)'}, -- Shield of Vengeance usage if enabled in UI. {'&Shield of Vengeance', 'UI(S_SOVE)&player.health<=UI(S_SOV)'}, -- Eye for an Eye usage if enabled in UI. {'Eye for an Eye', 'talent(5,2)&UI(S_EFAEE)&player.health<=UI(S_EFAE)'}, -- Every Man for Himself usage if enabled in UI. --{'&Every Man for Himself', 'UI(S_EMFHSE)&player.state(stun)'}, -- Blessing of Freedom usage if enabled in UI. --{'!Blessing of Freedom', 'UI(S_BOFRE)&player.state(root)'}, -- Blessing of Freedom usage if enabled in UI. --{'!Blessing of Freedom', 'UI(S_BOFSE)&player.state(snare)'}, -- Gift of the Naaru usage if enabled in UI. {'&Gift of the Naaru', 'UI(S_GOTNE)&{!player.debuff(Ignite Soul)}&player.health<=UI(S_GOTN)'}, -- Healthstone usage if enabled in UI. {'#5512', 'UI(S_HSE)&{!player.debuff(Ignite Soul)}&player.health<=UI(S_HS)'}, -- Ancient Healing Potion usage if enabled in UI. {'#127834', 'UI(S_AHPE)&{!player.debuff(Ignite Soul)}&player.health<=UI(S_AHP)'}, } local Player = { -- Flash of Light usage if enabled in UI. {'!Flash of Light', 'UI(S_FOLE)&{!player.debuff(Ignite Soul)}&player.health<=UI(S_FOL)', 'player'}, } local Emergency = { -- Flash of Light usage if enabled in UI. {'!Flash of Light', 'UI(E_GAE)&{!lowest.debuff(Ignite Soul)}&lowest.health<=UI(E_FOL)', 'lowest'}, -- Lay on Hands usage if enabled in UI. {'!Lay on Hands', 'UI(E_GAE)&{!lowest.debuff(Ignite Soul)}&lowest.health<=UI(E_LOH)', 'lowest'}, -- Blessing of Protection usage if enabled in UI. {'!Blessing of Protection', 'UI(E_GAE)&{!lowest.debuff(Ignite Soul)}&lowest.health<=UI(E_BOP)', 'lowest'}, } local Interrupts = { {'&Rebuke', 'target.range<=5'}, {'Hammer of Justice', '!equipped(Justice Gaze)&target.range<=10&spell(Rebuke).cooldown>gcd&!lastgcd(Rebuke)'}, {'Hammer of Justice', 'equipped(Justice Gaze)&target.health>=75&target.range<=10&spell(Rebuke).cooldown>gcd&!lastgcd(Rebuke)'}, {'Blinding Light', 'talent(3,3)&target.range<=10&spell(Rebuke).cooldown>gcd&!lastgcd(Rebuke)'}, {'&Arcane Torrent', 'target.range<=8&spell(Rebuke).cooldown>gcd&!lastgcd(Rebuke)'}, } local Dispel = { {'%dispelself'}, } local Blessings = { {'Greater Blessing of Kings', 'UI(B_BOKP)&!player.buff(Greater Blessing of Kings)', 'player'}, {'Greater Blessing of Wisdom', 'UI(B_BOWP)&!player.buff(Greater Blessing of Wisdom)', 'player'}, } -- #################################################################################### -- Primairly sourced from legion-dev SimC. -- Updates to rotations from sources are considered for implementation. -- #################################################################################### -- SimC APL 4/20/2017 -- https://github.com/simulationcraft/simc/blob/legion-dev/profiles/Tier19M/Paladin_Retribution_T19M.simc local Cooldowns = { --actions+=/arcane_torrent,if=holy_power<5&(buff.crusade.up|buff.avenging_wrath.up|time<2) {'&Arcane Torrent', 'holypower<5&{player.buff(Crusade)||player.buff(Avenging Wrath)||combat(player).time<2}'}, --actions+=/holy_wrath {'Holy Wrath', 'talent(7,3)'}, --actions+=/avenging_wrath {'&Avenging Wrath', '!talent(7,2)'}, --actions+=/crusade,if=holy_power>=5&!equipped.137048|((equipped.137048|race.blood_elf)&holy_power>=2) {'&Crusade', 'talent(7,2)&{holypower>=5&!equipped(Liadrin\'s Fury Unleashed)||{equipped(Liadrin\'s Fury Unleashed)&holypower>=2}}'}, } local Combat = { {'/startattack', '!isattacking'}, --actions+=/judgment,if=time<2 {'Judgment', 'combat(player).time<2'}, --actions+=/blade_of_justice,if=time<2&(equipped.137048|race.blood_elf) {'Blade of Justice', 'combat(player).time<2&equipped(Liadrin\'s Fury Unleashed)'}, --actions+=/divine_hammer,if=time<2&(equipped.137048|race.blood_elf) {'Divine Hammer', 'talent(4,3)&combat(player).time<2&equipped(Liadrin\'s Fury Unleashed)'}, --actions+=/wake_of_ashes,if=holy_power<=1&time<2 {'Wake of Ashes', 'holypower<=1&combat(player).time<2'}, --actions+=/execution_sentence,if=spell_targets.divine_storm<=3&(cooldown.judgment.remains<gcd*4.5|debuff.judgment.remains>gcd*4.5)&(!talent.crusade.enabled|cooldown.crusade.remains>gcd*2) {'Execution Sentence','talent(1,2)&player.area(8).enemies<=3&{spell(Judgment).cooldown<gcd*4.5||target.debuff(judgment).duration>gcd*4.5}&{!talent(7,2)||talent(7,2)&!toggle(cooldowns)||spell(Crusade).cooldown>gcd*2}'}, --actions+=/divine_storm,if=debuff.judgment.up&spell_targets.divine_storm>=2&buff.divine_purpose.up&buff.divine_purpose.remains<gcd*2 {'Divine Storm', 'target.debuff(Judgment)&player.area(8).enemies>=2&player.buff(Divine Purpose).duration<gcd*2'}, --actions+=/divine_storm,if=debuff.judgment.up&spell_targets.divine_storm>=2&holy_power>=5&buff.divine_purpose.react {'Divine Storm', 'target.debuff(Judgment)&player.area(8).enemies>=2&holypower>=5&player.buff(Divine Purpose)'}, --actions+=/divine_storm,if=debuff.judgment.up&spell_targets.divine_storm>=2&holy_power>=3&(buff.crusade.up&(buff.crusade.stack<15|buff.bloodlust.up)|buff.liadrins_fury_unleashed.up) {'Divine Storm', 'target.debuff(Judgment)&player.area(8).enemies>=2&holypower>=3&{player.buff(Crusade)&{player.buff(Crusade).count<15||hashero}||player.buff(Liadrin\'s Fury Unleashed)}'}, --actions+=/divine_storm,if=debuff.judgment.up&spell_targets.divine_storm>=2&holy_power>=5&(!talent.crusade.enabled|cooldown.crusade.remains>gcd*3) {'Divine Storm', 'target.debuff(Judgment)&player.area(8).enemies>=2&holypower>=5&{!talent(7,2)||talent(7,2)&!toggle(cooldowns)||spell(Crusade).cooldown>gcd*3}'}, --actions+=/templars_verdict,if=debuff.judgment.up&buff.divine_purpose.up&buff.divine_purpose.remains<gcd*2 {'Templar\'s Verdict', 'target.debuff(Judgment)&player.buff(Divine Purpose).duration<gcd*2'}, --actions+=/templars_verdict,if=debuff.judgment.up&holy_power>=5&buff.divine_purpose.react {'Templar\'s Verdict', 'target.debuff(Judgment)&holypower>=5&player.buff(Divine Purpose)'}, --actions+=/templars_verdict,if=debuff.judgment.up&holy_power>=3&(buff.crusade.up&(buff.crusade.stack<15|buff.bloodlust.up)|buff.liadrins_fury_unleashed.up) {'Templar\'s Verdict', 'target.debuff(Judgment)&holypower>=3&{player.buff(Crusade)&{player.buff(Crusade).count<15||hashero}||player.buff(Liadrin\'s Fury Unleashed)}'}, --actions+=/templars_verdict,if=debuff.judgment.up&holy_power>=5&(!talent.crusade.enabled|cooldown.crusade.remains>gcd*3)&(!talent.execution_sentence.enabled|cooldown.execution_sentence.remains>gcd) {'Templar\'s Verdict', 'target.debuff(Judgment)&holypower>=5&{!talent(7,2)||talent(7,2)&!toggle(cooldowns)||spell(Crusade).cooldown>gcd*3}&{!talent(1,2)||spell(Execution Sentence).cooldown>gcd}'}, --actions+=/divine_storm,if=debuff.judgment.up&holy_power>=3&spell_targets.divine_storm>=2&(cooldown.wake_of_ashes.remains<gcd*2&artifact.wake_of_ashes.enabled|buff.whisper_of_the_nathrezim.up&buff.whisper_of_the_nathrezim.remains<gcd)&(!talent.crusade.enabled|cooldown.crusade.remains>gcd*4) {'Divine Storm', 'target.debuff(Judgment)&holypower>=3&player.area(8).enemies>=2&{spell(Wake of Ashes).cooldown<gcd*2&artifact(Wake of Ashes).enabled||player.buff(Whisper of the Nathrezim).duration<gcd}&{!talent(7,2)||talent(7,2)&!toggle(cooldowns)||spell(Crusade).cooldown>gcd*4}'}, --actions+=/templars_verdict,if=debuff.judgment.up&holy_power>=3&(cooldown.wake_of_ashes.remains<gcd*2&artifact.wake_of_ashes.enabled|buff.whisper_of_the_nathrezim.up&buff.whisper_of_the_nathrezim.remains<gcd)&(!talent.crusade.enabled|cooldown.crusade.remains>gcd*4) {'Templar\'s Verdict', 'target.debuff(Judgment)&holypower>=3&{spell(Wake of Ashes).cooldown<gcd*2&artifact(Wake of Ashes).enabled||player.buff(Whisper of the Nathrezim).duration<gcd}&{!talent(7,2)||talent(7,2)&!toggle(cooldowns)||spell(Crusade).cooldown>gcd*4}'}, --actions+=/judgment,if=dot.execution_sentence.ticking&dot.execution_sentence.remains<gcd*2&debuff.judgment.remains<gcd*2 {'Judgment', 'target.debuff(Execution Sentence).duration<gcd*2&target.debuff(Judgment).duration<gcd*2'}, --actions+=/wake_of_ashes,if=(!raid_event.adds.exists|raid_event.adds.in>15)&(holy_power=0|holy_power=1&(cooldown.blade_of_justice.remains>gcd|cooldown.divine_hammer.remains>gcd)|holy_power=2&(cooldown.zeal.charges_fractional<=0.65|cooldown.crusader_strike.charges_fractional<=0.65)) {'Wake of Ashes', 'holypower=0||holypower=1&{spell(Blade of Justice).cooldown>gcd||spell(Divine Hammer).cooldown>gcd}||holypower=2&{spell(Zeal).charges<=0.65||spell(Crusader Strike).charges<=0.65}'}, --actions+=/blade_of_justice,if=(holy_power<=2&set_bonus.tier20_2pc=1|holy_power<=3&set_bonus.tier20_2pc=0) {'Blade of Justice', 'holypower<=2&set_bonus(T20)>=2||holypower<=3&set_bonus(T20)=0'}, --actions+=/divine_hammer,if=(holy_power<=2&set_bonus.tier20_2pc=1|holy_power<=3&set_bonus.tier20_2pc=0) {'Divine Hammer', 'holypower<=2&set_bonus(T20)>=2||holypower<=3&set_bonus(T20)=0'}, --actions+=/hammer_of_justice,if=equipped.137065&target.health.pct>=75&holy_power<=4 {'Hammer of Justice', 'equipped(Justice Gaze)&target.health>=75&holypower<=4'}, --actions+=/judgment {'Judgment'}, --actions+=/zeal,if=charges=2&(set_bonus.tier20_2pc=0&holy_power<=2|(holy_power<=4&(cooldown.divine_hammer.remains>gcd*2|cooldown.blade_of_justice.remains>gcd*2)&cooldown.judgment.remains>gcd*2))|(set_bonus.tier20_2pc=1&holy_power<=1|(holy_power<=4&(cooldown.divine_hammer.remains>gcd*2|cooldown.blade_of_justice.remains>gcd*2)&cooldown.judgment.remains>gcd*2)) {'Zeal', 'talent(2,2)&spell(Zeal).charges=2&{set_bonus(T20)=0&holypower<=2||{holypower<=4&{spell(Divine Hammer).cooldown>gcd*2||spell(Blade of Justice).cooldown>gcd*2}&spell(Judgment).cooldown>gcd*2}}||{set_bonus(T20)>=2&holypower<=1||{holypower<=4&{spell(Divine Hammer).cooldown>gcd*2||spell(Blade of Justice).cooldown>gcd*2}&spell(Judgment).cooldown>gcd*2}}'}, --actions+=/crusader_strike,if=charges=2&(set_bonus.tier20_2pc=0&holy_power<=2|(holy_power<=4&(cooldown.divine_hammer.remains>gcd*2|cooldown.blade_of_justice.remains>gcd*2)&cooldown.judgment.remains>gcd*2))|(set_bonus.tier20_2pc=1&holy_power<=1|(holy_power<=4&(cooldown.divine_hammer.remains>gcd*2|cooldown.blade_of_justice.remains>gcd*2)&cooldown.judgment.remains>gcd*2)) {'Crusader Strike', '!talent(2,2)&spell(Crusader Strike).charges=2&{set_bonus(T20)=0&holypower<=2||{holypower<=4&{spell(Divine Hammer).cooldown>gcd*2||spell(Blade of Justice).cooldown>gcd*2}&spell(Judgment).cooldown>gcd*2}}||{set_bonus(T20)>=2&holypower<=1||{holypower<=4&{spell(Divine Hammer).cooldown>gcd*2||spell(Blade of Justice).cooldown>gcd*2}&spell(Judgment).cooldown>gcd*2}}'}, --actions+=/consecration {'Consecration', 'talent(1,3)'}, --actions+=/divine_storm,if=debuff.judgment.up&spell_targets.divine_storm>=2&buff.divine_purpose.react {'Divine Storm', 'target.debuff(Judgment)&player.area(8).enemies>=2&player.buff(Divine Purpose)'}, --actions+=/divine_storm,if=debuff.judgment.up&spell_targets.divine_storm>=2&buff.the_fires_of_justice.react&(!talent.crusade.enabled|cooldown.crusade.remains>gcd*3) {'Divine Storm', 'target.debuff(Judgment)&player.area(8).enemies>=2&player.buff(The Fires of Justice)&{!talent(7,2)||talent(7,2)&!toggle(cooldowns)||spell(Crusade).cooldown>gcd*3}'}, --actions+=/divine_storm,if=debuff.judgment.up&spell_targets.divine_storm>=2&holy_power>=4&(!talent.crusade.enabled|cooldown.crusade.remains>gcd*4) {'Divine Storm', 'target.debuff(Judgment)&player.area(8).enemies>=2&holypower>=4&{!talent(7,2)||talent(7,2)&!toggle(cooldowns)||spell(Crusade).cooldown>gcd*4}'}, --actions+=/templars_verdict,if=debuff.judgment.up&buff.divine_purpose.react {'Templar\'s Verdict', 'target.debuff(Judgment)&player.buff(Divine Purpose)'}, --actions+=/templars_verdict,if=debuff.judgment.up&buff.the_fires_of_justice.react&(!talent.crusade.enabled|cooldown.crusade.remains>gcd*3) {'Templar\'s Verdict', 'target.debuff(Judgment)&player.buff(The Fires of Justice)&{!talent(7,2)||talent(7,2)&!toggle(cooldowns)||spell(Crusade).cooldown>gcd*3}'}, --actions+=/templars_verdict,if=debuff.judgment.up&holy_power>=4&(!talent.crusade.enabled|cooldown.crusade.remains>gcd*4)&(!talent.execution_sentence.enabled|cooldown.execution_sentence.remains>gcd*2) {'Templar\'s Verdict', 'target.debuff(Judgment)&holypower>=4&{!talent(7,2)||talent(7,2)&!toggle(cooldowns)||spell(Crusade).cooldown>gcd*4}&{!talent(1,2)||spell(Execution Sentence).cooldown>gcd*2}'}, --actions+=/zeal,if=holy_power<=4 {'Zeal', 'talent(2,2)&holypower<=4'}, --actions+=/crusader_strike,if=holy_power<=4 {'Crusader Strike', '!talent(2,2)&holypower<=4'}, --actions+=/divine_storm,if=debuff.judgment.up&holy_power>=3&spell_targets.divine_storm>=2&(!talent.crusade.enabled|cooldown.crusade.remains>gcd*5) {'Divine Storm', 'target.debuff(Judgment)&holypower>=3&player.area(8).enemies>=2&{!talent(7,2)||talent(7,2)&!toggle(cooldowns)||spell(Crusade).cooldown>gcd*5}'}, --actions+=/templars_verdict,if=debuff.judgment.up&holy_power>=3&(!talent.crusade.enabled|cooldown.crusade.remains>gcd*5) {'Templar\'s Verdict', 'target.debuff(Judgment)&holypower>=3&{!talent(7,2)||talent(7,2)&!toggle(cooldowns)||spell(Crusade).cooldown>gcd*5}'}, } local inCombat = { {Dispel, '{!moving||moving}&toggle(yuCT)&spell(Cleanse Toxins).cooldown=0'}, {Survival, '{!moving||moving}'}, {Blessings, '{!moving||moving}'}, {Player, '!moving&{!ingroup||ingroup}'}, {Emergency, '!moving&ingroup&toggle(yuEGA)'}, {Interrupts, '{!moving||moving}&toggle(interrupts)&target.interruptAt(70)&target.infront'}, {Cooldowns, '{!moving||moving}&toggle(cooldowns)'}, {Combat, '{!moving||moving}&target.infront&target.range<=8'}, } local outCombat = { {Dispel, '{!moving||moving}&toggle(yuCT)&spell(Cleanse Toxins).cooldown=0'}, {Interrupts, '{!moving||moving}&toggle(interrupts)&target.interruptAt(70)&target.infront'}, {Blessings, '{!moving||moving}'}, {Emergency, '!moving&ingroup&toggle(yuEGA)'}, {'Flash of Light', '!moving&player.health<=70', 'player'}, } NeP.CR:Add(70, { name = '|r[|cff00fff0Yumad|r] |cfff58cbaPaladin|r - |cfff58cbaRETRIBUTION|r', ic = inCombat, ooc = outCombat, gui = GUI, load = exeOnLoad })
{'content_hash': 'c7616b79a3240f3cbe1e3df5e9f507c4', 'timestamp': '', 'source': 'github', 'line_count': 235, 'max_line_length': 386, 'avg_line_length': 74.63404255319149, 'alnum_prop': 0.6929699526768915, 'repo_name': 'damuY/NerdPack-Yumad', 'id': '98f0d77faae8519aed20647b8c750d214e2ff153', 'size': '17539', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'rotations/paladin/retribution.lua', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'Lua', 'bytes': '105029'}]}
import time import game import instances import palette import registry from entities import entity from entities.creatures import player from statuses import hastestatus class TwitchChatManager(entity.Entity): special_viewers = [] def __init__(self): super().__init__(' ') self.hidden = True self.time_since_last_help_message = 0 TwitchChatManager.special_viewers = [viewer.lower() for viewer in game.Game.config['TWITCH']['SpecialViewers'].split('\n') if viewer] def get_config_color(self, key): return tuple([int(d) for d in game.Game.config['TWITCH'][key].strip(' ').split(',')]) def handle_events(self, event): current_scene = instances.scene_root if event.type == 'TWITCHCHATMESSAGE': if event.message: if event.message.upper() == '!JOIN': player_names = [e.name for e in current_scene.children if hasattr(e, 'name')] bonus = None if not event.nickname in player_names: # Set player color if 'broadcaster' in event.tags['badges']: try: player_color = self.get_config_color('BroadcasterColor') except: player_color = palette.get_nearest((255, 163, 0)) elif event.tags['subscriber'] != '0': try: player_color = self.get_config_color('SubscriberColor') except: player_color = palette.BRIGHT_BLUE bonus = registry.Registry.get('weapon')() elif event.nickname.lower() in TwitchChatManager.special_viewers: try: player_color = self.get_config_color('SpecialViewerColor') except: player_color = palette.BRIGHT_RED else: try: player_color = self.get_config_color('ViewerColor') except: player_color = palette.get_nearest((255, 163, 0)) # Add player pos = current_scene.get_location_near_stairs() p = player.Player(event.nickname[0], pos, fg=player_color) p.name = event.nickname if bonus: p.equip_weapon(bonus) current_scene.append(p) instances.console.print('{} has joined!'.format(p.display_string)) elif event.message.upper() == '!LEAVE': for e in current_scene.children: if not e.isinstance('Player'): continue if e.name == event.nickname: e.die() instances.console.print('{} has left.'.format(e.display_string)) elif event.message.upper().startswith('!CHEER'): s = event.message.split(' ') if len(s) <= 1: return player_names = [p.name for p in instances.scene_root.players if p.state != 'PlayerExitedState'] if event.nickname in player_names: return player_name = s[1].lower() if player_name[0] == '@': player_name = player_name[1:] target_player = [p for p in instances.scene_root.players if p.state != 'PlayerExitedState' and p.name == player_name] target_player = target_player[0] if target_player else None if target_player: target_player.add_status(hastestatus.HasteStatus(target_player)) elif event.message.upper() == '!HELP': current_time = time.time() if current_time - self.time_since_last_help_message > 30: help_message = 'Available commands: !join !leave !move [uldr] !move @username !stop !attack [uldr] !throw [uldr] !drop !cheer @username' instances.game.observer.send_message(help_message, instances.game.channel) self.time_since_last_help_message = current_time
{'content_hash': 'eca08351fb6487a47772453eacbb8a2c', 'timestamp': '', 'source': 'github', 'line_count': 111, 'max_line_length': 160, 'avg_line_length': 41.2972972972973, 'alnum_prop': 0.48276614310645727, 'repo_name': 'JoshuaSkelly/lunch-break-rl', 'id': 'ef49018a54b21a5b06d0e69a64e788b92e4ecddc', 'size': '4584', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'twitchchatmanager.py', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'Python', 'bytes': '69311'}]}
namespace { using google_breakpad::Minidump; using google_breakpad::MinidumpContext; using google_breakpad::MinidumpException; using google_breakpad::MinidumpMemoryInfo; using google_breakpad::MinidumpMemoryInfoList; using google_breakpad::MinidumpMemoryList; using google_breakpad::MinidumpMemoryRegion; using google_breakpad::MinidumpModule; using google_breakpad::MinidumpModuleList; using google_breakpad::MinidumpSystemInfo; using google_breakpad::MinidumpThread; using google_breakpad::MinidumpThreadList; using google_breakpad::SynthMinidump::Context; using google_breakpad::SynthMinidump::Dump; using google_breakpad::SynthMinidump::Exception; using google_breakpad::SynthMinidump::Memory; using google_breakpad::SynthMinidump::Module; using google_breakpad::SynthMinidump::Stream; using google_breakpad::SynthMinidump::String; using google_breakpad::SynthMinidump::SystemInfo; using google_breakpad::SynthMinidump::Thread; using google_breakpad::test_assembler::kBigEndian; using google_breakpad::test_assembler::kLittleEndian; using std::ifstream; using std::istringstream; using std::vector; using ::testing::Return; class MinidumpTest : public ::testing::Test { public: void SetUp() { minidump_file_ = string(getenv("srcdir") ? getenv("srcdir") : ".") + "/src/processor/testdata/minidump2.dmp"; } string minidump_file_; }; TEST_F(MinidumpTest, TestMinidumpFromFile) { Minidump minidump(minidump_file_); ASSERT_EQ(minidump.path(), minidump_file_); ASSERT_TRUE(minidump.Read()); const MDRawHeader* header = minidump.header(); ASSERT_NE(header, (MDRawHeader*)NULL); ASSERT_EQ(header->signature, u_int32_t(MD_HEADER_SIGNATURE)); //TODO: add more checks here } TEST_F(MinidumpTest, TestMinidumpFromStream) { // read minidump contents into memory, construct a stringstream around them ifstream file_stream(minidump_file_.c_str(), std::ios::in); ASSERT_TRUE(file_stream.good()); vector<char> bytes; file_stream.seekg(0, std::ios_base::end); ASSERT_TRUE(file_stream.good()); bytes.resize(file_stream.tellg()); file_stream.seekg(0, std::ios_base::beg); ASSERT_TRUE(file_stream.good()); file_stream.read(&bytes[0], bytes.size()); ASSERT_TRUE(file_stream.good()); string str(&bytes[0], bytes.size()); istringstream stream(str); ASSERT_TRUE(stream.good()); // now read minidump from stringstream Minidump minidump(stream); ASSERT_EQ(minidump.path(), ""); ASSERT_TRUE(minidump.Read()); const MDRawHeader* header = minidump.header(); ASSERT_NE(header, (MDRawHeader*)NULL); ASSERT_EQ(header->signature, u_int32_t(MD_HEADER_SIGNATURE)); //TODO: add more checks here } TEST(Dump, ReadBackEmpty) { Dump dump(0); dump.Finish(); string contents; ASSERT_TRUE(dump.GetContents(&contents)); istringstream stream(contents); Minidump minidump(stream); ASSERT_TRUE(minidump.Read()); ASSERT_EQ(0U, minidump.GetDirectoryEntryCount()); } TEST(Dump, ReadBackEmptyBigEndian) { Dump big_minidump(0, kBigEndian); big_minidump.Finish(); string contents; ASSERT_TRUE(big_minidump.GetContents(&contents)); istringstream stream(contents); Minidump minidump(stream); ASSERT_TRUE(minidump.Read()); ASSERT_EQ(0U, minidump.GetDirectoryEntryCount()); } TEST(Dump, OneStream) { Dump dump(0, kBigEndian); Stream stream(dump, 0xfbb7fa2bU); stream.Append("stream contents"); dump.Add(&stream); dump.Finish(); string contents; ASSERT_TRUE(dump.GetContents(&contents)); istringstream minidump_stream(contents); Minidump minidump(minidump_stream); ASSERT_TRUE(minidump.Read()); ASSERT_EQ(1U, minidump.GetDirectoryEntryCount()); const MDRawDirectory *dir = minidump.GetDirectoryEntryAtIndex(0); ASSERT_TRUE(dir != NULL); EXPECT_EQ(0xfbb7fa2bU, dir->stream_type); u_int32_t stream_length; ASSERT_TRUE(minidump.SeekToStreamType(0xfbb7fa2bU, &stream_length)); ASSERT_EQ(15U, stream_length); char stream_contents[15]; ASSERT_TRUE(minidump.ReadBytes(stream_contents, sizeof(stream_contents))); EXPECT_EQ(string("stream contents"), string(stream_contents, sizeof(stream_contents))); EXPECT_FALSE(minidump.GetThreadList()); EXPECT_FALSE(minidump.GetModuleList()); EXPECT_FALSE(minidump.GetMemoryList()); EXPECT_FALSE(minidump.GetException()); EXPECT_FALSE(minidump.GetAssertion()); EXPECT_FALSE(minidump.GetSystemInfo()); EXPECT_FALSE(minidump.GetMiscInfo()); EXPECT_FALSE(minidump.GetBreakpadInfo()); } TEST(Dump, OneMemory) { Dump dump(0, kBigEndian); Memory memory(dump, 0x309d68010bd21b2cULL); memory.Append("memory contents"); dump.Add(&memory); dump.Finish(); string contents; ASSERT_TRUE(dump.GetContents(&contents)); istringstream minidump_stream(contents); Minidump minidump(minidump_stream); ASSERT_TRUE(minidump.Read()); ASSERT_EQ(1U, minidump.GetDirectoryEntryCount()); const MDRawDirectory *dir = minidump.GetDirectoryEntryAtIndex(0); ASSERT_TRUE(dir != NULL); EXPECT_EQ((u_int32_t) MD_MEMORY_LIST_STREAM, dir->stream_type); MinidumpMemoryList *memory_list = minidump.GetMemoryList(); ASSERT_TRUE(memory_list != NULL); ASSERT_EQ(1U, memory_list->region_count()); MinidumpMemoryRegion *region1 = memory_list->GetMemoryRegionAtIndex(0); ASSERT_EQ(0x309d68010bd21b2cULL, region1->GetBase()); ASSERT_EQ(15U, region1->GetSize()); const u_int8_t *region1_bytes = region1->GetMemory(); ASSERT_TRUE(memcmp("memory contents", region1_bytes, 15) == 0); } // One thread --- and its requisite entourage. TEST(Dump, OneThread) { Dump dump(0, kLittleEndian); Memory stack(dump, 0x2326a0fa); stack.Append("stack for thread"); MDRawContextX86 raw_context; const u_int32_t kExpectedEIP = 0x6913f540; raw_context.context_flags = MD_CONTEXT_X86_INTEGER | MD_CONTEXT_X86_CONTROL; raw_context.edi = 0x3ecba80d; raw_context.esi = 0x382583b9; raw_context.ebx = 0x7fccc03f; raw_context.edx = 0xf62f8ec2; raw_context.ecx = 0x46a6a6a8; raw_context.eax = 0x6a5025e2; raw_context.ebp = 0xd9fabb4a; raw_context.eip = kExpectedEIP; raw_context.cs = 0xbffe6eda; raw_context.eflags = 0xb2ce1e2d; raw_context.esp = 0x659caaa4; raw_context.ss = 0x2e951ef7; Context context(dump, raw_context); Thread thread(dump, 0xa898f11b, stack, context, 0x9e39439f, 0x4abfc15f, 0xe499898a, 0x0d43e939dcfd0372ULL); dump.Add(&stack); dump.Add(&context); dump.Add(&thread); dump.Finish(); string contents; ASSERT_TRUE(dump.GetContents(&contents)); istringstream minidump_stream(contents); Minidump minidump(minidump_stream); ASSERT_TRUE(minidump.Read()); ASSERT_EQ(2U, minidump.GetDirectoryEntryCount()); MinidumpMemoryList *md_memory_list = minidump.GetMemoryList(); ASSERT_TRUE(md_memory_list != NULL); ASSERT_EQ(1U, md_memory_list->region_count()); MinidumpMemoryRegion *md_region = md_memory_list->GetMemoryRegionAtIndex(0); ASSERT_EQ(0x2326a0faU, md_region->GetBase()); ASSERT_EQ(16U, md_region->GetSize()); const u_int8_t *region_bytes = md_region->GetMemory(); ASSERT_TRUE(memcmp("stack for thread", region_bytes, 16) == 0); MinidumpThreadList *thread_list = minidump.GetThreadList(); ASSERT_TRUE(thread_list != NULL); ASSERT_EQ(1U, thread_list->thread_count()); MinidumpThread *md_thread = thread_list->GetThreadAtIndex(0); ASSERT_TRUE(md_thread != NULL); u_int32_t thread_id; ASSERT_TRUE(md_thread->GetThreadID(&thread_id)); ASSERT_EQ(0xa898f11bU, thread_id); MinidumpMemoryRegion *md_stack = md_thread->GetMemory(); ASSERT_TRUE(md_stack != NULL); ASSERT_EQ(0x2326a0faU, md_stack->GetBase()); ASSERT_EQ(16U, md_stack->GetSize()); const u_int8_t *md_stack_bytes = md_stack->GetMemory(); ASSERT_TRUE(memcmp("stack for thread", md_stack_bytes, 16) == 0); MinidumpContext *md_context = md_thread->GetContext(); ASSERT_TRUE(md_context != NULL); ASSERT_EQ((u_int32_t) MD_CONTEXT_X86, md_context->GetContextCPU()); u_int64_t eip; ASSERT_TRUE(md_context->GetInstructionPointer(&eip)); EXPECT_EQ(kExpectedEIP, eip); const MDRawContextX86 *md_raw_context = md_context->GetContextX86(); ASSERT_TRUE(md_raw_context != NULL); ASSERT_EQ((u_int32_t) (MD_CONTEXT_X86_INTEGER | MD_CONTEXT_X86_CONTROL), (md_raw_context->context_flags & (MD_CONTEXT_X86_INTEGER | MD_CONTEXT_X86_CONTROL))); EXPECT_EQ(0x3ecba80dU, raw_context.edi); EXPECT_EQ(0x382583b9U, raw_context.esi); EXPECT_EQ(0x7fccc03fU, raw_context.ebx); EXPECT_EQ(0xf62f8ec2U, raw_context.edx); EXPECT_EQ(0x46a6a6a8U, raw_context.ecx); EXPECT_EQ(0x6a5025e2U, raw_context.eax); EXPECT_EQ(0xd9fabb4aU, raw_context.ebp); EXPECT_EQ(kExpectedEIP, raw_context.eip); EXPECT_EQ(0xbffe6edaU, raw_context.cs); EXPECT_EQ(0xb2ce1e2dU, raw_context.eflags); EXPECT_EQ(0x659caaa4U, raw_context.esp); EXPECT_EQ(0x2e951ef7U, raw_context.ss); } TEST(Dump, ThreadMissingMemory) { Dump dump(0, kLittleEndian); Memory stack(dump, 0x2326a0fa); // Stack has no contents. MDRawContextX86 raw_context; memset(&raw_context, 0, sizeof(raw_context)); raw_context.context_flags = MD_CONTEXT_X86_INTEGER | MD_CONTEXT_X86_CONTROL; Context context(dump, raw_context); Thread thread(dump, 0xa898f11b, stack, context, 0x9e39439f, 0x4abfc15f, 0xe499898a, 0x0d43e939dcfd0372ULL); dump.Add(&stack); dump.Add(&context); dump.Add(&thread); dump.Finish(); string contents; ASSERT_TRUE(dump.GetContents(&contents)); istringstream minidump_stream(contents); Minidump minidump(minidump_stream); ASSERT_TRUE(minidump.Read()); ASSERT_EQ(2U, minidump.GetDirectoryEntryCount()); // This should succeed even though the thread has no stack memory. MinidumpThreadList* thread_list = minidump.GetThreadList(); ASSERT_TRUE(thread_list != NULL); ASSERT_EQ(1U, thread_list->thread_count()); MinidumpThread* md_thread = thread_list->GetThreadAtIndex(0); ASSERT_TRUE(md_thread != NULL); u_int32_t thread_id; ASSERT_TRUE(md_thread->GetThreadID(&thread_id)); ASSERT_EQ(0xa898f11bU, thread_id); MinidumpContext* md_context = md_thread->GetContext(); ASSERT_NE(reinterpret_cast<MinidumpContext*>(NULL), md_context); MinidumpMemoryRegion* md_stack = md_thread->GetMemory(); ASSERT_EQ(reinterpret_cast<MinidumpMemoryRegion*>(NULL), md_stack); } TEST(Dump, ThreadMissingContext) { Dump dump(0, kLittleEndian); Memory stack(dump, 0x2326a0fa); stack.Append("stack for thread"); // Context is empty. Context context(dump); Thread thread(dump, 0xa898f11b, stack, context, 0x9e39439f, 0x4abfc15f, 0xe499898a, 0x0d43e939dcfd0372ULL); dump.Add(&stack); dump.Add(&context); dump.Add(&thread); dump.Finish(); string contents; ASSERT_TRUE(dump.GetContents(&contents)); istringstream minidump_stream(contents); Minidump minidump(minidump_stream); ASSERT_TRUE(minidump.Read()); ASSERT_EQ(2U, minidump.GetDirectoryEntryCount()); // This should succeed even though the thread has no stack memory. MinidumpThreadList* thread_list = minidump.GetThreadList(); ASSERT_TRUE(thread_list != NULL); ASSERT_EQ(1U, thread_list->thread_count()); MinidumpThread* md_thread = thread_list->GetThreadAtIndex(0); ASSERT_TRUE(md_thread != NULL); u_int32_t thread_id; ASSERT_TRUE(md_thread->GetThreadID(&thread_id)); ASSERT_EQ(0xa898f11bU, thread_id); MinidumpMemoryRegion* md_stack = md_thread->GetMemory(); ASSERT_NE(reinterpret_cast<MinidumpMemoryRegion*>(NULL), md_stack); MinidumpContext* md_context = md_thread->GetContext(); ASSERT_EQ(reinterpret_cast<MinidumpContext*>(NULL), md_context); } TEST(Dump, OneModule) { static const MDVSFixedFileInfo fixed_file_info = { 0xb2fba33a, // signature 0x33d7a728, // struct_version 0x31afcb20, // file_version_hi 0xe51cdab1, // file_version_lo 0xd1ea6907, // product_version_hi 0x03032857, // product_version_lo 0x11bf71d7, // file_flags_mask 0x5fb8cdbf, // file_flags 0xe45d0d5d, // file_os 0x107d9562, // file_type 0x5a8844d4, // file_subtype 0xa8d30b20, // file_date_hi 0x651c3e4e // file_date_lo }; Dump dump(0, kBigEndian); String module_name(dump, "single module"); Module module(dump, 0xa90206ca83eb2852ULL, 0xada542bd, module_name, 0xb1054d2a, 0x34571371, fixed_file_info, // from synth_minidump_unittest_data.h NULL, NULL); dump.Add(&module); dump.Add(&module_name); dump.Finish(); string contents; ASSERT_TRUE(dump.GetContents(&contents)); istringstream minidump_stream(contents); Minidump minidump(minidump_stream); ASSERT_TRUE(minidump.Read()); ASSERT_EQ(1U, minidump.GetDirectoryEntryCount()); const MDRawDirectory *dir = minidump.GetDirectoryEntryAtIndex(0); ASSERT_TRUE(dir != NULL); EXPECT_EQ((u_int32_t) MD_MODULE_LIST_STREAM, dir->stream_type); MinidumpModuleList *md_module_list = minidump.GetModuleList(); ASSERT_TRUE(md_module_list != NULL); ASSERT_EQ(1U, md_module_list->module_count()); const MinidumpModule *md_module = md_module_list->GetModuleAtIndex(0); ASSERT_TRUE(md_module != NULL); ASSERT_EQ(0xa90206ca83eb2852ULL, md_module->base_address()); ASSERT_EQ(0xada542bd, md_module->size()); ASSERT_EQ("single module", md_module->code_file()); const MDRawModule *md_raw_module = md_module->module(); ASSERT_TRUE(md_raw_module != NULL); ASSERT_EQ(0xb1054d2aU, md_raw_module->time_date_stamp); ASSERT_EQ(0x34571371U, md_raw_module->checksum); ASSERT_TRUE(memcmp(&md_raw_module->version_info, &fixed_file_info, sizeof(fixed_file_info)) == 0); } TEST(Dump, OneSystemInfo) { Dump dump(0, kLittleEndian); String csd_version(dump, "Petulant Pierogi"); SystemInfo system_info(dump, SystemInfo::windows_x86, csd_version); dump.Add(&system_info); dump.Add(&csd_version); dump.Finish(); string contents; ASSERT_TRUE(dump.GetContents(&contents)); istringstream minidump_stream(contents); Minidump minidump(minidump_stream); ASSERT_TRUE(minidump.Read()); ASSERT_EQ(1U, minidump.GetDirectoryEntryCount()); const MDRawDirectory *dir = minidump.GetDirectoryEntryAtIndex(0); ASSERT_TRUE(dir != NULL); EXPECT_EQ((u_int32_t) MD_SYSTEM_INFO_STREAM, dir->stream_type); MinidumpSystemInfo *md_system_info = minidump.GetSystemInfo(); ASSERT_TRUE(md_system_info != NULL); ASSERT_EQ("windows", md_system_info->GetOS()); ASSERT_EQ("x86", md_system_info->GetCPU()); ASSERT_EQ("Petulant Pierogi", *md_system_info->GetCSDVersion()); ASSERT_EQ("GenuineIntel", *md_system_info->GetCPUVendor()); } TEST(Dump, BigDump) { Dump dump(0, kLittleEndian); // A SystemInfo stream. String csd_version(dump, "Munificent Macaque"); SystemInfo system_info(dump, SystemInfo::windows_x86, csd_version); dump.Add(&csd_version); dump.Add(&system_info); // Five threads! Memory stack0(dump, 0x70b9ebfc); stack0.Append("stack for thread zero"); MDRawContextX86 raw_context0; raw_context0.context_flags = MD_CONTEXT_X86_INTEGER; raw_context0.eip = 0xaf0709e4; Context context0(dump, raw_context0); Thread thread0(dump, 0xbbef4432, stack0, context0, 0xd0377e7b, 0xdb8eb0cf, 0xd73bc314, 0x09d357bac7f9a163ULL); dump.Add(&stack0); dump.Add(&context0); dump.Add(&thread0); Memory stack1(dump, 0xf988cc45); stack1.Append("stack for thread one"); MDRawContextX86 raw_context1; raw_context1.context_flags = MD_CONTEXT_X86_INTEGER; raw_context1.eip = 0xe4f56f81; Context context1(dump, raw_context1); Thread thread1(dump, 0x657c3f58, stack1, context1, 0xa68fa182, 0x6f3cf8dd, 0xe3a78ccf, 0x78cc84775e4534bbULL); dump.Add(&stack1); dump.Add(&context1); dump.Add(&thread1); Memory stack2(dump, 0xc8a92e7c); stack2.Append("stack for thread two"); MDRawContextX86 raw_context2; raw_context2.context_flags = MD_CONTEXT_X86_INTEGER; raw_context2.eip = 0xb336a438; Context context2(dump, raw_context2); Thread thread2(dump, 0xdf4b8a71, stack2, context2, 0x674c26b6, 0x445d7120, 0x7e700c56, 0xd89bf778e7793e17ULL); dump.Add(&stack2); dump.Add(&context2); dump.Add(&thread2); Memory stack3(dump, 0x36d08e08); stack3.Append("stack for thread three"); MDRawContextX86 raw_context3; raw_context3.context_flags = MD_CONTEXT_X86_INTEGER; raw_context3.eip = 0xdf99a60c; Context context3(dump, raw_context3); Thread thread3(dump, 0x86e6c341, stack3, context3, 0x32dc5c55, 0x17a2aba8, 0xe0cc75e7, 0xa46393994dae83aeULL); dump.Add(&stack3); dump.Add(&context3); dump.Add(&thread3); Memory stack4(dump, 0x1e0ab4fa); stack4.Append("stack for thread four"); MDRawContextX86 raw_context4; raw_context4.context_flags = MD_CONTEXT_X86_INTEGER; raw_context4.eip = 0xaa646267; Context context4(dump, raw_context4); Thread thread4(dump, 0x261a28d4, stack4, context4, 0x6ebd389e, 0xa0cd4759, 0x30168846, 0x164f650a0cf39d35ULL); dump.Add(&stack4); dump.Add(&context4); dump.Add(&thread4); // Three modules! String module1_name(dump, "module one"); Module module1(dump, 0xeb77da57b5d4cbdaULL, 0x83cd5a37, module1_name); dump.Add(&module1_name); dump.Add(&module1); String module2_name(dump, "module two"); Module module2(dump, 0x8675884adfe5ac90ULL, 0xb11e4ea3, module2_name); dump.Add(&module2_name); dump.Add(&module2); String module3_name(dump, "module three"); Module module3(dump, 0x95fc1544da321b6cULL, 0x7c2bf081, module3_name); dump.Add(&module3_name); dump.Add(&module3); // Add one more memory region, on top of the five stacks. Memory memory5(dump, 0x61979e828040e564ULL); memory5.Append("contents of memory 5"); dump.Add(&memory5); dump.Finish(); string contents; ASSERT_TRUE(dump.GetContents(&contents)); istringstream minidump_stream(contents); Minidump minidump(minidump_stream); ASSERT_TRUE(minidump.Read()); ASSERT_EQ(4U, minidump.GetDirectoryEntryCount()); // Check the threads. MinidumpThreadList *thread_list = minidump.GetThreadList(); ASSERT_TRUE(thread_list != NULL); ASSERT_EQ(5U, thread_list->thread_count()); u_int32_t thread_id; ASSERT_TRUE(thread_list->GetThreadAtIndex(0)->GetThreadID(&thread_id)); ASSERT_EQ(0xbbef4432U, thread_id); ASSERT_EQ(0x70b9ebfcU, thread_list->GetThreadAtIndex(0)->GetMemory()->GetBase()); ASSERT_EQ(0xaf0709e4U, thread_list->GetThreadAtIndex(0)->GetContext()->GetContextX86() ->eip); ASSERT_TRUE(thread_list->GetThreadAtIndex(1)->GetThreadID(&thread_id)); ASSERT_EQ(0x657c3f58U, thread_id); ASSERT_EQ(0xf988cc45U, thread_list->GetThreadAtIndex(1)->GetMemory()->GetBase()); ASSERT_EQ(0xe4f56f81U, thread_list->GetThreadAtIndex(1)->GetContext()->GetContextX86() ->eip); ASSERT_TRUE(thread_list->GetThreadAtIndex(2)->GetThreadID(&thread_id)); ASSERT_EQ(0xdf4b8a71U, thread_id); ASSERT_EQ(0xc8a92e7cU, thread_list->GetThreadAtIndex(2)->GetMemory()->GetBase()); ASSERT_EQ(0xb336a438U, thread_list->GetThreadAtIndex(2)->GetContext()->GetContextX86() ->eip); ASSERT_TRUE(thread_list->GetThreadAtIndex(3)->GetThreadID(&thread_id)); ASSERT_EQ(0x86e6c341U, thread_id); ASSERT_EQ(0x36d08e08U, thread_list->GetThreadAtIndex(3)->GetMemory()->GetBase()); ASSERT_EQ(0xdf99a60cU, thread_list->GetThreadAtIndex(3)->GetContext()->GetContextX86() ->eip); ASSERT_TRUE(thread_list->GetThreadAtIndex(4)->GetThreadID(&thread_id)); ASSERT_EQ(0x261a28d4U, thread_id); ASSERT_EQ(0x1e0ab4faU, thread_list->GetThreadAtIndex(4)->GetMemory()->GetBase()); ASSERT_EQ(0xaa646267U, thread_list->GetThreadAtIndex(4)->GetContext()->GetContextX86() ->eip); // Check the modules. MinidumpModuleList *md_module_list = minidump.GetModuleList(); ASSERT_TRUE(md_module_list != NULL); ASSERT_EQ(3U, md_module_list->module_count()); EXPECT_EQ(0xeb77da57b5d4cbdaULL, md_module_list->GetModuleAtIndex(0)->base_address()); EXPECT_EQ(0x8675884adfe5ac90ULL, md_module_list->GetModuleAtIndex(1)->base_address()); EXPECT_EQ(0x95fc1544da321b6cULL, md_module_list->GetModuleAtIndex(2)->base_address()); } TEST(Dump, OneMemoryInfo) { Dump dump(0, kBigEndian); Stream stream(dump, MD_MEMORY_INFO_LIST_STREAM); // Add the MDRawMemoryInfoList header. const u_int64_t kNumberOfEntries = 1; stream.D32(sizeof(MDRawMemoryInfoList)) // size_of_header .D32(sizeof(MDRawMemoryInfo)) // size_of_entry .D64(kNumberOfEntries); // number_of_entries // Now add a MDRawMemoryInfo entry. const u_int64_t kBaseAddress = 0x1000; const u_int64_t kRegionSize = 0x2000; stream.D64(kBaseAddress) // base_address .D64(kBaseAddress) // allocation_base .D32(MD_MEMORY_PROTECT_EXECUTE_READWRITE) // allocation_protection .D32(0) // __alignment1 .D64(kRegionSize) // region_size .D32(MD_MEMORY_STATE_COMMIT) // state .D32(MD_MEMORY_PROTECT_EXECUTE_READWRITE) // protection .D32(MD_MEMORY_TYPE_PRIVATE) // type .D32(0); // __alignment2 dump.Add(&stream); dump.Finish(); string contents; ASSERT_TRUE(dump.GetContents(&contents)); istringstream minidump_stream(contents); Minidump minidump(minidump_stream); ASSERT_TRUE(minidump.Read()); ASSERT_EQ(1U, minidump.GetDirectoryEntryCount()); const MDRawDirectory *dir = minidump.GetDirectoryEntryAtIndex(0); ASSERT_TRUE(dir != NULL); EXPECT_EQ((u_int32_t) MD_MEMORY_INFO_LIST_STREAM, dir->stream_type); MinidumpMemoryInfoList *info_list = minidump.GetMemoryInfoList(); ASSERT_TRUE(info_list != NULL); ASSERT_EQ(1U, info_list->info_count()); const MinidumpMemoryInfo *info1 = info_list->GetMemoryInfoAtIndex(0); ASSERT_EQ(kBaseAddress, info1->GetBase()); ASSERT_EQ(kRegionSize, info1->GetSize()); ASSERT_TRUE(info1->IsExecutable()); ASSERT_TRUE(info1->IsWritable()); // Should get back the same memory region here. const MinidumpMemoryInfo *info2 = info_list->GetMemoryInfoForAddress(kBaseAddress + kRegionSize / 2); ASSERT_EQ(kBaseAddress, info2->GetBase()); ASSERT_EQ(kRegionSize, info2->GetSize()); } TEST(Dump, OneExceptionX86) { Dump dump(0, kLittleEndian); MDRawContextX86 raw_context; raw_context.context_flags = MD_CONTEXT_X86_INTEGER | MD_CONTEXT_X86_CONTROL; raw_context.edi = 0x3ecba80d; raw_context.esi = 0x382583b9; raw_context.ebx = 0x7fccc03f; raw_context.edx = 0xf62f8ec2; raw_context.ecx = 0x46a6a6a8; raw_context.eax = 0x6a5025e2; raw_context.ebp = 0xd9fabb4a; raw_context.eip = 0x6913f540; raw_context.cs = 0xbffe6eda; raw_context.eflags = 0xb2ce1e2d; raw_context.esp = 0x659caaa4; raw_context.ss = 0x2e951ef7; Context context(dump, raw_context); Exception exception(dump, context, 0x1234abcd, // thread id 0xdcba4321, // exception code 0xf0e0d0c0, // exception flags 0x0919a9b9c9d9e9f9ULL); // exception address dump.Add(&context); dump.Add(&exception); dump.Finish(); string contents; ASSERT_TRUE(dump.GetContents(&contents)); istringstream minidump_stream(contents); Minidump minidump(minidump_stream); ASSERT_TRUE(minidump.Read()); ASSERT_EQ(1U, minidump.GetDirectoryEntryCount()); MinidumpException *md_exception = minidump.GetException(); ASSERT_TRUE(md_exception != NULL); u_int32_t thread_id; ASSERT_TRUE(md_exception->GetThreadID(&thread_id)); ASSERT_EQ(0x1234abcdU, thread_id); const MDRawExceptionStream* raw_exception = md_exception->exception(); ASSERT_TRUE(raw_exception != NULL); EXPECT_EQ(0xdcba4321, raw_exception->exception_record.exception_code); EXPECT_EQ(0xf0e0d0c0, raw_exception->exception_record.exception_flags); EXPECT_EQ(0x0919a9b9c9d9e9f9ULL, raw_exception->exception_record.exception_address); MinidumpContext *md_context = md_exception->GetContext(); ASSERT_TRUE(md_context != NULL); ASSERT_EQ((u_int32_t) MD_CONTEXT_X86, md_context->GetContextCPU()); const MDRawContextX86 *md_raw_context = md_context->GetContextX86(); ASSERT_TRUE(md_raw_context != NULL); ASSERT_EQ((u_int32_t) (MD_CONTEXT_X86_INTEGER | MD_CONTEXT_X86_CONTROL), (md_raw_context->context_flags & (MD_CONTEXT_X86_INTEGER | MD_CONTEXT_X86_CONTROL))); EXPECT_EQ(0x3ecba80dU, raw_context.edi); EXPECT_EQ(0x382583b9U, raw_context.esi); EXPECT_EQ(0x7fccc03fU, raw_context.ebx); EXPECT_EQ(0xf62f8ec2U, raw_context.edx); EXPECT_EQ(0x46a6a6a8U, raw_context.ecx); EXPECT_EQ(0x6a5025e2U, raw_context.eax); EXPECT_EQ(0xd9fabb4aU, raw_context.ebp); EXPECT_EQ(0x6913f540U, raw_context.eip); EXPECT_EQ(0xbffe6edaU, raw_context.cs); EXPECT_EQ(0xb2ce1e2dU, raw_context.eflags); EXPECT_EQ(0x659caaa4U, raw_context.esp); EXPECT_EQ(0x2e951ef7U, raw_context.ss); } TEST(Dump, OneExceptionX86XState) { Dump dump(0, kLittleEndian); MDRawContextX86 raw_context; raw_context.context_flags = MD_CONTEXT_X86_INTEGER | MD_CONTEXT_X86_CONTROL | MD_CONTEXT_X86_XSTATE; raw_context.edi = 0x3ecba80d; raw_context.esi = 0x382583b9; raw_context.ebx = 0x7fccc03f; raw_context.edx = 0xf62f8ec2; raw_context.ecx = 0x46a6a6a8; raw_context.eax = 0x6a5025e2; raw_context.ebp = 0xd9fabb4a; raw_context.eip = 0x6913f540; raw_context.cs = 0xbffe6eda; raw_context.eflags = 0xb2ce1e2d; raw_context.esp = 0x659caaa4; raw_context.ss = 0x2e951ef7; Context context(dump, raw_context); Exception exception(dump, context, 0x1234abcd, // thread id 0xdcba4321, // exception code 0xf0e0d0c0, // exception flags 0x0919a9b9c9d9e9f9ULL); // exception address dump.Add(&context); dump.Add(&exception); dump.Finish(); string contents; ASSERT_TRUE(dump.GetContents(&contents)); istringstream minidump_stream(contents); Minidump minidump(minidump_stream); ASSERT_TRUE(minidump.Read()); ASSERT_EQ(1U, minidump.GetDirectoryEntryCount()); MinidumpException *md_exception = minidump.GetException(); ASSERT_TRUE(md_exception != NULL); u_int32_t thread_id; ASSERT_TRUE(md_exception->GetThreadID(&thread_id)); ASSERT_EQ(0x1234abcdU, thread_id); const MDRawExceptionStream* raw_exception = md_exception->exception(); ASSERT_TRUE(raw_exception != NULL); EXPECT_EQ(0xdcba4321, raw_exception->exception_record.exception_code); EXPECT_EQ(0xf0e0d0c0, raw_exception->exception_record.exception_flags); EXPECT_EQ(0x0919a9b9c9d9e9f9ULL, raw_exception->exception_record.exception_address); MinidumpContext *md_context = md_exception->GetContext(); ASSERT_TRUE(md_context != NULL); ASSERT_EQ((u_int32_t) MD_CONTEXT_X86, md_context->GetContextCPU()); const MDRawContextX86 *md_raw_context = md_context->GetContextX86(); ASSERT_TRUE(md_raw_context != NULL); ASSERT_EQ((u_int32_t) (MD_CONTEXT_X86_INTEGER | MD_CONTEXT_X86_CONTROL), (md_raw_context->context_flags & (MD_CONTEXT_X86_INTEGER | MD_CONTEXT_X86_CONTROL))); EXPECT_EQ(0x3ecba80dU, raw_context.edi); EXPECT_EQ(0x382583b9U, raw_context.esi); EXPECT_EQ(0x7fccc03fU, raw_context.ebx); EXPECT_EQ(0xf62f8ec2U, raw_context.edx); EXPECT_EQ(0x46a6a6a8U, raw_context.ecx); EXPECT_EQ(0x6a5025e2U, raw_context.eax); EXPECT_EQ(0xd9fabb4aU, raw_context.ebp); EXPECT_EQ(0x6913f540U, raw_context.eip); EXPECT_EQ(0xbffe6edaU, raw_context.cs); EXPECT_EQ(0xb2ce1e2dU, raw_context.eflags); EXPECT_EQ(0x659caaa4U, raw_context.esp); EXPECT_EQ(0x2e951ef7U, raw_context.ss); } TEST(Dump, OneExceptionARM) { Dump dump(0, kLittleEndian); MDRawContextARM raw_context; raw_context.context_flags = MD_CONTEXT_ARM_INTEGER; raw_context.iregs[0] = 0x3ecba80d; raw_context.iregs[1] = 0x382583b9; raw_context.iregs[2] = 0x7fccc03f; raw_context.iregs[3] = 0xf62f8ec2; raw_context.iregs[4] = 0x46a6a6a8; raw_context.iregs[5] = 0x6a5025e2; raw_context.iregs[6] = 0xd9fabb4a; raw_context.iregs[7] = 0x6913f540; raw_context.iregs[8] = 0xbffe6eda; raw_context.iregs[9] = 0xb2ce1e2d; raw_context.iregs[10] = 0x659caaa4; raw_context.iregs[11] = 0xf0e0d0c0; raw_context.iregs[12] = 0xa9b8c7d6; raw_context.iregs[13] = 0x12345678; raw_context.iregs[14] = 0xabcd1234; raw_context.iregs[15] = 0x10203040; raw_context.cpsr = 0x2e951ef7; Context context(dump, raw_context); Exception exception(dump, context, 0x1234abcd, // thread id 0xdcba4321, // exception code 0xf0e0d0c0, // exception flags 0x0919a9b9c9d9e9f9ULL); // exception address dump.Add(&context); dump.Add(&exception); dump.Finish(); string contents; ASSERT_TRUE(dump.GetContents(&contents)); istringstream minidump_stream(contents); Minidump minidump(minidump_stream); ASSERT_TRUE(minidump.Read()); ASSERT_EQ(1U, minidump.GetDirectoryEntryCount()); MinidumpException *md_exception = minidump.GetException(); ASSERT_TRUE(md_exception != NULL); u_int32_t thread_id; ASSERT_TRUE(md_exception->GetThreadID(&thread_id)); ASSERT_EQ(0x1234abcdU, thread_id); const MDRawExceptionStream* raw_exception = md_exception->exception(); ASSERT_TRUE(raw_exception != NULL); EXPECT_EQ(0xdcba4321, raw_exception->exception_record.exception_code); EXPECT_EQ(0xf0e0d0c0, raw_exception->exception_record.exception_flags); EXPECT_EQ(0x0919a9b9c9d9e9f9ULL, raw_exception->exception_record.exception_address); MinidumpContext *md_context = md_exception->GetContext(); ASSERT_TRUE(md_context != NULL); ASSERT_EQ((u_int32_t) MD_CONTEXT_ARM, md_context->GetContextCPU()); const MDRawContextARM *md_raw_context = md_context->GetContextARM(); ASSERT_TRUE(md_raw_context != NULL); ASSERT_EQ((u_int32_t) MD_CONTEXT_ARM_INTEGER, (md_raw_context->context_flags & MD_CONTEXT_ARM_INTEGER)); EXPECT_EQ(0x3ecba80dU, raw_context.iregs[0]); EXPECT_EQ(0x382583b9U, raw_context.iregs[1]); EXPECT_EQ(0x7fccc03fU, raw_context.iregs[2]); EXPECT_EQ(0xf62f8ec2U, raw_context.iregs[3]); EXPECT_EQ(0x46a6a6a8U, raw_context.iregs[4]); EXPECT_EQ(0x6a5025e2U, raw_context.iregs[5]); EXPECT_EQ(0xd9fabb4aU, raw_context.iregs[6]); EXPECT_EQ(0x6913f540U, raw_context.iregs[7]); EXPECT_EQ(0xbffe6edaU, raw_context.iregs[8]); EXPECT_EQ(0xb2ce1e2dU, raw_context.iregs[9]); EXPECT_EQ(0x659caaa4U, raw_context.iregs[10]); EXPECT_EQ(0xf0e0d0c0U, raw_context.iregs[11]); EXPECT_EQ(0xa9b8c7d6U, raw_context.iregs[12]); EXPECT_EQ(0x12345678U, raw_context.iregs[13]); EXPECT_EQ(0xabcd1234U, raw_context.iregs[14]); EXPECT_EQ(0x10203040U, raw_context.iregs[15]); EXPECT_EQ(0x2e951ef7U, raw_context.cpsr); } TEST(Dump, OneExceptionARMOldFlags) { Dump dump(0, kLittleEndian); MDRawContextARM raw_context; // MD_CONTEXT_ARM_INTEGER, but with _OLD raw_context.context_flags = MD_CONTEXT_ARM_OLD | 0x00000002; raw_context.iregs[0] = 0x3ecba80d; raw_context.iregs[1] = 0x382583b9; raw_context.iregs[2] = 0x7fccc03f; raw_context.iregs[3] = 0xf62f8ec2; raw_context.iregs[4] = 0x46a6a6a8; raw_context.iregs[5] = 0x6a5025e2; raw_context.iregs[6] = 0xd9fabb4a; raw_context.iregs[7] = 0x6913f540; raw_context.iregs[8] = 0xbffe6eda; raw_context.iregs[9] = 0xb2ce1e2d; raw_context.iregs[10] = 0x659caaa4; raw_context.iregs[11] = 0xf0e0d0c0; raw_context.iregs[12] = 0xa9b8c7d6; raw_context.iregs[13] = 0x12345678; raw_context.iregs[14] = 0xabcd1234; raw_context.iregs[15] = 0x10203040; raw_context.cpsr = 0x2e951ef7; Context context(dump, raw_context); Exception exception(dump, context, 0x1234abcd, // thread id 0xdcba4321, // exception code 0xf0e0d0c0, // exception flags 0x0919a9b9c9d9e9f9ULL); // exception address dump.Add(&context); dump.Add(&exception); dump.Finish(); string contents; ASSERT_TRUE(dump.GetContents(&contents)); istringstream minidump_stream(contents); Minidump minidump(minidump_stream); ASSERT_TRUE(minidump.Read()); ASSERT_EQ(1U, minidump.GetDirectoryEntryCount()); MinidumpException *md_exception = minidump.GetException(); ASSERT_TRUE(md_exception != NULL); u_int32_t thread_id; ASSERT_TRUE(md_exception->GetThreadID(&thread_id)); ASSERT_EQ(0x1234abcdU, thread_id); const MDRawExceptionStream* raw_exception = md_exception->exception(); ASSERT_TRUE(raw_exception != NULL); EXPECT_EQ(0xdcba4321, raw_exception->exception_record.exception_code); EXPECT_EQ(0xf0e0d0c0, raw_exception->exception_record.exception_flags); EXPECT_EQ(0x0919a9b9c9d9e9f9ULL, raw_exception->exception_record.exception_address); MinidumpContext *md_context = md_exception->GetContext(); ASSERT_TRUE(md_context != NULL); ASSERT_EQ((u_int32_t) MD_CONTEXT_ARM, md_context->GetContextCPU()); const MDRawContextARM *md_raw_context = md_context->GetContextARM(); ASSERT_TRUE(md_raw_context != NULL); ASSERT_EQ((u_int32_t) MD_CONTEXT_ARM_INTEGER, (md_raw_context->context_flags & MD_CONTEXT_ARM_INTEGER)); EXPECT_EQ(0x3ecba80dU, raw_context.iregs[0]); EXPECT_EQ(0x382583b9U, raw_context.iregs[1]); EXPECT_EQ(0x7fccc03fU, raw_context.iregs[2]); EXPECT_EQ(0xf62f8ec2U, raw_context.iregs[3]); EXPECT_EQ(0x46a6a6a8U, raw_context.iregs[4]); EXPECT_EQ(0x6a5025e2U, raw_context.iregs[5]); EXPECT_EQ(0xd9fabb4aU, raw_context.iregs[6]); EXPECT_EQ(0x6913f540U, raw_context.iregs[7]); EXPECT_EQ(0xbffe6edaU, raw_context.iregs[8]); EXPECT_EQ(0xb2ce1e2dU, raw_context.iregs[9]); EXPECT_EQ(0x659caaa4U, raw_context.iregs[10]); EXPECT_EQ(0xf0e0d0c0U, raw_context.iregs[11]); EXPECT_EQ(0xa9b8c7d6U, raw_context.iregs[12]); EXPECT_EQ(0x12345678U, raw_context.iregs[13]); EXPECT_EQ(0xabcd1234U, raw_context.iregs[14]); EXPECT_EQ(0x10203040U, raw_context.iregs[15]); EXPECT_EQ(0x2e951ef7U, raw_context.cpsr); } } // namespace
{'content_hash': 'f94f54cb89eb0e4ea499942621181f06', 'timestamp': '', 'source': 'github', 'line_count': 955, 'max_line_length': 78, 'avg_line_length': 36.30994764397906, 'alnum_prop': 0.6985234744491867, 'repo_name': 'mhoran/google-breakpad', 'id': '1faf169d5c2a5128982dd28aecbfcbf57613fd52', 'size': '36710', 'binary': False, 'copies': '2', 'ref': 'refs/heads/master', 'path': 'src/processor/minidump_unittest.cc', 'mode': '33188', 'license': 'bsd-3-clause', 'language': [{'name': 'Assembly', 'bytes': '7921'}, {'name': 'C', 'bytes': '1701689'}, {'name': 'C++', 'bytes': '6143738'}, {'name': 'Objective-C', 'bytes': '455134'}, {'name': 'Perl', 'bytes': '125'}, {'name': 'Prolog', 'bytes': '3262'}, {'name': 'Python', 'bytes': '447592'}, {'name': 'Ruby', 'bytes': '107'}, {'name': 'Shell', 'bytes': '565789'}]}
//====================================================================================================================// // File: qcan_server_memeory.hpp // // Description: QCAN classes - CAN server // // // // Copyright (C) MicroControl GmbH & Co. KG // // 53844 Troisdorf - Germany // // www.microcontrol.net // // // //--------------------------------------------------------------------------------------------------------------------// // Redistribution and use in source and binary forms, with or without modification, are permitted provided that the // // following conditions are met: // // 1. Redistributions of source code must retain the above copyright notice, this list of conditions, the following // // disclaimer and the referenced file 'LICENSE'. // // 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the // // following disclaimer in the documentation and/or other materials provided with the distribution. // // 3. Neither the name of MicroControl nor the names of its contributors may be used to endorse or promote products // // derived from this software without specific prior written permission. // // // // 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. // // // //====================================================================================================================// /*--------------------------------------------------------------------------------------------------------------------*\ ** Include files ** ** ** \*--------------------------------------------------------------------------------------------------------------------*/ #include "qcan_defs.hpp" /*--------------------------------------------------------------------------------------------------------------------*\ ** Definitions ** ** ** \*--------------------------------------------------------------------------------------------------------------------*/ #define QCAN_MEMORY_KEY "QCAN_SERVER_SHARED_KEY" /*--------------------------------------------------------------------------------------------------------------------*\ ** Structures ** ** ** \*--------------------------------------------------------------------------------------------------------------------*/ typedef struct Server_s { uint32_t ulVersionMajor; uint32_t ulVersionMinor; } Server_ts; typedef struct Network_s { uint32_t ulVersionMajor; uint32_t ulVersionMinor; } Network_ts; typedef struct ServerSettings_s { Server_ts tsServer; Network_ts atsNetwork[QCAN_NETWORK_MAX]; } ServerSettings_ts;
{'content_hash': '788a0242d048df14435187c11527b5aa', 'timestamp': '', 'source': 'github', 'line_count': 64, 'max_line_length': 120, 'avg_line_length': 82.03125, 'alnum_prop': 0.27390476190476193, 'repo_name': 'JoTid/CANpie', 'id': '4f6e40cb83b578d82ad00dca3ad4767a7bcfa101', 'size': '5250', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'source/qcan/qcan_server_memory.hpp', 'mode': '33188', 'license': 'apache-2.0', 'language': [{'name': 'Batchfile', 'bytes': '1816'}, {'name': 'C', 'bytes': '580757'}, {'name': 'C++', 'bytes': '1054376'}, {'name': 'Makefile', 'bytes': '16403'}, {'name': 'Objective-C', 'bytes': '47189'}, {'name': 'Prolog', 'bytes': '1153'}, {'name': 'QMake', 'bytes': '55893'}, {'name': 'Shell', 'bytes': '848'}]}
[react-babylonjs](../README.md) / [Exports](../modules.md) / loaders # Module: loaders ## Table of contents ### Enumerations - [LoaderStatus](../enums/loaders.loaderstatus.md) - [TaskType](../enums/loaders.tasktype.md) ### Classes - [LoadedModel](../classes/loaders.loadedmodel.md) ### Interfaces - [ILoadedModel](../interfaces/loaders.iloadedmodel.md) ### Type aliases - [AssetManagerContextProviderProps](loaders.md#assetmanagercontextproviderprops) - [AssetManagerContextType](loaders.md#assetmanagercontexttype) - [AssetManagerOptions](loaders.md#assetmanageroptions) - [AssetManagerProgressType](loaders.md#assetmanagerprogresstype) - [BinaryTask](loaders.md#binarytask) - [MeshTask](loaders.md#meshtask) - [SceneLoaderContextProviderProps](loaders.md#sceneloadercontextproviderprops) - [SceneLoaderContextType](loaders.md#sceneloadercontexttype) - [SceneLoaderOptions](loaders.md#sceneloaderoptions) - [Task](loaders.md#task) - [TextureTask](loaders.md#texturetask) ### Variables - [AssetManagerContext](loaders.md#assetmanagercontext) - [AssetManagerContextProvider](loaders.md#assetmanagercontextprovider) - [SceneLoaderContext](loaders.md#sceneloadercontext) - [SceneLoaderContextProvider](loaders.md#sceneloadercontextprovider) ### Functions - [useAssetManager](loaders.md#useassetmanager) - [useSceneLoader](loaders.md#usesceneloader) ## Type aliases ### AssetManagerContextProviderProps Ƭ **AssetManagerContextProviderProps**: { `children`: React.ReactNode ; `startProgress?`: [*AssetManagerProgressType*](loaders_useassetmanager.md#assetmanagerprogresstype) } #### Type declaration: Name | Type | ------ | ------ | `children` | React.ReactNode | `startProgress?` | [*AssetManagerProgressType*](loaders_useassetmanager.md#assetmanagerprogresstype) | Defined in: [loaders/useAssetManager.tsx:48](https://github.com/brianzinn/react-babylonjs/blob/eba7b00/src/hooks/loaders/useAssetManager.tsx#L48) ___ ### AssetManagerContextType Ƭ **AssetManagerContextType**: { `lastProgress?`: [*AssetManagerProgressType*](loaders_useassetmanager.md#assetmanagerprogresstype) ; `updateProgress`: (`progress`: [*AssetManagerProgressType*](loaders_useassetmanager.md#assetmanagerprogresstype)) => *void* } \| *undefined* Defined in: [loaders/useAssetManager.tsx:36](https://github.com/brianzinn/react-babylonjs/blob/eba7b00/src/hooks/loaders/useAssetManager.tsx#L36) ___ ### AssetManagerOptions Ƭ **AssetManagerOptions**: { `reportProgress?`: *boolean* ; `scene?`: Scene ; `useDefaultLoadingScreen?`: *boolean* } #### Type declaration: Name | Type | ------ | ------ | `reportProgress?` | *boolean* | `scene?` | Scene | `useDefaultLoadingScreen?` | *boolean* | Defined in: [loaders/useAssetManager.tsx:61](https://github.com/brianzinn/react-babylonjs/blob/eba7b00/src/hooks/loaders/useAssetManager.tsx#L61) ___ ### AssetManagerProgressType Ƭ **AssetManagerProgressType**: { `eventData`: IAssetsProgressEvent ; `eventState`: EventState } \| *undefined* Defined in: [loaders/useAssetManager.tsx:43](https://github.com/brianzinn/react-babylonjs/blob/eba7b00/src/hooks/loaders/useAssetManager.tsx#L43) ___ ### BinaryTask Ƭ **BinaryTask**: { `name`: *string* ; `taskType`: [*Binary*](../enums/loaders/useassetmanager.tasktype.md#binary) ; `url`: *string* } #### Type declaration: Name | Type | ------ | ------ | `name` | *string* | `taskType` | [*Binary*](../enums/loaders/useassetmanager.tasktype.md#binary) | `url` | *string* | Defined in: [loaders/useAssetManager.tsx:11](https://github.com/brianzinn/react-babylonjs/blob/eba7b00/src/hooks/loaders/useAssetManager.tsx#L11) ___ ### MeshTask Ƭ **MeshTask**: { `meshesNames?`: *any* ; `name`: *string* ; `rootUrl`: *string* ; `sceneFilename`: *string* ; `taskType`: [*Mesh*](../enums/loaders/useassetmanager.tasktype.md#mesh) } #### Type declaration: Name | Type | ------ | ------ | `meshesNames?` | *any* | `name` | *string* | `rootUrl` | *string* | `sceneFilename` | *string* | `taskType` | [*Mesh*](../enums/loaders/useassetmanager.tasktype.md#mesh) | Defined in: [loaders/useAssetManager.tsx:17](https://github.com/brianzinn/react-babylonjs/blob/eba7b00/src/hooks/loaders/useAssetManager.tsx#L17) ___ ### SceneLoaderContextProviderProps Ƭ **SceneLoaderContextProviderProps**: { `children`: React.ReactNode ; `startProgress?`: ISceneLoaderProgressEvent } #### Type declaration: Name | Type | ------ | ------ | `children` | React.ReactNode | `startProgress?` | ISceneLoaderProgressEvent | Defined in: [loaders/useSceneLoader.tsx:14](https://github.com/brianzinn/react-babylonjs/blob/eba7b00/src/hooks/loaders/useSceneLoader.tsx#L14) ___ ### SceneLoaderContextType Ƭ **SceneLoaderContextType**: { `lastProgress?`: *Nullable*<ISceneLoaderProgressEvent\> ; `updateProgress`: (`progress`: ISceneLoaderProgressEvent) => *void* } \| *undefined* Defined in: [loaders/useSceneLoader.tsx:7](https://github.com/brianzinn/react-babylonjs/blob/eba7b00/src/hooks/loaders/useSceneLoader.tsx#L7) ___ ### SceneLoaderOptions Ƭ **SceneLoaderOptions**: { `alwaysSelectAsActiveMesh?`: *boolean* ; `onModelLoaded?`: (`loadedModel`: [*ILoadedModel*](../interfaces/loaders/loadedmodel.iloadedmodel.md)) => *void* ; `receiveShadows?`: *boolean* ; `reportProgress?`: *boolean* ; `scaleToDimension?`: *number* ; `scene?`: Scene } #### Type declaration: Name | Type | Description | ------ | ------ | ------ | `alwaysSelectAsActiveMesh?` | *boolean* | Always select root mesh as active. Defaults to false. | `onModelLoaded?` | (`loadedModel`: [*ILoadedModel*](../interfaces/loaders/loadedmodel.iloadedmodel.md)) => *void* | Access to loaded model as soon as it is loaded, so it provides a way to hide or scale the meshes before the first render. | `receiveShadows?` | *boolean* | set that all meshes receive shadows. Defaults to false. | `reportProgress?` | *boolean* | SceneLoader progress events are set on context provider (when available). Defaults to false. | `scaleToDimension?` | *number* | Scale entire model within these square bounds Defaults to no scaling. | `scene?` | Scene | - | Defined in: [loaders/useSceneLoader.tsx:27](https://github.com/brianzinn/react-babylonjs/blob/eba7b00/src/hooks/loaders/useSceneLoader.tsx#L27) ___ ### Task Ƭ **Task**: [*BinaryTask*](loaders_useassetmanager.md#binarytask) \| [*MeshTask*](loaders_useassetmanager.md#meshtask) \| [*TextureTask*](loaders_useassetmanager.md#texturetask) Defined in: [loaders/useAssetManager.tsx:34](https://github.com/brianzinn/react-babylonjs/blob/eba7b00/src/hooks/loaders/useAssetManager.tsx#L34) ___ ### TextureTask Ƭ **TextureTask**: { `invertY?`: *boolean* ; `name`: *string* ; `noMipmap?`: *boolean* ; `samplingMode?`: *number* ; `taskType`: [*Texture*](../enums/loaders/useassetmanager.tasktype.md#texture) ; `url`: *string* } #### Type declaration: Name | Type | ------ | ------ | `invertY?` | *boolean* | `name` | *string* | `noMipmap?` | *boolean* | `samplingMode?` | *number* | `taskType` | [*Texture*](../enums/loaders/useassetmanager.tasktype.md#texture) | `url` | *string* | Defined in: [loaders/useAssetManager.tsx:25](https://github.com/brianzinn/react-babylonjs/blob/eba7b00/src/hooks/loaders/useAssetManager.tsx#L25) ## Variables ### AssetManagerContext • `Const` **AssetManagerContext**: *Context*<[*AssetManagerContextType*](loaders_useassetmanager.md#assetmanagercontexttype)\> Defined in: [loaders/useAssetManager.tsx:41](https://github.com/brianzinn/react-babylonjs/blob/eba7b00/src/hooks/loaders/useAssetManager.tsx#L41) ___ ### AssetManagerContextProvider • `Const` **AssetManagerContextProvider**: *React.FC*<[*AssetManagerContextProviderProps*](loaders_useassetmanager.md#assetmanagercontextproviderprops)\> Defined in: [loaders/useAssetManager.tsx:53](https://github.com/brianzinn/react-babylonjs/blob/eba7b00/src/hooks/loaders/useAssetManager.tsx#L53) ___ ### SceneLoaderContext • `Const` **SceneLoaderContext**: *Context*<[*SceneLoaderContextType*](loaders_usesceneloader.md#sceneloadercontexttype)\> Defined in: [loaders/useSceneLoader.tsx:12](https://github.com/brianzinn/react-babylonjs/blob/eba7b00/src/hooks/loaders/useSceneLoader.tsx#L12) ___ ### SceneLoaderContextProvider • `Const` **SceneLoaderContextProvider**: *React.FC*<[*SceneLoaderContextProviderProps*](loaders_usesceneloader.md#sceneloadercontextproviderprops)\> Defined in: [loaders/useSceneLoader.tsx:19](https://github.com/brianzinn/react-babylonjs/blob/eba7b00/src/hooks/loaders/useSceneLoader.tsx#L19) ## Functions ### useAssetManager ▸ `Const`**useAssetManager**(`tasks`: [*Task*](loaders_useassetmanager.md#task)[], `options?`: [*AssetManagerOptions*](loaders_useassetmanager.md#assetmanageroptions)): AssetManagerResult #### Parameters: Name | Type | ------ | ------ | `tasks` | [*Task*](loaders_useassetmanager.md#task)[] | `options?` | [*AssetManagerOptions*](loaders_useassetmanager.md#assetmanageroptions) | **Returns:** AssetManagerResult Defined in: [loaders/useAssetManager.tsx:249](https://github.com/brianzinn/react-babylonjs/blob/eba7b00/src/hooks/loaders/useAssetManager.tsx#L249) ___ ### useSceneLoader ▸ `Const`**useSceneLoader**(`rootUrl`: *string*, `sceneFilename`: *string*, `pluginExtension?`: *string*, `options?`: [*SceneLoaderOptions*](loaders_usesceneloader.md#sceneloaderoptions)): [*LoadedModel*](../classes/loaders/loadedmodel.loadedmodel.md) #### Parameters: Name | Type | ------ | ------ | `rootUrl` | *string* | `sceneFilename` | *string* | `pluginExtension?` | *string* | `options?` | [*SceneLoaderOptions*](loaders_usesceneloader.md#sceneloaderoptions) | **Returns:** [*LoadedModel*](../classes/loaders/loadedmodel.loadedmodel.md) Defined in: [loaders/useSceneLoader.tsx:202](https://github.com/brianzinn/react-babylonjs/blob/eba7b00/src/hooks/loaders/useSceneLoader.tsx#L202)
{'content_hash': 'efc4b738c896959586b0276690520833', 'timestamp': '', 'source': 'github', 'line_count': 262, 'max_line_length': 296, 'avg_line_length': 37.48091603053435, 'alnum_prop': 0.7344195519348269, 'repo_name': 'brianzinn/react-babylonJS', 'id': 'dec1387e403e9efd81620c5642b04ed3df2913ea', 'size': '9843', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'docs/hooks/modules/loaders.md', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'JavaScript', 'bytes': '1014'}, {'name': 'TypeScript', 'bytes': '24537'}]}
function SendChatMessage(...) end; function SendAddonMessage(...) end; function GetDefaultLanguage() return "Common"; end;
{'content_hash': 'b7f92922f981fb3896a0311358c8fdcc', 'timestamp': '', 'source': 'github', 'line_count': 9, 'max_line_length': 30, 'avg_line_length': 14.0, 'alnum_prop': 0.746031746031746, 'repo_name': 'Thonik/FritoMod', 'id': '752bbbd9051336f91963032e6e76ff3befa68dc4', 'size': '126', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'wow/api/Chat.lua', 'mode': '33188', 'license': 'mit', 'language': []}
package com.intellij.java.codeInsight.daemon; import com.intellij.JavaTestUtil; import com.intellij.codeInsight.daemon.DaemonAnalyzerTestCase; import com.intellij.codeInsight.daemon.impl.HighlightInfo; import com.intellij.codeInsight.intention.IntentionAction; import com.intellij.codeInspection.redundantCast.RedundantCastInspection; import com.intellij.lang.annotation.HighlightSeverity; import com.intellij.lang.java.JavaDocumentationProvider; import com.intellij.openapi.editor.Document; import com.intellij.openapi.editor.Editor; import com.intellij.openapi.editor.EditorFactory; import com.intellij.openapi.progress.EmptyProgressIndicator; import com.intellij.openapi.progress.ProgressManager; import com.intellij.openapi.project.Project; import com.intellij.openapi.util.Disposer; import com.intellij.psi.*; import com.intellij.psi.infos.CandidateInfo; import com.intellij.psi.search.searches.ReferencesSearch; import com.intellij.psi.util.PsiTreeUtil; import com.intellij.psi.util.TypeConversionUtil; import com.intellij.testFramework.fixtures.LightJavaCodeInsightFixtureTestCase; import com.intellij.testFramework.fixtures.impl.CodeInsightTestFixtureImpl; import com.intellij.util.ArrayUtilRt; import java.util.List; import static org.assertj.core.api.Assertions.assertThat; public class LightAdvHighlightingFixtureTest extends LightJavaCodeInsightFixtureTestCase { @Override protected String getBasePath() { return JavaTestUtil.getRelativeJavaTestDataPath() + "/codeInsight/daemonCodeAnalyzer/advFixture"; } public void testHidingOnDemandImports() { //noinspection StaticNonFinalField myFixture.addClass("package foo; public class Foo {" + " public static String foo;" + "}"); myFixture.addClass("package foo; public class Bar {" + " public static void foo(String s) {}" + "}"); myFixture.configureByFile(getTestName(false) + ".java"); myFixture.checkHighlighting(false, false, false); } public void testFilteredCandidates() { PsiFile file = myFixture.configureByText("a.java", "class a {{new StringBuilder().ap<caret>pend();}}"); PsiCallExpression callExpression = PsiTreeUtil.getParentOfType(file.findElementAt(myFixture.getEditor().getCaretModel().getOffset()), PsiCallExpression.class); assertNotNull(callExpression); CandidateInfo[] candidates = PsiResolveHelper.getInstance(myFixture.getProject()).getReferencedMethodCandidates(callExpression, false); assertSize(27, candidates); String generateDoc = new JavaDocumentationProvider().generateDoc(callExpression, callExpression); assertEquals("<html>Candidates for method call <b>new StringBuilder().append()</b> are:<br><br>&nbsp;&nbsp;" + "<a href=\"psi_element://java.lang.StringBuilder#append(java.lang.Object)\">StringBuilder append(Object)</a><br>&nbsp;&nbsp;" + "<a href=\"psi_element://java.lang.StringBuilder#append(java.lang.String)\">StringBuilder append(String)</a><br>&nbsp;&nbsp;" + "<a href=\"psi_element://java.lang.StringBuilder#append(java.lang.StringBuilder)\">StringBuilder append(StringBuilder)</a><br>&nbsp;&nbsp;" + "<a href=\"psi_element://java.lang.StringBuilder#append(java.lang.StringBuffer)\">StringBuilder append(StringBuffer)</a><br>&nbsp;&nbsp;" + "<a href=\"psi_element://java.lang.StringBuilder#append(java.lang.CharSequence)\">StringBuilder append(CharSequence)</a><br>&nbsp;&nbsp;" + "<a href=\"psi_element://java.lang.StringBuilder#append(java.lang.CharSequence, int, int)\">StringBuilder append(CharSequence, int, int)</a><br>&nbsp;&nbsp;" + "<a href=\"psi_element://java.lang.StringBuilder#append(char[])\">StringBuilder append(char[])</a><br>&nbsp;&nbsp;" + "<a href=\"psi_element://java.lang.StringBuilder#append(char[], int, int)\">StringBuilder append(char[], int, int)</a><br>&nbsp;&nbsp;" + "<a href=\"psi_element://java.lang.StringBuilder#append(boolean)\">StringBuilder append(boolean)</a><br>&nbsp;&nbsp;" + "<a href=\"psi_element://java.lang.StringBuilder#append(char)\">StringBuilder append(char)</a><br>&nbsp;&nbsp;" + "<a href=\"psi_element://java.lang.StringBuilder#append(int)\">StringBuilder append(int)</a><br>&nbsp;&nbsp;" + "<a href=\"psi_element://java.lang.StringBuilder#append(long)\">StringBuilder append(long)</a><br>&nbsp;&nbsp;" + "<a href=\"psi_element://java.lang.StringBuilder#append(float)\">StringBuilder append(float)</a><br>&nbsp;&nbsp;" + "<a href=\"psi_element://java.lang.StringBuilder#append(double)\">StringBuilder append(double)</a><br></html>", generateDoc); } public void testPackageNamedAsClassInDefaultPackage() { myFixture.addClass("package test; public class A {}"); PsiClass aClass = myFixture.addClass("public class test {}"); doTest(); assertNull(ProgressManager.getInstance().runProcess(() -> ReferencesSearch.search(aClass).findFirst(), new EmptyProgressIndicator())); } public void testPackageNameAsClassFQName() { myFixture.addClass("package foo.Bar; class A {}"); myFixture.addClass("package foo; public class Bar { public static class Inner {}}"); doTest(); } public void testInaccessibleFunctionalTypeParameter() { myFixture.addClass("package test; class A {}"); myFixture.addClass("package test; public interface I { void m(A a);}"); myFixture.addClass("package test; public interface J { A m();}"); doTest(); } public void testBoundsPromotionWithCapturedWildcards() { myFixture.addClass("package a; public interface Provider<A> {}"); myFixture.addClass("package b; public interface Provider<B> {}"); doTest(); } public void testStaticImportCompoundWithInheritance() { myFixture.addClass("package a; public interface A { static void foo(Object o){} static void foo(String str) {}}"); doTest(); } public void testSuppressedInGenerated() { myFixture.enableInspections(new RedundantCastInspection()); myFixture.addClass("package javax.annotation; public @interface Generated {}"); doTest(); } public void testReferenceThroughInheritance() { myFixture.addClass("package test;\n" + "public class A {\n" + " public static class B {}\n" + "}"); doTest(); } public void testReferenceThroughInheritance1() { //noinspection UnnecessaryInterfaceModifier myFixture.addClass("package me;\n" + "import me.Serializer.Format;\n" + "public interface Serializer<F extends Format> {\n" + " public static interface Format {}\n" + "}\n"); doTest(); } public void testUsageOfProtectedAnnotationOutsideAPackage() { myFixture.addClass("package a;\n" + "import java.lang.annotation.ElementType;\n" + "import java.lang.annotation.Target;\n" + "\n" + "public class A {\n" + " @Target( { ElementType.METHOD, ElementType.TYPE } )\n" + " protected @interface Test{\n" + " }\n" + "}"); doTest(); } public void testPackageLocalClassUsedInArrayTypeOutsidePackage() { myFixture.addClass("package a; class A {}"); myFixture.addClass("package a; public class B {public static A[] getAs() {return null;}}"); doTest(); } public void testProtectedFieldUsedInAnnotationParameterOfInheritor() { myFixture.addClass("package a; public class A {protected final static String A_FOO = \"A\";}"); doTest(); } public void testStaticImportClassConflictingWithPackageName() { myFixture.addClass("package p.P1; class Unrelated {}"); myFixture.addClass("package p; public class P1 {public static final int FOO = 1;}"); doTest(); } public void testAmbiguousMethodCallWhenStaticImported() { myFixture.addClass("package p;" + "class A<K> {\n" + " static <T> A<T> of(T t) {\n" + " return null;\n" + " }\n" + "}\n" + "class B<K> {\n" + " static <T> B<T> of(T t) {\n" + " return null;\n" + " }\n" + " static <T> B<T> of(T... t) {\n" + " return null;\n" + " }\n" + "}\n"); doTest(); } public void testClassPackageConflict() { myFixture.addClass("package a; public class b {}"); myFixture.addClass("package c; public class a {}"); doTest(); } public void testClassPackageConflict1() { myFixture.addClass("package a; public class b {}"); myFixture.addClass("package c.d; public class a {}"); doTest(); } public void testTypeAnnotations() { myFixture.addClass("import java.lang.annotation.ElementType;\n" + "import java.lang.annotation.Target;\n" + "@Target({ElementType.TYPE_USE})\n" + "@interface Nullable {}\n"); myFixture.addClass("class Middle<R> extends Base<@Nullable R, String>{}"); myFixture.addClass("class Child<R> extends Middle<R>{}"); PsiClass baseClass = myFixture.addClass("class Base<R, C> {}"); PsiClass fooClass = myFixture.addClass("class Foo {\n" + " Child<String> field;\n" + "}"); PsiField fooField = fooClass.findFieldByName("field", false); PsiType substituted = TypeConversionUtil.getSuperClassSubstitutor(baseClass, (PsiClassType)fooField.getType()).substitute(baseClass.getTypeParameters()[0]); assertEquals(1, substituted.getAnnotations().length); } public void testCodeFragmentMayAccessDefaultPackage() { myFixture.addClass("public class MainClass { }"); Project project = getProject(); PsiElement context = JavaPsiFacade.getInstance(project).findPackage(""); JavaCodeFragment fragment = JavaCodeFragmentFactory.getInstance(project).createReferenceCodeFragment("MainClass", context, true, true); Document document = PsiDocumentManager.getInstance(project).getDocument(fragment); Editor editor = EditorFactory.getInstance().createViewer(document, project); Disposer.register(myFixture.getTestRootDisposable(), () -> EditorFactory.getInstance().releaseEditor(editor)); List<HighlightInfo> highlights = CodeInsightTestFixtureImpl.instantiateAndRun(fragment, editor, ArrayUtilRt.EMPTY_INT_ARRAY, false); List<HighlightInfo> problems = DaemonAnalyzerTestCase.filter(highlights, HighlightSeverity.WARNING); assertThat(problems).isEmpty(); } public void testImplicitConstructorAccessibility() { myFixture.addClass("package a; public class Base {" + "private Base() {}\n" + "protected Base(int... i) {}\n" + "}"); doTest(); } public void testDiamondsWithAnonymousProtectedConstructor() { myFixture.addClass("package a; public class Base<T> { protected Base() {}}"); doTest(); } public void testDiamondsWithProtectedCallInConstruction() { myFixture.addClass("package a; public class Base { " + " protected String createString() {return null;}" + "}"); doTest(); } public void testDefaultAnnotationsApplicability() { myFixture.addClass("package foo; public @interface A {}"); myFixture.configureByFile("module-info.java"); myFixture.checkHighlighting(); } public void testAlwaysFalseForLoop() { doTest(); IntentionAction action = myFixture.findSingleIntention("Remove 'for' statement"); myFixture.launchAction(action); myFixture.checkResultByFile(getTestName(false) + "_after.java"); } public void testProtectedInnerClass() { myFixture.addClass("package a;\n" + "public class Outer {\n" + " public Object get(Inner key) {\n" + " return null;\n" + " }\n" + " public Inner get1() {return null;} \n" + " public Inner f; \n" + " protected class Inner {}\n" + "}"); doTest(); } public void testProtectedInnerClass1() { myFixture.addClass("package a;\n" + "public class A<T> {\n" + " public T getData() {return null;}\n" + "}"); myFixture.addClass("package a;\n" + "public class Outer extends A<Outer.Inner> {\n" + " protected class Inner {}\n" + "}"); doTest(); } private void doTest() { myFixture.configureByFile(getTestName(false) + ".java"); myFixture.checkHighlighting(); } }
{'content_hash': 'ef7d91961df677bfcbca9006a8fcdde5', 'timestamp': '', 'source': 'github', 'line_count': 285, 'max_line_length': 176, 'avg_line_length': 46.435087719298245, 'alnum_prop': 0.6320840259936528, 'repo_name': 'google/intellij-community', 'id': '913fb7ace30ea2c7bbdb34897f4ae4c15628b887', 'size': '13355', 'binary': False, 'copies': '5', 'ref': 'refs/heads/master', 'path': 'java/java-tests/testSrc/com/intellij/java/codeInsight/daemon/LightAdvHighlightingFixtureTest.java', 'mode': '33188', 'license': 'apache-2.0', 'language': []}
// Copyright 2012 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. // Unit tests for the SyncApi. Note that a lot of the underlying // functionality is provided by the Syncable layer, which has its own // unit tests. We'll test SyncApi specific things in this harness. #include <cstddef> #include <map> #include "base/basictypes.h" #include "base/callback.h" #include "base/compiler_specific.h" #include "base/files/scoped_temp_dir.h" #include "base/format_macros.h" #include "base/location.h" #include "base/memory/scoped_ptr.h" #include "base/message_loop.h" #include "base/message_loop/message_loop_proxy.h" #include "base/strings/string_number_conversions.h" #include "base/strings/stringprintf.h" #include "base/strings/utf_string_conversions.h" #include "base/test/values_test_util.h" #include "base/values.h" #include "sync/engine/sync_scheduler.h" #include "sync/internal_api/public/base/model_type_test_util.h" #include "sync/internal_api/public/change_record.h" #include "sync/internal_api/public/engine/model_safe_worker.h" #include "sync/internal_api/public/engine/polling_constants.h" #include "sync/internal_api/public/http_post_provider_factory.h" #include "sync/internal_api/public/http_post_provider_interface.h" #include "sync/internal_api/public/read_node.h" #include "sync/internal_api/public/read_transaction.h" #include "sync/internal_api/public/test/test_entry_factory.h" #include "sync/internal_api/public/test/test_internal_components_factory.h" #include "sync/internal_api/public/test/test_user_share.h" #include "sync/internal_api/public/write_node.h" #include "sync/internal_api/public/write_transaction.h" #include "sync/internal_api/sync_encryption_handler_impl.h" #include "sync/internal_api/sync_manager_impl.h" #include "sync/internal_api/syncapi_internal.h" #include "sync/js/js_arg_list.h" #include "sync/js/js_backend.h" #include "sync/js/js_event_handler.h" #include "sync/js/js_reply_handler.h" #include "sync/js/js_test_util.h" #include "sync/notifier/fake_invalidation_handler.h" #include "sync/notifier/fake_invalidator.h" #include "sync/notifier/invalidation_handler.h" #include "sync/notifier/invalidator.h" #include "sync/protocol/bookmark_specifics.pb.h" #include "sync/protocol/encryption.pb.h" #include "sync/protocol/extension_specifics.pb.h" #include "sync/protocol/password_specifics.pb.h" #include "sync/protocol/preference_specifics.pb.h" #include "sync/protocol/proto_value_conversions.h" #include "sync/protocol/sync.pb.h" #include "sync/sessions/sync_session.h" #include "sync/syncable/directory.h" #include "sync/syncable/entry.h" #include "sync/syncable/mutable_entry.h" #include "sync/syncable/nigori_util.h" #include "sync/syncable/syncable_id.h" #include "sync/syncable/syncable_read_transaction.h" #include "sync/syncable/syncable_util.h" #include "sync/syncable/syncable_write_transaction.h" #include "sync/test/callback_counter.h" #include "sync/test/engine/fake_sync_scheduler.h" #include "sync/test/engine/test_id_factory.h" #include "sync/test/fake_encryptor.h" #include "sync/test/fake_extensions_activity_monitor.h" #include "sync/util/cryptographer.h" #include "sync/util/extensions_activity_monitor.h" #include "sync/util/test_unrecoverable_error_handler.h" #include "sync/util/time.h" #include "testing/gmock/include/gmock/gmock.h" #include "testing/gtest/include/gtest/gtest.h" using base::ExpectDictStringValue; using testing::_; using testing::DoAll; using testing::InSequence; using testing::Return; using testing::SaveArg; using testing::StrictMock; namespace syncer { using sessions::SyncSessionSnapshot; using syncable::GET_BY_HANDLE; using syncable::IS_DEL; using syncable::IS_UNSYNCED; using syncable::NON_UNIQUE_NAME; using syncable::SPECIFICS; using syncable::kEncryptedString; namespace { const char kTestChromeVersion[] = "test chrome version"; void ExpectInt64Value(int64 expected_value, const base::DictionaryValue& value, const std::string& key) { std::string int64_str; EXPECT_TRUE(value.GetString(key, &int64_str)); int64 val = 0; EXPECT_TRUE(base::StringToInt64(int64_str, &val)); EXPECT_EQ(expected_value, val); } void ExpectTimeValue(const base::Time& expected_value, const base::DictionaryValue& value, const std::string& key) { std::string time_str; EXPECT_TRUE(value.GetString(key, &time_str)); EXPECT_EQ(GetTimeDebugString(expected_value), time_str); } // Makes a non-folder child of the root node. Returns the id of the // newly-created node. int64 MakeNode(UserShare* share, ModelType model_type, const std::string& client_tag) { WriteTransaction trans(FROM_HERE, share); ReadNode root_node(&trans); root_node.InitByRootLookup(); WriteNode node(&trans); WriteNode::InitUniqueByCreationResult result = node.InitUniqueByCreation(model_type, root_node, client_tag); EXPECT_EQ(WriteNode::INIT_SUCCESS, result); node.SetIsFolder(false); return node.GetId(); } // Makes a folder child of a non-root node. Returns the id of the // newly-created node. int64 MakeFolderWithParent(UserShare* share, ModelType model_type, int64 parent_id, BaseNode* predecessor) { WriteTransaction trans(FROM_HERE, share); ReadNode parent_node(&trans); EXPECT_EQ(BaseNode::INIT_OK, parent_node.InitByIdLookup(parent_id)); WriteNode node(&trans); EXPECT_TRUE(node.InitBookmarkByCreation(parent_node, predecessor)); node.SetIsFolder(true); return node.GetId(); } int64 MakeBookmarkWithParent(UserShare* share, int64 parent_id, BaseNode* predecessor) { WriteTransaction trans(FROM_HERE, share); ReadNode parent_node(&trans); EXPECT_EQ(BaseNode::INIT_OK, parent_node.InitByIdLookup(parent_id)); WriteNode node(&trans); EXPECT_TRUE(node.InitBookmarkByCreation(parent_node, predecessor)); return node.GetId(); } // Creates the "synced" root node for a particular datatype. We use the syncable // methods here so that the syncer treats these nodes as if they were already // received from the server. int64 MakeServerNodeForType(UserShare* share, ModelType model_type) { sync_pb::EntitySpecifics specifics; AddDefaultFieldValue(model_type, &specifics); syncable::WriteTransaction trans( FROM_HERE, syncable::UNITTEST, share->directory.get()); // Attempt to lookup by nigori tag. std::string type_tag = ModelTypeToRootTag(model_type); syncable::Id node_id = syncable::Id::CreateFromServerId(type_tag); syncable::MutableEntry entry(&trans, syncable::CREATE_NEW_UPDATE_ITEM, node_id); EXPECT_TRUE(entry.good()); entry.Put(syncable::BASE_VERSION, 1); entry.Put(syncable::SERVER_VERSION, 1); entry.Put(syncable::IS_UNAPPLIED_UPDATE, false); entry.Put(syncable::SERVER_PARENT_ID, syncable::GetNullId()); entry.Put(syncable::SERVER_IS_DIR, true); entry.Put(syncable::IS_DIR, true); entry.Put(syncable::SERVER_SPECIFICS, specifics); entry.Put(syncable::UNIQUE_SERVER_TAG, type_tag); entry.Put(syncable::NON_UNIQUE_NAME, type_tag); entry.Put(syncable::IS_DEL, false); entry.Put(syncable::SPECIFICS, specifics); return entry.Get(syncable::META_HANDLE); } // Simulates creating a "synced" node as a child of the root datatype node. int64 MakeServerNode(UserShare* share, ModelType model_type, const std::string& client_tag, const std::string& hashed_tag, const sync_pb::EntitySpecifics& specifics) { syncable::WriteTransaction trans( FROM_HERE, syncable::UNITTEST, share->directory.get()); syncable::Entry root_entry(&trans, syncable::GET_BY_SERVER_TAG, ModelTypeToRootTag(model_type)); EXPECT_TRUE(root_entry.good()); syncable::Id root_id = root_entry.Get(syncable::ID); syncable::Id node_id = syncable::Id::CreateFromServerId(client_tag); syncable::MutableEntry entry(&trans, syncable::CREATE_NEW_UPDATE_ITEM, node_id); EXPECT_TRUE(entry.good()); entry.Put(syncable::BASE_VERSION, 1); entry.Put(syncable::SERVER_VERSION, 1); entry.Put(syncable::IS_UNAPPLIED_UPDATE, false); entry.Put(syncable::SERVER_PARENT_ID, root_id); entry.Put(syncable::PARENT_ID, root_id); entry.Put(syncable::SERVER_IS_DIR, false); entry.Put(syncable::IS_DIR, false); entry.Put(syncable::SERVER_SPECIFICS, specifics); entry.Put(syncable::NON_UNIQUE_NAME, client_tag); entry.Put(syncable::UNIQUE_CLIENT_TAG, hashed_tag); entry.Put(syncable::IS_DEL, false); entry.Put(syncable::SPECIFICS, specifics); return entry.Get(syncable::META_HANDLE); } } // namespace class SyncApiTest : public testing::Test { public: virtual void SetUp() { test_user_share_.SetUp(); } virtual void TearDown() { test_user_share_.TearDown(); } protected: base::MessageLoop message_loop_; TestUserShare test_user_share_; }; TEST_F(SyncApiTest, SanityCheckTest) { { ReadTransaction trans(FROM_HERE, test_user_share_.user_share()); EXPECT_TRUE(trans.GetWrappedTrans()); } { WriteTransaction trans(FROM_HERE, test_user_share_.user_share()); EXPECT_TRUE(trans.GetWrappedTrans()); } { // No entries but root should exist ReadTransaction trans(FROM_HERE, test_user_share_.user_share()); ReadNode node(&trans); // Metahandle 1 can be root, sanity check 2 EXPECT_EQ(BaseNode::INIT_FAILED_ENTRY_NOT_GOOD, node.InitByIdLookup(2)); } } TEST_F(SyncApiTest, BasicTagWrite) { { ReadTransaction trans(FROM_HERE, test_user_share_.user_share()); ReadNode root_node(&trans); root_node.InitByRootLookup(); EXPECT_EQ(root_node.GetFirstChildId(), 0); } ignore_result(MakeNode(test_user_share_.user_share(), BOOKMARKS, "testtag")); { ReadTransaction trans(FROM_HERE, test_user_share_.user_share()); ReadNode node(&trans); EXPECT_EQ(BaseNode::INIT_OK, node.InitByClientTagLookup(BOOKMARKS, "testtag")); ReadNode root_node(&trans); root_node.InitByRootLookup(); EXPECT_NE(node.GetId(), 0); EXPECT_EQ(node.GetId(), root_node.GetFirstChildId()); } } TEST_F(SyncApiTest, ModelTypesSiloed) { { WriteTransaction trans(FROM_HERE, test_user_share_.user_share()); ReadNode root_node(&trans); root_node.InitByRootLookup(); EXPECT_EQ(root_node.GetFirstChildId(), 0); } ignore_result(MakeNode(test_user_share_.user_share(), BOOKMARKS, "collideme")); ignore_result(MakeNode(test_user_share_.user_share(), PREFERENCES, "collideme")); ignore_result(MakeNode(test_user_share_.user_share(), AUTOFILL, "collideme")); { ReadTransaction trans(FROM_HERE, test_user_share_.user_share()); ReadNode bookmarknode(&trans); EXPECT_EQ(BaseNode::INIT_OK, bookmarknode.InitByClientTagLookup(BOOKMARKS, "collideme")); ReadNode prefnode(&trans); EXPECT_EQ(BaseNode::INIT_OK, prefnode.InitByClientTagLookup(PREFERENCES, "collideme")); ReadNode autofillnode(&trans); EXPECT_EQ(BaseNode::INIT_OK, autofillnode.InitByClientTagLookup(AUTOFILL, "collideme")); EXPECT_NE(bookmarknode.GetId(), prefnode.GetId()); EXPECT_NE(autofillnode.GetId(), prefnode.GetId()); EXPECT_NE(bookmarknode.GetId(), autofillnode.GetId()); } } TEST_F(SyncApiTest, ReadMissingTagsFails) { { ReadTransaction trans(FROM_HERE, test_user_share_.user_share()); ReadNode node(&trans); EXPECT_EQ(BaseNode::INIT_FAILED_ENTRY_NOT_GOOD, node.InitByClientTagLookup(BOOKMARKS, "testtag")); } { WriteTransaction trans(FROM_HERE, test_user_share_.user_share()); WriteNode node(&trans); EXPECT_EQ(BaseNode::INIT_FAILED_ENTRY_NOT_GOOD, node.InitByClientTagLookup(BOOKMARKS, "testtag")); } } // TODO(chron): Hook this all up to the server and write full integration tests // for update->undelete behavior. TEST_F(SyncApiTest, TestDeleteBehavior) { int64 node_id; int64 folder_id; std::string test_title("test1"); { WriteTransaction trans(FROM_HERE, test_user_share_.user_share()); ReadNode root_node(&trans); root_node.InitByRootLookup(); // we'll use this spare folder later WriteNode folder_node(&trans); EXPECT_TRUE(folder_node.InitBookmarkByCreation(root_node, NULL)); folder_id = folder_node.GetId(); WriteNode wnode(&trans); WriteNode::InitUniqueByCreationResult result = wnode.InitUniqueByCreation(BOOKMARKS, root_node, "testtag"); EXPECT_EQ(WriteNode::INIT_SUCCESS, result); wnode.SetIsFolder(false); wnode.SetTitle(UTF8ToWide(test_title)); node_id = wnode.GetId(); } // Ensure we can delete something with a tag. { WriteTransaction trans(FROM_HERE, test_user_share_.user_share()); WriteNode wnode(&trans); EXPECT_EQ(BaseNode::INIT_OK, wnode.InitByClientTagLookup(BOOKMARKS, "testtag")); EXPECT_FALSE(wnode.GetIsFolder()); EXPECT_EQ(wnode.GetTitle(), test_title); wnode.Tombstone(); } // Lookup of a node which was deleted should return failure, // but have found some data about the node. { ReadTransaction trans(FROM_HERE, test_user_share_.user_share()); ReadNode node(&trans); EXPECT_EQ(BaseNode::INIT_FAILED_ENTRY_IS_DEL, node.InitByClientTagLookup(BOOKMARKS, "testtag")); // Note that for proper function of this API this doesn't need to be // filled, we're checking just to make sure the DB worked in this test. EXPECT_EQ(node.GetTitle(), test_title); } { WriteTransaction trans(FROM_HERE, test_user_share_.user_share()); ReadNode folder_node(&trans); EXPECT_EQ(BaseNode::INIT_OK, folder_node.InitByIdLookup(folder_id)); WriteNode wnode(&trans); // This will undelete the tag. WriteNode::InitUniqueByCreationResult result = wnode.InitUniqueByCreation(BOOKMARKS, folder_node, "testtag"); EXPECT_EQ(WriteNode::INIT_SUCCESS, result); EXPECT_EQ(wnode.GetIsFolder(), false); EXPECT_EQ(wnode.GetParentId(), folder_node.GetId()); EXPECT_EQ(wnode.GetId(), node_id); EXPECT_NE(wnode.GetTitle(), test_title); // Title should be cleared wnode.SetTitle(UTF8ToWide(test_title)); } // Now look up should work. { ReadTransaction trans(FROM_HERE, test_user_share_.user_share()); ReadNode node(&trans); EXPECT_EQ(BaseNode::INIT_OK, node.InitByClientTagLookup(BOOKMARKS, "testtag")); EXPECT_EQ(node.GetTitle(), test_title); EXPECT_EQ(node.GetModelType(), BOOKMARKS); } } TEST_F(SyncApiTest, WriteAndReadPassword) { KeyParams params = {"localhost", "username", "passphrase"}; { ReadTransaction trans(FROM_HERE, test_user_share_.user_share()); trans.GetCryptographer()->AddKey(params); } { WriteTransaction trans(FROM_HERE, test_user_share_.user_share()); ReadNode root_node(&trans); root_node.InitByRootLookup(); WriteNode password_node(&trans); WriteNode::InitUniqueByCreationResult result = password_node.InitUniqueByCreation(PASSWORDS, root_node, "foo"); EXPECT_EQ(WriteNode::INIT_SUCCESS, result); sync_pb::PasswordSpecificsData data; data.set_password_value("secret"); password_node.SetPasswordSpecifics(data); } { ReadTransaction trans(FROM_HERE, test_user_share_.user_share()); ReadNode root_node(&trans); root_node.InitByRootLookup(); ReadNode password_node(&trans); EXPECT_EQ(BaseNode::INIT_OK, password_node.InitByClientTagLookup(PASSWORDS, "foo")); const sync_pb::PasswordSpecificsData& data = password_node.GetPasswordSpecifics(); EXPECT_EQ("secret", data.password_value()); } } TEST_F(SyncApiTest, WriteEncryptedTitle) { KeyParams params = {"localhost", "username", "passphrase"}; { ReadTransaction trans(FROM_HERE, test_user_share_.user_share()); trans.GetCryptographer()->AddKey(params); } test_user_share_.encryption_handler()->EnableEncryptEverything(); int bookmark_id; { WriteTransaction trans(FROM_HERE, test_user_share_.user_share()); ReadNode root_node(&trans); root_node.InitByRootLookup(); WriteNode bookmark_node(&trans); ASSERT_TRUE(bookmark_node.InitBookmarkByCreation(root_node, NULL)); bookmark_id = bookmark_node.GetId(); bookmark_node.SetTitle(UTF8ToWide("foo")); WriteNode pref_node(&trans); WriteNode::InitUniqueByCreationResult result = pref_node.InitUniqueByCreation(PREFERENCES, root_node, "bar"); ASSERT_EQ(WriteNode::INIT_SUCCESS, result); pref_node.SetTitle(UTF8ToWide("bar")); } { ReadTransaction trans(FROM_HERE, test_user_share_.user_share()); ReadNode root_node(&trans); root_node.InitByRootLookup(); ReadNode bookmark_node(&trans); ASSERT_EQ(BaseNode::INIT_OK, bookmark_node.InitByIdLookup(bookmark_id)); EXPECT_EQ("foo", bookmark_node.GetTitle()); EXPECT_EQ(kEncryptedString, bookmark_node.GetEntry()->Get(syncable::NON_UNIQUE_NAME)); ReadNode pref_node(&trans); ASSERT_EQ(BaseNode::INIT_OK, pref_node.InitByClientTagLookup(PREFERENCES, "bar")); EXPECT_EQ(kEncryptedString, pref_node.GetTitle()); } } TEST_F(SyncApiTest, BaseNodeSetSpecifics) { int64 child_id = MakeNode(test_user_share_.user_share(), BOOKMARKS, "testtag"); WriteTransaction trans(FROM_HERE, test_user_share_.user_share()); WriteNode node(&trans); EXPECT_EQ(BaseNode::INIT_OK, node.InitByIdLookup(child_id)); sync_pb::EntitySpecifics entity_specifics; entity_specifics.mutable_bookmark()->set_url("http://www.google.com"); EXPECT_NE(entity_specifics.SerializeAsString(), node.GetEntitySpecifics().SerializeAsString()); node.SetEntitySpecifics(entity_specifics); EXPECT_EQ(entity_specifics.SerializeAsString(), node.GetEntitySpecifics().SerializeAsString()); } TEST_F(SyncApiTest, BaseNodeSetSpecificsPreservesUnknownFields) { int64 child_id = MakeNode(test_user_share_.user_share(), BOOKMARKS, "testtag"); WriteTransaction trans(FROM_HERE, test_user_share_.user_share()); WriteNode node(&trans); EXPECT_EQ(BaseNode::INIT_OK, node.InitByIdLookup(child_id)); EXPECT_TRUE(node.GetEntitySpecifics().unknown_fields().empty()); sync_pb::EntitySpecifics entity_specifics; entity_specifics.mutable_bookmark()->set_url("http://www.google.com"); entity_specifics.mutable_unknown_fields()->AddFixed32(5, 100); node.SetEntitySpecifics(entity_specifics); EXPECT_FALSE(node.GetEntitySpecifics().unknown_fields().empty()); entity_specifics.mutable_unknown_fields()->Clear(); node.SetEntitySpecifics(entity_specifics); EXPECT_FALSE(node.GetEntitySpecifics().unknown_fields().empty()); } namespace { void CheckNodeValue(const BaseNode& node, const base::DictionaryValue& value, bool is_detailed) { size_t expected_field_count = 4; ExpectInt64Value(node.GetId(), value, "id"); { bool is_folder = false; EXPECT_TRUE(value.GetBoolean("isFolder", &is_folder)); EXPECT_EQ(node.GetIsFolder(), is_folder); } ExpectDictStringValue(node.GetTitle(), value, "title"); ModelType expected_model_type = node.GetModelType(); std::string type_str; EXPECT_TRUE(value.GetString("type", &type_str)); if (expected_model_type >= FIRST_REAL_MODEL_TYPE) { ModelType model_type = ModelTypeFromString(type_str); EXPECT_EQ(expected_model_type, model_type); } else if (expected_model_type == TOP_LEVEL_FOLDER) { EXPECT_EQ("Top-level folder", type_str); } else if (expected_model_type == UNSPECIFIED) { EXPECT_EQ("Unspecified", type_str); } else { ADD_FAILURE(); } if (is_detailed) { { scoped_ptr<base::DictionaryValue> expected_entry( node.GetEntry()->ToValue(NULL)); const base::Value* entry = NULL; EXPECT_TRUE(value.Get("entry", &entry)); EXPECT_TRUE(base::Value::Equals(entry, expected_entry.get())); } ExpectInt64Value(node.GetParentId(), value, "parentId"); ExpectTimeValue(node.GetModificationTime(), value, "modificationTime"); ExpectInt64Value(node.GetExternalId(), value, "externalId"); expected_field_count += 4; if (value.HasKey("predecessorId")) { ExpectInt64Value(node.GetPredecessorId(), value, "predecessorId"); expected_field_count++; } if (value.HasKey("successorId")) { ExpectInt64Value(node.GetSuccessorId(), value, "successorId"); expected_field_count++; } if (value.HasKey("firstChildId")) { ExpectInt64Value(node.GetFirstChildId(), value, "firstChildId"); expected_field_count++; } } EXPECT_EQ(expected_field_count, value.size()); } } // namespace TEST_F(SyncApiTest, BaseNodeGetSummaryAsValue) { ReadTransaction trans(FROM_HERE, test_user_share_.user_share()); ReadNode node(&trans); node.InitByRootLookup(); scoped_ptr<base::DictionaryValue> details(node.GetSummaryAsValue()); if (details) { CheckNodeValue(node, *details, false); } else { ADD_FAILURE(); } } TEST_F(SyncApiTest, BaseNodeGetDetailsAsValue) { ReadTransaction trans(FROM_HERE, test_user_share_.user_share()); ReadNode node(&trans); node.InitByRootLookup(); scoped_ptr<base::DictionaryValue> details(node.GetDetailsAsValue()); if (details) { CheckNodeValue(node, *details, true); } else { ADD_FAILURE(); } } TEST_F(SyncApiTest, EmptyTags) { WriteTransaction trans(FROM_HERE, test_user_share_.user_share()); ReadNode root_node(&trans); root_node.InitByRootLookup(); WriteNode node(&trans); std::string empty_tag; WriteNode::InitUniqueByCreationResult result = node.InitUniqueByCreation(TYPED_URLS, root_node, empty_tag); EXPECT_NE(WriteNode::INIT_SUCCESS, result); EXPECT_EQ(BaseNode::INIT_FAILED_PRECONDITION, node.InitByTagLookup(empty_tag)); } // Test counting nodes when the type's root node has no children. TEST_F(SyncApiTest, GetTotalNodeCountEmpty) { int64 type_root = MakeServerNodeForType(test_user_share_.user_share(), BOOKMARKS); { ReadTransaction trans(FROM_HERE, test_user_share_.user_share()); ReadNode type_root_node(&trans); EXPECT_EQ(BaseNode::INIT_OK, type_root_node.InitByIdLookup(type_root)); EXPECT_EQ(1, type_root_node.GetTotalNodeCount()); } } // Test counting nodes when there is one child beneath the type's root. TEST_F(SyncApiTest, GetTotalNodeCountOneChild) { int64 type_root = MakeServerNodeForType(test_user_share_.user_share(), BOOKMARKS); int64 parent = MakeFolderWithParent(test_user_share_.user_share(), BOOKMARKS, type_root, NULL); { ReadTransaction trans(FROM_HERE, test_user_share_.user_share()); ReadNode type_root_node(&trans); EXPECT_EQ(BaseNode::INIT_OK, type_root_node.InitByIdLookup(type_root)); EXPECT_EQ(2, type_root_node.GetTotalNodeCount()); ReadNode parent_node(&trans); EXPECT_EQ(BaseNode::INIT_OK, parent_node.InitByIdLookup(parent)); EXPECT_EQ(1, parent_node.GetTotalNodeCount()); } } // Test counting nodes when there are multiple children beneath the type root, // and one of those children has children of its own. TEST_F(SyncApiTest, GetTotalNodeCountMultipleChildren) { int64 type_root = MakeServerNodeForType(test_user_share_.user_share(), BOOKMARKS); int64 parent = MakeFolderWithParent(test_user_share_.user_share(), BOOKMARKS, type_root, NULL); ignore_result(MakeFolderWithParent(test_user_share_.user_share(), BOOKMARKS, type_root, NULL)); int64 child1 = MakeFolderWithParent( test_user_share_.user_share(), BOOKMARKS, parent, NULL); ignore_result(MakeBookmarkWithParent( test_user_share_.user_share(), parent, NULL)); ignore_result(MakeBookmarkWithParent( test_user_share_.user_share(), child1, NULL)); { ReadTransaction trans(FROM_HERE, test_user_share_.user_share()); ReadNode type_root_node(&trans); EXPECT_EQ(BaseNode::INIT_OK, type_root_node.InitByIdLookup(type_root)); EXPECT_EQ(6, type_root_node.GetTotalNodeCount()); ReadNode node(&trans); EXPECT_EQ(BaseNode::INIT_OK, node.InitByIdLookup(parent)); EXPECT_EQ(4, node.GetTotalNodeCount()); } } namespace { class TestHttpPostProviderInterface : public HttpPostProviderInterface { public: virtual ~TestHttpPostProviderInterface() {} virtual void SetExtraRequestHeaders(const char* headers) OVERRIDE {} virtual void SetURL(const char* url, int port) OVERRIDE {} virtual void SetPostPayload(const char* content_type, int content_length, const char* content) OVERRIDE {} virtual bool MakeSynchronousPost(int* error_code, int* response_code) OVERRIDE { return false; } virtual int GetResponseContentLength() const OVERRIDE { return 0; } virtual const char* GetResponseContent() const OVERRIDE { return ""; } virtual const std::string GetResponseHeaderValue( const std::string& name) const OVERRIDE { return std::string(); } virtual void Abort() OVERRIDE {} }; class TestHttpPostProviderFactory : public HttpPostProviderFactory { public: virtual ~TestHttpPostProviderFactory() {} virtual HttpPostProviderInterface* Create() OVERRIDE { return new TestHttpPostProviderInterface(); } virtual void Destroy(HttpPostProviderInterface* http) OVERRIDE { delete static_cast<TestHttpPostProviderInterface*>(http); } }; class SyncManagerObserverMock : public SyncManager::Observer { public: MOCK_METHOD1(OnSyncCycleCompleted, void(const SyncSessionSnapshot&)); // NOLINT MOCK_METHOD4(OnInitializationComplete, void(const WeakHandle<JsBackend>&, const WeakHandle<DataTypeDebugInfoListener>&, bool, syncer::ModelTypeSet)); // NOLINT MOCK_METHOD1(OnConnectionStatusChange, void(ConnectionStatus)); // NOLINT MOCK_METHOD0(OnStopSyncingPermanently, void()); // NOLINT MOCK_METHOD1(OnUpdatedToken, void(const std::string&)); // NOLINT MOCK_METHOD1(OnActionableError, void(const SyncProtocolError&)); // NOLINT }; class SyncEncryptionHandlerObserverMock : public SyncEncryptionHandler::Observer { public: MOCK_METHOD2(OnPassphraseRequired, void(PassphraseRequiredReason, const sync_pb::EncryptedData&)); // NOLINT MOCK_METHOD0(OnPassphraseAccepted, void()); // NOLINT MOCK_METHOD2(OnBootstrapTokenUpdated, void(const std::string&, BootstrapTokenType type)); // NOLINT MOCK_METHOD2(OnEncryptedTypesChanged, void(ModelTypeSet, bool)); // NOLINT MOCK_METHOD0(OnEncryptionComplete, void()); // NOLINT MOCK_METHOD1(OnCryptographerStateChanged, void(Cryptographer*)); // NOLINT MOCK_METHOD2(OnPassphraseTypeChanged, void(PassphraseType, base::Time)); // NOLINT }; } // namespace class SyncManagerTest : public testing::Test, public SyncManager::ChangeDelegate { protected: enum NigoriStatus { DONT_WRITE_NIGORI, WRITE_TO_NIGORI }; enum EncryptionStatus { UNINITIALIZED, DEFAULT_ENCRYPTION, FULL_ENCRYPTION }; SyncManagerTest() : fake_invalidator_(NULL), sync_manager_("Test sync manager") { switches_.encryption_method = InternalComponentsFactory::ENCRYPTION_KEYSTORE; } virtual ~SyncManagerTest() { EXPECT_FALSE(fake_invalidator_); } // Test implementation. void SetUp() { ASSERT_TRUE(temp_dir_.CreateUniqueTempDir()); SyncCredentials credentials; credentials.email = "[email protected]"; credentials.sync_token = "sometoken"; fake_invalidator_ = new FakeInvalidator(); sync_manager_.AddObserver(&manager_observer_); EXPECT_CALL(manager_observer_, OnInitializationComplete(_, _, _, _)). WillOnce(SaveArg<0>(&js_backend_)); EXPECT_FALSE(js_backend_.IsInitialized()); std::vector<ModelSafeWorker*> workers; ModelSafeRoutingInfo routing_info; GetModelSafeRoutingInfo(&routing_info); // Takes ownership of |fake_invalidator_|. sync_manager_.Init( temp_dir_.path(), WeakHandle<JsEventHandler>(), "bogus", 0, false, scoped_ptr<HttpPostProviderFactory>(new TestHttpPostProviderFactory()), workers, &extensions_activity_monitor_, this, credentials, scoped_ptr<Invalidator>(fake_invalidator_), "fake_invalidator_client_id", std::string(), std::string(), // bootstrap tokens scoped_ptr<InternalComponentsFactory>(GetFactory()), &encryptor_, &handler_, NULL, false); sync_manager_.GetEncryptionHandler()->AddObserver(&encryption_observer_); EXPECT_TRUE(js_backend_.IsInitialized()); for (ModelSafeRoutingInfo::iterator i = routing_info.begin(); i != routing_info.end(); ++i) { type_roots_[i->first] = MakeServerNodeForType( sync_manager_.GetUserShare(), i->first); } PumpLoop(); EXPECT_TRUE(fake_invalidator_->IsHandlerRegistered(&sync_manager_)); } void TearDown() { sync_manager_.RemoveObserver(&manager_observer_); sync_manager_.ShutdownOnSyncThread(); // We can't assert that |sync_manager_| isn't registered with // |fake_invalidator_| anymore because |fake_invalidator_| is now // destroyed. fake_invalidator_ = NULL; PumpLoop(); } void GetModelSafeRoutingInfo(ModelSafeRoutingInfo* out) { (*out)[NIGORI] = GROUP_PASSIVE; (*out)[DEVICE_INFO] = GROUP_PASSIVE; (*out)[EXPERIMENTS] = GROUP_PASSIVE; (*out)[BOOKMARKS] = GROUP_PASSIVE; (*out)[THEMES] = GROUP_PASSIVE; (*out)[SESSIONS] = GROUP_PASSIVE; (*out)[PASSWORDS] = GROUP_PASSIVE; (*out)[PREFERENCES] = GROUP_PASSIVE; (*out)[PRIORITY_PREFERENCES] = GROUP_PASSIVE; } virtual void OnChangesApplied( ModelType model_type, int64 model_version, const BaseTransaction* trans, const ImmutableChangeRecordList& changes) OVERRIDE {} virtual void OnChangesComplete(ModelType model_type) OVERRIDE {} // Helper methods. bool SetUpEncryption(NigoriStatus nigori_status, EncryptionStatus encryption_status) { UserShare* share = sync_manager_.GetUserShare(); // We need to create the nigori node as if it were an applied server update. int64 nigori_id = GetIdForDataType(NIGORI); if (nigori_id == kInvalidId) return false; // Set the nigori cryptographer information. if (encryption_status == FULL_ENCRYPTION) sync_manager_.GetEncryptionHandler()->EnableEncryptEverything(); WriteTransaction trans(FROM_HERE, share); Cryptographer* cryptographer = trans.GetCryptographer(); if (!cryptographer) return false; if (encryption_status != UNINITIALIZED) { KeyParams params = {"localhost", "dummy", "foobar"}; cryptographer->AddKey(params); } else { DCHECK_NE(nigori_status, WRITE_TO_NIGORI); } if (nigori_status == WRITE_TO_NIGORI) { sync_pb::NigoriSpecifics nigori; cryptographer->GetKeys(nigori.mutable_encryption_keybag()); share->directory->GetNigoriHandler()->UpdateNigoriFromEncryptedTypes( &nigori, trans.GetWrappedTrans()); WriteNode node(&trans); EXPECT_EQ(BaseNode::INIT_OK, node.InitByIdLookup(nigori_id)); node.SetNigoriSpecifics(nigori); } return cryptographer->is_ready(); } int64 GetIdForDataType(ModelType type) { if (type_roots_.count(type) == 0) return 0; return type_roots_[type]; } void PumpLoop() { message_loop_.RunUntilIdle(); } void SendJsMessage(const std::string& name, const JsArgList& args, const WeakHandle<JsReplyHandler>& reply_handler) { js_backend_.Call(FROM_HERE, &JsBackend::ProcessJsMessage, name, args, reply_handler); PumpLoop(); } void SetJsEventHandler(const WeakHandle<JsEventHandler>& event_handler) { js_backend_.Call(FROM_HERE, &JsBackend::SetJsEventHandler, event_handler); PumpLoop(); } // Looks up an entry by client tag and resets IS_UNSYNCED value to false. // Returns true if entry was previously unsynced, false if IS_UNSYNCED was // already false. bool ResetUnsyncedEntry(ModelType type, const std::string& client_tag) { UserShare* share = sync_manager_.GetUserShare(); syncable::WriteTransaction trans( FROM_HERE, syncable::UNITTEST, share->directory.get()); const std::string hash = syncable::GenerateSyncableHash(type, client_tag); syncable::MutableEntry entry(&trans, syncable::GET_BY_CLIENT_TAG, hash); EXPECT_TRUE(entry.good()); if (!entry.Get(IS_UNSYNCED)) return false; entry.Put(IS_UNSYNCED, false); return true; } virtual InternalComponentsFactory* GetFactory() { return new TestInternalComponentsFactory(GetSwitches(), STORAGE_IN_MEMORY); } // Returns true if we are currently encrypting all sync data. May // be called on any thread. bool EncryptEverythingEnabledForTest() { return sync_manager_.GetEncryptionHandler()->EncryptEverythingEnabled(); } // Gets the set of encrypted types from the cryptographer // Note: opens a transaction. May be called from any thread. ModelTypeSet GetEncryptedTypes() { ReadTransaction trans(FROM_HERE, sync_manager_.GetUserShare()); return GetEncryptedTypesWithTrans(&trans); } ModelTypeSet GetEncryptedTypesWithTrans(BaseTransaction* trans) { return trans->GetDirectory()->GetNigoriHandler()-> GetEncryptedTypes(trans->GetWrappedTrans()); } void SimulateInvalidatorStateChangeForTest(InvalidatorState state) { DCHECK(sync_manager_.thread_checker_.CalledOnValidThread()); sync_manager_.OnInvalidatorStateChange(state); } void TriggerOnIncomingNotificationForTest(ModelTypeSet model_types) { DCHECK(sync_manager_.thread_checker_.CalledOnValidThread()); ModelTypeInvalidationMap invalidation_map = ModelTypeSetToInvalidationMap(model_types, std::string()); sync_manager_.OnIncomingInvalidation( ModelTypeInvalidationMapToObjectIdInvalidationMap( invalidation_map)); } void SetProgressMarkerForType(ModelType type, bool set) { if (set) { sync_pb::DataTypeProgressMarker marker; marker.set_token("token"); marker.set_data_type_id(GetSpecificsFieldNumberFromModelType(type)); sync_manager_.directory()->SetDownloadProgress(type, marker); } else { sync_pb::DataTypeProgressMarker marker; sync_manager_.directory()->SetDownloadProgress(type, marker); } } InternalComponentsFactory::Switches GetSwitches() const { return switches_; } private: // Needed by |sync_manager_|. base::MessageLoop message_loop_; // Needed by |sync_manager_|. base::ScopedTempDir temp_dir_; // Sync Id's for the roots of the enabled datatypes. std::map<ModelType, int64> type_roots_; FakeExtensionsActivityMonitor extensions_activity_monitor_; protected: FakeEncryptor encryptor_; TestUnrecoverableErrorHandler handler_; FakeInvalidator* fake_invalidator_; SyncManagerImpl sync_manager_; WeakHandle<JsBackend> js_backend_; StrictMock<SyncManagerObserverMock> manager_observer_; StrictMock<SyncEncryptionHandlerObserverMock> encryption_observer_; InternalComponentsFactory::Switches switches_; }; TEST_F(SyncManagerTest, UpdateEnabledTypes) { ModelSafeRoutingInfo routes; GetModelSafeRoutingInfo(&routes); const ModelTypeSet enabled_types = GetRoutingInfoTypes(routes); sync_manager_.UpdateEnabledTypes(enabled_types); EXPECT_EQ(ModelTypeSetToObjectIdSet(enabled_types), fake_invalidator_->GetRegisteredIds(&sync_manager_)); } TEST_F(SyncManagerTest, RegisterInvalidationHandler) { FakeInvalidationHandler fake_handler; sync_manager_.RegisterInvalidationHandler(&fake_handler); EXPECT_TRUE(fake_invalidator_->IsHandlerRegistered(&fake_handler)); const ObjectIdSet& ids = ModelTypeSetToObjectIdSet(ModelTypeSet(BOOKMARKS, PREFERENCES)); sync_manager_.UpdateRegisteredInvalidationIds(&fake_handler, ids); EXPECT_EQ(ids, fake_invalidator_->GetRegisteredIds(&fake_handler)); sync_manager_.UnregisterInvalidationHandler(&fake_handler); EXPECT_FALSE(fake_invalidator_->IsHandlerRegistered(&fake_handler)); } TEST_F(SyncManagerTest, ProcessJsMessage) { const JsArgList kNoArgs; StrictMock<MockJsReplyHandler> reply_handler; base::ListValue disabled_args; disabled_args.Append(new base::StringValue("TRANSIENT_INVALIDATION_ERROR")); EXPECT_CALL(reply_handler, HandleJsReply("getNotificationState", HasArgsAsList(disabled_args))); // This message should be dropped. SendJsMessage("unknownMessage", kNoArgs, reply_handler.AsWeakHandle()); SendJsMessage("getNotificationState", kNoArgs, reply_handler.AsWeakHandle()); } TEST_F(SyncManagerTest, ProcessJsMessageGetRootNodeDetails) { const JsArgList kNoArgs; StrictMock<MockJsReplyHandler> reply_handler; JsArgList return_args; EXPECT_CALL(reply_handler, HandleJsReply("getRootNodeDetails", _)) .WillOnce(SaveArg<1>(&return_args)); SendJsMessage("getRootNodeDetails", kNoArgs, reply_handler.AsWeakHandle()); EXPECT_EQ(1u, return_args.Get().GetSize()); const base::DictionaryValue* node_info = NULL; EXPECT_TRUE(return_args.Get().GetDictionary(0, &node_info)); if (node_info) { ReadTransaction trans(FROM_HERE, sync_manager_.GetUserShare()); ReadNode node(&trans); node.InitByRootLookup(); CheckNodeValue(node, *node_info, true); } else { ADD_FAILURE(); } } void CheckGetNodesByIdReturnArgs(SyncManager* sync_manager, const JsArgList& return_args, int64 id, bool is_detailed) { EXPECT_EQ(1u, return_args.Get().GetSize()); const base::ListValue* nodes = NULL; ASSERT_TRUE(return_args.Get().GetList(0, &nodes)); ASSERT_TRUE(nodes); EXPECT_EQ(1u, nodes->GetSize()); const base::DictionaryValue* node_info = NULL; EXPECT_TRUE(nodes->GetDictionary(0, &node_info)); ASSERT_TRUE(node_info); ReadTransaction trans(FROM_HERE, sync_manager->GetUserShare()); ReadNode node(&trans); EXPECT_EQ(BaseNode::INIT_OK, node.InitByIdLookup(id)); CheckNodeValue(node, *node_info, is_detailed); } class SyncManagerGetNodesByIdTest : public SyncManagerTest { protected: virtual ~SyncManagerGetNodesByIdTest() {} void RunGetNodesByIdTest(const char* message_name, bool is_detailed) { int64 root_id = kInvalidId; { ReadTransaction trans(FROM_HERE, sync_manager_.GetUserShare()); ReadNode root_node(&trans); root_node.InitByRootLookup(); root_id = root_node.GetId(); } int64 child_id = MakeNode(sync_manager_.GetUserShare(), BOOKMARKS, "testtag"); StrictMock<MockJsReplyHandler> reply_handler; JsArgList return_args; const int64 ids[] = { root_id, child_id }; EXPECT_CALL(reply_handler, HandleJsReply(message_name, _)) .Times(arraysize(ids)).WillRepeatedly(SaveArg<1>(&return_args)); for (size_t i = 0; i < arraysize(ids); ++i) { base::ListValue args; base::ListValue* id_values = new base::ListValue(); args.Append(id_values); id_values->Append(new base::StringValue(base::Int64ToString(ids[i]))); SendJsMessage(message_name, JsArgList(&args), reply_handler.AsWeakHandle()); CheckGetNodesByIdReturnArgs(&sync_manager_, return_args, ids[i], is_detailed); } } void RunGetNodesByIdFailureTest(const char* message_name) { StrictMock<MockJsReplyHandler> reply_handler; base::ListValue empty_list_args; empty_list_args.Append(new base::ListValue()); EXPECT_CALL(reply_handler, HandleJsReply(message_name, HasArgsAsList(empty_list_args))) .Times(6); { base::ListValue args; SendJsMessage(message_name, JsArgList(&args), reply_handler.AsWeakHandle()); } { base::ListValue args; args.Append(new base::ListValue()); SendJsMessage(message_name, JsArgList(&args), reply_handler.AsWeakHandle()); } { base::ListValue args; base::ListValue* ids = new base::ListValue(); args.Append(ids); ids->Append(new base::StringValue(std::string())); SendJsMessage( message_name, JsArgList(&args), reply_handler.AsWeakHandle()); } { base::ListValue args; base::ListValue* ids = new base::ListValue(); args.Append(ids); ids->Append(new base::StringValue("nonsense")); SendJsMessage(message_name, JsArgList(&args), reply_handler.AsWeakHandle()); } { base::ListValue args; base::ListValue* ids = new base::ListValue(); args.Append(ids); ids->Append(new base::StringValue("0")); SendJsMessage(message_name, JsArgList(&args), reply_handler.AsWeakHandle()); } { base::ListValue args; base::ListValue* ids = new base::ListValue(); args.Append(ids); ids->Append(new base::StringValue("9999")); SendJsMessage(message_name, JsArgList(&args), reply_handler.AsWeakHandle()); } } }; TEST_F(SyncManagerGetNodesByIdTest, GetNodeSummariesById) { RunGetNodesByIdTest("getNodeSummariesById", false); } TEST_F(SyncManagerGetNodesByIdTest, GetNodeDetailsById) { RunGetNodesByIdTest("getNodeDetailsById", true); } TEST_F(SyncManagerGetNodesByIdTest, GetNodeSummariesByIdFailure) { RunGetNodesByIdFailureTest("getNodeSummariesById"); } TEST_F(SyncManagerGetNodesByIdTest, GetNodeDetailsByIdFailure) { RunGetNodesByIdFailureTest("getNodeDetailsById"); } TEST_F(SyncManagerTest, GetChildNodeIds) { StrictMock<MockJsReplyHandler> reply_handler; JsArgList return_args; EXPECT_CALL(reply_handler, HandleJsReply("getChildNodeIds", _)) .Times(1).WillRepeatedly(SaveArg<1>(&return_args)); { base::ListValue args; args.Append(new base::StringValue("1")); SendJsMessage("getChildNodeIds", JsArgList(&args), reply_handler.AsWeakHandle()); } EXPECT_EQ(1u, return_args.Get().GetSize()); const base::ListValue* nodes = NULL; ASSERT_TRUE(return_args.Get().GetList(0, &nodes)); ASSERT_TRUE(nodes); EXPECT_EQ(9u, nodes->GetSize()); } TEST_F(SyncManagerTest, GetChildNodeIdsFailure) { StrictMock<MockJsReplyHandler> reply_handler; base::ListValue empty_list_args; empty_list_args.Append(new base::ListValue()); EXPECT_CALL(reply_handler, HandleJsReply("getChildNodeIds", HasArgsAsList(empty_list_args))) .Times(5); { base::ListValue args; SendJsMessage("getChildNodeIds", JsArgList(&args), reply_handler.AsWeakHandle()); } { base::ListValue args; args.Append(new base::StringValue(std::string())); SendJsMessage( "getChildNodeIds", JsArgList(&args), reply_handler.AsWeakHandle()); } { base::ListValue args; args.Append(new base::StringValue("nonsense")); SendJsMessage("getChildNodeIds", JsArgList(&args), reply_handler.AsWeakHandle()); } { base::ListValue args; args.Append(new base::StringValue("0")); SendJsMessage("getChildNodeIds", JsArgList(&args), reply_handler.AsWeakHandle()); } { base::ListValue args; args.Append(new base::StringValue("9999")); SendJsMessage("getChildNodeIds", JsArgList(&args), reply_handler.AsWeakHandle()); } } TEST_F(SyncManagerTest, GetAllNodesTest) { StrictMock<MockJsReplyHandler> reply_handler; JsArgList return_args; EXPECT_CALL(reply_handler, HandleJsReply("getAllNodes", _)) .Times(1).WillRepeatedly(SaveArg<1>(&return_args)); { base::ListValue args; SendJsMessage("getAllNodes", JsArgList(&args), reply_handler.AsWeakHandle()); } // There's not much value in verifying every attribute on every node here. // Most of the value of this test has already been achieved: we've verified we // can call the above function without crashing or leaking memory. // // Let's just check the list size and a few of its elements. Anything more // would make this test brittle without greatly increasing our chances of // catching real bugs. const base::ListValue* node_list; const base::DictionaryValue* first_result; // The resulting argument list should have one argument, a list of nodes. ASSERT_EQ(1U, return_args.Get().GetSize()); ASSERT_TRUE(return_args.Get().GetList(0, &node_list)); // The database creation logic depends on the routing info. // Refer to setup methods for more information. ModelSafeRoutingInfo routes; GetModelSafeRoutingInfo(&routes); size_t directory_size = routes.size() + 1; ASSERT_EQ(directory_size, node_list->GetSize()); ASSERT_TRUE(node_list->GetDictionary(0, &first_result)); EXPECT_TRUE(first_result->HasKey("ID")); EXPECT_TRUE(first_result->HasKey("NON_UNIQUE_NAME")); } // Simulate various invalidator state changes. Those should propagate // JS events. TEST_F(SyncManagerTest, OnInvalidatorStateChangeJsEvents) { StrictMock<MockJsEventHandler> event_handler; base::DictionaryValue enabled_details; enabled_details.SetString("state", "INVALIDATIONS_ENABLED"); base::DictionaryValue credentials_rejected_details; credentials_rejected_details.SetString( "state", "INVALIDATION_CREDENTIALS_REJECTED"); base::DictionaryValue transient_error_details; transient_error_details.SetString("state", "TRANSIENT_INVALIDATION_ERROR"); base::DictionaryValue auth_error_details; auth_error_details.SetString("status", "CONNECTION_AUTH_ERROR"); EXPECT_CALL(manager_observer_, OnConnectionStatusChange(CONNECTION_AUTH_ERROR)); EXPECT_CALL( event_handler, HandleJsEvent("onConnectionStatusChange", HasDetailsAsDictionary(auth_error_details))); EXPECT_CALL(event_handler, HandleJsEvent("onNotificationStateChange", HasDetailsAsDictionary(enabled_details))); EXPECT_CALL( event_handler, HandleJsEvent("onNotificationStateChange", HasDetailsAsDictionary(credentials_rejected_details))) .Times(2); EXPECT_CALL(event_handler, HandleJsEvent("onNotificationStateChange", HasDetailsAsDictionary(transient_error_details))); // Test needs to simulate INVALIDATION_CREDENTIALS_REJECTED with event handler // attached because this is the only time when CONNECTION_AUTH_ERROR // notification will be generated, therefore the only chance to verify that // "onConnectionStatusChange" event is delivered SetJsEventHandler(event_handler.AsWeakHandle()); SimulateInvalidatorStateChangeForTest(INVALIDATION_CREDENTIALS_REJECTED); SetJsEventHandler(WeakHandle<JsEventHandler>()); SimulateInvalidatorStateChangeForTest(INVALIDATIONS_ENABLED); SimulateInvalidatorStateChangeForTest(INVALIDATION_CREDENTIALS_REJECTED); SimulateInvalidatorStateChangeForTest(TRANSIENT_INVALIDATION_ERROR); SetJsEventHandler(event_handler.AsWeakHandle()); SimulateInvalidatorStateChangeForTest(INVALIDATIONS_ENABLED); SimulateInvalidatorStateChangeForTest(INVALIDATION_CREDENTIALS_REJECTED); SimulateInvalidatorStateChangeForTest(TRANSIENT_INVALIDATION_ERROR); SetJsEventHandler(WeakHandle<JsEventHandler>()); SimulateInvalidatorStateChangeForTest(INVALIDATIONS_ENABLED); SimulateInvalidatorStateChangeForTest(INVALIDATION_CREDENTIALS_REJECTED); SimulateInvalidatorStateChangeForTest(TRANSIENT_INVALIDATION_ERROR); // Should trigger the replies. PumpLoop(); } // Simulate the invalidator's credentials being rejected. That should // also clear the sync token. TEST_F(SyncManagerTest, OnInvalidatorStateChangeCredentialsRejected) { EXPECT_CALL(manager_observer_, OnConnectionStatusChange(CONNECTION_AUTH_ERROR)); EXPECT_FALSE(sync_manager_.GetHasInvalidAuthTokenForTest()); SimulateInvalidatorStateChangeForTest(INVALIDATION_CREDENTIALS_REJECTED); EXPECT_TRUE(sync_manager_.GetHasInvalidAuthTokenForTest()); // Should trigger the replies. PumpLoop(); } TEST_F(SyncManagerTest, OnIncomingNotification) { StrictMock<MockJsEventHandler> event_handler; const ModelTypeSet empty_model_types; const ModelTypeSet model_types( BOOKMARKS, THEMES); // Build expected_args to have a single argument with the string // equivalents of model_types. base::DictionaryValue expected_details; { base::ListValue* model_type_list = new base::ListValue(); expected_details.SetString("source", "REMOTE_INVALIDATION"); expected_details.Set("changedTypes", model_type_list); for (ModelTypeSet::Iterator it = model_types.First(); it.Good(); it.Inc()) { model_type_list->Append( new base::StringValue(ModelTypeToString(it.Get()))); } } EXPECT_CALL(event_handler, HandleJsEvent("onIncomingNotification", HasDetailsAsDictionary(expected_details))); TriggerOnIncomingNotificationForTest(empty_model_types); TriggerOnIncomingNotificationForTest(model_types); SetJsEventHandler(event_handler.AsWeakHandle()); TriggerOnIncomingNotificationForTest(model_types); SetJsEventHandler(WeakHandle<JsEventHandler>()); TriggerOnIncomingNotificationForTest(empty_model_types); TriggerOnIncomingNotificationForTest(model_types); // Should trigger the replies. PumpLoop(); } TEST_F(SyncManagerTest, RefreshEncryptionReady) { EXPECT_TRUE(SetUpEncryption(WRITE_TO_NIGORI, DEFAULT_ENCRYPTION)); EXPECT_CALL(encryption_observer_, OnEncryptionComplete()); EXPECT_CALL(encryption_observer_, OnCryptographerStateChanged(_)); EXPECT_CALL(encryption_observer_, OnEncryptedTypesChanged(_, false)); sync_manager_.GetEncryptionHandler()->Init(); PumpLoop(); const ModelTypeSet encrypted_types = GetEncryptedTypes(); EXPECT_TRUE(encrypted_types.Has(PASSWORDS)); EXPECT_FALSE(EncryptEverythingEnabledForTest()); { ReadTransaction trans(FROM_HERE, sync_manager_.GetUserShare()); ReadNode node(&trans); EXPECT_EQ(BaseNode::INIT_OK, node.InitByIdLookup(GetIdForDataType(NIGORI))); sync_pb::NigoriSpecifics nigori = node.GetNigoriSpecifics(); EXPECT_TRUE(nigori.has_encryption_keybag()); Cryptographer* cryptographer = trans.GetCryptographer(); EXPECT_TRUE(cryptographer->is_ready()); EXPECT_TRUE(cryptographer->CanDecrypt(nigori.encryption_keybag())); } } // Attempt to refresh encryption when nigori not downloaded. TEST_F(SyncManagerTest, RefreshEncryptionNotReady) { // Don't set up encryption (no nigori node created). // Should fail. Triggers an OnPassphraseRequired because the cryptographer // is not ready. EXPECT_CALL(encryption_observer_, OnPassphraseRequired(_, _)).Times(1); EXPECT_CALL(encryption_observer_, OnCryptographerStateChanged(_)); EXPECT_CALL(encryption_observer_, OnEncryptedTypesChanged(_, false)); sync_manager_.GetEncryptionHandler()->Init(); PumpLoop(); const ModelTypeSet encrypted_types = GetEncryptedTypes(); EXPECT_TRUE(encrypted_types.Has(PASSWORDS)); // Hardcoded. EXPECT_FALSE(EncryptEverythingEnabledForTest()); } // Attempt to refresh encryption when nigori is empty. TEST_F(SyncManagerTest, RefreshEncryptionEmptyNigori) { EXPECT_TRUE(SetUpEncryption(DONT_WRITE_NIGORI, DEFAULT_ENCRYPTION)); EXPECT_CALL(encryption_observer_, OnEncryptionComplete()).Times(1); EXPECT_CALL(encryption_observer_, OnCryptographerStateChanged(_)); EXPECT_CALL(encryption_observer_, OnEncryptedTypesChanged(_, false)); // Should write to nigori. sync_manager_.GetEncryptionHandler()->Init(); PumpLoop(); const ModelTypeSet encrypted_types = GetEncryptedTypes(); EXPECT_TRUE(encrypted_types.Has(PASSWORDS)); // Hardcoded. EXPECT_FALSE(EncryptEverythingEnabledForTest()); { ReadTransaction trans(FROM_HERE, sync_manager_.GetUserShare()); ReadNode node(&trans); EXPECT_EQ(BaseNode::INIT_OK, node.InitByIdLookup(GetIdForDataType(NIGORI))); sync_pb::NigoriSpecifics nigori = node.GetNigoriSpecifics(); EXPECT_TRUE(nigori.has_encryption_keybag()); Cryptographer* cryptographer = trans.GetCryptographer(); EXPECT_TRUE(cryptographer->is_ready()); EXPECT_TRUE(cryptographer->CanDecrypt(nigori.encryption_keybag())); } } TEST_F(SyncManagerTest, EncryptDataTypesWithNoData) { EXPECT_TRUE(SetUpEncryption(WRITE_TO_NIGORI, DEFAULT_ENCRYPTION)); EXPECT_CALL(encryption_observer_, OnEncryptedTypesChanged( HasModelTypes(EncryptableUserTypes()), true)); EXPECT_CALL(encryption_observer_, OnEncryptionComplete()); sync_manager_.GetEncryptionHandler()->EnableEncryptEverything(); EXPECT_TRUE(EncryptEverythingEnabledForTest()); } TEST_F(SyncManagerTest, EncryptDataTypesWithData) { size_t batch_size = 5; EXPECT_TRUE(SetUpEncryption(WRITE_TO_NIGORI, DEFAULT_ENCRYPTION)); // Create some unencrypted unsynced data. int64 folder = MakeFolderWithParent(sync_manager_.GetUserShare(), BOOKMARKS, GetIdForDataType(BOOKMARKS), NULL); // First batch_size nodes are children of folder. size_t i; for (i = 0; i < batch_size; ++i) { MakeBookmarkWithParent(sync_manager_.GetUserShare(), folder, NULL); } // Next batch_size nodes are a different type and on their own. for (; i < 2*batch_size; ++i) { MakeNode(sync_manager_.GetUserShare(), SESSIONS, base::StringPrintf("%" PRIuS "", i)); } // Last batch_size nodes are a third type that will not need encryption. for (; i < 3*batch_size; ++i) { MakeNode(sync_manager_.GetUserShare(), THEMES, base::StringPrintf("%" PRIuS "", i)); } { ReadTransaction trans(FROM_HERE, sync_manager_.GetUserShare()); EXPECT_TRUE(GetEncryptedTypesWithTrans(&trans).Equals( SyncEncryptionHandler::SensitiveTypes())); EXPECT_TRUE(syncable::VerifyDataTypeEncryptionForTest( trans.GetWrappedTrans(), BOOKMARKS, false /* not encrypted */)); EXPECT_TRUE(syncable::VerifyDataTypeEncryptionForTest( trans.GetWrappedTrans(), SESSIONS, false /* not encrypted */)); EXPECT_TRUE(syncable::VerifyDataTypeEncryptionForTest( trans.GetWrappedTrans(), THEMES, false /* not encrypted */)); } EXPECT_CALL(encryption_observer_, OnEncryptedTypesChanged( HasModelTypes(EncryptableUserTypes()), true)); EXPECT_CALL(encryption_observer_, OnEncryptionComplete()); sync_manager_.GetEncryptionHandler()->EnableEncryptEverything(); EXPECT_TRUE(EncryptEverythingEnabledForTest()); { ReadTransaction trans(FROM_HERE, sync_manager_.GetUserShare()); EXPECT_TRUE(GetEncryptedTypesWithTrans(&trans).Equals( EncryptableUserTypes())); EXPECT_TRUE(syncable::VerifyDataTypeEncryptionForTest( trans.GetWrappedTrans(), BOOKMARKS, true /* is encrypted */)); EXPECT_TRUE(syncable::VerifyDataTypeEncryptionForTest( trans.GetWrappedTrans(), SESSIONS, true /* is encrypted */)); EXPECT_TRUE(syncable::VerifyDataTypeEncryptionForTest( trans.GetWrappedTrans(), THEMES, true /* is encrypted */)); } // Trigger's a ReEncryptEverything with new passphrase. testing::Mock::VerifyAndClearExpectations(&encryption_observer_); EXPECT_CALL(encryption_observer_, OnBootstrapTokenUpdated(_, PASSPHRASE_BOOTSTRAP_TOKEN)); EXPECT_CALL(encryption_observer_, OnPassphraseAccepted()); EXPECT_CALL(encryption_observer_, OnEncryptionComplete()); EXPECT_CALL(encryption_observer_, OnCryptographerStateChanged(_)); EXPECT_CALL(encryption_observer_, OnPassphraseTypeChanged(CUSTOM_PASSPHRASE, _)); sync_manager_.GetEncryptionHandler()->SetEncryptionPassphrase( "new_passphrase", true); EXPECT_TRUE(EncryptEverythingEnabledForTest()); { ReadTransaction trans(FROM_HERE, sync_manager_.GetUserShare()); EXPECT_TRUE(GetEncryptedTypesWithTrans(&trans).Equals( EncryptableUserTypes())); EXPECT_TRUE(syncable::VerifyDataTypeEncryptionForTest( trans.GetWrappedTrans(), BOOKMARKS, true /* is encrypted */)); EXPECT_TRUE(syncable::VerifyDataTypeEncryptionForTest( trans.GetWrappedTrans(), SESSIONS, true /* is encrypted */)); EXPECT_TRUE(syncable::VerifyDataTypeEncryptionForTest( trans.GetWrappedTrans(), THEMES, true /* is encrypted */)); } // Calling EncryptDataTypes with an empty encrypted types should not trigger // a reencryption and should just notify immediately. testing::Mock::VerifyAndClearExpectations(&encryption_observer_); EXPECT_CALL(encryption_observer_, OnBootstrapTokenUpdated(_, PASSPHRASE_BOOTSTRAP_TOKEN)).Times(0); EXPECT_CALL(encryption_observer_, OnPassphraseAccepted()).Times(0); EXPECT_CALL(encryption_observer_, OnEncryptionComplete()).Times(0); sync_manager_.GetEncryptionHandler()->EnableEncryptEverything(); } // Test that when there are no pending keys and the cryptographer is not // initialized, we add a key based on the current GAIA password. // (case 1 in SyncManager::SyncInternal::SetEncryptionPassphrase) TEST_F(SyncManagerTest, SetInitialGaiaPass) { EXPECT_FALSE(SetUpEncryption(DONT_WRITE_NIGORI, UNINITIALIZED)); EXPECT_CALL(encryption_observer_, OnBootstrapTokenUpdated(_, PASSPHRASE_BOOTSTRAP_TOKEN)); EXPECT_CALL(encryption_observer_, OnPassphraseAccepted()); EXPECT_CALL(encryption_observer_, OnEncryptionComplete()); EXPECT_CALL(encryption_observer_, OnCryptographerStateChanged(_)); sync_manager_.GetEncryptionHandler()->SetEncryptionPassphrase( "new_passphrase", false); EXPECT_EQ(IMPLICIT_PASSPHRASE, sync_manager_.GetEncryptionHandler()->GetPassphraseType()); EXPECT_FALSE(EncryptEverythingEnabledForTest()); { ReadTransaction trans(FROM_HERE, sync_manager_.GetUserShare()); ReadNode node(&trans); EXPECT_EQ(BaseNode::INIT_OK, node.InitByTagLookup(kNigoriTag)); sync_pb::NigoriSpecifics nigori = node.GetNigoriSpecifics(); Cryptographer* cryptographer = trans.GetCryptographer(); EXPECT_TRUE(cryptographer->is_ready()); EXPECT_TRUE(cryptographer->CanDecrypt(nigori.encryption_keybag())); } } // Test that when there are no pending keys and we have on the old GAIA // password, we update and re-encrypt everything with the new GAIA password. // (case 1 in SyncManager::SyncInternal::SetEncryptionPassphrase) TEST_F(SyncManagerTest, UpdateGaiaPass) { EXPECT_TRUE(SetUpEncryption(WRITE_TO_NIGORI, DEFAULT_ENCRYPTION)); Cryptographer verifier(&encryptor_); { ReadTransaction trans(FROM_HERE, sync_manager_.GetUserShare()); Cryptographer* cryptographer = trans.GetCryptographer(); std::string bootstrap_token; cryptographer->GetBootstrapToken(&bootstrap_token); verifier.Bootstrap(bootstrap_token); } EXPECT_CALL(encryption_observer_, OnBootstrapTokenUpdated(_, PASSPHRASE_BOOTSTRAP_TOKEN)); EXPECT_CALL(encryption_observer_, OnPassphraseAccepted()); EXPECT_CALL(encryption_observer_, OnEncryptionComplete()); EXPECT_CALL(encryption_observer_, OnCryptographerStateChanged(_)); sync_manager_.GetEncryptionHandler()->SetEncryptionPassphrase( "new_passphrase", false); EXPECT_EQ(IMPLICIT_PASSPHRASE, sync_manager_.GetEncryptionHandler()->GetPassphraseType()); EXPECT_FALSE(EncryptEverythingEnabledForTest()); { ReadTransaction trans(FROM_HERE, sync_manager_.GetUserShare()); Cryptographer* cryptographer = trans.GetCryptographer(); EXPECT_TRUE(cryptographer->is_ready()); // Verify the default key has changed. sync_pb::EncryptedData encrypted; cryptographer->GetKeys(&encrypted); EXPECT_FALSE(verifier.CanDecrypt(encrypted)); } } // Sets a new explicit passphrase. This should update the bootstrap token // and re-encrypt everything. // (case 2 in SyncManager::SyncInternal::SetEncryptionPassphrase) TEST_F(SyncManagerTest, SetPassphraseWithPassword) { Cryptographer verifier(&encryptor_); EXPECT_TRUE(SetUpEncryption(WRITE_TO_NIGORI, DEFAULT_ENCRYPTION)); { WriteTransaction trans(FROM_HERE, sync_manager_.GetUserShare()); // Store the default (soon to be old) key. Cryptographer* cryptographer = trans.GetCryptographer(); std::string bootstrap_token; cryptographer->GetBootstrapToken(&bootstrap_token); verifier.Bootstrap(bootstrap_token); ReadNode root_node(&trans); root_node.InitByRootLookup(); WriteNode password_node(&trans); WriteNode::InitUniqueByCreationResult result = password_node.InitUniqueByCreation(PASSWORDS, root_node, "foo"); EXPECT_EQ(WriteNode::INIT_SUCCESS, result); sync_pb::PasswordSpecificsData data; data.set_password_value("secret"); password_node.SetPasswordSpecifics(data); } EXPECT_CALL(encryption_observer_, OnBootstrapTokenUpdated(_, PASSPHRASE_BOOTSTRAP_TOKEN)); EXPECT_CALL(encryption_observer_, OnPassphraseAccepted()); EXPECT_CALL(encryption_observer_, OnEncryptionComplete()); EXPECT_CALL(encryption_observer_, OnCryptographerStateChanged(_)); EXPECT_CALL(encryption_observer_, OnPassphraseTypeChanged(CUSTOM_PASSPHRASE, _)); sync_manager_.GetEncryptionHandler()->SetEncryptionPassphrase( "new_passphrase", true); EXPECT_EQ(CUSTOM_PASSPHRASE, sync_manager_.GetEncryptionHandler()->GetPassphraseType()); EXPECT_FALSE(EncryptEverythingEnabledForTest()); { ReadTransaction trans(FROM_HERE, sync_manager_.GetUserShare()); Cryptographer* cryptographer = trans.GetCryptographer(); EXPECT_TRUE(cryptographer->is_ready()); // Verify the default key has changed. sync_pb::EncryptedData encrypted; cryptographer->GetKeys(&encrypted); EXPECT_FALSE(verifier.CanDecrypt(encrypted)); ReadNode password_node(&trans); EXPECT_EQ(BaseNode::INIT_OK, password_node.InitByClientTagLookup(PASSWORDS, "foo")); const sync_pb::PasswordSpecificsData& data = password_node.GetPasswordSpecifics(); EXPECT_EQ("secret", data.password_value()); } } // Manually set the pending keys in the cryptographer/nigori to reflect the data // being encrypted with a new (unprovided) GAIA password, then supply the // password. // (case 7 in SyncManager::SyncInternal::SetDecryptionPassphrase) TEST_F(SyncManagerTest, SupplyPendingGAIAPass) { EXPECT_TRUE(SetUpEncryption(WRITE_TO_NIGORI, DEFAULT_ENCRYPTION)); Cryptographer other_cryptographer(&encryptor_); { WriteTransaction trans(FROM_HERE, sync_manager_.GetUserShare()); Cryptographer* cryptographer = trans.GetCryptographer(); std::string bootstrap_token; cryptographer->GetBootstrapToken(&bootstrap_token); other_cryptographer.Bootstrap(bootstrap_token); // Now update the nigori to reflect the new keys, and update the // cryptographer to have pending keys. KeyParams params = {"localhost", "dummy", "passphrase2"}; other_cryptographer.AddKey(params); WriteNode node(&trans); EXPECT_EQ(BaseNode::INIT_OK, node.InitByTagLookup(kNigoriTag)); sync_pb::NigoriSpecifics nigori; other_cryptographer.GetKeys(nigori.mutable_encryption_keybag()); cryptographer->SetPendingKeys(nigori.encryption_keybag()); EXPECT_TRUE(cryptographer->has_pending_keys()); node.SetNigoriSpecifics(nigori); } EXPECT_CALL(encryption_observer_, OnBootstrapTokenUpdated(_, PASSPHRASE_BOOTSTRAP_TOKEN)); EXPECT_CALL(encryption_observer_, OnPassphraseAccepted()); EXPECT_CALL(encryption_observer_, OnEncryptionComplete()); EXPECT_CALL(encryption_observer_, OnCryptographerStateChanged(_)); sync_manager_.GetEncryptionHandler()->SetDecryptionPassphrase("passphrase2"); EXPECT_EQ(IMPLICIT_PASSPHRASE, sync_manager_.GetEncryptionHandler()->GetPassphraseType()); EXPECT_FALSE(EncryptEverythingEnabledForTest()); { ReadTransaction trans(FROM_HERE, sync_manager_.GetUserShare()); Cryptographer* cryptographer = trans.GetCryptographer(); EXPECT_TRUE(cryptographer->is_ready()); // Verify we're encrypting with the new key. sync_pb::EncryptedData encrypted; cryptographer->GetKeys(&encrypted); EXPECT_TRUE(other_cryptographer.CanDecrypt(encrypted)); } } // Manually set the pending keys in the cryptographer/nigori to reflect the data // being encrypted with an old (unprovided) GAIA password. Attempt to supply // the current GAIA password and verify the bootstrap token is updated. Then // supply the old GAIA password, and verify we re-encrypt all data with the // new GAIA password. // (cases 4 and 5 in SyncManager::SyncInternal::SetEncryptionPassphrase) TEST_F(SyncManagerTest, SupplyPendingOldGAIAPass) { EXPECT_TRUE(SetUpEncryption(WRITE_TO_NIGORI, DEFAULT_ENCRYPTION)); Cryptographer other_cryptographer(&encryptor_); { WriteTransaction trans(FROM_HERE, sync_manager_.GetUserShare()); Cryptographer* cryptographer = trans.GetCryptographer(); std::string bootstrap_token; cryptographer->GetBootstrapToken(&bootstrap_token); other_cryptographer.Bootstrap(bootstrap_token); // Now update the nigori to reflect the new keys, and update the // cryptographer to have pending keys. KeyParams params = {"localhost", "dummy", "old_gaia"}; other_cryptographer.AddKey(params); WriteNode node(&trans); EXPECT_EQ(BaseNode::INIT_OK, node.InitByTagLookup(kNigoriTag)); sync_pb::NigoriSpecifics nigori; other_cryptographer.GetKeys(nigori.mutable_encryption_keybag()); node.SetNigoriSpecifics(nigori); cryptographer->SetPendingKeys(nigori.encryption_keybag()); // other_cryptographer now contains all encryption keys, and is encrypting // with the newest gaia. KeyParams new_params = {"localhost", "dummy", "new_gaia"}; other_cryptographer.AddKey(new_params); } // The bootstrap token should have been updated. Save it to ensure it's based // on the new GAIA password. std::string bootstrap_token; EXPECT_CALL(encryption_observer_, OnBootstrapTokenUpdated(_, PASSPHRASE_BOOTSTRAP_TOKEN)) .WillOnce(SaveArg<0>(&bootstrap_token)); EXPECT_CALL(encryption_observer_, OnPassphraseRequired(_,_)); EXPECT_CALL(encryption_observer_, OnCryptographerStateChanged(_)); sync_manager_.GetEncryptionHandler()->SetEncryptionPassphrase( "new_gaia", false); EXPECT_EQ(IMPLICIT_PASSPHRASE, sync_manager_.GetEncryptionHandler()->GetPassphraseType()); EXPECT_FALSE(EncryptEverythingEnabledForTest()); testing::Mock::VerifyAndClearExpectations(&encryption_observer_); { ReadTransaction trans(FROM_HERE, sync_manager_.GetUserShare()); Cryptographer* cryptographer = trans.GetCryptographer(); EXPECT_TRUE(cryptographer->is_initialized()); EXPECT_FALSE(cryptographer->is_ready()); // Verify we're encrypting with the new key, even though we have pending // keys. sync_pb::EncryptedData encrypted; other_cryptographer.GetKeys(&encrypted); EXPECT_TRUE(cryptographer->CanDecrypt(encrypted)); } EXPECT_CALL(encryption_observer_, OnBootstrapTokenUpdated(_, PASSPHRASE_BOOTSTRAP_TOKEN)); EXPECT_CALL(encryption_observer_, OnPassphraseAccepted()); EXPECT_CALL(encryption_observer_, OnEncryptionComplete()); EXPECT_CALL(encryption_observer_, OnCryptographerStateChanged(_)); sync_manager_.GetEncryptionHandler()->SetEncryptionPassphrase( "old_gaia", false); EXPECT_EQ(IMPLICIT_PASSPHRASE, sync_manager_.GetEncryptionHandler()->GetPassphraseType()); { ReadTransaction trans(FROM_HERE, sync_manager_.GetUserShare()); Cryptographer* cryptographer = trans.GetCryptographer(); EXPECT_TRUE(cryptographer->is_ready()); // Verify we're encrypting with the new key. sync_pb::EncryptedData encrypted; other_cryptographer.GetKeys(&encrypted); EXPECT_TRUE(cryptographer->CanDecrypt(encrypted)); // Verify the saved bootstrap token is based on the new gaia password. Cryptographer temp_cryptographer(&encryptor_); temp_cryptographer.Bootstrap(bootstrap_token); EXPECT_TRUE(temp_cryptographer.CanDecrypt(encrypted)); } } // Manually set the pending keys in the cryptographer/nigori to reflect the data // being encrypted with an explicit (unprovided) passphrase, then supply the // passphrase. // (case 9 in SyncManager::SyncInternal::SetDecryptionPassphrase) TEST_F(SyncManagerTest, SupplyPendingExplicitPass) { EXPECT_TRUE(SetUpEncryption(WRITE_TO_NIGORI, DEFAULT_ENCRYPTION)); Cryptographer other_cryptographer(&encryptor_); { WriteTransaction trans(FROM_HERE, sync_manager_.GetUserShare()); Cryptographer* cryptographer = trans.GetCryptographer(); std::string bootstrap_token; cryptographer->GetBootstrapToken(&bootstrap_token); other_cryptographer.Bootstrap(bootstrap_token); // Now update the nigori to reflect the new keys, and update the // cryptographer to have pending keys. KeyParams params = {"localhost", "dummy", "explicit"}; other_cryptographer.AddKey(params); WriteNode node(&trans); EXPECT_EQ(BaseNode::INIT_OK, node.InitByTagLookup(kNigoriTag)); sync_pb::NigoriSpecifics nigori; other_cryptographer.GetKeys(nigori.mutable_encryption_keybag()); cryptographer->SetPendingKeys(nigori.encryption_keybag()); EXPECT_TRUE(cryptographer->has_pending_keys()); nigori.set_keybag_is_frozen(true); node.SetNigoriSpecifics(nigori); } EXPECT_CALL(encryption_observer_, OnCryptographerStateChanged(_)); EXPECT_CALL(encryption_observer_, OnPassphraseTypeChanged(CUSTOM_PASSPHRASE, _)); EXPECT_CALL(encryption_observer_, OnPassphraseRequired(_, _)); EXPECT_CALL(encryption_observer_, OnEncryptedTypesChanged(_, false)); sync_manager_.GetEncryptionHandler()->Init(); EXPECT_CALL(encryption_observer_, OnBootstrapTokenUpdated(_, PASSPHRASE_BOOTSTRAP_TOKEN)); EXPECT_CALL(encryption_observer_, OnPassphraseAccepted()); EXPECT_CALL(encryption_observer_, OnEncryptionComplete()); EXPECT_CALL(encryption_observer_, OnCryptographerStateChanged(_)); sync_manager_.GetEncryptionHandler()->SetDecryptionPassphrase("explicit"); EXPECT_EQ(CUSTOM_PASSPHRASE, sync_manager_.GetEncryptionHandler()->GetPassphraseType()); EXPECT_FALSE(EncryptEverythingEnabledForTest()); { ReadTransaction trans(FROM_HERE, sync_manager_.GetUserShare()); Cryptographer* cryptographer = trans.GetCryptographer(); EXPECT_TRUE(cryptographer->is_ready()); // Verify we're encrypting with the new key. sync_pb::EncryptedData encrypted; cryptographer->GetKeys(&encrypted); EXPECT_TRUE(other_cryptographer.CanDecrypt(encrypted)); } } // Manually set the pending keys in the cryptographer/nigori to reflect the data // being encrypted with a new (unprovided) GAIA password, then supply the // password as a user-provided password. // This is the android case 7/8. TEST_F(SyncManagerTest, SupplyPendingGAIAPassUserProvided) { EXPECT_FALSE(SetUpEncryption(DONT_WRITE_NIGORI, UNINITIALIZED)); Cryptographer other_cryptographer(&encryptor_); { WriteTransaction trans(FROM_HERE, sync_manager_.GetUserShare()); Cryptographer* cryptographer = trans.GetCryptographer(); // Now update the nigori to reflect the new keys, and update the // cryptographer to have pending keys. KeyParams params = {"localhost", "dummy", "passphrase"}; other_cryptographer.AddKey(params); WriteNode node(&trans); EXPECT_EQ(BaseNode::INIT_OK, node.InitByTagLookup(kNigoriTag)); sync_pb::NigoriSpecifics nigori; other_cryptographer.GetKeys(nigori.mutable_encryption_keybag()); node.SetNigoriSpecifics(nigori); cryptographer->SetPendingKeys(nigori.encryption_keybag()); EXPECT_FALSE(cryptographer->is_ready()); } EXPECT_CALL(encryption_observer_, OnBootstrapTokenUpdated(_, PASSPHRASE_BOOTSTRAP_TOKEN)); EXPECT_CALL(encryption_observer_, OnPassphraseAccepted()); EXPECT_CALL(encryption_observer_, OnEncryptionComplete()); EXPECT_CALL(encryption_observer_, OnCryptographerStateChanged(_)); sync_manager_.GetEncryptionHandler()->SetEncryptionPassphrase( "passphrase", false); EXPECT_EQ(IMPLICIT_PASSPHRASE, sync_manager_.GetEncryptionHandler()->GetPassphraseType()); EXPECT_FALSE(EncryptEverythingEnabledForTest()); { ReadTransaction trans(FROM_HERE, sync_manager_.GetUserShare()); Cryptographer* cryptographer = trans.GetCryptographer(); EXPECT_TRUE(cryptographer->is_ready()); } } TEST_F(SyncManagerTest, SetPassphraseWithEmptyPasswordNode) { EXPECT_TRUE(SetUpEncryption(WRITE_TO_NIGORI, DEFAULT_ENCRYPTION)); int64 node_id = 0; std::string tag = "foo"; { WriteTransaction trans(FROM_HERE, sync_manager_.GetUserShare()); ReadNode root_node(&trans); root_node.InitByRootLookup(); WriteNode password_node(&trans); WriteNode::InitUniqueByCreationResult result = password_node.InitUniqueByCreation(PASSWORDS, root_node, tag); EXPECT_EQ(WriteNode::INIT_SUCCESS, result); node_id = password_node.GetId(); } EXPECT_CALL(encryption_observer_, OnBootstrapTokenUpdated(_, PASSPHRASE_BOOTSTRAP_TOKEN)); EXPECT_CALL(encryption_observer_, OnPassphraseAccepted()); EXPECT_CALL(encryption_observer_, OnEncryptionComplete()); EXPECT_CALL(encryption_observer_, OnCryptographerStateChanged(_)); EXPECT_CALL(encryption_observer_, OnPassphraseTypeChanged(CUSTOM_PASSPHRASE, _)); sync_manager_.GetEncryptionHandler()->SetEncryptionPassphrase( "new_passphrase", true); EXPECT_EQ(CUSTOM_PASSPHRASE, sync_manager_.GetEncryptionHandler()->GetPassphraseType()); EXPECT_FALSE(EncryptEverythingEnabledForTest()); { ReadTransaction trans(FROM_HERE, sync_manager_.GetUserShare()); ReadNode password_node(&trans); EXPECT_EQ(BaseNode::INIT_FAILED_DECRYPT_IF_NECESSARY, password_node.InitByClientTagLookup(PASSWORDS, tag)); } { ReadTransaction trans(FROM_HERE, sync_manager_.GetUserShare()); ReadNode password_node(&trans); EXPECT_EQ(BaseNode::INIT_FAILED_DECRYPT_IF_NECESSARY, password_node.InitByIdLookup(node_id)); } } TEST_F(SyncManagerTest, NudgeDelayTest) { EXPECT_EQ(sync_manager_.GetNudgeDelayTimeDelta(BOOKMARKS), base::TimeDelta::FromMilliseconds( SyncManagerImpl::GetDefaultNudgeDelay())); EXPECT_EQ(sync_manager_.GetNudgeDelayTimeDelta(AUTOFILL), base::TimeDelta::FromSeconds( kDefaultShortPollIntervalSeconds)); EXPECT_EQ(sync_manager_.GetNudgeDelayTimeDelta(PREFERENCES), base::TimeDelta::FromMilliseconds( SyncManagerImpl::GetPreferencesNudgeDelay())); } // Friended by WriteNode, so can't be in an anonymouse namespace. TEST_F(SyncManagerTest, EncryptBookmarksWithLegacyData) { EXPECT_TRUE(SetUpEncryption(WRITE_TO_NIGORI, DEFAULT_ENCRYPTION)); std::string title; SyncAPINameToServerName("Google", &title); std::string url = "http://www.google.com"; std::string raw_title2 = ".."; // An invalid cosmo title. std::string title2; SyncAPINameToServerName(raw_title2, &title2); std::string url2 = "http://www.bla.com"; // Create a bookmark using the legacy format. int64 node_id1 = MakeNode(sync_manager_.GetUserShare(), BOOKMARKS, "testtag"); int64 node_id2 = MakeNode(sync_manager_.GetUserShare(), BOOKMARKS, "testtag2"); { WriteTransaction trans(FROM_HERE, sync_manager_.GetUserShare()); WriteNode node(&trans); EXPECT_EQ(BaseNode::INIT_OK, node.InitByIdLookup(node_id1)); sync_pb::EntitySpecifics entity_specifics; entity_specifics.mutable_bookmark()->set_url(url); node.SetEntitySpecifics(entity_specifics); // Set the old style title. syncable::MutableEntry* node_entry = node.entry_; node_entry->Put(syncable::NON_UNIQUE_NAME, title); WriteNode node2(&trans); EXPECT_EQ(BaseNode::INIT_OK, node2.InitByIdLookup(node_id2)); sync_pb::EntitySpecifics entity_specifics2; entity_specifics2.mutable_bookmark()->set_url(url2); node2.SetEntitySpecifics(entity_specifics2); // Set the old style title. syncable::MutableEntry* node_entry2 = node2.entry_; node_entry2->Put(syncable::NON_UNIQUE_NAME, title2); } { ReadTransaction trans(FROM_HERE, sync_manager_.GetUserShare()); ReadNode node(&trans); EXPECT_EQ(BaseNode::INIT_OK, node.InitByIdLookup(node_id1)); EXPECT_EQ(BOOKMARKS, node.GetModelType()); EXPECT_EQ(title, node.GetTitle()); EXPECT_EQ(title, node.GetBookmarkSpecifics().title()); EXPECT_EQ(url, node.GetBookmarkSpecifics().url()); ReadNode node2(&trans); EXPECT_EQ(BaseNode::INIT_OK, node2.InitByIdLookup(node_id2)); EXPECT_EQ(BOOKMARKS, node2.GetModelType()); // We should de-canonicalize the title in GetTitle(), but the title in the // specifics should be stored in the server legal form. EXPECT_EQ(raw_title2, node2.GetTitle()); EXPECT_EQ(title2, node2.GetBookmarkSpecifics().title()); EXPECT_EQ(url2, node2.GetBookmarkSpecifics().url()); } { ReadTransaction trans(FROM_HERE, sync_manager_.GetUserShare()); EXPECT_TRUE(syncable::VerifyDataTypeEncryptionForTest( trans.GetWrappedTrans(), BOOKMARKS, false /* not encrypted */)); } EXPECT_CALL(encryption_observer_, OnEncryptedTypesChanged( HasModelTypes(EncryptableUserTypes()), true)); EXPECT_CALL(encryption_observer_, OnEncryptionComplete()); sync_manager_.GetEncryptionHandler()->EnableEncryptEverything(); EXPECT_TRUE(EncryptEverythingEnabledForTest()); { ReadTransaction trans(FROM_HERE, sync_manager_.GetUserShare()); EXPECT_TRUE(GetEncryptedTypesWithTrans(&trans).Equals( EncryptableUserTypes())); EXPECT_TRUE(syncable::VerifyDataTypeEncryptionForTest( trans.GetWrappedTrans(), BOOKMARKS, true /* is encrypted */)); ReadNode node(&trans); EXPECT_EQ(BaseNode::INIT_OK, node.InitByIdLookup(node_id1)); EXPECT_EQ(BOOKMARKS, node.GetModelType()); EXPECT_EQ(title, node.GetTitle()); EXPECT_EQ(title, node.GetBookmarkSpecifics().title()); EXPECT_EQ(url, node.GetBookmarkSpecifics().url()); ReadNode node2(&trans); EXPECT_EQ(BaseNode::INIT_OK, node2.InitByIdLookup(node_id2)); EXPECT_EQ(BOOKMARKS, node2.GetModelType()); // We should de-canonicalize the title in GetTitle(), but the title in the // specifics should be stored in the server legal form. EXPECT_EQ(raw_title2, node2.GetTitle()); EXPECT_EQ(title2, node2.GetBookmarkSpecifics().title()); EXPECT_EQ(url2, node2.GetBookmarkSpecifics().url()); } } // Create a bookmark and set the title/url, then verify the data was properly // set. This replicates the unique way bookmarks have of creating sync nodes. // See BookmarkChangeProcessor::PlaceSyncNode(..). TEST_F(SyncManagerTest, CreateLocalBookmark) { std::string title = "title"; std::string url = "url"; { WriteTransaction trans(FROM_HERE, sync_manager_.GetUserShare()); ReadNode bookmark_root(&trans); ASSERT_EQ(BaseNode::INIT_OK, bookmark_root.InitByTagLookup(ModelTypeToRootTag(BOOKMARKS))); WriteNode node(&trans); ASSERT_TRUE(node.InitBookmarkByCreation(bookmark_root, NULL)); node.SetIsFolder(false); node.SetTitle(UTF8ToWide(title)); sync_pb::BookmarkSpecifics bookmark_specifics(node.GetBookmarkSpecifics()); bookmark_specifics.set_url(url); node.SetBookmarkSpecifics(bookmark_specifics); } { ReadTransaction trans(FROM_HERE, sync_manager_.GetUserShare()); ReadNode bookmark_root(&trans); ASSERT_EQ(BaseNode::INIT_OK, bookmark_root.InitByTagLookup(ModelTypeToRootTag(BOOKMARKS))); int64 child_id = bookmark_root.GetFirstChildId(); ReadNode node(&trans); ASSERT_EQ(BaseNode::INIT_OK, node.InitByIdLookup(child_id)); EXPECT_FALSE(node.GetIsFolder()); EXPECT_EQ(title, node.GetTitle()); EXPECT_EQ(url, node.GetBookmarkSpecifics().url()); } } // Verifies WriteNode::UpdateEntryWithEncryption does not make unnecessary // changes. TEST_F(SyncManagerTest, UpdateEntryWithEncryption) { std::string client_tag = "title"; sync_pb::EntitySpecifics entity_specifics; entity_specifics.mutable_bookmark()->set_url("url"); entity_specifics.mutable_bookmark()->set_title("title"); MakeServerNode(sync_manager_.GetUserShare(), BOOKMARKS, client_tag, syncable::GenerateSyncableHash(BOOKMARKS, client_tag), entity_specifics); // New node shouldn't start off unsynced. EXPECT_FALSE(ResetUnsyncedEntry(BOOKMARKS, client_tag)); // Manually change to the same data. Should not set is_unsynced. { WriteTransaction trans(FROM_HERE, sync_manager_.GetUserShare()); WriteNode node(&trans); EXPECT_EQ(BaseNode::INIT_OK, node.InitByClientTagLookup(BOOKMARKS, client_tag)); node.SetEntitySpecifics(entity_specifics); } EXPECT_FALSE(ResetUnsyncedEntry(BOOKMARKS, client_tag)); // Encrypt the datatatype, should set is_unsynced. EXPECT_CALL(encryption_observer_, OnEncryptedTypesChanged( HasModelTypes(EncryptableUserTypes()), true)); EXPECT_CALL(encryption_observer_, OnEncryptionComplete()); EXPECT_TRUE(SetUpEncryption(WRITE_TO_NIGORI, FULL_ENCRYPTION)); EXPECT_CALL(encryption_observer_, OnCryptographerStateChanged(_)); EXPECT_CALL(encryption_observer_, OnEncryptedTypesChanged(_, true)); sync_manager_.GetEncryptionHandler()->Init(); PumpLoop(); { ReadTransaction trans(FROM_HERE, sync_manager_.GetUserShare()); ReadNode node(&trans); EXPECT_EQ(BaseNode::INIT_OK, node.InitByClientTagLookup(BOOKMARKS, client_tag)); const syncable::Entry* node_entry = node.GetEntry(); const sync_pb::EntitySpecifics& specifics = node_entry->Get(SPECIFICS); EXPECT_TRUE(specifics.has_encrypted()); EXPECT_EQ(kEncryptedString, node_entry->Get(NON_UNIQUE_NAME)); Cryptographer* cryptographer = trans.GetCryptographer(); EXPECT_TRUE(cryptographer->is_ready()); EXPECT_TRUE(cryptographer->CanDecryptUsingDefaultKey( specifics.encrypted())); } EXPECT_TRUE(ResetUnsyncedEntry(BOOKMARKS, client_tag)); // Set a new passphrase. Should set is_unsynced. testing::Mock::VerifyAndClearExpectations(&encryption_observer_); EXPECT_CALL(encryption_observer_, OnBootstrapTokenUpdated(_, PASSPHRASE_BOOTSTRAP_TOKEN)); EXPECT_CALL(encryption_observer_, OnPassphraseAccepted()); EXPECT_CALL(encryption_observer_, OnEncryptionComplete()); EXPECT_CALL(encryption_observer_, OnCryptographerStateChanged(_)); EXPECT_CALL(encryption_observer_, OnPassphraseTypeChanged(CUSTOM_PASSPHRASE, _)); sync_manager_.GetEncryptionHandler()->SetEncryptionPassphrase( "new_passphrase", true); { ReadTransaction trans(FROM_HERE, sync_manager_.GetUserShare()); ReadNode node(&trans); EXPECT_EQ(BaseNode::INIT_OK, node.InitByClientTagLookup(BOOKMARKS, client_tag)); const syncable::Entry* node_entry = node.GetEntry(); const sync_pb::EntitySpecifics& specifics = node_entry->Get(SPECIFICS); EXPECT_TRUE(specifics.has_encrypted()); EXPECT_EQ(kEncryptedString, node_entry->Get(NON_UNIQUE_NAME)); Cryptographer* cryptographer = trans.GetCryptographer(); EXPECT_TRUE(cryptographer->is_ready()); EXPECT_TRUE(cryptographer->CanDecryptUsingDefaultKey( specifics.encrypted())); } EXPECT_TRUE(ResetUnsyncedEntry(BOOKMARKS, client_tag)); // Force a re-encrypt everything. Should not set is_unsynced. testing::Mock::VerifyAndClearExpectations(&encryption_observer_); EXPECT_CALL(encryption_observer_, OnEncryptionComplete()); EXPECT_CALL(encryption_observer_, OnCryptographerStateChanged(_)); EXPECT_CALL(encryption_observer_, OnEncryptedTypesChanged(_, true)); sync_manager_.GetEncryptionHandler()->Init(); PumpLoop(); { ReadTransaction trans(FROM_HERE, sync_manager_.GetUserShare()); ReadNode node(&trans); EXPECT_EQ(BaseNode::INIT_OK, node.InitByClientTagLookup(BOOKMARKS, client_tag)); const syncable::Entry* node_entry = node.GetEntry(); const sync_pb::EntitySpecifics& specifics = node_entry->Get(SPECIFICS); EXPECT_TRUE(specifics.has_encrypted()); EXPECT_EQ(kEncryptedString, node_entry->Get(NON_UNIQUE_NAME)); Cryptographer* cryptographer = trans.GetCryptographer(); EXPECT_TRUE(cryptographer->CanDecryptUsingDefaultKey( specifics.encrypted())); } EXPECT_FALSE(ResetUnsyncedEntry(BOOKMARKS, client_tag)); // Manually change to the same data. Should not set is_unsynced. { WriteTransaction trans(FROM_HERE, sync_manager_.GetUserShare()); WriteNode node(&trans); EXPECT_EQ(BaseNode::INIT_OK, node.InitByClientTagLookup(BOOKMARKS, client_tag)); node.SetEntitySpecifics(entity_specifics); const syncable::Entry* node_entry = node.GetEntry(); const sync_pb::EntitySpecifics& specifics = node_entry->Get(SPECIFICS); EXPECT_TRUE(specifics.has_encrypted()); EXPECT_FALSE(node_entry->Get(IS_UNSYNCED)); EXPECT_EQ(kEncryptedString, node_entry->Get(NON_UNIQUE_NAME)); Cryptographer* cryptographer = trans.GetCryptographer(); EXPECT_TRUE(cryptographer->CanDecryptUsingDefaultKey( specifics.encrypted())); } EXPECT_FALSE(ResetUnsyncedEntry(BOOKMARKS, client_tag)); // Manually change to different data. Should set is_unsynced. { entity_specifics.mutable_bookmark()->set_url("url2"); entity_specifics.mutable_bookmark()->set_title("title2"); WriteTransaction trans(FROM_HERE, sync_manager_.GetUserShare()); WriteNode node(&trans); EXPECT_EQ(BaseNode::INIT_OK, node.InitByClientTagLookup(BOOKMARKS, client_tag)); node.SetEntitySpecifics(entity_specifics); const syncable::Entry* node_entry = node.GetEntry(); const sync_pb::EntitySpecifics& specifics = node_entry->Get(SPECIFICS); EXPECT_TRUE(specifics.has_encrypted()); EXPECT_TRUE(node_entry->Get(IS_UNSYNCED)); EXPECT_EQ(kEncryptedString, node_entry->Get(NON_UNIQUE_NAME)); Cryptographer* cryptographer = trans.GetCryptographer(); EXPECT_TRUE(cryptographer->CanDecryptUsingDefaultKey( specifics.encrypted())); } } // Passwords have their own handling for encryption. Verify it does not result // in unnecessary writes via SetEntitySpecifics. TEST_F(SyncManagerTest, UpdatePasswordSetEntitySpecificsNoChange) { std::string client_tag = "title"; EXPECT_TRUE(SetUpEncryption(WRITE_TO_NIGORI, DEFAULT_ENCRYPTION)); sync_pb::EntitySpecifics entity_specifics; { ReadTransaction trans(FROM_HERE, sync_manager_.GetUserShare()); Cryptographer* cryptographer = trans.GetCryptographer(); sync_pb::PasswordSpecificsData data; data.set_password_value("secret"); cryptographer->Encrypt( data, entity_specifics.mutable_password()-> mutable_encrypted()); } MakeServerNode(sync_manager_.GetUserShare(), PASSWORDS, client_tag, syncable::GenerateSyncableHash(PASSWORDS, client_tag), entity_specifics); // New node shouldn't start off unsynced. EXPECT_FALSE(ResetUnsyncedEntry(PASSWORDS, client_tag)); // Manually change to the same data via SetEntitySpecifics. Should not set // is_unsynced. { WriteTransaction trans(FROM_HERE, sync_manager_.GetUserShare()); WriteNode node(&trans); EXPECT_EQ(BaseNode::INIT_OK, node.InitByClientTagLookup(PASSWORDS, client_tag)); node.SetEntitySpecifics(entity_specifics); } EXPECT_FALSE(ResetUnsyncedEntry(PASSWORDS, client_tag)); } // Passwords have their own handling for encryption. Verify it does not result // in unnecessary writes via SetPasswordSpecifics. TEST_F(SyncManagerTest, UpdatePasswordSetPasswordSpecifics) { std::string client_tag = "title"; EXPECT_TRUE(SetUpEncryption(WRITE_TO_NIGORI, DEFAULT_ENCRYPTION)); sync_pb::EntitySpecifics entity_specifics; { ReadTransaction trans(FROM_HERE, sync_manager_.GetUserShare()); Cryptographer* cryptographer = trans.GetCryptographer(); sync_pb::PasswordSpecificsData data; data.set_password_value("secret"); cryptographer->Encrypt( data, entity_specifics.mutable_password()-> mutable_encrypted()); } MakeServerNode(sync_manager_.GetUserShare(), PASSWORDS, client_tag, syncable::GenerateSyncableHash(PASSWORDS, client_tag), entity_specifics); // New node shouldn't start off unsynced. EXPECT_FALSE(ResetUnsyncedEntry(PASSWORDS, client_tag)); // Manually change to the same data via SetPasswordSpecifics. Should not set // is_unsynced. { WriteTransaction trans(FROM_HERE, sync_manager_.GetUserShare()); WriteNode node(&trans); EXPECT_EQ(BaseNode::INIT_OK, node.InitByClientTagLookup(PASSWORDS, client_tag)); node.SetPasswordSpecifics(node.GetPasswordSpecifics()); } EXPECT_FALSE(ResetUnsyncedEntry(PASSWORDS, client_tag)); // Manually change to different data. Should set is_unsynced. { WriteTransaction trans(FROM_HERE, sync_manager_.GetUserShare()); WriteNode node(&trans); EXPECT_EQ(BaseNode::INIT_OK, node.InitByClientTagLookup(PASSWORDS, client_tag)); Cryptographer* cryptographer = trans.GetCryptographer(); sync_pb::PasswordSpecificsData data; data.set_password_value("secret2"); cryptographer->Encrypt( data, entity_specifics.mutable_password()->mutable_encrypted()); node.SetPasswordSpecifics(data); const syncable::Entry* node_entry = node.GetEntry(); EXPECT_TRUE(node_entry->Get(IS_UNSYNCED)); } } // Passwords have their own handling for encryption. Verify setting a new // passphrase updates the data. TEST_F(SyncManagerTest, UpdatePasswordNewPassphrase) { std::string client_tag = "title"; EXPECT_TRUE(SetUpEncryption(WRITE_TO_NIGORI, DEFAULT_ENCRYPTION)); sync_pb::EntitySpecifics entity_specifics; { ReadTransaction trans(FROM_HERE, sync_manager_.GetUserShare()); Cryptographer* cryptographer = trans.GetCryptographer(); sync_pb::PasswordSpecificsData data; data.set_password_value("secret"); cryptographer->Encrypt( data, entity_specifics.mutable_password()->mutable_encrypted()); } MakeServerNode(sync_manager_.GetUserShare(), PASSWORDS, client_tag, syncable::GenerateSyncableHash(PASSWORDS, client_tag), entity_specifics); // New node shouldn't start off unsynced. EXPECT_FALSE(ResetUnsyncedEntry(PASSWORDS, client_tag)); // Set a new passphrase. Should set is_unsynced. testing::Mock::VerifyAndClearExpectations(&encryption_observer_); EXPECT_CALL(encryption_observer_, OnBootstrapTokenUpdated(_, PASSPHRASE_BOOTSTRAP_TOKEN)); EXPECT_CALL(encryption_observer_, OnPassphraseAccepted()); EXPECT_CALL(encryption_observer_, OnEncryptionComplete()); EXPECT_CALL(encryption_observer_, OnCryptographerStateChanged(_)); EXPECT_CALL(encryption_observer_, OnPassphraseTypeChanged(CUSTOM_PASSPHRASE, _)); sync_manager_.GetEncryptionHandler()->SetEncryptionPassphrase( "new_passphrase", true); EXPECT_EQ(CUSTOM_PASSPHRASE, sync_manager_.GetEncryptionHandler()->GetPassphraseType()); EXPECT_TRUE(ResetUnsyncedEntry(PASSWORDS, client_tag)); } // Passwords have their own handling for encryption. Verify it does not result // in unnecessary writes via ReencryptEverything. TEST_F(SyncManagerTest, UpdatePasswordReencryptEverything) { std::string client_tag = "title"; EXPECT_TRUE(SetUpEncryption(WRITE_TO_NIGORI, DEFAULT_ENCRYPTION)); sync_pb::EntitySpecifics entity_specifics; { ReadTransaction trans(FROM_HERE, sync_manager_.GetUserShare()); Cryptographer* cryptographer = trans.GetCryptographer(); sync_pb::PasswordSpecificsData data; data.set_password_value("secret"); cryptographer->Encrypt( data, entity_specifics.mutable_password()->mutable_encrypted()); } MakeServerNode(sync_manager_.GetUserShare(), PASSWORDS, client_tag, syncable::GenerateSyncableHash(PASSWORDS, client_tag), entity_specifics); // New node shouldn't start off unsynced. EXPECT_FALSE(ResetUnsyncedEntry(PASSWORDS, client_tag)); // Force a re-encrypt everything. Should not set is_unsynced. testing::Mock::VerifyAndClearExpectations(&encryption_observer_); EXPECT_CALL(encryption_observer_, OnEncryptionComplete()); EXPECT_CALL(encryption_observer_, OnCryptographerStateChanged(_)); EXPECT_CALL(encryption_observer_, OnEncryptedTypesChanged(_, false)); sync_manager_.GetEncryptionHandler()->Init(); PumpLoop(); EXPECT_FALSE(ResetUnsyncedEntry(PASSWORDS, client_tag)); } // Verify SetTitle(..) doesn't unnecessarily set IS_UNSYNCED for bookmarks // when we write the same data, but does set it when we write new data. TEST_F(SyncManagerTest, SetBookmarkTitle) { std::string client_tag = "title"; sync_pb::EntitySpecifics entity_specifics; entity_specifics.mutable_bookmark()->set_url("url"); entity_specifics.mutable_bookmark()->set_title("title"); MakeServerNode(sync_manager_.GetUserShare(), BOOKMARKS, client_tag, syncable::GenerateSyncableHash(BOOKMARKS, client_tag), entity_specifics); // New node shouldn't start off unsynced. EXPECT_FALSE(ResetUnsyncedEntry(BOOKMARKS, client_tag)); // Manually change to the same title. Should not set is_unsynced. { WriteTransaction trans(FROM_HERE, sync_manager_.GetUserShare()); WriteNode node(&trans); EXPECT_EQ(BaseNode::INIT_OK, node.InitByClientTagLookup(BOOKMARKS, client_tag)); node.SetTitle(UTF8ToWide(client_tag)); } EXPECT_FALSE(ResetUnsyncedEntry(BOOKMARKS, client_tag)); // Manually change to new title. Should set is_unsynced. { WriteTransaction trans(FROM_HERE, sync_manager_.GetUserShare()); WriteNode node(&trans); EXPECT_EQ(BaseNode::INIT_OK, node.InitByClientTagLookup(BOOKMARKS, client_tag)); node.SetTitle(UTF8ToWide("title2")); } EXPECT_TRUE(ResetUnsyncedEntry(BOOKMARKS, client_tag)); } // Verify SetTitle(..) doesn't unnecessarily set IS_UNSYNCED for encrypted // bookmarks when we write the same data, but does set it when we write new // data. TEST_F(SyncManagerTest, SetBookmarkTitleWithEncryption) { std::string client_tag = "title"; sync_pb::EntitySpecifics entity_specifics; entity_specifics.mutable_bookmark()->set_url("url"); entity_specifics.mutable_bookmark()->set_title("title"); MakeServerNode(sync_manager_.GetUserShare(), BOOKMARKS, client_tag, syncable::GenerateSyncableHash(BOOKMARKS, client_tag), entity_specifics); // New node shouldn't start off unsynced. EXPECT_FALSE(ResetUnsyncedEntry(BOOKMARKS, client_tag)); // Encrypt the datatatype, should set is_unsynced. EXPECT_CALL(encryption_observer_, OnEncryptedTypesChanged( HasModelTypes(EncryptableUserTypes()), true)); EXPECT_CALL(encryption_observer_, OnEncryptionComplete()); EXPECT_TRUE(SetUpEncryption(WRITE_TO_NIGORI, FULL_ENCRYPTION)); EXPECT_CALL(encryption_observer_, OnCryptographerStateChanged(_)); EXPECT_CALL(encryption_observer_, OnEncryptedTypesChanged(_, true)); sync_manager_.GetEncryptionHandler()->Init(); PumpLoop(); EXPECT_TRUE(ResetUnsyncedEntry(BOOKMARKS, client_tag)); // Manually change to the same title. Should not set is_unsynced. // NON_UNIQUE_NAME should be kEncryptedString. { WriteTransaction trans(FROM_HERE, sync_manager_.GetUserShare()); WriteNode node(&trans); EXPECT_EQ(BaseNode::INIT_OK, node.InitByClientTagLookup(BOOKMARKS, client_tag)); node.SetTitle(UTF8ToWide(client_tag)); const syncable::Entry* node_entry = node.GetEntry(); const sync_pb::EntitySpecifics& specifics = node_entry->Get(SPECIFICS); EXPECT_TRUE(specifics.has_encrypted()); EXPECT_EQ(kEncryptedString, node_entry->Get(NON_UNIQUE_NAME)); } EXPECT_FALSE(ResetUnsyncedEntry(BOOKMARKS, client_tag)); // Manually change to new title. Should set is_unsynced. NON_UNIQUE_NAME // should still be kEncryptedString. { WriteTransaction trans(FROM_HERE, sync_manager_.GetUserShare()); WriteNode node(&trans); EXPECT_EQ(BaseNode::INIT_OK, node.InitByClientTagLookup(BOOKMARKS, client_tag)); node.SetTitle(UTF8ToWide("title2")); const syncable::Entry* node_entry = node.GetEntry(); const sync_pb::EntitySpecifics& specifics = node_entry->Get(SPECIFICS); EXPECT_TRUE(specifics.has_encrypted()); EXPECT_EQ(kEncryptedString, node_entry->Get(NON_UNIQUE_NAME)); } EXPECT_TRUE(ResetUnsyncedEntry(BOOKMARKS, client_tag)); } // Verify SetTitle(..) doesn't unnecessarily set IS_UNSYNCED for non-bookmarks // when we write the same data, but does set it when we write new data. TEST_F(SyncManagerTest, SetNonBookmarkTitle) { std::string client_tag = "title"; sync_pb::EntitySpecifics entity_specifics; entity_specifics.mutable_preference()->set_name("name"); entity_specifics.mutable_preference()->set_value("value"); MakeServerNode(sync_manager_.GetUserShare(), PREFERENCES, client_tag, syncable::GenerateSyncableHash(PREFERENCES, client_tag), entity_specifics); // New node shouldn't start off unsynced. EXPECT_FALSE(ResetUnsyncedEntry(PREFERENCES, client_tag)); // Manually change to the same title. Should not set is_unsynced. { WriteTransaction trans(FROM_HERE, sync_manager_.GetUserShare()); WriteNode node(&trans); EXPECT_EQ(BaseNode::INIT_OK, node.InitByClientTagLookup(PREFERENCES, client_tag)); node.SetTitle(UTF8ToWide(client_tag)); } EXPECT_FALSE(ResetUnsyncedEntry(PREFERENCES, client_tag)); // Manually change to new title. Should set is_unsynced. { WriteTransaction trans(FROM_HERE, sync_manager_.GetUserShare()); WriteNode node(&trans); EXPECT_EQ(BaseNode::INIT_OK, node.InitByClientTagLookup(PREFERENCES, client_tag)); node.SetTitle(UTF8ToWide("title2")); } EXPECT_TRUE(ResetUnsyncedEntry(PREFERENCES, client_tag)); } // Verify SetTitle(..) doesn't unnecessarily set IS_UNSYNCED for encrypted // non-bookmarks when we write the same data or when we write new data // data (should remained kEncryptedString). TEST_F(SyncManagerTest, SetNonBookmarkTitleWithEncryption) { std::string client_tag = "title"; sync_pb::EntitySpecifics entity_specifics; entity_specifics.mutable_preference()->set_name("name"); entity_specifics.mutable_preference()->set_value("value"); MakeServerNode(sync_manager_.GetUserShare(), PREFERENCES, client_tag, syncable::GenerateSyncableHash(PREFERENCES, client_tag), entity_specifics); // New node shouldn't start off unsynced. EXPECT_FALSE(ResetUnsyncedEntry(PREFERENCES, client_tag)); // Encrypt the datatatype, should set is_unsynced. EXPECT_CALL(encryption_observer_, OnEncryptedTypesChanged( HasModelTypes(EncryptableUserTypes()), true)); EXPECT_CALL(encryption_observer_, OnEncryptionComplete()); EXPECT_TRUE(SetUpEncryption(WRITE_TO_NIGORI, FULL_ENCRYPTION)); EXPECT_CALL(encryption_observer_, OnCryptographerStateChanged(_)); EXPECT_CALL(encryption_observer_, OnEncryptedTypesChanged(_, true)); sync_manager_.GetEncryptionHandler()->Init(); PumpLoop(); EXPECT_TRUE(ResetUnsyncedEntry(PREFERENCES, client_tag)); // Manually change to the same title. Should not set is_unsynced. // NON_UNIQUE_NAME should be kEncryptedString. { WriteTransaction trans(FROM_HERE, sync_manager_.GetUserShare()); WriteNode node(&trans); EXPECT_EQ(BaseNode::INIT_OK, node.InitByClientTagLookup(PREFERENCES, client_tag)); node.SetTitle(UTF8ToWide(client_tag)); const syncable::Entry* node_entry = node.GetEntry(); const sync_pb::EntitySpecifics& specifics = node_entry->Get(SPECIFICS); EXPECT_TRUE(specifics.has_encrypted()); EXPECT_EQ(kEncryptedString, node_entry->Get(NON_UNIQUE_NAME)); } EXPECT_FALSE(ResetUnsyncedEntry(PREFERENCES, client_tag)); // Manually change to new title. Should not set is_unsynced because the // NON_UNIQUE_NAME should still be kEncryptedString. { WriteTransaction trans(FROM_HERE, sync_manager_.GetUserShare()); WriteNode node(&trans); EXPECT_EQ(BaseNode::INIT_OK, node.InitByClientTagLookup(PREFERENCES, client_tag)); node.SetTitle(UTF8ToWide("title2")); const syncable::Entry* node_entry = node.GetEntry(); const sync_pb::EntitySpecifics& specifics = node_entry->Get(SPECIFICS); EXPECT_TRUE(specifics.has_encrypted()); EXPECT_EQ(kEncryptedString, node_entry->Get(NON_UNIQUE_NAME)); EXPECT_FALSE(node_entry->Get(IS_UNSYNCED)); } } // Ensure that titles are truncated to 255 bytes, and attempting to reset // them to their longer version does not set IS_UNSYNCED. TEST_F(SyncManagerTest, SetLongTitle) { const int kNumChars = 512; const std::string kClientTag = "tag"; std::string title(kNumChars, '0'); sync_pb::EntitySpecifics entity_specifics; entity_specifics.mutable_preference()->set_name("name"); entity_specifics.mutable_preference()->set_value("value"); MakeServerNode(sync_manager_.GetUserShare(), PREFERENCES, "short_title", syncable::GenerateSyncableHash(PREFERENCES, kClientTag), entity_specifics); // New node shouldn't start off unsynced. EXPECT_FALSE(ResetUnsyncedEntry(PREFERENCES, kClientTag)); // Manually change to the long title. Should set is_unsynced. { WriteTransaction trans(FROM_HERE, sync_manager_.GetUserShare()); WriteNode node(&trans); EXPECT_EQ(BaseNode::INIT_OK, node.InitByClientTagLookup(PREFERENCES, kClientTag)); node.SetTitle(UTF8ToWide(title)); EXPECT_EQ(node.GetTitle(), title.substr(0, 255)); } EXPECT_TRUE(ResetUnsyncedEntry(PREFERENCES, kClientTag)); // Manually change to the same title. Should not set is_unsynced. { WriteTransaction trans(FROM_HERE, sync_manager_.GetUserShare()); WriteNode node(&trans); EXPECT_EQ(BaseNode::INIT_OK, node.InitByClientTagLookup(PREFERENCES, kClientTag)); node.SetTitle(UTF8ToWide(title)); EXPECT_EQ(node.GetTitle(), title.substr(0, 255)); } EXPECT_FALSE(ResetUnsyncedEntry(PREFERENCES, kClientTag)); // Manually change to new title. Should set is_unsynced. { WriteTransaction trans(FROM_HERE, sync_manager_.GetUserShare()); WriteNode node(&trans); EXPECT_EQ(BaseNode::INIT_OK, node.InitByClientTagLookup(PREFERENCES, kClientTag)); node.SetTitle(UTF8ToWide("title2")); } EXPECT_TRUE(ResetUnsyncedEntry(PREFERENCES, kClientTag)); } // Create an encrypted entry when the cryptographer doesn't think the type is // marked for encryption. Ensure reads/writes don't break and don't unencrypt // the data. TEST_F(SyncManagerTest, SetPreviouslyEncryptedSpecifics) { std::string client_tag = "tag"; std::string url = "url"; std::string url2 = "new_url"; std::string title = "title"; sync_pb::EntitySpecifics entity_specifics; EXPECT_TRUE(SetUpEncryption(WRITE_TO_NIGORI, DEFAULT_ENCRYPTION)); { ReadTransaction trans(FROM_HERE, sync_manager_.GetUserShare()); Cryptographer* crypto = trans.GetCryptographer(); sync_pb::EntitySpecifics bm_specifics; bm_specifics.mutable_bookmark()->set_title("title"); bm_specifics.mutable_bookmark()->set_url("url"); sync_pb::EncryptedData encrypted; crypto->Encrypt(bm_specifics, &encrypted); entity_specifics.mutable_encrypted()->CopyFrom(encrypted); AddDefaultFieldValue(BOOKMARKS, &entity_specifics); } MakeServerNode(sync_manager_.GetUserShare(), BOOKMARKS, client_tag, syncable::GenerateSyncableHash(BOOKMARKS, client_tag), entity_specifics); { // Verify the data. ReadTransaction trans(FROM_HERE, sync_manager_.GetUserShare()); ReadNode node(&trans); EXPECT_EQ(BaseNode::INIT_OK, node.InitByClientTagLookup(BOOKMARKS, client_tag)); EXPECT_EQ(title, node.GetTitle()); EXPECT_EQ(url, node.GetBookmarkSpecifics().url()); } { // Overwrite the url (which overwrites the specifics). WriteTransaction trans(FROM_HERE, sync_manager_.GetUserShare()); WriteNode node(&trans); EXPECT_EQ(BaseNode::INIT_OK, node.InitByClientTagLookup(BOOKMARKS, client_tag)); sync_pb::BookmarkSpecifics bookmark_specifics(node.GetBookmarkSpecifics()); bookmark_specifics.set_url(url2); node.SetBookmarkSpecifics(bookmark_specifics); } { // Verify it's still encrypted and it has the most recent url. ReadTransaction trans(FROM_HERE, sync_manager_.GetUserShare()); ReadNode node(&trans); EXPECT_EQ(BaseNode::INIT_OK, node.InitByClientTagLookup(BOOKMARKS, client_tag)); EXPECT_EQ(title, node.GetTitle()); EXPECT_EQ(url2, node.GetBookmarkSpecifics().url()); const syncable::Entry* node_entry = node.GetEntry(); EXPECT_EQ(kEncryptedString, node_entry->Get(NON_UNIQUE_NAME)); const sync_pb::EntitySpecifics& specifics = node_entry->Get(SPECIFICS); EXPECT_TRUE(specifics.has_encrypted()); } } // Verify transaction version of a model type is incremented when node of // that type is updated. TEST_F(SyncManagerTest, IncrementTransactionVersion) { ModelSafeRoutingInfo routing_info; GetModelSafeRoutingInfo(&routing_info); { ReadTransaction read_trans(FROM_HERE, sync_manager_.GetUserShare()); for (ModelSafeRoutingInfo::iterator i = routing_info.begin(); i != routing_info.end(); ++i) { // Transaction version is incremented when SyncManagerTest::SetUp() // creates a node of each type. EXPECT_EQ(1, sync_manager_.GetUserShare()->directory-> GetTransactionVersion(i->first)); } } // Create bookmark node to increment transaction version of bookmark model. std::string client_tag = "title"; sync_pb::EntitySpecifics entity_specifics; entity_specifics.mutable_bookmark()->set_url("url"); entity_specifics.mutable_bookmark()->set_title("title"); MakeServerNode(sync_manager_.GetUserShare(), BOOKMARKS, client_tag, syncable::GenerateSyncableHash(BOOKMARKS, client_tag), entity_specifics); { ReadTransaction read_trans(FROM_HERE, sync_manager_.GetUserShare()); for (ModelSafeRoutingInfo::iterator i = routing_info.begin(); i != routing_info.end(); ++i) { EXPECT_EQ(i->first == BOOKMARKS ? 2 : 1, sync_manager_.GetUserShare()->directory-> GetTransactionVersion(i->first)); } } } class MockSyncScheduler : public FakeSyncScheduler { public: MockSyncScheduler() : FakeSyncScheduler() {} virtual ~MockSyncScheduler() {} MOCK_METHOD1(Start, void(SyncScheduler::Mode)); MOCK_METHOD1(ScheduleConfiguration, bool(const ConfigurationParams&)); }; class ComponentsFactory : public TestInternalComponentsFactory { public: ComponentsFactory(const Switches& switches, SyncScheduler* scheduler_to_use, sessions::SyncSessionContext** session_context) : TestInternalComponentsFactory(switches, syncer::STORAGE_IN_MEMORY), scheduler_to_use_(scheduler_to_use), session_context_(session_context) {} virtual ~ComponentsFactory() {} virtual scoped_ptr<SyncScheduler> BuildScheduler( const std::string& name, sessions::SyncSessionContext* context) OVERRIDE { *session_context_ = context; return scheduler_to_use_.Pass(); } private: scoped_ptr<SyncScheduler> scheduler_to_use_; sessions::SyncSessionContext** session_context_; }; class SyncManagerTestWithMockScheduler : public SyncManagerTest { public: SyncManagerTestWithMockScheduler() : scheduler_(NULL) {} virtual InternalComponentsFactory* GetFactory() OVERRIDE { scheduler_ = new MockSyncScheduler(); return new ComponentsFactory(GetSwitches(), scheduler_, &session_context_); } MockSyncScheduler* scheduler() { return scheduler_; } sessions::SyncSessionContext* session_context() { return session_context_; } private: MockSyncScheduler* scheduler_; sessions::SyncSessionContext* session_context_; }; // Test that the configuration params are properly created and sent to // ScheduleConfigure. No callback should be invoked. Any disabled datatypes // should be purged. TEST_F(SyncManagerTestWithMockScheduler, BasicConfiguration) { ConfigureReason reason = CONFIGURE_REASON_RECONFIGURATION; ModelTypeSet types_to_download(BOOKMARKS, PREFERENCES); ModelSafeRoutingInfo new_routing_info; GetModelSafeRoutingInfo(&new_routing_info); ModelTypeSet enabled_types = GetRoutingInfoTypes(new_routing_info); ModelTypeSet disabled_types = Difference(ModelTypeSet::All(), enabled_types); ConfigurationParams params; EXPECT_CALL(*scheduler(), Start(SyncScheduler::CONFIGURATION_MODE)); EXPECT_CALL(*scheduler(), ScheduleConfiguration(_)). WillOnce(DoAll(SaveArg<0>(&params), Return(true))); // Set data for all types. ModelTypeSet protocol_types = ProtocolTypes(); for (ModelTypeSet::Iterator iter = protocol_types.First(); iter.Good(); iter.Inc()) { SetProgressMarkerForType(iter.Get(), true); } CallbackCounter ready_task_counter, retry_task_counter; sync_manager_.ConfigureSyncer( reason, types_to_download, ModelTypeSet(), ModelTypeSet(), ModelTypeSet(), new_routing_info, base::Bind(&CallbackCounter::Callback, base::Unretained(&ready_task_counter)), base::Bind(&CallbackCounter::Callback, base::Unretained(&retry_task_counter))); EXPECT_EQ(0, ready_task_counter.times_called()); EXPECT_EQ(0, retry_task_counter.times_called()); EXPECT_EQ(sync_pb::GetUpdatesCallerInfo::RECONFIGURATION, params.source); EXPECT_TRUE(types_to_download.Equals(params.types_to_download)); EXPECT_EQ(new_routing_info, params.routing_info); // Verify all the disabled types were purged. EXPECT_TRUE(sync_manager_.InitialSyncEndedTypes().Equals( enabled_types)); EXPECT_TRUE(sync_manager_.GetTypesWithEmptyProgressMarkerToken( ModelTypeSet::All()).Equals(disabled_types)); } // Test that on a reconfiguration (configuration where the session context // already has routing info), only those recently disabled types are purged. TEST_F(SyncManagerTestWithMockScheduler, ReConfiguration) { ConfigureReason reason = CONFIGURE_REASON_RECONFIGURATION; ModelTypeSet types_to_download(BOOKMARKS, PREFERENCES); ModelTypeSet disabled_types = ModelTypeSet(THEMES, SESSIONS); ModelSafeRoutingInfo old_routing_info; ModelSafeRoutingInfo new_routing_info; GetModelSafeRoutingInfo(&old_routing_info); new_routing_info = old_routing_info; new_routing_info.erase(THEMES); new_routing_info.erase(SESSIONS); ModelTypeSet enabled_types = GetRoutingInfoTypes(new_routing_info); ConfigurationParams params; EXPECT_CALL(*scheduler(), Start(SyncScheduler::CONFIGURATION_MODE)); EXPECT_CALL(*scheduler(), ScheduleConfiguration(_)). WillOnce(DoAll(SaveArg<0>(&params), Return(true))); // Set data for all types except those recently disabled (so we can verify // only those recently disabled are purged) . ModelTypeSet protocol_types = ProtocolTypes(); for (ModelTypeSet::Iterator iter = protocol_types.First(); iter.Good(); iter.Inc()) { if (!disabled_types.Has(iter.Get())) { SetProgressMarkerForType(iter.Get(), true); } else { SetProgressMarkerForType(iter.Get(), false); } } // Set the context to have the old routing info. session_context()->set_routing_info(old_routing_info); CallbackCounter ready_task_counter, retry_task_counter; sync_manager_.ConfigureSyncer( reason, types_to_download, ModelTypeSet(), ModelTypeSet(), ModelTypeSet(), new_routing_info, base::Bind(&CallbackCounter::Callback, base::Unretained(&ready_task_counter)), base::Bind(&CallbackCounter::Callback, base::Unretained(&retry_task_counter))); EXPECT_EQ(0, ready_task_counter.times_called()); EXPECT_EQ(0, retry_task_counter.times_called()); EXPECT_EQ(sync_pb::GetUpdatesCallerInfo::RECONFIGURATION, params.source); EXPECT_TRUE(types_to_download.Equals(params.types_to_download)); EXPECT_EQ(new_routing_info, params.routing_info); // Verify only the recently disabled types were purged. EXPECT_TRUE(sync_manager_.GetTypesWithEmptyProgressMarkerToken( ProtocolTypes()).Equals(disabled_types)); } // Test that the retry callback is invoked on configuration failure. TEST_F(SyncManagerTestWithMockScheduler, ConfigurationRetry) { ConfigureReason reason = CONFIGURE_REASON_RECONFIGURATION; ModelTypeSet types_to_download(BOOKMARKS, PREFERENCES); ModelSafeRoutingInfo new_routing_info; GetModelSafeRoutingInfo(&new_routing_info); ConfigurationParams params; EXPECT_CALL(*scheduler(), Start(SyncScheduler::CONFIGURATION_MODE)); EXPECT_CALL(*scheduler(), ScheduleConfiguration(_)). WillOnce(DoAll(SaveArg<0>(&params), Return(false))); CallbackCounter ready_task_counter, retry_task_counter; sync_manager_.ConfigureSyncer( reason, types_to_download, ModelTypeSet(), ModelTypeSet(), ModelTypeSet(), new_routing_info, base::Bind(&CallbackCounter::Callback, base::Unretained(&ready_task_counter)), base::Bind(&CallbackCounter::Callback, base::Unretained(&retry_task_counter))); EXPECT_EQ(0, ready_task_counter.times_called()); EXPECT_EQ(1, retry_task_counter.times_called()); EXPECT_EQ(sync_pb::GetUpdatesCallerInfo::RECONFIGURATION, params.source); EXPECT_TRUE(types_to_download.Equals(params.types_to_download)); EXPECT_EQ(new_routing_info, params.routing_info); } // Test that PurgePartiallySyncedTypes purges only those types that have not // fully completed their initial download and apply. TEST_F(SyncManagerTest, PurgePartiallySyncedTypes) { ModelSafeRoutingInfo routing_info; GetModelSafeRoutingInfo(&routing_info); ModelTypeSet enabled_types = GetRoutingInfoTypes(routing_info); UserShare* share = sync_manager_.GetUserShare(); // The test harness automatically initializes all types in the routing info. // Check that autofill is not among them. ASSERT_FALSE(enabled_types.Has(AUTOFILL)); // Further ensure that the test harness did not create its root node. { syncable::ReadTransaction trans(FROM_HERE, share->directory.get()); syncable::Entry autofill_root_node(&trans, syncable::GET_BY_SERVER_TAG, ModelTypeToRootTag(AUTOFILL)); ASSERT_FALSE(autofill_root_node.good()); } // One more redundant check. ASSERT_FALSE(sync_manager_.InitialSyncEndedTypes().Has(AUTOFILL)); // Give autofill a progress marker. sync_pb::DataTypeProgressMarker autofill_marker; autofill_marker.set_data_type_id( GetSpecificsFieldNumberFromModelType(AUTOFILL)); autofill_marker.set_token("token"); share->directory->SetDownloadProgress(AUTOFILL, autofill_marker); // Also add a pending autofill root node update from the server. TestEntryFactory factory_(share->directory.get()); int autofill_meta = factory_.CreateUnappliedRootNode(AUTOFILL); // Preferences is an enabled type. Check that the harness initialized it. ASSERT_TRUE(enabled_types.Has(PREFERENCES)); ASSERT_TRUE(sync_manager_.InitialSyncEndedTypes().Has(PREFERENCES)); // Give preferencse a progress marker. sync_pb::DataTypeProgressMarker prefs_marker; prefs_marker.set_data_type_id( GetSpecificsFieldNumberFromModelType(PREFERENCES)); prefs_marker.set_token("token"); share->directory->SetDownloadProgress(PREFERENCES, prefs_marker); // Add a fully synced preferences node under the root. std::string pref_client_tag = "prefABC"; std::string pref_hashed_tag = "hashXYZ"; sync_pb::EntitySpecifics pref_specifics; AddDefaultFieldValue(PREFERENCES, &pref_specifics); int pref_meta = MakeServerNode( share, PREFERENCES, pref_client_tag, pref_hashed_tag, pref_specifics); // And now, the purge. EXPECT_TRUE(sync_manager_.PurgePartiallySyncedTypes()); // Ensure that autofill lost its progress marker, but preferences did not. ModelTypeSet empty_tokens = sync_manager_.GetTypesWithEmptyProgressMarkerToken(ModelTypeSet::All()); EXPECT_TRUE(empty_tokens.Has(AUTOFILL)); EXPECT_FALSE(empty_tokens.Has(PREFERENCES)); // Ensure that autofill lots its node, but preferences did not. { syncable::ReadTransaction trans(FROM_HERE, share->directory.get()); syncable::Entry autofill_node(&trans, GET_BY_HANDLE, autofill_meta); syncable::Entry pref_node(&trans, GET_BY_HANDLE, pref_meta); EXPECT_FALSE(autofill_node.good()); EXPECT_TRUE(pref_node.good()); } } // Test CleanupDisabledTypes properly purges all disabled types as specified // by the previous and current enabled params. TEST_F(SyncManagerTest, PurgeDisabledTypes) { ModelSafeRoutingInfo routing_info; GetModelSafeRoutingInfo(&routing_info); ModelTypeSet enabled_types = GetRoutingInfoTypes(routing_info); ModelTypeSet disabled_types = Difference(ModelTypeSet::All(), enabled_types); // The harness should have initialized the enabled_types for us. EXPECT_TRUE(enabled_types.Equals(sync_manager_.InitialSyncEndedTypes())); // Set progress markers for all types. ModelTypeSet protocol_types = ProtocolTypes(); for (ModelTypeSet::Iterator iter = protocol_types.First(); iter.Good(); iter.Inc()) { SetProgressMarkerForType(iter.Get(), true); } // Verify all the enabled types remain after cleanup, and all the disabled // types were purged. sync_manager_.PurgeDisabledTypes(ModelTypeSet::All(), enabled_types, ModelTypeSet(), ModelTypeSet()); EXPECT_TRUE(enabled_types.Equals(sync_manager_.InitialSyncEndedTypes())); EXPECT_TRUE(disabled_types.Equals( sync_manager_.GetTypesWithEmptyProgressMarkerToken(ModelTypeSet::All()))); // Disable some more types. disabled_types.Put(BOOKMARKS); disabled_types.Put(PREFERENCES); ModelTypeSet new_enabled_types = Difference(ModelTypeSet::All(), disabled_types); // Verify only the non-disabled types remain after cleanup. sync_manager_.PurgeDisabledTypes(enabled_types, new_enabled_types, ModelTypeSet(), ModelTypeSet()); EXPECT_TRUE(new_enabled_types.Equals(sync_manager_.InitialSyncEndedTypes())); EXPECT_TRUE(disabled_types.Equals( sync_manager_.GetTypesWithEmptyProgressMarkerToken(ModelTypeSet::All()))); } // Test PurgeDisabledTypes properly unapplies types by deleting their local data // and preserving their server data and progress marker. TEST_F(SyncManagerTest, PurgeUnappliedTypes) { ModelSafeRoutingInfo routing_info; GetModelSafeRoutingInfo(&routing_info); ModelTypeSet unapplied_types = ModelTypeSet(BOOKMARKS, PREFERENCES); ModelTypeSet enabled_types = GetRoutingInfoTypes(routing_info); ModelTypeSet disabled_types = Difference(ModelTypeSet::All(), enabled_types); // The harness should have initialized the enabled_types for us. EXPECT_TRUE(enabled_types.Equals(sync_manager_.InitialSyncEndedTypes())); // Set progress markers for all types. ModelTypeSet protocol_types = ProtocolTypes(); for (ModelTypeSet::Iterator iter = protocol_types.First(); iter.Good(); iter.Inc()) { SetProgressMarkerForType(iter.Get(), true); } // Add the following kinds of items: // 1. Fully synced preference. // 2. Locally created preference, server unknown, unsynced // 3. Locally deleted preference, server known, unsynced // 4. Server deleted preference, locally known. // 5. Server created preference, locally unknown, unapplied. // 6. A fully synced bookmark (no unique_client_tag). UserShare* share = sync_manager_.GetUserShare(); sync_pb::EntitySpecifics pref_specifics; AddDefaultFieldValue(PREFERENCES, &pref_specifics); sync_pb::EntitySpecifics bm_specifics; AddDefaultFieldValue(BOOKMARKS, &bm_specifics); int pref1_meta = MakeServerNode( share, PREFERENCES, "pref1", "hash1", pref_specifics); int64 pref2_meta = MakeNode(share, PREFERENCES, "pref2"); int pref3_meta = MakeServerNode( share, PREFERENCES, "pref3", "hash3", pref_specifics); int pref4_meta = MakeServerNode( share, PREFERENCES, "pref4", "hash4", pref_specifics); int pref5_meta = MakeServerNode( share, PREFERENCES, "pref5", "hash5", pref_specifics); int bookmark_meta = MakeServerNode( share, BOOKMARKS, "bookmark", "", bm_specifics); { syncable::WriteTransaction trans(FROM_HERE, syncable::SYNCER, share->directory.get()); // Pref's 1 and 2 are already set up properly. // Locally delete pref 3. syncable::MutableEntry pref3(&trans, GET_BY_HANDLE, pref3_meta); pref3.Put(IS_DEL, true); pref3.Put(IS_UNSYNCED, true); // Delete pref 4 at the server. syncable::MutableEntry pref4(&trans, GET_BY_HANDLE, pref4_meta); pref4.Put(syncable::SERVER_IS_DEL, true); pref4.Put(syncable::IS_UNAPPLIED_UPDATE, true); pref4.Put(syncable::SERVER_VERSION, 2); // Pref 5 is an new unapplied update. syncable::MutableEntry pref5(&trans, GET_BY_HANDLE, pref5_meta); pref5.Put(syncable::IS_UNAPPLIED_UPDATE, true); pref5.Put(syncable::IS_DEL, true); pref5.Put(syncable::BASE_VERSION, -1); // Bookmark is already set up properly } // Take a snapshot to clear all the dirty bits. share->directory.get()->SaveChanges(); // Now request a purge for the unapplied types. disabled_types.PutAll(unapplied_types); ModelTypeSet new_enabled_types = Difference(ModelTypeSet::All(), disabled_types); sync_manager_.PurgeDisabledTypes(enabled_types, new_enabled_types, ModelTypeSet(), unapplied_types); // Verify the unapplied types still have progress markers and initial sync // ended after cleanup. EXPECT_TRUE(sync_manager_.InitialSyncEndedTypes().HasAll(unapplied_types)); EXPECT_TRUE( sync_manager_.GetTypesWithEmptyProgressMarkerToken(unapplied_types). Empty()); // Ensure the items were unapplied as necessary. { syncable::ReadTransaction trans(FROM_HERE, share->directory.get()); syncable::Entry pref_node(&trans, GET_BY_HANDLE, pref1_meta); ASSERT_TRUE(pref_node.good()); EXPECT_TRUE(pref_node.GetKernelCopy().is_dirty()); EXPECT_FALSE(pref_node.Get(syncable::IS_UNSYNCED)); EXPECT_TRUE(pref_node.Get(syncable::IS_UNAPPLIED_UPDATE)); EXPECT_TRUE(pref_node.Get(IS_DEL)); EXPECT_GT(pref_node.Get(syncable::SERVER_VERSION), 0); EXPECT_EQ(pref_node.Get(syncable::BASE_VERSION), -1); // Pref 2 should just be locally deleted. syncable::Entry pref2_node(&trans, GET_BY_HANDLE, pref2_meta); ASSERT_TRUE(pref2_node.good()); EXPECT_TRUE(pref2_node.GetKernelCopy().is_dirty()); EXPECT_FALSE(pref2_node.Get(syncable::IS_UNSYNCED)); EXPECT_TRUE(pref2_node.Get(syncable::IS_DEL)); EXPECT_FALSE(pref2_node.Get(syncable::IS_UNAPPLIED_UPDATE)); EXPECT_TRUE(pref2_node.Get(IS_DEL)); EXPECT_EQ(pref2_node.Get(syncable::SERVER_VERSION), 0); EXPECT_EQ(pref2_node.Get(syncable::BASE_VERSION), -1); syncable::Entry pref3_node(&trans, GET_BY_HANDLE, pref3_meta); ASSERT_TRUE(pref3_node.good()); EXPECT_TRUE(pref3_node.GetKernelCopy().is_dirty()); EXPECT_FALSE(pref3_node.Get(syncable::IS_UNSYNCED)); EXPECT_TRUE(pref3_node.Get(syncable::IS_UNAPPLIED_UPDATE)); EXPECT_TRUE(pref3_node.Get(IS_DEL)); EXPECT_GT(pref3_node.Get(syncable::SERVER_VERSION), 0); EXPECT_EQ(pref3_node.Get(syncable::BASE_VERSION), -1); syncable::Entry pref4_node(&trans, GET_BY_HANDLE, pref4_meta); ASSERT_TRUE(pref4_node.good()); EXPECT_TRUE(pref4_node.GetKernelCopy().is_dirty()); EXPECT_FALSE(pref4_node.Get(syncable::IS_UNSYNCED)); EXPECT_TRUE(pref4_node.Get(syncable::IS_UNAPPLIED_UPDATE)); EXPECT_TRUE(pref4_node.Get(IS_DEL)); EXPECT_GT(pref4_node.Get(syncable::SERVER_VERSION), 0); EXPECT_EQ(pref4_node.Get(syncable::BASE_VERSION), -1); // Pref 5 should remain untouched. syncable::Entry pref5_node(&trans, GET_BY_HANDLE, pref5_meta); ASSERT_TRUE(pref5_node.good()); EXPECT_FALSE(pref5_node.GetKernelCopy().is_dirty()); EXPECT_FALSE(pref5_node.Get(syncable::IS_UNSYNCED)); EXPECT_TRUE(pref5_node.Get(syncable::IS_UNAPPLIED_UPDATE)); EXPECT_TRUE(pref5_node.Get(IS_DEL)); EXPECT_GT(pref5_node.Get(syncable::SERVER_VERSION), 0); EXPECT_EQ(pref5_node.Get(syncable::BASE_VERSION), -1); syncable::Entry bookmark_node(&trans, GET_BY_HANDLE, bookmark_meta); ASSERT_TRUE(bookmark_node.good()); EXPECT_TRUE(bookmark_node.GetKernelCopy().is_dirty()); EXPECT_FALSE(bookmark_node.Get(syncable::IS_UNSYNCED)); EXPECT_TRUE(bookmark_node.Get(syncable::IS_UNAPPLIED_UPDATE)); EXPECT_TRUE(bookmark_node.Get(IS_DEL)); EXPECT_GT(bookmark_node.Get(syncable::SERVER_VERSION), 0); EXPECT_EQ(bookmark_node.Get(syncable::BASE_VERSION), -1); } } // A test harness to exercise the code that processes and passes changes from // the "SYNCER"-WriteTransaction destructor, through the SyncManager, to the // ChangeProcessor. class SyncManagerChangeProcessingTest : public SyncManagerTest { public: virtual void OnChangesApplied( ModelType model_type, int64 model_version, const BaseTransaction* trans, const ImmutableChangeRecordList& changes) OVERRIDE { last_changes_ = changes; } virtual void OnChangesComplete(ModelType model_type) OVERRIDE {} const ImmutableChangeRecordList& GetRecentChangeList() { return last_changes_; } UserShare* share() { return sync_manager_.GetUserShare(); } // Set some flags so our nodes reasonably approximate the real world scenario // and can get past CheckTreeInvariants. // // It's never going to be truly accurate, since we're squashing update // receipt, processing and application into a single transaction. void SetNodeProperties(syncable::MutableEntry *entry) { entry->Put(syncable::ID, id_factory_.NewServerId()); entry->Put(syncable::BASE_VERSION, 10); entry->Put(syncable::SERVER_VERSION, 10); } // Looks for the given change in the list. Returns the index at which it was // found. Returns -1 on lookup failure. size_t FindChangeInList(int64 id, ChangeRecord::Action action) { SCOPED_TRACE(id); for (size_t i = 0; i < last_changes_.Get().size(); ++i) { if (last_changes_.Get()[i].id == id && last_changes_.Get()[i].action == action) { return i; } } ADD_FAILURE() << "Failed to find specified change"; return -1; } // Returns the current size of the change list. // // Note that spurious changes do not necessarily indicate a problem. // Assertions on change list size can help detect problems, but it may be // necessary to reduce their strictness if the implementation changes. size_t GetChangeListSize() { return last_changes_.Get().size(); } protected: ImmutableChangeRecordList last_changes_; TestIdFactory id_factory_; }; // Test creation of a folder and a bookmark. TEST_F(SyncManagerChangeProcessingTest, AddBookmarks) { int64 type_root = GetIdForDataType(BOOKMARKS); int64 folder_id = kInvalidId; int64 child_id = kInvalidId; // Create a folder and a bookmark under it. { syncable::WriteTransaction trans( FROM_HERE, syncable::SYNCER, share()->directory.get()); syncable::Entry root(&trans, syncable::GET_BY_HANDLE, type_root); ASSERT_TRUE(root.good()); syncable::MutableEntry folder(&trans, syncable::CREATE, BOOKMARKS, root.Get(syncable::ID), "folder"); ASSERT_TRUE(folder.good()); SetNodeProperties(&folder); folder.Put(syncable::IS_DIR, true); folder_id = folder.Get(syncable::META_HANDLE); syncable::MutableEntry child(&trans, syncable::CREATE, BOOKMARKS, folder.Get(syncable::ID), "child"); ASSERT_TRUE(child.good()); SetNodeProperties(&child); child_id = child.Get(syncable::META_HANDLE); } // The closing of the above scope will delete the transaction. Its processed // changes should be waiting for us in a member of the test harness. EXPECT_EQ(2UL, GetChangeListSize()); // We don't need to check these return values here. The function will add a // non-fatal failure if these changes are not found. size_t folder_change_pos = FindChangeInList(folder_id, ChangeRecord::ACTION_ADD); size_t child_change_pos = FindChangeInList(child_id, ChangeRecord::ACTION_ADD); // Parents are delivered before children. EXPECT_LT(folder_change_pos, child_change_pos); } // Test moving a bookmark into an empty folder. TEST_F(SyncManagerChangeProcessingTest, MoveBookmarkIntoEmptyFolder) { int64 type_root = GetIdForDataType(BOOKMARKS); int64 folder_b_id = kInvalidId; int64 child_id = kInvalidId; // Create two folders. Place a child under folder A. { syncable::WriteTransaction trans( FROM_HERE, syncable::SYNCER, share()->directory.get()); syncable::Entry root(&trans, syncable::GET_BY_HANDLE, type_root); ASSERT_TRUE(root.good()); syncable::MutableEntry folder_a(&trans, syncable::CREATE, BOOKMARKS, root.Get(syncable::ID), "folderA"); ASSERT_TRUE(folder_a.good()); SetNodeProperties(&folder_a); folder_a.Put(syncable::IS_DIR, true); syncable::MutableEntry folder_b(&trans, syncable::CREATE, BOOKMARKS, root.Get(syncable::ID), "folderB"); ASSERT_TRUE(folder_b.good()); SetNodeProperties(&folder_b); folder_b.Put(syncable::IS_DIR, true); folder_b_id = folder_b.Get(syncable::META_HANDLE); syncable::MutableEntry child(&trans, syncable::CREATE, BOOKMARKS, folder_a.Get(syncable::ID), "child"); ASSERT_TRUE(child.good()); SetNodeProperties(&child); child_id = child.Get(syncable::META_HANDLE); } // Close that transaction. The above was to setup the initial scenario. The // real test starts now. // Move the child from folder A to folder B. { syncable::WriteTransaction trans( FROM_HERE, syncable::SYNCER, share()->directory.get()); syncable::Entry folder_b(&trans, syncable::GET_BY_HANDLE, folder_b_id); syncable::MutableEntry child(&trans, syncable::GET_BY_HANDLE, child_id); child.Put(syncable::PARENT_ID, folder_b.Get(syncable::ID)); } EXPECT_EQ(1UL, GetChangeListSize()); // Verify that this was detected as a real change. An early version of the // UniquePosition code had a bug where moves from one folder to another were // ignored unless the moved node's UniquePosition value was also changed in // some way. FindChangeInList(child_id, ChangeRecord::ACTION_UPDATE); } // Test moving a bookmark into a non-empty folder. TEST_F(SyncManagerChangeProcessingTest, MoveIntoPopulatedFolder) { int64 type_root = GetIdForDataType(BOOKMARKS); int64 child_a_id = kInvalidId; int64 child_b_id = kInvalidId; // Create two folders. Place one child each under folder A and folder B. { syncable::WriteTransaction trans( FROM_HERE, syncable::SYNCER, share()->directory.get()); syncable::Entry root(&trans, syncable::GET_BY_HANDLE, type_root); ASSERT_TRUE(root.good()); syncable::MutableEntry folder_a(&trans, syncable::CREATE, BOOKMARKS, root.Get(syncable::ID), "folderA"); ASSERT_TRUE(folder_a.good()); SetNodeProperties(&folder_a); folder_a.Put(syncable::IS_DIR, true); syncable::MutableEntry folder_b(&trans, syncable::CREATE, BOOKMARKS, root.Get(syncable::ID), "folderB"); ASSERT_TRUE(folder_b.good()); SetNodeProperties(&folder_b); folder_b.Put(syncable::IS_DIR, true); syncable::MutableEntry child_a(&trans, syncable::CREATE, BOOKMARKS, folder_a.Get(syncable::ID), "childA"); ASSERT_TRUE(child_a.good()); SetNodeProperties(&child_a); child_a_id = child_a.Get(syncable::META_HANDLE); syncable::MutableEntry child_b(&trans, syncable::CREATE, BOOKMARKS, folder_b.Get(syncable::ID), "childB"); SetNodeProperties(&child_b); child_b_id = child_b.Get(syncable::META_HANDLE); } // Close that transaction. The above was to setup the initial scenario. The // real test starts now. { syncable::WriteTransaction trans( FROM_HERE, syncable::SYNCER, share()->directory.get()); syncable::MutableEntry child_a(&trans, syncable::GET_BY_HANDLE, child_a_id); syncable::MutableEntry child_b(&trans, syncable::GET_BY_HANDLE, child_b_id); // Move child A from folder A to folder B and update its position. child_a.Put(syncable::PARENT_ID, child_b.Get(syncable::PARENT_ID)); child_a.PutPredecessor(child_b.Get(syncable::ID)); } EXPECT_EQ(1UL, GetChangeListSize()); // Verify that only child a is in the change list. // (This function will add a failure if the lookup fails.) FindChangeInList(child_a_id, ChangeRecord::ACTION_UPDATE); } // Tests the ordering of deletion changes. TEST_F(SyncManagerChangeProcessingTest, DeletionsAndChanges) { int64 type_root = GetIdForDataType(BOOKMARKS); int64 folder_a_id = kInvalidId; int64 folder_b_id = kInvalidId; int64 child_id = kInvalidId; // Create two folders. Place a child under folder A. { syncable::WriteTransaction trans( FROM_HERE, syncable::SYNCER, share()->directory.get()); syncable::Entry root(&trans, syncable::GET_BY_HANDLE, type_root); ASSERT_TRUE(root.good()); syncable::MutableEntry folder_a(&trans, syncable::CREATE, BOOKMARKS, root.Get(syncable::ID), "folderA"); ASSERT_TRUE(folder_a.good()); SetNodeProperties(&folder_a); folder_a.Put(syncable::IS_DIR, true); folder_a_id = folder_a.Get(syncable::META_HANDLE); syncable::MutableEntry folder_b(&trans, syncable::CREATE, BOOKMARKS, root.Get(syncable::ID), "folderB"); ASSERT_TRUE(folder_b.good()); SetNodeProperties(&folder_b); folder_b.Put(syncable::IS_DIR, true); folder_b_id = folder_b.Get(syncable::META_HANDLE); syncable::MutableEntry child(&trans, syncable::CREATE, BOOKMARKS, folder_a.Get(syncable::ID), "child"); ASSERT_TRUE(child.good()); SetNodeProperties(&child); child_id = child.Get(syncable::META_HANDLE); } // Close that transaction. The above was to setup the initial scenario. The // real test starts now. { syncable::WriteTransaction trans( FROM_HERE, syncable::SYNCER, share()->directory.get()); syncable::MutableEntry folder_a( &trans, syncable::GET_BY_HANDLE, folder_a_id); syncable::MutableEntry folder_b( &trans, syncable::GET_BY_HANDLE, folder_b_id); syncable::MutableEntry child(&trans, syncable::GET_BY_HANDLE, child_id); // Delete folder B and its child. child.Put(syncable::IS_DEL, true); folder_b.Put(syncable::IS_DEL, true); // Make an unrelated change to folder A. folder_a.Put(syncable::NON_UNIQUE_NAME, "NewNameA"); } EXPECT_EQ(3UL, GetChangeListSize()); size_t folder_a_pos = FindChangeInList(folder_a_id, ChangeRecord::ACTION_UPDATE); size_t folder_b_pos = FindChangeInList(folder_b_id, ChangeRecord::ACTION_DELETE); size_t child_pos = FindChangeInList(child_id, ChangeRecord::ACTION_DELETE); // Deletes should appear before updates. EXPECT_LT(child_pos, folder_a_pos); EXPECT_LT(folder_b_pos, folder_a_pos); } } // namespace
{'content_hash': 'c1554cd8ff509d8b3221f1b041f94392', 'timestamp': '', 'source': 'github', 'line_count': 3580, 'max_line_length': 80, 'avg_line_length': 38.94469273743017, 'alnum_prop': 0.6963606891308401, 'repo_name': 'hujiajie/pa-chromium', 'id': '7ef301466ed7613529d1f598226b23acca6881da', 'size': '139422', 'binary': False, 'copies': '3', 'ref': 'refs/heads/master', 'path': 'sync/internal_api/sync_manager_impl_unittest.cc', 'mode': '33188', 'license': 'bsd-3-clause', 'language': [{'name': 'ASP', 'bytes': '853'}, {'name': 'AppleScript', 'bytes': '6973'}, {'name': 'Arduino', 'bytes': '464'}, {'name': 'Assembly', 'bytes': '1176000'}, {'name': 'Awk', 'bytes': '9519'}, {'name': 'C', 'bytes': '74909991'}, {'name': 'C#', 'bytes': '1132'}, {'name': 'C++', 'bytes': '174451678'}, {'name': 'DOT', 'bytes': '1559'}, {'name': 'F#', 'bytes': '381'}, {'name': 'Java', 'bytes': '3787983'}, {'name': 'JavaScript', 'bytes': '19649328'}, {'name': 'Logos', 'bytes': '4517'}, {'name': 'M', 'bytes': '2190'}, {'name': 'Matlab', 'bytes': '3044'}, {'name': 'Objective-C', 'bytes': '7600008'}, {'name': 'PHP', 'bytes': '97817'}, {'name': 'Perl', 'bytes': '1473407'}, {'name': 'Python', 'bytes': '10022969'}, {'name': 'R', 'bytes': '262'}, {'name': 'Shell', 'bytes': '1590292'}, {'name': 'Tcl', 'bytes': '277077'}, {'name': 'XSLT', 'bytes': '13493'}]}
// Copyright (c) 2014, Oracle and/or its affiliates. // Contributed and/or modified by Menelaos Karavelas, on behalf of Oracle // Licensed under the Boost Software License version 1.0. // http://www.boost.org/users/license.html #include <test_geometries/custom_lon_lat_point.hpp> #include <boost/geometry/core/cs.hpp> #include <boost/geometry/geometries/point.hpp> #include <boost/geometry/geometries/concepts/check.hpp> namespace bg = boost::geometry; template <typename CoordinateSystem> inline void test_coordinate_system() { typedef bg::model::point<double, 2, CoordinateSystem> bg_double_point; typedef bg::model::point<int, 2, CoordinateSystem> bg_int_point; typedef rw_lon_lat_point<double, CoordinateSystem> rw_double_point; typedef ro_lon_lat_point<double, CoordinateSystem> ro_double_point; typedef rw_lon_lat_point<int, CoordinateSystem> rw_int_point; typedef ro_lon_lat_point<int, CoordinateSystem> ro_int_point; bg::concept::check<bg_int_point>(); bg::concept::check<bg_int_point const>(); bg::concept::check<bg_double_point>(); bg::concept::check<bg_double_point const>(); bg::concept::check<rw_int_point>(); bg::concept::check<rw_int_point const>(); bg::concept::check<ro_int_point const>(); bg::concept::check<rw_double_point>(); bg::concept::check<rw_double_point const>(); bg::concept::check<ro_double_point const>(); } int main() { test_coordinate_system<bg::cs::geographic<bg::degree> >(); test_coordinate_system<bg::cs::geographic<bg::radian> >(); test_coordinate_system<bg::cs::spherical<bg::degree> >(); test_coordinate_system<bg::cs::spherical<bg::radian> >(); test_coordinate_system<bg::cs::spherical_equatorial<bg::degree> >(); test_coordinate_system<bg::cs::spherical_equatorial<bg::radian> >(); test_coordinate_system<bg::cs::polar<bg::degree> >(); test_coordinate_system<bg::cs::polar<bg::radian> >(); return 0; }
{'content_hash': '098700a3746a729e8eaeea9345ae0414', 'timestamp': '', 'source': 'github', 'line_count': 62, 'max_line_length': 74, 'avg_line_length': 32.67741935483871, 'alnum_prop': 0.6742349457058243, 'repo_name': 'Franky666/programmiersprachen-raytracer', 'id': '36166d85b5049516033bb9b4da8d0b3e7e0752d1', 'size': '2095', 'binary': False, 'copies': '5', 'ref': 'refs/heads/master', 'path': 'external/boost_1_59_0/libs/geometry/test/concepts/point_well_formed_non_cartesian.cpp', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'C', 'bytes': '905071'}, {'name': 'C++', 'bytes': '46207'}, {'name': 'CMake', 'bytes': '4419'}]}
package com.kerchin.yellownote.data.event; /** * Created by hkq325800 on 2016/12/7. */ public class NoteDeleteErrorEvent { public String getStr() { return str; } public void setStr(String str) { this.str = str; } private String str; public NoteDeleteErrorEvent(String str) { this.str = str; } }
{'content_hash': '3afe4b0d3020a8947953f1436713aeae', 'timestamp': '', 'source': 'github', 'line_count': 21, 'max_line_length': 45, 'avg_line_length': 16.857142857142858, 'alnum_prop': 0.6129943502824858, 'repo_name': 'hkq325800/YellowNote', 'id': '51bc5dab46fe49e839ca24f808fa1a2a3157ebef', 'size': '354', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'app/src/main/java/com/kerchin/yellownote/data/event/NoteDeleteErrorEvent.java', 'mode': '33188', 'license': 'apache-2.0', 'language': [{'name': 'Java', 'bytes': '959303'}]}
class Room attr_accessor :name, :description, :paths def initialize(name, description) @name = name @description = description @paths = {} end def go(direction) @paths[direction] end def add_paths(paths) @paths.update(paths) end end central_corridor = Room.new("Central Corridor", %q{ The Gothons of Planet Percal #25 have invaded your ship and destroyed your entire crew. You are the last surviving member and your last mission is to get the neutron destruct bomb from the Weapons Armory, put it in the bridge, and blow the ship up after getting into an escape pod. You're running down the central corridor to the Weapons Armory when a Gothon jumps out, red scaly skin, dark grimy teeth, and evil clown costume flowing around his hate filled body. He's blocking the door to the Armory and about to pull a weapon to blast you. }) laser_weapon_armory = Room.new("Laser Weapon Armory", %q{ Lucky for you they made you learn Gothon insults in the academy. You tell the one Gothon joke you know: Lbhe zbgure vf fb sng, jura fur fvgf nebhaq gur ubhfr, fur fvgf nebhaq gur ubhfr. The Gothon stops, tries not to laugh, then busts out laughing and can't move. While he's laughing you run up and shoot him square in the head putting him down, then jump through the Weapon Armory door. You do a dive roll into the Weapon Armory, crouch and scan the room for more Gothons that might be hiding. It's dead quiet, too quiet. You stand up and run to the far side of the room and find the neutron bomb in its container. There's a keypad lock on the box and you need the code to get the bomb out. If you get the code wrong 10 times then the lock closes forever and you can't get the bomb. The code is 3 digits. }) the_bridge = Room.new("The Bridge", %q{ The container clicks open and the seal breaks, letting gas out. You grab the neutron bomb and run as fast as you can to the bridge where you must place it in the right spot. You burst onto the Bridge with the neutron destruct bomb under your arm and surprise 5 Gothons who are trying to take control of the ship. Each of them has an even uglier clown costume than the last. They haven't pulled their weapons out yet, as they see the active bomb under your arm and don't want to set it off. }) escape_pod = Room.new("Escape Pod", %q{ You point your blaster at the bomb under your arm and the Gothons put their hands up and start to sweat. You inch backward to the door, open it, and then carefully place the bomb on the floor, pointing your blaster at it. You then jump back through the door, punch the close button and blast the lock so the Gothons can't get out. Now that the bomb is placed you run to the escape pod to get off this tin can. You rush through the ship desperately trying to make it to the escape pod before the whole ship explodes. It seems like hardly any Gothons are on the ship, so your run is clear of interference. You get to the chamber with the escape pods, and now need to pick one to take. Some of them could be damaged but you don't have time to look. There's 5 pods, which one do you take? }) the_end_winner = Room.new("The End", %q{ You jump into pod 2 and hit the eject button. The pod easily slides out into space heading to the planet below. As it flies to the planet, you look back and see your ship implode then explode like a bright star, taking out the Gothon ship at the same time. You won! }) the_end_loser = Room.new("The End", %q{ You jump into a random pod and hit the eject button. The pod escapes out into the void of space, then implodes as the hull ruptures, crushing your body into jam jelly. }) escape_pod.add_paths({ '2' => the_end_winner, '*' => the_end_loser }) central_corridor_shoot = Room.new("Death", %q{ Quick on the draw you yank out your blaster and fire it at the Gothon. His clown costume is flowing and moving around his body, which throws off your aim. Your laser hits his costume but misses him entirely. This completely ruins his brand new costume his mother bought him, which makes him fly into an insane rage and blast you repeatedly in the face unitl you are dead. Then he eats you. }) central_corridor_dodge = Room.new("Death", %q{ Like a world class boxer you dodge, weave, slip and slide right as the Gothon's blaster cranks a laser past your head. In the middle of your artful dodge your foot slips and you bang your head on the metal wall and pass out. You wake up shortly after only to die as the Gothon stomps on your head and eats you. }) the_bridge_bomb = Room.new("Death", %q{ In a panic you throw the bomb at the group of Gothons and make a leap for the door. Right as you drop it a Gothon shoots you right in hte back killing you. As you die you see another Gothon frantically tyr to disarm the bomb. You die knowing they will probably blow up when it goes off. }) laser_weapon_armory_fail = Room.new("Death", %q{ The lock buzzes one last time and then you hear a sickening melting sound as the mechanism is fused together. You decide to sit there, and finally the Gothons blow up the ship from their ship and you die. }) the_bridge.add_paths({ 'throw the bomb' => the_bridge_bomb, 'slowly place the bomb' => escape_pod }) laser_weapon_armory.add_paths({ '0132' => the_bridge, '*' => laser_weapon_armory_fail }) central_corridor.add_paths({ 'shoot!' => central_corridor_shoot, 'dodge!' => central_corridor_dodge, 'tell a joke' => laser_weapon_armory }) START = central_corridor ROOMS = { "central_corridor" => central_corridor, "central_corridor_shoot" => central_corridor_shoot, "central_corridor_dodge" => central_corridor_dodge, "laser_weapon_armory" => laser_weapon_armory, "laser_weapon_armory_fail" => laser_weapon_armory_fail, "the_bridge" => the_bridge, "the_bridge_bomb" => the_bridge_bomb, "escape_pod" => escape_pod, "the_end_winner" => the_end_winner, "the_end_loser" => the_end_loser }
{'content_hash': '79bdf1f5afb031f0b6f0d47bc5dbb008', 'timestamp': '', 'source': 'github', 'line_count': 170, 'max_line_length': 82, 'avg_line_length': 35.72941176470588, 'alnum_prop': 0.724399078037537, 'repo_name': 'j0rgy/gothonweb', 'id': '0a5521729c53f049e097cae019927020d7ab463a', 'size': '6074', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'lib/map.rb', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'Ruby', 'bytes': '11917'}]}
var startgame = function(){ location.href = "http:localhost:8080/play"; };
{'content_hash': '7385feb6712caa9db6b09603d43682d3', 'timestamp': '', 'source': 'github', 'line_count': 3, 'max_line_length': 45, 'avg_line_length': 25.333333333333332, 'alnum_prop': 0.6973684210526315, 'repo_name': 'abhilash-dev/professor-X', 'id': '2c2bb6a20688dd06c71cf99437e2c413400839d7', 'size': '76', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'Professor-X/src/main/resources/static/js/start.js', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'CSS', 'bytes': '47246'}, {'name': 'HTML', 'bytes': '22208'}, {'name': 'Java', 'bytes': '69219'}, {'name': 'JavaScript', 'bytes': '17123'}]}
export interface Middleware<T> { (context: T, next: ContinuationMiddleware<T>): any } export interface ContinuationMiddleware<T> { (context?: T, next?: Middleware<T>): any } const flatten = <T>(values: Array<T | Array<T>>) => ([] as any).concat(...values) as T[], noop = function noop() { return Promise.resolve() } function throwIfHasBeenCalled(fn: any) { if (fn.__appbuildercalled) { throw new Error('Cannot call next more than once') } return (fn.__appbuildercalled = true) } function tryInvokeMiddleware<T>(context: T, middleware: Middleware<T>, next: ContinuationMiddleware<T> = noop) { try { return Promise.resolve(middleware ? middleware(context, next) : context) } catch (error) { return Promise.reject(error) } } export function functionList<T = any>(list: Function | Function[], ...args: any[]): Middleware<T>[] { const arrayList = Symbol.iterator in list ? Array.from(list as Function[]) : [list as Function] return arrayList.map((x) => { return (_: any, next: any) => Promise.resolve(x(...args)).then(next) }) } /** * Create a function to invoke all passed middleware functions * with a single argument <T>context * @param middleware */ export function compose<T = any>(...middleware: (Middleware<T> | Middleware<T>[])[]): ContinuationMiddleware<T> { return flatten(middleware) .filter((x) => { if ('function' !== typeof x) { throw new TypeError(`${x}, must be a middleware function accpeting (context, next) arguments`) } return x }) .reduceRight((composed: Middleware<T>, mw: Middleware<T>) => { return function (context: T, nextFn: ContinuationMiddleware<T>) { const next = () => throwIfHasBeenCalled(next) && composed(context, nextFn) return tryInvokeMiddleware(context, mw, next) } }, tryInvokeMiddleware) as ContinuationMiddleware<T> }
{'content_hash': '6ae61642b7c58194f1728c38a9412b57', 'timestamp': '', 'source': 'github', 'line_count': 54, 'max_line_length': 113, 'avg_line_length': 34.833333333333336, 'alnum_prop': 0.6634768740031898, 'repo_name': 'calebboyd/app-builder', 'id': '3d2827115e8ff8387651397c026eedf9eed49bbd', 'size': '1881', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'src/compose.ts', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'TypeScript', 'bytes': '6288'}]}
/** * A simple custom row expander that does not add a "+" / "-" column. */ Ext.define('ExecDashboard.ux.plugin.RowExpander', { extend: 'Ext.grid.plugin.RowExpander', alias: 'plugin.ux-rowexpander', rowBodyTpl: [ '<div class="text-wrapper">', '<div class="news-data">', '<div class="news-paragraph">{paragraph}</div>', '<div class="news-toggle collapse"><span>COLLAPSE</span><img src="https://static.rasc.ch/ext-6.5.2/build/examples/classic/executive-dashboard/resources/icons/collapse-news.png"></div>', '</div>', '</div>' ], // don't add the expander +/- because we will use a custom one instead addExpander: Ext.emptyFn, addCollapsedCls: { fn: function(out, values, parent) { var me = this.rowExpander; if (!me.recordsExpanded[values.record.internalId]) { values.itemClasses.push(me.rowCollapsedCls); } else { values.itemClasses.push('x-grid-row-expanded'); } this.nextTpl.applyOut(values, out, parent); }, syncRowHeights: function(lockedItem, normalItem) { this.rowExpander.syncRowHeights(lockedItem, normalItem); }, // We need a high priority to get in ahead of the outerRowTpl // so we can setup row data priority: 20000 } });
{'content_hash': '9423061655f413b2039420abbaea9703', 'timestamp': '', 'source': 'github', 'line_count': 41, 'max_line_length': 201, 'avg_line_length': 34.292682926829265, 'alnum_prop': 0.5839260312944523, 'repo_name': 'ralscha/extdirectspring-demo', 'id': '37024e5bb022671dcdaff7954f911359cbec2c0f', 'size': '1406', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'src/main/resources/static/extjs6classic/executive-dashboard/app/ux/plugin/RowExpander.js', 'mode': '33188', 'license': 'apache-2.0', 'language': [{'name': 'Batchfile', 'bytes': '683'}, {'name': 'CSS', 'bytes': '17363'}, {'name': 'HTML', 'bytes': '136892'}, {'name': 'Java', 'bytes': '370333'}, {'name': 'JavaScript', 'bytes': '1171254'}]}
using System; using NUnit.Framework; using osu.Framework.Allocation; using osu.Framework.Bindables; using osu.Framework.Graphics; using osu.Framework.Graphics.Containers; using osu.Game.Online.Rooms; using osu.Game.Screens.OnlinePlay; namespace osu.Game.Tests.Visual.OnlinePlay { /// <summary> /// A base test scene for all online play components and screens. /// </summary> public abstract class OnlinePlayTestScene : ScreenTestScene, IOnlinePlayTestSceneDependencies { public Bindable<Room> SelectedRoom => OnlinePlayDependencies?.SelectedRoom; public IRoomManager RoomManager => OnlinePlayDependencies?.RoomManager; public OngoingOperationTracker OngoingOperationTracker => OnlinePlayDependencies?.OngoingOperationTracker; public OnlinePlayBeatmapAvailabilityTracker AvailabilityTracker => OnlinePlayDependencies?.AvailabilityTracker; /// <summary> /// All dependencies required for online play components and screens. /// </summary> protected OnlinePlayTestSceneDependencies OnlinePlayDependencies => dependencies?.OnlinePlayDependencies; private DelegatedDependencyContainer dependencies; protected override Container<Drawable> Content => content; private readonly Container content; private readonly Container drawableDependenciesContainer; protected OnlinePlayTestScene() { base.Content.AddRange(new Drawable[] { drawableDependenciesContainer = new Container { RelativeSizeAxes = Axes.Both }, content = new Container { RelativeSizeAxes = Axes.Both }, }); } protected override IReadOnlyDependencyContainer CreateChildDependencies(IReadOnlyDependencyContainer parent) { dependencies = new DelegatedDependencyContainer(base.CreateChildDependencies(parent)); return dependencies; } [SetUp] public void Setup() => Schedule(() => { // Reset the room dependencies to a fresh state. drawableDependenciesContainer.Clear(); dependencies.OnlinePlayDependencies = CreateOnlinePlayDependencies(); drawableDependenciesContainer.AddRange(OnlinePlayDependencies.DrawableComponents); }); /// <summary> /// Creates the room dependencies. Called every <see cref="Setup"/>. /// </summary> /// <remarks> /// Any custom dependencies required for online play sub-classes should be added here. /// </remarks> protected virtual OnlinePlayTestSceneDependencies CreateOnlinePlayDependencies() => new OnlinePlayTestSceneDependencies(); /// <summary> /// A <see cref="IReadOnlyDependencyContainer"/> providing a mutable lookup source for online play dependencies. /// </summary> private class DelegatedDependencyContainer : IReadOnlyDependencyContainer { /// <summary> /// The online play dependencies. /// </summary> public OnlinePlayTestSceneDependencies OnlinePlayDependencies { get; set; } private readonly IReadOnlyDependencyContainer parent; private readonly DependencyContainer injectableDependencies; /// <summary> /// Creates a new <see cref="DelegatedDependencyContainer"/>. /// </summary> /// <param name="parent">The fallback <see cref="IReadOnlyDependencyContainer"/> to use when <see cref="OnlinePlayDependencies"/> cannot satisfy a dependency.</param> public DelegatedDependencyContainer(IReadOnlyDependencyContainer parent) { this.parent = parent; injectableDependencies = new DependencyContainer(this); } public object Get(Type type) => OnlinePlayDependencies?.Get(type) ?? parent.Get(type); public object Get(Type type, CacheInfo info) => OnlinePlayDependencies?.Get(type, info) ?? parent.Get(type, info); public void Inject<T>(T instance) where T : class => injectableDependencies.Inject(instance); } } }
{'content_hash': '736eb04da0b759ce60643001076f0352', 'timestamp': '', 'source': 'github', 'line_count': 99, 'max_line_length': 178, 'avg_line_length': 42.90909090909091, 'alnum_prop': 0.6664312617702448, 'repo_name': 'peppy/osu-new', 'id': '87166460747311eea3c23459cf12a782158c8427', 'size': '4398', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'osu.Game/Tests/Visual/OnlinePlay/OnlinePlayTestScene.cs', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'C#', 'bytes': '281779'}]}
/* * Created on May 6, 2005 * */ namespace NPOI.SS.Formula.Functions { using System; using NPOI.SS.Formula.Eval; /** * @author Amol S. Deshmukh &lt; amolweb at ya hoo dot com &gt; * */ internal class True : Fixed0ArgFunction { public override ValueEval Evaluate(int srcRowIndex, int srcColumnIndex) { return BoolEval.TRUE; } } }
{'content_hash': '3dac27e2d71e747a523afb589cf0a7f3', 'timestamp': '', 'source': 'github', 'line_count': 23, 'max_line_length': 79, 'avg_line_length': 18.82608695652174, 'alnum_prop': 0.5496535796766744, 'repo_name': 'treenew/sofire', 'id': '891d8a2a05c1ed4945d09ab5bed7a8831ebb4580', 'size': '1234', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'src/Core/Sofire.Extends/Excel/NPOI/SS/Formula/Functions/Boolean/True.cs', 'mode': '33188', 'license': 'apache-2.0', 'language': [{'name': 'C#', 'bytes': '17254659'}, {'name': 'Shell', 'bytes': '682'}]}
#include "BaseLibInternals.h" /** Multiples a 64-bit unsigned integer by a 32-bit unsigned integer and generates a 64-bit unsigned result. This function multiples the 64-bit unsigned value Multiplicand by the 32-bit unsigned value Multiplier and generates a 64-bit unsigned result. This 64- bit unsigned result is returned. @param Multiplicand A 64-bit unsigned value. @param Multiplier A 32-bit unsigned value. @return Multiplicand * Multiplier **/ UINT64 EFIAPI GlueMultU64x32 ( IN UINT64 Multiplicand, IN UINT32 Multiplier ) { UINT64 Result; Result = InternalMathMultU64x32 (Multiplicand, Multiplier); return Result; }
{'content_hash': '882efd20bf0166267fbdc1bda59412dd', 'timestamp': '', 'source': 'github', 'line_count': 31, 'max_line_length': 78, 'avg_line_length': 23.870967741935484, 'alnum_prop': 0.6716216216216216, 'repo_name': 'tianocore/edk', 'id': '93b1411b1ea2179ef002c4168005e2e517b3fdf8', 'size': '1550', 'binary': False, 'copies': '2', 'ref': 'refs/heads/master', 'path': 'Foundation/Library/EdkIIGlueLib/Library/BaseLib/MultU64x32.c', 'mode': '33188', 'license': 'bsd-3-clause', 'language': [{'name': 'Assembly', 'bytes': '947898'}, {'name': 'C', 'bytes': '18163757'}, {'name': 'C++', 'bytes': '1437397'}, {'name': 'GAP', 'bytes': '256118'}, {'name': 'Objective-C', 'bytes': '2657772'}, {'name': 'Shell', 'bytes': '60476'}]}
import Notifications from './Notifications.js'; export default Notifications;
{'content_hash': '23bf4d090837565ef76e7fb1c41a3b01', 'timestamp': '', 'source': 'github', 'line_count': 2, 'max_line_length': 47, 'avg_line_length': 39.0, 'alnum_prop': 0.8205128205128205, 'repo_name': 'Axivity/openmovement-axsys-client', 'id': '1d62ec7049974c62d8ccd4cb2c158a52ddce63ae', 'size': '78', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'vendor/react-notifications/src/index.js', 'mode': '33188', 'license': 'bsd-2-clause', 'language': [{'name': 'CSS', 'bytes': '3987'}, {'name': 'HTML', 'bytes': '2091'}, {'name': 'JavaScript', 'bytes': '150611'}]}
.class public Lcom/android/server/pm/PersistentPreferredIntentResolver; .super Lcom/android/server/IntentResolver; .source "PersistentPreferredIntentResolver.java" # annotations .annotation system Ldalvik/annotation/Signature; value = { "Lcom/android/server/IntentResolver", "<", "Lcom/android/server/pm/PersistentPreferredActivity;", "Lcom/android/server/pm/PersistentPreferredActivity;", ">;" } .end annotation # direct methods .method public constructor <init>()V .locals 0 .prologue .line 23 invoke-direct {p0}, Lcom/android/server/IntentResolver;-><init>()V return-void .end method # virtual methods .method protected bridge synthetic isPackageForFilter(Ljava/lang/String;Landroid/content/IntentFilter;)Z .locals 1 .param p1, "x0" # Ljava/lang/String; .param p2, "x1" # Landroid/content/IntentFilter; .prologue .line 23 check-cast p2, Lcom/android/server/pm/PersistentPreferredActivity; .end local p2 # "x1":Landroid/content/IntentFilter; invoke-virtual {p0, p1, p2}, Lcom/android/server/pm/PersistentPreferredIntentResolver;->isPackageForFilter(Ljava/lang/String;Lcom/android/server/pm/PersistentPreferredActivity;)Z move-result v0 return v0 .end method .method protected isPackageForFilter(Ljava/lang/String;Lcom/android/server/pm/PersistentPreferredActivity;)Z .locals 1 .param p1, "packageName" # Ljava/lang/String; .param p2, "filter" # Lcom/android/server/pm/PersistentPreferredActivity; .prologue .line 32 iget-object v0, p2, Lcom/android/server/pm/PersistentPreferredActivity;->mComponent:Landroid/content/ComponentName; invoke-virtual {v0}, Landroid/content/ComponentName;->getPackageName()Ljava/lang/String; move-result-object v0 invoke-virtual {p1, v0}, Ljava/lang/String;->equals(Ljava/lang/Object;)Z move-result v0 return v0 .end method .method protected bridge synthetic newArray(I)[Landroid/content/IntentFilter; .locals 1 .param p1, "x0" # I .prologue .line 23 invoke-virtual {p0, p1}, Lcom/android/server/pm/PersistentPreferredIntentResolver;->newArray(I)[Lcom/android/server/pm/PersistentPreferredActivity; move-result-object v0 return-object v0 .end method .method protected newArray(I)[Lcom/android/server/pm/PersistentPreferredActivity; .locals 1 .param p1, "size" # I .prologue .line 27 new-array v0, p1, [Lcom/android/server/pm/PersistentPreferredActivity; return-object v0 .end method
{'content_hash': 'f0dbbe5a7aa396ea4f36b943cfe29952', 'timestamp': '', 'source': 'github', 'line_count': 90, 'max_line_length': 182, 'avg_line_length': 28.5, 'alnum_prop': 0.7228070175438597, 'repo_name': 'hexiaoshuai/Flyme_device_ZTE_A1', 'id': '7d0c6cd70cf586abf4521839e05ebd3f5c60f508', 'size': '2565', 'binary': False, 'copies': '2', 'ref': 'refs/heads/C880AV1.0.0B06', 'path': 'services.jar.out/smali/com/android/server/pm/PersistentPreferredIntentResolver.smali', 'mode': '33188', 'license': 'apache-2.0', 'language': [{'name': 'GLSL', 'bytes': '1500'}, {'name': 'HTML', 'bytes': '10195'}, {'name': 'Makefile', 'bytes': '11258'}, {'name': 'Python', 'bytes': '924'}, {'name': 'Shell', 'bytes': '2734'}, {'name': 'Smali', 'bytes': '234274633'}]}
export * from "./from-exports";
{'content_hash': '943b6e87d11b9904fa19cc67ed91983c', 'timestamp': '', 'source': 'github', 'line_count': 1, 'max_line_length': 31, 'avg_line_length': 32.0, 'alnum_prop': 0.65625, 'repo_name': 'stealjs/steal-tools', 'id': 'f1addbd36840c6b3da5f8b37ec36dc17800f36d5', 'size': '33', 'binary': False, 'copies': '2', 'ref': 'refs/heads/master', 'path': 'test/treeshake/disabled/reexports.js', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'CSS', 'bytes': '454'}, {'name': 'HTML', 'bytes': '26153'}, {'name': 'JavaScript', 'bytes': '1116049'}, {'name': 'Less', 'bytes': '1521'}]}
@interface demoUITests : XCTestCase @end @implementation demoUITests - (void)setUp { [super setUp]; // Put setup code here. This method is called before the invocation of each test method in the class. // In UI tests it is usually best to stop immediately when a failure occurs. self.continueAfterFailure = NO; // UI tests must launch the application that they test. Doing this in setup will make sure it happens for each test method. [[[XCUIApplication alloc] init] launch]; // In UI tests it’s important to set the initial state - such as interface orientation - required for your tests before they run. The setUp method is a good place to do this. } - (void)tearDown { // Put teardown code here. This method is called after the invocation of each test method in the class. [super tearDown]; } - (void)testExample { // Use recording to get started writing UI tests. // Use XCTAssert and related functions to verify your tests produce the correct results. } @end
{'content_hash': 'fbde17640562b01554a7d611a5455993', 'timestamp': '', 'source': 'github', 'line_count': 30, 'max_line_length': 178, 'avg_line_length': 34.3, 'alnum_prop': 0.7152575315840622, 'repo_name': 'zhangjie579/ZJPhotoBrower', 'id': '9493072379a33bdd01fcb5f60093a36b19cdf6a7', 'size': '1191', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'demoUITests/demoUITests.m', 'mode': '33261', 'license': 'mit', 'language': [{'name': 'Objective-C', 'bytes': '2073'}, {'name': 'Ruby', 'bytes': '647'}]}
<!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.11"/> <title>Lua-API++: Class Index</title> <link href="tabs.css" rel="stylesheet" type="text/css"/> <script type="text/javascript" src="jquery.js"></script> <script type="text/javascript" src="dynsections.js"></script> <link href="navtree.css" rel="stylesheet" type="text/css"/> <script type="text/javascript" src="resize.js"></script> <script type="text/javascript" src="navtreedata.js"></script> <script type="text/javascript" src="navtree.js"></script> <script type="text/javascript"> $(document).ready(initResizable); $(window).load(resizeHeight); </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/javascript"> $(document).ready(function() { init_search(); }); </script> <link href="doxygen.css" rel="stylesheet" type="text/css" /> </head> <body> <div id="top"><!-- do not remove this div, it is closed by doxygen! --> <div id="titlearea"> <table cellspacing="0" cellpadding="0"> <tbody> <tr style="height: 56px;"> <td id="projectlogo"><img alt="Logo" src="lpp_logo.png"/></td> <td id="projectalign" style="padding-left: 0.5em;"> <div id="projectname">Lua-API++ &#160;<span id="projectnumber">2015-02-12-3</span> </div> <div id="projectbrief">Lua-API++ library</div> </td> </tr> </tbody> </table> </div> <!-- end header part --> <!-- Generated by Doxygen 1.8.11 --> <script type="text/javascript"> var searchBox = new SearchBox("searchBox", "search",false,'Search'); </script> <div id="navrow1" class="tabs"> <ul class="tablist"> <li><a href="index.html"><span>Main&#160;Page</span></a></li> <li><a href="pages.html"><span>Related&#160;Pages</span></a></li> <li class="current"><a href="annotated.html"><span>Classes</span></a></li> <li><a href="files.html"><span>Files</span></a></li> <li> <div id="MSearchBox" class="MSearchBoxInactive"> <span class="left"> <img id="MSearchSelect" src="search/mag_sel.png" onmouseover="return searchBox.OnSearchSelectShow()" onmouseout="return searchBox.OnSearchSelectHide()" alt=""/> <input type="text" id="MSearchField" value="Search" accesskey="S" onfocus="searchBox.OnSearchFieldFocus(true)" onblur="searchBox.OnSearchFieldFocus(false)" onkeyup="searchBox.OnSearchFieldChange(event)"/> </span><span class="right"> <a id="MSearchClose" href="javascript:searchBox.CloseResultsWindow()"><img id="MSearchCloseImg" border="0" src="search/close.png" alt=""/></a> </span> </div> </li> </ul> </div> <div id="navrow2" class="tabs2"> <ul class="tablist"> <li><a href="annotated.html"><span>Class&#160;List</span></a></li> <li class="current"><a href="classes.html"><span>Class&#160;Index</span></a></li> <li><a href="hierarchy.html"><span>Class&#160;Hierarchy</span></a></li> <li><a href="functions.html"><span>Class&#160;Members</span></a></li> </ul> </div> </div><!-- top --> <div id="side-nav" class="ui-resizable side-nav-resizable"> <div id="nav-tree"> <div id="nav-tree-contents"> <div id="nav-sync" class="sync"></div> </div> </div> <div id="splitbar" style="-moz-user-select:none;" class="ui-resizable-handle"> </div> </div> <script type="text/javascript"> $(document).ready(function(){initNavTree('classes.html','');}); </script> <div id="doc-content"> <!-- 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 class="header"> <div class="headertitle"> <div class="title">Class Index</div> </div> </div><!--header--> <div class="contents"> <div class="qindex"><a class="qindex" href="#letter_C">C</a>&#160;|&#160;<a class="qindex" href="#letter_N">N</a>&#160;|&#160;<a class="qindex" href="#letter_R">R</a>&#160;|&#160;<a class="qindex" href="#letter_S">S</a>&#160;|&#160;<a class="qindex" href="#letter_T">T</a>&#160;|&#160;<a class="qindex" href="#letter_V">V</a></div> <table class="classindex"> <tr><td rowspan="2" valign="bottom"><a name="letter_C"></a><table border="0" cellspacing="0" cellpadding="0"><tr><td><div class="ah">&#160;&#160;C&#160;&#160;</div></td></tr></table> </td><td rowspan="2" valign="bottom"><a name="letter_R"></a><table border="0" cellspacing="0" cellpadding="0"><tr><td><div class="ah">&#160;&#160;R&#160;&#160;</div></td></tr></table> </td><td rowspan="2" valign="bottom"><a name="letter_T"></a><table border="0" cellspacing="0" cellpadding="0"><tr><td><div class="ah">&#160;&#160;T&#160;&#160;</div></td></tr></table> </td><td valign="top"><a class="el" href="classlua_1_1_valref.html">Valref</a> (<a class="el" href="namespacelua.html">lua</a>)&#160;&#160;&#160;</td></tr> <tr><td valign="top"><a class="el" href="classlua_1_1_valset.html">Valset</a> (<a class="el" href="namespacelua.html">lua</a>)&#160;&#160;&#160;</td></tr> <tr><td valign="top"><a class="el" href="namespacelua.html#structlua_1_1_closure_info">ClosureInfo</a> (<a class="el" href="namespacelua.html">lua</a>)&#160;&#160;&#160;</td><td valign="top"><a class="el" href="classlua_1_1_context_1_1_registry.html">Context::Registry</a> (<a class="el" href="namespacelua.html">lua</a>)&#160;&#160;&#160;</td><td valign="top"><a class="el" href="classlua_1_1_table.html">Table</a> (<a class="el" href="namespacelua.html">lua</a>)&#160;&#160;&#160;</td><td valign="top"><a class="el" href="classlua_1_1_value.html">Value</a> (<a class="el" href="namespacelua.html">lua</a>)&#160;&#160;&#160;</td></tr> <tr><td valign="top"><a class="el" href="classlua_1_1_context.html">Context</a> (<a class="el" href="namespacelua.html">lua</a>)&#160;&#160;&#160;</td><td valign="top"><a class="el" href="classlua_1_1_registry_key.html">RegistryKey</a> (<a class="el" href="namespacelua.html">lua</a>)&#160;&#160;&#160;</td><td valign="top"><a class="el" href="namespacelua.html#classlua_1_1_temporary">Temporary</a> (<a class="el" href="namespacelua.html">lua</a>)&#160;&#160;&#160;</td><td></td></tr> <tr><td rowspan="2" valign="bottom"><a name="letter_N"></a><table border="0" cellspacing="0" cellpadding="0"><tr><td><div class="ah">&#160;&#160;N&#160;&#160;</div></td></tr></table> </td><td valign="top"><a class="el" href="classlua_1_1_retval.html">Retval</a> (<a class="el" href="namespacelua.html">lua</a>)&#160;&#160;&#160;</td><td valign="top"><a class="el" href="structlua_1_1_type_i_d.html">TypeID</a> (<a class="el" href="namespacelua.html">lua</a>)&#160;&#160;&#160;</td><td></td></tr> <tr><td rowspan="2" valign="bottom"><a name="letter_S"></a><table border="0" cellspacing="0" cellpadding="0"><tr><td><div class="ah">&#160;&#160;S&#160;&#160;</div></td></tr></table> </td><td rowspan="2" valign="bottom"><a name="letter_V"></a><table border="0" cellspacing="0" cellpadding="0"><tr><td><div class="ah">&#160;&#160;V&#160;&#160;</div></td></tr></table> </td><td></td></tr> <tr><td valign="top"><a class="el" href="namespacelua.html#classlua_1_1_nil">Nil</a> (<a class="el" href="namespacelua.html">lua</a>)&#160;&#160;&#160;</td><td></td></tr> <tr><td></td><td valign="top"><a class="el" href="classlua_1_1_state.html">State</a> (<a class="el" href="namespacelua.html">lua</a>)&#160;&#160;&#160;</td><td valign="top"><a class="el" href="namespacelua.html#classlua_1_1_valobj">Valobj</a> (<a class="el" href="namespacelua.html">lua</a>)&#160;&#160;&#160;</td><td></td></tr> <tr><td></td><td></td><td></td><td></td></tr> </table> <div class="qindex"><a class="qindex" href="#letter_C">C</a>&#160;|&#160;<a class="qindex" href="#letter_N">N</a>&#160;|&#160;<a class="qindex" href="#letter_R">R</a>&#160;|&#160;<a class="qindex" href="#letter_S">S</a>&#160;|&#160;<a class="qindex" href="#letter_T">T</a>&#160;|&#160;<a class="qindex" href="#letter_V">V</a></div> </div><!-- contents --> </div><!-- doc-content --> <!-- start footer part --> <div id="nav-path" class="navpath"><!-- id is needed for treeview function! --> <ul> <li class="footer">Generated by <a href="http://www.doxygen.org/index.html"> <img class="footer" src="doxygen.png" alt="doxygen"/></a> 1.8.11 </li> </ul> </div> </body> </html>
{'content_hash': '82adb62672427a69ba38bee4f7010e5a', 'timestamp': '', 'source': 'github', 'line_count': 145, 'max_line_length': 635, 'avg_line_length': 62.04137931034483, 'alnum_prop': 0.630057803468208, 'repo_name': 'tnovits-d2d/luapp', 'id': '1958466a8b2e57a52274b9d635d6c3e0f7b20dc7', 'size': '8996', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'doc/html/classes.html', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'C', 'bytes': '918'}, {'name': 'C++', 'bytes': '317526'}, {'name': 'Objective-C', 'bytes': '511'}]}
package com.lithiumsheep.jacketapp; import org.junit.Test; import static org.junit.Assert.assertEquals; /** * Example local unit test, which will execute on the development machine (host). * * @see <a href="http://d.android.com/tools/testing">Testing documentation</a> */ public class ExampleUnitTest { @Test public void addition_isCorrect() throws Exception { assertEquals(4, 2 + 2); } }
{'content_hash': '07d6825d0c75c153af3253ecc3a8a832', 'timestamp': '', 'source': 'github', 'line_count': 17, 'max_line_length': 81, 'avg_line_length': 24.41176470588235, 'alnum_prop': 0.7060240963855422, 'repo_name': 'lolsheeplol/jacketapp', 'id': 'dca56c0a239fb244077f7d789a21d3506278e552', 'size': '415', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'app/src/test/java/com/lithiumsheep/jacketapp/ExampleUnitTest.java', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'Java', 'bytes': '59431'}]}
<?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> <parent> <groupId>org.kie.server</groupId> <artifactId>kie-server-parent</artifactId> <version>7.0.0-SNAPSHOT</version> </parent> <artifactId>kie-server-controller</artifactId> <name>KIE :: Execution Server :: Controller</name> <description>KIE Execution Server Controller</description> <packaging>pom</packaging> <modules> <module>kie-server-controller-api</module> <module>kie-server-controller-impl</module> <module>kie-server-controller-rest</module> <module>kie-server-controller-test-war</module> </modules> </project>
{'content_hash': '300c41f75effbe997a0100e753cd1dc0', 'timestamp': '', 'source': 'github', 'line_count': 24, 'max_line_length': 108, 'avg_line_length': 36.25, 'alnum_prop': 0.6988505747126437, 'repo_name': 'murador/droolsjbpm-integration', 'id': '41a9dcfee9bcbcba77722e45a66d081de28bd73e', 'size': '870', 'binary': False, 'copies': '6', 'ref': 'refs/heads/master', 'path': 'kie-server-parent/kie-server-controller/pom.xml', 'mode': '33188', 'license': 'apache-2.0', 'language': [{'name': 'Batchfile', 'bytes': '2569'}, {'name': 'CSS', 'bytes': '7748'}, {'name': 'HTML', 'bytes': '2654'}, {'name': 'Java', 'bytes': '5623797'}, {'name': 'JavaScript', 'bytes': '32051'}, {'name': 'Shell', 'bytes': '3525'}, {'name': 'XSLT', 'bytes': '2865'}]}
package com.unnamed.b.atv.sample.holder; import android.content.Context; import android.view.LayoutInflater; import android.view.View; import android.widget.CheckBox; import android.widget.CompoundButton; import android.widget.TextView; import com.github.johnkil.print.PrintView; import com.unnamed.b.atv.model.TreeNode; import com.unnamed.b.atv.sample.R; /** * Created by Bogdan Melnychuk on 2/15/15, modified by Szigeti Peter 2/2/16. */ public class ArrowExpandSelectableHeaderHolder extends TreeNode.BaseNodeViewHolder<IconTreeItemHolder.IconTreeItem> { private TextView tvValue; private PrintView arrowView; private CheckBox nodeSelector; public ArrowExpandSelectableHeaderHolder(Context context) { super(context); } @Override public View createNodeView(final TreeNode node, IconTreeItemHolder.IconTreeItem value) { final LayoutInflater inflater = LayoutInflater.from(context); final View view = inflater.inflate(R.layout.layout_selectable_header, null, false); tvValue = (TextView) view.findViewById(R.id.node_value); tvValue.setText(value.text); final PrintView iconView = (PrintView) view.findViewById(R.id.icon); iconView.setIconText(context.getResources().getString(value.icon)); arrowView = (PrintView) view.findViewById(R.id.arrow_icon); arrowView.setPadding(20,10,10,10); if (node.isLeaf()) { arrowView.setVisibility(View.GONE); } arrowView.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { tView.toggleNode(node); } }); nodeSelector = (CheckBox) view.findViewById(R.id.node_selector); nodeSelector.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() { @Override public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) { node.setSelected(isChecked); for (TreeNode n : node.getChildren()) { getTreeView().selectNode(n, isChecked); } } }); nodeSelector.setChecked(node.isSelected()); return view; } @Override public void toggle(boolean active) { arrowView.setIconText(context.getResources().getString(active ? R.string.ic_keyboard_arrow_down : R.string.ic_keyboard_arrow_right)); } @Override public void toggleSelectionMode(boolean editModeEnabled) { nodeSelector.setVisibility(editModeEnabled ? View.VISIBLE : View.GONE); nodeSelector.setChecked(mNode.isSelected()); } }
{'content_hash': 'e9aafb0eae131a7ebffe799aa7bd4f78', 'timestamp': '', 'source': 'github', 'line_count': 74, 'max_line_length': 141, 'avg_line_length': 36.054054054054056, 'alnum_prop': 0.6829085457271364, 'repo_name': 'yehe01/AndroidTreeView', 'id': 'c58d0842a856a86b7196b5357d9f09d0dc2c06db', 'size': '2668', 'binary': False, 'copies': '2', 'ref': 'refs/heads/master', 'path': 'app/src/main/java/com/unnamed/b/atv/sample/holder/ArrowExpandSelectableHeaderHolder.java', 'mode': '33188', 'license': 'apache-2.0', 'language': [{'name': 'Java', 'bytes': '120189'}]}
using LmpClient.Base; using LmpClient.Base.Interface; using LmpClient.Extensions; using LmpCommon.Enums; using LmpCommon.Message.Data.Kerbal; using LmpCommon.Message.Interface; using LmpCommon.Message.Types; using System.Collections.Concurrent; namespace LmpClient.Systems.KerbalSys { public class KerbalMessageHandler : SubSystem<KerbalSystem>, IMessageHandler { public ConcurrentQueue<IServerMessageBase> IncomingMessages { get; set; } = new ConcurrentQueue<IServerMessageBase>(); public void HandleMessage(IServerMessageBase msg) { if (!(msg.Data is KerbalBaseMsgData msgData)) return; switch (msgData.KerbalMessageType) { case KerbalMessageType.Remove: System.KerbalsToRemove.Enqueue(((KerbalRemoveMsgData)msgData).KerbalName); break; case KerbalMessageType.Reply: HandleKerbalReply(msgData as KerbalReplyMsgData); break; case KerbalMessageType.Proto: HandleKerbalProto(msgData as KerbalProtoMsgData); break; default: LunaLog.LogError("[LMP]: Invalid Kerbal message type"); break; } } /// <summary> /// Just load the received kerbal into game and refresh dialogs /// </summary> private static void HandleKerbalProto(KerbalProtoMsgData messageData) { ProcessKerbal(messageData.Kerbal.KerbalData, messageData.Kerbal.NumBytes); } /// <summary> /// Appends the received kerbal to the dictionary /// </summary> private static void ProcessKerbal(byte[] kerbalData, int numBytes) { var kerbalNode = kerbalData.DeserializeToConfigNode(numBytes); if (kerbalNode != null) { System.KerbalsToProcess.Enqueue(kerbalNode); } else LunaLog.LogError("[LMP]: Failed to load kerbal!"); } /// <summary> /// We store all the kerbals in the KerbalProtoQueue dictionary so later once the game starts we load them /// </summary> /// <param name="messageData"></param> private static void HandleKerbalReply(KerbalReplyMsgData messageData) { for (var i = 0; i < messageData.KerbalsCount; i++) { ProcessKerbal(messageData.Kerbals[i].KerbalData, messageData.Kerbals[i].NumBytes); } LunaLog.Log("[LMP]: Kerbals Synced!"); MainSystem.NetworkState = ClientState.KerbalsSynced; } } }
{'content_hash': '2a1675195d29087b473ac18426494fdc', 'timestamp': '', 'source': 'github', 'line_count': 74, 'max_line_length': 126, 'avg_line_length': 36.648648648648646, 'alnum_prop': 0.6010324483775811, 'repo_name': 'gavazquez/LunaMultiPlayer', 'id': '8fcb7fdfb64dfb91f1784867c3f456374d3cd524', 'size': '2714', 'binary': False, 'copies': '2', 'ref': 'refs/heads/master', 'path': 'LmpClient/Systems/KerbalSys/KerbalMessageHandler.cs', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'Batchfile', 'bytes': '3648'}, {'name': 'C#', 'bytes': '2055657'}, {'name': 'CSS', 'bytes': '1100'}, {'name': 'HTML', 'bytes': '484'}, {'name': 'JavaScript', 'bytes': '1252'}, {'name': 'Smalltalk', 'bytes': '15844'}]}
import sys from conftest import rvo_output, rvo_err from click.testing import CliRunner from rvo import cli def test_add_all_parameters(isatty_true): options = ['add', '-t', 'test', '-c', 'test', '--content', 'test'] output = ['Document "test" created.'] rvo_output(options,output) def test_add_tags(isatty_true): options = ['add', '-t', 'test', '--content', 'test'] output = ['Document "test" created.'] rvo_output(options,output) def test_add_title_test(isatty_true): options = ['add', '-t', 'test', '--content', 'THIS IS A TITLE'] output = ['Document "THIS IS A TITLE" created.'] rvo_output(options,output) def test_add_title_test_gnarf(isatty_true): runner = CliRunner() result = runner.invoke(cli.cli, ['add', '-c', 'töstcät', '-x', 'gnarf']) assert not result.exception assert result.output.strip().endswith('Document "gnarf" created.') def test_add_title_test_gnarf(isatty_true): runner = CliRunner() result = runner.invoke(cli.cli, ['add', '-c', 'töstcät', '-x', 'gnarf\nfoo']) assert not result.exception assert result.output.strip().endswith('Document "gnarf" created.') def test_add_title_test_hashtag(isatty_true): options = ['add', '-t', 'test', '--content', '# THIS IS A TITLE'] output = ['Document "THIS IS A TITLE" created.'] rvo_output(options,output) def test_add_title_test_hashtag(isatty_true): options = ['add', '-t', 'test', '--content', '# THIS IS A TITLE\nmutliline'] output = ['Document "THIS IS A TITLE" created.'] rvo_output(options,output) def test_add_very_long_title(isatty_true): options = ['add', '-t', 'test', '--content', '# THIS IS A VERY VERY LONG NEVER ENDING TITLE THAT EXCEEDS LIMITS'] output = ['Document "THIS IS A VERY VERY LONG NEVER ENDING TITLE THAT E" created.'] rvo_output(options,output) def test_add_no_parameters(isatty_true): runner = CliRunner() result = runner.invoke(cli.cli, ['add']) assert result.output.strip().endswith('Document "TEST" created.') assert not result.exception def test_add_one_parameters_tag(isatty_true): runner = CliRunner() result = runner.invoke(cli.cli, ['add', '-t', 'testtag']) assert result.output.strip().endswith('Document "TEST" created.') assert not result.exception def test_add_utf8_cat(isatty_true): runner = CliRunner() result = runner.invoke(cli.cli, ['add', '-c', 'töstcät']) assert result.output.strip().endswith('Document "TEST" created.') assert not result.exception def test_add_utf8_cat_multi(isatty_true): runner = CliRunner() result = runner.invoke(cli.cli, ['add', '-c', 'tüütüü', '-c', 'töstcät']) assert result.output.strip().endswith('Document "TEST" created.') assert not result.exception def test_add_utf8_tag(isatty_true): runner = CliRunner() result = runner.invoke(cli.cli, ['add', '-t', 'töstcät']) assert result.output.strip().endswith('Document "TEST" created.') assert not result.exception def test_add_utf8_tag_multi(isatty_true): runner = CliRunner() result = runner.invoke(cli.cli, ['add', '-t', 'tüütüü', '-t', 'töstcät']) assert result.output.strip().endswith('Document "TEST" created.') assert not result.exception def test_add_encrypt_by_parameter_wrong_pw(isatty_true): runner = CliRunner() result = runner.invoke(cli.cli, ['add', '-e', '-p', 'thispasswordistotallywrong', '-t', 'encryption', '-c', 'test']) assert result.output.strip().endswith('Invalid Password') assert result.exception def test_add_encrypt_by_parameter(isatty_true): runner = CliRunner() result = runner.invoke(cli.cli, ['add', '-e', '-p', 'test123', '-t', 'encryption', '-c', 'test']) assert result.output.strip().endswith('Document "TEST" created.') assert not result.exception def test_add_encrypt_by_input(isatty_true): runner = CliRunner() result = runner.invoke(cli.cli, ['add', '-e', '-t', 'encryption', '-c', 'test'], input="test123\n") assert result.output.strip().endswith('Document "TEST" created.') assert not result.exception def test_add_encrypt_by_input_with_content(isatty_true): runner = CliRunner() result = runner.invoke(cli.cli, ['add', '-e', '-t', 'encryption', '-x', 'TEST', '-c', 'test'], input="test123\n") assert result.output.strip().endswith('Document "TEST" created.') assert not result.exception def test_add_encrypt_by_input_wrong_pw(isatty_true): runner = CliRunner() result = runner.invoke(cli.cli, ['add', '-e', '-t', 'encryption', '-c', 'test'], input="test2123\n") assert result.output.strip().endswith('Invalid Password') assert result.exception def test_add_read_from_stdin(isatty_false): runner = CliRunner() result = runner.invoke(cli.cli, ['add'], input="Schwifty\nSchwifty..lol\nMorty\n\n") assert result.output.strip().endswith('Document "Schwifty" created.') assert not result.exception def test_add_read_from_stdin_with_cat(isatty_false): runner = CliRunner() result = runner.invoke(cli.cli, ['add', '-c', 'test'], input="Schwifty\nSchwifty..lol\nMorty\n\n") assert result.output.strip().endswith('Document "Schwifty" created.') assert not result.exception def test_add_read_from_stdin_with_tag(isatty_false): runner = CliRunner() result = runner.invoke(cli.cli, ['add', '-t', 'tag'], input="Schwifty\nSchwifty..lol\nMorty\n\n") assert not result.exception assert result.output.strip().endswith('Document "Schwifty" created.') def test_add_conflicting_stdin_reading(isatty_false): runner = CliRunner() result = runner.invoke(cli.cli, ['add', '-e'], input="Schwifty\nSchwifty..lol\nMorty\n\n") assert result.exception assert result.output.strip().endswith('Invalid Password') def test_add_location_germany(isatty_true): runner = CliRunner() result = runner.invoke(cli.cli, ['add', '-l', 'Nuremberg', '-c', 'test']) assert result.output.strip().endswith('Document "TEST" created.') assert not result.exception def test_add_location_invalid(isatty_true): runner = CliRunner() result = runner.invoke(cli.cli, ['add', '-l', 'DOESNOTEXISTTOWNATLEASTIHOPE', '-c', 'test']) assert result.exception
{'content_hash': 'f3c656fac22c9e8bb6d3154d825ff145', 'timestamp': '', 'source': 'github', 'line_count': 147, 'max_line_length': 120, 'avg_line_length': 42.31972789115646, 'alnum_prop': 0.6651663719659219, 'repo_name': 'noqqe/rvo', 'id': '27e97720b7f7607b81cff91683a91c7ab63ddf6f', 'size': '6288', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'tests/test_add.py', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'Python', 'bytes': '96671'}, {'name': 'Shell', 'bytes': '724'}]}
package com.charlesbishop.webrest.util; import java.io.Serializable; import org.springframework.context.support.ClassPathXmlApplicationContext; import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder; import com.charlesbishop.webrest.dao.AppUserDAO; import com.charlesbishop.webrest.model.AppUser; /** * @author charlie * This utility class contains helper methods that can assist in the creation of an AppUser object */ public class UserCreationUtil { private final static String ROLE_USER = "USER"; private static BCryptPasswordEncoder encoder = new BCryptPasswordEncoder(); public static AppUser createUser(String username, String rawPassword){ ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext("spring.xml"); AppUser user = new AppUser(); user.setUsername(username); user.setPassword(encoder.encode(rawPassword)); user.setUserRole(ROLE_USER); AppUserDAO userDAO = context.getBean(AppUserDAO.class); Serializable id = userDAO.save(user); context.close(); try { return (id != null) ? user: null; } catch (Exception e){ return null; } } // Check if a password is valid or not public static boolean passwordIsValid(String password){ boolean validLength = (password.length() >= 8 && password.length() <= 14); boolean hasSpecial = !password.matches("[A-Za-z0-9 ]*"); boolean hasUppercase = !password.equals(password.toLowerCase()); boolean hasLowercase = !password.equals(password.toUpperCase()); return validLength & hasSpecial & hasUppercase & hasLowercase; } }
{'content_hash': '204af6d29650b4f2e1595826ea1b235e', 'timestamp': '', 'source': 'github', 'line_count': 49, 'max_line_length': 98, 'avg_line_length': 32.183673469387756, 'alnum_prop': 0.7564996829422955, 'repo_name': 'charleshb417/webrest', 'id': '1577cffa3fe00991c89ef2d990185cc0f979338b', 'size': '1577', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'src/main/java/com/charlesbishop/webrest/util/UserCreationUtil.java', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'CSS', 'bytes': '2155'}, {'name': 'HTML', 'bytes': '4177'}, {'name': 'Java', 'bytes': '55582'}, {'name': 'JavaScript', 'bytes': '22330'}]}
#import "GPAppDelegate.h" int main(int argc, char *argv[]) { @autoreleasepool { return UIApplicationMain(argc, argv, nil, NSStringFromClass([GPAppDelegate class])); } }
{'content_hash': '0638b209ea0d2dc6d4b80cac9bc7c7e3', 'timestamp': '', 'source': 'github', 'line_count': 9, 'max_line_length': 92, 'avg_line_length': 20.88888888888889, 'alnum_prop': 0.6702127659574468, 'repo_name': 'Gi-lo/AboutMe-WWDC', 'id': '5e37e4c2232e423af3bde3ea29df85af2e3ef2e7', 'size': '1545', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'Giulio Petek/Giulio Petek/Supporting Files/main.m', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'Objective-C', 'bytes': '134726'}]}
package io.aeron.samples; import io.aeron.*; import io.aeron.driver.*; import io.aeron.logbuffer.*; import org.agrona.*; import org.agrona.concurrent.*; import java.nio.ByteBuffer; import java.util.concurrent.atomic.AtomicBoolean; import java.util.concurrent.locks.LockSupport; import static org.agrona.BitUtil.CACHE_LINE_LENGTH; import static org.agrona.SystemUtil.loadPropertiesFiles; import static org.agrona.UnsafeAccess.UNSAFE; public class EmbeddedIpcThroughput { public static final int BURST_LENGTH = 1_000_000; public static final int MESSAGE_LENGTH = SampleConfiguration.MESSAGE_LENGTH; public static final int MESSAGE_COUNT_LIMIT = SampleConfiguration.FRAGMENT_COUNT_LIMIT; public static final String CHANNEL = CommonContext.IPC_CHANNEL; public static final int STREAM_ID = SampleConfiguration.STREAM_ID; public static void main(final String[] args) throws Exception { loadPropertiesFiles(args); final AtomicBoolean running = new AtomicBoolean(true); SigInt.register(() -> running.set(false)); final MediaDriver.Context ctx = new MediaDriver.Context() .threadingMode(ThreadingMode.SHARED) .sharedIdleStrategy(new NoOpIdleStrategy()); try (MediaDriver ignore = MediaDriver.launch(ctx); Aeron aeron = Aeron.connect(); Publication publication = aeron.addPublication(CHANNEL, STREAM_ID); Subscription subscription = aeron.addSubscription(CHANNEL, STREAM_ID)) { final Subscriber subscriber = new Subscriber(running, subscription); final Thread subscriberThread = new Thread(subscriber); subscriberThread.setName("subscriber"); final Thread publisherThread = new Thread(new Publisher(running, publication)); publisherThread.setName("publisher"); final Thread rateReporterThread = new Thread(new RateReporter(running, subscriber)); rateReporterThread.setName("rate-reporter"); rateReporterThread.start(); subscriberThread.start(); publisherThread.start(); subscriberThread.join(); publisherThread.join(); rateReporterThread.join(); } } public static final class RateReporter implements Runnable { private final AtomicBoolean running; private final Subscriber subscriber; public RateReporter(final AtomicBoolean running, final Subscriber subscriber) { this.running = running; this.subscriber = subscriber; } public void run() { long lastTimeStamp = System.currentTimeMillis(); long lastTotalBytes = subscriber.totalBytes(); while (running.get()) { LockSupport.parkNanos(1_000_000_000); final long newTimeStamp = System.currentTimeMillis(); final long newTotalBytes = subscriber.totalBytes(); final long duration = newTimeStamp - lastTimeStamp; final long bytesTransferred = newTotalBytes - lastTotalBytes; System.out.format( "Duration %dms - %,d messages - %,d payload bytes%n", duration, bytesTransferred / MESSAGE_LENGTH, bytesTransferred); lastTimeStamp = newTimeStamp; lastTotalBytes = newTotalBytes; } } } public static final class Publisher implements Runnable { private final AtomicBoolean running; private final Publication publication; public Publisher(final AtomicBoolean running, final Publication publication) { this.running = running; this.publication = publication; } public void run() { final Publication publication = this.publication; final ByteBuffer byteBuffer = BufferUtil.allocateDirectAligned( publication.maxMessageLength(), CACHE_LINE_LENGTH); final UnsafeBuffer buffer = new UnsafeBuffer(byteBuffer); long backPressureCount = 0; long totalMessageCount = 0; outputResults: while (running.get()) { for (int i = 0; i < BURST_LENGTH; i++) { while (publication.offer(buffer, 0, MESSAGE_LENGTH) <= 0) { ++backPressureCount; if (!running.get()) { break outputResults; } } ++totalMessageCount; } } final double backPressureRatio = backPressureCount / (double)totalMessageCount; System.out.format("Publisher back pressure ratio: %f%n", backPressureRatio); } } public static final class Subscriber implements Runnable, FragmentHandler { private static final long TOTAL_BYTES_OFFSET; static { try { TOTAL_BYTES_OFFSET = UNSAFE.objectFieldOffset(Subscriber.class.getDeclaredField("totalBytes")); } catch (final Exception ex) { throw new RuntimeException(ex); } } private final AtomicBoolean running; private final Subscription subscription; private volatile long totalBytes = 0; public Subscriber(final AtomicBoolean running, final Subscription subscription) { this.running = running; this.subscription = subscription; } public long totalBytes() { return totalBytes; } public void run() { while (!subscription.isConnected()) { Thread.yield(); } final Image image = subscription.imageAtIndex(0); long failedPolls = 0; long successfulPolls = 0; while (running.get()) { final int fragmentsRead = image.poll(this, MESSAGE_COUNT_LIMIT); if (0 == fragmentsRead) { ++failedPolls; } else { ++successfulPolls; } } final double failureRatio = failedPolls / (double)(successfulPolls + failedPolls); System.out.format("Subscriber poll failure ratio: %f%n", failureRatio); } public void onFragment(final DirectBuffer buffer, final int offset, final int length, final Header header) { UNSAFE.putOrderedLong(this, TOTAL_BYTES_OFFSET, totalBytes + length); } } }
{'content_hash': 'c7579036649a7a0f90a8c95aaeaa261d', 'timestamp': '', 'source': 'github', 'line_count': 205, 'max_line_length': 114, 'avg_line_length': 33.40487804878049, 'alnum_prop': 0.5867406542056075, 'repo_name': 'galderz/Aeron', 'id': 'e6115c3fc747af9ffe07efd3185e1fe055665939', 'size': '7447', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'aeron-samples/src/main/java/io/aeron/samples/EmbeddedIpcThroughput.java', 'mode': '33188', 'license': 'apache-2.0', 'language': [{'name': 'Batchfile', 'bytes': '28890'}, {'name': 'C', 'bytes': '955025'}, {'name': 'C++', 'bytes': '1444914'}, {'name': 'CMake', 'bytes': '41954'}, {'name': 'Java', 'bytes': '3802252'}, {'name': 'Shell', 'bytes': '35251'}]}
package io.fabric8.activemq.facade; import org.apache.activemq.command.ActiveMQDestination; import java.util.Collection; /** * A facade for either a local in JVM broker or a remote broker over JMX * * * */ public interface BrokerFacade { /** * @return a unique id for this resource, typically a JMX ObjectName * @throws Exception */ String getId() throws Exception; /** * Returns all the available brokers. * * @return not <code>null</code> * @throws Exception */ public BrokerFacade[] getBrokers() throws Exception; /** * The name of the active broker (f.e. 'localhost' or 'my broker'). * * @return not <code>null</code> * @throws Exception */ String getBrokerName() throws Exception; /** * Admin view of the broker. * * @return not <code>null</code> * @throws Exception */ BrokerViewFacade getBrokerAdmin() throws Exception; /** * All queues known to the broker. * * @return not <code>null</code> * @throws Exception */ Collection<QueueViewFacade> getQueues() throws Exception; /** * All topics known to the broker. * * @return not <code>null</code> * @throws Exception */ Collection<TopicViewFacade> getTopics() throws Exception; /** * All active consumers of a queue. * * @param queueName * the name of the queue, not <code>null</code> * @return not <code>null</code> * @throws Exception */ Collection<SubscriptionViewFacade> getQueueConsumers(String queueName) throws Exception; /** * Returns the consumers available on the given topic */ Collection<SubscriptionViewFacade> getTopicConsumers(String topicName) throws Exception; /** * Returns the durable consumers available on the given topic */ Collection<DurableSubscriptionViewFacade> getTopicDurableConsumers(String topicName) throws Exception; /** * Returns the producers available on the given queue */ Collection<ProducerViewFacade> getQueueProducers(String queueName) throws Exception; /** * Returns the producers available on the given topic */ Collection<ProducerViewFacade> getTopicProducers(String topicName) throws Exception; /** * Active durable subscribers to topics of the broker. * * @return not <code>null</code> * @throws Exception */ Collection<DurableSubscriptionViewFacade> getDurableTopicSubscribers() throws Exception; /** * Inactive durable subscribers to topics of the broker. * * @return not <code>null</code> * @throws Exception */ Collection<DurableSubscriptionViewFacade> getInactiveDurableTopicSubscribers() throws Exception; /** * The names of all transport connectors of the broker (f.e. openwire, ssl) * * @return not <code>null</code> * @throws Exception */ Collection<String> getConnectors() throws Exception; /** * A transport connectors. * * @param name * name of the connector (f.e. openwire) * @return <code>null</code> if not found * @throws Exception */ ConnectorViewFacade getConnector(String name) throws Exception; /** * All connections to all transport connectors of the broker. * * @return not <code>null</code> * @throws Exception */ Collection<ConnectionViewFacade> getConnections() throws Exception; /** * The names of all connections to a specific transport connectors of the * broker. * * @see #getConnection(String) * @param connectorName * not <code>null</code> * @return not <code>null</code> * @throws Exception */ Collection<String> getConnections(String connectorName) throws Exception; /** * A specific connection to the broker. * * @param connectionName * the name of the connection, not <code>null</code> * @return not <code>null</code> * @throws Exception */ ConnectionViewFacade getConnection(String connectionName) throws Exception; /** * Returns all consumers of a connection. * * @param connectionName * the name of the connection, not <code>null</code> * @return not <code>null</code> * @throws Exception */ Collection<SubscriptionViewFacade> getConsumersOnConnection( String connectionName) throws Exception; /** * The brokers network connectors. * * @return not <code>null</code> * @throws Exception */ Collection<NetworkConnectorViewFacade> getNetworkConnectors() throws Exception; /** * The brokers network bridges. * * @return not <code>null</code> * @throws Exception */ Collection<NetworkBridgeViewFacade> getNetworkBridges() throws Exception; /** * Purges the given destination * * @param destination * @throws Exception */ void purgeQueue(ActiveMQDestination destination) throws Exception; /** * Get the view of the queue with the specified name. * * @param name * not <code>null</code> * @return <code>null</code> if no queue with this name exists * @throws Exception */ QueueViewFacade getQueue(String name) throws Exception; /** * Get the view of the topic with the specified name. * * @param name * not <code>null</code> * @return <code>null</code> if no topic with this name exists * @throws Exception */ TopicViewFacade getTopic(String name) throws Exception; /** * Get the JobScheduler MBean * @return the jobScheduler or null if not configured * @throws Exception */ JobSchedulerViewFacade getJobScheduler() throws Exception; /** * Get the JobScheduler MBean * @return the jobScheduler or null if not configured * @throws Exception */ Collection<JobFacade> getScheduledJobs() throws Exception; boolean isJobSchedulerStarted(); }
{'content_hash': '721459e845a5da7add68a4a701a66ffa', 'timestamp': '', 'source': 'github', 'line_count': 231, 'max_line_length': 106, 'avg_line_length': 24.874458874458874, 'alnum_prop': 0.6801253045596937, 'repo_name': 'alexeev/jboss-fuse-mirror', 'id': 'a2ecf4d144d92f3c59a9453b2d7247ad73d2fba7', 'size': '6377', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'tooling/tooling-activemq-facade/src/main/java/io/fabric8/activemq/facade/BrokerFacade.java', 'mode': '33188', 'license': 'apache-2.0', 'language': [{'name': 'CSS', 'bytes': '313969'}, {'name': 'CoffeeScript', 'bytes': '278706'}, {'name': 'Java', 'bytes': '8498768'}, {'name': 'JavaScript', 'bytes': '2483260'}, {'name': 'Kotlin', 'bytes': '14282'}, {'name': 'Scala', 'bytes': '484151'}, {'name': 'Shell', 'bytes': '11547'}, {'name': 'XSLT', 'bytes': '26098'}]}
<!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.11"/> <title>Arch Game Engine: Class Members - Functions</title> <link href="tabs.css" rel="stylesheet" type="text/css"/> <script type="text/javascript" src="jquery.js"></script> <script type="text/javascript" src="dynsections.js"></script> <link href="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/javascript"> $(document).ready(function() { init_search(); }); </script> <link href="doxygen.css" rel="stylesheet" type="text/css" /> </head> <body> <div id="top"><!-- do not remove this div, it is closed by doxygen! --> <div id="titlearea"> <table cellspacing="0" cellpadding="0"> <tbody> <tr style="height: 56px;"> <td id="projectalign" style="padding-left: 0.5em;"> <div id="projectname">Arch Game Engine &#160;<span id="projectnumber">0.2</span> </div> </td> </tr> </tbody> </table> </div> <!-- end header part --> <!-- Generated by Doxygen 1.8.11 --> <script type="text/javascript"> var searchBox = new SearchBox("searchBox", "search",false,'Search'); </script> <div id="navrow1" class="tabs"> <ul class="tablist"> <li><a href="index.html"><span>Main&#160;Page</span></a></li> <li class="current"><a href="annotated.html"><span>Classes</span></a></li> <li><a href="files.html"><span>Files</span></a></li> <li> <div id="MSearchBox" class="MSearchBoxInactive"> <span class="left"> <img id="MSearchSelect" src="search/mag_sel.png" onmouseover="return searchBox.OnSearchSelectShow()" onmouseout="return searchBox.OnSearchSelectHide()" alt=""/> <input type="text" id="MSearchField" value="Search" accesskey="S" onfocus="searchBox.OnSearchFieldFocus(true)" onblur="searchBox.OnSearchFieldFocus(false)" onkeyup="searchBox.OnSearchFieldChange(event)"/> </span><span class="right"> <a id="MSearchClose" href="javascript:searchBox.CloseResultsWindow()"><img id="MSearchCloseImg" border="0" src="search/close.png" alt=""/></a> </span> </div> </li> </ul> </div> <div id="navrow2" class="tabs2"> <ul class="tablist"> <li><a href="annotated.html"><span>Class&#160;List</span></a></li> <li><a href="classes.html"><span>Class&#160;Index</span></a></li> <li><a href="inherits.html"><span>Class&#160;Hierarchy</span></a></li> <li class="current"><a href="functions.html"><span>Class&#160;Members</span></a></li> </ul> </div> <div id="navrow3" class="tabs2"> <ul class="tablist"> <li><a href="functions.html"><span>All</span></a></li> <li class="current"><a href="functions_func.html"><span>Functions</span></a></li> <li><a href="functions_vars.html"><span>Variables</span></a></li> </ul> </div> <div id="navrow4" class="tabs3"> <ul class="tablist"> <li><a href="functions_func.html#index_a"><span>a</span></a></li> <li><a href="functions_func_b.html#index_b"><span>b</span></a></li> <li><a href="functions_func_c.html#index_c"><span>c</span></a></li> <li><a href="functions_func_d.html#index_d"><span>d</span></a></li> <li><a href="functions_func_f.html#index_f"><span>f</span></a></li> <li><a href="functions_func_g.html#index_g"><span>g</span></a></li> <li><a href="functions_func_h.html#index_h"><span>h</span></a></li> <li><a href="functions_func_i.html#index_i"><span>i</span></a></li> <li><a href="functions_func_k.html#index_k"><span>k</span></a></li> <li><a href="functions_func_l.html#index_l"><span>l</span></a></li> <li class="current"><a href="functions_func_m.html#index_m"><span>m</span></a></li> <li><a href="functions_func_o.html#index_o"><span>o</span></a></li> <li><a href="functions_func_r.html#index_r"><span>r</span></a></li> <li><a href="functions_func_s.html#index_s"><span>s</span></a></li> <li><a href="functions_func_u.html#index_u"><span>u</span></a></li> <li><a href="functions_func_0x7e.html#index_0x7e"><span>~</span></a></li> </ul> </div> </div><!-- top --> <!-- 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 class="contents"> &#160; <h3><a class="anchor" id="index_m"></a>- m -</h3><ul> <li>move() : <a class="el" href="classLevel.html#a9184b25173fbf468a63a633bd3510bd6">Level</a> , <a class="el" href="classObject.html#af4133db64f4051294dc103a2f3553a6a">Object</a> </li> <li>moveTowards() : <a class="el" href="classPhysics.html#a8e53f9bf088c0d4f208b3c2029d69ab2">Physics</a> </li> <li>moveX() : <a class="el" href="classObject.html#a43f3220cb27a282c28afaea57ac9a098">Object</a> </li> <li>moveY() : <a class="el" href="classObject.html#a58bab6e78efd8282996d742530c98034">Object</a> </li> </ul> </div><!-- contents --> <!-- start footer part --> <hr class="footer"/><address class="footer"><small> Generated by &#160;<a href="http://www.doxygen.org/index.html"> <img class="footer" src="doxygen.png" alt="doxygen"/> </a> 1.8.11 </small></address> </body> </html>
{'content_hash': '6d609a8ae85150b0d0ec24c54e903aa2', 'timestamp': '', 'source': 'github', 'line_count': 138, 'max_line_length': 154, 'avg_line_length': 42.78260869565217, 'alnum_prop': 0.6321138211382114, 'repo_name': 'jarreed0/ArchGE', 'id': 'de8855bacfd51d6ab2de6ce2b10b6c15f14e1de5', 'size': '5904', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'docs/html/functions_func_m.html', 'mode': '33188', 'license': 'apache-2.0', 'language': [{'name': 'C++', 'bytes': '232681'}, {'name': 'Shell', 'bytes': '10667'}]}
using System; public interface IExecutionScope : IDisposable #if NATIVE_ASYNC , IAsyncDisposable #endif { }
{'content_hash': 'dba4eb24c8b66c72fb0856faf979ff42', 'timestamp': '', 'source': 'github', 'line_count': 8, 'max_line_length': 46, 'avg_line_length': 13.875, 'alnum_prop': 0.7747747747747747, 'repo_name': 'linq2db/linq2db', 'id': '8fe6042321283fe54eb99b53ef62ef9ba0ca4fb8', 'size': '113', 'binary': False, 'copies': '2', 'ref': 'refs/heads/master', 'path': 'Source/LinqToDB/DataProvider/IExecutionScope.cs', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'Batchfile', 'bytes': '29203'}, {'name': 'C#', 'bytes': '18569855'}, {'name': 'F#', 'bytes': '15865'}, {'name': 'PLSQL', 'bytes': '29278'}, {'name': 'PLpgSQL', 'bytes': '15809'}, {'name': 'PowerShell', 'bytes': '5130'}, {'name': 'SQLPL', 'bytes': '10530'}, {'name': 'Shell', 'bytes': '29373'}, {'name': 'Smalltalk', 'bytes': '11'}, {'name': 'TSQL', 'bytes': '104099'}, {'name': 'Visual Basic .NET', 'bytes': '3871'}]}
using System; using System.Collections.Generic; using System.ComponentModel.Design; using Cirrious.MvvmCross.Plugins.Email; using Cirrious.MvvmCross.Plugins.WebBrowser; using codestuffers.MvvmCross.Plugins.FeedbackDialog.OpenCriteria; using codestuffers.MvvmCross.Plugins.UserInteraction; using FluentAssertions; using Moq; using NUnit.Framework; namespace codestuffers.MvvmCross.Plugins.FeedbackDialog.Tests { [TestFixture] public class MvxFeedbackDialogTests { private Mock<IMvxUserInteraction> _userInteraction; private Mock<IFeedbackDataService> _dataService; private Mock<IMvxComposeEmailTask> _emailTask; private Mock<IMvxWebBrowserTask> _webBrowser; private Mock<FeedbackData> _data; private FeedbackDialogConfiguration _configuration; private List<IOpenDialogCriteria> _criteria; private MvxFeedbackDialog _testObject; [SetUp] public void Setup() { _criteria = new List<IOpenDialogCriteria>(); _data = new Mock<FeedbackData>(); _data.SetupProperty(x => x.DialogWasShown); _userInteraction = new Mock<IMvxUserInteraction>(); _dataService = new Mock<IFeedbackDataService>(); _dataService.Setup(x => x.GetData()).Returns(() => _data.Object); _emailTask = new Mock<IMvxComposeEmailTask>(); _webBrowser = new Mock<IMvxWebBrowserTask>(); _configuration = new FeedbackDialogConfiguration {OpenCriteria = _criteria}; _testObject = new MvxFeedbackDialog(_userInteraction.Object, _dataService.Object, _emailTask.Object, _webBrowser.Object); _testObject.SetConfiguration(_configuration); } [Test] public void RecordAppStart_ShouldNotRecordAppStart_WhenDialogHasAlreadyBeenOpened() { _data.Setup(x => x.DialogWasShown).Returns(true); _testObject.RecordAppStart(); _data.Verify(x => x.AppHasOpened(), Times.Never()); } [Test] public void RecordAppStart_ShouldRecordAppStart_WhenDialogHasNotBeenOpened() { _data.Setup(x => x.DialogWasShown).Returns(false); _testObject.RecordAppStart(); _data.Verify(x => x.AppHasOpened(), Times.Once()); } [Test] public void RecordAppStart_ShouldMarkDialogAsOpened_WhenAllCriteriaIsTrue() { var criteria1 = new Mock<IOpenDialogCriteria>(); criteria1.Setup(x => x.ShouldOpen(It.IsAny<FeedbackData>())).Returns(true); var criteria2 = new Mock<IOpenDialogCriteria>(); criteria2.Setup(x => x.ShouldOpen(It.IsAny<FeedbackData>())).Returns(true); _criteria.Add(criteria1.Object); _criteria.Add(criteria2.Object); _data.SetupSet(x => x.DialogWasShown = true); _testObject.RecordAppStart(); _data.VerifySet(x => x.DialogWasShown = true); } [TestCase(false, true)] [TestCase(true, false)] [TestCase(false, false)] public void RecordAppStart_ShouldNotMarkDialogAsOpened_WhenAnyCriteriaIsFalse(bool crit1, bool crit2) { var criteria1 = new Mock<IOpenDialogCriteria>(); criteria1.Setup(x => x.ShouldOpen(It.IsAny<FeedbackData>())).Returns(crit1); var criteria2 = new Mock<IOpenDialogCriteria>(); criteria2.Setup(x => x.ShouldOpen(It.IsAny<FeedbackData>())).Returns(crit2); _criteria.Add(criteria1.Object); _criteria.Add(criteria2.Object); _data.SetupSet(x => x.DialogWasShown = false); _testObject.RecordAppStart(); _data.VerifySet(x => x.DialogWasShown = false); } [Test] public void RecordAppStart_ShouldNotMarkDialogAsOpened_WhenThereAreNoCriteria() { _data.SetupProperty(x => x.DialogWasShown, false); _testObject.RecordAppStart(); _data.Object.DialogWasShown.Should().BeFalse(); } [Test] public void RecordAppStart_ShouldSaveData_WhenDialogHasNotBeenOpened() { _data.Setup(x => x.DialogWasShown).Returns(false); _testObject.RecordAppStart(); _dataService.Verify(x => x.SaveData(_data.Object), Times.Once()); } [Test] public void RecordAppStart_ShouldOpenDialog_WhenAllCriteriaIsTrue() { var criteria1 = new Mock<IOpenDialogCriteria>(); criteria1.Setup(x => x.ShouldOpen(It.IsAny<FeedbackData>())).Returns(true); _criteria.Add(criteria1.Object); _testObject.RecordAppStart(); _userInteraction.Verify(x => x.ShowDialog(It.IsAny<string>(), It.IsAny<string>(), It.IsAny<string>(), It.IsAny<string>(), It.IsAny<Action>(), It.IsAny<Action>())); } } }
{'content_hash': '02e350f8aaf8f3dc50af6531bac879ca', 'timestamp': '', 'source': 'github', 'line_count': 123, 'max_line_length': 175, 'avg_line_length': 39.8780487804878, 'alnum_prop': 0.6332313965341488, 'repo_name': 'codestuffers/MvvmCrossPlugins', 'id': '5f6368e674642a4bf1562e9743ab9f29696b71a6', 'size': '4907', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'src/FeedbackDialog/Tests/codestuffers.MvvmCross.Plugins.FeedbackDialog.Tests/MvxFeedbackDialogTests.cs', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'C#', 'bytes': '124864'}, {'name': 'PowerShell', 'bytes': '203'}, {'name': 'Puppet', 'bytes': '906'}]}
/* * cs170 -- Rich wolski * producer-consumer example using kthreads * uses condition variables for full/empty conditions * uses condition variable to fulfill order * uses separate lock for each stock */ #include <unistd.h> #include <stdlib.h> #include <stdio.h> #include <string.h> #include "c-timer.h" #include "kt.h" #define RAND() (drand48()) struct order { int stock_id; int quantity; int action; /* buy or sell */ kt_sem fulfilled; }; struct order_que { struct order **orders; int size; int head; int tail; kt_sem full; kt_sem empty; }; struct stock { int quantity; }; struct market { struct stock *stocks; int count; }; struct order *InitOrder(int id, int quantity, int action) { struct order *order; order = (struct order *)malloc(sizeof(struct order)); if(order == NULL) { return(NULL); } order->stock_id = id; order->quantity = quantity; order->action = action; order->fulfilled = make_kt_sem(0); return(order); } void FreeOrder(struct order *order) { kill_kt_sem(order->fulfilled); free(order); } struct order_que *InitOrderQue(int size) { struct order_que *oq; oq = (struct order_que *)malloc(sizeof(struct order_que)); if(oq == NULL) { return(NULL); } memset(oq,0,sizeof(struct order_que)); oq->size = size+1; /* empty condition burns a slot */ oq->orders = (struct order **)malloc(size*sizeof(struct order *)); if(oq->orders == NULL) { free(oq); return(NULL); } memset(oq->orders,0,size*sizeof(struct order *)); oq->full = make_kt_sem(size); oq->empty = make_kt_sem(0); return(oq); } void FreeOrderQue(struct order_que *oq) { while(oq->head != oq->tail) { FreeOrder(oq->orders[oq->tail]); oq->tail = (oq->tail + 1) % oq->size; } kill_kt_sem(oq->full); kill_kt_sem(oq->empty); free(oq->orders); free(oq); return; } struct market *InitMarket(int stock_count, int init_quantity) { struct market *m; int i; m = (struct market *)malloc(sizeof(struct market)); if(m == NULL) { return(NULL); } m->count = stock_count; m->stocks = (struct stock *)malloc(stock_count*sizeof(struct stock)); if(m->stocks == NULL) { free(m); return(NULL); } for(i=0; i < stock_count; i++) { m->stocks[i].quantity = init_quantity; } return(m); } void FreeMarket(struct market *m) { free(m->stocks); free(m); return; } void PrintMarket(struct market *m) { int i; for(i=0; i < m->count; i++) { printf("stock: %d, quantity: %d\n", i,m->stocks[i].quantity); } return; } struct client_arg { int id; int order_count; struct order_que *order_que; int max_stock_id; int max_quantity; int verbose; }; struct trader_arg { int id; struct order_que *order_que; struct market *market; int *done; int verbose; }; void ClientThread(void *arg) { struct client_arg *ca = (struct client_arg *)arg; int i; int next; struct order *order; int stock_id; int quantity; int action; int queued; double now; for(i=0; i < ca->order_count; i++) { /* * create an order for a random stock */ stock_id = (int)(RAND() * ca->max_stock_id); quantity = (int)(RAND() * ca->max_quantity); if(RAND() > 0.5) { action = 0; /* 0 => buy */ } else { action = 1; /* 1 => sell */ } order = InitOrder(stock_id,quantity,action); if(order == NULL) { fprintf(stderr,"no space for order\n"); exit(1); } /* * queue it for the traders */ P_kt_sem(ca->order_que->full); next = (ca->order_que->head + 1) % ca->order_que->size; /* * there is space in the queue, add the order and bump * the head */ if(ca->verbose == 1) { now = CTimer(); printf("%10.0f client %d: ",now,ca->id); printf("queued stock %d, for %d, %s\n", order->stock_id, order->quantity, (order->action ? "SELL" : "BUY")); } ca->order_que->orders[next] = order; ca->order_que->head = next; /* * signal traders that there is another order */ V_kt_sem(ca->order_que->empty); /* * wait until the order is fulfilled */ P_kt_sem(order->fulfilled); /* * done, free the order and repeat */ FreeOrder(order); } return; } void TraderThread(void *arg) { struct trader_arg *ta = (struct trader_arg *)arg; int dequeued; struct order *order; int tail; double now; int next; struct stock *stock; while(1) { /* * wait until there is a new order */ P_kt_sem(ta->order_que->empty); /* * are we done? Tell the next trader and exit */ if(*(ta->done) == 1) { V_kt_sem(ta->order_que->empty); kt_exit(); } /* * get the next order */ next = (ta->order_que->tail + 1) % ta->order_que->size; order = ta->order_que->orders[next]; ta->order_que->tail = next; /* * tell the clients there is another free slot */ V_kt_sem(ta->order_que->full); /* * have an order to process */ stock = &(ta->market->stocks[order->stock_id]); if(order->action == 1) { /* BUY */ stock->quantity -= order->quantity; if(stock->quantity < 0) { stock->quantity = 0; } } else { stock->quantity += order->quantity; } if(ta->verbose == 1) { now = CTimer(); printf("%10.0f trader: %d ",now,ta->id); printf("fulfilled stock %d for %d\n", order->stock_id, order->quantity); } /* * tell the client the order is done */ V_kt_sem(order->fulfilled); } return; } #define ARGS "c:t:o:q:s:V" char *Usage = "market1 -c clients -t traders -o orders -q queue-size -s stock-count -V <verbose on>\n"; #define INIT_COUNT 5000 int main(int argc, char **argv) { int c; int client_threads; int trader_threads; int orders_per_client; int que_size; int max_stock; int verbose; struct client_arg *ca; struct trader_arg *ta; void **client_ids; void **trader_ids; struct order_que *order_que; struct market *market; int i; int done; int err; double start; double end; /* * defaults */ client_threads = 1; trader_threads = 1; orders_per_client = 1; verbose = 0; que_size = 1; max_stock = 1; while((c = getopt(argc,argv,ARGS)) != EOF) { switch(c) { case 'c': client_threads = atoi(optarg); break; case 't': trader_threads = atoi(optarg); break; case 'o': orders_per_client = atoi(optarg); break; case 'q': que_size = atoi(optarg); break; case 's': max_stock = atoi(optarg); break; case 'V': verbose = 1; break; default: fprintf(stderr, "unrecognized command %c\n", (char)c); fprintf(stderr,"usage: %s",Usage); exit(1); } } client_ids = (void **)malloc(client_threads*sizeof(void *)); if(client_ids == NULL) { exit(1); } ca = (struct client_arg *)malloc(client_threads*sizeof(struct client_arg)); if(ca == NULL) { exit(1); } trader_ids = (void **)malloc(trader_threads*sizeof(void *)); if(trader_ids == NULL) { exit(1); } ta = (struct trader_arg *)malloc(trader_threads*sizeof(struct trader_arg)); if(ta == NULL) { exit(1); } order_que = InitOrderQue(que_size); if(order_que == NULL) { exit(1); } market = InitMarket(max_stock,INIT_COUNT); if(market == NULL) { exit(1); } start = CTimer(); for(i=0; i < client_threads; i++) { ca[i].id = i; ca[i].order_count = orders_per_client; ca[i].max_stock_id = max_stock; ca[i].max_quantity = INIT_COUNT; ca[i].order_que = order_que; ca[i].verbose = verbose; client_ids[i] = kt_fork(ClientThread,(void *)&ca[i]); if(client_ids[i] == NULL) { fprintf(stderr,"client thread create %d failed\n",i); exit(1); } } done = 0; for(i=0; i < trader_threads; i++) { ta[i].id = i; ta[i].order_que = order_que; ta[i].market = market; ta[i].done = &done; ta[i].verbose = verbose; trader_ids[i] = kt_fork(TraderThread,(void *)&ta[i]); if(trader_ids[i] == NULL) { fprintf(stderr,"trader thread create %d failed\n",i); exit(1); } } /* * wait for the clients to finish */ for(i=0; i < client_threads; i++) { kt_join(client_ids[i]); } /* * tell the traders we are done */ done = 1; V_kt_sem(order_que->empty); for(i=0; i < trader_threads; i++) { kt_join(trader_ids[i]); } end = CTimer(); if(verbose == 1) { PrintMarket(market); } printf("%f transactions / sec\n", (double)(orders_per_client*client_threads) / (end-start)); free(ca); free(ta); free(client_ids); free(trader_ids); FreeMarket(market); FreeOrderQue(order_que); return(0); }
{'content_hash': 'abcc4e4038574450a3e9091fa1b259aa', 'timestamp': '', 'source': 'github', 'line_count': 465, 'max_line_length': 103, 'avg_line_length': 17.974193548387095, 'alnum_prop': 0.6057669298875329, 'repo_name': 'SeraphRoy/SeraphRoy.github.io', 'id': '8a8573a8be750ca694d05a0824a8b9b82f9f346f', 'size': '8358', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'assets/market-kthreads.c', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'C', 'bytes': '96402'}, {'name': 'HTML', 'bytes': '36'}, {'name': 'Ruby', 'bytes': '8813'}]}
package client const ( StatefulSetSpecType = "statefulSetSpec" StatefulSetSpecFieldActiveDeadlineSeconds = "activeDeadlineSeconds" StatefulSetSpecFieldAutomountServiceAccountToken = "automountServiceAccountToken" StatefulSetSpecFieldContainers = "containers" StatefulSetSpecFieldDNSConfig = "dnsConfig" StatefulSetSpecFieldDNSPolicy = "dnsPolicy" StatefulSetSpecFieldEnableServiceLinks = "enableServiceLinks" StatefulSetSpecFieldEphemeralContainers = "ephemeralContainers" StatefulSetSpecFieldFSGroupChangePolicy = "fsGroupChangePolicy" StatefulSetSpecFieldFsgid = "fsgid" StatefulSetSpecFieldGids = "gids" StatefulSetSpecFieldHostAliases = "hostAliases" StatefulSetSpecFieldHostIPC = "hostIPC" StatefulSetSpecFieldHostNetwork = "hostNetwork" StatefulSetSpecFieldHostPID = "hostPID" StatefulSetSpecFieldHostname = "hostname" StatefulSetSpecFieldImagePullSecrets = "imagePullSecrets" StatefulSetSpecFieldNodeID = "nodeId" StatefulSetSpecFieldObjectMeta = "metadata" StatefulSetSpecFieldOverhead = "overhead" StatefulSetSpecFieldPreemptionPolicy = "preemptionPolicy" StatefulSetSpecFieldReadinessGates = "readinessGates" StatefulSetSpecFieldRestartPolicy = "restartPolicy" StatefulSetSpecFieldRunAsGroup = "runAsGroup" StatefulSetSpecFieldRunAsNonRoot = "runAsNonRoot" StatefulSetSpecFieldRuntimeClassName = "runtimeClassName" StatefulSetSpecFieldScale = "scale" StatefulSetSpecFieldScheduling = "scheduling" StatefulSetSpecFieldSeccompProfile = "seccompProfile" StatefulSetSpecFieldSelector = "selector" StatefulSetSpecFieldServiceAccountName = "serviceAccountName" StatefulSetSpecFieldSetHostnameAsFQDN = "setHostnameAsFQDN" StatefulSetSpecFieldShareProcessNamespace = "shareProcessNamespace" StatefulSetSpecFieldStatefulSetConfig = "statefulSetConfig" StatefulSetSpecFieldSubdomain = "subdomain" StatefulSetSpecFieldSysctls = "sysctls" StatefulSetSpecFieldTerminationGracePeriodSeconds = "terminationGracePeriodSeconds" StatefulSetSpecFieldTopologySpreadConstraints = "topologySpreadConstraints" StatefulSetSpecFieldUid = "uid" StatefulSetSpecFieldVolumes = "volumes" StatefulSetSpecFieldWindowsOptions = "windowsOptions" ) type StatefulSetSpec struct { ActiveDeadlineSeconds *int64 `json:"activeDeadlineSeconds,omitempty" yaml:"activeDeadlineSeconds,omitempty"` AutomountServiceAccountToken *bool `json:"automountServiceAccountToken,omitempty" yaml:"automountServiceAccountToken,omitempty"` Containers []Container `json:"containers,omitempty" yaml:"containers,omitempty"` DNSConfig *PodDNSConfig `json:"dnsConfig,omitempty" yaml:"dnsConfig,omitempty"` DNSPolicy string `json:"dnsPolicy,omitempty" yaml:"dnsPolicy,omitempty"` EnableServiceLinks *bool `json:"enableServiceLinks,omitempty" yaml:"enableServiceLinks,omitempty"` EphemeralContainers []EphemeralContainer `json:"ephemeralContainers,omitempty" yaml:"ephemeralContainers,omitempty"` FSGroupChangePolicy string `json:"fsGroupChangePolicy,omitempty" yaml:"fsGroupChangePolicy,omitempty"` Fsgid *int64 `json:"fsgid,omitempty" yaml:"fsgid,omitempty"` Gids []int64 `json:"gids,omitempty" yaml:"gids,omitempty"` HostAliases []HostAlias `json:"hostAliases,omitempty" yaml:"hostAliases,omitempty"` HostIPC bool `json:"hostIPC,omitempty" yaml:"hostIPC,omitempty"` HostNetwork bool `json:"hostNetwork,omitempty" yaml:"hostNetwork,omitempty"` HostPID bool `json:"hostPID,omitempty" yaml:"hostPID,omitempty"` Hostname string `json:"hostname,omitempty" yaml:"hostname,omitempty"` ImagePullSecrets []LocalObjectReference `json:"imagePullSecrets,omitempty" yaml:"imagePullSecrets,omitempty"` NodeID string `json:"nodeId,omitempty" yaml:"nodeId,omitempty"` ObjectMeta *ObjectMeta `json:"metadata,omitempty" yaml:"metadata,omitempty"` Overhead map[string]string `json:"overhead,omitempty" yaml:"overhead,omitempty"` PreemptionPolicy string `json:"preemptionPolicy,omitempty" yaml:"preemptionPolicy,omitempty"` ReadinessGates []PodReadinessGate `json:"readinessGates,omitempty" yaml:"readinessGates,omitempty"` RestartPolicy string `json:"restartPolicy,omitempty" yaml:"restartPolicy,omitempty"` RunAsGroup *int64 `json:"runAsGroup,omitempty" yaml:"runAsGroup,omitempty"` RunAsNonRoot *bool `json:"runAsNonRoot,omitempty" yaml:"runAsNonRoot,omitempty"` RuntimeClassName string `json:"runtimeClassName,omitempty" yaml:"runtimeClassName,omitempty"` Scale *int64 `json:"scale,omitempty" yaml:"scale,omitempty"` Scheduling *Scheduling `json:"scheduling,omitempty" yaml:"scheduling,omitempty"` SeccompProfile *SeccompProfile `json:"seccompProfile,omitempty" yaml:"seccompProfile,omitempty"` Selector *LabelSelector `json:"selector,omitempty" yaml:"selector,omitempty"` ServiceAccountName string `json:"serviceAccountName,omitempty" yaml:"serviceAccountName,omitempty"` SetHostnameAsFQDN *bool `json:"setHostnameAsFQDN,omitempty" yaml:"setHostnameAsFQDN,omitempty"` ShareProcessNamespace *bool `json:"shareProcessNamespace,omitempty" yaml:"shareProcessNamespace,omitempty"` StatefulSetConfig *StatefulSetConfig `json:"statefulSetConfig,omitempty" yaml:"statefulSetConfig,omitempty"` Subdomain string `json:"subdomain,omitempty" yaml:"subdomain,omitempty"` Sysctls []Sysctl `json:"sysctls,omitempty" yaml:"sysctls,omitempty"` TerminationGracePeriodSeconds *int64 `json:"terminationGracePeriodSeconds,omitempty" yaml:"terminationGracePeriodSeconds,omitempty"` TopologySpreadConstraints []TopologySpreadConstraint `json:"topologySpreadConstraints,omitempty" yaml:"topologySpreadConstraints,omitempty"` Uid *int64 `json:"uid,omitempty" yaml:"uid,omitempty"` Volumes []Volume `json:"volumes,omitempty" yaml:"volumes,omitempty"` WindowsOptions *WindowsSecurityContextOptions `json:"windowsOptions,omitempty" yaml:"windowsOptions,omitempty"` }
{'content_hash': '2c8148bdf5839f1bfa3f8340ae67bd26', 'timestamp': '', 'source': 'github', 'line_count': 88, 'max_line_length': 157, 'avg_line_length': 89.73863636363636, 'alnum_prop': 0.609725212105863, 'repo_name': 'rancherio/rancher', 'id': 'f6c34d4ef8c3521031a7be0be14f8c275599d81f', 'size': '7897', 'binary': False, 'copies': '2', 'ref': 'refs/heads/master', 'path': 'pkg/client/generated/project/v3/zz_generated_stateful_set_spec.go', 'mode': '33188', 'license': 'apache-2.0', 'language': [{'name': 'Python', 'bytes': '6795'}, {'name': 'Shell', 'bytes': '25328'}]}
$LOAD_PATH.unshift './lib' require 'tilia/dav' require 'rack' Time.zone = 'Berlin' testserver_root = File.join(File.dirname(__FILE__), 'testserver_root') Dir.mkdir(testserver_root) unless File.exist?(testserver_root) fail "could not create root directory #{testserver_root}" unless File.directory?(testserver_root) app = proc do |env| root = Tilia::Dav::Fs::Directory.new(testserver_root) server = Tilia::Dav::Server.new(env, [root]) server.add_plugin(Tilia::Dav::Browser::Plugin.new) server.exec end Rack::Handler::WEBrick.run app
{'content_hash': 'cc738eb13c043629a7de5cdba34238a4', 'timestamp': '', 'source': 'github', 'line_count': 22, 'max_line_length': 97, 'avg_line_length': 24.90909090909091, 'alnum_prop': 0.7226277372262774, 'repo_name': 'tilia/tilia-dav', 'id': '5777ca23fc049c5001c704b5f1a705f423fa19ca', 'size': '627', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'examples/minimal.rb', 'mode': '33261', 'license': 'bsd-3-clause', 'language': [{'name': 'CSS', 'bytes': '17084'}, {'name': 'Ruby', 'bytes': '1797621'}]}
using System; using System.Collections.Generic; using System.Linq; using System.Web; using iTextSharp.text; using iTextSharp.text.pdf; using SysAgropec.Class; using SysAgropec.Models; namespace SysAgropec.Class { public class Relatorio : RelatorioHelper { public override void MontaCorpoDados() { base.MontaCorpoDados(); PdfPTable table = new PdfPTable(5); BaseColor preto = new BaseColor(0, 0, 0); BaseColor fundo = new BaseColor(200, 200, 200); Font font = FontFactory.GetFont("Verdana", 8, Font.NORMAL, preto); Font titulo = FontFactory.GetFont("Verdana", 8, Font.BOLD, preto); float[] colsW = { 10, 10, 10, 10, 10 }; table.SetWidths(colsW); table.HeaderRows = 1; table.WidthPercentage = 100f; table.DefaultCell.Border = PdfPCell.BOTTOM_BORDER; table.DefaultCell.BorderColor = preto; table.DefaultCell.BorderColorBottom = new BaseColor(255, 255, 255); table.DefaultCell.Padding = 10; if (TipoRelatorio == 0) { table.AddCell(getNewCell("Animal", titulo, Element.ALIGN_LEFT, 10, PdfPCell.BOTTOM_BORDER, preto, fundo)); table.AddCell(getNewCell("Registro", titulo, Element.ALIGN_LEFT, 10, PdfPCell.BOTTOM_BORDER, preto, fundo)); table.AddCell(getNewCell("Tatuagem", titulo, Element.ALIGN_LEFT, 10, PdfPCell.BOTTOM_BORDER, preto, fundo)); table.AddCell(getNewCell("Sexo", titulo, Element.ALIGN_LEFT, 10, PdfPCell.BOTTOM_BORDER, preto, fundo)); table.AddCell(getNewCell("Cadastrado Em:", titulo, Element.ALIGN_LEFT, 10, PdfPCell.BOTTOM_BORDER, preto, fundo)); AnimalViewModel a = new AnimalViewModel(); HttpContext httpContext = HttpContext.Current; int idfazenda =Convert.ToInt16( httpContext.ApplicationInstance.Session["idfazenda"].ToString()); var animais = a.RelatorioAnimais(idfazenda, datIni, datFin); var animalOLD = 0; foreach(var an in animais) { if (an.Raca_ID != animalOLD) { var cell = getNewCell("Raça: " + an.nomeraca, titulo, Element.ALIGN_LEFT, 10, PdfPCell.BOTTOM_BORDER); cell.Colspan = 5; table.AddCell(cell); animalOLD = an.Raca_ID; } table.AddCell(getNewCell(an.Descricao, font, Element.ALIGN_LEFT, 5, PdfPCell.BOTTOM_BORDER)); table.AddCell(getNewCell(an.Registro, font, Element.ALIGN_LEFT, 5, PdfPCell.BOTTOM_BORDER)); table.AddCell(getNewCell(an.Tatuagem, font, Element.ALIGN_LEFT, 5, PdfPCell.BOTTOM_BORDER)); table.AddCell(getNewCell(an.descriSexo, font, Element.ALIGN_LEFT, 5, PdfPCell.BOTTOM_BORDER)); table.AddCell(getNewCell(an.Datacadastro.ToString("dd/MM/yyyy"), font, Element.ALIGN_LEFT, 5, PdfPCell.BOTTOM_BORDER)); } var cell2 = getNewCell("Filtros de Pesquisa " + Filtros, titulo, Element.ALIGN_LEFT, 10, PdfPCell.BOTTOM_BORDER); cell2.Colspan = 5; table.AddCell(cell2); } else if(TipoRelatorio == 1) { table.AddCell(getNewCell("Medicamento", titulo, Element.ALIGN_LEFT, 5, PdfPCell.BOTTOM_BORDER, preto, fundo)); table.AddCell(getNewCell("Qtd Mínima", titulo, Element.ALIGN_LEFT, 5, PdfPCell.BOTTOM_BORDER, preto, fundo)); table.AddCell(getNewCell("Qtd Atual", titulo, Element.ALIGN_LEFT, 5, PdfPCell.BOTTOM_BORDER, preto, fundo)); table.AddCell(getNewCell("Estocado Em:", titulo, Element.ALIGN_LEFT, 5, PdfPCell.BOTTOM_BORDER, preto, fundo)); table.AddCell(getNewCell("", titulo, Element.ALIGN_LEFT, 5, PdfPCell.BOTTOM_BORDER, preto, fundo)); Estoque_MedicamentoViewModel a = new Estoque_MedicamentoViewModel(); var es = a.RelatorioEstoque(datIni, datFin); foreach (var an in es) { table.AddCell(getNewCell(an.nomeMedicamento, font, Element.ALIGN_LEFT, 5, PdfPCell.BOTTOM_BORDER)); table.AddCell(getNewCell(Convert.ToString(an.Quantidademinima), font, Element.ALIGN_LEFT, 5, PdfPCell.BOTTOM_BORDER)); table.AddCell(getNewCell(Convert.ToString(an.Quantidadeatual), font, Element.ALIGN_LEFT, 5, PdfPCell.BOTTOM_BORDER)); table.AddCell(getNewCell(an.Data_Estocado.ToString("dd/MM/yyyy"), font, Element.ALIGN_LEFT, 5, PdfPCell.BOTTOM_BORDER)); table.AddCell(getNewCell("", font, Element.ALIGN_LEFT, 5, PdfPCell.BOTTOM_BORDER)); } var cell2 = getNewCell("Filtros de Pesquisa " + Filtros, titulo, Element.ALIGN_LEFT, 10, PdfPCell.BOTTOM_BORDER); cell2.Colspan = 5; table.AddCell(cell2); } else { table.AddCell(getNewCell("Data de Produção", titulo, Element.ALIGN_LEFT, 5, PdfPCell.BOTTOM_BORDER, preto, fundo)); table.AddCell(getNewCell("Qtd (KG)", titulo, Element.ALIGN_LEFT, 5, PdfPCell.BOTTOM_BORDER, preto, fundo)); table.AddCell(getNewCell("Observação", titulo, Element.ALIGN_LEFT, 5, PdfPCell.BOTTOM_BORDER, preto, fundo)); table.AddCell(getNewCell("", titulo, Element.ALIGN_LEFT, 5, PdfPCell.BOTTOM_BORDER, preto, fundo)); table.AddCell(getNewCell("", titulo, Element.ALIGN_LEFT, 5, PdfPCell.BOTTOM_BORDER, preto, fundo)); ProducaoViewModel prod = new ProducaoViewModel(); var prods = prod.RelatorioAnimais(datIni, datFin); var prodOLD = 0; double totalProduzido = 0; double totalGeral = 0; int contador = 0; foreach (var pr in prods) { int quantidadeRegistros = prods.Count; contador++; if (pr.Animail_ID != prodOLD) { if (totalProduzido > 0) { var cell1 = getNewCell("Total produzido: " + totalProduzido + " KG", titulo, Element.ALIGN_LEFT, 10, PdfPCell.BOTTOM_BORDER); cell1.Colspan = 5; table.AddCell(cell1); totalGeral = totalGeral + totalProduzido; } var cell = getNewCell("Animal: " + pr.nomeAnimal, titulo, Element.ALIGN_LEFT, 10, PdfPCell.BOTTOM_BORDER); cell.Colspan = 5; table.AddCell(cell); prodOLD = pr.Animail_ID; totalProduzido = 0; } table.AddCell(getNewCell(pr.Datarealizada.ToShortDateString(), font, Element.ALIGN_LEFT, 5, PdfPCell.BOTTOM_BORDER)); table.AddCell(getNewCell(Convert.ToString(pr.Quantidade), font, Element.ALIGN_LEFT, 5, PdfPCell.BOTTOM_BORDER)); table.AddCell(getNewCell(pr.Observacao, font, Element.ALIGN_LEFT, 5, PdfPCell.BOTTOM_BORDER)); table.AddCell(getNewCell("", font, Element.ALIGN_LEFT, 5, PdfPCell.BOTTOM_BORDER)); table.AddCell(getNewCell("", font, Element.ALIGN_LEFT, 5, PdfPCell.BOTTOM_BORDER)); totalProduzido = totalProduzido + pr.Quantidade; if (contador == quantidadeRegistros) { var cell1 = getNewCell("Total produzido: " + totalProduzido + " KG", titulo, Element.ALIGN_LEFT, 10, PdfPCell.BOTTOM_BORDER); cell1.Colspan = 5; table.AddCell(cell1); totalGeral = totalGeral + totalProduzido; } } var cell2 = getNewCell("Total Geral: " + totalGeral + " KG", titulo, Element.ALIGN_LEFT, 10, PdfPCell.BOTTOM_BORDER); cell2.Colspan = 5; table.AddCell(cell2); var cell3 = getNewCell("Filtros de Pesquisa " + Filtros, titulo, Element.ALIGN_LEFT, 10, PdfPCell.BOTTOM_BORDER); cell3.Colspan = 5; table.AddCell(cell3); } doc.Add(table); } } }
{'content_hash': '72caf857cf70fdea2f0fc8a19565d814', 'timestamp': '', 'source': 'github', 'line_count': 181, 'max_line_length': 153, 'avg_line_length': 48.049723756906076, 'alnum_prop': 0.5604231344141658, 'repo_name': 'ThamiresMancilio/TCC', 'id': 'e9583029604166bff26f1623faab440c4cf337f6', 'size': '8705', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'SysAgropec/SysAgropec/Class/Relatorio.cs', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'ASP', 'bytes': '202'}, {'name': 'C#', 'bytes': '456820'}, {'name': 'CSS', 'bytes': '289439'}, {'name': 'JavaScript', 'bytes': '1398046'}, {'name': 'PowerShell', 'bytes': '177592'}]}
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <!--NewPage--> <HTML> <HEAD> <!-- Generated by javadoc (build 1.6.0_29) on Sat Mar 17 18:06:03 MSK 2012 --> <TITLE> Uses of Class org.apache.poi.hwpf.model.types.TBDAbstractType (POI API Documentation) </TITLE> <META NAME="date" CONTENT="2012-03-17"> <LINK REL ="stylesheet" TYPE="text/css" HREF="../../../../../../../stylesheet.css" TITLE="Style"> <SCRIPT type="text/javascript"> function windowTitle() { if (location.href.indexOf('is-external=true') == -1) { parent.document.title="Uses of Class org.apache.poi.hwpf.model.types.TBDAbstractType (POI API Documentation)"; } } </SCRIPT> <NOSCRIPT> </NOSCRIPT> </HEAD> <BODY BGCOLOR="white" onload="windowTitle();"> <HR> <!-- ========= START OF TOP NAVBAR ======= --> <A NAME="navbar_top"><!-- --></A> <A HREF="#skip-navbar_top" title="Skip navigation links"></A> <TABLE BORDER="0" WIDTH="100%" CELLPADDING="1" CELLSPACING="0" SUMMARY=""> <TR> <TD COLSPAN=2 BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A NAME="navbar_top_firstrow"><!-- --></A> <TABLE BORDER="0" CELLPADDING="0" CELLSPACING="3" SUMMARY=""> <TR ALIGN="center" VALIGN="top"> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../../../overview-summary.html"><FONT CLASS="NavBarFont1"><B>Overview</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../package-summary.html"><FONT CLASS="NavBarFont1"><B>Package</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../../../org/apache/poi/hwpf/model/types/TBDAbstractType.html" title="class in org.apache.poi.hwpf.model.types"><FONT CLASS="NavBarFont1"><B>Class</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#FFFFFF" CLASS="NavBarCell1Rev"> &nbsp;<FONT CLASS="NavBarFont1Rev"><B>Use</B></FONT>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../package-tree.html"><FONT CLASS="NavBarFont1"><B>Tree</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../../../deprecated-list.html"><FONT CLASS="NavBarFont1"><B>Deprecated</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../../../index-all.html"><FONT CLASS="NavBarFont1"><B>Index</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../../../help-doc.html"><FONT CLASS="NavBarFont1"><B>Help</B></FONT></A>&nbsp;</TD> </TR> </TABLE> </TD> <TD ALIGN="right" VALIGN="top" ROWSPAN=3><EM> </EM> </TD> </TR> <TR> <TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2"> &nbsp;PREV&nbsp; &nbsp;NEXT</FONT></TD> <TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2"> <A HREF="../../../../../../../index.html?org/apache/poi/hwpf/model/types/\class-useTBDAbstractType.html" target="_top"><B>FRAMES</B></A> &nbsp; &nbsp;<A HREF="TBDAbstractType.html" target="_top"><B>NO FRAMES</B></A> &nbsp; &nbsp;<SCRIPT type="text/javascript"> <!-- if(window==top) { document.writeln('<A HREF="../../../../../../../allclasses-noframe.html"><B>All Classes</B></A>'); } //--> </SCRIPT> <NOSCRIPT> <A HREF="../../../../../../../allclasses-noframe.html"><B>All Classes</B></A> </NOSCRIPT> </FONT></TD> </TR> </TABLE> <A NAME="skip-navbar_top"></A> <!-- ========= END OF TOP NAVBAR ========= --> <HR> <CENTER> <H2> <B>Uses of Class<br>org.apache.poi.hwpf.model.types.TBDAbstractType</B></H2> </CENTER> <TABLE BORDER="1" WIDTH="100%" CELLPADDING="3" CELLSPACING="0" SUMMARY=""> <TR BGCOLOR="#CCCCFF" CLASS="TableHeadingColor"> <TH ALIGN="left" COLSPAN="2"><FONT SIZE="+2"> Packages that use <A HREF="../../../../../../../org/apache/poi/hwpf/model/types/TBDAbstractType.html" title="class in org.apache.poi.hwpf.model.types">TBDAbstractType</A></FONT></TH> </TR> <TR BGCOLOR="white" CLASS="TableRowColor"> <TD><A HREF="#org.apache.poi.hwpf.model"><B>org.apache.poi.hwpf.model</B></A></TD> <TD>&nbsp;&nbsp;</TD> </TR> </TABLE> &nbsp; <P> <A NAME="org.apache.poi.hwpf.model"><!-- --></A> <TABLE BORDER="1" WIDTH="100%" CELLPADDING="3" CELLSPACING="0" SUMMARY=""> <TR BGCOLOR="#CCCCFF" CLASS="TableHeadingColor"> <TH ALIGN="left" COLSPAN="2"><FONT SIZE="+2"> Uses of <A HREF="../../../../../../../org/apache/poi/hwpf/model/types/TBDAbstractType.html" title="class in org.apache.poi.hwpf.model.types">TBDAbstractType</A> in <A HREF="../../../../../../../org/apache/poi/hwpf/model/package-summary.html">org.apache.poi.hwpf.model</A></FONT></TH> </TR> </TABLE> &nbsp; <P> <TABLE BORDER="1" WIDTH="100%" CELLPADDING="3" CELLSPACING="0" SUMMARY=""> <TR BGCOLOR="#CCCCFF" CLASS="TableSubHeadingColor"> <TH ALIGN="left" COLSPAN="2">Subclasses of <A HREF="../../../../../../../org/apache/poi/hwpf/model/types/TBDAbstractType.html" title="class in org.apache.poi.hwpf.model.types">TBDAbstractType</A> in <A HREF="../../../../../../../org/apache/poi/hwpf/model/package-summary.html">org.apache.poi.hwpf.model</A></FONT></TH> </TR> <TR BGCOLOR="white" CLASS="TableRowColor"> <TD ALIGN="right" VALIGN="top" WIDTH="1%"><FONT SIZE="-1"> <CODE>&nbsp;class</CODE></FONT></TD> <TD><CODE><B><A HREF="../../../../../../../org/apache/poi/hwpf/model/TabDescriptor.html" title="class in org.apache.poi.hwpf.model">TabDescriptor</A></B></CODE> <BR> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;Tab descriptor.</TD> </TR> </TABLE> &nbsp; <P> <HR> <!-- ======= START OF BOTTOM NAVBAR ====== --> <A NAME="navbar_bottom"><!-- --></A> <A HREF="#skip-navbar_bottom" title="Skip navigation links"></A> <TABLE BORDER="0" WIDTH="100%" CELLPADDING="1" CELLSPACING="0" SUMMARY=""> <TR> <TD COLSPAN=2 BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A NAME="navbar_bottom_firstrow"><!-- --></A> <TABLE BORDER="0" CELLPADDING="0" CELLSPACING="3" SUMMARY=""> <TR ALIGN="center" VALIGN="top"> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../../../overview-summary.html"><FONT CLASS="NavBarFont1"><B>Overview</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../package-summary.html"><FONT CLASS="NavBarFont1"><B>Package</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../../../org/apache/poi/hwpf/model/types/TBDAbstractType.html" title="class in org.apache.poi.hwpf.model.types"><FONT CLASS="NavBarFont1"><B>Class</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#FFFFFF" CLASS="NavBarCell1Rev"> &nbsp;<FONT CLASS="NavBarFont1Rev"><B>Use</B></FONT>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../package-tree.html"><FONT CLASS="NavBarFont1"><B>Tree</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../../../deprecated-list.html"><FONT CLASS="NavBarFont1"><B>Deprecated</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../../../index-all.html"><FONT CLASS="NavBarFont1"><B>Index</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../../../help-doc.html"><FONT CLASS="NavBarFont1"><B>Help</B></FONT></A>&nbsp;</TD> </TR> </TABLE> </TD> <TD ALIGN="right" VALIGN="top" ROWSPAN=3><EM> </EM> </TD> </TR> <TR> <TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2"> &nbsp;PREV&nbsp; &nbsp;NEXT</FONT></TD> <TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2"> <A HREF="../../../../../../../index.html?org/apache/poi/hwpf/model/types/\class-useTBDAbstractType.html" target="_top"><B>FRAMES</B></A> &nbsp; &nbsp;<A HREF="TBDAbstractType.html" target="_top"><B>NO FRAMES</B></A> &nbsp; &nbsp;<SCRIPT type="text/javascript"> <!-- if(window==top) { document.writeln('<A HREF="../../../../../../../allclasses-noframe.html"><B>All Classes</B></A>'); } //--> </SCRIPT> <NOSCRIPT> <A HREF="../../../../../../../allclasses-noframe.html"><B>All Classes</B></A> </NOSCRIPT> </FONT></TD> </TR> </TABLE> <A NAME="skip-navbar_bottom"></A> <!-- ======== END OF BOTTOM NAVBAR ======= --> <HR> <i>Copyright 2012 The Apache Software Foundation or its licensors, as applicable.</i> </BODY> </HTML>
{'content_hash': 'a5471c70fcd296c6061c079a61600013', 'timestamp': '', 'source': 'github', 'line_count': 183, 'max_line_length': 318, 'avg_line_length': 44.43715846994535, 'alnum_prop': 0.6158386620757501, 'repo_name': 'Stephania16/ProductDesignGame', 'id': 'd17b86608108f73dd5441560fa2b281c0fad0e56', 'size': '8132', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'MinimaxAlgorithm/poi-3.8/docs/apidocs/org/apache/poi/hwpf/model/types/class-use/TBDAbstractType.html', 'mode': '33188', 'license': 'apache-2.0', 'language': [{'name': 'CSS', 'bytes': '15337'}, {'name': 'HTML', 'bytes': '74071650'}, {'name': 'Java', 'bytes': '37924'}]}
<!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.11"/> <title>V8 API Reference Guide for node.js v8.6.0: Member List</title> <link href="tabs.css" rel="stylesheet" type="text/css"/> <script type="text/javascript" src="jquery.js"></script> <script type="text/javascript" src="dynsections.js"></script> <link href="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/javascript"> $(document).ready(function() { init_search(); }); </script> <link href="doxygen.css" rel="stylesheet" type="text/css" /> </head> <body> <div id="top"><!-- do not remove this div, it is closed by doxygen! --> <div id="titlearea"> <table cellspacing="0" cellpadding="0"> <tbody> <tr style="height: 56px;"> <td id="projectalign" style="padding-left: 0.5em;"> <div id="projectname">V8 API Reference Guide for node.js v8.6.0 </div> </td> </tr> </tbody> </table> </div> <!-- end header part --> <!-- Generated by Doxygen 1.8.11 --> <script type="text/javascript"> var searchBox = new SearchBox("searchBox", "search",false,'Search'); </script> <div id="navrow1" class="tabs"> <ul class="tablist"> <li><a href="index.html"><span>Main&#160;Page</span></a></li> <li><a href="namespaces.html"><span>Namespaces</span></a></li> <li class="current"><a href="annotated.html"><span>Classes</span></a></li> <li><a href="files.html"><span>Files</span></a></li> <li><a href="examples.html"><span>Examples</span></a></li> <li> <div id="MSearchBox" class="MSearchBoxInactive"> <span class="left"> <img id="MSearchSelect" src="search/mag_sel.png" onmouseover="return searchBox.OnSearchSelectShow()" onmouseout="return searchBox.OnSearchSelectHide()" alt=""/> <input type="text" id="MSearchField" value="Search" accesskey="S" onfocus="searchBox.OnSearchFieldFocus(true)" onblur="searchBox.OnSearchFieldFocus(false)" onkeyup="searchBox.OnSearchFieldChange(event)"/> </span><span class="right"> <a id="MSearchClose" href="javascript:searchBox.CloseResultsWindow()"><img id="MSearchCloseImg" border="0" src="search/close.png" alt=""/></a> </span> </div> </li> </ul> </div> <div id="navrow2" class="tabs2"> <ul class="tablist"> <li><a href="annotated.html"><span>Class&#160;List</span></a></li> <li><a href="classes.html"><span>Class&#160;Index</span></a></li> <li><a href="inherits.html"><span>Class&#160;Hierarchy</span></a></li> <li><a href="functions.html"><span>Class&#160;Members</span></a></li> </ul> </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="namespacev8.html">v8</a></li><li class="navelem"><a class="el" href="classv8_1_1Task.html">Task</a></li> </ul> </div> </div><!-- top --> <div class="header"> <div class="headertitle"> <div class="title">v8::Task Member List</div> </div> </div><!--header--> <div class="contents"> <p>This is the complete list of members for <a class="el" href="classv8_1_1Task.html">v8::Task</a>, including all inherited members.</p> <table class="directory"> <tr bgcolor="#f0f0f0" class="even"><td class="entry"><b>Run</b>()=0 (defined in <a class="el" href="classv8_1_1Task.html">v8::Task</a>)</td><td class="entry"><a class="el" href="classv8_1_1Task.html">v8::Task</a></td><td class="entry"><span class="mlabel">pure virtual</span></td></tr> <tr bgcolor="#f0f0f0"><td class="entry"><b>~Task</b>()=default (defined in <a class="el" href="classv8_1_1Task.html">v8::Task</a>)</td><td class="entry"><a class="el" href="classv8_1_1Task.html">v8::Task</a></td><td class="entry"><span class="mlabel">virtual</span></td></tr> </table></div><!-- contents --> <!-- start footer part --> <hr class="footer"/><address class="footer"><small> Generated by &#160;<a href="http://www.doxygen.org/index.html"> <img class="footer" src="doxygen.png" alt="doxygen"/> </a> 1.8.11 </small></address> </body> </html>
{'content_hash': '39c70ece54199c42a55df6c4f32976e1', 'timestamp': '', 'source': 'github', 'line_count': 108, 'max_line_length': 287, 'avg_line_length': 45.583333333333336, 'alnum_prop': 0.6416819012797075, 'repo_name': 'v8-dox/v8-dox.github.io', 'id': 'deb53b715e952cd65334a43479530468d409c8ba', 'size': '4923', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': '2e75ac0/html/classv8_1_1Task-members.html', 'mode': '33188', 'license': 'mit', 'language': []}
title: Telerik.Web.UI.BreadcrumbClientEvents page_title: Telerik.Web.UI.BreadcrumbClientEvents description: Telerik.Web.UI.BreadcrumbClientEvents --- # Telerik.Web.UI.BreadcrumbClientEvents Defines the client events handlers. ## Inheritance Hierarchy * System.Object * Telerik.Web.StateManager : IMarkableStateManager, IStateManager * Telerik.Web.UI.BreadcrumbClientEvents : IDefaultCheck ## Properties ### OnChange `String` Fires when the value of the Breadcrumb is changed. ### OnClick `String` Fires when an item or a rootitem is clicked. ### OnInitialize `String` Fired when the control is initialized. ### OnLoad `String` Fired when the control is loaded on the page.
{'content_hash': '539d82a9eace8e95fd39b98e2a7a51de', 'timestamp': '', 'source': 'github', 'line_count': 33, 'max_line_length': 65, 'avg_line_length': 20.939393939393938, 'alnum_prop': 0.7771345875542692, 'repo_name': 'telerik/ajax-docs', 'id': '9ed81c353cab7bd85a80dae4e117517da68b1dcc', 'size': '695', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'api/server/Telerik.Web.UI/BreadcrumbClientEvents.md', 'mode': '33188', 'license': 'apache-2.0', 'language': [{'name': 'ASP.NET', 'bytes': '2253'}, {'name': 'C#', 'bytes': '6026'}, {'name': 'HTML', 'bytes': '2240'}, {'name': 'JavaScript', 'bytes': '3052'}, {'name': 'Ruby', 'bytes': '3275'}]}
<div class="mdl-grid"> <div class="mdl-layout-spacer"> </div> <div class="mdl-cell mdl-cell--4-col"> <div class="mdl-card mdl-shadow--2dp"> <form name="confirmFulfillment" novalidate> <h3>Confirm Alumni Request Fulfillment for {{ orgName }}</h3> <div class="mdl-textfield mdl-js-textfield"> <textarea class="mdl-textfield__input" type="text" ng-model="alumniNames" placeholder="Names of alumni that you have chosen (each on a different line)" required> </textarea> </div> <div class="mdl-textfield mdl-js-textfield"> <textarea class="mdl-textfield__input" type="text" ng-model="alumniEmails" placeholder="Their emails in same order (each on a different line)" required> </textarea> </div> <button ng-disabled="confirmFulfillment.$invalid || numAlumni == 0" class="mdl-button mdl-shadow--2dp" ng-click="fulfill()">Fulfill!</button> </form> </div> </div> <div class="mdl-layout-spacer"></div> </div>
{'content_hash': '37b1b71329d7140fa7e3398826ce9590', 'timestamp': '', 'source': 'github', 'line_count': 21, 'max_line_length': 181, 'avg_line_length': 54.333333333333336, 'alnum_prop': 0.5705521472392638, 'repo_name': 'Srokit/UMStudentOrgAlumniRequestGW', 'id': 'f30aa6f95d353d63fd15f114f38adc2643c62c84', 'size': '1141', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'ng_app/comps/fulfillrequest/fulfillrequest.view.html', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'CSS', 'bytes': '185'}, {'name': 'HTML', 'bytes': '34247'}, {'name': 'JavaScript', 'bytes': '52993'}]}
package site.zhangqun.lanagina; import org.junit.Test; import static org.junit.Assert.*; /** * Example local unit test, which will execute on the development machine (host). * * @see <a href="http://d.android.com/tools/testing">Testing documentation</a> */ public class ExampleUnitTest { @Test public void addition_isCorrect() throws Exception { assertEquals(4, 2 + 2); } }
{'content_hash': 'e86e6b6ab3a8a1123bf2670896f0a35a', 'timestamp': '', 'source': 'github', 'line_count': 17, 'max_line_length': 81, 'avg_line_length': 23.529411764705884, 'alnum_prop': 0.6925, 'repo_name': 'uffuff/LSMS', 'id': '9f5f92f824d0df4c8377375ec92eb1f17b931b70', 'size': '400', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'app/src/test/java/site/zhangqun/lanagina/ExampleUnitTest.java', 'mode': '33188', 'license': 'apache-2.0', 'language': [{'name': 'CSS', 'bytes': '61834'}, {'name': 'Groovy', 'bytes': '11701'}, {'name': 'HTML', 'bytes': '255867'}, {'name': 'Java', 'bytes': '149374'}, {'name': 'JavaScript', 'bytes': '186353'}, {'name': 'PHP', 'bytes': '2333'}]}
""" relief.schema.meta ~~~~~~~~~~~~~~~~~~ :copyright: 2013 by Daniel Neuhäuser :license: BSD, see LICENSE.rst for details """ from relief.utils import class_cloner from relief.constants import Unspecified from relief.schema.core import BaseElement class Maybe(BaseElement): """ A meta element that represents an element that is optional. The value of this element will be `None` unless the contained element's value is not `Unspecified`. >>> from relief import Unicode >>> Maybe.of(Unicode)().value None >>> Maybe.of(Unicode)(u'foobar').value u'foobar .. versionadded:: 2.1.0 """ member_schema = None @class_cloner def of(cls, schema): cls.member_schema = schema return cls def __init__(self, value=Unspecified): self.member = self.member_schema() super(Maybe, self).__init__(value) if self.member_schema is None: raise TypeError('member_schema is unknown') @property def value(self): return None if self.member.value is Unspecified else self.member.value @value.setter def value(self, new_value): if new_value is not Unspecified: raise AttributeError("can't set attribute") def serialize(self, value): if value is None: return Unspecified return self.member.serialize(value) def unserialize(self, raw_value): value = self.member.unserialize(raw_value) return None if value is Unspecified else value def set_from_raw(self, raw_value): self.raw_value = raw_value value = self.unserialize(raw_value) if value is None: self.member.set_from_raw(Unspecified) else: self.member.set_from_raw(raw_value) self.is_valid = None def set_from_native(self, value): self.member.set_from_native(value) self.raw_value = self.member.raw_value self.is_valid = None def validate(self, context=None): if context is None: context = {} self.is_valid = self.member.validate() or self.value is None return self.is_valid
{'content_hash': 'bbc965975be60db1f6c19f3ada479c22', 'timestamp': '', 'source': 'github', 'line_count': 76, 'max_line_length': 78, 'avg_line_length': 28.539473684210527, 'alnum_prop': 0.6251728907330567, 'repo_name': 'DasIch/relief', 'id': '3587702365831b464512bf75714095614e3c9290', 'size': '2186', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'relief/schema/meta.py', 'mode': '33188', 'license': 'bsd-3-clause', 'language': [{'name': 'Python', 'bytes': '117437'}, {'name': 'Shell', 'bytes': '6701'}]}
package serialization import ( "github.com/cloudfoundry-incubator/receptor" "github.com/cloudfoundry-incubator/runtime-schema/models" ) func ActualLRPToResponse(actualLRP models.ActualLRP, evacuating bool) receptor.ActualLRPResponse { return receptor.ActualLRPResponse{ ProcessGuid: actualLRP.ProcessGuid, InstanceGuid: actualLRP.InstanceGuid, CellID: actualLRP.CellID, Domain: actualLRP.Domain, Index: actualLRP.Index, Address: actualLRP.Address, Ports: PortMappingFromModel(actualLRP.Ports), State: actualLRPStateToResponseState(actualLRP.State), PlacementError: actualLRP.PlacementError, Since: actualLRP.Since, CrashCount: actualLRP.CrashCount, CrashReason: actualLRP.CrashReason, Evacuating: evacuating, ModificationTag: actualLRPModificationTagToResponseModificationTag(actualLRP.ModificationTag), } } func actualLRPStateToResponseState(state models.ActualLRPState) receptor.ActualLRPState { switch state { case models.ActualLRPStateUnclaimed: return receptor.ActualLRPStateUnclaimed case models.ActualLRPStateClaimed: return receptor.ActualLRPStateClaimed case models.ActualLRPStateRunning: return receptor.ActualLRPStateRunning case models.ActualLRPStateCrashed: return receptor.ActualLRPStateCrashed default: return receptor.ActualLRPStateInvalid } } func actualLRPModificationTagToResponseModificationTag(modificationTag models.ModificationTag) receptor.ModificationTag { return receptor.ModificationTag{ Epoch: modificationTag.Epoch, Index: modificationTag.Index, } }
{'content_hash': '081f0633d2a532b022420bf0e8d0a3ee', 'timestamp': '', 'source': 'github', 'line_count': 47, 'max_line_length': 121, 'avg_line_length': 34.59574468085106, 'alnum_prop': 0.7878228782287823, 'repo_name': 'mikegehard/lattice', 'id': 'f902410a95f756fb23089e415597384a13835119', 'size': '1626', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'ltc/Godeps/_workspace/src/github.com/cloudfoundry-incubator/receptor/serialization/actual_lrps.go', 'mode': '33188', 'license': 'apache-2.0', 'language': [{'name': 'Go', 'bytes': '345389'}, {'name': 'Shell', 'bytes': '43093'}]}
package org.apache.webapp.admin.realm; import java.io.IOException; import java.net.URLEncoder; import java.util.Locale; import java.util.ArrayList; import javax.servlet.ServletException; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpSession; import org.apache.struts.action.Action; import org.apache.struts.action.ActionErrors; import org.apache.struts.action.ActionForm; import org.apache.struts.action.ActionForward; import org.apache.struts.action.ActionMapping; import org.apache.struts.util.MessageResources; import org.apache.webapp.admin.LabelValueBean; import org.apache.webapp.admin.Lists; /** * The <code>Action</code> that sets up <em>Add Realm</em> transactions. * * @author Manveen Kaur * @version $Revision: 1.5 $ $Date: 2002/08/13 22:35:20 $ */ public class AddRealmAction extends Action { /** * The MessageResources we will be retrieving messages from. */ private MessageResources resources = null; // the list for types of realms private ArrayList types = null; // --------------------------------------------------------- Public Methods /** * Process the specified HTTP request, and create the corresponding HTTP * response (or forward to another web component that will create it). * Return an <code>ActionForward</code> instance describing where and how * control should be forwarded, or <code>null</code> if the response has * already been completed. * * @param mapping The ActionMapping used to select this instance * @param actionForm The optional ActionForm bean for this request (if any) * @param request The HTTP request we are processing * @param response The HTTP response we are creating * * @exception IOException if an input/output error occurs * @exception ServletException if a servlet exception occurs */ public ActionForward perform(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException { // Acquire the resources that we need HttpSession session = request.getSession(); Locale locale = (Locale) session.getAttribute(Action.LOCALE_KEY); if (resources == null) { resources = getServlet().getResources(); } // Fill in the form values for display and editing String realmTypes[] = new String[4]; realmTypes[0] = "UserDatabaseRealm"; realmTypes[1] = "JNDIRealm"; realmTypes[2] = "MemoryRealm"; realmTypes[3] = "JDBCRealm"; String parent = request.getParameter("parent"); String type = request.getParameter("type"); if (type == null) type = "UserDatabaseRealm"; // default type is UserDatabaseRealm types = new ArrayList(); // the first element in the select list should be the type selected types.add(new LabelValueBean(type, "/admin/AddRealm.do?parent=" + URLEncoder.encode(parent) + "&type=" + type)); for (int i=0; i< realmTypes.length; i++) { if (!type.equalsIgnoreCase(realmTypes[i])) { types.add(new LabelValueBean(realmTypes[i], "/admin/AddRealm.do?parent=" + URLEncoder.encode(parent) + "&type=" + realmTypes[i])); } } if ("UserDatabaseRealm".equalsIgnoreCase(type)) { createUserDatabaseRealm(session, parent); } else if ("JNDIRealm".equalsIgnoreCase(type)) { createJNDIRealm(session, parent); } else if ("MemoryRealm".equalsIgnoreCase(type)) { createMemoryRealm(session, parent); } else { //JDBC createJDBCRealm(session, parent); } // Forward to the realm display page return (mapping.findForward(type)); } private void createUserDatabaseRealm(HttpSession session, String parent) { UserDatabaseRealmForm realmFm = new UserDatabaseRealmForm(); session.setAttribute("userDatabaseRealmForm", realmFm); realmFm.setAdminAction("Create"); realmFm.setObjectName(""); realmFm.setParentObjectName(parent); String realmType = "UserDatabaseRealm"; realmFm.setNodeLabel("Realm (" + realmType + ")"); realmFm.setRealmType(realmType); realmFm.setDebugLvl("0"); realmFm.setResource(""); realmFm.setDebugLvlVals(Lists.getDebugLevels()); realmFm.setRealmTypeVals(types); } private void createJNDIRealm(HttpSession session, String parent) { JNDIRealmForm realmFm = new JNDIRealmForm(); session.setAttribute("jndiRealmForm", realmFm); realmFm.setAdminAction("Create"); realmFm.setObjectName(""); realmFm.setParentObjectName(parent); String realmType = "JNDIRealm"; realmFm.setNodeLabel("Realm (" + realmType + ")"); realmFm.setRealmType(realmType); realmFm.setDebugLvl("0"); realmFm.setDigest(""); realmFm.setRoleBase(""); realmFm.setUserSubtree("false"); realmFm.setRoleSubtree("false"); realmFm.setRolePattern(""); realmFm.setUserRoleName(""); realmFm.setRoleName(""); realmFm.setRoleBase(""); realmFm.setContextFactory(""); realmFm.setUserBase(""); realmFm.setUserPattern(""); realmFm.setUserSearch(""); realmFm.setUserPassword(""); realmFm.setConnectionName(""); realmFm.setConnectionPassword(""); realmFm.setConnectionURL(""); realmFm.setDebugLvlVals(Lists.getDebugLevels()); realmFm.setSearchVals(Lists.getBooleanValues()); realmFm.setRealmTypeVals(types); } private void createMemoryRealm(HttpSession session, String parent) { MemoryRealmForm realmFm = new MemoryRealmForm(); session.setAttribute("memoryRealmForm", realmFm); realmFm.setAdminAction("Create"); realmFm.setObjectName(""); realmFm.setParentObjectName(parent); String realmType = "MemoryRealm"; realmFm.setNodeLabel("Realm (" + realmType + ")"); realmFm.setRealmType(realmType); realmFm.setDebugLvl("0"); realmFm.setPathName(""); realmFm.setDebugLvlVals(Lists.getDebugLevels()); realmFm.setRealmTypeVals(types); } private void createJDBCRealm(HttpSession session, String parent) { JDBCRealmForm realmFm = new JDBCRealmForm(); session.setAttribute("jdbcRealmForm", realmFm); realmFm.setAdminAction("Create"); realmFm.setObjectName(""); realmFm.setParentObjectName(parent); String realmType = "JDBCRealm"; realmFm.setNodeLabel("Realm (" + realmType + ")"); realmFm.setRealmType(realmType); realmFm.setDebugLvl("0"); realmFm.setDigest(""); realmFm.setDriver(""); realmFm.setRoleNameCol(""); realmFm.setPasswordCol(""); realmFm.setUserTable(""); realmFm.setRoleTable(""); realmFm.setConnectionName(""); realmFm.setConnectionPassword(""); realmFm.setConnectionURL(""); realmFm.setDebugLvlVals(Lists.getDebugLevels()); realmFm.setRealmTypeVals(types); } }
{'content_hash': '9f59cebd16b0faf2a91280e5b5d50f57', 'timestamp': '', 'source': 'github', 'line_count': 200, 'max_line_length': 79, 'avg_line_length': 37.285, 'alnum_prop': 0.6403379375083814, 'repo_name': 'devjin24/howtomcatworks', 'id': 'f653b9093fbad4c95195360a324d63168ce11c8e', 'size': '10327', 'binary': False, 'copies': '2', 'ref': 'refs/heads/master', 'path': 'bookrefer/jakarta-tomcat-4.1.12-src/webapps/admin/WEB-INF/classes/org/apache/webapp/admin/realm/AddRealmAction.java', 'mode': '33261', 'license': 'apache-2.0', 'language': [{'name': 'Batchfile', 'bytes': '52224'}, {'name': 'C', 'bytes': '2123859'}, {'name': 'C++', 'bytes': '5454'}, {'name': 'CSS', 'bytes': '4762'}, {'name': 'HTML', 'bytes': '232523'}, {'name': 'Java', 'bytes': '25349050'}, {'name': 'Makefile', 'bytes': '2331'}, {'name': 'NSIS', 'bytes': '25933'}, {'name': 'Perl', 'bytes': '100975'}, {'name': 'Shell', 'bytes': '49871'}, {'name': 'Visual Basic', 'bytes': '9998'}, {'name': 'XSLT', 'bytes': '27566'}]}
<TS language="nl" version="2.0"> <defaultcodec>UTF-8</defaultcodec> <context> <name>AboutDialog</name> <message> <source>About Lambocoin</source> <translation>Over Lambocoin</translation> </message> <message> <source>&lt;b&gt;Lambocoin&lt;/b&gt; version</source> <translation>&lt;html&gt;&lt;head/&gt;&lt;body&gt;&lt;p&gt;&lt;span style=" font-weight:600;"&gt;Lambocoin&lt;/span&gt;&lt;/p&gt;&lt;/body&gt;&lt;/html&gt;</translation> </message> </context> <context> <name>AddressBookPage</name> <message> <source>Address Book</source> <translation>Adresboek</translation> </message> <message> <source>These are your Lambocoin 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>Dit zijn je Lambocoin adressen om bedragen te ontvangen. Je kan een verschillend adres opgeven voor iedere geaddresseerde zodat je kan achterhalen wie jouw betaalt.</translation> </message> <message> <source>Double-click to edit address or label</source> <translation>Dubbelklik om adres of label te wijzigen</translation> </message> <message> <source>Create a new address</source> <translation>Maak een nieuw adres aan</translation> </message> <message> <source>Copy the currently selected address to the system clipboard</source> <translation>Kopieer het huidig geselecteerde adres naar het klembord</translation> </message> <message> <source>&amp;New Address</source> <translation>&amp;Nieuw Adres</translation> </message> <message> <source>&amp;Copy Address</source> <translation>&amp;Kopieer Adres</translation> </message> <message> <source>Show &amp;QR Code</source> <translation>Toon &amp;QR-Code</translation> </message> <message> <source>Sign a message to prove you own this address</source> <translation>Onderteken een bericht om te bewijzen dat u dit adres bezit</translation> </message> <message> <source>&amp;Sign Message</source> <translation>&amp;Onderteken Bericht</translation> </message> <message> <source>Delete the currently selected address from the list. Only sending addresses can be deleted.</source> <translation>Verwijder het huidige geselecteerde adres van de lijst. Alleen verzend-adressen kunnen verwijderd worden, niet uw ontvangstadressen.</translation> </message> <message> <source>&amp;Delete</source> <translation>&amp;Verwijder</translation> </message> <message> <source>Copy &amp;Label</source> <translation>Kopieer &amp;Label</translation> </message> <message> <source>&amp;Edit</source> <translation>&amp;Bewerken</translation> </message> <message> <source>Export Address Book Data</source> <translation>Exporteer Gegevens van het Adresboek</translation> </message> <message> <source>Comma separated file (*.csv)</source> <translation>Kommagescheiden bestand (*.csv)</translation> </message> <message> <source>Error exporting</source> <translation>Fout bij exporteren</translation> </message> <message> <source>Could not write to file %1.</source> <translation>Kon niet schrijven naar bestand %1.</translation> </message> </context> <context> <name>AddressTableModel</name> <message> <source>Label</source> <translation>Label</translation> </message> <message> <source>Address</source> <translation>Adres</translation> </message> <message> <source>(no label)</source> <translation>(geen label)</translation> </message> </context> <context> <name>AskPassphraseDialog</name> <message> <source>Enter passphrase</source> <translation>Huidige wachtwoordzin</translation> </message> <message> <source>New passphrase</source> <translation>Nieuwe wachtwoordzin</translation> </message> <message> <source>Repeat new passphrase</source> <translation>Herhaal wachtwoordzin</translation> </message> <message> <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>Vul een nieuw wachtwoord in voor uw portemonnee. &lt;br/&gt; Gebruik een wachtwoord van &lt;b&gt;10 of meer lukrake karakters&lt;/b&gt;, of &lt;b&gt; acht of meer woorden&lt;/b&gt; . </translation> </message> <message> <source>Encrypt wallet</source> <translation>Versleutel portemonnee</translation> </message> <message> <source>This operation needs your wallet passphrase to unlock the wallet.</source> <translation>Deze operatie vereist uw portemonnee wachtwoordzin om de portemonnee te openen.</translation> </message> <message> <source>Unlock wallet</source> <translation>Open portemonnee</translation> </message> <message> <source>This operation needs your wallet passphrase to decrypt the wallet.</source> <translation>Deze operatie vereist uw portemonnee wachtwoordzin om de portemonnee te ontsleutelen</translation> </message> <message> <source>Decrypt wallet</source> <translation>Ontsleutel portemonnee</translation> </message> <message> <source>Change passphrase</source> <translation>Wijzig de wachtwoordzin</translation> </message> <message> <source>Confirm wallet encryption</source> <translation>Bevestig versleuteling van de portemonnee</translation> </message> <message> <source>Wallet encrypted</source> <translation>Portemonnee versleuteld</translation> </message> <message> <source>Warning: The Caps Lock key is on.</source> <translation>Waarschuwing: De Caps-Lock-toets staat aan.</translation> </message> <message> <source>Wallet encryption failed</source> <translation>Portemonneeversleuteling mislukt</translation> </message> <message> <source>WARNING: If you encrypt your wallet and lose your passphrase, you will &lt;b&gt;LOSE ALL OF YOUR PAYCOINS&lt;/b&gt;! Are you sure you wish to encrypt your wallet?</source> <translation>WAARSCHUWING: Indien je de portemonnee versleutelt en je wachtwoordzin verliest, dan verlies je &lt;b&gt; AL JE PAYCOINS&lt;/b&gt;! Weet je zeker dat je de portemonee wilt versleutelen?</translation> </message> <message> <source>Lambocoin will close now to finish the encryption process. Remember that encrypting your wallet cannot fully protect your Lambocoins from being stolen by malware infecting your computer.</source> <translation>Lambocoin sluit nu af om het versleutelings proces te beeindigen. Onthoud dat het versleutelen van de portemonnee je Lambocoins niet volledig kan beschermen tegen schadelijke software op een geinfecteerde computer</translation> </message> <message> <source>Wallet encryption failed due to an internal error. Your wallet was not encrypted.</source> <translation>Portemonneeversleuteling mislukt door een interne fout. Uw portemonnee is niet versleuteld.</translation> </message> <message> <source>The supplied passphrases do not match.</source> <translation>De opgegeven wachtwoordzin is niet correct</translation> </message> <message> <source>Wallet unlock failed</source> <translation>Portemonnee openen mislukt</translation> </message> <message> <source>The passphrase entered for the wallet decryption was incorrect.</source> <translation>De opgegeven wachtwoordzin voor de portemonnee-ontsleuteling is niet correct.</translation> </message> <message> <source>Wallet decryption failed</source> <translation>Portemonnee-ontsleuteling mislukt</translation> </message> <message> <source>Wallet passphrase was successfully changed.</source> <translation>Portemonnee wachtwoordzin is succesvol gewijzigd</translation> </message> </context> <context> <name>BitcoinGUI</name> <message> <source>&amp;Overview</source> <translation>&amp;Overzicht</translation> </message> <message> <source>Show general overview of wallet</source> <translation>Toon algemeen overzicht van de portemonnee</translation> </message> <message> <source>&amp;Transactions</source> <translation>&amp;Transacties</translation> </message> <message> <source>Browse transaction history</source> <translation>Blader door transactieverleden</translation> </message> <message> <source>&amp;Address Book</source> <translation>&amp;Adresboek</translation> </message> <message> <source>Edit the list of stored addresses and labels</source> <translation>Bewerk de lijst van opgeslagen adressen en labels</translation> </message> <message> <source>&amp;Receive coins</source> <translation>&amp;Ontvang munten</translation> </message> <message> <source>Show the list of addresses for receiving payments</source> <translation>Toon lijst van betalingsadressen</translation> </message> <message> <source>&amp;Send coins</source> <translation>&amp;Verstuur munten</translation> </message> <message> <source>Prove you control an address</source> <translation>Bewijs dat u een adres bezit</translation> </message> <message> <source>E&amp;xit</source> <translation>&amp;Afsluiten</translation> </message> <message> <source>Quit application</source> <translation>Programma afsluiten</translation> </message> <message> <source>Show information about Lambocoin</source> <translation>Toon informatie over Lambocoin</translation> </message> <message> <source>About &amp;Qt</source> <translation>Over &amp;Qt</translation> </message> <message> <source>Show information about Qt</source> <translation>Toon informatie over Qt</translation> </message> <message> <source>&amp;Options...</source> <translation>&amp;Opties...</translation> </message> <message> <source>&amp;Export...</source> <translation>&amp;Exporteer...</translation> </message> <message> <source>Export the data in the current tab to a file</source> <translation>Exporteer de data in de huidige tab naar een bestand</translation> </message> <message> <source>Encrypt or decrypt wallet</source> <translation>Versleutel of ontsleutel portemonnee</translation> </message> <message> <source>&amp;Unlock Wallet for Minting Only</source> <translation>&amp;Ontsleutel portemonnee alleen om te minten</translation> </message> <message> <source>Unlock wallet only for minting. Sending coins will still require the passphrase.</source> <translation>Ontsleutel portemonnee alleen om te minten. Voor het versturen van munten is nog een wachtwoordzin nodig</translation> </message> <message> <source>Backup wallet to another location</source> <translation>&amp;Backup portemonnee naar een andere locatie</translation> </message> <message> <source>Change the passphrase used for wallet encryption</source> <translation>Wijzig de wachtwoordzin voor uw portemonneversleuteling</translation> </message> <message> <source>&amp;Debug window</source> <translation>&amp;Debug scherm</translation> </message> <message> <source>Open debugging and diagnostic console</source> <translation>Open debugging en diagnostische console</translation> </message> <message> <source>&amp;File</source> <translation>&amp;Bestand</translation> </message> <message> <source>&amp;Settings</source> <translation>&amp;Instellingen</translation> </message> <message> <source>&amp;Help</source> <translation>&amp;Hulp</translation> </message> <message> <source>Tabs toolbar</source> <translation>Tab-werkbalk</translation> </message> <message> <source>Actions toolbar</source> <translation>Actie-werkbalk</translation> </message> <message> <source>[testnet]</source> <translation>[testnetwerk]</translation> </message> <message> <source>Lambocoin Wallet</source> <translation>Lambocoin portemonnee</translation> </message> <message> <source>Send coins to a Lambocoin address</source> <translation>Zend munten naar een Lambocoin adres</translation> </message> <message> <source>&amp;About Lambocoin</source> <translation>Over Lambocoin</translation> </message> <message> <source>Modify configuration options for Lambocoin</source> <translation>Wijzig configuratie opties voor Lambocoin</translation> </message> <message> <source>Show/Hide &amp;Lambocoin</source> <translation>Toon/Verberg &amp;Lambocoin</translation> </message> <message> <source>Show or hide the Lambocoin window</source> <translation>Toon of verberg het Lambocoin scherm</translation> </message> <message> <source>&amp;Encrypt Wallet...</source> <translation>&amp;Versleutel Portemonnee</translation> </message> <message> <source>&amp;Backup Wallet...</source> <translation>&amp;Backup Portemonnee</translation> </message> <message> <source>Lambocoin client</source> <translation>Lambocoin client</translation> </message> <message> <source>Synchronizing with network...</source> <translation>Synchroniseren met netwerk...</translation> </message> <message> <source>Downloaded %1 blocks of transaction history.</source> <translation>%1 blokken van transactiehistorie opgehaald.</translation> </message> <message numerus="yes"> <source>%n second(s) ago</source> <translation><numerusform>%n seconde geleden</numerusform><numerusform>%n seconde geleden</numerusform></translation> </message> <message numerus="yes"> <source>%n minute(s) ago</source> <translation><numerusform>%n minuut geleden</numerusform><numerusform>%n minuten geleden</numerusform></translation> </message> <message numerus="yes"> <source>%n hour(s) ago</source> <translation><numerusform>%n uur geleden</numerusform><numerusform>%n uur geleden</numerusform></translation> </message> <message numerus="yes"> <source>%n day(s) ago</source> <translation><numerusform>%n dag geleden</numerusform><numerusform>%n dagen geleden</numerusform></translation> </message> <message> <source>Up to date</source> <translation>Bijgewerkt</translation> </message> <message> <source>Catching up...</source> <translation>Aan het bijwerken...</translation> </message> <message> <source>Last received block was generated %1.</source> <translation>Laatst ontvangen blok is %1 gegenereerd.</translation> </message> <message> <source>Sent transaction</source> <translation>Verzonden transactie</translation> </message> <message> <source>Incoming transaction</source> <translation>Binnenkomende transactie</translation> </message> <message> <source>Date: %1 Amount: %2 Type: %3 Address: %4 </source> <translation>Datum: %1 Bedrag: %2 Type: %3 Adres: %4 </translation> </message> <message> <source>Wallet is &lt;b&gt;encrypted&lt;/b&gt; and currently &lt;b&gt;unlocked for block minting only&lt;/b&gt;</source> <translation>Portemonnee is &lt;b&gt;versleuteld&lt;/b&gt; en momenteel &lt;b&gt;geopend om blokken te minten&lt;/b&gt;</translation> </message> <message> <source>Wallet is &lt;b&gt;encrypted&lt;/b&gt; and currently &lt;b&gt;unlocked&lt;/b&gt;</source> <translation>Portemonnee is &lt;b&gt;versleuteld&lt;/b&gt; en momenteel &lt;b&gt;geopend&lt;/b&gt;</translation> </message> <message> <source>Wallet is &lt;b&gt;encrypted&lt;/b&gt; and currently &lt;b&gt;locked&lt;/b&gt;</source> <translation>Portemonnee is &lt;b&gt;versleuteld&lt;/b&gt; en momenteel &lt;b&gt;gesloten&lt;/b&gt;</translation> </message> <message> <source>Backup Wallet</source> <translation>Backup Portemonnee</translation> </message> <message> <source>Wallet Data (*.dat)</source> <translation>Portemonnee-data (*.dat)</translation> </message> <message> <source>Backup Failed</source> <translation>Backup Mislukt</translation> </message> <message> <source>There was an error trying to save the wallet data to the new location.</source> <translation>Er is een fout opgetreden bij het wegschrijven van de portemonnee-data naar de nieuwe locatie.</translation> </message> <message> <source>A fatal error occurred. Lambocoin can no longer continue safely and will quit.</source> <translation>Een fatale fout heeft plaatsgevonden. Lambocoin kan niet langer veilig doorgaan en zal afsluiten.</translation> </message> </context> <context> <name>CoinControlDialog</name> <message> <source>Coin Control</source> <translation>Munt Controle</translation> </message> <message> <source>Quantity:</source> <translation>Aantal:</translation> </message> <message> <source>0</source> <translation>0</translation> </message> <message> <source>Bytes:</source> <translation>Bytes:</translation> </message> <message> <source>Amount:</source> <translation>Bedrag:</translation> </message> <message> <source>0.00 BTC</source> <translation>123.456 BTC {0.00 ?}</translation> </message> <message> <source>Priority:</source> <translation>Prioriteit:</translation> </message> <message> <source>Fee:</source> <translation>Transactiekosten:</translation> </message> <message> <source>Low Output:</source> <translation>Kopieer lage uitvoer</translation> </message> <message> <source>no</source> <translation>nee</translation> </message> <message> <source>After Fee:</source> <translation>Na aftrek kosten:</translation> </message> <message> <source>Change:</source> <translation>Teruggave:</translation> </message> <message> <source>(un)select all</source> <translation>Alles (de)selecteren</translation> </message> <message> <source>Tree mode</source> <translation>Toon boomstructuur</translation> </message> <message> <source>List mode</source> <translation>Lijst modus</translation> </message> <message> <source>Amount</source> <translation>Bedrag</translation> </message> <message> <source>Address</source> <translation>Adres</translation> </message> <message> <source>Date</source> <translation>Datum</translation> </message> <message> <source>Confirmations</source> <translation>Bevestigingen</translation> </message> <message> <source>Confirmed</source> <translation>Bevestigd</translation> </message> <message> <source>Priority</source> <translation>Prioriteit</translation> </message> <message> <source>Copy address</source> <translation>Kopieer adres</translation> </message> <message> <source>Copy label</source> <translation>Kopieer label</translation> </message> <message> <source>Copy amount</source> <translation>Kopieer bedrag</translation> </message> <message> <source>Copy transaction ID</source> <translation>Kopieer transactie ID</translation> </message> <message> <source>Copy quantity</source> <translation>Kopieer aantal</translation> </message> <message> <source>Copy fee</source> <translation>Kopieer kosten</translation> </message> <message> <source>Copy after fee</source> <translation>Kopieer na kosten</translation> </message> <message> <source>Copy bytes</source> <translation>Kopieer bytes</translation> </message> <message> <source>Copy priority</source> <translation>Kopieer prioriteit</translation> </message> <message> <source>Copy low output</source> <translation>Kopieer lage uitvoer</translation> </message> <message> <source>Copy change</source> <translation>Kopieer teruggave</translation> </message> <message> <source>highest</source> <translation>hoogste</translation> </message> <message> <source>high</source> <translation>Hoogste</translation> </message> <message> <source>medium-high</source> <translation>medium-hoog</translation> </message> <message> <source>medium</source> <translation>medium</translation> </message> <message> <source>low-medium</source> <translation>laag-medium</translation> </message> <message> <source>low</source> <translation>laag</translation> </message> <message> <source>lowest</source> <translation>laagste</translation> </message> <message> <source>DUST</source> <translation>STOF</translation> </message> <message> <source>yes</source> <translation>ja</translation> </message> <message> <source>(no label)</source> <translation>(geen label)</translation> </message> <message> <source>change from %1 (%2)</source> <translation>gewijzigd van %1 (%2)</translation> </message> <message> <source>(change)</source> <translation>(wijzig)</translation> </message> </context> <context> <name>DisplayOptionsPage</name> <message> <source>&amp;Unit to show amounts in: </source> <translation>&amp;Eenheid om bedrag in te tonen:</translation> </message> <message> <source>Choose the default subdivision unit to show in the interface, and when sending coins</source> <translation>Kies de standaard onderverdelingseenheid om weer te geven in uw programma, en voor het versturen van munten</translation> </message> <message> <source>&amp;Display addresses in transaction list</source> <translation>Toon adressen in transactielijst</translation> </message> <message> <source>Whether to show Lambocoin addresses in the transaction list</source> <translation>Toon Lambocoinadressen in transactielijst</translation> </message> <message> <source>Display coin control features (experts only!)</source> <translation>Laat muntcontrole functies zien (alleen voor experts!)</translation> </message> <message> <source>Whether to show coin control features or not</source> <translation>Munt controle mogelijkheden of niet</translation> </message> <message> <source>Warning</source> <translation>Waarschuwing</translation> </message> </context> <context> <name>EditAddressDialog</name> <message> <source>Edit Address</source> <translation>Bewerk Adres</translation> </message> <message> <source>&amp;Label</source> <translation>&amp;Label</translation> </message> <message> <source>The label associated with this address book entry</source> <translation>Het label dat geassocieerd is met dit adres</translation> </message> <message> <source>&amp;Address</source> <translation>&amp;Adres</translation> </message> <message> <source>The address associated with this address book entry. This can only be modified for sending addresses.</source> <translation>Het adres dat geassocieerd is met deze adresboek-opgave. Dit kan alleen worden veranderd voor zend-adressen.</translation> </message> <message> <source>New receiving address</source> <translation>Nieuw ontvangstadres</translation> </message> <message> <source>New sending address</source> <translation>Nieuw adres om naar te versturen</translation> </message> <message> <source>Edit receiving address</source> <translation>Bewerk ontvangstadres</translation> </message> <message> <source>Edit sending address</source> <translation>Bewerk verzendadres</translation> </message> <message> <source>The entered address "%1" is already in the address book.</source> <translation>Het opgegeven adres "%1" bestaat al in uw adresboek.</translation> </message> <message> <source>The entered address "%1" is not a valid Lambocoin address.</source> <translation>Het ingevoerde adres "%1" is geen geldig Lambocoin adres.</translation> </message> <message> <source>Could not unlock wallet.</source> <translation>Kon de portemonnee niet openen.</translation> </message> <message> <source>New key generation failed.</source> <translation>Genereren nieuwe sleutel mislukt.</translation> </message> </context> <context> <name>GUIUtil::HelpMessageBox</name> </context> <context> <name>MainOptionsPage</name> <message> <source>Detach block and address databases at shutdown. This means they can be moved to another data directory, but it slows down shutdown. The wallet is always detached.</source> <translation>Ontkoppel blok en adres database tijdens afsluiten. Dit betekent dat ze kunnen worden verplaatst naar een andere bestandslokatie, maar het afsluiten is daardoor langzamer. De portomonnee is altijd ontkoppeld.</translation> </message> </context> <context> <name>MintingTableModel</name> <message> <source>Transaction</source> <translation>Transactie</translation> </message> <message> <source>Address</source> <translation>Adres</translation> </message> <message> <source>Age</source> <translation>Leeftijd</translation> </message> <message> <source>Balance</source> <translation>Balans</translation> </message> <message> <source>minutes</source> <translation>minuten</translation> </message> <message> <source>hours</source> <translation>uren</translation> </message> <message> <source>days</source> <translation>dagen</translation> </message> </context> <context> <name>MintingView</name> <message> <source>10 min</source> <translation>10 min</translation> </message> <message> <source>24 hours</source> <translation>24 uur</translation> </message> <message> <source>30 days</source> <translation>30 dagen</translation> </message> <message> <source>90 days</source> <translation>90 dagen</translation> </message> <message> <source>Comma separated file (*.csv)</source> <translation>Kommagescheiden bestand (*.csv)</translation> </message> <message> <source>Address</source> <translation>Adres</translation> </message> <message> <source>Transaction</source> <translation>Transactie</translation> </message> <message> <source>Age</source> <translation>Leeftijd</translation> </message> <message> <source>Balance</source> <translation>Balans</translation> </message> <message> <source>Error exporting</source> <translation>Fout bij exporteren</translation> </message> <message> <source>Could not write to file %1.</source> <translation>Kon niet schrijven naar bestand %1.</translation> </message> </context> <context> <name>MultisigAddressEntry</name> <message> <source>Form</source> <translation>Vorm</translation> </message> <message> <source>Alt+P</source> <translation>Alt+P</translation> </message> <message> <source>&amp;Address:</source> <translation>&amp;Adres</translation> </message> <message> <source>Choose address from address book</source> <translation>Kies adres uit adresboek</translation> </message> <message> <source>Alt+A</source> <translation>Alt+A</translation> </message> <message> <source>Label:</source> <translation>Label:</translation> </message> </context> <context> <name>MultisigDialog</name> <message> <source>Clear all</source> <translation>Verwijder alles</translation> </message> <message> <source>Fee:</source> <translation>Transactiekosten:</translation> </message> <message> <source>Paste address from clipboard</source> <translation>Plak adres vanuit klembord</translation> </message> <message> <source>Alt+P</source> <translation>Alt+P</translation> </message> </context> <context> <name>MultisigInputEntry</name> <message> <source>Form</source> <translation>Vorm</translation> </message> <message> <source>Alt+P</source> <translation>Alt+P</translation> </message> <message> <source>Alt+A</source> <translation>Alt+A</translation> </message> </context> <context> <name>NetworkOptionsPage</name> <message> <source>Network</source> <translation>Netwerk</translation> </message> </context> <context> <name>OptionsDialog</name> <message> <source>Options</source> <translation>Opties</translation> </message> </context> <context> <name>OverviewPage</name> <message> <source>Form</source> <translation>Vorm</translation> </message> <message> <source>Balance:</source> <translation>Saldo:</translation> </message> <message> <source>Number of transactions:</source> <translation>Aantal transacties:</translation> </message> <message> <source>Unconfirmed:</source> <translation>Onbevestigd:</translation> </message> <message> <source>Stake:</source> <translation>Inzet:</translation> </message> <message> <source>Wallet</source> <translation>Portemonnee</translation> </message> <message> <source>&lt;b&gt;Recent transactions&lt;/b&gt;</source> <translation>&lt;b&gt;Recente transacties&lt;/b&gt;</translation> </message> <message> <source>Your current balance</source> <translation>Uw huidige saldo</translation> </message> <message> <source>Your current stake</source> <translation>Huidige inzet</translation> </message> <message> <source>Total of transactions that have yet to be confirmed, and do not yet count toward the current balance</source> <translation>Totaal aantal transacties dat nog moet worden bevestigd, en nog niet is meegeteld in uw huidige saldo </translation> </message> <message> <source>Total number of transactions in wallet</source> <translation>Totaal aantal transacties in uw portemonnee</translation> </message> </context> <context> <name>QRCodeDialog</name> <message> <source>QR Code</source> <translation>QR-code</translation> </message> <message> <source>Request Payment</source> <translation>Vraag betaling aan</translation> </message> <message> <source>Amount:</source> <translation>Bedrag:</translation> </message> <message> <source>Label:</source> <translation>Label:</translation> </message> <message> <source>Message:</source> <translation>Bericht:</translation> </message> <message> <source>&amp;Save As...</source> <translation>&amp;Opslaan Als...</translation> </message> <message> <source>Error encoding URI into QR Code.</source> <translation>Fout in codering URI naar QR-code</translation> </message> <message> <source>Resulting URI too long, try to reduce the text for label / message.</source> <translation>Resultaat URI te lang, probeer de tekst in te korten.</translation> </message> <message> <source>PNG Images (*.png)</source> <translation>PNG-Afbeeldingen (*.png)</translation> </message> </context> <context> <name>RPCConsole</name> <message> <source>Client name</source> <translation>Client naam</translation> </message> <message> <source>N/A</source> <translation>N.v.t.</translation> </message> <message> <source>Client version</source> <translation>Client versie</translation> </message> <message> <source>Network</source> <translation>Netwerk</translation> </message> <message> <source>Number of connections</source> <translation>Aantal connecties</translation> </message> <message> <source>On testnet</source> <translation>Op testnetwerk</translation> </message> <message> <source>Block chain</source> <translation>Blokkenketen</translation> </message> <message> <source>Current number of blocks</source> <translation>Huidig aantal blokken</translation> </message> <message> <source>Estimated total blocks</source> <translation>Geschat aantal blokken</translation> </message> <message> <source>Last block time</source> <translation>Laaste bloktijd</translation> </message> <message> <source>Build date</source> <translation>Bouwdatum</translation> </message> <message> <source>Clear console</source> <translation>Console opschonen</translation> </message> <message> <source>Welcome to the Lambocoin RPC console.&lt;br&gt;Use up and down arrows to navigate history, and &lt;b&gt;Ctrl-L&lt;/b&gt; to clear screen.&lt;br&gt;Type &lt;b&gt;help&lt;/b&gt; for an overview of available commands.</source> <translation>Welkom bij de Lambocoin RPC console. &lt;br&gt;Gebruik pijltjes naar boven en naar beneden om de geschiedenis te navigeren, en &lt;b&gt;Ctrl-L&lt;/b&gt; om het scherm te wissen.&lt;br&gt;Typ &lt;b&gt;help&lt;/b&gt; voor een overzicht met commandos.</translation> </message> </context> <context> <name>SendCoinsDialog</name> <message> <source>Send Coins</source> <translation>Verstuur munten</translation> </message> <message> <source>Coin Control Features</source> <translation>Munt controle opties</translation> </message> <message> <source>Inputs...</source> <translation>Toevoer...</translation> </message> <message> <source>automatically selected</source> <translation>automatisch geselecteerd</translation> </message> <message> <source>Insufficient funds!</source> <translation>Onvoldoende fondsen!</translation> </message> <message> <source>Quantity:</source> <translation>Aantal:</translation> </message> <message> <source>0</source> <translation>0</translation> </message> <message> <source>Bytes:</source> <translation>Bytes:</translation> </message> <message> <source>Amount:</source> <translation>Bedrag:</translation> </message> <message> <source>0.00 BTC</source> <translation>123.456 BTC {0.00 ?}</translation> </message> <message> <source>Priority:</source> <translation>Prioriteit:</translation> </message> <message> <source>medium</source> <translation>medium</translation> </message> <message> <source>Fee:</source> <translation>Transactiekosten:</translation> </message> <message> <source>Low Output:</source> <translation>Kopieer lage uitvoer</translation> </message> <message> <source>no</source> <translation>nee</translation> </message> <message> <source>After Fee:</source> <translation>Na aftrek kosten:</translation> </message> <message> <source>Change</source> <translation>Teruggave</translation> </message> <message> <source>custom change address</source> <translation>zelfopgegeven teruggaveadres</translation> </message> <message> <source>Send to multiple recipients at once</source> <translation>Verstuur aan verschillende ontvangers tegelijkertijd</translation> </message> <message> <source>Remove all transaction fields</source> <translation>Verwijder alle transactievelden</translation> </message> <message> <source>Balance:</source> <translation>Saldo:</translation> </message> <message> <source>123.456 BTC</source> <translation>123.456 BTC</translation> </message> <message> <source>Confirm the send action</source> <translation>Bevestig de verstuuractie</translation> </message> <message> <source>&amp;Send</source> <translation>&amp;Verstuur</translation> </message> <message> <source>Copy quantity</source> <translation>Kopieer aantal</translation> </message> <message> <source>Copy amount</source> <translation>Kopieer bedrag</translation> </message> <message> <source>Copy fee</source> <translation>Kopieer kosten</translation> </message> <message> <source>Copy after fee</source> <translation>Kopieer na kosten</translation> </message> <message> <source>Copy bytes</source> <translation>Kopieer bytes</translation> </message> <message> <source>Copy priority</source> <translation>Kopieer prioriteit</translation> </message> <message> <source>Copy low output</source> <translation>Kopieer lage uitvoer</translation> </message> <message> <source>Copy change</source> <translation>Kopieer teruggave</translation> </message> <message> <source>&lt;b&gt;%1&lt;/b&gt; to %2 (%3)</source> <translation>&lt;b&gt;%1&lt;/b&gt; aan %2 (%3)</translation> </message> <message> <source>Confirm send coins</source> <translation>Bevestig versturen munten</translation> </message> <message> <source>Are you sure you want to send %1?</source> <translation>Weet u zeker dat u %1 wil versturen?</translation> </message> <message> <source> and </source> <translation> en </translation> </message> <message> <source>The amount to pay must be at least one cent (0.01).</source> <translation>Het te betalen bedrag moet minimaal een cent zijn (0.01).</translation> </message> <message> <source>Warning: Invalid Lambocoin address</source> <translation>Waarschuwing: Ongeldig Lambocoin adres</translation> </message> <message> <source>Warning: Unknown change address</source> <translation>Waarschuwing: onbekend teruggave adres</translation> </message> <message> <source>(no label)</source> <translation>(geen label)</translation> </message> <message> <source>Enter a Lambocoin address</source> <translation>Voer een Lambocoin adres in</translation> </message> </context> <context> <name>SendCoinsEntry</name> <message> <source>Form</source> <translation>Vorm</translation> </message> <message> <source>A&amp;mount:</source> <translation>Bedra&amp;g:</translation> </message> <message> <source>Pay &amp;To:</source> <translation>Betaal &amp;Aan:</translation> </message> <message> <source>Enter a label for this address to add it to your address book</source> <translation>Vul een label in voor dit adres om het toe te voegen aan uw adresboek</translation> </message> <message> <source>&amp;Label:</source> <translation>&amp;Label:</translation> </message> <message> <source>The address to send the payment to</source> <translation>Het verzendadres voor de betaling</translation> </message> <message> <source>Choose address from address book</source> <translation>Kies adres uit adresboek</translation> </message> <message> <source>Alt+A</source> <translation>Alt+A</translation> </message> <message> <source>Paste address from clipboard</source> <translation>Plak adres vanuit klembord</translation> </message> <message> <source>Alt+P</source> <translation>Alt+P</translation> </message> <message> <source>Remove this recipient</source> <translation>Verwijder deze ontvanger</translation> </message> </context> <context> <name>SignVerifyMessageDialog</name> <message> <source>Signatures - Sign / Verify a Message</source> <translation>Ondertekeningen - Onderteken / verifieer een bericht</translation> </message> <message> <source>&amp;Sign Message</source> <translation>&amp;Onderteken Bericht</translation> </message> <message> <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>U kunt berichten ondertekenen met een van uw adressen om te bewijzen dat u dit adres bezit. Pas op dat u geen onduidelijke dingen ondertekent, want phishingaanvallen zouden u voor de gek kunnen houden om zo uw identiteit te stelen. Onderteken alleen berichten waarmee u het volledig eens bent.</translation> </message> <message> <source>The address to sign the message with</source> <translation>Het ondertekenings adres voor het bericht</translation> </message> <message> <source>Choose previously used address</source> <translation>Kies eerder gebruikt adres</translation> </message> <message> <source>Alt+A</source> <translation>Alt+A</translation> </message> <message> <source>Paste address from clipboard</source> <translation>Plak adres vanuit klembord</translation> </message> <message> <source>Alt+P</source> <translation>Alt+P</translation> </message> <message> <source>Enter the message you want to sign here</source> <translation>Typ hier het bericht dat u wilt ondertekenen</translation> </message> <message> <source>Signature</source> <translation>Ondertekening</translation> </message> <message> <source>Copy the current signature to the system clipboard</source> <translation>Kopieer de huidige onderteking naar het systeem klembord</translation> </message> <message> <source>Sign the message to prove you own this Lambocoin address</source> <translation>Bewijs dat je dit Lambocoin adres bezit door het te ondertekenen </translation> </message> <message> <source>Sign &amp;Message</source> <translation>Onderteken &amp;Bericht</translation> </message> <message> <source>Reset all sign message fields</source> <translation>Herinitialiseer alle ondertekende bericht velden</translation> </message> <message> <source>Clear &amp;All</source> <translation>&amp;Alles wissen</translation> </message> <message> <source>&amp;Verify Message</source> <translation>&amp;Verifieer bericht</translation> </message> <message> <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>Voer hieronder het ondertekeningsadres in, het bericht (vergeet niet precies alle regelafbrekingen, spaties, tabulaties, etc. in te voeren) en ondertekening om het bericht te verifieren. Wees voorzichtig om verder te lezen waar de tekst niet deel uitmaakt van het ondertekende bericht, dit om te voorkomen dat je verleid wordt door een man-in-het-midden aanval.</translation> </message> <message> <source>The address the message was signed with</source> <translation>Het adres waarmee het bericht getekend was</translation> </message> <message> <source>Verify the message to ensure it was signed with the specified Lambocoin address</source> <translation>Verifieer het bericht om vast te stellen dat het bericht ondertekend was met het gespecificeerde Lambocoin adres</translation> </message> <message> <source>Verify &amp;Message</source> <translation>&amp;Verifieer bericht</translation> </message> <message> <source>Reset all verify message fields</source> <translation>Herinitialiseer alle geverifieerde bericht velden</translation> </message> <message> <source>Click "Sign Message" to generate signature</source> <translation>Klik 'Onderteken bericht' om te ondertekenen</translation> </message> <message> <source>Enter the signature of the message</source> <translation>Voer de ondertekening in voor het bericht</translation> </message> <message> <source>Enter a Lambocoin address</source> <translation>Voer een Lambocoin adres in</translation> </message> <message> <source>The entered address is invalid.</source> <translation>Het ingevoerde adres is onjuist</translation> </message> <message> <source>Please check the address and try again.</source> <translation>Controleer het adres and probeer opnieuw.</translation> </message> <message> <source>The entered address does not refer to a key.</source> <translation>Het ingevoerde adres refereert niet naar een sleutel</translation> </message> <message> <source>Wallet unlock was cancelled.</source> <translation>Portemonnee ontsleuteling is afgebroken.</translation> </message> <message> <source>Private key for the entered address is not available.</source> <translation>Geheime sleutel voor het ingevoerde adres is niet beschikbaar.</translation> </message> <message> <source>Message signing failed.</source> <translation>Bericht ondertekening mislukt.</translation> </message> <message> <source>Message signed.</source> <translation>Bericht ontedertekend.</translation> </message> <message> <source>The signature could not be decoded.</source> <translation>De ondertekeing kan niet worden ontcijferd.</translation> </message> <message> <source>Please check the signature and try again.</source> <translation>Controleer de ondertekening and probeer opnieuw.</translation> </message> <message> <source>The signature did not match the message digest.</source> <translation>De ondertekening komt niet overeen met de bericht samenvatting.</translation> </message> <message> <source>Message verification failed.</source> <translation>Bericht verficatie mislukt.</translation> </message> <message> <source>Message verified.</source> <translation>Bericht geverifieerd.</translation> </message> </context> <context> <name>SplashScreen</name> <message> <source>[testnet]</source> <translation>[testnetwerk]</translation> </message> </context> <context> <name>TransactionDesc</name> <message> <source>Open until %1</source> <translation>Open tot %1</translation> </message> <message> <source>%1/unconfirmed</source> <translation>%1/onbevestigd</translation> </message> <message> <source>%1 confirmations</source> <translation>%1 bevestigingen</translation> </message> <message> <source>Date</source> <translation>Datum</translation> </message> <message> <source>Transaction</source> <translation>Transactie</translation> </message> <message> <source>Amount</source> <translation>Bedrag</translation> </message> <message> <source>, has not been successfully broadcast yet</source> <translation>, is nog niet succesvol uitgezonden</translation> </message> <message> <source>unknown</source> <translation>onbekend</translation> </message> </context> <context> <name>TransactionDescDialog</name> <message> <source>Transaction details</source> <translation>Transactiedetails</translation> </message> <message> <source>This pane shows a detailed description of the transaction</source> <translation>Dit venster laat een uitgebreide beschrijving van de transactie zien</translation> </message> </context> <context> <name>TransactionTableModel</name> <message> <source>Date</source> <translation>Datum</translation> </message> <message> <source>Type</source> <translation>Type</translation> </message> <message> <source>Address</source> <translation>Adres</translation> </message> <message> <source>Amount</source> <translation>Bedrag</translation> </message> <message numerus="yes"> <source>Open for %n block(s)</source> <translation><numerusform>Open gedurende %n blok</numerusform><numerusform>Open gedurende %n blokken</numerusform></translation> </message> <message> <source>Open until %1</source> <translation>Open tot %1</translation> </message> <message> <source>Offline (%1 confirmations)</source> <translation>Niet verbonden (%1 bevestigingen)</translation> </message> <message> <source>Unconfirmed (%1 of %2 confirmations)</source> <translation>Onbevestigd (%1 van %2 bevestigd)</translation> </message> <message> <source>Confirmed (%1 confirmations)</source> <translation>Bevestigd (%1 bevestigingen)</translation> </message> <message numerus="yes"> <source>Mined balance will be available in %n more blocks</source> <translation><numerusform>Ontgonnen saldo komt beschikbaar na %n blok</numerusform><numerusform>Ontgonnen saldo komt beschikbaar na %n blokken</numerusform></translation> </message> <message> <source>This block was not received by any other nodes and will probably not be accepted!</source> <translation>Dit blok is niet ontvangen bij andere nodes en zal waarschijnlijk niet worden geaccepteerd!</translation> </message> <message> <source>Generated but not accepted</source> <translation>Gegenereerd maar niet geaccepteerd</translation> </message> <message> <source>Received with</source> <translation>Ontvangen met</translation> </message> <message> <source>Received from</source> <translation>Ontvangen van</translation> </message> <message> <source>Sent to</source> <translation>Verzonden aan</translation> </message> <message> <source>Payment to yourself</source> <translation>Betaling aan uzelf</translation> </message> <message> <source>Mined</source> <translation>Ontgonnen</translation> </message> <message> <source>Mint by stake</source> <translation>Minten met inzet</translation> </message> <message> <source>(n/a)</source> <translation>(nvt)</translation> </message> <message> <source>Transaction status. Hover over this field to show number of confirmations.</source> <translation>Transactiestatus. Houd de muiscursor boven dit veld om het aantal bevestigingen te laten zien.</translation> </message> <message> <source>Date and time that the transaction was received.</source> <translation>Datum en tijd waarop deze transactie is ontvangen.</translation> </message> <message> <source>Type of transaction.</source> <translation>Type transactie.</translation> </message> <message> <source>Destination address of transaction.</source> <translation>Ontvangend adres van transactie</translation> </message> <message> <source>Amount removed from or added to balance.</source> <translation>Bedrag verwijderd van of toegevoegd aan saldo</translation> </message> </context> <context> <name>TransactionView</name> <message> <source>All</source> <translation>Alles</translation> </message> <message> <source>Today</source> <translation>Vandaag</translation> </message> <message> <source>This week</source> <translation>Deze week</translation> </message> <message> <source>This month</source> <translation>Deze maand</translation> </message> <message> <source>Last month</source> <translation>Vorige maand</translation> </message> <message> <source>This year</source> <translation>Dit jaar</translation> </message> <message> <source>Range...</source> <translation>Bereik...</translation> </message> <message> <source>Received with</source> <translation>Ontvangen met</translation> </message> <message> <source>Sent to</source> <translation>Verzonden aan</translation> </message> <message> <source>To yourself</source> <translation>Aan uzelf</translation> </message> <message> <source>Mined</source> <translation>Ontgonnen</translation> </message> <message> <source>Mint by stake</source> <translation>Minten met inzet</translation> </message> <message> <source>Other</source> <translation>Anders</translation> </message> <message> <source>Enter address or label to search</source> <translation>Vul adres of label in om te zoeken</translation> </message> <message> <source>Min amount</source> <translation>Min. bedrag</translation> </message> <message> <source>Copy address</source> <translation>Kopieer adres</translation> </message> <message> <source>Copy label</source> <translation>Kopieer label</translation> </message> <message> <source>Copy amount</source> <translation>Kopieer bedrag</translation> </message> <message> <source>Edit label</source> <translation>Bewerk label</translation> </message> <message> <source>Export Transaction Data</source> <translation>Exporteer transactiegegevens</translation> </message> <message> <source>Comma separated file (*.csv)</source> <translation>Kommagescheiden bestand (*.csv)</translation> </message> <message> <source>Confirmed</source> <translation>Bevestigd</translation> </message> <message> <source>Date</source> <translation>Datum</translation> </message> <message> <source>Type</source> <translation>Type</translation> </message> <message> <source>Label</source> <translation>Label</translation> </message> <message> <source>Address</source> <translation>Adres</translation> </message> <message> <source>Amount</source> <translation>Bedrag</translation> </message> <message> <source>ID</source> <translation>ID</translation> </message> <message> <source>Error exporting</source> <translation>Fout bij exporteren</translation> </message> <message> <source>Could not write to file %1.</source> <translation>Kon niet schrijven naar bestand %1.</translation> </message> <message> <source>Range:</source> <translation>Bereik:</translation> </message> <message> <source>to</source> <translation>naar</translation> </message> </context> <context> <name>WalletModel</name> <message> <source>Sending...</source> <translation>Versturen...</translation> </message> </context> <context> <name>WindowOptionsPage</name> </context> <context> <name>bitcoin-core</name> <message> <source>Usage:</source> <translation>Gebruik:</translation> </message> <message> <source>Lambocoin version</source> <translation>Lambocoin versie</translation> </message> <message> <source>List commands</source> <translation>List van commando's </translation> </message> <message> <source>Get help for a command</source> <translation>Toon hulp voor een commando </translation> </message> <message> <source>Options:</source> <translation>Opties: </translation> </message> <message> <source>Specify configuration file (default: Lambocoin.conf)</source> <translation>Configuratiebestand specificeren (standaard: Lambocoin.conf)</translation> </message> <message> <source>Specify pid file (default: Lambocoind.pid)</source> <translation>Specifieer pid-bestand (standaard: Lambocoind.pid) </translation> </message> <message> <source>Generate coins</source> <translation>Genereer munten </translation> </message> <message> <source>Don't generate coins</source> <translation>Genereer geen munten</translation> </message> <message> <source>Specify data directory</source> <translation>Stel datamap in </translation> </message> <message> <source>Set database cache size in megabytes (default: 25)</source> <translation>Database cache instellen in Mb (standaard: 25)</translation> </message> <message> <source>Set database disk log size in megabytes (default: 100)</source> <translation>Database logbestandgrootte instellen in Mb (standaard: 100)</translation> </message> <message> <source>Specify connection timeout (in milliseconds)</source> <translation>Specificeer de time-out tijd (in milliseconden) </translation> </message> <message> <source>Maintain at most &lt;n&gt; connections to peers (default: 125)</source> <translation>Onderhoud maximaal &lt;n&gt; verbindingen naar peers (standaard: 125)</translation> </message> <message> <source>Add a node to connect to and attempt to keep the connection open</source> <translation>Maak connectie met een node en houd deze open</translation> </message> <message> <source>Connect only to the specified node</source> <translation>Verbind alleen met deze node </translation> </message> <message> <source>Accept connections from outside (default: 1)</source> <translation>Connecties van buiten accepteren (standaard: 1)</translation> </message> <message> <source>Find peers using DNS lookup (default: 1)</source> <translation>Zoek anderen via DNS (standaard: 1)</translation> </message> <message> <source>Threshold for disconnecting misbehaving peers (default: 100)</source> <translation>Drempel om verbinding te verbreken naar zich misdragende peers (standaard: 100)</translation> </message> <message> <source>Number of seconds to keep misbehaving peers from reconnecting (default: 86400)</source> <translation>Aantal seconden dat zich misdragende peers niet opnieuw mogen verbinden (standaard: 86400)</translation> </message> <message> <source>Maximum per-connection receive buffer, &lt;n&gt;*1000 bytes (default: 10000)</source> <translation>Maximale ontvangstbuffer per connectie, &lt;n&gt;*1000 bytes (standaard: 10000)</translation> </message> <message> <source>Maximum per-connection send buffer, &lt;n&gt;*1000 bytes (default: 10000)</source> <translation>Maximale zendbuffer per connectie, &lt;n&gt;*1000 bytes (standaard: 10000)</translation> </message> <message> <source>Use Universal Plug and Play to map the listening port (default: 1)</source> <translation>Gebruik uPNP om de netwerk poort in te delen (standaard 1)</translation> </message> <message> <source>Use Universal Plug and Play to map the listening port (default: 0)</source> <translation>Gebruik uPNP om de netwerkpoort in te delen (standaard 0)</translation> </message> <message> <source>Fee per KB to add to transactions you send</source> <translation>Kosten per kB voor te versturen transacties</translation> </message> <message> <source>Run in the background as a daemon and accept commands</source> <translation>Draai in de achtergrond als daemon en aanvaard commando's </translation> </message> <message> <source>Use the test network</source> <translation>Gebruik het testnetwerk </translation> </message> <message> <source>Prepend debug output with timestamp</source> <translation>Voorzie de debuggingsuitvoer van een tijdsaanduiding</translation> </message> <message> <source>Send trace/debug info to console instead of debug.log file</source> <translation>Stuur opsporing/debug-info naar de console in plaats van het debug.log bestand</translation> </message> <message> <source>Send trace/debug info to debugger</source> <translation>Stuur opsporings/debug-info naar debugger</translation> </message> <message> <source>Username for JSON-RPC connections</source> <translation>Gebruikersnaam voor JSON-RPC verbindingen </translation> </message> <message> <source>Password for JSON-RPC connections</source> <translation>Wachtwoord voor JSON-RPC verbindingen </translation> </message> <message> <source>Allow JSON-RPC connections from specified IP address</source> <translation>Sta JSON-RPC verbindingen van opgegeven IP adres toe </translation> </message> <message> <source>Send commands to node running on &lt;ip&gt; (default: 127.0.0.1)</source> <translation>Verstuur commando's naar proces dat op &lt;ip&gt; draait (standaard: 127.0.0.1) </translation> </message> <message> <source>Execute command when the best block changes (%s in cmd is replaced by block hash)</source> <translation>Voer commando uit indien het hoogste blok verandert (%s in cmd is herplaats met blok hash)</translation> </message> <message> <source>Upgrade wallet to latest format</source> <translation>Opwaardeer portemonnee naar laatste formaat</translation> </message> <message> <source>Set key pool size to &lt;n&gt; (default: 100)</source> <translation>Stel sleutelpoelgrootte in op &lt;n&gt; (standaard: 100) </translation> </message> <message> <source>Rescan the block chain for missing wallet transactions</source> <translation>Doorzoek de blokkenketen op ontbrekende portemonnee-transacties</translation> </message> <message> <source>How many blocks to check at startup (default: 2500, 0 = all)</source> <translation>Aantal blokken bij opstarten controleren (standaard: 2500, 0 = alle)</translation> </message> <message> <source>How thorough the block verification is (0-6, default: 1)</source> <translation>Grondigheid blok verificatie (0-6, standaard: 1)</translation> </message> <message> <source>Use OpenSSL (https) for JSON-RPC connections</source> <translation>Gebruik OpenSSL (https) voor JSON-RPC verbindingen </translation> </message> <message> <source>Server certificate file (default: server.cert)</source> <translation>Certificaat-bestand voor server (standaard: server.cert) </translation> </message> <message> <source>Server private key (default: server.pem)</source> <translation>Geheime sleutel voor server (standaard: server.pem) </translation> </message> <message> <source>Acceptable ciphers (default: TLSv1+HIGH:!SSLv2:!aNULL:!eNULL:!AH:!3DES:@STRENGTH)</source> <translation>Aanvaardbare sleuteltypen (standaard: TLSv1+HIGH:!SSLv2:!aNULL:!eNULL:!AH:!3DES:@STRENGTH)</translation> </message> <message> <source>Cannot obtain a lock on data directory %s. Lambocoin is probably already running.</source> <translation>Blokkeren van data folder %s is niet gelukt. Lambocoin is mogelijk al opgestart.</translation> </message> <message> <source>Lambocoin</source> <translation>Lambocoin</translation> </message> <message> <source>Error loading wallet.dat: Wallet requires newer version of Lambocoin</source> <translation>Fout geconstateerd bij het laden van wallet.dat: Portemonnee vereist een nieuwere versie van Lambocoin</translation> </message> <message> <source>Wallet needed to be rewritten: restart Lambocoin to complete</source> <translation>Portemonnee dient opnieuw bewerkt te worden: start Lambocoin opnieuw op om te voltooien</translation> </message> <message> <source>Warning: Please check that your computer's date and time are correct. If your clock is wrong Lambocoin will not work properly.</source> <translation>Waarschuwing: controleer of de datum en tijd op uw computer correct zijn. Indien uw klok verkeerd staat, zal Lambocoin niet goed werken</translation> </message> <message> <source>Loading addresses...</source> <translation>Adressen aan het laden...</translation> </message> <message> <source>Loading block index...</source> <translation>Blokindex aan het laden...</translation> </message> <message> <source>Error loading blkindex.dat</source> <translation>Fout bij laden blkindex.dat</translation> </message> <message> <source>Loading wallet...</source> <translation>Portemonnee aan het laden...</translation> </message> <message> <source>Error loading wallet.dat: Wallet corrupted</source> <translation>Fout bij laden wallet.dat: Portemonnee corrupt</translation> </message> <message> <source>Error loading wallet.dat</source> <translation>Fout bij laden wallet.dat</translation> </message> <message> <source>Cannot downgrade wallet</source> <translation>Kan portemonnee niet degraderen</translation> </message> <message> <source>Cannot initialize keypool</source> <translation>Kan sleutelpoel niet initaliseren</translation> </message> <message> <source>Cannot write default address</source> <translation>Kan niet schrijven naar standaard adres</translation> </message> <message> <source>Rescanning...</source> <translation>Opnieuw aan het scannen ...</translation> </message> <message> <source>Done loading</source> <translation>Klaar met laden</translation> </message> <message> <source>Warning: -paytxfee is set very high. This is the transaction fee you will pay if you send a transaction.</source> <translation>Waarschuwing: -paytxfee is zeer hoog ingesteld. Dit zijn de transactiekosten die u betaalt bij het versturen van een transactie.</translation> </message> <message> <source>To use the %s option</source> <translation>Gebruik de %s optie</translation> </message> <message> <source>Error</source> <translation>Fout</translation> </message> <message> <source>An error occurred while setting up the RPC port %i for listening: %s</source> <translation>Een fout geconstateerd met het opzetten van RPC port %i om te luisteren: %s</translation> </message> <message> <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>Je moet rpcpassword=&lt;password&gt; in het configuratie bestand instellen: %s Indien het bestand niet bestaat, maak het aan met alleen gebruikers leesrechten op het bestand.</translation> </message> <message> <source>Error: Wallet locked, unable to create transaction </source> <translation>Fout: Portemonnee is gesloten, kan geen nieuwe transactie aanmaken</translation> </message> <message> <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>Fout: Deze transactie vereist minstens %s transactie kosten vanwege het bedrag, moeilijkheid, of recent ontvangen fondsen</translation> </message> <message> <source>Error: Transaction creation failed </source> <translation>Fout: Aanmaak transactie mislukt</translation> </message> <message> <source>Sending...</source> <translation>Versturen...</translation> </message> <message> <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>Fout: De transactie was afgewezen. Dit kan gebeuren als u eerder uitgegeven munten opnieuw wilt versturen, zoals wanneer u een kopie van uw wallet.dat heeft gebruikt en in de kopie deze munten zijn gemarkeerd als uitgegeven, maar in de huidige nog niet.</translation> </message> <message> <source>Invalid amount</source> <translation>Onjuist bedrag</translation> </message> <message> <source>Insufficient funds</source> <translation>Onvoldoende fondsen</translation> </message> </context> </TS>
{'content_hash': 'e67a53e9ce08617135ab53d1810ab78b', 'timestamp': '', 'source': 'github', 'line_count': 1984, 'max_line_length': 396, 'avg_line_length': 36.482358870967744, 'alnum_prop': 0.6512897030988796, 'repo_name': 'LambocoinFoundation/Lambocoin', 'id': '606708bd1411301b8af658afd71f1adb0d717194', 'size': '72381', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'src/qt/locale/paycoin_nl.ts', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'C', 'bytes': '5537'}, {'name': 'C++', 'bytes': '2381407'}, {'name': 'Makefile', 'bytes': '9025'}, {'name': 'NSIS', 'bytes': '6629'}, {'name': 'Objective-C', 'bytes': '858'}, {'name': 'Objective-C++', 'bytes': '3537'}, {'name': 'Python', 'bytes': '54574'}, {'name': 'QMake', 'bytes': '11762'}, {'name': 'Roff', 'bytes': '12841'}, {'name': 'Shell', 'bytes': '5118'}]}
#import <Foundation/Foundation.h> #import <WebDriverAgentLib/FBCommandStatus.h> #import <WebDriverAgentLib/FBResponsePayload.h> #import <WebDriverAgentLib/FBRoute.h> #import <WebDriverAgentLib/FBResponsePayload.h> NS_ASSUME_NONNULL_BEGIN /** Protocol for Classes to declare intent to implement responses to commands */ @protocol FBCommandHandler <NSObject> /** * Should return map of FBRouteCommandHandler block with keys as supported routes * * @return map an NSArray<FBRoute *> of routes. */ + (NSArray *)routes; @optional /** * @return BOOL deciding if class should be added to route handlers automatically, default (if not implemented) is YES */ + (BOOL)shouldRegisterAutomatically; @end NS_ASSUME_NONNULL_END
{'content_hash': '059fc37c5e0ef04073302605c3d61e3a', 'timestamp': '', 'source': 'github', 'line_count': 32, 'max_line_length': 118, 'avg_line_length': 22.84375, 'alnum_prop': 0.7688098495212038, 'repo_name': 'calabash/WebDriverAgent', 'id': 'bde028d68b01d9668b9ea11664fe07bfcf31d522', 'size': '1039', 'binary': False, 'copies': '13', 'ref': 'refs/heads/master', 'path': 'WebDriverAgentLib/Routing/FBCommandHandler.h', 'mode': '33188', 'license': 'bsd-3-clause', 'language': [{'name': 'CSS', 'bytes': '2413'}, {'name': 'HTML', 'bytes': '191'}, {'name': 'JavaScript', 'bytes': '17764'}, {'name': 'Objective-C', 'bytes': '446149'}, {'name': 'Shell', 'bytes': '3516'}]}
package io.budgetapp.configuration; import com.bazaarvoice.dropwizard.assets.AssetsBundleConfiguration; import com.bazaarvoice.dropwizard.assets.AssetsConfiguration; import com.fasterxml.jackson.annotation.JsonProperty; import io.budgetapp.model.Budget; import io.budgetapp.model.Category; import io.dropwizard.Configuration; import io.dropwizard.db.DataSourceFactory; import javax.validation.Valid; import javax.validation.constraints.NotNull; import java.util.ArrayList; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; /** * */ public class AppConfiguration extends Configuration implements AssetsBundleConfiguration { @Valid @NotNull private DataSourceFactory database = new DataSourceFactory(); @Valid @NotNull private final AssetsConfiguration assets = new AssetsConfiguration(); @Valid @NotNull private List<Category> categories = new ArrayList<>(); @Valid @NotNull @JsonProperty("budgets") private Map<String, List<Budget>> budgets = new LinkedHashMap<>(); public DataSourceFactory getDataSourceFactory() { return database; } @Override public AssetsConfiguration getAssetsConfiguration() { return assets; } @JsonProperty("assets") public AssetsConfiguration getAssets() { return assets; } @JsonProperty("database") public void setDatabase(DataSourceFactory database) { this.database = database; } @JsonProperty("categories") public void setCategories(List<Category> categories) { this.categories = categories; } public void setBudgets(Map<String, List<Budget>> budgets) { this.budgets = budgets; } public List<Category> getCategories() { return categories; } public Map<String, List<Budget>> getBudgets() { return budgets; } }
{'content_hash': '6ac792ce4188a0e6b9d778c0cd448972', 'timestamp': '', 'source': 'github', 'line_count': 75, 'max_line_length': 90, 'avg_line_length': 25.0, 'alnum_prop': 0.7168, 'repo_name': 'navneetkarnani/budgetapp', 'id': '1728522cce034a4b84e09529b2528e03d9cc1287', 'size': '1875', 'binary': False, 'copies': '2', 'ref': 'refs/heads/master', 'path': 'src/main/java/io/budgetapp/configuration/AppConfiguration.java', 'mode': '33188', 'license': 'apache-2.0', 'language': [{'name': 'CSS', 'bytes': '86255'}, {'name': 'HTML', 'bytes': '53279'}, {'name': 'Java', 'bytes': '154498'}, {'name': 'JavaScript', 'bytes': '61073'}, {'name': 'Shell', 'bytes': '174'}]}
Usage Examples ============== Pika has various methods of use, between the synchronous BlockingConnection adapter and the various asynchronous connection adapter. The following examples illustrate the various ways that you can use Pika in your projects. Pika有很多种使用方法,包括BlockingConnection适配器和各种异步连接适配器之间。下面的例子说明,你可以在你的项目中使用Pika的各种方法。 .. toctree:: :glob: :maxdepth: 1 examples/using_urlparameters examples/connecting_async examples/blocking_basic_get examples/blocking_consume examples/blocking_consumer_generator examples/comparing_publishing_sync_async examples/blocking_delivery_confirmations examples/blocking_publish_mandatory examples/asynchronous_consumer_example examples/asynchronous_publisher_example examples/twisted_example examples/tornado_consumer
{'content_hash': '784056a4f2ea0648a9a07b9fabd915e1', 'timestamp': '', 'source': 'github', 'line_count': 23, 'max_line_length': 223, 'avg_line_length': 35.04347826086956, 'alnum_prop': 0.8014888337468983, 'repo_name': 'zixiliuyue/pika', 'id': '1505adedff05b78446494407599aca3a2773def9', 'size': '910', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'docs/examples.rst', 'mode': '33188', 'license': 'bsd-3-clause', 'language': [{'name': 'Python', 'bytes': '842302'}]}
## m --- - [Usage](#usage) - [Binding to data](#binding-to-data) - [Using HTML entities](#using-html-entities) - [Accessing the real DOM element](#accessing-the-real-dom-element) - [Persisting config data](#persisting-config-data) - [Destructors](#destructors) - [Persisting DOM elements across route changes](#persisting-dom-elements-across-route-changes) - [SVG](#svg) - [Dealing with focus](#dealing-with-focus) - [Dealing with sorting and deleting in lists](#dealing-with-sorting-and-deleting-in-lists) - [Component shorthand](#component-shorthand) - [Signature](#signature) - [The `config` attribute](#the-config-attribute) --- This is a convenience method to compose virtual elements that can be rendered via [`m.render()`](mithril.render.md). You are encouraged to use CSS selectors to define virtual elements. See "Signature" section for details. --- ### Usage You can use simple tag selectors to make templates resemble HTML: ```javascript m("br"); //yields a virtual element that represents <br> m("div", "Hello"); //yields <div>Hello</div> m("div", {class: "container"}, "Hello"); //yields <div class="container">Hello</div> ``` Note that the output value from `m()` is not an actual DOM element. In order to turn the virtual element into a real DOM element, you must call [`m.render()`](mithril.render.md). ```javascript m.render(document.body, m("br")); //puts a <br> in <body> ``` You can also use more complex CSS selectors: ```javascript m(".container"); //yields <div class="container"></div> m("#layout"); //yields <div id="layout"></div> m("a[name=top]"); //yields <a name="top"></a> m("[contenteditable]"); //yields <div contenteditable></div> m("a#google.external[href='http://google.com']", "Google"); //yields <a id="google" class="external" href="http://google.com">Google</a> ``` Each `m()` call creates a virtual DOM element, that is, a Javascript object that represents a DOM element, and which is eventually converted into one. You can, of course, nest virtual elements: ```javascript m("ul", [ m("li", "item 1"), m("li", "item 2"), ]); /* yields <ul> <li>item 1</li> <li>item 2</li> </ul> */ ``` --- The CSS selector syntax (e.g. `a#google.external[href='http://google.com']`) is meant to be used for declaring static attributes in the element, i.e. attribute values that don't change dynamically when the user interacts with the app. The `attributes` argument (i.e. the second parameter in the `m("div", {class: "container"}, "Hello")` example) is meant to be used for attributes whose values we want to dynamically populate. For example, let's say that you're generating a link from an entry that comes from a web service: ```javascript //assume the variable `link` came from a web service var link = {url: "http://google.com", title: "Google"} m("a", {href: link.url}, link.title); //yields <a href="http://google.com">Google</a> ``` Here's a less trivial example: ```javascript var links = [ {title: "item 1", url: "/item1"}, {title: "item 2", url: "/item2"}, {title: "item 3", url: "/item3"} ]; m.render(document.body, [ m("ul.nav", links.map(function(link) { return m("li", m("a", {href: link.url}, link.title) ); }) ) ]); ``` yields: ```markup <body> <ul class="nav"> <li><a href="/item1">item 1</a></li> <li><a href="/item2">item 2</a></li> <li><a href="/item3">item 3</a></li> </ul> </body> ``` As you can see, flow control is done with vanilla Javascript. This allows the developer to abstract away any aspect of the template at will. --- Note that you can use both Javascript property names and HTML attribute names to set values in the `attributes` argument, but you should pass a value of appropriate type. If an attribute has the same name in Javascript and in HTML, then Mithril assumes you're setting the Javascript property. ```javascript m("div", {class: "widget"}); //yields <div class="widget"></div> m("div", {className: "widget"}); //yields <div class="widget"></div> m("button", {onclick: alert}); //yields <button></button>, which alerts its event argument when clicked //note this uses the Javascript syntax (uppercase "O") for `readonly` //in order to set the boolean javascript property instead of the HTML attribute m("input", {readOnly: true}); //yields <input readonly /> //using the HTML attribute name will call `setAttribute`, which may not be what you want m("input", {readonly: false}); //yields <input readonly="false" />, which is still readonly ``` --- Note that you can use JSON syntax if the attribute name you are setting has non-alphanumeric characters: ```javascript m("div", {"data-index": 1}); //yields <div data-index="1"></div> ``` You can set inline styles like this: ```javascript m("div", {style: {border: "1px solid red"}}); //yields <div style="border:1px solid red;"></div> ``` Note that in order to keep the framework lean, Mithril does not auto-append units like `px` or `%` to any values. Typically, you should not even be using inline styles to begin with (unless you are dynamically changing them). Mithril also does not auto-camel-case CSS properties on inline style attributes, so you should use the Javascript syntax when setting them via Javascript objects: ```javascript m("div", {style: {textAlign: "center"}}); //yields <div style="text-align:center;"></div> m("div", {style: {cssFloat: "left"}}); //yields <div style="float:left;"></div> //this does not work m("div", {style: {"text-align": "center"}}); m("div", {style: {float: "left"}}); ``` You can find the [Javascript syntax for all the CSS rules here](https://developer.mozilla.org/en-US/docs/Web/CSS/CSS_Properties_Reference). You can, however, use CSS syntax when defining style rules as inline strings: ```javascript m("div[style='text-align:center']"); //yields <div style="text-align:center;"></div> ``` One caveat of using the CSS syntax is that it clobbers the `style` attribute in the DOM element on redraws, so this syntax is not appropriate if you need to use it in conjunction with 3rd party tools that modify the element's style outside of Mithril's templates (e.g. via `config`, which is explained below) --- ### Binding to data In order to stay flexible, Mithril doesn't provide helpers for bi-directional bindings out of the box. However, bindings can be implemented easily: ```javascript //a data store var name = m.prop("") //binding the data store in a view m("input", {oninput: m.withAttr("value", name), value: name()}) ``` In the code above, the `oninput` event handler updates the `name` getter-setter, and the Mithril auto-redrawing system redraws the template in order to update the displayed value. You can read more about the [`m.prop` getter-setter utility here](mithril.prop.md) and the [`m.withAttr` event handler factory here](mithril.withAttr.md). You can also [learn how the redrawing system works here](auto-redrawing.md). Note that Mithril always considers the model layer data to be canonical. This means that in the code below, the input on screen will overwritten by the model data any time a redraw happens: ```javascript //note that we are not updating the value of the `name` getter-setter via an event handler //redraws will always overwrite the current UI value with the value of `name()` m("input", {value: name()}) ``` Expressiveness can be achieved using standard refactoring techniques: ```javascript //refactor the binding to a simple helper var binds = function(prop) { return {oninput: m.withAttr("value", prop), value: prop()} } //a data store var name = m.prop("") //binding the data store in a view m("input", binds(name)) ``` Here's an example of a more aggressive refactor: ```javascript //refactor the binding to a simple helper var input = function(prop) { return m("input", {oninput: m.withAttr("value", prop), value: prop()}) } //a data store var name = m.prop("") //binding the data store in a view input(name) ``` Alternatively, you can also explore other techniques in order to achieve better [performance](http://lhorie.github.io/mithril-blog/asymmetrical-data-bindings.html) and [expressiveness](http://lhorie.github.io/mithril-blog/extending-the-view-language.html). --- ### Using HTML entities By default, Mithril escapes HTML strings in order to help prevent XSS attacks. ```javascript m("div", "&times;") //becomes <div>&amp;times;</div> ``` You can unescape trusted HTML strings by using [`m.trust`](mithril.trust.md) ```javascript m("div", m.trust("&times;")) //becomes <div>&times;</div> ``` --- #### Accessing the real DOM element You can define a non-HTML-standard attribute called `config`. This special parameter allows you to call methods on the DOM element after it gets created. This is useful, for example, if you declare a `canvas` element and want to use the Javascript API to draw: ```javascript function draw(element, isInitialized, context) { //don't redraw if we did once already if (isInitialized) return; var ctx = element.getContext("2d"); /* draws stuff */ } var view = [ m("canvas", {config: draw}) ] //this creates the canvas element, and therefore, `isInitialized` is false m.render(document.body, view); //here, isInitialized is `true` m.render(document.body, view); ``` One common way of using `config` is in conjunction with [`m.route`](mithril.route.md), which is an unobtrusive extension to links that allow Mithril's routing system to work transparently regardless of which routing mode is used. ```javascript //this link can use any of Mithril's routing system modes //(i.e. it can use either the hash, the querystring or the pathname as the router implementation) //without needing to hard-code any syntax (`#` or `?`) in the `href` attribute. m("a[href='/dashboard']", {config: m.route}, "Dashboard"); ``` The `config` mechanism can also be used to put focus on form inputs, and call methods that would not be possible to execute via the regular attribute syntax. Also note that the `config` callback only runs after a rendering lifecycle is done. Therefore, you should not use `config` to modify controller and model values, if you expect these changes to render immediately. Changes to controller and model values in this fashion will only render on the next `m.render` or `m.mount` call. You can use this mechanism to attach custom event listeners to controller methods (for example, when integrating with third party libraries), but you are responsible for making sure the integration with Mithril's autoredrawing system is in place. See the [integration guide](integration.md) for more information. You can also use it to attach events to other elements (for example, `window.onresize`), but you should remove such event handlers via `ctx.onunload` to avoid surprises. --- #### Persisting config data The third argument for `config` allows you to map data to a virtual DOM element in a way that persists across redraws. This is useful when a `config` instantiates 3rd party classes and accesses the instance on redraws. The example below shows a contrived redraw counter. In it, the count is stored in the context object and re-accessed on each redraw. ```javascript function alertsRedrawCount(element, isInit, context) { if (!isInit) context.count = 0 alert(++context.count) } m("div", {config: alertsRedrawCount}) ``` --- #### Destructors If the `context` object that is passed to a `config` function has a property called `onunload`, this function will be called when the element gets detached from the document by Mithril's diff engine. This is useful if there are cleanup tasks that need to be run when an element is destroyed (e.g. clearing `setTimeout`'s, etc) ```javascript function unloadable(element, isInit, context) { context.timer = setTimeout(function() { alert("timed out!"); }, 1000); context.onunload = function() { clearTimeout(context.timer); console.log("unloaded the div"); } }; m.render(document, m("div", {config: unloadable})); m.render(document, m("a")); //logs `unloaded the div` and `alert` never gets called ``` --- #### Persisting DOM elements across route changes When using the [router](mithril.route.md), a route change recreates the DOM tree from scratch in order to unload plugins from the previous page. If you want to keep a DOM element intact across a route change, you can set the `retain` flag in the config's context object. In the example below, there are two routes, each of which loads a component when a user navigates to their respective URLs. Both components use a `menu` template, which contains links for navigation between the two components, and an expensive-to-reinitialize element. Setting `context.retain = true` in the element's config function allows the span to stay intact after a route change. ```javascript //a menu template var menu = function() { return m("div", [ m("a[href='/']", {config: m.route}, "Home"), m("a[href='/contact']", {config: m.route}, "Contact"), //an expensive-to-initialize DOM element m("span", {config: persistent}) ]) } //a configuration that persists across route changes function persistent(el, isInit, context) { context.retain = true if (!isInit) { //only runs once, even if you move back and forth between `/` and `/contact` doSomethingExpensive(el) } } //components that use the menu above var Home = { controller: function() {}, view: function() { return m("div", [ menu(), m("h1", "Home") ]) } } var Contact = { view: function() { return m("div", [ menu(), m("h2", "Contact") ]) } } m.route(document.body, "/", { "/": Home, "/contact": Contact }) ``` Note that even if you set `context.retain = true`, the element will still be destroyed and recreated if it is different enough from the existing element. An element is considered "different enough" if: - the tag name changes, or - the list of HTML attributes changes, or - the value of the element's id attribute changes In addition, setting `context.retain = false` will also cause the element to be recreated, even if it is not considered different enough. --- #### SVG You can use Mithril to create SVG documents (as long as you don't need to support browsers that don't support SVG natively). Mithril automatically figures out the correct XML namespaces when it sees an SVG island in the virtual DOM tree. ```javascript m("svg[height='200px'][width='200px']", [ m("image[href='foo.jpg'][height='200px'][width='200px']") ]) ``` --- #### Dealing with focus The virtual DOM diffing algorithm has a weakness: a naive diff is not aware of the identity of DOM elements. In practice, this means performing operations like shifting an item from the beginning of a list would cause every element in the list to be diffed and potentially recreated. Another side-effect is that UI state like input focus is not tracked correctly if the focused element moves around, and likewise, state for 3rd party plugins that are added via `config` can also end up in the wrong element. Fortunately, with Mithril, it's possible for developers to attach an identity key to elements so that array operations like shift, splice and sort only affect the minimum amount of elements required, leaving the rest of the DOM elements untouched when a redraw happens. This allows us to maintain input focus and plugin state correctly. To maintain the identities of DOM elements, you need to add a `key` property to the direct children of the array that you're planning to modify. The key for each child must be unique among a list of sibling DOM elements, but it does not need to be globally unique. Also, keys must be either strings or numbers. ```javascript m("ul", [ items.map(function(item) { return m("li", {key: item.id}, [ m("input") ]); }) ]); ``` In the example above, input focus would be maintained correctly after a redraw even if `items` got sorted or reversed. The key is defined in the `li`, which is the closest element to the `items` array, not directly on the `input`, even though we want to track focus on the input. Note that in addition to the presence of the `key` attribute, diffing rules also apply in determining whether an element is recreated. Elements are recreated if either their node name changes, or if the list of attribute names change, or if the ID attribute changes. To avoid surprises, be sure to change only attribute values, using `undefined` or `null` as values if appropriate, rather than conditionally substituting attribute dictionaries altogether. ```javascript //avoid using this idiom m("li", selected ? {class: "active"} : {}) //use this idiom instead m("li", {class: selected ? "active" : ""}) ``` --- ### Dealing with sorting and deleting in lists As with input focus, we can maintain referential integrity between data in a list and the respective DOM representation by using keys. ```javascript m("ul", [ items.map(function(item) { return m("li", {key: item.id}, [ m("input") ]); }) ]); ``` You should always use keys if you need to sort lists, remove items from them or splice them in any way. --- ### Component Shorthand If the first argument to `m()` is a component, it acts as an alias of `m.component()` ```javascript var MyComponent = { controller: function() { return {greeting: "hello"} }, view: function(ctrl, args) { return m("h1", ctrl.greeting + " " + args.data) } } m.render(document.body, [ //the two lines below are equivalent m(MyComponent, {data: "world"}), m.component(MyComponent, {data: "world"}) ]) ``` See [components](mithril.component.md) for more information. --- ### Signature [How to read signatures](how-to-read-signatures.md) ```clike VirtualElement m(String selector [, Attributes attributes] [, Children... children]) where: VirtualElement :: Object { String tag, Attributes attributes, Children children } Attributes :: Object<any | void config(DOMElement element, Boolean isInitialized, Object context, VirtualElement vdom)> Children :: String text | VirtualElement virtualElement | Component | SubtreeDirective directive | Array<Children children> Component :: Object { Function? controller, Function view } SubtreeDirective :: Object { String subtree } ``` - **String selector** This string should be a CSS rule that represents a DOM element. Only tag, id, class and attribute selectors are supported. If the tag selector is omitted, it defaults to `div`. Note that if the same attribute is defined in the both `selector` and `attributes` parameters, the value in `attributes` is used. For developer convenience, Mithril makes an exception for the `class` attribute: if there are classes defined in both parameters, they are concatenated as a space separated list. It does not, however, de-dupe classes if the same class is declared twice. *Examples:* `"div"` `"#container"` `".active"` `"[title='Application']"` `"div#container.active[title='Application']"` `".active#container"` - **Attributes attributes** (optional) This key-value map should define a list of HTML attributes and their respective values. You can use both HTML and Javascript attribute names. For example, both `class` and `className` are valid. Values' types should match the expected type for the respective attribute. For example, the value for `className` should be a string. When a attribute name expects different types for the value in HTML and Javascript, the Javascript type should be used. For example, the value for the `onclick` attribute should be a function. Similar, setting the value of attribute `readonly` to `false` is equivalent to removing the attribute in HTML. It's also possible to set values to Javascript-only properties, such as `hash` in a `<a>` element. Note that if the same attribute is defined in the both `selector` and `attributes` parameters, the value in `attributes` is used. For developer convenience, Mithril makes an exception for the `class` attribute: if there are classes defined in both parameters, they are concatenated as a space separated list. It does not, however, de-dupe classes if the same class is declared twice. *Examples:* `{ title: "Application" }` `{ onclick: function(e) { /*do stuff*/ } }` `{ style: {border: "1px solid red"} }` - #### The `config` attribute **void config(DOMElement element, Boolean isInitialized, Object context, VirtualElement vdom)** (optional) You can define a non-HTML-standard attribute called `config`. This special parameter allows you to call methods on the DOM element after it gets created. This is useful, for example, if you declare a `canvas` element and want to use the Javascript API to draw: ```javascript function draw(element, isInitialized) { //don't redraw if we did once already if (isInitialized) return; var ctx = element.getContext("2d"); /* draws stuff */ } var view = [ m("canvas", {config: draw}) ] //this creates the canvas element, and therefore, `isInitialized` is false m.render(document.body, view); //here, isInitialized is `true` m.render(document.body, view); ``` One common way of using `config` is in conjunction with [`m.route`](mithril.route.md), which is an unobtrusive extension to links that allow Mithril's routing system to work transparently regardless of which routing mode is used. ```javascript //this link can use any of Mithril's routing system modes //(i.e. it can use either the hash, the querystring or the pathname as the router implementation) //without needing to hard-code any syntax (`#` or `?`) in the `href` attribute. m("a[href='/dashboard']", {config: m.route}, "Dashboard"); ``` The `config` mechanism can also be used to put focus on form inputs, and call methods that would not be possible to execute via the regular attribute syntax. Also note that the `config` callback only runs after a rendering lifecycle is done. Therefore, you should not use `config` to modify controller and model values, if you expect these changes to render immediately. Changes to controller and model values in this fashion will only render on the next `m.render` or `m.mount` call. You can use this mechanism to attach custom event listeners to controller methods (for example, when integrating with third party libraries), but you are responsible for making sure the integration with Mithril's autoredrawing system is in place. See the [integration guide](integration.md) for more information. You can also use it to attach events to other elements (for example, `window.onresize`), but you should remove such event handlers via `ctx.onunload` to avoid surprises. - **DOMElement element** The DOM element that corresponds to virtual element defined by the `m()` call. - **Boolean isInitialized** Whether this is the first time we are running this function on this element. This flag is false the first time it runs on an element, and true on redraws that happen after the element has been created. - **Object context** An object that retains its state across redraws. It can be used to store instances of 3rd party classes that need to be accessed more than one time throughout the lifecycle of a page. The example below shows a contrived redraw counter. In it, the count is stored in the context object and re-accessed on each redraw. ```javascript function alertsRedrawCount(element, isInit, context) { if (!isInit) context.count = 0 alert(++context.count) } m("div", {config: alertsRedrawCount}) ``` If the `context` object that is passed to a `config` function has a property called `onunload`, this function will be called when the element gets detached from the document by Mithril's diff engine. This is useful if there are cleanup tasks that need to be run when an element is destroyed (e.g. clearing `setTimeout`'s, etc) ```javascript function unloadable(element, isInit, context) { context.timer = setTimeout(function() { alert("timed out!"); }, 1000); context.onunload = function() { clearTimeout(context.timer); console.log("unloaded the div"); } }; m.render(document, m("div", {config: unloadable})); m.render(document, m("a")); //logs `unloaded the div` and `alert` never gets called ``` - **VirtualElement vdom** The virtual DOM element to which the `config` function is attached - **Children children** (optional) If this argument is a string, it will be rendered as a text node. To render a string as HTML, see [`m.trust`](mithril.trust.md) If it's a VirtualElement, it will be rendered as a DOM Element. If it's a [component](mithril.component.md), the component will be instantiated and managed internally by Mithril If it's a list, its contents will recursively be rendered as appropriate and appended as children of the element being created. If it's a SubtreeDirective with the value "retain", it will retain the existing DOM tree in place, if any. See [subtree directives.md](mithril.render.md#subtree-directives) for more information. - **returns** VirtualElement The returned VirtualElement is a Javascript data structure that represents the DOM element to be rendered by [`m.render`](mithril.render.md)
{'content_hash': '019c130827cf9dff2398348ed5027c90', 'timestamp': '', 'source': 'github', 'line_count': 671, 'max_line_length': 507, 'avg_line_length': 37.58867362146051, 'alnum_prop': 0.7245262072793592, 'repo_name': 'futurist/mithril_0.2.x', 'id': '10fa215b7b93b08321e418fc6db337e613bbfb72', 'size': '25222', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'docs/mithril.md', 'mode': '33261', 'license': 'mit', 'language': [{'name': 'CSS', 'bytes': '36786'}, {'name': 'HTML', 'bytes': '2914489'}, {'name': 'JavaScript', 'bytes': '925918'}]}
<?php return [ /* |-------------------------------------------------------------------------- | Application Environment |-------------------------------------------------------------------------- | | This value determines the "environment" your application is currently | running in. This may determine how you prefer to configure various | services your application utilizes. Set this in your ".env" file. | */ 'env' => env('APP_ENV', 'production'), /* |-------------------------------------------------------------------------- | Application Debug Mode |-------------------------------------------------------------------------- | | When your application is in debug mode, detailed error messages with | stack traces will be shown on every error that occurs within your | application. If disabled, a simple generic error page is shown. | */ 'debug' => env('APP_DEBUG', true), /* |-------------------------------------------------------------------------- | Application URL |-------------------------------------------------------------------------- | | This URL is used by the console to properly generate URLs when using | the Artisan command line tool. You should set this to the root of | your application so that it is used when running Artisan tasks. | */ 'url' => env('APP_URL', 'http://localhost'), /* |-------------------------------------------------------------------------- | Application Timezone |-------------------------------------------------------------------------- | | Here you may specify the default timezone for your application, which | will be used by the PHP date and date-time functions. We have gone | ahead and set this to a sensible default for you out of the box. | */ 'timezone' => 'UTC', /* |-------------------------------------------------------------------------- | Application Locale Configuration |-------------------------------------------------------------------------- | | The application locale determines the default locale that will be used | by the translation service provider. You are free to set this value | to any of the locales which will be supported by the application. | */ 'locale' => 'en', /* |-------------------------------------------------------------------------- | Application Fallback Locale |-------------------------------------------------------------------------- | | The fallback locale determines the locale to use when the current one | is not available. You may change the value to correspond to any of | the language folders that are provided through your application. | */ 'fallback_locale' => 'en', /* |-------------------------------------------------------------------------- | Encryption Key |-------------------------------------------------------------------------- | | This key is used by the Illuminate encrypter service and should be set | to a random, 32 character string, otherwise these encrypted strings | will not be safe. Please do this before deploying an application! | */ 'key' => env('APP_KEY'), 'cipher' => 'AES-256-CBC', /* |-------------------------------------------------------------------------- | Logging Configuration |-------------------------------------------------------------------------- | | Here you may configure the log settings for your application. Out of | the box, Laravel uses the Monolog PHP logging library. This gives | you a variety of powerful log handlers / formatters to utilize. | | Available Settings: "single", "daily", "syslog", "errorlog" | */ 'log' => env('APP_LOG', 'daily'), /* |-------------------------------------------------------------------------- | Autoloaded Service Providers |-------------------------------------------------------------------------- | | The service providers listed here will be automatically loaded on the | request to your application. Feel free to add your own services to | this array to grant expanded functionality to your applications. | */ 'providers' => [ /* * Laravel Framework Service Providers... */ Illuminate\Auth\AuthServiceProvider::class, Illuminate\Broadcasting\BroadcastServiceProvider::class, Illuminate\Bus\BusServiceProvider::class, Illuminate\Cache\CacheServiceProvider::class, Illuminate\Foundation\Providers\ConsoleSupportServiceProvider::class, Illuminate\Cookie\CookieServiceProvider::class, Illuminate\Database\DatabaseServiceProvider::class, Illuminate\Encryption\EncryptionServiceProvider::class, Illuminate\Filesystem\FilesystemServiceProvider::class, Illuminate\Foundation\Providers\FoundationServiceProvider::class, Illuminate\Hashing\HashServiceProvider::class, Illuminate\Mail\MailServiceProvider::class, Illuminate\Pagination\PaginationServiceProvider::class, Illuminate\Pipeline\PipelineServiceProvider::class, Illuminate\Queue\QueueServiceProvider::class, Illuminate\Redis\RedisServiceProvider::class, Illuminate\Auth\Passwords\PasswordResetServiceProvider::class, Illuminate\Session\SessionServiceProvider::class, Illuminate\Translation\TranslationServiceProvider::class, Illuminate\Validation\ValidationServiceProvider::class, Illuminate\View\ViewServiceProvider::class, /* * Application Service Providers... */ App\Providers\AppServiceProvider::class, App\Providers\AuthServiceProvider::class, App\Providers\EventServiceProvider::class, App\Providers\RouteServiceProvider::class, /* * Entrust Service Provider */ Zizaco\Entrust\EntrustServiceProvider::class, /* * LaravelCollective Html Form & Html */ Collective\Html\HtmlServiceProvider::class, Laravel\Socialite\SocialiteServiceProvider::class, ], /* |-------------------------------------------------------------------------- | Class Aliases |-------------------------------------------------------------------------- | | This array of class aliases will be registered when this application | is started. However, feel free to register as many as you wish as | the aliases are "lazy" loaded so they don't hinder performance. | */ 'aliases' => [ 'App' => Illuminate\Support\Facades\App::class, 'Artisan' => Illuminate\Support\Facades\Artisan::class, 'Auth' => Illuminate\Support\Facades\Auth::class, 'Blade' => Illuminate\Support\Facades\Blade::class, 'Cache' => Illuminate\Support\Facades\Cache::class, 'Config' => Illuminate\Support\Facades\Config::class, 'Cookie' => Illuminate\Support\Facades\Cookie::class, 'Crypt' => Illuminate\Support\Facades\Crypt::class, 'DB' => Illuminate\Support\Facades\DB::class, 'Eloquent' => Illuminate\Database\Eloquent\Model::class, 'Event' => Illuminate\Support\Facades\Event::class, 'File' => Illuminate\Support\Facades\File::class, 'Gate' => Illuminate\Support\Facades\Gate::class, 'Hash' => Illuminate\Support\Facades\Hash::class, 'Lang' => Illuminate\Support\Facades\Lang::class, 'Log' => Illuminate\Support\Facades\Log::class, 'Mail' => Illuminate\Support\Facades\Mail::class, 'Password' => Illuminate\Support\Facades\Password::class, 'Queue' => Illuminate\Support\Facades\Queue::class, 'Redirect' => Illuminate\Support\Facades\Redirect::class, 'Redis' => Illuminate\Support\Facades\Redis::class, 'Request' => Illuminate\Support\Facades\Request::class, 'Response' => Illuminate\Support\Facades\Response::class, 'Route' => Illuminate\Support\Facades\Route::class, 'Schema' => Illuminate\Support\Facades\Schema::class, 'Session' => Illuminate\Support\Facades\Session::class, 'Storage' => Illuminate\Support\Facades\Storage::class, 'URL' => Illuminate\Support\Facades\URL::class, 'Validator' => Illuminate\Support\Facades\Validator::class, 'View' => Illuminate\Support\Facades\View::class, /* * Entrust alias */ 'Entrust' => Zizaco\Entrust\EntrustFacade::class, /* * LaravelCollective Html Form & Html */ 'Form' => Collective\Html\FormFacade::class, 'Html' => Collective\Html\HtmlFacade::class, 'Socialite' => Laravel\Socialite\Facades\Socialite::class, ], ];
{'content_hash': '2d5ee0dc643fd6d7e0737c071b27f42b', 'timestamp': '', 'source': 'github', 'line_count': 229, 'max_line_length': 79, 'avg_line_length': 38.88209606986899, 'alnum_prop': 0.5367250673854448, 'repo_name': 'pviswanath/New-Cassel-first-code-base', 'id': 'b273d4c18f15bc1087bbb33b74a20ef06029c369', 'size': '8904', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'config/app.php', 'mode': '33261', 'license': 'mit', 'language': [{'name': 'ApacheConf', 'bytes': '553'}, {'name': 'CSS', 'bytes': '4027'}, {'name': 'HTML', 'bytes': '67156'}, {'name': 'JavaScript', 'bytes': '15056'}, {'name': 'PHP', 'bytes': '162829'}]}
<?php App::uses('ShellDispatcher', 'Console'); App::uses('TestShell', 'Console/Command'); /** * TestTestShell * * @package Cake.Test.Case.Console.Command */ class TestTestShell extends TestShell { public function mapFileToCase($file, $category, $throwOnMissingFile = true) { return $this->_mapFileToCase($file, $category, $throwOnMissingFile); } public function mapFileToCategory($file) { return $this->_mapFileToCategory($file); } } /** * TestShellTest * * @package Cake.Test.Case.Console.Command */ class TestShellTest extends CakeTestCase { /** * setUp test case * * @return void */ public function setUp() { parent::setUp(); $out = $this->getMock('ConsoleOutput', array(), array(), '', false); $in = $this->getMock('ConsoleInput', array(), array(), '', false); $this->Shell = $this->getMock( 'TestTestShell', array('in', 'out', 'hr', 'help', 'error', 'err', '_stop', 'initialize', '_run', 'clear'), array($out, $out, $in) ); $this->Shell->OptionParser = $this->getMock('ConsoleOptionParser', array(), array(null, false)); } /** * tearDown method * * @return void */ public function tearDown() { parent::tearDown(); unset($this->Dispatch, $this->Shell); } /** * testMapCoreFileToCategory * * @return void */ public function testMapCoreFileToCategory() { $this->Shell->startup(); $return = $this->Shell->mapFileToCategory('lib/Cake/basics.php'); $this->assertSame('core', $return); $return = $this->Shell->mapFileToCategory('lib/Cake/Core/App.php'); $this->assertSame('core', $return); $return = $this->Shell->mapFileToCategory('lib/Cake/Some/Deeply/Nested/Structure.php'); $this->assertSame('core', $return); } /** * testMapCoreFileToCase * * basics.php is a slightly special case - it's the only file in the core with a test that isn't Capitalized * * @return void */ public function testMapCoreFileToCase() { $this->Shell->startup(); $return = $this->Shell->mapFileToCase('lib/Cake/basics.php', 'core'); $this->assertSame('Basics', $return); $return = $this->Shell->mapFileToCase('lib/Cake/Core/App.php', 'core'); $this->assertSame('Core/App', $return); $return = $this->Shell->mapFileToCase('lib/Cake/Some/Deeply/Nested/Structure.php', 'core', false); $this->assertSame('Some/Deeply/Nested/Structure', $return); } /** * testMapAppFileToCategory * * @return void */ public function testMapAppFileToCategory() { $this->Shell->startup(); $return = $this->Shell->mapFileToCategory(APP . 'Controller/ExampleController.php'); $this->assertSame('app', $return); $return = $this->Shell->mapFileToCategory(APP . 'My/File/Is/Here.php'); $this->assertSame('app', $return); } /** * testMapAppFileToCase * * @return void */ public function testMapAppFileToCase() { $this->Shell->startup(); $return = $this->Shell->mapFileToCase(APP . 'Controller/ExampleController.php', 'app', false); $this->assertSame('Controller/ExampleController', $return); $return = $this->Shell->mapFileToCase(APP . 'My/File/Is/Here.php', 'app', false); $this->assertSame('My/File/Is/Here', $return); } /** * testMapPluginFileToCategory * * @return void */ public function testMapPluginFileToCategory() { $this->Shell->startup(); $return = $this->Shell->mapFileToCategory(APP . 'Plugin/awesome/Controller/ExampleController.php'); $this->assertSame('awesome', $return); $return = $this->Shell->mapFileToCategory(dirname(CAKE) . 'plugins/awesome/Controller/ExampleController.php'); $this->assertSame('awesome', $return); } /** * testMapPluginFileToCase * * @return void */ public function testMapPluginFileToCase() { $this->Shell->startup(); $return = $this->Shell->mapFileToCase(APP . 'Plugin/awesome/Controller/ExampleController.php', 'awesome', false); $this->assertSame('Controller/ExampleController', $return); $return = $this->Shell->mapFileToCase(dirname(CAKE) . 'plugins/awesome/Controller/ExampleController.php', 'awesome', false); $this->assertSame('Controller/ExampleController', $return); } /** * testMapCoreTestToCategory * * @return void */ public function testMapCoreTestToCategory() { $this->Shell->startup(); $return = $this->Shell->mapFileToCategory('lib/Cake/Test/Case/BasicsTest.php'); $this->assertSame('core', $return); $return = $this->Shell->mapFileToCategory('lib/Cake/Test/Case/BasicsTest.php'); $this->assertSame('core', $return); $return = $this->Shell->mapFileToCategory('lib/Cake/Test/Case/Some/Deeply/Nested/StructureTest.php'); $this->assertSame('core', $return); } /** * testMapCoreTestToCase * * basics.php is a slightly special case - it's the only file in the core with a test that isn't Capitalized * * @return void */ public function testMapCoreTestToCase() { $this->Shell->startup(); $return = $this->Shell->mapFileToCase('lib/Cake/Test/Case/BasicsTest.php', 'core'); $this->assertSame('Basics', $return); $return = $this->Shell->mapFileToCase('lib/Cake/Test/Case/Core/AppTest.php', 'core'); $this->assertSame('Core/App', $return); $return = $this->Shell->mapFileToCase('lib/Cake/Test/Case/Some/Deeply/Nested/StructureTest.php', 'core', false); $this->assertSame('Some/Deeply/Nested/Structure', $return); } /** * testMapAppTestToCategory * * @return void */ public function testMapAppTestToCategory() { $this->Shell->startup(); $return = $this->Shell->mapFileToCategory(APP . 'Test/Case/Controller/ExampleControllerTest.php'); $this->assertSame('app', $return); $return = $this->Shell->mapFileToCategory(APP . 'Test/Case/My/File/Is/HereTest.php'); $this->assertSame('app', $return); } /** * testMapAppTestToCase * * @return void */ public function testMapAppTestToCase() { $this->Shell->startup(); $return = $this->Shell->mapFileToCase(APP . 'Test/Case/Controller/ExampleControllerTest.php', 'app', false); $this->assertSame('Controller/ExampleController', $return); $return = $this->Shell->mapFileToCase(APP . 'Test/Case/My/File/Is/HereTest.php', 'app', false); $this->assertSame('My/File/Is/Here', $return); } /** * testMapPluginTestToCategory * * @return void */ public function testMapPluginTestToCategory() { $this->Shell->startup(); $return = $this->Shell->mapFileToCategory(APP . 'Plugin/awesome/Test/Case/Controller/ExampleControllerTest.php'); $this->assertSame('awesome', $return); $return = $this->Shell->mapFileToCategory(dirname(CAKE) . 'plugins/awesome/Test/Case/Controller/ExampleControllerTest.php'); $this->assertSame('awesome', $return); } /** * testMapPluginTestToCase * * @return void */ public function testMapPluginTestToCase() { $this->Shell->startup(); $return = $this->Shell->mapFileToCase(APP . 'Plugin/awesome/Test/Case/Controller/ExampleControllerTest.php', 'awesome', false); $this->assertSame('Controller/ExampleController', $return); $return = $this->Shell->mapFileToCase(dirname(CAKE) . 'plugins/awesome/Test/Case/Controller/ExampleControllerTest.php', 'awesome', false); $this->assertSame('Controller/ExampleController', $return); } /** * testMapNotTestToNothing * * @return void */ public function testMapNotTestToNothing() { $this->Shell->startup(); $return = $this->Shell->mapFileToCategory(APP . 'Test/Case/NotATestFile.php'); $this->assertSame('app', $return); $return = $this->Shell->mapFileToCase(APP . 'Test/Case/NotATestFile.php', false, false); $this->assertFalse($return); $return = $this->Shell->mapFileToCategory(APP . 'Test/Fixture/SomeTest.php'); $this->assertSame('app', $return); $return = $this->Shell->mapFileToCase(APP . 'Test/Fixture/SomeTest.php', false, false); $this->assertFalse($return); } /** * test available list of test cases for an empty category * * @return void */ public function testAvailableWithEmptyList() { $this->Shell->startup(); $this->Shell->args = array('unexistant-category'); $this->Shell->expects($this->at(0))->method('out')->with(__d('cake_console', "No test cases available \n\n")); $this->Shell->OptionParser->expects($this->once())->method('help'); $this->Shell->available(); } /** * test available list of test cases for core category * * @return void */ public function testAvailableCoreCategory() { $this->Shell->startup(); $this->Shell->args = array('core'); $this->Shell->expects($this->at(0))->method('out')->with('Core Test Cases:'); $this->Shell->expects($this->at(1))->method('out') ->with($this->stringContains('[1]')); $this->Shell->expects($this->at(2))->method('out') ->with($this->stringContains('[2]')); $this->Shell->expects($this->once())->method('in') ->with(__d('cake_console', 'What test case would you like to run?'), null, 'q') ->will($this->returnValue('1')); $this->Shell->expects($this->once())->method('_run'); $this->Shell->available(); $this->assertEquals(array('core', 'AllBehaviors'), $this->Shell->args); } /** * Tests that correct option for test runner are passed * * @return void */ public function testRunnerOptions() { $this->Shell->startup(); $this->Shell->args = array('core', 'Basics'); $this->Shell->params = array('filter' => 'myFilter', 'colors' => true, 'verbose' => true); $this->Shell->expects($this->once())->method('_run') ->with( array('app' => false, 'plugin' => null, 'core' => true, 'output' => 'text', 'case' => 'Basics'), array('--filter', 'myFilter', '--colors', '--verbose') ); $this->Shell->main(); } /** * Tests that the 'quiet' parameter gets swallowed before calling PHPUnit * * @return void */ public function testRunnerOptionsQuiet() { $this->Shell->startup(); $this->Shell->args = array('core', 'Basics'); $this->Shell->params = array('quiet' => true); $this->Shell->expects($this->once())->method('_run') ->with( array('app' => false, 'plugin' => null, 'core' => true, 'output' => 'text', 'case' => 'Basics'), array('--colors') ); $this->Shell->main(); } /** * Tests that the '--directive' parameter change to '-d' before calling PHPUnit * * @return void */ public function testRunnerOptionsDirective() { $this->Shell->startup(); $this->Shell->args = array('core', 'Basics'); $this->Shell->params = array('directive' => 'memory_limit=128M'); $this->Shell->expects($this->once())->method('_run') ->with( array('app' => false, 'plugin' => null, 'core' => true, 'output' => 'text', 'case' => 'Basics'), array('-d', 'memory_limit=128M', '--colors') ); $this->Shell->main(); } }
{'content_hash': '6a24b1b49f2293b93258f70726a16841', 'timestamp': '', 'source': 'github', 'line_count': 365, 'max_line_length': 140, 'avg_line_length': 28.854794520547944, 'alnum_prop': 0.66473604253703, 'repo_name': 'ibrsp/comanage-registry', 'id': '7dfe63c27f2aa80931528d4553f4728ad271f522', 'size': '11209', 'binary': False, 'copies': '25', 'ref': 'refs/heads/master', 'path': 'lib/Cake/Test/Case/Console/Command/TestShellTest.php', 'mode': '33188', 'license': 'apache-2.0', 'language': [{'name': 'Batchfile', 'bytes': '2824'}, {'name': 'CSS', 'bytes': '480345'}, {'name': 'HTML', 'bytes': '32588'}, {'name': 'JavaScript', 'bytes': '267012'}, {'name': 'PHP', 'bytes': '13272572'}, {'name': 'Shell', 'bytes': '5430'}, {'name': 'XSLT', 'bytes': '808'}]}
<?php /** * EventManager.php * 2013 Petr Dvorak, petr-dvorak.cz / 15.4.13 20:21 */ namespace ITILSimulator\Runtime\Events; use ITILSimulator\Runtime\Training\ActiveConfigurationItem; /** * EventManager for publishing and subscribing to events of various types. * Events are fired by workflow or UI. * @package ITILSimulator\Runtime\Events */ class EventManager { /** * Event channel listeners * @var array */ protected $listeners = array('*' => array()); /** * IO channel listeners * @var array */ protected $ioListeners = array(); #region "Event channel" /** * Dispatch new event through Event channel * @param $eventName * @param Event $event */ public function dispatch($eventName, Event $event) { $listeners = $this->listeners['*']; if (array_key_exists($eventName, $this->listeners)) { $listeners = array_merge($listeners, $this->listeners[$eventName]); } if (!$listeners) return; $event->setName($eventName); foreach ($listeners as $listener) { call_user_func($listener, $event); if ($event->isPropagationStopped()) { break; } } } /** * Add new listener to Event channel * @param $eventName * @param $callback */ public function addListener($eventName, $callback) { $eventName = (string) $eventName; if (!array_key_exists($eventName, $this->listeners)) $this->listeners[$eventName] = array(); $this->listeners[$eventName][] = $callback; } #endregion #region "IO channel" /** * Dispatch event through IO channel * @param $ioId */ public function dispatchIO($ioId) { if (!isset($this->ioListeners[$ioId])) return; foreach($this->ioListeners[$ioId] as $item) { /** @var $item ActiveConfigurationItem */ $item->receiveInput($ioId); } } /** * Add new listener to IO channel * @param $ioId * @param ActiveConfigurationItem $item */ public function addIOListener($ioId, ActiveConfigurationItem $item) { if (!isset($this->ioListeners[$ioId])) $this->ioListeners[$ioId] = array(); $this->ioListeners[$ioId][] = $item; } #endregion }
{'content_hash': '430c779bfaabb90858ed23d6b6db9551', 'timestamp': '', 'source': 'github', 'line_count': 102, 'max_line_length': 74, 'avg_line_length': 20.41176470588235, 'alnum_prop': 0.6575408261287223, 'repo_name': 'petrolep/itilsimulator', 'id': '610590efe72606475569b94a8140a9b99b1b66e9', 'size': '2082', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'application/app/model/Runtime/Events/EventManager.php', 'mode': '33188', 'license': 'bsd-3-clause', 'language': [{'name': 'JavaScript', 'bytes': '1336953'}, {'name': 'PHP', 'bytes': '697825'}, {'name': 'Shell', 'bytes': '68'}]}
/* * This file is derived from various .h and .c files from the zlib-1.0.4 * distribution by Jean-loup Gailly and Mark Adler, with some additions * by Paul Mackerras to aid in implementing Deflate compression and * decompression for PPP packets. See zlib.h for conditions of * distribution and use. * * Changes that have been made include: * - added Z_PACKET_FLUSH (see zlib.h for details) * - added inflateIncomp and deflateOutputPending * - allow strm->next_out to be NULL, meaning discard the output * * $FreeBSD: soc2013/dpl/head/sys/net/zlib.c 246301 2013-01-06 14:59:59Z peter $ */ /* * ==FILEVERSION 971210== * * This marker is used by the Linux installation script to determine * whether an up-to-date version of this file is already installed. */ #define NO_DUMMY_DECL #define NO_ZCFUNCS #define MY_ZCALLOC #if defined(__FreeBSD__) && defined(_KERNEL) #define _tr_init _zlib104_tr_init #define _tr_align _zlib104_tr_align #define _tr_tally _zlib104_tr_tally #define _tr_flush_block _zlib104_tr_flush_block #define _tr_stored_block _zlib104_tr_stored_block #define inflate_fast _zlib104_inflate_fast #define inflate _zlib104_inflate #define zlibVersion _zlib104_Version #endif /* +++ zutil.h */ /*- * zutil.h -- internal interface and configuration of the compression library * Copyright (C) 1995-1996 Jean-loup Gailly. * For conditions of distribution and use, see copyright notice in zlib.h */ /* WARNING: this file should *not* be used by applications. It is part of the implementation of the compression library and is subject to change. Applications should only use zlib.h. */ /* From: zutil.h,v 1.16 1996/07/24 13:41:13 me Exp $ */ #ifndef _Z_UTIL_H #define _Z_UTIL_H #ifdef _KERNEL #include <net/zlib.h> #else #include "zlib.h" #endif #ifdef _KERNEL /* Assume this is a *BSD or SVR4 kernel */ #include <sys/types.h> #include <sys/time.h> #include <sys/systm.h> #include <sys/param.h> #include <sys/kernel.h> #include <sys/module.h> # define HAVE_MEMCPY #else #if defined(__KERNEL__) /* Assume this is a Linux kernel */ #include <linux/string.h> #define HAVE_MEMCPY #else /* not kernel */ #if defined(MSDOS)||defined(VMS)||defined(CRAY)||defined(WIN32)||defined(RISCOS) # include <stddef.h> # include <errno.h> #else extern int errno; #endif #ifdef STDC # include <string.h> # include <stdlib.h> #endif #endif /* __KERNEL__ */ #endif /* _KERNEL */ #ifndef local # define local static #endif /* compile with -Dlocal if your debugger can't find static symbols */ typedef unsigned char uch; typedef uch FAR uchf; typedef unsigned short ush; typedef ush FAR ushf; typedef unsigned long ulg; static const char *z_errmsg[10]; /* indexed by 2-zlib_error */ /* (size given to avoid silly warnings with Visual C++) */ #define ERR_MSG(err) z_errmsg[Z_NEED_DICT-(err)] #define ERR_RETURN(strm,err) \ return (strm->msg = (const char*)ERR_MSG(err), (err)) /* To be used only when the state is known to be valid */ /* common constants */ #ifndef DEF_WBITS # define DEF_WBITS MAX_WBITS #endif /* default windowBits for decompression. MAX_WBITS is for compression only */ #if MAX_MEM_LEVEL >= 8 # define DEF_MEM_LEVEL 8 #else # define DEF_MEM_LEVEL MAX_MEM_LEVEL #endif /* default memLevel */ #define STORED_BLOCK 0 #define STATIC_TREES 1 #define DYN_TREES 2 /* The three kinds of block type */ #define MIN_MATCH 3 #define MAX_MATCH 258 /* The minimum and maximum match lengths */ #define PRESET_DICT 0x20 /* preset dictionary flag in zlib header */ /* target dependencies */ #ifdef MSDOS # define OS_CODE 0x00 # ifdef __TURBOC__ # include <alloc.h> # else /* MSC or DJGPP */ # include <malloc.h> # endif #endif #ifdef OS2 # define OS_CODE 0x06 #endif #ifdef WIN32 /* Window 95 & Windows NT */ # define OS_CODE 0x0b #endif #if defined(VAXC) || defined(VMS) # define OS_CODE 0x02 # define FOPEN(name, mode) \ fopen((name), (mode), "mbc=60", "ctx=stm", "rfm=fix", "mrs=512") #endif #ifdef AMIGA # define OS_CODE 0x01 #endif #if defined(ATARI) || defined(atarist) # define OS_CODE 0x05 #endif #ifdef MACOS # define OS_CODE 0x07 #endif #ifdef __50SERIES /* Prime/PRIMOS */ # define OS_CODE 0x0F #endif #ifdef TOPS20 # define OS_CODE 0x0a #endif #if defined(_BEOS_) || defined(RISCOS) # define fdopen(fd,mode) NULL /* No fdopen() */ #endif /* Common defaults */ #ifndef OS_CODE # define OS_CODE 0x03 /* assume Unix */ #endif #ifndef FOPEN # define FOPEN(name, mode) fopen((name), (mode)) #endif /* functions */ #ifdef HAVE_STRERROR extern char *strerror OF((int)); # define zstrerror(errnum) strerror(errnum) #else # define zstrerror(errnum) "" #endif #if defined(pyr) # define NO_MEMCPY #endif #if (defined(M_I86SM) || defined(M_I86MM)) && !defined(_MSC_VER) /* Use our own functions for small and medium model with MSC <= 5.0. * You may have to use the same strategy for Borland C (untested). */ # define NO_MEMCPY #endif #if defined(STDC) && !defined(HAVE_MEMCPY) && !defined(NO_MEMCPY) # define HAVE_MEMCPY #endif #ifdef HAVE_MEMCPY # ifdef SMALL_MEDIUM /* MSDOS small or medium model */ # define zmemcpy _fmemcpy # define zmemcmp _fmemcmp # define zmemzero(dest, len) _fmemset(dest, 0, len) # else # define zmemcpy memcpy # define zmemcmp memcmp # define zmemzero(dest, len) memset(dest, 0, len) # endif #else extern void zmemcpy OF((Bytef* dest, Bytef* source, uInt len)); extern int zmemcmp OF((Bytef* s1, Bytef* s2, uInt len)); extern void zmemzero OF((Bytef* dest, uInt len)); #endif /* Diagnostic functions */ #ifdef DEBUG_ZLIB # include <stdio.h> # ifndef verbose # define verbose 0 # endif extern void z_error OF((char *m)); # define Assert(cond,msg) {if(!(cond)) z_error(msg);} # define Trace(x) fprintf x # define Tracev(x) {if (verbose) fprintf x ;} # define Tracevv(x) {if (verbose>1) fprintf x ;} # define Tracec(c,x) {if (verbose && (c)) fprintf x ;} # define Tracecv(c,x) {if (verbose>1 && (c)) fprintf x ;} #else # define Assert(cond,msg) # define Trace(x) # define Tracev(x) # define Tracevv(x) # define Tracec(c,x) # define Tracecv(c,x) #endif typedef uLong (*check_func) OF((uLong check, const Bytef *buf, uInt len)); voidpf zcalloc OF((voidpf opaque, unsigned items, unsigned size)); void zcfree OF((voidpf opaque, voidpf ptr)); #define ZALLOC(strm, items, size) \ (*((strm)->zalloc))((strm)->opaque, (items), (size)) #define ZFREE(strm, addr) (*((strm)->zfree))((strm)->opaque, (voidpf)(addr)) #define TRY_FREE(s, p) {if (p) ZFREE(s, p);} #endif /* _Z_UTIL_H */ /* --- zutil.h */ /* +++ deflate.h */ /* deflate.h -- internal compression state * Copyright (C) 1995-1996 Jean-loup Gailly * For conditions of distribution and use, see copyright notice in zlib.h */ /* WARNING: this file should *not* be used by applications. It is part of the implementation of the compression library and is subject to change. Applications should only use zlib.h. */ /* From: deflate.h,v 1.10 1996/07/02 12:41:00 me Exp $ */ #ifndef _DEFLATE_H #define _DEFLATE_H /* #include "zutil.h" */ /* =========================================================================== * Internal compression state. */ #define LENGTH_CODES 29 /* number of length codes, not counting the special END_BLOCK code */ #define LITERALS 256 /* number of literal bytes 0..255 */ #define L_CODES (LITERALS+1+LENGTH_CODES) /* number of Literal or Length codes, including the END_BLOCK code */ #define D_CODES 30 /* number of distance codes */ #define BL_CODES 19 /* number of codes used to transfer the bit lengths */ #define HEAP_SIZE (2*L_CODES+1) /* maximum heap size */ #define MAX_BITS 15 /* All codes must not exceed MAX_BITS bits */ #define INIT_STATE 42 #define BUSY_STATE 113 #define FINISH_STATE 666 /* Stream status */ /* Data structure describing a single value and its code string. */ typedef struct ct_data_s { union { ush freq; /* frequency count */ ush code; /* bit string */ } fc; union { ush dad; /* father node in Huffman tree */ ush len; /* length of bit string */ } dl; } FAR ct_data; #define Freq fc.freq #define Code fc.code #define Dad dl.dad #define Len dl.len typedef struct static_tree_desc_s static_tree_desc; typedef struct tree_desc_s { ct_data *dyn_tree; /* the dynamic tree */ int max_code; /* largest code with non zero frequency */ static_tree_desc *stat_desc; /* the corresponding static tree */ } FAR tree_desc; typedef ush Pos; typedef Pos FAR Posf; typedef unsigned IPos; /* A Pos is an index in the character window. We use short instead of int to * save space in the various tables. IPos is used only for parameter passing. */ typedef struct deflate_state { z_streamp strm; /* pointer back to this zlib stream */ int status; /* as the name implies */ Bytef *pending_buf; /* output still pending */ ulg pending_buf_size; /* size of pending_buf */ Bytef *pending_out; /* next pending byte to output to the stream */ int pending; /* nb of bytes in the pending buffer */ int noheader; /* suppress zlib header and adler32 */ Byte data_type; /* UNKNOWN, BINARY or ASCII */ Byte method; /* STORED (for zip only) or DEFLATED */ int last_flush; /* value of flush param for previous deflate call */ /* used by deflate.c: */ uInt w_size; /* LZ77 window size (32K by default) */ uInt w_bits; /* log2(w_size) (8..16) */ uInt w_mask; /* w_size - 1 */ Bytef *window; /* Sliding window. Input bytes are read into the second half of the window, * and move to the first half later to keep a dictionary of at least wSize * bytes. With this organization, matches are limited to a distance of * wSize-MAX_MATCH bytes, but this ensures that IO is always * performed with a length multiple of the block size. Also, it limits * the window size to 64K, which is quite useful on MSDOS. * To do: use the user input buffer as sliding window. */ ulg window_size; /* Actual size of window: 2*wSize, except when the user input buffer * is directly used as sliding window. */ Posf *prev; /* Link to older string with same hash index. To limit the size of this * array to 64K, this link is maintained only for the last 32K strings. * An index in this array is thus a window index modulo 32K. */ Posf *head; /* Heads of the hash chains or NIL. */ uInt ins_h; /* hash index of string to be inserted */ uInt hash_size; /* number of elements in hash table */ uInt hash_bits; /* log2(hash_size) */ uInt hash_mask; /* hash_size-1 */ uInt hash_shift; /* Number of bits by which ins_h must be shifted at each input * step. It must be such that after MIN_MATCH steps, the oldest * byte no longer takes part in the hash key, that is: * hash_shift * MIN_MATCH >= hash_bits */ long block_start; /* Window position at the beginning of the current output block. Gets * negative when the window is moved backwards. */ uInt match_length; /* length of best match */ IPos prev_match; /* previous match */ int match_available; /* set if previous match exists */ uInt strstart; /* start of string to insert */ uInt match_start; /* start of matching string */ uInt lookahead; /* number of valid bytes ahead in window */ uInt prev_length; /* Length of the best match at previous step. Matches not greater than this * are discarded. This is used in the lazy match evaluation. */ uInt max_chain_length; /* To speed up deflation, hash chains are never searched beyond this * length. A higher limit improves compression ratio but degrades the * speed. */ uInt max_lazy_match; /* Attempt to find a better match only when the current match is strictly * smaller than this value. This mechanism is used only for compression * levels >= 4. */ # define max_insert_length max_lazy_match /* Insert new strings in the hash table only if the match length is not * greater than this length. This saves time but degrades compression. * max_insert_length is used only for compression levels <= 3. */ int level; /* compression level (1..9) */ int strategy; /* favor or force Huffman coding*/ uInt good_match; /* Use a faster search when the previous match is longer than this */ int nice_match; /* Stop searching when current match exceeds this */ /* used by trees.c: */ /* Didn't use ct_data typedef below to supress compiler warning */ struct ct_data_s dyn_ltree[HEAP_SIZE]; /* literal and length tree */ struct ct_data_s dyn_dtree[2*D_CODES+1]; /* distance tree */ struct ct_data_s bl_tree[2*BL_CODES+1]; /* Huffman tree for bit lengths */ struct tree_desc_s l_desc; /* desc. for literal tree */ struct tree_desc_s d_desc; /* desc. for distance tree */ struct tree_desc_s bl_desc; /* desc. for bit length tree */ ush bl_count[MAX_BITS+1]; /* number of codes at each bit length for an optimal tree */ int heap[2*L_CODES+1]; /* heap used to build the Huffman trees */ int heap_len; /* number of elements in the heap */ int heap_max; /* element of largest frequency */ /* The sons of heap[n] are heap[2*n] and heap[2*n+1]. heap[0] is not used. * The same heap array is used to build all trees. */ uch depth[2*L_CODES+1]; /* Depth of each subtree used as tie breaker for trees of equal frequency */ uchf *l_buf; /* buffer for literals or lengths */ uInt lit_bufsize; /* Size of match buffer for literals/lengths. There are 4 reasons for * limiting lit_bufsize to 64K: * - frequencies can be kept in 16 bit counters * - if compression is not successful for the first block, all input * data is still in the window so we can still emit a stored block even * when input comes from standard input. (This can also be done for * all blocks if lit_bufsize is not greater than 32K.) * - if compression is not successful for a file smaller than 64K, we can * even emit a stored file instead of a stored block (saving 5 bytes). * This is applicable only for zip (not gzip or zlib). * - creating new Huffman trees less frequently may not provide fast * adaptation to changes in the input data statistics. (Take for * example a binary file with poorly compressible code followed by * a highly compressible string table.) Smaller buffer sizes give * fast adaptation but have of course the overhead of transmitting * trees more frequently. * - I can't count above 4 */ uInt last_lit; /* running index in l_buf */ ushf *d_buf; /* Buffer for distances. To simplify the code, d_buf and l_buf have * the same number of elements. To use different lengths, an extra flag * array would be necessary. */ ulg opt_len; /* bit length of current block with optimal trees */ ulg static_len; /* bit length of current block with static trees */ ulg compressed_len; /* total bit length of compressed file */ uInt matches; /* number of string matches in current block */ int last_eob_len; /* bit length of EOB code for last block */ #ifdef DEBUG_ZLIB ulg bits_sent; /* bit length of the compressed data */ #endif ush bi_buf; /* Output buffer. bits are inserted starting at the bottom (least * significant bits). */ int bi_valid; /* Number of valid bits in bi_buf. All bits above the last valid bit * are always zero. */ } FAR deflate_state; /* Output a byte on the stream. * IN assertion: there is enough room in pending_buf. */ #define put_byte(s, c) {s->pending_buf[s->pending++] = (c);} #define MIN_LOOKAHEAD (MAX_MATCH+MIN_MATCH+1) /* Minimum amount of lookahead, except at the end of the input file. * See deflate.c for comments about the MIN_MATCH+1. */ #define MAX_DIST(s) ((s)->w_size-MIN_LOOKAHEAD) /* In order to simplify the code, particularly on 16 bit machines, match * distances are limited to MAX_DIST instead of WSIZE. */ /* in trees.c */ void _tr_init OF((deflate_state *s)); int _tr_tally OF((deflate_state *s, unsigned dist, unsigned lc)); ulg _tr_flush_block OF((deflate_state *s, charf *buf, ulg stored_len, int eof)); void _tr_align OF((deflate_state *s)); void _tr_stored_block OF((deflate_state *s, charf *buf, ulg stored_len, int eof)); void _tr_stored_type_only OF((deflate_state *)); #endif /* --- deflate.h */ /* +++ deflate.c */ /* deflate.c -- compress data using the deflation algorithm * Copyright (C) 1995-1996 Jean-loup Gailly. * For conditions of distribution and use, see copyright notice in zlib.h */ /* * ALGORITHM * * The "deflation" process depends on being able to identify portions * of the input text which are identical to earlier input (within a * sliding window trailing behind the input currently being processed). * * The most straightforward technique turns out to be the fastest for * most input files: try all possible matches and select the longest. * The key feature of this algorithm is that insertions into the string * dictionary are very simple and thus fast, and deletions are avoided * completely. Insertions are performed at each input character, whereas * string matches are performed only when the previous match ends. So it * is preferable to spend more time in matches to allow very fast string * insertions and avoid deletions. The matching algorithm for small * strings is inspired from that of Rabin & Karp. A brute force approach * is used to find longer strings when a small match has been found. * A similar algorithm is used in comic (by Jan-Mark Wams) and freeze * (by Leonid Broukhis). * A previous version of this file used a more sophisticated algorithm * (by Fiala and Greene) which is guaranteed to run in linear amortized * time, but has a larger average cost, uses more memory and is patented. * However the F&G algorithm may be faster for some highly redundant * files if the parameter max_chain_length (described below) is too large. * * ACKNOWLEDGEMENTS * * The idea of lazy evaluation of matches is due to Jan-Mark Wams, and * I found it in 'freeze' written by Leonid Broukhis. * Thanks to many people for bug reports and testing. * * REFERENCES * * Deutsch, L.P.,"DEFLATE Compressed Data Format Specification". * Available in ftp://ds.internic.net/rfc/rfc1951.txt * * A description of the Rabin and Karp algorithm is given in the book * "Algorithms" by R. Sedgewick, Addison-Wesley, p252. * * Fiala,E.R., and Greene,D.H. * Data Compression with Finite Windows, Comm.ACM, 32,4 (1989) 490-595 * */ /* From: deflate.c,v 1.15 1996/07/24 13:40:58 me Exp $ */ /* #include "deflate.h" */ char deflate_copyright[] = " deflate 1.0.4 Copyright 1995-1996 Jean-loup Gailly "; /* If you use the zlib library in a product, an acknowledgment is welcome in the documentation of your product. If for some reason you cannot include such an acknowledgment, I would appreciate that you keep this copyright string in the executable of your product. */ /* =========================================================================== * Function prototypes. */ typedef enum { need_more, /* block not completed, need more input or more output */ block_done, /* block flush performed */ finish_started, /* finish started, need only more output at next deflate */ finish_done /* finish done, accept no more input or output */ } block_state; typedef block_state (*compress_func) OF((deflate_state *s, int flush)); /* Compression function. Returns the block state after the call. */ local void fill_window OF((deflate_state *s)); local block_state deflate_stored OF((deflate_state *s, int flush)); local block_state deflate_fast OF((deflate_state *s, int flush)); local block_state deflate_slow OF((deflate_state *s, int flush)); local void lm_init OF((deflate_state *s)); local void putShortMSB OF((deflate_state *s, uInt b)); local void flush_pending OF((z_streamp strm)); local int read_buf OF((z_streamp strm, charf *buf, unsigned size)); #ifdef ASMV void match_init OF((void)); /* asm code initialization */ uInt longest_match OF((deflate_state *s, IPos cur_match)); #else local uInt longest_match OF((deflate_state *s, IPos cur_match)); #endif #ifdef DEBUG_ZLIB local void check_match OF((deflate_state *s, IPos start, IPos match, int length)); #endif /* =========================================================================== * Local data */ #define NIL 0 /* Tail of hash chains */ #ifndef TOO_FAR # define TOO_FAR 4096 #endif /* Matches of length 3 are discarded if their distance exceeds TOO_FAR */ #define MIN_LOOKAHEAD (MAX_MATCH+MIN_MATCH+1) /* Minimum amount of lookahead, except at the end of the input file. * See deflate.c for comments about the MIN_MATCH+1. */ /* Values for max_lazy_match, good_match and max_chain_length, depending on * the desired pack level (0..9). The values given below have been tuned to * exclude worst case performance for pathological files. Better values may be * found for specific files. */ typedef struct config_s { ush good_length; /* reduce lazy search above this match length */ ush max_lazy; /* do not perform lazy search above this match length */ ush nice_length; /* quit search above this match length */ ush max_chain; compress_func func; } config; local config configuration_table[10] = { /* good lazy nice chain */ /* 0 */ {0, 0, 0, 0, deflate_stored}, /* store only */ /* 1 */ {4, 4, 8, 4, deflate_fast}, /* maximum speed, no lazy matches */ /* 2 */ {4, 5, 16, 8, deflate_fast}, /* 3 */ {4, 6, 32, 32, deflate_fast}, /* 4 */ {4, 4, 16, 16, deflate_slow}, /* lazy matches */ /* 5 */ {8, 16, 32, 32, deflate_slow}, /* 6 */ {8, 16, 128, 128, deflate_slow}, /* 7 */ {8, 32, 128, 256, deflate_slow}, /* 8 */ {32, 128, 258, 1024, deflate_slow}, /* 9 */ {32, 258, 258, 4096, deflate_slow}}; /* maximum compression */ /* Note: the deflate() code requires max_lazy >= MIN_MATCH and max_chain >= 4 * For deflate_fast() (levels <= 3) good is ignored and lazy has a different * meaning. */ #define EQUAL 0 /* result of memcmp for equal strings */ #ifndef NO_DUMMY_DECL struct static_tree_desc_s {int dummy;}; /* for buggy compilers */ #endif /* =========================================================================== * Update a hash value with the given input byte * IN assertion: all calls to to UPDATE_HASH are made with consecutive * input characters, so that a running hash key can be computed from the * previous key instead of complete recalculation each time. */ #define UPDATE_HASH(s,h,c) (h = (((h)<<s->hash_shift) ^ (c)) & s->hash_mask) /* =========================================================================== * Insert string str in the dictionary and set match_head to the previous head * of the hash chain (the most recent string with same hash key). Return * the previous length of the hash chain. * IN assertion: all calls to to INSERT_STRING are made with consecutive * input characters and the first MIN_MATCH bytes of str are valid * (except for the last MIN_MATCH-1 bytes of the input file). */ #define INSERT_STRING(s, str, match_head) \ (UPDATE_HASH(s, s->ins_h, s->window[(str) + (MIN_MATCH-1)]), \ s->prev[(str) & s->w_mask] = match_head = s->head[s->ins_h], \ s->head[s->ins_h] = (Pos)(str)) /* =========================================================================== * Initialize the hash table (avoiding 64K overflow for 16 bit systems). * prev[] will be initialized on the fly. */ #define CLEAR_HASH(s) \ s->head[s->hash_size-1] = NIL; \ zmemzero((charf *)s->head, (unsigned)(s->hash_size-1)*sizeof(*s->head)); /* ========================================================================= */ int deflateInit_(strm, level, version, stream_size) z_streamp strm; int level; const char *version; int stream_size; { return deflateInit2_(strm, level, Z_DEFLATED, MAX_WBITS, DEF_MEM_LEVEL, Z_DEFAULT_STRATEGY, version, stream_size); /* To do: ignore strm->next_in if we use it as window */ } /* ========================================================================= */ int deflateInit2_(strm, level, method, windowBits, memLevel, strategy, version, stream_size) z_streamp strm; int level; int method; int windowBits; int memLevel; int strategy; const char *version; int stream_size; { deflate_state *s; int noheader = 0; static char* my_version = ZLIB_VERSION; ushf *overlay; /* We overlay pending_buf and d_buf+l_buf. This works since the average * output size for (length,distance) codes is <= 24 bits. */ if (version == Z_NULL || version[0] != my_version[0] || stream_size != sizeof(z_stream)) { return Z_VERSION_ERROR; } if (strm == Z_NULL) return Z_STREAM_ERROR; strm->msg = Z_NULL; #ifndef NO_ZCFUNCS if (strm->zalloc == Z_NULL) { strm->zalloc = zcalloc; strm->opaque = (voidpf)0; } if (strm->zfree == Z_NULL) strm->zfree = zcfree; #endif if (level == Z_DEFAULT_COMPRESSION) level = 6; if (windowBits < 0) { /* undocumented feature: suppress zlib header */ noheader = 1; windowBits = -windowBits; } if (memLevel < 1 || memLevel > MAX_MEM_LEVEL || method != Z_DEFLATED || windowBits < 9 || windowBits > 15 || level < 0 || level > 9 || strategy < 0 || strategy > Z_HUFFMAN_ONLY) { return Z_STREAM_ERROR; } s = (deflate_state *) ZALLOC(strm, 1, sizeof(deflate_state)); if (s == Z_NULL) return Z_MEM_ERROR; strm->state = (struct internal_state FAR *)s; s->strm = strm; s->noheader = noheader; s->w_bits = windowBits; s->w_size = 1 << s->w_bits; s->w_mask = s->w_size - 1; s->hash_bits = memLevel + 7; s->hash_size = 1 << s->hash_bits; s->hash_mask = s->hash_size - 1; s->hash_shift = ((s->hash_bits+MIN_MATCH-1)/MIN_MATCH); s->window = (Bytef *) ZALLOC(strm, s->w_size, 2*sizeof(Byte)); s->prev = (Posf *) ZALLOC(strm, s->w_size, sizeof(Pos)); s->head = (Posf *) ZALLOC(strm, s->hash_size, sizeof(Pos)); s->lit_bufsize = 1 << (memLevel + 6); /* 16K elements by default */ overlay = (ushf *) ZALLOC(strm, s->lit_bufsize, sizeof(ush)+2); s->pending_buf = (uchf *) overlay; s->pending_buf_size = (ulg)s->lit_bufsize * (sizeof(ush)+2L); if (s->window == Z_NULL || s->prev == Z_NULL || s->head == Z_NULL || s->pending_buf == Z_NULL) { strm->msg = (const char*)ERR_MSG(Z_MEM_ERROR); deflateEnd (strm); return Z_MEM_ERROR; } s->d_buf = overlay + s->lit_bufsize/sizeof(ush); s->l_buf = s->pending_buf + (1+sizeof(ush))*s->lit_bufsize; s->level = level; s->strategy = strategy; s->method = (Byte)method; return deflateReset(strm); } /* ========================================================================= */ int deflateSetDictionary (strm, dictionary, dictLength) z_streamp strm; const Bytef *dictionary; uInt dictLength; { deflate_state *s; uInt length = dictLength; uInt n; IPos hash_head = 0; if (strm == Z_NULL || strm->state == Z_NULL || dictionary == Z_NULL) return Z_STREAM_ERROR; s = (deflate_state *) strm->state; if (s->status != INIT_STATE) return Z_STREAM_ERROR; strm->adler = adler32(strm->adler, dictionary, dictLength); if (length < MIN_MATCH) return Z_OK; if (length > MAX_DIST(s)) { length = MAX_DIST(s); #ifndef USE_DICT_HEAD dictionary += dictLength - length; /* use the tail of the dictionary */ #endif } zmemcpy((charf *)s->window, dictionary, length); s->strstart = length; s->block_start = (long)length; /* Insert all strings in the hash table (except for the last two bytes). * s->lookahead stays null, so s->ins_h will be recomputed at the next * call of fill_window. */ s->ins_h = s->window[0]; UPDATE_HASH(s, s->ins_h, s->window[1]); for (n = 0; n <= length - MIN_MATCH; n++) { INSERT_STRING(s, n, hash_head); } if (hash_head) hash_head = 0; /* to make compiler happy */ return Z_OK; } /* ========================================================================= */ int deflateReset (strm) z_streamp strm; { deflate_state *s; if (strm == Z_NULL || strm->state == Z_NULL || strm->zalloc == Z_NULL || strm->zfree == Z_NULL) return Z_STREAM_ERROR; strm->total_in = strm->total_out = 0; strm->msg = Z_NULL; /* use zfree if we ever allocate msg dynamically */ strm->data_type = Z_UNKNOWN; s = (deflate_state *)strm->state; s->pending = 0; s->pending_out = s->pending_buf; if (s->noheader < 0) { s->noheader = 0; /* was set to -1 by deflate(..., Z_FINISH); */ } s->status = s->noheader ? BUSY_STATE : INIT_STATE; strm->adler = 1; s->last_flush = Z_NO_FLUSH; _tr_init(s); lm_init(s); return Z_OK; } /* ========================================================================= */ int deflateParams(strm, level, strategy) z_streamp strm; int level; int strategy; { deflate_state *s; compress_func func; int err = Z_OK; if (strm == Z_NULL || strm->state == Z_NULL) return Z_STREAM_ERROR; s = (deflate_state *) strm->state; if (level == Z_DEFAULT_COMPRESSION) { level = 6; } if (level < 0 || level > 9 || strategy < 0 || strategy > Z_HUFFMAN_ONLY) { return Z_STREAM_ERROR; } func = configuration_table[s->level].func; if (func != configuration_table[level].func && strm->total_in != 0) { /* Flush the last buffer: */ err = deflate(strm, Z_PARTIAL_FLUSH); } if (s->level != level) { s->level = level; s->max_lazy_match = configuration_table[level].max_lazy; s->good_match = configuration_table[level].good_length; s->nice_match = configuration_table[level].nice_length; s->max_chain_length = configuration_table[level].max_chain; } s->strategy = strategy; return err; } /* ========================================================================= * Put a short in the pending buffer. The 16-bit value is put in MSB order. * IN assertion: the stream state is correct and there is enough room in * pending_buf. */ local void putShortMSB (s, b) deflate_state *s; uInt b; { put_byte(s, (Byte)(b >> 8)); put_byte(s, (Byte)(b & 0xff)); } /* ========================================================================= * Flush as much pending output as possible. All deflate() output goes * through this function so some applications may wish to modify it * to avoid allocating a large strm->next_out buffer and copying into it. * (See also read_buf()). */ local void flush_pending(strm) z_streamp strm; { deflate_state *s = (deflate_state *) strm->state; unsigned len = s->pending; if (len > strm->avail_out) len = strm->avail_out; if (len == 0) return; if (strm->next_out != Z_NULL) { zmemcpy(strm->next_out, s->pending_out, len); strm->next_out += len; } s->pending_out += len; strm->total_out += len; strm->avail_out -= len; s->pending -= len; if (s->pending == 0) { s->pending_out = s->pending_buf; } } /* ========================================================================= */ int deflate (strm, flush) z_streamp strm; int flush; { int old_flush; /* value of flush param for previous deflate call */ deflate_state *s; if (strm == Z_NULL || strm->state == Z_NULL || flush > Z_FINISH || flush < 0) { return Z_STREAM_ERROR; } s = (deflate_state *) strm->state; if ((strm->next_in == Z_NULL && strm->avail_in != 0) || (s->status == FINISH_STATE && flush != Z_FINISH)) { ERR_RETURN(strm, Z_STREAM_ERROR); } if (strm->avail_out == 0) ERR_RETURN(strm, Z_BUF_ERROR); s->strm = strm; /* just in case */ old_flush = s->last_flush; s->last_flush = flush; /* Write the zlib header */ if (s->status == INIT_STATE) { uInt header = (Z_DEFLATED + ((s->w_bits-8)<<4)) << 8; uInt level_flags = (s->level-1) >> 1; if (level_flags > 3) level_flags = 3; header |= (level_flags << 6); if (s->strstart != 0) header |= PRESET_DICT; header += 31 - (header % 31); s->status = BUSY_STATE; putShortMSB(s, header); /* Save the adler32 of the preset dictionary: */ if (s->strstart != 0) { putShortMSB(s, (uInt)(strm->adler >> 16)); putShortMSB(s, (uInt)(strm->adler & 0xffff)); } strm->adler = 1L; } /* Flush as much pending output as possible */ if (s->pending != 0) { flush_pending(strm); if (strm->avail_out == 0) { /* Since avail_out is 0, deflate will be called again with * more output space, but possibly with both pending and * avail_in equal to zero. There won't be anything to do, * but this is not an error situation so make sure we * return OK instead of BUF_ERROR at next call of deflate: */ s->last_flush = -1; return Z_OK; } /* Make sure there is something to do and avoid duplicate consecutive * flushes. For repeated and useless calls with Z_FINISH, we keep * returning Z_STREAM_END instead of Z_BUFF_ERROR. */ } else if (strm->avail_in == 0 && flush <= old_flush && flush != Z_FINISH) { ERR_RETURN(strm, Z_BUF_ERROR); } /* User must not provide more input after the first FINISH: */ if (s->status == FINISH_STATE && strm->avail_in != 0) { ERR_RETURN(strm, Z_BUF_ERROR); } /* Start a new block or continue the current one. */ if (strm->avail_in != 0 || s->lookahead != 0 || (flush != Z_NO_FLUSH && s->status != FINISH_STATE)) { block_state bstate; bstate = (*(configuration_table[s->level].func))(s, flush); if (bstate == finish_started || bstate == finish_done) { s->status = FINISH_STATE; } if (bstate == need_more || bstate == finish_started) { if (strm->avail_out == 0) { s->last_flush = -1; /* avoid BUF_ERROR next call, see above */ } return Z_OK; /* If flush != Z_NO_FLUSH && avail_out == 0, the next call * of deflate should use the same flush parameter to make sure * that the flush is complete. So we don't have to output an * empty block here, this will be done at next call. This also * ensures that for a very small output buffer, we emit at most * one empty block. */ } if (bstate == block_done) { if (flush == Z_PARTIAL_FLUSH) { _tr_align(s); } else if (flush == Z_PACKET_FLUSH) { /* Output just the 3-bit `stored' block type value, but not a zero length. */ _tr_stored_type_only(s); } else { /* FULL_FLUSH or SYNC_FLUSH */ _tr_stored_block(s, (char*)0, 0L, 0); /* For a full flush, this empty block will be recognized * as a special marker by inflate_sync(). */ if (flush == Z_FULL_FLUSH) { CLEAR_HASH(s); /* forget history */ } } flush_pending(strm); if (strm->avail_out == 0) { s->last_flush = -1; /* avoid BUF_ERROR at next call, see above */ return Z_OK; } } } Assert(strm->avail_out > 0, "bug2"); if (flush != Z_FINISH) return Z_OK; if (s->noheader) return Z_STREAM_END; /* Write the zlib trailer (adler32) */ putShortMSB(s, (uInt)(strm->adler >> 16)); putShortMSB(s, (uInt)(strm->adler & 0xffff)); flush_pending(strm); /* If avail_out is zero, the application will call deflate again * to flush the rest. */ s->noheader = -1; /* write the trailer only once! */ return s->pending != 0 ? Z_OK : Z_STREAM_END; } /* ========================================================================= */ int deflateEnd (strm) z_streamp strm; { int status; deflate_state *s; if (strm == Z_NULL || strm->state == Z_NULL) return Z_STREAM_ERROR; s = (deflate_state *) strm->state; status = s->status; if (status != INIT_STATE && status != BUSY_STATE && status != FINISH_STATE) { return Z_STREAM_ERROR; } /* Deallocate in reverse order of allocations: */ TRY_FREE(strm, s->pending_buf); TRY_FREE(strm, s->head); TRY_FREE(strm, s->prev); TRY_FREE(strm, s->window); ZFREE(strm, s); strm->state = Z_NULL; return status == BUSY_STATE ? Z_DATA_ERROR : Z_OK; } /* ========================================================================= * Copy the source state to the destination state. */ int deflateCopy (dest, source) z_streamp dest; z_streamp source; { deflate_state *ds; deflate_state *ss; ushf *overlay; if (source == Z_NULL || dest == Z_NULL || source->state == Z_NULL) return Z_STREAM_ERROR; ss = (deflate_state *) source->state; zmemcpy(dest, source, sizeof(*dest)); ds = (deflate_state *) ZALLOC(dest, 1, sizeof(deflate_state)); if (ds == Z_NULL) return Z_MEM_ERROR; dest->state = (struct internal_state FAR *) ds; zmemcpy(ds, ss, sizeof(*ds)); ds->strm = dest; ds->window = (Bytef *) ZALLOC(dest, ds->w_size, 2*sizeof(Byte)); ds->prev = (Posf *) ZALLOC(dest, ds->w_size, sizeof(Pos)); ds->head = (Posf *) ZALLOC(dest, ds->hash_size, sizeof(Pos)); overlay = (ushf *) ZALLOC(dest, ds->lit_bufsize, sizeof(ush)+2); ds->pending_buf = (uchf *) overlay; if (ds->window == Z_NULL || ds->prev == Z_NULL || ds->head == Z_NULL || ds->pending_buf == Z_NULL) { deflateEnd (dest); return Z_MEM_ERROR; } /* ??? following zmemcpy doesn't work for 16-bit MSDOS */ zmemcpy(ds->window, ss->window, ds->w_size * 2 * sizeof(Byte)); zmemcpy(ds->prev, ss->prev, ds->w_size * sizeof(Pos)); zmemcpy(ds->head, ss->head, ds->hash_size * sizeof(Pos)); zmemcpy(ds->pending_buf, ss->pending_buf, (uInt)ds->pending_buf_size); ds->pending_out = ds->pending_buf + (ss->pending_out - ss->pending_buf); ds->d_buf = overlay + ds->lit_bufsize/sizeof(ush); ds->l_buf = ds->pending_buf + (1+sizeof(ush))*ds->lit_bufsize; ds->l_desc.dyn_tree = ds->dyn_ltree; ds->d_desc.dyn_tree = ds->dyn_dtree; ds->bl_desc.dyn_tree = ds->bl_tree; return Z_OK; } /* =========================================================================== * Return the number of bytes of output which are immediately available * for output from the decompressor. */ int deflateOutputPending (strm) z_streamp strm; { if (strm == Z_NULL || strm->state == Z_NULL) return 0; return ((deflate_state *)(strm->state))->pending; } /* =========================================================================== * Read a new buffer from the current input stream, update the adler32 * and total number of bytes read. All deflate() input goes through * this function so some applications may wish to modify it to avoid * allocating a large strm->next_in buffer and copying from it. * (See also flush_pending()). */ local int read_buf(strm, buf, size) z_streamp strm; charf *buf; unsigned size; { unsigned len = strm->avail_in; if (len > size) len = size; if (len == 0) return 0; strm->avail_in -= len; if (!((deflate_state *)(strm->state))->noheader) { strm->adler = adler32(strm->adler, strm->next_in, len); } zmemcpy(buf, strm->next_in, len); strm->next_in += len; strm->total_in += len; return (int)len; } /* =========================================================================== * Initialize the "longest match" routines for a new zlib stream */ local void lm_init (s) deflate_state *s; { s->window_size = (ulg)2L*s->w_size; CLEAR_HASH(s); /* Set the default configuration parameters: */ s->max_lazy_match = configuration_table[s->level].max_lazy; s->good_match = configuration_table[s->level].good_length; s->nice_match = configuration_table[s->level].nice_length; s->max_chain_length = configuration_table[s->level].max_chain; s->strstart = 0; s->block_start = 0L; s->lookahead = 0; s->match_length = s->prev_length = MIN_MATCH-1; s->match_available = 0; s->ins_h = 0; #ifdef ASMV match_init(); /* initialize the asm code */ #endif } /* =========================================================================== * Set match_start to the longest match starting at the given string and * return its length. Matches shorter or equal to prev_length are discarded, * in which case the result is equal to prev_length and match_start is * garbage. * IN assertions: cur_match is the head of the hash chain for the current * string (strstart) and its distance is <= MAX_DIST, and prev_length >= 1 * OUT assertion: the match length is not greater than s->lookahead. */ #ifndef ASMV /* For 80x86 and 680x0, an optimized version will be provided in match.asm or * match.S. The code will be functionally equivalent. */ local uInt longest_match(s, cur_match) deflate_state *s; IPos cur_match; /* current match */ { unsigned chain_length = s->max_chain_length;/* max hash chain length */ register Bytef *scan = s->window + s->strstart; /* current string */ register Bytef *match; /* matched string */ register int len; /* length of current match */ int best_len = s->prev_length; /* best match length so far */ int nice_match = s->nice_match; /* stop if match long enough */ IPos limit = s->strstart > (IPos)MAX_DIST(s) ? s->strstart - (IPos)MAX_DIST(s) : NIL; /* Stop when cur_match becomes <= limit. To simplify the code, * we prevent matches with the string of window index 0. */ Posf *prev = s->prev; uInt wmask = s->w_mask; #ifdef UNALIGNED_OK /* Compare two bytes at a time. Note: this is not always beneficial. * Try with and without -DUNALIGNED_OK to check. */ register Bytef *strend = s->window + s->strstart + MAX_MATCH - 1; register ush scan_start = *(ushf*)scan; register ush scan_end = *(ushf*)(scan+best_len-1); #else register Bytef *strend = s->window + s->strstart + MAX_MATCH; register Byte scan_end1 = scan[best_len-1]; register Byte scan_end = scan[best_len]; #endif /* The code is optimized for HASH_BITS >= 8 and MAX_MATCH-2 multiple of 16. * It is easy to get rid of this optimization if necessary. */ Assert(s->hash_bits >= 8 && MAX_MATCH == 258, "Code too clever"); /* Do not waste too much time if we already have a good match: */ if (s->prev_length >= s->good_match) { chain_length >>= 2; } /* Do not look for matches beyond the end of the input. This is necessary * to make deflate deterministic. */ if ((uInt)nice_match > s->lookahead) nice_match = s->lookahead; Assert((ulg)s->strstart <= s->window_size-MIN_LOOKAHEAD, "need lookahead"); do { Assert(cur_match < s->strstart, "no future"); match = s->window + cur_match; /* Skip to next match if the match length cannot increase * or if the match length is less than 2: */ #if (defined(UNALIGNED_OK) && MAX_MATCH == 258) /* This code assumes sizeof(unsigned short) == 2. Do not use * UNALIGNED_OK if your compiler uses a different size. */ if (*(ushf*)(match+best_len-1) != scan_end || *(ushf*)match != scan_start) continue; /* It is not necessary to compare scan[2] and match[2] since they are * always equal when the other bytes match, given that the hash keys * are equal and that HASH_BITS >= 8. Compare 2 bytes at a time at * strstart+3, +5, ... up to strstart+257. We check for insufficient * lookahead only every 4th comparison; the 128th check will be made * at strstart+257. If MAX_MATCH-2 is not a multiple of 8, it is * necessary to put more guard bytes at the end of the window, or * to check more often for insufficient lookahead. */ Assert(scan[2] == match[2], "scan[2]?"); scan++, match++; do { } while (*(ushf*)(scan+=2) == *(ushf*)(match+=2) && *(ushf*)(scan+=2) == *(ushf*)(match+=2) && *(ushf*)(scan+=2) == *(ushf*)(match+=2) && *(ushf*)(scan+=2) == *(ushf*)(match+=2) && scan < strend); /* The funny "do {}" generates better code on most compilers */ /* Here, scan <= window+strstart+257 */ Assert(scan <= s->window+(unsigned)(s->window_size-1), "wild scan"); if (*scan == *match) scan++; len = (MAX_MATCH - 1) - (int)(strend-scan); scan = strend - (MAX_MATCH-1); #else /* UNALIGNED_OK */ if (match[best_len] != scan_end || match[best_len-1] != scan_end1 || *match != *scan || *++match != scan[1]) continue; /* The check at best_len-1 can be removed because it will be made * again later. (This heuristic is not always a win.) * It is not necessary to compare scan[2] and match[2] since they * are always equal when the other bytes match, given that * the hash keys are equal and that HASH_BITS >= 8. */ scan += 2, match++; Assert(*scan == *match, "match[2]?"); /* We check for insufficient lookahead only every 8th comparison; * the 256th check will be made at strstart+258. */ do { } while (*++scan == *++match && *++scan == *++match && *++scan == *++match && *++scan == *++match && *++scan == *++match && *++scan == *++match && *++scan == *++match && *++scan == *++match && scan < strend); Assert(scan <= s->window+(unsigned)(s->window_size-1), "wild scan"); len = MAX_MATCH - (int)(strend - scan); scan = strend - MAX_MATCH; #endif /* UNALIGNED_OK */ if (len > best_len) { s->match_start = cur_match; best_len = len; if (len >= nice_match) break; #ifdef UNALIGNED_OK scan_end = *(ushf*)(scan+best_len-1); #else scan_end1 = scan[best_len-1]; scan_end = scan[best_len]; #endif } } while ((cur_match = prev[cur_match & wmask]) > limit && --chain_length != 0); if ((uInt)best_len <= s->lookahead) return best_len; return s->lookahead; } #endif /* ASMV */ #ifdef DEBUG_ZLIB /* =========================================================================== * Check that the match at match_start is indeed a match. */ local void check_match(s, start, match, length) deflate_state *s; IPos start, match; int length; { /* check that the match is indeed a match */ if (zmemcmp((charf *)s->window + match, (charf *)s->window + start, length) != EQUAL) { fprintf(stderr, " start %u, match %u, length %d\n", start, match, length); do { fprintf(stderr, "%c%c", s->window[match++], s->window[start++]); } while (--length != 0); z_error("invalid match"); } if (z_verbose > 1) { fprintf(stderr,"\\[%d,%d]", start-match, length); do { putc(s->window[start++], stderr); } while (--length != 0); } } #else # define check_match(s, start, match, length) #endif /* =========================================================================== * Fill the window when the lookahead becomes insufficient. * Updates strstart and lookahead. * * IN assertion: lookahead < MIN_LOOKAHEAD * OUT assertions: strstart <= window_size-MIN_LOOKAHEAD * At least one byte has been read, or avail_in == 0; reads are * performed for at least two bytes (required for the zip translate_eol * option -- not supported here). */ local void fill_window(s) deflate_state *s; { register unsigned n, m; register Posf *p; unsigned more; /* Amount of free space at the end of the window. */ uInt wsize = s->w_size; do { more = (unsigned)(s->window_size -(ulg)s->lookahead -(ulg)s->strstart); /* Deal with !@#$% 64K limit: */ if (more == 0 && s->strstart == 0 && s->lookahead == 0) { more = wsize; } else if (more == (unsigned)(-1)) { /* Very unlikely, but possible on 16 bit machine if strstart == 0 * and lookahead == 1 (input done one byte at time) */ more--; /* If the window is almost full and there is insufficient lookahead, * move the upper half to the lower one to make room in the upper half. */ } else if (s->strstart >= wsize+MAX_DIST(s)) { zmemcpy((charf *)s->window, (charf *)s->window+wsize, (unsigned)wsize); s->match_start -= wsize; s->strstart -= wsize; /* we now have strstart >= MAX_DIST */ s->block_start -= (long) wsize; /* Slide the hash table (could be avoided with 32 bit values at the expense of memory usage). We slide even when level == 0 to keep the hash table consistent if we switch back to level > 0 later. (Using level 0 permanently is not an optimal usage of zlib, so we don't care about this pathological case.) */ n = s->hash_size; p = &s->head[n]; do { m = *--p; *p = (Pos)(m >= wsize ? m-wsize : NIL); } while (--n); n = wsize; p = &s->prev[n]; do { m = *--p; *p = (Pos)(m >= wsize ? m-wsize : NIL); /* If n is not on any hash chain, prev[n] is garbage but * its value will never be used. */ } while (--n); more += wsize; } if (s->strm->avail_in == 0) return; /* If there was no sliding: * strstart <= WSIZE+MAX_DIST-1 && lookahead <= MIN_LOOKAHEAD - 1 && * more == window_size - lookahead - strstart * => more >= window_size - (MIN_LOOKAHEAD-1 + WSIZE + MAX_DIST-1) * => more >= window_size - 2*WSIZE + 2 * In the BIG_MEM or MMAP case (not yet supported), * window_size == input_size + MIN_LOOKAHEAD && * strstart + s->lookahead <= input_size => more >= MIN_LOOKAHEAD. * Otherwise, window_size == 2*WSIZE so more >= 2. * If there was sliding, more >= WSIZE. So in all cases, more >= 2. */ Assert(more >= 2, "more < 2"); n = read_buf(s->strm, (charf *)s->window + s->strstart + s->lookahead, more); s->lookahead += n; /* Initialize the hash value now that we have some input: */ if (s->lookahead >= MIN_MATCH) { s->ins_h = s->window[s->strstart]; UPDATE_HASH(s, s->ins_h, s->window[s->strstart+1]); #if MIN_MATCH != 3 Call UPDATE_HASH() MIN_MATCH-3 more times #endif } /* If the whole input has less than MIN_MATCH bytes, ins_h is garbage, * but this is not important since only literal bytes will be emitted. */ } while (s->lookahead < MIN_LOOKAHEAD && s->strm->avail_in != 0); } /* =========================================================================== * Flush the current block, with given end-of-file flag. * IN assertion: strstart is set to the end of the current match. */ #define FLUSH_BLOCK_ONLY(s, eof) { \ _tr_flush_block(s, (s->block_start >= 0L ? \ (charf *)&s->window[(unsigned)s->block_start] : \ (charf *)Z_NULL), \ (ulg)((long)s->strstart - s->block_start), \ (eof)); \ s->block_start = s->strstart; \ flush_pending(s->strm); \ Tracev((stderr,"[FLUSH]")); \ } /* Same but force premature exit if necessary. */ #define FLUSH_BLOCK(s, eof) { \ FLUSH_BLOCK_ONLY(s, eof); \ if (s->strm->avail_out == 0) return (eof) ? finish_started : need_more; \ } /* =========================================================================== * Copy without compression as much as possible from the input stream, return * the current block state. * This function does not insert new strings in the dictionary since * uncompressible data is probably not useful. This function is used * only for the level=0 compression option. * NOTE: this function should be optimized to avoid extra copying from * window to pending_buf. */ local block_state deflate_stored(s, flush) deflate_state *s; int flush; { /* Stored blocks are limited to 0xffff bytes, pending_buf is limited * to pending_buf_size, and each stored block has a 5 byte header: */ ulg max_block_size = 0xffff; ulg max_start; if (max_block_size > s->pending_buf_size - 5) { max_block_size = s->pending_buf_size - 5; } /* Copy as much as possible from input to output: */ for (;;) { /* Fill the window as much as possible: */ if (s->lookahead <= 1) { Assert(s->strstart < s->w_size+MAX_DIST(s) || s->block_start >= (long)s->w_size, "slide too late"); fill_window(s); if (s->lookahead == 0 && flush == Z_NO_FLUSH) return need_more; if (s->lookahead == 0) break; /* flush the current block */ } Assert(s->block_start >= 0L, "block gone"); s->strstart += s->lookahead; s->lookahead = 0; /* Emit a stored block if pending_buf will be full: */ max_start = s->block_start + max_block_size; if (s->strstart == 0 || (ulg)s->strstart >= max_start) { /* strstart == 0 is possible when wraparound on 16-bit machine */ s->lookahead = (uInt)(s->strstart - max_start); s->strstart = (uInt)max_start; FLUSH_BLOCK(s, 0); } /* Flush if we may have to slide, otherwise block_start may become * negative and the data will be gone: */ if (s->strstart - (uInt)s->block_start >= MAX_DIST(s)) { FLUSH_BLOCK(s, 0); } } FLUSH_BLOCK(s, flush == Z_FINISH); return flush == Z_FINISH ? finish_done : block_done; } /* =========================================================================== * Compress as much as possible from the input stream, return the current * block state. * This function does not perform lazy evaluation of matches and inserts * new strings in the dictionary only for unmatched strings or for short * matches. It is used only for the fast compression options. */ local block_state deflate_fast(s, flush) deflate_state *s; int flush; { IPos hash_head = NIL; /* head of the hash chain */ int bflush; /* set if current block must be flushed */ for (;;) { /* Make sure that we always have enough lookahead, except * at the end of the input file. We need MAX_MATCH bytes * for the next match, plus MIN_MATCH bytes to insert the * string following the next match. */ if (s->lookahead < MIN_LOOKAHEAD) { fill_window(s); if (s->lookahead < MIN_LOOKAHEAD && flush == Z_NO_FLUSH) { return need_more; } if (s->lookahead == 0) break; /* flush the current block */ } /* Insert the string window[strstart .. strstart+2] in the * dictionary, and set hash_head to the head of the hash chain: */ if (s->lookahead >= MIN_MATCH) { INSERT_STRING(s, s->strstart, hash_head); } /* Find the longest match, discarding those <= prev_length. * At this point we have always match_length < MIN_MATCH */ if (hash_head != NIL && s->strstart - hash_head <= MAX_DIST(s)) { /* To simplify the code, we prevent matches with the string * of window index 0 (in particular we have to avoid a match * of the string with itself at the start of the input file). */ if (s->strategy != Z_HUFFMAN_ONLY) { s->match_length = longest_match (s, hash_head); } /* longest_match() sets match_start */ } if (s->match_length >= MIN_MATCH) { check_match(s, s->strstart, s->match_start, s->match_length); bflush = _tr_tally(s, s->strstart - s->match_start, s->match_length - MIN_MATCH); s->lookahead -= s->match_length; /* Insert new strings in the hash table only if the match length * is not too large. This saves time but degrades compression. */ if (s->match_length <= s->max_insert_length && s->lookahead >= MIN_MATCH) { s->match_length--; /* string at strstart already in hash table */ do { s->strstart++; INSERT_STRING(s, s->strstart, hash_head); /* strstart never exceeds WSIZE-MAX_MATCH, so there are * always MIN_MATCH bytes ahead. */ } while (--s->match_length != 0); s->strstart++; } else { s->strstart += s->match_length; s->match_length = 0; s->ins_h = s->window[s->strstart]; UPDATE_HASH(s, s->ins_h, s->window[s->strstart+1]); #if MIN_MATCH != 3 Call UPDATE_HASH() MIN_MATCH-3 more times #endif /* If lookahead < MIN_MATCH, ins_h is garbage, but it does not * matter since it will be recomputed at next deflate call. */ } } else { /* No match, output a literal byte */ Tracevv((stderr,"%c", s->window[s->strstart])); bflush = _tr_tally (s, 0, s->window[s->strstart]); s->lookahead--; s->strstart++; } if (bflush) FLUSH_BLOCK(s, 0); } FLUSH_BLOCK(s, flush == Z_FINISH); return flush == Z_FINISH ? finish_done : block_done; } /* =========================================================================== * Same as above, but achieves better compression. We use a lazy * evaluation for matches: a match is finally adopted only if there is * no better match at the next window position. */ local block_state deflate_slow(s, flush) deflate_state *s; int flush; { IPos hash_head = NIL; /* head of hash chain */ int bflush; /* set if current block must be flushed */ /* Process the input block. */ for (;;) { /* Make sure that we always have enough lookahead, except * at the end of the input file. We need MAX_MATCH bytes * for the next match, plus MIN_MATCH bytes to insert the * string following the next match. */ if (s->lookahead < MIN_LOOKAHEAD) { fill_window(s); if (s->lookahead < MIN_LOOKAHEAD && flush == Z_NO_FLUSH) { return need_more; } if (s->lookahead == 0) break; /* flush the current block */ } /* Insert the string window[strstart .. strstart+2] in the * dictionary, and set hash_head to the head of the hash chain: */ if (s->lookahead >= MIN_MATCH) { INSERT_STRING(s, s->strstart, hash_head); } /* Find the longest match, discarding those <= prev_length. */ s->prev_length = s->match_length, s->prev_match = s->match_start; s->match_length = MIN_MATCH-1; if (hash_head != NIL && s->prev_length < s->max_lazy_match && s->strstart - hash_head <= MAX_DIST(s)) { /* To simplify the code, we prevent matches with the string * of window index 0 (in particular we have to avoid a match * of the string with itself at the start of the input file). */ if (s->strategy != Z_HUFFMAN_ONLY) { s->match_length = longest_match (s, hash_head); } /* longest_match() sets match_start */ if (s->match_length <= 5 && (s->strategy == Z_FILTERED || (s->match_length == MIN_MATCH && s->strstart - s->match_start > TOO_FAR))) { /* If prev_match is also MIN_MATCH, match_start is garbage * but we will ignore the current match anyway. */ s->match_length = MIN_MATCH-1; } } /* If there was a match at the previous step and the current * match is not better, output the previous match: */ if (s->prev_length >= MIN_MATCH && s->match_length <= s->prev_length) { uInt max_insert = s->strstart + s->lookahead - MIN_MATCH; /* Do not insert strings in hash table beyond this. */ check_match(s, s->strstart-1, s->prev_match, s->prev_length); bflush = _tr_tally(s, s->strstart -1 - s->prev_match, s->prev_length - MIN_MATCH); /* Insert in hash table all strings up to the end of the match. * strstart-1 and strstart are already inserted. If there is not * enough lookahead, the last two strings are not inserted in * the hash table. */ s->lookahead -= s->prev_length-1; s->prev_length -= 2; do { if (++s->strstart <= max_insert) { INSERT_STRING(s, s->strstart, hash_head); } } while (--s->prev_length != 0); s->match_available = 0; s->match_length = MIN_MATCH-1; s->strstart++; if (bflush) FLUSH_BLOCK(s, 0); } else if (s->match_available) { /* If there was no match at the previous position, output a * single literal. If there was a match but the current match * is longer, truncate the previous match to a single literal. */ Tracevv((stderr,"%c", s->window[s->strstart-1])); if (_tr_tally (s, 0, s->window[s->strstart-1])) { FLUSH_BLOCK_ONLY(s, 0); } s->strstart++; s->lookahead--; if (s->strm->avail_out == 0) return need_more; } else { /* There is no previous match to compare with, wait for * the next step to decide. */ s->match_available = 1; s->strstart++; s->lookahead--; } } Assert (flush != Z_NO_FLUSH, "no flush?"); if (s->match_available) { Tracevv((stderr,"%c", s->window[s->strstart-1])); _tr_tally (s, 0, s->window[s->strstart-1]); s->match_available = 0; } FLUSH_BLOCK(s, flush == Z_FINISH); return flush == Z_FINISH ? finish_done : block_done; } /* --- deflate.c */ /* +++ trees.c */ /* trees.c -- output deflated data using Huffman coding * Copyright (C) 1995-1996 Jean-loup Gailly * For conditions of distribution and use, see copyright notice in zlib.h */ /* * ALGORITHM * * The "deflation" process uses several Huffman trees. The more * common source values are represented by shorter bit sequences. * * Each code tree is stored in a compressed form which is itself * a Huffman encoding of the lengths of all the code strings (in * ascending order by source values). The actual code strings are * reconstructed from the lengths in the inflate process, as described * in the deflate specification. * * REFERENCES * * Deutsch, L.P.,"'Deflate' Compressed Data Format Specification". * Available in ftp.uu.net:/pub/archiving/zip/doc/deflate-1.1.doc * * Storer, James A. * Data Compression: Methods and Theory, pp. 49-50. * Computer Science Press, 1988. ISBN 0-7167-8156-5. * * Sedgewick, R. * Algorithms, p290. * Addison-Wesley, 1983. ISBN 0-201-06672-6. */ /* From: trees.c,v 1.11 1996/07/24 13:41:06 me Exp $ */ /* #include "deflate.h" */ #ifdef DEBUG_ZLIB # include <ctype.h> #endif /* =========================================================================== * Constants */ #define MAX_BL_BITS 7 /* Bit length codes must not exceed MAX_BL_BITS bits */ #define END_BLOCK 256 /* end of block literal code */ #define REP_3_6 16 /* repeat previous bit length 3-6 times (2 bits of repeat count) */ #define REPZ_3_10 17 /* repeat a zero length 3-10 times (3 bits of repeat count) */ #define REPZ_11_138 18 /* repeat a zero length 11-138 times (7 bits of repeat count) */ local int extra_lbits[LENGTH_CODES] /* extra bits for each length code */ = {0,0,0,0,0,0,0,0,1,1,1,1,2,2,2,2,3,3,3,3,4,4,4,4,5,5,5,5,0}; local int extra_dbits[D_CODES] /* extra bits for each distance code */ = {0,0,0,0,1,1,2,2,3,3,4,4,5,5,6,6,7,7,8,8,9,9,10,10,11,11,12,12,13,13}; local int extra_blbits[BL_CODES]/* extra bits for each bit length code */ = {0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,2,3,7}; local uch bl_order[BL_CODES] = {16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15}; /* The lengths of the bit length codes are sent in order of decreasing * probability, to avoid transmitting the lengths for unused bit length codes. */ #define Buf_size (8 * 2*sizeof(char)) /* Number of bits used within bi_buf. (bi_buf might be implemented on * more than 16 bits on some systems.) */ /* =========================================================================== * Local data. These are initialized only once. */ local ct_data static_ltree[L_CODES+2]; /* The static literal tree. Since the bit lengths are imposed, there is no * need for the L_CODES extra codes used during heap construction. However * The codes 286 and 287 are needed to build a canonical tree (see _tr_init * below). */ local ct_data static_dtree[D_CODES]; /* The static distance tree. (Actually a trivial tree since all codes use * 5 bits.) */ local uch dist_code[512]; /* distance codes. The first 256 values correspond to the distances * 3 .. 258, the last 256 values correspond to the top 8 bits of * the 15 bit distances. */ local uch length_code[MAX_MATCH-MIN_MATCH+1]; /* length code for each normalized match length (0 == MIN_MATCH) */ local int base_length[LENGTH_CODES]; /* First normalized length for each code (0 = MIN_MATCH) */ local int base_dist[D_CODES]; /* First normalized distance for each code (0 = distance of 1) */ struct static_tree_desc_s { ct_data *static_tree; /* static tree or NULL */ intf *extra_bits; /* extra bits for each code or NULL */ int extra_base; /* base index for extra_bits */ int elems; /* max number of elements in the tree */ int max_length; /* max bit length for the codes */ }; local static_tree_desc static_l_desc = {static_ltree, extra_lbits, LITERALS+1, L_CODES, MAX_BITS}; local static_tree_desc static_d_desc = {static_dtree, extra_dbits, 0, D_CODES, MAX_BITS}; local static_tree_desc static_bl_desc = {(ct_data *)0, extra_blbits, 0, BL_CODES, MAX_BL_BITS}; /* =========================================================================== * Local (static) routines in this file. */ local void tr_static_init OF((void)); local void init_block OF((deflate_state *s)); local void pqdownheap OF((deflate_state *s, ct_data *tree, int k)); local void gen_bitlen OF((deflate_state *s, tree_desc *desc)); local void gen_codes OF((ct_data *tree, int max_code, ushf *bl_count)); local void build_tree OF((deflate_state *s, tree_desc *desc)); local void scan_tree OF((deflate_state *s, ct_data *tree, int max_code)); local void send_tree OF((deflate_state *s, ct_data *tree, int max_code)); local int build_bl_tree OF((deflate_state *s)); local void send_all_trees OF((deflate_state *s, int lcodes, int dcodes, int blcodes)); local void compress_block OF((deflate_state *s, ct_data *ltree, ct_data *dtree)); local void set_data_type OF((deflate_state *s)); local unsigned bi_reverse OF((unsigned value, int length)); local void bi_windup OF((deflate_state *s)); local void bi_flush OF((deflate_state *s)); local void copy_block OF((deflate_state *s, charf *buf, unsigned len, int header)); #ifndef DEBUG_ZLIB # define send_code(s, c, tree) send_bits(s, tree[(c)].Code, tree[(c)].Len) /* Send a code of the given tree. c and tree must not have side effects */ #else /* DEBUG_ZLIB */ # define send_code(s, c, tree) \ { if (verbose>2) fprintf(stderr,"\ncd %3d ",(c)); \ send_bits(s, tree[c].Code, tree[c].Len); } #endif #define d_code(dist) \ ((dist) < 256 ? dist_code[dist] : dist_code[256+((dist)>>7)]) /* Mapping from a distance to a distance code. dist is the distance - 1 and * must not have side effects. dist_code[256] and dist_code[257] are never * used. */ /* =========================================================================== * Output a short LSB first on the stream. * IN assertion: there is enough room in pendingBuf. */ #define put_short(s, w) { \ put_byte(s, (uch)((w) & 0xff)); \ put_byte(s, (uch)((ush)(w) >> 8)); \ } /* =========================================================================== * Send a value on a given number of bits. * IN assertion: length <= 16 and value fits in length bits. */ #ifdef DEBUG_ZLIB local void send_bits OF((deflate_state *s, int value, int length)); local void send_bits(s, value, length) deflate_state *s; int value; /* value to send */ int length; /* number of bits */ { Tracevv((stderr," l %2d v %4x ", length, value)); Assert(length > 0 && length <= 15, "invalid length"); s->bits_sent += (ulg)length; /* If not enough room in bi_buf, use (valid) bits from bi_buf and * (16 - bi_valid) bits from value, leaving (width - (16-bi_valid)) * unused bits in value. */ if (s->bi_valid > (int)Buf_size - length) { s->bi_buf |= (value << s->bi_valid); put_short(s, s->bi_buf); s->bi_buf = (ush)value >> (Buf_size - s->bi_valid); s->bi_valid += length - Buf_size; } else { s->bi_buf |= value << s->bi_valid; s->bi_valid += length; } } #else /* !DEBUG_ZLIB */ #define send_bits(s, value, length) \ { int len = (length);\ if ((s)->bi_valid > (int)Buf_size - len) {\ int val = (value);\ (s)->bi_buf |= (val << (s)->bi_valid);\ put_short((s), (s)->bi_buf);\ (s)->bi_buf = (ush)val >> (Buf_size - (s)->bi_valid);\ (s)->bi_valid += len - Buf_size;\ } else {\ (s)->bi_buf |= (value) << (s)->bi_valid;\ (s)->bi_valid += len;\ }\ } #endif /* DEBUG_ZLIB */ /* the arguments must not have side effects */ /* =========================================================================== * Initialize the various 'constant' tables. In a multi-threaded environment, * this function may be called by two threads concurrently, but this is * harmless since both invocations do exactly the same thing. */ local void tr_static_init() { static int static_init_done = 0; int n; /* iterates over tree elements */ int bits; /* bit counter */ int length; /* length value */ int code; /* code value */ int dist; /* distance index */ ush bl_count[MAX_BITS+1]; /* number of codes at each bit length for an optimal tree */ if (static_init_done) return; /* Initialize the mapping length (0..255) -> length code (0..28) */ length = 0; for (code = 0; code < LENGTH_CODES-1; code++) { base_length[code] = length; for (n = 0; n < (1<<extra_lbits[code]); n++) { length_code[length++] = (uch)code; } } Assert (length == 256, "tr_static_init: length != 256"); /* Note that the length 255 (match length 258) can be represented * in two different ways: code 284 + 5 bits or code 285, so we * overwrite length_code[255] to use the best encoding: */ length_code[length-1] = (uch)code; /* Initialize the mapping dist (0..32K) -> dist code (0..29) */ dist = 0; for (code = 0 ; code < 16; code++) { base_dist[code] = dist; for (n = 0; n < (1<<extra_dbits[code]); n++) { dist_code[dist++] = (uch)code; } } Assert (dist == 256, "tr_static_init: dist != 256"); dist >>= 7; /* from now on, all distances are divided by 128 */ for ( ; code < D_CODES; code++) { base_dist[code] = dist << 7; for (n = 0; n < (1<<(extra_dbits[code]-7)); n++) { dist_code[256 + dist++] = (uch)code; } } Assert (dist == 256, "tr_static_init: 256+dist != 512"); /* Construct the codes of the static literal tree */ for (bits = 0; bits <= MAX_BITS; bits++) bl_count[bits] = 0; n = 0; while (n <= 143) static_ltree[n++].Len = 8, bl_count[8]++; while (n <= 255) static_ltree[n++].Len = 9, bl_count[9]++; while (n <= 279) static_ltree[n++].Len = 7, bl_count[7]++; while (n <= 287) static_ltree[n++].Len = 8, bl_count[8]++; /* Codes 286 and 287 do not exist, but we must include them in the * tree construction to get a canonical Huffman tree (longest code * all ones) */ gen_codes((ct_data *)static_ltree, L_CODES+1, bl_count); /* The static distance tree is trivial: */ for (n = 0; n < D_CODES; n++) { static_dtree[n].Len = 5; static_dtree[n].Code = bi_reverse((unsigned)n, 5); } static_init_done = 1; } /* =========================================================================== * Initialize the tree data structures for a new zlib stream. */ void _tr_init(s) deflate_state *s; { tr_static_init(); s->compressed_len = 0L; s->l_desc.dyn_tree = s->dyn_ltree; s->l_desc.stat_desc = &static_l_desc; s->d_desc.dyn_tree = s->dyn_dtree; s->d_desc.stat_desc = &static_d_desc; s->bl_desc.dyn_tree = s->bl_tree; s->bl_desc.stat_desc = &static_bl_desc; s->bi_buf = 0; s->bi_valid = 0; s->last_eob_len = 8; /* enough lookahead for inflate */ #ifdef DEBUG_ZLIB s->bits_sent = 0L; #endif /* Initialize the first block of the first file: */ init_block(s); } /* =========================================================================== * Initialize a new block. */ local void init_block(s) deflate_state *s; { int n; /* iterates over tree elements */ /* Initialize the trees. */ for (n = 0; n < L_CODES; n++) s->dyn_ltree[n].Freq = 0; for (n = 0; n < D_CODES; n++) s->dyn_dtree[n].Freq = 0; for (n = 0; n < BL_CODES; n++) s->bl_tree[n].Freq = 0; s->dyn_ltree[END_BLOCK].Freq = 1; s->opt_len = s->static_len = 0L; s->last_lit = s->matches = 0; } #define SMALLEST 1 /* Index within the heap array of least frequent node in the Huffman tree */ /* =========================================================================== * Remove the smallest element from the heap and recreate the heap with * one less element. Updates heap and heap_len. */ #define pqremove(s, tree, top) \ {\ top = s->heap[SMALLEST]; \ s->heap[SMALLEST] = s->heap[s->heap_len--]; \ pqdownheap(s, tree, SMALLEST); \ } /* =========================================================================== * Compares to subtrees, using the tree depth as tie breaker when * the subtrees have equal frequency. This minimizes the worst case length. */ #define smaller(tree, n, m, depth) \ (tree[n].Freq < tree[m].Freq || \ (tree[n].Freq == tree[m].Freq && depth[n] <= depth[m])) /* =========================================================================== * Restore the heap property by moving down the tree starting at node k, * exchanging a node with the smallest of its two sons if necessary, stopping * when the heap property is re-established (each father smaller than its * two sons). */ local void pqdownheap(s, tree, k) deflate_state *s; ct_data *tree; /* the tree to restore */ int k; /* node to move down */ { int v = s->heap[k]; int j = k << 1; /* left son of k */ while (j <= s->heap_len) { /* Set j to the smallest of the two sons: */ if (j < s->heap_len && smaller(tree, s->heap[j+1], s->heap[j], s->depth)) { j++; } /* Exit if v is smaller than both sons */ if (smaller(tree, v, s->heap[j], s->depth)) break; /* Exchange v with the smallest son */ s->heap[k] = s->heap[j]; k = j; /* And continue down the tree, setting j to the left son of k */ j <<= 1; } s->heap[k] = v; } /* =========================================================================== * Compute the optimal bit lengths for a tree and update the total bit length * for the current block. * IN assertion: the fields freq and dad are set, heap[heap_max] and * above are the tree nodes sorted by increasing frequency. * OUT assertions: the field len is set to the optimal bit length, the * array bl_count contains the frequencies for each bit length. * The length opt_len is updated; static_len is also updated if stree is * not null. */ local void gen_bitlen(s, desc) deflate_state *s; tree_desc *desc; /* the tree descriptor */ { ct_data *tree = desc->dyn_tree; int max_code = desc->max_code; ct_data *stree = desc->stat_desc->static_tree; intf *extra = desc->stat_desc->extra_bits; int base = desc->stat_desc->extra_base; int max_length = desc->stat_desc->max_length; int h; /* heap index */ int n, m; /* iterate over the tree elements */ int bits; /* bit length */ int xbits; /* extra bits */ ush f; /* frequency */ int overflow = 0; /* number of elements with bit length too large */ for (bits = 0; bits <= MAX_BITS; bits++) s->bl_count[bits] = 0; /* In a first pass, compute the optimal bit lengths (which may * overflow in the case of the bit length tree). */ tree[s->heap[s->heap_max]].Len = 0; /* root of the heap */ for (h = s->heap_max+1; h < HEAP_SIZE; h++) { n = s->heap[h]; bits = tree[tree[n].Dad].Len + 1; if (bits > max_length) bits = max_length, overflow++; tree[n].Len = (ush)bits; /* We overwrite tree[n].Dad which is no longer needed */ if (n > max_code) continue; /* not a leaf node */ s->bl_count[bits]++; xbits = 0; if (n >= base) xbits = extra[n-base]; f = tree[n].Freq; s->opt_len += (ulg)f * (bits + xbits); if (stree) s->static_len += (ulg)f * (stree[n].Len + xbits); } if (overflow == 0) return; Trace((stderr,"\nbit length overflow\n")); /* This happens for example on obj2 and pic of the Calgary corpus */ /* Find the first bit length which could increase: */ do { bits = max_length-1; while (s->bl_count[bits] == 0) bits--; s->bl_count[bits]--; /* move one leaf down the tree */ s->bl_count[bits+1] += 2; /* move one overflow item as its brother */ s->bl_count[max_length]--; /* The brother of the overflow item also moves one step up, * but this does not affect bl_count[max_length] */ overflow -= 2; } while (overflow > 0); /* Now recompute all bit lengths, scanning in increasing frequency. * h is still equal to HEAP_SIZE. (It is simpler to reconstruct all * lengths instead of fixing only the wrong ones. This idea is taken * from 'ar' written by Haruhiko Okumura.) */ for (bits = max_length; bits != 0; bits--) { n = s->bl_count[bits]; while (n != 0) { m = s->heap[--h]; if (m > max_code) continue; if (tree[m].Len != (unsigned) bits) { Trace((stderr,"code %d bits %d->%d\n", m, tree[m].Len, bits)); s->opt_len += ((long)bits - (long)tree[m].Len) *(long)tree[m].Freq; tree[m].Len = (ush)bits; } n--; } } } /* =========================================================================== * Generate the codes for a given tree and bit counts (which need not be * optimal). * IN assertion: the array bl_count contains the bit length statistics for * the given tree and the field len is set for all tree elements. * OUT assertion: the field code is set for all tree elements of non * zero code length. */ local void gen_codes (tree, max_code, bl_count) ct_data *tree; /* the tree to decorate */ int max_code; /* largest code with non zero frequency */ ushf *bl_count; /* number of codes at each bit length */ { ush next_code[MAX_BITS+1]; /* next code value for each bit length */ ush code = 0; /* running code value */ int bits; /* bit index */ int n; /* code index */ /* The distribution counts are first used to generate the code values * without bit reversal. */ for (bits = 1; bits <= MAX_BITS; bits++) { next_code[bits] = code = (code + bl_count[bits-1]) << 1; } /* Check that the bit counts in bl_count are consistent. The last code * must be all ones. */ Assert (code + bl_count[MAX_BITS]-1 == (1<<MAX_BITS)-1, "inconsistent bit counts"); Tracev((stderr,"\ngen_codes: max_code %d ", max_code)); for (n = 0; n <= max_code; n++) { int len = tree[n].Len; if (len == 0) continue; /* Now reverse the bits */ tree[n].Code = bi_reverse(next_code[len]++, len); Tracecv(tree != static_ltree, (stderr,"\nn %3d %c l %2d c %4x (%x) ", n, (isgraph(n) ? n : ' '), len, tree[n].Code, next_code[len]-1)); } } /* =========================================================================== * Construct one Huffman tree and assigns the code bit strings and lengths. * Update the total bit length for the current block. * IN assertion: the field freq is set for all tree elements. * OUT assertions: the fields len and code are set to the optimal bit length * and corresponding code. The length opt_len is updated; static_len is * also updated if stree is not null. The field max_code is set. */ local void build_tree(s, desc) deflate_state *s; tree_desc *desc; /* the tree descriptor */ { ct_data *tree = desc->dyn_tree; ct_data *stree = desc->stat_desc->static_tree; int elems = desc->stat_desc->elems; int n, m; /* iterate over heap elements */ int max_code = -1; /* largest code with non zero frequency */ int node; /* new node being created */ /* Construct the initial heap, with least frequent element in * heap[SMALLEST]. The sons of heap[n] are heap[2*n] and heap[2*n+1]. * heap[0] is not used. */ s->heap_len = 0, s->heap_max = HEAP_SIZE; for (n = 0; n < elems; n++) { if (tree[n].Freq != 0) { s->heap[++(s->heap_len)] = max_code = n; s->depth[n] = 0; } else { tree[n].Len = 0; } } /* The pkzip format requires that at least one distance code exists, * and that at least one bit should be sent even if there is only one * possible code. So to avoid special checks later on we force at least * two codes of non zero frequency. */ while (s->heap_len < 2) { node = s->heap[++(s->heap_len)] = (max_code < 2 ? ++max_code : 0); tree[node].Freq = 1; s->depth[node] = 0; s->opt_len--; if (stree) s->static_len -= stree[node].Len; /* node is 0 or 1 so it does not have extra bits */ } desc->max_code = max_code; /* The elements heap[heap_len/2+1 .. heap_len] are leaves of the tree, * establish sub-heaps of increasing lengths: */ for (n = s->heap_len/2; n >= 1; n--) pqdownheap(s, tree, n); /* Construct the Huffman tree by repeatedly combining the least two * frequent nodes. */ node = elems; /* next internal node of the tree */ do { pqremove(s, tree, n); /* n = node of least frequency */ m = s->heap[SMALLEST]; /* m = node of next least frequency */ s->heap[--(s->heap_max)] = n; /* keep the nodes sorted by frequency */ s->heap[--(s->heap_max)] = m; /* Create a new node father of n and m */ tree[node].Freq = tree[n].Freq + tree[m].Freq; s->depth[node] = (uch) (MAX(s->depth[n], s->depth[m]) + 1); tree[n].Dad = tree[m].Dad = (ush)node; #ifdef DUMP_BL_TREE if (tree == s->bl_tree) { fprintf(stderr,"\nnode %d(%d), sons %d(%d) %d(%d)", node, tree[node].Freq, n, tree[n].Freq, m, tree[m].Freq); } #endif /* and insert the new node in the heap */ s->heap[SMALLEST] = node++; pqdownheap(s, tree, SMALLEST); } while (s->heap_len >= 2); s->heap[--(s->heap_max)] = s->heap[SMALLEST]; /* At this point, the fields freq and dad are set. We can now * generate the bit lengths. */ gen_bitlen(s, (tree_desc *)desc); /* The field len is now set, we can generate the bit codes */ gen_codes ((ct_data *)tree, max_code, s->bl_count); } /* =========================================================================== * Scan a literal or distance tree to determine the frequencies of the codes * in the bit length tree. */ local void scan_tree (s, tree, max_code) deflate_state *s; ct_data *tree; /* the tree to be scanned */ int max_code; /* and its largest code of non zero frequency */ { int n; /* iterates over all tree elements */ int prevlen = -1; /* last emitted length */ int curlen; /* length of current code */ int nextlen = tree[0].Len; /* length of next code */ int count = 0; /* repeat count of the current code */ int max_count = 7; /* max repeat count */ int min_count = 4; /* min repeat count */ if (nextlen == 0) max_count = 138, min_count = 3; tree[max_code+1].Len = (ush)0xffff; /* guard */ for (n = 0; n <= max_code; n++) { curlen = nextlen; nextlen = tree[n+1].Len; if (++count < max_count && curlen == nextlen) { continue; } else if (count < min_count) { s->bl_tree[curlen].Freq += count; } else if (curlen != 0) { if (curlen != prevlen) s->bl_tree[curlen].Freq++; s->bl_tree[REP_3_6].Freq++; } else if (count <= 10) { s->bl_tree[REPZ_3_10].Freq++; } else { s->bl_tree[REPZ_11_138].Freq++; } count = 0; prevlen = curlen; if (nextlen == 0) { max_count = 138, min_count = 3; } else if (curlen == nextlen) { max_count = 6, min_count = 3; } else { max_count = 7, min_count = 4; } } } /* =========================================================================== * Send a literal or distance tree in compressed form, using the codes in * bl_tree. */ local void send_tree (s, tree, max_code) deflate_state *s; ct_data *tree; /* the tree to be scanned */ int max_code; /* and its largest code of non zero frequency */ { int n; /* iterates over all tree elements */ int prevlen = -1; /* last emitted length */ int curlen; /* length of current code */ int nextlen = tree[0].Len; /* length of next code */ int count = 0; /* repeat count of the current code */ int max_count = 7; /* max repeat count */ int min_count = 4; /* min repeat count */ /* tree[max_code+1].Len = -1; */ /* guard already set */ if (nextlen == 0) max_count = 138, min_count = 3; for (n = 0; n <= max_code; n++) { curlen = nextlen; nextlen = tree[n+1].Len; if (++count < max_count && curlen == nextlen) { continue; } else if (count < min_count) { do { send_code(s, curlen, s->bl_tree); } while (--count != 0); } else if (curlen != 0) { if (curlen != prevlen) { send_code(s, curlen, s->bl_tree); count--; } Assert(count >= 3 && count <= 6, " 3_6?"); send_code(s, REP_3_6, s->bl_tree); send_bits(s, count-3, 2); } else if (count <= 10) { send_code(s, REPZ_3_10, s->bl_tree); send_bits(s, count-3, 3); } else { send_code(s, REPZ_11_138, s->bl_tree); send_bits(s, count-11, 7); } count = 0; prevlen = curlen; if (nextlen == 0) { max_count = 138, min_count = 3; } else if (curlen == nextlen) { max_count = 6, min_count = 3; } else { max_count = 7, min_count = 4; } } } /* =========================================================================== * Construct the Huffman tree for the bit lengths and return the index in * bl_order of the last bit length code to send. */ local int build_bl_tree(s) deflate_state *s; { int max_blindex; /* index of last bit length code of non zero freq */ /* Determine the bit length frequencies for literal and distance trees */ scan_tree(s, (ct_data *)s->dyn_ltree, s->l_desc.max_code); scan_tree(s, (ct_data *)s->dyn_dtree, s->d_desc.max_code); /* Build the bit length tree: */ build_tree(s, (tree_desc *)(&(s->bl_desc))); /* opt_len now includes the length of the tree representations, except * the lengths of the bit lengths codes and the 5+5+4 bits for the counts. */ /* Determine the number of bit length codes to send. The pkzip format * requires that at least 4 bit length codes be sent. (appnote.txt says * 3 but the actual value used is 4.) */ for (max_blindex = BL_CODES-1; max_blindex >= 3; max_blindex--) { if (s->bl_tree[bl_order[max_blindex]].Len != 0) break; } /* Update opt_len to include the bit length tree and counts */ s->opt_len += 3*(max_blindex+1) + 5+5+4; Tracev((stderr, "\ndyn trees: dyn %ld, stat %ld", s->opt_len, s->static_len)); return max_blindex; } /* =========================================================================== * Send the header for a block using dynamic Huffman trees: the counts, the * lengths of the bit length codes, the literal tree and the distance tree. * IN assertion: lcodes >= 257, dcodes >= 1, blcodes >= 4. */ local void send_all_trees(s, lcodes, dcodes, blcodes) deflate_state *s; int lcodes, dcodes, blcodes; /* number of codes for each tree */ { int rank; /* index in bl_order */ Assert (lcodes >= 257 && dcodes >= 1 && blcodes >= 4, "not enough codes"); Assert (lcodes <= L_CODES && dcodes <= D_CODES && blcodes <= BL_CODES, "too many codes"); Tracev((stderr, "\nbl counts: ")); send_bits(s, lcodes-257, 5); /* not +255 as stated in appnote.txt */ send_bits(s, dcodes-1, 5); send_bits(s, blcodes-4, 4); /* not -3 as stated in appnote.txt */ for (rank = 0; rank < blcodes; rank++) { Tracev((stderr, "\nbl code %2d ", bl_order[rank])); send_bits(s, s->bl_tree[bl_order[rank]].Len, 3); } Tracev((stderr, "\nbl tree: sent %ld", s->bits_sent)); send_tree(s, (ct_data *)s->dyn_ltree, lcodes-1); /* literal tree */ Tracev((stderr, "\nlit tree: sent %ld", s->bits_sent)); send_tree(s, (ct_data *)s->dyn_dtree, dcodes-1); /* distance tree */ Tracev((stderr, "\ndist tree: sent %ld", s->bits_sent)); } /* =========================================================================== * Send a stored block */ void _tr_stored_block(s, buf, stored_len, eof) deflate_state *s; charf *buf; /* input block */ ulg stored_len; /* length of input block */ int eof; /* true if this is the last block for a file */ { send_bits(s, (STORED_BLOCK<<1)+eof, 3); /* send block type */ s->compressed_len = (s->compressed_len + 3 + 7) & (ulg)~7L; s->compressed_len += (stored_len + 4) << 3; copy_block(s, buf, (unsigned)stored_len, 1); /* with header */ } /* Send just the `stored block' type code without any length bytes or data. */ void _tr_stored_type_only(s) deflate_state *s; { send_bits(s, (STORED_BLOCK << 1), 3); bi_windup(s); s->compressed_len = (s->compressed_len + 3) & ~7L; } /* =========================================================================== * Send one empty static block to give enough lookahead for inflate. * This takes 10 bits, of which 7 may remain in the bit buffer. * The current inflate code requires 9 bits of lookahead. If the * last two codes for the previous block (real code plus EOB) were coded * on 5 bits or less, inflate may have only 5+3 bits of lookahead to decode * the last real code. In this case we send two empty static blocks instead * of one. (There are no problems if the previous block is stored or fixed.) * To simplify the code, we assume the worst case of last real code encoded * on one bit only. */ void _tr_align(s) deflate_state *s; { send_bits(s, STATIC_TREES<<1, 3); send_code(s, END_BLOCK, static_ltree); s->compressed_len += 10L; /* 3 for block type, 7 for EOB */ bi_flush(s); /* Of the 10 bits for the empty block, we have already sent * (10 - bi_valid) bits. The lookahead for the last real code (before * the EOB of the previous block) was thus at least one plus the length * of the EOB plus what we have just sent of the empty static block. */ if (1 + s->last_eob_len + 10 - s->bi_valid < 9) { send_bits(s, STATIC_TREES<<1, 3); send_code(s, END_BLOCK, static_ltree); s->compressed_len += 10L; bi_flush(s); } s->last_eob_len = 7; } /* =========================================================================== * Determine the best encoding for the current block: dynamic trees, static * trees or store, and output the encoded block to the zip file. This function * returns the total compressed length for the file so far. */ ulg _tr_flush_block(s, buf, stored_len, eof) deflate_state *s; charf *buf; /* input block, or NULL if too old */ ulg stored_len; /* length of input block */ int eof; /* true if this is the last block for a file */ { ulg opt_lenb, static_lenb; /* opt_len and static_len in bytes */ int max_blindex = 0; /* index of last bit length code of non zero freq */ /* Build the Huffman trees unless a stored block is forced */ if (s->level > 0) { /* Check if the file is ascii or binary */ if (s->data_type == Z_UNKNOWN) set_data_type(s); /* Construct the literal and distance trees */ build_tree(s, (tree_desc *)(&(s->l_desc))); Tracev((stderr, "\nlit data: dyn %ld, stat %ld", s->opt_len, s->static_len)); build_tree(s, (tree_desc *)(&(s->d_desc))); Tracev((stderr, "\ndist data: dyn %ld, stat %ld", s->opt_len, s->static_len)); /* At this point, opt_len and static_len are the total bit lengths of * the compressed block data, excluding the tree representations. */ /* Build the bit length tree for the above two trees, and get the index * in bl_order of the last bit length code to send. */ max_blindex = build_bl_tree(s); /* Determine the best encoding. Compute first the block length in bytes*/ opt_lenb = (s->opt_len+3+7)>>3; static_lenb = (s->static_len+3+7)>>3; Tracev((stderr, "\nopt %lu(%lu) stat %lu(%lu) stored %lu lit %u ", opt_lenb, s->opt_len, static_lenb, s->static_len, stored_len, s->last_lit)); if (static_lenb <= opt_lenb) opt_lenb = static_lenb; } else { Assert(buf != (char*)0, "lost buf"); opt_lenb = static_lenb = stored_len + 5; /* force a stored block */ } /* If compression failed and this is the first and last block, * and if the .zip file can be seeked (to rewrite the local header), * the whole file is transformed into a stored file: */ #ifdef STORED_FILE_OK # ifdef FORCE_STORED_FILE if (eof && s->compressed_len == 0L) { /* force stored file */ # else if (stored_len <= opt_lenb && eof && s->compressed_len==0L && seekable()) { # endif /* Since LIT_BUFSIZE <= 2*WSIZE, the input data must be there: */ if (buf == (charf*)0) error ("block vanished"); copy_block(s, buf, (unsigned)stored_len, 0); /* without header */ s->compressed_len = stored_len << 3; s->method = STORED; } else #endif /* STORED_FILE_OK */ #ifdef FORCE_STORED if (buf != (char*)0) { /* force stored block */ #else if (stored_len+4 <= opt_lenb && buf != (char*)0) { /* 4: two words for the lengths */ #endif /* The test buf != NULL is only necessary if LIT_BUFSIZE > WSIZE. * Otherwise we can't have processed more than WSIZE input bytes since * the last block flush, because compression would have been * successful. If LIT_BUFSIZE <= WSIZE, it is never too late to * transform a block into a stored block. */ _tr_stored_block(s, buf, stored_len, eof); #ifdef FORCE_STATIC } else if (static_lenb >= 0) { /* force static trees */ #else } else if (static_lenb == opt_lenb) { #endif send_bits(s, (STATIC_TREES<<1)+eof, 3); compress_block(s, (ct_data *)static_ltree, (ct_data *)static_dtree); s->compressed_len += 3 + s->static_len; } else { send_bits(s, (DYN_TREES<<1)+eof, 3); send_all_trees(s, s->l_desc.max_code+1, s->d_desc.max_code+1, max_blindex+1); compress_block(s, (ct_data *)s->dyn_ltree, (ct_data *)s->dyn_dtree); s->compressed_len += 3 + s->opt_len; } Assert (s->compressed_len == s->bits_sent, "bad compressed size"); init_block(s); if (eof) { bi_windup(s); s->compressed_len += 7; /* align on byte boundary */ } Tracev((stderr,"\ncomprlen %lu(%lu) ", s->compressed_len>>3, s->compressed_len-7*eof)); return s->compressed_len >> 3; } /* =========================================================================== * Save the match info and tally the frequency counts. Return true if * the current block must be flushed. */ int _tr_tally (s, dist, lc) deflate_state *s; unsigned dist; /* distance of matched string */ unsigned lc; /* match length-MIN_MATCH or unmatched char (if dist==0) */ { s->d_buf[s->last_lit] = (ush)dist; s->l_buf[s->last_lit++] = (uch)lc; if (dist == 0) { /* lc is the unmatched char */ s->dyn_ltree[lc].Freq++; } else { s->matches++; /* Here, lc is the match length - MIN_MATCH */ dist--; /* dist = match distance - 1 */ Assert((ush)dist < (ush)MAX_DIST(s) && (ush)lc <= (ush)(MAX_MATCH-MIN_MATCH) && (ush)d_code(dist) < (ush)D_CODES, "_tr_tally: bad match"); s->dyn_ltree[length_code[lc]+LITERALS+1].Freq++; s->dyn_dtree[d_code(dist)].Freq++; } /* Try to guess if it is profitable to stop the current block here */ if (s->level > 2 && (s->last_lit & 0xfff) == 0) { /* Compute an upper bound for the compressed length */ ulg out_length = (ulg)s->last_lit*8L; ulg in_length = (ulg)((long)s->strstart - s->block_start); int dcode; for (dcode = 0; dcode < D_CODES; dcode++) { out_length += (ulg)s->dyn_dtree[dcode].Freq * (5L+extra_dbits[dcode]); } out_length >>= 3; Tracev((stderr,"\nlast_lit %u, in %ld, out ~%ld(%ld%%) ", s->last_lit, in_length, out_length, 100L - out_length*100L/in_length)); if (s->matches < s->last_lit/2 && out_length < in_length/2) return 1; } return (s->last_lit == s->lit_bufsize-1); /* We avoid equality with lit_bufsize because of wraparound at 64K * on 16 bit machines and because stored blocks are restricted to * 64K-1 bytes. */ } /* =========================================================================== * Send the block data compressed using the given Huffman trees */ local void compress_block(s, ltree, dtree) deflate_state *s; ct_data *ltree; /* literal tree */ ct_data *dtree; /* distance tree */ { unsigned dist; /* distance of matched string */ int lc; /* match length or unmatched char (if dist == 0) */ unsigned lx = 0; /* running index in l_buf */ unsigned code; /* the code to send */ int extra; /* number of extra bits to send */ if (s->last_lit != 0) do { dist = s->d_buf[lx]; lc = s->l_buf[lx++]; if (dist == 0) { send_code(s, lc, ltree); /* send a literal byte */ Tracecv(isgraph(lc), (stderr," '%c' ", lc)); } else { /* Here, lc is the match length - MIN_MATCH */ code = length_code[lc]; send_code(s, code+LITERALS+1, ltree); /* send the length code */ extra = extra_lbits[code]; if (extra != 0) { lc -= base_length[code]; send_bits(s, lc, extra); /* send the extra length bits */ } dist--; /* dist is now the match distance - 1 */ code = d_code(dist); Assert (code < D_CODES, "bad d_code"); send_code(s, code, dtree); /* send the distance code */ extra = extra_dbits[code]; if (extra != 0) { dist -= base_dist[code]; send_bits(s, dist, extra); /* send the extra distance bits */ } } /* literal or match pair ? */ /* Check that the overlay between pending_buf and d_buf+l_buf is ok: */ Assert(s->pending < s->lit_bufsize + 2*lx, "pendingBuf overflow"); } while (lx < s->last_lit); send_code(s, END_BLOCK, ltree); s->last_eob_len = ltree[END_BLOCK].Len; } /* =========================================================================== * Set the data type to ASCII or BINARY, using a crude approximation: * binary if more than 20% of the bytes are <= 6 or >= 128, ascii otherwise. * IN assertion: the fields freq of dyn_ltree are set and the total of all * frequencies does not exceed 64K (to fit in an int on 16 bit machines). */ local void set_data_type(s) deflate_state *s; { int n = 0; unsigned ascii_freq = 0; unsigned bin_freq = 0; while (n < 7) bin_freq += s->dyn_ltree[n++].Freq; while (n < 128) ascii_freq += s->dyn_ltree[n++].Freq; while (n < LITERALS) bin_freq += s->dyn_ltree[n++].Freq; s->data_type = (Byte)(bin_freq > (ascii_freq >> 2) ? Z_BINARY : Z_ASCII); } /* =========================================================================== * Reverse the first len bits of a code, using straightforward code (a faster * method would use a table) * IN assertion: 1 <= len <= 15 */ local unsigned bi_reverse(code, len) unsigned code; /* the value to invert */ int len; /* its bit length */ { register unsigned res = 0; do { res |= code & 1; code >>= 1, res <<= 1; } while (--len > 0); return res >> 1; } /* =========================================================================== * Flush the bit buffer, keeping at most 7 bits in it. */ local void bi_flush(s) deflate_state *s; { if (s->bi_valid == 16) { put_short(s, s->bi_buf); s->bi_buf = 0; s->bi_valid = 0; } else if (s->bi_valid >= 8) { put_byte(s, (Byte)s->bi_buf); s->bi_buf >>= 8; s->bi_valid -= 8; } } /* =========================================================================== * Flush the bit buffer and align the output on a byte boundary */ local void bi_windup(s) deflate_state *s; { if (s->bi_valid > 8) { put_short(s, s->bi_buf); } else if (s->bi_valid > 0) { put_byte(s, (Byte)s->bi_buf); } s->bi_buf = 0; s->bi_valid = 0; #ifdef DEBUG_ZLIB s->bits_sent = (s->bits_sent+7) & ~7; #endif } /* =========================================================================== * Copy a stored block, storing first the length and its * one's complement if requested. */ local void copy_block(s, buf, len, header) deflate_state *s; charf *buf; /* the input data */ unsigned len; /* its length */ int header; /* true if block header must be written */ { bi_windup(s); /* align on byte boundary */ s->last_eob_len = 8; /* enough lookahead for inflate */ if (header) { put_short(s, (ush)len); put_short(s, (ush)~len); #ifdef DEBUG_ZLIB s->bits_sent += 2*16; #endif } #ifdef DEBUG_ZLIB s->bits_sent += (ulg)len<<3; #endif /* bundle up the put_byte(s, *buf++) calls */ zmemcpy(&s->pending_buf[s->pending], buf, len); s->pending += len; } /* --- trees.c */ /* +++ inflate.c */ /* inflate.c -- zlib interface to inflate modules * Copyright (C) 1995-1996 Mark Adler * For conditions of distribution and use, see copyright notice in zlib.h */ /* #include "zutil.h" */ /* +++ infblock.h */ /* infblock.h -- header to use infblock.c * Copyright (C) 1995-1996 Mark Adler * For conditions of distribution and use, see copyright notice in zlib.h */ /* WARNING: this file should *not* be used by applications. It is part of the implementation of the compression library and is subject to change. Applications should only use zlib.h. */ struct inflate_blocks_state; typedef struct inflate_blocks_state FAR inflate_blocks_statef; extern inflate_blocks_statef * inflate_blocks_new OF(( z_streamp z, check_func c, /* check function */ uInt w)); /* window size */ extern int inflate_blocks OF(( inflate_blocks_statef *, z_streamp , int)); /* initial return code */ extern void inflate_blocks_reset OF(( inflate_blocks_statef *, z_streamp , uLongf *)); /* check value on output */ extern int inflate_blocks_free OF(( inflate_blocks_statef *, z_streamp , uLongf *)); /* check value on output */ extern void inflate_set_dictionary OF(( inflate_blocks_statef *s, const Bytef *d, /* dictionary */ uInt n)); /* dictionary length */ extern int inflate_addhistory OF(( inflate_blocks_statef *, z_streamp)); extern int inflate_packet_flush OF(( inflate_blocks_statef *)); /* --- infblock.h */ #ifndef NO_DUMMY_DECL struct inflate_blocks_state {int dummy;}; /* for buggy compilers */ #endif /* inflate private state */ struct internal_state { /* mode */ enum { METHOD, /* waiting for method byte */ FLAG, /* waiting for flag byte */ DICT4, /* four dictionary check bytes to go */ DICT3, /* three dictionary check bytes to go */ DICT2, /* two dictionary check bytes to go */ DICT1, /* one dictionary check byte to go */ DICT0, /* waiting for inflateSetDictionary */ BLOCKS, /* decompressing blocks */ CHECK4, /* four check bytes to go */ CHECK3, /* three check bytes to go */ CHECK2, /* two check bytes to go */ CHECK1, /* one check byte to go */ DONE, /* finished check, done */ BAD} /* got an error--stay here */ mode; /* current inflate mode */ /* mode dependent information */ union { uInt method; /* if FLAGS, method byte */ struct { uLong was; /* computed check value */ uLong need; /* stream check value */ } check; /* if CHECK, check values to compare */ uInt marker; /* if BAD, inflateSync's marker bytes count */ } sub; /* submode */ /* mode independent information */ int nowrap; /* flag for no wrapper */ uInt wbits; /* log2(window size) (8..15, defaults to 15) */ inflate_blocks_statef *blocks; /* current inflate_blocks state */ }; int inflateReset(z) z_streamp z; { uLong c; if (z == Z_NULL || z->state == Z_NULL) return Z_STREAM_ERROR; z->total_in = z->total_out = 0; z->msg = Z_NULL; z->state->mode = z->state->nowrap ? BLOCKS : METHOD; inflate_blocks_reset(z->state->blocks, z, &c); Trace((stderr, "inflate: reset\n")); return Z_OK; } int inflateEnd(z) z_streamp z; { uLong c; if (z == Z_NULL || z->state == Z_NULL || z->zfree == Z_NULL) return Z_STREAM_ERROR; if (z->state->blocks != Z_NULL) inflate_blocks_free(z->state->blocks, z, &c); ZFREE(z, z->state); z->state = Z_NULL; Trace((stderr, "inflate: end\n")); return Z_OK; } int inflateInit2_(z, w, version, stream_size) z_streamp z; int w; const char *version; int stream_size; { if (version == Z_NULL || version[0] != ZLIB_VERSION[0] || stream_size != sizeof(z_stream)) return Z_VERSION_ERROR; /* initialize state */ if (z == Z_NULL) return Z_STREAM_ERROR; z->msg = Z_NULL; #ifndef NO_ZCFUNCS if (z->zalloc == Z_NULL) { z->zalloc = zcalloc; z->opaque = (voidpf)0; } if (z->zfree == Z_NULL) z->zfree = zcfree; #endif if ((z->state = (struct internal_state FAR *) ZALLOC(z,1,sizeof(struct internal_state))) == Z_NULL) return Z_MEM_ERROR; z->state->blocks = Z_NULL; /* handle undocumented nowrap option (no zlib header or check) */ z->state->nowrap = 0; if (w < 0) { w = - w; z->state->nowrap = 1; } /* set window size */ if (w < 8 || w > 15) { inflateEnd(z); return Z_STREAM_ERROR; } z->state->wbits = (uInt)w; /* create inflate_blocks state */ if ((z->state->blocks = inflate_blocks_new(z, z->state->nowrap ? Z_NULL : adler32, (uInt)1 << w)) == Z_NULL) { inflateEnd(z); return Z_MEM_ERROR; } Trace((stderr, "inflate: allocated\n")); /* reset state */ inflateReset(z); return Z_OK; } int inflateInit_(z, version, stream_size) z_streamp z; const char *version; int stream_size; { return inflateInit2_(z, DEF_WBITS, version, stream_size); } #define NEEDBYTE {if(z->avail_in==0)goto empty;r=Z_OK;} #define NEXTBYTE (z->avail_in--,z->total_in++,*z->next_in++) int inflate(z, f) z_streamp z; int f; { int r; uInt b; if (z == Z_NULL || z->state == Z_NULL || z->next_in == Z_NULL || f < 0) return Z_STREAM_ERROR; r = Z_BUF_ERROR; while (1) switch (z->state->mode) { case METHOD: NEEDBYTE if (((z->state->sub.method = NEXTBYTE) & 0xf) != Z_DEFLATED) { z->state->mode = BAD; z->msg = (char*)"unknown compression method"; z->state->sub.marker = 5; /* can't try inflateSync */ break; } if ((z->state->sub.method >> 4) + 8 > z->state->wbits) { z->state->mode = BAD; z->msg = (char*)"invalid window size"; z->state->sub.marker = 5; /* can't try inflateSync */ break; } z->state->mode = FLAG; case FLAG: NEEDBYTE b = NEXTBYTE; if (((z->state->sub.method << 8) + b) % 31) { z->state->mode = BAD; z->msg = (char*)"incorrect header check"; z->state->sub.marker = 5; /* can't try inflateSync */ break; } Trace((stderr, "inflate: zlib header ok\n")); if (!(b & PRESET_DICT)) { z->state->mode = BLOCKS; break; } z->state->mode = DICT4; case DICT4: NEEDBYTE z->state->sub.check.need = (uLong)NEXTBYTE << 24; z->state->mode = DICT3; case DICT3: NEEDBYTE z->state->sub.check.need += (uLong)NEXTBYTE << 16; z->state->mode = DICT2; case DICT2: NEEDBYTE z->state->sub.check.need += (uLong)NEXTBYTE << 8; z->state->mode = DICT1; case DICT1: NEEDBYTE z->state->sub.check.need += (uLong)NEXTBYTE; z->adler = z->state->sub.check.need; z->state->mode = DICT0; return Z_NEED_DICT; case DICT0: z->state->mode = BAD; z->msg = (char*)"need dictionary"; z->state->sub.marker = 0; /* can try inflateSync */ return Z_STREAM_ERROR; case BLOCKS: r = inflate_blocks(z->state->blocks, z, r); if (f == Z_PACKET_FLUSH && z->avail_in == 0 && z->avail_out != 0) r = inflate_packet_flush(z->state->blocks); if (r == Z_DATA_ERROR) { z->state->mode = BAD; z->state->sub.marker = 0; /* can try inflateSync */ break; } if (r != Z_STREAM_END) return r; r = Z_OK; inflate_blocks_reset(z->state->blocks, z, &z->state->sub.check.was); if (z->state->nowrap) { z->state->mode = DONE; break; } z->state->mode = CHECK4; case CHECK4: NEEDBYTE z->state->sub.check.need = (uLong)NEXTBYTE << 24; z->state->mode = CHECK3; case CHECK3: NEEDBYTE z->state->sub.check.need += (uLong)NEXTBYTE << 16; z->state->mode = CHECK2; case CHECK2: NEEDBYTE z->state->sub.check.need += (uLong)NEXTBYTE << 8; z->state->mode = CHECK1; case CHECK1: NEEDBYTE z->state->sub.check.need += (uLong)NEXTBYTE; if (z->state->sub.check.was != z->state->sub.check.need) { z->state->mode = BAD; z->msg = (char*)"incorrect data check"; z->state->sub.marker = 5; /* can't try inflateSync */ break; } Trace((stderr, "inflate: zlib check ok\n")); z->state->mode = DONE; case DONE: return Z_STREAM_END; case BAD: return Z_DATA_ERROR; default: return Z_STREAM_ERROR; } empty: if (f != Z_PACKET_FLUSH) return r; z->state->mode = BAD; z->msg = (char *)"need more for packet flush"; z->state->sub.marker = 0; /* can try inflateSync */ return Z_DATA_ERROR; } int inflateSetDictionary(z, dictionary, dictLength) z_streamp z; const Bytef *dictionary; uInt dictLength; { uInt length = dictLength; if (z == Z_NULL || z->state == Z_NULL || z->state->mode != DICT0) return Z_STREAM_ERROR; if (adler32(1L, dictionary, dictLength) != z->adler) return Z_DATA_ERROR; z->adler = 1L; if (length >= ((uInt)1<<z->state->wbits)) { length = (1<<z->state->wbits)-1; dictionary += dictLength - length; } inflate_set_dictionary(z->state->blocks, dictionary, length); z->state->mode = BLOCKS; return Z_OK; } /* * This subroutine adds the data at next_in/avail_in to the output history * without performing any output. The output buffer must be "caught up"; * i.e. no pending output (hence s->read equals s->write), and the state must * be BLOCKS (i.e. we should be willing to see the start of a series of * BLOCKS). On exit, the output will also be caught up, and the checksum * will have been updated if need be. */ int inflateIncomp(z) z_stream *z; { if (z->state->mode != BLOCKS) return Z_DATA_ERROR; return inflate_addhistory(z->state->blocks, z); } int inflateSync(z) z_streamp z; { uInt n; /* number of bytes to look at */ Bytef *p; /* pointer to bytes */ uInt m; /* number of marker bytes found in a row */ uLong r, w; /* temporaries to save total_in and total_out */ /* set up */ if (z == Z_NULL || z->state == Z_NULL) return Z_STREAM_ERROR; if (z->state->mode != BAD) { z->state->mode = BAD; z->state->sub.marker = 0; } if ((n = z->avail_in) == 0) return Z_BUF_ERROR; p = z->next_in; m = z->state->sub.marker; /* search */ while (n && m < 4) { if (*p == (Byte)(m < 2 ? 0 : 0xff)) m++; else if (*p) m = 0; else m = 4 - m; p++, n--; } /* restore */ z->total_in += p - z->next_in; z->next_in = p; z->avail_in = n; z->state->sub.marker = m; /* return no joy or set up to restart on a new block */ if (m != 4) return Z_DATA_ERROR; r = z->total_in; w = z->total_out; inflateReset(z); z->total_in = r; z->total_out = w; z->state->mode = BLOCKS; return Z_OK; } #undef NEEDBYTE #undef NEXTBYTE /* --- inflate.c */ /* +++ infblock.c */ /* infblock.c -- interpret and process block types to last block * Copyright (C) 1995-1996 Mark Adler * For conditions of distribution and use, see copyright notice in zlib.h */ /* #include "zutil.h" */ /* #include "infblock.h" */ /* +++ inftrees.h */ /* inftrees.h -- header to use inftrees.c * Copyright (C) 1995-1996 Mark Adler * For conditions of distribution and use, see copyright notice in zlib.h */ /* WARNING: this file should *not* be used by applications. It is part of the implementation of the compression library and is subject to change. Applications should only use zlib.h. */ /* Huffman code lookup table entry--this entry is four bytes for machines that have 16-bit pointers (e.g. PC's in the small or medium model). */ typedef struct inflate_huft_s FAR inflate_huft; struct inflate_huft_s { union { struct { Byte Exop; /* number of extra bits or operation */ Byte Bits; /* number of bits in this code or subcode */ } what; Bytef *pad; /* pad structure to a power of 2 (4 bytes for */ } word; /* 16-bit, 8 bytes for 32-bit machines) */ union { uInt Base; /* literal, length base, or distance base */ inflate_huft *Next; /* pointer to next level of table */ } more; }; #ifdef DEBUG_ZLIB extern uInt inflate_hufts; #endif extern int inflate_trees_bits OF(( uIntf *, /* 19 code lengths */ uIntf *, /* bits tree desired/actual depth */ inflate_huft * FAR *, /* bits tree result */ z_streamp )); /* for zalloc, zfree functions */ extern int inflate_trees_dynamic OF(( uInt, /* number of literal/length codes */ uInt, /* number of distance codes */ uIntf *, /* that many (total) code lengths */ uIntf *, /* literal desired/actual bit depth */ uIntf *, /* distance desired/actual bit depth */ inflate_huft * FAR *, /* literal/length tree result */ inflate_huft * FAR *, /* distance tree result */ z_streamp )); /* for zalloc, zfree functions */ extern int inflate_trees_fixed OF(( uIntf *, /* literal desired/actual bit depth */ uIntf *, /* distance desired/actual bit depth */ inflate_huft * FAR *, /* literal/length tree result */ inflate_huft * FAR *)); /* distance tree result */ extern int inflate_trees_free OF(( inflate_huft *, /* tables to free */ z_streamp )); /* for zfree function */ /* --- inftrees.h */ /* +++ infcodes.h */ /* infcodes.h -- header to use infcodes.c * Copyright (C) 1995-1996 Mark Adler * For conditions of distribution and use, see copyright notice in zlib.h */ /* WARNING: this file should *not* be used by applications. It is part of the implementation of the compression library and is subject to change. Applications should only use zlib.h. */ struct inflate_codes_state; typedef struct inflate_codes_state FAR inflate_codes_statef; extern inflate_codes_statef *inflate_codes_new OF(( uInt, uInt, inflate_huft *, inflate_huft *, z_streamp )); extern int inflate_codes OF(( inflate_blocks_statef *, z_streamp , int)); extern void inflate_codes_free OF(( inflate_codes_statef *, z_streamp )); /* --- infcodes.h */ /* +++ infutil.h */ /* infutil.h -- types and macros common to blocks and codes * Copyright (C) 1995-1996 Mark Adler * For conditions of distribution and use, see copyright notice in zlib.h */ /* WARNING: this file should *not* be used by applications. It is part of the implementation of the compression library and is subject to change. Applications should only use zlib.h. */ #ifndef _INFUTIL_H #define _INFUTIL_H typedef enum { TYPE, /* get type bits (3, including end bit) */ LENS, /* get lengths for stored */ STORED, /* processing stored block */ TABLE, /* get table lengths */ BTREE, /* get bit lengths tree for a dynamic block */ DTREE, /* get length, distance trees for a dynamic block */ CODES, /* processing fixed or dynamic block */ DRY, /* output remaining window bytes */ DONEB, /* finished last block, done */ BADB} /* got a data error--stuck here */ inflate_block_mode; /* inflate blocks semi-private state */ struct inflate_blocks_state { /* mode */ inflate_block_mode mode; /* current inflate_block mode */ /* mode dependent information */ union { uInt left; /* if STORED, bytes left to copy */ struct { uInt table; /* table lengths (14 bits) */ uInt index; /* index into blens (or border) */ uIntf *blens; /* bit lengths of codes */ uInt bb; /* bit length tree depth */ inflate_huft *tb; /* bit length decoding tree */ } trees; /* if DTREE, decoding info for trees */ struct { inflate_huft *tl; inflate_huft *td; /* trees to free */ inflate_codes_statef *codes; } decode; /* if CODES, current state */ } sub; /* submode */ uInt last; /* true if this block is the last block */ /* mode independent information */ uInt bitk; /* bits in bit buffer */ uLong bitb; /* bit buffer */ Bytef *window; /* sliding window */ Bytef *end; /* one byte after sliding window */ Bytef *read; /* window read pointer */ Bytef *write; /* window write pointer */ check_func checkfn; /* check function */ uLong check; /* check on output */ }; /* defines for inflate input/output */ /* update pointers and return */ #define UPDBITS {s->bitb=b;s->bitk=k;} #define UPDIN {z->avail_in=n;z->total_in+=p-z->next_in;z->next_in=p;} #define UPDOUT {s->write=q;} #define UPDATE {UPDBITS UPDIN UPDOUT} #define LEAVE {UPDATE return inflate_flush(s,z,r);} /* get bytes and bits */ #define LOADIN {p=z->next_in;n=z->avail_in;b=s->bitb;k=s->bitk;} #define NEEDBYTE {if(n)r=Z_OK;else LEAVE} #define NEXTBYTE (n--,*p++) #define NEEDBITS(j) {while(k<(j)){NEEDBYTE;b|=((uLong)NEXTBYTE)<<k;k+=8;}} #define DUMPBITS(j) {b>>=(j);k-=(j);} /* output bytes */ #define WAVAIL (uInt)(q<s->read?s->read-q-1:s->end-q) #define LOADOUT {q=s->write;m=(uInt)WAVAIL;} #define WWRAP {if(q==s->end&&s->read!=s->window){q=s->window;m=(uInt)WAVAIL;}} #define FLUSH {UPDOUT r=inflate_flush(s,z,r); LOADOUT} #define NEEDOUT {if(m==0){WWRAP if(m==0){FLUSH WWRAP if(m==0) LEAVE}}r=Z_OK;} #define OUTBYTE(a) {*q++=(Byte)(a);m--;} /* load local pointers */ #define LOAD {LOADIN LOADOUT} /* masks for lower bits (size given to avoid silly warnings with Visual C++) */ extern uInt inflate_mask[17]; /* copy as much as possible from the sliding window to the output area */ extern int inflate_flush OF(( inflate_blocks_statef *, z_streamp , int)); #ifndef NO_DUMMY_DECL struct internal_state {int dummy;}; /* for buggy compilers */ #endif #endif /* --- infutil.h */ #ifndef NO_DUMMY_DECL struct inflate_codes_state {int dummy;}; /* for buggy compilers */ #endif /* Table for deflate from PKZIP's appnote.txt. */ local const uInt border[] = { /* Order of the bit length code lengths */ 16, 17, 18, 0, 8, 7, 9, 6, 10, 5, 11, 4, 12, 3, 13, 2, 14, 1, 15}; /* Notes beyond the 1.93a appnote.txt: 1. Distance pointers never point before the beginning of the output stream. 2. Distance pointers can point back across blocks, up to 32k away. 3. There is an implied maximum of 7 bits for the bit length table and 15 bits for the actual data. 4. If only one code exists, then it is encoded using one bit. (Zero would be more efficient, but perhaps a little confusing.) If two codes exist, they are coded using one bit each (0 and 1). 5. There is no way of sending zero distance codes--a dummy must be sent if there are none. (History: a pre 2.0 version of PKZIP would store blocks with no distance codes, but this was discovered to be too harsh a criterion.) Valid only for 1.93a. 2.04c does allow zero distance codes, which is sent as one code of zero bits in length. 6. There are up to 286 literal/length codes. Code 256 represents the end-of-block. Note however that the static length tree defines 288 codes just to fill out the Huffman codes. Codes 286 and 287 cannot be used though, since there is no length base or extra bits defined for them. Similarily, there are up to 30 distance codes. However, static trees define 32 codes (all 5 bits) to fill out the Huffman codes, but the last two had better not show up in the data. 7. Unzip can check dynamic Huffman blocks for complete code sets. The exception is that a single code would not be complete (see #4). 8. The five bits following the block type is really the number of literal codes sent minus 257. 9. Length codes 8,16,16 are interpreted as 13 length codes of 8 bits (1+6+6). Therefore, to output three times the length, you output three codes (1+1+1), whereas to output four times the same length, you only need two codes (1+3). Hmm. 10. In the tree reconstruction algorithm, Code = Code + Increment only if BitLength(i) is not zero. (Pretty obvious.) 11. Correction: 4 Bits: # of Bit Length codes - 4 (4 - 19) 12. Note: length code 284 can represent 227-258, but length code 285 really is 258. The last length deserves its own, short code since it gets used a lot in very redundant files. The length 258 is special since 258 - 3 (the min match length) is 255. 13. The literal/length and distance code bit lengths are read as a single stream of lengths. It is possible (and advantageous) for a repeat code (16, 17, or 18) to go across the boundary between the two sets of lengths. */ void inflate_blocks_reset(s, z, c) inflate_blocks_statef *s; z_streamp z; uLongf *c; { if (s->checkfn != Z_NULL) *c = s->check; if (s->mode == BTREE || s->mode == DTREE) ZFREE(z, s->sub.trees.blens); if (s->mode == CODES) { inflate_codes_free(s->sub.decode.codes, z); inflate_trees_free(s->sub.decode.td, z); inflate_trees_free(s->sub.decode.tl, z); } s->mode = TYPE; s->bitk = 0; s->bitb = 0; s->read = s->write = s->window; if (s->checkfn != Z_NULL) z->adler = s->check = (*s->checkfn)(0L, Z_NULL, 0); Trace((stderr, "inflate: blocks reset\n")); } inflate_blocks_statef *inflate_blocks_new(z, c, w) z_streamp z; check_func c; uInt w; { inflate_blocks_statef *s; if ((s = (inflate_blocks_statef *)ZALLOC (z,1,sizeof(struct inflate_blocks_state))) == Z_NULL) return s; if ((s->window = (Bytef *)ZALLOC(z, 1, w)) == Z_NULL) { ZFREE(z, s); return Z_NULL; } s->end = s->window + w; s->checkfn = c; s->mode = TYPE; Trace((stderr, "inflate: blocks allocated\n")); inflate_blocks_reset(s, z, &s->check); return s; } #ifdef DEBUG_ZLIB extern uInt inflate_hufts; #endif int inflate_blocks(s, z, r) inflate_blocks_statef *s; z_streamp z; int r; { uInt t; /* temporary storage */ uLong b; /* bit buffer */ uInt k; /* bits in bit buffer */ Bytef *p; /* input data pointer */ uInt n; /* bytes available there */ Bytef *q; /* output window write pointer */ uInt m; /* bytes to end of window or read pointer */ /* copy input/output information to locals (UPDATE macro restores) */ LOAD /* process input based on current state */ while (1) switch (s->mode) { case TYPE: NEEDBITS(3) t = (uInt)b & 7; s->last = t & 1; switch (t >> 1) { case 0: /* stored */ Trace((stderr, "inflate: stored block%s\n", s->last ? " (last)" : "")); DUMPBITS(3) t = k & 7; /* go to byte boundary */ DUMPBITS(t) s->mode = LENS; /* get length of stored block */ break; case 1: /* fixed */ Trace((stderr, "inflate: fixed codes block%s\n", s->last ? " (last)" : "")); { uInt bl, bd; inflate_huft *tl, *td; inflate_trees_fixed(&bl, &bd, &tl, &td); s->sub.decode.codes = inflate_codes_new(bl, bd, tl, td, z); if (s->sub.decode.codes == Z_NULL) { r = Z_MEM_ERROR; LEAVE } s->sub.decode.tl = Z_NULL; /* don't try to free these */ s->sub.decode.td = Z_NULL; } DUMPBITS(3) s->mode = CODES; break; case 2: /* dynamic */ Trace((stderr, "inflate: dynamic codes block%s\n", s->last ? " (last)" : "")); DUMPBITS(3) s->mode = TABLE; break; case 3: /* illegal */ DUMPBITS(3) s->mode = BADB; z->msg = (char*)"invalid block type"; r = Z_DATA_ERROR; LEAVE } break; case LENS: NEEDBITS(32) if ((((~b) >> 16) & 0xffff) != (b & 0xffff)) { s->mode = BADB; z->msg = (char*)"invalid stored block lengths"; r = Z_DATA_ERROR; LEAVE } s->sub.left = (uInt)b & 0xffff; b = k = 0; /* dump bits */ Tracev((stderr, "inflate: stored length %u\n", s->sub.left)); s->mode = s->sub.left ? STORED : (s->last ? DRY : TYPE); break; case STORED: if (n == 0) LEAVE NEEDOUT t = s->sub.left; if (t > n) t = n; if (t > m) t = m; zmemcpy(q, p, t); p += t; n -= t; q += t; m -= t; if ((s->sub.left -= t) != 0) break; Tracev((stderr, "inflate: stored end, %lu total out\n", z->total_out + (q >= s->read ? q - s->read : (s->end - s->read) + (q - s->window)))); s->mode = s->last ? DRY : TYPE; break; case TABLE: NEEDBITS(14) s->sub.trees.table = t = (uInt)b & 0x3fff; #ifndef PKZIP_BUG_WORKAROUND if ((t & 0x1f) > 29 || ((t >> 5) & 0x1f) > 29) { s->mode = BADB; z->msg = (char*)"too many length or distance symbols"; r = Z_DATA_ERROR; LEAVE } #endif t = 258 + (t & 0x1f) + ((t >> 5) & 0x1f); if (t < 19) t = 19; if ((s->sub.trees.blens = (uIntf*)ZALLOC(z, t, sizeof(uInt))) == Z_NULL) { r = Z_MEM_ERROR; LEAVE } DUMPBITS(14) s->sub.trees.index = 0; Tracev((stderr, "inflate: table sizes ok\n")); s->mode = BTREE; case BTREE: while (s->sub.trees.index < 4 + (s->sub.trees.table >> 10)) { NEEDBITS(3) s->sub.trees.blens[border[s->sub.trees.index++]] = (uInt)b & 7; DUMPBITS(3) } while (s->sub.trees.index < 19) s->sub.trees.blens[border[s->sub.trees.index++]] = 0; s->sub.trees.bb = 7; t = inflate_trees_bits(s->sub.trees.blens, &s->sub.trees.bb, &s->sub.trees.tb, z); if (t != Z_OK) { r = t; if (r == Z_DATA_ERROR) { ZFREE(z, s->sub.trees.blens); s->mode = BADB; } LEAVE } s->sub.trees.index = 0; Tracev((stderr, "inflate: bits tree ok\n")); s->mode = DTREE; case DTREE: while (t = s->sub.trees.table, s->sub.trees.index < 258 + (t & 0x1f) + ((t >> 5) & 0x1f)) { inflate_huft *h; uInt i, j, c; t = s->sub.trees.bb; NEEDBITS(t) h = s->sub.trees.tb + ((uInt)b & inflate_mask[t]); t = h->word.what.Bits; c = h->more.Base; if (c < 16) { DUMPBITS(t) s->sub.trees.blens[s->sub.trees.index++] = c; } else /* c == 16..18 */ { i = c == 18 ? 7 : c - 14; j = c == 18 ? 11 : 3; NEEDBITS(t + i) DUMPBITS(t) j += (uInt)b & inflate_mask[i]; DUMPBITS(i) i = s->sub.trees.index; t = s->sub.trees.table; if (i + j > 258 + (t & 0x1f) + ((t >> 5) & 0x1f) || (c == 16 && i < 1)) { inflate_trees_free(s->sub.trees.tb, z); ZFREE(z, s->sub.trees.blens); s->mode = BADB; z->msg = (char*)"invalid bit length repeat"; r = Z_DATA_ERROR; LEAVE } c = c == 16 ? s->sub.trees.blens[i - 1] : 0; do { s->sub.trees.blens[i++] = c; } while (--j); s->sub.trees.index = i; } } inflate_trees_free(s->sub.trees.tb, z); s->sub.trees.tb = Z_NULL; { uInt bl, bd; inflate_huft *tl, *td; inflate_codes_statef *c; bl = 9; /* must be <= 9 for lookahead assumptions */ bd = 6; /* must be <= 9 for lookahead assumptions */ t = s->sub.trees.table; #ifdef DEBUG_ZLIB inflate_hufts = 0; #endif t = inflate_trees_dynamic(257 + (t & 0x1f), 1 + ((t >> 5) & 0x1f), s->sub.trees.blens, &bl, &bd, &tl, &td, z); if (t != Z_OK) { if (t == (uInt)Z_DATA_ERROR) { ZFREE(z, s->sub.trees.blens); s->mode = BADB; } r = t; LEAVE } Tracev((stderr, "inflate: trees ok, %d * %d bytes used\n", inflate_hufts, sizeof(inflate_huft))); if ((c = inflate_codes_new(bl, bd, tl, td, z)) == Z_NULL) { inflate_trees_free(td, z); inflate_trees_free(tl, z); r = Z_MEM_ERROR; LEAVE } /* * this ZFREE must occur *BEFORE* we mess with sub.decode, because * sub.trees is union'd with sub.decode. */ ZFREE(z, s->sub.trees.blens); s->sub.decode.codes = c; s->sub.decode.tl = tl; s->sub.decode.td = td; } s->mode = CODES; case CODES: UPDATE if ((r = inflate_codes(s, z, r)) != Z_STREAM_END) return inflate_flush(s, z, r); r = Z_OK; inflate_codes_free(s->sub.decode.codes, z); inflate_trees_free(s->sub.decode.td, z); inflate_trees_free(s->sub.decode.tl, z); LOAD Tracev((stderr, "inflate: codes end, %lu total out\n", z->total_out + (q >= s->read ? q - s->read : (s->end - s->read) + (q - s->window)))); if (!s->last) { s->mode = TYPE; break; } if (k > 7) /* return unused byte, if any */ { Assert(k < 16, "inflate_codes grabbed too many bytes") k -= 8; n++; p--; /* can always return one */ } s->mode = DRY; case DRY: FLUSH if (s->read != s->write) LEAVE s->mode = DONEB; case DONEB: r = Z_STREAM_END; LEAVE case BADB: r = Z_DATA_ERROR; LEAVE default: r = Z_STREAM_ERROR; LEAVE } } int inflate_blocks_free(s, z, c) inflate_blocks_statef *s; z_streamp z; uLongf *c; { inflate_blocks_reset(s, z, c); ZFREE(z, s->window); ZFREE(z, s); Trace((stderr, "inflate: blocks freed\n")); return Z_OK; } void inflate_set_dictionary(s, d, n) inflate_blocks_statef *s; const Bytef *d; uInt n; { zmemcpy((charf *)s->window, d, n); s->read = s->write = s->window + n; } /* * This subroutine adds the data at next_in/avail_in to the output history * without performing any output. The output buffer must be "caught up"; * i.e. no pending output (hence s->read equals s->write), and the state must * be BLOCKS (i.e. we should be willing to see the start of a series of * BLOCKS). On exit, the output will also be caught up, and the checksum * will have been updated if need be. */ int inflate_addhistory(s, z) inflate_blocks_statef *s; z_stream *z; { uLong b; /* bit buffer */ /* NOT USED HERE */ uInt k; /* bits in bit buffer */ /* NOT USED HERE */ uInt t; /* temporary storage */ Bytef *p; /* input data pointer */ uInt n; /* bytes available there */ Bytef *q; /* output window write pointer */ uInt m; /* bytes to end of window or read pointer */ if (s->read != s->write) return Z_STREAM_ERROR; if (s->mode != TYPE) return Z_DATA_ERROR; /* we're ready to rock */ LOAD /* while there is input ready, copy to output buffer, moving * pointers as needed. */ while (n) { t = n; /* how many to do */ /* is there room until end of buffer? */ if (t > m) t = m; /* update check information */ if (s->checkfn != Z_NULL) s->check = (*s->checkfn)(s->check, q, t); zmemcpy(q, p, t); q += t; p += t; n -= t; z->total_out += t; s->read = q; /* drag read pointer forward */ /* WWRAP */ /* expand WWRAP macro by hand to handle s->read */ if (q == s->end) { s->read = q = s->window; m = WAVAIL; } } UPDATE return Z_OK; } /* * At the end of a Deflate-compressed PPP packet, we expect to have seen * a `stored' block type value but not the (zero) length bytes. */ int inflate_packet_flush(s) inflate_blocks_statef *s; { if (s->mode != LENS) return Z_DATA_ERROR; s->mode = TYPE; return Z_OK; } /* --- infblock.c */ /* +++ inftrees.c */ /* inftrees.c -- generate Huffman trees for efficient decoding * Copyright (C) 1995-1996 Mark Adler * For conditions of distribution and use, see copyright notice in zlib.h */ /* #include "zutil.h" */ /* #include "inftrees.h" */ char inflate_copyright[] = " inflate 1.0.4 Copyright 1995-1996 Mark Adler "; /* If you use the zlib library in a product, an acknowledgment is welcome in the documentation of your product. If for some reason you cannot include such an acknowledgment, I would appreciate that you keep this copyright string in the executable of your product. */ #ifndef NO_DUMMY_DECL struct internal_state {int dummy;}; /* for buggy compilers */ #endif /* simplify the use of the inflate_huft type with some defines */ #define base more.Base #define next more.Next #define exop word.what.Exop #define bits word.what.Bits local int huft_build OF(( uIntf *, /* code lengths in bits */ uInt, /* number of codes */ uInt, /* number of "simple" codes */ const uIntf *, /* list of base values for non-simple codes */ const uIntf *, /* list of extra bits for non-simple codes */ inflate_huft * FAR*,/* result: starting table */ uIntf *, /* maximum lookup bits (returns actual) */ z_streamp )); /* for zalloc function */ local voidpf falloc OF(( voidpf, /* opaque pointer (not used) */ uInt, /* number of items */ uInt)); /* size of item */ /* Tables for deflate from PKZIP's appnote.txt. */ local const uInt cplens[31] = { /* Copy lengths for literal codes 257..285 */ 3, 4, 5, 6, 7, 8, 9, 10, 11, 13, 15, 17, 19, 23, 27, 31, 35, 43, 51, 59, 67, 83, 99, 115, 131, 163, 195, 227, 258, 0, 0}; /* see note #13 above about 258 */ local const uInt cplext[31] = { /* Extra bits for literal codes 257..285 */ 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 2, 2, 2, 2, 3, 3, 3, 3, 4, 4, 4, 4, 5, 5, 5, 5, 0, 112, 112}; /* 112==invalid */ local const uInt cpdist[30] = { /* Copy offsets for distance codes 0..29 */ 1, 2, 3, 4, 5, 7, 9, 13, 17, 25, 33, 49, 65, 97, 129, 193, 257, 385, 513, 769, 1025, 1537, 2049, 3073, 4097, 6145, 8193, 12289, 16385, 24577}; local const uInt cpdext[30] = { /* Extra bits for distance codes */ 0, 0, 0, 0, 1, 1, 2, 2, 3, 3, 4, 4, 5, 5, 6, 6, 7, 7, 8, 8, 9, 9, 10, 10, 11, 11, 12, 12, 13, 13}; /* Huffman code decoding is performed using a multi-level table lookup. The fastest way to decode is to simply build a lookup table whose size is determined by the longest code. However, the time it takes to build this table can also be a factor if the data being decoded is not very long. The most common codes are necessarily the shortest codes, so those codes dominate the decoding time, and hence the speed. The idea is you can have a shorter table that decodes the shorter, more probable codes, and then point to subsidiary tables for the longer codes. The time it costs to decode the longer codes is then traded against the time it takes to make longer tables. This results of this trade are in the variables lbits and dbits below. lbits is the number of bits the first level table for literal/ length codes can decode in one step, and dbits is the same thing for the distance codes. Subsequent tables are also less than or equal to those sizes. These values may be adjusted either when all of the codes are shorter than that, in which case the longest code length in bits is used, or when the shortest code is *longer* than the requested table size, in which case the length of the shortest code in bits is used. There are two different values for the two tables, since they code a different number of possibilities each. The literal/length table codes 286 possible values, or in a flat code, a little over eight bits. The distance table codes 30 possible values, or a little less than five bits, flat. The optimum values for speed end up being about one bit more than those, so lbits is 8+1 and dbits is 5+1. The optimum values may differ though from machine to machine, and possibly even between compilers. Your mileage may vary. */ /* If BMAX needs to be larger than 16, then h and x[] should be uLong. */ #define BMAX 15 /* maximum bit length of any code */ #define N_MAX 288 /* maximum number of codes in any set */ #ifdef DEBUG_ZLIB uInt inflate_hufts; #endif local int huft_build(b, n, s, d, e, t, m, zs) uIntf *b; /* code lengths in bits (all assumed <= BMAX) */ uInt n; /* number of codes (assumed <= N_MAX) */ uInt s; /* number of simple-valued codes (0..s-1) */ const uIntf *d; /* list of base values for non-simple codes */ const uIntf *e; /* list of extra bits for non-simple codes */ inflate_huft * FAR *t; /* result: starting table */ uIntf *m; /* maximum lookup bits, returns actual */ z_streamp zs; /* for zalloc function */ /* Given a list of code lengths and a maximum table size, make a set of tables to decode that set of codes. Return Z_OK on success, Z_BUF_ERROR if the given code set is incomplete (the tables are still built in this case), Z_DATA_ERROR if the input is invalid (an over-subscribed set of lengths), or Z_MEM_ERROR if not enough memory. */ { uInt a; /* counter for codes of length k */ uInt c[BMAX+1]; /* bit length count table */ uInt f; /* i repeats in table every f entries */ int g; /* maximum code length */ int h; /* table level */ register uInt i; /* counter, current code */ register uInt j; /* counter */ register int k; /* number of bits in current code */ int l; /* bits per table (returned in m) */ register uIntf *p; /* pointer into c[], b[], or v[] */ inflate_huft *q; /* points to current table */ struct inflate_huft_s r; /* table entry for structure assignment */ inflate_huft *u[BMAX]; /* table stack */ uInt v[N_MAX]; /* values in order of bit length */ register int w; /* bits before this table == (l * h) */ uInt x[BMAX+1]; /* bit offsets, then code stack */ uIntf *xp; /* pointer into x */ int y; /* number of dummy codes added */ uInt z; /* number of entries in current table */ /* Generate counts for each bit length */ p = c; #define C0 *p++ = 0; #define C2 C0 C0 C0 C0 #define C4 C2 C2 C2 C2 C4 /* clear c[]--assume BMAX+1 is 16 */ p = b; i = n; do { c[*p++]++; /* assume all entries <= BMAX */ } while (--i); if (c[0] == n) /* null input--all zero length codes */ { *t = (inflate_huft *)Z_NULL; *m = 0; return Z_OK; } /* Find minimum and maximum length, bound *m by those */ l = *m; for (j = 1; j <= BMAX; j++) if (c[j]) break; k = j; /* minimum code length */ if ((uInt)l < j) l = j; for (i = BMAX; i; i--) if (c[i]) break; g = i; /* maximum code length */ if ((uInt)l > i) l = i; *m = l; /* Adjust last length count to fill out codes, if needed */ for (y = 1 << j; j < i; j++, y <<= 1) if ((y -= c[j]) < 0) return Z_DATA_ERROR; if ((y -= c[i]) < 0) return Z_DATA_ERROR; c[i] += y; /* Generate starting offsets into the value table for each length */ x[1] = j = 0; p = c + 1; xp = x + 2; while (--i) { /* note that i == g from above */ *xp++ = (j += *p++); } /* Make a table of values in order of bit lengths */ p = b; i = 0; do { if ((j = *p++) != 0) v[x[j]++] = i; } while (++i < n); n = x[g]; /* set n to length of v */ /* Generate the Huffman codes and for each, make the table entries */ x[0] = i = 0; /* first Huffman code is zero */ p = v; /* grab values in bit order */ h = -1; /* no tables yet--level -1 */ w = -l; /* bits decoded == (l * h) */ u[0] = (inflate_huft *)Z_NULL; /* just to keep compilers happy */ q = (inflate_huft *)Z_NULL; /* ditto */ z = 0; /* ditto */ /* go through the bit lengths (k already is bits in shortest code) */ for (; k <= g; k++) { a = c[k]; while (a--) { /* here i is the Huffman code of length k bits for value *p */ /* make tables up to required level */ while (k > w + l) { h++; w += l; /* previous table always l bits */ /* compute minimum size table less than or equal to l bits */ z = g - w; z = z > (uInt)l ? l : z; /* table size upper limit */ if ((f = 1 << (j = k - w)) > a + 1) /* try a k-w bit table */ { /* too few codes for k-w bit table */ f -= a + 1; /* deduct codes from patterns left */ xp = c + k; if (j < z) while (++j < z) /* try smaller tables up to z bits */ { if ((f <<= 1) <= *++xp) break; /* enough codes to use up j bits */ f -= *xp; /* else deduct codes from patterns */ } } z = 1 << j; /* table entries for j-bit table */ /* allocate and link in new table */ if ((q = (inflate_huft *)ZALLOC (zs,z + 1,sizeof(inflate_huft))) == Z_NULL) { if (h) inflate_trees_free(u[0], zs); return Z_MEM_ERROR; /* not enough memory */ } #ifdef DEBUG_ZLIB inflate_hufts += z + 1; #endif *t = q + 1; /* link to list for huft_free() */ *(t = &(q->next)) = Z_NULL; u[h] = ++q; /* table starts after link */ /* connect to last table, if there is one */ if (h) { x[h] = i; /* save pattern for backing up */ r.bits = (Byte)l; /* bits to dump before this table */ r.exop = (Byte)j; /* bits in this table */ r.next = q; /* pointer to this table */ j = i >> (w - l); /* (get around Turbo C bug) */ u[h-1][j] = r; /* connect to last table */ } } /* set up table entry in r */ r.bits = (Byte)(k - w); if (p >= v + n) r.exop = 128 + 64; /* out of values--invalid code */ else if (*p < s) { r.exop = (Byte)(*p < 256 ? 0 : 32 + 64); /* 256 is end-of-block */ r.base = *p++; /* simple code is just the value */ } else { r.exop = (Byte)(e[*p - s] + 16 + 64);/* non-simple--look up in lists */ r.base = d[*p++ - s]; } /* fill code-like entries with r */ f = 1 << (k - w); for (j = i >> w; j < z; j += f) q[j] = r; /* backwards increment the k-bit code i */ for (j = 1 << (k - 1); i & j; j >>= 1) i ^= j; i ^= j; /* backup over finished tables */ while ((i & ((1 << w) - 1)) != x[h]) { h--; /* don't need to update q */ w -= l; } } } /* Return Z_BUF_ERROR if we were given an incomplete table */ return y != 0 && g != 1 ? Z_BUF_ERROR : Z_OK; } int inflate_trees_bits(c, bb, tb, z) uIntf *c; /* 19 code lengths */ uIntf *bb; /* bits tree desired/actual depth */ inflate_huft * FAR *tb; /* bits tree result */ z_streamp z; /* for zfree function */ { int r; r = huft_build(c, 19, 19, (uIntf*)Z_NULL, (uIntf*)Z_NULL, tb, bb, z); if (r == Z_DATA_ERROR) z->msg = (char*)"oversubscribed dynamic bit lengths tree"; else if (r == Z_BUF_ERROR || *bb == 0) { inflate_trees_free(*tb, z); z->msg = (char*)"incomplete dynamic bit lengths tree"; r = Z_DATA_ERROR; } return r; } int inflate_trees_dynamic(nl, nd, c, bl, bd, tl, td, z) uInt nl; /* number of literal/length codes */ uInt nd; /* number of distance codes */ uIntf *c; /* that many (total) code lengths */ uIntf *bl; /* literal desired/actual bit depth */ uIntf *bd; /* distance desired/actual bit depth */ inflate_huft * FAR *tl; /* literal/length tree result */ inflate_huft * FAR *td; /* distance tree result */ z_streamp z; /* for zfree function */ { int r; /* build literal/length tree */ r = huft_build(c, nl, 257, cplens, cplext, tl, bl, z); if (r != Z_OK || *bl == 0) { if (r == Z_DATA_ERROR) z->msg = (char*)"oversubscribed literal/length tree"; else if (r != Z_MEM_ERROR) { inflate_trees_free(*tl, z); z->msg = (char*)"incomplete literal/length tree"; r = Z_DATA_ERROR; } return r; } /* build distance tree */ r = huft_build(c + nl, nd, 0, cpdist, cpdext, td, bd, z); if (r != Z_OK || (*bd == 0 && nl > 257)) { if (r == Z_DATA_ERROR) z->msg = (char*)"oversubscribed distance tree"; else if (r == Z_BUF_ERROR) { #ifdef PKZIP_BUG_WORKAROUND r = Z_OK; } #else inflate_trees_free(*td, z); z->msg = (char*)"incomplete distance tree"; r = Z_DATA_ERROR; } else if (r != Z_MEM_ERROR) { z->msg = (char*)"empty distance tree with lengths"; r = Z_DATA_ERROR; } inflate_trees_free(*tl, z); return r; #endif } /* done */ return Z_OK; } /* build fixed tables only once--keep them here */ local int fixed_built = 0; #define FIXEDH 530 /* number of hufts used by fixed tables */ local inflate_huft fixed_mem[FIXEDH]; local uInt fixed_bl; local uInt fixed_bd; local inflate_huft *fixed_tl; local inflate_huft *fixed_td; local voidpf falloc(q, n, s) voidpf q; /* opaque pointer */ uInt n; /* number of items */ uInt s; /* size of item */ { Assert(s == sizeof(inflate_huft) && n <= *(intf *)q, "inflate_trees falloc overflow"); *(intf *)q -= n+s-s; /* s-s to avoid warning */ return (voidpf)(fixed_mem + *(intf *)q); } int inflate_trees_fixed(bl, bd, tl, td) uIntf *bl; /* literal desired/actual bit depth */ uIntf *bd; /* distance desired/actual bit depth */ inflate_huft * FAR *tl; /* literal/length tree result */ inflate_huft * FAR *td; /* distance tree result */ { /* build fixed tables if not already (multiple overlapped executions ok) */ if (!fixed_built) { int k; /* temporary variable */ unsigned c[288]; /* length list for huft_build */ z_stream z; /* for falloc function */ int f = FIXEDH; /* number of hufts left in fixed_mem */ /* set up fake z_stream for memory routines */ z.zalloc = falloc; z.zfree = Z_NULL; z.opaque = (voidpf)&f; /* literal table */ for (k = 0; k < 144; k++) c[k] = 8; for (; k < 256; k++) c[k] = 9; for (; k < 280; k++) c[k] = 7; for (; k < 288; k++) c[k] = 8; fixed_bl = 7; huft_build(c, 288, 257, cplens, cplext, &fixed_tl, &fixed_bl, &z); /* distance table */ for (k = 0; k < 30; k++) c[k] = 5; fixed_bd = 5; huft_build(c, 30, 0, cpdist, cpdext, &fixed_td, &fixed_bd, &z); /* done */ Assert(f == 0, "invalid build of fixed tables"); fixed_built = 1; } *bl = fixed_bl; *bd = fixed_bd; *tl = fixed_tl; *td = fixed_td; return Z_OK; } int inflate_trees_free(t, z) inflate_huft *t; /* table to free */ z_streamp z; /* for zfree function */ /* Free the malloc'ed tables built by huft_build(), which makes a linked list of the tables it made, with the links in a dummy first entry of each table. */ { register inflate_huft *p, *q, *r; /* Reverse linked list */ p = Z_NULL; q = t; while (q != Z_NULL) { r = (q - 1)->next; (q - 1)->next = p; p = q; q = r; } /* Go through linked list, freeing from the malloced (t[-1]) address. */ while (p != Z_NULL) { q = (--p)->next; ZFREE(z,p); p = q; } return Z_OK; } /* --- inftrees.c */ /* +++ infcodes.c */ /* infcodes.c -- process literals and length/distance pairs * Copyright (C) 1995-1996 Mark Adler * For conditions of distribution and use, see copyright notice in zlib.h */ /* #include "zutil.h" */ /* #include "inftrees.h" */ /* #include "infblock.h" */ /* #include "infcodes.h" */ /* #include "infutil.h" */ /* +++ inffast.h */ /* inffast.h -- header to use inffast.c * Copyright (C) 1995-1996 Mark Adler * For conditions of distribution and use, see copyright notice in zlib.h */ /* WARNING: this file should *not* be used by applications. It is part of the implementation of the compression library and is subject to change. Applications should only use zlib.h. */ extern int inflate_fast OF(( uInt, uInt, inflate_huft *, inflate_huft *, inflate_blocks_statef *, z_streamp )); /* --- inffast.h */ /* simplify the use of the inflate_huft type with some defines */ #define base more.Base #define next more.Next #define exop word.what.Exop #define bits word.what.Bits /* inflate codes private state */ struct inflate_codes_state { /* mode */ enum { /* waiting for "i:"=input, "o:"=output, "x:"=nothing */ START, /* x: set up for LEN */ LEN, /* i: get length/literal/eob next */ LENEXT, /* i: getting length extra (have base) */ DIST, /* i: get distance next */ DISTEXT, /* i: getting distance extra */ COPY, /* o: copying bytes in window, waiting for space */ LIT, /* o: got literal, waiting for output space */ WASH, /* o: got eob, possibly still output waiting */ END, /* x: got eob and all data flushed */ BADCODE} /* x: got error */ mode; /* current inflate_codes mode */ /* mode dependent information */ uInt len; union { struct { inflate_huft *tree; /* pointer into tree */ uInt need; /* bits needed */ } code; /* if LEN or DIST, where in tree */ uInt lit; /* if LIT, literal */ struct { uInt get; /* bits to get for extra */ uInt dist; /* distance back to copy from */ } copy; /* if EXT or COPY, where and how much */ } sub; /* submode */ /* mode independent information */ Byte lbits; /* ltree bits decoded per branch */ Byte dbits; /* dtree bits decoder per branch */ inflate_huft *ltree; /* literal/length/eob tree */ inflate_huft *dtree; /* distance tree */ }; inflate_codes_statef *inflate_codes_new(bl, bd, tl, td, z) uInt bl, bd; inflate_huft *tl; inflate_huft *td; /* need separate declaration for Borland C++ */ z_streamp z; { inflate_codes_statef *c; if ((c = (inflate_codes_statef *) ZALLOC(z,1,sizeof(struct inflate_codes_state))) != Z_NULL) { c->mode = START; c->lbits = (Byte)bl; c->dbits = (Byte)bd; c->ltree = tl; c->dtree = td; Tracev((stderr, "inflate: codes new\n")); } return c; } int inflate_codes(s, z, r) inflate_blocks_statef *s; z_streamp z; int r; { uInt j; /* temporary storage */ inflate_huft *t; /* temporary pointer */ uInt e; /* extra bits or operation */ uLong b; /* bit buffer */ uInt k; /* bits in bit buffer */ Bytef *p; /* input data pointer */ uInt n; /* bytes available there */ Bytef *q; /* output window write pointer */ uInt m; /* bytes to end of window or read pointer */ Bytef *f; /* pointer to copy strings from */ inflate_codes_statef *c = s->sub.decode.codes; /* codes state */ /* copy input/output information to locals (UPDATE macro restores) */ LOAD /* process input and output based on current state */ while (1) switch (c->mode) { /* waiting for "i:"=input, "o:"=output, "x:"=nothing */ case START: /* x: set up for LEN */ #ifndef SLOW if (m >= 258 && n >= 10) { UPDATE r = inflate_fast(c->lbits, c->dbits, c->ltree, c->dtree, s, z); LOAD if (r != Z_OK) { c->mode = r == Z_STREAM_END ? WASH : BADCODE; break; } } #endif /* !SLOW */ c->sub.code.need = c->lbits; c->sub.code.tree = c->ltree; c->mode = LEN; case LEN: /* i: get length/literal/eob next */ j = c->sub.code.need; NEEDBITS(j) t = c->sub.code.tree + ((uInt)b & inflate_mask[j]); DUMPBITS(t->bits) e = (uInt)(t->exop); if (e == 0) /* literal */ { c->sub.lit = t->base; Tracevv((stderr, t->base >= 0x20 && t->base < 0x7f ? "inflate: literal '%c'\n" : "inflate: literal 0x%02x\n", t->base)); c->mode = LIT; break; } if (e & 16) /* length */ { c->sub.copy.get = e & 15; c->len = t->base; c->mode = LENEXT; break; } if ((e & 64) == 0) /* next table */ { c->sub.code.need = e; c->sub.code.tree = t->next; break; } if (e & 32) /* end of block */ { Tracevv((stderr, "inflate: end of block\n")); c->mode = WASH; break; } c->mode = BADCODE; /* invalid code */ z->msg = (char*)"invalid literal/length code"; r = Z_DATA_ERROR; LEAVE case LENEXT: /* i: getting length extra (have base) */ j = c->sub.copy.get; NEEDBITS(j) c->len += (uInt)b & inflate_mask[j]; DUMPBITS(j) c->sub.code.need = c->dbits; c->sub.code.tree = c->dtree; Tracevv((stderr, "inflate: length %u\n", c->len)); c->mode = DIST; case DIST: /* i: get distance next */ j = c->sub.code.need; NEEDBITS(j) t = c->sub.code.tree + ((uInt)b & inflate_mask[j]); DUMPBITS(t->bits) e = (uInt)(t->exop); if (e & 16) /* distance */ { c->sub.copy.get = e & 15; c->sub.copy.dist = t->base; c->mode = DISTEXT; break; } if ((e & 64) == 0) /* next table */ { c->sub.code.need = e; c->sub.code.tree = t->next; break; } c->mode = BADCODE; /* invalid code */ z->msg = (char*)"invalid distance code"; r = Z_DATA_ERROR; LEAVE case DISTEXT: /* i: getting distance extra */ j = c->sub.copy.get; NEEDBITS(j) c->sub.copy.dist += (uInt)b & inflate_mask[j]; DUMPBITS(j) Tracevv((stderr, "inflate: distance %u\n", c->sub.copy.dist)); c->mode = COPY; case COPY: /* o: copying bytes in window, waiting for space */ #ifndef __TURBOC__ /* Turbo C bug for following expression */ f = (uInt)(q - s->window) < c->sub.copy.dist ? s->end - (c->sub.copy.dist - (q - s->window)) : q - c->sub.copy.dist; #else f = q - c->sub.copy.dist; if ((uInt)(q - s->window) < c->sub.copy.dist) f = s->end - (c->sub.copy.dist - (uInt)(q - s->window)); #endif while (c->len) { NEEDOUT OUTBYTE(*f++) if (f == s->end) f = s->window; c->len--; } c->mode = START; break; case LIT: /* o: got literal, waiting for output space */ NEEDOUT OUTBYTE(c->sub.lit) c->mode = START; break; case WASH: /* o: got eob, possibly more output */ FLUSH if (s->read != s->write) LEAVE c->mode = END; case END: r = Z_STREAM_END; LEAVE case BADCODE: /* x: got error */ r = Z_DATA_ERROR; LEAVE default: r = Z_STREAM_ERROR; LEAVE } } void inflate_codes_free(c, z) inflate_codes_statef *c; z_streamp z; { ZFREE(z, c); Tracev((stderr, "inflate: codes free\n")); } /* --- infcodes.c */ /* +++ infutil.c */ /* inflate_util.c -- data and routines common to blocks and codes * Copyright (C) 1995-1996 Mark Adler * For conditions of distribution and use, see copyright notice in zlib.h */ /* #include "zutil.h" */ /* #include "infblock.h" */ /* #include "inftrees.h" */ /* #include "infcodes.h" */ /* #include "infutil.h" */ #ifndef NO_DUMMY_DECL struct inflate_codes_state {int dummy;}; /* for buggy compilers */ #endif /* And'ing with mask[n] masks the lower n bits */ uInt inflate_mask[17] = { 0x0000, 0x0001, 0x0003, 0x0007, 0x000f, 0x001f, 0x003f, 0x007f, 0x00ff, 0x01ff, 0x03ff, 0x07ff, 0x0fff, 0x1fff, 0x3fff, 0x7fff, 0xffff }; /* copy as much as possible from the sliding window to the output area */ int inflate_flush(s, z, r) inflate_blocks_statef *s; z_streamp z; int r; { uInt n; Bytef *p; Bytef *q; /* local copies of source and destination pointers */ p = z->next_out; q = s->read; /* compute number of bytes to copy as far as end of window */ n = (uInt)((q <= s->write ? s->write : s->end) - q); if (n > z->avail_out) n = z->avail_out; if (n && r == Z_BUF_ERROR) r = Z_OK; /* update counters */ z->avail_out -= n; z->total_out += n; /* update check information */ if (s->checkfn != Z_NULL) z->adler = s->check = (*s->checkfn)(s->check, q, n); /* copy as far as end of window */ if (p != Z_NULL) { zmemcpy(p, q, n); p += n; } q += n; /* see if more to copy at beginning of window */ if (q == s->end) { /* wrap pointers */ q = s->window; if (s->write == s->end) s->write = s->window; /* compute bytes to copy */ n = (uInt)(s->write - q); if (n > z->avail_out) n = z->avail_out; if (n && r == Z_BUF_ERROR) r = Z_OK; /* update counters */ z->avail_out -= n; z->total_out += n; /* update check information */ if (s->checkfn != Z_NULL) z->adler = s->check = (*s->checkfn)(s->check, q, n); /* copy */ if (p != Z_NULL) { zmemcpy(p, q, n); p += n; } q += n; } /* update pointers */ z->next_out = p; s->read = q; /* done */ return r; } /* --- infutil.c */ /* +++ inffast.c */ /* inffast.c -- process literals and length/distance pairs fast * Copyright (C) 1995-1996 Mark Adler * For conditions of distribution and use, see copyright notice in zlib.h */ /* #include "zutil.h" */ /* #include "inftrees.h" */ /* #include "infblock.h" */ /* #include "infcodes.h" */ /* #include "infutil.h" */ /* #include "inffast.h" */ #ifndef NO_DUMMY_DECL struct inflate_codes_state {int dummy;}; /* for buggy compilers */ #endif /* simplify the use of the inflate_huft type with some defines */ #define base more.Base #define next more.Next #define exop word.what.Exop #define bits word.what.Bits /* macros for bit input with no checking and for returning unused bytes */ #define GRABBITS(j) {while(k<(j)){b|=((uLong)NEXTBYTE)<<k;k+=8;}} #define UNGRAB {n+=(c=k>>3);p-=c;k&=7;} /* Called with number of bytes left to write in window at least 258 (the maximum string length) and number of input bytes available at least ten. The ten bytes are six bytes for the longest length/ distance pair plus four bytes for overloading the bit buffer. */ int inflate_fast(bl, bd, tl, td, s, z) uInt bl, bd; inflate_huft *tl; inflate_huft *td; /* need separate declaration for Borland C++ */ inflate_blocks_statef *s; z_streamp z; { inflate_huft *t; /* temporary pointer */ uInt e; /* extra bits or operation */ uLong b; /* bit buffer */ uInt k; /* bits in bit buffer */ Bytef *p; /* input data pointer */ uInt n; /* bytes available there */ Bytef *q; /* output window write pointer */ uInt m; /* bytes to end of window or read pointer */ uInt ml; /* mask for literal/length tree */ uInt md; /* mask for distance tree */ uInt c; /* bytes to copy */ uInt d; /* distance back to copy from */ Bytef *r; /* copy source pointer */ /* load input, output, bit values */ LOAD /* initialize masks */ ml = inflate_mask[bl]; md = inflate_mask[bd]; /* do until not enough input or output space for fast loop */ do { /* assume called with m >= 258 && n >= 10 */ /* get literal/length code */ GRABBITS(20) /* max bits for literal/length code */ if ((e = (t = tl + ((uInt)b & ml))->exop) == 0) { DUMPBITS(t->bits) Tracevv((stderr, t->base >= 0x20 && t->base < 0x7f ? "inflate: * literal '%c'\n" : "inflate: * literal 0x%02x\n", t->base)); *q++ = (Byte)t->base; m--; continue; } do { DUMPBITS(t->bits) if (e & 16) { /* get extra bits for length */ e &= 15; c = t->base + ((uInt)b & inflate_mask[e]); DUMPBITS(e) Tracevv((stderr, "inflate: * length %u\n", c)); /* decode distance base of block to copy */ GRABBITS(15); /* max bits for distance code */ e = (t = td + ((uInt)b & md))->exop; do { DUMPBITS(t->bits) if (e & 16) { /* get extra bits to add to distance base */ e &= 15; GRABBITS(e) /* get extra bits (up to 13) */ d = t->base + ((uInt)b & inflate_mask[e]); DUMPBITS(e) Tracevv((stderr, "inflate: * distance %u\n", d)); /* do the copy */ m -= c; if ((uInt)(q - s->window) >= d) /* offset before dest */ { /* just copy */ r = q - d; *q++ = *r++; c--; /* minimum count is three, */ *q++ = *r++; c--; /* so unroll loop a little */ } else /* else offset after destination */ { e = d - (uInt)(q - s->window); /* bytes from offset to end */ r = s->end - e; /* pointer to offset */ if (c > e) /* if source crosses, */ { c -= e; /* copy to end of window */ do { *q++ = *r++; } while (--e); r = s->window; /* copy rest from start of window */ } } do { /* copy all or what's left */ *q++ = *r++; } while (--c); break; } else if ((e & 64) == 0) e = (t = t->next + ((uInt)b & inflate_mask[e]))->exop; else { z->msg = (char*)"invalid distance code"; UNGRAB UPDATE return Z_DATA_ERROR; } } while (1); break; } if ((e & 64) == 0) { if ((e = (t = t->next + ((uInt)b & inflate_mask[e]))->exop) == 0) { DUMPBITS(t->bits) Tracevv((stderr, t->base >= 0x20 && t->base < 0x7f ? "inflate: * literal '%c'\n" : "inflate: * literal 0x%02x\n", t->base)); *q++ = (Byte)t->base; m--; break; } } else if (e & 32) { Tracevv((stderr, "inflate: * end of block\n")); UNGRAB UPDATE return Z_STREAM_END; } else { z->msg = (char*)"invalid literal/length code"; UNGRAB UPDATE return Z_DATA_ERROR; } } while (1); } while (m >= 258 && n >= 10); /* not enough input or output--restore pointers and return */ UNGRAB UPDATE return Z_OK; } /* --- inffast.c */ /* +++ zutil.c */ /* zutil.c -- target dependent utility functions for the compression library * Copyright (C) 1995-1996 Jean-loup Gailly. * For conditions of distribution and use, see copyright notice in zlib.h */ /* From: zutil.c,v 1.17 1996/07/24 13:41:12 me Exp $ */ #ifdef DEBUG_ZLIB #include <stdio.h> #endif /* #include "zutil.h" */ #ifndef NO_DUMMY_DECL struct internal_state {int dummy;}; /* for buggy compilers */ #endif #ifndef STDC extern void exit OF((int)); #endif static const char *z_errmsg[10] = { "need dictionary", /* Z_NEED_DICT 2 */ "stream end", /* Z_STREAM_END 1 */ "", /* Z_OK 0 */ "file error", /* Z_ERRNO (-1) */ "stream error", /* Z_STREAM_ERROR (-2) */ "data error", /* Z_DATA_ERROR (-3) */ "insufficient memory", /* Z_MEM_ERROR (-4) */ "buffer error", /* Z_BUF_ERROR (-5) */ "incompatible version",/* Z_VERSION_ERROR (-6) */ ""}; const char *zlibVersion() { return ZLIB_VERSION; } #ifdef DEBUG_ZLIB void z_error (m) char *m; { fprintf(stderr, "%s\n", m); exit(1); } #endif #ifndef HAVE_MEMCPY void zmemcpy(dest, source, len) Bytef* dest; Bytef* source; uInt len; { if (len == 0) return; do { *dest++ = *source++; /* ??? to be unrolled */ } while (--len != 0); } int zmemcmp(s1, s2, len) Bytef* s1; Bytef* s2; uInt len; { uInt j; for (j = 0; j < len; j++) { if (s1[j] != s2[j]) return 2*(s1[j] > s2[j])-1; } return 0; } void zmemzero(dest, len) Bytef* dest; uInt len; { if (len == 0) return; do { *dest++ = 0; /* ??? to be unrolled */ } while (--len != 0); } #endif #ifdef __TURBOC__ #if (defined( __BORLANDC__) || !defined(SMALL_MEDIUM)) && !defined(__32BIT__) /* Small and medium model in Turbo C are for now limited to near allocation * with reduced MAX_WBITS and MAX_MEM_LEVEL */ # define MY_ZCALLOC /* Turbo C malloc() does not allow dynamic allocation of 64K bytes * and farmalloc(64K) returns a pointer with an offset of 8, so we * must fix the pointer. Warning: the pointer must be put back to its * original form in order to free it, use zcfree(). */ #define MAX_PTR 10 /* 10*64K = 640K */ local int next_ptr = 0; typedef struct ptr_table_s { voidpf org_ptr; voidpf new_ptr; } ptr_table; local ptr_table table[MAX_PTR]; /* This table is used to remember the original form of pointers * to large buffers (64K). Such pointers are normalized with a zero offset. * Since MSDOS is not a preemptive multitasking OS, this table is not * protected from concurrent access. This hack doesn't work anyway on * a protected system like OS/2. Use Microsoft C instead. */ voidpf zcalloc (voidpf opaque, unsigned items, unsigned size) { voidpf buf = opaque; /* just to make some compilers happy */ ulg bsize = (ulg)items*size; /* If we allocate less than 65520 bytes, we assume that farmalloc * will return a usable pointer which doesn't have to be normalized. */ if (bsize < 65520L) { buf = farmalloc(bsize); if (*(ush*)&buf != 0) return buf; } else { buf = farmalloc(bsize + 16L); } if (buf == NULL || next_ptr >= MAX_PTR) return NULL; table[next_ptr].org_ptr = buf; /* Normalize the pointer to seg:0 */ *((ush*)&buf+1) += ((ush)((uch*)buf-0) + 15) >> 4; *(ush*)&buf = 0; table[next_ptr++].new_ptr = buf; return buf; } void zcfree (voidpf opaque, voidpf ptr) { int n; if (*(ush*)&ptr != 0) { /* object < 64K */ farfree(ptr); return; } /* Find the original pointer */ for (n = 0; n < next_ptr; n++) { if (ptr != table[n].new_ptr) continue; farfree(table[n].org_ptr); while (++n < next_ptr) { table[n-1] = table[n]; } next_ptr--; return; } ptr = opaque; /* just to make some compilers happy */ Assert(0, "zcfree: ptr not found"); } #endif #endif /* __TURBOC__ */ #if defined(M_I86) && !defined(__32BIT__) /* Microsoft C in 16-bit mode */ # define MY_ZCALLOC #if (!defined(_MSC_VER) || (_MSC_VER < 600)) # define _halloc halloc # define _hfree hfree #endif voidpf zcalloc (voidpf opaque, unsigned items, unsigned size) { if (opaque) opaque = 0; /* to make compiler happy */ return _halloc((long)items, size); } void zcfree (voidpf opaque, voidpf ptr) { if (opaque) opaque = 0; /* to make compiler happy */ _hfree(ptr); } #endif /* MSC */ #ifndef MY_ZCALLOC /* Any system without a special alloc function */ #ifndef STDC extern voidp calloc OF((uInt items, uInt size)); extern void free OF((voidpf ptr)); #endif voidpf zcalloc (opaque, items, size) voidpf opaque; unsigned items; unsigned size; { if (opaque) items += size - size; /* make compiler happy */ return (voidpf)calloc(items, size); } void zcfree (opaque, ptr) voidpf opaque; voidpf ptr; { free(ptr); if (opaque) return; /* make compiler happy */ } #endif /* MY_ZCALLOC */ /* --- zutil.c */ /* +++ adler32.c */ /* adler32.c -- compute the Adler-32 checksum of a data stream * Copyright (C) 1995-1996 Mark Adler * For conditions of distribution and use, see copyright notice in zlib.h */ /* From: adler32.c,v 1.10 1996/05/22 11:52:18 me Exp $ */ /* #include "zlib.h" */ #define BASE 65521L /* largest prime smaller than 65536 */ #define NMAX 5552 /* NMAX is the largest n such that 255n(n+1)/2 + (n+1)(BASE-1) <= 2^32-1 */ #define DO1(buf,i) {s1 += buf[(i)]; s2 += s1;} #define DO2(buf,i) DO1(buf,i); DO1(buf,(i)+1); #define DO4(buf,i) DO2(buf,i); DO2(buf,(i)+2); #define DO8(buf,i) DO4(buf,i); DO4(buf,(i)+4); #define DO16(buf) DO8(buf,0); DO8(buf,8); /* ========================================================================= */ uLong adler32(adler, buf, len) uLong adler; const Bytef *buf; uInt len; { unsigned long s1 = adler & 0xffff; unsigned long s2 = (adler >> 16) & 0xffff; int k; if (buf == Z_NULL) return 1L; while (len > 0) { k = len < NMAX ? len : NMAX; len -= k; while (k >= 16) { DO16(buf); buf += 16; k -= 16; } if (k != 0) do { s1 += *buf++; s2 += s1; } while (--k); s1 %= BASE; s2 %= BASE; } return (s2 << 16) | s1; } /* --- adler32.c */ #ifdef _KERNEL static int zlib_modevent(module_t mod, int type, void *unused) { switch (type) { case MOD_LOAD: return 0; case MOD_UNLOAD: return 0; } return EINVAL; } static moduledata_t zlib_mod = { "zlib", zlib_modevent, 0 }; DECLARE_MODULE(zlib, zlib_mod, SI_SUB_DRIVERS, SI_ORDER_FIRST); MODULE_VERSION(zlib, 1); #endif /* _KERNEL */
{'content_hash': 'b0f3a46a1a836cf5cb7e6eddf1b1927c', 'timestamp': '', 'source': 'github', 'line_count': 5414, 'max_line_length': 82, 'avg_line_length': 33.080716660509786, 'alnum_prop': 0.5529846621142497, 'repo_name': 'dplbsd/zcaplib', 'id': '09511c11644e203f2f3d96f4637d08d335d5507f', 'size': '179099', 'binary': False, 'copies': '2', 'ref': 'refs/heads/master', 'path': 'head/sys/net/zlib.c', 'mode': '33188', 'license': 'bsd-2-clause', 'language': [{'name': 'AGS Script', 'bytes': '62471'}, {'name': 'Assembly', 'bytes': '4478661'}, {'name': 'Awk', 'bytes': '278525'}, {'name': 'Batchfile', 'bytes': '20417'}, {'name': 'C', 'bytes': '383420305'}, {'name': 'C++', 'bytes': '72796771'}, {'name': 'CSS', 'bytes': '109748'}, {'name': 'ChucK', 'bytes': '39'}, {'name': 'D', 'bytes': '3784'}, {'name': 'DIGITAL Command Language', 'bytes': '10640'}, {'name': 'DTrace', 'bytes': '2311027'}, {'name': 'Emacs Lisp', 'bytes': '65902'}, {'name': 'EmberScript', 'bytes': '286'}, {'name': 'Forth', 'bytes': '184405'}, {'name': 'GAP', 'bytes': '72156'}, {'name': 'Groff', 'bytes': '32248806'}, {'name': 'HTML', 'bytes': '6749816'}, {'name': 'IGOR Pro', 'bytes': '6301'}, {'name': 'Java', 'bytes': '112547'}, {'name': 'KRL', 'bytes': '4950'}, {'name': 'Lex', 'bytes': '398817'}, {'name': 'Limbo', 'bytes': '3583'}, {'name': 'Logos', 'bytes': '187900'}, {'name': 'Makefile', 'bytes': '3551839'}, {'name': 'Mathematica', 'bytes': '9556'}, {'name': 'Max', 'bytes': '4178'}, {'name': 'Module Management System', 'bytes': '817'}, {'name': 'NSIS', 'bytes': '3383'}, {'name': 'Objective-C', 'bytes': '836351'}, {'name': 'PHP', 'bytes': '6649'}, {'name': 'Perl', 'bytes': '5530761'}, {'name': 'Perl6', 'bytes': '41802'}, {'name': 'PostScript', 'bytes': '140088'}, {'name': 'Prolog', 'bytes': '29514'}, {'name': 'Protocol Buffer', 'bytes': '61933'}, {'name': 'Python', 'bytes': '299247'}, {'name': 'R', 'bytes': '764'}, {'name': 'Rebol', 'bytes': '738'}, {'name': 'Ruby', 'bytes': '45958'}, {'name': 'Scilab', 'bytes': '197'}, {'name': 'Shell', 'bytes': '10501540'}, {'name': 'SourcePawn', 'bytes': '463194'}, {'name': 'SuperCollider', 'bytes': '80208'}, {'name': 'Tcl', 'bytes': '80913'}, {'name': 'TeX', 'bytes': '719821'}, {'name': 'VimL', 'bytes': '22201'}, {'name': 'XS', 'bytes': '25451'}, {'name': 'XSLT', 'bytes': '31488'}, {'name': 'Yacc', 'bytes': '1857830'}]}
#pragma once #include "Actor/Material/Material.h" #include <memory> namespace ph { class InputPacket; class CookingContext; class SurfaceMaterial; class VolumeMaterial; // TODO: volume material class FullMaterial final : public Material, public TCommandInterface<FullMaterial> { public: FullMaterial(); FullMaterial(const std::shared_ptr<SurfaceMaterial>& surfaceMaterial); void genBehaviors(CookingContext& context, PrimitiveMetadata& metadata) const override; private: std::shared_ptr<SurfaceMaterial> m_surfaceMaterial; std::shared_ptr<VolumeMaterial> m_interiorMaterial; std::shared_ptr<VolumeMaterial> m_exteriorMaterial; // command interface public: explicit FullMaterial(const InputPacket& packet); static SdlTypeInfo ciTypeInfo(); static void ciRegister(CommandRegister& cmdRegister); }; }// end namespace ph /* <SDL_interface> <category> material </category> <type_name> full </type_name> <extend> material.material </extend> <name> Full Material </name> <description> A material model that combines surface and volume properties. </description> <command type="creator"> <input name="surface" type="material"> <description>A surface material.</description> </input> <input name="interior" type="material"> <description>A volume material describing the inside of the surface.</description> </input> <input name="exterior" type="material"> <description>A volume material describing the outside of the surface.</description> </input> </command> </SDL_interface> */
{'content_hash': '683a356489491864c7ccfc956ac8d98b', 'timestamp': '', 'source': 'github', 'line_count': 64, 'max_line_length': 88, 'avg_line_length': 24.296875, 'alnum_prop': 0.7434083601286173, 'repo_name': 'TzuChieh/Photon-v2', 'id': 'bb9c31840a3331eef3937829bf25e2d7ec23ecbb', 'size': '1555', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'Engine/Source/Actor/Material/FullMaterial.h', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'Batchfile', 'bytes': '429'}, {'name': 'C', 'bytes': '7059'}, {'name': 'C++', 'bytes': '1572544'}, {'name': 'CMake', 'bytes': '7944'}, {'name': 'Java', 'bytes': '265901'}, {'name': 'Objective-C', 'bytes': '336'}, {'name': 'Python', 'bytes': '171368'}, {'name': 'Shell', 'bytes': '439'}]}
'use strict'; /** * Module dependencies. */ var should = require('should'), mongoose = require('mongoose'), User = mongoose.model('User'), Player = mongoose.model('Player'); /** * Globals */ var user, player; /** * Unit tests */ describe('Player Model Unit Tests:', function() { beforeEach(function(done) { user = new User({ firstName: 'Full', lastName: 'Name', displayName: 'Full Name', email: '[email protected]', username: 'username', password: 'password' }); user.save(function() { player = new Player({ name: 'Player Name', user: user }); done(); }); }); describe('Method Save', function() { it('should be able to save without problems', function(done) { return player.save(function(err) { should.not.exist(err); done(); }); }); it('should be able to show an error when try to save without name', function(done) { player.name = ''; return player.save(function(err) { should.exist(err); done(); }); }); }); afterEach(function(done) { Player.remove().exec(); User.remove().exec(); done(); }); });
{'content_hash': '355913364d83c5a4285a66bb7279ba03', 'timestamp': '', 'source': 'github', 'line_count': 64, 'max_line_length': 87, 'avg_line_length': 17.359375, 'alnum_prop': 0.5931593159315932, 'repo_name': 'oferlivny/iteammaker', 'id': '4e7b56a0c36ea60489ae56d7564e561a216d2dc4', 'size': '1111', 'binary': False, 'copies': '8', 'ref': 'refs/heads/master', 'path': 'app/tests/player.server.model.test.js', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'CSS', 'bytes': '538'}, {'name': 'HTML', 'bytes': '27971'}, {'name': 'JavaScript', 'bytes': '133065'}, {'name': 'Shell', 'bytes': '414'}]}
var sys = require('sys'); module.exports = function(id, bufferSize, maxBaseNicknameLength) { var room = {}; var clientCount = 0; var clients = {}; var nicknames = {}; var buffer = []; var broadcast = function(message, sender) { for (sessionId in clients) { var client = clients[sessionId]; if (buffer.length > bufferSize) buffer.shift(); if (!sender || sender.sessionId != client.sessionId) { client.send(message); } } }; var splitNickname = function(str) { var reverse = parseInt(str.split('').reverse().join(''), 10); if (isNaN(reverse)) return {prefix: str, suffix: null}; var suffix = parseInt(String(reverse).split('').reverse().join(''), 10); return {prefix: str.substring(0, str.length - String(suffix).length), suffix: suffix}; }; var assignNickname = function(nickname, client) { nickname = nickname.substring(0, maxBaseNicknameLength); var nicks = {}; for (sessionId in nicknames) { nicks[nicknames[sessionId]] = sessionId; } if (!(nickname in nicks)) { nicknames[client.sessionId] = nickname; return; } var nick = splitNickname(nickname); var i = nick.suffix ? nick.suffix : 1; while ((nick.prefix + i) in nicks && nicks[nick.prefix + i] != client.sessionId) { i++; } nicknames[client.sessionId] = nick.prefix + i; }; var getNickname = function(client) { if (!client) return null; return nicknames[client.sessionId]; }; room.addClient = function(nickname, client) { clients[client.sessionId] = client; assignNickname(nickname, client); clientCount++; client.send({ action: 'init', value: { buffer: buffer, nicknames: nicknames, roomId: id } }); room.broadcastAnnouncement(getNickname(client) + ' has joined.', client); broadcast({action: 'nicknamesUpdated', value: nicknames}); }; room.removeClient = function(client) { room.broadcastAnnouncement(getNickname(client) + ' has left.', client); delete clients[client.sessionId]; delete nicknames[client.sessionId]; clientCount--; broadcast({action: 'nicknamesUpdated', value: nicknames}); }; room.getClientCount = function() { return clientCount; }; room.getID = function() { return id; }; room.broadcastAnnouncement = function(message, sender) { buffer.push({message: message, type: 'announcement', nickname: getNickname(sender)}); broadcast({action: 'announcement', value: {message: message, nickname: getNickname(sender)}}, sender); }; room.broadcastStatus = function(status, sender) { status = getNickname(sender) + ' ' + status; room.broadcastAnnouncement(status); }; room.broadcastMessage = function(message, sender) { buffer.push({message: message, type: 'message', nickname: getNickname(sender)}); broadcast({action: 'message', value: {message: message, nickname: getNickname(sender)}}, sender); }; room.changeNickname = function(nickname, client) { var oldNick = getNickname(client); if (oldNick === nickname) { return; } assignNickname(nickname, client); var newNick = getNickname(client); if (oldNick === newNick) { return; } broadcast({action: 'nicknamesUpdated', value: nicknames}); room.broadcastAnnouncement(oldNick + ' is now known as ' + newNick); }; return room; };
{'content_hash': 'cd153d09951fec364460d7cb8c882bdd', 'timestamp': '', 'source': 'github', 'line_count': 117, 'max_line_length': 104, 'avg_line_length': 27.726495726495727, 'alnum_prop': 0.6778668310727497, 'repo_name': 'ipartola/natchat', 'id': '680c65dcc50099fb11bd46109372cf92eb45c2b7', 'size': '3244', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'chat-room.js', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'JavaScript', 'bytes': '78785'}, {'name': 'Python', 'bytes': '655'}]}
'use strict'; angular.module('myApp.register', ['ngRoute']) // Declared route .config(['$routeProvider', function($routeProvider) { $routeProvider.when('/register', { templateUrl: 'register/register.html', controller: 'RegisterCtrl' }); }]) // Register controller .controller('RegisterCtrl', [function() { }]);
{'content_hash': 'b448e6505a990f4891411871b85109ea', 'timestamp': '', 'source': 'github', 'line_count': 16, 'max_line_length': 53, 'avg_line_length': 21.1875, 'alnum_prop': 0.6519174041297935, 'repo_name': 'toshibakru/FinTech', 'id': '8701eb275730a498179f35f7289721264dd44239', 'size': '339', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'app/register/register.js', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'CSS', 'bytes': '1187'}, {'name': 'HTML', 'bytes': '16806'}, {'name': 'JavaScript', 'bytes': '14021'}]}
<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title>Page hosted, for webview sample</title> </head> <body> <p>This page is hosted at an external server. Observe how it interacts with the embedder application</p> <button id="sendmessage">Send message to app</button><br> <button id="pointerlock">Pointer lock</button><br> <button id="captureimage">Capture image</button><br> <button id="geoloc">Request geolocation</button><br> <a href="http://google.com">Go to google.com</a><br> <div id="log"></div><br> <script type="text/javascript"> (function() { var log=document.getElementById("log"); var appWindow, appOrigin; function onMessage(e) { appWindow = e.source; appOrigin = e.origin; console.log(e); } function doSendMessage() { log.innerText=""; if (appWindow && appOrigin) { appWindow.postMessage("this is a message from the page!", appOrigin) log.innerText="message sent"; } else { log.innerText="ERROR: don't have app info - no initial message received"; } } function doPointerLock() { document.body.webkitRequestPointerLock(); log.innerText="Pointer lock requested"; } function doCaptureImage() { var video = document.querySelector('video'); if (!video) { video = document.createElement('video'); video.style.width="200px"; video.autoplay = true; document.body.appendChild(video); } navigator.webkitGetUserMedia( {video: true, audio: true}, function(stream) { video.src = window.URL.createObjectURL(stream); log.innerText="video running, enjoy!"; }); } function doGeoloc() { log.innerText="requested position"; if (navigator.geolocation) { navigator.geolocation.getCurrentPosition(function(position) { log.innerText='position='+position; }); } } window.addEventListener('message', onMessage); document.getElementById("sendmessage").addEventListener('click', doSendMessage); document.getElementById("pointerlock").addEventListener('click', doPointerLock); document.getElementById("captureimage").addEventListener('click', doCaptureImage); document.getElementById("geoloc").addEventListener('click', doGeoloc); })(); </script> </body> </html>
{'content_hash': '468be6263b5582b61bb3ab2e9e89278a', 'timestamp': '', 'source': 'github', 'line_count': 81, 'max_line_length': 106, 'avg_line_length': 27.0, 'alnum_prop': 0.7037037037037037, 'repo_name': 'hohanhb285/chrome-app-samples', 'id': '8c5a5e1faf80d1ce395e205da79c73fd789ae65a', 'size': '2187', 'binary': False, 'copies': '6', 'ref': 'refs/heads/master', 'path': 'webview/page_hosted_in_external_server.html', 'mode': '33188', 'license': 'apache-2.0', 'language': []}
{% extends "base.html" %} {% block title%}{% endblock %} {% block header %} <link rel="stylesheet" href="/static/css/chat.css?fs"> {% endblock %} {% block pager %} {% if paginator.page_count!=1 %} <div class="pager"> {{paginator.pager(format='~20~')}} </div> {% endif %} {% endblock %} {% block content %} {{ self.pager() }} <div id="archiveConversation"> {% if lines|length!=0 %} {% if mode=='normal': %} {% set last_date = None %} {% for line in lines %} {% set current_date = line['datetime'].date() %} {% if current_date!=last_date %} <h1>{{current_date.strftime("%A %d %B %Y")}}</h1> {% set last_date = current_date %} {% endif %} <p style="color: #{{line['color']}}" class="{% if line.counter==-1 %}system{% else %}user{{line['counter']}}{% endif %}">{{line['line']}}<span class="timestamp">{{line['datetime'].strftime('%X')}}</span></p> {% endfor %} <p><a href="{{url_for('view_log', chat=chat, page=current_page, mode='bbcode' )}}">View as BBCode</a></p> {% elif mode=='bbcode': %} {% for line in lines %} <p>[color=#{{line.color}}]{{line.line}}[/color]</p> {% endfor %} <p><a href="{{url_for('view_log', chat=chat, page=current_page, mode='normal' )}}">View as text</a></p> {% endif %} {% endif %} <p><a href="/chat/{{chat}}/export">Export this log</a></p> </div> {{ self.pager() }} <script> function getURLParameter(name) { return decodeURI( (RegExp(name + '=' + '(.+?)(&|$)').exec(location.search)||[,null])[1] ); } function linkify(inputText) { var replacedText, replacePattern1, replacePattern2; //URLs starting with http://, https://, or ftp:// replacePattern1 = /]?=?https?:\/\/[-a-zA-Z0-9@:%._\+~#=]{2,256}\.[a-z]{2,6}\b([-a-zA-Z0-9@:%_\+.~#?&//=]*)/gim; replacedText = inputText.replace(replacePattern1, function(m) { if (m.substr(0,1) == "=" || m.substr(0,1) == "]") { return m; } else { return "[url]"+m+"[/url]"; } }); //Change email addresses to mailto:: links. replacePattern2 = /(\w+@[a-zA-Z_]+?\.[a-zA-Z]{2,6})/gim; replacedText = replacedText.replace(replacePattern2, '[email]$1[/email]'); return replacedText; } if (getURLParameter('mode') == 'bbcode') { } else if (getURLParameter('mode') == 'plaintext') { $('#archiveConversation p').each(function() { line = htmlEncode(bbRemove($(this).html())); $(this).html(line); }); } else { $('#archiveConversation p').each(function() { if ($(this).attr('class')) { linin = $(this).html(); BS = linin.substr(linin.length-39); linin = linin.substr(0,linin.length-39); line = bbEncode(linkify(linin)); $(this).html(line).append(BS); } }); } $('.spoiler').live('click', function() { if ($(this).css('opacity') == '0') { $(this).css('opacity','1'); } else { $(this).css('opacity','0'); } }); var storage = (function() { var uid = new Date; var result; try { localStorage.setItem(uid, uid); result = localStorage.getItem(uid) == uid; localStorage.removeItem(uid); return result && localStorage; } catch (exception) {} }()); if (storage){ if (localStorage.creppy == 'creppy'){ $('head').append('<link rel="stylesheet" id="creppyid" href="/static/css/mscreppy_chat.css?41031" type="text/css" />'); } } </script> {% endblock %}
{'content_hash': '5fa4c19a9f7eac9a24e75f2475900373', 'timestamp': '', 'source': 'github', 'line_count': 115, 'max_line_length': 208, 'avg_line_length': 31.043478260869566, 'alnum_prop': 0.5260504201680672, 'repo_name': 'MSPARP/MSPARP', 'id': '85aca0cceee09ca8733a58efd72d245b736506c7', 'size': '3570', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'templates/log.html', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'CSS', 'bytes': '51494'}, {'name': 'HTML', 'bytes': '77834'}, {'name': 'JavaScript', 'bytes': '98022'}, {'name': 'Python', 'bytes': '115220'}]}
@interface MenuViewController () <UITableViewDelegate> { } @property (weak, nonatomic) IBOutlet UITableView *menuTableVIew; @property (strong, nonatomic) MenuDataSource *menuDataSource; @end @implementation MenuViewController #pragma mark - Table View Delegate - (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath { [tableView deselectRowAtIndexPath:indexPath animated:NO]; // NSLog(@"%@", [self.menuDataSource menuDataWithIndexPath:indexPath]); [self.menuDrawerVC.appVC closeDrawerWithAnimation:YES completion:^(BOOL finished){ NSLog(@"%s", __PRETTY_FUNCTION__); }]; } #pragma mark - View Controller - (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil { self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil]; if (self) { self.menuDataSource = [MenuDataSource new]; } return self; } - (void)viewDidLoad { [super viewDidLoad]; self.menuTableVIew.dataSource = self.menuDataSource; self.menuTableVIew.delegate = self; } - (void)didReceiveMemoryWarning { [super didReceiveMemoryWarning]; // Dispose of any resources that can be recreated. } - (void)viewDidLayoutSubviews { [super viewDidLayoutSubviews]; [self.view layoutSubviews]; } @end
{'content_hash': 'e44a1da2dc282a12d3cb6ccdff7262d5', 'timestamp': '', 'source': 'github', 'line_count': 61, 'max_line_length': 91, 'avg_line_length': 25.049180327868854, 'alnum_prop': 0.6230366492146597, 'repo_name': 'ykmt/MovingView', 'id': 'ec762c70f6032f61ac6ad6410f91607e54abd0ab', 'size': '1779', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'MovingView/MenuViewController.m', 'mode': '33188', 'license': 'bsd-3-clause', 'language': [{'name': 'Objective-C', 'bytes': '31187'}]}
require 'chefspec' require 'chefspec/berkshelf' RSpec.configure do |config| config.log_level = :fatal # Guard against people using deprecated RSpec syntax config.raise_errors_for_deprecations! # Why aren't these the defaults? config.filter_run focus: true config.run_all_when_everything_filtered = true # Set a default platform (this is overriden as needed) config.platform = 'freebsd' config.version = '12' # Be random! config.order = 'random' end
{'content_hash': 'c6094ae385dd4921dc7808bd4def2a5c', 'timestamp': '', 'source': 'github', 'line_count': 20, 'max_line_length': 56, 'avg_line_length': 23.95, 'alnum_prop': 0.7265135699373695, 'repo_name': 'chef-cookbooks/freebsd', 'id': '8a8ff7dedca28b8334763687ff3b27412ec97222', 'size': '479', 'binary': False, 'copies': '2', 'ref': 'refs/heads/main', 'path': 'spec/spec_helper.rb', 'mode': '33188', 'license': 'apache-2.0', 'language': [{'name': 'Ruby', 'bytes': '11492'}]}
import com.google.common.collect.Lists; import jetbrains.buildServer.BaseTestCase; import jetbrains.buildServer.vsoRooms.notificator.VSOTeamRoomIdsCache; import jetbrains.buildServer.vsoRooms.rest.TeamRoom; import jetbrains.buildServer.vsoRooms.rest.VSOTeamRoomsAPIConnection; import org.jmock.Expectations; import org.jmock.Mockery; import org.testng.annotations.BeforeMethod; import org.testng.annotations.Test; /** * @author Evgeniy.Koshkin */ public class VSOTeamRoomIdsCacheTest extends BaseTestCase { private VSOTeamRoomIdsCache myCache; private Mockery myMockery; @Override @BeforeMethod public void setUp() throws Exception { super.setUp(); myCache = new VSOTeamRoomIdsCache(); myMockery = new Mockery(); } @Test public void test_room_names_collision_in_separate_accounts() throws Exception { final VSOTeamRoomsAPIConnection apiConnection = myMockery.mock(VSOTeamRoomsAPIConnection.class); myMockery.checking(new Expectations() {{ one(apiConnection).getListOfRooms("accountA"); will(returnValue(Lists.newArrayList(new TeamRoom(1L, "room", "accountA room")))); one(apiConnection).getListOfRooms("accountB"); will(returnValue(Lists.newArrayList(new TeamRoom(2L, "room", "accountB room")))); }}); assertEquals(Long.valueOf(1), myCache.getOrResolveRoomId("accountA", "room", apiConnection)); assertEquals(Long.valueOf(2), myCache.getOrResolveRoomId("accountB", "room", apiConnection)); myMockery.assertIsSatisfied(); } @Test public void should_be_case_insensitive_for_team_room_name() throws Exception { final VSOTeamRoomsAPIConnection apiConnection = myMockery.mock(VSOTeamRoomsAPIConnection.class); myMockery.checking(new Expectations() {{ one(apiConnection).getListOfRooms("account"); will(returnValue(Lists.newArrayList(new TeamRoom(1L, "Room", "account room")))); }}); assertEquals(Long.valueOf(1), myCache.getOrResolveRoomId("account", "ROOM", apiConnection)); assertEquals(Long.valueOf(1), myCache.getOrResolveRoomId("account", "room", apiConnection)); assertEquals(Long.valueOf(1), myCache.getOrResolveRoomId("account", "Room", apiConnection)); myMockery.assertIsSatisfied(); } @Test public void should_be_case_insensitive_for_account() throws Exception { final VSOTeamRoomsAPIConnection apiConnection = myMockery.mock(VSOTeamRoomsAPIConnection.class); myMockery.checking(new Expectations() {{ one(apiConnection).getListOfRooms("account"); will(returnValue(Lists.newArrayList(new TeamRoom(1L, "room", "account room")))); }}); assertEquals(Long.valueOf(1), myCache.getOrResolveRoomId("account", "room", apiConnection)); assertEquals(Long.valueOf(1), myCache.getOrResolveRoomId("Account", "room", apiConnection)); assertEquals(Long.valueOf(1), myCache.getOrResolveRoomId("ACCOUNT", "room", apiConnection)); myMockery.assertIsSatisfied(); } @Test public void should_resolve_all_account_room_ids_on_first_call() throws Exception { final VSOTeamRoomsAPIConnection apiConnection = myMockery.mock(VSOTeamRoomsAPIConnection.class); myMockery.checking(new Expectations() {{ one(apiConnection).getListOfRooms("account"); will(returnValue(Lists.newArrayList(new TeamRoom(1L, "room1", "account room 1"), new TeamRoom(2L, "room2", "account room 2")))); }}); assertEquals(Long.valueOf(1), myCache.getOrResolveRoomId("account", "room1", apiConnection)); assertEquals(Long.valueOf(2), myCache.getOrResolveRoomId("account", "room2", apiConnection)); } }
{'content_hash': '09b11d0e3e2514debcb8d378584bf1d1', 'timestamp': '', 'source': 'github', 'line_count': 79, 'max_line_length': 134, 'avg_line_length': 45.164556962025316, 'alnum_prop': 0.7480381165919282, 'repo_name': 'JetBrains/tc-vso-rooms', 'id': '05be5b05bf48c5fb274e46dac9aca6365229e087', 'size': '4168', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'tests/src/VSOTeamRoomIdsCacheTest.java', 'mode': '33188', 'license': 'apache-2.0', 'language': [{'name': 'CSS', 'bytes': '791'}, {'name': 'FreeMarker', 'bytes': '13486'}, {'name': 'Java', 'bytes': '90553'}, {'name': 'JavaScript', 'bytes': '3180'}]}
namespace device { // static base::WeakPtr<BluetoothLocalGattService> BluetoothLocalGattService::Create( BluetoothAdapter* adapter, const BluetoothUUID& uuid, bool is_primary, BluetoothLocalGattService* included_service, BluetoothLocalGattService::Delegate* delegate) { bluez::BluetoothAdapterBlueZ* adapter_bluez = static_cast<bluez::BluetoothAdapterBlueZ*>(adapter); bluez::BluetoothLocalGattServiceBlueZ* service = new bluez::BluetoothLocalGattServiceBlueZ(adapter_bluez, uuid, is_primary, delegate); return service->weak_ptr_factory_.GetWeakPtr(); } } // namespace device namespace bluez { BluetoothLocalGattServiceBlueZ::BluetoothLocalGattServiceBlueZ( BluetoothAdapterBlueZ* adapter, const device::BluetoothUUID& uuid, bool is_primary, device::BluetoothLocalGattService::Delegate* delegate) : BluetoothGattServiceBlueZ( adapter, AddGuidToObjectPath(adapter->GetApplicationObjectPath().value() + "/service")), uuid_(uuid), is_primary_(is_primary), delegate_(delegate), weak_ptr_factory_(this) { VLOG(1) << "Creating local GATT service with identifier: " << GetIdentifier(); adapter->AddLocalGattService(base::WrapUnique(this)); } BluetoothLocalGattServiceBlueZ::~BluetoothLocalGattServiceBlueZ() {} device::BluetoothUUID BluetoothLocalGattServiceBlueZ::GetUUID() const { return uuid_; } bool BluetoothLocalGattServiceBlueZ::IsPrimary() const { return is_primary_; } void BluetoothLocalGattServiceBlueZ::Register( const base::Closure& callback, const ErrorCallback& error_callback) { GetAdapter()->RegisterGattService(this, callback, error_callback); } void BluetoothLocalGattServiceBlueZ::Unregister( const base::Closure& callback, const ErrorCallback& error_callback) { DCHECK(GetAdapter()); GetAdapter()->UnregisterGattService(this, callback, error_callback); } bool BluetoothLocalGattServiceBlueZ::IsRegistered() { return GetAdapter()->IsGattServiceRegistered(this); } void BluetoothLocalGattServiceBlueZ::Delete() { weak_ptr_factory_.InvalidateWeakPtrs(); GetAdapter()->RemoveLocalGattService(this); } device::BluetoothLocalGattCharacteristic* BluetoothLocalGattServiceBlueZ::GetCharacteristic( const std::string& identifier) { const auto& service = characteristics_.find(dbus::ObjectPath(identifier)); return service == characteristics_.end() ? nullptr : service->second.get(); }; const std::map<dbus::ObjectPath, std::unique_ptr<BluetoothLocalGattCharacteristicBlueZ>>& BluetoothLocalGattServiceBlueZ::GetCharacteristics() const { return characteristics_; } // static dbus::ObjectPath BluetoothLocalGattServiceBlueZ::AddGuidToObjectPath( const std::string& path) { std::string GuidString = base::GenerateGUID(); base::RemoveChars(GuidString, "-", &GuidString); return dbus::ObjectPath(path + GuidString); } void BluetoothLocalGattServiceBlueZ::AddCharacteristic( std::unique_ptr<BluetoothLocalGattCharacteristicBlueZ> characteristic) { characteristics_[characteristic->object_path()] = std::move(characteristic); } } // namespace bluez
{'content_hash': '046c85ff169f4b53c3b1273284400a27', 'timestamp': '', 'source': 'github', 'line_count': 98, 'max_line_length': 80, 'avg_line_length': 32.88775510204081, 'alnum_prop': 0.7381321749922433, 'repo_name': 'wuhengzhi/chromium-crosswalk', 'id': '36fe94fe3691b8d344e81d8fafe18c2307e7e07d', 'size': '3673', 'binary': False, 'copies': '10', 'ref': 'refs/heads/master', 'path': 'device/bluetooth/bluez/bluetooth_local_gatt_service_bluez.cc', 'mode': '33188', 'license': 'bsd-3-clause', 'language': []}
""" Tests For Cells Utility methods """ import inspect import random from nova.cells import utils as cells_utils from nova import db from nova import test class CellsUtilsTestCase(test.TestCase): """Test case for Cells utility methods.""" def test_get_instances_to_sync(self): fake_context = 'fake_context' call_info = {'get_all': 0, 'shuffle': 0} def random_shuffle(_list): call_info['shuffle'] += 1 def instance_get_all_by_filters(context, filters, sort_key, sort_order): self.assertEqual(context, fake_context) self.assertEqual(sort_key, 'deleted') self.assertEqual(sort_order, 'asc') call_info['got_filters'] = filters call_info['get_all'] += 1 return ['fake_instance1', 'fake_instance2', 'fake_instance3'] self.stubs.Set(db, 'instance_get_all_by_filters', instance_get_all_by_filters) self.stubs.Set(random, 'shuffle', random_shuffle) instances = cells_utils.get_instances_to_sync(fake_context) self.assertTrue(inspect.isgenerator(instances)) self.assertTrue(len([x for x in instances]), 3) self.assertEqual(call_info['get_all'], 1) self.assertEqual(call_info['got_filters'], {}) self.assertEqual(call_info['shuffle'], 0) instances = cells_utils.get_instances_to_sync(fake_context, shuffle=True) self.assertTrue(inspect.isgenerator(instances)) self.assertTrue(len([x for x in instances]), 3) self.assertEqual(call_info['get_all'], 2) self.assertEqual(call_info['got_filters'], {}) self.assertEqual(call_info['shuffle'], 1) instances = cells_utils.get_instances_to_sync(fake_context, updated_since='fake-updated-since') self.assertTrue(inspect.isgenerator(instances)) self.assertTrue(len([x for x in instances]), 3) self.assertEqual(call_info['get_all'], 3) self.assertEqual(call_info['got_filters'], {'changes-since': 'fake-updated-since'}) self.assertEqual(call_info['shuffle'], 1) instances = cells_utils.get_instances_to_sync(fake_context, project_id='fake-project', updated_since='fake-updated-since', shuffle=True) self.assertTrue(inspect.isgenerator(instances)) self.assertTrue(len([x for x in instances]), 3) self.assertEqual(call_info['get_all'], 4) self.assertEqual(call_info['got_filters'], {'changes-since': 'fake-updated-since', 'project_id': 'fake-project'}) self.assertEqual(call_info['shuffle'], 2) def test_split_cell_and_item(self): path = 'australia', 'queensland', 'gold_coast' cell = cells_utils._PATH_CELL_SEP.join(path) item = 'host_5' together = cells_utils.cell_with_item(cell, item) self.assertEqual(cells_utils._CELL_ITEM_SEP.join([cell, item]), together) # Test normal usage result_cell, result_item = cells_utils.split_cell_and_item(together) self.assertEqual(cell, result_cell) self.assertEqual(item, result_item) # Test with no cell cell = None together = cells_utils.cell_with_item(cell, item) self.assertEqual(item, together) result_cell, result_item = cells_utils.split_cell_and_item(together) self.assertEqual(cell, result_cell) self.assertEqual(item, result_item)
{'content_hash': '04d15b8373e81751e0aadb6587a4cac3', 'timestamp': '', 'source': 'github', 'line_count': 89, 'max_line_length': 76, 'avg_line_length': 40.337078651685395, 'alnum_prop': 0.6094707520891365, 'repo_name': 'sridevikoushik31/nova', 'id': '337556282122659f0166cd5cd345b1b240a05fba', 'size': '4226', 'binary': False, 'copies': '3', 'ref': 'refs/heads/port_id_in_vif_on_devide', 'path': 'nova/tests/cells/test_cells_utils.py', 'mode': '33188', 'license': 'apache-2.0', 'language': [{'name': 'JavaScript', 'bytes': '7403'}, {'name': 'Python', 'bytes': '9944606'}, {'name': 'Ruby', 'bytes': '782'}, {'name': 'Shell', 'bytes': '17522'}]}
namespace omaha { namespace internal { void CommandLineParserArgs::Reset() { switch_arguments_.clear(); } // Assumes switch_name is already lower case. HRESULT CommandLineParserArgs::AddSwitch(const CString& switch_name) { ASSERT1(CString(switch_name).MakeLower().Compare(switch_name) == 0); if (switch_arguments_.find(switch_name) != switch_arguments_.end()) { return E_INVALIDARG; } StringVector string_vector; switch_arguments_[switch_name] = string_vector; return S_OK; } // Assumes switch_name is already lower case. HRESULT CommandLineParserArgs::AddSwitchArgument(const CString& switch_name, const CString& value) { ASSERT1(CString(switch_name).MakeLower().Compare(switch_name) == 0); ASSERT1(!switch_name.IsEmpty()); if (switch_name.IsEmpty()) { // We don't have a switch yet, so this is just a base argument. // Example command line: "foo.exe myarg /someswitch" // Here, myarg would be a base argument. // TODO(omaha): base_args_.push_back(switch_name_str); return E_INVALIDARG; } SwitchAndArgumentsMap::iterator iter = switch_arguments_.find(switch_name); if (iter == switch_arguments_.end()) { return E_UNEXPECTED; } (*iter).second.push_back(value); return S_OK; } int CommandLineParserArgs::GetSwitchCount() const { return switch_arguments_.size(); } bool CommandLineParserArgs::HasSwitch(const CString& switch_name) const { CString switch_name_lower = switch_name; switch_name_lower.MakeLower(); return switch_arguments_.find(switch_name_lower) != switch_arguments_.end(); } // The value at a particular index may change if switch_names are added // since we're using a map underneath. But this keeps us from having to write // an interator and expose it externally. HRESULT CommandLineParserArgs::GetSwitchNameAtIndex(int index, CString* name) const { ASSERT1(name); if (index >= static_cast<int>(switch_arguments_.size())) { return E_INVALIDARG; } SwitchAndArgumentsMapIter iter = switch_arguments_.begin(); for (int i = 0; i < index; ++i) { ++iter; } *name = (*iter).first; return S_OK; } HRESULT CommandLineParserArgs::GetSwitchArgumentCount( const CString& switch_name, int* count) const { ASSERT1(count); CString switch_name_lower = switch_name; switch_name_lower.MakeLower(); SwitchAndArgumentsMapIter iter = switch_arguments_.find(switch_name_lower); if (iter == switch_arguments_.end()) { return E_INVALIDARG; } *count = (*iter).second.size(); return S_OK; } HRESULT CommandLineParserArgs::GetSwitchArgumentValue( const CString& switch_name, int argument_index, CString* argument_value) const { ASSERT1(argument_value); CString switch_name_lower = switch_name; switch_name_lower.MakeLower(); int count = 0; HRESULT hr = GetSwitchArgumentCount(switch_name_lower, &count); if (FAILED(hr)) { return hr; } if (argument_index >= count) { return E_INVALIDARG; } SwitchAndArgumentsMapIter iter = switch_arguments_.find(switch_name_lower); if (iter == switch_arguments_.end()) { return E_INVALIDARG; } *argument_value = (*iter).second[argument_index]; return S_OK; } } // namespace internal CommandLineParser::CommandLineParser() { } CommandLineParser::~CommandLineParser() { } HRESULT CommandLineParser::ParseFromString(const wchar_t* command_line) { CString command_line_str(command_line); command_line_str.Trim(_T(" ")); int argc = 0; wchar_t** argv = ::CommandLineToArgvW(command_line_str, &argc); if (!argv) { return HRESULTFromLastError(); } HRESULT hr = ParseFromArgv(argc, argv); ::LocalFree(argv); return hr; } // TODO(Omaha): Move the rule parser into a separate class. // TODO(Omaha): Fail the regular command parser if [/ switch is passed. // ParseFromArgv parses either a rule or a command line. // // Rules have required and optional parameters. An example of a rule is: // "gu.exe /install <extraargs> [/oem [/appargs <appargs> [/silent" // This creates a rule for a command line that requires "/install" for the rule // to match. The other parameters are optional, indicated by prefixes of "[/". // // Command lines do not use "[/", and use "/" for all parameters. // A command line that looks like this: // "gu.exe /install <extraargs> /oem /appargs <appargs>" // will match the rule above. HRESULT CommandLineParser::ParseFromArgv(int argc, wchar_t** argv) { if (argc == 0 || !argv) { return E_INVALIDARG; } CORE_LOG(L5, (_T("[CommandLineParser::ParseFromArgv][argc=%d]"), argc)); Reset(); if (argc == 1) { // We only have the program name. So, we're done parsing. ASSERT1(!IsSwitch(argv[0])); return S_OK; } CString current_switch_name; bool is_optional_switch = false; // Start parsing at the first argument after the program name (index 1). for (int i = 1; i < argc; ++i) { HRESULT hr = S_OK; CString token = argv[i]; token.Trim(_T(" ")); CORE_LOG(L5, (_T("[Parsing arg][i=%d][argv[i]=%s]"), i, token)); if (IsSwitch(token)) { hr = StripSwitchNameFromArgv(token, &current_switch_name); if (FAILED(hr)) { return hr; } hr = AddSwitch(current_switch_name); if (FAILED(hr)) { CORE_LOG(LE, (_T("[AddSwitch failed][%s][0x%x]"), current_switch_name, hr)); return hr; } is_optional_switch = false; } else if (IsOptionalSwitch(token)) { hr = StripOptionalSwitchNameFromArgv(token, &current_switch_name); if (FAILED(hr)) { return hr; } hr = AddOptionalSwitch(current_switch_name); if (FAILED(hr)) { CORE_LOG(LE, (_T("[AddOptionalSwitch failed][%s][0x%x]"), current_switch_name, hr)); return hr; } is_optional_switch = true; } else { hr = is_optional_switch ? AddOptionalSwitchArgument(current_switch_name, token) : AddSwitchArgument(current_switch_name, token); if (FAILED(hr)) { CORE_LOG(LE, (_T("[Adding switch argument failed][%d][%s][%s][0x%x]"), is_optional_switch, current_switch_name, token, hr)); return hr; } } } return S_OK; } bool CommandLineParser::IsSwitch(const CString& param) const { // Switches must have a prefix (/) or (-), and at least one character. if (param.GetLength() < 2) { return false; } // All switches must start with / or -, and not contain any spaces. // Since the argv parser strips out the enclosing quotes around an argument, // we need to handle the following cases properly: // * foo.exe /switch arg -- /switch is a switch, arg is an arg // * foo.exe /switch "/x y" -- /switch is a switch, '/x y' is an arg and it // will get here _without_ the quotes. // If param_str starts with / and contains no spaces, then it's a switch. return ((param[0] == _T('/')) || (param[0] == _T('-'))) && (param.Find(_T(" ")) == -1) && (param.Find(_T("%20")) == -1); } bool CommandLineParser::IsOptionalSwitch(const CString& param) const { // Optional switches must have a prefix ([/) or ([-), and at least one // character. return param[0] == _T('[') && IsSwitch(param.Right(param.GetLength() - 1)); } HRESULT CommandLineParser::StripSwitchNameFromArgv(const CString& param, CString* switch_name) { ASSERT1(switch_name); if (!IsSwitch(param)) { return E_INVALIDARG; } *switch_name = param.Right(param.GetLength() - 1); switch_name->Trim(_T(" ")); switch_name->MakeLower(); return S_OK; } HRESULT CommandLineParser::StripOptionalSwitchNameFromArgv(const CString& param, CString* name) { ASSERT1(name); if (!IsOptionalSwitch(param)) { return E_INVALIDARG; } return StripSwitchNameFromArgv(param.Right(param.GetLength() - 1), name); } void CommandLineParser::Reset() { required_args_.Reset(); optional_args_.Reset(); } HRESULT CommandLineParser::AddSwitch(const CString& switch_name) { ASSERT1(switch_name == CString(switch_name).MakeLower()); return required_args_.AddSwitch(switch_name); } HRESULT CommandLineParser::AddSwitchArgument(const CString& switch_name, const CString& argument_value) { ASSERT1(switch_name == CString(switch_name).MakeLower()); return required_args_.AddSwitchArgument(switch_name, argument_value); } int CommandLineParser::GetSwitchCount() const { return required_args_.GetSwitchCount(); } bool CommandLineParser::HasSwitch(const CString& switch_name) const { return required_args_.HasSwitch(switch_name); } // The value at a particular index may change if switch_names are added // since we're using a map underneath. But this keeps us from having to write // an interator and expose it externally. HRESULT CommandLineParser::GetSwitchNameAtIndex(int index, CString* switch_name) const { return required_args_.GetSwitchNameAtIndex(index, switch_name); } HRESULT CommandLineParser::GetSwitchArgumentCount(const CString& switch_name, int* count) const { return required_args_.GetSwitchArgumentCount(switch_name, count); } HRESULT CommandLineParser::GetSwitchArgumentValue( const CString& switch_name, int argument_index, CString* argument_value) const { return required_args_.GetSwitchArgumentValue(switch_name, argument_index, argument_value); } HRESULT CommandLineParser::AddOptionalSwitch(const CString& switch_name) { ASSERT1(switch_name == CString(switch_name).MakeLower()); return optional_args_.AddSwitch(switch_name); } HRESULT CommandLineParser::AddOptionalSwitchArgument(const CString& switch_name, const CString& value) { ASSERT1(switch_name == CString(switch_name).MakeLower()); return optional_args_.AddSwitchArgument(switch_name, value); } int CommandLineParser::GetOptionalSwitchCount() const { return optional_args_.GetSwitchCount(); } bool CommandLineParser::HasOptionalSwitch(const CString& switch_name) const { return optional_args_.HasSwitch(switch_name); } // The value at a particular index may change if switch_names are added // since we're using a map underneath. But this keeps us from having to write // an interator and expose it externally. HRESULT CommandLineParser::GetOptionalSwitchNameAtIndex(int index, CString* name) const { return optional_args_.GetSwitchNameAtIndex(index, name); } HRESULT CommandLineParser::GetOptionalSwitchArgumentCount(const CString& name, int* count) const { return optional_args_.GetSwitchArgumentCount(name, count); } HRESULT CommandLineParser::GetOptionalSwitchArgumentValue(const CString& name, int argument_index, CString* val) const { return optional_args_.GetSwitchArgumentValue(name, argument_index, val); } } // namespace omaha
{'content_hash': '503ca43fc87a4d8178cc54a2b11a163e', 'timestamp': '', 'source': 'github', 'line_count': 354, 'max_line_length': 80, 'avg_line_length': 32.57344632768361, 'alnum_prop': 0.6390599254184373, 'repo_name': 'taxilian/omaha', 'id': '66e9d3fa6bed99af015749e8b1330c759c72bfed', 'size': '12373', 'binary': False, 'copies': '3', 'ref': 'refs/heads/master', 'path': 'goopdate/command_line_parser.cc', 'mode': '33188', 'license': 'apache-2.0', 'language': [{'name': 'Assembly', 'bytes': '1957'}, {'name': 'C', 'bytes': '2626743'}, {'name': 'C#', 'bytes': '2385'}, {'name': 'C++', 'bytes': '4634004'}, {'name': 'Python', 'bytes': '103638'}]}
const path = require('path') const existsSync = require('exists-sync') const httpProxy = require('http-proxy') const proxy = httpProxy.createProxyServer() function createDevelopmentProxy(app) { // add error handling to avoid https://github.com/nodejitsu/node-http-proxy/issues/527 proxy.on('error', require('./handleProxyError.js')) // eg /assets/* app.all(`${STATS.publicPath}*`, (req, res) => { // try to send the file from assets/* // if it doesn't exist, use the proxy instead const filename = path.join(__dirname, 'assets', path.basename(req.url)) if (existsSync(filename)) { return res.sendFile(filename) } return proxy.web(req, res, { target: 'http://localhost:8080' }) }) } module.exports = createDevelopmentProxy
{'content_hash': '36456f5820120397d0b62f03f0fa11bb', 'timestamp': '', 'source': 'github', 'line_count': 22, 'max_line_length': 88, 'avg_line_length': 34.77272727272727, 'alnum_prop': 0.6862745098039216, 'repo_name': 'dferber90/webapp-starter-pack', 'id': 'b30175a0e2c5a965b4ef2f08c353746a1a27b7b0', 'size': '765', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'modules/utils/createDevelopmentProxy.js', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'CSS', 'bytes': '2591'}, {'name': 'JavaScript', 'bytes': '92712'}]}
<?php namespace Integrated\Common\Channel\Exporter\Queue; /** * @author Jan Sanne Mulder <[email protected]> */ interface RequestSerializerInterface { /** * @param Request $data * * @return string */ public function serialize(Request $data); /** * @param string $data * * @return Request */ public function deserialize($data); }
{'content_hash': 'e1ac5697344436a5e1556ef219259148', 'timestamp': '', 'source': 'github', 'line_count': 25, 'max_line_length': 51, 'avg_line_length': 15.8, 'alnum_prop': 0.6050632911392405, 'repo_name': 'integratedfordevelopers/integrated', 'id': 'd05be5b615b237cf0de38ecb2f6fb2362c8b5ffe', 'size': '628', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'src/Common/Channel/Exporter/Queue/RequestSerializerInterface.php', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'CSS', 'bytes': '4803'}, {'name': 'HTML', 'bytes': '1438'}, {'name': 'JavaScript', 'bytes': '64697'}, {'name': 'PHP', 'bytes': '3152918'}, {'name': 'SCSS', 'bytes': '48270'}, {'name': 'Twig', 'bytes': '540896'}]}
ACCEPTED #### According to International Plant Names Index #### Published in null #### Original name null ### Remarks null
{'content_hash': '46d60a72238c32d606238c822de8be90', 'timestamp': '', 'source': 'github', 'line_count': 13, 'max_line_length': 31, 'avg_line_length': 9.692307692307692, 'alnum_prop': 0.7063492063492064, 'repo_name': 'mdoering/backbone', 'id': '7f94d476203038d68eb8eae90ddd687e0e9b8753', 'size': '175', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'life/Plantae/Magnoliophyta/Magnoliopsida/Gentianales/Apocynaceae/Plumeria/Plumeria stenophylla/README.md', 'mode': '33188', 'license': 'apache-2.0', 'language': []}
var SecretHandshake = require('./secret_handshake'); describe("Secret Handshake", function() { it("1 is a wink", function() { var handshake = new SecretHandshake(1); expect(handshake.commands()).toEqual(["wink"]); }); xit("10 is a double blink", function() { var handshake = new SecretHandshake(2); expect(handshake.commands()).toEqual(["double blink"]); }); xit("100 is close your eyes", function() { var handshake = new SecretHandshake(4); expect(handshake.commands()).toEqual(["close your eyes"]); }); xit("1000 is jump", function() { var handshake = new SecretHandshake(8); expect(handshake.commands()).toEqual(["jump"]); }); xit("11 is wink and double blink", function() { var handshake = new SecretHandshake(3); expect(handshake.commands()).toEqual(["wink","double blink"]); }); xit("10011 is double blink and wink", function() { var handshake = new SecretHandshake(19); expect(handshake.commands()).toEqual(["double blink","wink"]); }); xit("11111 is jump, close your eyes, double blink, and wink", function() { var handshake = new SecretHandshake(31); expect(handshake.commands()).toEqual(["jump","close your eyes","double blink","wink"]); }); xit("text is an invalid secret handshake", function() { expect( function () { var handshake = new SecretHandshake("piggies"); }).toThrow(new Error("Handshake must be a number")); }); });
{'content_hash': '74dbebef1497961e89cb134722e3ef90', 'timestamp': '', 'source': 'github', 'line_count': 44, 'max_line_length': 91, 'avg_line_length': 32.93181818181818, 'alnum_prop': 0.6487232574189096, 'repo_name': 'nicgallardo/xjavascript', 'id': '37b4a27a56ba3a7c8dd004126a4a3f5fbce3e4d9', 'size': '1449', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'secret-handshake/secret_handshake_test.spec.js', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'JavaScript', 'bytes': '172436'}, {'name': 'Makefile', 'bytes': '1019'}, {'name': 'Shell', 'bytes': '640'}]}
<!-- Please leave this section at the top of the change log. Changes for the current release should go under the section titled "Current Release", and should adhere to the following format: ## Current Release * Overview of change #1 - Additional information about change #1 * Overview of change #2 - Additional information about change #2 - Additional information about change #2 * Overview of change #3 * Overview of change #4 - Additional information about change #4 ## YYYY.MM.DD - Version X.Y.Z (Previous Release) * Overview of change #1 - Additional information about change #1 --> ## Current Release ## Version 4.3.1 ## Version 4.3.0 * Fix for issue: https://github.com/Azure/azure-powershell/issues/4323 ## Version 4.2.1 ## Version 4.2.0 * Added support for user managed KeyVault key rotations in the Set-AzureRMDataLakeStoreAccount cmdlet * Added a quality of life update to automatically trigger an `enableKeyVault` call when a user managed KeyVault is added or a key is rotated. * Updated the token audience for job and catalog APIs to use the correct Data Lake specific audience instead of the Azure Resource audience. * Fixed a bug limiting the size of files created/appended using the following cmdlets: - New-AzureRmDataLakeStoreItem - Add-AzureRmDataLakeStoreItemContent ## Version 4.1.0 * Enable-AzureRmDataLakeStoreKeyVault (Enable-AdlStoreKeyVault) * Enable KeyVault managed encryption for a DataLake Store ## Version 4.0.1 ## Version 4.0.0 * For `Import-AzureRMDataLakeStoreItem` and `Export-AzureRMDataLakeStoreItem` trace logging has been disabled by default to improve performance. If trace logging is desired please use the `-DiagnosticLogLevel` and `-DiagnosticLogPath` parameters * Fixed a bug that would sometimes cause PowerShell to crash when uploading lots of small file to ADLS. ## Version 3.6.0 * Add support for head and tail to the `Get-AzureRMDataLakeStoreItemContent` cmdlet. This enables returning the top N or last N new line delimited rows to be displayed. ## Version 3.5.0 ## Version 3.4.0 * Update Upload and Download commands to use the new and improved Upload/Download helpers in the new DataLake.Store clients. This also gives better diagnostic logging, if enabled. * Default thread counts for Upload and download are now computed on a best effort basis based on the data being uploaded or downloaded. This should allow for good performance without specifying a thread count. * Update to Set-AzureRMDataLakeStoreAccount to allow for enabling and disabling Azure originating IPs through the firewall * Add warnings to Add and Set-AzureRMDataLakeStoreFirewallRule and AzureRMDataLakeStoreTrustedIdProvider if they are disabled * Remove explicit restrictions on resource locations. If Data Lake Store is not supported in a region, we will surface an error from the service. ## Version 3.3.0 * Updated help for all cmdlets to include output as well as more descriptions of parameters and the inclusion of aliases. * Update New-AdlStore and Set-AdlStore to support commitment tier options for the service. * Added OutputType mismatch warnings to all cmdlets with incorrect OutputType attributes. These will be fixed in a future breaking change release. * Add Diagnostic logging support to Import-AdlStoreItem and Export-AdlStoreItem. This can be enabled through the following parameters: * -Debug, enables full diagnostic logging as well as debug logging to the PowerShell console. Most verbose options * -DiagnosticLogLevel, allows finer control of the output than debug. If used with debug, this is ignored and debug logging is used. * -DiagnosticLogPath, optionally specify the file to write diagnostic logs to. By default it is written to a file under %LOCALAPPDATA%\AdlDataTransfer * Added support to New-AdlStore to explicitly opt-out of account encryption. To do so, create the account with the -DisableEncryption flag. ## Version 3.2.0 * Introduction of deprecation warning for nested properties for all ARM resources. Nested properties will be removed in a future release and all properties will be moved one level up. * Removed the ability to set encryption in Set-AzureRMDataLakeStoreAccount (never was supported) * Added ability to enable/disable firewall rules and the trusted id providers during Set-AzureRMDataLakeStoreAccount * Added a new cmdlet: Set-AzureRMDataLakeStoreItemExpiry, which allows the user to set or remove the expiration for files (not folders) in their ADLS account. * Small fix for friendly date properties to pivot off UTC time instead of local time, ensuring standard time reporting. ## Version 3.1.0 * Improvements to import and export data cmdlets - Drastically increased performance for distributed download scenarios, where multiple sessions are running across many clients targeting the same ADLS account. - Better error handling and messaging for both upload and download scenarios. * Full Firewall rules management CRUD - The below cmdlets can be used to manage firewall rules for an ADLS account: - Add-AzureRMDataLakeStoreFirewallRule - Set-AzureRMDataLakeStoreFirewallRule - Get-AzureRMDataLakeStoreFirewallRule - Remove-AzureRMDataLakeStoreFirewallRule * Full Trusted ID provider management CRUD - The below cmdlets can be used to manage trusted identity providers for an ADLS account: - Add-AzureRMDataLakeStoreTrustedIdProvider - Set-AzureRMDataLakeStoreTrustedIdProvider - Get-AzureRMDataLakeStoreTrustedIdProvider - Remove-AzureRMDataLakeStoreTrustedIdProvider * Account Encryption Support - You can now encrypt newly created ADLS accounts as well as enable encryption on existing ADLS accounts using the New-AzureRMDataLakeStoreAccount and Set-AzureRMDataLakeStoreAccount cmdlets, respectively.
{'content_hash': '0a066b9b9ec7b8b29a51870d4e0209f8', 'timestamp': '', 'source': 'github', 'line_count': 93, 'max_line_length': 245, 'avg_line_length': 62.924731182795696, 'alnum_prop': 0.7886192754613808, 'repo_name': 'hungmai-msft/azure-powershell', 'id': '96b0ac4b9ca2dda18fc7669a13354a4628dd2fb3', 'size': '5854', 'binary': False, 'copies': '2', 'ref': 'refs/heads/preview', 'path': 'src/ResourceManager/DataLakeStore/ChangeLog.md', 'mode': '33188', 'license': 'apache-2.0', 'language': [{'name': 'Batchfile', 'bytes': '16509'}, {'name': 'C#', 'bytes': '39328004'}, {'name': 'HTML', 'bytes': '209'}, {'name': 'JavaScript', 'bytes': '4979'}, {'name': 'PHP', 'bytes': '41'}, {'name': 'PowerShell', 'bytes': '3983165'}, {'name': 'Ruby', 'bytes': '265'}, {'name': 'Shell', 'bytes': '50'}, {'name': 'XSLT', 'bytes': '6114'}]}
/** * \file * \brief Implementation of the necessary initialization for the RadauII-A solver * * \author Nicholas Curtis * \date 03/09/2015 * */ #ifdef GENERATE_DOCS namespace radau2a { #endif void initialize_solver() { } /*! \fn char* solver_name() \brief Returns a descriptive solver name */ const char* solver_name() { const char* name = "radau2a-int"; return name; } void cleanup_solver() { //nothing to do } void init_solver_log() { } void solver_log() { } #ifdef GENERATE_DOCS } #endif
{'content_hash': '3a3425e943cf2b7a5e70198f55b8c6b8', 'timestamp': '', 'source': 'github', 'line_count': 40, 'max_line_length': 81, 'avg_line_length': 13.225, 'alnum_prop': 0.6483931947069943, 'repo_name': 'SLACKHA/accelerInt', 'id': '24ada842cfa2172e3141dbf1e75da8e1ed93cb80', 'size': '529', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'radau2a/radau2a_init.c', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'C', 'bytes': '144786'}, {'name': 'C++', 'bytes': '16646'}, {'name': 'Cuda', 'bytes': '183418'}, {'name': 'Python', 'bytes': '80505'}, {'name': 'Shell', 'bytes': '3317'}]}
var fork = require("child_process").fork; var path = require("path"); var bin = "./node_modules/.bin/istanbul"; var cov = "cover --report=lcov --dir=test/coverage/js _mocha --".split(" "); if (process.platform === 'win32') { bin = "./node_modules/mocha/bin/mocha"; cov = []; } var args = cov.concat([ "test/runner", "test/tests", "--expose-gc", "--timeout", "15000" ]); if (!process.env.APPVEYOR && !process.env.TRAVIS) { var local = path.join.bind(path, __dirname); var dummyPath = local("home"); process.env.HOME = dummyPath; process.env.USERPROFILE = dummyPath; } fork(bin, args, { cwd: path.join(__dirname, "../") }).on("close", process.exit);
{'content_hash': 'b90dc19d2f75e8fc7ca8f44b6b31a228', 'timestamp': '', 'source': 'github', 'line_count': 27, 'max_line_length': 80, 'avg_line_length': 25.0, 'alnum_prop': 0.6207407407407407, 'repo_name': 'jdgarcia/nodegit', 'id': '52cbff50ef10cbcd44564023d9eec225aab528d8', 'size': '675', 'binary': False, 'copies': '2', 'ref': 'refs/heads/master', 'path': 'test/index.js', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'C', 'bytes': '1789'}, {'name': 'C++', 'bytes': '128326'}, {'name': 'JavaScript', 'bytes': '439349'}, {'name': 'Python', 'bytes': '2142'}, {'name': 'Shell', 'bytes': '864'}]}
/* * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.addthis.hydra.data.query.engine; import java.util.concurrent.ScheduledExecutorService; import java.util.concurrent.ScheduledThreadPoolExecutor; import java.util.concurrent.TimeUnit; import com.addthis.basis.util.Parameter; import com.google.common.base.Objects; import com.google.common.cache.CacheBuilder; import com.google.common.cache.LoadingCache; import com.google.common.util.concurrent.MoreExecutors; import com.google.common.util.concurrent.ThreadFactoryBuilder; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * This class implements an LRU cache to keep our QueryEngines. It is instantiated only from MeshQuerySource. * <p/> * It uses guava's cache loader to do most of the work. We periodically check to see if new data is available for * a job, and if so, asynchronously prepare the new database before swapping it in. Multiple get or refresh attempts * will block and wait on the existing one to finish. * <p/> * As per guava's specs, it is not guaranteed that we will wait until we are at maximum capacity to evict engines. * Also, we are okay with evicting non-idle engines, but we do not force them to close. Rather, we set a flag and * trust the query using them to close it when it is finished. This means we may have a number of engines open equal * to the cache capacity + number of running queries. It is also possible for a few engines to be transiently open * while waiting for the eviction listener to close engines. This is somewhat balanced by guava's more aggressive * eviction policy, but in general we should not rely on the capacity as being an absolute hard max. In practice, it * should be more than sufficient though. * <p/> * Basic flow is : * Constructed from MQSource * MQSource calls getAndLease() * See if we have a suitable engine * If so, return it, if not, make one and return it */ public class QueryEngineCache { private static final Logger log = LoggerFactory.getLogger(QueryEngineCache.class); /** * 'soft cap' on the number of engines to have open. this + concurrent queries +/- a few should closely * resemble the real cap on open engines */ private static final long DEFAULT_ENGINE_CACHE_SIZE = Parameter.longValue("queryEngineCache.engineCacheSize", 5); /** * seconds to let an engine be in cache before attempting to refresh it. Refreshing it means checking whether * or not the job has finished running and has a new data directory; it does not force the reopening of the same * directory. It is important to note that this scheduled refresh is not checked unless a get is called on it, * and that even if the refresh returns the old engine, it resets the fail timer. */ private static final long DEFAULT_REFRESH_INTERVAL = Parameter.longValue("queryEngineCache.refreshInterval", 2 * 60); /** * seconds in between cache malongenance runs. This helps query sources and jobs in lower throughput environments. * It does the guava api clean up method which handles any pending expiration events, and also attempts to provoke * refresh attempts on cached keys by calling get on them. The latter is more important for our purposes. Without it, * relatively idle engines would become stale or subject to undesired eviction by the fail longerval. 0 disables it. */ private static final long DEFAULT_MAINTENANCE_INTERVAL = Parameter.longValue("queryEngineCache.maintenanceInterval", 20 * 60); /** * seconds to let an engine be in cache after the most recent write. This is longended only for situations * where re-opening that engine is failing, and thus while the refresh is not occuring. it might appear that * an engine is alive and up to date and this attempts to limit that disparity if desired. Note that by failing, * we mean that the refresh method is throwing exceptions. */ private static final long DEFAULT_FAIL_INTERVAL = Parameter.longValue("queryEngineCache.failInterval", 70 * 60); /** * thread pool for cache maintenance runs. Should only need one thread. */ private final ScheduledExecutorService queryEngineCacheMaintainer = MoreExecutors .getExitingScheduledExecutorService(new ScheduledThreadPoolExecutor(1, new ThreadFactoryBuilder().setNameFormat("queryEngineCacheMaintainer=%d").build())); /** * The {@link LoadingCache} that provides the backing data structure for this class. * Acts like an intelligent semi-persistent Map that has logic for loading and reloading complex objects. */ protected final LoadingCache<String, QueryEngine> loadingEngineCache; private final long engineCacheSize; private final long refreshInterval; private final long failInterval; private final long maintenanceInterval; /** * Initialize a {@link LoadingCache} that is capable of loading and reloading * {@link QueryEngine}s. Reloads occur asynchronously to prevent blocking operations * during unrelated calls to the cache. When reload is called the current engine will be compared with the * newest available data directory. If the current engine is up to date it will be returned, otherwise a new * engine will be opened to replace the current engine with the latest available. * <p/> * On removal, we have a listener that will call closeWhenIdle on engines. It has a guard against removal events * generated by refreshes where we decide to keep the existing engine (no new job data is available). There is a * race condition where that test can be passed more than once so any clean up done there must be okay with that. * The race condition is such that the test will always be passed at least once, and never when the engine is still * available to new get calls. This meets our requirements. */ public QueryEngineCache() { this(DEFAULT_ENGINE_CACHE_SIZE, DEFAULT_REFRESH_INTERVAL, DEFAULT_FAIL_INTERVAL, DEFAULT_MAINTENANCE_INTERVAL); } public QueryEngineCache(long engineCacheSize, long refreshInterval, long failInterval, long maintenanceInterval) { this(engineCacheSize, refreshInterval, failInterval, maintenanceInterval, new EngineLoader()); } public QueryEngineCache(long engineCacheSize, long refreshInterval, long failInterval, long maintenanceInterval, EngineLoader engineLoader) { this.engineCacheSize = engineCacheSize; this.refreshInterval = refreshInterval; this.failInterval = failInterval; this.maintenanceInterval = maintenanceInterval; log.info("Initializing QueryEngineCache: {}", this); //using 'this' is just more efficient // no easy way around escaping 'this' here, but at least it is more obvious what is going on now loadingEngineCache = CacheBuilder.newBuilder() .maximumWeight(engineCacheSize * 100) .<String, QueryEngine>weigher( (dir, engine) -> (int) (100 * engine.getTree().getAdvancedSettings().cacheWeight())) .refreshAfterWrite(refreshInterval, TimeUnit.SECONDS) .expireAfterWrite(failInterval, TimeUnit.SECONDS) .removalListener(new EngineRemovalListener(this)) .build(engineLoader); //schedule maintenance runs maybeInitMaintenance(); } /** * schedules maintenance for the cache using the maintenanceInterval parameter. Values less than 1 * are treated as 'do not do maintenance'. Maintenance includes cache loader cleanUp() and an attempt * to trigger refreshes in relatively idle engines. This is done by the thread safe iterator from * the loading cache and performing getIfPresent calls on each entry. This will only trigger refreshes * if the refresh interval has passed, and avoids a potential race condition where doing refresh() could * end up re-loading an engine that was just evicted. This is important because in addition to being * incorrect cache behavior, refresh will block instead of being asynchronous while doing so -- possibly * leading to even more race conditions. * <p/> * since the thread safe iterator is weakly consistent, it is a good idea to configure the intervals so * that maintenance will be performed more than once before the fail interval occurs (if we do not desire * to evict and close 'relatively idle' engines). eg. maintenanceInterval * 2 < failInterval * <p/> * unfortunately, this somewhat confuses the eviction order heuristic because it considers these all to be * valid r/ws. This is one reason to keep this value relatively long. It is possible to optimize against this * somewhat, but probably at the cost of greatly increased complexity. It seems unlikely that it will have a * large impact if performed infrequently enough though, especially since the evictor is not a simple LRU. */ private void maybeInitMaintenance() { if (maintenanceInterval > 0) { queryEngineCacheMaintainer.scheduleAtFixedRate(() -> { loadingEngineCache.cleanUp(); loadingEngineCache.asMap().keySet().forEach(loadingEngineCache::getIfPresent); }, maintenanceInterval, maintenanceInterval, TimeUnit.SECONDS); } } /** * Takes an unresolved (usually the gold path) path to a bdb query directory. This is mostly a thin * layer between this class and the backing LoadingCache. * <p/> * Most importantly, it also attempts to lease the engine. This is because there is a rare race condition * where after acquiring the engine, but before leasing it ourselves, it is evicted from the cache. Probably * caused by refresh, since it is less likely that an engine we just acquired would be the target of size * eviction in most cases. It is relatively unlikely to happen even twice in a row, but we try three times * here anyway. I have never seen this exception but if we start to see it a lot, we can re-evaluate this approach. * * @param directoryPath The path of the engine directory * @return a QueryEngine from the cache or constructed on demand (constructing blocks this thread) * @throws Exception - any problem while getting the engine. Likely either an issue with leasing or with opening an engine */ public QueryEngine getAndLease(String directoryPath) throws Exception { for (int i = 0; i < 3; i++) { QueryEngine qe = loadingEngineCache.get(directoryPath); if (qe.lease()) { return qe; } } log.warn("Tried three times but unable to get lease for engine with path: {}", directoryPath); throw new RuntimeException("Can't lease engine"); } @Override public String toString() { return Objects.toStringHelper(this) .add("engineCacheSize", engineCacheSize) .add("refreshInterval", refreshInterval) .add("maintenanceInterval", maintenanceInterval) .add("failInterval", failInterval) .toString(); } }
{'content_hash': 'adc024dcbfaacae34001cd8e0682b7a5', 'timestamp': '', 'source': 'github', 'line_count': 212, 'max_line_length': 130, 'avg_line_length': 55.60849056603774, 'alnum_prop': 0.7211807617270337, 'repo_name': 'mythguided/hydra', 'id': '12e6ca02fa41c099d8300355623fa6ff8cc95be5', 'size': '11789', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'hydra-data/src/main/java/com/addthis/hydra/data/query/engine/QueryEngineCache.java', 'mode': '33188', 'license': 'apache-2.0', 'language': [{'name': 'CSS', 'bytes': '37939'}, {'name': 'HTML', 'bytes': '103283'}, {'name': 'Java', 'bytes': '4732762'}, {'name': 'JavaScript', 'bytes': '582863'}, {'name': 'Shell', 'bytes': '13923'}]}