code
stringlengths
3
1.05M
repo_name
stringlengths
4
116
path
stringlengths
4
991
language
stringclasses
9 values
license
stringclasses
15 values
size
int32
3
1.05M
package hudson.util; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; /** * Adds more to commons-io. * * @author Kohsuke Kawaguchi * @since 1.337 */ public class IOUtils extends org.apache.commons.io.IOUtils { public static void copy(File src, OutputStream out) throws IOException { FileInputStream in = new FileInputStream(src); try { copy(in,out); } finally { closeQuietly(in); } } public static void copy(InputStream in, File out) throws IOException { FileOutputStream fos = new FileOutputStream(out); try { copy(in,fos); } finally { closeQuietly(fos); } } /** * Ensures that the given directory exists (if not, it's created, including all the parent directories.) * * @return * This method returns the 'dir' parameter so that the method call flows better. */ public static File mkdirs(File dir) throws IOException { if(dir.mkdirs() || dir.exists()) return dir; // following Ant <mkdir> task to avoid possible race condition. try { Thread.sleep(10); } catch (InterruptedException e) { // ignore } if (dir.mkdirs() || dir.exists()) return dir; throw new IOException("Failed to create a directory at "+dir); } /** * Fully skips the specified size from the given input stream * @since 1.349 */ public static InputStream skip(InputStream in, long size) throws IOException { while (size>0) size -= in.skip(size); return in; } }
vivek/hudson
core/src/main/java/hudson/util/IOUtils.java
Java
mit
1,790
<?xml version="1.0" ?><!DOCTYPE TS><TS language="it" version="2.0"> <defaultcodec>UTF-8</defaultcodec> <context> <name>AboutDialog</name> <message> <location filename="../forms/aboutdialog.ui" line="+14"/> <source>About stripecoin</source> <translation>Info su stripecoin</translation> </message> <message> <location line="+39"/> <source>&lt;b&gt;stripecoin&lt;/b&gt; version</source> <translation>Versione di &lt;b&gt;stripecoin&lt;/b&gt;</translation> </message> <message> <location line="+57"/> <source> This is experimental software. Distributed under the MIT/X11 software license, see the accompanying file COPYING or http://www.opensource.org/licenses/mit-license.php. This product includes software developed by the OpenSSL Project for use in the OpenSSL Toolkit (http://www.openssl.org/) and cryptographic software written by Eric Young (eay@cryptsoft.com) and UPnP software written by Thomas Bernard.</source> <translation> Questo è un software sperimentale. Distribuito sotto la licenza software MIT/X11, vedi il file COPYING incluso oppure su http://www.opensource.org/licenses/mit-license.php. Questo prodotto include software sviluppato dal progetto OpenSSL per l&apos;uso del Toolkit OpenSSL (http://www.openssl.org/), software crittografico scritto da Eric Young (eay@cryptsoft.com) e software UPnP scritto da Thomas Bernard.</translation> </message> <message> <location filename="../aboutdialog.cpp" line="+14"/> <source>Copyright</source> <translation>Copyright</translation> </message> <message> <location line="+0"/> <source>The stripecoin developers</source> <translation>Sviluppatori di stripecoin</translation> </message> </context> <context> <name>AddressBookPage</name> <message> <location filename="../forms/addressbookpage.ui" line="+14"/> <source>Address Book</source> <translation>Rubrica</translation> </message> <message> <location line="+19"/> <source>Double-click to edit address or label</source> <translation>Fai doppio click per modificare o cancellare l&apos;etichetta</translation> </message> <message> <location line="+27"/> <source>Create a new address</source> <translation>Crea un nuovo indirizzo</translation> </message> <message> <location line="+14"/> <source>Copy the currently selected address to the system clipboard</source> <translation>Copia l&apos;indirizzo attualmente selezionato nella clipboard</translation> </message> <message> <location line="-11"/> <source>&amp;New Address</source> <translation>&amp;Nuovo indirizzo</translation> </message> <message> <location filename="../addressbookpage.cpp" line="+63"/> <source>These are your stripecoin 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>Questi sono i tuoi indirizzi stripecoin per ricevere pagamenti. Potrai darne uno diverso ad ognuno per tenere così traccia di chi ti sta pagando.</translation> </message> <message> <location filename="../forms/addressbookpage.ui" line="+14"/> <source>&amp;Copy Address</source> <translation>&amp;Copia l&apos;indirizzo</translation> </message> <message> <location line="+11"/> <source>Show &amp;QR Code</source> <translation>Mostra il codice &amp;QR</translation> </message> <message> <location line="+11"/> <source>Sign a message to prove you own a stripecoin address</source> <translation>Firma un messaggio per dimostrare di possedere questo indirizzo</translation> </message> <message> <location line="+3"/> <source>Sign &amp;Message</source> <translation>Firma il &amp;messaggio</translation> </message> <message> <location line="+25"/> <source>Delete the currently selected address from the list</source> <translation>Cancella l&apos;indirizzo attualmente selezionato dalla lista</translation> </message> <message> <location line="+27"/> <source>Export the data in the current tab to a file</source> <translation>Esporta i dati nella tabella corrente su un file</translation> </message> <message> <location line="+3"/> <source>&amp;Export</source> <translation>&amp;Esporta...</translation> </message> <message> <location line="-44"/> <source>Verify a message to ensure it was signed with a specified stripecoin address</source> <translation>Verifica un messaggio per accertarsi che sia firmato con un indirizzo stripecoin specifico</translation> </message> <message> <location line="+3"/> <source>&amp;Verify Message</source> <translation>&amp;Verifica Messaggio</translation> </message> <message> <location line="+14"/> <source>&amp;Delete</source> <translation>&amp;Cancella</translation> </message> <message> <location filename="../addressbookpage.cpp" line="-5"/> <source>These are your stripecoin addresses for sending payments. Always check the amount and the receiving address before sending coins.</source> <translation type="unfinished"/> </message> <message> <location line="+13"/> <source>Copy &amp;Label</source> <translation>Copia &amp;l&apos;etichetta</translation> </message> <message> <location line="+1"/> <source>&amp;Edit</source> <translation>&amp;Modifica</translation> </message> <message> <location line="+1"/> <source>Send &amp;Coins</source> <translation>Invia &amp;stripecoin</translation> </message> <message> <location line="+260"/> <source>Export Address Book Data</source> <translation>Esporta gli indirizzi della rubrica</translation> </message> <message> <location line="+1"/> <source>Comma separated file (*.csv)</source> <translation>Testo CSV (*.csv)</translation> </message> <message> <location line="+13"/> <source>Error exporting</source> <translation>Errore nell&apos;esportazione</translation> </message> <message> <location line="+0"/> <source>Could not write to file %1.</source> <translation>Impossibile scrivere sul file %1.</translation> </message> </context> <context> <name>AddressTableModel</name> <message> <location filename="../addresstablemodel.cpp" line="+144"/> <source>Label</source> <translation>Etichetta</translation> </message> <message> <location line="+0"/> <source>Address</source> <translation>Indirizzo</translation> </message> <message> <location line="+36"/> <source>(no label)</source> <translation>(nessuna etichetta)</translation> </message> </context> <context> <name>AskPassphraseDialog</name> <message> <location filename="../forms/askpassphrasedialog.ui" line="+26"/> <source>Passphrase Dialog</source> <translation>Finestra passphrase</translation> </message> <message> <location line="+21"/> <source>Enter passphrase</source> <translation>Inserisci la passphrase</translation> </message> <message> <location line="+14"/> <source>New passphrase</source> <translation>Nuova passphrase</translation> </message> <message> <location line="+14"/> <source>Repeat new passphrase</source> <translation>Ripeti la passphrase</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>Inserisci la passphrase per il portamonete.&lt;br/&gt;Per piacere usare unapassphrase di &lt;b&gt;10 o più caratteri casuali&lt;/b&gt;, o &lt;b&gt;otto o più parole&lt;/b&gt;.</translation> </message> <message> <location line="+1"/> <source>Encrypt wallet</source> <translation>Cifra il portamonete</translation> </message> <message> <location line="+3"/> <source>This operation needs your wallet passphrase to unlock the wallet.</source> <translation>Quest&apos;operazione necessita della passphrase per sbloccare il portamonete.</translation> </message> <message> <location line="+5"/> <source>Unlock wallet</source> <translation>Sblocca il portamonete</translation> </message> <message> <location line="+3"/> <source>This operation needs your wallet passphrase to decrypt the wallet.</source> <translation>Quest&apos;operazione necessita della passphrase per decifrare il portamonete,</translation> </message> <message> <location line="+5"/> <source>Decrypt wallet</source> <translation>Decifra il portamonete</translation> </message> <message> <location line="+3"/> <source>Change passphrase</source> <translation>Cambia la passphrase</translation> </message> <message> <location line="+1"/> <source>Enter the old and new passphrase to the wallet.</source> <translation>Inserisci la vecchia e la nuova passphrase per il portamonete.</translation> </message> <message> <location line="+46"/> <source>Confirm wallet encryption</source> <translation>Conferma la cifratura del portamonete</translation> </message> <message> <location line="+1"/> <source>Warning: If you encrypt your wallet and lose your passphrase, you will &lt;b&gt;LOSE ALL OF YOUR LITECOINS&lt;/b&gt;!</source> <translation>Attenzione: se si cifra il portamonete e si perde la frase d&apos;ordine, &lt;b&gt;SI PERDERANNO TUTTI I PROPRI stripecoin&lt;/b&gt;!</translation> </message> <message> <location line="+0"/> <source>Are you sure you wish to encrypt your wallet?</source> <translation>Si è sicuri di voler cifrare il portamonete?</translation> </message> <message> <location line="+15"/> <source>IMPORTANT: Any previous backups you have made of your wallet file should be replaced with the newly generated, encrypted wallet file. For security reasons, previous backups of the unencrypted wallet file will become useless as soon as you start using the new, encrypted wallet.</source> <translation>IMPORTANTE: qualsiasi backup del portafoglio effettuato precedentemente dovrebbe essere sostituito con il file del portafoglio criptato appena generato. Per ragioni di sicurezza, i backup precedenti del file del portafoglio non criptato diventeranno inservibili non appena si inizi ad usare il nuovo portafoglio criptato.</translation> </message> <message> <location line="+100"/> <location line="+24"/> <source>Warning: The Caps Lock key is on!</source> <translation>Attenzione: tasto Blocco maiuscole attivo.</translation> </message> <message> <location line="-130"/> <location line="+58"/> <source>Wallet encrypted</source> <translation>Portamonete cifrato</translation> </message> <message> <location line="-56"/> <source>stripecoin will close now to finish the encryption process. Remember that encrypting your wallet cannot fully protect your litecoins from being stolen by malware infecting your computer.</source> <translation>stripecoin verrà ora chiuso per finire il processo di crittazione. Ricorda che criptare il tuo portamonete non può fornire una protezione totale contro furti causati da malware che dovessero infettare il tuo computer.</translation> </message> <message> <location line="+13"/> <location line="+7"/> <location line="+42"/> <location line="+6"/> <source>Wallet encryption failed</source> <translation>Cifratura del portamonete fallita</translation> </message> <message> <location line="-54"/> <source>Wallet encryption failed due to an internal error. Your wallet was not encrypted.</source> <translation>Cifratura del portamonete fallita a causa di un errore interno. Il portamonete non è stato cifrato.</translation> </message> <message> <location line="+7"/> <location line="+48"/> <source>The supplied passphrases do not match.</source> <translation>Le passphrase inserite non corrispondono.</translation> </message> <message> <location line="-37"/> <source>Wallet unlock failed</source> <translation>Sblocco del portamonete fallito</translation> </message> <message> <location line="+1"/> <location line="+11"/> <location line="+19"/> <source>The passphrase entered for the wallet decryption was incorrect.</source> <translation>La passphrase inserita per la decifrazione del portamonete è errata.</translation> </message> <message> <location line="-20"/> <source>Wallet decryption failed</source> <translation>Decifrazione del portamonete fallita</translation> </message> <message> <location line="+14"/> <source>Wallet passphrase was successfully changed.</source> <translation>Passphrase del portamonete modificata con successo.</translation> </message> </context> <context> <name>BitcoinGUI</name> <message> <location filename="../bitcoingui.cpp" line="+233"/> <source>Sign &amp;message...</source> <translation>Firma il &amp;messaggio...</translation> </message> <message> <location line="+280"/> <source>Synchronizing with network...</source> <translation>Sto sincronizzando con la rete...</translation> </message> <message> <location line="-349"/> <source>&amp;Overview</source> <translation>&amp;Sintesi</translation> </message> <message> <location line="+1"/> <source>Show general overview of wallet</source> <translation>Mostra lo stato generale del portamonete</translation> </message> <message> <location line="+20"/> <source>&amp;Transactions</source> <translation>&amp;Transazioni</translation> </message> <message> <location line="+1"/> <source>Browse transaction history</source> <translation>Cerca nelle transazioni</translation> </message> <message> <location line="+7"/> <source>Edit the list of stored addresses and labels</source> <translation>Modifica la lista degli indirizzi salvati e delle etichette</translation> </message> <message> <location line="-14"/> <source>Show the list of addresses for receiving payments</source> <translation>Mostra la lista di indirizzi su cui ricevere pagamenti</translation> </message> <message> <location line="+31"/> <source>E&amp;xit</source> <translation>&amp;Esci</translation> </message> <message> <location line="+1"/> <source>Quit application</source> <translation>Chiudi applicazione</translation> </message> <message> <location line="+4"/> <source>Show information about stripecoin</source> <translation>Mostra informazioni su stripecoin</translation> </message> <message> <location line="+2"/> <source>About &amp;Qt</source> <translation>Informazioni su &amp;Qt</translation> </message> <message> <location line="+1"/> <source>Show information about Qt</source> <translation>Mostra informazioni su Qt</translation> </message> <message> <location line="+2"/> <source>&amp;Options...</source> <translation>&amp;Opzioni...</translation> </message> <message> <location line="+6"/> <source>&amp;Encrypt Wallet...</source> <translation>&amp;Cifra il portamonete...</translation> </message> <message> <location line="+3"/> <source>&amp;Backup Wallet...</source> <translation>&amp;Backup Portamonete...</translation> </message> <message> <location line="+2"/> <source>&amp;Change Passphrase...</source> <translation>&amp;Cambia la passphrase...</translation> </message> <message> <location line="+285"/> <source>Importing blocks from disk...</source> <translation>Importa blocchi dal disco...</translation> </message> <message> <location line="+3"/> <source>Reindexing blocks on disk...</source> <translation>Re-indicizzazione blocchi su disco...</translation> </message> <message> <location line="-347"/> <source>Send coins to a stripecoin address</source> <translation>Invia monete ad un indirizzo stripecoin</translation> </message> <message> <location line="+49"/> <source>Modify configuration options for stripecoin</source> <translation>Modifica configurazione opzioni per stripecoin</translation> </message> <message> <location line="+9"/> <source>Backup wallet to another location</source> <translation>Backup portamonete in un&apos;altra locazione</translation> </message> <message> <location line="+2"/> <source>Change the passphrase used for wallet encryption</source> <translation>Cambia la passphrase per la cifratura del portamonete</translation> </message> <message> <location line="+6"/> <source>&amp;Debug window</source> <translation>Finestra &amp;Debug</translation> </message> <message> <location line="+1"/> <source>Open debugging and diagnostic console</source> <translation>Apri la console di degugging e diagnostica</translation> </message> <message> <location line="-4"/> <source>&amp;Verify message...</source> <translation>&amp;Verifica messaggio...</translation> </message> <message> <location line="-165"/> <location line="+530"/> <source>stripecoin</source> <translation>stripecoin</translation> </message> <message> <location line="-530"/> <source>Wallet</source> <translation>Portamonete</translation> </message> <message> <location line="+101"/> <source>&amp;Send</source> <translation>&amp;Spedisci</translation> </message> <message> <location line="+7"/> <source>&amp;Receive</source> <translation>&amp;Ricevi</translation> </message> <message> <location line="+14"/> <source>&amp;Addresses</source> <translation>&amp;Indirizzi</translation> </message> <message> <location line="+22"/> <source>&amp;About stripecoin</source> <translation>&amp;Info su stripecoin</translation> </message> <message> <location line="+9"/> <source>&amp;Show / Hide</source> <translation>&amp;Mostra/Nascondi</translation> </message> <message> <location line="+1"/> <source>Show or hide the main Window</source> <translation>Mostra o nascondi la Finestra principale</translation> </message> <message> <location line="+3"/> <source>Encrypt the private keys that belong to your wallet</source> <translation>Crittografa le chiavi private che appartengono al tuo portafoglio</translation> </message> <message> <location line="+7"/> <source>Sign messages with your stripecoin addresses to prove you own them</source> <translation>Firma i messaggi con il tuo indirizzo stripecoin per dimostrare di possederli</translation> </message> <message> <location line="+2"/> <source>Verify messages to ensure they were signed with specified stripecoin addresses</source> <translation>Verifica i messaggi per accertarsi che siano stati firmati con gli indirizzi stripecoin specificati</translation> </message> <message> <location line="+28"/> <source>&amp;File</source> <translation>&amp;File</translation> </message> <message> <location line="+7"/> <source>&amp;Settings</source> <translation>&amp;Impostazioni</translation> </message> <message> <location line="+6"/> <source>&amp;Help</source> <translation>&amp;Aiuto</translation> </message> <message> <location line="+9"/> <source>Tabs toolbar</source> <translation>Barra degli strumenti &quot;Tabs&quot;</translation> </message> <message> <location line="+17"/> <location line="+10"/> <source>[testnet]</source> <translation>[testnet]</translation> </message> <message> <location line="+47"/> <source>stripecoin client</source> <translation>stripecoin client</translation> </message> <message numerus="yes"> <location line="+141"/> <source>%n active connection(s) to stripecoin network</source> <translation><numerusform>%n connessione attiva alla rete stripecoin</numerusform><numerusform>%n connessioni attive alla rete stripecoin</numerusform></translation> </message> <message> <location line="+22"/> <source>No block source available...</source> <translation type="unfinished"/> </message> <message> <location line="+12"/> <source>Processed %1 of %2 (estimated) blocks of transaction history.</source> <translation>Processati %1 di %2 (circa) blocchi della cronologia transazioni.</translation> </message> <message> <location line="+4"/> <source>Processed %1 blocks of transaction history.</source> <translation>Processati %1 blocchi della cronologia transazioni.</translation> </message> <message numerus="yes"> <location line="+20"/> <source>%n hour(s)</source> <translation><numerusform>%n ora</numerusform><numerusform>%n ore</numerusform></translation> </message> <message numerus="yes"> <location line="+4"/> <source>%n day(s)</source> <translation><numerusform>%n giorno</numerusform><numerusform>%n giorni</numerusform></translation> </message> <message numerus="yes"> <location line="+4"/> <source>%n week(s)</source> <translation><numerusform>%n settimana</numerusform><numerusform>%n settimane</numerusform></translation> </message> <message> <location line="+4"/> <source>%1 behind</source> <translation type="unfinished"/> </message> <message> <location line="+14"/> <source>Last received block was generated %1 ago.</source> <translation>L&apos;ultimo blocco ricevuto è stato generato %1 fa.</translation> </message> <message> <location line="+2"/> <source>Transactions after this will not yet be visible.</source> <translation type="unfinished"/> </message> <message> <location line="+22"/> <source>Error</source> <translation>Errore</translation> </message> <message> <location line="+3"/> <source>Warning</source> <translation>Attenzione</translation> </message> <message> <location line="+3"/> <source>Information</source> <translation>Informazione</translation> </message> <message> <location line="+70"/> <source>This transaction is over the size limit. You can still send it for a fee of %1, which goes to the nodes that process your transaction and helps to support the network. Do you want to pay the fee?</source> <translation>Questa transazione è superiore al limite di dimensione. È comunque possibile inviarla con una commissione di %1, che va ai nodi che processano la tua transazione e contribuisce a sostenere la rete. Vuoi pagare la commissione?</translation> </message> <message> <location line="-140"/> <source>Up to date</source> <translation>Aggiornato</translation> </message> <message> <location line="+31"/> <source>Catching up...</source> <translation>In aggiornamento...</translation> </message> <message> <location line="+113"/> <source>Confirm transaction fee</source> <translation>Conferma compenso transazione</translation> </message> <message> <location line="+8"/> <source>Sent transaction</source> <translation>Transazione inviata</translation> </message> <message> <location line="+0"/> <source>Incoming transaction</source> <translation>Transazione ricevuta</translation> </message> <message> <location line="+1"/> <source>Date: %1 Amount: %2 Type: %3 Address: %4 </source> <translation>Data: %1 Quantità: %2 Tipo: %3 Indirizzo: %4 </translation> </message> <message> <location line="+33"/> <location line="+23"/> <source>URI handling</source> <translation>Gestione URI</translation> </message> <message> <location line="-23"/> <location line="+23"/> <source>URI can not be parsed! This can be caused by an invalid stripecoin address or malformed URI parameters.</source> <translation>Impossibile interpretare l&apos;URI! Ciò può essere causato da un indirizzo stripecoin invalido o da parametri URI non corretti.</translation> </message> <message> <location line="+17"/> <source>Wallet is &lt;b&gt;encrypted&lt;/b&gt; and currently &lt;b&gt;unlocked&lt;/b&gt;</source> <translation>Il portamonete è &lt;b&gt;cifrato&lt;/b&gt; e attualmente &lt;b&gt;sbloccato&lt;/b&gt;</translation> </message> <message> <location line="+8"/> <source>Wallet is &lt;b&gt;encrypted&lt;/b&gt; and currently &lt;b&gt;locked&lt;/b&gt;</source> <translation>Il portamonete è &lt;b&gt;cifrato&lt;/b&gt; e attualmente &lt;b&gt;bloccato&lt;/b&gt;</translation> </message> <message> <location filename="../bitcoin.cpp" line="+111"/> <source>A fatal error occurred. stripecoin can no longer continue safely and will quit.</source> <translation>Riscontrato un errore irreversibile. stripecoin non può più continuare in sicurezza e verrà terminato.</translation> </message> </context> <context> <name>ClientModel</name> <message> <location filename="../clientmodel.cpp" line="+104"/> <source>Network Alert</source> <translation>Avviso di rete</translation> </message> </context> <context> <name>EditAddressDialog</name> <message> <location filename="../forms/editaddressdialog.ui" line="+14"/> <source>Edit Address</source> <translation>Modifica l&apos;indirizzo</translation> </message> <message> <location line="+11"/> <source>&amp;Label</source> <translation>&amp;Etichetta</translation> </message> <message> <location line="+10"/> <source>The label associated with this address book entry</source> <translation>L&apos;etichetta associata a questo indirizzo nella rubrica</translation> </message> <message> <location line="+7"/> <source>&amp;Address</source> <translation>&amp;Indirizzo</translation> </message> <message> <location line="+10"/> <source>The address associated with this address book entry. This can only be modified for sending addresses.</source> <translation>L&apos;indirizzo associato a questa voce della rubrica. Si può modificare solo negli indirizzi di spedizione.</translation> </message> <message> <location filename="../editaddressdialog.cpp" line="+21"/> <source>New receiving address</source> <translation>Nuovo indirizzo di ricezione</translation> </message> <message> <location line="+4"/> <source>New sending address</source> <translation>Nuovo indirizzo d&apos;invio</translation> </message> <message> <location line="+3"/> <source>Edit receiving address</source> <translation>Modifica indirizzo di ricezione</translation> </message> <message> <location line="+4"/> <source>Edit sending address</source> <translation>Modifica indirizzo d&apos;invio</translation> </message> <message> <location line="+76"/> <source>The entered address &quot;%1&quot; is already in the address book.</source> <translation>L&apos;indirizzo inserito &quot;%1&quot; è già in rubrica.</translation> </message> <message> <location line="-5"/> <source>The entered address &quot;%1&quot; is not a valid stripecoin address.</source> <translation>L&apos;indirizzo inserito &quot;%1&quot; non è un indirizzo stripecoin valido.</translation> </message> <message> <location line="+10"/> <source>Could not unlock wallet.</source> <translation>Impossibile sbloccare il portamonete.</translation> </message> <message> <location line="+5"/> <source>New key generation failed.</source> <translation>Generazione della nuova chiave non riuscita.</translation> </message> </context> <context> <name>GUIUtil::HelpMessageBox</name> <message> <location filename="../guiutil.cpp" line="+424"/> <location line="+12"/> <source>stripecoin-Qt</source> <translation>stripecoin-Qt</translation> </message> <message> <location line="-12"/> <source>version</source> <translation>versione</translation> </message> <message> <location line="+2"/> <source>Usage:</source> <translation>Utilizzo:</translation> </message> <message> <location line="+1"/> <source>command-line options</source> <translation>opzioni riga di comando</translation> </message> <message> <location line="+4"/> <source>UI options</source> <translation>UI opzioni</translation> </message> <message> <location line="+1"/> <source>Set language, for example &quot;de_DE&quot; (default: system locale)</source> <translation>Imposta lingua, ad esempio &quot;it_IT&quot; (predefinita: lingua di sistema)</translation> </message> <message> <location line="+1"/> <source>Start minimized</source> <translation>Parti in icona </translation> </message> <message> <location line="+1"/> <source>Show splash screen on startup (default: 1)</source> <translation>Mostra finestra di presentazione all&apos;avvio (default: 1)</translation> </message> </context> <context> <name>OptionsDialog</name> <message> <location filename="../forms/optionsdialog.ui" line="+14"/> <source>Options</source> <translation>Opzioni</translation> </message> <message> <location line="+16"/> <source>&amp;Main</source> <translation>&amp;Principale</translation> </message> <message> <location line="+6"/> <source>Optional transaction fee per kB that helps make sure your transactions are processed quickly. Most transactions are 1 kB.</source> <translation type="unfinished"/> </message> <message> <location line="+15"/> <source>Pay transaction &amp;fee</source> <translation>Paga la &amp;commissione</translation> </message> <message> <location line="+31"/> <source>Automatically start stripecoin after logging in to the system.</source> <translation>Avvia automaticamente stripecoin all&apos;accensione del computer</translation> </message> <message> <location line="+3"/> <source>&amp;Start stripecoin on system login</source> <translation>&amp;Fai partire stripecoin all&apos;avvio del sistema</translation> </message> <message> <location line="+35"/> <source>Reset all client options to default.</source> <translation>Ripristina tutte le opzioni del client alle predefinite.</translation> </message> <message> <location line="+3"/> <source>&amp;Reset Options</source> <translation>&amp;Ripristina Opzioni</translation> </message> <message> <location line="+13"/> <source>&amp;Network</source> <translation>Rete</translation> </message> <message> <location line="+6"/> <source>Automatically open the stripecoin client port on the router. This only works when your router supports UPnP and it is enabled.</source> <translation>Apri automaticamente la porta del client stripecoin sul router. Questo funziona solo se il router supporta UPnP ed è abilitato.</translation> </message> <message> <location line="+3"/> <source>Map port using &amp;UPnP</source> <translation>Mappa le porte tramite l&apos;&amp;UPnP</translation> </message> <message> <location line="+7"/> <source>Connect to the stripecoin network through a SOCKS proxy (e.g. when connecting through Tor).</source> <translation>Connettiti alla rete Bitcon attraverso un proxy SOCKS (ad esempio quando ci si collega via Tor)</translation> </message> <message> <location line="+3"/> <source>&amp;Connect through SOCKS proxy:</source> <translation>&amp;Collegati tramite SOCKS proxy:</translation> </message> <message> <location line="+9"/> <source>Proxy &amp;IP:</source> <translation>&amp;IP del proxy:</translation> </message> <message> <location line="+19"/> <source>IP address of the proxy (e.g. 127.0.0.1)</source> <translation>Indirizzo IP del proxy (ad esempio 127.0.0.1)</translation> </message> <message> <location line="+7"/> <source>&amp;Port:</source> <translation>&amp;Porta:</translation> </message> <message> <location line="+19"/> <source>Port of the proxy (e.g. 9050)</source> <translation>Porta del proxy (es. 9050)</translation> </message> <message> <location line="+7"/> <source>SOCKS &amp;Version:</source> <translation>SOCKS &amp;Version:</translation> </message> <message> <location line="+13"/> <source>SOCKS version of the proxy (e.g. 5)</source> <translation>Versione SOCKS del proxy (es. 5)</translation> </message> <message> <location line="+36"/> <source>&amp;Window</source> <translation>&amp;Finestra</translation> </message> <message> <location line="+6"/> <source>Show only a tray icon after minimizing the window.</source> <translation>Mostra solo un&apos;icona nel tray quando si minimizza la finestra</translation> </message> <message> <location line="+3"/> <source>&amp;Minimize to the tray instead of the taskbar</source> <translation>&amp;Minimizza sul tray invece che sulla barra delle applicazioni</translation> </message> <message> <location line="+7"/> <source>Minimize instead of exit the application when the window is closed. When this option is enabled, the application will be closed only after selecting Quit in the menu.</source> <translation>Riduci ad icona, invece di uscire dall&apos;applicazione quando la finestra viene chiusa. Quando questa opzione è attivata, l&apos;applicazione verrà chiusa solo dopo aver selezionato Esci nel menu.</translation> </message> <message> <location line="+3"/> <source>M&amp;inimize on close</source> <translation>M&amp;inimizza alla chiusura</translation> </message> <message> <location line="+21"/> <source>&amp;Display</source> <translation>&amp;Mostra</translation> </message> <message> <location line="+8"/> <source>User Interface &amp;language:</source> <translation>&amp;Lingua Interfaccia Utente:</translation> </message> <message> <location line="+13"/> <source>The user interface language can be set here. This setting will take effect after restarting stripecoin.</source> <translation>La lingua dell&apos;interfaccia utente può essere impostata qui. L&apos;impostazione avrà effetto dopo il riavvio di stripecoin.</translation> </message> <message> <location line="+11"/> <source>&amp;Unit to show amounts in:</source> <translation>&amp;Unità di misura degli importi in:</translation> </message> <message> <location line="+13"/> <source>Choose the default subdivision unit to show in the interface and when sending coins.</source> <translation>Scegli l&apos;unità di suddivisione di default per l&apos;interfaccia e per l&apos;invio di monete</translation> </message> <message> <location line="+9"/> <source>Whether to show stripecoin addresses in the transaction list or not.</source> <translation>Se mostrare l&apos;indirizzo stripecoin nella transazione o meno.</translation> </message> <message> <location line="+3"/> <source>&amp;Display addresses in transaction list</source> <translation>&amp;Mostra gli indirizzi nella lista delle transazioni</translation> </message> <message> <location line="+71"/> <source>&amp;OK</source> <translation>&amp;OK</translation> </message> <message> <location line="+7"/> <source>&amp;Cancel</source> <translation>&amp;Cancella</translation> </message> <message> <location line="+10"/> <source>&amp;Apply</source> <translation>&amp;Applica</translation> </message> <message> <location filename="../optionsdialog.cpp" line="+53"/> <source>default</source> <translation>default</translation> </message> <message> <location line="+130"/> <source>Confirm options reset</source> <translation>Conferma ripristino opzioni</translation> </message> <message> <location line="+1"/> <source>Some settings may require a client restart to take effect.</source> <translation>Alcune modifiche necessitano del riavvio del programma per essere salvate.</translation> </message> <message> <location line="+0"/> <source>Do you want to proceed?</source> <translation>Vuoi procedere?</translation> </message> <message> <location line="+42"/> <location line="+9"/> <source>Warning</source> <translation>Attenzione</translation> </message> <message> <location line="-9"/> <location line="+9"/> <source>This setting will take effect after restarting stripecoin.</source> <translation>L&apos;impostazione avrà effetto dopo il riavvio di stripecoin.</translation> </message> <message> <location line="+29"/> <source>The supplied proxy address is invalid.</source> <translation>L&apos;indirizzo proxy che hai fornito è invalido.</translation> </message> </context> <context> <name>OverviewPage</name> <message> <location filename="../forms/overviewpage.ui" line="+14"/> <source>Form</source> <translation>Modulo</translation> </message> <message> <location line="+50"/> <location line="+166"/> <source>The displayed information may be out of date. Your wallet automatically synchronizes with the stripecoin network after a connection is established, but this process has not completed yet.</source> <translation>Le informazioni visualizzate sono datate. Il tuo partafogli verrà sincronizzato automaticamente con il network stripecoin dopo che la connessione è stabilita, ma questo processo non può essere completato ora.</translation> </message> <message> <location line="-124"/> <source>Balance:</source> <translation>Saldo</translation> </message> <message> <location line="+29"/> <source>Unconfirmed:</source> <translation>Non confermato:</translation> </message> <message> <location line="-78"/> <source>Wallet</source> <translation>Portamonete</translation> </message> <message> <location line="+107"/> <source>Immature:</source> <translation>Immaturo:</translation> </message> <message> <location line="+13"/> <source>Mined balance that has not yet matured</source> <translation>Importo scavato che non è ancora maturato</translation> </message> <message> <location line="+46"/> <source>&lt;b&gt;Recent transactions&lt;/b&gt;</source> <translation>&lt;b&gt;Transazioni recenti&lt;/b&gt;</translation> </message> <message> <location line="-101"/> <source>Your current balance</source> <translation>Saldo attuale</translation> </message> <message> <location line="+29"/> <source>Total of transactions that have yet to be confirmed, and do not yet count toward the current balance</source> <translation>Totale delle transazioni in corso di conferma, che non sono ancora incluse nel saldo attuale</translation> </message> <message> <location filename="../overviewpage.cpp" line="+116"/> <location line="+1"/> <source>out of sync</source> <translation>fuori sincrono</translation> </message> </context> <context> <name>PaymentServer</name> <message> <location filename="../paymentserver.cpp" line="+107"/> <source>Cannot start stripecoin: click-to-pay handler</source> <translation type="unfinished"/> </message> </context> <context> <name>QRCodeDialog</name> <message> <location filename="../forms/qrcodedialog.ui" line="+14"/> <source>QR Code Dialog</source> <translation>Codice QR di dialogo</translation> </message> <message> <location line="+59"/> <source>Request Payment</source> <translation>Richiedi pagamento</translation> </message> <message> <location line="+56"/> <source>Amount:</source> <translation>Importo:</translation> </message> <message> <location line="-44"/> <source>Label:</source> <translation>Etichetta:</translation> </message> <message> <location line="+19"/> <source>Message:</source> <translation>Messaggio:</translation> </message> <message> <location line="+71"/> <source>&amp;Save As...</source> <translation>&amp;Salva come...</translation> </message> <message> <location filename="../qrcodedialog.cpp" line="+62"/> <source>Error encoding URI into QR Code.</source> <translation>Errore nella codifica URI nel codice QR</translation> </message> <message> <location line="+40"/> <source>The entered amount is invalid, please check.</source> <translation>L&apos;importo specificato non è valido, prego verificare.</translation> </message> <message> <location line="+23"/> <source>Resulting URI too long, try to reduce the text for label / message.</source> <translation>L&apos;URI risulta troppo lungo, prova a ridurre il testo nell&apos;etichetta / messaggio.</translation> </message> <message> <location line="+25"/> <source>Save QR Code</source> <translation>Salva codice QR</translation> </message> <message> <location line="+0"/> <source>PNG Images (*.png)</source> <translation>Immagini PNG (*.png)</translation> </message> </context> <context> <name>RPCConsole</name> <message> <location filename="../forms/rpcconsole.ui" line="+46"/> <source>Client name</source> <translation>Nome del client</translation> </message> <message> <location line="+10"/> <location line="+23"/> <location line="+26"/> <location line="+23"/> <location line="+23"/> <location line="+36"/> <location line="+53"/> <location line="+23"/> <location line="+23"/> <location filename="../rpcconsole.cpp" line="+339"/> <source>N/A</source> <translation>N/D</translation> </message> <message> <location line="-217"/> <source>Client version</source> <translation>Versione client</translation> </message> <message> <location line="-45"/> <source>&amp;Information</source> <translation>&amp;Informazione</translation> </message> <message> <location line="+68"/> <source>Using OpenSSL version</source> <translation>Versione OpenSSL in uso</translation> </message> <message> <location line="+49"/> <source>Startup time</source> <translation>Tempo di avvio</translation> </message> <message> <location line="+29"/> <source>Network</source> <translation>Rete</translation> </message> <message> <location line="+7"/> <source>Number of connections</source> <translation>Numero connessioni</translation> </message> <message> <location line="+23"/> <source>On testnet</source> <translation>Nel testnet</translation> </message> <message> <location line="+23"/> <source>Block chain</source> <translation>Block chain</translation> </message> <message> <location line="+7"/> <source>Current number of blocks</source> <translation>Numero attuale di blocchi</translation> </message> <message> <location line="+23"/> <source>Estimated total blocks</source> <translation>Numero totale stimato di blocchi</translation> </message> <message> <location line="+23"/> <source>Last block time</source> <translation>Ora dell blocco piu recente</translation> </message> <message> <location line="+52"/> <source>&amp;Open</source> <translation>&amp;Apri</translation> </message> <message> <location line="+16"/> <source>Command-line options</source> <translation>opzioni riga di comando</translation> </message> <message> <location line="+7"/> <source>Show the stripecoin-Qt help message to get a list with possible stripecoin command-line options.</source> <translation>Mostra il messaggio di aiuto di stripecoin-QT per avere la lista di tutte le opzioni della riga di comando di stripecoin.</translation> </message> <message> <location line="+3"/> <source>&amp;Show</source> <translation>&amp;Mostra</translation> </message> <message> <location line="+24"/> <source>&amp;Console</source> <translation>&amp;Console</translation> </message> <message> <location line="-260"/> <source>Build date</source> <translation>Data di creazione</translation> </message> <message> <location line="-104"/> <source>stripecoin - Debug window</source> <translation>stripecoin - Finestra debug</translation> </message> <message> <location line="+25"/> <source>stripecoin Core</source> <translation type="unfinished"/> </message> <message> <location line="+279"/> <source>Debug log file</source> <translation>File log del Debug</translation> </message> <message> <location line="+7"/> <source>Open the stripecoin debug log file from the current data directory. This can take a few seconds for large log files.</source> <translation>Apri il file di log del debug di stripecoin dalla cartella attuale. Può richiedere alcuni secondi per file di log grandi.</translation> </message> <message> <location line="+102"/> <source>Clear console</source> <translation>Svuota console</translation> </message> <message> <location filename="../rpcconsole.cpp" line="-30"/> <source>Welcome to the stripecoin RPC console.</source> <translation>Benvenuto nella console RPC di stripecoin</translation> </message> <message> <location line="+1"/> <source>Use up and down arrows to navigate history, and &lt;b&gt;Ctrl-L&lt;/b&gt; to clear screen.</source> <translation>Usa le frecce direzionali per navigare la cronologia, and &lt;b&gt;Ctrl-L&lt;/b&gt; per cancellarla.</translation> </message> <message> <location line="+1"/> <source>Type &lt;b&gt;help&lt;/b&gt; for an overview of available commands.</source> <translation>Scrivi &lt;b&gt;help&lt;/b&gt; per un riassunto dei comandi disponibili</translation> </message> </context> <context> <name>SendCoinsDialog</name> <message> <location filename="../forms/sendcoinsdialog.ui" line="+14"/> <location filename="../sendcoinsdialog.cpp" line="+124"/> <location line="+5"/> <location line="+5"/> <location line="+5"/> <location line="+6"/> <location line="+5"/> <location line="+5"/> <source>Send Coins</source> <translation>Spedisci stripecoin</translation> </message> <message> <location line="+50"/> <source>Send to multiple recipients at once</source> <translation>Spedisci a diversi beneficiari in una volta sola</translation> </message> <message> <location line="+3"/> <source>Add &amp;Recipient</source> <translation>&amp;Aggiungi beneficiario</translation> </message> <message> <location line="+20"/> <source>Remove all transaction fields</source> <translation>Rimuovi tutti i campi della transazione</translation> </message> <message> <location line="+3"/> <source>Clear &amp;All</source> <translation>Cancella &amp;tutto</translation> </message> <message> <location line="+22"/> <source>Balance:</source> <translation>Saldo:</translation> </message> <message> <location line="+10"/> <source>123.456 BTC</source> <translation>123,456 BTC</translation> </message> <message> <location line="+31"/> <source>Confirm the send action</source> <translation>Conferma la spedizione</translation> </message> <message> <location line="+3"/> <source>S&amp;end</source> <translation>&amp;Spedisci</translation> </message> <message> <location filename="../sendcoinsdialog.cpp" line="-59"/> <source>&lt;b&gt;%1&lt;/b&gt; to %2 (%3)</source> <translation>&lt;b&gt;%1&lt;/b&gt; to %2 (%3)</translation> </message> <message> <location line="+5"/> <source>Confirm send coins</source> <translation>Conferma la spedizione di stripecoin</translation> </message> <message> <location line="+1"/> <source>Are you sure you want to send %1?</source> <translation>Si è sicuri di voler spedire %1?</translation> </message> <message> <location line="+0"/> <source> and </source> <translation> e </translation> </message> <message> <location line="+23"/> <source>The recipient address is not valid, please recheck.</source> <translation>L&apos;indirizzo del beneficiario non è valido, per cortesia controlla.</translation> </message> <message> <location line="+5"/> <source>The amount to pay must be larger than 0.</source> <translation>L&apos;importo da pagare dev&apos;essere maggiore di 0.</translation> </message> <message> <location line="+5"/> <source>The amount exceeds your balance.</source> <translation>L&apos;importo è superiore al saldo attuale</translation> </message> <message> <location line="+5"/> <source>The total exceeds your balance when the %1 transaction fee is included.</source> <translation>Il totale è superiore al saldo attuale includendo la commissione %1.</translation> </message> <message> <location line="+6"/> <source>Duplicate address found, can only send to each address once per send operation.</source> <translation>Trovato un indirizzo doppio, si può spedire solo una volta a ciascun indirizzo in una singola operazione.</translation> </message> <message> <location line="+5"/> <source>Error: Transaction creation failed!</source> <translation>Errore: Creazione transazione fallita!</translation> </message> <message> <location line="+5"/> <source>Error: The transaction was rejected. This might happen if some of the coins in your wallet were already spent, such as if you used a copy of wallet.dat and coins were spent in the copy but not marked as spent here.</source> <translation>Errore: la transazione è stata rifiutata. Ciò accade se alcuni stripecoin nel portamonete sono stati già spesi, ad esempio se è stata usata una copia del file wallet.dat e i stripecoin sono stati spesi dalla copia ma non segnati come spesi qui.</translation> </message> </context> <context> <name>SendCoinsEntry</name> <message> <location filename="../forms/sendcoinsentry.ui" line="+14"/> <source>Form</source> <translation>Modulo</translation> </message> <message> <location line="+15"/> <source>A&amp;mount:</source> <translation>&amp;Importo:</translation> </message> <message> <location line="+13"/> <source>Pay &amp;To:</source> <translation>Paga &amp;a:</translation> </message> <message> <location line="+34"/> <source>The address to send the payment to (e.g. Ler4HNAEfwYhBmGXcFP2Po1NpRUEiK8km2)</source> <translation>L&apos;indirizzo del beneficiario a cui inviare il pagamento (ad esempio Ler4HNAEfwYhBmGXcFP2Po1NpRUEiK8km2)</translation> </message> <message> <location line="+60"/> <location filename="../sendcoinsentry.cpp" line="+26"/> <source>Enter a label for this address to add it to your address book</source> <translation>Inserisci un&apos;etichetta per questo indirizzo, per aggiungerlo nella rubrica</translation> </message> <message> <location line="-78"/> <source>&amp;Label:</source> <translation>&amp;Etichetta</translation> </message> <message> <location line="+28"/> <source>Choose address from address book</source> <translation>Scegli l&apos;indirizzo dalla rubrica</translation> </message> <message> <location line="+10"/> <source>Alt+A</source> <translation>Alt+A</translation> </message> <message> <location line="+7"/> <source>Paste address from clipboard</source> <translation>Incollare l&apos;indirizzo dagli appunti</translation> </message> <message> <location line="+10"/> <source>Alt+P</source> <translation>Alt+P</translation> </message> <message> <location line="+7"/> <source>Remove this recipient</source> <translation>Rimuovere questo beneficiario</translation> </message> <message> <location filename="../sendcoinsentry.cpp" line="+1"/> <source>Enter a stripecoin address (e.g. Ler4HNAEfwYhBmGXcFP2Po1NpRUEiK8km2)</source> <translation>Inserisci un indirizzo stripecoin (ad esempio Ler4HNAEfwYhBmGXcFP2Po1NpRUEiK8km2)</translation> </message> </context> <context> <name>SignVerifyMessageDialog</name> <message> <location filename="../forms/signverifymessagedialog.ui" line="+14"/> <source>Signatures - Sign / Verify a Message</source> <translation>Firme - Firma / Verifica un messaggio</translation> </message> <message> <location line="+13"/> <source>&amp;Sign Message</source> <translation>&amp;Firma il messaggio</translation> </message> <message> <location line="+6"/> <source>You can sign messages with your addresses to prove you own them. Be careful not to sign anything vague, as phishing attacks may try to trick you into signing your identity over to them. Only sign fully-detailed statements you agree to.</source> <translation>Puoi firmare messeggi con i tuoi indirizzi per dimostrare che sono tuoi. Fai attenzione a non firmare niente di vago, visto che gli attacchi di phishing potrebbero cercare di spingerti a mettere la tua firma su di loro. Firma solo dichiarazioni completamente dettagliate con cui sei d&apos;accordo.</translation> </message> <message> <location line="+18"/> <source>The address to sign the message with (e.g. Ler4HNAEfwYhBmGXcFP2Po1NpRUEiK8km2)</source> <translation>Inserisci un indirizzo stripecoin (ad esempio Ler4HNAEfwYhBmGXcFP2Po1NpRUEiK8km2)</translation> </message> <message> <location line="+10"/> <location line="+213"/> <source>Choose an address from the address book</source> <translation>Scegli l&apos;indirizzo dalla rubrica</translation> </message> <message> <location line="-203"/> <location line="+213"/> <source>Alt+A</source> <translation>Alt+A</translation> </message> <message> <location line="-203"/> <source>Paste address from clipboard</source> <translation>Incollare l&apos;indirizzo dagli appunti</translation> </message> <message> <location line="+10"/> <source>Alt+P</source> <translation>Alt+P</translation> </message> <message> <location line="+12"/> <source>Enter the message you want to sign here</source> <translation>Inserisci qui il messaggio che vuoi firmare</translation> </message> <message> <location line="+7"/> <source>Signature</source> <translation>Firma</translation> </message> <message> <location line="+27"/> <source>Copy the current signature to the system clipboard</source> <translation>Copia la firma corrente nella clipboard</translation> </message> <message> <location line="+21"/> <source>Sign the message to prove you own this stripecoin address</source> <translation>Firma un messaggio per dimostrare di possedere questo indirizzo</translation> </message> <message> <location line="+3"/> <source>Sign &amp;Message</source> <translation>Firma &amp;messaggio</translation> </message> <message> <location line="+14"/> <source>Reset all sign message fields</source> <translation>Reimposta tutti i campi della firma</translation> </message> <message> <location line="+3"/> <location line="+146"/> <source>Clear &amp;All</source> <translation>Cancella &amp;tutto</translation> </message> <message> <location line="-87"/> <source>&amp;Verify Message</source> <translation>&amp;Verifica Messaggio</translation> </message> <message> <location line="+6"/> <source>Enter the signing address, message (ensure you copy line breaks, spaces, tabs, etc. exactly) and signature below to verify the message. Be careful not to read more into the signature than what is in the signed message itself, to avoid being tricked by a man-in-the-middle attack.</source> <translation type="unfinished"/> </message> <message> <location line="+21"/> <source>The address the message was signed with (e.g. Ler4HNAEfwYhBmGXcFP2Po1NpRUEiK8km2)</source> <translation>Inserisci un indirizzo stripecoin (ad esempio Ler4HNAEfwYhBmGXcFP2Po1NpRUEiK8km2)</translation> </message> <message> <location line="+40"/> <source>Verify the message to ensure it was signed with the specified stripecoin address</source> <translation>Verifica il messaggio per assicurarsi che sia stato firmato con l&apos;indirizzo stripecoin specificato</translation> </message> <message> <location line="+3"/> <source>Verify &amp;Message</source> <translation>&amp;Verifica Messaggio</translation> </message> <message> <location line="+14"/> <source>Reset all verify message fields</source> <translation>Reimposta tutti i campi della verifica messaggio</translation> </message> <message> <location filename="../signverifymessagedialog.cpp" line="+27"/> <location line="+3"/> <source>Enter a stripecoin address (e.g. Ler4HNAEfwYhBmGXcFP2Po1NpRUEiK8km2)</source> <translation>Inserisci un indirizzo stripecoin (ad esempio Ler4HNAEfwYhBmGXcFP2Po1NpRUEiK8km2)</translation> </message> <message> <location line="-2"/> <source>Click &quot;Sign Message&quot; to generate signature</source> <translation>Clicca &quot;Firma il messaggio&quot; per ottenere la firma</translation> </message> <message> <location line="+3"/> <source>Enter stripecoin signature</source> <translation>Inserisci firma stripecoin</translation> </message> <message> <location line="+82"/> <location line="+81"/> <source>The entered address is invalid.</source> <translation>L&apos;indirizzo inserito non è valido.</translation> </message> <message> <location line="-81"/> <location line="+8"/> <location line="+73"/> <location line="+8"/> <source>Please check the address and try again.</source> <translation>Per favore controlla l&apos;indirizzo e prova ancora</translation> </message> <message> <location line="-81"/> <location line="+81"/> <source>The entered address does not refer to a key.</source> <translation>L&apos;indirizzo stripecoin inserito non è associato a nessuna chiave.</translation> </message> <message> <location line="-73"/> <source>Wallet unlock was cancelled.</source> <translation>Sblocco del portafoglio annullato.</translation> </message> <message> <location line="+8"/> <source>Private key for the entered address is not available.</source> <translation>La chiave privata per l&apos;indirizzo inserito non è disponibile.</translation> </message> <message> <location line="+12"/> <source>Message signing failed.</source> <translation>Firma messaggio fallita.</translation> </message> <message> <location line="+5"/> <source>Message signed.</source> <translation>Messaggio firmato.</translation> </message> <message> <location line="+59"/> <source>The signature could not be decoded.</source> <translation>Non è stato possibile decodificare la firma.</translation> </message> <message> <location line="+0"/> <location line="+13"/> <source>Please check the signature and try again.</source> <translation>Per favore controlla la firma e prova ancora.</translation> </message> <message> <location line="+0"/> <source>The signature did not match the message digest.</source> <translation>La firma non corrisponde al sunto del messaggio.</translation> </message> <message> <location line="+7"/> <source>Message verification failed.</source> <translation>Verifica messaggio fallita.</translation> </message> <message> <location line="+5"/> <source>Message verified.</source> <translation>Messaggio verificato.</translation> </message> </context> <context> <name>SplashScreen</name> <message> <location filename="../splashscreen.cpp" line="+22"/> <source>The stripecoin developers</source> <translation>Sviluppatori di stripecoin</translation> </message> <message> <location line="+1"/> <source>[testnet]</source> <translation>[testnet]</translation> </message> </context> <context> <name>TransactionDesc</name> <message> <location filename="../transactiondesc.cpp" line="+20"/> <source>Open until %1</source> <translation>Aperto fino a %1</translation> </message> <message> <location line="+6"/> <source>%1/offline</source> <translation>%1/offline</translation> </message> <message> <location line="+2"/> <source>%1/unconfirmed</source> <translation>%1/non confermato</translation> </message> <message> <location line="+2"/> <source>%1 confirmations</source> <translation>%1 conferme</translation> </message> <message> <location line="+18"/> <source>Status</source> <translation>Stato</translation> </message> <message numerus="yes"> <location line="+7"/> <source>, broadcast through %n node(s)</source> <translation><numerusform>, trasmesso attraverso %n nodo</numerusform><numerusform>, trasmesso attraverso %n nodi</numerusform></translation> </message> <message> <location line="+4"/> <source>Date</source> <translation>Data</translation> </message> <message> <location line="+7"/> <source>Source</source> <translation>Sorgente</translation> </message> <message> <location line="+0"/> <source>Generated</source> <translation>Generato</translation> </message> <message> <location line="+5"/> <location line="+17"/> <source>From</source> <translation>Da</translation> </message> <message> <location line="+1"/> <location line="+22"/> <location line="+58"/> <source>To</source> <translation>A</translation> </message> <message> <location line="-77"/> <location line="+2"/> <source>own address</source> <translation>proprio indirizzo</translation> </message> <message> <location line="-2"/> <source>label</source> <translation>etichetta</translation> </message> <message> <location line="+37"/> <location line="+12"/> <location line="+45"/> <location line="+17"/> <location line="+30"/> <source>Credit</source> <translation>Credito</translation> </message> <message numerus="yes"> <location line="-102"/> <source>matures in %n more block(s)</source> <translation><numerusform>matura in %n ulteriore blocco</numerusform><numerusform>matura in altri %n blocchi</numerusform></translation> </message> <message> <location line="+2"/> <source>not accepted</source> <translation>non accettate</translation> </message> <message> <location line="+44"/> <location line="+8"/> <location line="+15"/> <location line="+30"/> <source>Debit</source> <translation>Debito</translation> </message> <message> <location line="-39"/> <source>Transaction fee</source> <translation>Tranzakciós díj</translation> </message> <message> <location line="+16"/> <source>Net amount</source> <translation>Importo netto</translation> </message> <message> <location line="+6"/> <source>Message</source> <translation>Messaggio</translation> </message> <message> <location line="+2"/> <source>Comment</source> <translation>Commento</translation> </message> <message> <location line="+2"/> <source>Transaction ID</source> <translation>ID della transazione</translation> </message> <message> <location line="+3"/> <source>Generated coins must mature 120 blocks before they can be spent. When you generated this block, it was broadcast to the network to be added to the block chain. If it fails to get into the chain, its state will change to &quot;not accepted&quot; and it won&apos;t be spendable. This may occasionally happen if another node generates a block within a few seconds of yours.</source> <translation>Bisogna attendere 120 blocchi prima di spendere I stripecoin generati. Quando è stato generato questo blocco, è stato trasmesso alla rete per aggiungerlo alla catena di blocchi. Se non riesce a entrare nella catena, verrà modificato in &quot;non accettato&quot; e non sarà spendibile. Questo può accadere a volte, se un altro nodo genera un blocco entro pochi secondi del tuo.</translation> </message> <message> <location line="+7"/> <source>Debug information</source> <translation>Informazione di debug</translation> </message> <message> <location line="+8"/> <source>Transaction</source> <translation>Transazione</translation> </message> <message> <location line="+3"/> <source>Inputs</source> <translation>Input</translation> </message> <message> <location line="+23"/> <source>Amount</source> <translation>Importo</translation> </message> <message> <location line="+1"/> <source>true</source> <translation>vero</translation> </message> <message> <location line="+0"/> <source>false</source> <translation>falso</translation> </message> <message> <location line="-209"/> <source>, has not been successfully broadcast yet</source> <translation>, non è stato ancora trasmesso con successo</translation> </message> <message numerus="yes"> <location line="-35"/> <source>Open for %n more block(s)</source> <translation><numerusform>Aperto per %n altro blocco</numerusform><numerusform>Aperto per altri %n blocchi</numerusform></translation> </message> <message> <location line="+70"/> <source>unknown</source> <translation>sconosciuto</translation> </message> </context> <context> <name>TransactionDescDialog</name> <message> <location filename="../forms/transactiondescdialog.ui" line="+14"/> <source>Transaction details</source> <translation>Dettagli sulla transazione</translation> </message> <message> <location line="+6"/> <source>This pane shows a detailed description of the transaction</source> <translation>Questo pannello mostra una descrizione dettagliata della transazione</translation> </message> </context> <context> <name>TransactionTableModel</name> <message> <location filename="../transactiontablemodel.cpp" line="+225"/> <source>Date</source> <translation>Data</translation> </message> <message> <location line="+0"/> <source>Type</source> <translation>Tipo</translation> </message> <message> <location line="+0"/> <source>Address</source> <translation>Indirizzo</translation> </message> <message> <location line="+0"/> <source>Amount</source> <translation>Importo</translation> </message> <message numerus="yes"> <location line="+57"/> <source>Open for %n more block(s)</source> <translation><numerusform>Aperto per %n altro blocco</numerusform><numerusform>Aperto per altri %n blocchi</numerusform></translation> </message> <message> <location line="+3"/> <source>Open until %1</source> <translation>Aperto fino a %1</translation> </message> <message> <location line="+3"/> <source>Offline (%1 confirmations)</source> <translation>Offline (%1 conferme)</translation> </message> <message> <location line="+3"/> <source>Unconfirmed (%1 of %2 confirmations)</source> <translation>Non confermati (%1 su %2 conferme)</translation> </message> <message> <location line="+3"/> <source>Confirmed (%1 confirmations)</source> <translation>Confermato (%1 conferme)</translation> </message> <message numerus="yes"> <location line="+8"/> <source>Mined balance will be available when it matures in %n more block(s)</source> <translation><numerusform>Il saldo generato sarà disponibile quando maturerà in %n altro blocco</numerusform><numerusform>Il saldo generato sarà disponibile quando maturerà in altri %n blocchi</numerusform></translation> </message> <message> <location line="+5"/> <source>This block was not received by any other nodes and will probably not be accepted!</source> <translation>Questo blocco non è stato ricevuto da altri nodi e probabilmente non sarà accettato!</translation> </message> <message> <location line="+3"/> <source>Generated but not accepted</source> <translation>Generati, ma non accettati</translation> </message> <message> <location line="+43"/> <source>Received with</source> <translation>Ricevuto tramite</translation> </message> <message> <location line="+2"/> <source>Received from</source> <translation>Ricevuto da</translation> </message> <message> <location line="+3"/> <source>Sent to</source> <translation>Spedito a</translation> </message> <message> <location line="+2"/> <source>Payment to yourself</source> <translation>Pagamento a te stesso</translation> </message> <message> <location line="+2"/> <source>Mined</source> <translation>Ottenuto dal mining</translation> </message> <message> <location line="+38"/> <source>(n/a)</source> <translation>(N / a)</translation> </message> <message> <location line="+199"/> <source>Transaction status. Hover over this field to show number of confirmations.</source> <translation>Stato della transazione. Passare con il mouse su questo campo per vedere il numero di conferme.</translation> </message> <message> <location line="+2"/> <source>Date and time that the transaction was received.</source> <translation>Data e ora in cui la transazione è stata ricevuta.</translation> </message> <message> <location line="+2"/> <source>Type of transaction.</source> <translation>Tipo di transazione.</translation> </message> <message> <location line="+2"/> <source>Destination address of transaction.</source> <translation>Indirizzo di destinazione della transazione.</translation> </message> <message> <location line="+2"/> <source>Amount removed from or added to balance.</source> <translation>Importo rimosso o aggiunto al saldo.</translation> </message> </context> <context> <name>TransactionView</name> <message> <location filename="../transactionview.cpp" line="+52"/> <location line="+16"/> <source>All</source> <translation>Tutti</translation> </message> <message> <location line="-15"/> <source>Today</source> <translation>Oggi</translation> </message> <message> <location line="+1"/> <source>This week</source> <translation>Questa settimana</translation> </message> <message> <location line="+1"/> <source>This month</source> <translation>Questo mese</translation> </message> <message> <location line="+1"/> <source>Last month</source> <translation>Il mese scorso</translation> </message> <message> <location line="+1"/> <source>This year</source> <translation>Quest&apos;anno</translation> </message> <message> <location line="+1"/> <source>Range...</source> <translation>Intervallo...</translation> </message> <message> <location line="+11"/> <source>Received with</source> <translation>Ricevuto tramite</translation> </message> <message> <location line="+2"/> <source>Sent to</source> <translation>Spedito a</translation> </message> <message> <location line="+2"/> <source>To yourself</source> <translation>A te</translation> </message> <message> <location line="+1"/> <source>Mined</source> <translation>Ottenuto dal mining</translation> </message> <message> <location line="+1"/> <source>Other</source> <translation>Altro</translation> </message> <message> <location line="+7"/> <source>Enter address or label to search</source> <translation>Inserisci un indirizzo o un&apos;etichetta da cercare</translation> </message> <message> <location line="+7"/> <source>Min amount</source> <translation>Importo minimo</translation> </message> <message> <location line="+34"/> <source>Copy address</source> <translation>Copia l&apos;indirizzo</translation> </message> <message> <location line="+1"/> <source>Copy label</source> <translation>Copia l&apos;etichetta</translation> </message> <message> <location line="+1"/> <source>Copy amount</source> <translation>Copia l&apos;importo</translation> </message> <message> <location line="+1"/> <source>Copy transaction ID</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Edit label</source> <translation>Modifica l&apos;etichetta</translation> </message> <message> <location line="+1"/> <source>Show transaction details</source> <translation>Mostra i dettagli della transazione</translation> </message> <message> <location line="+139"/> <source>Export Transaction Data</source> <translation>Esporta i dati della transazione</translation> </message> <message> <location line="+1"/> <source>Comma separated file (*.csv)</source> <translation>Testo CSV (*.csv)</translation> </message> <message> <location line="+8"/> <source>Confirmed</source> <translation>Confermato</translation> </message> <message> <location line="+1"/> <source>Date</source> <translation>Data</translation> </message> <message> <location line="+1"/> <source>Type</source> <translation>Tipo</translation> </message> <message> <location line="+1"/> <source>Label</source> <translation>Etichetta</translation> </message> <message> <location line="+1"/> <source>Address</source> <translation>Indirizzo</translation> </message> <message> <location line="+1"/> <source>Amount</source> <translation>Importo</translation> </message> <message> <location line="+1"/> <source>ID</source> <translation>ID</translation> </message> <message> <location line="+4"/> <source>Error exporting</source> <translation>Errore nell&apos;esportazione</translation> </message> <message> <location line="+0"/> <source>Could not write to file %1.</source> <translation>Impossibile scrivere sul file %1.</translation> </message> <message> <location line="+100"/> <source>Range:</source> <translation>Intervallo:</translation> </message> <message> <location line="+8"/> <source>to</source> <translation>a</translation> </message> </context> <context> <name>WalletModel</name> <message> <location filename="../walletmodel.cpp" line="+193"/> <source>Send Coins</source> <translation>Spedisci stripecoin</translation> </message> </context> <context> <name>WalletView</name> <message> <location filename="../walletview.cpp" line="+42"/> <source>&amp;Export</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Export the data in the current tab to a file</source> <translation>Esporta i dati nella tabella corrente su un file</translation> </message> <message> <location line="+193"/> <source>Backup Wallet</source> <translation type="unfinished"/> </message> <message> <location line="+0"/> <source>Wallet Data (*.dat)</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>Backup Failed</source> <translation>Backup fallito</translation> </message> <message> <location line="+0"/> <source>There was an error trying to save the wallet data to the new location.</source> <translation type="unfinished"/> </message> <message> <location line="+4"/> <source>Backup Successful</source> <translation>Backup eseguito con successo</translation> </message> <message> <location line="+0"/> <source>The wallet data was successfully saved to the new location.</source> <translation>Il portafoglio è stato correttamente salvato nella nuova cartella.</translation> </message> </context> <context> <name>bitcoin-core</name> <message> <location filename="../bitcoinstrings.cpp" line="+94"/> <source>stripecoin version</source> <translation>Versione di stripecoin</translation> </message> <message> <location line="+102"/> <source>Usage:</source> <translation>Utilizzo:</translation> </message> <message> <location line="-29"/> <source>Send command to -server or stripecoind</source> <translation>Manda il comando a -server o stripecoind </translation> </message> <message> <location line="-23"/> <source>List commands</source> <translation>Lista comandi </translation> </message> <message> <location line="-12"/> <source>Get help for a command</source> <translation>Aiuto su un comando </translation> </message> <message> <location line="+24"/> <source>Options:</source> <translation>Opzioni: </translation> </message> <message> <location line="+24"/> <source>Specify configuration file (default: stripecoin.conf)</source> <translation>Specifica il file di configurazione (di default: stripecoin.conf) </translation> </message> <message> <location line="+3"/> <source>Specify pid file (default: stripecoind.pid)</source> <translation>Specifica il file pid (default: stripecoind.pid) </translation> </message> <message> <location line="-1"/> <source>Specify data directory</source> <translation>Specifica la cartella dati </translation> </message> <message> <location line="-9"/> <source>Set database cache size in megabytes (default: 25)</source> <translation>Imposta la dimensione cache del database in megabyte (default: 25)</translation> </message> <message> <location line="-28"/> <source>Listen for connections on &lt;port&gt; (default: 33615 or testnet: 19333)</source> <translation>Ascolta le connessioni JSON-RPC su &lt;porta&gt; (default: 33615 o testnet: 19333)</translation> </message> <message> <location line="+5"/> <source>Maintain at most &lt;n&gt; connections to peers (default: 125)</source> <translation>Mantieni al massimo &lt;n&gt; connessioni ai peer (default: 125)</translation> </message> <message> <location line="-48"/> <source>Connect to a node to retrieve peer addresses, and disconnect</source> <translation>Connessione ad un nodo per ricevere l&apos;indirizzo del peer, e disconnessione</translation> </message> <message> <location line="+82"/> <source>Specify your own public address</source> <translation>Specifica il tuo indirizzo pubblico</translation> </message> <message> <location line="+3"/> <source>Threshold for disconnecting misbehaving peers (default: 100)</source> <translation>Soglia di disconnessione dei peer di cattiva qualità (default: 100)</translation> </message> <message> <location line="-134"/> <source>Number of seconds to keep misbehaving peers from reconnecting (default: 86400)</source> <translation>Numero di secondi di sospensione che i peer di cattiva qualità devono trascorrere prima di riconnettersi (default: 86400)</translation> </message> <message> <location line="-29"/> <source>An error occurred while setting up the RPC port %u for listening on IPv4: %s</source> <translation>Errore riscontrato durante l&apos;impostazione della porta RPC %u per l&apos;ascolto su IPv4: %s</translation> </message> <message> <location line="+27"/> <source>Listen for JSON-RPC connections on &lt;port&gt; (default: 33616 or testnet: 19332)</source> <translation>Attendi le connessioni JSON-RPC su &lt;porta&gt; (default: 33616 or testnet: 19332)</translation> </message> <message> <location line="+37"/> <source>Accept command line and JSON-RPC commands</source> <translation>Accetta da linea di comando e da comandi JSON-RPC </translation> </message> <message> <location line="+76"/> <source>Run in the background as a daemon and accept commands</source> <translation>Esegui in background come demone e accetta i comandi </translation> </message> <message> <location line="+37"/> <source>Use the test network</source> <translation>Utilizza la rete di prova </translation> </message> <message> <location line="-112"/> <source>Accept connections from outside (default: 1 if no -proxy or -connect)</source> <translation>Accetta connessioni dall&apos;esterno (default: 1 se no -proxy o -connect)</translation> </message> <message> <location line="-80"/> <source>%s, you must set a rpcpassword in the configuration file: %s It is recommended you use the following random password: rpcuser=litecoinrpc rpcpassword=%s (you do not need to remember this password) The username and password MUST NOT be the same. If the file does not exist, create it with owner-readable-only file permissions. It is also recommended to set alertnotify so you are notified of problems; for example: alertnotify=echo %%s | mail -s &quot;stripecoin Alert&quot; admin@foo.com </source> <translation type="unfinished"/> </message> <message> <location line="+17"/> <source>An error occurred while setting up the RPC port %u for listening on IPv6, falling back to IPv4: %s</source> <translation>Errore riscontrato durante l&apos;impostazione della porta RPC %u per l&apos;ascolto su IPv6, tornando su IPv4: %s</translation> </message> <message> <location line="+3"/> <source>Bind to given address and always listen on it. Use [host]:port notation for IPv6</source> <translation>Collega all&apos;indirizzo indicato e resta sempre in ascolto su questo. Usa la notazione [host]:porta per l&apos;IPv6</translation> </message> <message> <location line="+3"/> <source>Cannot obtain a lock on data directory %s. stripecoin is probably already running.</source> <translation>Non è possibile ottenere i dati sulla cartella %s. Probabilmente stripecoin è già in esecuzione.</translation> </message> <message> <location line="+3"/> <source>Error: The transaction was rejected! This might happen if some of the coins in your wallet were already spent, such as if you used a copy of wallet.dat and coins were spent in the copy but not marked as spent here.</source> <translation>Errore: la transazione è stata rifiutata. Ciò accade se alcuni stripecoin nel portamonete sono stati già spesi, ad esempio se è stata usata una copia del file wallet.dat e i stripecoin sono stati spesi dalla copia ma non segnati come spesi qui.</translation> </message> <message> <location line="+4"/> <source>Error: This transaction requires a transaction fee of at least %s because of its amount, complexity, or use of recently received funds!</source> <translation>Errore: questa transazione necessita di una commissione di almeno %s a causa del suo ammontare, della sua complessità, o dell&apos;uso di fondi recentemente ricevuti!</translation> </message> <message> <location line="+3"/> <source>Execute command when a relevant alert is received (%s in cmd is replaced by message)</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>Execute command when a wallet transaction changes (%s in cmd is replaced by TxID)</source> <translation>Esegui comando quando una transazione del portafoglio cambia (%s in cmd è sostituito da TxID)</translation> </message> <message> <location line="+11"/> <source>Set maximum size of high-priority/low-fee transactions in bytes (default: 27000)</source> <translation>Imposta dimensione massima delle transazioni ad alta priorità/bassa-tassa in bytes (predefinito: 27000)</translation> </message> <message> <location line="+6"/> <source>This is a pre-release test build - use at your own risk - do not use for mining or merchant applications</source> <translation>Questa versione è una compilazione pre-rilascio - usala a tuo rischio - non utilizzarla per la generazione o per applicazioni di commercio</translation> </message> <message> <location line="+5"/> <source>Warning: -paytxfee is set very high! This is the transaction fee you will pay if you send a transaction.</source> <translation>Attenzione: -paytxfee è molto alta. Questa è la commissione che si paga quando si invia una transazione.</translation> </message> <message> <location line="+3"/> <source>Warning: Displayed transactions may not be correct! You may need to upgrade, or other nodes may need to upgrade.</source> <translation>Attenzione: le transazioni mostrate potrebbero essere sbagliate! Potresti aver bisogno di aggiornare, o altri nodi ne hanno bisogno.</translation> </message> <message> <location line="+3"/> <source>Warning: Please check that your computer&apos;s date and time are correct! If your clock is wrong stripecoin will not work properly.</source> <translation>Attenzione: si prega di controllare che la data del computer e l&apos;ora siano corrette. Se il vostro orologio è sbagliato stripecoin non funziona correttamente.</translation> </message> <message> <location line="+3"/> <source>Warning: error reading wallet.dat! All keys read correctly, but transaction data or address book entries might be missing or incorrect.</source> <translation>Attenzione: errore di lettura di wallet.dat! Tutte le chiave lette correttamente, ma i dati delle transazioni o le voci in rubrica potrebbero mancare o non essere corretti.</translation> </message> <message> <location line="+3"/> <source>Warning: wallet.dat corrupt, data salvaged! Original wallet.dat saved as wallet.{timestamp}.bak in %s; if your balance or transactions are incorrect you should restore from a backup.</source> <translation>Attenzione: wallet.dat corrotto, dati salvati! Il wallet.dat originale salvato come wallet.{timestamp}.bak in %s; se il tuo bilancio o le transazioni non sono corrette dovresti ripristinare da un backup.</translation> </message> <message> <location line="+14"/> <source>Attempt to recover private keys from a corrupt wallet.dat</source> <translation>Tenta di recuperare le chiavi private da un wallet.dat corrotto</translation> </message> <message> <location line="+2"/> <source>Block creation options:</source> <translation>Opzioni creazione blocco:</translation> </message> <message> <location line="+5"/> <source>Connect only to the specified node(s)</source> <translation>Connetti solo al nodo specificato</translation> </message> <message> <location line="+3"/> <source>Corrupted block database detected</source> <translation>Rilevato database blocchi corrotto</translation> </message> <message> <location line="+1"/> <source>Discover own IP address (default: 1 when listening and no -externalip)</source> <translation>Scopri proprio indirizzo IP (default: 1 se in ascolto e no -externalip)</translation> </message> <message> <location line="+1"/> <source>Do you want to rebuild the block database now?</source> <translation>Vuoi ricostruire ora il database dei blocchi?</translation> </message> <message> <location line="+2"/> <source>Error initializing block database</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Error initializing wallet database environment %s!</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Error loading block database</source> <translation>Errore caricamento database blocchi</translation> </message> <message> <location line="+4"/> <source>Error opening block database</source> <translation>Errore caricamento database blocchi</translation> </message> <message> <location line="+2"/> <source>Error: Disk space is low!</source> <translation>Errore: la spazio libero sul disco è poco!</translation> </message> <message> <location line="+1"/> <source>Error: Wallet locked, unable to create transaction!</source> <translation>Errore: portafoglio bloccato, impossibile creare la transazione!</translation> </message> <message> <location line="+1"/> <source>Error: system error: </source> <translation>Errore: errore di sistema:</translation> </message> <message> <location line="+1"/> <source>Failed to listen on any port. Use -listen=0 if you want this.</source> <translation>Impossibile mettersi in ascolto su una porta. Usa -listen=0 se vuoi usare questa opzione.</translation> </message> <message> <location line="+1"/> <source>Failed to read block info</source> <translation>Lettura informazioni blocco fallita</translation> </message> <message> <location line="+1"/> <source>Failed to read block</source> <translation>Lettura blocco fallita</translation> </message> <message> <location line="+1"/> <source>Failed to sync block index</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Failed to write block index</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Failed to write block info</source> <translation>Scrittura informazioni blocco fallita</translation> </message> <message> <location line="+1"/> <source>Failed to write block</source> <translation>Scrittura blocco fallita</translation> </message> <message> <location line="+1"/> <source>Failed to write file info</source> <translation>Scrittura informazioni file fallita</translation> </message> <message> <location line="+1"/> <source>Failed to write to coin database</source> <translation>Scrittura nel database dei stripecoin fallita</translation> </message> <message> <location line="+1"/> <source>Failed to write transaction index</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Failed to write undo data</source> <translation type="unfinished"/> </message> <message> <location line="+2"/> <source>Find peers using DNS lookup (default: 1 unless -connect)</source> <translation>Trova peer utilizzando la ricerca DNS (predefinito: 1 finché utilizzato -connect)</translation> </message> <message> <location line="+1"/> <source>Generate coins (default: 0)</source> <translation type="unfinished"/> </message> <message> <location line="+2"/> <source>How many blocks to check at startup (default: 288, 0 = all)</source> <translation>Quanti blocchi da controllare all&apos;avvio (predefinito: 288, 0 = tutti)</translation> </message> <message> <location line="+1"/> <source>How thorough the block verification is (0-4, default: 3)</source> <translation type="unfinished"/> </message> <message> <location line="+19"/> <source>Not enough file descriptors available.</source> <translation type="unfinished"/> </message> <message> <location line="+8"/> <source>Rebuild block chain index from current blk000??.dat files</source> <translation type="unfinished"/> </message> <message> <location line="+16"/> <source>Set the number of threads to service RPC calls (default: 4)</source> <translation type="unfinished"/> </message> <message> <location line="+26"/> <source>Verifying blocks...</source> <translation>Verifica blocchi...</translation> </message> <message> <location line="+1"/> <source>Verifying wallet...</source> <translation>Verifica portafoglio...</translation> </message> <message> <location line="-69"/> <source>Imports blocks from external blk000??.dat file</source> <translation>Importa blocchi da un file blk000??.dat esterno</translation> </message> <message> <location line="-76"/> <source>Set the number of script verification threads (up to 16, 0 = auto, &lt;0 = leave that many cores free, default: 0)</source> <translation type="unfinished"/> </message> <message> <location line="+77"/> <source>Information</source> <translation>Informazione</translation> </message> <message> <location line="+3"/> <source>Invalid -tor address: &apos;%s&apos;</source> <translation>Indirizzo -tor non valido: &apos;%s&apos;</translation> </message> <message> <location line="+1"/> <source>Invalid amount for -minrelaytxfee=&lt;amount&gt;: &apos;%s&apos;</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Invalid amount for -mintxfee=&lt;amount&gt;: &apos;%s&apos;</source> <translation type="unfinished"/> </message> <message> <location line="+8"/> <source>Maintain a full transaction index (default: 0)</source> <translation type="unfinished"/> </message> <message> <location line="+2"/> <source>Maximum per-connection receive buffer, &lt;n&gt;*1000 bytes (default: 5000)</source> <translation>Buffer di ricezione massimo per connessione, &lt;n&gt;*1000 byte (default: 5000)</translation> </message> <message> <location line="+1"/> <source>Maximum per-connection send buffer, &lt;n&gt;*1000 bytes (default: 1000)</source> <translation>Buffer di invio massimo per connessione, &lt;n&gt;*1000 byte (default: 1000)</translation> </message> <message> <location line="+2"/> <source>Only accept block chain matching built-in checkpoints (default: 1)</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Only connect to nodes in network &lt;net&gt; (IPv4, IPv6 or Tor)</source> <translation>Connetti solo a nodi nella rete &lt;net&gt; (IPv4, IPv6 o Tor)</translation> </message> <message> <location line="+2"/> <source>Output extra debugging information. Implies all other -debug* options</source> <translation>Produci informazioni extra utili al debug. Implies all other -debug* options</translation> </message> <message> <location line="+1"/> <source>Output extra network debugging information</source> <translation>Genera informazioni extra utili al debug della rete</translation> </message> <message> <location line="+2"/> <source>Prepend debug output with timestamp</source> <translation>Anteponi all&apos;output di debug una marca temporale</translation> </message> <message> <location line="+5"/> <source>SSL options: (see the stripecoin Wiki for SSL setup instructions)</source> <translation>Opzioni SSL: (vedi il wiki di stripecoin per le istruzioni di configurazione SSL)</translation> </message> <message> <location line="+1"/> <source>Select the version of socks proxy to use (4-5, default: 5)</source> <translation>Selezionare la versione del proxy socks da usare (4-5, default: 5)</translation> </message> <message> <location line="+3"/> <source>Send trace/debug info to console instead of debug.log file</source> <translation>Invia le informazioni di trace/debug alla console invece che al file debug.log</translation> </message> <message> <location line="+1"/> <source>Send trace/debug info to debugger</source> <translation>Invia le informazioni di trace/debug al debugger</translation> </message> <message> <location line="+5"/> <source>Set maximum block size in bytes (default: 250000)</source> <translation>Imposta dimensione massima del blocco in bytes (predefinito: 250000)</translation> </message> <message> <location line="+1"/> <source>Set minimum block size in bytes (default: 0)</source> <translation>Imposta dimensione minima del blocco in bytes (predefinito: 0)</translation> </message> <message> <location line="+2"/> <source>Shrink debug.log file on client startup (default: 1 when no -debug)</source> <translation>Riduci il file debug.log all&apos;avvio del client (predefinito: 1 se non impostato -debug)</translation> </message> <message> <location line="+1"/> <source>Signing transaction failed</source> <translation type="unfinished"/> </message> <message> <location line="+2"/> <source>Specify connection timeout in milliseconds (default: 5000)</source> <translation>Specifica il timeout di connessione in millisecondi (default: 5000)</translation> </message> <message> <location line="+4"/> <source>System error: </source> <translation>Errore di sistema:</translation> </message> <message> <location line="+4"/> <source>Transaction amount too small</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Transaction amounts must be positive</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Transaction too large</source> <translation type="unfinished"/> </message> <message> <location line="+7"/> <source>Use UPnP to map the listening port (default: 0)</source> <translation>UPnP-használat engedélyezése a figyelő port feltérképezésénél (default: 0)</translation> </message> <message> <location line="+1"/> <source>Use UPnP to map the listening port (default: 1 when listening)</source> <translation>UPnP-használat engedélyezése a figyelő port feltérképezésénél (default: 1 when listening)</translation> </message> <message> <location line="+1"/> <source>Use proxy to reach tor hidden services (default: same as -proxy)</source> <translation>Usa un proxy per raggiungere servizi nascosti di tor (predefinito: uguale a -proxy)</translation> </message> <message> <location line="+2"/> <source>Username for JSON-RPC connections</source> <translation>Nome utente per connessioni JSON-RPC </translation> </message> <message> <location line="+4"/> <source>Warning</source> <translation>Attenzione</translation> </message> <message> <location line="+1"/> <source>Warning: This version is obsolete, upgrade required!</source> <translation>Attenzione: questa versione è obsoleta, aggiornamento necessario!</translation> </message> <message> <location line="+1"/> <source>You need to rebuild the databases using -reindex to change -txindex</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>wallet.dat corrupt, salvage failed</source> <translation>wallet.dat corrotto, salvataggio fallito</translation> </message> <message> <location line="-50"/> <source>Password for JSON-RPC connections</source> <translation>Password per connessioni JSON-RPC </translation> </message> <message> <location line="-67"/> <source>Allow JSON-RPC connections from specified IP address</source> <translation>Consenti connessioni JSON-RPC dall&apos;indirizzo IP specificato </translation> </message> <message> <location line="+76"/> <source>Send commands to node running on &lt;ip&gt; (default: 127.0.0.1)</source> <translation>Inviare comandi al nodo in esecuzione su &lt;ip&gt; (default: 127.0.0.1) </translation> </message> <message> <location line="-120"/> <source>Execute command when the best block changes (%s in cmd is replaced by block hash)</source> <translation>Esegui il comando quando il miglior block cambia(%s nel cmd è sostituito dall&apos;hash del blocco)</translation> </message> <message> <location line="+147"/> <source>Upgrade wallet to latest format</source> <translation>Aggiorna il wallet all&apos;ultimo formato</translation> </message> <message> <location line="-21"/> <source>Set key pool size to &lt;n&gt; (default: 100)</source> <translation>Impostare la quantità di chiavi di riserva a &lt;n&gt; (default: 100) </translation> </message> <message> <location line="-12"/> <source>Rescan the block chain for missing wallet transactions</source> <translation>Ripeti analisi della catena dei blocchi per cercare le transazioni mancanti dal portamonete </translation> </message> <message> <location line="+35"/> <source>Use OpenSSL (https) for JSON-RPC connections</source> <translation>Utilizzare OpenSSL (https) per le connessioni JSON-RPC </translation> </message> <message> <location line="-26"/> <source>Server certificate file (default: server.cert)</source> <translation>File certificato del server (default: server.cert) </translation> </message> <message> <location line="+1"/> <source>Server private key (default: server.pem)</source> <translation>Chiave privata del server (default: server.pem) </translation> </message> <message> <location line="-151"/> <source>Acceptable ciphers (default: TLSv1+HIGH:!SSLv2:!aNULL:!eNULL:!AH:!3DES:@STRENGTH)</source> <translation>Cifrari accettabili (default: TLSv1+HIGH:!SSLv2:!aNULL:!eNULL:!AH:!3DES:@STRENGTH) </translation> </message> <message> <location line="+165"/> <source>This help message</source> <translation>Questo messaggio di aiuto </translation> </message> <message> <location line="+6"/> <source>Unable to bind to %s on this computer (bind returned error %d, %s)</source> <translation>Impossibile collegarsi alla %s su questo computer (bind returned error %d, %s)</translation> </message> <message> <location line="-91"/> <source>Connect through socks proxy</source> <translation>Connessione tramite socks proxy</translation> </message> <message> <location line="-10"/> <source>Allow DNS lookups for -addnode, -seednode and -connect</source> <translation>Consenti ricerche DNS per aggiungere nodi e collegare </translation> </message> <message> <location line="+55"/> <source>Loading addresses...</source> <translation>Caricamento indirizzi...</translation> </message> <message> <location line="-35"/> <source>Error loading wallet.dat: Wallet corrupted</source> <translation>Errore caricamento wallet.dat: Wallet corrotto</translation> </message> <message> <location line="+1"/> <source>Error loading wallet.dat: Wallet requires newer version of stripecoin</source> <translation>Errore caricamento wallet.dat: il wallet richiede una versione nuova di stripecoin</translation> </message> <message> <location line="+93"/> <source>Wallet needed to be rewritten: restart stripecoin to complete</source> <translation>Il portamonete deve essere riscritto: riavviare stripecoin per completare</translation> </message> <message> <location line="-95"/> <source>Error loading wallet.dat</source> <translation>Errore caricamento wallet.dat</translation> </message> <message> <location line="+28"/> <source>Invalid -proxy address: &apos;%s&apos;</source> <translation>Indirizzo -proxy non valido: &apos;%s&apos;</translation> </message> <message> <location line="+56"/> <source>Unknown network specified in -onlynet: &apos;%s&apos;</source> <translation>Rete sconosciuta specificata in -onlynet: &apos;%s&apos;</translation> </message> <message> <location line="-1"/> <source>Unknown -socks proxy version requested: %i</source> <translation>Versione -socks proxy sconosciuta richiesta: %i</translation> </message> <message> <location line="-96"/> <source>Cannot resolve -bind address: &apos;%s&apos;</source> <translation>Impossibile risolvere -bind address: &apos;%s&apos;</translation> </message> <message> <location line="+1"/> <source>Cannot resolve -externalip address: &apos;%s&apos;</source> <translation>Impossibile risolvere indirizzo -externalip: &apos;%s&apos;</translation> </message> <message> <location line="+44"/> <source>Invalid amount for -paytxfee=&lt;amount&gt;: &apos;%s&apos;</source> <translation>Importo non valido per -paytxfee=&lt;amount&gt;: &apos;%s&apos;</translation> </message> <message> <location line="+1"/> <source>Invalid amount</source> <translation>Importo non valido</translation> </message> <message> <location line="-6"/> <source>Insufficient funds</source> <translation>Fondi insufficienti</translation> </message> <message> <location line="+10"/> <source>Loading block index...</source> <translation>Caricamento dell&apos;indice del blocco...</translation> </message> <message> <location line="-57"/> <source>Add a node to connect to and attempt to keep the connection open</source> <translation>Elérendő csomópont megadása and attempt to keep the connection open</translation> </message> <message> <location line="-25"/> <source>Unable to bind to %s on this computer. stripecoin is probably already running.</source> <translation>Impossibile collegarsi alla %s su questo computer. Probabilmente stripecoin è già in esecuzione.</translation> </message> <message> <location line="+64"/> <source>Fee per KB to add to transactions you send</source> <translation>Commissione per KB da aggiungere alle transazioni in uscita</translation> </message> <message> <location line="+19"/> <source>Loading wallet...</source> <translation>Caricamento portamonete...</translation> </message> <message> <location line="-52"/> <source>Cannot downgrade wallet</source> <translation>Non è possibile retrocedere il wallet</translation> </message> <message> <location line="+3"/> <source>Cannot write default address</source> <translation>Non è possibile scrivere l&apos;indirizzo di default</translation> </message> <message> <location line="+64"/> <source>Rescanning...</source> <translation>Ripetere la scansione...</translation> </message> <message> <location line="-57"/> <source>Done loading</source> <translation>Caricamento completato</translation> </message> <message> <location line="+82"/> <source>To use the %s option</source> <translation>Per usare la opzione %s</translation> </message> <message> <location line="-74"/> <source>Error</source> <translation>Errore</translation> </message> <message> <location line="-31"/> <source>You must set rpcpassword=&lt;password&gt; in the configuration file: %s If the file does not exist, create it with owner-readable-only file permissions.</source> <translation>Devi settare rpcpassword=&lt;password&gt; nel file di configurazione: %s Se il file non esiste, crealo con i permessi di amministratore</translation> </message> </context> </TS>
stripecoin/stripecoin
src/qt/locale/bitcoin_it.ts
TypeScript
mit
116,607
#include <iostream> #include <stddef.h> #include <fitsio.h> #include <fitsio2.h> #include <longnam.h> #include "leastsq.h" #include <cmath> /* */ using namespace std; // error handling void printerror( int status) { /*****************************************************/ /* Print out cfitsio error messages and exit program */ /*****************************************************/ if (status) { fits_report_error(stderr, status); /* print error report */ exit( status ); /* terminate the program, returning error status */ } return; } int main( int argc, char** argv ) { if( argc!=3 && argc!=4 ) { std::cerr <<"Usage: " << argv[0] << " <inputfile> <outputfile> (verboseflag)"<< std::endl; std::cerr <<"Input image must be image with background pixels set to -1, objects > 0."<<std::endl; ::exit(1); } int v =0; if(argc==4) v =1; char* filename = argv[1]; char* outfilename = argv[2]; /* Most of the code to load the fits file, I have brazenly stolen from the cfitsio manual examples*/ if(v) cout<<"Start reading FITS file"<<endl; fitsfile *fptr; /* FITS file pointer, defined in fitsio.h */ int status = 0; /* CFITSIO status value MUST be initialized to zero! */ int bitpix; // not important int naxis;// number of axes. Better be 2. int ii;// iterator long naxes[2] = {1,1};// number of pixels in axis{x,y} long fpixel[2] = {1,1};// effectively an iterator int NaxisX=0; int NaxisY=0; int Npixels=0; int max = 0; //minimum val int min = 99999; double average=0; double total=0; int open_file_flag=0,img_param_flag=0; // Open FITS file: open_file_flag = fits_open_file(&fptr, filename, READONLY, &status); if(open_file_flag) { printf("Error: Cannot open file\n"); return 0;} if(v) cout<<"FileOpen"<<endl; // Get Parameters: NaxisX & NaxisY from header img_param_flag = fits_get_img_param(fptr, 2, &bitpix, &naxis, naxes, &status); if (img_param_flag ) {printf("Error: Cannot find image dimensions\n");return 0; } NaxisX = naxes[0]; NaxisY = naxes[1]; Npixels = NaxisX * NaxisY; if(v) cout<<"Nx = "<< NaxisX<<"; Ny = "<< NaxisY<<endl; if (naxis > 2 || naxis == 0) { printf("Error: only 1D or 2D images are supported\n"); return 0; } // Define Masks double **imagearray = new double*[NaxisX]; // the input image double **maskarray = new double*[NaxisX]; // intermediate mask. for(int iter = 0; iter < NaxisX ; iter++){ imagearray[iter] = new double [NaxisY]; maskarray [iter] = new double [NaxisY]; } /* get memory for 1 row */ double *pixels = new double[NaxisX]; if(v) cout<<"Starting Reading File"<<endl; /* loop over all the rows in the image, top to bottom */ for (fpixel[1] = naxes[1]; fpixel[1] >= 1; fpixel[1]--) { /* read row of pixels */ if (fits_read_pix(fptr, TDOUBLE, fpixel, naxes[0], NULL, pixels, NULL, &status) ) { break;} /* jump out of loop on error */ for (ii = 0; ii < naxes[0]; ii++) { imagearray[ii][fpixel[1]-1] = pixels[ii]; // Fill array } } free(pixels); /* Close the file*/ fits_close_file(fptr, &status); if(v) cout<<"Closed infile"<<endl; if (status) fits_report_error(stderr, status); /* print any error message */ //mask arrays are for(int i=0; i<NaxisX; i++) { for(int j=0; j<NaxisY; j++) { maskarray[i][j]=0; } } for(int jcol = 0; jcol<NaxisX; jcol++) { for(int jrow = 0; jrow<NaxisY; jrow++) { float val = imagearray[jcol][jrow]; if(val < 0.5) continue; // Nothin doin else { for(int localx = jcol-1; localx <= jcol+1; localx++) { for(int localy = jrow-1; localy <= jrow+1; localy++) { // Make sure we're still on the image! if(!(localx<0 || localx>=NaxisX || localy<0 || localy>=NaxisY)) { maskarray[localx][localy] = 1; } } } } } } /******************************************************/ /* Create a FITS primary array containing a 2-D image */ /* ... Again, stolen from the cfitsio doc */ /******************************************************/ fitsfile *fptrout; /* pointer to the FITS file, defined in fitsio.h */ int statusout; long fpixelout, nelements; unsigned short *array[NaxisY]; /* initialize FITS image parameters */ bitpix = -32; /* 16-bit unsigned short pixel values */ /* allocate memory for the whole image */ array[0] = (unsigned short *)malloc( naxes[0] * naxes[1] * sizeof( unsigned short ) ); /* initialize pointers to the start of each row of the image */ for( ii=1; ii<naxes[1]; ii++ ) { array[ii] = array[ii-1] + naxes[0]; } remove(outfilename); /* Delete old file if it already exists */ statusout = 0; /* initialize statusout before calling fitsio routines */ if (fits_create_file(&fptrout, outfilename, &statusout)) /* create new FITS file */ printerror( statusout ); /* call printerror if error occurs */ if ( fits_create_img(fptrout, bitpix, naxis, naxes, &statusout) ) printerror( statusout ); /* set the values in the image with the mask values */ for (int jj = 0; jj < naxes[1]; jj++) { for (ii = 0; ii < naxes[0]; ii++) { array[jj][ii] = maskarray[ii][jj]; } } fpixelout = 1; /* first pixel to write */ nelements = naxes[0] * naxes[1]; /* number of pixels to write */ if ( fits_write_img(fptrout, TUSHORT, fpixelout, nelements, array[0], &statusout) ) printerror( statusout ); free( array[0] ); /* free previously allocated memory */ if ( fits_close_file(fptrout, &statusout) ) /* close the file */ printerror( statusout ); if(v) cout<<"Done."<<endl; return 0; }
deapplegate/wtgpipeline
sfdir/expand_cosmics_mask.cc
C++
mit
6,037
package com.lanceolata.leetcode; public class Question_0082_Remove_Duplicates_from_Sorted_List_II { // Definition for singly-linked list. public class ListNode { int val; ListNode next; ListNode(int x) { val = x; next = null; } } public ListNode deleteDuplicates(ListNode head) { if (head == null || head.next == null) { return head; } ListNode node = new ListNode(0); node.next = head; ListNode pre = node; while (pre.next != null) { ListNode cur = pre.next; while (cur.next != null && cur.val == cur.next.val) { cur = cur.next; } if (pre.next != cur) { pre.next = cur.next; } else { pre = pre.next; } } return node.next; } }
Lanceolata/code-problems
java/src/main/java/com/lanceolata/leetcode/Question_0082_Remove_Duplicates_from_Sorted_List_II.java
Java
mit
901
/* * Squidex Headless CMS * * @license * Copyright (c) Squidex UG (haftungsbeschränkt). All rights reserved. */ import { Directive, EmbeddedViewRef, Input, OnChanges, OnDestroy, OnInit, SimpleChanges, TemplateRef, ViewContainerRef } from '@angular/core'; @Directive({ selector: '[sqxTemplateWrapper]', }) export class TemplateWrapperDirective implements OnDestroy, OnInit, OnChanges { @Input() public item: any; @Input() public index = 0; @Input() public context: any; @Input('sqxTemplateWrapper') public templateRef!: TemplateRef<any>; public view?: EmbeddedViewRef<any>; public constructor( private readonly viewContainer: ViewContainerRef, ) { } public ngOnDestroy() { if (this.view) { this.view.destroy(); } } public ngOnInit() { const { index, context } = this; const data = { $implicit: this.item, index, context, }; this.view = this.viewContainer.createEmbeddedView(this.templateRef, data); } public ngOnChanges(changes: SimpleChanges) { if (this.view) { if (changes.item) { this.view.context.$implicit = this.item; } if (changes.index) { this.view.context.index = this.index; } if (changes.context) { this.view.context.context = this.context; } } } }
Squidex/squidex
frontend/src/app/framework/angular/template-wrapper.directive.ts
TypeScript
mit
1,495
using System.Collections.Generic; using System.Threading.Tasks; using Majorsilence.MediaService.Dto; namespace Majorsilence.MediaService.RepoInterfaces { public interface IMediaFileInfoRepo { Task<IEnumerable<MediaFileInfo>> SearchAsync(long id); } }
majorsilence/MediaService
Majorsilence.MediaService.RepoInterfaces/IMediaFileInfoRepo.cs
C#
mit
284
using System; using System.Collections.Generic; using System.Linq; using System.Windows.Forms; namespace DDZProj { static class Program { /// <summary> /// The main entry point for the application. /// </summary> [STAThread] static void Main() { Application.EnableVisualStyles(); Application.SetCompatibleTextRenderingDefault(false); Application.Run(new Main()); } } }
flysnoopy1984/DDZ_Live
DDZProj/Program.cs
C#
mit
477
<?php namespace Vicus\Controller; /** * Description of ErrorContorller * * @author Michael Koert <mkoert at bluebikeproductions.com> */ use Symfony\Component\HttpFoundation\Response; use Symfony\Component\HttpKernel\Exception\FlattenException; class ErrorController { public function indexAction(FlattenException $exception) { // $msg = 'Something went wrong! ('.$exception->getMessage().')'; // // return new Response($msg, $exception->getStatusCode()); $msg = 'Something went wrong!'; return new Response($msg, $exception->getStatusCode()); } public function exceptionAction(FlattenException $exception) { // $msg = 'Something went wrong! ('.$exception->getMessage().')'; // // return new Response($msg, $exception->getStatusCode()); $msg = 'Something went wrong!'; return new Response($msg, $exception->getStatusCode()); } }
opensourcerefinery/vicus
src/Controller/ErrorController.php
PHP
mit
915
using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; using BackEnd; namespace Assignment5 { //types aliasing using S = BackEnd.Student<long>; using P = BackEnd.Paper<long>; using E = BackEnd.Enrollment<long>; public partial class MainForm : Form { /// <summary> /// fields /// </summary> private BackEnd.University _Uni; private DetailForm _Detail; /// <summary> /// Ctor /// </summary> public MainForm() { this.InitializeComponent(); _Uni = new BackEnd.University(); _Detail = new DetailForm(); this.SetupColumnsFittingPapers(_GridPapers); this.SetupColumnsFittingStudents(_GridStudents); this.SetAlternatingRowStyles(Color.White, Color.Azure); } /// <summary> /// event handler for right click /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void RightClickOnGrid(object sender, DataGridViewCellMouseEventArgs e) { if (e.Button == MouseButtons.Right) { _ContextMenuStrip.Show(MousePosition); (_GridPapers.Focused ? _GridStudents : _GridPapers).ClearSelection(); } } /// <summary> /// import students event handler /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void _StudentsToolStripMenuItemClick(object sender, EventArgs e) { if (_OpenFileDialog.ShowDialog() == DialogResult.OK) { try { var count = _Uni.ImportStudents(_OpenFileDialog.FileName); this.UpdateGrids(); MessageBox.Show(count + " students loaded."); } catch (Exception ex) { MessageBox.Show(ex.Message); } } } /// <summary> /// event handler for papers item /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void _PapersToolStripMenuItemClick(object sender, EventArgs e) { if (_OpenFileDialog.ShowDialog() == DialogResult.OK) { try { var count = _Uni.ImportPapers(_OpenFileDialog.FileName); this.UpdateGrids(); MessageBox.Show(count + " papers loaded."); } catch (Exception ex) { MessageBox.Show(ex.Message); } } } /// <summary> /// event handler for enroll item /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void _EnrollmentsToolStripMenuItemClick(object sender, EventArgs e) { if (_Uni.Papers.Count == 0 || _Uni.Students.Count == 0) { MessageBox.Show("Please import students and papers first."); return; } if (_OpenFileDialog.ShowDialog() == DialogResult.OK) { try { var count = _Uni.ImportEnrollments(_OpenFileDialog.FileName); MessageBox.Show(count + " pieces of enrollments info loaed."); } catch (Exception ex) { MessageBox.Show(ex.Message); } } } /// <summary> /// event handler for export item /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void exportToolStripMenuItemClick(object sender, EventArgs e) { var fdb = new FolderBrowserDialog(); if (fdb.ShowDialog() == DialogResult.OK) { try { MessageBox.Show(_Uni.ExportAllData(fdb.SelectedPath) ? "Done" : "Failed"); } catch (Exception ex) { MessageBox.Show(ex.Message); } } } /// <summary> /// event handler for detail item /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void _DetailToolStripMenuItemClick(object sender, EventArgs e) { if (_GridPapers.Focused) { if (_GridPapers.CurrentRow == null || _GridPapers.CurrentRow.Cells["Code"].Value == null) { MessageBox.Show("No valid cell specified"); return; } long code; if (Int64.TryParse(_GridPapers.CurrentRow.Cells["Code"].Value.ToString(), out code)) this.PopulateEnrolledStudents(_Detail._Grid, code); _Detail.Text = "Students enrolled for Paper " + code; _Detail.ShowDialog(); } if(_GridStudents.Focused) { if (_GridStudents.CurrentRow == null || _GridStudents.CurrentRow.Cells["Id"].Value == null) { MessageBox.Show("No valid cell specified"); return; } long id; if (Int64.TryParse(_GridStudents.CurrentRow.Cells["Id"].Value.ToString(), out id)) this.PopulateEnrolledPapers(_Detail._Grid, id); _Detail.Text = "Student " + id + " have enrolled in "; _Detail.ShowDialog(); } } /// <summary> /// event handler for OnRowValidating /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void CheckAndSaveOnRowValidating(object sender, DataGridViewCellCancelEventArgs e) { var grid = sender as DataGridView; if (e.RowIndex == grid.RowCount - 1) return; var cells = grid.Rows[e.RowIndex].Cells; //check if any cell is empty if (cells.Cast<DataGridViewCell>().Any(c => c.Value == null)) { e.Cancel = true; MessageBox.Show("Empty cell"); return; } //check paper code or student id long codeOrId = 0; if (!Int64.TryParse(cells[0].Value.ToString(), out codeOrId)) { e.Cancel = true; MessageBox.Show("Invalid input for number"); grid.ClearSelection(); cells[0].Selected = true; return; } if(grid == _GridPapers) { long code = codeOrId; string name = cells["Name"].Value.ToString(); string coordinator = cells["Coordinator"].Value.ToString(); _Uni.Add(new P(code, name, coordinator)); } if(grid == _GridStudents) { DateTime birth; if (!DateTime.TryParse(cells["Birth"].Value.ToString(), out birth)) { e.Cancel = true; MessageBox.Show("Invalid Date"); grid.ClearSelection(); cells["Birth"].Selected = true; return; } long id = codeOrId; string name = cells["Name"].Value.ToString(); string address = cells["Address"].Value.ToString(); _Uni.Add(new S(id, name, birth, address)); } } /// <summary> /// event handler for enrol item /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void _EnrollToolStripMenuItemClick(object sender, EventArgs e) { var grid = _GridPapers.Focused ? _GridPapers : _GridStudents; if (grid.CurrentRow == null || grid.CurrentRow.Cells[0].Value == null) { MessageBox.Show("Incompleted row"); return; } var cells = grid.CurrentRow.Cells; long codeOrId = 0; if (!Int64.TryParse(cells[0].Value.ToString(), out codeOrId)) { MessageBox.Show("Bad number"); return; } if(grid == _GridPapers) { long code = codeOrId; _Detail.Text = "Students to choose"; if (0 == this.PopulateAvailableStudents(_Detail._Grid, code)) { MessageBox.Show("No availabe students"); return; } if(_Detail.ShowDialog(this) == DialogResult.Cancel) { long id = Convert.ToInt64(_Detail._Grid.CurrentRow.Cells["Id"].Value.ToString()); bool result = _Uni.Enrol(code, id); MessageBox.Show(result ? "Enrolled" : "Failed"); } } if(grid == _GridStudents) { long id = codeOrId; _Detail.Text = "Papers to choose"; if (0 == this.PopulateAvailablePapers(_Detail._Grid, id)) { MessageBox.Show("No availabe papers"); return; } if (_Detail.ShowDialog(this) == DialogResult.Cancel) { long code = Convert.ToInt64(_Detail._Grid.CurrentRow.Cells["Code"].Value.ToString()); bool result = _Uni.Enrol(code, id); MessageBox.Show(result ? "Enrolled" : "Failed"); } } } } }
Mooophy/158212
Assignment5/Assignment5/MainForm.cs
C#
mit
10,271
using System; using System.Collections.Generic; using System.Net.Http; using System.Threading; using System.Threading.Tasks; namespace LinqToTwitter { public partial class TwitterContext { /// <summary> /// Adds a user subscription to specified webhook /// </summary> /// <param name="webhookID">ID of webhook user is subscribing to.</param> /// <returns>Account Activity data.</returns> /// <exception cref="TwitterQueryException"> /// Throws TwitterQueryException when an AddAccountActivitySubscriptionAsync fails. /// </exception> public async Task<AccountActivity> AddAccountActivitySubscriptionAsync(ulong webhookID, CancellationToken cancelToken = default(CancellationToken)) { if (webhookID == default(ulong)) throw new ArgumentException($"{nameof(webhookID)} must be set.", nameof(webhookID)); var newUrl = BaseUrl + $"account_activity/webhooks/{webhookID}/subscriptions.json"; var accActValue = new AccountActivityValue(); RawResult = await TwitterExecutor.SendJsonToTwitterAsync( HttpMethod.Post.ToString(), newUrl, new Dictionary<string, string>(), accActValue, cancelToken) .ConfigureAwait(false); var reqProc = new AccountActivityRequestProcessor<AccountActivity>(); AccountActivity accAct = reqProc.ProcessActionResult(RawResult, AccountActivityType.Subscriptions); accAct.WebhookID = webhookID; return accAct; } /// <summary> /// Adds a new webhook to account /// </summary> /// <param name="url">Url of webhook.</param> /// <returns>Account Activity data.</returns> public async Task<AccountActivity> AddAccountActivityWebhookAsync(string url, CancellationToken cancelToken = default(CancellationToken)) { if (string.IsNullOrWhiteSpace(url)) throw new ArgumentException($"{nameof(url)} must be set.", nameof(url)); var newUrl = BaseUrl + $"account_activity/webhooks.json"; RawResult = await TwitterExecutor.PostFormUrlEncodedToTwitterAsync<AccountActivity>( HttpMethod.Post.ToString(), newUrl, new Dictionary<string, string> { { "url", url } }, cancelToken) .ConfigureAwait(false); var reqProc = new AccountActivityRequestProcessor<AccountActivity>(); AccountActivity accAct = reqProc.ProcessActionResult(RawResult, AccountActivityType.Webhooks); accAct.Url = url; return accAct; } /// <summary> /// Sends a CRC check to a webhook for testing /// </summary> /// <param name="webhookID">ID of webhook to send CRC to.</param> /// <returns>Account Activity data.</returns> public async Task<AccountActivity> SendAccountActivityCrcAsync(ulong webhookID, CancellationToken cancelToken = default(CancellationToken)) { if (webhookID == default(ulong)) throw new ArgumentException($"{nameof(webhookID)} must be set.", nameof(webhookID)); var newUrl = BaseUrl + $"account_activity/webhooks/{webhookID}.json"; var accActValue = new AccountActivityValue(); RawResult = await TwitterExecutor.SendJsonToTwitterAsync( HttpMethod.Put.ToString(), newUrl, new Dictionary<string, string>(), accActValue, cancelToken) .ConfigureAwait(false); var reqProc = new AccountActivityRequestProcessor<AccountActivity>(); AccountActivity accAct = reqProc.ProcessActionResult(RawResult, AccountActivityType.Webhooks); accAct.WebhookID = webhookID; return accAct; } /// <summary> /// Deletes a user subscription to specified webhook /// </summary> /// <param name="webhookID">ID of webhook user is subscribing to.</param> /// <returns>Account Activity data.</returns> public async Task<AccountActivity> DeleteAccountActivitySubscriptionAsync(ulong webhookID, CancellationToken cancelToken = default(CancellationToken)) { if (webhookID == default(ulong)) throw new ArgumentException($"{nameof(webhookID)} must be set.", nameof(webhookID)); var newUrl = BaseUrl + $"account_activity/webhooks/{webhookID}/subscriptions.json"; var accActValue = new AccountActivityValue(); RawResult = await TwitterExecutor.SendJsonToTwitterAsync( HttpMethod.Delete.ToString(), newUrl, new Dictionary<string, string>(), accActValue, cancelToken) .ConfigureAwait(false); var reqProc = new AccountActivityRequestProcessor<AccountActivity>(); AccountActivity accAct = reqProc.ProcessActionResult(RawResult, AccountActivityType.Subscriptions); accAct.WebhookID = webhookID; return accAct; } /// <summary> /// Deletes a new webhook to account /// </summary> /// <param name="webhookID">Url of webhook.</param> /// <returns>Account Activity data.</returns> public async Task<AccountActivity> DeleteAccountActivityWebhookAsync(ulong webhookID, CancellationToken cancelToken = default(CancellationToken)) { if (webhookID == default(ulong)) throw new ArgumentException($"{nameof(webhookID)} must be set.", nameof(webhookID)); var newUrl = BaseUrl + $"account_activity/webhooks/{webhookID}.json"; var accActValue = new AccountActivity { WebhookID = webhookID }; RawResult = await TwitterExecutor.SendJsonToTwitterAsync( HttpMethod.Delete.ToString(), newUrl, new Dictionary<string, string>(), accActValue, cancelToken) .ConfigureAwait(false); var reqProc = new AccountActivityRequestProcessor<AccountActivity>(); AccountActivity accAct = reqProc.ProcessActionResult(RawResult, AccountActivityType.Webhooks); accAct.WebhookID = webhookID; return accAct; } } }
JoeMayo/LinqToTwitter
src/LinqToTwitter5/LinqToTwitter.Shared/AccountActivity/TwitterContextAccountActivityCommands.cs
C#
mit
6,813
<?php namespace Acme\BookBundle\Tests\Controller; use Symfony\Bundle\FrameworkBundle\Test\WebTestCase; class AuthorControllerTest extends WebTestCase { /* public function testCompleteScenario() { // Create a new client to browse the application $client = static::createClient(); // Create a new entry in the database $crawler = $client->request('GET', '/author/'); $this->assertTrue(200 === $client->getResponse()->getStatusCode()); $crawler = $client->click($crawler->selectLink('Create a new entry')->link()); // Fill in the form and submit it $form = $crawler->selectButton('Create')->form(array( 'acme_bookbundle_authortype[field_name]' => 'Test', // ... other fields to fill )); $client->submit($form); $crawler = $client->followRedirect(); // Check data in the show view $this->assertTrue($crawler->filter('td:contains("Test")')->count() > 0); // Edit the entity $crawler = $client->click($crawler->selectLink('Edit')->link()); $form = $crawler->selectButton('Edit')->form(array( 'acme_bookbundle_authortype[field_name]' => 'Foo', // ... other fields to fill )); $client->submit($form); $crawler = $client->followRedirect(); // Check the element contains an attribute with value equals "Foo" $this->assertTrue($crawler->filter('[value="Foo"]')->count() > 0); // Delete the entity $client->submit($crawler->selectButton('Delete')->form()); $crawler = $client->followRedirect(); // Check the entity has been delete on the list $this->assertNotRegExp('/Foo/', $client->getResponse()->getContent()); } */ }
okovalov/alexbookstore
src/Acme/BookBundle/Tests/Controller/AuthorControllerTest.php
PHP
mit
1,800
from matplotlib import pyplot as plt import seaborn as sns import pandas as pd from ..ml.linear_algebra import distmat def scatter_2d(orig_df: pd.DataFrame, colx, coly, label_col, xmin=None, xmax=None, ymin=None, ymax=None): """ Return scatter plot of 2 columns in a DataFrame, taking labels as colours. """ plt.scatter(orig_df[colx], orig_df[coly], c=orig_df[label_col].values, cmap='viridis') plt.colorbar() plt.xlim(xmin, xmax) plt.ylim(ymin, ymax) plt.show() def visualise_dist(fframe=None, metric='euclidean'): """ Plot a distance matrix from a DataFrame containing only feature columns. The plot is a heatmap, and the distance metric is specified with `metric` """ plt.figure(figsize=(14, 10)) # ax = plt.gca() sns.heatmap(distmat(fframe, metric=metric)) plt.show()
Seiji-Armstrong/seipy
seipy/plots_/base.py
Python
mit
875
package ita8 // Constants var ( ClipboardPath = "clipboard" OpenPath = "open" )
yushi/ita8
ita8.go
GO
mit
88
module PettanrPublicDomainV01Licenses VERSION = "0.1.11" end
yasushiito/pettanr_pd_v01_licenses
lib/pettanr_public_domain_v01_licenses/version.rb
Ruby
mit
63
using System; using System.Collections.Generic; using System.ComponentModel; using System.Net.Http.Headers; namespace ContosoUniversity.WebApi.Areas.HelpPage { /// <summary> /// This is used to identify the place where the sample should be applied. /// </summary> public class HelpPageSampleKey { /// <summary> /// Creates a new <see cref="HelpPageSampleKey"/> based on media type. /// </summary> /// <param name="mediaType">The media type.</param> public HelpPageSampleKey(MediaTypeHeaderValue mediaType) { if (mediaType == null) { throw new ArgumentNullException("mediaType"); } ActionName = String.Empty; ControllerName = String.Empty; MediaType = mediaType; ParameterNames = new HashSet<string>(StringComparer.OrdinalIgnoreCase); } /// <summary> /// Creates a new <see cref="HelpPageSampleKey"/> based on media type and CLR type. /// </summary> /// <param name="mediaType">The media type.</param> /// <param name="type">The CLR type.</param> public HelpPageSampleKey(MediaTypeHeaderValue mediaType, Type type) : this(mediaType) { if (type == null) { throw new ArgumentNullException("type"); } ParameterType = type; } /// <summary> /// Creates a new <see cref="HelpPageSampleKey"/> based on <see cref="SampleDirection"/>, controller name, action name and parameter names. /// </summary> /// <param name="sampleDirection">The <see cref="SampleDirection"/>.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> /// <param name="parameterNames">The parameter names.</param> public HelpPageSampleKey(SampleDirection sampleDirection, string controllerName, string actionName, IEnumerable<string> parameterNames) { if (!Enum.IsDefined(typeof(SampleDirection), sampleDirection)) { throw new InvalidEnumArgumentException("sampleDirection", (int)sampleDirection, typeof(SampleDirection)); } if (controllerName == null) { throw new ArgumentNullException("controllerName"); } if (actionName == null) { throw new ArgumentNullException("actionName"); } if (parameterNames == null) { throw new ArgumentNullException("parameterNames"); } ControllerName = controllerName; ActionName = actionName; ParameterNames = new HashSet<string>(parameterNames, StringComparer.OrdinalIgnoreCase); SampleDirection = sampleDirection; } /// <summary> /// Creates a new <see cref="HelpPageSampleKey"/> based on media type, <see cref="SampleDirection"/>, controller name, action name and parameter names. /// </summary> /// <param name="mediaType">The media type.</param> /// <param name="sampleDirection">The <see cref="SampleDirection"/>.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> /// <param name="parameterNames">The parameter names.</param> public HelpPageSampleKey(MediaTypeHeaderValue mediaType, SampleDirection sampleDirection, string controllerName, string actionName, IEnumerable<string> parameterNames) : this(sampleDirection, controllerName, actionName, parameterNames) { if (mediaType == null) { throw new ArgumentNullException("mediaType"); } MediaType = mediaType; } /// <summary> /// Gets the name of the controller. /// </summary> /// <value> /// The name of the controller. /// </value> public string ControllerName { get; private set; } /// <summary> /// Gets the name of the action. /// </summary> /// <value> /// The name of the action. /// </value> public string ActionName { get; private set; } /// <summary> /// Gets the media type. /// </summary> /// <value> /// The media type. /// </value> public MediaTypeHeaderValue MediaType { get; private set; } /// <summary> /// Gets the parameter names. /// </summary> public HashSet<string> ParameterNames { get; private set; } public Type ParameterType { get; private set; } /// <summary> /// Gets the <see cref="SampleDirection"/>. /// </summary> public SampleDirection? SampleDirection { get; private set; } public override bool Equals(object obj) { HelpPageSampleKey otherKey = obj as HelpPageSampleKey; if (otherKey == null) { return false; } return String.Equals(ControllerName, otherKey.ControllerName, StringComparison.OrdinalIgnoreCase) && String.Equals(ActionName, otherKey.ActionName, StringComparison.OrdinalIgnoreCase) && (MediaType == otherKey.MediaType || (MediaType != null && MediaType.Equals(otherKey.MediaType))) && ParameterType == otherKey.ParameterType && SampleDirection == otherKey.SampleDirection && ParameterNames.SetEquals(otherKey.ParameterNames); } public override int GetHashCode() { int hashCode = ControllerName.ToUpperInvariant().GetHashCode() ^ ActionName.ToUpperInvariant().GetHashCode(); if (MediaType != null) { hashCode ^= MediaType.GetHashCode(); } if (SampleDirection != null) { hashCode ^= SampleDirection.GetHashCode(); } if (ParameterType != null) { hashCode ^= ParameterType.GetHashCode(); } foreach (string parameterName in ParameterNames) { hashCode ^= parameterName.ToUpperInvariant().GetHashCode(); } return hashCode; } } }
ChauThan/WebApi101
src/ContosoUniversity.WebApi/Areas/HelpPage/SampleGeneration/HelpPageSampleKey.cs
C#
mit
6,488
module ActiveRecord # = Active Record Autosave Association # # AutosaveAssociation is a module that takes care of automatically saving # associated records when their parent is saved. In addition to saving, it # also destroys any associated records that were marked for destruction. # (See #mark_for_destruction and #marked_for_destruction?). # # Saving of the parent, its associations, and the destruction of marked # associations, all happen inside a transaction. This should never leave the # database in an inconsistent state. # # If validations for any of the associations fail, their error messages will # be applied to the parent. # # Note that it also means that associations marked for destruction won't # be destroyed directly. They will however still be marked for destruction. # # Note that <tt>autosave: false</tt> is not same as not declaring <tt>:autosave</tt>. # When the <tt>:autosave</tt> option is not present then new association records are # saved but the updated association records are not saved. # # == Validation # # Child records are validated unless <tt>:validate</tt> is +false+. # # == Callbacks # # Association with autosave option defines several callbacks on your # model (before_save, after_create, after_update). Please note that # callbacks are executed in the order they were defined in # model. You should avoid modifying the association content, before # autosave callbacks are executed. Placing your callbacks after # associations is usually a good practice. # # === One-to-one Example # # class Post < ActiveRecord::Base # has_one :author, autosave: true # end # # Saving changes to the parent and its associated model can now be performed # automatically _and_ atomically: # # post = Post.find(1) # post.title # => "The current global position of migrating ducks" # post.author.name # => "alloy" # # post.title = "On the migration of ducks" # post.author.name = "Eloy Duran" # # post.save # post.reload # post.title # => "On the migration of ducks" # post.author.name # => "Eloy Duran" # # Destroying an associated model, as part of the parent's save action, is as # simple as marking it for destruction: # # post.author.mark_for_destruction # post.author.marked_for_destruction? # => true # # Note that the model is _not_ yet removed from the database: # # id = post.author.id # Author.find_by(id: id).nil? # => false # # post.save # post.reload.author # => nil # # Now it _is_ removed from the database: # # Author.find_by(id: id).nil? # => true # # === One-to-many Example # # When <tt>:autosave</tt> is not declared new children are saved when their parent is saved: # # class Post < ActiveRecord::Base # has_many :comments # :autosave option is not declared # end # # post = Post.new(title: 'ruby rocks') # post.comments.build(body: 'hello world') # post.save # => saves both post and comment # # post = Post.create(title: 'ruby rocks') # post.comments.build(body: 'hello world') # post.save # => saves both post and comment # # post = Post.create(title: 'ruby rocks') # post.comments.create(body: 'hello world') # post.save # => saves both post and comment # # When <tt>:autosave</tt> is true all children are saved, no matter whether they # are new records or not: # # class Post < ActiveRecord::Base # has_many :comments, autosave: true # end # # post = Post.create(title: 'ruby rocks') # post.comments.create(body: 'hello world') # post.comments[0].body = 'hi everyone' # post.comments.build(body: "good morning.") # post.title += "!" # post.save # => saves both post and comments. # # Destroying one of the associated models as part of the parent's save action # is as simple as marking it for destruction: # # post.comments # => [#<Comment id: 1, ...>, #<Comment id: 2, ...]> # post.comments[1].mark_for_destruction # post.comments[1].marked_for_destruction? # => true # post.comments.length # => 2 # # Note that the model is _not_ yet removed from the database: # # id = post.comments.last.id # Comment.find_by(id: id).nil? # => false # # post.save # post.reload.comments.length # => 1 # # Now it _is_ removed from the database: # # Comment.find_by(id: id).nil? # => true module AutosaveAssociation extend ActiveSupport::Concern module AssociationBuilderExtension #:nodoc: def self.build(model, reflection) model.send(:add_autosave_association_callbacks, reflection) end def self.valid_options [ :autosave ] end end included do Associations::Builder::Association.extensions << AssociationBuilderExtension mattr_accessor :index_nested_attribute_errors, instance_writer: false self.index_nested_attribute_errors = false end module ClassMethods # :nodoc: private def define_non_cyclic_method(name, &block) return if method_defined?(name) define_method(name) do |*args| result = true; @_already_called ||= {} # Loop prevention for validation of associations unless @_already_called[name] begin @_already_called[name] = true result = instance_eval(&block) ensure @_already_called[name] = false end end result end end # Adds validation and save callbacks for the association as specified by # the +reflection+. # # For performance reasons, we don't check whether to validate at runtime. # However the validation and callback methods are lazy and those methods # get created when they are invoked for the very first time. However, # this can change, for instance, when using nested attributes, which is # called _after_ the association has been defined. Since we don't want # the callbacks to get defined multiple times, there are guards that # check if the save or validation methods have already been defined # before actually defining them. def add_autosave_association_callbacks(reflection) save_method = :"autosave_associated_records_for_#{reflection.name}" if reflection.collection? before_save :before_save_collection_association define_non_cyclic_method(save_method) { save_collection_association(reflection) } # Doesn't use after_save as that would save associations added in after_create/after_update twice after_create save_method after_update save_method elsif reflection.has_one? define_method(save_method) { save_has_one_association(reflection) } unless method_defined?(save_method) # Configures two callbacks instead of a single after_save so that # the model may rely on their execution order relative to its # own callbacks. # # For example, given that after_creates run before after_saves, if # we configured instead an after_save there would be no way to fire # a custom after_create callback after the child association gets # created. after_create save_method after_update save_method else define_non_cyclic_method(save_method) { throw(:abort) if save_belongs_to_association(reflection) == false } before_save save_method end define_autosave_validation_callbacks(reflection) end def define_autosave_validation_callbacks(reflection) validation_method = :"validate_associated_records_for_#{reflection.name}" if reflection.validate? && !method_defined?(validation_method) if reflection.collection? method = :validate_collection_association else method = :validate_single_association end define_non_cyclic_method(validation_method) do send(method, reflection) # TODO: remove the following line as soon as the return value of # callbacks is ignored, that is, returning `false` does not # display a deprecation warning or halts the callback chain. true end validate validation_method after_validation :_ensure_no_duplicate_errors end end end # Reloads the attributes of the object as usual and clears <tt>marked_for_destruction</tt> flag. def reload(options = nil) @marked_for_destruction = false @destroyed_by_association = nil super end # Marks this record to be destroyed as part of the parent's save transaction. # This does _not_ actually destroy the record instantly, rather child record will be destroyed # when <tt>parent.save</tt> is called. # # Only useful if the <tt>:autosave</tt> option on the parent is enabled for this associated model. def mark_for_destruction @marked_for_destruction = true end # Returns whether or not this record will be destroyed as part of the parent's save transaction. # # Only useful if the <tt>:autosave</tt> option on the parent is enabled for this associated model. def marked_for_destruction? @marked_for_destruction end # Records the association that is being destroyed and destroying this # record in the process. def destroyed_by_association=(reflection) @destroyed_by_association = reflection end # Returns the association for the parent being destroyed. # # Used to avoid updating the counter cache unnecessarily. def destroyed_by_association @destroyed_by_association end # Returns whether or not this record has been changed in any way (including whether # any of its nested autosave associations are likewise changed) def changed_for_autosave? new_record? || has_changes_to_save? || marked_for_destruction? || nested_records_changed_for_autosave? end private # Returns the record for an association collection that should be validated # or saved. If +autosave+ is +false+ only new records will be returned, # unless the parent is/was a new record itself. def associated_records_to_validate_or_save(association, new_record, autosave) if new_record || autosave association && association.target else association.target.find_all(&:new_record?) end end # go through nested autosave associations that are loaded in memory (without loading # any new ones), and return true if is changed for autosave def nested_records_changed_for_autosave? @_nested_records_changed_for_autosave_already_called ||= false return false if @_nested_records_changed_for_autosave_already_called begin @_nested_records_changed_for_autosave_already_called = true self.class._reflections.values.any? do |reflection| if reflection.options[:autosave] association = association_instance_get(reflection.name) association && Array.wrap(association.target).any?(&:changed_for_autosave?) end end ensure @_nested_records_changed_for_autosave_already_called = false end end # Validate the association if <tt>:validate</tt> or <tt>:autosave</tt> is # turned on for the association. def validate_single_association(reflection) association = association_instance_get(reflection.name) record = association && association.reader association_valid?(reflection, record) if record end # Validate the associated records if <tt>:validate</tt> or # <tt>:autosave</tt> is turned on for the association specified by # +reflection+. def validate_collection_association(reflection) if association = association_instance_get(reflection.name) if records = associated_records_to_validate_or_save(association, new_record?, reflection.options[:autosave]) records.each_with_index { |record, index| association_valid?(reflection, record, index) } end end end # Returns whether or not the association is valid and applies any errors to # the parent, <tt>self</tt>, if it wasn't. Skips any <tt>:autosave</tt> # enabled records if they're marked_for_destruction? or destroyed. def association_valid?(reflection, record, index = nil) return true if record.destroyed? || (reflection.options[:autosave] && record.marked_for_destruction?) validation_context = self.validation_context unless [:create, :update].include?(self.validation_context) unless valid = record.valid?(validation_context) if reflection.options[:autosave] indexed_attribute = !index.nil? && (reflection.options[:index_errors] || ActiveRecord::Base.index_nested_attribute_errors) record.errors.each do |attribute, message| attribute = normalize_reflection_attribute(indexed_attribute, reflection, index, attribute) errors[attribute] << message errors[attribute].uniq! end record.errors.details.each_key do |attribute| reflection_attribute = normalize_reflection_attribute(indexed_attribute, reflection, index, attribute).to_sym record.errors.details[attribute].each do |error| errors.details[reflection_attribute] << error errors.details[reflection_attribute].uniq! end end else errors.add(reflection.name) end end valid end def normalize_reflection_attribute(indexed_attribute, reflection, index, attribute) if indexed_attribute "#{reflection.name}[#{index}].#{attribute}" else "#{reflection.name}.#{attribute}" end end # Is used as a before_save callback to check while saving a collection # association whether or not the parent was a new record before saving. def before_save_collection_association @new_record_before_save = new_record? true end # Saves any new associated records, or all loaded autosave associations if # <tt>:autosave</tt> is enabled on the association. # # In addition, it destroys all children that were marked for destruction # with #mark_for_destruction. # # This all happens inside a transaction, _if_ the Transactions module is included into # ActiveRecord::Base after the AutosaveAssociation module, which it does by default. def save_collection_association(reflection) if association = association_instance_get(reflection.name) autosave = reflection.options[:autosave] # reconstruct the scope now that we know the owner's id association.reset_scope if association.respond_to?(:reset_scope) if records = associated_records_to_validate_or_save(association, @new_record_before_save, autosave) if autosave records_to_destroy = records.select(&:marked_for_destruction?) records_to_destroy.each { |record| association.destroy(record) } records -= records_to_destroy end records.each do |record| next if record.destroyed? saved = true if autosave != false && (@new_record_before_save || record.new_record?) if autosave saved = association.insert_record(record, false) else association.insert_record(record) unless reflection.nested? end elsif autosave saved = record.save(validate: false) end raise ActiveRecord::Rollback unless saved end end end end # Saves the associated record if it's new or <tt>:autosave</tt> is enabled # on the association. # # In addition, it will destroy the association if it was marked for # destruction with #mark_for_destruction. # # This all happens inside a transaction, _if_ the Transactions module is included into # ActiveRecord::Base after the AutosaveAssociation module, which it does by default. def save_has_one_association(reflection) association = association_instance_get(reflection.name) record = association && association.load_target if record && !record.destroyed? autosave = reflection.options[:autosave] if autosave && record.marked_for_destruction? record.destroy elsif autosave != false key = reflection.options[:primary_key] ? send(reflection.options[:primary_key]) : id if (autosave && record.changed_for_autosave?) || new_record? || record_changed?(reflection, record, key) unless reflection.through_reflection record[reflection.foreign_key] = key end saved = record.save(validate: !autosave) raise ActiveRecord::Rollback if !saved && autosave saved end end end end # If the record is new or it has changed, returns true. def record_changed?(reflection, record, key) record.new_record? || (record.has_attribute?(reflection.foreign_key) && record[reflection.foreign_key] != key) || record.will_save_change_to_attribute?(reflection.foreign_key) end # Saves the associated record if it's new or <tt>:autosave</tt> is enabled. # # In addition, it will destroy the association if it was marked for destruction. def save_belongs_to_association(reflection) association = association_instance_get(reflection.name) return unless association && association.loaded? && !association.stale_target? record = association.load_target if record && !record.destroyed? autosave = reflection.options[:autosave] if autosave && record.marked_for_destruction? self[reflection.foreign_key] = nil record.destroy elsif autosave != false saved = record.save(validate: !autosave) if record.new_record? || (autosave && record.changed_for_autosave?) if association.updated? association_id = record.send(reflection.options[:primary_key] || :id) self[reflection.foreign_key] = association_id association.loaded! end saved if autosave end end end def _ensure_no_duplicate_errors errors.messages.each_key do |attribute| errors[attribute].uniq! end end end end
tijwelch/rails
activerecord/lib/active_record/autosave_association.rb
Ruby
mit
19,240
/** * clientCacheProvider **/ angular.module('providers') .provider('clientCacheProvider', function ClientCacheProvider($state, clientCacheService) { console.log(clientCacheService) console.log(clientCacheService.logout()); var forceLogin = false; this.forceLogin = function(clientCacheService) { forceLogin = clientCacheService.logout(); $state.go('/login'); } });
evoila/cf-spring-web-management-console
frontend/app/js/providers/general/clientCacheProvider.js
JavaScript
mit
407
<!-- Main Header --> <header class="main-header"> <!-- Logo --> <a href="/admin" class="logo"> <!-- mini logo for sidebar mini 50x50 pixels --> <span class="logo-mini"><b>C</b>MS</span> <!-- logo for regular state and mobile devices --> <span class="logo-lg"><b>The</b>CMS</span> </a> <!-- Header Navbar --> <nav class="navbar navbar-static-top" role="navigation"> <!-- Sidebar toggle button--> <a href="#" class="sidebar-toggle" data-toggle="offcanvas" role="button"> <span class="sr-only">Toggle navigation</span> </a> <!-- Navbar Right Menu --> <div class="navbar-custom-menu"> <ul class="nav navbar-nav"> <!-- Messages: style can be found in dropdown.less--> <? if($tcadmin_config['has_feedbacks']):?> <li class="dropdown messages-menu"> <!-- Menu toggle button --> <a href="#" class="dropdown-toggle" data-toggle="dropdown"> <i class="fa fa-envelope-o"></i> <span class="label label-success"><?= $unread_feedback_count; ?></span> </a> <ul class="dropdown-menu"> <li class="header">У вас <?= $unread_feedback_count; ?> не прочитанных отзыва</li> <? if(count($unread_feedbacks) > 0): ?> <li> <ul class="menu"> <? foreach($unread_feedbacks as $model): ?> <li><!-- start message --> <a href="/admin/feedback/view/<?= $model->id; ?>"> <h4> <?= $model->user_name;?> <small><i class="fa fa-clock-o"></i> <?= Date::forge($model->created_at)->format("%d/%m/%Y %H:%M"); ?></small> </h4> <!-- The message --> <p><?= Fuel\Core\Str::truncate($model->text, 50, '...'); ?></p> </a> </li><!-- end message --> <? endforeach; ?> </ul><!-- /.menu --> </li> <li class="footer"><a href="/admin/feedback/index">Смотреть все</a></li> <? endif; ?> </ul> </li><!-- /.messages-menu --> <? endif; ?> <!-- Notifications Menu --> <!--<li class="dropdown notifications-menu"> <a href="#" class="dropdown-toggle" data-toggle="dropdown"> <i class="fa fa-bell-o"></i> <span class="label label-warning">10</span> </a> <ul class="dropdown-menu"> <li class="header">You have 10 notifications</li> <li> <ul class="menu"> <li> <a href="#"> <i class="fa fa-users text-aqua"></i> 5 new members joined today </a> </li> </ul> </li> <li class="footer"><a href="#">View all</a></li> </ul> </li> <li class="dropdown tasks-menu"> <a href="#" class="dropdown-toggle" data-toggle="dropdown"> <i class="fa fa-flag-o"></i> <span class="label label-danger">9</span> </a> <ul class="dropdown-menu"> <li class="header">You have 9 tasks</li> <li> <ul class="menu"> <li> <a href="#"> <h3> Design some buttons <small class="pull-right">20%</small> </h3> <div class="progress xs"> <div class="progress-bar progress-bar-aqua" style="width: 20%" role="progressbar" aria-valuenow="20" aria-valuemin="0" aria-valuemax="100"> <span class="sr-only">20% Complete</span> </div> </div> </a> </li> </ul> </li> <li class="footer"> <a href="#">View all tasks</a> </li> </ul> </li>--> <!-- User Account Menu --> <li class="dropdown user user-menu"> <!-- Menu Toggle Button --> <a href="#" class="dropdown-toggle" data-toggle="dropdown"> <!-- The user image in the navbar--> <img src="/assets/img/aninimus.jpg" class="user-image" alt="User Image"> <!-- hidden-xs hides the username on small devices so only the image appears. --> <span class="hidden-xs"><?= Auth::get('username'); ?></span> </a> <ul class="dropdown-menu"> <!-- The user image in the menu --> <li class="user-header"> <img src="/assets/img/aninimus.jpg" class="img-circle" alt="User Image"> <p> <?= Auth::get('username'); ?> - Administrator <small>Member since <?= Date::forge(Auth::get('created_at'))->format("%d/%m/%Y"); ?></small> </p> </li> <!-- Menu Body --> <!--<li class="user-body"> <div class="col-xs-4 text-center"> <a href="#">Followers</a> </div> <div class="col-xs-4 text-center"> <a href="#">Sales</a> </div> <div class="col-xs-4 text-center"> <a href="#">Friends</a> </div> </li>--> <!-- Menu Footer--> <li class="user-footer"> <div class="pull-left"> <!--<a href="#" class="btn btn-default btn-flat">Profile</a>--> </div> <div class="pull-right"> <a href="/admin/auth/logout" class="btn btn-default btn-flat">Sign out</a> </div> </li> </ul> </li> <!-- Control Sidebar Toggle Button --> <!-- <li> <a href="#" data-toggle="control-sidebar"><i class="fa fa-gears"></i></a> </li>--> </ul> </div> </nav> </header>
SergeyOlifir/The-CMS-2.0
fuel/app/views/admin/main/header.php
PHP
mit
6,499
/* tslint:disable */ /* eslint-disable */ // @ts-nocheck import { ReaderFragment } from "relay-runtime"; import { FragmentRefs } from "relay-runtime"; export type ArtworkFilterArtworkGrid_filtered_artworks = { readonly id: string; readonly pageInfo: { readonly hasNextPage: boolean; readonly endCursor: string | null; }; readonly pageCursors: { readonly " $fragmentRefs": FragmentRefs<"Pagination_pageCursors">; }; readonly edges: ReadonlyArray<{ readonly node: { readonly id: string; } | null; } | null> | null; readonly " $fragmentRefs": FragmentRefs<"ArtworkGrid_artworks">; readonly " $refType": "ArtworkFilterArtworkGrid_filtered_artworks"; }; export type ArtworkFilterArtworkGrid_filtered_artworks$data = ArtworkFilterArtworkGrid_filtered_artworks; export type ArtworkFilterArtworkGrid_filtered_artworks$key = { readonly " $data"?: ArtworkFilterArtworkGrid_filtered_artworks$data; readonly " $fragmentRefs": FragmentRefs<"ArtworkFilterArtworkGrid_filtered_artworks">; }; const node: ReaderFragment = (function(){ var v0 = { "alias": null, "args": null, "kind": "ScalarField", "name": "id", "storageKey": null }; return { "argumentDefinitions": [], "kind": "Fragment", "metadata": null, "name": "ArtworkFilterArtworkGrid_filtered_artworks", "selections": [ (v0/*: any*/), { "alias": null, "args": null, "concreteType": "PageInfo", "kind": "LinkedField", "name": "pageInfo", "plural": false, "selections": [ { "alias": null, "args": null, "kind": "ScalarField", "name": "hasNextPage", "storageKey": null }, { "alias": null, "args": null, "kind": "ScalarField", "name": "endCursor", "storageKey": null } ], "storageKey": null }, { "alias": null, "args": null, "concreteType": "PageCursors", "kind": "LinkedField", "name": "pageCursors", "plural": false, "selections": [ { "args": null, "kind": "FragmentSpread", "name": "Pagination_pageCursors" } ], "storageKey": null }, { "alias": null, "args": null, "concreteType": "FilterArtworksEdge", "kind": "LinkedField", "name": "edges", "plural": true, "selections": [ { "alias": null, "args": null, "concreteType": "Artwork", "kind": "LinkedField", "name": "node", "plural": false, "selections": [ (v0/*: any*/) ], "storageKey": null } ], "storageKey": null }, { "args": null, "kind": "FragmentSpread", "name": "ArtworkGrid_artworks" } ], "type": "FilterArtworksConnection", "abstractKey": null }; })(); (node as any).hash = '04cd49aefae4484840f678821ea905e1'; export default node;
artsy/force
src/v2/__generated__/ArtworkFilterArtworkGrid_filtered_artworks.graphql.ts
TypeScript
mit
3,068
# encoding: utf-8 # Code generated by Microsoft (R) AutoRest Code Generator. # Changes may cause incorrect behavior and will be lost if the code is # regenerated. module Azure::CDN::Mgmt::V2020_09_01 module Models # # Result of the request to list endpoints. It contains a list of endpoint # objects and a URL link to get the next set of results. # class AFDEndpointListResult include MsRestAzure include MsRest::JSONable # @return [Array<AFDEndpoint>] List of AzureFrontDoor endpoints within a # profile attr_accessor :value # @return [String] URL to get the next set of endpoint objects if there # is any. attr_accessor :next_link # return [Proc] with next page method call. attr_accessor :next_method # # Gets the rest of the items for the request, enabling auto-pagination. # # @return [Array<AFDEndpoint>] operation results. # def get_all_items items = @value page = self while page.next_link != nil && !page.next_link.strip.empty? do page = page.get_next_page items.concat(page.value) end items end # # Gets the next page of results. # # @return [AFDEndpointListResult] with next page content. # def get_next_page response = @next_method.call(@next_link).value! unless @next_method.nil? unless response.nil? @next_link = response.body.next_link @value = response.body.value self end end # # Mapper for AFDEndpointListResult class as Ruby Hash. # This will be used for serialization/deserialization. # def self.mapper() { client_side_validation: true, required: false, serialized_name: 'AFDEndpointListResult', type: { name: 'Composite', class_name: 'AFDEndpointListResult', model_properties: { value: { client_side_validation: true, required: false, read_only: true, serialized_name: 'value', type: { name: 'Sequence', element: { client_side_validation: true, required: false, serialized_name: 'AFDEndpointElementType', type: { name: 'Composite', class_name: 'AFDEndpoint' } } } }, next_link: { client_side_validation: true, required: false, serialized_name: 'nextLink', type: { name: 'String' } } } } } end end end end
Azure/azure-sdk-for-ruby
management/azure_mgmt_cdn/lib/2020-09-01/generated/azure_mgmt_cdn/models/afdendpoint_list_result.rb
Ruby
mit
2,932
/* eslint react/no-multi-comp:0, no-console:0 */ import { createForm } from 'rc-form'; import React, { PropTypes } from 'react'; import ReactDOM from 'react-dom'; import { regionStyle, errorStyle } from './styles'; let Form = React.createClass({ propTypes: { form: PropTypes.object, }, setEmail() { this.props.form.setFieldsValue({ email: 'yiminghe@gmail.com', }); }, render() { const { getFieldProps, getFieldError } = this.props.form; const errors = getFieldError('email'); return (<div style={ regionStyle }> <div>email:</div> <div> <input {...getFieldProps('email', { rules: [{ type: 'email', }], })} /> </div> <div style={errorStyle}> {(errors) ? errors.join(',') : null} </div> <button onClick={this.setEmail}>set</button> </div>); }, }); Form = createForm()(Form); class App extends React.Component { render() { return (<div> <h2>setFieldsValue</h2> <Form /> </div>); } } ReactDOM.render(<App />, document.getElementById('__react-content'));
setState/form
examples/setFieldsValue.js
JavaScript
mit
1,127
package de.hawhamburg.vs.wise15.superteam.client.worker; import de.hawhamburg.vs.wise15.superteam.client.PlayerServiceFacade; import de.hawhamburg.vs.wise15.superteam.client.callback.CallbackA; import de.hawhamburg.vs.wise15.superteam.client.model.Command; import javax.swing.*; import java.io.IOException; import java.util.List; import java.util.Map; /** * Created by florian on 09.01.16. */ public class CommandListener implements Runnable { private final PlayerServiceFacade facade; private final Map<String, List<CallbackA<String>>> listenerMap; public CommandListener(PlayerServiceFacade facade, Map<String, List<CallbackA<String>>> ListenerMap) { this.facade = facade; listenerMap = ListenerMap; } @Override public void run() { while (facade.isConnected()) { Command command = null; try { command = facade.getCommand(); } catch (IOException e) { e.printStackTrace(); } if (listenerMap.containsKey(command.getCommand())) { for (CallbackA<String> callback : listenerMap.get(command.getCommand())) { final Command finalCommand = command; SwingUtilities.invokeLater(() -> callback.callback(finalCommand.getContent())); } } } } }
flbaue/vs-wise15
client/src/main/java/de/hawhamburg/vs/wise15/superteam/client/worker/CommandListener.java
Java
mit
1,377
''' Created on Jan 30, 2011 @author: snail ''' import logging import logging.handlers import os import sys from os.path import join from os import getcwd from logging import DEBUG, INFO, WARNING, ERROR, CRITICAL from pickle import dumps LogPath = "Logs" #ensure the logging path exists. try: from os import mkdir mkdir(join(getcwd(), LogPath)) del mkdir except: pass def currentframe(): """Return the frame object for the caller's stack frame.""" try: raise Exception except: return sys.exc_info()[2].tb_frame.f_back def CreateLogger(name, level=None): l = logging.getLogger(name) l.setLevel(DEBUG) if level != None: l.setLevel(level) handler = logging.handlers.RotatingFileHandler(join( LogPath, "%s.log" % name), maxBytes=10240, backupCount=10) formatter = logging.Formatter("%(asctime)s|%(thread)d|%(levelno)s|%(module)s:%(funcName)s:%(lineno)d|%(message)s") handler.setFormatter(formatter) l.addHandler(handler) return l class LogFile: def __init__(self, output, minLevel=WARNING): self.minLevel = minLevel self._log = CreateLogger(output) self._log.findCaller = self.findCaller def findCaller(self): """ Find the stack frame of the caller so that we can note the source file name, line number and function name. """ f = currentframe() if f is not None: f = f.f_back rv = "(unknown file)", 0, "(unknown function)" i = 5 while hasattr(f, "f_code") and i > 0: i = i - 1 co = f.f_code rv = (co.co_filename, f.f_lineno, co.co_name) f = f.f_back return rv def debug(self, *vals, **kws): self.log(DEBUG, *vals, **kws) def note(self, *vals, **kws): self.log(INFO, *vals, **kws) def info(self, *vals, **kws): self.log(INFO, *vals, **kws) def warning(self, *vals, **kws): self.log(WARNING, *vals, **kws) def error(self, *vals, **kws): self.log(ERROR, *vals, **kws) def critical(self, *vals, **kws): self.log(CRITICAL, *vals, **kws) def dict(self, d, *vals): if d: lines = map(lambda (x, y): str(x) + " => " + str(y), d.items()) else: lines = ["None"] lines+=vals self.log(DEBUG, *lines) def exception(self, *vals): lines = list(vals) import sys import traceback tb = sys.exc_info() tbLines = (traceback.format_exception(*tb)) for l in tbLines: lines += l[:-1].split("\n") self.log(ERROR,*lines) global ExceptionLog ExceptionLog.log(ERROR,*lines) def log(self, level, *vals, **kws): self._log.log(level, "\t".join(map(str, vals))) ExceptionLog = LogFile("Exceptions") if __name__ == "__main__": import threading import time import random class Worker(threading.Thread): log = None def run(self): for i in range(20): time.sleep(random.random() * .1) if self.log: self.foo() self.log.debug("Exception time!") try: self.bar() except: self.log.exception("Exception while doing math!") def bar(self): i = 1 / 0 def foo(self): self.log.warning(i, "abc", "123") logger = LogFile("test") for i in range(20): w = Worker() w.log = logger w.start() logger.dict({"a":"a","foo":"bar",1:[1]})
theepicsnail/SuperBot2
Logging.py
Python
mit
3,658
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ import 'vs/css!./quickInput'; import { Component } from 'vs/workbench/common/component'; import { IQuickInputService, IQuickPickItem, IPickOptions, IInputOptions, IQuickNavigateConfiguration, IQuickPick, IQuickInput, IQuickInputButton, IInputBox, IQuickPickItemButtonEvent, QuickPickInput, IQuickPickSeparator, IKeyMods } from 'vs/platform/quickinput/common/quickInput'; import { IPartService } from 'vs/workbench/services/part/common/partService'; import * as dom from 'vs/base/browser/dom'; import { IInstantiationService } from 'vs/platform/instantiation/common/instantiation'; import { IThemeService } from 'vs/platform/theme/common/themeService'; import { contrastBorder, widgetShadow } from 'vs/platform/theme/common/colorRegistry'; import { SIDE_BAR_BACKGROUND, SIDE_BAR_FOREGROUND } from 'vs/workbench/common/theme'; import { IQuickOpenService } from 'vs/platform/quickOpen/common/quickOpen'; import { CancellationToken } from 'vs/base/common/cancellation'; import { QuickInputList } from './quickInputList'; import { QuickInputBox } from './quickInputBox'; import { KeyCode } from 'vs/base/common/keyCodes'; import { StandardKeyboardEvent } from 'vs/base/browser/keyboardEvent'; import { localize } from 'vs/nls'; import { IConfigurationService } from 'vs/platform/configuration/common/configuration'; import { CLOSE_ON_FOCUS_LOST_CONFIG } from 'vs/workbench/browser/quickopen'; import { CountBadge } from 'vs/base/browser/ui/countBadge/countBadge'; import { attachBadgeStyler, attachProgressBarStyler, attachButtonStyler } from 'vs/platform/theme/common/styler'; import { IEnvironmentService } from 'vs/platform/environment/common/environment'; import { ProgressBar } from 'vs/base/browser/ui/progressbar/progressbar'; import { debounceEvent, Emitter, Event } from 'vs/base/common/event'; import { Button } from 'vs/base/browser/ui/button/button'; import { dispose, IDisposable } from 'vs/base/common/lifecycle'; import Severity from 'vs/base/common/severity'; import { IEditorGroupsService } from 'vs/workbench/services/group/common/editorGroupsService'; import { IContextKeyService, RawContextKey, IContextKey } from 'vs/platform/contextkey/common/contextkey'; import { ICommandAndKeybindingRule, KeybindingWeight } from 'vs/platform/keybinding/common/keybindingsRegistry'; import { inQuickOpenContext } from 'vs/workbench/browser/parts/quickopen/quickopen'; import { ActionBar, ActionItem } from 'vs/base/browser/ui/actionbar/actionbar'; import { Action } from 'vs/base/common/actions'; import { URI } from 'vs/base/common/uri'; import { IKeybindingService } from 'vs/platform/keybinding/common/keybinding'; import { equals } from 'vs/base/common/arrays'; import { TimeoutTimer } from 'vs/base/common/async'; import { getIconClass } from 'vs/workbench/browser/parts/quickinput/quickInputUtils'; import { AccessibilitySupport } from 'vs/base/common/platform'; import * as browser from 'vs/base/browser/browser'; import { IEditorOptions } from 'vs/editor/common/config/editorOptions'; import { IStorageService } from 'vs/platform/storage/common/storage'; const $ = dom.$; type Writeable<T> = { -readonly [P in keyof T]: T[P] }; const backButton = { iconPath: { dark: URI.parse(require.toUrl('vs/workbench/browser/parts/quickinput/media/dark/arrow-left.svg')), light: URI.parse(require.toUrl('vs/workbench/browser/parts/quickinput/media/light/arrow-left.svg')) }, tooltip: localize('quickInput.back', "Back"), handle: -1 // TODO }; interface QuickInputUI { container: HTMLElement; leftActionBar: ActionBar; title: HTMLElement; rightActionBar: ActionBar; checkAll: HTMLInputElement; inputBox: QuickInputBox; visibleCount: CountBadge; count: CountBadge; message: HTMLElement; progressBar: ProgressBar; list: QuickInputList; onDidAccept: Event<void>; onDidTriggerButton: Event<IQuickInputButton>; ignoreFocusOut: boolean; keyMods: Writeable<IKeyMods>; isScreenReaderOptimized(): boolean; show(controller: QuickInput): void; setVisibilities(visibilities: Visibilities): void; setComboboxAccessibility(enabled: boolean): void; setEnabled(enabled: boolean): void; setContextKey(contextKey?: string): void; hide(): void; } type Visibilities = { title?: boolean; checkAll?: boolean; inputBox?: boolean; visibleCount?: boolean; count?: boolean; message?: boolean; list?: boolean; ok?: boolean; }; class QuickInput implements IQuickInput { private _title: string; private _steps: number; private _totalSteps: number; protected visible = false; private _enabled = true; private _contextKey: string; private _busy = false; private _ignoreFocusOut = false; private _buttons: IQuickInputButton[] = []; private buttonsUpdated = false; private onDidTriggerButtonEmitter = new Emitter<IQuickInputButton>(); private onDidHideEmitter = new Emitter<void>(); protected visibleDisposables: IDisposable[] = []; protected disposables: IDisposable[] = [ this.onDidTriggerButtonEmitter, this.onDidHideEmitter, ]; private busyDelay: TimeoutTimer; constructor(protected ui: QuickInputUI) { } get title() { return this._title; } set title(title: string) { this._title = title; this.update(); } get step() { return this._steps; } set step(step: number) { this._steps = step; this.update(); } get totalSteps() { return this._totalSteps; } set totalSteps(totalSteps: number) { this._totalSteps = totalSteps; this.update(); } get enabled() { return this._enabled; } set enabled(enabled: boolean) { this._enabled = enabled; this.update(); } get contextKey() { return this._contextKey; } set contextKey(contextKey: string) { this._contextKey = contextKey; this.update(); } get busy() { return this._busy; } set busy(busy: boolean) { this._busy = busy; this.update(); } get ignoreFocusOut() { return this._ignoreFocusOut; } set ignoreFocusOut(ignoreFocusOut: boolean) { this._ignoreFocusOut = ignoreFocusOut; this.update(); } get buttons() { return this._buttons; } set buttons(buttons: IQuickInputButton[]) { this._buttons = buttons; this.buttonsUpdated = true; this.update(); } onDidTriggerButton = this.onDidTriggerButtonEmitter.event; show(): void { if (this.visible) { return; } this.visibleDisposables.push( this.ui.onDidTriggerButton(button => { if (this.buttons.indexOf(button) !== -1) { this.onDidTriggerButtonEmitter.fire(button); } }), ); this.ui.show(this); this.visible = true; this.update(); } hide(): void { if (!this.visible) { return; } this.ui.hide(); } didHide(): void { this.visible = false; this.visibleDisposables = dispose(this.visibleDisposables); this.onDidHideEmitter.fire(); } onDidHide = this.onDidHideEmitter.event; protected update() { if (!this.visible) { return; } const title = this.getTitle(); if (this.ui.title.textContent !== title) { this.ui.title.textContent = title; } if (this.busy && !this.busyDelay) { this.busyDelay = new TimeoutTimer(); this.busyDelay.setIfNotSet(() => { if (this.visible) { this.ui.progressBar.infinite(); } }, 800); } if (!this.busy && this.busyDelay) { this.ui.progressBar.stop(); this.busyDelay.cancel(); this.busyDelay = null; } if (this.buttonsUpdated) { this.buttonsUpdated = false; this.ui.leftActionBar.clear(); const leftButtons = this.buttons.filter(button => button === backButton); this.ui.leftActionBar.push(leftButtons.map((button, index) => { const action = new Action(`id-${index}`, '', button.iconClass || getIconClass(button.iconPath), true, () => this.onDidTriggerButtonEmitter.fire(button)); action.tooltip = button.tooltip; return action; }), { icon: true, label: false }); this.ui.rightActionBar.clear(); const rightButtons = this.buttons.filter(button => button !== backButton); this.ui.rightActionBar.push(rightButtons.map((button, index) => { const action = new Action(`id-${index}`, '', button.iconClass || getIconClass(button.iconPath), true, () => this.onDidTriggerButtonEmitter.fire(button)); action.tooltip = button.tooltip; return action; }), { icon: true, label: false }); } this.ui.ignoreFocusOut = this.ignoreFocusOut; this.ui.setEnabled(this.enabled); this.ui.setContextKey(this.contextKey); } private getTitle() { if (this.title && this.step) { return `${this.title} (${this.getSteps()})`; } if (this.title) { return this.title; } if (this.step) { return this.getSteps(); } return ''; } private getSteps() { if (this.step && this.totalSteps) { return localize('quickInput.steps', "{0}/{1}", this.step, this.totalSteps); } if (this.step) { return String(this.step); } return ''; } public dispose(): void { this.hide(); this.disposables = dispose(this.disposables); } } class QuickPick<T extends IQuickPickItem> extends QuickInput implements IQuickPick<T> { private static INPUT_BOX_ARIA_LABEL = localize('quickInputBox.ariaLabel', "Type to narrow down results."); private _value = ''; private _placeholder; private onDidChangeValueEmitter = new Emitter<string>(); private onDidAcceptEmitter = new Emitter<string>(); private _items: (T | IQuickPickSeparator)[] = []; private itemsUpdated = false; private _canSelectMany = false; private _matchOnDescription = false; private _matchOnDetail = false; private _activeItems: T[] = []; private activeItemsUpdated = false; private activeItemsToConfirm: T[] = []; private onDidChangeActiveEmitter = new Emitter<T[]>(); private _selectedItems: T[] = []; private selectedItemsUpdated = false; private selectedItemsToConfirm: T[] = []; private onDidChangeSelectionEmitter = new Emitter<T[]>(); private onDidTriggerItemButtonEmitter = new Emitter<IQuickPickItemButtonEvent<T>>(); quickNavigate: IQuickNavigateConfiguration; constructor(ui: QuickInputUI) { super(ui); this.disposables.push( this.onDidChangeValueEmitter, this.onDidAcceptEmitter, this.onDidChangeActiveEmitter, this.onDidChangeSelectionEmitter, this.onDidTriggerItemButtonEmitter, ); } get value() { return this._value; } set value(value: string) { this._value = value || ''; this.update(); } get placeholder() { return this._placeholder; } set placeholder(placeholder: string) { this._placeholder = placeholder; this.update(); } onDidChangeValue = this.onDidChangeValueEmitter.event; onDidAccept = this.onDidAcceptEmitter.event; get items() { return this._items; } set items(items: (T | IQuickPickSeparator)[]) { this._items = items; this.itemsUpdated = true; this.update(); } get canSelectMany() { return this._canSelectMany; } set canSelectMany(canSelectMany: boolean) { this._canSelectMany = canSelectMany; this.update(); } get matchOnDescription() { return this._matchOnDescription; } set matchOnDescription(matchOnDescription: boolean) { this._matchOnDescription = matchOnDescription; this.update(); } get matchOnDetail() { return this._matchOnDetail; } set matchOnDetail(matchOnDetail: boolean) { this._matchOnDetail = matchOnDetail; this.update(); } get activeItems() { return this._activeItems; } set activeItems(activeItems: T[]) { this._activeItems = activeItems; this.activeItemsUpdated = true; this.update(); } onDidChangeActive = this.onDidChangeActiveEmitter.event; get selectedItems() { return this._selectedItems; } set selectedItems(selectedItems: T[]) { this._selectedItems = selectedItems; this.selectedItemsUpdated = true; this.update(); } get keyMods() { return this.ui.keyMods; } onDidChangeSelection = this.onDidChangeSelectionEmitter.event; onDidTriggerItemButton = this.onDidTriggerItemButtonEmitter.event; show() { if (!this.visible) { this.visibleDisposables.push( this.ui.inputBox.onDidChange(value => { if (value === this.value) { return; } this._value = value; this.ui.list.filter(this.ui.inputBox.value); if (!this.ui.isScreenReaderOptimized() && !this.canSelectMany) { this.ui.list.focus('First'); } this.onDidChangeValueEmitter.fire(value); }), this.ui.inputBox.onKeyDown(event => { switch (event.keyCode) { case KeyCode.DownArrow: this.ui.list.focus('Next'); if (this.canSelectMany) { this.ui.list.domFocus(); } break; case KeyCode.UpArrow: if (this.ui.list.getFocusedElements().length) { this.ui.list.focus('Previous'); } else { this.ui.list.focus('Last'); } if (this.canSelectMany) { this.ui.list.domFocus(); } break; case KeyCode.PageDown: if (this.ui.list.getFocusedElements().length) { this.ui.list.focus('NextPage'); } else { this.ui.list.focus('First'); } if (this.canSelectMany) { this.ui.list.domFocus(); } break; case KeyCode.PageUp: if (this.ui.list.getFocusedElements().length) { this.ui.list.focus('PreviousPage'); } else { this.ui.list.focus('Last'); } if (this.canSelectMany) { this.ui.list.domFocus(); } break; } }), this.ui.onDidAccept(() => { if (!this.canSelectMany && this.activeItems[0]) { this._selectedItems = [this.activeItems[0]]; this.onDidChangeSelectionEmitter.fire(this.selectedItems); } this.onDidAcceptEmitter.fire(); }), this.ui.list.onDidChangeFocus(focusedItems => { if (this.activeItemsUpdated) { return; // Expect another event. } if (this.activeItemsToConfirm !== this._activeItems && equals(focusedItems, this._activeItems, (a, b) => a === b)) { return; } this._activeItems = focusedItems as T[]; this.onDidChangeActiveEmitter.fire(focusedItems as T[]); }), this.ui.list.onDidChangeSelection(selectedItems => { if (this.canSelectMany) { if (selectedItems.length) { this.ui.list.setSelectedElements([]); } return; } if (this.selectedItemsToConfirm !== this._selectedItems && equals(selectedItems, this._selectedItems, (a, b) => a === b)) { return; } this._selectedItems = selectedItems as T[]; this.onDidChangeSelectionEmitter.fire(selectedItems as T[]); if (selectedItems.length) { this.onDidAcceptEmitter.fire(); } }), this.ui.list.onChangedCheckedElements(checkedItems => { if (!this.canSelectMany) { return; } if (this.selectedItemsToConfirm !== this._selectedItems && equals(checkedItems, this._selectedItems, (a, b) => a === b)) { return; } this._selectedItems = checkedItems as T[]; this.onDidChangeSelectionEmitter.fire(checkedItems as T[]); }), this.ui.list.onButtonTriggered(event => this.onDidTriggerItemButtonEmitter.fire(event as IQuickPickItemButtonEvent<T>)), this.registerQuickNavigation() ); } super.show(); // TODO: Why have show() bubble up while update() trickles down? (Could move setComboboxAccessibility() here.) } private registerQuickNavigation() { return dom.addDisposableListener(this.ui.container, dom.EventType.KEY_UP, (e: KeyboardEvent) => { if (this.canSelectMany || !this.quickNavigate) { return; } const keyboardEvent: StandardKeyboardEvent = new StandardKeyboardEvent(e as KeyboardEvent); const keyCode = keyboardEvent.keyCode; // Select element when keys are pressed that signal it const quickNavKeys = this.quickNavigate.keybindings; const wasTriggerKeyPressed = keyCode === KeyCode.Enter || quickNavKeys.some(k => { const [firstPart, chordPart] = k.getParts(); if (chordPart) { return false; } if (firstPart.shiftKey && keyCode === KeyCode.Shift) { if (keyboardEvent.ctrlKey || keyboardEvent.altKey || keyboardEvent.metaKey) { return false; // this is an optimistic check for the shift key being used to navigate back in quick open } return true; } if (firstPart.altKey && keyCode === KeyCode.Alt) { return true; } if (firstPart.ctrlKey && keyCode === KeyCode.Ctrl) { return true; } if (firstPart.metaKey && keyCode === KeyCode.Meta) { return true; } return false; }); if (wasTriggerKeyPressed && this.activeItems[0]) { this._selectedItems = [this.activeItems[0]]; this.onDidChangeSelectionEmitter.fire(this.selectedItems); this.onDidAcceptEmitter.fire(); } }); } protected update() { super.update(); if (!this.visible) { return; } if (this.ui.inputBox.value !== this.value) { this.ui.inputBox.value = this.value; } if (this.ui.inputBox.placeholder !== (this.placeholder || '')) { this.ui.inputBox.placeholder = (this.placeholder || ''); } if (this.itemsUpdated) { this.itemsUpdated = false; this.ui.list.setElements(this.items); this.ui.list.filter(this.ui.inputBox.value); this.ui.checkAll.checked = this.ui.list.getAllVisibleChecked(); this.ui.visibleCount.setCount(this.ui.list.getVisibleCount()); this.ui.count.setCount(this.ui.list.getCheckedCount()); if (!this.ui.isScreenReaderOptimized() && !this.canSelectMany) { this.ui.list.focus('First'); } } if (this.ui.container.classList.contains('show-checkboxes') !== !!this.canSelectMany) { if (this.canSelectMany) { this.ui.list.clearFocus(); } else if (!this.ui.isScreenReaderOptimized()) { this.ui.list.focus('First'); } } if (this.activeItemsUpdated) { this.activeItemsUpdated = false; this.activeItemsToConfirm = this._activeItems; this.ui.list.setFocusedElements(this.activeItems); if (this.activeItemsToConfirm === this._activeItems) { this.activeItemsToConfirm = null; } } if (this.selectedItemsUpdated) { this.selectedItemsUpdated = false; this.selectedItemsToConfirm = this._selectedItems; if (this.canSelectMany) { this.ui.list.setCheckedElements(this.selectedItems); } else { this.ui.list.setSelectedElements(this.selectedItems); } if (this.selectedItemsToConfirm === this._selectedItems) { this.selectedItemsToConfirm = null; } } this.ui.list.matchOnDescription = this.matchOnDescription; this.ui.list.matchOnDetail = this.matchOnDetail; this.ui.setComboboxAccessibility(true); this.ui.inputBox.setAttribute('aria-label', QuickPick.INPUT_BOX_ARIA_LABEL); this.ui.setVisibilities(this.canSelectMany ? { title: !!this.title || !!this.step, checkAll: true, inputBox: true, visibleCount: true, count: true, ok: true, list: true } : { title: !!this.title || !!this.step, inputBox: true, visibleCount: true, list: true }); } } class InputBox extends QuickInput implements IInputBox { private static noPromptMessage = localize('inputModeEntry', "Press 'Enter' to confirm your input or 'Escape' to cancel"); private _value = ''; private _valueSelection: Readonly<[number, number]>; private valueSelectionUpdated = true; private _placeholder: string; private _password = false; private _prompt: string; private noValidationMessage = InputBox.noPromptMessage; private _validationMessage: string; private onDidValueChangeEmitter = new Emitter<string>(); private onDidAcceptEmitter = new Emitter<string>(); constructor(ui: QuickInputUI) { super(ui); this.disposables.push( this.onDidValueChangeEmitter, this.onDidAcceptEmitter, ); } get value() { return this._value; } set value(value: string) { this._value = value || ''; this.update(); } set valueSelection(valueSelection: Readonly<[number, number]>) { this._valueSelection = valueSelection; this.valueSelectionUpdated = true; this.update(); } get placeholder() { return this._placeholder; } set placeholder(placeholder: string) { this._placeholder = placeholder; this.update(); } get password() { return this._password; } set password(password: boolean) { this._password = password; this.update(); } get prompt() { return this._prompt; } set prompt(prompt: string) { this._prompt = prompt; this.noValidationMessage = prompt ? localize('inputModeEntryDescription', "{0} (Press 'Enter' to confirm or 'Escape' to cancel)", prompt) : InputBox.noPromptMessage; this.update(); } get validationMessage() { return this._validationMessage; } set validationMessage(validationMessage: string) { this._validationMessage = validationMessage; this.update(); } onDidChangeValue = this.onDidValueChangeEmitter.event; onDidAccept = this.onDidAcceptEmitter.event; show() { if (!this.visible) { this.visibleDisposables.push( this.ui.inputBox.onDidChange(value => { if (value === this.value) { return; } this._value = value; this.onDidValueChangeEmitter.fire(value); }), this.ui.onDidAccept(() => this.onDidAcceptEmitter.fire()), ); this.valueSelectionUpdated = true; } super.show(); } protected update() { super.update(); if (!this.visible) { return; } if (this.ui.inputBox.value !== this.value) { this.ui.inputBox.value = this.value; } if (this.valueSelectionUpdated) { this.valueSelectionUpdated = false; this.ui.inputBox.select(this._valueSelection && { start: this._valueSelection[0], end: this._valueSelection[1] }); } if (this.ui.inputBox.placeholder !== (this.placeholder || '')) { this.ui.inputBox.placeholder = (this.placeholder || ''); } if (this.ui.inputBox.password !== this.password) { this.ui.inputBox.password = this.password; } if (!this.validationMessage && this.ui.message.textContent !== this.noValidationMessage) { this.ui.message.textContent = this.noValidationMessage; this.ui.inputBox.showDecoration(Severity.Ignore); } if (this.validationMessage && this.ui.message.textContent !== this.validationMessage) { this.ui.message.textContent = this.validationMessage; this.ui.inputBox.showDecoration(Severity.Error); } this.ui.setVisibilities({ title: !!this.title || !!this.step, inputBox: true, message: true }); } } export class QuickInputService extends Component implements IQuickInputService { public _serviceBrand: any; private static readonly ID = 'workbench.component.quickinput'; private static readonly MAX_WIDTH = 600; // Max total width of quick open widget private idPrefix = 'quickInput_'; // Constant since there is still only one. private layoutDimensions: dom.Dimension; private titleBar: HTMLElement; private filterContainer: HTMLElement; private visibleCountContainer: HTMLElement; private countContainer: HTMLElement; private okContainer: HTMLElement; private ok: Button; private ui: QuickInputUI; private comboboxAccessibility = false; private enabled = true; private inQuickOpenWidgets: Record<string, boolean> = {}; private inQuickOpenContext: IContextKey<boolean>; private contexts: { [id: string]: IContextKey<boolean>; } = Object.create(null); private onDidAcceptEmitter = this._register(new Emitter<void>()); private onDidTriggerButtonEmitter = this._register(new Emitter<IQuickInputButton>()); private keyMods: Writeable<IKeyMods> = { ctrlCmd: false, alt: false }; private controller: QuickInput; constructor( @IEnvironmentService private environmentService: IEnvironmentService, @IConfigurationService private configurationService: IConfigurationService, @IInstantiationService private instantiationService: IInstantiationService, @IPartService private partService: IPartService, @IQuickOpenService private quickOpenService: IQuickOpenService, @IEditorGroupsService private editorGroupService: IEditorGroupsService, @IKeybindingService private keybindingService: IKeybindingService, @IContextKeyService private contextKeyService: IContextKeyService, @IThemeService themeService: IThemeService, @IStorageService storageService: IStorageService ) { super(QuickInputService.ID, themeService, storageService); this.inQuickOpenContext = new RawContextKey<boolean>('inQuickOpen', false).bindTo(contextKeyService); this._register(this.quickOpenService.onShow(() => this.inQuickOpen('quickOpen', true))); this._register(this.quickOpenService.onHide(() => this.inQuickOpen('quickOpen', false))); this.registerKeyModsListeners(); } private inQuickOpen(widget: 'quickInput' | 'quickOpen', open: boolean) { if (open) { this.inQuickOpenWidgets[widget] = true; } else { delete this.inQuickOpenWidgets[widget]; } if (Object.keys(this.inQuickOpenWidgets).length) { if (!this.inQuickOpenContext.get()) { this.inQuickOpenContext.set(true); } } else { if (this.inQuickOpenContext.get()) { this.inQuickOpenContext.reset(); } } } private setContextKey(id?: string) { let key: IContextKey<boolean>; if (id) { key = this.contexts[id]; if (!key) { key = new RawContextKey<boolean>(id, false) .bindTo(this.contextKeyService); this.contexts[id] = key; } } if (key && key.get()) { return; // already active context } this.resetContextKeys(); if (key) { key.set(true); } } private resetContextKeys() { for (const key in this.contexts) { if (this.contexts[key].get()) { this.contexts[key].reset(); } } } private registerKeyModsListeners() { const workbench = this.partService.getWorkbenchElement(); this._register(dom.addDisposableListener(workbench, dom.EventType.KEY_DOWN, (e: KeyboardEvent) => { const event = new StandardKeyboardEvent(e); switch (event.keyCode) { case KeyCode.Ctrl: case KeyCode.Meta: this.keyMods.ctrlCmd = true; break; case KeyCode.Alt: this.keyMods.alt = true; break; } })); this._register(dom.addDisposableListener(workbench, dom.EventType.KEY_UP, (e: KeyboardEvent) => { const event = new StandardKeyboardEvent(e); switch (event.keyCode) { case KeyCode.Ctrl: case KeyCode.Meta: this.keyMods.ctrlCmd = false; break; case KeyCode.Alt: this.keyMods.alt = false; break; } })); } private create() { if (this.ui) { return; } const workbench = this.partService.getWorkbenchElement(); const container = dom.append(workbench, $('.quick-input-widget.show-file-icons')); container.tabIndex = -1; container.style.display = 'none'; this.titleBar = dom.append(container, $('.quick-input-titlebar')); const leftActionBar = this._register(new ActionBar(this.titleBar)); leftActionBar.domNode.classList.add('quick-input-left-action-bar'); const title = dom.append(this.titleBar, $('.quick-input-title')); const rightActionBar = this._register(new ActionBar(this.titleBar)); rightActionBar.domNode.classList.add('quick-input-right-action-bar'); const headerContainer = dom.append(container, $('.quick-input-header')); const checkAll = <HTMLInputElement>dom.append(headerContainer, $('input.quick-input-check-all')); checkAll.type = 'checkbox'; this._register(dom.addStandardDisposableListener(checkAll, dom.EventType.CHANGE, e => { const checked = checkAll.checked; list.setAllVisibleChecked(checked); })); this._register(dom.addDisposableListener(checkAll, dom.EventType.CLICK, e => { if (e.x || e.y) { // Avoid 'click' triggered by 'space'... inputBox.setFocus(); } })); this.filterContainer = dom.append(headerContainer, $('.quick-input-filter')); const inputBox = this._register(new QuickInputBox(this.filterContainer)); inputBox.setAttribute('aria-describedby', `${this.idPrefix}message`); this.visibleCountContainer = dom.append(this.filterContainer, $('.quick-input-visible-count')); this.visibleCountContainer.setAttribute('aria-live', 'polite'); this.visibleCountContainer.setAttribute('aria-atomic', 'true'); const visibleCount = new CountBadge(this.visibleCountContainer, { countFormat: localize({ key: 'quickInput.visibleCount', comment: ['This tells the user how many items are shown in a list of items to select from. The items can be anything. Currently not visible, but read by screen readers.'] }, "{0} Results") }); this.countContainer = dom.append(this.filterContainer, $('.quick-input-count')); this.countContainer.setAttribute('aria-live', 'polite'); const count = new CountBadge(this.countContainer, { countFormat: localize({ key: 'quickInput.countSelected', comment: ['This tells the user how many items are selected in a list of items to select from. The items can be anything.'] }, "{0} Selected") }); this._register(attachBadgeStyler(count, this.themeService)); this.okContainer = dom.append(headerContainer, $('.quick-input-action')); this.ok = new Button(this.okContainer); attachButtonStyler(this.ok, this.themeService); this.ok.label = localize('ok', "OK"); this._register(this.ok.onDidClick(e => { this.onDidAcceptEmitter.fire(); })); const message = dom.append(container, $(`#${this.idPrefix}message.quick-input-message`)); const progressBar = new ProgressBar(container); dom.addClass(progressBar.getContainer(), 'quick-input-progress'); this._register(attachProgressBarStyler(progressBar, this.themeService)); const list = this._register(this.instantiationService.createInstance(QuickInputList, container, this.idPrefix + 'list')); this._register(list.onChangedAllVisibleChecked(checked => { checkAll.checked = checked; })); this._register(list.onChangedVisibleCount(c => { visibleCount.setCount(c); })); this._register(list.onChangedCheckedCount(c => { count.setCount(c); })); this._register(list.onLeave(() => { // Defer to avoid the input field reacting to the triggering key. setTimeout(() => { inputBox.setFocus(); if (this.controller instanceof QuickPick && this.controller.canSelectMany) { list.clearFocus(); } }, 0); })); this._register(list.onDidChangeFocus(() => { if (this.comboboxAccessibility) { this.ui.inputBox.setAttribute('aria-activedescendant', this.ui.list.getActiveDescendant()); } })); const focusTracker = dom.trackFocus(container); this._register(focusTracker); this._register(focusTracker.onDidBlur(() => { if (!this.ui.ignoreFocusOut && !this.environmentService.args['sticky-quickopen'] && this.configurationService.getValue(CLOSE_ON_FOCUS_LOST_CONFIG)) { this.hide(true); } })); this._register(dom.addDisposableListener(container, dom.EventType.KEY_DOWN, (e: KeyboardEvent) => { const event = new StandardKeyboardEvent(e); switch (event.keyCode) { case KeyCode.Enter: dom.EventHelper.stop(e, true); this.onDidAcceptEmitter.fire(); break; case KeyCode.Escape: dom.EventHelper.stop(e, true); this.hide(); break; case KeyCode.Tab: if (!event.altKey && !event.ctrlKey && !event.metaKey) { const selectors = ['.action-label.icon']; if (container.classList.contains('show-checkboxes')) { selectors.push('input'); } else { selectors.push('input[type=text]'); } if (this.ui.list.isDisplayed()) { selectors.push('.monaco-list'); } const stops = container.querySelectorAll<HTMLElement>(selectors.join(', ')); if (event.shiftKey && event.target === stops[0]) { dom.EventHelper.stop(e, true); stops[stops.length - 1].focus(); } else if (!event.shiftKey && event.target === stops[stops.length - 1]) { dom.EventHelper.stop(e, true); stops[0].focus(); } } break; } })); this._register(this.quickOpenService.onShow(() => this.hide(true))); this.ui = { container, leftActionBar, title, rightActionBar, checkAll, inputBox, visibleCount, count, message, progressBar, list, onDidAccept: this.onDidAcceptEmitter.event, onDidTriggerButton: this.onDidTriggerButtonEmitter.event, ignoreFocusOut: false, keyMods: this.keyMods, isScreenReaderOptimized: () => this.isScreenReaderOptimized(), show: controller => this.show(controller), hide: () => this.hide(), setVisibilities: visibilities => this.setVisibilities(visibilities), setComboboxAccessibility: enabled => this.setComboboxAccessibility(enabled), setEnabled: enabled => this.setEnabled(enabled), setContextKey: contextKey => this.setContextKey(contextKey), }; this.updateStyles(); } pick<T extends IQuickPickItem, O extends IPickOptions<T>>(picks: Promise<QuickPickInput<T>[]> | QuickPickInput<T>[], options: O = <O>{}, token: CancellationToken = CancellationToken.None): Promise<O extends { canPickMany: true } ? T[] : T> { return new Promise<O extends { canPickMany: true } ? T[] : T>((doResolve, reject) => { let resolve = (result: any) => { resolve = doResolve; if (options.onKeyMods) { options.onKeyMods(input.keyMods); } doResolve(result); }; if (token.isCancellationRequested) { resolve(undefined); return; } const input = this.createQuickPick<T>(); let activeItem: T; const disposables = [ input, input.onDidAccept(() => { if (input.canSelectMany) { resolve(<any>input.selectedItems.slice()); input.hide(); } else { const result = input.activeItems[0]; if (result) { resolve(<any>result); input.hide(); } } }), input.onDidChangeActive(items => { const focused = items[0]; if (focused && options.onDidFocus) { options.onDidFocus(focused); } }), input.onDidChangeSelection(items => { if (!input.canSelectMany) { const result = items[0]; if (result) { resolve(<any>result); input.hide(); } } }), input.onDidTriggerItemButton(event => options.onDidTriggerItemButton && options.onDidTriggerItemButton({ ...event, removeItem: () => { const index = input.items.indexOf(event.item); if (index !== -1) { const items = input.items.slice(); items.splice(index, 1); input.items = items; } } })), input.onDidChangeValue(value => { if (activeItem && !value && (input.activeItems.length !== 1 || input.activeItems[0] !== activeItem)) { input.activeItems = [activeItem]; } }), token.onCancellationRequested(() => { input.hide(); }), input.onDidHide(() => { dispose(disposables); resolve(undefined); }), ]; input.canSelectMany = options.canPickMany; input.placeholder = options.placeHolder; input.ignoreFocusOut = options.ignoreFocusLost; input.matchOnDescription = options.matchOnDescription; input.matchOnDetail = options.matchOnDetail; input.quickNavigate = options.quickNavigate; input.contextKey = options.contextKey; input.busy = true; Promise.all([picks, options.activeItem]) .then(([items, _activeItem]) => { activeItem = _activeItem; input.busy = false; input.items = items; if (input.canSelectMany) { input.selectedItems = items.filter(item => item.type !== 'separator' && item.picked) as T[]; } if (activeItem) { input.activeItems = [activeItem]; } }); input.show(); Promise.resolve(picks).then(null, err => { reject(err); input.hide(); }); }); } input(options: IInputOptions = {}, token: CancellationToken = CancellationToken.None): Promise<string> { return new Promise<string>((resolve, reject) => { if (token.isCancellationRequested) { resolve(undefined); return; } const input = this.createInputBox(); const validateInput = options.validateInput || (() => <Thenable<undefined>>Promise.resolve(undefined)); const onDidValueChange = debounceEvent(input.onDidChangeValue, (last, cur) => cur, 100); let validationValue = options.value || ''; let validation = Promise.resolve(validateInput(validationValue)); const disposables = [ input, onDidValueChange(value => { if (value !== validationValue) { validation = Promise.resolve(validateInput(value)); validationValue = value; } validation.then(result => { if (value === validationValue) { input.validationMessage = result; } }); }), input.onDidAccept(() => { const value = input.value; if (value !== validationValue) { validation = Promise.resolve(validateInput(value)); validationValue = value; } validation.then(result => { if (!result) { resolve(value); input.hide(); } else if (value === validationValue) { input.validationMessage = result; } }); }), token.onCancellationRequested(() => { input.hide(); }), input.onDidHide(() => { dispose(disposables); resolve(undefined); }), ]; input.value = options.value; input.valueSelection = options.valueSelection; input.prompt = options.prompt; input.placeholder = options.placeHolder; input.password = options.password; input.ignoreFocusOut = options.ignoreFocusLost; input.show(); }); } backButton = backButton; createQuickPick<T extends IQuickPickItem>(): IQuickPick<T> { this.create(); return new QuickPick<T>(this.ui); } createInputBox(): IInputBox { this.create(); return new InputBox(this.ui); } private show(controller: QuickInput) { this.create(); this.quickOpenService.close(); const oldController = this.controller; this.controller = controller; if (oldController) { oldController.didHide(); } this.setEnabled(true); this.ui.leftActionBar.clear(); this.ui.title.textContent = ''; this.ui.rightActionBar.clear(); this.ui.checkAll.checked = false; // this.ui.inputBox.value = ''; Avoid triggering an event. this.ui.inputBox.placeholder = ''; this.ui.inputBox.password = false; this.ui.inputBox.showDecoration(Severity.Ignore); this.ui.visibleCount.setCount(0); this.ui.count.setCount(0); this.ui.message.textContent = ''; this.ui.progressBar.stop(); this.ui.list.setElements([]); this.ui.list.matchOnDescription = false; this.ui.list.matchOnDetail = false; this.ui.ignoreFocusOut = false; this.setComboboxAccessibility(false); this.ui.inputBox.removeAttribute('aria-label'); const keybinding = this.keybindingService.lookupKeybinding(BackAction.ID); backButton.tooltip = keybinding ? localize('quickInput.backWithKeybinding', "Back ({0})", keybinding.getLabel()) : localize('quickInput.back', "Back"); this.inQuickOpen('quickInput', true); this.resetContextKeys(); this.ui.container.style.display = ''; this.updateLayout(); this.ui.inputBox.setFocus(); } private setVisibilities(visibilities: Visibilities) { this.ui.title.style.display = visibilities.title ? '' : 'none'; this.ui.checkAll.style.display = visibilities.checkAll ? '' : 'none'; this.filterContainer.style.display = visibilities.inputBox ? '' : 'none'; this.visibleCountContainer.style.display = visibilities.visibleCount ? '' : 'none'; this.countContainer.style.display = visibilities.count ? '' : 'none'; this.okContainer.style.display = visibilities.ok ? '' : 'none'; this.ui.message.style.display = visibilities.message ? '' : 'none'; this.ui.list.display(visibilities.list); this.ui.container.classList[visibilities.checkAll ? 'add' : 'remove']('show-checkboxes'); this.updateLayout(); // TODO } private setComboboxAccessibility(enabled: boolean) { if (enabled !== this.comboboxAccessibility) { this.comboboxAccessibility = enabled; if (this.comboboxAccessibility) { this.ui.inputBox.setAttribute('role', 'combobox'); this.ui.inputBox.setAttribute('aria-haspopup', 'true'); this.ui.inputBox.setAttribute('aria-autocomplete', 'list'); this.ui.inputBox.setAttribute('aria-activedescendant', this.ui.list.getActiveDescendant()); } else { this.ui.inputBox.removeAttribute('role'); this.ui.inputBox.removeAttribute('aria-haspopup'); this.ui.inputBox.removeAttribute('aria-autocomplete'); this.ui.inputBox.removeAttribute('aria-activedescendant'); } } } private isScreenReaderOptimized() { const detected = browser.getAccessibilitySupport() === AccessibilitySupport.Enabled; const config = this.configurationService.getValue<IEditorOptions>('editor').accessibilitySupport; return config === 'on' || (config === 'auto' && detected); } private setEnabled(enabled: boolean) { if (enabled !== this.enabled) { this.enabled = enabled; for (const item of this.ui.leftActionBar.items) { (item as ActionItem).getAction().enabled = enabled; } for (const item of this.ui.rightActionBar.items) { (item as ActionItem).getAction().enabled = enabled; } this.ui.checkAll.disabled = !enabled; // this.ui.inputBox.enabled = enabled; Avoid loosing focus. this.ok.enabled = enabled; this.ui.list.enabled = enabled; } } private hide(focusLost?: boolean) { const controller = this.controller; if (controller) { this.controller = null; this.inQuickOpen('quickInput', false); this.resetContextKeys(); this.ui.container.style.display = 'none'; if (!focusLost) { this.editorGroupService.activeGroup.focus(); } controller.didHide(); } } focus() { if (this.isDisplayed()) { this.ui.inputBox.setFocus(); } } toggle() { if (this.isDisplayed() && this.controller instanceof QuickPick && this.controller.canSelectMany) { this.ui.list.toggleCheckbox(); } } navigate(next: boolean, quickNavigate?: IQuickNavigateConfiguration) { if (this.isDisplayed() && this.ui.list.isDisplayed()) { this.ui.list.focus(next ? 'Next' : 'Previous'); if (quickNavigate && this.controller instanceof QuickPick) { this.controller.quickNavigate = quickNavigate; } } } accept() { this.onDidAcceptEmitter.fire(); return Promise.resolve(undefined); } back() { this.onDidTriggerButtonEmitter.fire(this.backButton); return Promise.resolve(undefined); } cancel() { this.hide(); return Promise.resolve(undefined); } layout(dimension: dom.Dimension): void { this.layoutDimensions = dimension; this.updateLayout(); } private updateLayout() { if (this.layoutDimensions && this.ui) { const titlebarOffset = this.partService.getTitleBarOffset(); this.ui.container.style.top = `${titlebarOffset}px`; const style = this.ui.container.style; const width = Math.min(this.layoutDimensions.width * 0.62 /* golden cut */, QuickInputService.MAX_WIDTH); style.width = width + 'px'; style.marginLeft = '-' + (width / 2) + 'px'; this.ui.inputBox.layout(); this.ui.list.layout(); } } protected updateStyles() { const theme = this.themeService.getTheme(); if (this.ui) { // TODO const titleColor = { dark: 'rgba(255, 255, 255, 0.105)', light: 'rgba(0,0,0,.06)', hc: 'black' }[theme.type]; this.titleBar.style.backgroundColor = titleColor ? titleColor.toString() : null; this.ui.inputBox.style(theme); const sideBarBackground = theme.getColor(SIDE_BAR_BACKGROUND); this.ui.container.style.backgroundColor = sideBarBackground ? sideBarBackground.toString() : null; const sideBarForeground = theme.getColor(SIDE_BAR_FOREGROUND); this.ui.container.style.color = sideBarForeground ? sideBarForeground.toString() : null; const contrastBorderColor = theme.getColor(contrastBorder); this.ui.container.style.border = contrastBorderColor ? `1px solid ${contrastBorderColor}` : null; const widgetShadowColor = theme.getColor(widgetShadow); this.ui.container.style.boxShadow = widgetShadowColor ? `0 5px 8px ${widgetShadowColor}` : null; } } private isDisplayed() { return this.ui && this.ui.container.style.display !== 'none'; } } export const QuickPickManyToggle: ICommandAndKeybindingRule = { id: 'workbench.action.quickPickManyToggle', weight: KeybindingWeight.WorkbenchContrib, when: inQuickOpenContext, primary: undefined, handler: accessor => { const quickInputService = accessor.get(IQuickInputService); quickInputService.toggle(); } }; export class BackAction extends Action { public static readonly ID = 'workbench.action.quickInputBack'; public static readonly LABEL = localize('back', "Back"); constructor(id: string, label: string, @IQuickInputService private quickInputService: IQuickInputService) { super(id, label); } public run(): Promise<any> { this.quickInputService.back(); return Promise.resolve(null); } }
DustinCampbell/vscode
src/vs/workbench/browser/parts/quickinput/quickInput.ts
TypeScript
mit
44,636
/** * @summary Race timing system * @author Guillaume Deconinck & Wojciech Grynczel */ 'use strict'; // time-model.js - A mongoose model // // See http://mongoosejs.com/docs/models.html // for more of what you can do here. const mongoose = require('mongoose'); const Schema = mongoose.Schema; const timeSchema = new Schema({ checkpoint_id: { type: Number, required: true }, tag: { type: Schema.Types.Mixed, required: true }, timestamp: { type: Date, required: true } }); const timeModel = mongoose.model('times', timeSchema); module.exports = timeModel;
osrts/osrts-backend
src/services/times/time-model.js
JavaScript
mit
568
<?php /* FOSUserBundle:Group:edit.html.twig */ class __TwigTemplate_ef57f06f37b4b105df31eabec2d1cd20acba6f1995ab286ffcc795254ca469ef extends Sonata\CacheBundle\Twig\TwigTemplate14 { public function __construct(Twig_Environment $env) { parent::__construct($env); // line 1 try { $this->parent = $this->env->loadTemplate("FOSUserBundle::layout.html.twig"); } catch (Twig_Error_Loader $e) { $e->setTemplateFile($this->getTemplateName()); $e->setTemplateLine(1); throw $e; } $this->blocks = array( 'fos_user_content' => array($this, 'block_fos_user_content'), ); } protected function doGetParent(array $context) { return "FOSUserBundle::layout.html.twig"; } protected function doDisplay(array $context, array $blocks = array()) { $this->parent->display($context, array_merge($this->blocks, $blocks)); } // line 3 public function block_fos_user_content($context, array $blocks = array()) { // line 4 $this->env->loadTemplate("FOSUserBundle:Group:edit_content.html.twig")->display($context); } public function getTemplateName() { return "FOSUserBundle:Group:edit.html.twig"; } public function isTraitable() { return false; } public function getDebugInfo() { return array ( 39 => 4, 36 => 3, 11 => 1,); } }
wieloming/GPI
1/ef/57/f06f37b4b105df31eabec2d1cd20acba6f1995ab286ffcc795254ca469ef.php
PHP
mit
1,473
<?php use Illuminate\Database\Schema\Blueprint; use Illuminate\Database\Migrations\Migration; class CreateRoleUserTable extends Migration { /** * Run the migrations. * * @return void */ public function up() { Schema::create('role_user', function (Blueprint $table) { // $table->integer('role_id')->unsigned(); $table->integer('user_id')->unsigned(); $table->foreign('role_id') ->references('id') ->on('roles') ->onDelete('cascade'); $table->foreign('user_id') ->references('id') ->on('users') ->onDelete('cascade'); $table->primary('role_id', 'user_id'); }); } /** * Reverse the migrations. * * @return void */ public function down() { Schema::drop('role_user'); } }
Khairulrabbi/htmis
database/migrations/2016_04_21_052356_create_role_user_table.php
PHP
mit
968
module Garages class ToggleStatusController < ApplicationController before_action :set_garage, only: :update after_action :verify_authorized def update authorize @garage @garage.toggle_status respond_to do |format| format.html { redirect_to garages_url } end end private def set_garage @garage = Garage.find(secure_id) end def garage_params params.permit(:id) end def secure_id garage_params[:id].to_i end end end
jonnyjava/ewoks
app/controllers/garages/toggle_status_controller.rb
Ruby
mit
534
#!/usr/bin/env python import sys, json from confusionmatrix import ConfusionMatrix as CM def main(): for line in sys.stdin: cm = json.loads(line) print CM(cm["TP"], cm["FP"], cm["FN"], cm["TN"]) if __name__ == '__main__': main()
yatmingyatming/LogisticRegressionSGDMapReduce
display_stats.py
Python
mit
264
/* * @(#)ByteBufferAs-X-Buffer.java 1.18 05/11/17 * * Copyright 2006 Sun Microsystems, Inc. All rights reserved. * SUN PROPRIETARY/CONFIDENTIAL. Use is subject to license terms. */ // -- This file was mechanically generated: Do not edit! -- // package java.nio; class ByteBufferAsDoubleBufferB // package-private extends DoubleBuffer { protected final ByteBuffer bb; protected final int offset; ByteBufferAsDoubleBufferB(ByteBuffer bb) { // package-private super(-1, 0, bb.remaining() >> 3, bb.remaining() >> 3); this.bb = bb; // enforce limit == capacity int cap = this.capacity(); this.limit(cap); int pos = this.position(); assert (pos <= cap); offset = pos; } ByteBufferAsDoubleBufferB(ByteBuffer bb, int mark, int pos, int lim, int cap, int off) { super(mark, pos, lim, cap); this.bb = bb; offset = off; } public DoubleBuffer slice() { int pos = this.position(); int lim = this.limit(); assert (pos <= lim); int rem = (pos <= lim ? lim - pos : 0); int off = (pos << 3) + offset; assert (off >= 0); return new ByteBufferAsDoubleBufferB(bb, -1, 0, rem, rem, off); } public DoubleBuffer duplicate() { return new ByteBufferAsDoubleBufferB(bb, this.markValue(), this.position(), this.limit(), this.capacity(), offset); } public DoubleBuffer asReadOnlyBuffer() { return new ByteBufferAsDoubleBufferRB(bb, this.markValue(), this.position(), this.limit(), this.capacity(), offset); } protected int ix(int i) { return (i << 3) + offset; } public double get() { return Bits.getDoubleB(bb, ix(nextGetIndex())); } public double get(int i) { return Bits.getDoubleB(bb, ix(checkIndex(i))); } public DoubleBuffer put(double x) { Bits.putDoubleB(bb, ix(nextPutIndex()), x); return this; } public DoubleBuffer put(int i, double x) { Bits.putDoubleB(bb, ix(checkIndex(i)), x); return this; } public DoubleBuffer compact() { int pos = position(); int lim = limit(); assert (pos <= lim); int rem = (pos <= lim ? lim - pos : 0); ByteBuffer db = bb.duplicate(); db.limit(ix(lim)); db.position(ix(0)); ByteBuffer sb = db.slice(); sb.position(pos << 3); sb.compact(); position(rem); limit(capacity()); return this; } public boolean isDirect() { return bb.isDirect(); } public boolean isReadOnly() { return false; } public ByteOrder order() { return ByteOrder.BIG_ENDIAN; } }
jgaltidor/VarJ
analyzed_libs/jdk1.6.0_06_src/java/nio/ByteBufferAsDoubleBufferB.java
Java
mit
2,856
import { Injectable } from 'angular2/core'; @Injectable() export class Config { SERVER_URL:string = "http://128.199.158.79:9000/"; }
alexsalesdev/fiori-blossoms-ui-web-angular-2
public/app/service/config.ts
TypeScript
mit
138
class GeometryTests < PostgreSQLExtensionsTestCase def test_create_geometry Mig.create_table(:foo) do |t| t.geometry :the_geom, :srid => 4326 end expected = [] expected << strip_heredoc(<<-SQL) CREATE TABLE "foo" ( "id" serial primary key, "the_geom" geometry, CONSTRAINT "enforce_srid_the_geom" CHECK (ST_srid("the_geom") = (4326)), CONSTRAINT "enforce_dims_the_geom" CHECK (ST_ndims("the_geom") = 2) ); SQL expected << strip_heredoc(<<-SQL) DELETE FROM "geometry_columns" WHERE f_table_catalog = '' AND f_table_schema = 'public' AND f_table_name = 'foo' AND f_geometry_column = 'the_geom'; SQL expected << strip_heredoc(<<-SQL) INSERT INTO "geometry_columns" VALUES ('', 'public', 'foo', 'the_geom', 2, 4326, 'GEOMETRY'); SQL expected << strip_heredoc(<<-SQL) CREATE INDEX "foo_the_geom_gist_index" ON PUBLIC."foo" USING "gist"("the_geom"); SQL assert_equal(expected, statements) end def test_create_geometry_with_spatial Mig.create_table(:foo) do |t| t.spatial :the_geom, :srid => 4326 end expected = [] expected << strip_heredoc(<<-SQL) CREATE TABLE "foo" ( "id" serial primary key, "the_geom" geometry, CONSTRAINT "enforce_srid_the_geom" CHECK (ST_srid("the_geom") = (4326)), CONSTRAINT "enforce_dims_the_geom" CHECK (ST_ndims("the_geom") = 2) ); SQL expected << strip_heredoc(<<-SQL) DELETE FROM "geometry_columns" WHERE f_table_catalog = '' AND f_table_schema = 'public' AND f_table_name = 'foo' AND f_geometry_column = 'the_geom'; SQL expected << strip_heredoc(<<-SQL) INSERT INTO "geometry_columns" VALUES ('', 'public', 'foo', 'the_geom', 2, 4326, 'GEOMETRY'); SQL expected << strip_heredoc(<<-SQL) CREATE INDEX "foo_the_geom_gist_index" ON PUBLIC."foo" USING "gist"("the_geom"); SQL assert_equal(expected, statements) end def test_create_geometry_with_spatial_and_spatial_column_type Mig.create_table(:foo) do |t| t.spatial :the_geom, :srid => 4326, :spatial_column_type => :geography end expected = [] expected << strip_heredoc(<<-SQL) CREATE TABLE "foo" ( "id" serial primary key, "the_geom" geography, CONSTRAINT "enforce_srid_the_geom" CHECK (ST_srid("the_geom") = (4326)), CONSTRAINT "enforce_dims_the_geom" CHECK (ST_ndims("the_geom") = 2) ); SQL expected << strip_heredoc(<<-SQL) CREATE INDEX "foo_the_geom_gist_index" ON PUBLIC."foo" USING "gist"("the_geom"); SQL assert_equal(expected, statements) end def test_create_geography Mig.create_table(:foo) do |t| t.geography :the_geom, :srid => 4326 end expected = [] expected << strip_heredoc(<<-SQL) CREATE TABLE "foo" ( "id" serial primary key, "the_geom" geography, CONSTRAINT "enforce_srid_the_geom" CHECK (ST_srid("the_geom") = (4326)), CONSTRAINT "enforce_dims_the_geom" CHECK (ST_ndims("the_geom") = 2) ); SQL expected << strip_heredoc(<<-SQL) CREATE INDEX "foo_the_geom_gist_index" ON PUBLIC."foo" USING "gist"("the_geom"); SQL assert_equal(expected, statements) end def test_create_geometry_with_schema Mig.create_table('shabba.foo') do |t| t.geometry :the_geom, :srid => 4326 end expected = [] expected << strip_heredoc(<<-SQL) CREATE TABLE "shabba"."foo" ( "id" serial primary key, "the_geom" geometry, CONSTRAINT "enforce_srid_the_geom" CHECK (ST_srid("the_geom") = (4326)), CONSTRAINT "enforce_dims_the_geom" CHECK (ST_ndims("the_geom") = 2) ); SQL expected << strip_heredoc(<<-SQL) DELETE FROM "geometry_columns" WHERE f_table_catalog = '' AND f_table_schema = 'shabba' AND f_table_name = 'foo' AND f_geometry_column = 'the_geom'; SQL expected << strip_heredoc(<<-SQL) INSERT INTO "geometry_columns" VALUES ('', 'shabba', 'foo', 'the_geom', 2, 4326, 'GEOMETRY'); SQL expected << strip_heredoc(<<-SQL) CREATE INDEX "foo_the_geom_gist_index" ON "shabba"."foo" USING "gist"("the_geom"); SQL assert_equal(expected, statements) end def test_create_geometry_with_not_null Mig.create_table(:foo) do |t| t.geometry :the_geom, :srid => 4326, :null => false end expected = [] expected << strip_heredoc(<<-SQL) CREATE TABLE "foo" ( "id" serial primary key, "the_geom" geometry NOT NULL, CONSTRAINT "enforce_srid_the_geom" CHECK (ST_srid("the_geom") = (4326)), CONSTRAINT "enforce_dims_the_geom" CHECK (ST_ndims("the_geom") = 2) ); SQL expected << strip_heredoc(<<-SQL) DELETE FROM "geometry_columns" WHERE f_table_catalog = '' AND f_table_schema = 'public' AND f_table_name = 'foo' AND f_geometry_column = 'the_geom'; SQL expected << strip_heredoc(<<-SQL) INSERT INTO "geometry_columns" VALUES ('', 'public', 'foo', 'the_geom', 2, 4326, 'GEOMETRY'); SQL expected << strip_heredoc(<<-SQL) CREATE INDEX "foo_the_geom_gist_index" ON PUBLIC."foo" USING "gist"("the_geom"); SQL assert_equal(expected, statements) end def test_create_geometry_with_null_and_type Mig.create_table(:foo) do |t| t.geometry :the_geom, :srid => 4326, :geometry_type => :polygon end expected = [] expected << strip_heredoc(<<-SQL) CREATE TABLE "foo" ( "id" serial primary key, "the_geom" geometry, CONSTRAINT "enforce_srid_the_geom" CHECK (ST_srid("the_geom") = (4326)), CONSTRAINT "enforce_dims_the_geom" CHECK (ST_ndims("the_geom") = 2), CONSTRAINT "enforce_geotype_the_geom" CHECK (geometrytype("the_geom") = 'POLYGON'::text OR "the_geom" IS NULL) ); SQL expected << strip_heredoc(<<-SQL) DELETE FROM "geometry_columns" WHERE f_table_catalog = '' AND f_table_schema = 'public' AND f_table_name = 'foo' AND f_geometry_column = 'the_geom'; SQL expected << strip_heredoc(<<-SQL) INSERT INTO "geometry_columns" VALUES ('', 'public', 'foo', 'the_geom', 2, 4326, 'POLYGON'); SQL expected << strip_heredoc(<<-SQL) CREATE INDEX "foo_the_geom_gist_index" ON PUBLIC."foo" USING "gist"("the_geom"); SQL assert_equal(expected, statements) end def test_change_table_add_geometry Mig.change_table(:foo) do |t| t.geometry :the_geom, :srid => 4326 end expected = [ %{ALTER TABLE "foo" ADD COLUMN "the_geom" geometry}, %{ALTER TABLE "foo" ADD CONSTRAINT "enforce_srid_the_geom" CHECK (ST_srid("the_geom") = (4326));}, %{ALTER TABLE "foo" ADD CONSTRAINT "enforce_dims_the_geom" CHECK (ST_ndims("the_geom") = 2);}, %{DELETE FROM "geometry_columns" WHERE f_table_catalog = '' AND f_table_schema = 'public' AND f_table_name = 'foo' AND f_geometry_column = 'the_geom';}, %{INSERT INTO "geometry_columns" VALUES ('', 'public', 'foo', 'the_geom', 2, 4326, 'GEOMETRY');}, %{CREATE INDEX "foo_the_geom_gist_index" ON PUBLIC."foo" USING "gist"("the_geom");} ] assert_equal(expected, statements) end def test_change_table_add_geometry_with_spatial Mig.change_table(:foo) do |t| t.spatial :the_geom, :srid => 4326 end expected = [ %{ALTER TABLE "foo" ADD COLUMN "the_geom" geometry}, %{ALTER TABLE "foo" ADD CONSTRAINT "enforce_srid_the_geom" CHECK (ST_srid("the_geom") = (4326));}, %{ALTER TABLE "foo" ADD CONSTRAINT "enforce_dims_the_geom" CHECK (ST_ndims("the_geom") = 2);}, %{DELETE FROM "geometry_columns" WHERE f_table_catalog = '' AND f_table_schema = 'public' AND f_table_name = 'foo' AND f_geometry_column = 'the_geom';}, %{INSERT INTO "geometry_columns" VALUES ('', 'public', 'foo', 'the_geom', 2, 4326, 'GEOMETRY');}, %{CREATE INDEX "foo_the_geom_gist_index" ON PUBLIC."foo" USING "gist"("the_geom");} ] assert_equal(expected, statements) end def test_change_table_geometry_with_spatial_and_spatial_column_type Mig.change_table(:foo) do |t| t.spatial :the_geom, :srid => 4326, :spatial_column_type => :geography end expected = [ %{ALTER TABLE "foo" ADD COLUMN "the_geom" geography}, %{ALTER TABLE "foo" ADD CONSTRAINT "enforce_srid_the_geom" CHECK (ST_srid("the_geom") = (4326));}, %{ALTER TABLE "foo" ADD CONSTRAINT "enforce_dims_the_geom" CHECK (ST_ndims("the_geom") = 2);}, %{CREATE INDEX "foo_the_geom_gist_index" ON PUBLIC."foo" USING "gist"("the_geom");} ] assert_equal(expected, statements) end def test_change_table_geography Mig.change_table(:foo) do |t| t.geography :the_geom, :srid => 4326 end expected = [ %{ALTER TABLE "foo" ADD COLUMN "the_geom" geography}, %{ALTER TABLE "foo" ADD CONSTRAINT "enforce_srid_the_geom" CHECK (ST_srid("the_geom") = (4326));}, %{ALTER TABLE "foo" ADD CONSTRAINT "enforce_dims_the_geom" CHECK (ST_ndims("the_geom") = 2);}, %{CREATE INDEX "foo_the_geom_gist_index" ON PUBLIC."foo" USING "gist"("the_geom");} ] assert_equal(expected, statements) end def test_change_table_geometry_with_force_constraints Mig.change_table(:foo) do |t| t.geometry :the_geom, :srid => 4326, :force_constraints => true end expected = [ %{ALTER TABLE "foo" ADD COLUMN "the_geom" geometry}, %{ALTER TABLE "foo" ADD CONSTRAINT "enforce_srid_the_geom" CHECK (ST_srid("the_geom") = (4326));}, %{ALTER TABLE "foo" ADD CONSTRAINT "enforce_dims_the_geom" CHECK (ST_ndims("the_geom") = 2);}, %{DELETE FROM "geometry_columns" WHERE f_table_catalog = '' AND f_table_schema = 'public' AND f_table_name = 'foo' AND f_geometry_column = 'the_geom';}, %{INSERT INTO "geometry_columns" VALUES ('', 'public', 'foo', 'the_geom', 2, 4326, 'GEOMETRY');}, %{CREATE INDEX "foo_the_geom_gist_index" ON PUBLIC."foo" USING "gist"("the_geom");} ] assert_equal(expected, statements) end def test_change_table_geometry_with_schema Mig.change_table('shabba.foo') do |t| t.geometry :the_geom, :srid => 4326 end expected = [ %{ALTER TABLE "shabba"."foo" ADD COLUMN "the_geom" geometry}, %{ALTER TABLE "shabba"."foo" ADD CONSTRAINT "enforce_srid_the_geom" CHECK (ST_srid("the_geom") = (4326));}, %{ALTER TABLE "shabba"."foo" ADD CONSTRAINT "enforce_dims_the_geom" CHECK (ST_ndims("the_geom") = 2);}, %{DELETE FROM "geometry_columns" WHERE f_table_catalog = '' AND f_table_schema = 'shabba' AND f_table_name = 'foo' AND f_geometry_column = 'the_geom';}, %{INSERT INTO "geometry_columns" VALUES ('', 'shabba', 'foo', 'the_geom', 2, 4326, 'GEOMETRY');}, %{CREATE INDEX "foo_the_geom_gist_index" ON "shabba"."foo" USING "gist"("the_geom");} ] assert_equal(expected, statements) end def test_change_table_geometry_with_not_null Mig.change_table(:foo) do |t| t.geometry :the_geom, :srid => 4326, :null => false end expected = [ %{ALTER TABLE "foo" ADD COLUMN "the_geom" geometry NOT NULL}, %{ALTER TABLE "foo" ADD CONSTRAINT "enforce_srid_the_geom" CHECK (ST_srid("the_geom") = (4326));}, %{ALTER TABLE "foo" ADD CONSTRAINT "enforce_dims_the_geom" CHECK (ST_ndims("the_geom") = 2);}, %{DELETE FROM "geometry_columns" WHERE f_table_catalog = '' AND f_table_schema = 'public' AND f_table_name = 'foo' AND f_geometry_column = 'the_geom';}, %{INSERT INTO "geometry_columns" VALUES ('', 'public', 'foo', 'the_geom', 2, 4326, 'GEOMETRY');}, %{CREATE INDEX "foo_the_geom_gist_index" ON PUBLIC."foo" USING "gist"("the_geom");} ] assert_equal(expected, statements) end def test_change_table_geometry_with_null_and_type Mig.change_table(:foo) do |t| t.geometry :the_geom, :srid => 4326, :geometry_type => :polygon end expected = [ %{ALTER TABLE "foo" ADD COLUMN "the_geom" geometry}, %{ALTER TABLE "foo" ADD CONSTRAINT "enforce_srid_the_geom" CHECK (ST_srid("the_geom") = (4326));}, %{ALTER TABLE "foo" ADD CONSTRAINT "enforce_dims_the_geom" CHECK (ST_ndims("the_geom") = 2);}, %{ALTER TABLE "foo" ADD CONSTRAINT "enforce_geotype_the_geom" CHECK (geometrytype("the_geom") = 'POLYGON'::text OR "the_geom" IS NULL);}, %{DELETE FROM "geometry_columns" WHERE f_table_catalog = '' AND f_table_schema = 'public' AND f_table_name = 'foo' AND f_geometry_column = 'the_geom';}, %{INSERT INTO "geometry_columns" VALUES ('', 'public', 'foo', 'the_geom', 2, 4326, 'POLYGON');}, %{CREATE INDEX "foo_the_geom_gist_index" ON PUBLIC."foo" USING "gist"("the_geom");} ] assert_equal(expected, statements) end end
zoocasa/activerecord-postgresql-extensions
test/geometry_tests_legacy_postgis.rb
Ruby
mit
12,763
module FrankAfcProxy VERSION = "0.0.1" end
suzumura-ss/frank_afc_proxy
lib/frank_afc_proxy/version.rb
Ruby
mit
45
/// <reference path="//Microsoft.WinJS.1.0/js/base.js" /> /// <reference path="../model/event.js" /> (function () { var initAppBarGlobalCommands = function () { var eventsButton = document.getElementById("navigate-onClick-to-events"); eventsButton.addEventListener("click", function () { WinJS.Navigation.navigate("/js/view/events/events.html"); }); } var initAppBarrEventsCommands = function () { var eventsButton = document.getElementById("call-form-for-event"); eventsButton.addEventListener("click", function () { var eventCreationFormHolder = document.getElementById("event-form-creation-form").winControl; eventCreationFormHolder.show(eventCreationFormHolder, "right", "center"); }); } var initNewEventCreateBtn = function () { var createEventBtn = document.getElementById("create-event-btn"); createEventBtn.addEventListener("click", function () { var eventDTO = Models.Event.eventDTO; var title = document.getElementById("new-event-title").value; var description = document.getElementById("new-event-description").innerHTML; eventDTO.title = title; eventDTO.description = description; var localFolder = Windows.Storage.ApplicationData.current.localFolder; localFolder.createFileAsync("events", Windows.Storage.CreationCollisionOption.openIfExists).then(function (file) { var content = JSON.stringify(eventDTO); Windows.Storage.FileIO.readTextAsync(file).then(function (oldContent) { oldContent = oldContent.replace("[", ""); oldContent = oldContent.replace("]", ""); content = content + ',' + oldContent; Windows.Storage.FileIO.writeTextAsync(file, "[" + content + "]"); }); }); }); } var readEventsFromLocalFolder = function () { var localFolder = Windows.Storage.ApplicationData.current.localFolder; return localFolder.createFileAsync("events", Windows.Storage.CreationCollisionOption.openIfExists); } WinJS.Namespace.define("Commands", { initAppBarCommands: initAppBarGlobalCommands, initAppBarrEventsCommands: initAppBarrEventsCommands, initNewEventCreateBtn: initNewEventCreateBtn, readEventsFromLocalFolder: readEventsFromLocalFolder, }); })();
vaster/RestReminder
RestReminderApp/RestReminderApp/js/commands/command.js
JavaScript
mit
2,545
<?php if (count($brands) > 0): ?> <?php if ($sf_request->hasParameter('is_search')): ?> <?php $action = '@product_search' ?> <?php else: ?> <?php $action = '@product_list' ?> <?php endif; ?> <?php if ($sf_request->hasParameter('path')): ?> <?php $path = '?path=' . $sf_request->getParameter('path') ?> <?php else: ?> <?php $path = '' ?> <?php endif; ?> <b><?php echo __('Filter by brand') ?>:</b> <?php $link = link_to( __('All'), url_for($action . $path, true) . '?filters[brand_id]=all&filter=filter', array('post' => true) ) ?> <?php if (!isset($filter['brand_id'])): ?> <b><?php echo $link ?></b> <?php else: ?> <?php echo $link ?> <?php endif; ?> <?php foreach ($brands as $brand): ?> <?php $link = link_to( $brand->getTitle(), url_for($action . $path, true) . '?filters[brand_id]=' . $brand->getId() . '&filter=filter', array('post' => true) ) ?> <?php if (isset($filter['brand_id']) && $brand->getId() == $filter['brand_id']): ?> <b><?php echo $link ?></b> <?php else: ?> <?php echo $link ?> <?php endif; ?> <?php endforeach; ?> <?php endif; ?>
alecslupu/sfshop
plugins/sfsProductPlugin/modules/brand/templates/_filterList.php
PHP
mit
1,333
package tile; import java.net.URL; public class Box extends Tile { public Box(URL url, char key) { // TODO Auto-generated constructor stub super(url, key); this.canMove = false; } }
Sy4z/The-Excellent-Adventure
src/tile/Box.java
Java
mit
193
// Generated by CoffeeScript 1.7.1 (function() { var pf, pfr; pf = function(n) { return pfr(n, 2, []); }; pfr = function(n, d, f) { if (n < 2) { return f; } if (n % d === 0) { return [d].concat(pfr(n / d, d, f)); } return pfr(n, d + 1, f); }; module.exports = pf; }).call(this);
dlwire/coffeescript-barebones
javascripts/pf.js
JavaScript
mit
331
var plan = require('./index'); module.exports = plan; var HOST = 'brainbug.local'; plan.target('single', function(done) { setTimeout(function() { done([ { host: HOST + 'lol', username: 'pstadler', agent: process.env.SSH_AUTH_SOCK, failsafe: true }, { host: HOST, username: 'pstadler', agent: process.env.SSH_AUTH_SOCK, } ]); }, 1000); }, { sudoUser: 'bar' }); plan.target('multi', [ { host: HOST, username: 'pstadler', privateKey: '/Users/pstadler/.ssh/id_rsa', passphrase: '' //agent: process.env.SSH_AUTH_SOCK }, { host: HOST, username: 'pstadler', privateKey: '/Users/pstadler/.ssh/id_rsa', passphrase: '' //agent: process.env.SSH_AUTH_SOCK } ]); plan.remote(function(remote) { remote.ls(); }); plan.local(function(local) { console.log(plan.runtime.options); var foo = local.prompt('Hello?'); console.log(foo); local.failsafe(); local.ls('-al', {exec: { cwd: '/'}}); local.transfer('lib/', '/tmp'); }); plan.remote(function(remote) { //remote.exec('read', {exec: {pty: true}}); //remote.exec('tail -f /tmp/foo/index.js'); // remote.silent(); // remote.ls('-al'); // remote.verbose(); remote.ls('-al'); // remote.exec('ls -al', { exec: { pty: true } }); // remote.sudo('ls -al', { user: 'node' }); }); plan.local(function(local) { local.ls('-al foooo', {failsafe: true}); //plan.abort(); }); plan.remote(function(remote) { remote.ls('-al'); }); // plan.local(function(local) { // local.with('cd /tmp', { failsafe: true }, function() { // local.ls('-al bar'); // local.with('echo hello world', { failsafe: false }, function() { // local.ls('-al bar', { failsafe: true }); // }); // }); // var files = local.ls({ silent: true }); // local.transfer(files, '/tmp/foo'); // local.prompt('Do you really want to foo?', {hidden: true}); // }); // plan.local(function(local) { // local.log('this is a user message'); // local.echo('hello world'); // //plan.abort(); // //local.prompt('foo', {hidden: true}); // }); // plan.local('default', function(local) { // local.exec('ls -al'); // local.exec('ls foo', { failsafe: true }); // try { // local.exec('ls foo'); // } catch(e) { // console.log(e); // } // local.with('cd /tmp', { silent: true }, function() { // local.ls(); // }) // }); // plan.remote(function(remote) { // remote.silent(); // remote.ls('-al'); // remote.ls('foo', { failsafe: true }) // remote.ls('foo'); // remote.sudo('echo foo', { user: 'node' }); // remote.verbose(); // remote.with('cd /tmp', function() { // remote.sudo('ls -al', { user: 'node' }); // }); // }); // plan.remote(function(remote) { // remote.ls('-al /tmp/foo'); // console.log(remote.target); // console.log(plan.runtime); // }); //plan.run('default', 'multi', { debug: true });
thundernixon/thundernixon2015wp-sage
node_modules/flightplan/flightplan.js
JavaScript
mit
2,931
<?php namespace AppBundle\Controller; use Symfony\Bundle\FrameworkBundle\Controller\Controller; use Symfony\Component\HttpFoundation\Request; class SecurityController extends Controller { public function loginAction(Request $request) { $authUtils = $this->get('security.authentication_utils'); $error = $authUtils->getLastAuthenticationError(); $lastUsername = $authUtils->getLastUsername(); return $this->render('security/login.html.twig', [ 'error' => $error, 'last_username' => $lastUsername ]); } }
marko126/symfony-nastava
src/AppBundle/Controller/SecurityController.php
PHP
mit
612
require File.dirname(__FILE__) + '/spec_helper' module SDP describe "Dokken iteration 3" do before(:all) do @iteration = Iteration.new(3, "Dokken", Date.parse('01/21/2008'), Date.parse('01/25/2008')) s = <<EOQ http://bugzilla.songbirdnest.com/buglist.cgi?quicksearch=632%2C754%2C2025%2C3370%2C3600%2C3708%2C3921%2C4017%2C4030%2C4161%2C4200%2C4461%2C4544%2C4571%2C4809%2C5008%2C5026%2C5382%2C5428%2C5496%2C5609%2C5774%2C6198%2C6206%2C6247%2C6248%2C6253%2C6294%2C6322%2C6324%2C6325%2C6329%2C6337%2C6356%2C6371%2C6427%2C6459%2C6471%2C6472%2C6486%2C6515%2C6519%2C6524%2C6525%2C6537%2C6640%2C6642%2C6652%2C6671%2C6676%2C6677%2C6678%2C6680%2C6681%2C6684%2C6685%2C6686%2C6688%2C6699%2C6705%2C6706%2C6707%2C6708%2C6709%2C6710%2C6711%2C6712%2C6713%2C6714%2C6715%2C6717%2C6726%2C6736%2C6788%2C6797%2C6804%2C6805%2C6806%2C6807%2C6808%2C6810%2C6811%2C6812%2C6813%2C6815%2C6816%2C6817%2C6818%2C6819%2C6820%2C6821%2C6822%2C6823%2C6824%2C6825%2C6826%2C6827%2C6828%2C6829%2C6830%2C6831%2C6834%2C6838%2C6839%2C6841%2C6853%2C6854%2C6856%2C6857%2C6858%2C6859%2C6860%2C6861%2C6862%2C6863%2C6864%2C6865%2C6866%2C6867%2C6868%2C6904%2C6905 EOQ @iteration.remaining_at_start = View.from_query(Query.from_s(s)) s = <<EOQ http://bugzilla.songbirdnest.com/buglist.cgi?quicksearch=2025%2C3370%2C3600%2C3921%2C4017%2C4030%2C4161%2C4200%2C4461%2C4544%2C4571%2C4809%2C4845%2C5008%2C5026%2C5382%2C5428%2C5496%2C5609%2C5774%2C5981%2C6198%2C6206%2C6247%2C6253%2C6316%2C6322%2C6324%2C6325%2C6337%2C6346%2C6356%2C6371%2C6427%2C6459%2C6471%2C6472%2C6486%2C6490%2C6515%2C6519%2C6537%2C6640%2C6642%2C6652%2C6671%2C6676%2C6677%2C6680%2C6684%2C6685%2C6688%2C6699%2C6705%2C6706%2C6707%2C6708%2C6709%2C6710%2C6711%2C6712%2C6713%2C6714%2C6715%2C6717%2C6726%2C6736%2C6788%2C6796%2C6797%2C6804%2C6807%2C6808%2C6810%2C6811%2C6812%2C6813%2C6815%2C6816%2C6817%2C6818%2C6819%2C6820%2C6821%2C6822%2C6823%2C6824%2C6825%2C6826%2C6827%2C6828%2C6829%2C6830%2C6831%2C6834%2C6838%2C6839%2C6860%2C6862%2C6863%2C6864%2C6865%2C6866%2C6867%2C6868%2C6904%2C6905%2C6912%2C6922%2C6933%2C6937%2C6949%2C6952%2C6953%2C6954%2C6955%2C6963%2C6989%2C6993%2C7005%2C7006%2C7008%2C7009 EOQ @iteration.remaining_at_end = View.from_query(Query.from_s(s)) s = <<EOQ http://bugzilla.songbirdnest.com/buglist.cgi?quicksearch=754%2C6329%2C6607%2C6681%2C6693%2C6841%2C6853%2C6854%2C6856%2C6857%2C6858%2C6248%2C6524%2C6525%2C6678%2C6805%2C6806%2C6859%2C6923%2C632%2C3708%2C6686%2C6861 EOQ @iteration.completed = View.from_query(Query.from_s(s)) s = <<EOQ http://bugzilla.songbirdnest.com/buglist.cgi?quicksearch=2244%2C4017%2C4030%2C4461%2C4809%2C5611%2C6248%2C6346%2C6371%2C6708%2C6713%2C6714%2C6715%2C6807%2C6808%2C6810%2C6811%2C6860%2C6862%2C6863%2C6865%2C6866%2C6905%2C6933%2C6963%2C6989%2C6864 EOQ @iteration.carry_over = View.from_query(Query.from_s(s)) s = <<EOQ http://bugzilla.songbirdnest.com/buglist.cgi?quicksearch=754%2C3708%2C4017%2C4030%2C4461%2C6329%2C6371%2C6678%2C6681%2C6686%2C6708%2C6713%2C6714%2C6715%2C6805%2C6810%2C6841%2C6853%2C6854%2C6856%2C6857%2C6858%2C6859%2C6860%2C6861%2C6862%2C6866 EOQ @iteration.planned = View.from_query(Query.from_s(s)) end it "should have length" do @iteration.length.should == 4 end it "should have expected items remaining at start" do @iteration.remaining_at_start.size.should == 122 end it "should have expected cost remaining at start" do begin @iteration.remaining_at_start.total_cost.should == 200 rescue View::CostMissingException => e puts e.view end end it "should have expected items planned" do @iteration.planned.size.should == 27 end it "should have expected cost planned" do begin @iteration.planned.total_cost.should == 45 rescue View::CostMissingException => e puts e.view end end it "should have expected items remaining at end" do @iteration.remaining_at_end.size.should == 123 end it "should have expected cost remaining at end" do begin @iteration.remaining_at_end.total_cost.should == 192 rescue View::CostMissingException => e puts e.view end end it "should have expected items carried over" do @iteration.carry_over.size.should == 27 end it "should have expected cost for carried over" do @iteration.carry_over.total_cost.should == 47 end it "should have expected items completed" do @iteration.completed.size.should == 23 end it "should have expected cost for completed" do @iteration.completed.total_cost.should == 39 end it "should have expected velocity" do @iteration.velocity.should == 9.75 end it "should compute changed" do q =<<EOQ http://bugzilla.songbirdnest.com/buglist.cgi?quicksearch=6607%2C6693%2C4845%2C6923%2C5981%2C6316%2C6294%2C6346%2C6490%2C6796%2C6912%2C6922%2C6933%2C6937%2C6949%2C6952%2C6953%2C6954%2C6955%2C6963%2C6989%2C6993%2C7005%2C7006%2C7008%2C7009 EOQ @iteration.changed.should == View.from_query(Query.from_s(q)) end it "should have expected items that changed" do @iteration.changed.size.should == 26 end it "should compute net intake cost" do @iteration.changed_net_cost.should == 31 end end end
skelliam/sdpbot
spec/dokken_iteration_3_spec.rb
Ruby
mit
5,352
class TweetsController < ApplicationController def create # Planned on rendering json for line 6 to Ajax a new post back onto the page # But this single-app feature wouldn't grab new tweets. Having it live update # through streaming would take care of this, otherwise, just refresh page client.update(params[:tweet]) redirect_to root_path end end
heycait/twitter
app/controllers/tweets_controller.rb
Ruby
mit
371
<?php defined('BASEPATH') OR exit('No direct script access allowed'); /* | ------------------------------------------------------------------- | AUTO-LOADER | ------------------------------------------------------------------- | This file specifies which systems should be loaded by default. | | In order to keep the framework as light-weight as possible only the | absolute minimal resources are loaded by default. For example, | the database is not connected to automatically since no assumption | is made regarding whether you intend to use it. This file lets | you globally define which systems you would like loaded with every | request. | | ------------------------------------------------------------------- | Instructions | ------------------------------------------------------------------- | | These are the things you can load automatically: | | 1. Packages | 2. Libraries | 3. Drivers | 4. Helper files | 5. Custom config files | 6. Language files | 7. Models | */ /* | ------------------------------------------------------------------- | Auto-load Packages | ------------------------------------------------------------------- | Prototype: | | $autoload['packages'] = array(APPPATH.'third_party', '/usr/local/shared'); | */ $autoload['packages'] = array('database'); /* | ------------------------------------------------------------------- | Auto-load Libraries | ------------------------------------------------------------------- | These are the classes located in the system/libraries folder | or in your application/libraries folder. | | Prototype: | | $autoload['libraries'] = array('database', 'email', 'session'); | | You can also supply an alternative library name to be assigned | in the controller: | | $autoload['libraries'] = array('user_agent' => 'ua'); */ $autoload['libraries'] = array('session','database'); /* | ------------------------------------------------------------------- | Auto-load Drivers | ------------------------------------------------------------------- | These classes are located in the system/libraries folder or in your | application/libraries folder within their own subdirectory. They | offer multiple interchangeable driver options. | | Prototype: | | $autoload['drivers'] = array('cache'); */ $autoload['drivers'] = array(); /* | ------------------------------------------------------------------- | Auto-load Helper Files | ------------------------------------------------------------------- | Prototype: | | $autoload['helper'] = array('url', 'file'); */ $autoload['helper'] = array('url'); /* | ------------------------------------------------------------------- | Auto-load Config files | ------------------------------------------------------------------- | Prototype: | | $autoload['config'] = array('config1', 'config2'); | | NOTE: This item is intended for use ONLY if you have created custom | config files. Otherwise, leave it blank. | */ $autoload['config'] = array(); /* | ------------------------------------------------------------------- | Auto-load Language files | ------------------------------------------------------------------- | Prototype: | | $autoload['language'] = array('lang1', 'lang2'); | | NOTE: Do not include the "_lang" part of your file. For example | "codeigniter_lang.php" would be referenced as array('codeigniter'); | */ $autoload['language'] = array(); /* | ------------------------------------------------------------------- | Auto-load Models | ------------------------------------------------------------------- | Prototype: | | $autoload['model'] = array('first_model', 'second_model'); | | You can also supply an alternative model name to be assigned | in the controller: | | $autoload['model'] = array('first_model' => 'first'); */ $autoload['model'] = array('Cdn_model' => 'cdn');
opengbu/gbuonline
application/config/autoload.php
PHP
mit
3,814
#include <iostream> #include <seqan/file.h> #include <seqan/sequence.h> #include <seqan/score.h> template <typename TText, typename TPattern> int computeLocalScore(TText const &subText, TPattern const &pattern) { int localScore = 0; for (unsigned i = 0; i < seqan::length(pattern); ++i) if (subText[i] == pattern[i]) ++localScore; return localScore; } template <typename TText> int computeLocalScore(TText const & subText, seqan::String<seqan::AminoAcid> const & pattern) { int localScore = 0; for (unsigned i = 0; i < seqan::length(pattern); ++i) localScore += seqan::score(seqan::Blosum62(), subText[i], pattern[i]); return localScore; } template <typename TText, typename TPattern> seqan::String<int> computeScore(TText const &text, TPattern const &pattern) { seqan::String<int> score; seqan::resize(score, seqan::length(text), 0); for (unsigned i = 0; i < seqan::length(text) - seqan::length(pattern) + 1; ++i) score[i] = computeLocalScore(infix(text, i, i + seqan::length(pattern)), pattern); return score; } template <typename Ty> void print(Ty const &score) { for (unsigned i = 0; i < seqan::length(score); ++i) {std::cout << score[i] << " ";} std::cout << std::endl; } template <> void print(seqan::String<int> const &score) { for (unsigned i = 0; i < seqan::length(score); ++i) {std::cout << score[i] << " ";} std::cout << std::endl; } int main() { seqan::String<char> text = "This is an awesome tutorial to get to now SeqAn!"; seqan::String<char> pattern = "tutorial"; seqan::String<int> score = computeScore(text, pattern); print(score); return 0; }
bkahlert/seqan-research
raw/pmsb13/pmsb13-data-20130530/sources/caivjx2geotu92t0/2013-04-09T16-09-03.492+0200/sandbox/my_sandbox/apps/firstSteps1/firstSteps1.cpp
C++
mit
1,740
package denvlib import ( "encoding/json" "io/ioutil" "os" git "github.com/buckhx/gitlib" "github.com/buckhx/pathutil" ) /* DenvInfo is a mechanism for handling state of the denv environment. It flushed it's contents to disk and reads from a given location */ type DenvInfo struct { Current *Denv Path string Repository *git.Repository } var Info DenvInfo func (d *DenvInfo) Clear() { d.Current = nil } func (d *DenvInfo) Flush() { content := []byte(d.ToString()) err := ioutil.WriteFile(d.Path, content, 0644) check(err) } func (d *DenvInfo) IsActive() bool { return d.Current != nil } func (d *DenvInfo) Load() { //TODO make sure that this is an available file content, err := ioutil.ReadFile(d.Path) check(err) err = json.Unmarshal(content, &d) check(err) } func (d *DenvInfo) ToString() string { content, err := json.Marshal(d) check(err) return string(content) } func bootstrap() error { //TODO: maybe this should live somewhere else // Create DENVHOME if !pathutil.Exists(Settings.DenvHome) { err := os.MkdirAll(Settings.DenvHome, 0744) if err != nil { return err } } if !git.IsRepository(Settings.DenvHome) { repo, err := git.NewRepository(Settings.DenvHome) check(err) repo.Init() repo.Exclude("/.*") // exclude hidden root files } return nil } func init() { bootstrap() path := Settings.InfoFile Info.Path = path repo, err := git.NewRepository(Settings.DenvHome) check(err) Info.Repository = repo if !pathutil.Exists(path) { Info.Flush() } Info.Load() }
buckhx/denv
denvlib/info.go
GO
mit
1,538
<?php /** * Created by JetBrains PhpStorm. * User: etienne.lejariel * Date: 03/07/15 * Time: 09:46 * To change this template use File | Settings | File Templates. */ namespace Enneite\SwaggerBundle\Tests\Creator; use Symfony\Bundle\FrameworkBundle\Test\WebTestCase; use Enneite\SwaggerBundle\Creator\ApiControllerCreator; class ApiControllerCreatorTest extends WebTestCase { public function setup() { //$this->config = json_decode(file_get_contents(realpath( __DIR__ .'/../../Resources/example/config/swagger.json')), true); } public function testConstructAndGetters() { $twig = $this->getMockBuilder('\Twig_Environment')->disableOriginalConstructor()->getMock(); $apiModelCreator = $this->getMockBuilder('Enneite\SwaggerBundle\Creator\ApiModelCreator')->disableOriginalConstructor()->getMock(); $apiRoutingCreator = $this->getMockBuilder('Enneite\SwaggerBundle\Creator\ApiRoutingCreator')->disableOriginalConstructor()->getMock(); $creator = new ApiControllerCreator($twig, $apiModelCreator, $apiRoutingCreator); $this->assertInstanceOf('\Twig_Environment', $creator->getTwig(), 'twigEnv property must be an instance of \Twig_Environment'); $this->assertInstanceOf('Enneite\SwaggerBundle\Creator\ApiModelCreator', \PHPUnit_Framework_Assert::readAttribute($creator, 'apiModelCreator')); $this->assertInstanceOf('Enneite\SwaggerBundle\Creator\ApiRoutingCreator', \PHPUnit_Framework_Assert::readAttribute($creator, 'apiRoutingCreator')); } public function testGetAvailableExceptions() { $twig = $this->getMockBuilder('\Twig_Environment')->disableOriginalConstructor()->getMock(); $apiModelCreator = $this->getMockBuilder('Enneite\SwaggerBundle\Creator\ApiModelCreator')->disableOriginalConstructor()->getMock(); $apiRoutingCreator = $this->getMockBuilder('Enneite\SwaggerBundle\Creator\ApiRoutingCreator')->disableOriginalConstructor()->getMock(); $creator = new ApiControllerCreator($twig, $apiModelCreator, $apiRoutingCreator); $exceptions = $creator->getAvailableExceptions(); $this->assertInternalType('array', $exceptions); foreach (array(401, 403, 404) as $status) { $this->assertArrayHasKey($status, $exceptions); } } public function testHasResponseSchema() { $twig = $this->getMockBuilder('\Twig_Environment')->disableOriginalConstructor()->getMock(); $apiModelCreator = $this->getMockBuilder('Enneite\SwaggerBundle\Creator\ApiModelCreator')->disableOriginalConstructor()->getMock(); $apiRoutingCreator = $this->getMockBuilder('Enneite\SwaggerBundle\Creator\ApiRoutingCreator')->disableOriginalConstructor()->getMock(); $creator = new ApiControllerCreator($twig, $apiModelCreator, $apiRoutingCreator); $response = array( 'description' => 'successful operation', ); $this->assertFalse($creator->hasResponseSchema($response)); $response = array( 'description' => 'successful operation', 'schema' => array( 'type' => 'array', ), 'items' => array( "\$ref" => '#/definitions/Pet', ), ); $this->assertTrue($creator->hasResponseSchema($response)); } public function testHasResponseModel() { $twig = $this->getMockBuilder('\Twig_Environment')->disableOriginalConstructor()->getMock(); $apiModelCreator = $this->getMockBuilder('Enneite\SwaggerBundle\Creator\ApiModelCreator')->disableOriginalConstructor()->getMock(); $apiRoutingCreator = $this->getMockBuilder('Enneite\SwaggerBundle\Creator\ApiRoutingCreator')->disableOriginalConstructor()->getMock(); $creator = new ApiControllerCreator($twig, $apiModelCreator, $apiRoutingCreator); $response = array( 'description' => 'successful operation', ); $this->assertFalse($creator->hasResponseModel($response)); $response = array( 'description' => 'successful operation', 'schema' => array( 'type' => 'array', ), 'items' => array( "\$ref" => '#/definitions/Pet', ), ); $this->assertFalse($creator->hasResponseModel($response)); $response = array( 'description' => 'successful operation', 'schema' => array( "\$ref" => '#/definitions/Pet', ), ); $this->assertTrue($creator->hasResponseModel($response)); } public function testHasResponseCollection() { $twig = $this->getMockBuilder('\Twig_Environment')->disableOriginalConstructor()->getMock(); $apiModelCreator = $this->getMockBuilder('Enneite\SwaggerBundle\Creator\ApiModelCreator')->disableOriginalConstructor()->getMock(); $apiRoutingCreator = $this->getMockBuilder('Enneite\SwaggerBundle\Creator\ApiRoutingCreator')->disableOriginalConstructor()->getMock(); $creator = new ApiControllerCreator($twig, $apiModelCreator, $apiRoutingCreator); $response = array( 'description' => 'successful operation', ); $this->assertFalse($creator->hasResponseCollection($response)); $response = array( 'description' => 'successful operation', 'schema' => array( 'type' => 'array', 'items' => array( "\$ref" => '#/definitions/Pet', ), ), ); $this->assertTrue($creator->hasResponseCollection($response)); $response = array( 'description' => 'successful operation', 'schema' => array( "\$ref" => '#/definitions/Pet', ), ); $this->assertfalse($creator->hasResponseCollection($response)); } /** * @expectedException \Exception */ public function testHasResponseCollectionWithException() { $twig = $this->getMockBuilder('\Twig_Environment')->disableOriginalConstructor()->getMock(); $apiModelCreator = $this->getMockBuilder('Enneite\SwaggerBundle\Creator\ApiModelCreator')->disableOriginalConstructor()->getMock(); $apiRoutingCreator = $this->getMockBuilder('Enneite\SwaggerBundle\Creator\ApiRoutingCreator')->disableOriginalConstructor()->getMock(); $creator = new ApiControllerCreator($twig, $apiModelCreator, $apiRoutingCreator); $response = array( 'description' => 'successful operation', 'schema' => array( 'type' => 'array', ), ); $res = $creator->hasResponseCollection($response); } public function testGetAssociatedModel() { $twig = $this->getMockBuilder('\Twig_Environment')->disableOriginalConstructor()->getMock(); $apiModelCreator = $this->getMockBuilder('Enneite\SwaggerBundle\Creator\ApiModelCreator')->disableOriginalConstructor()->getMock(); $apiModelCreator->expects($this->any()) ->method('extractModel') ->will($this->returnValue('Pet')); $apiRoutingCreator = $this->getMockBuilder('Enneite\SwaggerBundle\Creator\ApiRoutingCreator')->disableOriginalConstructor()->getMock(); $creator = new ApiControllerCreator($twig, $apiModelCreator, $apiRoutingCreator); $response = array( 'description' => 'successful operation', 'schema' => array( "\$ref" => '#/definitions/Pet', ), ); $res = $creator->getAssociatedModel($response); $this->assertEquals('Pet', $res); $response = array( 'description' => 'successful operation', 'schema' => array( 'type' => 'array', 'items' => array( "\$ref" => '#/definitions/Pet', ), ), ); $res = $creator->getAssociatedModel($response); $this->assertEquals(false, $res); } public function testGetAssociatedCollection() { $twig = $this->getMockBuilder('\Twig_Environment')->disableOriginalConstructor()->getMock(); $apiModelCreator = $this->getMockBuilder('Enneite\SwaggerBundle\Creator\ApiModelCreator')->disableOriginalConstructor()->getMock(); $apiModelCreator->expects($this->any()) ->method('extractModel') ->will($this->returnValue('Pet')); $apiRoutingCreator = $this->getMockBuilder('Enneite\SwaggerBundle\Creator\ApiRoutingCreator')->disableOriginalConstructor()->getMock(); $creator = new ApiControllerCreator($twig, $apiModelCreator, $apiRoutingCreator); $response = array( 'description' => 'successful operation', 'schema' => array( "\$ref" => '#/definitions/Pet', ), ); $res = $creator->getAssociatedCollection($response); $this->assertEquals(false, $res); $response = array( 'description' => 'successful operation', 'schema' => array( 'type' => 'array', 'items' => array( "\$ref" => '#/definitions/Pet', ), ), ); $res = $creator->getAssociatedCollection($response); $this->assertEquals('PetCollection', $res); } public function testExtractCodesbyStatus() { $twig = $this->getMockBuilder('\Twig_Environment')->disableOriginalConstructor()->getMock(); $apiModelCreator = $this->getMockBuilder('Enneite\SwaggerBundle\Creator\ApiModelCreator')->disableOriginalConstructor()->getMock(); $apiRoutingCreator = $this->getMockBuilder('Enneite\SwaggerBundle\Creator\ApiRoutingCreator')->disableOriginalConstructor()->getMock(); $creator = new ApiControllerCreator($twig, $apiModelCreator, $apiRoutingCreator); $this->assertEquals(array(200), $creator->extractCodesByStatus(array(200, 401, 403, 500), 2)); $this->assertEquals(array(), $creator->extractCodesByStatus(array(200, 401, 403, 500), 3)); $this->assertEquals(array(401, 403), $creator->extractCodesByStatus(array(200, 401, 403, 500), 4)); $this->assertEquals(array(500), $creator->extractCodesByStatus(array(200, 401, 403, 500), 5)); } public function testGetActionParameters() { $twig = $this->getMockBuilder('\Twig_Environment')->disableOriginalConstructor()->getMock(); $apiModelCreator = $this->getMockBuilder('Enneite\SwaggerBundle\Creator\ApiModelCreator')->disableOriginalConstructor()->getMock(); $apiModelCreator->expects($this->any()) ->method('formatProperty') ->will($this->returnValue('myVariable')); $apiRoutingCreator = $this->getMockBuilder('Enneite\SwaggerBundle\Creator\ApiRoutingCreator')->disableOriginalConstructor()->getMock(); $creator = new ApiControllerCreator($twig, $apiModelCreator, $apiRoutingCreator); $objects = array( 'parameters' => array( array( 'description' => 'titi tata', 'name' => 'code', 'in' => 'path', 'type' => 'integer', 'required' => true, ), array( 'description' => 'user language', 'name' => 'Accept-language', 'in' => 'header', 'type' => 'string', ), ), ); $this->assertEquals(array( array( 'description' => null, 'name' => 'myVariable', 'in' => 'path', 'type' => 'integer', 'required' => true, ), array( 'description' => 'user language', 'name' => 'myVariable', 'in' => 'header', 'type' => 'string', 'required' => false, ), ), $creator->getActionParameters('get', $objects)); } /** * @expectedException \Exception */ public function testGetActionParametersWithException() { $twig = $this->getMockBuilder('\Twig_Environment')->disableOriginalConstructor()->getMock(); $apiModelCreator = $this->getMockBuilder('Enneite\SwaggerBundle\Creator\ApiModelCreator')->disableOriginalConstructor()->getMock(); $apiRoutingCreator = $this->getMockBuilder('Enneite\SwaggerBundle\Creator\ApiRoutingCreator')->disableOriginalConstructor()->getMock(); $creator = new ApiControllerCreator($twig, $apiModelCreator, $apiRoutingCreator); $objects = array( 'parameters' => array( array( 'description' => 'titi tata', 'name' => 'code', // 'in' => 'path', // parameter 'in' is missing => will throw an exception 'type' => 'integer', 'required' => true, ), ), ); $res = $creator->getActionParameters('get', $objects); } public function testCreateActionParameters() { $php = '(Request $request, $id)'; $template = $this->getMockBuilder('\Twig_Template')->disableOriginalConstructor()->getMock(); $template->expects($this->any()) ->method('render') ->will($this->returnvalue($php)); $twig = $this->getMockBuilder('\Twig_Environment')->disableOriginalConstructor()->getMock(); $twig->expects($this->any()) ->method('loadTemplate') ->will($this->returnvalue($template)); $apiModelCreator = $this->getMockBuilder('Enneite\SwaggerBundle\Creator\ApiModelCreator')->disableOriginalConstructor()->getMock(); $apiRoutingCreator = $this->getMockBuilder('Enneite\SwaggerBundle\Creator\ApiRoutingCreator')->disableOriginalConstructor()->getMock(); $creator = new ApiControllerCreator($twig, $apiModelCreator, $apiRoutingCreator); $objects = array( 'parameters' => array( array( 'name' => 'id', 'in' => 'path', 'type' => 'integer', 'required' => true, ), ), ); $this->assertEquals($php, $creator->createActionParameters('get', $objects)); } /** * @expectedException \Exception */ public function testCreateActionParametersWithException() { $twig = $this->getMockBuilder('\Twig_Environment')->disableOriginalConstructor()->getMock(); $apiModelCreator = $this->getMockBuilder('Enneite\SwaggerBundle\Creator\ApiModelCreator')->disableOriginalConstructor()->getMock(); $apiRoutingCreator = $this->getMockBuilder('Enneite\SwaggerBundle\Creator\ApiRoutingCreator')->disableOriginalConstructor()->getMock(); $creator = new ApiControllerCreator($twig, $apiModelCreator, $apiRoutingCreator); $objects = array( 'parameters' => array( array( 'name' => 'id', // 'in' => 'path', // parameter 'in' is missing => will throw an exception 'type' => 'integer', 'required' => true, ), ), ); $res = $creator->createActionParameters(200, $objects); } /** * */ public function testGetRoutingAnnotation() { $twig = $this->getMockBuilder('\Twig_Environment')->disableOriginalConstructor()->getMock(); $apiModelCreator = $this->getMockBuilder('Enneite\SwaggerBundle\Creator\ApiModelCreator')->disableOriginalConstructor()->getMock(); $apiRoutingCreator = $this->getMockBuilder('Enneite\SwaggerBundle\Creator\ApiRoutingCreator')->disableOriginalConstructor()->getMock(); $apiRoutingCreator->expects($this->any()) ->method('getRouteParametersAsArray') ->will($this->returnvalue(array())); $creator = new ApiControllerCreator($twig, $apiModelCreator, $apiRoutingCreator); $objects = array( 'parameters' => array( array( 'name' => 'id', // 'in' => 'path', // parameter 'in' is missing => will throw an exception 'type' => 'integer', 'required' => true, ), ), ); $this->assertEquals(array( 'route' => '/pets', 'parameters' => array(), 'method' => 'GET', ), $creator->getRoutingAnnotation('get', $objects, '/pets')); } /** * */ public function testGetActionComments() { $twig = $this->getMockBuilder('\Twig_Environment')->disableOriginalConstructor()->getMock(); $apiModelCreator = $this->getMockBuilder('Enneite\SwaggerBundle\Creator\ApiModelCreator')->disableOriginalConstructor()->getMock(); $apiModelCreator->expects($this->any()) ->method('formatProperty') ->will($this->returnvalue('id')); $apiRoutingCreator = $this->getMockBuilder('Enneite\SwaggerBundle\Creator\ApiRoutingCreator')->disableOriginalConstructor()->getMock(); $apiRoutingCreator->expects($this->any()) ->method('getRouteParametersAsArray') ->will($this->returnvalue(array())); $creator = new ApiControllerCreator($twig, $apiModelCreator, $apiRoutingCreator); // case 1 : without routing annotation generation and with description set $objects = array( 'description' => 'this is a good description', 'parameters' => array( array( 'name' => 'id', 'in' => 'path', // parameter 'in' is missing => will throw an exception 'type' => 'integer', 'required' => true, ), ), ); $this->assertEquals(array( 'description' => 'this is a good description', 'routing' => null, 'params' => array('id'), ), $creator->getActionComments('get', $objects, '/pets', false)); // case 2 : with routing annotation generation and no description set $objects = array( 'parameters' => array( array( 'name' => 'id', 'in' => 'path', // parameter 'in' is missing => will throw an exception 'type' => 'integer', 'required' => true, ), ), ); $this->assertEquals(array( 'description' => 'empty', 'routing' => array( 'route' => '/pets', 'parameters' => array(), 'method' => 'GET', ), 'params' => array('id'), ), $creator->getActionComments('get', $objects, '/pets', true)); } public function testExtractArguments() { include_once __DIR__ . '/../Controller/Mock/ProductController.php'; $reflexion = new \ReflectionClass('Enneite\SwaggerBundle\Tests\Controller\Mock\ProductController'); $method = $reflexion->getMethod('getAction'); $twig = $this->getMockBuilder('\Twig_Environment')->disableOriginalConstructor()->getMock(); $apiModelCreator = $this->getMockBuilder('Enneite\SwaggerBundle\Creator\ApiModelCreator')->disableOriginalConstructor()->getMock(); $apiRoutingCreator = $this->getMockBuilder('Enneite\SwaggerBundle\Creator\ApiRoutingCreator')->disableOriginalConstructor()->getMock(); $creator = new ApiControllerCreator($twig, $apiModelCreator, $apiRoutingCreator); $this->assertEquals(array('id'), $creator->extractArguments($method)); } public function testGetSchemaResponse() { $php = '(Request $request, $id)'; $template = $this->getMockBuilder('\Twig_Template')->disableOriginalConstructor()->getMock(); $template->expects($this->any()) ->method('render') ->will($this->returnvalue($php)); $twig = $this->getMockBuilder('\Twig_Environment')->disableOriginalConstructor()->getMock(); $twig->expects($this->any()) ->method('loadTemplate') ->will($this->returnvalue($template)); $apiModelCreator = $this->getMockBuilder('Enneite\SwaggerBundle\Creator\ApiModelCreator')->disableOriginalConstructor()->getMock(); $apiModelCreator->expects($this->any()) ->method('extractModel') ->will($this->returnvalue('Product')); $apiRoutingCreator = $this->getMockBuilder('Enneite\SwaggerBundle\Creator\ApiRoutingCreator')->disableOriginalConstructor()->getMock(); $creator = new ApiControllerCreator($twig, $apiModelCreator, $apiRoutingCreator); // tests the template twig arguments generation : $this->assertEquals(array('model' => null, 'method' => null), $creator->getSchemaPhpCode(array())); $this->assertEquals(array('model' => null, 'method' => null), $creator->getSchemaPhpCode(array('schema' => array('type' => 'string')))); $this->assertEquals(array('model' => 'Product', 'method' => 'buildResource'), $creator->getSchemaPhpCode(array( 'schema' => array( '$ref' => '#/definitions/Product', ), ))); $this->assertEquals(array('model' => 'Product', 'method' => 'buildCollection'), $creator->getSchemaPhpCode(array( 'schema' => array( 'type' => 'array', 'items' => array( '$ref' => '#/definitions/Product', ), ), ))); // test the php generation code : $this->assertEquals($php, $creator->createSchemaPhpCode(array())); } public function testCreateClassName() { $twig = $this->getMockBuilder('\Twig_Environment')->disableOriginalConstructor()->getMock(); $apiModelCreator = $this->getMockBuilder('Enneite\SwaggerBundle\Creator\ApiModelCreator')->disableOriginalConstructor()->getMock(); $apiRoutingCreator = $this->getMockBuilder('Enneite\SwaggerBundle\Creator\ApiRoutingCreator')->disableOriginalConstructor()->getMock(); $creator = new ApiControllerCreator($twig, $apiModelCreator, $apiRoutingCreator); $this->assertEquals('PetsController', $creator->getClassName('/pets')); $this->assertEquals('PetsIdController', $creator->getClassName('/pets/{id}')); $this->assertEquals('PetsIdController', $creator->getClassName('/pets/*/{id}$$$')); } }
enneite/swagger-bundle
Tests/Creator/ApiControllerCreatorTest.php
PHP
mit
23,086
var notify = require('gulp-notify'), path = require('path'); var c = exports; c.all = allFiles; c.target = targetFolder; c.TARGET_FOLDER = "./dist"; // fonts c.FOLDER_FONTS = './node_modules/font-awesome/fonts/*'; c.TARGET_FOLDER_FONTS = 'fonts'; // images c.FOLDER_IMAGES = './resources/images/*'; c.TARGET_FOLDER_IMAGES = 'images'; // images c.FOLDER_SOUNDS = './resources/sounds/*'; c.TARGET_FOLDER_SOUNDS = 'sounds'; // less c.FOLDER_LESS = './resources/less'; c.PATH_LESS_ENTRY = './resources/less/app.less'; c.TARGET_FILE_CSS = 'app.css'; c.TARGET_PATH_CSS = 'css/app.css'; c.TARGET_FOLDER_CSS = 'css'; // js c.FOLDER_JS = './resources/js'; c.PATH_JS_ENTRY = './resources/js/app.js'; c.TARGET_FILE_JS = 'app.js'; c.TARGET_PATH_JS = 'js/app.js'; c.TARGET_FOLDER_JS = 'js'; // html files c.PATH_INDEX = "./resources/html/index.html"; c.FOLDER_TEMPLATES = "./resources/templates"; // tests c.FOLDER_TESTS = './resources/js/tests'; // rev c.FILES_REV = [ { name: "appCss", entryPath: c.TARGET_PATH_CSS, targetFile: c.TARGET_FILE_CSS }, { name: "appJs", entryPath: c.TARGET_PATH_JS, targetFile: c.TARGET_FILE_JS }, ]; c.TARGET_FOLDER_ALL = [ c.TARGET_FOLDER_CSS, c.TARGET_FOLDER_FONTS, c.TARGET_FOLDER_JS ] .map(targetFolder) .map(function (folder) { return path.join(folder, "**"); }); c.notify = function (title, message) { return notify({ title: title, message: message }); }; c.notifyError = function notifyError (description) { return function () { var args = [].slice.call(arguments); notify.onError({ title: description + " error", message: "<%= error.message %>" }).apply(this, args); this.emit('end'); // Keep gulp from hanging on this task }; }; function allFiles (folder) { return path.join(folder, '**'); } function targetFolder (folder) { var root = c.TARGET_FOLDER; if (folder) { return path.join(root, folder); } return root; }
bekk/bekkboard
GUI/tasks/config.js
JavaScript
mit
1,991
# -*- coding: utf-8 -*- # Generated by Django 1.10.2 on 2017-08-17 20:30 from __future__ import unicode_literals from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): dependencies = [ ('app_pessoa', '0004_auto_20170817_1727'), ] operations = [ migrations.AlterField( model_name='pessoa', name='profissao', field=models.ForeignKey(null=True, on_delete=django.db.models.deletion.CASCADE, to='app_pessoa.Profissao'), ), ]
LEDS/X-data
Xdata/app_pessoa/migrations/0005_auto_20170817_1730.py
Python
mit
559
class AvailabilitiesController < ApplicationController before_action :authorise_booking_manager! def show @search = SlotSearch.new(search_params) @slots = @search.results end private def search_params params .fetch(:search, {}) .permit(:date, :room, :available) .merge( page: params[:page], location: location ) end def rooms @rooms ||= location.rooms.order(:name) end helper_method :rooms def location @location ||= current_user.locations.find(params[:location_id]) end helper_method :location end
guidance-guarantee-programme/tesco_planner
app/controllers/availabilities_controller.rb
Ruby
mit
589
#include "Build.h" #include "Profiler.h" #include "config/Git.h" #include "config/Version.h" #include <sstream> #include <vector> //OS #if defined(PR_OS_LINUX) #define PR_OS_NAME "Linux" #elif defined(PR_OS_WINDOWS_32) #define PR_OS_NAME "Microsoft Windows 32 Bit" #elif defined(PR_OS_WINDOWS_64) #define PR_OS_NAME "Microsoft Windows 64 Bit" #else #define PR_OS_NAME "Unknown" #endif //Compiler #if defined(PR_CC_CYGWIN) #define PR_CC_NAME "Cygwin" #endif #if defined(PR_CC_GNU) #define PR_CC_NAME "GNU C/C++" #endif #if defined(PR_CC_MINGW32) #if !defined(PR_CC_GNU) #define PR_CC_NAME "MinGW 32" #else #undef PR_CC_NAME #define PR_CC_NAME "GNU C/C++(MinGW 32)" #endif #endif #if defined(PR_CC_INTEL) #define PR_CC_NAME "Intel C/C++" #endif #if defined(PR_CC_MSC) #define PR_CC_NAME "Microsoft Visual C++" #endif #if !defined(PR_CC_NAME) #define PR_CC_NAME "Unknown" #endif #if defined(PR_DEBUG) #define PR_BUILDVARIANT_NAME "Debug" #else #define PR_BUILDVARIANT_NAME "Release" #endif namespace PR { namespace Build { Version getVersion() { return Version{ PR_VERSION_MAJOR, PR_VERSION_MINOR }; } std::string getVersionString() { return PR_VERSION_STRING; } std::string getGitString() { return PR_GIT_BRANCH " " PR_GIT_REVISION; } std::string getCopyrightString() { return PR_NAME_STRING " " PR_VERSION_STRING " (C) " PR_VENDOR_STRING; } std::string getCompilerName() { return PR_CC_NAME; } std::string getOSName() { return PR_OS_NAME; } std::string getBuildVariant() { return PR_BUILDVARIANT_NAME; } std::string getFeatureSet() { std::vector<std::string> list; // Skip basic features required by x64 anyway /*#ifdef PR_HAS_HW_FEATURE_MMX list.emplace_back("MMX"); #endif #ifdef PR_HAS_HW_FEATURE_SSE list.emplace_back("SSE"); #endif #ifdef PR_HAS_HW_FEATURE_SSE2 list.emplace_back("SSE2"); #endif*/ #ifdef PR_HAS_HW_FEATURE_SSE3 list.emplace_back("SSE3"); #endif #ifdef PR_HAS_HW_FEATURE_SSSE3 list.emplace_back("SSSE3"); #endif #ifdef PR_HAS_HW_FEATURE_SSE4_1 list.emplace_back("SSE4.1"); #endif #ifdef PR_HAS_HW_FEATURE_SSE4_2 list.emplace_back("SSE4.2"); #endif #ifdef PR_HAS_HW_FEATURE_AVX list.emplace_back("AVX"); #endif #ifdef PR_HAS_HW_FEATURE_AVX2 list.emplace_back("AVX2"); #endif #ifdef PR_HAS_HW_FEATURE_AVX512_F list.emplace_back("AVX512_F"); #endif #ifdef PR_HAS_HW_FEATURE_AVX512_DQ list.emplace_back("AVX512_DQ"); #endif #ifdef PR_HAS_HW_FEATURE_AVX512_IFMA list.emplace_back("AVX512_IFMA"); #endif #ifdef PR_HAS_HW_FEATURE_AVX512_PF list.emplace_back("AVX512_PF"); #endif #ifdef PR_HAS_HW_FEATURE_AVX512_ER list.emplace_back("AVX512_ER"); #endif #ifdef PR_HAS_HW_FEATURE_AVX512_CD list.emplace_back("AVX512_CD"); #endif #ifdef PR_HAS_HW_FEATURE_AVX512_BW list.emplace_back("AVX512_BW"); #endif #ifdef PR_HAS_HW_FEATURE_AVX512_VL list.emplace_back("AVX512_VL"); #endif #ifdef PR_HAS_HW_FEATURE_AVX512_VBMI list.emplace_back("AVX512_VBMI"); #endif #ifdef PR_HAS_HW_FEATURE_AVX512_VBMI2 list.emplace_back("AVX512_VBMI2"); #endif #ifdef PR_HAS_HW_FEATURE_AVX512_VNNI list.emplace_back("AVX512_VNNI"); #endif #ifdef PR_HAS_HW_FEATURE_AVX512_BITALG list.emplace_back("AVX512_BITALG"); #endif #ifdef PR_HAS_HW_FEATURE_AVX512_VPOPCNTDQ list.emplace_back("AVX512_VPOPCNTDQ"); #endif #ifdef PR_HAS_HW_FEATURE_AVX512_4VNNIW list.emplace_back("AVX512_4VNNIW"); #endif #ifdef PR_HAS_HW_FEATURE_AVX512_4FMAPS list.emplace_back("AVX512_4FMAPS"); #endif #ifdef PR_HAS_HW_FEATURE_AVX512_BF16 list.emplace_back("AVX512_BF16"); #endif #ifdef PR_HAS_HW_FEATURE_HLE list.emplace_back("HLE"); #endif #ifdef PR_HAS_HW_FEATURE_RTM list.emplace_back("RTM"); #endif #ifdef PR_HAS_HW_FEATURE_FMA list.emplace_back("FMA3"); #endif #ifdef PR_HAS_HW_FEATURE_FMA4 list.emplace_back("FMA4"); #endif #ifdef PR_HAS_HW_FEATURE_POPCNT list.emplace_back("POPCNT"); #endif if (list.empty()) return "NONE"; std::stringstream stream; for (size_t i = 0; i < (list.size() - 1); ++i) stream << list.at(i) << "; "; stream << list.back(); return stream.str(); } std::string getBuildString() { #ifdef PR_NO_ASSERTS constexpr bool hasAsserts = false; #else constexpr bool hasAsserts = true; #endif #ifdef PR_WITH_PROFILER constexpr bool hasProfiler = true; #else constexpr bool hasProfiler = false; #endif std::stringstream stream; stream << std::boolalpha << PR_NAME_STRING << " " << PR_VERSION_STRING << " (" << getBuildVariant() << ") on " __DATE__ " at " __TIME__ << " with " << getCompilerName() << " { OS: " << getOSName() << "; Branch: " PR_GIT_BRANCH << "; Rev: " PR_GIT_REVISION << "} [Features:<" << getFeatureSet() << ">; Asserts: " << hasAsserts << "; Profile: " << hasProfiler << "]"; return stream.str(); } } // namespace Build } // namespace PR
PearCoding/PearRay
src/base/config/Build.cpp
C++
mit
4,753
<?php class Contact_model extends CI_Model { function insert($arr = ''){ if(empty($arr)) return ; $sql = "insert into contact (name,email,message,ceatetime,ip) VALUES ('{$arr['name']}','{$arr['email']}','{$arr['message']}','".date('Y-m-d H:i:s')."','{$arr['ip']}')"; $this->db->query($sql); } }
0372/blog
blog/front/models/Contact_model.php
PHP
mit
327
package br.edu.fjn.maternidade.application.impl; import java.util.List; import br.edu.fjn.maternidade.application.SecretarioApplication; import br.edu.fjn.maternidade.domain.secretario.Secretario; import br.edu.fjn.maternidade.domain.secretario.SecretarioRepository; import br.edu.fjn.maternidade.domain.usuario.Usuario; import br.edu.fjn.maternidade.infraestructure.util.MaternidadeException; import br.edu.fjn.maternidade.repository.impl.SecretarioRepositoryImpl; public class SecretarioApplicationImpl implements SecretarioApplication { private SecretarioRepository repository = new SecretarioRepositoryImpl(); @Override public void inserir(Secretario secretario) { repository.inserir(secretario); } @Override public void alterar(Secretario secretario) { repository.alterar(secretario); } @Override public void apagar(Secretario secretario) throws MaternidadeException { if (repository.listar() != null) repository.apagar(secretario); else throw new MaternidadeException( "Voc� n�o pode remover este secret�rio, pois n�o existem outros cadastrados!"); } @Override public Secretario buscarPorId(Integer id) throws MaternidadeException { Secretario busca = repository.buscarPorId(id); if (busca == null) { throw new MaternidadeException("Não há registro de secretário para esta id"); } return busca; } @Override public List<Secretario> listar() throws MaternidadeException { List<Secretario> busca = repository.listar(); if (busca == null || busca.size() == 0) { throw new MaternidadeException("Não há registros de secretários"); } return busca; } @Override public Secretario buscarPorUsuario(Usuario usuario) throws MaternidadeException { Secretario busca = repository.buscarPorUsuario(usuario); if (busca == null) { throw new MaternidadeException("Não há registro de secretário para este usuário"); } return busca; } }
aldaypinheiro/maternidade-core
src/br/edu/fjn/maternidade/application/impl/SecretarioApplicationImpl.java
Java
mit
1,940
<?php session_start(); // declare that sessions are being used session_unset(); // unset sessions session_destroy(); // now destory them and remove them from the users browser header('Location: http://thewebbster.info/get/loginForm.php?logout=yes');// Forwards to a new page after logout exit(); // exit ?>
chwebb1/InsecureGetLoginFormPHP
logout.php
PHP
mit
413
lock '3.4.0' set :application, "people" set :repo_url, "git://github.com/netguru/people.git" set :deploy_to, ENV['DEPLOY_PATH'] set :docker_links, %w(postgres_ambassador:postgres) set :docker_additional_options, -> { "--env-file #{shared_path}/.env" } set :docker_apparmor_profile, "docker-ptrace" namespace :docker do namespace :npm do task :build do on roles(fetch(:docker_role)) do execute :docker, task_command("npm run build") end end end end after "docker:npm:install", "docker:npm:build"
netguru/people
config/deploy.rb
Ruby
mit
532
require 'spec_helper' # TODO: the usual respond_to? method doesn't seem to work on Thor objects. # Why not? For now, we'll check against instance_methods. RSpec.describe Moose::Inventory::Cli::Host do before(:all) do # Set up the configuration object @mockarg_parts = { config: File.join(spec_root, 'config/config.yml'), format: 'yaml', env: 'test', } @mockargs = [] @mockarg_parts.each do |key, val| @mockargs << "--#{key}" @mockargs << val end @config = Moose::Inventory::Config @config.init(@mockargs) @db = Moose::Inventory::DB @db.init if @db.db.nil? @host = Moose::Inventory::Cli::Host @app = Moose::Inventory::Cli::Application end before(:each) do @db.reset end #======================= describe 'addgroup' do #------------------------ it 'Host.addgroup() should be responsive' do result = @host.instance_methods(false).include?(:addgroup) expect(result).to eq(true) end #------------------------ it 'host addgroup <missing args> ... should abort with an error' do actual = runner do @app.start(%w(host addgroup)) # <- no group given end # Check output desired = { aborted: true } desired[:STDERR] = "ERROR: Wrong number of arguments, 0 for 2 or more.\n" expected(actual, desired) end #------------------------ it 'host addgroup HOST GROUP ... should abort if the host does not exist' do actual = runner do @app.start(%w(host addgroup not-a-host example)) end # Check output desired = { aborted: true } desired[:STDOUT] = "Associate host 'not-a-host' with groups 'example':\n"\ " - Retrieve host 'not-a-host'...\n" desired[:STDERR] = "An error occurred during a transaction, any changes have been rolled back.\n"\ "ERROR: The host 'not-a-host' was not found in the database.\n" expected(actual, desired) end #------------------------ it 'host addgroup HOST GROUP ... should add the host to an existing group' do # 1. Should add the host to the group # 2. Should remove the host from the 'ungrouped' automatic group name = 'test1' group_name = 'testgroup1' runner { @app.start(%W(host add #{name})) } @db.models[:group].create(name: group_name) actual = runner { @app.start(%W(host addgroup #{name} #{group_name})) } # rubocop:disable Metrics/LineLength desired = { aborted: false } desired[:STDOUT] = "Associate host '#{name}' with groups '#{group_name}':\n"\ " - Retrieve host '#{name}'...\n"\ " - OK\n"\ " - Add association {host:#{name} <-> group:#{group_name}}...\n"\ " - OK\n"\ " - Remove automatic association {host:#{name} <-> group:ungrouped}...\n"\ " - OK\n"\ " - All OK\n"\ "Succeeded\n" expected(actual, desired) # rubocop:enable Metrics/LineLength # We should have the correct group associations host = @db.models[:host].find(name: name) groups = host.groups_dataset expect(groups.count).to eq(1) expect(groups[name: group_name]).not_to be_nil expect(groups[name: 'ungrouped']).to be_nil # redundant, but for clarity! end #------------------------ it 'HOST \'ungrouped\' ... should abort with an error' do name = 'test1' group_name = 'ungrouped' runner { @app.start(%W(host add #{name})) } actual = runner { @app.start(%W(host addgroup #{name} #{group_name})) } desired = { aborted: true } desired[:STDERR] = "ERROR: Cannot manually manipulate the automatic group 'ungrouped'.\n" expected(actual, desired) end #------------------------ it 'HOST GROUP ... should add the host to an group, creating the group if necessary' do name = 'test1' group_name = 'testgroup1' runner { @app.start(%W(host add #{name})) } # DON'T CREATE THE GROUP! That's the point of the test. ;o) actual = runner { @app.start(%W(host addgroup #{name} #{group_name})) } # Check output desired = { aborted: false } desired[:STDOUT] = "Associate host '#{name}' with groups '#{group_name}':\n"\ " - Retrieve host '#{name}'...\n"\ " - OK\n"\ " - Add association {host:#{name} <-> group:#{group_name}}...\n"\ " - Group does not exist, creating now...\n"\ " - OK\n"\ " - OK\n"\ " - Remove automatic association {host:#{name} <-> group:ungrouped}...\n"\ " - OK\n"\ " - All OK\n"\ "Succeeded\n" desired[:STDERR] = "WARNING: Group '#{group_name}' does not exist and will be created." expected(actual, desired) # Check db host = @db.models[:host].find(name: name) groups = host.groups_dataset expect(groups.count).to eq(1) expect(groups[name: group_name]).not_to be_nil expect(groups[name: 'ungrouped']).to be_nil # redundant, but for clarity! end #------------------------ it 'HOST GROUP ... should skip associations that already '\ ' exist, but raise a warning.' do name = 'test1' group_name = 'testgroup1' runner { @app.start(%W(host add #{name})) } # DON'T CREATE THE GROUP! That's the point of the test. ;o) # Run once to make the association runner { @app.start(%W(host addgroup #{name} #{group_name})) } # Run again, to prove expected result actual = runner { @app.start(%W(host addgroup #{name} #{group_name})) } # Check output # Note: This time, we don't expect to see any messages about # dissociation from 'ungrouped' desired = { aborted: false } desired[:STDOUT] = "Associate host '#{name}' with groups '#{group_name}':\n"\ " - Retrieve host \'#{name}\'...\n"\ " - OK\n"\ " - Add association {host:#{name} <-> group:#{group_name}}...\n"\ " - Already exists, skipping.\n"\ " - OK\n"\ " - All OK\n"\ "Succeeded\n" desired[:STDERR] = "WARNING: Association {host:#{name} <-> group:#{group_name}} already exists, skipping." expected(actual, desired) # Check db host = @db.models[:host].find(name: name) groups = host.groups_dataset expect(groups.count).to eq(1) expect(groups[name: group_name]).not_to be_nil expect(groups[name: 'ungrouped']).to be_nil # redundant, but for clarity! end #------------------------ it 'host addgroup GROUP1 GROUP1 ... should add the host to'\ ' multiple groups at once' do name = 'test1' group_names = %w(group1 group2 group3) runner { @app.start(%W(host add #{name})) } actual = runner { @app.start(%W(host addgroup #{name}) + group_names) } # Check output desired = { aborted: false, STDERR: '' } desired[:STDOUT] = "Associate host '#{name}' with groups '#{group_names.join(',')}':\n"\ " - Retrieve host '#{name}'...\n"\ " - OK\n" group_names.each do |group| desired[:STDOUT] = desired[:STDOUT] + " - Add association {host:#{name} <-> group:#{group}}...\n"\ " - Group does not exist, creating now...\n"\ " - OK\n"\ " - OK\n" desired[:STDERR] = desired[:STDERR] + "WARNING: Group '#{group}' does not exist and will be created." end desired[:STDOUT] = desired[:STDOUT] + " - Remove automatic association {host:#{name} <-> group:ungrouped}...\n"\ " - OK\n"\ " - All OK\n"\ "Succeeded\n" expected(actual, desired) # We should have group associations host = @db.models[:host].find(name: name) groups = host.groups_dataset expect(groups).not_to be_nil # There should be 3 relationships, but not with 'ungrouped' expect(groups.count).to eq(3) group_names.each do |group| expect(groups[name: group]).not_to be_nil end expect(groups[name: 'ungrouped']).to be_nil end end end
RusDavies/moose-inventory
spec/lib/moose_inventory/cli/host_addgroup_spec.rb
Ruby
mit
8,359
$(function() { //switch the menu style in a area of site $(window).on("scroll", function() { var black_opacity = $("#top-session"); var projetos = $("#projetos"); var contatos = $("#contato"); var offsetblack_opacity = black_opacity.offset(); var offsetprojetos = projetos.offset(); var offsetcontatos = contatos.offset(); //scroll on top session div if($(window).scrollTop() >= offsetblack_opacity.top) { $("#menu-project").removeClass("menu-active"); $("#menu-inicio").addClass("menu-active"); $("#menu-contact").removeClass("menu-active"); $(".menu-text").css("color", "#FFF"); $("#ic_sn").attr("src", "images/sidenav_ic_light.png"); } //scroll on projects div if($(window).scrollTop() >= offsetprojetos.top) { $(".menu").addClass("menu2"); $("#menu-project").addClass("menu-active"); $("#menu-inicio").removeClass("menu-active"); $("#menu-contact").removeClass("menu-active"); $(".menu-text").css("color", "#282727"); $("#ic_sn").attr("src", "images/sidenav_ic_gray.png"); } else { $(".menu").removeClass("menu2"); } //scroll on contact div if($(window).scrollTop() >= offsetcontatos.top) { $("#menu-project").removeClass("menu-active"); $("#menu-inicio").removeClass("menu-active"); $("#menu-contact").addClass("menu-active"); } }); });
gabrieldev525/me
js/script-jquery.js
JavaScript
mit
1,335
<script type="text/javascript"> $(document).ready(function(){ $("#new-user").submit(function(e){ e.preventDefault(); if($("input[name=user_confirm_password]").val() != $("input[name=user_password]").val()){ $("input[name=user_password]").css("border-bottom", "1px solid red"); $("input[name=user_confirm_password]").css("border-bottom", "1px solid red").focus(); return false; }else{ $.ajax({ url: "<?php echo site_url('/UserController/createUser')?>", type: "POST", data: $("#new-user").serialize(), success: function(data){ if(data == 1){ Materialize.toast("Usuário cadastrado com sucesso", 4000); $("#new-user").each (function(){ this.reset(); }); }else{ Materialize.toast(data, 4000); } }, error: function(data){ console.log(data); Materialize.toast("Ocorreu algum erro", 4000); } }); } }); }); </script> <div class="container"> <div class="row"> <a href="<?=base_url('users') ?>">< Voltar para usuários</a> <div div class="row card-panel"> <h4 class="center">Novo Usuário</h4> <form id="new-user"> <div> <label for="user-name">Nome *</label> <input name="user_name" required="required" type="text"> </div> <div> <label for="user-name">Login de acesso *</label> <input name="user_login" required="required" type="text"> </div> <div> <label for="user-name">Senha *</label> <input name="user_password" required="required" type="password"> </div> <div> <label for="user-name">Confirmar senha *</label> <input name="user_confirm_password" required="required" type="password"> </div> <div class="" align="right"> <button type="submit" id="" class="btn green">Salvar<i class="material-icons right">send</i> </button> </div> </form> </div> </div> </div>
lds-ulbra-torres/projeto-slave
application/views/users/CreateUserView.php
PHP
mit
1,898
Items = new Mongo.Collection('items'); Items.allow({ insert: function(userId, doc) { return !!userId; }, update: function(userId, doc) { return !!userId; }, remove: function(userId, doc) { return !!userId; } }); ItemSchema = new SimpleSchema({ name: { type: String, label: "Item Name" }, description: { type: String, label: "Description" }, weight: { type: Number, label: "Weight" }, quantity: { type: Number, label: "Quantity" }, session: { type: String, label: "Session", autoValue: function(){ return this.userId }, autoform: { type: "hidden" } }, owner: { type: String, label: "Owner", defaultValue: "DM", autoform: { type: "hidden" } }, createdAt: { type: Date, label: "Created At", autoValue: function(){ return new Date() }, autoform: { type: "hidden" } }, inGroupStash: { type: Boolean, label: 'In Group Stash', defaultValue: false, autoform: { type: "hidden" } } }); Meteor.methods({ toggleGroupItem: function(id, currentState) { Items.update(id, { $set: { inGroupStash: !currentState } }); }, toggleDMItem: function(id) { Items.update(id, { $set: { owner: 'Group' } }); }, togglePlayerItem: function(id, newOwner) { Items.update(id, { $set: { owner: newOwner } }); } }); Items.attachSchema(ItemSchema);
mrogach2350/rpgLoot
collections/items.js
JavaScript
mit
1,589
package handler import ( "encoding/json" "io/ioutil" "net/http" "net/url" "strings" "github.com/playlyfe/go-graphql" "golang.org/x/net/context" ) //Shortcuts for the Content-Type header const ( ContentTypeJSON = "application/json" ContentTypeGraphQL = "application/graphql" ContentTypeFormURLEncoded = "application/x-www-form-urlencoded" ) //Handler structure type Handler struct { Executor *graphql.Executor Context interface{} Pretty bool } //RequestParameters from query like " /graphql?query=getUser($id:ID){lastName}&variables={"id":"4"} " type RequestParameters struct { Query string `json:"query" url:"query" schema:"query"` Variables map[string]interface{} `json:"variables" url:"variables" schema:"variables"` OperationName string `json:"operationName" url:"operationName" schema:"operationName"` } //RequestParametersCompatibility represents an workaround for getting`variables` as a JSON string type RequestParametersCompatibility struct { Query string `json:"query" url:"query" schema:"query"` Variables string `json:"variables" url:"variables" schema:"variables"` OperationName string `json:"operationName" url:"operationName" schema:"operationName"` } func getFromURL(values url.Values) *RequestParameters { if values.Get("query") != "" { // get variables map var variables map[string]interface{} variablesStr := values.Get("variables") json.Unmarshal([]byte(variablesStr), variables) return &RequestParameters{ Query: values.Get("query"), Variables: variables, OperationName: values.Get("operationName"), } } return nil } // NewRequestParameters Parses a http.Request into GraphQL request options struct func NewRequestParameters(r *http.Request) *RequestParameters { if reqParams := getFromURL(r.URL.Query()); reqParams != nil { return reqParams } if r.Method != "POST" { return &RequestParameters{} } if r.Body == nil { return &RequestParameters{} } // TODO: improve Content-Type handling contentTypeStr := r.Header.Get("Content-Type") contentTypeTokens := strings.Split(contentTypeStr, ";") contentType := contentTypeTokens[0] switch contentType { case ContentTypeGraphQL: body, err := ioutil.ReadAll(r.Body) if err != nil { return &RequestParameters{} } return &RequestParameters{ Query: string(body), } case ContentTypeFormURLEncoded: if err := r.ParseForm(); err != nil { return &RequestParameters{} } if reqParams := getFromURL(r.PostForm); reqParams != nil { return reqParams } return &RequestParameters{} case ContentTypeJSON: fallthrough default: var params RequestParameters body, err := ioutil.ReadAll(r.Body) if err != nil { return &params } err = json.Unmarshal(body, &params) if err != nil { // Probably `variables` was sent as a string instead of an object. // So, we try to be polite and try to parse that as a JSON string var CompatibleParams RequestParametersCompatibility json.Unmarshal(body, &CompatibleParams) json.Unmarshal([]byte(CompatibleParams.Variables), &params.Variables) } return &params } } // ContextHandler provides an entrypoint into executing graphQL queries with a // user-provided context. func (h *Handler) ContextHandler(ctx context.Context, w http.ResponseWriter, r *http.Request) { // get query params := NewRequestParameters(r) // execute graphql query result, _ := (h.Executor).Execute(h.Context, params.Query, params.Variables, params.OperationName) if h.Pretty { w.WriteHeader(200) //http.StatusOK = 200 buff, _ := json.MarshalIndent(result, "", " ") w.Write(buff) } else { w.WriteHeader(200) //http.StatusOK = 200 buff, _ := json.Marshal(result) w.Write(buff) } } // ServeHTTP provides an entrypoint into executing graphQL queries. func (h *Handler) ServeHTTP(w http.ResponseWriter, r *http.Request) { h.ContextHandler(context.Background(), w, r) } //Config for handler of the schema type Config Handler //New config func New(c *Config) *Handler { if c == nil { c = &Config{ Executor: nil, Context: "", Pretty: true, } } if c.Executor == nil { panic("Undefined GraphQL Executor") } return &Handler{ Executor: c.Executor, Context: c.Context, Pretty: c.Pretty, } }
krypton97/HandleGraphQL
handler.go
GO
mit
4,325
/** * The slideshow controller. * Get settings and initialise PrismSlider for each layer, * add controls and events, then call slideTo method on click. * @return {Object} The set of public methods. */ var slideshow = (function(window, undefined) { 'use strict'; /** * Enum navigation classes, attributes and * provide navigation DOM element container. */ var navigation = { selector: '.navigation', element: null, bullet: 'li', attrs: { active: 'active', index: 'data-index' } }; /** * Enum main element, sizes and provide * main DOM element container. * @type {Object} */ var container = { selector: '.prism-slider', element: null, sizes: { w: 1200, h: 960 } }; /** * Set of images to be used. * @type {Array} */ var slides = [ 'img/nature-a.jpg', 'img/nature-b.jpg', 'img/nature-c.jpg', 'img/nature-d.jpg' ]; /** * Set of masks with related effects. * @type {Array} */ var masks = [ { source: 'img/masks/cube-a.svg', effects: { flip: 'Y', rotate: 167 // degrees } }, { source: 'img/masks/cube-b.svg', effects: { flip: 'X', rotate: 90 // degrees } }, { source: 'img/masks/cube-c.svg', effects: { flip: false, rotate: 13 // degrees } } ]; /** * Set global easing. * @type {Function(currentTime)} */ var easing = Easing.easeInOutQuint; /** * Set global duration. * @type {Number} */ var duration = 1300; /** * Container for PrismSlider instances. * @type {Object} */ var instances = {}; /** * Init. */ function init() { getContainer_(); initSlider_(); initPrism_(); addNavigation_(); addEvents_(); } /** * Get main container element, and store in container element. */ function getContainer_() { container.element = document.querySelector(container.selector); } /** * Init Slides. * Create and initialise main background slider (first layer). * Since we'll use this as main slider no mask is given. */ function initSlider_() { instances.slider = new PrismSlider({ container: container, slides: slides, mask: false, duration: duration, easing: easing }); // Initialise instance. instances.slider.init(); } /** * Init Masks. * Loop masks variable and create a new layer for each mask object. */ function initPrism_() { masks.forEach(function(mask, i) { // Generate reference name. var name = 'mask_' + i; instances[name] = new PrismSlider({ container: container, slides: slides, mask: mask, // Here is the mask object. duration: duration, easing: easing }); // Initialise instance. instances[name].init(); }); } /** * Add Navigation. * Create a new bullet for each slide and add it to navigation (ul) * with data-index reference. */ function addNavigation_() { // Store navigation element. navigation.element = document.querySelector(navigation.selector); slides.forEach(function(slide, i) { var bullet = document.createElement(navigation.bullet); bullet.setAttribute(navigation.attrs.index, i); // When it's first bullet set class as active. if (i === 0) bullet.className = navigation.attrs.active; navigation.element.appendChild(bullet); }); } /** * Add Events. * Bind click on bullets. */ function addEvents_() { // Detect click on navigation elment (ul). navigation.element.addEventListener('click', function(e) { // Get clicked element. var bullet = e.target; // Detect if the clicked element is actually a bullet (li). var isBullet = bullet.nodeName === navigation.bullet.toUpperCase(); // Check bullet and prevent action if animation is in progress. if (isBullet && !instances.slider.isAnimated) { // Remove active class from all bullets. for (var i = 0; i < navigation.element.childNodes.length; i++) { navigation.element.childNodes[i].className = ''; } // Add active class to clicked bullet. bullet.className = navigation.attrs.active; // Get index from data attribute and convert string to number. var index = Number(bullet.getAttribute(navigation.attrs.index)); // Call slideAllTo method with index. slideAllTo_(index); } }); } /** * Call slideTo method of each instance. * In order to sync sliding of all layers we'll loop through the * instances object and call the slideTo method for each instance. * @param {Number} index The index of the destination slide. */ function slideAllTo_(index) { // Loop PrismSlider instances. for (var key in instances) { if (instances.hasOwnProperty(key)) { // Call slideTo for current instance. instances[key].slideTo(index); } } } return { init: init }; })(window); /** * Bootstrap slideshow plugin. * For demo purposes images are preloaded inside a div hidden with css, * the plugin initialisation is delayed through window.onload, in a real life * scenario would be better to preload images asynchronously with javascript. */ window.onload = slideshow.init;
claudiocalautti/prism-slider
js/slideshow3.js
JavaScript
mit
5,466
// Chargement des données (en queuing pour plus de rapidité) queue(1) .defer(d3.json, "/dataviz/rgph2014/tunisiageo.json") .defer(d3.csv, "/dataviz/rgph2014/rgph2014.csv") .awaitAll(function(error, results){ var topology = results[0] var governorates = topojson.feature(topology, topology.objects.governorates).features; // gouvernorats var data = results[1] data = d3.nest() .key(function(d){ return d.id_gouv ; }) .rollup(function(d){ return d[0]; }) .map(data, d3.map); var margin = {top: 0, right: 350, bottom: 50, left: 0}; var width = 680 - margin.left - margin.right, height = 580 - margin.top - margin.bottom; var scale = 3000; var map_container = d3.select("#carto").append("svg") .attr("width", width + margin.left + margin.right) .attr("height", height + margin.top + margin.bottom); var left_map = map_container.append("g") .attr("transform", "translate(" + margin.left + "," + margin.top + ")"); // créer la carte var projection = d3.geo.mercator() .center([9.7, 33.95]) .scale(scale) .translate([width/2 , height/2]); var path = d3.geo.path().projection(projection); left_map.selectAll(".governorate").data(governorates).enter().append("path") .attr("d", path) .attr("class", "governorate"); var right_map = map_container.append("g") .attr("transform", "translate(" + (margin.left + 400) + "," + margin.top + ")"); // créer la carte var projection = d3.geo.mercator() .center([9.7, 33.95]) .scale(scale) .translate([width/2 , height/2]); var path = d3.geo.path().projection(projection); right_map.selectAll(".governorate").data(governorates).enter().append("path") .attr("d", path) .attr("class", "governorate"); var chomage_color_scale = d3.scale.quantile() .domain(data.values().map(function(d){ return 100*+d.nb_chomeurs_total/(+d.nb_chomeurs_total + +d.nb_occupes_total) })) .range(colorbrewer.Reds[5]); var analphabetisme_color_scale = d3.scale.quantile() .domain(data.values().map(function(d){ return 100*+d.nb_analphabetes_total/+d.nb_population_total })) .range(colorbrewer.Oranges[5]); left_map.selectAll(".governorate").style("fill", function(d){ return chomage_color_scale( 100*+data.get(d.properties.gov_id).nb_chomeurs_total/(+data.get(d.properties.gov_id).nb_chomeurs_total + +data.get(d.properties.gov_id).nb_occupes_total)); }) right_map.selectAll(".governorate").style("fill", function(d){ return analphabetisme_color_scale( 100*+data.get(d.properties.gov_id).nb_analphabetes_total/+data.get(d.properties.gov_id).nb_population_total ); }) var left_legend = map_container.append("g") .attr("transform", "translate(" + (margin.left) + "," + (margin.top + height) + ")"); left_legend.append("text").text("Taux de chômage (%)").attr("class", "legend-title"); })
mahrsi/mahrsi.github.io
dataviz/rgph2014/rgph2014.js
JavaScript
mit
3,263
# frozen_string_literal: true module PeopleHelper def private_information(info, name: false) if name session[:privacy_mode] ? info.initials : info.full_name else session[:privacy_mode] ? 'hidden' : info end end alias pii private_information def address_fields_to_sentence(person) person.address? ? person.address_fields_to_sentence : 'No address' end def city_state_to_sentence(person) str = [person.city, person.state].reject(&:blank?).join(', ') str.empty? ? 'No address' : str end end
BlueRidgeLabs/kimball
app/helpers/people_helper.rb
Ruby
mit
541
// @flow import React, { Component } from 'react'; import type { Children } from 'react'; import { Sidebar } from '../components'; export default class App extends Component { props: { children: Children }; render() { return ( <div> <Sidebar /> <div className="main-panel"> {this.props.children} </div> </div> ); } }
hlynn93/basic_ims
app/containers/App.js
JavaScript
mit
385
import styled from 'styled-components'; import { colors } from '@keen.io/colors'; export const Wrapper = styled.div` padding: 20px; border-top: solid 1px ${colors.gray[300]}; `; export const Container = styled.div` display: flex; gap: 20px; `; export const TitleContainer = styled.div` min-width: 100px; `;
keen/explorer
src/components/BrowserPreview/components/DashboardsConnection/DashboardsConnection.styles.ts
TypeScript
mit
320
using BasicMessaging.Domain.Places.Models; using Brickweave.Cqrs; namespace BasicMessaging.Domain.Places.Commands { public class CreatePlace : ICommand<Place> { public CreatePlace(string name) { Name = name; } public string Name { get; } } }
agartee/Brickweave
samples/2. BasicMessaging/src/BasicMessaging.Domain/Places/Commands/CreatePlace.cs
C#
mit
303
/* * The MIT License (MIT) * * Copyright (c) 2014-2016 Christian Schudt * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package rocks.xmpp.extensions.muc.model; import rocks.xmpp.addr.Jid; /** * The {@code <actor/>} element, which is used in both <code>#admin</code> and <code>#user</code> namespace to indicate who has kicked or banned another user. * * @author Christian Schudt */ public interface Actor { /** * Gets the nick name. * * @return The nick name. */ String getNick(); /** * Gets the JID. * * @return The JID. */ Jid getJid(); }
jeozey/XmppServerTester
xmpp-extensions/src/main/java/rocks/xmpp/extensions/muc/model/Actor.java
Java
mit
1,690
export * from './components'; export * from './questions.module';
dormd/ng2-countries-trivia
src/app/modules/questions/index.ts
TypeScript
mit
65
<!-- Safe sample input : reads the field UserData from the variable $_GET sanitize : cast via + = 0 File : unsafe, use of untrusted data in the function setInterval --> <!--Copyright 2015 Bertrand STIVALET Permission is hereby granted, without written agreement or royalty fee, to use, copy, modify, and distribute this software and its documentation for any purpose, provided that the above copyright notice and the following three paragraphs appear in all copies of this software. IN NO EVENT SHALL AUTHORS BE LIABLE TO ANY PARTY FOR DIRECT, INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OF THIS SOFTWARE AND ITS DOCUMENTATION, EVEN IF AUTHORS HAVE BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. AUTHORS SPECIFICALLY DISCLAIM ANY WARRANTIES INCLUDING, BUT NOT LIMITED TO THE IMPLIED WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE, AND NON-INFRINGEMENT. THE SOFTWARE IS PROVIDED ON AN "AS-IS" BASIS AND AUTHORS HAVE NO OBLIGATION TO PROVIDE MAINTENANCE, SUPPORT, UPDATES, ENHANCEMENTS, OR MODIFICATIONS.--> <!DOCTYPE html> <html> <head> <script> <?php $tainted = $_GET['UserData']; $tainted += 0 ; echo "window.setInterval('". $tainted ."');" ; ?> </script> </head> <body> <h1>Hello World!</h1> </body> </html>
stivalet/PHP-Vulnerability-test-suite
XSS/CWE_79/safe/CWE_79__GET__CAST-cast_int_sort_of__Use_untrusted_data_script-window_SetInterval.php
PHP
mit
1,289
<?php /* * This file is part of App/Validation. * * (c) Alexandre Gomes Gaigalas <alexandre@gaigalas.net> * * For the full copyright and license information, please view the "LICENSE.md" * file that was distributed with this source code. */ namespace App\Validation\Rules\SubdivisionCode; use App\Validation\Rules\AbstractSearcher; /** * Validator for El Salvador subdivision code. * * ISO 3166-1 alpha-2: SV * * @link http://www.geonames.org/SV/administrative-division-el-salvador.html */ class SvSubdivisionCode extends AbstractSearcher { public $haystack = [ 'AH', // Ahuachapan 'CA', // Cabanas 'CH', // Chalatenango 'CU', // Cuscatlan 'LI', // La Libertad 'MO', // Morazan 'PA', // La Paz 'SA', // Santa Ana 'SM', // San Miguel 'SO', // Sonsonate 'SS', // San Salvador 'SV', // San Vicente 'UN', // La Union 'US', // Usulutan ]; public $compareIdentical = true; }
Javier-Solis/admin-project
app/Validation/Rules/SubdivisionCode/SvSubdivisionCode.php
PHP
mit
1,011
package kusto // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. See License.txt in the project root for license information. // // Code generated by Microsoft (R) AutoRest Code Generator. // Changes may cause incorrect behavior and will be lost if the code is regenerated. import ( "context" "github.com/Azure/go-autorest/autorest" "github.com/Azure/go-autorest/autorest/azure" "github.com/Azure/go-autorest/autorest/validation" "github.com/Azure/go-autorest/tracing" "net/http" ) // DataConnectionsClient is the the Azure Kusto management API provides a RESTful set of web services that interact // with Azure Kusto services to manage your clusters and databases. The API enables you to create, update, and delete // clusters and databases. type DataConnectionsClient struct { BaseClient } // NewDataConnectionsClient creates an instance of the DataConnectionsClient client. func NewDataConnectionsClient(subscriptionID string) DataConnectionsClient { return NewDataConnectionsClientWithBaseURI(DefaultBaseURI, subscriptionID) } // NewDataConnectionsClientWithBaseURI creates an instance of the DataConnectionsClient client using a custom endpoint. // Use this when interacting with an Azure cloud that uses a non-standard base URI (sovereign clouds, Azure stack). func NewDataConnectionsClientWithBaseURI(baseURI string, subscriptionID string) DataConnectionsClient { return DataConnectionsClient{NewWithBaseURI(baseURI, subscriptionID)} } // CheckNameAvailability checks that the data connection name is valid and is not already in use. // Parameters: // resourceGroupName - the name of the resource group containing the Kusto cluster. // clusterName - the name of the Kusto cluster. // databaseName - the name of the database in the Kusto cluster. // dataConnectionName - the name of the data connection. func (client DataConnectionsClient) CheckNameAvailability(ctx context.Context, resourceGroupName string, clusterName string, databaseName string, dataConnectionName DataConnectionCheckNameRequest) (result CheckNameResult, err error) { if tracing.IsEnabled() { ctx = tracing.StartSpan(ctx, fqdn+"/DataConnectionsClient.CheckNameAvailability") defer func() { sc := -1 if result.Response.Response != nil { sc = result.Response.Response.StatusCode } tracing.EndSpan(ctx, sc, err) }() } if err := validation.Validate([]validation.Validation{ {TargetValue: dataConnectionName, Constraints: []validation.Constraint{{Target: "dataConnectionName.Name", Name: validation.Null, Rule: true, Chain: nil}, {Target: "dataConnectionName.Type", Name: validation.Null, Rule: true, Chain: nil}}}}); err != nil { return result, validation.NewError("kusto.DataConnectionsClient", "CheckNameAvailability", err.Error()) } req, err := client.CheckNameAvailabilityPreparer(ctx, resourceGroupName, clusterName, databaseName, dataConnectionName) if err != nil { err = autorest.NewErrorWithError(err, "kusto.DataConnectionsClient", "CheckNameAvailability", nil, "Failure preparing request") return } resp, err := client.CheckNameAvailabilitySender(req) if err != nil { result.Response = autorest.Response{Response: resp} err = autorest.NewErrorWithError(err, "kusto.DataConnectionsClient", "CheckNameAvailability", resp, "Failure sending request") return } result, err = client.CheckNameAvailabilityResponder(resp) if err != nil { err = autorest.NewErrorWithError(err, "kusto.DataConnectionsClient", "CheckNameAvailability", resp, "Failure responding to request") return } return } // CheckNameAvailabilityPreparer prepares the CheckNameAvailability request. func (client DataConnectionsClient) CheckNameAvailabilityPreparer(ctx context.Context, resourceGroupName string, clusterName string, databaseName string, dataConnectionName DataConnectionCheckNameRequest) (*http.Request, error) { pathParameters := map[string]interface{}{ "clusterName": autorest.Encode("path", clusterName), "databaseName": autorest.Encode("path", databaseName), "resourceGroupName": autorest.Encode("path", resourceGroupName), "subscriptionId": autorest.Encode("path", client.SubscriptionID), } const APIVersion = "2019-01-21" queryParameters := map[string]interface{}{ "api-version": APIVersion, } preparer := autorest.CreatePreparer( autorest.AsContentType("application/json; charset=utf-8"), autorest.AsPost(), autorest.WithBaseURL(client.BaseURI), autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Kusto/clusters/{clusterName}/databases/{databaseName}/checkNameAvailability", pathParameters), autorest.WithJSON(dataConnectionName), autorest.WithQueryParameters(queryParameters)) return preparer.Prepare((&http.Request{}).WithContext(ctx)) } // CheckNameAvailabilitySender sends the CheckNameAvailability request. The method will close the // http.Response Body if it receives an error. func (client DataConnectionsClient) CheckNameAvailabilitySender(req *http.Request) (*http.Response, error) { return client.Send(req, azure.DoRetryWithRegistration(client.Client)) } // CheckNameAvailabilityResponder handles the response to the CheckNameAvailability request. The method always // closes the http.Response Body. func (client DataConnectionsClient) CheckNameAvailabilityResponder(resp *http.Response) (result CheckNameResult, err error) { err = autorest.Respond( resp, azure.WithErrorUnlessStatusCode(http.StatusOK), autorest.ByUnmarshallingJSON(&result), autorest.ByClosing()) result.Response = autorest.Response{Response: resp} return } // CreateOrUpdate creates or updates a data connection. // Parameters: // resourceGroupName - the name of the resource group containing the Kusto cluster. // clusterName - the name of the Kusto cluster. // databaseName - the name of the database in the Kusto cluster. // dataConnectionName - the name of the data connection. // parameters - the data connection parameters supplied to the CreateOrUpdate operation. func (client DataConnectionsClient) CreateOrUpdate(ctx context.Context, resourceGroupName string, clusterName string, databaseName string, dataConnectionName string, parameters BasicDataConnection) (result DataConnectionsCreateOrUpdateFuture, err error) { if tracing.IsEnabled() { ctx = tracing.StartSpan(ctx, fqdn+"/DataConnectionsClient.CreateOrUpdate") defer func() { sc := -1 if result.FutureAPI != nil && result.FutureAPI.Response() != nil { sc = result.FutureAPI.Response().StatusCode } tracing.EndSpan(ctx, sc, err) }() } req, err := client.CreateOrUpdatePreparer(ctx, resourceGroupName, clusterName, databaseName, dataConnectionName, parameters) if err != nil { err = autorest.NewErrorWithError(err, "kusto.DataConnectionsClient", "CreateOrUpdate", nil, "Failure preparing request") return } result, err = client.CreateOrUpdateSender(req) if err != nil { err = autorest.NewErrorWithError(err, "kusto.DataConnectionsClient", "CreateOrUpdate", result.Response(), "Failure sending request") return } return } // CreateOrUpdatePreparer prepares the CreateOrUpdate request. func (client DataConnectionsClient) CreateOrUpdatePreparer(ctx context.Context, resourceGroupName string, clusterName string, databaseName string, dataConnectionName string, parameters BasicDataConnection) (*http.Request, error) { pathParameters := map[string]interface{}{ "clusterName": autorest.Encode("path", clusterName), "databaseName": autorest.Encode("path", databaseName), "dataConnectionName": autorest.Encode("path", dataConnectionName), "resourceGroupName": autorest.Encode("path", resourceGroupName), "subscriptionId": autorest.Encode("path", client.SubscriptionID), } const APIVersion = "2019-01-21" queryParameters := map[string]interface{}{ "api-version": APIVersion, } preparer := autorest.CreatePreparer( autorest.AsContentType("application/json; charset=utf-8"), autorest.AsPut(), autorest.WithBaseURL(client.BaseURI), autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Kusto/clusters/{clusterName}/databases/{databaseName}/dataConnections/{dataConnectionName}", pathParameters), autorest.WithJSON(parameters), autorest.WithQueryParameters(queryParameters)) return preparer.Prepare((&http.Request{}).WithContext(ctx)) } // CreateOrUpdateSender sends the CreateOrUpdate request. The method will close the // http.Response Body if it receives an error. func (client DataConnectionsClient) CreateOrUpdateSender(req *http.Request) (future DataConnectionsCreateOrUpdateFuture, err error) { var resp *http.Response future.FutureAPI = &azure.Future{} resp, err = client.Send(req, azure.DoRetryWithRegistration(client.Client)) if err != nil { return } var azf azure.Future azf, err = azure.NewFutureFromResponse(resp) future.FutureAPI = &azf future.Result = future.result return } // CreateOrUpdateResponder handles the response to the CreateOrUpdate request. The method always // closes the http.Response Body. func (client DataConnectionsClient) CreateOrUpdateResponder(resp *http.Response) (result DataConnectionModel, err error) { err = autorest.Respond( resp, azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusCreated, http.StatusAccepted), autorest.ByUnmarshallingJSON(&result.Value), autorest.ByClosing()) result.Response = autorest.Response{Response: resp} return } // DataConnectionValidationMethod checks that the data connection parameters are valid. // Parameters: // resourceGroupName - the name of the resource group containing the Kusto cluster. // clusterName - the name of the Kusto cluster. // databaseName - the name of the database in the Kusto cluster. // parameters - the data connection parameters supplied to the CreateOrUpdate operation. func (client DataConnectionsClient) DataConnectionValidationMethod(ctx context.Context, resourceGroupName string, clusterName string, databaseName string, parameters DataConnectionValidation) (result DataConnectionValidationListResult, err error) { if tracing.IsEnabled() { ctx = tracing.StartSpan(ctx, fqdn+"/DataConnectionsClient.DataConnectionValidationMethod") defer func() { sc := -1 if result.Response.Response != nil { sc = result.Response.Response.StatusCode } tracing.EndSpan(ctx, sc, err) }() } req, err := client.DataConnectionValidationMethodPreparer(ctx, resourceGroupName, clusterName, databaseName, parameters) if err != nil { err = autorest.NewErrorWithError(err, "kusto.DataConnectionsClient", "DataConnectionValidationMethod", nil, "Failure preparing request") return } resp, err := client.DataConnectionValidationMethodSender(req) if err != nil { result.Response = autorest.Response{Response: resp} err = autorest.NewErrorWithError(err, "kusto.DataConnectionsClient", "DataConnectionValidationMethod", resp, "Failure sending request") return } result, err = client.DataConnectionValidationMethodResponder(resp) if err != nil { err = autorest.NewErrorWithError(err, "kusto.DataConnectionsClient", "DataConnectionValidationMethod", resp, "Failure responding to request") return } return } // DataConnectionValidationMethodPreparer prepares the DataConnectionValidationMethod request. func (client DataConnectionsClient) DataConnectionValidationMethodPreparer(ctx context.Context, resourceGroupName string, clusterName string, databaseName string, parameters DataConnectionValidation) (*http.Request, error) { pathParameters := map[string]interface{}{ "clusterName": autorest.Encode("path", clusterName), "databaseName": autorest.Encode("path", databaseName), "resourceGroupName": autorest.Encode("path", resourceGroupName), "subscriptionId": autorest.Encode("path", client.SubscriptionID), } const APIVersion = "2019-01-21" queryParameters := map[string]interface{}{ "api-version": APIVersion, } preparer := autorest.CreatePreparer( autorest.AsContentType("application/json; charset=utf-8"), autorest.AsPost(), autorest.WithBaseURL(client.BaseURI), autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Kusto/clusters/{clusterName}/databases/{databaseName}/dataConnectionValidation", pathParameters), autorest.WithJSON(parameters), autorest.WithQueryParameters(queryParameters)) return preparer.Prepare((&http.Request{}).WithContext(ctx)) } // DataConnectionValidationMethodSender sends the DataConnectionValidationMethod request. The method will close the // http.Response Body if it receives an error. func (client DataConnectionsClient) DataConnectionValidationMethodSender(req *http.Request) (*http.Response, error) { return client.Send(req, azure.DoRetryWithRegistration(client.Client)) } // DataConnectionValidationMethodResponder handles the response to the DataConnectionValidationMethod request. The method always // closes the http.Response Body. func (client DataConnectionsClient) DataConnectionValidationMethodResponder(resp *http.Response) (result DataConnectionValidationListResult, err error) { err = autorest.Respond( resp, azure.WithErrorUnlessStatusCode(http.StatusOK), autorest.ByUnmarshallingJSON(&result), autorest.ByClosing()) result.Response = autorest.Response{Response: resp} return } // Delete deletes the data connection with the given name. // Parameters: // resourceGroupName - the name of the resource group containing the Kusto cluster. // clusterName - the name of the Kusto cluster. // databaseName - the name of the database in the Kusto cluster. // dataConnectionName - the name of the data connection. func (client DataConnectionsClient) Delete(ctx context.Context, resourceGroupName string, clusterName string, databaseName string, dataConnectionName string) (result DataConnectionsDeleteFuture, err error) { if tracing.IsEnabled() { ctx = tracing.StartSpan(ctx, fqdn+"/DataConnectionsClient.Delete") defer func() { sc := -1 if result.FutureAPI != nil && result.FutureAPI.Response() != nil { sc = result.FutureAPI.Response().StatusCode } tracing.EndSpan(ctx, sc, err) }() } req, err := client.DeletePreparer(ctx, resourceGroupName, clusterName, databaseName, dataConnectionName) if err != nil { err = autorest.NewErrorWithError(err, "kusto.DataConnectionsClient", "Delete", nil, "Failure preparing request") return } result, err = client.DeleteSender(req) if err != nil { err = autorest.NewErrorWithError(err, "kusto.DataConnectionsClient", "Delete", result.Response(), "Failure sending request") return } return } // DeletePreparer prepares the Delete request. func (client DataConnectionsClient) DeletePreparer(ctx context.Context, resourceGroupName string, clusterName string, databaseName string, dataConnectionName string) (*http.Request, error) { pathParameters := map[string]interface{}{ "clusterName": autorest.Encode("path", clusterName), "databaseName": autorest.Encode("path", databaseName), "dataConnectionName": autorest.Encode("path", dataConnectionName), "resourceGroupName": autorest.Encode("path", resourceGroupName), "subscriptionId": autorest.Encode("path", client.SubscriptionID), } const APIVersion = "2019-01-21" queryParameters := map[string]interface{}{ "api-version": APIVersion, } preparer := autorest.CreatePreparer( autorest.AsDelete(), autorest.WithBaseURL(client.BaseURI), autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Kusto/clusters/{clusterName}/databases/{databaseName}/dataConnections/{dataConnectionName}", pathParameters), autorest.WithQueryParameters(queryParameters)) return preparer.Prepare((&http.Request{}).WithContext(ctx)) } // DeleteSender sends the Delete request. The method will close the // http.Response Body if it receives an error. func (client DataConnectionsClient) DeleteSender(req *http.Request) (future DataConnectionsDeleteFuture, err error) { var resp *http.Response future.FutureAPI = &azure.Future{} resp, err = client.Send(req, azure.DoRetryWithRegistration(client.Client)) if err != nil { return } var azf azure.Future azf, err = azure.NewFutureFromResponse(resp) future.FutureAPI = &azf future.Result = future.result return } // DeleteResponder handles the response to the Delete request. The method always // closes the http.Response Body. func (client DataConnectionsClient) DeleteResponder(resp *http.Response) (result autorest.Response, err error) { err = autorest.Respond( resp, azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusAccepted, http.StatusNoContent), autorest.ByClosing()) result.Response = resp return } // Get returns a data connection. // Parameters: // resourceGroupName - the name of the resource group containing the Kusto cluster. // clusterName - the name of the Kusto cluster. // databaseName - the name of the database in the Kusto cluster. // dataConnectionName - the name of the data connection. func (client DataConnectionsClient) Get(ctx context.Context, resourceGroupName string, clusterName string, databaseName string, dataConnectionName string) (result DataConnectionModel, err error) { if tracing.IsEnabled() { ctx = tracing.StartSpan(ctx, fqdn+"/DataConnectionsClient.Get") defer func() { sc := -1 if result.Response.Response != nil { sc = result.Response.Response.StatusCode } tracing.EndSpan(ctx, sc, err) }() } req, err := client.GetPreparer(ctx, resourceGroupName, clusterName, databaseName, dataConnectionName) if err != nil { err = autorest.NewErrorWithError(err, "kusto.DataConnectionsClient", "Get", nil, "Failure preparing request") return } resp, err := client.GetSender(req) if err != nil { result.Response = autorest.Response{Response: resp} err = autorest.NewErrorWithError(err, "kusto.DataConnectionsClient", "Get", resp, "Failure sending request") return } result, err = client.GetResponder(resp) if err != nil { err = autorest.NewErrorWithError(err, "kusto.DataConnectionsClient", "Get", resp, "Failure responding to request") return } return } // GetPreparer prepares the Get request. func (client DataConnectionsClient) GetPreparer(ctx context.Context, resourceGroupName string, clusterName string, databaseName string, dataConnectionName string) (*http.Request, error) { pathParameters := map[string]interface{}{ "clusterName": autorest.Encode("path", clusterName), "databaseName": autorest.Encode("path", databaseName), "dataConnectionName": autorest.Encode("path", dataConnectionName), "resourceGroupName": autorest.Encode("path", resourceGroupName), "subscriptionId": autorest.Encode("path", client.SubscriptionID), } const APIVersion = "2019-01-21" queryParameters := map[string]interface{}{ "api-version": APIVersion, } preparer := autorest.CreatePreparer( autorest.AsGet(), autorest.WithBaseURL(client.BaseURI), autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Kusto/clusters/{clusterName}/databases/{databaseName}/dataConnections/{dataConnectionName}", pathParameters), autorest.WithQueryParameters(queryParameters)) return preparer.Prepare((&http.Request{}).WithContext(ctx)) } // GetSender sends the Get request. The method will close the // http.Response Body if it receives an error. func (client DataConnectionsClient) GetSender(req *http.Request) (*http.Response, error) { return client.Send(req, azure.DoRetryWithRegistration(client.Client)) } // GetResponder handles the response to the Get request. The method always // closes the http.Response Body. func (client DataConnectionsClient) GetResponder(resp *http.Response) (result DataConnectionModel, err error) { err = autorest.Respond( resp, azure.WithErrorUnlessStatusCode(http.StatusOK), autorest.ByUnmarshallingJSON(&result), autorest.ByClosing()) result.Response = autorest.Response{Response: resp} return } // ListByDatabase returns the list of data connections of the given Kusto database. // Parameters: // resourceGroupName - the name of the resource group containing the Kusto cluster. // clusterName - the name of the Kusto cluster. // databaseName - the name of the database in the Kusto cluster. func (client DataConnectionsClient) ListByDatabase(ctx context.Context, resourceGroupName string, clusterName string, databaseName string) (result DataConnectionListResult, err error) { if tracing.IsEnabled() { ctx = tracing.StartSpan(ctx, fqdn+"/DataConnectionsClient.ListByDatabase") defer func() { sc := -1 if result.Response.Response != nil { sc = result.Response.Response.StatusCode } tracing.EndSpan(ctx, sc, err) }() } req, err := client.ListByDatabasePreparer(ctx, resourceGroupName, clusterName, databaseName) if err != nil { err = autorest.NewErrorWithError(err, "kusto.DataConnectionsClient", "ListByDatabase", nil, "Failure preparing request") return } resp, err := client.ListByDatabaseSender(req) if err != nil { result.Response = autorest.Response{Response: resp} err = autorest.NewErrorWithError(err, "kusto.DataConnectionsClient", "ListByDatabase", resp, "Failure sending request") return } result, err = client.ListByDatabaseResponder(resp) if err != nil { err = autorest.NewErrorWithError(err, "kusto.DataConnectionsClient", "ListByDatabase", resp, "Failure responding to request") return } return } // ListByDatabasePreparer prepares the ListByDatabase request. func (client DataConnectionsClient) ListByDatabasePreparer(ctx context.Context, resourceGroupName string, clusterName string, databaseName string) (*http.Request, error) { pathParameters := map[string]interface{}{ "clusterName": autorest.Encode("path", clusterName), "databaseName": autorest.Encode("path", databaseName), "resourceGroupName": autorest.Encode("path", resourceGroupName), "subscriptionId": autorest.Encode("path", client.SubscriptionID), } const APIVersion = "2019-01-21" queryParameters := map[string]interface{}{ "api-version": APIVersion, } preparer := autorest.CreatePreparer( autorest.AsGet(), autorest.WithBaseURL(client.BaseURI), autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Kusto/clusters/{clusterName}/databases/{databaseName}/dataConnections", pathParameters), autorest.WithQueryParameters(queryParameters)) return preparer.Prepare((&http.Request{}).WithContext(ctx)) } // ListByDatabaseSender sends the ListByDatabase request. The method will close the // http.Response Body if it receives an error. func (client DataConnectionsClient) ListByDatabaseSender(req *http.Request) (*http.Response, error) { return client.Send(req, azure.DoRetryWithRegistration(client.Client)) } // ListByDatabaseResponder handles the response to the ListByDatabase request. The method always // closes the http.Response Body. func (client DataConnectionsClient) ListByDatabaseResponder(resp *http.Response) (result DataConnectionListResult, err error) { err = autorest.Respond( resp, azure.WithErrorUnlessStatusCode(http.StatusOK), autorest.ByUnmarshallingJSON(&result), autorest.ByClosing()) result.Response = autorest.Response{Response: resp} return } // Update updates a data connection. // Parameters: // resourceGroupName - the name of the resource group containing the Kusto cluster. // clusterName - the name of the Kusto cluster. // databaseName - the name of the database in the Kusto cluster. // dataConnectionName - the name of the data connection. // parameters - the data connection parameters supplied to the Update operation. func (client DataConnectionsClient) Update(ctx context.Context, resourceGroupName string, clusterName string, databaseName string, dataConnectionName string, parameters BasicDataConnection) (result DataConnectionsUpdateFuture, err error) { if tracing.IsEnabled() { ctx = tracing.StartSpan(ctx, fqdn+"/DataConnectionsClient.Update") defer func() { sc := -1 if result.FutureAPI != nil && result.FutureAPI.Response() != nil { sc = result.FutureAPI.Response().StatusCode } tracing.EndSpan(ctx, sc, err) }() } req, err := client.UpdatePreparer(ctx, resourceGroupName, clusterName, databaseName, dataConnectionName, parameters) if err != nil { err = autorest.NewErrorWithError(err, "kusto.DataConnectionsClient", "Update", nil, "Failure preparing request") return } result, err = client.UpdateSender(req) if err != nil { err = autorest.NewErrorWithError(err, "kusto.DataConnectionsClient", "Update", result.Response(), "Failure sending request") return } return } // UpdatePreparer prepares the Update request. func (client DataConnectionsClient) UpdatePreparer(ctx context.Context, resourceGroupName string, clusterName string, databaseName string, dataConnectionName string, parameters BasicDataConnection) (*http.Request, error) { pathParameters := map[string]interface{}{ "clusterName": autorest.Encode("path", clusterName), "databaseName": autorest.Encode("path", databaseName), "dataConnectionName": autorest.Encode("path", dataConnectionName), "resourceGroupName": autorest.Encode("path", resourceGroupName), "subscriptionId": autorest.Encode("path", client.SubscriptionID), } const APIVersion = "2019-01-21" queryParameters := map[string]interface{}{ "api-version": APIVersion, } preparer := autorest.CreatePreparer( autorest.AsContentType("application/json; charset=utf-8"), autorest.AsPatch(), autorest.WithBaseURL(client.BaseURI), autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Kusto/clusters/{clusterName}/databases/{databaseName}/dataConnections/{dataConnectionName}", pathParameters), autorest.WithJSON(parameters), autorest.WithQueryParameters(queryParameters)) return preparer.Prepare((&http.Request{}).WithContext(ctx)) } // UpdateSender sends the Update request. The method will close the // http.Response Body if it receives an error. func (client DataConnectionsClient) UpdateSender(req *http.Request) (future DataConnectionsUpdateFuture, err error) { var resp *http.Response future.FutureAPI = &azure.Future{} resp, err = client.Send(req, azure.DoRetryWithRegistration(client.Client)) if err != nil { return } var azf azure.Future azf, err = azure.NewFutureFromResponse(resp) future.FutureAPI = &azf future.Result = future.result return } // UpdateResponder handles the response to the Update request. The method always // closes the http.Response Body. func (client DataConnectionsClient) UpdateResponder(resp *http.Response) (result DataConnectionModel, err error) { err = autorest.Respond( resp, azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusCreated, http.StatusAccepted), autorest.ByUnmarshallingJSON(&result.Value), autorest.ByClosing()) result.Response = autorest.Response{Response: resp} return }
Azure/azure-sdk-for-go
services/kusto/mgmt/2019-01-21/kusto/dataconnections.go
GO
mit
27,128
require 'rails_helper' RSpec.describe Parties::EmailsController, type: :request do describe '#edit' do before { signin_party } subject! { get '/party/email/edit' } it { expect(response).to be_success } end describe '#update' do before { signin_party } context 'success' do subject { put '/party/email', party: { email: '5566@gmail.com', current_password: '12321313213' } } it { expect { subject }.to change_sidekiq_jobs_size_of(Devise::Async::Backend::Sidekiq) } it { expect(subject).to redirect_to('/party/profile') } end context 'wrong password' do subject! { put '/party/email', party: { email: '5566@gmail.com', current_password: '' } } it { expect(current_party.email).not_to eq('5566@gmail.com') } it { expect(response.body).to match('5566@gmail.com') } it { expect(response.body).not_to match('目前等待驗證中信箱') } end end describe '#resend_confirmation_mail' do let!(:party) { create :party, :with_unconfirmed_email, :with_confirmation_token } before { signin_party(party) } subject { post '/party/email/resend_confirmation_mail' } it { expect { subject }.to change_sidekiq_jobs_size_of(CustomDeviseMailer, :resend_confirmation_instructions) } context 'redirect success' do before { subject } it { expect(flash[:notice]).to eq('您將在幾分鐘後收到一封電子郵件,內有驗證帳號的步驟說明。') } it { expect(response).to redirect_to('/party/profile') } end end end
JRF-tw/sunshine.jrf.org.tw
spec/requests/parties/emails_controller_spec.rb
Ruby
mit
1,540
package jsettlers.graphics.map.controls.original.panel.button; import jsettlers.common.images.EImageLinkType; import jsettlers.common.images.OriginalImageLink; import jsettlers.common.material.EMaterialType; import jsettlers.graphics.action.Action; import jsettlers.graphics.localization.Labels; import jsettlers.graphics.ui.Button; import jsettlers.graphics.ui.UIPanel; /** * A special material button with a green/red dot and a * * @author Michael Zangl */ public class MaterialButton extends Button { public enum DotColor { RED(7), GREEN(0), YELLOW(3); private OriginalImageLink image; private DotColor(int imageIndex) { image = new OriginalImageLink(EImageLinkType.SETTLER, 4, 6, imageIndex); } public OriginalImageLink getImage() { return image; } } private final EMaterialType material; private final UIPanel dot = new UIPanel(); private final UIPanel selected = new UIPanel(); public MaterialButton(Action action, EMaterialType material) { super(action, material.getIcon(), material.getIcon(), Labels.getName(material, false)); this.material = material; setBackground(material.getIcon()); addChild(dot, .1f, .6f, .4f, .9f); addChild(selected, 0, 0, 1, 1); } public void setDotColor(DotColor color) { dot.setBackground(color == null ? null : color.image); } public EMaterialType getMaterial() { return material; } public void setSelected(boolean selected) { this.selected.setBackground(selected ? new OriginalImageLink(EImageLinkType.GUI, 3, 339) : null); } }
JKatzwinkel/settlers-remake
jsettlers.graphics/src/jsettlers/graphics/map/controls/original/panel/button/MaterialButton.java
Java
mit
1,533
// Code generated by protoc-gen-go. DO NOT EDIT. // source: google/ads/googleads/v0/enums/frequency_cap_level.proto package enums // import "google.golang.org/genproto/googleapis/ads/googleads/v0/enums" import proto "github.com/golang/protobuf/proto" import fmt "fmt" import math "math" // Reference imports to suppress errors if they are not otherwise used. var _ = proto.Marshal var _ = fmt.Errorf var _ = math.Inf // This is a compile-time assertion to ensure that this generated file // is compatible with the proto package it is being compiled against. // A compilation error at this line likely means your copy of the // proto package needs to be updated. const _ = proto.ProtoPackageIsVersion2 // please upgrade the proto package // The level on which the cap is to be applied (e.g ad group ad, ad group). // Cap is applied to all the resources of this level. type FrequencyCapLevelEnum_FrequencyCapLevel int32 const ( // Not specified. FrequencyCapLevelEnum_UNSPECIFIED FrequencyCapLevelEnum_FrequencyCapLevel = 0 // Used for return value only. Represents value unknown in this version. FrequencyCapLevelEnum_UNKNOWN FrequencyCapLevelEnum_FrequencyCapLevel = 1 // The cap is applied at the ad group ad level. FrequencyCapLevelEnum_AD_GROUP_AD FrequencyCapLevelEnum_FrequencyCapLevel = 2 // The cap is applied at the ad group level. FrequencyCapLevelEnum_AD_GROUP FrequencyCapLevelEnum_FrequencyCapLevel = 3 // The cap is applied at the campaign level. FrequencyCapLevelEnum_CAMPAIGN FrequencyCapLevelEnum_FrequencyCapLevel = 4 ) var FrequencyCapLevelEnum_FrequencyCapLevel_name = map[int32]string{ 0: "UNSPECIFIED", 1: "UNKNOWN", 2: "AD_GROUP_AD", 3: "AD_GROUP", 4: "CAMPAIGN", } var FrequencyCapLevelEnum_FrequencyCapLevel_value = map[string]int32{ "UNSPECIFIED": 0, "UNKNOWN": 1, "AD_GROUP_AD": 2, "AD_GROUP": 3, "CAMPAIGN": 4, } func (x FrequencyCapLevelEnum_FrequencyCapLevel) String() string { return proto.EnumName(FrequencyCapLevelEnum_FrequencyCapLevel_name, int32(x)) } func (FrequencyCapLevelEnum_FrequencyCapLevel) EnumDescriptor() ([]byte, []int) { return fileDescriptor_frequency_cap_level_ca8c642a1d3010c4, []int{0, 0} } // Container for enum describing the level on which the cap is to be applied. type FrequencyCapLevelEnum struct { XXX_NoUnkeyedLiteral struct{} `json:"-"` XXX_unrecognized []byte `json:"-"` XXX_sizecache int32 `json:"-"` } func (m *FrequencyCapLevelEnum) Reset() { *m = FrequencyCapLevelEnum{} } func (m *FrequencyCapLevelEnum) String() string { return proto.CompactTextString(m) } func (*FrequencyCapLevelEnum) ProtoMessage() {} func (*FrequencyCapLevelEnum) Descriptor() ([]byte, []int) { return fileDescriptor_frequency_cap_level_ca8c642a1d3010c4, []int{0} } func (m *FrequencyCapLevelEnum) XXX_Unmarshal(b []byte) error { return xxx_messageInfo_FrequencyCapLevelEnum.Unmarshal(m, b) } func (m *FrequencyCapLevelEnum) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { return xxx_messageInfo_FrequencyCapLevelEnum.Marshal(b, m, deterministic) } func (dst *FrequencyCapLevelEnum) XXX_Merge(src proto.Message) { xxx_messageInfo_FrequencyCapLevelEnum.Merge(dst, src) } func (m *FrequencyCapLevelEnum) XXX_Size() int { return xxx_messageInfo_FrequencyCapLevelEnum.Size(m) } func (m *FrequencyCapLevelEnum) XXX_DiscardUnknown() { xxx_messageInfo_FrequencyCapLevelEnum.DiscardUnknown(m) } var xxx_messageInfo_FrequencyCapLevelEnum proto.InternalMessageInfo func init() { proto.RegisterType((*FrequencyCapLevelEnum)(nil), "google.ads.googleads.v0.enums.FrequencyCapLevelEnum") proto.RegisterEnum("google.ads.googleads.v0.enums.FrequencyCapLevelEnum_FrequencyCapLevel", FrequencyCapLevelEnum_FrequencyCapLevel_name, FrequencyCapLevelEnum_FrequencyCapLevel_value) } func init() { proto.RegisterFile("google/ads/googleads/v0/enums/frequency_cap_level.proto", fileDescriptor_frequency_cap_level_ca8c642a1d3010c4) } var fileDescriptor_frequency_cap_level_ca8c642a1d3010c4 = []byte{ // 300 bytes of a gzipped FileDescriptorProto 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0xe2, 0x32, 0x4f, 0xcf, 0xcf, 0x4f, 0xcf, 0x49, 0xd5, 0x4f, 0x4c, 0x29, 0xd6, 0x87, 0x30, 0x41, 0xac, 0x32, 0x03, 0xfd, 0xd4, 0xbc, 0xd2, 0xdc, 0x62, 0xfd, 0xb4, 0xa2, 0xd4, 0xc2, 0xd2, 0xd4, 0xbc, 0xe4, 0xca, 0xf8, 0xe4, 0xc4, 0x82, 0xf8, 0x9c, 0xd4, 0xb2, 0xd4, 0x1c, 0xbd, 0x82, 0xa2, 0xfc, 0x92, 0x7c, 0x21, 0x59, 0x88, 0x6a, 0xbd, 0xc4, 0x94, 0x62, 0x3d, 0xb8, 0x46, 0xbd, 0x32, 0x03, 0x3d, 0xb0, 0x46, 0xa5, 0x72, 0x2e, 0x51, 0x37, 0x98, 0x5e, 0xe7, 0xc4, 0x02, 0x1f, 0x90, 0x4e, 0xd7, 0xbc, 0xd2, 0x5c, 0xa5, 0x38, 0x2e, 0x41, 0x0c, 0x09, 0x21, 0x7e, 0x2e, 0xee, 0x50, 0xbf, 0xe0, 0x00, 0x57, 0x67, 0x4f, 0x37, 0x4f, 0x57, 0x17, 0x01, 0x06, 0x21, 0x6e, 0x2e, 0xf6, 0x50, 0x3f, 0x6f, 0x3f, 0xff, 0x70, 0x3f, 0x01, 0x46, 0x90, 0xac, 0xa3, 0x4b, 0xbc, 0x7b, 0x90, 0x7f, 0x68, 0x40, 0xbc, 0xa3, 0x8b, 0x00, 0x93, 0x10, 0x0f, 0x17, 0x07, 0x4c, 0x40, 0x80, 0x19, 0xc4, 0x73, 0x76, 0xf4, 0x0d, 0x70, 0xf4, 0x74, 0xf7, 0x13, 0x60, 0x71, 0x7a, 0xcd, 0xc8, 0xa5, 0x98, 0x9c, 0x9f, 0xab, 0x87, 0xd7, 0x79, 0x4e, 0x62, 0x18, 0x6e, 0x08, 0x00, 0xf9, 0x2a, 0x80, 0x31, 0xca, 0x09, 0xaa, 0x31, 0x3d, 0x3f, 0x27, 0x31, 0x2f, 0x5d, 0x2f, 0xbf, 0x28, 0x5d, 0x3f, 0x3d, 0x35, 0x0f, 0xec, 0x67, 0x58, 0x00, 0x15, 0x64, 0x16, 0xe3, 0x08, 0x2f, 0x6b, 0x30, 0xb9, 0x88, 0x89, 0xd9, 0xdd, 0xd1, 0x71, 0x15, 0x93, 0xac, 0x3b, 0xc4, 0x28, 0xc7, 0x94, 0x62, 0x3d, 0x08, 0x13, 0xc4, 0x0a, 0x33, 0xd0, 0x03, 0x05, 0x44, 0xf1, 0x29, 0x98, 0x7c, 0x8c, 0x63, 0x4a, 0x71, 0x0c, 0x5c, 0x3e, 0x26, 0xcc, 0x20, 0x06, 0x2c, 0xff, 0x8a, 0x49, 0x11, 0x22, 0x68, 0x65, 0xe5, 0x98, 0x52, 0x6c, 0x65, 0x05, 0x57, 0x61, 0x65, 0x15, 0x66, 0x60, 0x65, 0x05, 0x56, 0x93, 0xc4, 0x06, 0x76, 0x98, 0x31, 0x20, 0x00, 0x00, 0xff, 0xff, 0x1e, 0x6c, 0x55, 0x4b, 0xc7, 0x01, 0x00, 0x00, }
cloudfoundry-community/firehose-to-syslog
vendor/google.golang.org/genproto/googleapis/ads/googleads/v0/enums/frequency_cap_level.pb.go
GO
mit
5,878
// // 2_2_DefineVariables.cpp // CPP // // Created by akshay raj gollahalli on 2/02/16. // Copyright © 2016 akshay raj gollahalli. All rights reserved. // #include <cstdio> int main(int argc, char ** argv) { int someNumber = 10; /* this can also be written as int someNumber; someNumber = 10; */ const int constantNumber = 10; // constantNumber = 11; // this cannot be changed once initalized. printf("some number is %d\n", someNumber); printf("constant number is %d\n", constantNumber); return 0; }
akshaybabloo/CPP-Notes
2_Basics/2_2_DefineVariables.cpp
C++
mit
519
from django import forms from django.contrib.auth.forms import AuthenticationForm from django.utils.translation import ugettext_lazy as _ class EmailAuthenticationForm(AuthenticationForm): """Email authentication Form increase the size of the username field to fit long emails""" # TODO: consider to change this to an email only field username = forms.CharField(label=_("Username"), widget=forms.TextInput(attrs={'class': 'text'})) password = forms.CharField(label=_("Password"), widget=forms.PasswordInput( attrs={'class': 'text'})) remember_me = forms.BooleanField(label='Keep me logged in', required=False)
theteam/django-theteamcommon
src/theteamcommon/forms.py
Python
mit
770
module.exports = { Shape: require('./lib/shape'), Node: require('./lib/node'), Error: require('./lib/node_error'), MemorySource: require('./lib/memory_source'), };
LastLeaf/datree
index.js
JavaScript
mit
180
<?php /* FOSUserBundle:Profile:show.html.twig */ class __TwigTemplate_2d974d2be07c528b56adfa6823dca8b997fac47403b46447cbcad246a9aa4057 extends Twig_Template { public function __construct(Twig_Environment $env) { parent::__construct($env); $this->parent = $this->env->loadTemplate("FOSUserBundle::layout.html.twig"); $this->blocks = array( 'fos_user_content' => array($this, 'block_fos_user_content'), ); } protected function doGetParent(array $context) { return "FOSUserBundle::layout.html.twig"; } protected function doDisplay(array $context, array $blocks = array()) { $this->parent->display($context, array_merge($this->blocks, $blocks)); } // line 3 public function block_fos_user_content($context, array $blocks = array()) { // line 4 $this->env->loadTemplate("FOSUserBundle:Profile:show_content.html.twig")->display($context); } public function getTemplateName() { return "FOSUserBundle:Profile:show.html.twig"; } public function isTraitable() { return false; } public function getDebugInfo() { return array ( 31 => 4, 28 => 3,); } }
efrax/IMDER
app/cache/dev/twig/2d/97/4d2be07c528b56adfa6823dca8b997fac47403b46447cbcad246a9aa4057.php
PHP
mit
1,239
<?php /* * Skeleton Bundle * This file is part of the BardisCMS. * * (c) George Bardis <george@bardis.info> * */ namespace BardisCMS\SkeletonBundle\Repository; use Doctrine\ORM\EntityRepository; class SkeletonRepository extends EntityRepository { // Function to retrieve the pages of a category with pagination public function getCategoryItems($categoryIds, $currentPageId, $publishStates, $currentpage, $totalpageitems) { $pageList = null; if (!empty($categoryIds)) { // Initalize the query builder variables $qb = $this->_em->createQueryBuilder(); $countqb = $this->_em->createQueryBuilder(); // The query to get the page items for the current paginated listing page $qb->select('DISTINCT p') ->from('SkeletonBundle:Skeleton', 'p') ->innerJoin('p.categories', 'c') ->where($qb->expr()->andX( $qb->expr()->in('c.id', ':category'), $qb->expr()->in('p.publishState', ':publishState'), $qb->expr()->neq('p.pagetype', ':categorypagePageType'), $qb->expr()->neq('p.id', ':currentPage') )) ->orderBy('p.date', 'DESC') ->setParameter('category', $categoryIds) ->setParameter('publishState', $publishStates) ->setParameter('categorypagePageType', 'category_page') ->setParameter('currentPage', $currentPageId) ; // The query to get the total page items count $countqb->select('COUNT(DISTINCT p.id)') ->from('SkeletonBundle:Skeleton', 'p') ->innerJoin('p.categories', 'c') ->where($countqb->expr()->andX( $countqb->expr()->in('c.id', ':category'), $countqb->expr()->in('p.publishState', ':publishState'), $countqb->expr()->neq('p.pagetype', ':categorypagePageType'), $countqb->expr()->neq('p.id', ':currentPage') )) ->orderBy('p.date', 'DESC') ->setParameter('category', $categoryIds) ->setParameter('publishState', $publishStates) ->setParameter('categorypagePageType', 'category_page') ->setParameter('currentPage', $currentPageId) ; $totalResultsCount = intval($countqb->getQuery()->getSingleScalarResult()); // Get the paginated results $pageList = $this->getPaginatedResults($qb, $totalResultsCount, $currentpage, $totalpageitems); } return $pageList; } // Function to retrieve the pages of tag/category combination with pagination public function getTaggedCategoryItems($categoryIds, $currentPageId, $publishStates, $currentpage, $totalpageitems, $tagIds) { $pageList = null; if (!empty($categoryIds)) { // Initalize the query builder variables $qb = $this->_em->createQueryBuilder(); $countqb = $this->_em->createQueryBuilder(); // The query to get the page items for the current paginated listing page $qb->select('DISTINCT p') ->from('SkeletonBundle:Skeleton', 'p') ->innerJoin('p.categories', 'c') ->innerJoin('p.tags', 't') ->where($qb->expr()->andX( $qb->expr()->in('c.id', ':category'), $qb->expr()->in('t.id', ':tag'), $qb->expr()->in('p.publishState', ':publishState'), $qb->expr()->neq('p.id', ':currentPage'), $qb->expr()->eq('p.pagetype', ':pagetype') )) ->orderBy('p.date', 'DESC') ->setParameter('category', $categoryIds) ->setParameter('tag', $tagIds) ->setParameter('publishState', $publishStates) ->setParameter('pagetype', 'skeleton_article') ->setParameter('currentPage', $currentPageId) ; // The query to get the total page items count $countqb->select('COUNT(DISTINCT p.id)') ->from('SkeletonBundle:Skeleton', 'p') ->innerJoin('p.categories', 'c') ->innerJoin('p.tags', 't') ->where($countqb->expr()->andX( $countqb->expr()->in('c.id', ':category'), $countqb->expr()->in('t.id', ':tag'), $countqb->expr()->in('p.publishState', ':publishState'), $countqb->expr()->neq('p.id', ':currentPage'), $countqb->expr()->eq('p.pagetype', ':pagetype') )) ->orderBy('p.date', 'DESC') ->setParameter('category', $categoryIds) ->setParameter('tag', $tagIds) ->setParameter('publishState', $publishStates) ->setParameter('pagetype', 'skeleton_article') ->setParameter('currentPage', $currentPageId) ; $totalResultsCount = intval($countqb->getQuery()->getSingleScalarResult()); // Get the paginated results $pageList = $this->getPaginatedResults($qb, $totalResultsCount, $currentpage, $totalpageitems); } return $pageList; } // Function to retrieve the pages of a tag with pagination public function getTaggedItems($tagIds, $currentPageId, $publishStates, $currentpage, $totalpageitems) { $pageList = null; if (!empty($tagIds)) { // Initalize the query builder variables $qb = $this->_em->createQueryBuilder(); $countqb = $this->_em->createQueryBuilder(); // The query to get the page items for the current paginated listing page $qb->select('DISTINCT p') ->from('SkeletonBundle:Skeleton', 'p') ->innerJoin('p.tags', 't') ->where($qb->expr()->andX( $qb->expr()->in('t.id', ':tag'), $qb->expr()->in('p.publishState', ':publishState'), $qb->expr()->eq('p.pagetype', ':pagetype'), $qb->expr()->neq('p.id', ':currentPage') )) ->orderBy('p.date', 'DESC') ->setParameter('tag', $tagIds) ->setParameter('publishState', $publishStates) ->setParameter('pagetype', 'skeleton_article') ->setParameter('currentPage', $currentPageId) ; // The query to get the total page items count $countqb->select('COUNT(DISTINCT p.id)') ->from('SkeletonBundle:Skeleton', 'p') ->innerJoin('p.tags', 't') ->where($countqb->expr()->andX( $countqb->expr()->in('t.id', ':tag'), $countqb->expr()->in('p.publishState', ':publishState'), $countqb->expr()->eq('p.pagetype', ':pagetype'), $countqb->expr()->neq('p.id', ':currentPage') )) ->orderBy('p.date', 'DESC') ->setParameter('tag', $tagIds) ->setParameter('publishState', $publishStates) ->setParameter('pagetype', 'skeleton_article') ->setParameter('currentPage', $currentPageId) ; $totalResultsCount = intval($countqb->getQuery()->getSingleScalarResult()); // Get the paginated results $pageList = $this->getPaginatedResults($qb, $totalResultsCount, $currentpage, $totalpageitems); } return $pageList; } // Function to retrieve all the pages public function getAllItems($currentPageId, $publishStates, $currentpage, $totalpageitems) { $pageList = null; // Initalize the query builder variables $qb = $this->_em->createQueryBuilder(); $countqb = $this->_em->createQueryBuilder(); // The query to get the page items for the current paginated listing page $qb->select('p') ->from('SkeletonBundle:Skeleton', 'DISTINCT p') ->where($qb->expr()->andX( $qb->expr()->in('p.publishState', ':publishState'), $qb->expr()->eq('p.pagetype', ':pagetype'), $qb->expr()->neq('p.id', ':currentPage') )) ->orderBy('p.date', 'DESC') ->setParameter('publishState', $publishStates) ->setParameter('pagetype', 'skeleton_article') ->setParameter('currentPage', $currentPageId) ; // The query to get the total page items count $countqb->select('COUNT(DISTINCT p.id)') ->from('SkeletonBundle:Skeleton', 'p') ->where($countqb->expr()->andX( $countqb->expr()->in('p.publishState', ':publishState'), $countqb->expr()->eq('p.pagetype', ':pagetype'), $countqb->expr()->neq('p.id', ':currentPage') )) ->orderBy('p.date', 'DESC') ->setParameter('publishState', $publishStates) ->setParameter('pagetype', 'skeleton_article') ->setParameter('currentPage', $currentPageId) ; $totalResultsCount = intval($countqb->getQuery()->getSingleScalarResult()); // Get the paginated results $pageList = $this->getPaginatedResults($qb, $totalResultsCount, $currentpage, $totalpageitems); return $pageList; } // Function to retrieve the pages of the homepage category public function getHomepageItems($categoryIds, $publishStates) { $pageList = null; if (!empty($categoryIds)) { // Initalize the query builder variables $qb = $this->_em->createQueryBuilder(); // The query to get the page items for the homepage page $qb->select('DISTINCT p') ->from('SkeletonBundle:Skeleton', 'p') ->innerJoin('p.categories', 'c') ->where($qb->expr()->andX( $qb->expr()->in('c.id', ':category'), $qb->expr()->in('p.publishState', ':publishState') )) ->orderBy('p.pageOrder', 'ASC') ->setParameter('category', $categoryIds) ->setParameter('publishState', $publishStates) ; // Get the results $pageList = $qb->getQuery()->getResult(); } return $pageList; } // Function to retrieve a page list for sitemap public function getSitemapList($publishStates) { // Initalize the query builder variables $qb = $this->_em->createQueryBuilder(); // The query to get all page items $qb->select('DISTINCT p') ->from('SkeletonBundle:Skeleton', 'p') ->where( $qb->expr()->in('p.publishState', ':publishState') ) ->orderBy('p.id', 'ASC') ->setParameter('publishState', $publishStates) ; // Get the results $sitemapList = $qb->getQuery()->getResult(); return $sitemapList; } // Function to define what page items will be returned for each paginated listing page public function getPaginatedResults($qb, $totalResultsCount, $currentpage, $totalpageitems) { $pages = null; $totalPages = 1; // Calculate and set the starting and last page item to retrieve if ((isset($currentpage)) && (isset($totalpageitems))) { if ($totalpageitems > 0) { $startingItem = (intval($currentpage) * $totalpageitems); $qb->setFirstResult($startingItem); $qb->setMaxResults($totalpageitems); } } // Get paginated results $pages = $qb->getQuery()->getResult(); // Get the total pagination pages $totalPages = ceil($totalResultsCount / $totalpageitems); // Set the page items and pagination to be returned $pageList = array('pages' => $pages, 'totalPages' => $totalPages); return $pageList; } }
bardius/the-web-dev-ninja-blog
src/BardisCMS/SkeletonBundle/Repository/SkeletonRepository.php
PHP
mit
12,435
// Code generated by ffjson <https://github.com/pquerna/ffjson>. DO NOT EDIT. // source: vestingbalance.go package types import ( "bytes" "fmt" fflib "github.com/pquerna/ffjson/fflib/v1" ) // MarshalJSON marshal bytes to json - template func (j *VestingBalance) MarshalJSON() ([]byte, error) { var buf fflib.Buffer if j == nil { buf.WriteString("null") return buf.Bytes(), nil } err := j.MarshalJSONBuf(&buf) if err != nil { return nil, err } return buf.Bytes(), nil } // MarshalJSONBuf marshal buff to json - template func (j *VestingBalance) MarshalJSONBuf(buf fflib.EncodingBuffer) error { if j == nil { buf.WriteString("null") return nil } var err error var obj []byte _ = obj _ = err buf.WriteString(`{"id":`) { obj, err = j.ID.MarshalJSON() if err != nil { return err } buf.Write(obj) } buf.WriteString(`,"balance":`) { err = j.Balance.MarshalJSONBuf(buf) if err != nil { return err } } buf.WriteString(`,"owner":`) { obj, err = j.Owner.MarshalJSON() if err != nil { return err } buf.Write(obj) } buf.WriteString(`,"policy":`) { obj, err = j.Policy.MarshalJSON() if err != nil { return err } buf.Write(obj) } buf.WriteByte('}') return nil } const ( ffjtVestingBalancebase = iota ffjtVestingBalancenosuchkey ffjtVestingBalanceID ffjtVestingBalanceBalance ffjtVestingBalanceOwner ffjtVestingBalancePolicy ) var ffjKeyVestingBalanceID = []byte("id") var ffjKeyVestingBalanceBalance = []byte("balance") var ffjKeyVestingBalanceOwner = []byte("owner") var ffjKeyVestingBalancePolicy = []byte("policy") // UnmarshalJSON umarshall json - template of ffjson func (j *VestingBalance) UnmarshalJSON(input []byte) error { fs := fflib.NewFFLexer(input) return j.UnmarshalJSONFFLexer(fs, fflib.FFParse_map_start) } // UnmarshalJSONFFLexer fast json unmarshall - template ffjson func (j *VestingBalance) UnmarshalJSONFFLexer(fs *fflib.FFLexer, state fflib.FFParseState) error { var err error currentKey := ffjtVestingBalancebase _ = currentKey tok := fflib.FFTok_init wantedTok := fflib.FFTok_init mainparse: for { tok = fs.Scan() // println(fmt.Sprintf("debug: tok: %v state: %v", tok, state)) if tok == fflib.FFTok_error { goto tokerror } switch state { case fflib.FFParse_map_start: if tok != fflib.FFTok_left_bracket { wantedTok = fflib.FFTok_left_bracket goto wrongtokenerror } state = fflib.FFParse_want_key continue case fflib.FFParse_after_value: if tok == fflib.FFTok_comma { state = fflib.FFParse_want_key } else if tok == fflib.FFTok_right_bracket { goto done } else { wantedTok = fflib.FFTok_comma goto wrongtokenerror } case fflib.FFParse_want_key: // json {} ended. goto exit. woo. if tok == fflib.FFTok_right_bracket { goto done } if tok != fflib.FFTok_string { wantedTok = fflib.FFTok_string goto wrongtokenerror } kn := fs.Output.Bytes() if len(kn) <= 0 { // "" case. hrm. currentKey = ffjtVestingBalancenosuchkey state = fflib.FFParse_want_colon goto mainparse } else { switch kn[0] { case 'b': if bytes.Equal(ffjKeyVestingBalanceBalance, kn) { currentKey = ffjtVestingBalanceBalance state = fflib.FFParse_want_colon goto mainparse } case 'i': if bytes.Equal(ffjKeyVestingBalanceID, kn) { currentKey = ffjtVestingBalanceID state = fflib.FFParse_want_colon goto mainparse } case 'o': if bytes.Equal(ffjKeyVestingBalanceOwner, kn) { currentKey = ffjtVestingBalanceOwner state = fflib.FFParse_want_colon goto mainparse } case 'p': if bytes.Equal(ffjKeyVestingBalancePolicy, kn) { currentKey = ffjtVestingBalancePolicy state = fflib.FFParse_want_colon goto mainparse } } if fflib.SimpleLetterEqualFold(ffjKeyVestingBalancePolicy, kn) { currentKey = ffjtVestingBalancePolicy state = fflib.FFParse_want_colon goto mainparse } if fflib.SimpleLetterEqualFold(ffjKeyVestingBalanceOwner, kn) { currentKey = ffjtVestingBalanceOwner state = fflib.FFParse_want_colon goto mainparse } if fflib.SimpleLetterEqualFold(ffjKeyVestingBalanceBalance, kn) { currentKey = ffjtVestingBalanceBalance state = fflib.FFParse_want_colon goto mainparse } if fflib.SimpleLetterEqualFold(ffjKeyVestingBalanceID, kn) { currentKey = ffjtVestingBalanceID state = fflib.FFParse_want_colon goto mainparse } currentKey = ffjtVestingBalancenosuchkey state = fflib.FFParse_want_colon goto mainparse } case fflib.FFParse_want_colon: if tok != fflib.FFTok_colon { wantedTok = fflib.FFTok_colon goto wrongtokenerror } state = fflib.FFParse_want_value continue case fflib.FFParse_want_value: if tok == fflib.FFTok_left_brace || tok == fflib.FFTok_left_bracket || tok == fflib.FFTok_integer || tok == fflib.FFTok_double || tok == fflib.FFTok_string || tok == fflib.FFTok_bool || tok == fflib.FFTok_null { switch currentKey { case ffjtVestingBalanceID: goto handle_ID case ffjtVestingBalanceBalance: goto handle_Balance case ffjtVestingBalanceOwner: goto handle_Owner case ffjtVestingBalancePolicy: goto handle_Policy case ffjtVestingBalancenosuchkey: err = fs.SkipField(tok) if err != nil { return fs.WrapErr(err) } state = fflib.FFParse_after_value goto mainparse } } else { goto wantedvalue } } } handle_ID: /* handler: j.ID type=types.VestingBalanceID kind=struct quoted=false*/ { if tok == fflib.FFTok_null { } else { tbuf, err := fs.CaptureField(tok) if err != nil { return fs.WrapErr(err) } err = j.ID.UnmarshalJSON(tbuf) if err != nil { return fs.WrapErr(err) } } state = fflib.FFParse_after_value } state = fflib.FFParse_after_value goto mainparse handle_Balance: /* handler: j.Balance type=types.AssetAmount kind=struct quoted=false*/ { if tok == fflib.FFTok_null { } else { err = j.Balance.UnmarshalJSONFFLexer(fs, fflib.FFParse_want_key) if err != nil { return err } } state = fflib.FFParse_after_value } state = fflib.FFParse_after_value goto mainparse handle_Owner: /* handler: j.Owner type=types.AccountID kind=struct quoted=false*/ { if tok == fflib.FFTok_null { } else { tbuf, err := fs.CaptureField(tok) if err != nil { return fs.WrapErr(err) } err = j.Owner.UnmarshalJSON(tbuf) if err != nil { return fs.WrapErr(err) } } state = fflib.FFParse_after_value } state = fflib.FFParse_after_value goto mainparse handle_Policy: /* handler: j.Policy type=types.VestingPolicy kind=struct quoted=false*/ { if tok == fflib.FFTok_null { } else { tbuf, err := fs.CaptureField(tok) if err != nil { return fs.WrapErr(err) } err = j.Policy.UnmarshalJSON(tbuf) if err != nil { return fs.WrapErr(err) } } state = fflib.FFParse_after_value } state = fflib.FFParse_after_value goto mainparse wantedvalue: return fs.WrapErr(fmt.Errorf("wanted value token, but got token: %v", tok)) wrongtokenerror: return fs.WrapErr(fmt.Errorf("ffjson: wanted token: %v, but got token: %v output=%s", wantedTok, tok, fs.Output.String())) tokerror: if fs.BigError != nil { return fs.WrapErr(fs.BigError) } err = fs.Error.ToError() if err != nil { return fs.WrapErr(err) } panic("ffjson-generated: unreachable, please report bug.") done: return nil }
denkhaus/bitshares
types/vestingbalance_ffjson.go
GO
mit
7,613
require "pact_broker/domain/pact" module PactBroker module Pacts class PlaceholderPact < PactBroker::Domain::Pact def initialize consumer = OpenStruct.new(name: "placeholder-consumer", labels: [OpenStruct.new(name: "placeholder-consumer-label")]) @provider = OpenStruct.new(name: "placeholder-provider", labels: [OpenStruct.new(name: "placeholder-provider-label")]) @consumer_version = OpenStruct.new(number: "gggghhhhjjjjkkkkllll66667777888899990000", pacticipant: consumer, tags: [OpenStruct.new(name: "master")]) @consumer_version_number = @consumer_version.number @created_at = DateTime.now @revision_number = 1 @pact_version_sha = "5d445a4612743728dfd99ccd4210423c052bb9db" end end end end
pact-foundation/pact_broker
lib/pact_broker/pacts/placeholder_pact.rb
Ruby
mit
776
<?php defined('BASEPATH') OR exit('No direct script access allowed'); // This can be removed if you use __autoload() in config.php OR use Modular Extensions require_once APPPATH . '/libraries/REST_Controller.php'; class Services extends REST_Controller { public function __construct() { parent::__construct(); $this->load->helper('url_helper'); } public function newHistoryDaily_post() { if($this->post()) { $this->load->model('User_model'); $this->load->model('Target_model'); $normalExpense = $this->Target_model->detail_target($this->post('id_target'))->normal_expense; $offset = $this->Target_model->detail_target($this->post('id_target'))->offset; $targetData = $this->User_model->detail_user($this->post('username')); $data = []; $save = 0; $expense = 0; foreach($this->post() as $key => $value) { $data[$key] = $value; if($key != 'username' && $key != 'id_target' && $key != 'date') { $expense += intval($value); } } $save = floor($targetData->penghasilan/30) - $expense; $data['save'] = $save; $data['expense'] = $expense; $offset = $offset+($normalExpense - $expense); $this->Target_model->update_offset_target($this->post('id_target'),$offset); $inp = file_get_contents(base_url().'json/history.json'); $tempArray = json_decode($inp); array_push($tempArray, $data); $jsonData = json_encode($tempArray); file_put_contents('././json/history.json', $jsonData); $this->response([[ 'status' => TRUE, 'message' => 'Pengeluaran Daily added' ]], REST_Controller::HTTP_CREATED); // OK (200) being the HTTP response code } else { $this->response(NULL, REST_Controller::HTTP_BAD_REQUEST); // BAD_REQUEST (400) being the HTTP response code } } public function newHistoryDailyV1_post() { if($this->post()) { $this->load->model('User_model'); $this->load->model('Target_model'); $normalExpense = $this->Target_model->detail_target($this->post('id_target'))->normal_expense; $offset = $this->Target_model->detail_target($this->post('id_target'))->offset; $targetData = $this->User_model->detail_user($this->post('username')); $data = []; $save = 0; $expense = 0; foreach($this->post() as $key => $value) { $data[$key] = $value; if($key != 'username' && $key != 'id_target' && $key != 'date') { $expense += intval($value); } } $save = floor($targetData->penghasilan/30) - $expense; $data['save'] = $save; $data['expense'] = $expense; $offset = $offset+($normalExpense - $expense); $this->Target_model->update_offset_target($this->post('id_target'),$offset); $inp = file_get_contents(base_url().'json/history.json'); $tempArray = json_decode($inp); array_push($tempArray, $data); $jsonData = json_encode($tempArray); file_put_contents('././json/history.json', $jsonData); $this->response([[ 'status' => TRUE, 'message' => 'Pengeluaran Daily added' ]], REST_Controller::HTTP_CREATED); // OK (200) being the HTTP response code } else { $this->response(NULL, REST_Controller::HTTP_BAD_REQUEST); // BAD_REQUEST (400) being the HTTP response code } } public function updateHistoryDaily_post() { $this->load->model('Target_model'); $normalExpense = $this->Target_model->detail_target($this->post('id_target'))->normal_expense; $offset = $this->Target_model->detail_target($this->post('id_target'))->offset; $amountKeys = []; $keys = []; foreach($this->post() as $key => $value) { if(substr($key,0,7) == 'amount_') { $datum = []; $datum['key'] = $key; $datum['value'] = $value; array_push($amountKeys,$datum); } else if($key != 'username' && $key != 'id_target' && $key != 'date'){ $datum = []; $datum['key'] = $key; $datum['value'] = $value; array_push($keys,$datum); } } $inp = file_get_contents(base_url().'json/history.json'); $tempArray = json_decode($inp); $i = 0; foreach($tempArray as $temp) { if ($temp->username == $this->post('username') && $temp->id_target == $this->post('id_target') && $temp->date == $this->post('date')) { $tempExpense = $temp->expense; foreach($amountKeys as $amountKey) { $tempKey = substr($amountKey['key'],7); $diff = $temp->$tempKey - $amountKey['value']; $temp->$tempKey = $amountKey['value']; $temp->save = $temp->save + $diff; $temp->expense = $temp->expense - $diff; } $endExpense = $tempExpense - $temp->expense; $offset = $offset+$endExpense; $this->Target_model->update_offset_target($this->post('id_target'),$offset); foreach($keys as $k) { if($k['value'] != $k['key']) { $tempArray[$i]->$k['value'] = $tempArray[$i]->$k['key']; unset($tempArray[$i]->$k['key']); } } } $i = $i+1; } $jsonData = json_encode($tempArray); file_put_contents('././json/history.json', $jsonData); $this->response([[ 'status' => TRUE, 'message' => 'Pengeluaran Daily updated' ]], REST_Controller::HTTP_CREATED); // OK (200) being the HTTP response code } public function updateHistoryDailyAmount_post() { $this->load->model('Target_model'); $normalExpense = $this->Target_model->detail_target($this->post('id_target'))->normal_expense; $offset = $this->Target_model->detail_target($this->post('id_target'))->offset; foreach($this->post() as $key => $value) { if($key != 'username' && $key != 'id_target' && $key != 'date') { $field = $key; } } $inp = file_get_contents(base_url().'json/history.json'); $tempArray = json_decode($inp); foreach($tempArray as $temp) { if ($temp->username == $this->post('username') && $temp->id_target == $this->post('id_target') && $temp->date == $this->post('date')) { foreach($temp as $key => $value) { if($key == $field) { $diff = $temp->$field - $this->post($field); $temp->$field = $this->post($field); } } $temp->save = $temp->save + $diff; $offset = $offset+$diff; $temp->expense = $temp->expense - $diff; $this->Target_model->update_offset_target($this->post('id_target'),$offset); } } $jsonData = json_encode($tempArray); file_put_contents('././json/history.json', $jsonData); $this->response([[ 'status' => TRUE, 'message' => 'Pengeluaran Daily updated' ]], REST_Controller::HTTP_CREATED); // OK (200) being the HTTP response code } public function deleteHistoryDaily_post() { $this->load->model('Target_model'); $normalExpense = $this->Target_model->detail_target($this->post('id_target'))->normal_expense; $offset = $this->Target_model->detail_target($this->post('id_target'))->offset; foreach($this->post() as $key => $value) { if($key != 'username' && $key != 'id_target' && $key != 'date') { $field = $key; } } $inp = file_get_contents(base_url().'json/history.json'); $tempArray = json_decode($inp, true); $i = 0; foreach($tempArray as $temp) { if ($temp['username'] == $this->post('username') && $temp['id_target'] == $this->post('id_target') && $temp['date'] == $this->post('date')) { foreach($temp as $key => $value) { if($key == $field) { $diff = $temp[$field]; unset($temp[$field]); $tempArray[$i] = $temp; } } $tempArray[$i]['save'] = $tempArray[$i]['save'] + $diff; $offset = $offset+$diff; $this->Target_model->update_offset_target($this->post('id_target'),$offset); $tempArray[$i]['expense'] = $tempArray[$i]['expense'] - $diff; } $i=$i+1; } // var_dump($temp); $jsonData = json_encode($tempArray); file_put_contents('././json/history.json', $jsonData); $this->response([[ 'status' => TRUE, 'message' => 'Pengeluaran Daily updated' ]], REST_Controller::HTTP_CREATED); // OK (200) being the HTTP response code } public function getHistoryDaily_get() { $response = array(); $inp = file_get_contents(base_url().'json/history.json'); $tempArray = json_decode($inp); foreach($tempArray as $temp) { if ($temp->username == $this->get('username') && $temp->id_target == $this->get('id_target')) { $response = array_push($response, $temp); } } $this->response($response, REST_Controller::HTTP_OK); } public function login_post() { $this->load->model('User_model'); $username = $this->post('username'); $password = $this->post('password'); if($username != NULL && $password != NULL) { $user = $this->User_model->login($username, md5($password)); if($user) { $this->response([[ 'status' => TRUE, 'message' => 'Login succeeded', 'username' => $user->username, 'nama_user' => $user->nama_user ]], REST_Controller::HTTP_OK); // OK (200) being the HTTP response code } else { $this->response([[ 'status' => FALSE, 'message' => 'Wrong username or password' ]]); } } else { $this->response(NULL, REST_Controller::HTTP_BAD_REQUEST); // BAD_REQUEST (400) being the HTTP response code } } public function penghasilan_post(){ $this->load->model('User_model'); $username = $this->post('username'); $penghasilan = $this->post('penghasilan'); $responses = $this->User_model->updatePenghasilan($username, $penghasilan); $this->response(NULL, REST_Controller::HTTP_OK); } public function pengeluaran_get() { $this->load->model('Pengeluaran_model'); $username = $this->get('username'); if($username != NULL) { $responses = $this->Pengeluaran_model->getPengeluaranDefault($username); $this->response($responses, REST_Controller::HTTP_OK); } else { $this->response(NULL, REST_Controller::HTTP_BAD_REQUEST); } } public function historyTarget_get() { $this->load->model('HistoryTarget_model'); $username = $this->get('username'); $response = $this->HistoryTarget_model->getHistoryTarget($username); $this->response($response, REST_Controller::HTTP_OK); } public function newPengeluaran_post() { $this->load->model('Pengeluaran_model'); $username = $this->post('username'); $desc = $this->post('description'); $amount = $this->post('amount'); $response = $this->Pengeluaran_model->newPengeluaranDefault($username, $desc, $amount); if($response) { $this->response([[ 'status' => TRUE, 'message' => 'Pengeluaran added' ]], REST_Controller::HTTP_CREATED); // OK (200) being the HTTP response code } else { $this->response([[ 'status' => FALSE, 'message' => 'Pengeluaran failed' ]]); } } public function updatePengeluaran_post() { $this->load->model('Pengeluaran_model'); $username = $this->post('username'); $desc = $this->post('description'); $amount = $this->post('amount'); $response = $this->Pengeluaran_model->updatePengeluaranDefault($username, $desc, $amount); if($response) { $this->response([[ 'status' => TRUE, 'message' => 'Pengeluaran modified' ]], REST_Controller::HTTP_OK); // OK (200) being the HTTP response code } else { $this->response([[ 'status' => FALSE, 'message' => 'Wrong username or password' ]]); } } public function deletePengeluaran_post() { $this->load->model('Pengeluaran_model'); $username = $this->post('username'); $desc = $this->post('description'); $response = $this->Pengeluaran_model->deletePengeluaranDefault($username, $desc); if($response) { $this->response([[ 'status' => TRUE, 'message' => 'Pengeluaran deleted' ]], REST_Controller::HTTP_CREATED); // OK (200) being the HTTP response code } else { $this->response([[ 'status' => FALSE, 'message' => 'Wrong username or password' ]]); } } public function register_post() { $this->load->model('User_model'); $username = $this->post('username'); $password = $this->post('password'); $name = $this->post('nama_user'); if($username != NULL && $password != NULL && $name != NULL) { $post = array( 'username' => $username, 'password' => md5($password), 'nama_user' => $name ); if($this->User_model->register($post)) { $this->response([[ 'status' => TRUE, 'message' => 'User created' ]], REST_Controller::HTTP_CREATED); } else { $this->response([[ 'status' => FALSE, 'message' => 'Username already taken' ]], REST_Controller::HTTP_BAD_REQUEST); } } else { $this->response(NULL, REST_Controller::HTTP_BAD_REQUEST); // BAD_REQUEST (400) being the HTTP response code } } public function newTarget_post() { $this->load->model('Target_model'); $this->load->model('HistoryTarget_model'); $desc = $this->post('target_desc'); $amount = $this->post('target_amount'); $startDate = $this->post('target_startdate'); $dueDate = $this->post('target_duedate'); $normalExpense = $this->post('normal_expense'); $username = $this->post('username'); if($username != NULL && $desc != NULL && $amount != NULL && $startDate != NULL && $dueDate != NULL && $normalExpense != NULL) { $args = array( 'target_desc' => $desc, 'target_amount' => $amount, 'target_startdate' => $startDate, 'target_duedate' => $dueDate, 'normal_expense' => $normalExpense ); $idTarget = $this->Target_model->insert_target($args); $post = array( 'id_target' => $idTarget, ); $this->Target_model->update_targetUser($username, $post); $history = array( 'username' => $username, 'id_target' => $idTarget ); $this->HistoryTarget_model->insert_historyTarget($history); $this->response([[ 'status' => TRUE, 'message' => 'Target created' ]], REST_Controller::HTTP_CREATED); } else { $this->response(NULL, REST_Controller::HTTP_BAD_REQUEST); // BAD_REQUEST (400) being the HTTP response code } } public function updateTarget_post() { $this->load->model('Target_model'); $id = $this->post('id_target'); $desc = $this->post('target_desc'); $amount = $this->post('target_amount'); $startDate = $this->post('target_startdate'); $dueDate = $this->post('target_duedate'); $normalExpense = $this->post('normal_expense'); if($id != NULL && $desc != NULL && $amount != NULL && $startDate != NULL && $dueDate != NULL && $normalExpense != NULL) { $args = array( 'target_desc' => $desc, 'target_amount' => $amount, 'target_startdate' => $startDate, 'target_duedate' => $dueDate, 'normal_expense' => $normalExpense ); $idTarget = $this->Target_model->update_target($id, $args); $this->response([[ 'status' => TRUE, 'message' => 'Target updated' ]], REST_Controller::HTTP_OK); } else { $this->response(NULL, REST_Controller::HTTP_BAD_REQUEST); // BAD_REQUEST (400) being the HTTP response code } } public function updateStatusTarget_post() { $this->load->model('Target_model'); $id = $this->post('id_target'); if($id != NULL) { $args = array( 'status' => 0, ); $idTarget = $this->Target_model->update_status_target($id, $args); $this->response([[ 'status' => TRUE, 'message' => 'Target updated' ]], REST_Controller::HTTP_OK); } else { $this->response(NULL, REST_Controller::HTTP_BAD_REQUEST); // BAD_REQUEST (400) being the HTTP response code } } public function deleteTarget_post() { $this->load->model('Target_model'); $this->load->model('HistoryTarget_model'); $id = $this->post('id_target'); if($id != NULL) { $this->HistoryTarget_model->delete_history($id); $this->Target_model->delete_target($id); $this->response([[ 'status' => TRUE, 'message' => 'Target deleted' ]], REST_Controller::HTTP_OK); } else { $this->response(NULL, REST_Controller::HTTP_BAD_REQUEST); // BAD_REQUEST (400) being the HTTP response code } } public function User_get() { $this->load->model('User_model'); $username = $this->get('username'); if($username != NULL) { $user = $this->User_model->detail_user($username); if($user) { $this->response($user, REST_Controller::HTTP_OK); } else { $this->response([[ 'status' => FALSE, 'message' => 'Username not found.' ]], REST_Controller::HTTP_BAD_REQUEST); } } else { $this->response(NULL, REST_Controller::HTTP_BAD_REQUEST); // BAD_REQUEST (400) being the HTTP response code } } public function Target_get() { $this->load->model('Target_model'); $id = $this->get('id_target'); if($id != NULL) { $target = $this->Target_model->detail_target($id); if($target) { $this->response($target, REST_Controller::HTTP_OK); } else { $this->response([[ 'status' => FALSE, 'message' => 'Target not found.' ]], REST_Controller::HTTP_BAD_REQUEST); } } else { $this->response(NULL, REST_Controller::HTTP_BAD_REQUEST); // BAD_REQUEST (400) being the HTTP response code } } }
vny1422/Asumu
application/controllers/Services.php
PHP
mit
17,633
from discrete import * f = factorial(100) s = str(f) print sum([int(s[i]) for i in range(len(s))])
jreese/euler
python/problem20.py
Python
mit
101
package de.mineformers.investiture.allomancy.network; import de.mineformers.investiture.allomancy.impl.misting.temporal.SpeedBubble; import de.mineformers.investiture.network.Message; import net.minecraft.util.math.BlockPos; import java.util.UUID; /** * Updates a metal extractor tile entity */ public class SpeedBubbleUpdate extends Message { public static final int ACTION_ADD = 0; public static final int ACTION_REMOVE = 1; public int action; public UUID owner; public int dimension; public BlockPos position; public double radius; public SpeedBubbleUpdate() { } public SpeedBubbleUpdate(int action, SpeedBubble bubble) { this.action = action; this.owner = bubble.owner; this.dimension = bubble.dimension; this.position = bubble.position; this.radius = bubble.radius; } }
PaleoCrafter/Allomancy
src/main/java/de/mineformers/investiture/allomancy/network/SpeedBubbleUpdate.java
Java
mit
875
// Copyright (c) 2011-2013 The Bitcoin developers // Distributed under the MIT/X11 software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include "qvalidatedlineedit.h" #include "vikingcoinaddressvalidator.h" #include "guiconstants.h" QValidatedLineEdit::QValidatedLineEdit(QWidget *parent) : QLineEdit(parent), valid(true), checkValidator(0) { connect(this, SIGNAL(textChanged(QString)), this, SLOT(markValid())); } void QValidatedLineEdit::setValid(bool valid) { if(valid == this->valid) { return; } if(valid) { setStyleSheet(""); } else { setStyleSheet(STYLE_INVALID); } this->valid = valid; } void QValidatedLineEdit::focusInEvent(QFocusEvent *evt) { // Clear invalid flag on focus setValid(true); QLineEdit::focusInEvent(evt); } void QValidatedLineEdit::focusOutEvent(QFocusEvent *evt) { checkValidity(); QLineEdit::focusOutEvent(evt); } void QValidatedLineEdit::markValid() { // As long as a user is typing ensure we display state as valid setValid(true); } void QValidatedLineEdit::clear() { setValid(true); QLineEdit::clear(); } void QValidatedLineEdit::setEnabled(bool enabled) { if (!enabled) { // A disabled QValidatedLineEdit should be marked valid setValid(true); } else { // Recheck validity when QValidatedLineEdit gets enabled checkValidity(); } QLineEdit::setEnabled(enabled); } void QValidatedLineEdit::checkValidity() { if (text().isEmpty()) { setValid(true); } else if (hasAcceptableInput()) { setValid(true); // Check contents on focus out if (checkValidator) { QString address = text(); int pos = 0; if (checkValidator->validate(address, pos) == QValidator::Acceptable) setValid(true); else setValid(false); } } else setValid(false); } void QValidatedLineEdit::setCheckValidator(const QValidator *v) { checkValidator = v; }
i3lome/failfial
src/qt/qvalidatedlineedit.cpp
C++
mit
2,162
/* * Copyright 1997-2015 Optimatika (www.optimatika.se) * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package org.ojalgo.matrix.store; import org.ojalgo.ProgrammingError; import org.ojalgo.access.Access1D; import org.ojalgo.constant.PrimitiveMath; import org.ojalgo.scalar.Scalar; /** * IdentityStore * * @author apete */ final class IdentityStore<N extends Number> extends FactoryStore<N> { private final int myDimension; private IdentityStore(final org.ojalgo.matrix.store.PhysicalStore.Factory<N, ?> factory, final int rowsCount, final int columnsCount) { super(factory, rowsCount, columnsCount); myDimension = 0; ProgrammingError.throwForIllegalInvocation(); } IdentityStore(final PhysicalStore.Factory<N, ?> factory, final int dimension) { super(factory, dimension, dimension); myDimension = dimension; } @Override public MatrixStore<N> conjugate() { return this; } @Override public PhysicalStore<N> copy() { return this.factory().makeEye(myDimension, myDimension); } public double doubleValue(final long aRow, final long aCol) { if (aRow == aCol) { return PrimitiveMath.ONE; } else { return PrimitiveMath.ZERO; } } public int firstInColumn(final int col) { return col; } public int firstInRow(final int row) { return row; } public N get(final long aRow, final long aCol) { if (aRow == aCol) { return this.factory().scalar().one().getNumber(); } else { return this.factory().scalar().zero().getNumber(); } } @Override public int limitOfColumn(final int col) { return col + 1; } @Override public int limitOfRow(final int row) { return row + 1; } @Override public MatrixStore<N> multiply(final Access1D<N> right) { if (this.getColDim() == right.count()) { return this.factory().columns(right); } else if (right instanceof MatrixStore<?>) { return ((MatrixStore<N>) right).copy(); } else { return super.multiply(right); } } @Override public MatrixStore<N> multiplyLeft(final Access1D<N> leftMtrx) { if (leftMtrx.count() == this.getRowDim()) { return this.factory().rows(leftMtrx); } else if (leftMtrx instanceof MatrixStore<?>) { return ((MatrixStore<N>) leftMtrx).copy(); } else { return super.multiplyLeft(leftMtrx); } } public Scalar<N> toScalar(final long row, final long column) { if (row == column) { return this.factory().scalar().one(); } else { return this.factory().scalar().zero(); } } @Override public MatrixStore<N> transpose() { return this; } }
jpalves/ojAlgo
src/org/ojalgo/matrix/store/IdentityStore.java
Java
mit
3,940
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using XOMNI.SDK.Core.ApiAccess; using XOMNI.SDK.Core.Providers; namespace XOMNI.SDK.Private.ApiAccess.Catalog.ItemPrice { internal class BatchPrice : ApiAccessBase { protected override string SingleOperationBaseUrl { get { throw new NotImplementedException(); } } protected override string ListOperationBaseUrl { get { return "/private/catalog/items/{0}/prices"; } } public Task<List<Model.Private.Catalog.Price>> UpdateItemPricesAsync(int itemId, List<Model.Private.Catalog.Price> priceList, ApiBasicCredential credential) { return HttpProvider.PutAsync<List<Model.Private.Catalog.Price>>(GenerateUrl(string.Format(ListOperationBaseUrl, itemId)), priceList, credential); } internal XOMNIRequestMessage<List<Model.Private.Catalog.Price>> CreateUpdateItemPricesRequest(int itemId, List<Model.Private.Catalog.Price> priceList, ApiBasicCredential credential) { return new XOMNIRequestMessage<List<Model.Private.Catalog.Price>>(HttpProvider.CreatePutRequest(GenerateUrl(string.Format(ListOperationBaseUrl, itemId)), credential, priceList)); } } }
nseckinoral/xomni-sdk-dotnet
src/XOMNI.SDK.Private/ApiAccess/Catalog/ItemPrice/BatchPrice.cs
C#
mit
1,322
// All code points in the `Sora_Sompeng` script as per Unicode v8.0.0: [ 0x110D0, 0x110D1, 0x110D2, 0x110D3, 0x110D4, 0x110D5, 0x110D6, 0x110D7, 0x110D8, 0x110D9, 0x110DA, 0x110DB, 0x110DC, 0x110DD, 0x110DE, 0x110DF, 0x110E0, 0x110E1, 0x110E2, 0x110E3, 0x110E4, 0x110E5, 0x110E6, 0x110E7, 0x110E8, 0x110F0, 0x110F1, 0x110F2, 0x110F3, 0x110F4, 0x110F5, 0x110F6, 0x110F7, 0x110F8, 0x110F9 ];
mathiasbynens/unicode-data
8.0.0/scripts/Sora_Sompeng-code-points.js
JavaScript
mit
424
using System; namespace Dust { public interface IServiceAspect<TRequest, TResponse> { TResponse Process(TRequest request, Func<TRequest, TResponse> serviceOperation); } }
pjtown/dusty-web-services
Dust/IServiceAspect.cs
C#
mit
176
namespace nUpdate.Administration.Core.Operations.Panels { partial class ScriptExecuteOperationPanel { /// <summary> /// Erforderliche Designervariable. /// </summary> private System.ComponentModel.IContainer components = null; /// <summary> /// Verwendete Ressourcen bereinigen. /// </summary> /// <param name="disposing">True, wenn verwaltete Ressourcen gelöscht werden sollen; andernfalls False.</param> protected override void Dispose(bool disposing) { if (disposing && (components != null)) { components.Dispose(); } base.Dispose(disposing); } #region Vom Komponenten-Designer generierter Code /// <summary> /// Erforderliche Methode für die Designerunterstützung. /// Der Inhalt der Methode darf nicht mit dem Code-Editor geändert werden. /// </summary> private void InitializeComponent() { this.components = new System.ComponentModel.Container(); System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(ScriptExecuteOperationPanel)); this.codeTextBox = new FastColoredTextBoxNS.FastColoredTextBox(); this.tabControl1 = new System.Windows.Forms.TabControl(); this.sourceCodeTabPage = new System.Windows.Forms.TabPage(); this.errorsTabPage = new System.Windows.Forms.TabPage(); this.errorListView = new System.Windows.Forms.ListView(); this.numberHeader = ((System.Windows.Forms.ColumnHeader)(new System.Windows.Forms.ColumnHeader())); this.descriptionHeader = ((System.Windows.Forms.ColumnHeader)(new System.Windows.Forms.ColumnHeader())); this.lineHeader = ((System.Windows.Forms.ColumnHeader)(new System.Windows.Forms.ColumnHeader())); this.columnHeader = ((System.Windows.Forms.ColumnHeader)(new System.Windows.Forms.ColumnHeader())); ((System.ComponentModel.ISupportInitialize)(this.codeTextBox)).BeginInit(); this.tabControl1.SuspendLayout(); this.sourceCodeTabPage.SuspendLayout(); this.errorsTabPage.SuspendLayout(); this.SuspendLayout(); // // codeTextBox // this.codeTextBox.Anchor = ((System.Windows.Forms.AnchorStyles)((((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Bottom) | System.Windows.Forms.AnchorStyles.Left) | System.Windows.Forms.AnchorStyles.Right))); this.codeTextBox.AutoCompleteBracketsList = new char[] { '(', ')', '{', '}', '[', ']', '\"', '\"', '\'', '\''}; this.codeTextBox.AutoScrollMinSize = new System.Drawing.Size(907, 252); this.codeTextBox.BackBrush = null; this.codeTextBox.CharHeight = 14; this.codeTextBox.CharWidth = 8; this.codeTextBox.Cursor = System.Windows.Forms.Cursors.IBeam; this.codeTextBox.DisabledColor = System.Drawing.Color.FromArgb(((int)(((byte)(100)))), ((int)(((byte)(180)))), ((int)(((byte)(180)))), ((int)(((byte)(180))))); this.codeTextBox.IsReplaceMode = false; this.codeTextBox.LeftBracket = '{'; this.codeTextBox.LeftBracket2 = '['; this.codeTextBox.Location = new System.Drawing.Point(0, 0); this.codeTextBox.Name = "codeTextBox"; this.codeTextBox.Paddings = new System.Windows.Forms.Padding(0); this.codeTextBox.RightBracket = '}'; this.codeTextBox.RightBracket2 = ']'; this.codeTextBox.SelectionColor = System.Drawing.Color.FromArgb(((int)(((byte)(60)))), ((int)(((byte)(0)))), ((int)(((byte)(0)))), ((int)(((byte)(255))))); this.codeTextBox.Size = new System.Drawing.Size(468, 197); this.codeTextBox.TabIndex = 2; this.codeTextBox.Text = resources.GetString("codeTextBox.Text"); this.codeTextBox.Zoom = 100; this.codeTextBox.TextChanged += new System.EventHandler<FastColoredTextBoxNS.TextChangedEventArgs>(this.codeTextBox_TextChanged); this.codeTextBox.Leave += new System.EventHandler(this.codeTextBox_Leave); // // tabControl1 // this.tabControl1.Controls.Add(this.sourceCodeTabPage); this.tabControl1.Controls.Add(this.errorsTabPage); this.tabControl1.Location = new System.Drawing.Point(2, 2); this.tabControl1.Name = "tabControl1"; this.tabControl1.SelectedIndex = 0; this.tabControl1.Size = new System.Drawing.Size(476, 223); this.tabControl1.TabIndex = 3; // // sourceCodeTabPage // this.sourceCodeTabPage.Controls.Add(this.codeTextBox); this.sourceCodeTabPage.Location = new System.Drawing.Point(4, 22); this.sourceCodeTabPage.Name = "sourceCodeTabPage"; this.sourceCodeTabPage.Padding = new System.Windows.Forms.Padding(3); this.sourceCodeTabPage.Size = new System.Drawing.Size(468, 197); this.sourceCodeTabPage.TabIndex = 0; this.sourceCodeTabPage.Text = "Source code"; this.sourceCodeTabPage.UseVisualStyleBackColor = true; // // errorsTabPage // this.errorsTabPage.Controls.Add(this.errorListView); this.errorsTabPage.Location = new System.Drawing.Point(4, 22); this.errorsTabPage.Name = "errorsTabPage"; this.errorsTabPage.Padding = new System.Windows.Forms.Padding(3); this.errorsTabPage.Size = new System.Drawing.Size(468, 197); this.errorsTabPage.TabIndex = 1; this.errorsTabPage.Text = "Errors (0)"; this.errorsTabPage.UseVisualStyleBackColor = true; // // errorListView // this.errorListView.Columns.AddRange(new System.Windows.Forms.ColumnHeader[] { this.numberHeader, this.descriptionHeader, this.lineHeader, this.columnHeader}); this.errorListView.Location = new System.Drawing.Point(0, 0); this.errorListView.Name = "errorListView"; this.errorListView.Size = new System.Drawing.Size(468, 197); this.errorListView.TabIndex = 0; this.errorListView.UseCompatibleStateImageBehavior = false; this.errorListView.View = System.Windows.Forms.View.Details; // // numberHeader // this.numberHeader.Text = "Number"; this.numberHeader.Width = 78; // // descriptionHeader // this.descriptionHeader.Text = "Description"; this.descriptionHeader.Width = 255; // // lineHeader // this.lineHeader.Text = "Line"; this.lineHeader.Width = 63; // // columnHeader // this.columnHeader.Text = "Column"; this.columnHeader.Width = 68; // // ScriptExecuteOperationPanel // this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F); this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font; this.BackColor = System.Drawing.SystemColors.Window; this.Controls.Add(this.tabControl1); this.Name = "ScriptExecuteOperationPanel"; this.Size = new System.Drawing.Size(488, 225); ((System.ComponentModel.ISupportInitialize)(this.codeTextBox)).EndInit(); this.tabControl1.ResumeLayout(false); this.sourceCodeTabPage.ResumeLayout(false); this.errorsTabPage.ResumeLayout(false); this.ResumeLayout(false); } #endregion private FastColoredTextBoxNS.FastColoredTextBox codeTextBox; private System.Windows.Forms.TabControl tabControl1; private System.Windows.Forms.TabPage sourceCodeTabPage; private System.Windows.Forms.TabPage errorsTabPage; private System.Windows.Forms.ListView errorListView; private System.Windows.Forms.ColumnHeader descriptionHeader; private System.Windows.Forms.ColumnHeader lineHeader; private System.Windows.Forms.ColumnHeader columnHeader; private System.Windows.Forms.ColumnHeader numberHeader; } }
ProgTrade/nUpdate
nUpdate.Administration/Core/Operations/Panels/ScriptExecuteOperationPanel.Designer.cs
C#
mit
8,690
import cPickle as pickle import numpy as np import os import sys sys.path.append('../') import gp from uitools import UITools class Manager(object): def __init__(self, output_dir): ''' ''' self._data_path = '/home/d/dojo_xp/data/' self._output_path = os.path.join(self._data_path, 'ui_out', output_dir) self._merge_errors = None self._corrections = [] self._correction_times = [] self._correction_vis = [] self._mode = 'GP' def start( self, mode, cnn_path='../nets/IPMLB_FULL.p', verbose=True ): ''' ''' self._cnn = UITools.load_cnn(cnn_path) self._mode = mode if self._mode == 'GP*': # now we use the matlab engine print 'Using Active Label Suggestion' import matlab.engine eng = matlab.engine.start_matlab() self._merge_errors = self.load_merge_errors() self._bigM = self.load_split_errors() # let's generate our active label features and store a lsit elif self._mode == 'GP': if verbose: print 'Using GP proper' self._merge_errors = self.load_merge_errors() self._bigM = self.load_split_errors() elif self._mode == 'FP': print 'Using FP' self._merge_errors = [] self._bigM = self.load_split_errors(filename='bigM_fp.p') elif self._mode == 'TEST': print 'Test mode using FP' self._merge_errors = [] self._bigM = self.load_split_errors(filename='bigM_fp_test.p') else: print 'WRONG MODE, should be GP, GP* or FP' sys.exit(2) # load data if self._mode == 'TEST': print 'We are using dummy data for testing' input_image, input_prob, input_gold, input_rhoana, dojo_bbox = gp.Legacy.read_dojo_test_data() self._mode = 'FP' else: input_image, input_prob, input_gold, input_rhoana, dojo_bbox = gp.Legacy.read_dojo_data() self._input_image = input_image self._input_prob = input_prob self._input_gold = input_gold self._input_rhoana = input_rhoana self._dojo_bbox = dojo_bbox if verbose: print 'VI at start:', UITools.VI(self._input_gold, self._input_rhoana)[1] print 'aRE at start:', UITools.adaptedRandError(self._input_rhoana, self._input_gold)[1] def gen_active_label_features(self): ''' ''' active_labels_file = os.path.join(self._data_path, 'split_active_labels.p') if os.path.exists(active_labels_file): with open(active_labels_file, 'rb') as f: feature_vector = pickle.load(f) print 'Feature vector loaded from pickle.' else: print 'Calculating active labels...' # we work on a copy of bigM, let's call it bigD like daddy bigD = self._bigM.copy() import theano import theano.tensor as T from lasagne.layers import get_output # go from highest prob to lowest in our bigD prediction = np.inf while prediction > -1: z, labels, prediction = UITools.find_next_split_error(bigD) # create patch l,n = labels patches = [] patches_l, patches_n = Patch.grab(image, prob, segmentation, l, n, sample_rate=10, oversampling=False) patches += patches_l patches += patches_n grouped_patches = Patch.group(patches) # let CNN without softmax analyze the patch to create features x = X_test[100].reshape(1,4,75,75) layer = net.layers_['hidden5'] xs = T.tensor4('xs').astype(theano.config.floatX) get_activity = theano.function([xs], get_output(layer, xs)) activity = get_activity(x) # create feature vector # store feature vector to pickle with open(active_labels_file, 'wb') as f: pickle.dump(feature_vector, f) print 'Feature vector stored.' # Now, we need to represent the distance between each of these items using the graph Laplacian matrix 'LGReg'. # We're going to build this now using a MATLAB function - 'BuildLGRegularizer.m' # First, we need to set two parameters, as this is an approximation of the true graph laplacian to allow us to # use this on very large datasets manifoldDim = 17; kNNSize = 20; # Second, we set the regularization strength of this graph Laplacian lambdaRP = 0.005; # Next, we call the function #LGReg = eng.BuildLGRegularizer( x, manifoldDim, kNNSize, nargout=1 ); # ...but, two problems: # 1) We need to transform our numpy array x into something MATLAB can handle xM = matlab.double( size=[nItems, nFeatures] ) for j in range(0, nFeatures-1): for i in range(0, nItems-1): xM[i][j] = x[i][j]; # 2) LGReg is a 'sparse' matrix type, and python doesn't support that. # Let's leave the output variable in the MATLAB workspace, and until we need to use it. eng.workspace['xM'] = xM; # We also need to pass our function variables eng.workspace['nItems'] = nItems; eng.workspace['nFeatures'] = nFeatures; eng.workspace['lambdaRP'] = lambdaRP; eng.workspace['manifoldDim'] = manifoldDim; eng.workspace['kNNSize'] = kNNSize; # OK, now let's call our function eng.eval( "LGReg = BuildLGRegularizer( xM, manifoldDim, kNNSize )", nargout=0 ) def load_merge_errors(self, filename='merges_new_cnn.p'): ''' ''' with open(os.path.join(self._data_path, filename), 'rb') as f: merge_errors = pickle.load(f) return sorted(merge_errors, key=lambda x: x[3], reverse=False) def load_split_errors(self, filename='bigM_new_cnn.p'): ''' ''' with open(os.path.join(self._data_path, filename), 'rb') as f: bigM = pickle.load(f) return bigM def get_next_merge_error(self): ''' ''' if len(self._merge_errors) == 0: return None return self._merge_errors[0] def get_next_split_error(self): ''' ''' if self._mode == 'GP' or self._mode == 'FP': z, labels, prediction = UITools.find_next_split_error(self._bigM) elif self._mode == 'GP*': # # here, let's check for the next active label suggestion # but only if we already corrected twice # pass self._split_error = (z, labels, prediction) return self._split_error def get_merge_error_image(self, merge_error, number): border = merge_error[3][number][1] z = merge_error[0] label = merge_error[1] prob = merge_error[2] input_image = self._input_image input_prob = self._input_prob input_rhoana = self._input_rhoana a,b,c,d,e,f,g,h,i,j,k = gp.Legacy.get_merge_error_image(input_image[z], input_rhoana[z], label, border, returnbb=True) border_before = b labels_before = h border_after = c labels_after = i slice_overview = g cropped_slice_overview = j bbox = k return border_before, border_after, labels_before, labels_after, slice_overview, cropped_slice_overview, bbox def get_split_error_image(self, split_error, number=1): z = split_error[0] labels = split_error[1] input_image = self._input_image input_prob = self._input_prob input_rhoana = self._input_rhoana a,b,c,d,e,f,g,h = gp.Legacy.get_split_error_image(input_image[z], input_rhoana[z], labels, returnbb=True) labels_before = b borders_before = c borders_after = d labels_after = e slice_overview = f cropped_slice_overview = g bbox = h return borders_before, borders_after, labels_before, labels_after, slice_overview, cropped_slice_overview, bbox def correct_merge(self, clicked_correction, do_oracle=False, do_GT=False): input_image = self._input_image input_prob = self._input_prob input_rhoana = self._input_rhoana # # # oracle_choice = '' delta_vi = -1 if do_oracle: # lets check what the oracle would do merge_error = self._merge_errors[0] number = 0 border = merge_error[3][number][1] z = merge_error[0] label = merge_error[1] a,b,c,d,e,f,g,h,i,j = gp.Legacy.get_merge_error_image(input_image[z], input_rhoana[z], label, border) oracle_rhoana = f # check VI delta old_vi = gp.Util.vi(self._input_gold[z], self._input_rhoana[z]) new_vi = gp.Util.vi(self._input_gold[z], oracle_rhoana) delta_vi = old_vi - new_vi if delta_vi > 0: oracle_choice = '1' else: oracle_choice = 'current' if not clicked_correction == 'current': clicked_correction = int(clicked_correction)-1 # # correct the merge # merge_error = self._merge_errors[0] number = clicked_correction border = merge_error[3][number][1] z = merge_error[0] label = merge_error[1] a,b,c,d,e,f,g,h,i,j = gp.Legacy.get_merge_error_image(input_image[z], input_rhoana[z], label, border) new_rhoana = f self._input_rhoana[z] = new_rhoana vi = UITools.VI(self._input_gold, input_rhoana) #print 'New global VI', vi[0] self._correction_vis.append(vi[2]) # # and remove the original label from our bigM matrix # self._bigM[z][label,:] = -3 self._bigM[z][:,label] = -3 # now add the two new labels label1 = new_rhoana.max() label2 = new_rhoana.max()-1 new_m = np.zeros((self._bigM[z].shape[0]+2, self._bigM[z].shape[1]+2), dtype=self._bigM[z].dtype) new_m[:,:] = -1 new_m[0:-2,0:-2] = self._bigM[z] #print 'adding', label1, 'to', z new_m = gp.Legacy.add_new_label_to_M(self._cnn, new_m, input_image[z], input_prob[z], new_rhoana, label1) new_m = gp.Legacy.add_new_label_to_M(self._cnn, new_m, input_image[z], input_prob[z], new_rhoana, label2) # re-propapage new_m to bigM self._bigM[z] = new_m # remove merge error del self._merge_errors[0] mode = 'merge' if len(self._merge_errors) == 0: mode = 'split' return mode, oracle_choice, delta_vi def correct_split(self, clicked_correction, do_oracle=False): input_image = self._input_image input_prob = self._input_prob input_rhoana = self._input_rhoana split_error = self._split_error z = split_error[0] labels = split_error[1] m = self._bigM[z] # # # oracle_choice = '' delta_vi = -1 if do_oracle: oracle_m, oracle_rhoana = UITools.correct_split(self._cnn, m, self._mode, input_image[z], input_prob[z], input_rhoana[z], labels[0], labels[1], oversampling=False) # check VI delta old_vi = gp.Util.vi(self._input_gold[z], self._input_rhoana[z]) new_vi = gp.Util.vi(self._input_gold[z], oracle_rhoana) delta_vi = old_vi - new_vi if delta_vi > 0: oracle_choice = '1' else: oracle_choice = 'current' if clicked_correction == 'current': # we skip this split # print 'FP or current' new_m = UITools.skip_split(m, labels[0], labels[1]) self._bigM[z] = new_m else: # we correct this split # print 'fixing slice',z,'labels', labels # vi = gp.Util.vi(self._input_gold[z], self._input_rhoana[z]) # print 'bef vi', vi new_m, new_rhoana = UITools.correct_split(self._cnn, m, self._mode, input_image[z], input_prob[z], input_rhoana[z], labels[0], labels[1], oversampling=False) self._bigM[z] = new_m self._input_rhoana[z] = new_rhoana # vi = gp.Util.vi(self._input_gold[z], self._input_rhoana[z]) # print 'New VI', vi[0] vi = UITools.VI(self._input_gold, self._input_rhoana) #print 'New global VI', vi[0] self._correction_vis.append(vi[2]) # self.finish() return 'split', oracle_choice, delta_vi def store(self): vi = UITools.VI(self._input_gold, self._input_rhoana) print 'New VI', vi[1] are = UITools.adaptedRandError(self._input_rhoana, self._input_gold) print 'New aRE', are[1] if not os.path.exists(self._output_path): os.makedirs(self._output_path) # store our changed rhoana with open(os.path.join(self._output_path, 'ui_results.p'), 'wb') as f: pickle.dump(self._input_rhoana, f) # store the times with open(os.path.join(self._output_path, 'times.p'), 'wb') as f: pickle.dump(self._correction_times, f) # store the corrections with open(os.path.join(self._output_path, 'corrections.p'), 'wb') as f: pickle.dump(self._corrections, f) with open(os.path.join(self._output_path, 'correction_vis.p'), 'wb') as f: pickle.dump(self._correction_vis, f) print 'All stored.'
VCG/gp
ui/manager.py
Python
mit
12,894
/* * This file is part of ViaVersion - https://github.com/ViaVersion/ViaVersion * Copyright (C) 2016-2021 ViaVersion and contributors * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package us.myles.ViaVersion.api.boss; @Deprecated public enum BossColor { PINK(0), BLUE(1), RED(2), GREEN(3), YELLOW(4), PURPLE(5), WHITE(6); private final int id; BossColor(int id) { this.id = id; } public int getId() { return id; } }
MylesIsCool/ViaVersion
api-legacy/src/main/java/us/myles/ViaVersion/api/boss/BossColor.java
Java
mit
1,520
require "active_support/core_ext/string/inflections" module GreatPretender class Pretender def initialize(mockup) @mockup = mockup end def to_module pretenders = load_pretenders Module.new do define_method(:method_missing) do |method_name, *args, &block| pretender = pretenders.find { |p| p.respond_to?(method_name) } if pretender if defined? Rails deprecation_warning = I18n.t('great_pretender.deprecated_pretender') deprecation_warning_args = [method_name, pretender.class.name.underscore.gsub(/_pretender$/, ''), method_name] Rails.logger.debug deprecation_warning % deprecation_warning_args end pretender.send(method_name, *args, &block) else super(method_name, *args, &block) end end end end private def load_pretender(class_name) class_name = class_name + 'Pretender' begin klass = class_name.constantize rescue NameError return nil end initialize = klass.instance_method(:initialize) if initialize.arity == 1 klass.new(@mockup) else klass.new end end def load_pretenders pretenders = [] @mockup.slug.split("/").each do |pretender_name| # Given a mockup named something like 'social_contents', # support pretenders named 'SocialContentsPretender' AND 'SocialContentPretender' singular_class = pretender_name.classify plural_class = singular_class.pluralize [singular_class, plural_class].each do |class_name| if instance = load_pretender(class_name) pretenders.push(instance) end end end pretenders.reverse end end end
BackForty/great_pretender
lib/great_pretender/pretender.rb
Ruby
mit
1,831
{{-- Master Layout --}} @extends('cortex/foundation::frontarea.layouts.default') {{-- Page Title --}} @section('title') {{ extract_title(Breadcrumbs::render()) }} @endsection {{-- Scripts --}} @push('inline-scripts') {!! JsValidator::formRequest(Cortex\Auth\Http\Requests\Frontarea\TenantRegistrationProcessRequest::class)->selector("#frontarea-tenant-registration-form")->ignore('.skip-validation') !!} <script> window.countries = @json($countries); window.selectedCountry = '{{ old('tenant.country_code') }}'; </script> @endpush @section('body-attributes')class="auth-page"@endsection {{-- Main Content --}} @section('content') <div class="container"> <div class="row"> <div class="col-md-6 col-md-offset-3"> <section class="auth-form"> {{ Form::open(['url' => route('frontarea.register.tenant.process'), 'id' => 'frontarea-tenant-registration-form', 'role' => 'auth']) }} <div class="centered"><strong>{{ trans('cortex/auth::common.account_register') }}</strong></div> <div id="accordion" class="wizard"> <div class="panel wizard-step"> <div> <h4 class="wizard-step-title"> <a role="button" data-toggle="collapse" data-parent="#accordion" href="#collapseOne">{{ trans('cortex/auth::common.manager_account') }}</a> </h4> </div> <div id="collapseOne" class="collapse in"> <div class="wizard-step-body"> <div class="form-group has-feedback{{ $errors->has('manager.given_name') ? ' has-error' : '' }}"> {{ Form::text('manager[given_name]', old('manager.given_name'), ['class' => 'form-control input-lg', 'placeholder' => trans('cortex/auth::common.given_name'), 'required' => 'required', 'autofocus' => 'autofocus']) }} @if ($errors->has('manager.given_name')) <span class="help-block">{{ $errors->first('manager.given_name') }}</span> @endif </div> <div class="form-group has-feedback{{ $errors->has('manager.family_name') ? ' has-error' : '' }}"> {{ Form::text('manager[family_name]', old('manager.family_name'), ['class' => 'form-control input-lg', 'placeholder' => trans('cortex/auth::common.family_name')]) }} @if ($errors->has('manager.family_name')) <span class="help-block">{{ $errors->first('manager.family_name') }}</span> @endif </div> <div class="form-group has-feedback{{ $errors->has('manager.username') ? ' has-error' : '' }}"> {{ Form::text('manager[username]', old('manager.username'), ['class' => 'form-control input-lg', 'placeholder' => trans('cortex/auth::common.username'), 'required' => 'required']) }} @if ($errors->has('manager.username')) <span class="help-block">{{ $errors->first('manager.username') }}</span> @endif </div> <div class="form-group has-feedback{{ $errors->has('manager.email') ? ' has-error' : '' }}"> {{ Form::email('manager[email]', old('manager.email'), ['class' => 'form-control input-lg', 'placeholder' => trans('cortex/auth::common.email'), 'required' => 'required']) }} @if ($errors->has('manager.email')) <span class="help-block">{{ $errors->first('manager.email') }}</span> @endif </div> <div class="form-group has-feedback{{ $errors->has('manager.password') ? ' has-error' : '' }}"> {{ Form::password('manager[password]', ['class' => 'form-control input-lg', 'placeholder' => trans('cortex/auth::common.password'), 'required' => 'required']) }} @if ($errors->has('manager.password')) <span class="help-block">{{ $errors->first('manager.password') }}</span> @endif </div> <div class="form-group has-feedback{{ $errors->has('manager.password_confirmation') ? ' has-error' : '' }}"> {{ Form::password('manager[password_confirmation]', ['class' => 'form-control input-lg', 'placeholder' => trans('cortex/auth::common.password_confirmation'), 'required' => 'required']) }} @if ($errors->has('manager.password_confirmation')) <span class="help-block">{{ $errors->first('manager.password_confirmation') }}</span> @endif </div> </div> </div> </div> <div class="panel wizard-step"> <div role="tab" id="headingTwo"> <h4 class="wizard-step-title"> <a class="collapsed" role="button" data-toggle="collapse" data-parent="#accordion" href="#collapseTwo">{{ trans('cortex/auth::common.tenant_details') }}</a> </h4> </div> <div id="collapseTwo" class="panel-collapse collapse"> <div class="wizard-step-body"> <div class="form-group has-feedback{{ $errors->has('tenant.title') ? ' has-error' : '' }}"> {{ Form::text('tenant[title]', old('tenant.title'), ['class' => 'form-control input-lg', 'placeholder' => trans('cortex/auth::common.title'), 'data-slugify' => '[name="tenant\[name\]"]', 'required' => 'required']) }} @if ($errors->has('tenant.title')) <span class="help-block">{{ $errors->first('tenant.title') }}</span> @endif </div> <div class="form-group has-feedback{{ $errors->has('tenant.slug') ? ' has-error' : '' }}"> {{ Form::text('tenant[slug]', old('tenant.slug'), ['class' => 'form-control input-lg', 'placeholder' => trans('cortex/auth::common.slug'), 'required' => 'required']) }} @if ($errors->has('tenant.slug')) <span class="help-block">{{ $errors->first('tenant.slug') }}</span> @endif </div> <div class="form-group has-feedback{{ $errors->has('tenant.email') ? ' has-error' : '' }}"> {{ Form::text('tenant[email]', old('tenant.email'), ['class' => 'form-control input-lg', 'placeholder' => trans('cortex/auth::common.email'), 'required' => 'required']) }} @if ($errors->has('tenant.email')) <span class="help-block">{{ $errors->first('tenant.email') }}</span> @endif </div> <div class="form-group has-feedback{{ $errors->has('tenant.country_code') ? ' has-error' : '' }}"> {{ Form::hidden('tenant[country_code]', '', ['class' => 'skip-validation']) }} {{ Form::select('tenant[country_code]', [], null, ['class' => 'form-control select2 input-lg', 'placeholder' => trans('cortex/auth::common.select_country'), 'required' => 'required', 'data-allow-clear' => 'true', 'data-width' => '100%']) }} @if ($errors->has('tenant.country_code')) <span class="help-block">{{ $errors->first('tenant.country_code') }}</span> @endif </div> <div class="form-group{{ $errors->has('tenant.language_code') ? ' has-error' : '' }}"> {{ Form::hidden('tenant[language_code]', '') }} {{ Form::select('tenant[language_code]', $languages, null, ['class' => 'form-control select2', 'placeholder' => trans('cortex/auth::common.select_language'), 'data-allow-clear' => 'true', 'data-width' => '100%']) }} @if ($errors->has('tenant.language_code')) <span class="help-block">{{ $errors->first('tenant.language_code') }}</span> @endif </div> </div> </div> </div> </div> {{ Form::button('<i class="fa fa-user-plus"></i> '.trans('cortex/auth::common.register'), ['class' => 'btn btn-lg btn-primary btn-block', 'type' => 'submit']) }} <div> {{ Html::link(route('frontarea.login'), trans('cortex/auth::common.account_login')) }} {{ trans('cortex/foundation::common.or') }} {{ Html::link(route('frontarea.passwordreset.request'), trans('cortex/auth::common.passwordreset')) }} </div> {{ Form::close() }} </section> </div> </div> </div> @endsection
rinvex/cortex-fort
resources/views/frontarea/pages/tenant-registration.blade.php
PHP
mit
10,976
/** * The AnalysisShapeUploadView module. * * @return AnalysisShapeUploadView class (extends Backbone.View). */ define( [ 'backbone', 'mps', 'turf', 'map/services/ShapefileService', 'helpers/geojsonUtilsHelper' ], function(Backbone, mps, turf, ShapefileService, geojsonUtilsHelper) { 'use strict'; var AnalysisShapeUploadView = Backbone.View.extend({ defaults: { fileSizeLimit: 1000000 }, initialize: function() { this.fileSizeLimit = this.defaults.fileSizeLimit; this.$dropable = document.getElementById('drop-shape-analysis'); this.$fileSelector = document.getElementById('analysis-file-upload'); this._initDroppable(); }, _initDroppable: function() { if (this.$dropable && this.$fileSelector) { this.$fileSelector.addEventListener( 'change', function() { var file = this.$fileSelector.files[0]; if (file) { this._handleUpload(file); } }.bind(this) ); this.$dropable.addEventListener( 'click', function(event) { if (event.target.classList.contains('source')) { return true; } $(this.$fileSelector).trigger('click'); }.bind(this) ); this.$dropable.ondragover = function() { this.$dropable.classList.toggle('moving'); return false; }.bind(this); this.$dropable.ondragend = function() { this.$dropable.classList.toggle('moving'); return false; }.bind(this); this.$dropable.ondrop = function(e) { e.preventDefault(); var file = e.dataTransfer.files[0]; this._handleUpload(file); return false; }.bind(this); } }, _handleUpload: function(file) { var sizeMessage = 'The selected file is quite large and uploading ' + 'it might result in browser instability. Do you want to continue?'; if (file.size > this.fileSizeLimit && !window.confirm(sizeMessage)) { this.$dropable.classList.remove('moving'); return; } mps.publish('Spinner/start', []); var shapeService = new ShapefileService({ shapefile: file }); shapeService.toGeoJSON().then( function(data) { var combinedFeatures = data.features.reduce(turf.union); var bounds = geojsonUtilsHelper.getBoundsFromGeojson( combinedFeatures ); mps.publish('Analysis/upload', [combinedFeatures.geometry]); this.trigger('analysis:shapeUpload:draw', combinedFeatures); this.trigger('analysis:shapeUpload:fitBounds', bounds); }.bind(this) ); this.$dropable.classList.remove('moving'); } }); return AnalysisShapeUploadView; } );
Vizzuality/gfw-climate
app/assets/javascripts/map/views/tabs/AnalysisShapeUploadView.js
JavaScript
mit
3,022
class Api::V1::CharactersController < ApplicationController def show character = Character.find(params[:id]) response = Api::V1::CharacterSerializer.new(character) render(json: response) end def index if params[:name] character = Character.find_by(name: params[:name]) if character.nil? response = "Character does not exist." else response = Api::V1::CharacterSerializer.new(character) render(json: response) end else render plain: "Not authorized", status: 401 # characters = Character.all # # render( # json: ActiveModel::ArraySerializer.new( # characters, # each_serializer: Api::V1::CharacterSerializer, # root: 'characters', # ) # ) end end end
mbroadwater/shadowrun
app/controllers/api/v1/characters_controller.rb
Ruby
mit
806
package eu.thog92.isbrh.example; import eu.thog92.isbrh.ISBRH; import eu.thog92.isbrh.render.ITextureHandler; import eu.thog92.isbrh.render.TextureLoader; import net.minecraft.block.Block; import net.minecraft.block.material.Material; import net.minecraft.block.state.IBlockState; import net.minecraft.client.renderer.texture.TextureAtlasSprite; import net.minecraft.creativetab.CreativeTabs; import net.minecraft.util.BlockPos; import net.minecraft.util.EnumFacing; import net.minecraft.util.EnumWorldBlockLayer; import net.minecraft.util.ResourceLocation; import net.minecraft.world.IBlockAccess; import net.minecraftforge.fml.relauncher.Side; import net.minecraftforge.fml.relauncher.SideOnly; public class BlockExample extends Block implements ITextureHandler { @SideOnly(Side.CLIENT) private TextureLoader textureLoader; @SideOnly(Side.CLIENT) private final ResourceLocation textureLocation = new ResourceLocation( "isbrhcore:blocks/test"); public BlockExample() { super(Material.iron); this.setCreativeTab(CreativeTabs.tabBlock); } @Override public boolean isOpaqueCube() { return false; } @SideOnly(Side.CLIENT) public int getRenderType() { return ISBRH.testId; } @Override public boolean isNormalCube() { return false; } @SideOnly(Side.CLIENT) @Override public boolean shouldSideBeRendered(IBlockAccess world, BlockPos pos, EnumFacing face) { return true; } @SideOnly(Side.CLIENT) public EnumWorldBlockLayer getBlockLayer() { return EnumWorldBlockLayer.SOLID; } public boolean isFullCube() { return false; } @Override public TextureAtlasSprite getSidedTexture(IBlockState state, EnumFacing facing) { return textureLoader.getTextureMap().getAtlasSprite(textureLocation.toString()); } @Override public void loadTextures(TextureLoader loader) { this.textureLoader = loader; loader.registerTexture(textureLocation); } }
Thog/ISBRH
src/main/java/eu/thog92/isbrh/example/BlockExample.java
Java
mit
2,078
new Vue({ el: document.querySelector('.page-app-detail'), data: { selectedApp: {} }, created() { this._loadApp(); }, methods: { refreshSecret() { axios.post(`${AppConf.apiHost}/app/${serverData.appId}/refresh_secret`) .then(res => { this.selectedApp.AppSecret = res.data; }); }, _loadApp() { axios.get(`${AppConf.apiHost}/app/${serverData.appId}`) .then(res => { this.selectedApp = res.data; }); } } });
hstarorg/simple-sso
src/assets/js/app-detail.js
JavaScript
mit
506
// This is an open source non-commercial project. Dear PVS-Studio, please check it. // PVS-Studio Static Code Analyzer for C, C++ and C#: http://www.viva64.com /* SearchContext.cs -- * Ars Magna project, http://arsmagna.ru * ------------------------------------------------------- * Status: poor */ #region Using directives using AM; using JetBrains.Annotations; using ManagedIrbis.Client; #endregion namespace ManagedIrbis.Search { /// <summary> /// /// </summary> [PublicAPI] public sealed class SearchContext { #region Properties /// <summary> /// Search manager. /// </summary> [NotNull] public SearchManager Manager { get; private set; } /// <summary> /// Providr. /// </summary> [NotNull] public IrbisProvider Provider { get; private set; } #endregion #region Construction /// <summary> /// Constructor. /// </summary> public SearchContext ( [NotNull] SearchManager manager, [NotNull] IrbisProvider provider ) { Sure.NotNull(manager, nameof(manager)); Sure.NotNull(provider, nameof(provider)); Manager = manager; Provider = provider; } #endregion } }
amironov73/ManagedIrbis2
OldSource/Libs/ManagedIrbis/Source/Search/Infrastructure/SearchContext.cs
C#
mit
1,370
import DetailsList from '@components/details-list.vue' describe('DetailsList Component', () => { let wrapper let options beforeEach(() => { options = { propsData: { id: '01-01', }, } wrapper = createWrapper(DetailsList, options) }) it('is a Vue instance', () => { expect(wrapper.exists()).toBeTruthy() }) it('renders correctly', () => { expect(wrapper).toMatchSnapshot() }) it('does not render correctly', () => { const wrapper = createWrapper( DetailsList, { ...options, }, { getters: { getArtworkById: () => () => { return null }, }, } ) expect(wrapper).toMatchSnapshot() }) })
patrickcate/dutch-art-daily
__tests__/unit/components/details-list.spec.js
JavaScript
mit
745
using System.Collections.Generic; using System.Linq; using PivotalTrackerDotNet.Domain; using RestSharp; using Parallel = System.Threading.Tasks.Parallel; namespace PivotalTrackerDotNet { public class StoryService : AAuthenticatedService, IStoryService { private const string SpecifiedIterationEndpoint = "projects/{0}/iterations?scope={1}"; private const string SingleStoryEndpoint = "projects/{0}/stories/{1}"; private const string StoriesEndpoint = "projects/{0}/stories"; private const string TaskEndpoint = "projects/{0}/stories/{1}/tasks"; private const string StoryActivityEndpoint = "projects/{0}/stories/{1}/activity"; private const string StoryCommentsEndpoint = "projects/{0}/stories/{1}/comments"; private const string SaveNewCommentEndpoint = "projects/{0}/stories/{1}/comments?text={2}"; private const string SingleTaskEndpoint = "projects/{0}/stories/{1}/tasks/{2}"; private const string StoryStateEndpoint = "projects/{0}/stories/{1}?story[current_state]={2}"; private const string StoryFilterEndpoint = StoriesEndpoint + "?filter={1}"; private const string IterationEndPoint = "projects/{0}/iterations"; private const string IterationRecentEndPoint = IterationEndPoint + "/done?offset=-{1}"; public StoryService(string token) : base(token) { } public StoryService(AuthenticationToken token) : base(token) { } public List<Story> GetAllStories(int projectId) { var request = BuildGetRequest(); request.Resource = string.Format(StoriesEndpoint, projectId); return this.GetStories(request); } public List<Story> GetAllStories(int projectId, StoryIncludeFields fields) { var request = BuildGetRequest(); request.Resource = string.Format(StoriesEndpoint, projectId); string fieldsQuery = ":default"; var fieldsToInclude = this.GetFieldsNames(fields); if (fieldsToInclude.Any()) fieldsQuery += "," + string.Join(",", fieldsToInclude); request.AddQueryParameter("fields", fieldsQuery); return this.GetStories(request); } public PagedResult<Story> GetAllStories(int projectId, int limit, int offset) { var request = this.BuildGetRequest(string.Format(StoriesEndpoint, projectId)) .SetPagination(offset, limit); return this.RestClient.ExecuteRequestWithChecks<PagedResult<Story>>(request); } public List<Story> GetAllStoriesMatchingFilter(int projectId, string filter) { var request = BuildGetRequest(); request.Resource = string.Format(StoryFilterEndpoint, projectId, filter); return this.GetStories(request); } public List<Story> GetAllStoriesMatchingFilter(int projectId, string filter, StoryIncludeFields fields) { var request = BuildGetRequest(); request.Resource = string.Format(StoryFilterEndpoint, projectId, filter); string fieldsQuery = ":default"; var fieldsToInclude = this.GetFieldsNames(fields); if (fieldsToInclude.Any()) fieldsQuery += "," + string.Join(",", fieldsToInclude); request.AddQueryParameter("fields", fieldsQuery); return this.GetStories(request); } public PagedResult<Story> GetAllStoriesMatchingFilter(int projectId, string filter, int limit, int offset) { var request = this.BuildGetRequest(string.Format(StoryFilterEndpoint, projectId, filter)) .SetPagination(offset, limit); return this.RestClient.ExecuteRequestWithChecks<PagedResult<Story>>(request); } public PagedResult<Story> GetAllStoriesMatchingFilter(int projectId, FilteringCriteria filter, int limit, int offset) { return this.GetAllStoriesMatchingFilter(projectId, filter.ToString(), limit, offset); } public List<Story> GetAllStoriesMatchingFilter(int projectId, FilteringCriteria filter) { return this.GetAllStoriesMatchingFilter(projectId, filter.ToString()); } public List<Story> GetAllStoriesMatchingFilter(int projectId, FilteringCriteria filter, StoryIncludeFields fields) { return this.GetAllStoriesMatchingFilter(projectId, filter.ToString(), fields); } public Story FinishStory(int projectId, int storyId) { var originalStory = this.GetStory(projectId, storyId); string finished = originalStory.StoryType == StoryType.Chore ? "accepted" : "finished"; var request = BuildPutRequest(); request.Resource = string.Format(StoryStateEndpoint, projectId, storyId, finished); var response = RestClient.Execute<Story>(request); var story = response.Data; return story; } public Story StartStory(int projectId, int storyId) { var request = BuildPutRequest(); request.Resource = string.Format(StoryStateEndpoint, projectId, storyId, "started"); var response = RestClient.Execute<Story>(request); var story = response.Data; return story; } public Story GetStory(int projectId, int storyId) { var request = BuildGetRequest(string.Format(SingleStoryEndpoint, projectId, storyId)); return RestClient.ExecuteRequestWithChecks<Story>(request); } public Story GetStory(int projectId, int storyId, StoryIncludeFields fields) { var request = BuildGetRequest(string.Format(SingleStoryEndpoint, projectId, storyId)); string fieldsQuery = ":default"; var fieldsToInclude = this.GetFieldsNames(fields); if (fieldsToInclude.Any()) fieldsQuery += "," + string.Join(",", fieldsToInclude); request.AddQueryParameter("fields", fieldsQuery); return RestClient.ExecuteRequestWithChecks<Story>(request); } public List<Iteration> GetAllIterations(int projectId) { var request = BuildGetRequest(); request.Resource = string.Format(IterationEndPoint, projectId); return this.GetIterations(request); } public List<Iteration> GetAllIterations(int projectId, StoryIncludeFields fields) { var request = BuildGetRequest(); request.Resource = string.Format(IterationEndPoint, projectId); string fieldsQuery = ":default"; var fieldsToInclude = this.GetFieldsNames(fields); if (fieldsToInclude.Any()) fieldsQuery += "," + string.Join(",", fieldsToInclude); request.AddQueryParameter("fields", ":default,stories(" + fieldsQuery + ")"); return this.GetIterations(request); } public PagedResult<Iteration> GetAllIterations(int projectId, int limit, int offset) { var request = this.BuildGetRequest(string.Format(IterationEndPoint, projectId)) .SetPagination(offset, limit); return this.RestClient.ExecuteRequestWithChecks<PagedResult<Iteration>>(request); } public List<Iteration> GetLastIterations(long projectId, int number) { var request = BuildGetRequest(); request.Resource = string.Format(IterationRecentEndPoint, projectId, number); return this.GetIterations(request); } public List<Iteration> GetCurrentIterations(int projectId) { return this.GetIterationsByType(projectId, "current"); } public List<Iteration> GetDoneIterations(int projectId) { return this.GetIterationsByType(projectId, "done"); } public List<Iteration> GetBacklogIterations(int projectId) { return this.GetIterationsByType(projectId, "backlog"); } public List<Story> GetCurrentStories(int projectId) { return this.GetStoriesByIterationType(projectId, "current"); } public List<Story> GetDoneStories(int projectId) { return this.GetStoriesByIterationType(projectId, "done"); } public List<Story> GetIceboxStories(int projectId) { return this.GetAllStoriesMatchingFilter(projectId, FilteringCriteria.FilterBy.State(StoryStatus.Unscheduled)); } public List<Story> GetBacklogStories(int projectId) { return this.GetStoriesByIterationType(projectId, "backlog"); } public void RemoveStory(int projectId, int storyId) { var request = BuildDeleteRequest(); request.Resource = string.Format(SingleStoryEndpoint, projectId, storyId); RestClient.ExecuteRequestWithChecks(request); } public Story AddNewStory(int projectId, Story toBeSaved) { var request = BuildPostRequest(); request.Resource = string.Format(StoriesEndpoint, projectId); request.AddParameter("application/json", toBeSaved.ToJson(), ParameterType.RequestBody); return RestClient.ExecuteRequestWithChecks<Story>(request); } public Story UpdateStory(int projectId, Story story) { var request = BuildPutRequest(); request.Resource = string.Format(SingleStoryEndpoint, projectId, story.Id); request.AddParameter("application/json", story.ToJson(), ParameterType.RequestBody); return RestClient.ExecuteRequestWithChecks<Story>(request); } public Task SaveTask(Task task) { var request = BuildPutRequest(); request.Resource = string.Format(SingleTaskEndpoint, task.ProjectId, task.StoryId, task.Id); request.AddParameter("application/json", task.ToJson(), ParameterType.RequestBody); var savedTask = RestClient.ExecuteRequestWithChecks<Task>(request); savedTask.ProjectId = task.ProjectId; return savedTask; } public void ReorderTasks(int projectId, int storyId, List<Task> tasks) { Parallel.ForEach(tasks, t => { var request = BuildPutRequest(); request.Resource = string.Format(TaskEndpoint + "/{2}?task[position]={3}", t.ProjectId, t.StoryId, t.Id, t.Position); RestClient.ExecuteRequestWithChecks(request); }); } public Task AddNewTask(Task task) { var request = BuildPostRequest(); request.Resource = string.Format(TaskEndpoint, task.ProjectId, task.StoryId); request.AddParameter("application/json", task.ToJson(), ParameterType.RequestBody); var savedTask = RestClient.ExecuteRequestWithChecks<Task>(request); savedTask.ProjectId = task.ProjectId; return savedTask; } public bool RemoveTask(int projectId, int storyId, int taskId) { var request = BuildDeleteRequest(); request.Resource = string.Format(SingleTaskEndpoint, projectId, storyId, taskId); var response = RestClient.ExecuteRequestWithChecks<Task>(request); return response == null; } public Task GetTask(int projectId, int storyId, int taskId) { var request = BuildGetRequest(); request.Resource = string.Format(SingleTaskEndpoint, projectId, storyId, taskId); var output = RestClient.ExecuteRequestWithChecks<Task>(request); output.StoryId = storyId; output.ProjectId = projectId; return output; } public List<Task> GetTasksForStory(int projectId, int storyId) { var request = this.BuildGetRequest(); request.Resource = string.Format(TaskEndpoint, projectId, storyId); return RestClient.ExecuteRequestWithChecks<List<Task>>(request); } public List<Task> GetTasksForStory(int projectId, Story story) { return this.GetTasksForStory(projectId, story.Id); } public void AddComment(int projectId, int storyId, string comment) { var request = BuildPostRequest(); request.Resource = string.Format(SaveNewCommentEndpoint, projectId, storyId, comment); RestClient.ExecuteRequestWithChecks(request); } public List<Activity> GetStoryActivity(int projectId, int storyId) { var request = this.BuildGetRequest(string.Format(StoryActivityEndpoint, projectId, storyId)); return RestClient.ExecuteRequestWithChecks<List<Activity>>(request); } public PagedResult<Activity> GetStoryActivity(int projectId, int storyId, int offset, int limit) { var request = this.BuildGetRequest(string.Format(StoryActivityEndpoint, projectId, storyId)) .SetPagination(offset, limit); return RestClient.ExecuteRequestWithChecks<PagedResult<Activity>>(request); } public List<Comment> GetStoryComments(int projectId, int storyId) { var request = this.BuildGetRequest(string.Format(StoryCommentsEndpoint, projectId, storyId)); return RestClient.ExecuteRequestWithChecks<List<Comment>>(request); } private List<Iteration> GetIterationsByType(int projectId, string iterationType) { var request = BuildGetRequest(); request.Resource = string.Format(SpecifiedIterationEndpoint, projectId, iterationType); return this.GetIterations(request); } private List<Story> GetStoriesByIterationType(int projectId, string iterationType) { var request = BuildGetRequest(); request.Resource = string.Format(SpecifiedIterationEndpoint, projectId, iterationType); var el = RestClient.ExecuteRequestWithChecks(request); var stories = new Stories(); stories.AddRange(el[0]["stories"].Select(storey => storey.ToObject<Story>())); return stories; } private List<Iteration> GetIterations(RestRequest request) { return RestClient.ExecuteRequestWithChecks<List<Iteration>>(request); } private List<Story> GetStories(RestRequest request) { return RestClient.ExecuteRequestWithChecks<List<Story>>(request); //var el = RestClient.ExecuteRequestWithChecks<List<Story>>(request); //var stories = new Stories(); //stories.AddRange(el.Select(storey => storey.ToObject<Story>())); //return stories; } private IEnumerable<string> GetFieldsNames(StoryIncludeFields fields) { if (fields.HasFlag(StoryIncludeFields.AfterId)) yield return "after_id"; if (fields.HasFlag(StoryIncludeFields.BeforeId)) yield return "before_id"; if (fields.HasFlag(StoryIncludeFields.Comments)) { yield return "comments(:default,person,file_attachments,google_attachments)"; } else if (fields.HasFlag(StoryIncludeFields.CommentIds)) yield return "comment_ids"; if (fields.HasFlag(StoryIncludeFields.Followers)) yield return "followers"; else if (fields.HasFlag(StoryIncludeFields.FollowerIds)) yield return "follower_ids"; if (fields.HasFlag(StoryIncludeFields.Tasks)) yield return "tasks"; else if (fields.HasFlag(StoryIncludeFields.TaskIds)) yield return "task_ids"; if (fields.HasFlag(StoryIncludeFields.Owners)) yield return "owners"; else if (fields.HasFlag(StoryIncludeFields.OwnerIds)) yield return "owner_ids"; if (fields.HasFlag(StoryIncludeFields.RequestedBy)) yield return "requested_by"; } } }
Charcoals/PivotalTracker.NET
PivotalTrackerDotNet/StoryService.cs
C#
mit
17,068
using System; using System.Globalization; using System.Reflection; using System.Windows.Media; namespace DataServer { public static class ColorReflector { public static void SetFromHex(this Color c, string hex) { var c1 = ToColorFromHex(hex); c.A = c1.A; c.R = c1.R; c.G = c1.G; c.B = c1.B; } public static Color GetThisColor(string colorString) { var colorType = (typeof (Colors)); if (colorType.GetProperty(colorString) != null) { var o = colorType.InvokeMember(colorString, BindingFlags.GetProperty, null, null, null); if (o != null) { return (Color) o; } } return Colors.Black; } public static Color? ToColorFromHexWithUndefined(string hex) { return string.IsNullOrEmpty(hex) ? (Color? )null : ToColorFromHex(hex); } public static Color ToColorFromHex(string hex) { if (string.IsNullOrEmpty(hex)) { return Colors.Transparent; } // remove any "#" characters while (hex.StartsWith("#")) { hex = hex.Substring(1); } var num = 0; // get the number out of the string if (!Int32.TryParse(hex, NumberStyles.HexNumber, null, out num)) { return GetThisColor(hex); } var pieces = new int[4]; if (hex.Length > 7) { pieces[0] = ((num >> 24) & 0x000000ff); pieces[1] = ((num >> 16) & 0x000000ff); pieces[2] = ((num >> 8) & 0x000000ff); pieces[3] = (num & 0x000000ff); } else if (hex.Length > 5) { pieces[0] = 255; pieces[1] = ((num >> 16) & 0x000000ff); pieces[2] = ((num >> 8) & 0x000000ff); pieces[3] = (num & 0x000000ff); } else if (hex.Length == 3) { pieces[0] = 255; pieces[1] = ((num >> 8) & 0x0000000f); pieces[1] += pieces[1]*16; pieces[2] = ((num >> 4) & 0x000000f); pieces[2] += pieces[2]*16; pieces[3] = (num & 0x000000f); pieces[3] += pieces[3]*16; } return Color.FromArgb((byte) pieces[0], (byte) pieces[1], (byte) pieces[2], (byte) pieces[3]); } } }
TNOCS/csTouch
framework/csCommonSense/Types/DataServer/PoI/ColorReflector.cs
C#
mit
2,540