text
stringlengths
2
1.04M
meta
dict
<?xml version="1.0" ?><!DOCTYPE TS><TS language="uk" version="2.0"> <defaultcodec>UTF-8</defaultcodec> <context> <name>AboutDialog</name> <message> <location filename="../forms/aboutdialog.ui" line="+14"/> <source>About CharityCoinHelps</source> <translation>Про CharityCoinHelps</translation> </message> <message> <location line="+39"/> <source>&lt;b&gt;CharityCoinHelps&lt;/b&gt; version</source> <translation>Версія &lt;b&gt;CharityCoinHelps&apos;a&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 ([email protected]) and UPnP software written by Thomas Bernard.</source> <translation> Це програмне забезпечення є експериментальним. Поширюється за ліцензією MIT/X11, додаткова інформація міститься у файлі COPYING, а також за адресою http://www.opensource.org/licenses/mit-license.php. Цей продукт включає в себе програмне забезпечення, розроблене в рамках проекту OpenSSL (http://www.openssl.org/), криптографічне програмне забезпечення, написане Еріком Янгом ([email protected]), та функції для роботи з UPnP, написані Томасом Бернардом.</translation> </message> <message> <location filename="../aboutdialog.cpp" line="+14"/> <source>Copyright</source> <translation>Авторське право</translation> </message> <message> <location line="+0"/> <source>The CharityCoinHelps developers</source> <translation type="unfinished"/> </message> </context> <context> <name>AddressBookPage</name> <message> <location filename="../forms/addressbookpage.ui" line="+14"/> <source>Address Book</source> <translation>Адресна книга</translation> </message> <message> <location line="+19"/> <source>Double-click to edit address or label</source> <translation>Двічі клікніть на адресу чи назву для їх зміни</translation> </message> <message> <location line="+27"/> <source>Create a new address</source> <translation>Створити нову адресу</translation> </message> <message> <location line="+14"/> <source>Copy the currently selected address to the system clipboard</source> <translation>Копіювати виділену адресу в буфер обміну</translation> </message> <message> <location line="-11"/> <source>&amp;New Address</source> <translation>&amp;Створити адресу</translation> </message> <message> <location filename="../addressbookpage.cpp" line="+63"/> <source>These are your CharityCoinHelps 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>Це ваші адреси для отримання платежів. Ви можете давати різні адреси різним людям, таким чином маючи можливість відслідкувати хто конкретно і скільки вам заплатив.</translation> </message> <message> <location filename="../forms/addressbookpage.ui" line="+14"/> <source>&amp;Copy Address</source> <translation>&amp;Скопіювати адресу</translation> </message> <message> <location line="+11"/> <source>Show &amp;QR Code</source> <translation>Показати QR-&amp;Код</translation> </message> <message> <location line="+11"/> <source>Sign a message to prove you own a CharityCoinHelps address</source> <translation>Підпишіть повідомлення щоб довести, що ви є власником цієї адреси</translation> </message> <message> <location line="+3"/> <source>Sign &amp;Message</source> <translation>&amp;Підписати повідомлення</translation> </message> <message> <location line="+25"/> <source>Delete the currently selected address from the list</source> <translation>Вилучити вибрані адреси з переліку</translation> </message> <message> <location line="+27"/> <source>Export the data in the current tab to a file</source> <translation>Експортувати дані з поточної вкладки в файл</translation> </message> <message> <location line="+3"/> <source>&amp;Export</source> <translation type="unfinished"/> </message> <message> <location line="-44"/> <source>Verify a message to ensure it was signed with a specified CharityCoinHelps address</source> <translation>Перевірте повідомлення для впевненості, що воно підписано вказаною CharityCoinHelps-адресою</translation> </message> <message> <location line="+3"/> <source>&amp;Verify Message</source> <translation>Перевірити повідомлення</translation> </message> <message> <location line="+14"/> <source>&amp;Delete</source> <translation>&amp;Видалити</translation> </message> <message> <location filename="../addressbookpage.cpp" line="-5"/> <source>These are your CharityCoinHelps 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>Скопіювати &amp;мітку</translation> </message> <message> <location line="+1"/> <source>&amp;Edit</source> <translation>&amp;Редагувати</translation> </message> <message> <location line="+1"/> <source>Send &amp;Coins</source> <translation type="unfinished"/> </message> <message> <location line="+260"/> <source>Export Address Book Data</source> <translation>Експортувати адресну книгу</translation> </message> <message> <location line="+1"/> <source>Comma separated file (*.csv)</source> <translation>Файли відділені комами (*.csv)</translation> </message> <message> <location line="+13"/> <source>Error exporting</source> <translation>Помилка при експортуванні</translation> </message> <message> <location line="+0"/> <source>Could not write to file %1.</source> <translation>Неможливо записати у файл %1.</translation> </message> </context> <context> <name>AddressTableModel</name> <message> <location filename="../addresstablemodel.cpp" line="+144"/> <source>Label</source> <translation>Назва</translation> </message> <message> <location line="+0"/> <source>Address</source> <translation>Адреса</translation> </message> <message> <location line="+36"/> <source>(no label)</source> <translation>(немає назви)</translation> </message> </context> <context> <name>AskPassphraseDialog</name> <message> <location filename="../forms/askpassphrasedialog.ui" line="+26"/> <source>Passphrase Dialog</source> <translation>Діалог введення паролю</translation> </message> <message> <location line="+21"/> <source>Enter passphrase</source> <translation>Введіть пароль</translation> </message> <message> <location line="+14"/> <source>New passphrase</source> <translation>Новий пароль</translation> </message> <message> <location line="+14"/> <source>Repeat new passphrase</source> <translation>Повторіть пароль</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>Введіть новий пароль для гаманця.&lt;br/&gt;Будь ласка, використовуйте паролі що містять &lt;b&gt;як мінімум 10 випадкових символів&lt;/b&gt;, або &lt;b&gt;як мінімум 8 слів&lt;/b&gt;.</translation> </message> <message> <location line="+1"/> <source>Encrypt wallet</source> <translation>Зашифрувати гаманець</translation> </message> <message> <location line="+3"/> <source>This operation needs your wallet passphrase to unlock the wallet.</source> <translation>Ця операція потребує пароль для розблокування гаманця.</translation> </message> <message> <location line="+5"/> <source>Unlock wallet</source> <translation>Розблокувати гаманець</translation> </message> <message> <location line="+3"/> <source>This operation needs your wallet passphrase to decrypt the wallet.</source> <translation>Ця операція потребує пароль для дешифрування гаманця.</translation> </message> <message> <location line="+5"/> <source>Decrypt wallet</source> <translation>Дешифрувати гаманець</translation> </message> <message> <location line="+3"/> <source>Change passphrase</source> <translation>Змінити пароль</translation> </message> <message> <location line="+1"/> <source>Enter the old and new passphrase to the wallet.</source> <translation>Ввести старий та новий паролі для гаманця.</translation> </message> <message> <location line="+46"/> <source>Confirm wallet encryption</source> <translation>Підтвердити шифрування гаманця</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 CHARITYCOINHELPS&lt;/b&gt;!</source> <translation>УВАГА: Якщо ви зашифруєте гаманець і забудете пароль, ви &lt;b&gt;ВТРАТИТЕ ВСІ СВОЇ БІТКОІНИ&lt;/b&gt;!</translation> </message> <message> <location line="+0"/> <source>Are you sure you wish to encrypt your wallet?</source> <translation>Ви дійсно хочете зашифрувати свій гаманець?</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 type="unfinished"/> </message> <message> <location line="+100"/> <location line="+24"/> <source>Warning: The Caps Lock key is on!</source> <translation>Увага: Ввімкнено Caps Lock!</translation> </message> <message> <location line="-130"/> <location line="+58"/> <source>Wallet encrypted</source> <translation>Гаманець зашифровано</translation> </message> <message> <location line="-56"/> <source>CharityCoinHelps will close now to finish the encryption process. Remember that encrypting your wallet cannot fully protect your charitycoinhelpss from being stolen by malware infecting your computer.</source> <translation>Біткоін-клієнт буде закрито для завершення процесу шифрування. Пам&apos;ятайте, що шифрування гаманця не може повністю захистити ваші біткоіни від крадіжки, у випадку якщо ваш комп&apos;ютер буде інфіковано шкідливими програмами.</translation> </message> <message> <location line="+13"/> <location line="+7"/> <location line="+42"/> <location line="+6"/> <source>Wallet encryption failed</source> <translation>Не вдалося зашифрувати гаманець</translation> </message> <message> <location line="-54"/> <source>Wallet encryption failed due to an internal error. Your wallet was not encrypted.</source> <translation>Виникла помилка під час шифрування гаманця. Ваш гаманець не було зашифровано.</translation> </message> <message> <location line="+7"/> <location line="+48"/> <source>The supplied passphrases do not match.</source> <translation>Введені паролі не співпадають.</translation> </message> <message> <location line="-37"/> <source>Wallet unlock failed</source> <translation>Не вдалося розблокувати гаманець</translation> </message> <message> <location line="+1"/> <location line="+11"/> <location line="+19"/> <source>The passphrase entered for the wallet decryption was incorrect.</source> <translation>Введений пароль є невірним.</translation> </message> <message> <location line="-20"/> <source>Wallet decryption failed</source> <translation>Не вдалося розшифрувати гаманець</translation> </message> <message> <location line="+14"/> <source>Wallet passphrase was successfully changed.</source> <translation>Пароль було успішно змінено.</translation> </message> </context> <context> <name>BitcoinGUI</name> <message> <location filename="../bitcoingui.cpp" line="+233"/> <source>Sign &amp;message...</source> <translation>&amp;Підписати повідомлення...</translation> </message> <message> <location line="+280"/> <source>Synchronizing with network...</source> <translation>Синхронізація з мережею...</translation> </message> <message> <location line="-349"/> <source>&amp;Overview</source> <translation>&amp;Огляд</translation> </message> <message> <location line="+1"/> <source>Show general overview of wallet</source> <translation>Показати загальний огляд гаманця</translation> </message> <message> <location line="+20"/> <source>&amp;Transactions</source> <translation>Транзакції</translation> </message> <message> <location line="+1"/> <source>Browse transaction history</source> <translation>Переглянути історію транзакцій</translation> </message> <message> <location line="+7"/> <source>Edit the list of stored addresses and labels</source> <translation>Редагувати список збережених адрес та міток</translation> </message> <message> <location line="-14"/> <source>Show the list of addresses for receiving payments</source> <translation>Показати список адрес для отримання платежів</translation> </message> <message> <location line="+31"/> <source>E&amp;xit</source> <translation>&amp;Вихід</translation> </message> <message> <location line="+1"/> <source>Quit application</source> <translation>Вийти</translation> </message> <message> <location line="+4"/> <source>Show information about CharityCoinHelps</source> <translation>Показати інформацію про CharityCoinHelps</translation> </message> <message> <location line="+2"/> <source>About &amp;Qt</source> <translation>&amp;Про Qt</translation> </message> <message> <location line="+1"/> <source>Show information about Qt</source> <translation>Показати інформацію про Qt</translation> </message> <message> <location line="+2"/> <source>&amp;Options...</source> <translation>&amp;Параметри...</translation> </message> <message> <location line="+6"/> <source>&amp;Encrypt Wallet...</source> <translation>&amp;Шифрування гаманця...</translation> </message> <message> <location line="+3"/> <source>&amp;Backup Wallet...</source> <translation>&amp;Резервне копіювання гаманця...</translation> </message> <message> <location line="+2"/> <source>&amp;Change Passphrase...</source> <translation>Змінити парол&amp;ь...</translation> </message> <message> <location line="+285"/> <source>Importing blocks from disk...</source> <translation>Імпорт блоків з диску...</translation> </message> <message> <location line="+3"/> <source>Reindexing blocks on disk...</source> <translation type="unfinished"/> </message> <message> <location line="-347"/> <source>Send coins to a CharityCoinHelps address</source> <translation>Відправити монети на вказану адресу</translation> </message> <message> <location line="+49"/> <source>Modify configuration options for CharityCoinHelps</source> <translation>Редагувати параметри</translation> </message> <message> <location line="+9"/> <source>Backup wallet to another location</source> <translation>Резервне копіювання гаманця в інше місце</translation> </message> <message> <location line="+2"/> <source>Change the passphrase used for wallet encryption</source> <translation>Змінити пароль, який використовується для шифрування гаманця</translation> </message> <message> <location line="+6"/> <source>&amp;Debug window</source> <translation>Вікно зневадження</translation> </message> <message> <location line="+1"/> <source>Open debugging and diagnostic console</source> <translation>Відкрити консоль зневадження і діагностики</translation> </message> <message> <location line="-4"/> <source>&amp;Verify message...</source> <translation>Перевірити повідомлення...</translation> </message> <message> <location line="-165"/> <location line="+530"/> <source>CharityCoinHelps</source> <translation>CharityCoinHelps</translation> </message> <message> <location line="-530"/> <source>Wallet</source> <translation>Гаманець</translation> </message> <message> <location line="+101"/> <source>&amp;Send</source> <translation type="unfinished"/> </message> <message> <location line="+7"/> <source>&amp;Receive</source> <translation type="unfinished"/> </message> <message> <location line="+14"/> <source>&amp;Addresses</source> <translation type="unfinished"/> </message> <message> <location line="+22"/> <source>&amp;About CharityCoinHelps</source> <translation>&amp;Про CharityCoinHelps</translation> </message> <message> <location line="+9"/> <source>&amp;Show / Hide</source> <translation>Показати / Приховати</translation> </message> <message> <location line="+1"/> <source>Show or hide the main Window</source> <translation>Показує або приховує головне вікно</translation> </message> <message> <location line="+3"/> <source>Encrypt the private keys that belong to your wallet</source> <translation type="unfinished"/> </message> <message> <location line="+7"/> <source>Sign messages with your CharityCoinHelps addresses to prove you own them</source> <translation>Підтвердіть, що Ви є власником повідомлення підписавши його Вашою CharityCoinHelps-адресою </translation> </message> <message> <location line="+2"/> <source>Verify messages to ensure they were signed with specified CharityCoinHelps addresses</source> <translation>Перевірте повідомлення для впевненості, що воно підписано вказаною CharityCoinHelps-адресою</translation> </message> <message> <location line="+28"/> <source>&amp;File</source> <translation>&amp;Файл</translation> </message> <message> <location line="+7"/> <source>&amp;Settings</source> <translation>&amp;Налаштування</translation> </message> <message> <location line="+6"/> <source>&amp;Help</source> <translation>&amp;Довідка</translation> </message> <message> <location line="+9"/> <source>Tabs toolbar</source> <translation>Панель вкладок</translation> </message> <message> <location line="+17"/> <location line="+10"/> <source>[testnet]</source> <translation>[тестова мережа]</translation> </message> <message> <location line="+47"/> <source>CharityCoinHelps client</source> <translation>CharityCoinHelps-клієнт</translation> </message> <message numerus="yes"> <location line="+141"/> <source>%n active connection(s) to CharityCoinHelps network</source> <translation><numerusform>%n активне з&apos;єднання з мережею</numerusform><numerusform>%n активні з&apos;єднання з мережею</numerusform><numerusform>%n активних з&apos;єднань з мережею</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 type="unfinished"/> </message> <message> <location line="+4"/> <source>Processed %1 blocks of transaction history.</source> <translation>Оброблено %1 блоків історії транзакцій.</translation> </message> <message numerus="yes"> <location line="+20"/> <source>%n hour(s)</source> <translation type="unfinished"><numerusform></numerusform><numerusform></numerusform><numerusform></numerusform></translation> </message> <message numerus="yes"> <location line="+4"/> <source>%n day(s)</source> <translation type="unfinished"><numerusform></numerusform><numerusform></numerusform><numerusform></numerusform></translation> </message> <message numerus="yes"> <location line="+4"/> <source>%n week(s)</source> <translation type="unfinished"><numerusform></numerusform><numerusform></numerusform><numerusform></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 type="unfinished"/> </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>Помилка</translation> </message> <message> <location line="+3"/> <source>Warning</source> <translation>Увага</translation> </message> <message> <location line="+3"/> <source>Information</source> <translation>Інформація</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 type="unfinished"/> </message> <message> <location line="-140"/> <source>Up to date</source> <translation>Синхронізовано</translation> </message> <message> <location line="+31"/> <source>Catching up...</source> <translation>Синхронізується...</translation> </message> <message> <location line="+113"/> <source>Confirm transaction fee</source> <translation>Підтвердити комісію</translation> </message> <message> <location line="+8"/> <source>Sent transaction</source> <translation>Надіслані транзакції</translation> </message> <message> <location line="+0"/> <source>Incoming transaction</source> <translation>Отримані перекази</translation> </message> <message> <location line="+1"/> <source>Date: %1 Amount: %2 Type: %3 Address: %4 </source> <translation>Дата: %1 Кількість: %2 Тип: %3 Адреса: %4 </translation> </message> <message> <location line="+33"/> <location line="+23"/> <source>URI handling</source> <translation>Обробка URI</translation> </message> <message> <location line="-23"/> <location line="+23"/> <source>URI can not be parsed! This can be caused by an invalid CharityCoinHelps address or malformed URI parameters.</source> <translation>Неможливо обробити URI! Це може бути викликано неправильною CharityCoinHelps-адресою, чи невірними параметрами URI.</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>&lt;b&gt;Зашифрований&lt;/b&gt; гаманець &lt;b&gt;розблоковано&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>&lt;b&gt;Зашифрований&lt;/b&gt; гаманець &lt;b&gt;заблоковано&lt;/b&gt;</translation> </message> <message> <location filename="../bitcoin.cpp" line="+111"/> <source>A fatal error occurred. CharityCoinHelps can no longer continue safely and will quit.</source> <translation type="unfinished"/> </message> </context> <context> <name>ClientModel</name> <message> <location filename="../clientmodel.cpp" line="+104"/> <source>Network Alert</source> <translation>Сповіщення мережі</translation> </message> </context> <context> <name>EditAddressDialog</name> <message> <location filename="../forms/editaddressdialog.ui" line="+14"/> <source>Edit Address</source> <translation>Редагувати адресу</translation> </message> <message> <location line="+11"/> <source>&amp;Label</source> <translation>&amp;Мітка</translation> </message> <message> <location line="+10"/> <source>The label associated with this address book entry</source> <translation>Мітка, пов&apos;язана з цим записом адресної книги</translation> </message> <message> <location line="+7"/> <source>&amp;Address</source> <translation>&amp;Адреса</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>Адреса, пов&apos;язана з цим записом адресної книги. Може бути змінено тільки для адреси відправника.</translation> </message> <message> <location filename="../editaddressdialog.cpp" line="+21"/> <source>New receiving address</source> <translation>Нова адреса для отримання</translation> </message> <message> <location line="+4"/> <source>New sending address</source> <translation>Нова адреса для відправлення</translation> </message> <message> <location line="+3"/> <source>Edit receiving address</source> <translation>Редагувати адресу для отримання</translation> </message> <message> <location line="+4"/> <source>Edit sending address</source> <translation>Редагувати адресу для відправлення</translation> </message> <message> <location line="+76"/> <source>The entered address &quot;%1&quot; is already in the address book.</source> <translation>Введена адреса «%1» вже присутня в адресній книзі.</translation> </message> <message> <location line="-5"/> <source>The entered address &quot;%1&quot; is not a valid CharityCoinHelps address.</source> <translation>Введена адреса «%1» не є коректною адресою в мережі CharityCoinHelps.</translation> </message> <message> <location line="+10"/> <source>Could not unlock wallet.</source> <translation>Неможливо розблокувати гаманець.</translation> </message> <message> <location line="+5"/> <source>New key generation failed.</source> <translation>Не вдалося згенерувати нові ключі.</translation> </message> </context> <context> <name>GUIUtil::HelpMessageBox</name> <message> <location filename="../guiutil.cpp" line="+424"/> <location line="+12"/> <source>CharityCoinHelps-Qt</source> <translation>CharityCoinHelps-Qt</translation> </message> <message> <location line="-12"/> <source>version</source> <translation>версія</translation> </message> <message> <location line="+2"/> <source>Usage:</source> <translation>Використання:</translation> </message> <message> <location line="+1"/> <source>command-line options</source> <translation>параметри командного рядка</translation> </message> <message> <location line="+4"/> <source>UI options</source> <translation>Параметри інтерфейсу</translation> </message> <message> <location line="+1"/> <source>Set language, for example &quot;de_DE&quot; (default: system locale)</source> <translation>Встановлення мови, наприклад &quot;de_DE&quot; (типово: системна)</translation> </message> <message> <location line="+1"/> <source>Start minimized</source> <translation>Запускати згорнутим</translation> </message> <message> <location line="+1"/> <source>Show splash screen on startup (default: 1)</source> <translation>Показувати заставку під час запуску (типово: 1)</translation> </message> </context> <context> <name>OptionsDialog</name> <message> <location filename="../forms/optionsdialog.ui" line="+14"/> <source>Options</source> <translation>Параметри</translation> </message> <message> <location line="+16"/> <source>&amp;Main</source> <translation>&amp;Головні</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>Заплатити комісі&amp;ю</translation> </message> <message> <location line="+31"/> <source>Automatically start CharityCoinHelps after logging in to the system.</source> <translation>Автоматично запускати гаманець при вході до системи.</translation> </message> <message> <location line="+3"/> <source>&amp;Start CharityCoinHelps on system login</source> <translation>&amp;Запускати гаманець при вході в систему</translation> </message> <message> <location line="+35"/> <source>Reset all client options to default.</source> <translation>Скинути всі параметри клієнта на типові.</translation> </message> <message> <location line="+3"/> <source>&amp;Reset Options</source> <translation>Скинути параметри</translation> </message> <message> <location line="+13"/> <source>&amp;Network</source> <translation>&amp;Мережа</translation> </message> <message> <location line="+6"/> <source>Automatically open the CharityCoinHelps client port on the router. This only works when your router supports UPnP and it is enabled.</source> <translation>Автоматично відкривати порт для клієнту біткоін на роутері. Працює лише якщо ваш роутер підтримує UPnP і ця функція увімкнена.</translation> </message> <message> <location line="+3"/> <source>Map port using &amp;UPnP</source> <translation>Відображення порту через &amp;UPnP</translation> </message> <message> <location line="+7"/> <source>Connect to the CharityCoinHelps network through a SOCKS proxy (e.g. when connecting through Tor).</source> <translation>Підключатись до мережі CharityCoinHelps через SOCKS-проксі (наприклад при використанні Tor).</translation> </message> <message> <location line="+3"/> <source>&amp;Connect through SOCKS proxy:</source> <translation>Підключатись через &amp;SOCKS-проксі:</translation> </message> <message> <location line="+9"/> <source>Proxy &amp;IP:</source> <translation>&amp;IP проксі:</translation> </message> <message> <location line="+19"/> <source>IP address of the proxy (e.g. 127.0.0.1)</source> <translation>IP-адреса проксі-сервера (наприклад 127.0.0.1)</translation> </message> <message> <location line="+7"/> <source>&amp;Port:</source> <translation>&amp;Порт:</translation> </message> <message> <location line="+19"/> <source>Port of the proxy (e.g. 9050)</source> <translation>Порт проксі-сервера (наприклад 9050)</translation> </message> <message> <location line="+7"/> <source>SOCKS &amp;Version:</source> <translation>SOCKS версії:</translation> </message> <message> <location line="+13"/> <source>SOCKS version of the proxy (e.g. 5)</source> <translation>Версія SOCKS-проксі (наприклад 5)</translation> </message> <message> <location line="+36"/> <source>&amp;Window</source> <translation>&amp;Вікно</translation> </message> <message> <location line="+6"/> <source>Show only a tray icon after minimizing the window.</source> <translation>Показувати лише іконку в треї після згортання вікна.</translation> </message> <message> <location line="+3"/> <source>&amp;Minimize to the tray instead of the taskbar</source> <translation>Мінімізувати &amp;у трей</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>Згортати замість закриття. Якщо ця опція включена, програма закриється лише після вибору відповідного пункту в меню.</translation> </message> <message> <location line="+3"/> <source>M&amp;inimize on close</source> <translation>Згортати замість закритт&amp;я</translation> </message> <message> <location line="+21"/> <source>&amp;Display</source> <translation>&amp;Відображення</translation> </message> <message> <location line="+8"/> <source>User Interface &amp;language:</source> <translation>Мова інтерфейсу користувача:</translation> </message> <message> <location line="+13"/> <source>The user interface language can be set here. This setting will take effect after restarting CharityCoinHelps.</source> <translation>Встановлює мову інтерфейсу. Зміни набудуть чинності після перезапуску CharityCoinHelps.</translation> </message> <message> <location line="+11"/> <source>&amp;Unit to show amounts in:</source> <translation>В&amp;имірювати монети в:</translation> </message> <message> <location line="+13"/> <source>Choose the default subdivision unit to show in the interface and when sending coins.</source> <translation>Виберіть одиницю вимірювання монет, яка буде відображатись в гаманці та при відправленні.</translation> </message> <message> <location line="+9"/> <source>Whether to show CharityCoinHelps addresses in the transaction list or not.</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>&amp;Display addresses in transaction list</source> <translation>&amp;Відображати адресу в списку транзакцій</translation> </message> <message> <location line="+71"/> <source>&amp;OK</source> <translation>&amp;Гаразд</translation> </message> <message> <location line="+7"/> <source>&amp;Cancel</source> <translation>&amp;Скасувати</translation> </message> <message> <location line="+10"/> <source>&amp;Apply</source> <translation>&amp;Застосувати</translation> </message> <message> <location filename="../optionsdialog.cpp" line="+53"/> <source>default</source> <translation>типово</translation> </message> <message> <location line="+130"/> <source>Confirm options reset</source> <translation>Підтвердження скидання параметрів</translation> </message> <message> <location line="+1"/> <source>Some settings may require a client restart to take effect.</source> <translation>Деякі параметри потребують перезапуск клієнта для набуття чинності.</translation> </message> <message> <location line="+0"/> <source>Do you want to proceed?</source> <translation>Продовжувати?</translation> </message> <message> <location line="+42"/> <location line="+9"/> <source>Warning</source> <translation>Увага</translation> </message> <message> <location line="-9"/> <location line="+9"/> <source>This setting will take effect after restarting CharityCoinHelps.</source> <translation>Цей параметр набуде чинності після перезапуску CharityCoinHelps.</translation> </message> <message> <location line="+29"/> <source>The supplied proxy address is invalid.</source> <translation>Невірно вказано адресу проксі.</translation> </message> </context> <context> <name>OverviewPage</name> <message> <location filename="../forms/overviewpage.ui" line="+14"/> <source>Form</source> <translation>Форма</translation> </message> <message> <location line="+50"/> <location line="+166"/> <source>The displayed information may be out of date. Your wallet automatically synchronizes with the CharityCoinHelps network after a connection is established, but this process has not completed yet.</source> <translation>Показана інформація вже може бути застарілою. Ваш гаманець буде автоматично синхронізовано з мережею CharityCoinHelps після встановлення підключення, але цей процес ще не завершено.</translation> </message> <message> <location line="-124"/> <source>Balance:</source> <translation>Баланс:</translation> </message> <message> <location line="+29"/> <source>Unconfirmed:</source> <translation>Непідтверджені:</translation> </message> <message> <location line="-78"/> <source>Wallet</source> <translation>Гаманець</translation> </message> <message> <location line="+107"/> <source>Immature:</source> <translation type="unfinished"/> </message> <message> <location line="+13"/> <source>Mined balance that has not yet matured</source> <translation type="unfinished"/> </message> <message> <location line="+46"/> <source>&lt;b&gt;Recent transactions&lt;/b&gt;</source> <translation>&lt;b&gt;Недавні транзакції&lt;/b&gt;</translation> </message> <message> <location line="-101"/> <source>Your current balance</source> <translation>Ваш поточний баланс</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>Загальна сума всіх транзакцій, які ще не підтверджені, та до цих пір не враховуються в загальному балансі</translation> </message> <message> <location filename="../overviewpage.cpp" line="+116"/> <location line="+1"/> <source>out of sync</source> <translation>не синхронізовано</translation> </message> </context> <context> <name>PaymentServer</name> <message> <location filename="../paymentserver.cpp" line="+107"/> <source>Cannot start charitycoinhelps: 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>Діалог QR-коду</translation> </message> <message> <location line="+59"/> <source>Request Payment</source> <translation>Запросити Платіж</translation> </message> <message> <location line="+56"/> <source>Amount:</source> <translation>Кількість:</translation> </message> <message> <location line="-44"/> <source>Label:</source> <translation>Мітка:</translation> </message> <message> <location line="+19"/> <source>Message:</source> <translation>Повідомлення:</translation> </message> <message> <location line="+71"/> <source>&amp;Save As...</source> <translation>&amp;Зберегти як...</translation> </message> <message> <location filename="../qrcodedialog.cpp" line="+62"/> <source>Error encoding URI into QR Code.</source> <translation>Помилка при кодуванні URI в QR-код.</translation> </message> <message> <location line="+40"/> <source>The entered amount is invalid, please check.</source> <translation>Невірно введено кількість, будь ласка, перевірте.</translation> </message> <message> <location line="+23"/> <source>Resulting URI too long, try to reduce the text for label / message.</source> <translation>Кінцевий URI занадто довгий, спробуйте зменшити текст для мітки / повідомлення.</translation> </message> <message> <location line="+25"/> <source>Save QR Code</source> <translation>Зберегти QR-код</translation> </message> <message> <location line="+0"/> <source>PNG Images (*.png)</source> <translation>PNG-зображення (*.png)</translation> </message> </context> <context> <name>RPCConsole</name> <message> <location filename="../forms/rpcconsole.ui" line="+46"/> <source>Client name</source> <translation>Назва клієнту</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>Н/Д</translation> </message> <message> <location line="-217"/> <source>Client version</source> <translation>Версія клієнту</translation> </message> <message> <location line="-45"/> <source>&amp;Information</source> <translation>&amp;Інформація</translation> </message> <message> <location line="+68"/> <source>Using OpenSSL version</source> <translation>Використовується OpenSSL версії</translation> </message> <message> <location line="+49"/> <source>Startup time</source> <translation type="unfinished"/> </message> <message> <location line="+29"/> <source>Network</source> <translation>Мережа</translation> </message> <message> <location line="+7"/> <source>Number of connections</source> <translation>Кількість підключень</translation> </message> <message> <location line="+23"/> <source>On testnet</source> <translation>В тестовій мережі</translation> </message> <message> <location line="+23"/> <source>Block chain</source> <translation type="unfinished"/> </message> <message> <location line="+7"/> <source>Current number of blocks</source> <translation>Поточне число блоків</translation> </message> <message> <location line="+23"/> <source>Estimated total blocks</source> <translation type="unfinished"/> </message> <message> <location line="+23"/> <source>Last block time</source> <translation type="unfinished"/> </message> <message> <location line="+52"/> <source>&amp;Open</source> <translation>Відкрити</translation> </message> <message> <location line="+16"/> <source>Command-line options</source> <translation>Параметри командного рядка</translation> </message> <message> <location line="+7"/> <source>Show the CharityCoinHelps-Qt help message to get a list with possible CharityCoinHelps command-line options.</source> <translation>Показати довідку CharityCoinHelps-Qt для отримання переліку можливих параметрів командного рядка.</translation> </message> <message> <location line="+3"/> <source>&amp;Show</source> <translation>Показати</translation> </message> <message> <location line="+24"/> <source>&amp;Console</source> <translation>Консоль</translation> </message> <message> <location line="-260"/> <source>Build date</source> <translation>Дата збирання</translation> </message> <message> <location line="-104"/> <source>CharityCoinHelps - Debug window</source> <translation>CharityCoinHelps - Вікно зневадження</translation> </message> <message> <location line="+25"/> <source>CharityCoinHelps Core</source> <translation type="unfinished"/> </message> <message> <location line="+279"/> <source>Debug log file</source> <translation>Файл звіту зневадження</translation> </message> <message> <location line="+7"/> <source>Open the CharityCoinHelps debug log file from the current data directory. This can take a few seconds for large log files.</source> <translation type="unfinished"/> </message> <message> <location line="+102"/> <source>Clear console</source> <translation>Очистити консоль</translation> </message> <message> <location filename="../rpcconsole.cpp" line="-30"/> <source>Welcome to the CharityCoinHelps RPC console.</source> <translation>Вітаємо у консолі CharityCoinHelps RPC.</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>Використовуйте стрілки вгору вниз для навігації по історії, і &lt;b&gt;Ctrl-L&lt;/b&gt; для очищення екрана.</translation> </message> <message> <location line="+1"/> <source>Type &lt;b&gt;help&lt;/b&gt; for an overview of available commands.</source> <translation>Наберіть &lt;b&gt;help&lt;/b&gt; для перегляду доступних команд.</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>Відправити</translation> </message> <message> <location line="+50"/> <source>Send to multiple recipients at once</source> <translation>Відправити на декілька адрес</translation> </message> <message> <location line="+3"/> <source>Add &amp;Recipient</source> <translation>Дод&amp;ати одержувача</translation> </message> <message> <location line="+20"/> <source>Remove all transaction fields</source> <translation>Видалити всі поля транзакції</translation> </message> <message> <location line="+3"/> <source>Clear &amp;All</source> <translation>Очистити &amp;все</translation> </message> <message> <location line="+22"/> <source>Balance:</source> <translation>Баланс:</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>Підтвердити відправлення</translation> </message> <message> <location line="+3"/> <source>S&amp;end</source> <translation>&amp;Відправити</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; адресату %2 (%3)</translation> </message> <message> <location line="+5"/> <source>Confirm send coins</source> <translation>Підтвердіть відправлення</translation> </message> <message> <location line="+1"/> <source>Are you sure you want to send %1?</source> <translation>Ви впевнені що хочете відправити %1?</translation> </message> <message> <location line="+0"/> <source> and </source> <translation> і </translation> </message> <message> <location line="+23"/> <source>The recipient address is not valid, please recheck.</source> <translation>Адреса отримувача невірна, будь ласка перепровірте.</translation> </message> <message> <location line="+5"/> <source>The amount to pay must be larger than 0.</source> <translation>Кількість монет для відправлення повинна бути більшою 0.</translation> </message> <message> <location line="+5"/> <source>The amount exceeds your balance.</source> <translation>Кількість монет для відправлення перевищує ваш баланс.</translation> </message> <message> <location line="+5"/> <source>The total exceeds your balance when the %1 transaction fee is included.</source> <translation>Сума перевищить ваш баланс, якщо комісія %1 буде додана до вашої транзакції.</translation> </message> <message> <location line="+6"/> <source>Duplicate address found, can only send to each address once per send operation.</source> <translation>Знайдено адресу що дублюється. Відправлення на кожну адресу дозволяється лише один раз на кожну операцію переказу.</translation> </message> <message> <location line="+5"/> <source>Error: Transaction creation failed!</source> <translation>Помилка: Не вдалося створити транзакцію!</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>Помилка: транзакцію було відхилено. Це може статись, якщо декілька монет з вашого гаманця вже використані, наприклад, якщо ви використовуєте одну копію гаманця (wallet.dat), а монети були використані з іншої копії, але не позначені як використані в цій.</translation> </message> </context> <context> <name>SendCoinsEntry</name> <message> <location filename="../forms/sendcoinsentry.ui" line="+14"/> <source>Form</source> <translation>Форма</translation> </message> <message> <location line="+15"/> <source>A&amp;mount:</source> <translation>&amp;Кількість:</translation> </message> <message> <location line="+13"/> <source>Pay &amp;To:</source> <translation>&amp;Отримувач:</translation> </message> <message> <location line="+34"/> <source>The address to send the payment to (e.g. Ler4HNAEfwYhBmGXcFP2Po1NpRUEiK8km2)</source> <translation type="unfinished"/> </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>Введіть мітку для цієї адреси для додавання її в адресну книгу</translation> </message> <message> <location line="-78"/> <source>&amp;Label:</source> <translation>&amp;Мітка:</translation> </message> <message> <location line="+28"/> <source>Choose address from address book</source> <translation>Вибрати адресу з адресної книги</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>Вставити адресу</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>Видалити цього отримувача</translation> </message> <message> <location filename="../sendcoinsentry.cpp" line="+1"/> <source>Enter a CharityCoinHelps address (e.g. Ler4HNAEfwYhBmGXcFP2Po1NpRUEiK8km2)</source> <translation>Введіть адресу CharityCoinHelps (наприклад Ler4HNAEfwYhBmGXcFP2Po1NpRUEiK8km2)</translation> </message> </context> <context> <name>SignVerifyMessageDialog</name> <message> <location filename="../forms/signverifymessagedialog.ui" line="+14"/> <source>Signatures - Sign / Verify a Message</source> <translation>Підписи - Підпис / Перевірка повідомлення</translation> </message> <message> <location line="+13"/> <source>&amp;Sign Message</source> <translation>&amp;Підписати повідомлення</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 type="unfinished"/> </message> <message> <location line="+18"/> <source>The address to sign the message with (e.g. Ler4HNAEfwYhBmGXcFP2Po1NpRUEiK8km2)</source> <translation>Введіть адресу CharityCoinHelps (наприклад Ler4HNAEfwYhBmGXcFP2Po1NpRUEiK8km2)</translation> </message> <message> <location line="+10"/> <location line="+213"/> <source>Choose an address from the address book</source> <translation>Вибрати адресу з адресної книги</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>Вставити адресу</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>Введіть повідомлення, яке ви хочете підписати тут</translation> </message> <message> <location line="+7"/> <source>Signature</source> <translation>Підпис</translation> </message> <message> <location line="+27"/> <source>Copy the current signature to the system clipboard</source> <translation>Копіювати поточну сигнатуру до системного буферу обміну</translation> </message> <message> <location line="+21"/> <source>Sign the message to prove you own this CharityCoinHelps address</source> <translation>Підпишіть повідомлення щоб довести, що ви є власником цієї адреси</translation> </message> <message> <location line="+3"/> <source>Sign &amp;Message</source> <translation>&amp;Підписати повідомлення</translation> </message> <message> <location line="+14"/> <source>Reset all sign message fields</source> <translation>Скинути всі поля підпису повідомлення</translation> </message> <message> <location line="+3"/> <location line="+146"/> <source>Clear &amp;All</source> <translation>Очистити &amp;все</translation> </message> <message> <location line="-87"/> <source>&amp;Verify Message</source> <translation>Перевірити повідомлення</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>Введіть адресу CharityCoinHelps (наприклад Ler4HNAEfwYhBmGXcFP2Po1NpRUEiK8km2)</translation> </message> <message> <location line="+40"/> <source>Verify the message to ensure it was signed with the specified CharityCoinHelps address</source> <translation>Перевірте повідомлення для впевненості, що воно підписано вказаною CharityCoinHelps-адресою</translation> </message> <message> <location line="+3"/> <source>Verify &amp;Message</source> <translation>Перевірити повідомлення</translation> </message> <message> <location line="+14"/> <source>Reset all verify message fields</source> <translation>Скинути всі поля перевірки повідомлення</translation> </message> <message> <location filename="../signverifymessagedialog.cpp" line="+27"/> <location line="+3"/> <source>Enter a CharityCoinHelps address (e.g. Ler4HNAEfwYhBmGXcFP2Po1NpRUEiK8km2)</source> <translation>Введіть адресу CharityCoinHelps (наприклад Ler4HNAEfwYhBmGXcFP2Po1NpRUEiK8km2)</translation> </message> <message> <location line="-2"/> <source>Click &quot;Sign Message&quot; to generate signature</source> <translation>Натисніть кнопку «Підписати повідомлення», для отримання підпису</translation> </message> <message> <location line="+3"/> <source>Enter CharityCoinHelps signature</source> <translation>Введіть сигнатуру CharityCoinHelps</translation> </message> <message> <location line="+82"/> <location line="+81"/> <source>The entered address is invalid.</source> <translation>Введена нечинна адреса.</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>Будь ласка, перевірте адресу та спробуйте ще.</translation> </message> <message> <location line="-81"/> <location line="+81"/> <source>The entered address does not refer to a key.</source> <translation type="unfinished"/> </message> <message> <location line="-73"/> <source>Wallet unlock was cancelled.</source> <translation type="unfinished"/> </message> <message> <location line="+8"/> <source>Private key for the entered address is not available.</source> <translation type="unfinished"/> </message> <message> <location line="+12"/> <source>Message signing failed.</source> <translation>Не вдалося підписати повідомлення.</translation> </message> <message> <location line="+5"/> <source>Message signed.</source> <translation>Повідомлення підписано.</translation> </message> <message> <location line="+59"/> <source>The signature could not be decoded.</source> <translation>Підпис не можливо декодувати.</translation> </message> <message> <location line="+0"/> <location line="+13"/> <source>Please check the signature and try again.</source> <translation>Будь ласка, перевірте підпис та спробуйте ще.</translation> </message> <message> <location line="+0"/> <source>The signature did not match the message digest.</source> <translation type="unfinished"/> </message> <message> <location line="+7"/> <source>Message verification failed.</source> <translation>Не вдалося перевірити повідомлення.</translation> </message> <message> <location line="+5"/> <source>Message verified.</source> <translation>Повідомлення перевірено.</translation> </message> </context> <context> <name>SplashScreen</name> <message> <location filename="../splashscreen.cpp" line="+22"/> <source>The CharityCoinHelps developers</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>[testnet]</source> <translation>[тестова мережа]</translation> </message> </context> <context> <name>TransactionDesc</name> <message> <location filename="../transactiondesc.cpp" line="+20"/> <source>Open until %1</source> <translation>Відкрити до %1</translation> </message> <message> <location line="+6"/> <source>%1/offline</source> <translation>%1/поза інтернетом</translation> </message> <message> <location line="+2"/> <source>%1/unconfirmed</source> <translation>%1/не підтверджено</translation> </message> <message> <location line="+2"/> <source>%1 confirmations</source> <translation>%1 підтверджень</translation> </message> <message> <location line="+18"/> <source>Status</source> <translation>Статус</translation> </message> <message numerus="yes"> <location line="+7"/> <source>, broadcast through %n node(s)</source> <translation type="unfinished"><numerusform></numerusform><numerusform></numerusform><numerusform></numerusform></translation> </message> <message> <location line="+4"/> <source>Date</source> <translation>Дата</translation> </message> <message> <location line="+7"/> <source>Source</source> <translation type="unfinished"/> </message> <message> <location line="+0"/> <source>Generated</source> <translation>Згенеровано</translation> </message> <message> <location line="+5"/> <location line="+17"/> <source>From</source> <translation>Відправник</translation> </message> <message> <location line="+1"/> <location line="+22"/> <location line="+58"/> <source>To</source> <translation>Отримувач</translation> </message> <message> <location line="-77"/> <location line="+2"/> <source>own address</source> <translation type="unfinished"/> </message> <message> <location line="-2"/> <source>label</source> <translation>Мітка</translation> </message> <message> <location line="+37"/> <location line="+12"/> <location line="+45"/> <location line="+17"/> <location line="+30"/> <source>Credit</source> <translation>Кредит</translation> </message> <message numerus="yes"> <location line="-102"/> <source>matures in %n more block(s)</source> <translation type="unfinished"><numerusform></numerusform><numerusform></numerusform><numerusform></numerusform></translation> </message> <message> <location line="+2"/> <source>not accepted</source> <translation>не прийнято</translation> </message> <message> <location line="+44"/> <location line="+8"/> <location line="+15"/> <location line="+30"/> <source>Debit</source> <translation>Дебет</translation> </message> <message> <location line="-39"/> <source>Transaction fee</source> <translation>Комісія за транзакцію</translation> </message> <message> <location line="+16"/> <source>Net amount</source> <translation>Загальна сума</translation> </message> <message> <location line="+6"/> <source>Message</source> <translation>Повідомлення</translation> </message> <message> <location line="+2"/> <source>Comment</source> <translation>Коментар</translation> </message> <message> <location line="+2"/> <source>Transaction ID</source> <translation>ID транзакції</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>Після генерації монет, потрібно зачекати 120 блоків, перш ніж їх можна буде використати. Коли ви згенерували цей блок, його було відправлено в мережу для того, щоб він був доданий до ланцюжка блоків. Якщо ця процедура не вдасться, статус буде змінено на «не підтверджено» і ви не зможете потратити згенеровані монету. Таке може статись, якщо хтось інший згенерував блок на декілька секунд раніше.</translation> </message> <message> <location line="+7"/> <source>Debug information</source> <translation type="unfinished"/> </message> <message> <location line="+8"/> <source>Transaction</source> <translation>Транзакція</translation> </message> <message> <location line="+3"/> <source>Inputs</source> <translation type="unfinished"/> </message> <message> <location line="+23"/> <source>Amount</source> <translation>Кількість</translation> </message> <message> <location line="+1"/> <source>true</source> <translation>true</translation> </message> <message> <location line="+0"/> <source>false</source> <translation>false</translation> </message> <message> <location line="-209"/> <source>, has not been successfully broadcast yet</source> <translation>, ще не було успішно розіслано</translation> </message> <message numerus="yes"> <location line="-35"/> <source>Open for %n more block(s)</source> <translation type="unfinished"><numerusform></numerusform><numerusform></numerusform><numerusform></numerusform></translation> </message> <message> <location line="+70"/> <source>unknown</source> <translation>невідомий</translation> </message> </context> <context> <name>TransactionDescDialog</name> <message> <location filename="../forms/transactiondescdialog.ui" line="+14"/> <source>Transaction details</source> <translation>Деталі транзакції</translation> </message> <message> <location line="+6"/> <source>This pane shows a detailed description of the transaction</source> <translation>Даний діалог показує детальну статистику по вибраній транзакції</translation> </message> </context> <context> <name>TransactionTableModel</name> <message> <location filename="../transactiontablemodel.cpp" line="+225"/> <source>Date</source> <translation>Дата</translation> </message> <message> <location line="+0"/> <source>Type</source> <translation>Тип</translation> </message> <message> <location line="+0"/> <source>Address</source> <translation>Адреса</translation> </message> <message> <location line="+0"/> <source>Amount</source> <translation>Кількість</translation> </message> <message numerus="yes"> <location line="+57"/> <source>Open for %n more block(s)</source> <translation type="unfinished"><numerusform></numerusform><numerusform></numerusform><numerusform></numerusform></translation> </message> <message> <location line="+3"/> <source>Open until %1</source> <translation>Відкрити до %1</translation> </message> <message> <location line="+3"/> <source>Offline (%1 confirmations)</source> <translation>Поза інтернетом (%1 підтверджень)</translation> </message> <message> <location line="+3"/> <source>Unconfirmed (%1 of %2 confirmations)</source> <translation>Непідтверджено (%1 із %2 підтверджень)</translation> </message> <message> <location line="+3"/> <source>Confirmed (%1 confirmations)</source> <translation>Підтверджено (%1 підтверджень)</translation> </message> <message numerus="yes"> <location line="+8"/> <source>Mined balance will be available when it matures in %n more block(s)</source> <translation type="unfinished"><numerusform></numerusform><numerusform></numerusform><numerusform></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>Цей блок не був отриманий жодними іншими вузлами і, ймовірно, не буде прийнятий!</translation> </message> <message> <location line="+3"/> <source>Generated but not accepted</source> <translation>Згенеровано, але не підтверджено</translation> </message> <message> <location line="+43"/> <source>Received with</source> <translation>Отримано</translation> </message> <message> <location line="+2"/> <source>Received from</source> <translation>Отримано від</translation> </message> <message> <location line="+3"/> <source>Sent to</source> <translation>Відправлено</translation> </message> <message> <location line="+2"/> <source>Payment to yourself</source> <translation>Відправлено собі</translation> </message> <message> <location line="+2"/> <source>Mined</source> <translation>Добуто</translation> </message> <message> <location line="+38"/> <source>(n/a)</source> <translation>(недоступно)</translation> </message> <message> <location line="+199"/> <source>Transaction status. Hover over this field to show number of confirmations.</source> <translation>Статус транзакції. Наведіть вказівник на це поле, щоб показати кількість підтверджень.</translation> </message> <message> <location line="+2"/> <source>Date and time that the transaction was received.</source> <translation>Дата і час, коли транзакцію було отримано.</translation> </message> <message> <location line="+2"/> <source>Type of transaction.</source> <translation>Тип транзакції.</translation> </message> <message> <location line="+2"/> <source>Destination address of transaction.</source> <translation>Адреса отримувача транзакції.</translation> </message> <message> <location line="+2"/> <source>Amount removed from or added to balance.</source> <translation>Сума, додана чи знята з балансу.</translation> </message> </context> <context> <name>TransactionView</name> <message> <location filename="../transactionview.cpp" line="+52"/> <location line="+16"/> <source>All</source> <translation>Всі</translation> </message> <message> <location line="-15"/> <source>Today</source> <translation>Сьогодні</translation> </message> <message> <location line="+1"/> <source>This week</source> <translation>На цьому тижні</translation> </message> <message> <location line="+1"/> <source>This month</source> <translation>На цьому місяці</translation> </message> <message> <location line="+1"/> <source>Last month</source> <translation>Минулого місяця</translation> </message> <message> <location line="+1"/> <source>This year</source> <translation>Цього року</translation> </message> <message> <location line="+1"/> <source>Range...</source> <translation>Проміжок...</translation> </message> <message> <location line="+11"/> <source>Received with</source> <translation>Отримані на</translation> </message> <message> <location line="+2"/> <source>Sent to</source> <translation>Відправлені на</translation> </message> <message> <location line="+2"/> <source>To yourself</source> <translation>Відправлені собі</translation> </message> <message> <location line="+1"/> <source>Mined</source> <translation>Добуті</translation> </message> <message> <location line="+1"/> <source>Other</source> <translation>Інше</translation> </message> <message> <location line="+7"/> <source>Enter address or label to search</source> <translation>Введіть адресу чи мітку для пошуку</translation> </message> <message> <location line="+7"/> <source>Min amount</source> <translation>Мінімальна сума</translation> </message> <message> <location line="+34"/> <source>Copy address</source> <translation>Скопіювати адресу</translation> </message> <message> <location line="+1"/> <source>Copy label</source> <translation>Скопіювати мітку</translation> </message> <message> <location line="+1"/> <source>Copy amount</source> <translation>Копіювати кількість</translation> </message> <message> <location line="+1"/> <source>Copy transaction ID</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Edit label</source> <translation>Редагувати мітку</translation> </message> <message> <location line="+1"/> <source>Show transaction details</source> <translation>Показати деталі транзакції</translation> </message> <message> <location line="+139"/> <source>Export Transaction Data</source> <translation>Експортувати дані транзакцій</translation> </message> <message> <location line="+1"/> <source>Comma separated file (*.csv)</source> <translation>Файли, розділені комою (*.csv)</translation> </message> <message> <location line="+8"/> <source>Confirmed</source> <translation>Підтверджені</translation> </message> <message> <location line="+1"/> <source>Date</source> <translation>Дата</translation> </message> <message> <location line="+1"/> <source>Type</source> <translation>Тип</translation> </message> <message> <location line="+1"/> <source>Label</source> <translation>Мітка</translation> </message> <message> <location line="+1"/> <source>Address</source> <translation>Адреса</translation> </message> <message> <location line="+1"/> <source>Amount</source> <translation>Кількість</translation> </message> <message> <location line="+1"/> <source>ID</source> <translation>Ідентифікатор</translation> </message> <message> <location line="+4"/> <source>Error exporting</source> <translation>Помилка експорту</translation> </message> <message> <location line="+0"/> <source>Could not write to file %1.</source> <translation>Неможливо записати у файл %1.</translation> </message> <message> <location line="+100"/> <source>Range:</source> <translation>Діапазон від:</translation> </message> <message> <location line="+8"/> <source>to</source> <translation>до</translation> </message> </context> <context> <name>WalletModel</name> <message> <location filename="../walletmodel.cpp" line="+193"/> <source>Send Coins</source> <translation>Відправити</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>Експортувати дані з поточної вкладки в файл</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 type="unfinished"/> </message> <message> <location line="+0"/> <source>There was an error trying to save the wallet data to the new location.</source> <translation>Виникла помилка при спробі зберегти гаманець в новому місці.</translation> </message> <message> <location line="+4"/> <source>Backup Successful</source> <translation>Успішне створення резервної копії</translation> </message> <message> <location line="+0"/> <source>The wallet data was successfully saved to the new location.</source> <translation>Данні гаманця успішно збережено в новому місці призначення.</translation> </message> </context> <context> <name>bitcoin-core</name> <message> <location filename="../bitcoinstrings.cpp" line="+94"/> <source>CharityCoinHelps version</source> <translation>Версія</translation> </message> <message> <location line="+102"/> <source>Usage:</source> <translation>Використання:</translation> </message> <message> <location line="-29"/> <source>Send command to -server or charitycoinhelpsd</source> <translation>Відправити команду серверу -server чи демону</translation> </message> <message> <location line="-23"/> <source>List commands</source> <translation>Список команд</translation> </message> <message> <location line="-12"/> <source>Get help for a command</source> <translation>Отримати довідку по команді</translation> </message> <message> <location line="+24"/> <source>Options:</source> <translation>Параметри:</translation> </message> <message> <location line="+24"/> <source>Specify configuration file (default: charitycoinhelps.conf)</source> <translation>Вкажіть файл конфігурації (типово: charitycoinhelps.conf)</translation> </message> <message> <location line="+3"/> <source>Specify pid file (default: charitycoinhelpsd.pid)</source> <translation>Вкажіть pid-файл (типово: charitycoinhelpsd.pid)</translation> </message> <message> <location line="-1"/> <source>Specify data directory</source> <translation>Вкажіть робочий каталог</translation> </message> <message> <location line="-9"/> <source>Set database cache size in megabytes (default: 25)</source> <translation>Встановити розмір кешу бази даних в мегабайтах (типово: 25)</translation> </message> <message> <location line="-28"/> <source>Listen for connections on &lt;port&gt; (default: 9793 or testnet: 19793)</source> <translation>Чекати на з&apos;єднання на &lt;port&gt; (типово: 9793 або тестова мережа: 19793)</translation> </message> <message> <location line="+5"/> <source>Maintain at most &lt;n&gt; connections to peers (default: 125)</source> <translation>Підтримувати не більше &lt;n&gt; зв&apos;язків з колегами (типово: 125)</translation> </message> <message> <location line="-48"/> <source>Connect to a node to retrieve peer addresses, and disconnect</source> <translation type="unfinished"/> </message> <message> <location line="+82"/> <source>Specify your own public address</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>Threshold for disconnecting misbehaving peers (default: 100)</source> <translation>Поріг відключення неправильно під&apos;єднаних пірів (типово: 100)</translation> </message> <message> <location line="-134"/> <source>Number of seconds to keep misbehaving peers from reconnecting (default: 86400)</source> <translation>Максимальній розмір вхідного буферу на одне з&apos;єднання (типово: 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 type="unfinished"/> </message> <message> <location line="+27"/> <source>Listen for JSON-RPC connections on &lt;port&gt; (default: 9792 or testnet: 19792)</source> <translation>Прослуховувати &lt;port&gt; для JSON-RPC-з&apos;єднань (типово: 9792 або тестова мережа: 19792)</translation> </message> <message> <location line="+37"/> <source>Accept command line and JSON-RPC commands</source> <translation>Приймати команди із командного рядка та команди JSON-RPC</translation> </message> <message> <location line="+76"/> <source>Run in the background as a daemon and accept commands</source> <translation>Запустити в фоновому режимі (як демон) та приймати команди</translation> </message> <message> <location line="+37"/> <source>Use the test network</source> <translation>Використовувати тестову мережу</translation> </message> <message> <location line="-112"/> <source>Accept connections from outside (default: 1 if no -proxy or -connect)</source> <translation type="unfinished"/> </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=charitycoinhelpsrpc 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;CharityCoinHelps Alert&quot; [email protected] </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 type="unfinished"/> </message> <message> <location line="+3"/> <source>Bind to given address and always listen on it. Use [host]:port notation for IPv6</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>Cannot obtain a lock on data directory %s. CharityCoinHelps is probably already running.</source> <translation type="unfinished"/> </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>Помилка: транзакцію було відхилено. Це може статись, якщо декілька монет з вашого гаманця вже використані, наприклад, якщо ви використовуєте одну копію гаманця (wallet.dat), а монети були використані з іншої копії, але не позначені як використані в цій.</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 type="unfinished"/> </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 type="unfinished"/> </message> <message> <location line="+11"/> <source>Set maximum size of high-priority/low-fee transactions in bytes (default: 27000)</source> <translation type="unfinished"/> </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 type="unfinished"/> </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>Увага: встановлено занадто велику комісію (-paytxfee). Комісія зніматиметься кожен раз коли ви проводитимете транзакції.</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 type="unfinished"/> </message> <message> <location line="+3"/> <source>Warning: Please check that your computer&apos;s date and time are correct! If your clock is wrong CharityCoinHelps will not work properly.</source> <translation>Увага: будь ласка, перевірте дату і час на своєму комп&apos;ютері. Якщо ваш годинник йде неправильно, CharityCoinHelps може працювати некоректно.</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>Увага: помилка читання wallet.dat! Всі ключі прочитано коректно, але дані транзакцій чи записи адресної книги можуть бути пропущені, або пошкоджені.</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>Увага: файл wallet.dat пошкоджено, дані врятовано! Оригінальний wallet.dat збережено як wallet.{timestamp}.bak до %s; якщо Ваш баланс чи транзакції неправильні, Ви можете відновити їх з резервної копії. </translation> </message> <message> <location line="+14"/> <source>Attempt to recover private keys from a corrupt wallet.dat</source> <translation>Спроба відновити закриті ключі з пошкодженого wallet.dat</translation> </message> <message> <location line="+2"/> <source>Block creation options:</source> <translation type="unfinished"/> </message> <message> <location line="+5"/> <source>Connect only to the specified node(s)</source> <translation>Підключитись лише до вказаного вузла</translation> </message> <message> <location line="+3"/> <source>Corrupted block database detected</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Discover own IP address (default: 1 when listening and no -externalip)</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Do you want to rebuild the block database now?</source> <translation type="unfinished"/> </message> <message> <location line="+2"/> <source>Error initializing block database</source> <translation>Помилка ініціалізації бази даних блоків</translation> </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>Помилка завантаження бази даних блоків</translation> </message> <message> <location line="+4"/> <source>Error opening block database</source> <translation type="unfinished"/> </message> <message> <location line="+2"/> <source>Error: Disk space is low!</source> <translation>Помилка: Мало вільного місця на диску!</translation> </message> <message> <location line="+1"/> <source>Error: Wallet locked, unable to create transaction!</source> <translation>Помилка: Гаманець заблокований, неможливо створити транзакцію!</translation> </message> <message> <location line="+1"/> <source>Error: system error: </source> <translation>Помилка: системна помилка: </translation> </message> <message> <location line="+1"/> <source>Failed to listen on any port. Use -listen=0 if you want this.</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Failed to read block info</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Failed to read block</source> <translation type="unfinished"/> </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 type="unfinished"/> </message> <message> <location line="+1"/> <source>Failed to write block</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Failed to write file info</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Failed to write to coin database</source> <translation type="unfinished"/> </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 type="unfinished"/> </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>Скільки блоків перевіряти під час запуску (типово: 288, 0 = всі)</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 type="unfinished"/> </message> <message> <location line="+1"/> <source>Verifying wallet...</source> <translation type="unfinished"/> </message> <message> <location line="-69"/> <source>Imports blocks from external blk000??.dat file</source> <translation>Імпорт блоків з зовнішнього файлу blk000??.dat</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>Інформація</translation> </message> <message> <location line="+3"/> <source>Invalid -tor address: &apos;%s&apos;</source> <translation>Помилка в адресі -tor: «%s»</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>Максимальний буфер, &lt;n&gt;*1000 байт (типово: 5000)</translation> </message> <message> <location line="+1"/> <source>Maximum per-connection send buffer, &lt;n&gt;*1000 bytes (default: 1000)</source> <translation>Максимальній розмір вихідного буферу на одне з&apos;єднання, &lt;n&gt;*1000 байт (типово: 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 type="unfinished"/> </message> <message> <location line="+2"/> <source>Output extra debugging information. Implies all other -debug* options</source> <translation>Виводити більше налагоджувальної інформації. Мається на увазі всі шнші -debug* параметри</translation> </message> <message> <location line="+1"/> <source>Output extra network debugging information</source> <translation type="unfinished"/> </message> <message> <location line="+2"/> <source>Prepend debug output with timestamp</source> <translation>Доповнювати налагоджувальний вивід відміткою часу</translation> </message> <message> <location line="+5"/> <source>SSL options: (see the CharityCoinHelps Wiki for SSL setup instructions)</source> <translation>Параметри SSL: (див. CharityCoinHelps Wiki для налаштування SSL)</translation> </message> <message> <location line="+1"/> <source>Select the version of socks proxy to use (4-5, default: 5)</source> <translation>Вибір версії socks-проксі для використання (4-5, типово: 5)</translation> </message> <message> <location line="+3"/> <source>Send trace/debug info to console instead of debug.log file</source> <translation>Відсилати налагоджувальну інформацію на консоль, а не у файл debug.log</translation> </message> <message> <location line="+1"/> <source>Send trace/debug info to debugger</source> <translation>Відсилати налагоджувальну інформацію до налагоджувача</translation> </message> <message> <location line="+5"/> <source>Set maximum block size in bytes (default: 250000)</source> <translation>Встановити максимальний розмір блоку у байтах (типово: 250000)</translation> </message> <message> <location line="+1"/> <source>Set minimum block size in bytes (default: 0)</source> <translation>Встановити мінімальний розмір блоку у байтах (типово: 0)</translation> </message> <message> <location line="+2"/> <source>Shrink debug.log file on client startup (default: 1 when no -debug)</source> <translation>Стискати файл debug.log під час старту клієнта (типово: 1 коли відсутутній параметр -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>Вказати тайм-аут підключення у мілісекундах (типово: 5000)</translation> </message> <message> <location line="+4"/> <source>System error: </source> <translation>Системна помилка: </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 для відображення порту, що прослуховується на роутері (default: 0)</translation> </message> <message> <location line="+1"/> <source>Use UPnP to map the listening port (default: 1 when listening)</source> <translation>Намагатись використовувати UPnP для відображення порту, що прослуховується на роутері (default: 1 when listening)</translation> </message> <message> <location line="+1"/> <source>Use proxy to reach tor hidden services (default: same as -proxy)</source> <translation type="unfinished"/> </message> <message> <location line="+2"/> <source>Username for JSON-RPC connections</source> <translation>Ім&apos;я користувача для JSON-RPC-з&apos;єднань</translation> </message> <message> <location line="+4"/> <source>Warning</source> <translation>Попередження</translation> </message> <message> <location line="+1"/> <source>Warning: This version is obsolete, upgrade required!</source> <translation>Увага: Поточна версія застаріла, необхідне оновлення!</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 пошкоджено, відновлення не вдалося</translation> </message> <message> <location line="-50"/> <source>Password for JSON-RPC connections</source> <translation>Пароль для JSON-RPC-з&apos;єднань</translation> </message> <message> <location line="-67"/> <source>Allow JSON-RPC connections from specified IP address</source> <translation>Дозволити JSON-RPC-з&apos;єднання з вказаної IP-адреси</translation> </message> <message> <location line="+76"/> <source>Send commands to node running on &lt;ip&gt; (default: 127.0.0.1)</source> <translation>Відправляти команди на вузол, запущений на &lt;ip&gt; (типово: 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 type="unfinished"/> </message> <message> <location line="+147"/> <source>Upgrade wallet to latest format</source> <translation>Модернізувати гаманець до останнього формату</translation> </message> <message> <location line="-21"/> <source>Set key pool size to &lt;n&gt; (default: 100)</source> <translation>Встановити розмір пулу ключів &lt;n&gt; (типово: 100)</translation> </message> <message> <location line="-12"/> <source>Rescan the block chain for missing wallet transactions</source> <translation>Пересканувати ланцюжок блоків, в пошуку втрачених транзакцій</translation> </message> <message> <location line="+35"/> <source>Use OpenSSL (https) for JSON-RPC connections</source> <translation>Використовувати OpenSSL (https) для JSON-RPC-з&apos;єднань</translation> </message> <message> <location line="-26"/> <source>Server certificate file (default: server.cert)</source> <translation>Файл сертифіката сервера (типово: server.cert)</translation> </message> <message> <location line="+1"/> <source>Server private key (default: server.pem)</source> <translation>Закритий ключ сервера (типово: server.pem)</translation> </message> <message> <location line="-151"/> <source>Acceptable ciphers (default: TLSv1+HIGH:!SSLv2:!aNULL:!eNULL:!AH:!3DES:@STRENGTH)</source> <translation>Допустимі шифри (типово: TLSv1+HIGH:!SSLv2:!aNULL:!eNULL:!AH:!3DES:@STRENGTH)</translation> </message> <message> <location line="+165"/> <source>This help message</source> <translation>Дана довідка</translation> </message> <message> <location line="+6"/> <source>Unable to bind to %s on this computer (bind returned error %d, %s)</source> <translation>Неможливо прив&apos;язати до порту %s на цьому комп&apos;ютері (bind returned error %d, %s)</translation> </message> <message> <location line="-91"/> <source>Connect through socks proxy</source> <translation>Підключитись через SOCKS-проксі</translation> </message> <message> <location line="-10"/> <source>Allow DNS lookups for -addnode, -seednode and -connect</source> <translation>Дозволити пошук в DNS для команд -addnode, -seednode та -connect</translation> </message> <message> <location line="+55"/> <source>Loading addresses...</source> <translation>Завантаження адрес...</translation> </message> <message> <location line="-35"/> <source>Error loading wallet.dat: Wallet corrupted</source> <translation>Помилка при завантаженні wallet.dat: Гаманець пошкоджено</translation> </message> <message> <location line="+1"/> <source>Error loading wallet.dat: Wallet requires newer version of CharityCoinHelps</source> <translation>Помилка при завантаженні wallet.dat: Гаманець потребує новішої версії Біткоін-клієнта</translation> </message> <message> <location line="+93"/> <source>Wallet needed to be rewritten: restart CharityCoinHelps to complete</source> <translation>Потрібно перезаписати гаманець: перезапустіть Біткоін-клієнт для завершення</translation> </message> <message> <location line="-95"/> <source>Error loading wallet.dat</source> <translation>Помилка при завантаженні wallet.dat</translation> </message> <message> <location line="+28"/> <source>Invalid -proxy address: &apos;%s&apos;</source> <translation>Помилка в адресі проксі-сервера: «%s»</translation> </message> <message> <location line="+56"/> <source>Unknown network specified in -onlynet: &apos;%s&apos;</source> <translation>Невідома мережа вказана в -onlynet: «%s»</translation> </message> <message> <location line="-1"/> <source>Unknown -socks proxy version requested: %i</source> <translation type="unfinished"/> </message> <message> <location line="-96"/> <source>Cannot resolve -bind address: &apos;%s&apos;</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Cannot resolve -externalip address: &apos;%s&apos;</source> <translation type="unfinished"/> </message> <message> <location line="+44"/> <source>Invalid amount for -paytxfee=&lt;amount&gt;: &apos;%s&apos;</source> <translation>Помилка у величині комісії -paytxfee=&lt;amount&gt;: «%s»</translation> </message> <message> <location line="+1"/> <source>Invalid amount</source> <translation>Некоректна кількість</translation> </message> <message> <location line="-6"/> <source>Insufficient funds</source> <translation>Недостатньо коштів</translation> </message> <message> <location line="+10"/> <source>Loading block index...</source> <translation>Завантаження індексу блоків...</translation> </message> <message> <location line="-57"/> <source>Add a node to connect to and attempt to keep the connection open</source> <translation>Додати вузол до підключення і лишити його відкритим</translation> </message> <message> <location line="-25"/> <source>Unable to bind to %s on this computer. CharityCoinHelps is probably already running.</source> <translation>Неможливо прив&apos;язати до порту %s на цьому комп&apos;ютері. Можливо гаманець вже запущено.</translation> </message> <message> <location line="+64"/> <source>Fee per KB to add to transactions you send</source> <translation>Комісія за КБ</translation> </message> <message> <location line="+19"/> <source>Loading wallet...</source> <translation>Завантаження гаманця...</translation> </message> <message> <location line="-52"/> <source>Cannot downgrade wallet</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>Cannot write default address</source> <translation>Неможливо записати типову адресу</translation> </message> <message> <location line="+64"/> <source>Rescanning...</source> <translation>Сканування...</translation> </message> <message> <location line="-57"/> <source>Done loading</source> <translation>Завантаження завершене</translation> </message> <message> <location line="+82"/> <source>To use the %s option</source> <translation type="unfinished"/> </message> <message> <location line="-74"/> <source>Error</source> <translation>Помилка</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>Ви мусите встановити rpcpassword=&lt;password&gt; в файлі конфігурації: %s Якщо файл не існує, створіть його із правами тільки для читання власником (owner-readable-only).</translation> </message> </context> </TS>
{ "content_hash": "f7341f6443c415ff67dbfb2d99f8d6d7", "timestamp": "", "source": "github", "line_count": 2928, "max_line_length": 431, "avg_line_length": 38.14549180327869, "alnum_prop": 0.6263586713224102, "repo_name": "CharityCoinHelps/charitycoinhelps-master-0.8", "id": "6dba5e91e18f218152e9850f10b98212fd1e54f6", "size": "124081", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/qt/locale/bitcoin_uk.ts", "mode": "33188", "license": "mit", "language": [ { "name": "C", "bytes": "103297" }, { "name": "C++", "bytes": "2523098" }, { "name": "CSS", "bytes": "1127" }, { "name": "IDL", "bytes": "14728" }, { "name": "Objective-C", "bytes": "5864" }, { "name": "Python", "bytes": "37296" }, { "name": "Shell", "bytes": "2527" }, { "name": "TypeScript", "bytes": "5270041" } ], "symlink_target": "" }
class Owner < ActiveRecord::Base has_many :widget_owners has_many :widgets, :through => :widget_owners end
{ "content_hash": "89f941cc7e60eeca691d7d401dd3e40f", "timestamp": "", "source": "github", "line_count": 4, "max_line_length": 46, "avg_line_length": 27.25, "alnum_prop": 0.7431192660550459, "repo_name": "matzko/query_sort_by_params", "id": "181ea2d5aa18de8d5827f1965f0d3d4c25bb832d", "size": "109", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "spec/dummy/app/models/owner.rb", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "686" }, { "name": "HTML", "bytes": "4883" }, { "name": "JavaScript", "bytes": "596" }, { "name": "Ruby", "bytes": "33377" } ], "symlink_target": "" }
require File.expand_path(File.dirname(__FILE__) + '/spec_helper') describe "PaperclipRmagick" do before do @monster = Monster.new @monster.image = File.open("#{File.dirname(__FILE__)}/support/monster.png") @monster.save end describe 'thumb' do subject{ @monster.image.queued_for_write[:thumb] } it "should be generated" do should_not be_nil end end describe 'vertical' do subject{ @monster.image.queued_for_write[:vertical] } it "should be generated" do should_not be_nil end end describe 'frame' do subject{ @monster.image.queued_for_write[:frame] } it "should be generated" do should_not be_nil system("open #{subject.path}") end end end
{ "content_hash": "0ae4f71fed04144504b7d6c4710f5877", "timestamp": "", "source": "github", "line_count": 31, "max_line_length": 79, "avg_line_length": 23.612903225806452, "alnum_prop": 0.6489071038251366, "repo_name": "mshibuya/paperclip-rmagick", "id": "f2e5ec395deea2ba7ec284b2b056d81e26394656", "size": "732", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "spec/paperclip-rmagick_spec.rb", "mode": "33188", "license": "mit", "language": [ { "name": "Ruby", "bytes": "8677" } ], "symlink_target": "" }
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd"> <html> <head> <meta http-equiv="content-type" content="text/html; charset=US-ASCII"> <title>PuTTY FAQ</title> <link rel="previous" href="Chapter10.html"> <link rel="ToC" href="index.html"> <link rel="up" href="index.html"> <link rel="index" href="IndexPage.html"> <link rel="next" href="AppendixB.html"> </head> <body> <p><a href="Chapter10.html">Previous</a> | <a href="index.html">Contents</a> | <a href="IndexPage.html">Index</a> | <a href="AppendixB.html">Next</a></p> <ul> <li><a href="#faq">Appendix A: PuTTY FAQ</a> <ul> <li><a href="#faq-intro">A.1 Introduction</a> <ul> <li><a href="#faq-what">A.1.1 What is PuTTY?</a></li> </ul></li> <li><a href="#faq-support">A.2 Features supported in PuTTY</a> <ul> <li><a href="#faq-ssh2">A.2.1 Does PuTTY support SSH-2?</a></li> <li><a href="#faq-ssh2-keyfmt">A.2.2 Does PuTTY support reading OpenSSH or <code>ssh.com</code> SSH-2 private key files?</a></li> <li><a href="#faq-ssh1">A.2.3 Does PuTTY support SSH-1?</a></li> <li><a href="#faq-localecho">A.2.4 Does PuTTY support local echo?</a></li> <li><a href="#faq-savedsettings">A.2.5 Does PuTTY support storing settings, so I don't have to change them every time?</a></li> <li><a href="#faq-disksettings">A.2.6 Does PuTTY support storing its settings in a disk file?</a></li> <li><a href="#faq-fullscreen">A.2.7 Does PuTTY support full-screen mode, like a DOS box?</a></li> <li><a href="#faq-password-remember">A.2.8 Does PuTTY have the ability to remember my password so I don't have to type it every time?</a></li> <li><a href="#faq-hostkeys">A.2.9 Is there an option to turn off the annoying host key prompts?</a></li> <li><a href="#faq-server">A.2.10 Will you write an SSH server for the PuTTY suite, to go with the client?</a></li> <li><a href="#faq-pscp-ascii">A.2.11 Can PSCP or PSFTP transfer files in ASCII mode?</a></li> </ul></li> <li><a href="#faq-ports">A.3 Ports to other operating systems</a> <ul> <li><a href="#faq-ports-general">A.3.1 What ports of PuTTY exist?</a></li> <li><a href="#faq-unix">A.3.2 Is there a port to Unix?</a></li> <li><a href="#faq-unix-why">A.3.3 What's the point of the Unix port? Unix has OpenSSH.</a></li> <li><a href="#faq-wince">A.3.4 Will there be a port to Windows CE or PocketPC?</a></li> <li><a href="#faq-win31">A.3.5 Is there a port to Windows 3.1?</a></li> <li><a href="#faq-mac-port">A.3.6 Will there be a port to the Mac?</a></li> <li><a href="#faq-epoc">A.3.7 Will there be a port to EPOC?</a></li> <li><a href="#faq-iphone">A.3.8 Will there be a port to the iPhone?</a></li> </ul></li> <li><a href="#faq-embedding">A.4 Embedding PuTTY in other programs</a> <ul> <li><a href="#faq-dll">A.4.1 Is the SSH or Telnet code available as a DLL?</a></li> <li><a href="#faq-vb">A.4.2 Is the SSH or Telnet code available as a Visual Basic component?</a></li> <li><a href="#faq-ipc">A.4.3 How can I use PuTTY to make an SSH connection from within another program?</a></li> </ul></li> <li><a href="#faq-details">A.5 Details of PuTTY's operation</a> <ul> <li><a href="#faq-term">A.5.1 What terminal type does PuTTY use?</a></li> <li><a href="#faq-settings">A.5.2 Where does PuTTY store its data?</a></li> </ul></li> <li><a href="#faq-howto">A.6 HOWTO questions</a> <ul> <li><a href="#faq-login">A.6.1 What login name / password should I use?</a></li> <li><a href="#faq-commands">A.6.2 What commands can I type into my PuTTY terminal window?</a></li> <li><a href="#faq-startmax">A.6.3 How can I make PuTTY start up maximised?</a></li> <li><a href="#faq-startsess">A.6.4 How can I create a Windows shortcut to start a particular saved session directly?</a></li> <li><a href="#faq-startssh">A.6.5 How can I start an SSH session straight from the command line?</a></li> <li><a href="#faq-cutpaste">A.6.6 How do I copy and paste between PuTTY and other Windows applications?</a></li> <li><a href="#faq-options">A.6.7 How do I use all PuTTY's features (public keys, proxying, cipher selection, etc.) in PSCP, PSFTP and Plink?</a></li> <li><a href="#faq-pscp">A.6.8 How do I use PSCP.EXE? When I double-click it gives me a command prompt window which then closes instantly.</a></li> <li><a href="#faq-pscp-spaces">A.6.9 How do I use PSCP to copy a file whose name has spaces in?</a></li> </ul></li> <li><a href="#faq-trouble">A.7 Troubleshooting</a> <ul> <li><a href="#faq-incorrect-mac">A.7.1 Why do I see &#8216;Incorrect MAC received on packet&#8217;?</a></li> <li><a href="#faq-pscp-protocol">A.7.2 Why do I see &#8216;Fatal: Protocol error: Expected control record&#8217; in PSCP?</a></li> <li><a href="#faq-colours">A.7.3 I clicked on a colour in the Colours panel, and the colour didn't change in my terminal.</a></li> <li><a href="#faq-winsock2">A.7.4 Plink on Windows 95 says it can't find <code>WS2_32.DLL</code>.</a></li> <li><a href="#faq-outofmem">A.7.5 After trying to establish an SSH-2 connection, PuTTY says &#8216;Out of memory&#8217; and dies.</a></li> <li><a href="#faq-outofmem2">A.7.6 When attempting a file transfer, either PSCP or PSFTP says &#8216;Out of memory&#8217; and dies.</a></li> <li><a href="#faq-psftp-slow">A.7.7 PSFTP transfers files much slower than PSCP.</a></li> <li><a href="#faq-bce">A.7.8 When I run full-colour applications, I see areas of black space where colour ought to be, or vice versa.</a></li> <li><a href="#faq-resetterm">A.7.9 When I change some terminal settings, nothing happens.</a></li> <li><a href="#faq-idleout">A.7.10 My PuTTY sessions unexpectedly close after they are idle for a while.</a></li> <li><a href="#faq-timeout">A.7.11 PuTTY's network connections time out too quickly when network connectivity is temporarily lost.</a></li> <li><a href="#faq-puttyputty">A.7.12 When I <code>cat</code> a binary file, I get &#8216;PuTTYPuTTYPuTTY&#8217; on my command line.</a></li> <li><a href="#faq-wintitle">A.7.13 When I <code>cat</code> a binary file, my window title changes to a nonsense string.</a></li> <li><a href="#faq-password-fails">A.7.14 My keyboard stops working once PuTTY displays the password prompt.</a></li> <li><a href="#faq-keyboard">A.7.15 One or more function keys don't do what I expected in a server-side application.</a></li> <li><a href="#faq-openssh-bad-openssl">A.7.16 Since my SSH server was upgraded to OpenSSH 3.1p1/3.4p1, I can no longer connect with PuTTY.</a></li> <li><a href="#faq-ssh2key-ssh1conn">A.7.17 Why do I see &#8216;Couldn't load private key from ...&#8217;? Why can PuTTYgen load my key but not PuTTY?</a></li> <li><a href="#faq-rh8-utf8">A.7.18 When I'm connected to a Red Hat Linux 8.0 system, some characters don't display properly.</a></li> <li><a href="#faq-screen">A.7.19 Since I upgraded to PuTTY 0.54, the scrollback has stopped working when I run <code>screen</code>.</a></li> <li><a href="#faq-alternate-localhost">A.7.20 Since I upgraded Windows XP to Service Pack 2, I can't use addresses like <code>127.0.0.2</code>.</a></li> <li><a href="#faq-missing-slash">A.7.21 PSFTP commands seem to be missing a directory separator (slash).</a></li> <li><a href="#faq-connaborted">A.7.22 Do you want to hear about &#8216;Software caused connection abort&#8217;?</a></li> <li><a href="#faq-rekey">A.7.23 My SSH-2 session locks up for a few seconds every so often.</a></li> <li><a href="#faq-xpwontrun">A.7.24 PuTTY fails to start up. Windows claims that &#8216;the application configuration is incorrect&#8217;.</a></li> </ul></li> <li><a href="#faq-secure">A.8 Security questions</a> <ul> <li><a href="#faq-publicpc">A.8.1 Is it safe for me to download PuTTY and use it on a public PC?</a></li> <li><a href="#faq-cleanup">A.8.2 What does PuTTY leave on a system? How can I clean up after it?</a></li> <li><a href="#faq-dsa">A.8.3 How come PuTTY now supports DSA, when the website used to say how insecure it was?</a></li> <li><a href="#faq-virtuallock">A.8.4 Couldn't Pageant use <code>VirtualLock()</code> to stop private keys being written to disk?</a></li> </ul></li> <li><a href="#faq-admin">A.9 Administrative questions</a> <ul> <li><a href="#faq-domain">A.9.1 Would you like me to register you a nicer domain name?</a></li> <li><a href="#faq-webhosting">A.9.2 Would you like free web hosting for the PuTTY web site?</a></li> <li><a href="#faq-link">A.9.3 Would you link to my web site from the PuTTY web site?</a></li> <li><a href="#faq-sourceforge">A.9.4 Why don't you move PuTTY to SourceForge?</a></li> <li><a href="#faq-mailinglist1">A.9.5 Why can't I subscribe to the putty-bugs mailing list?</a></li> <li><a href="#faq-mailinglist2">A.9.6 If putty-bugs isn't a general-subscription mailing list, what is?</a></li> <li><a href="#faq-donations">A.9.7 How can I donate to PuTTY development?</a></li> <li><a href="#faq-permission">A.9.8 Can I have permission to put PuTTY on a cover disk / distribute it with other software / etc?</a></li> <li><a href="#faq-indemnity">A.9.9 Can you sign an agreement indemnifying us against security problems in PuTTY?</a></li> <li><a href="#faq-permission-form">A.9.10 Can you sign this form granting us permission to use/distribute PuTTY?</a></li> <li><a href="#faq-permission-future">A.9.11 Can you write us a formal notice of permission to use PuTTY?</a></li> <li><a href="#faq-permission-general">A.9.12 Can you sign <em>anything</em> for us?</a></li> <li><a href="#faq-permission-assurance">A.9.13 If you won't sign anything, can you give us some sort of assurance that you won't make PuTTY closed-source in future?</a></li> <li><a href="#faq-export-cert">A.9.14 Can you provide us with export control information / FIPS certification for PuTTY?</a></li> </ul></li> <li><a href="#faq-misc">A.10 Miscellaneous questions</a> <ul> <li><a href="#faq-openssh">A.10.1 Is PuTTY a port of OpenSSH, or based on OpenSSH or OpenSSL?</a></li> <li><a href="#faq-sillyputty">A.10.2 Where can I buy silly putty?</a></li> <li><a href="#faq-meaning">A.10.3 What does &#8216;PuTTY&#8217; mean?</a></li> <li><a href="#faq-pronounce">A.10.4 How do I pronounce &#8216;PuTTY&#8217;?</a></li> </ul></li> </ul></li> </ul> <h1><a name="faq"></a><a name="AA"></a>Appendix A: PuTTY <a name="i0"></a>FAQ</h1> <p> This FAQ is published on the PuTTY web site, and also provided as an appendix in the manual. </p> <h2><a name="faq-intro"></a><a name="SA.1"></a>A.1 Introduction</h2> <h3><a name="faq-what"></a><a name="QA.1.1"></a>A.1.1 What is PuTTY?</h3> <p> PuTTY is a client program for the SSH, Telnet and Rlogin network protocols. </p> <p> These protocols are all used to run a remote session on a computer, over a network. PuTTY implements the client end of that session: the end at which the session is displayed, rather than the end at which it runs. </p> <p> In really simple terms: you run PuTTY on a Windows machine, and tell it to connect to (for example) a Unix machine. PuTTY opens a window. Then, anything you type into that window is sent straight to the Unix machine, and everything the Unix machine sends back is displayed in the window. So you can work on the Unix machine as if you were sitting at its console, while actually sitting somewhere else. </p> <h2><a name="faq-support"></a><a name="SA.2"></a>A.2 Features supported in PuTTY</h2> <p> <a name="i1"></a>In general, if you want to know if PuTTY supports a particular feature, you should look for it on the <a href="http://www.chiark.greenend.org.uk/~sgtatham/putty/">PuTTY web site</a>. In particular: </p> <ul><li> try the <a href="http://www.chiark.greenend.org.uk/~sgtatham/putty/changes.html">changes page</a>, and see if you can find the feature on there. If a feature is listed there, it's been implemented. If it's listed as a change made <em>since</em> the latest version, it should be available in the development snapshots, in which case testing will be very welcome. </li> <li> try the <a href="http://www.chiark.greenend.org.uk/~sgtatham/putty/wishlist/">Wishlist page</a>, and see if you can find the feature there. If it's on there, and not in the &#8216;Recently fixed&#8217; section, it probably <em>hasn't</em> been implemented. </li> </ul> <h3><a name="faq-ssh2"></a><a name="QA.2.1"></a>A.2.1 Does PuTTY support SSH-2?</h3> <p> Yes. SSH-2 support has been available in PuTTY since version 0.50. </p> <p> Public key authentication (both RSA and DSA) in SSH-2 is new in version 0.52. </p> <h3><a name="faq-ssh2-keyfmt"></a><a name="QA.2.2"></a>A.2.2 Does PuTTY support reading OpenSSH or <code>ssh.com</code> SSH-2 private key files?</h3> <p> PuTTY doesn't support this natively (see <a href="http://www.chiark.greenend.org.uk/~sgtatham/putty/wishlist/key-formats-natively.html">the wishlist entry</a> for reasons why not), but as of 0.53 PuTTYgen can convert both OpenSSH and <code>ssh.com</code> private key files into PuTTY's format. </p> <h3><a name="faq-ssh1"></a><a name="QA.2.3"></a>A.2.3 Does PuTTY support SSH-1?</h3> <p> Yes. SSH-1 support has always been available in PuTTY. </p> <h3><a name="faq-localecho"></a><a name="QA.2.4"></a>A.2.4 Does PuTTY support <a name="i2"></a>local echo?</h3> <p> Yes. Version 0.52 has proper support for local echo. </p> <p> In version 0.51 and before, local echo could not be separated from local line editing (where you type a line of text locally, and it is not sent to the server until you press Return, so you have the chance to edit it and correct mistakes <em>before</em> the server sees it). New in version 0.52, local echo and local line editing are separate options, and by default PuTTY will try to determine automatically whether to enable them or not, based on which protocol you have selected and also based on hints from the server. If you have a problem with PuTTY's default choice, you can force each option to be enabled or disabled as you choose. The controls are in the Terminal panel, in the section marked &#8216;Line discipline options&#8217;. </p> <h3><a name="faq-savedsettings"></a><a name="QA.2.5"></a>A.2.5 Does PuTTY support storing settings, so I don't have to change them every time?</h3> <p> Yes, all of PuTTY's settings can be saved in named session profiles. You can also change the default settings that are used for new sessions. See <a href="Chapter4.html#config-saving">section 4.1.2</a> in the documentation for how to do this. </p> <h3><a name="faq-disksettings"></a><a name="QA.2.6"></a>A.2.6 Does PuTTY support storing its settings in a disk file?</h3> <p> Not at present, although <a href="Chapter4.html#config-file">section 4.27</a> in the documentation gives a method of achieving the same effect. </p> <h3><a name="faq-fullscreen"></a><a name="QA.2.7"></a>A.2.7 Does PuTTY support full-screen mode, like a DOS box?</h3> <p> Yes; this is a new feature in version 0.52. </p> <h3><a name="faq-password-remember"></a><a name="QA.2.8"></a>A.2.8 Does PuTTY have the ability to <a name="i3"></a>remember my password so I don't have to type it every time?</h3> <p> No, it doesn't. </p> <p> Remembering your password is a bad plan for obvious security reasons: anyone who gains access to your machine while you're away from your desk can find out the remembered password, and use it, abuse it or change it. </p> <p> In addition, it's not even <em>possible</em> for PuTTY to automatically send your password in a Telnet session, because Telnet doesn't give the client software any indication of which part of the login process is the password prompt. PuTTY would have to guess, by looking for words like &#8216;password&#8217; in the session data; and if your login program is written in something other than English, this won't work. </p> <p> In SSH, remembering your password would be possible in theory, but there doesn't seem to be much point since SSH supports public key authentication, which is more flexible and more secure. See <a href="Chapter8.html#pubkey">chapter 8</a> in the documentation for a full discussion of public key authentication. </p> <h3><a name="faq-hostkeys"></a><a name="QA.2.9"></a>A.2.9 Is there an option to turn off the <a name="i4"></a>annoying host key prompts?</h3> <p> No, there isn't. And there won't be. Even if you write it yourself and send us the patch, we won't accept it. </p> <p> Those annoying host key prompts are the <em>whole point</em> of SSH. Without them, all the cryptographic technology SSH uses to secure your session is doing nothing more than making an attacker's job slightly harder; instead of sitting between you and the server with a packet sniffer, the attacker must actually subvert a router and start modifying the packets going back and forth. But that's not all that much harder than just sniffing; and without host key checking, it will go completely undetected by client or server. </p> <p> Host key checking is your guarantee that the encryption you put on your data at the client end is the <em>same</em> encryption taken off the data at the server end; it's your guarantee that it hasn't been removed and replaced somewhere on the way. Host key checking makes the attacker's job <em>astronomically</em> hard, compared to packet sniffing, and even compared to subverting a router. Instead of applying a little intelligence and keeping an eye on Bugtraq, the attacker must now perform a brute-force attack against at least one military-strength cipher. That insignificant host key prompt really does make <em>that</em> much difference. </p> <p> If you're having a specific problem with host key checking - perhaps you want an automated batch job to make use of PSCP or Plink, and the interactive host key prompt is hanging the batch process - then the right way to fix it is to add the correct host key to the Registry in advance. That way, you retain the <em>important</em> feature of host key checking: the right key will be accepted and the wrong ones will not. Adding an option to turn host key checking off completely is the wrong solution and we will not do it. </p> <p> If you have host keys available in the common <a name="i5"></a><code>known_hosts</code> format, we have a script called <a href="http://svn.tartarus.org/sgt/putty/contrib/kh2reg.py?view=markup"><code>kh2reg.py</code></a> to convert them to a Windows .REG file, which can be installed ahead of time by double-clicking or using <code>REGEDIT</code>. </p> <h3><a name="faq-server"></a><a name="QA.2.10"></a>A.2.10 Will you write an SSH server for the PuTTY suite, to go with the client?</h3> <p> No. The only reason we might want to would be if we could easily re-use existing code and significantly cut down the effort. We don't believe this is the case; there just isn't enough common ground between an SSH client and server to make it worthwhile. </p> <p> If someone else wants to use bits of PuTTY in the process of writing a Windows SSH server, they'd be perfectly welcome to of course, but I really can't see it being a lot less effort for us to do that than it would be for us to write a server from the ground up. We don't have time, and we don't have motivation. The code is available if anyone else wants to try it. </p> <h3><a name="faq-pscp-ascii"></a><a name="QA.2.11"></a>A.2.11 Can PSCP or PSFTP transfer files in <a name="i6"></a>ASCII mode?</h3> <p> Unfortunately not. </p> <p> Until recently, this was a limitation of the file transfer protocols: the SCP and SFTP protocols had no notion of transferring a file in anything other than binary mode. (This is still true of SCP.) </p> <p> The current draft protocol spec of SFTP proposes a means of implementing ASCII transfer. At some point PSCP/PSFTP may implement this proposal. </p> <h2><a name="faq-ports"></a><a name="SA.3"></a>A.3 Ports to other operating systems</h2> <p> The eventual goal is for PuTTY to be a multi-platform program, able to run on at least Windows, Mac OS and Unix. </p> <p> Porting will become easier once PuTTY has a generalised porting layer, drawing a clear line between platform-dependent and platform-independent code. The general intention was for this porting layer to evolve naturally as part of the process of doing the first port; a Unix port has now been released and the plan seems to be working so far. </p> <h3><a name="faq-ports-general"></a><a name="QA.3.1"></a>A.3.1 What ports of PuTTY exist?</h3> <p> Currently, release versions of PuTTY tools only run on full Win32 systems and Unix. &#8216;<a name="i7"></a>Win32&#8217; includes versions of Windows from Windows 95 onwards (as opposed to the 16-bit Windows 3.1; see <a href="#faq-win31">question A.3.5</a>), up to and including Windows 7; and we know of no reason why PuTTY should not continue to work on future versions of Windows. </p> <p> The Windows executables we provide are for the 32-bit &#8216;<a name="i8"></a>x86&#8217; processor architecture, but they should work fine on 64-bit processors that are backward-compatible with that architecture. (We used to also provide executables for Windows for the Alpha processor, but stopped after 0.58 due to lack of interest.) </p> <p> In the development code, partial ports to the Mac OSes exist (see <a href="#faq-mac-port">question A.3.6</a>). </p> <p> Currently PuTTY does <em>not</em> run on Windows CE (see <a href="#faq-wince">question A.3.4</a>). </p> <p> We do not have release-quality ports for any other systems at the present time. If anyone told you we had an EPOC port, or an iPaq port, or any other port of PuTTY, they were mistaken. We don't. </p> <p> There are some third-party ports to various platforms, mentioned on the <a href="http://www.chiark.greenend.org.uk/~sgtatham/putty/links.html">Links page of our website</a>. </p> <h3><a name="faq-unix"></a><a name="QA.3.2"></a>A.3.2 <a name="i9"></a>Is there a port to Unix?</h3> <p> As of 0.54, there are Unix ports of most of the traditional PuTTY tools, and also one entirely new application. </p> <p> If you look at the source release, you should find a <code>unix</code> subdirectory. There are a couple of ways of building it, including the usual <code>configure</code>/<code>make</code>; see the file <code>README</code> in the source distribution. This should build you Unix ports of Plink, PuTTY itself, PuTTYgen, PSCP, PSFTP, and also <a name="i10"></a><code>pterm</code> - an <code>xterm</code>-type program which supports the same terminal emulation as PuTTY. We do not yet have a Unix port of Pageant. </p> <p> If you don't have <a name="i11"></a>Gtk, you should still be able to build the command-line tools. </p> <p> Note that Unix PuTTY has mostly only been tested on Linux so far; portability problems such as BSD-style ptys or different header file requirements are expected. </p> <h3><a name="faq-unix-why"></a><a name="QA.3.3"></a>A.3.3 What's the point of the Unix port? Unix has OpenSSH.</h3> <p> All sorts of little things. <code>pterm</code> is directly useful to anyone who prefers PuTTY's terminal emulation to <code>xterm</code>'s, which at least some people do. Unix Plink has apparently found a niche among people who find the complexity of OpenSSL makes OpenSSH hard to install (and who don't mind Plink not having as many features). Some users want to generate a large number of SSH keys on Unix and then copy them all into PuTTY, and the Unix PuTTYgen should allow them to automate that conversion process. </p> <p> There were development advantages as well; porting PuTTY to Unix was a valuable path-finding effort for other future ports, and also allowed us to use the excellent Linux tool <a href="http://valgrind.kde.org/">Valgrind</a> to help with debugging, which has already improved PuTTY's stability on <em>all</em> platforms. </p> <p> However, if you're a Unix user and you can see no reason to switch from OpenSSH to PuTTY/Plink, then you're probably right. We don't expect our Unix port to be the right thing for everybody. </p> <h3><a name="faq-wince"></a><a name="QA.3.4"></a>A.3.4 Will there be a port to Windows CE or PocketPC?</h3> <p> We have done some work on such a port, but it only reached an early stage, and certainly not a useful one. It's no longer being actively worked on. </p> <p> However, there's a third-party port at <a href="http://www.pocketputty.net/"><code>http://www.pocketputty.net/</code></a>. </p> <h3><a name="faq-win31"></a><a name="QA.3.5"></a>A.3.5 Is there a port to <a name="i12"></a>Windows 3.1?</h3> <p> PuTTY is a 32-bit application from the ground up, so it won't run on Windows 3.1 as a native 16-bit program; and it would be <em>very</em> hard to port it to do so, because of Windows 3.1's vile memory allocation mechanisms. </p> <p> However, it is possible in theory to compile the existing PuTTY source in such a way that it will run under <a name="i13"></a>Win32s (an extension to Windows 3.1 to let you run 32-bit programs). In order to do this you'll need the right kind of C compiler - modern versions of Visual C at least have stopped being backwards compatible to Win32s. Also, the last time we tried this it didn't work very well. </p> <p> If you're interested in running PuTTY under Windows 3.1, help and testing in this area would be very welcome! </p> <h3><a name="faq-mac-port"></a><a name="QA.3.6"></a>A.3.6 Will there be a port to the <a name="i14"></a>Mac?</h3> <p> There are several answers to this question: </p> <ul><li> The Unix/Gtk port is already fully working under Mac OS X as an X11 application. </li> <li> A native (Cocoa) Mac OS X port has been started. It's just about usable, but is of nowhere near release quality yet, and is likely to behave in unexpected ways. Currently it's unlikely to be completed unless someone steps in to help. </li> <li> A separate port to the classic Mac OS (pre-OSX) is also in progress; it too is not ready yet. </li> </ul> <h3><a name="faq-epoc"></a><a name="QA.3.7"></a>A.3.7 Will there be a port to EPOC?</h3> <p> I hope so, but given that ports aren't really progressing very fast even on systems the developers <em>do</em> already know how to program for, it might be a long time before any of us get round to learning a new system and doing the port for that. </p> <p> However, some of the work has been done by other people; see the <a href="http://www.chiark.greenend.org.uk/~sgtatham/putty/links.html">Links page of our website</a> for various third-party ports. </p> <h3><a name="faq-iphone"></a><a name="QA.3.8"></a>A.3.8 Will there be a port to the iPhone?</h3> <p> We have no plans to write such a port ourselves; none of us has an iPhone, and developing and publishing applications for it looks awkward and expensive. Such a port would probably depend upon the stalled Mac OS X port (see <a href="#faq-mac-port">question A.3.6</a>). </p> <p> However, there is a third-party SSH client for the iPhone and iPod&nbsp;Touch called <a href="http://www.instantcocoa.com/products/pTerm/">pTerm</a>, which is apparently based on PuTTY. (This is nothing to do with our similarly-named <code>pterm</code>, which is a standalone terminal emulator for Unix systems; see <a href="#faq-unix">question A.3.2</a>.) </p> <h2><a name="faq-embedding"></a><a name="SA.4"></a>A.4 Embedding PuTTY in other programs</h2> <h3><a name="faq-dll"></a><a name="QA.4.1"></a>A.4.1 Is the SSH or Telnet code available as a DLL?</h3> <p> No, it isn't. It would take a reasonable amount of rewriting for this to be possible, and since the PuTTY project itself doesn't believe in DLLs (they make installation more error-prone) none of us has taken the time to do it. </p> <p> Most of the code cleanup work would be a good thing to happen in general, so if anyone feels like helping, we wouldn't say no. </p> <p> See also <a href="http://www.chiark.greenend.org.uk/~sgtatham/putty/wishlist/dll-frontend.html">the wishlist entry</a>. </p> <h3><a name="faq-vb"></a><a name="QA.4.2"></a>A.4.2 Is the SSH or Telnet code available as a Visual Basic component?</h3> <p> No, it isn't. None of the PuTTY team uses Visual Basic, and none of us has any particular need to make SSH connections from a Visual Basic application. In addition, all the preliminary work to turn it into a DLL would be necessary first; and furthermore, we don't even know how to write VB components. </p> <p> If someone offers to do some of this work for us, we might consider it, but unless that happens I can't see VB integration being anywhere other than the very bottom of our priority list. </p> <h3><a name="faq-ipc"></a><a name="QA.4.3"></a>A.4.3 How can I use PuTTY to make an SSH connection from within another program?</h3> <p> Probably your best bet is to use Plink, the command-line connection tool. If you can start Plink as a second Windows process, and arrange for your primary process to be able to send data to the Plink process, and receive data from it, through pipes, then you should be able to make SSH connections from your program. </p> <p> This is what CVS for Windows does, for example. </p> <h2><a name="faq-details"></a><a name="SA.5"></a>A.5 Details of PuTTY's operation</h2> <h3><a name="faq-term"></a><a name="QA.5.1"></a>A.5.1 What <a name="i15"></a>terminal type does PuTTY use?</h3> <p> For most purposes, PuTTY can be considered to be an <code>xterm</code> terminal. </p> <p> PuTTY also supports some terminal <a name="i16"></a>control sequences not supported by the real <code>xterm</code>: notably the Linux console sequences that reconfigure the colour palette, and the title bar control sequences used by <a name="i17"></a><code>DECterm</code> (which are different from the <code>xterm</code> ones; PuTTY supports both). </p> <p> By default, PuTTY announces its terminal type to the server as <code>xterm</code>. If you have a problem with this, you can reconfigure it to say something else; <code>vt220</code> might help if you have trouble. </p> <h3><a name="faq-settings"></a><a name="QA.5.2"></a>A.5.2 Where does PuTTY store its data?</h3> <p> On Windows, PuTTY stores most of its data (saved sessions, SSH host keys) in the <a name="i18"></a>Registry. The precise location is </p> <pre><code>HKEY_CURRENT_USER\Software\SimonTatham\PuTTY </code></pre> <p> and within that area, saved sessions are stored under <code>Sessions</code> while host keys are stored under <code>SshHostKeys</code>. </p> <p> PuTTY also requires a random number seed file, to improve the unpredictability of randomly chosen data needed as part of the SSH cryptography. This is stored by default in a file called <a name="i19"></a><code>PUTTY.RND</code>; this is stored by default in the &#8216;Application Data&#8217; directory, or failing that, one of a number of fallback locations. If you want to change the location of the random number seed file, you can put your chosen pathname in the Registry, at </p> <pre><code>HKEY_CURRENT_USER\Software\SimonTatham\PuTTY\RandSeedFile </code></pre> <p> You can ask PuTTY to delete all this data; see <a href="#faq-cleanup">question A.8.2</a>. </p> <p> On Unix, PuTTY stores all of this data in a directory <code>~/.putty</code>. </p> <h2><a name="faq-howto"></a><a name="SA.6"></a>A.6 HOWTO questions</h2> <h3><a name="faq-login"></a><a name="QA.6.1"></a>A.6.1 What login name / password should I use?</h3> <p> This is not a question you should be asking <em>us</em>. </p> <p> PuTTY is a communications tool, for making connections to other computers. We maintain the tool; we <em>don't</em> administer any computers that you're likely to be able to use, in the same way that the people who make web browsers aren't responsible for most of the content you can view in them. We cannot help with questions of this sort. </p> <p> If you know the name of the computer you want to connect to, but don't know what login name or password to use, you should talk to whoever administers that computer. If you don't know who that is, see the next question for some possible ways to find out. </p> <h3><a name="faq-commands"></a><a name="QA.6.2"></a>A.6.2 <a name="i20"></a>What commands can I type into my PuTTY terminal window?</h3> <p> Again, this is not a question you should be asking <em>us</em>. You need to read the manuals, or ask the administrator, of <em>the computer you have connected to</em>. </p> <p> PuTTY does not process the commands you type into it. It's only a communications tool. It makes a connection to another computer; it passes the commands you type to that other computer; and it passes the other computer's responses back to you. Therefore, the precise range of commands you can use will not depend on PuTTY, but on what kind of computer you have connected to and what software is running on it. The PuTTY team cannot help you with that. </p> <p> (Think of PuTTY as being a bit like a telephone. If you phone somebody up and you don't know what language to speak to make them understand you, it isn't <em>the telephone company</em>'s job to find that out for you. We just provide the means for you to get in touch; making yourself understood is somebody else's problem.) </p> <p> If you are unsure of where to start looking for the administrator of your server, a good place to start might be to remember how you found out the host name in the PuTTY configuration. If you were given that host name by e-mail, for example, you could try asking the person who sent you that e-mail. If your company's IT department provided you with ready-made PuTTY saved sessions, then that IT department can probably also tell you something about what commands you can type during those sessions. But the PuTTY maintainer team does not administer any server you are likely to be connecting to, and cannot help you with questions of this type. </p> <h3><a name="faq-startmax"></a><a name="QA.6.3"></a>A.6.3 How can I make PuTTY start up <a name="i21"></a>maximised?</h3> <p> Create a Windows shortcut to start PuTTY from, and set it as &#8216;Run Maximized&#8217;. </p> <h3><a name="faq-startsess"></a><a name="QA.6.4"></a>A.6.4 How can I create a <a name="i22"></a>Windows shortcut to start a particular saved session directly?</h3> <p> To run a PuTTY session saved under the name &#8216;<code>mysession</code>&#8217;, create a Windows shortcut that invokes PuTTY with a command line like </p> <pre><code>\path\name\to\putty.exe -load "mysession" </code></pre> <p> (Note: prior to 0.53, the syntax was <code>@session</code>. This is now deprecated and may be removed at some point.) </p> <h3><a name="faq-startssh"></a><a name="QA.6.5"></a>A.6.5 How can I start an SSH session straight from the command line?</h3> <p> Use the command line <code>putty -ssh host.name</code>. Alternatively, create a saved session that specifies the SSH protocol, and start the saved session as shown in <a href="#faq-startsess">question A.6.4</a>. </p> <h3><a name="faq-cutpaste"></a><a name="QA.6.6"></a>A.6.6 How do I <a name="i23"></a>copy and paste between PuTTY and other Windows applications?</h3> <p> Copy and paste works similarly to the X Window System. You use the left mouse button to select text in the PuTTY window. The act of selection <em>automatically</em> copies the text to the clipboard: there is no need to press Ctrl-Ins or Ctrl-C or anything else. In fact, pressing Ctrl-C will send a Ctrl-C character to the other end of your connection (just like it does the rest of the time), which may have unpleasant effects. The <em>only</em> thing you need to do, to copy text to the clipboard, is to select it. </p> <p> To paste the clipboard contents into a PuTTY window, by default you click the right mouse button. If you have a three-button mouse and are used to X applications, you can configure pasting to be done by the middle button instead, but this is not the default because most Windows users don't have a middle button at all. </p> <p> You can also paste by pressing Shift-Ins. </p> <h3><a name="faq-options"></a><a name="QA.6.7"></a>A.6.7 How do I use all PuTTY's features (public keys, proxying, cipher selection, etc.) in PSCP, PSFTP and Plink?</h3> <p> Most major features (e.g., public keys, port forwarding) are available through command line options. See the documentation. </p> <p> Not all features are accessible from the command line yet, although we'd like to fix this. In the meantime, you can use most of PuTTY's features if you create a PuTTY saved session, and then use the name of the saved session on the command line in place of a hostname. This works for PSCP, PSFTP and Plink (but don't expect port forwarding in the file transfer applications!). </p> <h3><a name="faq-pscp"></a><a name="QA.6.8"></a>A.6.8 How do I use PSCP.EXE? When I double-click it gives me a command prompt window which then closes instantly.</h3> <p> PSCP is a command-line application, not a GUI application. If you run it without arguments, it will simply print a help message and terminate. </p> <p> To use PSCP properly, run it from a Command Prompt window. See <a href="Chapter5.html#pscp">chapter 5</a> in the documentation for more details. </p> <h3><a name="faq-pscp-spaces"></a><a name="QA.6.9"></a>A.6.9 <a name="i24"></a>How do I use PSCP to copy a file whose name has spaces in?</h3> <p> If PSCP is using the traditional SCP protocol, this is confusing. If you're specifying a file at the local end, you just use one set of quotes as you would normally do: </p> <pre><code>pscp "local filename with spaces" user@host: pscp user@host:myfile "local filename with spaces" </code></pre> <p> But if the filename you're specifying is on the <em>remote</em> side, you have to use backslashes and two sets of quotes: </p> <pre><code>pscp user@host:"\"remote filename with spaces\"" local_filename pscp local_filename user@host:"\"remote filename with spaces\"" </code></pre> <p> Worse still, in a remote-to-local copy you have to specify the local file name explicitly, otherwise PSCP will complain that they don't match (unless you specified the <code>-unsafe</code> option). The following command will give an error message: </p> <pre><code>c:\&gt;pscp user@host:"\"oo er\"" . warning: remote host tried to write to a file called 'oo er' when we requested a file called '"oo er"'. </code></pre> <p> Instead, you need to specify the local file name in full: </p> <pre><code>c:\&gt;pscp user@host:"\"oo er\"" "oo er" </code></pre> <p> If PSCP is using the newer SFTP protocol, none of this is a problem, and all filenames with spaces in are specified using a single pair of quotes in the obvious way: </p> <pre><code>pscp "local file" user@host: pscp user@host:"remote file" . </code></pre> <h2><a name="faq-trouble"></a><a name="SA.7"></a>A.7 Troubleshooting</h2> <h3><a name="faq-incorrect-mac"></a><a name="QA.7.1"></a>A.7.1 Why do I see &#8216;Incorrect MAC received on packet&#8217;?</h3> <p> One possible cause of this that used to be common is a bug in old SSH-2 servers distributed by <code>ssh.com</code>. (This is not the only possible cause; see <a href="Chapter10.html#errors-crc">section 10.12</a> in the documentation.) Version 2.3.0 and below of their SSH-2 server constructs Message Authentication Codes in the wrong way, and expects the client to construct them in the same wrong way. PuTTY constructs the MACs correctly by default, and hence these old servers will fail to work with it. </p> <p> If you are using PuTTY version 0.52 or better, this should work automatically: PuTTY should detect the buggy servers from their version number announcement, and automatically start to construct its MACs in the same incorrect manner as they do, so it will be able to work with them. </p> <p> If you are using PuTTY version 0.51 or below, you can enable the workaround by going to the SSH panel and ticking the box labelled &#8216;Imitate SSH2 MAC bug&#8217;. It's possible that you might have to do this with 0.52 as well, if a buggy server exists that PuTTY doesn't know about. </p> <p> In this context MAC stands for <a name="i25"></a>Message Authentication Code. It's a cryptographic term, and it has nothing at all to do with Ethernet MAC (Media Access Control) addresses. </p> <h3><a name="faq-pscp-protocol"></a><a name="QA.7.2"></a>A.7.2 Why do I see &#8216;Fatal: Protocol error: Expected control record&#8217; in PSCP?</h3> <p> This happens because PSCP was expecting to see data from the server that was part of the PSCP protocol exchange, and instead it saw data that it couldn't make any sense of at all. </p> <p> This almost always happens because the <a name="i26"></a>startup scripts in your account on the server machine are generating output. This is impossible for PSCP, or any other SCP client, to work around. You should never use startup files (<code>.bashrc</code>, <code>.cshrc</code> and so on) which generate output in non-interactive sessions. </p> <p> This is not actually a PuTTY problem. If PSCP fails in this way, then all other SCP clients are likely to fail in exactly the same way. The problem is at the server end. </p> <h3><a name="faq-colours"></a><a name="QA.7.3"></a>A.7.3 I clicked on a colour in the <a name="i27"></a>Colours panel, and the colour didn't change in my terminal.</h3> <p> That isn't how you're supposed to use the Colours panel. </p> <p> During the course of a session, PuTTY potentially uses <em>all</em> the colours listed in the Colours panel. It's not a question of using only one of them and you choosing which one; PuTTY will use them <em>all</em>. The purpose of the Colours panel is to let you adjust the appearance of all the colours. So to change the colour of the cursor, for example, you would select &#8216;Cursor Colour&#8217;, press the &#8216;Modify&#8217; button, and select a new colour from the dialog box that appeared. Similarly, if you want your session to appear in green, you should select &#8216;Default Foreground&#8217; and press &#8216;Modify&#8217;. Clicking on &#8216;ANSI Green&#8217; won't turn your session green; it will only allow you to adjust the <em>shade</em> of green used when PuTTY is instructed by the server to display green text. </p> <h3><a name="faq-winsock2"></a><a name="QA.7.4"></a>A.7.4 Plink on <a name="i28"></a>Windows 95 says it can't find <a name="i29"></a><code>WS2_32.DLL</code>.</h3> <p> Plink requires the extended Windows network library, WinSock version 2. This is installed as standard on Windows 98 and above, and on Windows NT, and even on later versions of Windows 95; but early Win95 installations don't have it. </p> <p> In order to use Plink on these systems, you will need to download the <a href="http://www.microsoft.com/windows95/downloads/contents/wuadmintools/s_wunetworkingtools/w95sockets2/">WinSock 2 upgrade</a>: </p> <pre><code>http://www.microsoft.com/windows95/downloads/contents/ wuadmintools/s_wunetworkingtools/w95sockets2/ </code></pre> <h3><a name="faq-outofmem"></a><a name="QA.7.5"></a>A.7.5 After trying to establish an SSH-2 connection, PuTTY says &#8216;<a name="i30"></a>Out of memory&#8217; and dies.</h3> <p> If this happens just while the connection is starting up, this often indicates that for some reason the client and server have failed to establish a session encryption key. Somehow, they have performed calculations that should have given each of them the same key, but have ended up with different keys; so data encrypted by one and decrypted by the other looks like random garbage. </p> <p> This causes an &#8216;out of memory&#8217; error because the first encrypted data PuTTY expects to see is the length of an SSH message. Normally this will be something well under 100 bytes. If the decryption has failed, PuTTY will see a completely random length in the region of two <em>gigabytes</em>, and will try to allocate enough memory to store this non-existent message. This will immediately lead to it thinking it doesn't have enough memory, and panicking. </p> <p> If this happens to you, it is quite likely to still be a PuTTY bug and you should report it (although it might be a bug in your SSH server instead); but it doesn't necessarily mean you've actually run out of memory. </p> <h3><a name="faq-outofmem2"></a><a name="QA.7.6"></a>A.7.6 When attempting a file transfer, either PSCP or PSFTP says &#8216;<a name="i31"></a>Out of memory&#8217; and dies.</h3> <p> This is almost always caused by your <a name="i32"></a>login scripts on the server generating output. PSCP or PSFTP will receive that output when they were expecting to see the start of a file transfer protocol, and they will attempt to interpret the output as file-transfer protocol. This will usually lead to an &#8216;out of memory&#8217; error for much the same reasons as given in <a href="#faq-outofmem">question A.7.5</a>. </p> <p> This is a setup problem in your account on your server, <em>not</em> a PSCP/PSFTP bug. Your login scripts should <em>never</em> generate output during non-interactive sessions; secure file transfer is not the only form of remote access that will break if they do. </p> <p> On Unix, a simple fix is to ensure that all the parts of your login script that might generate output are in <code>.profile</code> (if you use a Bourne shell derivative) or <code>.login</code> (if you use a C shell). Putting them in more general files such as <code>.bashrc</code> or <code>.cshrc</code> is liable to lead to problems. </p> <h3><a name="faq-psftp-slow"></a><a name="QA.7.7"></a>A.7.7 PSFTP transfers files much slower than PSCP.</h3> <p> The throughput of PSFTP 0.54 should be much better than 0.53b and prior; we've added code to the SFTP backend to queue several blocks of data rather than waiting for an acknowledgement for each. (The SCP backend did not suffer from this performance issue because SCP is a much simpler protocol.) </p> <h3><a name="faq-bce"></a><a name="QA.7.8"></a>A.7.8 When I run full-colour applications, I see areas of black space where colour ought to be, or vice versa.</h3> <p> You almost certainly need to change the &#8216;Use <a name="i33"></a>background colour to erase screen&#8217; setting in the Terminal panel. If there is too much black space (the commoner situation), you should enable it, while if there is too much colour, you should disable it. (See <a href="Chapter4.html#config-erase">section 4.3.5</a>.) </p> <p> In old versions of PuTTY, this was disabled by default, and would not take effect until you reset the terminal (see <a href="#faq-resetterm">question A.7.9</a>). Since 0.54, it is enabled by default, and changes take effect immediately. </p> <h3><a name="faq-resetterm"></a><a name="QA.7.9"></a>A.7.9 When I change some terminal settings, nothing happens.</h3> <p> Some of the terminal options (notably <a name="i34"></a>Auto Wrap and background-colour screen erase) actually represent the <em>default</em> setting, rather than the currently active setting. The server can send sequences that modify these options in mid-session, but when the terminal is reset (by server action, or by you choosing &#8216;Reset Terminal&#8217; from the System menu) the defaults are restored. </p> <p> In versions 0.53b and prior, if you change one of these options in the middle of a session, you will find that the change does not immediately take effect. It will only take effect once you reset the terminal. </p> <p> In version 0.54, the behaviour has changed - changes to these settings take effect immediately. </p> <h3><a name="faq-idleout"></a><a name="QA.7.10"></a>A.7.10 My PuTTY sessions unexpectedly close after they are <a name="i35"></a>idle for a while.</h3> <p> Some types of <a name="i36"></a>firewall, and almost any router doing Network Address Translation (<a name="i37"></a>NAT, also known as IP masquerading), will forget about a connection through them if the connection does nothing for too long. This will cause the connection to be rudely cut off when contact is resumed. </p> <p> You can try to combat this by telling PuTTY to send <em>keepalives</em>: packets of data which have no effect on the actual session, but which reassure the router or firewall that the network connection is still active and worth remembering about. </p> <p> Keepalives don't solve everything, unfortunately; although they cause greater robustness against this sort of router, they can also cause a <em>loss</em> of robustness against network dropouts. See <a href="Chapter4.html#config-keepalive">section 4.13.1</a> in the documentation for more discussion of this. </p> <h3><a name="faq-timeout"></a><a name="QA.7.11"></a>A.7.11 PuTTY's network connections time out too quickly when <a name="i38"></a>network connectivity is temporarily lost.</h3> <p> This is a Windows problem, not a PuTTY problem. The timeout value can't be set on per application or per session basis. To increase the TCP timeout globally, you need to tinker with the Registry. </p> <p> On Windows 95, 98 or ME, the registry key you need to create or change is </p> <pre><code>HKEY_LOCAL_MACHINE\System\CurrentControlSet\Services\VxD\ MSTCP\MaxDataRetries </code></pre> <p> (it must be of type DWORD in Win95, or String in Win98/ME). (See MS Knowledge Base article <a href="http://support.microsoft.com/default.aspx?scid=kb;en-us;158474">158474</a> for more information.) </p> <p> On Windows NT, 2000, or XP, the registry key to create or change is </p> <pre><code>HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Services\Tcpip\ Parameters\TcpMaxDataRetransmissions </code></pre> <p> and it must be of type DWORD. (See MS Knowledge Base articles <a href="http://support.microsoft.com/default.aspx?scid=kb;en-us;120642">120642</a> and <a href="http://support.microsoft.com/default.aspx?scid=kb;en-us;314053">314053</a> for more information.) </p> <p> Set the key's value to something like 10. This will cause Windows to try harder to keep connections alive instead of abandoning them. </p> <h3><a name="faq-puttyputty"></a><a name="QA.7.12"></a>A.7.12 When I <code>cat</code> a binary file, I get &#8216;PuTTYPuTTYPuTTY&#8217; on my command line.</h3> <p> Don't do that, then. </p> <p> This is designed behaviour; when PuTTY receives the character Control-E from the remote server, it interprets it as a request to identify itself, and so it sends back the string &#8216;<code>PuTTY</code>&#8217; as if that string had been entered at the keyboard. Control-E should only be sent by programs that are prepared to deal with the response. Writing a binary file to your terminal is likely to output many Control-E characters, and cause this behaviour. Don't do it. It's a bad plan. </p> <p> To mitigate the effects, you could configure the answerback string to be empty (see <a href="Chapter4.html#config-answerback">section 4.3.7</a>); but writing binary files to your terminal is likely to cause various other unpleasant behaviour, so this is only a small remedy. </p> <h3><a name="faq-wintitle"></a><a name="QA.7.13"></a>A.7.13 When I <code>cat</code> a binary file, my <a name="i39"></a>window title changes to a nonsense string.</h3> <p> Don't do that, then. </p> <p> It is designed behaviour that PuTTY should have the ability to adjust the window title on instructions from the server. Normally the control sequence that does this should only be sent deliberately, by programs that know what they are doing and intend to put meaningful text in the window title. Writing a binary file to your terminal runs the risk of sending the same control sequence by accident, and cause unexpected changes in the window title. Don't do it. </p> <h3><a name="faq-password-fails"></a><a name="QA.7.14"></a>A.7.14 My <a name="i40"></a>keyboard stops working once PuTTY displays the <a name="i41"></a>password prompt.</h3> <p> No, it doesn't. PuTTY just doesn't display the password you type, so that someone looking at your screen can't see what it is. </p> <p> Unlike the Windows login prompts, PuTTY doesn't display the password as a row of asterisks either. This is so that someone looking at your screen can't even tell how <em>long</em> your password is, which might be valuable information. </p> <h3><a name="faq-keyboard"></a><a name="QA.7.15"></a>A.7.15 One or more <a name="i42"></a><a name="i43"></a>function keys don't do what I expected in a server-side application.</h3> <p> If you've already tried all the relevant options in the PuTTY Keyboard panel, you may need to mail the PuTTY maintainers and ask. </p> <p> It is <em>not</em> usually helpful just to tell us which application, which server operating system, and which key isn't working; in order to replicate the problem we would need to have a copy of every operating system, and every application, that anyone has ever complained about. </p> <p> PuTTY responds to function key presses by sending a sequence of control characters to the server. If a function key isn't doing what you expect, it's likely that the character sequence your application is expecting to receive is not the same as the one PuTTY is sending. Therefore what we really need to know is <em>what</em> sequence the application is expecting. </p> <p> The simplest way to investigate this is to find some other terminal environment, in which that function key <em>does</em> work; and then investigate what sequence the function key is sending in that situation. One reasonably easy way to do this on a <a name="i44"></a>Unix system is to type the command <a name="i45"></a><code>cat</code>, and then press the function key. This is likely to produce output of the form <code>^[[11~</code>. You can also do this in PuTTY, to find out what sequence the function key is producing in that. Then you can mail the PuTTY maintainers and tell us &#8216;I wanted the F1 key to send <code>^[[11~</code>, but instead it's sending <code>^[OP</code>, can this be done?&#8217;, or something similar. </p> <p> You should still read the <a href="http://www.chiark.greenend.org.uk/~sgtatham/putty/feedback.html">Feedback page</a> on the PuTTY website (also provided as <a href="AppendixB.html#feedback">appendix B</a> in the manual), and follow the guidelines contained in that. </p> <h3><a name="faq-openssh-bad-openssl"></a><a name="QA.7.16"></a>A.7.16 Since my SSH server was upgraded to <a name="i46"></a>OpenSSH 3.1p1/3.4p1, I can no longer connect with PuTTY.</h3> <p> There is a known problem when OpenSSH has been built against an incorrect version of OpenSSL; the quick workaround is to configure PuTTY to use SSH protocol 2 and the Blowfish cipher. </p> <p> For more details and OpenSSH patches, see <a href="http://bugzilla.mindrot.org/show_bug.cgi?id=138">bug 138</a> in the OpenSSH BTS. </p> <p> This is not a PuTTY-specific problem; if you try to connect with another client you'll likely have similar problems. (Although PuTTY's default cipher differs from many other clients.) </p> <p> <em>OpenSSH 3.1p1:</em> configurations known to be broken (and symptoms): </p> <ul><li> SSH-2 with AES cipher (PuTTY says &#8216;Assertion failed! Expression: (len &amp; 15) == 0&#8217; in <code>sshaes.c</code>, or &#8216;Out of memory&#8217;, or crashes) </li> <li> SSH-2 with 3DES (PuTTY says &#8216;Incorrect MAC received on packet&#8217;) </li> <li> SSH-1 with Blowfish (PuTTY says &#8216;Incorrect CRC received on packet&#8217;) </li> <li> SSH-1 with 3DES </li> </ul> <p> <em>OpenSSH 3.4p1:</em> as of 3.4p1, only the problem with SSH-1 and Blowfish remains. Rebuild your server, apply the patch linked to from bug 138 above, or use another cipher (e.g., 3DES) instead. </p> <p> <em>Other versions:</em> we occasionally get reports of the same symptom and workarounds with older versions of OpenSSH, although it's not clear the underlying cause is the same. </p> <h3><a name="faq-ssh2key-ssh1conn"></a><a name="QA.7.17"></a>A.7.17 Why do I see &#8216;Couldn't load private key from ...&#8217;? Why can PuTTYgen load my key but not PuTTY?</h3> <p> It's likely that you've generated an SSH protocol 2 key with PuTTYgen, but you're trying to use it in an SSH-1 connection. SSH-1 and SSH-2 keys have different formats, and (at least in 0.52) PuTTY's reporting of a key in the wrong format isn't optimal. </p> <p> To connect using SSH-2 to a server that supports both versions, you need to change the configuration from the default (see <a href="#faq-ssh2">question A.2.1</a>). </p> <h3><a name="faq-rh8-utf8"></a><a name="QA.7.18"></a>A.7.18 When I'm connected to a <a name="i47"></a>Red Hat Linux 8.0 system, some characters don't display properly.</h3> <p> A common complaint is that hyphens in man pages show up as a-acute. </p> <p> With release 8.0, Red Hat appear to have made <a name="i48"></a>UTF-8 the default character set. There appears to be no way for terminal emulators such as PuTTY to know this (as far as we know, the appropriate escape sequence to switch into UTF-8 mode isn't sent). </p> <p> A fix is to configure sessions to RH8 systems to use UTF-8 translation - see <a href="Chapter4.html#config-charset">section 4.10.1</a> in the documentation. (Note that if you use &#8216;Change Settings&#8217;, changes may not take place immediately - see <a href="#faq-resetterm">question A.7.9</a>.) </p> <p> If you really want to change the character set used by the server, the right place is <code>/etc/sysconfig/i18n</code>, but this shouldn't be necessary. </p> <h3><a name="faq-screen"></a><a name="QA.7.19"></a>A.7.19 Since I upgraded to PuTTY 0.54, the scrollback has stopped working when I run <code>screen</code>.</h3> <p> PuTTY's terminal emulator has always had the policy that when the &#8216;<a name="i49"></a>alternate screen&#8217; is in use, nothing is added to the scrollback. This is because the usual sorts of programs which use the alternate screen are things like text editors, which tend to scroll back and forth in the same document a lot; so (a) they would fill up the scrollback with a large amount of unhelpfully disordered text, and (b) they contain their <em>own</em> method for the user to scroll back to the bit they were interested in. We have generally found this policy to do the Right Thing in almost all situations. </p> <p> Unfortunately, <code>screen</code> is one exception: it uses the alternate screen, but it's still usually helpful to have PuTTY's scrollback continue working. The simplest solution is to go to the Features control panel and tick &#8216;Disable switching to alternate terminal screen&#8217;. (See <a href="Chapter4.html#config-features-altscreen">section 4.6.4</a> for more details.) Alternatively, you can tell <code>screen</code> itself not to use the alternate screen: the <a href="http://www4.informatik.uni-erlangen.de/~jnweiger/screen-faq.html"><code>screen</code> FAQ</a> suggests adding the line &#8216;<code>termcapinfo xterm ti@:te@</code>&#8217; to your <code>.screenrc</code> file. </p> <p> The reason why this only started to be a problem in 0.54 is because <code>screen</code> typically uses an unusual control sequence to switch to the alternate screen, and previous versions of PuTTY did not support this sequence. </p> <h3><a name="faq-alternate-localhost"></a><a name="QA.7.20"></a>A.7.20 Since I upgraded <a name="i50"></a>Windows XP to Service Pack 2, I can't use addresses like <code>127.0.0.2</code>.</h3> <p> Some people who ask PuTTY to listen on <a name="i51"></a>localhost addresses other than <code>127.0.0.1</code> to forward services such as <a name="i52"></a>SMB and <a name="i53"></a>Windows Terminal Services have found that doing so no longer works since they upgraded to WinXP SP2. </p> <p> This is apparently an issue with SP2 that is acknowledged by Microsoft in MS Knowledge Base article <a href="http://support.microsoft.com/default.aspx?scid=kb;en-us;884020">884020</a>. The article links to a fix you can download. </p> <p> (<em>However</em>, we've been told that SP2 <em>also</em> fixes the bug that means you need to use non-<code>127.0.0.1</code> addresses to forward Terminal Services in the first place.) </p> <h3><a name="faq-missing-slash"></a><a name="QA.7.21"></a>A.7.21 PSFTP commands seem to be missing a directory separator (slash).</h3> <p> Some people have reported the following incorrect behaviour with PSFTP: </p> <pre><code>psftp&gt; <em>pwd</em> Remote directory is /dir1/dir2 psftp&gt; <em>get filename.ext</em> /dir1/dir2filename.ext: no such file or directory </code></pre> <p> This is not a bug in PSFTP. There is a known bug in some versions of portable <a name="i54"></a>OpenSSH (<a href="http://bugzilla.mindrot.org/show_bug.cgi?id=697">bug 697</a>) that causes these symptoms; it appears to have been introduced around 3.7.x. It manifests only on certain platforms (AIX is what has been reported to us). </p> <p> There is a patch for OpenSSH attached to that bug; it's also fixed in recent versions of portable OpenSSH (from around 3.8). </p> <h3><a name="faq-connaborted"></a><a name="QA.7.22"></a>A.7.22 Do you want to hear about &#8216;Software caused connection abort&#8217;?</h3> <p> In the documentation for PuTTY 0.53 and 0.53b, we mentioned that we'd like to hear about any occurrences of this error. Since the release of PuTTY 0.54, however, we've been convinced that this error doesn't indicate that PuTTY's doing anything wrong, and we don't need to hear about further occurrences. See <a href="Chapter10.html#errors-connaborted">section 10.15</a> for our current documentation of this error. </p> <h3><a name="faq-rekey"></a><a name="QA.7.23"></a>A.7.23 My SSH-2 session <a name="i55"></a>locks up for a few seconds every so often.</h3> <p> Recent versions of PuTTY automatically initiate <a name="i56"></a>repeat key exchange once per hour, to improve session security. If your client or server machine is slow, you may experience this as a delay of anything up to thirty seconds or so. </p> <p> These <a name="i57"></a>delays are inconvenient, but they are there for your protection. If they really cause you a problem, you can choose to turn off periodic rekeying using the &#8216;Kex&#8217; configuration panel (see <a href="Chapter4.html#config-ssh-kex">section 4.19</a>), but be aware that you will be sacrificing security for this. (Falling back to SSH-1 would also remove the delays, but would lose a <em>lot</em> more security still. We do not recommend it.) </p> <h3><a name="faq-xpwontrun"></a><a name="QA.7.24"></a>A.7.24 PuTTY fails to start up. Windows claims that &#8216;the application configuration is incorrect&#8217;.</h3> <p> This is caused by a bug in certain versions of <a name="i58"></a>Windows XP which is triggered by PuTTY 0.58. This was fixed in 0.59. The <a href="http://www.chiark.greenend.org.uk/~sgtatham/putty/wishlist/xp-wont-run">&#8216;xp-wont-run&#8217;</a> entry in PuTTY's wishlist has more details. </p> <h2><a name="faq-secure"></a><a name="SA.8"></a>A.8 Security questions</h2> <h3><a name="faq-publicpc"></a><a name="QA.8.1"></a>A.8.1 Is it safe for me to download PuTTY and use it on a public PC?</h3> <p> It depends on whether you trust that PC. If you don't trust the public PC, don't use PuTTY on it, and don't use any other software you plan to type passwords into either. It might be watching your keystrokes, or it might tamper with the PuTTY binary you download. There is <em>no</em> program safe enough that you can run it on an actively malicious PC and get away with typing passwords into it. </p> <p> If you do trust the PC, then it's probably OK to use PuTTY on it (but if you don't trust the network, then the PuTTY download might be tampered with, so it would be better to carry PuTTY with you on a floppy). </p> <h3><a name="faq-cleanup"></a><a name="QA.8.2"></a>A.8.2 What does PuTTY leave on a system? How can I <a name="i59"></a>clean up after it?</h3> <p> PuTTY will leave some Registry entries, and a random seed file, on the PC (see <a href="#faq-settings">question A.5.2</a>). If you are using PuTTY on a public PC, or somebody else's PC, you might want to clean these up when you leave. You can do that automatically, by running the command <code>putty -cleanup</code>. (Note that this only removes settings for the currently logged-in user on <a name="i60"></a>multi-user systems.) </p> <p> If PuTTY was installed from the installer package, it will also appear in &#8216;Add/Remove Programs&#8217;. Older versions of the uninstaller do not remove the above-mentioned registry entries and file. </p> <h3><a name="faq-dsa"></a><a name="QA.8.3"></a>A.8.3 How come PuTTY now supports <a name="i61"></a>DSA, when the website used to say how insecure it was?</h3> <p> DSA has a major weakness <em>if badly implemented</em>: it relies on a random number generator to far too great an extent. If the random number generator produces a number an attacker can predict, the DSA private key is exposed - meaning that the attacker can log in as you on all systems that accept that key. </p> <p> The PuTTY policy changed because the developers were informed of ways to implement DSA which do not suffer nearly as badly from this weakness, and indeed which don't need to rely on random numbers at all. For this reason we now believe PuTTY's DSA implementation is probably OK. However, if you have the choice, we still recommend you use RSA instead. </p> <h3><a name="faq-virtuallock"></a><a name="QA.8.4"></a>A.8.4 Couldn't Pageant use <code>VirtualLock()</code> to stop private keys being written to disk?</h3> <p> Unfortunately not. The <code>VirtualLock()</code> function in the Windows API doesn't do a proper job: it may prevent small pieces of a process's memory from being paged to disk while the process is running, but it doesn't stop the process's memory as a whole from being swapped completely out to disk when the process is long-term inactive. And Pageant spends most of its time inactive. </p> <h2><a name="faq-admin"></a><a name="SA.9"></a>A.9 Administrative questions</h2> <h3><a name="faq-domain"></a><a name="QA.9.1"></a>A.9.1 Would you like me to register you a nicer domain name?</h3> <p> No, thank you. Even if you can find one (most of them seem to have been registered already, by people who didn't ask whether we actually wanted it before they applied), we're happy with the PuTTY web site being exactly where it is. It's not hard to find (just type &#8216;putty&#8217; into <a href="http://www.google.com/">google.com</a> and we're the first link returned), and we don't believe the administrative hassle of moving the site would be worth the benefit. </p> <p> In addition, if we <em>did</em> want a custom domain name, we would want to run it ourselves, so we knew for certain that it would continue to point where we wanted it, and wouldn't suddenly change or do strange things. Having it registered for us by a third party who we don't even know is not the best way to achieve this. </p> <h3><a name="faq-webhosting"></a><a name="QA.9.2"></a>A.9.2 Would you like free web hosting for the PuTTY web site?</h3> <p> We already have some, thanks. </p> <h3><a name="faq-link"></a><a name="QA.9.3"></a>A.9.3 Would you link to my web site from the PuTTY web site?</h3> <p> Only if the content of your web page is of definite direct interest to PuTTY users. If your content is unrelated, or only tangentially related, to PuTTY, then the link would simply be advertising for you. </p> <p> One very nice effect of the Google ranking mechanism is that by and large, the most popular web sites get the highest rankings. This means that when an ordinary person does a search, the top item in the search is very likely to be a high-quality site or the site they actually wanted, rather than the site which paid the most money for its ranking. </p> <p> The PuTTY web site is held in high esteem by Google, for precisely this reason: lots of people have linked to it simply because they like PuTTY, without us ever having to ask anyone to link to us. We feel that it would be an abuse of this esteem to use it to boost the ranking of random advertisers' web sites. If you want your web site to have a high Google ranking, we'd prefer that you achieve this the way we did - by being good enough at what you do that people will link to you simply because they like you. </p> <p> In particular, we aren't interested in trading links for money (see above), and we <em>certainly</em> aren't interested in trading links for other links (since we have no advertising on our web site, our Google ranking is not even directly worth anything to us). If we don't want to link to you for free, then we probably won't want to link to you at all. </p> <p> If you have software based on PuTTY, or specifically designed to interoperate with PuTTY, or in some other way of genuine interest to PuTTY users, then we will probably be happy to add a link to you on our Links page. And if you're running a particularly valuable mirror of the PuTTY web site, we might be interested in linking to you from our Mirrors page. </p> <h3><a name="faq-sourceforge"></a><a name="QA.9.4"></a>A.9.4 Why don't you move PuTTY to SourceForge?</h3> <p> Partly, because we don't want to move the web site location (see <a href="#faq-domain">question A.9.1</a>). </p> <p> Also, security reasons. PuTTY is a security product, and as such it is particularly important to guard the code and the web site against unauthorised modifications which might introduce subtle security flaws. Therefore, we prefer that the Subversion repository, web site and FTP site remain where they are, under the direct control of system administrators we know and trust personally, rather than being run by a large organisation full of people we've never met and which is known to have had breakins in the past. </p> <p> No offence to SourceForge; I think they do a wonderful job. But they're not ideal for everyone, and in particular they're not ideal for us. </p> <h3><a name="faq-mailinglist1"></a><a name="QA.9.5"></a>A.9.5 Why can't I subscribe to the putty-bugs mailing list?</h3> <p> Because you're not a member of the PuTTY core development team. The putty-bugs mailing list is not a general newsgroup-like discussion forum; it's a contact address for the core developers, and an <em>internal</em> mailing list for us to discuss things among ourselves. If we opened it up for everybody to subscribe to, it would turn into something more like a newsgroup and we would be completely overwhelmed by the volume of traffic. It's hard enough to keep up with the list as it is. </p> <h3><a name="faq-mailinglist2"></a><a name="QA.9.6"></a>A.9.6 If putty-bugs isn't a general-subscription mailing list, what is?</h3> <p> There isn't one, that we know of. </p> <p> If someone else wants to set up a mailing list or other forum for PuTTY users to help each other with common problems, that would be fine with us, though the PuTTY team would almost certainly not have the time to read it. It's probably better to use one of the established newsgroups for this purpose (see <a href="AppendixB.html#feedback-other-fora">section B.1.2</a>). </p> <h3><a name="faq-donations"></a><a name="QA.9.7"></a>A.9.7 How can I donate to PuTTY development?</h3> <p> Please, <em>please</em> don't feel you have to. PuTTY is completely free software, and not shareware. We think it's very important that <em>everybody</em> who wants to use PuTTY should be able to, whether they have any money or not; so the last thing we would want is for a PuTTY user to feel guilty because they haven't paid us any money. If you want to keep your money, please do keep it. We wouldn't dream of asking for any. </p> <p> Having said all that, if you still really <em>want</em> to give us money, we won't argue :-) The easiest way for us to accept donations is if you send money to <code>&lt;[email protected]&gt;</code> using PayPal (<a href="http://www.paypal.com/"><code>www.paypal.com</code></a>). If you don't like PayPal, talk to us; we can probably arrange some alternative means. </p> <p> Small donations (tens of dollars or tens of euros) will probably be spent on beer or curry, which helps motivate our volunteer team to continue doing this for the world. Larger donations will be spent on something that actually helps development, if we can find anything (perhaps new hardware, or a copy of Windows XP), but if we can't find anything then we'll just distribute the money among the developers. If you want to be sure your donation is going towards something worthwhile, ask us first. If you don't like these terms, feel perfectly free not to donate. We don't mind. </p> <h3><a name="faq-permission"></a><a name="QA.9.8"></a>A.9.8 Can I have permission to put PuTTY on a cover disk / distribute it with other software / etc?</h3> <p> Yes. For most things, you need not bother asking us explicitly for permission; our licence already grants you permission. </p> <p> See <a href="AppendixB.html#feedback-permission">section B.7</a> for more details. </p> <h3><a name="faq-indemnity"></a><a name="QA.9.9"></a>A.9.9 Can you sign an agreement indemnifying us against security problems in PuTTY?</h3> <p> No! </p> <p> A vendor of physical security products (e.g. locks) might plausibly be willing to accept financial liability for a product that failed to perform as advertised and resulted in damage (e.g. valuables being stolen). The reason they can afford to do this is because they sell a <em>lot</em> of units, and only a small proportion of them will fail; so they can meet their financial liability out of the income from all the rest of their sales, and still have enough left over to make a profit. Financial liability is intrinsically linked to selling your product for money. </p> <p> There are two reasons why PuTTY is not analogous to a physical lock in this context. One is that software products don't exhibit random variation: <em>if</em> PuTTY has a security hole (which does happen, although we do our utmost to prevent it and to respond quickly when it does), every copy of PuTTY will have the same hole, so it's likely to affect all the users at the same time. So even if our users were all paying us to use PuTTY, we wouldn't be able to <em>simultaneously</em> pay every affected user compensation in excess of the amount they had paid us in the first place. It just wouldn't work. </p> <p> The second, much more important, reason is that PuTTY users <em>don't</em> pay us. The PuTTY team does not have an income; it's a volunteer effort composed of people spending their spare time to try to write useful software. We aren't even a company or any kind of legally recognised organisation. We're just a bunch of people who happen to do some stuff in our spare time. </p> <p> Therefore, to ask us to assume financial liability is to ask us to assume a risk of having to pay it out of our own <em>personal</em> pockets: out of the same budget from which we buy food and clothes and pay our rent. That's more than we're willing to give. We're already giving a lot of our spare <em>time</em> to developing software for free; if we had to pay our own <em>money</em> to do it as well, we'd start to wonder why we were bothering. </p> <p> Free software fundamentally does not work on the basis of financial guarantees. Your guarantee of the software functioning correctly is simply that you have the source code and can check it before you use it. If you want to be sure there aren't any security holes, do a security audit of the PuTTY code, or hire a security engineer if you don't have the necessary skills yourself: instead of trying to ensure you can get compensation in the event of a disaster, try to ensure there isn't a disaster in the first place. </p> <p> If you <em>really</em> want financial security, see if you can find a security engineer who will take financial responsibility for the correctness of their review. (This might be less likely to suffer from the everything-failing-at-once problem mentioned above, because such an engineer would probably be reviewing a lot of <em>different</em> products which would tend to fail independently.) Failing that, see if you can persuade an insurance company to insure you against security incidents, and if the insurer demands it as a condition then get our code reviewed by a security engineer they're happy with. </p> <h3><a name="faq-permission-form"></a><a name="QA.9.10"></a>A.9.10 Can you sign this form granting us permission to use/distribute PuTTY?</h3> <p> If your form contains any clause along the lines of &#8216;the undersigned represents and warrants&#8217;, we're not going to sign it. This is particularly true if it asks us to warrant that PuTTY is secure; see <a href="#faq-indemnity">question A.9.9</a> for more discussion of this. But it doesn't really matter what we're supposed to be warranting: even if it's something we already believe is true, such as that we don't infringe any third-party copyright, we will not sign a document accepting any legal or financial liability. This is simply because the PuTTY development project has no income out of which to satisfy that liability, or pay legal costs, should it become necessary. We cannot afford to be sued. We are assuring you that <em>we have done our best</em>; if that isn't good enough for you, tough. </p> <p> The existing PuTTY licence document already gives you permission to use or distribute PuTTY in pretty much any way which does not involve pretending you wrote it or suing us if it goes wrong. We think that really ought to be enough for anybody. </p> <p> See also <a href="#faq-permission-general">question A.9.12</a> for another reason why we don't want to do this sort of thing. </p> <h3><a name="faq-permission-future"></a><a name="QA.9.11"></a>A.9.11 Can you write us a formal notice of permission to use PuTTY?</h3> <p> We could, in principle, but it isn't clear what use it would be. If you think there's a serious chance of one of the PuTTY copyright holders suing you (which we don't!), you would presumably want a signed notice from <em>all</em> of them; and we couldn't provide that even if we wanted to, because many of the copyright holders are people who contributed some code in the past and with whom we subsequently lost contact. Therefore the best we would be able to do <em>even in theory</em> would be to have the core development team sign the document, which wouldn't guarantee you that some other copyright holder might not sue. </p> <p> See also <a href="#faq-permission-general">question A.9.12</a> for another reason why we don't want to do this sort of thing. </p> <h3><a name="faq-permission-general"></a><a name="QA.9.12"></a>A.9.12 Can you sign <em>anything</em> for us?</h3> <p> Not unless there's an incredibly good reason. </p> <p> We are generally unwilling to set a precedent that involves us having to enter into individual agreements with PuTTY users. We estimate that we have literally <em>millions</em> of users, and we absolutely would not have time to go round signing specific agreements with every one of them. So if you want us to sign something specific for you, you might usefully stop to consider whether there's anything special that distinguishes you from 999,999 other users, and therefore any reason we should be willing to sign something for you without it setting such a precedent. </p> <p> If your company policy requires you to have an individual agreement with the supplier of any software you use, then your company policy is simply not well suited to using popular free software, and we urge you to consider this as a flaw in your policy. </p> <h3><a name="faq-permission-assurance"></a><a name="QA.9.13"></a>A.9.13 If you won't sign anything, can you give us some sort of assurance that you won't make PuTTY closed-source in future?</h3> <p> Yes and no. </p> <p> If what you want is an assurance that some <em>current version</em> of PuTTY which you've already downloaded will remain free, then you already have that assurance: it's called the PuTTY Licence. It grants you permission to use, distribute and copy the software to which it applies; once we've granted that permission (which we have), we can't just revoke it. </p> <p> On the other hand, if you want an assurance that <em>future</em> versions of PuTTY won't be closed-source, that's more difficult. We could in principle sign a document stating that we would never release a closed-source PuTTY, but that wouldn't assure you that we <em>would</em> keep releasing <em>open</em>-source PuTTYs: we would still have the option of ceasing to develop PuTTY at all, which would surely be even worse for you than making it closed-source! (And we almost certainly wouldn't <em>want</em> to sign a document guaranteeing that we would actually continue to do development work on PuTTY; we certainly wouldn't sign it for free. Documents like that are called contracts of employment, and are generally not signed except in return for a sizeable salary.) </p> <p> If we <em>were</em> to stop developing PuTTY, or to decide to make all future releases closed-source, then you would still be free to copy the last open release in accordance with the current licence, and in particular you could start your own fork of the project from that release. If this happened, I confidently predict that <em>somebody</em> would do that, and that some kind of a free PuTTY would continue to be developed. There's already precedent for that sort of thing happening in free software. We can't guarantee that somebody <em>other than you</em> would do it, of course; you might have to do it yourself. But we can assure you that there would be nothing <em>preventing</em> anyone from continuing free development if we stopped. </p> <p> (Finally, we can also confidently predict that if we made PuTTY closed-source and someone made an open-source fork, most people would switch to the latter. Therefore, it would be pretty stupid of us to try it.) </p> <h3><a name="faq-export-cert"></a><a name="QA.9.14"></a>A.9.14 Can you provide us with export control information / FIPS certification for PuTTY?</h3> <p> Some people have asked us for an Export Control Classification Number (ECCN) for PuTTY. We don't know whether we have one, and as a team of free software developers based in the UK we don't have the time, money, or effort to deal with US bureaucracy to investigate any further. We believe that PuTTY falls under 5D002 on the US Commerce Control List, but that shouldn't be taken as definitive. If you need to know more you should seek professional legal advice. The same applies to any other country's legal requirements and restrictions. </p> <p> Similarly, some people have asked us for FIPS certification of the PuTTY tools. Unless someone else is prepared to do the necessary work and pay any costs, we can't provide this. </p> <h2><a name="faq-misc"></a><a name="SA.10"></a>A.10 Miscellaneous questions</h2> <h3><a name="faq-openssh"></a><a name="QA.10.1"></a>A.10.1 Is PuTTY a port of <a name="i62"></a>OpenSSH, or based on OpenSSH or OpenSSL?</h3> <p> No, it isn't. PuTTY is almost completely composed of code written from scratch for PuTTY. The only code we share with OpenSSH is the detector for SSH-1 CRC compensation attacks, written by CORE SDI S.A; we share no code at all with OpenSSL. </p> <h3><a name="faq-sillyputty"></a><a name="QA.10.2"></a>A.10.2 Where can I buy silly putty?</h3> <p> You're looking at the wrong web site; the only PuTTY we know about here is the name of a computer program. </p> <p> If you want the kind of putty you can buy as an executive toy, the PuTTY team can personally recommend Thinking Putty, which you can buy from Crazy Aaron's Putty World, at <a href="http://www.puttyworld.com"><code>www.puttyworld.com</code></a>. </p> <h3><a name="faq-meaning"></a><a name="QA.10.3"></a>A.10.3 What does &#8216;PuTTY&#8217; mean?</h3> <p> It's the name of a popular SSH and Telnet client. Any other meaning is in the eye of the beholder. It's been rumoured that &#8216;PuTTY&#8217; is the antonym of &#8216;<code>getty</code>&#8217;, or that it's the stuff that makes your Windows useful, or that it's a kind of plutonium Teletype. We couldn't possibly comment on such allegations. </p> <h3><a name="faq-pronounce"></a><a name="QA.10.4"></a>A.10.4 How do I pronounce &#8216;PuTTY&#8217;?</h3> <p> Exactly like the English word &#8216;putty&#8217;, which we pronounce /&#712;p&#652;ti/. </p> <hr><p>If you want to provide feedback on this manual or on the PuTTY tools themselves, see the <a href="http://www.chiark.greenend.org.uk/~sgtatham/putty/feedback.html">Feedback page</a>.</p><address> [PuTTY release 0.62]</address></body> </html>
{ "content_hash": "1d4987eaedd3d7ca2fc8d6bb810ced1c", "timestamp": "", "source": "github", "line_count": 929, "max_line_length": 836, "avg_line_length": 90.5059203444564, "alnum_prop": 0.7342649857278782, "repo_name": "fredericjoanis/crc-scoreboard", "id": "982cdd01143030b093458205c196eba2899e7309", "size": "84080", "binary": false, "copies": "3", "ref": "refs/heads/master", "path": "tools/putty/doc/AppendixA.html", "mode": "33188", "license": "mit", "language": [ { "name": "Batchfile", "bytes": "1620" }, { "name": "CSS", "bytes": "10509" }, { "name": "Java", "bytes": "365492" }, { "name": "JavaScript", "bytes": "43637" }, { "name": "Lua", "bytes": "13217" }, { "name": "Shell", "bytes": "1267" } ], "symlink_target": "" }
<?xml version="1.0" encoding="utf-8" ?> <resources> <!--Replace placeholder ID with your tracking ID--> <string name="ga_trackingId">UA-46786960-1</string> <!--Enable automatic activity tracking--> <bool name="ga_autoActivityTracking">true</bool> <!--Enable automatic exception tracking--> <bool name="ga_reportUncaughtExceptions">true</bool> </resources>
{ "content_hash": "3d31835db82c35bf71894993454c742e", "timestamp": "", "source": "github", "line_count": 12, "max_line_length": 54, "avg_line_length": 30.833333333333332, "alnum_prop": 0.7081081081081081, "repo_name": "andytwmvp/NUU-WiFiAutoLogin", "id": "f6ef7615afa66b6b4324c37403a5f515b5482fa8", "size": "370", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "android/res/values/analytics.xml", "mode": "33188", "license": "mit", "language": [ { "name": "Java", "bytes": "10585" } ], "symlink_target": "" }
#include "core/html/HTMLSpanElement.h" #include "core/HTMLNames.h" namespace blink { using namespace HTMLNames; HTMLSpanElement::HTMLSpanElement(Document& document) : HTMLElement(spanTag, document) { } DEFINE_NODE_FACTORY(HTMLSpanElement) } // namespace blink
{ "content_hash": "c1d563df13c5a48c8fc9359a7015eafc", "timestamp": "", "source": "github", "line_count": 18, "max_line_length": 52, "avg_line_length": 15.11111111111111, "alnum_prop": 0.7610294117647058, "repo_name": "was4444/chromium.src", "id": "2b13688514614e26a88f41d8209072458c486130", "size": "1604", "binary": false, "copies": "9", "ref": "refs/heads/nw15", "path": "third_party/WebKit/Source/core/html/HTMLSpanElement.cpp", "mode": "33188", "license": "bsd-3-clause", "language": [], "symlink_target": "" }
<!-- #%L %% Copyright (C) 2011 - 2017 BMW Car IT GmbH %% Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. #L% --> <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> <groupId>io.joynr.cpp</groupId> <artifactId>tests</artifactId> <modelVersion>4.0.0</modelVersion> <packaging>pom</packaging> <name>${project.groupId}:${project.artifactId}</name> <parent> <groupId>io.joynr</groupId> <artifactId>cpp</artifactId> <version>0.29.0-SNAPSHOT</version> <relativePath>../pom.xml</relativePath> </parent> <dependencies> <!-- This dependency is needed to ensure the correct build order. Some artifacts is needed by the maven-dependency-plugin, which copies them to the currrent build directory. --> <dependency> <groupId>io.joynr.java.messaging.bounceproxy</groupId> <artifactId>single-bounceproxy</artifactId> <version>${project.version}</version> <type>war</type> </dependency> <!-- This dependency is needed to ensure the correct build order. Some artifacts is needed by the maven-dependency-plugin, which copies them to the currrent build directory. --> <dependency> <groupId>io.joynr.java.backend-services</groupId> <artifactId>discovery-directory-servlet</artifactId> <version>${project.version}</version> <type>war</type> </dependency> <!-- This dependency is needed to ensure the correct build order. Some artifacts is needed by the maven-dependency-plugin, which copies them to the currrent build directory. --> <dependency> <groupId>io.joynr.java.backend-services</groupId> <artifactId>domain-access-controller-servlet</artifactId> <version>${project.version}</version> <type>war</type> </dependency> </dependencies> <build> <plugins> <plugin> <groupId>io.joynr.tools.generator</groupId> <artifactId>joynr-generator-maven-plugin</artifactId> <configuration> <rootGenerator>io.joynr.generator.cpp.JoynrCppGenerator</rootGenerator> <outputPath>${basedir}/gen</outputPath> </configuration> <executions> <execution> <id>generate-common-test-classes</id> <phase>generate-test-sources</phase> <goals> <goal>generate</goal> </goals> <configuration> <model>${basedir}/../../basemodel/src/test/franca</model> </configuration> </execution> </executions> <dependencies> <dependency> <groupId>io.joynr.tools.generator</groupId> <artifactId>cpp-generator</artifactId> <version>${project.version}</version> </dependency> <dependency> <groupId>io.joynr</groupId> <artifactId>basemodel</artifactId> <classifier>tests</classifier> <version>${project.version}</version> </dependency> </dependencies> </plugin> <plugin> <artifactId>maven-clean-plugin</artifactId> <configuration> <filesets> <fileset> <directory>${basedir}</directory> <includes> <include>gen/communication-model/**</include> <include>gen/in-process/**</include> <include>gen/joynr-messaging/**</include> <include>gen/provider/**</include> <include>gen/proxy/**</include> <include>gen/include/**</include> </includes> </fileset> </filesets> </configuration> </plugin> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-dependency-plugin</artifactId> <executions> <execution> <id>copy-integration-test-dependencies</id> <phase>validate</phase> <goals> <goal>copy</goal> </goals> <configuration> <artifactItems> <artifactItem> <groupId>io.joynr.java.messaging.bounceproxy</groupId> <artifactId>single-bounceproxy</artifactId> <version>${project.version}</version> <type>war</type> <outputDirectory>${project.build.directory}</outputDirectory> <destFileName>bounceproxy.war</destFileName> </artifactItem> <artifactItem> <groupId>io.joynr.java.backend-services</groupId> <artifactId>discovery-directory-servlet</artifactId> <version>${project.version}</version> <type>war</type> <outputDirectory>${project.build.directory}</outputDirectory> <destFileName>discovery.war</destFileName> </artifactItem> <artifactItem> <groupId>io.joynr.java.backend-services</groupId> <artifactId>domain-access-controller-servlet</artifactId> <version>${project.version}</version> <type>war</type> <outputDirectory>${project.build.directory}</outputDirectory> <destFileName>accesscontrol.war</destFileName> </artifactItem> </artifactItems> <overWriteReleases>false</overWriteReleases> <overWriteSnapshots>true</overWriteSnapshots> </configuration> </execution> </executions> </plugin> <plugin> <artifactId>maven-resources-plugin</artifactId> <executions> <execution> <id>copy-jetty-config-files</id> <phase>validate</phase> <goals> <goal>copy-resources</goal> </goals> <configuration> <outputDirectory>${project.build.directory}/jetty-config-files</outputDirectory> <resources> <resource> <directory>resources</directory> <filtering>true</filtering> <includes> <include>jetty*.xml</include> </includes> </resource> <resource> <directory>resources</directory> <filtering>false</filtering> <includes> <include>localhost.jks</include> <include>truststore.jks</include> </includes> </resource> </resources> </configuration> </execution> </executions> </plugin> <plugin> <groupId>org.codehaus.mojo</groupId> <artifactId>properties-maven-plugin</artifactId> <executions> <execution> <goals> <goal>set-system-properties</goal> </goals> <configuration> <properties> <property> <name>log4j.configuration</name> <value>file:${basedir}/resources/log4j.properties</value> </property> </properties> </configuration> </execution> </executions> </plugin> <plugin> <groupId>org.eclipse.jetty</groupId> <artifactId>jetty-maven-plugin</artifactId> <configuration> <!-- Don't define system properties here, because it will override system properties defined in plugin management in super POM. --> <jettyXml>${project.build.directory}/jetty-config-files/jetty.xml,${project.build.directory}/jetty-config-files/jetty-http.xml,${project.build.directory}/jetty-config-files/jetty-ssl.xml,${project.build.directory}/jetty-config-files/jetty-https.xml</jettyXml> </configuration> </plugin> <plugin> <groupId>org.codehaus.mojo</groupId> <artifactId>license-maven-plugin</artifactId> <configuration> <verbose>false</verbose> <addSvnKeyWords>true</addSvnKeyWords> <licenseName>apache_v2</licenseName> <roots> <root>.</root> </roots> <excludes> <exclude>resources/ListOfCapabilitiesToInject.json</exclude> </excludes> </configuration> </plugin> </plugins> </build> </project>
{ "content_hash": "cb0dea0182542524bea6d82c9ef0ca64", "timestamp": "", "source": "github", "line_count": 241, "max_line_length": 264, "avg_line_length": 33.46058091286307, "alnum_prop": 0.6510416666666666, "repo_name": "clive-jevons/joynr", "id": "8063acfac5ecefe98874afdbe65c4a9161b28479", "size": "8064", "binary": false, "copies": "1", "ref": "refs/heads/develop", "path": "cpp/tests/pom.xml", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "C", "bytes": "1953" }, { "name": "C++", "bytes": "2702245" }, { "name": "CMake", "bytes": "125551" }, { "name": "CSS", "bytes": "3152" }, { "name": "HTML", "bytes": "43209" }, { "name": "Java", "bytes": "3236663" }, { "name": "JavaScript", "bytes": "2478252" }, { "name": "Shell", "bytes": "57216" }, { "name": "Xtend", "bytes": "1534" } ], "symlink_target": "" }
using System; using System.Collections.Generic; using System.Diagnostics; using CommonBotLibrary.Converters; using CommonBotLibrary.Interfaces.Models; using Newtonsoft.Json; namespace CommonBotLibrary.Services.Models { [DebuggerDisplay("{Id, nq}: {Title}")] public class SteamResult : IWebpage, IEquatable<SteamResult> { public uint Id { get; } [JsonProperty("tiny_image")] public string ImageUrl { get; set; } public string Metascore { get; set; } public bool StreamingVideo { get; set; } public Cost Price { get; set; } public Architecture Platforms { get; set; } public string Url { get; set; } public string Title { get; set; } [JsonConstructor] public SteamResult( string name, uint id, string tinyImage, string metascore, bool streamingVideo, Cost price, Architecture platforms) { Title = name; Url = $"https://store.steampowered.com/app/{id}"; Id = id; ImageUrl = tinyImage; Metascore = string.IsNullOrEmpty(metascore) ? null : metascore; StreamingVideo = streamingVideo; Price = price; Platforms = platforms; } #region IEquatable members public bool Equals(SteamResult other) { if (ReferenceEquals(null, other)) return false; if (ReferenceEquals(this, other)) return true; return Id == other.Id; } public override bool Equals(object obj) { if (ReferenceEquals(null, obj)) return false; if (ReferenceEquals(this, obj)) return true; var other = obj as SteamResult; return other != null && Equals(other); } public override int GetHashCode() => (int) Id; public static bool operator ==(SteamResult left, SteamResult right) => Equals(left, right); public static bool operator !=(SteamResult left, SteamResult right) => !Equals(left, right); #endregion #region Submodels public class Architecture { private string _asString; public bool Windows { get; set; } public bool Mac { get; set; } public bool Linux { get; set; } public override string ToString() { if (_asString != null) return _asString; var supported = new List<string>(); if (Windows) supported.Add(nameof(Windows)); if (Mac) supported.Add(nameof(Mac)); if (Linux) supported.Add(nameof(Linux)); return _asString = string.Join(", ", supported); } } [DebuggerDisplay("R: ${Regular, nq}, S: ${Sale, nq}")] public class Cost { [JsonConstructor] public Cost(int initial, int final) { Regular = (float)initial / 100; Sale = (float)final / 100; } public float Regular { get; set; } public float Sale { get; set; } public bool IsOnSale => Regular > Sale; } #endregion } public class SteamSpyData { public uint AppId { get; set; } public string Name { get; set; } public string Developer { get; set; } public string Publisher { get; set; } [JsonProperty("score_rank")] public string ScoreRank { get; set; } public uint Owners { get; set; } [JsonProperty("owners_variance")] public uint OwnersVariance { get; set; } [JsonProperty("players_forever")] public uint PlayersForever { get; set; } [JsonProperty("players_forever_variance")] public uint PlayersForeverVariance { get; set; } [JsonProperty("players_2weeks")] public uint Players2Weeks { get; set; } [JsonProperty("players_2weeks_variance")] public uint Players2WeeksVariance { get; set; } [JsonProperty("average_forever")] public uint AverageForever { get; set; } [JsonProperty("average_2weeks")] public uint Average2Weeks { get; set; } [JsonProperty("median_forever")] public uint MedianForever { get; set; } [JsonProperty("median_2weeks")] public uint Median2Weeks { get; set; } public uint Ccu { get; set; } public string Price { get; set; } [JsonConverter(typeof(DictionaryOrEmptyArrayConverter<string, int>))] public IDictionary<string, int> Tags { get; set; } } }
{ "content_hash": "a5cba407e98f648af373be876182eeb1", "timestamp": "", "source": "github", "line_count": 142, "max_line_length": 77, "avg_line_length": 33.15492957746479, "alnum_prop": 0.5609600679694138, "repo_name": "bcanseco/common-bot-library", "id": "3a7a586f45b3cfddfda0148d5093901dd63e96e6", "size": "4710", "binary": false, "copies": "1", "ref": "refs/heads/dev", "path": "src/CommonBotLibrary/Services/Models/SteamResult.cs", "mode": "33188", "license": "mit", "language": [ { "name": "C#", "bytes": "149781" }, { "name": "PowerShell", "bytes": "6110" }, { "name": "Shell", "bytes": "2936" } ], "symlink_target": "" }
# Use this hook to configure devise mailer, warden hooks and so forth. # Many of these configuration options can be set straight in your model. Devise.setup do |config| # The secret key used by Devise. Devise uses this key to generate # random tokens. Changing this key will render invalid all existing # confirmation, reset password and unlock tokens in the database. config.secret_key = ENV['DEVISE_SECRET_KEY'] # ==> ORM configuration # Load and configure the ORM. Supports :active_record (default) and # :mongoid (bson_ext recommended) by default. Other ORMs may be # available as additional gems. require 'devise/orm/active_record' # Configure which authentication keys should be case-insensitive. # These keys will be downcased upon creating or modifying a user and when used # to authenticate or find a user. Default is :email. # config.case_insensitive_keys = [ :email ] # Configure which authentication keys should have whitespace stripped. # These keys will have whitespace before and after removed upon creating or # modifying a user and when used to authenticate or find a user. Default is :email. # config.strip_whitespace_keys = [ :email ] # Tell if authentication through request.params is enabled. True by default. # It can be set to an array that will enable params authentication only for the # given strategies, for example, `config.params_authenticatable = [:database]` will # enable it only for database (email + password) authentication. config.params_authenticatable = true # Tell if authentication through HTTP Auth is enabled. False by default. # It can be set to an array that will enable http authentication only for the # given strategies, for example, `config.http_authenticatable = [:database]` will # enable it only for database authentication. The supported strategies are: # :database = Support basic authentication with authentication key + password config.http_authenticatable = false # If 401 status code should be returned for AJAX requests. True by default. # config.http_authenticatable_on_xhr = true # The realm used in Http Basic Authentication. 'Application' by default. # config.http_authentication_realm = 'Application' # It will change confirmation, password recovery and other workflows # to behave the same regardless if the e-mail provided was right or wrong. # Does not affect registerable. # config.paranoid = true # By default Devise will store the user in session. You can skip storage for # particular strategies by setting this option. # Notice that if you are skipping storage for all authentication paths, you # may want to disable generating routes to Devise's sessions controller by # passing skip: :sessions to `devise_for` in your config/routes.rb config.skip_session_storage = [:http_auth] # By default, Devise cleans up the CSRF token on authentication to # avoid CSRF token fixation attacks. This means that, when using AJAX # requests for sign in and sign up, you need to get a new CSRF token # from the server. You can disable this option at your own risk. config.clean_up_csrf_token_on_authentication = true # ==> Configuration for :database_authenticatable # For bcrypt, this is the cost for hashing the password and defaults to 10. If # using other encryptors, it sets how many times you want the password re-encrypted. # # Limiting the stretches to just one in testing will increase the performance of # your test suite dramatically. However, it is STRONGLY RECOMMENDED to not use # a value less than 10 in other environments. Note that, for bcrypt (the default # encryptor), the cost increases exponentially with the number of stretches (e.g. # a value of 20 is already extremely slow: approx. 60 seconds for 1 calculation). config.stretches = Rails.env.test? ? 1 : 10 # Setup a pepper to generate the encrypted password. # config.pepper = 'd68602c07af77ffeb4817fad17efeda6ece23b89d3b2b42126b56b2a99a8cf5c653f47ad1298a1b39d8e866835b48148875e84883c308c3addf4d3acbc124e60' # ==> Configuration for :rememberable # The time the user will be remembered without asking for credentials again. # config.remember_for = 2.weeks # Invalidates all the remember me tokens when the user signs out. config.expire_all_remember_me_on_sign_out = true # If true, extends the user's remember period when remembered via cookie. # config.extend_remember_period = false # Options to be passed to the created cookie. For instance, you can set # secure: true in order to force SSL only cookies. # config.rememberable_options = {} # ==> Configuration for :validatable # Range for password length. config.password_length = 8..128 # Email regex used to validate email formats. It simply asserts that # one (and only one) @ exists in the given string. This is mainly # to give user feedback and not to assert the e-mail validity. # config.email_regexp = /\A[^@]+@[^@]+\z/ # ==> Configuration for :timeoutable # The time you want to timeout the user session without activity. After this # time the user will be asked for credentials again. Default is 30 minutes. config.timeout_in = 30.minutes # ==> Navigation configuration # Lists the formats that should be treated as navigational. Formats like # :html, should redirect to the sign in page when the user does not have # access, but formats like :xml or :json, should return 401. # # If you have any extra navigational formats, like :iphone or :mobile, you # should add them to the navigational formats lists. # # The "*/*" below is required to match Internet Explorer requests. # config.navigational_formats = ['*/*', :html] # The default HTTP method used to sign out a resource. Default is :delete. config.sign_out_via = :delete end
{ "content_hash": "6566daedfd72412501cb6d535abacf13", "timestamp": "", "source": "github", "line_count": 117, "max_line_length": 150, "avg_line_length": 49.888888888888886, "alnum_prop": 0.747130375192736, "repo_name": "studentinsights/studentinsights", "id": "bdbb9cafe253d0048c67d8b2ff5b920fb3e08b3b", "size": "5837", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "config/initializers/devise.rb", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "8550" }, { "name": "HTML", "bytes": "67602" }, { "name": "JavaScript", "bytes": "2068243" }, { "name": "Procfile", "bytes": "173" }, { "name": "Ruby", "bytes": "1879416" }, { "name": "SCSS", "bytes": "16368" }, { "name": "Shell", "bytes": "30425" } ], "symlink_target": "" }
<?xml version="1.0" encoding="utf-8"?> <doctrine-mapping xmlns="http://doctrine-project.org/schemas/orm/doctrine-mapping" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://doctrine-project.org/schemas/orm/doctrine-mapping http://doctrine-project.org/schemas/orm/doctrine-mapping.xsd"> <entity name="CoursdeGratteBundle\Entity\Memo" table="memo"> <indexes> <index name="tuto_id" columns="tuto_id"/> <index name="user_id" columns="user_id"/> </indexes> <id name="id" type="integer" column="id"> <generator strategy="IDENTITY"/> </id> <field name="content" type="text" column="content" length="16777215" nullable="false"> <options> <option name="fixed"/> </options> </field> <many-to-one field="tuto" target-entity="Tutovideo" fetch="LAZY"> <join-columns> <join-column name="tuto_id" referenced-column-name="id"/> </join-columns> </many-to-one> <many-to-one field="user" target-entity="MyUserBundle\Entity\Users" fetch="LAZY"> <join-columns> <join-column name="user_id" referenced-column-name="id"/> </join-columns> </many-to-one> </entity> </doctrine-mapping>
{ "content_hash": "a870cd8ffbf309157bd0ceb98ca48113", "timestamp": "", "source": "github", "line_count": 27, "max_line_length": 276, "avg_line_length": 44.851851851851855, "alnum_prop": 0.6548307184145334, "repo_name": "Ipsaous/Cdg", "id": "023edc928f6661843a443e79b538eed1845b64b7", "size": "1211", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/CoursdeGratteBundle/Resources/config/doctrine/Memo.orm.xml", "mode": "33188", "license": "mit", "language": [ { "name": "ApacheConf", "bytes": "3638" }, { "name": "CSS", "bytes": "41570" }, { "name": "HTML", "bytes": "40166" }, { "name": "JavaScript", "bytes": "128209" }, { "name": "PHP", "bytes": "161701" } ], "symlink_target": "" }
<?php namespace WindowsAzure\Table\Models; use WindowsAzure\Common\Internal\Utilities; use WindowsAzure\Common\Internal\Validate; use WindowsAzure\Common\Internal\Resources; /** * Basic Windows Azure EDM Types used for table entity properties. * * @category Microsoft * @package WindowsAzure\Table\Models * @author Azure PHP SDK <[email protected]> * @copyright 2012 Microsoft Corporation * @license http://www.apache.org/licenses/LICENSE-2.0 Apache License 2.0 * @version Release: @package_version@ * @link https://github.com/windowsazure/azure-sdk-for-php */ class EdmType { // @codingStandardsIgnoreStart const DATETIME = 'Edm.DateTime'; const BINARY = 'Edm.Binary'; const BOOLEAN = 'Edm.Boolean'; const DOUBLE = 'Edm.Double'; const GUID = 'Edm.Guid'; const INT32 = 'Edm.Int32'; const INT64 = 'Edm.Int64'; const STRING = 'Edm.String'; /** * Converts the type to string if it's empty and validates the type. * * @param string $type The Edm type * * @return string */ public static function processType($type) { $type = empty($type) ? self::STRING : $type; Validate::isTrue(self::isValid($type), Resources::INVALID_EDM_MSG); return $type; } /** * Validates that the value associated with the EDM type is valid. * * @param string $type The EDM type. * @param mix $value The EDM value. * @param string &$condition The error message. * * @return boolean * * @throws \InvalidArgumentException */ public static function validateEdmValue($type, $value, &$condition = null) { // Having null value means that the user wants to remove the property name // associated with this value. Leave the value as null so this hold. if (is_null($value)) { return true; } else { switch ($type) { case EdmType::GUID: case EdmType::BINARY: case EdmType::STRING: case EdmType::INT64: case null: // NULL also is treated as EdmType::STRING $condition = 'is_string'; return is_string($value); case EdmType::DOUBLE: $condition = 'is_double'; return is_double($value); case EdmType::INT32: $condition = 'is_int'; return is_int($value); case EdmType::DATETIME: $condition = 'instanceof \DateTime'; return $value instanceof \DateTime; case EdmType::BOOLEAN: $condition = 'is_bool'; return is_bool($value); default: throw new \InvalidArgumentException(); } } } /** * Serializes EDM value into proper value for sending it to Windows Azure. * * @param string $type The EDM type. * @param mix $value The EDM value. * * @return string * * @throws \InvalidArgumentException */ public static function serializeValue($type, $value) { switch ($type) { case EdmType::DOUBLE: case EdmType::INT32: case EdmType::INT64: case EdmType::GUID: case EdmType::STRING: case null: // NULL also is treated as EdmType::STRING return strval($value); case EdmType::BINARY: return base64_encode($value); case EdmType::DATETIME: return Utilities::convertToEdmDateTime($value); case EdmType::BOOLEAN: return (is_null($value) ? '' : ($value == true ? '1' : '0')); default: throw new \InvalidArgumentException(); } } /** * Serializes EDM value into proper value to be used in query. * * @param string $type The EDM type. * @param mix $value The EDM value. * * @return string * * @throws \InvalidArgumentException */ public static function serializeQueryValue($type, $value) { switch ($type) { case EdmType::DATETIME: $edmDate = Utilities::convertToEdmDateTime($value); return 'datetime\'' . $edmDate . '\''; case EdmType::BINARY: return 'X\'' . implode('', unpack("H*", $value)) . '\''; case EdmType::BOOLEAN: return ($value ? 'true' : 'false'); case EdmType::DOUBLE: case EdmType::INT32: return $value; case EdmType::INT64: return $value . 'L'; case EdmType::GUID: return 'guid\'' . $value . '\''; case null: case EdmType::STRING: // NULL also is treated as EdmType::STRING return '\'' . str_replace('\'', '\'\'', $value) . '\''; default: throw new \InvalidArgumentException(); } } /** * Converts the value into its proper type. * * @param string $type The edm type. * @param string $value The edm value. * * @return mix * * @throws \InvalidArgumentException */ public static function unserializeQueryValue($type, $value) { // Having null value means that the user wants to remove the property name // associated with this value. Leave the value as null so this hold. if (is_null($value)) { return null; } else { switch ($type) { case self::GUID: case self::STRING: case self::INT64: case null: // NULL also is treated as EdmType::STRING return strval($value); case self::BINARY: return base64_decode($value); case self::DATETIME: return Utilities::convertToDateTime($value); case self::BOOLEAN: return Utilities::toBoolean($value); case self::DOUBLE: return doubleval($value); case self::INT32: return intval($value); default: throw new \InvalidArgumentException(); } } } /** * Check if the $type belongs to valid header types. * * @param string $type The type string to check. * * @return boolean */ public static function isValid($type) { switch($type) { case $type == self::DATETIME: case $type == self::BINARY: case $type == self::BOOLEAN: case $type == self::DOUBLE: case $type == self::GUID: case $type == self::INT32: case $type == self::INT64: case $type == self::STRING: case $type == null: // NULL also is treated as EdmType::STRING return true; default: return false; } } // @codingStandardsIgnoreEnd }
{ "content_hash": "48a5bf4bde5afeaa894bea1524d90feb", "timestamp": "", "source": "github", "line_count": 255, "max_line_length": 82, "avg_line_length": 29.058823529411764, "alnum_prop": 0.5087719298245614, "repo_name": "getupcloud/wordpress-ex", "id": "96ad3f6570653a5613764d251a58e7485ed4ec9b", "size": "8320", "binary": false, "copies": "9", "ref": "refs/heads/master", "path": "wp-content/plugins/windows-azure-storage/library/WindowsAzure/Table/Models/EdmType.php", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "ApacheConf", "bytes": "629" }, { "name": "CSS", "bytes": "1908102" }, { "name": "HTML", "bytes": "10554" }, { "name": "Java", "bytes": "14870" }, { "name": "JavaScript", "bytes": "2341277" }, { "name": "Modelica", "bytes": "10338" }, { "name": "PHP", "bytes": "19356824" }, { "name": "Perl", "bytes": "1953" }, { "name": "Shell", "bytes": "528" } ], "symlink_target": "" }
<html> <head> <meta http-equiv="Content-Type" content="text/html; charset=US-ASCII"> <title>Struct base_unit_info&lt;metric::hour_base_unit&gt;</title> <link rel="stylesheet" href="../../../../../../doc/src/boostbook.css" type="text/css"> <meta name="generator" content="DocBook XSL Stylesheets V1.76.1"> <link rel="home" href="../../index.html" title="Chapter&#160;1.&#160;Boost.Units 1.1.0"> <link rel="up" href="../../header/boost/units/base_units/metric/hour_hpp.html" title="Header &lt;boost/units/base_units/metric/hour.hpp&gt;"> <link rel="prev" href="../../header/boost/units/base_units/metric/hour_hpp.html" title="Header &lt;boost/units/base_units/metric/hour.hpp&gt;"> <link rel="next" href="../../header/boost/units/base_units/metric/knot_hpp.html" title="Header &lt;boost/units/base_units/metric/knot.hpp&gt;"> </head> <body bgcolor="white" text="black" link="#0000FF" vlink="#840084" alink="#0000FF"> <table cellpadding="2" width="100%"><tr> <td valign="top"><img alt="Boost C++ Libraries" width="277" height="86" src="../../../../../../boost.png"></td> <td align="center"><a href="../../../../../../index.html">Home</a></td> <td align="center"><a href="../../../../../../libs/libraries.htm">Libraries</a></td> <td align="center"><a href="http://www.boost.org/users/people.html">People</a></td> <td align="center"><a href="http://www.boost.org/users/faq.html">FAQ</a></td> <td align="center"><a href="../../../../../../more/index.htm">More</a></td> </tr></table> <hr> <div class="spirit-nav"> <a accesskey="p" href="../../header/boost/units/base_units/metric/hour_hpp.html"><img src="../../../../../../doc/src/images/prev.png" alt="Prev"></a><a accesskey="u" href="../../header/boost/units/base_units/metric/hour_hpp.html"><img src="../../../../../../doc/src/images/up.png" alt="Up"></a><a accesskey="h" href="../../index.html"><img src="../../../../../../doc/src/images/home.png" alt="Home"></a><a accesskey="n" href="../../header/boost/units/base_units/metric/knot_hpp.html"><img src="../../../../../../doc/src/images/next.png" alt="Next"></a> </div> <div class="refentry"> <a name="boost.units.base_unit_info_idp12417184"></a><div class="titlepage"></div> <div class="refnamediv"> <h2><span class="refentrytitle">Struct base_unit_info&lt;metric::hour_base_unit&gt;</span></h2> <p>boost::units::base_unit_info&lt;metric::hour_base_unit&gt;</p> </div> <h2 xmlns:rev="http://www.cs.rpi.edu/~gregod/boost/tools/doc/revision" class="refsynopsisdiv-title">Synopsis</h2> <div xmlns:rev="http://www.cs.rpi.edu/~gregod/boost/tools/doc/revision" class="refsynopsisdiv"><pre class="synopsis"><span class="comment">// In header: &lt;<a class="link" href="../../header/boost/units/base_units/metric/hour_hpp.html" title="Header &lt;boost/units/base_units/metric/hour.hpp&gt;">boost/units/base_units/metric/hour.hpp</a>&gt; </span> <span class="keyword">struct</span> <a class="link" href="base_unit_info_idp12417184.html" title="Struct base_unit_info&lt;metric::hour_base_unit&gt;">base_unit_info</a><span class="special">&lt;</span><span class="identifier">metric</span><span class="special">::</span><span class="identifier">hour_base_unit</span><span class="special">&gt;</span> <span class="special">{</span> <span class="comment">// <a class="link" href="base_unit_info_idp12417184.html#idp12418288-bb">public static functions</a></span> <span class="keyword">static</span> <span class="keyword">const</span> <span class="keyword">char</span> <span class="special">*</span> <a class="link" href="base_unit_info_idp12417184.html#idp12418848-bb"><span class="identifier">name</span></a><span class="special">(</span><span class="special">)</span><span class="special">;</span> <span class="keyword">static</span> <span class="keyword">const</span> <span class="keyword">char</span> <span class="special">*</span> <a class="link" href="base_unit_info_idp12417184.html#idp12419968-bb"><span class="identifier">symbol</span></a><span class="special">(</span><span class="special">)</span><span class="special">;</span> <span class="special">}</span><span class="special">;</span></pre></div> <div class="refsect1"> <a name="idp89548448"></a><h2>Description</h2> <div class="refsect2"> <a name="idp89548864"></a><h3> <a name="idp12418288-bb"></a><code class="computeroutput">base_unit_info</code> public static functions</h3> <div class="orderedlist"><ol class="orderedlist" type="1"> <li class="listitem"><pre class="literallayout"><span class="keyword">static</span> <span class="keyword">const</span> <span class="keyword">char</span> <span class="special">*</span> <a name="idp12418848-bb"></a><span class="identifier">name</span><span class="special">(</span><span class="special">)</span><span class="special">;</span></pre></li> <li class="listitem"><pre class="literallayout"><span class="keyword">static</span> <span class="keyword">const</span> <span class="keyword">char</span> <span class="special">*</span> <a name="idp12419968-bb"></a><span class="identifier">symbol</span><span class="special">(</span><span class="special">)</span><span class="special">;</span></pre></li> </ol></div> </div> </div> </div> <table xmlns:rev="http://www.cs.rpi.edu/~gregod/boost/tools/doc/revision" width="100%"><tr> <td align="left"></td> <td align="right"><div class="copyright-footer">Copyright &#169; 2003-2008 Matthias Christian Schabel<br>Copyright &#169; 2007-2010 Steven Watanabe<p> Distributed under the Boost Software License, Version 1.0. (See accompanying file LICENSE_1_0.txt or copy at <a href="http://www.boost.org/LICENSE_1_0.txt" target="_top">http://www.boost.org/LICENSE_1_0.txt</a>) </p> </div></td> </tr></table> <hr> <div class="spirit-nav"> <a accesskey="p" href="../../header/boost/units/base_units/metric/hour_hpp.html"><img src="../../../../../../doc/src/images/prev.png" alt="Prev"></a><a accesskey="u" href="../../header/boost/units/base_units/metric/hour_hpp.html"><img src="../../../../../../doc/src/images/up.png" alt="Up"></a><a accesskey="h" href="../../index.html"><img src="../../../../../../doc/src/images/home.png" alt="Home"></a><a accesskey="n" href="../../header/boost/units/base_units/metric/knot_hpp.html"><img src="../../../../../../doc/src/images/next.png" alt="Next"></a> </div> </body> </html>
{ "content_hash": "b33ed900885791745c0451eb4002bf30", "timestamp": "", "source": "github", "line_count": 67, "max_line_length": 552, "avg_line_length": 93.67164179104478, "alnum_prop": 0.6644359464627151, "repo_name": "nicecapj/crossplatfromMmorpgServer", "id": "33c3cd78c81a9d567025d5f4bdfa564726194766", "size": "6276", "binary": false, "copies": "3", "ref": "refs/heads/master", "path": "ThirdParty/boost_1_61_0/libs/units/doc/html/boost/units/base_unit_info_idp12417184.html", "mode": "33188", "license": "mit", "language": [ { "name": "Assembly", "bytes": "223360" }, { "name": "Batchfile", "bytes": "33694" }, { "name": "C", "bytes": "3967798" }, { "name": "C#", "bytes": "2093216" }, { "name": "C++", "bytes": "197077824" }, { "name": "CMake", "bytes": "203207" }, { "name": "CSS", "bytes": "427824" }, { "name": "CWeb", "bytes": "174166" }, { "name": "Cuda", "bytes": "52444" }, { "name": "DIGITAL Command Language", "bytes": "6246" }, { "name": "Emacs Lisp", "bytes": "7822" }, { "name": "Fortran", "bytes": "1856" }, { "name": "Go", "bytes": "8549" }, { "name": "HTML", "bytes": "234971359" }, { "name": "IDL", "bytes": "14" }, { "name": "Java", "bytes": "3809828" }, { "name": "JavaScript", "bytes": "1112586" }, { "name": "Lex", "bytes": "1231" }, { "name": "M4", "bytes": "135271" }, { "name": "Makefile", "bytes": "1266088" }, { "name": "Max", "bytes": "36857" }, { "name": "Objective-C", "bytes": "2928243" }, { "name": "Objective-C++", "bytes": "3527" }, { "name": "PHP", "bytes": "59372" }, { "name": "Perl", "bytes": "38649" }, { "name": "Perl6", "bytes": "2053" }, { "name": "Protocol Buffer", "bytes": "1576976" }, { "name": "Python", "bytes": "3257634" }, { "name": "QML", "bytes": "593" }, { "name": "QMake", "bytes": "16692" }, { "name": "Rebol", "bytes": "354" }, { "name": "Roff", "bytes": "5189" }, { "name": "Ruby", "bytes": "97584" }, { "name": "Shell", "bytes": "787152" }, { "name": "Swift", "bytes": "20519" }, { "name": "Tcl", "bytes": "1172" }, { "name": "TeX", "bytes": "32117" }, { "name": "Vim script", "bytes": "3759" }, { "name": "XSLT", "bytes": "552736" }, { "name": "Yacc", "bytes": "19623" } ], "symlink_target": "" }
namespace mscorlib { namespace System { class Type; class String; } } namespace mscorlib { namespace System { namespace Runtime { namespace CompilerServices { class SpecialNameAttribute : public mscorlib::System::Attribute , public virtual mscorlib::System::Runtime::InteropServices::_Attribute { public: SpecialNameAttribute() : mscorlib::System::Attribute(mscorlib::NativeTypeInfo::GetTypeInfo("mscorlib","System.Runtime.CompilerServices.SpecialNameAttribute")) , mscorlib::System::Runtime::InteropServices::_Attribute(NULL) { __native_object__ = Global::New("mscorlib", "System.Runtime.CompilerServices", "SpecialNameAttribute"); }; SpecialNameAttribute(mscorlib::NativeTypeInfo *nativeTypeInfo) : mscorlib::System::Attribute(nativeTypeInfo) , mscorlib::System::Runtime::InteropServices::_Attribute(NULL) { }; SpecialNameAttribute(MonoObject *nativeObject) : mscorlib::System::Attribute(nativeObject) , mscorlib::System::Runtime::InteropServices::_Attribute(nativeObject) { }; ~SpecialNameAttribute() { }; SpecialNameAttribute & operator=(SpecialNameAttribute &value) { __native_object__ = value.GetNativeObject(); return value; }; bool operator==(SpecialNameAttribute &value) { return mscorlib::System::Object::Equals(value); }; operator MonoObject*() { return __native_object__; }; MonoObject* operator=(MonoObject* value) { return __native_object__ = value; }; virtual MonoObject* GetNativeObject() override { return __native_object__; }; //Public Properties __declspec(property(get=get_TypeId)) mscorlib::System::Object TypeId; //Get Set Properties Methods // Get:TypeId mscorlib::System::Object get_TypeId() const; protected: private: }; } } } } #endif
{ "content_hash": "a38b878490627dbd53c646acbd35dc09", "timestamp": "", "source": "github", "line_count": 77, "max_line_length": 140, "avg_line_length": 24.92207792207792, "alnum_prop": 0.6649296508598228, "repo_name": "brunolauze/MonoNative", "id": "6a0a742862db60980c44b1fd1a7d6c715eb984e7", "size": "2304", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "MonoNative/mscorlib/System/Runtime/CompilerServices/mscorlib_System_Runtime_CompilerServices_SpecialNameAttribute.h", "mode": "33188", "license": "bsd-2-clause", "language": [ { "name": "C", "bytes": "137243" }, { "name": "C#", "bytes": "104880" }, { "name": "C++", "bytes": "18404064" }, { "name": "CSS", "bytes": "1754" }, { "name": "HTML", "bytes": "16925" }, { "name": "Shell", "bytes": "132" } ], "symlink_target": "" }
import Notifications from './Notifications.js'; export default Notifications;
{ "content_hash": "23bf4d090837565ef76e7fb1c41a3b01", "timestamp": "", "source": "github", "line_count": 2, "max_line_length": 47, "avg_line_length": 39, "alnum_prop": 0.8205128205128205, "repo_name": "Axivity/openmovement-axsys-client", "id": "1d62ec7049974c62d8ccd4cb2c158a52ddce63ae", "size": "78", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "vendor/react-notifications/src/index.js", "mode": "33188", "license": "bsd-2-clause", "language": [ { "name": "CSS", "bytes": "3987" }, { "name": "HTML", "bytes": "2091" }, { "name": "JavaScript", "bytes": "150611" } ], "symlink_target": "" }
using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; // General Information about an assembly is controlled through the following // set of attributes. Change these attribute values to modify the information // associated with an assembly. [assembly: AssemblyTitle("MicrosoftPractices.Tests")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("MicrosoftPractices.Tests")] [assembly: AssemblyCopyright("Copyright © 2009")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. [assembly: ComVisible(false)] // The following GUID is for the ID of the typelib if this project is exposed to COM [assembly: Guid("c0fe8e16-323b-40c6-920f-46f4bc014a94")] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Build and Revision Numbers // by using the '*' as shown below: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("1.0.0.0")] [assembly: AssemblyFileVersion("1.0.0.0")]
{ "content_hash": "865d27fb709dde8161e961d2c34da16d", "timestamp": "", "source": "github", "line_count": 36, "max_line_length": 84, "avg_line_length": 40.47222222222222, "alnum_prop": 0.7295813315030886, "repo_name": "thlorenz/pokertell", "id": "04bb2571cdf4a41e9634036d868de7f1dca435f2", "size": "1460", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "Src/Tests/FrameworkTests/MicrosoftPractices.Tests/Properties/AssemblyInfo.cs", "mode": "33188", "license": "mit", "language": [], "symlink_target": "" }
package com.intellij.openapi.fileChooser.tree; import com.intellij.openapi.vfs.VirtualFile; import com.intellij.ui.ColoredListCellRenderer; import com.intellij.ui.ColoredTableCellRenderer; import com.intellij.ui.ColoredTreeCellRenderer; import com.intellij.ui.SimpleColoredComponent; import com.intellij.ui.SimpleTextAttributes; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import java.awt.Color; import javax.swing.Icon; import javax.swing.JList; import javax.swing.JTable; import javax.swing.JTree; import static com.intellij.openapi.fileChooser.FileElement.isFileHidden; import static com.intellij.openapi.util.IconLoader.getTransparentIcon; public class FileRenderer { private static final Color GRAYED = SimpleTextAttributes.GRAYED_ATTRIBUTES.getFgColor(); private static final Color HIDDEN = SimpleTextAttributes.DARK_TEXT.getFgColor(); public <T> ColoredListCellRenderer<T> forList() { return new ColoredListCellRenderer<T>() { @Override protected void customizeCellRenderer(@NotNull JList<? extends T> list, T value, int index, boolean selected, boolean focused) { customize(this, value, selected, focused); } }; } public ColoredTableCellRenderer forTable() { return new ColoredTableCellRenderer() { @Override protected void customizeCellRenderer(JTable table, @Nullable Object value, boolean selected, boolean focused, int row, int column) { customize(this, value, selected, focused); } }; } public ColoredTreeCellRenderer forTree() { return new ColoredTreeCellRenderer() { @Override public void customizeCellRenderer(@NotNull JTree tree, Object value, boolean selected, boolean expanded, boolean leaf, int row, boolean focused) { customize(this, value, selected, focused); } }; } protected void customize(SimpleColoredComponent renderer, Object value, boolean selected, boolean focused) { int style = SimpleTextAttributes.STYLE_PLAIN; Color color = null; Icon icon = null; String name = null; String comment = null; boolean hidden = false; boolean valid = true; if (value instanceof FileNode) { FileNode node = (FileNode)value; icon = node.getIcon(); name = node.getName(); comment = node.getComment(); hidden = node.isHidden(); valid = node.isValid(); } else if (value instanceof VirtualFile) { VirtualFile file = (VirtualFile)value; name = file.getName(); hidden = isFileHidden(file); valid = file.isValid(); } else if (value != null) { name = value.toString(); color = GRAYED; } if (!valid) style |= SimpleTextAttributes.STYLE_STRIKEOUT; if (hidden) color = HIDDEN; renderer.setIcon(!hidden || icon == null ? icon : getTransparentIcon(icon)); SimpleTextAttributes attributes = new SimpleTextAttributes(style, color); if (name != null) renderer.append(name, attributes); if (comment != null) renderer.append(comment, attributes); } }
{ "content_hash": "60217e2c141a33edbb3ed73e704c5865", "timestamp": "", "source": "github", "line_count": 86, "max_line_length": 138, "avg_line_length": 36.093023255813954, "alnum_prop": 0.7061855670103093, "repo_name": "leafclick/intellij-community", "id": "c306e4a531cac61bde2526cf04d09d97835fc79a", "size": "3245", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "platform/platform-impl/src/com/intellij/openapi/fileChooser/tree/FileRenderer.java", "mode": "33188", "license": "apache-2.0", "language": [], "symlink_target": "" }
using System.Collections.Generic; using System.Collections.Immutable; using System.Linq; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.DocumentationComments; using Microsoft.CodeAnalysis.Shared.Extensions; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.LanguageServices { internal partial class AbstractSymbolDisplayService { protected abstract partial class AbstractSymbolDescriptionBuilder { private static readonly SymbolDisplayFormat s_typeParameterOwnerFormat = new SymbolDisplayFormat( globalNamespaceStyle: SymbolDisplayGlobalNamespaceStyle.Omitted, typeQualificationStyle: SymbolDisplayTypeQualificationStyle.NameAndContainingTypesAndNamespaces, genericsOptions: SymbolDisplayGenericsOptions.IncludeTypeParameters | SymbolDisplayGenericsOptions.IncludeVariance | SymbolDisplayGenericsOptions.IncludeTypeConstraints, memberOptions: SymbolDisplayMemberOptions.IncludeContainingType, parameterOptions: SymbolDisplayParameterOptions.None, miscellaneousOptions: SymbolDisplayMiscellaneousOptions.EscapeKeywordIdentifiers | SymbolDisplayMiscellaneousOptions.UseSpecialTypes | SymbolDisplayMiscellaneousOptions.UseErrorTypeSymbolName); private static readonly SymbolDisplayFormat s_memberSignatureDisplayFormat = new SymbolDisplayFormat( globalNamespaceStyle: SymbolDisplayGlobalNamespaceStyle.Omitted, genericsOptions: SymbolDisplayGenericsOptions.IncludeTypeParameters | SymbolDisplayGenericsOptions.IncludeTypeConstraints, memberOptions: SymbolDisplayMemberOptions.IncludeParameters | SymbolDisplayMemberOptions.IncludeType | SymbolDisplayMemberOptions.IncludeContainingType, kindOptions: SymbolDisplayKindOptions.IncludeMemberKeyword, propertyStyle: SymbolDisplayPropertyStyle.ShowReadWriteDescriptor, parameterOptions: SymbolDisplayParameterOptions.IncludeName | SymbolDisplayParameterOptions.IncludeType | SymbolDisplayParameterOptions.IncludeParamsRefOut | SymbolDisplayParameterOptions.IncludeExtensionThis | SymbolDisplayParameterOptions.IncludeDefaultValue | SymbolDisplayParameterOptions.IncludeOptionalBrackets, localOptions: SymbolDisplayLocalOptions.IncludeType, miscellaneousOptions: SymbolDisplayMiscellaneousOptions.EscapeKeywordIdentifiers | SymbolDisplayMiscellaneousOptions.UseSpecialTypes | SymbolDisplayMiscellaneousOptions.UseErrorTypeSymbolName); private static readonly SymbolDisplayFormat s_descriptionStyle = new SymbolDisplayFormat( typeQualificationStyle: SymbolDisplayTypeQualificationStyle.NameAndContainingTypesAndNamespaces, delegateStyle: SymbolDisplayDelegateStyle.NameAndSignature, genericsOptions: SymbolDisplayGenericsOptions.IncludeTypeParameters | SymbolDisplayGenericsOptions.IncludeVariance | SymbolDisplayGenericsOptions.IncludeTypeConstraints, parameterOptions: SymbolDisplayParameterOptions.IncludeType | SymbolDisplayParameterOptions.IncludeName | SymbolDisplayParameterOptions.IncludeParamsRefOut, miscellaneousOptions: SymbolDisplayMiscellaneousOptions.EscapeKeywordIdentifiers, kindOptions: SymbolDisplayKindOptions.IncludeNamespaceKeyword | SymbolDisplayKindOptions.IncludeTypeKeyword); private static readonly SymbolDisplayFormat s_globalNamespaceStyle = new SymbolDisplayFormat( globalNamespaceStyle: SymbolDisplayGlobalNamespaceStyle.Included); private readonly ISymbolDisplayService _displayService; private readonly SemanticModel _semanticModel; private readonly int _position; private readonly IAnonymousTypeDisplayService _anonymousTypeDisplayService; private readonly Dictionary<SymbolDescriptionGroups, IList<SymbolDisplayPart>> _groupMap = new Dictionary<SymbolDescriptionGroups, IList<SymbolDisplayPart>>(); protected readonly Workspace Workspace; protected readonly CancellationToken CancellationToken; protected AbstractSymbolDescriptionBuilder( ISymbolDisplayService displayService, SemanticModel semanticModel, int position, Workspace workspace, IAnonymousTypeDisplayService anonymousTypeDisplayService, CancellationToken cancellationToken) { _displayService = displayService; _anonymousTypeDisplayService = anonymousTypeDisplayService; this.Workspace = workspace; this.CancellationToken = cancellationToken; _semanticModel = semanticModel; _position = position; } protected abstract void AddExtensionPrefix(); protected abstract void AddAwaitablePrefix(); protected abstract void AddAwaitableExtensionPrefix(); protected abstract void AddDeprecatedPrefix(); protected abstract Task<ImmutableArray<SymbolDisplayPart>> GetInitializerSourcePartsAsync(ISymbol symbol); protected abstract SymbolDisplayFormat MinimallyQualifiedFormat { get; } protected abstract SymbolDisplayFormat MinimallyQualifiedFormatWithConstants { get; } protected void AddPrefixTextForAwaitKeyword() { AddToGroup(SymbolDescriptionGroups.MainDescription, PlainText(FeaturesResources.Awaited_task_returns), Space()); } protected void AddTextForSystemVoid() { AddToGroup(SymbolDescriptionGroups.MainDescription, PlainText(FeaturesResources.no_value)); } protected SemanticModel GetSemanticModel(SyntaxTree tree) { if (_semanticModel.SyntaxTree == tree) { return _semanticModel; } var model = _semanticModel.GetOriginalSemanticModel(); if (model.Compilation.ContainsSyntaxTree(tree)) { return model.Compilation.GetSemanticModel(tree); } // it is from one of its p2p references foreach (var referencedCompilation in model.Compilation.GetReferencedCompilations()) { // find the reference that contains the given tree if (referencedCompilation.ContainsSyntaxTree(tree)) { return referencedCompilation.GetSemanticModel(tree); } } // the tree, a source symbol is defined in, doesn't exist in universe // how this can happen? Contract.Requires(false, "How?"); return null; } private async Task AddPartsAsync(ImmutableArray<ISymbol> symbols) { await AddDescriptionPartAsync(symbols[0]).ConfigureAwait(false); AddOverloadCountPart(symbols); FixAllAnonymousTypes(symbols[0]); AddExceptions(symbols[0]); } private void AddExceptions(ISymbol symbol) { var exceptionTypes = symbol.GetDocumentationComment().ExceptionTypes; if (exceptionTypes.Any()) { var parts = new List<SymbolDisplayPart>(); parts.Add(new SymbolDisplayPart(kind: SymbolDisplayPartKind.Text, symbol: null, text: $"\r\n{WorkspacesResources.Exceptions_colon}")); foreach (var exceptionString in exceptionTypes) { parts.AddRange(LineBreak()); parts.AddRange(Space(count: 2)); parts.AddRange(AbstractDocumentationCommentFormattingService.CrefToSymbolDisplayParts(exceptionString, _position, _semanticModel)); } AddToGroup(SymbolDescriptionGroups.Exceptions, parts); } } public async Task<ImmutableArray<SymbolDisplayPart>> BuildDescriptionAsync( ImmutableArray<ISymbol> symbolGroup, SymbolDescriptionGroups groups) { Contract.ThrowIfFalse(symbolGroup.Length > 0); await AddPartsAsync(symbolGroup).ConfigureAwait(false); return this.BuildDescription(groups); } public async Task<IDictionary<SymbolDescriptionGroups, ImmutableArray<TaggedText>>> BuildDescriptionSectionsAsync(ImmutableArray<ISymbol> symbolGroup) { Contract.ThrowIfFalse(symbolGroup.Length > 0); await AddPartsAsync(symbolGroup).ConfigureAwait(false); return this.BuildDescriptionSections(); } private async Task AddDescriptionPartAsync(ISymbol symbol) { if (symbol.GetAttributes().Any(x => x.AttributeClass.MetadataName == "ObsoleteAttribute")) { AddDeprecatedPrefix(); } if (symbol is IDynamicTypeSymbol) { AddDescriptionForDynamicType(); } else if (symbol is IFieldSymbol) { await AddDescriptionForFieldAsync((IFieldSymbol)symbol).ConfigureAwait(false); } else if (symbol is ILocalSymbol) { await AddDescriptionForLocalAsync((ILocalSymbol)symbol).ConfigureAwait(false); } else if (symbol is IMethodSymbol) { AddDescriptionForMethod((IMethodSymbol)symbol); } else if (symbol is ILabelSymbol) { AddDescriptionForLabel((ILabelSymbol)symbol); } else if (symbol is INamedTypeSymbol) { await AddDescriptionForNamedTypeAsync((INamedTypeSymbol)symbol).ConfigureAwait(false); } else if (symbol is INamespaceSymbol) { AddDescriptionForNamespace((INamespaceSymbol)symbol); } else if (symbol is IParameterSymbol) { await AddDescriptionForParameterAsync((IParameterSymbol)symbol).ConfigureAwait(false); } else if (symbol is IPropertySymbol) { AddDescriptionForProperty((IPropertySymbol)symbol); } else if (symbol is IRangeVariableSymbol) { AddDescriptionForRangeVariable((IRangeVariableSymbol)symbol); } else if (symbol is ITypeParameterSymbol) { AddDescriptionForTypeParameter((ITypeParameterSymbol)symbol); } else if (symbol is IAliasSymbol) { await AddDescriptionPartAsync(((IAliasSymbol)symbol).Target).ConfigureAwait(false); } else { AddDescriptionForArbitrarySymbol(symbol); } } private ImmutableArray<SymbolDisplayPart> BuildDescription(SymbolDescriptionGroups groups) { var finalParts = new List<SymbolDisplayPart>(); var orderedGroups = _groupMap.Keys.OrderBy((g1, g2) => g1 - g2); foreach (var group in orderedGroups) { if ((groups & group) == 0) { continue; } if (!finalParts.IsEmpty()) { var newLines = GetPrecedingNewLineCount(group); finalParts.AddRange(LineBreak(newLines)); } var parts = _groupMap[group]; finalParts.AddRange(parts); } return finalParts.AsImmutable(); } private static int GetPrecedingNewLineCount(SymbolDescriptionGroups group) { switch (group) { case SymbolDescriptionGroups.MainDescription: // these parts are continuations of whatever text came before them return 0; case SymbolDescriptionGroups.Documentation: return 1; case SymbolDescriptionGroups.AnonymousTypes: return 0; case SymbolDescriptionGroups.Exceptions: case SymbolDescriptionGroups.TypeParameterMap: // Everything else is in a group on its own return 2; default: return Contract.FailWithReturn<int>("unknown part kind"); } } private IDictionary<SymbolDescriptionGroups, ImmutableArray<TaggedText>> BuildDescriptionSections() { return _groupMap.ToDictionary(kvp => kvp.Key, kvp => kvp.Value.ToTaggedText()); } private void AddDescriptionForDynamicType() { AddToGroup(SymbolDescriptionGroups.MainDescription, Keyword("dynamic")); AddToGroup(SymbolDescriptionGroups.Documentation, PlainText(FeaturesResources.Represents_an_object_whose_operations_will_be_resolved_at_runtime)); } private async Task AddDescriptionForNamedTypeAsync(INamedTypeSymbol symbol) { if (symbol.IsAwaitableNonDynamic(_semanticModel, _position)) { AddAwaitablePrefix(); } var token = await _semanticModel.SyntaxTree.GetTouchingTokenAsync(_position, this.CancellationToken).ConfigureAwait(false); if (token != default(SyntaxToken)) { var syntaxFactsService = this.Workspace.Services.GetLanguageServices(token.Language).GetService<ISyntaxFactsService>(); if (syntaxFactsService.IsAwaitKeyword(token)) { AddPrefixTextForAwaitKeyword(); if (symbol.SpecialType == SpecialType.System_Void) { AddTextForSystemVoid(); return; } } } if (symbol.TypeKind == TypeKind.Delegate) { var style = s_descriptionStyle.WithMiscellaneousOptions(SymbolDisplayMiscellaneousOptions.UseSpecialTypes); AddToGroup(SymbolDescriptionGroups.MainDescription, ToDisplayParts(symbol.OriginalDefinition, style)); } else { AddToGroup(SymbolDescriptionGroups.MainDescription, ToDisplayParts(symbol.OriginalDefinition, s_descriptionStyle)); } if (!symbol.IsUnboundGenericType && !TypeArgumentsAndParametersAreSame(symbol)) { var allTypeParameters = symbol.GetAllTypeParameters().ToList(); var allTypeArguments = symbol.GetAllTypeArguments().ToList(); AddTypeParameterMapPart(allTypeParameters, allTypeArguments); } } private bool TypeArgumentsAndParametersAreSame(INamedTypeSymbol symbol) { var typeArguments = symbol.GetAllTypeArguments().ToList(); var typeParameters = symbol.GetAllTypeParameters().ToList(); for (int i = 0; i < typeArguments.Count; i++) { var typeArgument = typeArguments[i]; var typeParameter = typeParameters[i]; if (typeArgument is ITypeParameterSymbol && typeArgument.Name == typeParameter.Name) { continue; } return false; } return true; } private void AddDescriptionForNamespace(INamespaceSymbol symbol) { if (symbol.IsGlobalNamespace) { AddToGroup(SymbolDescriptionGroups.MainDescription, ToDisplayParts(symbol, s_globalNamespaceStyle)); } else { AddToGroup(SymbolDescriptionGroups.MainDescription, ToDisplayParts(symbol, s_descriptionStyle)); } } private async Task AddDescriptionForFieldAsync(IFieldSymbol symbol) { var parts = await GetFieldPartsAsync(symbol).ConfigureAwait(false); // Don't bother showing disambiguating text for enum members. The icon displayed // on Quick Info should be enough. if (symbol.ContainingType != null && symbol.ContainingType.TypeKind == TypeKind.Enum) { AddToGroup(SymbolDescriptionGroups.MainDescription, parts); } else { AddToGroup(SymbolDescriptionGroups.MainDescription, symbol.IsConst ? Description(FeaturesResources.constant) : Description(FeaturesResources.field), parts); } } private async Task<ImmutableArray<SymbolDisplayPart>> GetFieldPartsAsync(IFieldSymbol symbol) { if (symbol.IsConst) { var initializerParts = await GetInitializerSourcePartsAsync(symbol).ConfigureAwait(false); if (!initializerParts.IsDefaultOrEmpty) { var parts = ArrayBuilder<SymbolDisplayPart>.GetInstance(); parts.AddRange(ToMinimalDisplayParts(symbol, MinimallyQualifiedFormat)); parts.AddRange(Space()); parts.AddRange(Punctuation("=")); parts.AddRange(Space()); parts.AddRange(initializerParts); return parts.ToImmutableAndFree(); } } return ToMinimalDisplayParts(symbol, MinimallyQualifiedFormatWithConstants); } private async Task AddDescriptionForLocalAsync(ILocalSymbol symbol) { var parts = await GetLocalPartsAsync(symbol).ConfigureAwait(false); AddToGroup(SymbolDescriptionGroups.MainDescription, symbol.IsConst ? Description(FeaturesResources.local_constant) : Description(FeaturesResources.local_variable), parts); } private async Task<ImmutableArray<SymbolDisplayPart>> GetLocalPartsAsync(ILocalSymbol symbol) { if (symbol.IsConst) { var initializerParts = await GetInitializerSourcePartsAsync(symbol).ConfigureAwait(false); if (initializerParts != null) { var parts = ArrayBuilder<SymbolDisplayPart>.GetInstance(); parts.AddRange(ToMinimalDisplayParts(symbol, MinimallyQualifiedFormat)); parts.AddRange(Space()); parts.AddRange(Punctuation("=")); parts.AddRange(Space()); parts.AddRange(initializerParts); return parts.ToImmutableAndFree(); } } return ToMinimalDisplayParts(symbol, MinimallyQualifiedFormatWithConstants); } private void AddDescriptionForLabel(ILabelSymbol symbol) { AddToGroup(SymbolDescriptionGroups.MainDescription, Description(FeaturesResources.label), ToMinimalDisplayParts(symbol)); } private void AddDescriptionForRangeVariable(IRangeVariableSymbol symbol) { AddToGroup(SymbolDescriptionGroups.MainDescription, Description(FeaturesResources.range_variable), ToMinimalDisplayParts(symbol)); } private void AddDescriptionForMethod(IMethodSymbol method) { // TODO : show duplicated member case var awaitable = method.IsAwaitableNonDynamic(_semanticModel, _position); var extension = method.IsExtensionMethod || method.MethodKind == MethodKind.ReducedExtension; if (awaitable && extension) { AddAwaitableExtensionPrefix(); } else if (awaitable) { AddAwaitablePrefix(); } else if (extension) { AddExtensionPrefix(); } AddToGroup(SymbolDescriptionGroups.MainDescription, ToMinimalDisplayParts(method, s_memberSignatureDisplayFormat)); if (awaitable) { AddAwaitableUsageText(method, _semanticModel, _position); } } protected abstract void AddAwaitableUsageText(IMethodSymbol method, SemanticModel semanticModel, int position); private async Task AddDescriptionForParameterAsync(IParameterSymbol symbol) { if (symbol.IsOptional) { var initializerParts = await GetInitializerSourcePartsAsync(symbol).ConfigureAwait(false); if (!initializerParts.IsDefaultOrEmpty) { var parts = ToMinimalDisplayParts(symbol, MinimallyQualifiedFormat).ToList(); parts.AddRange(Space()); parts.AddRange(Punctuation("=")); parts.AddRange(Space()); parts.AddRange(initializerParts); AddToGroup(SymbolDescriptionGroups.MainDescription, Description(FeaturesResources.parameter), parts); return; } } AddToGroup(SymbolDescriptionGroups.MainDescription, Description(FeaturesResources.parameter), ToMinimalDisplayParts(symbol, MinimallyQualifiedFormatWithConstants)); } protected void AddDescriptionForProperty(IPropertySymbol symbol) { AddToGroup(SymbolDescriptionGroups.MainDescription, ToMinimalDisplayParts(symbol, s_memberSignatureDisplayFormat)); } private void AddDescriptionForArbitrarySymbol(ISymbol symbol) { AddToGroup(SymbolDescriptionGroups.MainDescription, ToMinimalDisplayParts(symbol)); } private void AddDescriptionForTypeParameter(ITypeParameterSymbol symbol) { Contract.ThrowIfTrue(symbol.TypeParameterKind == TypeParameterKind.Cref); AddToGroup(SymbolDescriptionGroups.MainDescription, ToMinimalDisplayParts(symbol), Space(), PlainText(FeaturesResources.in_), Space(), ToMinimalDisplayParts(symbol.ContainingSymbol, s_typeParameterOwnerFormat)); } private void AddOverloadCountPart( ImmutableArray<ISymbol> symbolGroup) { var count = GetOverloadCount(symbolGroup); if (count >= 1) { AddToGroup(SymbolDescriptionGroups.MainDescription, Space(), Punctuation("("), Punctuation("+"), Space(), PlainText(count.ToString()), Space(), count == 1 ? PlainText(FeaturesResources.overload) : PlainText(FeaturesResources.overloads_), Punctuation(")")); } } private static int GetOverloadCount(ImmutableArray<ISymbol> symbolGroup) { return symbolGroup.Select(s => s.OriginalDefinition) .Where(s => !s.Equals(symbolGroup.First().OriginalDefinition)) .Where(s => s is IMethodSymbol || s.IsIndexer()) .Count(); } protected void AddTypeParameterMapPart( List<ITypeParameterSymbol> typeParameters, List<ITypeSymbol> typeArguments) { var parts = new List<SymbolDisplayPart>(); var count = typeParameters.Count; for (int i = 0; i < count; i++) { parts.AddRange(TypeParameterName(typeParameters[i].Name)); parts.AddRange(Space()); parts.AddRange(PlainText(FeaturesResources.is_)); parts.AddRange(Space()); parts.AddRange(ToMinimalDisplayParts(typeArguments[i])); if (i < count - 1) { parts.AddRange(LineBreak()); } } AddToGroup(SymbolDescriptionGroups.TypeParameterMap, parts); } protected void AddToGroup(SymbolDescriptionGroups group, params SymbolDisplayPart[] partsArray) { AddToGroup(group, (IEnumerable<SymbolDisplayPart>)partsArray); } protected void AddToGroup(SymbolDescriptionGroups group, params IEnumerable<SymbolDisplayPart>[] partsArray) { var partsList = partsArray.Flatten().ToList(); if (partsList.Count > 0) { if (!_groupMap.TryGetValue(group, out var existingParts)) { existingParts = new List<SymbolDisplayPart>(); _groupMap.Add(group, existingParts); } existingParts.AddRange(partsList); } } private IEnumerable<SymbolDisplayPart> Description(string description) { return Punctuation("(") .Concat(PlainText(description)) .Concat(Punctuation(")")) .Concat(Space()); } protected IEnumerable<SymbolDisplayPart> Keyword(string text) { return Part(SymbolDisplayPartKind.Keyword, text); } protected IEnumerable<SymbolDisplayPart> LineBreak(int count = 1) { for (int i = 0; i < count; i++) { yield return new SymbolDisplayPart(SymbolDisplayPartKind.LineBreak, null, "\r\n"); } } protected IEnumerable<SymbolDisplayPart> PlainText(string text) { return Part(SymbolDisplayPartKind.Text, text); } protected IEnumerable<SymbolDisplayPart> Punctuation(string text) { return Part(SymbolDisplayPartKind.Punctuation, text); } protected IEnumerable<SymbolDisplayPart> Space(int count = 1) { yield return new SymbolDisplayPart(SymbolDisplayPartKind.Space, null, new string(' ', count)); } protected ImmutableArray<SymbolDisplayPart> ToMinimalDisplayParts(ISymbol symbol, SymbolDisplayFormat format = null) { format = format ?? MinimallyQualifiedFormat; return _displayService.ToMinimalDisplayParts(_semanticModel, _position, symbol, format); } protected IEnumerable<SymbolDisplayPart> ToDisplayParts(ISymbol symbol, SymbolDisplayFormat format = null) { return _displayService.ToDisplayParts(symbol, format); } private IEnumerable<SymbolDisplayPart> Part(SymbolDisplayPartKind kind, ISymbol symbol, string text) { yield return new SymbolDisplayPart(kind, symbol, text); } private IEnumerable<SymbolDisplayPart> Part(SymbolDisplayPartKind kind, string text) { return Part(kind, null, text); } private IEnumerable<SymbolDisplayPart> TypeParameterName(string text) { return Part(SymbolDisplayPartKind.TypeParameterName, text); } } } }
{ "content_hash": "f4270cfbe7c37843bc12e0cf17ea5e12", "timestamp": "", "source": "github", "line_count": 690, "max_line_length": 189, "avg_line_length": 43.94927536231884, "alnum_prop": 0.5565045342126957, "repo_name": "a-ctor/roslyn", "id": "efb4566058889a08676869016e6e1cce687e58b1", "size": "30487", "binary": false, "copies": "3", "ref": "refs/heads/master", "path": "src/Features/Core/Portable/LanguageServices/SymbolDisplayService/AbstractSymbolDisplayService.AbstractSymbolDescriptionBuilder.cs", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "1C Enterprise", "bytes": "289100" }, { "name": "Batchfile", "bytes": "20688" }, { "name": "C#", "bytes": "85699636" }, { "name": "C++", "bytes": "5392" }, { "name": "F#", "bytes": "3632" }, { "name": "Groovy", "bytes": "9673" }, { "name": "Makefile", "bytes": "3339" }, { "name": "PowerShell", "bytes": "66445" }, { "name": "Shell", "bytes": "7465" }, { "name": "Visual Basic", "bytes": "63276193" } ], "symlink_target": "" }
var bw_interface = (function (app) { 'use strict'; app.registerModule('bw-interface', ['Upload', 'ngFileUpload', 'ngMaterial', 'ngAnimate', 'core', 'core.routes', 'photoWorks', 'videoWorks', 'about']); app.registerModule('bw-interface.services'); }(ApplicationConfiguration));
{ "content_hash": "376fdf941884fcfb68e9c83aa03cf59c", "timestamp": "", "source": "github", "line_count": 7, "max_line_length": 99, "avg_line_length": 46, "alnum_prop": 0.6149068322981367, "repo_name": "joshm101/blackwashed_portfolio", "id": "a9dde921a58db41372f0aa9b399e6a130391198f", "size": "322", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "modules/bw-interface/client/bw-interface.client.module.js", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "2536813" }, { "name": "HTML", "bytes": "164991" }, { "name": "JavaScript", "bytes": "1088083" }, { "name": "PowerShell", "bytes": "468" }, { "name": "Shell", "bytes": "1509" } ], "symlink_target": "" }
package org.apache.doris.common.util; public class SqlUtils { public static String escapeUnquote(String ident) { return ident.replaceAll("``", "`"); } public static String getIdentSql(String ident) { StringBuilder sb = new StringBuilder(); sb.append('`'); for (char ch : ident.toCharArray()) { if (ch == '`') { sb.append("``"); } else { sb.append(ch); } } sb.append('`'); return sb.toString(); } }
{ "content_hash": "87d65398dce9705d406a6cba3418be9b", "timestamp": "", "source": "github", "line_count": 21, "max_line_length": 54, "avg_line_length": 25.714285714285715, "alnum_prop": 0.49444444444444446, "repo_name": "imay/palo", "id": "f1bd21ab5772fc58267a74ad0b57599500274ac3", "size": "1342", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "fe/src/main/java/org/apache/doris/common/util/SqlUtils.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "C", "bytes": "439083" }, { "name": "C++", "bytes": "9302365" }, { "name": "CMake", "bytes": "59781" }, { "name": "CSS", "bytes": "3843" }, { "name": "Java", "bytes": "6067362" }, { "name": "JavaScript", "bytes": "383133" }, { "name": "Lex", "bytes": "28991" }, { "name": "Makefile", "bytes": "9065" }, { "name": "Protocol Buffer", "bytes": "6901" }, { "name": "Python", "bytes": "124344" }, { "name": "Shell", "bytes": "31602" }, { "name": "Thrift", "bytes": "168000" }, { "name": "Yacc", "bytes": "96795" } ], "symlink_target": "" }
ACCEPTED #### According to The Catalogue of Life, 3rd January 2011 #### Published in null #### Original name null ### Remarks null
{ "content_hash": "69556500b5708db8cc07eadff0d653e0", "timestamp": "", "source": "github", "line_count": 13, "max_line_length": 39, "avg_line_length": 10.307692307692308, "alnum_prop": 0.6940298507462687, "repo_name": "mdoering/backbone", "id": "d6fe477ad9a47fce7629d71478349a3c747ed996", "size": "196", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "life/Plantae/Magnoliophyta/Magnoliopsida/Rosales/Rosaceae/Rubus/Rubus laciniatus/Rubus laciniatus elegans/README.md", "mode": "33188", "license": "apache-2.0", "language": [], "symlink_target": "" }
(function() { 'use strict'; angular .module('proyService1App') .controller('UserManagementDeleteController', UserManagementDeleteController); UserManagementDeleteController.$inject = ['$uibModalInstance', 'entity', 'User']; function UserManagementDeleteController ($uibModalInstance, entity, User) { var vm = this; vm.user = entity; vm.clear = clear; vm.confirmDelete = confirmDelete; function clear () { $uibModalInstance.dismiss('cancel'); } function confirmDelete (login) { User.delete({login: login}, function () { $uibModalInstance.close(true); }); } } })();
{ "content_hash": "d088a009c24880d0015b8bad30a91260", "timestamp": "", "source": "github", "line_count": 28, "max_line_length": 86, "avg_line_length": 26.642857142857142, "alnum_prop": 0.5670241286863271, "repo_name": "gcorreageek/dhl", "id": "8878906ff2462a164904bf6420a6d49031ce6173", "size": "746", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "backend/ProyService1/src/main/webapp/app/admin/user-management/user-management-delete-dialog.controller.js", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Batchfile", "bytes": "5006" }, { "name": "CSS", "bytes": "169646" }, { "name": "Groovy", "bytes": "751" }, { "name": "HTML", "bytes": "232673" }, { "name": "Java", "bytes": "481760" }, { "name": "JavaScript", "bytes": "286876" }, { "name": "Scala", "bytes": "26925" }, { "name": "Shell", "bytes": "7058" } ], "symlink_target": "" }
package id.birokrazy.model; import com.fasterxml.jackson.annotation.JsonIgnore; import id.birokrazy.model.oauth2.OauthClientDetails; import javax.persistence.*; import java.io.Serializable; import java.util.*; /** * @author Arthur Purnama ([email protected]) */ @Entity public class UserData implements Serializable { @Id @GeneratedValue() private Long id; @Version @Column(columnDefinition = "bigint default 0") private Long version; @Column(nullable = false, unique = true) private String username; @Column(nullable = false) private String name; @Column(nullable = false, unique = true) private String email; @OneToMany(mappedBy = "user") @JsonIgnore private List<Review> reviewList; @OneToOne private OauthClientDetails oauthClientDetails; @Transient private Set<String> roles; public Long getId() { return id; } public void setId(Long id) { this.id = id; } public Long getVersion() { return version; } public void setVersion(Long version) { this.version = version; } public String getUsername() { return username; } public void setUsername(String username) { this.username = username; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getEmail() { return email; } public void setEmail(String email) { this.email = email; } public List<Review> getReviewList() { return reviewList; } public void setReviewList(List<Review> reviewList) { this.reviewList = reviewList; } public OauthClientDetails getOauthClientDetails() { return oauthClientDetails; } public void setOauthClientDetails(OauthClientDetails oauthClientDetails) { this.oauthClientDetails = oauthClientDetails; } public Set<String> getRoles() { return roles; } public void setRoles(Set<String> roles) { this.roles = roles; } }
{ "content_hash": "4c7c6760a389727bfb9e059312bd5515", "timestamp": "", "source": "github", "line_count": 106, "max_line_length": 78, "avg_line_length": 19.92452830188679, "alnum_prop": 0.640625, "repo_name": "purnama/birokrazy", "id": "afc476eaff5fd17f673ab91c62943fb467157a87", "size": "2112", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "src/main/java/id/birokrazy/model/UserData.java", "mode": "33188", "license": "mit", "language": [ { "name": "Batchfile", "bytes": "5006" }, { "name": "CSS", "bytes": "10642" }, { "name": "HTML", "bytes": "221388" }, { "name": "Java", "bytes": "76855" }, { "name": "JavaScript", "bytes": "133793" }, { "name": "Shell", "bytes": "7300" } ], "symlink_target": "" }
<?php declare(strict_types=1); namespace Cake\Log\Engine; /** * Syslog stream for Logging. Writes logs to the system logger */ class SyslogLog extends BaseLog { /** * Default config for this class * * By default messages are formatted as: * level: message * * To override the log format (e.g. to add your own info) define the format key when configuring * this logger * * If you wish to include a prefix to all messages, for instance to identify the * application or the web server, then use the prefix option. Please keep in mind * the prefix is shared by all streams using syslog, as it is dependent of * the running process. For a local prefix, to be used only by one stream, you * can use the format key. * * ### Example: * * ``` * Log::config('error', ] * 'engine' => 'Syslog', * 'levels' => ['emergency', 'alert', 'critical', 'error'], * 'format' => "%s: My-App - %s", * 'prefix' => 'Web Server 01' * ]); * ``` * * @var array */ protected $_defaultConfig = [ 'levels' => [], 'scopes' => [], 'format' => '%s: %s', 'flag' => LOG_ODELAY, 'prefix' => '', 'facility' => LOG_USER, ]; /** * Used to map the string names back to their LOG_* constants * * @var int[] */ protected $_levelMap = [ 'emergency' => LOG_EMERG, 'alert' => LOG_ALERT, 'critical' => LOG_CRIT, 'error' => LOG_ERR, 'warning' => LOG_WARNING, 'notice' => LOG_NOTICE, 'info' => LOG_INFO, 'debug' => LOG_DEBUG, ]; /** * Whether the logger connection is open or not * * @var bool */ protected $_open = false; /** * Writes a message to syslog * * Map the $level back to a LOG_ constant value, split multi-line messages into multiple * log messages, pass all messages through the format defined in the configuration * * @param string $level The severity level of log you are making. * @param string $message The message you want to log. * @param array $context Additional information about the logged message * @return void */ public function log($level, $message, array $context = []): void { if (!$this->_open) { $config = $this->_config; $this->_open($config['prefix'], $config['flag'], $config['facility']); $this->_open = true; } $priority = LOG_DEBUG; if (isset($this->_levelMap[$level])) { $priority = $this->_levelMap[$level]; } $messages = explode("\n", $this->_format($message, $context)); foreach ($messages as $message) { $message = sprintf($this->_config['format'], $level, $message); $this->_write($priority, $message); } } /** * Extracts the call to openlog() in order to run unit tests on it. This function * will initialize the connection to the system logger * * @param string $ident the prefix to add to all messages logged * @param int $options the options flags to be used for logged messages * @param int $facility the stream or facility to log to * @return void */ protected function _open(string $ident, int $options, int $facility): void { openlog($ident, $options, $facility); } /** * Extracts the call to syslog() in order to run unit tests on it. This function * will perform the actual write in the system logger * * @param int $priority Message priority. * @param string $message Message to log. * @return bool */ protected function _write(int $priority, string $message): bool { return syslog($priority, $message); } /** * Closes the logger connection */ public function __destruct() { closelog(); } }
{ "content_hash": "a0f0a6297e125a65cdc4589a66e7bbfb", "timestamp": "", "source": "github", "line_count": 137, "max_line_length": 100, "avg_line_length": 29.255474452554743, "alnum_prop": 0.5588822355289421, "repo_name": "dakota/cakephp", "id": "05e782de315dcfcb9e2e0e79a76d18cf990e8e2e", "size": "4601", "binary": false, "copies": "1", "ref": "refs/heads/4.x", "path": "src/Log/Engine/SyslogLog.php", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "15730" }, { "name": "HTML", "bytes": "405" }, { "name": "Hack", "bytes": "752" }, { "name": "JavaScript", "bytes": "171" }, { "name": "Makefile", "bytes": "6407" }, { "name": "PHP", "bytes": "10180619" }, { "name": "Shell", "bytes": "723" } ], "symlink_target": "" }
@interface QLMFreeAudio : NSObject ///多余字段1 @property (nonatomic, strong) NSString *resource_content; ///多余字段2 @property (nonatomic, strong) NSString *image_url; ///音频内容 @property (nonatomic, strong) NSString *resource_name; ///音频地址 @property (nonatomic, strong) NSString *audio_file_url; @end
{ "content_hash": "4d4da12dd35bbf9542000f34c3bd4f33", "timestamp": "", "source": "github", "line_count": 15, "max_line_length": 57, "avg_line_length": 19.933333333333334, "alnum_prop": 0.7391304347826086, "repo_name": "FocusTheOne/Qomolangma", "id": "c5bc65c80a2fa9319d86083450d126db489e8bd0", "size": "502", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "Qomolangma/Qomolangma/Classes/Home/Model/QLMFreeAudio.h", "mode": "33188", "license": "mit", "language": [ { "name": "Assembly", "bytes": "19637" }, { "name": "Batchfile", "bytes": "2475" }, { "name": "C", "bytes": "423078" }, { "name": "C++", "bytes": "7816490" }, { "name": "CMake", "bytes": "25089" }, { "name": "Emacs Lisp", "bytes": "13142" }, { "name": "Go", "bytes": "13628" }, { "name": "M4", "bytes": "42090" }, { "name": "Makefile", "bytes": "949607" }, { "name": "Objective-C", "bytes": "3648269" }, { "name": "Objective-C++", "bytes": "199064" }, { "name": "Protocol Buffer", "bytes": "8872" }, { "name": "Python", "bytes": "2490215" }, { "name": "Ruby", "bytes": "1628" }, { "name": "Shell", "bytes": "397051" } ], "symlink_target": "" }
using SAD, Features, DocOpt, Stage S(sf) = mask(sf, filter = (kind, start, fin, file) -> kind == "S") NS(sf) = mask(sf, filter = (kind, start, fin, file) -> kind == "NS" || kind == "NT") # ---------------------------------------------------------------------------------------------------------------- # main # ---------------------------------------------------------------------------------------------------------------- usage = """RATS SAD Train/test script Usage: rats.jl [options] Options: --audio=dir, -a Audio Directory relative to current path [default: rats-sample] --test=M Marks for testing and threshold optimization --train=M Marks with marks for training --kmeans=s Do K-Means Initialization instead of binary splitting the argument is the sample size [default: 0] --model=s Name of output model [default: rats-sad.gmm] --iterations=i Number of EM training iterations to perform during GMM training [default: 5] --gaussians=g, -g Number of gaussians to target for final GMM (should be a power of two if binary splitting [default: 2] """ args = docopt(usage, ARGS, version=v"0.0.1") # train if args["--train"] != nothing @info "training with $(args["--train"]) using audio from $(args["--audio"]) with $(args["--gaussians"]) gaussians and $(args["--iterations"]) iterations" files = marks(args["--train"], dir = args["--audio"]) s, ns = int(args["--kmeans"]) > 0 ? kmeans_train(files, g = int(args["--gaussians"]), iterations = int(args["--iterations"]), sample_size = int(args["--kmeans"]), speech_frames = rats_speech, nonspeech_frames = rats_nonspeech) : split_train(files, splits = int(log2(int(args["--gaussians"]))), iterations = int(args["--iterations"]), speech_frames = rats_speech, nonspeech_frames = rats_nonspeech) outf = open(args["--model"], "w") serialize(outf, s) serialize(outf, ns) close(outf) end # score if args["--test"] != nothing f = open(args["--model"], "r") s = deserialize(f) ns = deserialize(f) close(f) files = marks(args["--test"], dir = args["--audio"], collars = { "S" => 0.25f0, "NS" => 0.1f0, "NT" => 0.1f0 }) threshold, opt_fa, opt_miss, opt_dc, fa, miss, eer, N_speech, N_ns = optimize(files, s, ns, speech_mask = S, nonspeech_mask = NS) @info "optimum threshold = $threshold [eer = $eer, fa rate = $opt_fa, miss rate = $opt_miss, decision cost = $opt_dc]" FAs, misses, N, decisions = test(files, s, ns, threshold = threshold, speech_mask = S, nonspeech_mask = NS) @info "FA rate = $(FAs / N_ns) (N = $FAs / $N_ns)" @info "Miss rate = $(misses / N_speech) (N = $misses / $N_speech)" @info "N = $N" end
{ "content_hash": "14418d0ad110f41a8db2608459bd30e2", "timestamp": "", "source": "github", "line_count": 55, "max_line_length": 164, "avg_line_length": 51.21818181818182, "alnum_prop": 0.5470358537451189, "repo_name": "mit-nlp/SAD.jl", "id": "1a39154f84deb2a66b98f13238e4304d52a76fdf", "size": "2817", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "test/rats.jl", "mode": "33261", "license": "mit", "language": [ { "name": "Julia", "bytes": "13784" } ], "symlink_target": "" }
using System; using System.Collections.Generic; using System.Data; using System.Linq; using System.Text; using System.Threading.Tasks; namespace QTFK.Extensions.DataSets { public static class DataSetExtension { public static T Get<T>(this DataRow dr, string name) { if (dr.IsNull(name)) return default(T); return (T)dr[name]; } public static T Get<T>(this DataRow dr, int index) { if (dr.IsNull(index)) return default(T); return (T)dr[index]; } public static DataTable AsTable(this DataSet ds) { if (ds == null || ds.Tables.Count <= 0) return null; return ds.Tables[0]; } public static IEnumerable<DataColumn> GetColumns(this DataRow row) { return row.Table.GetColumns(); } public static IEnumerable<DataColumn> GetColumns(this DataTable table) { var e = table.Columns.GetEnumerator(); while (e.MoveNext()) yield return e.Current as DataColumn; } public static IDictionary<string,object> ToDictionary(this DataRow row) { return row .GetColumns() .Select(c => c.ColumnName) //.Distinct() .ToDictionary(k => k, k => row.IsNull(k) ? null : row[k] ) ; } } }
{ "content_hash": "5ca6e8c5c3dd8ed4709275b2680bf5ee", "timestamp": "", "source": "github", "line_count": 56, "max_line_length": 79, "avg_line_length": 26.464285714285715, "alnum_prop": 0.5256410256410257, "repo_name": "hossmi/qtfk", "id": "ca0c743ea78dddc658ef55dbfb5d339c4ba84aa3", "size": "1484", "binary": false, "copies": "1", "ref": "refs/heads/develop", "path": "QTFK.Core/QTFK/Extensions/DataSets/DataSetExtension.cs", "mode": "33188", "license": "mit", "language": [ { "name": "C#", "bytes": "201790" } ], "symlink_target": "" }
<?php /** Zend_Search_Lucene_Search_Query */ #require_once 'Zend/Search/Lucene/Search/Query.php'; /** * @category Zend * @package Zend_Search_Lucene * @subpackage Search * @copyright Copyright (c) 2005-2010 Zend Technologies USA Inc. (http://www.zend.com) * @license http://framework.zend.com/license/new-bsd New BSD License */ class Zend_Search_Lucene_Search_Query_Wildcard extends Zend_Search_Lucene_Search_Query { /** * Search pattern. * * Field has to be fully specified or has to be null * Text may contain '*' or '?' symbols * * @var Zend_Search_Lucene_Index_Term */ private $_pattern; /** * Matched terms. * * Matched terms list. * It's filled during the search (rewrite operation) and may be used for search result * post-processing * * Array of Zend_Search_Lucene_Index_Term objects * * @var array */ private $_matches = null; /** * Minimum term prefix length (number of minimum non-wildcard characters) * * @var integer */ private static $_minPrefixLength = 3; /** * Zend_Search_Lucene_Search_Query_Wildcard constructor. * * @param Zend_Search_Lucene_Index_Term $pattern */ public function __construct(Zend_Search_Lucene_Index_Term $pattern) { $this->_pattern = $pattern; } /** * Get minimum prefix length * * @return integer */ public static function getMinPrefixLength() { return self::$_minPrefixLength; } /** * Set minimum prefix length * * @param integer $minPrefixLength */ public static function setMinPrefixLength($minPrefixLength) { self::$_minPrefixLength = $minPrefixLength; } /** * Get terms prefix * * @param string $word * @return string */ private static function _getPrefix($word) { $questionMarkPosition = strpos($word, '?'); $astrericPosition = strpos($word, '*'); if ($questionMarkPosition !== false) { if ($astrericPosition !== false) { return substr($word, 0, min($questionMarkPosition, $astrericPosition)); } return substr($word, 0, $questionMarkPosition); } else if ($astrericPosition !== false) { return substr($word, 0, $astrericPosition); } return $word; } /** * Re-write query into primitive queries in the context of specified index * * @param Zend_Search_Lucene_Interface $index * @return Zend_Search_Lucene_Search_Query * @throws Zend_Search_Lucene_Exception */ public function rewrite(Zend_Search_Lucene_Interface $index) { $this->_matches = array(); if ($this->_pattern->field === null) { // Search through all fields $fields = $index->getFieldNames(true /* indexed fields list */); } else { $fields = array($this->_pattern->field); } $prefix = self::_getPrefix($this->_pattern->text); $prefixLength = strlen($prefix); $matchExpression = '/^' . str_replace(array('\\?', '\\*'), array('.', '.*') , preg_quote($this->_pattern->text, '/')) . '$/'; if ($prefixLength < self::$_minPrefixLength) { #require_once 'Zend/Search/Lucene/Exception.php'; throw new Zend_Search_Lucene_Exception('At least ' . self::$_minPrefixLength . ' non-wildcard characters are required at the beginning of pattern.'); } /** @todo check for PCRE unicode support may be performed through Zend_Environment in some future */ if (@preg_match('/\pL/u', 'a') == 1) { // PCRE unicode support is turned on // add Unicode modifier to the match expression $matchExpression .= 'u'; } $maxTerms = Zend_Search_Lucene::getTermsPerQueryLimit(); foreach ($fields as $field) { $index->resetTermsStream(); #require_once 'Zend/Search/Lucene/Index/Term.php'; if ($prefix != '') { $index->skipTo(new Zend_Search_Lucene_Index_Term($prefix, $field)); while ($index->currentTerm() !== null && $index->currentTerm()->field == $field && substr($index->currentTerm()->text, 0, $prefixLength) == $prefix) { if (preg_match($matchExpression, $index->currentTerm()->text) === 1) { $this->_matches[] = $index->currentTerm(); if ($maxTerms != 0 && count($this->_matches) > $maxTerms) { #require_once 'Zend/Search/Lucene/Exception.php'; throw new Zend_Search_Lucene_Exception('Terms per query limit is reached.'); } } $index->nextTerm(); } } else { $index->skipTo(new Zend_Search_Lucene_Index_Term('', $field)); while ($index->currentTerm() !== null && $index->currentTerm()->field == $field) { if (preg_match($matchExpression, $index->currentTerm()->text) === 1) { $this->_matches[] = $index->currentTerm(); if ($maxTerms != 0 && count($this->_matches) > $maxTerms) { #require_once 'Zend/Search/Lucene/Exception.php'; throw new Zend_Search_Lucene_Exception('Terms per query limit is reached.'); } } $index->nextTerm(); } } $index->closeTermsStream(); } if (count($this->_matches) == 0) { #require_once 'Zend/Search/Lucene/Search/Query/Empty.php'; return new Zend_Search_Lucene_Search_Query_Empty(); } else if (count($this->_matches) == 1) { #require_once 'Zend/Search/Lucene/Search/Query/Term.php'; return new Zend_Search_Lucene_Search_Query_Term(reset($this->_matches)); } else { #require_once 'Zend/Search/Lucene/Search/Query/MultiTerm.php'; $rewrittenQuery = new Zend_Search_Lucene_Search_Query_MultiTerm(); foreach ($this->_matches as $matchedTerm) { $rewrittenQuery->addTerm($matchedTerm); } return $rewrittenQuery; } } /** * Optimize query in the context of specified index * * @param Zend_Search_Lucene_Interface $index * @return Zend_Search_Lucene_Search_Query */ public function optimize(Zend_Search_Lucene_Interface $index) { #require_once 'Zend/Search/Lucene/Exception.php'; throw new Zend_Search_Lucene_Exception('Wildcard query should not be directly used for search. Use $query->rewrite($index)'); } /** * Returns query pattern * * @return Zend_Search_Lucene_Index_Term */ public function getPattern() { return $this->_pattern; } /** * Return query terms * * @return array * @throws Zend_Search_Lucene_Exception */ public function getQueryTerms() { if ($this->_matches === null) { #require_once 'Zend/Search/Lucene/Exception.php'; throw new Zend_Search_Lucene_Exception('Search has to be performed first to get matched terms'); } return $this->_matches; } /** * Constructs an appropriate Weight implementation for this query. * * @param Zend_Search_Lucene_Interface $reader * @return Zend_Search_Lucene_Search_Weight * @throws Zend_Search_Lucene_Exception */ public function createWeight(Zend_Search_Lucene_Interface $reader) { #require_once 'Zend/Search/Lucene/Exception.php'; throw new Zend_Search_Lucene_Exception('Wildcard query should not be directly used for search. Use $query->rewrite($index)'); } /** * Execute query in context of index reader * It also initializes necessary internal structures * * @param Zend_Search_Lucene_Interface $reader * @param Zend_Search_Lucene_Index_DocsFilter|null $docsFilter * @throws Zend_Search_Lucene_Exception */ public function execute(Zend_Search_Lucene_Interface $reader, $docsFilter = null) { #require_once 'Zend/Search/Lucene/Exception.php'; throw new Zend_Search_Lucene_Exception('Wildcard query should not be directly used for search. Use $query->rewrite($index)'); } /** * Get document ids likely matching the query * * It's an array with document ids as keys (performance considerations) * * @return array * @throws Zend_Search_Lucene_Exception */ public function matchedDocs() { #require_once 'Zend/Search/Lucene/Exception.php'; throw new Zend_Search_Lucene_Exception('Wildcard query should not be directly used for search. Use $query->rewrite($index)'); } /** * Score specified document * * @param integer $docId * @param Zend_Search_Lucene_Interface $reader * @return float * @throws Zend_Search_Lucene_Exception */ public function score($docId, Zend_Search_Lucene_Interface $reader) { #require_once 'Zend/Search/Lucene/Exception.php'; throw new Zend_Search_Lucene_Exception('Wildcard query should not be directly used for search. Use $query->rewrite($index)'); } /** * Query specific matches highlighting * * @param Zend_Search_Lucene_Search_Highlighter_Interface $highlighter Highlighter object (also contains doc for highlighting) */ protected function _highlightMatches(Zend_Search_Lucene_Search_Highlighter_Interface $highlighter) { $words = array(); $matchExpression = '/^' . str_replace(array('\\?', '\\*'), array('.', '.*') , preg_quote($this->_pattern->text, '/')) . '$/'; if (@preg_match('/\pL/u', 'a') == 1) { // PCRE unicode support is turned on // add Unicode modifier to the match expression $matchExpression .= 'u'; } $docBody = $highlighter->getDocument()->getFieldUtf8Value('body'); #require_once 'Zend/Search/Lucene/Analysis/Analyzer.php'; $tokens = Zend_Search_Lucene_Analysis_Analyzer::getDefault()->tokenize($docBody, 'UTF-8'); foreach ($tokens as $token) { if (preg_match($matchExpression, $token->getTermText()) === 1) { $words[] = $token->getTermText(); } } $highlighter->highlight($words); } /** * Print a query * * @return string */ public function __toString() { // It's used only for query visualisation, so we don't care about characters escaping if ($this->_pattern->field !== null) { $query = $this->_pattern->field . ':'; } else { $query = ''; } $query .= $this->_pattern->text; if ($this->getBoost() != 1) { $query = $query . '^' . round($this->getBoost(), 4); } return $query; } }
{ "content_hash": "245eacf5e14c05c34e7e73b4fa1cfe1c", "timestamp": "", "source": "github", "line_count": 343, "max_line_length": 161, "avg_line_length": 32.86588921282799, "alnum_prop": 0.5675507850616517, "repo_name": "StudioBOZ/thirdClass", "id": "cf69cb4fa3b6777cfdebad9af0d8db226651b28f", "size": "12044", "binary": false, "copies": "27", "ref": "refs/heads/master", "path": "lib/Zend/Search/Lucene/Search/Query/Wildcard.php", "mode": "33188", "license": "mit", "language": [ { "name": "ActionScript", "bytes": "19946" }, { "name": "CSS", "bytes": "1291126" }, { "name": "JavaScript", "bytes": "1277438" }, { "name": "PHP", "bytes": "43528858" }, { "name": "Shell", "bytes": "717" }, { "name": "XSLT", "bytes": "2135" } ], "symlink_target": "" }
require_relative 'provider/digital_ocean' module BinarySolo module Provider def all [DigitalOcean] end def default all.first end def supported?(name=nil) find_by_name(name).present? end def find_by_name(name=nil) all.find { |p| p.name == name } end extend self end end
{ "content_hash": "a9053f8501a557623d5720d091800563", "timestamp": "", "source": "github", "line_count": 25, "max_line_length": 41, "avg_line_length": 13.64, "alnum_prop": 0.6041055718475073, "repo_name": "felixroeser/binarysolo", "id": "4448fd093bfd98142ff151f78331b04057456709", "size": "341", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "lib/binary_solo/provider.rb", "mode": "33188", "license": "mit", "language": [ { "name": "Ruby", "bytes": "42230" } ], "symlink_target": "" }
Keys A **key** means a cryptographic key, used for HMAC-based authentication of certain requests. Keys are used to allow third party software to communicate with the RunOrg API through an insecure channel, such as through tokens handled in the client browser. For instance, you can use keys to [securely authenticate](/docs/#/contact/hmac.js) an user that is already logged into another service you control: 1. Dave, the _developer_, generates a new **key** (a random sequence of bytes) and registers it with API using the [create key](/docs/#/key/create.js) endpoint. This yields a **key-id**. 2. Dave then stores both the key and the key-id in MyTestApp (his own application). 3. Alice, the _user_, connects to MyTestApp. 4. MyTestApp creates an **assertion** that says "Until date X, assume the holder of this assertion to be Alice", and computes a cryptographic **proof** by applying `HMAC-SHA1(key,assertion)`. 5. Alice receives the assertion, the proof and the key-id from MyTestApp, and sends it to RunOrg. 6. RunOrg uses the key-id to retrieve the key from its internal database, computes `HMAC-SHA1(key,assertion)` and compares it with the provided proof. If they match, then it is certain that the assertion was generated by MyTestApp, and so RunOrg authenticates Alice. 7. Alice receives a RunOrg token and can start using the API. It is recommended to keep one API key for each third party application, and to disable individual keys if they are leaked or become too old.
{ "content_hash": "276d4269f4f4a7bc372b8123bf8c74fc", "timestamp": "", "source": "github", "line_count": 30, "max_line_length": 83, "avg_line_length": 50.86666666666667, "alnum_prop": 0.752948885976409, "repo_name": "RunOrg/RunOrg", "id": "a89aac7b31cbc8d104c9d741ba9d705796ce7e7e", "size": "1526", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "test/key.md", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "15641" }, { "name": "HTML", "bytes": "7273" }, { "name": "JavaScript", "bytes": "183305" }, { "name": "Makefile", "bytes": "1416" }, { "name": "OCaml", "bytes": "626227" }, { "name": "Shell", "bytes": "681" }, { "name": "Standard ML", "bytes": "369" } ], "symlink_target": "" }
using extension_function_test_utils::CreateEmptyExtension; using extension_function_test_utils::RunFunctionAndReturnSingleResult; namespace { class DnsApiTest : public ExtensionApiTest { public: DnsApiTest() : resolver_event_(true, false), resolver_creator_(new extensions::MockHostResolverCreator()) { } virtual void SetUpCommandLine(CommandLine* command_line) OVERRIDE { ExtensionApiTest::SetUpCommandLine(command_line); command_line->AppendSwitch(switches::kEnableExperimentalExtensionApis); } virtual void SetUpOnMainThread() OVERRIDE { extensions::HostResolverWrapper::GetInstance()->SetHostResolverForTesting( resolver_creator_->CreateMockHostResolver()); } virtual void CleanUpOnMainThread() OVERRIDE { extensions::HostResolverWrapper::GetInstance()-> SetHostResolverForTesting(NULL); resolver_creator_->DeleteMockHostResolver(); } private: base::WaitableEvent resolver_event_; // The MockHostResolver asserts that it's used on the same thread on which // it's created, which is actually a stronger rule than its real counterpart. // But that's fine; it's good practice. scoped_refptr<extensions::MockHostResolverCreator> resolver_creator_; }; } // namespace IN_PROC_BROWSER_TEST_F(DnsApiTest, DnsResolveIPLiteral) { scoped_refptr<extensions::DnsResolveFunction> resolve_function( new extensions::DnsResolveFunction()); scoped_refptr<extensions::Extension> empty_extension(CreateEmptyExtension()); resolve_function->set_extension(empty_extension.get()); resolve_function->set_has_callback(true); scoped_ptr<base::Value> result(RunFunctionAndReturnSingleResult( resolve_function.get(), "[\"127.0.0.1\"]", browser())); ASSERT_EQ(base::Value::TYPE_DICTIONARY, result->GetType()); base::DictionaryValue *value = static_cast<base::DictionaryValue*>(result.get()); int resultCode; EXPECT_TRUE(value->GetInteger("resultCode", &resultCode)); EXPECT_EQ(net::OK, resultCode); std::string address; EXPECT_TRUE(value->GetString("address", &address)); EXPECT_EQ("127.0.0.1", address); } IN_PROC_BROWSER_TEST_F(DnsApiTest, DnsResolveHostname) { scoped_refptr<extensions::DnsResolveFunction> resolve_function( new extensions::DnsResolveFunction()); scoped_refptr<extensions::Extension> empty_extension(CreateEmptyExtension()); resolve_function->set_extension(empty_extension.get()); resolve_function->set_has_callback(true); std::string function_arguments("[\""); function_arguments += extensions::MockHostResolverCreator::kHostname; function_arguments += "\"]"; scoped_ptr<base::Value> result( RunFunctionAndReturnSingleResult(resolve_function.get(), function_arguments, browser())); ASSERT_EQ(base::Value::TYPE_DICTIONARY, result->GetType()); base::DictionaryValue *value = static_cast<base::DictionaryValue*>(result.get()); int resultCode; EXPECT_TRUE(value->GetInteger("resultCode", &resultCode)); EXPECT_EQ(net::OK, resultCode); std::string address; EXPECT_TRUE(value->GetString("address", &address)); EXPECT_EQ(extensions::MockHostResolverCreator::kAddress, address); } IN_PROC_BROWSER_TEST_F(DnsApiTest, DnsExtension) { ASSERT_TRUE(RunExtensionTest("dns/api")) << message_; }
{ "content_hash": "387369ceb75ccaf66f53a9fac7119ad0", "timestamp": "", "source": "github", "line_count": 91, "max_line_length": 79, "avg_line_length": 36.38461538461539, "alnum_prop": 0.7308970099667774, "repo_name": "espadrine/opera", "id": "ccd960228c5702e0693ac1847eb7d63e174ab2bd", "size": "4026", "binary": false, "copies": "3", "ref": "refs/heads/master", "path": "chromium/src/chrome/browser/extensions/api/dns/dns_apitest.cc", "mode": "33188", "license": "bsd-3-clause", "language": [], "symlink_target": "" }
import React from 'react'; import PropTypes from 'prop-types'; import { pageToTitleI18n } from 'docs/src/modules/utils/helpers'; import PageContext from 'docs/src/modules/components/PageContext'; // TODO: it really wants to be named useTitle but we're not quite there yet. function PageTitle(props) { const { activePage } = React.useContext(PageContext); if (!activePage) { throw new Error('Missing activePage.'); } const title = pageToTitleI18n(activePage, props.t); return props.children(title); } PageTitle.propTypes = { children: PropTypes.func.isRequired, }; export default PageTitle;
{ "content_hash": "28f2b5786d337c12735d7ce40e8f892b", "timestamp": "", "source": "github", "line_count": 23, "max_line_length": 76, "avg_line_length": 26.608695652173914, "alnum_prop": 0.7401960784313726, "repo_name": "allanalexandre/material-ui", "id": "8580a7e2b5f052fce36308e065799e82996de4b1", "size": "612", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "docs/src/modules/components/PageTitle.js", "mode": "33188", "license": "mit", "language": [ { "name": "JavaScript", "bytes": "929297" } ], "symlink_target": "" }
import { lazyComponent } from '@waldur/core/lazyComponent'; import { StateDeclaration } from '@waldur/core/types'; import { checkPermission } from '@waldur/issues/utils'; const SupportDetailsContainer = lazyComponent( () => import( /* webpackChunkName: "SupportDetailsContainer" */ './SupportDetailsContainer' ), 'SupportDetailsContainer', ); const SupportEventsContainer = lazyComponent( () => import( /* webpackChunkName: "SupportEventsContainer" */ './SupportEventsContainer' ), 'SupportEventsContainer', ); export const states: StateDeclaration[] = [ { name: 'project.support-details', url: 'support/:resource_uuid/', component: SupportDetailsContainer, }, { name: 'support.events', url: 'events/', component: SupportEventsContainer, resolve: { permission: checkPermission, }, }, ];
{ "content_hash": "fc88f72fded64cbe71fa1e2d78ca8949", "timestamp": "", "source": "github", "line_count": 35, "max_line_length": 83, "avg_line_length": 24.914285714285715, "alnum_prop": 0.676605504587156, "repo_name": "opennode/waldur-homeport", "id": "c5f59bdf3e41c6b7d53b3669896f49b5c29dd54b", "size": "872", "binary": false, "copies": "1", "ref": "refs/heads/develop", "path": "src/support/routes.ts", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "181090" }, { "name": "Dockerfile", "bytes": "808" }, { "name": "HTML", "bytes": "195802" }, { "name": "JavaScript", "bytes": "1231952" }, { "name": "Shell", "bytes": "363" }, { "name": "TypeScript", "bytes": "1637778" } ], "symlink_target": "" }
// Copyright 2015 The Prometheus Authors // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // Types for unmarshalling gmond's XML output. // // Not used elements in gmond's XML output are commented. // In case you want to use them, please change the names so that one // can understand without needing to know what the acronym stands for. package ganglia import "encoding/xml" type ExtraElement struct { Name string `xml:"NAME,attr"` Val string `xml:"VAL,attr"` } type ExtraData struct { ExtraElements []ExtraElement `xml:"EXTRA_ELEMENT"` } type Metric struct { Name string `xml:"NAME,attr"` Value float64 `xml:"VAL,attr"` /* Unit string `xml:"UNITS,attr"` Slope string `xml:"SLOPE,attr"` Tn int `xml:"TN,attr"` Tmax int `xml:"TMAX,attr"` Dmax int `xml:"DMAX,attr"` */ ExtraData ExtraData `xml:"EXTRA_DATA"` } type Host struct { Name string `xml:"NAME,attr"` /* Ip string `xml:"IP,attr"` Tags string `xml:"TAGS,attr"` Reported int `xml:"REPORTED,attr"` Tn int `xml:"TN,attr"` Tmax int `xml:"TMAX,attr"` Dmax int `xml:"DMAX,attr"` Location string `xml:"LOCATION,attr"` GmondStarted int `xml:"GMOND_STARTED",attr"` */ Metrics []Metric `xml:"METRIC"` } type Cluster struct { Name string `xml:"NAME,attr"` /* Owner string `xml:"OWNER,attr"` LatLong string `xml:"LATLONG,attr"` Url string `xml:"URL,attr"` Localtime int `xml:"LOCALTIME,attr"` */ Hosts []Host `xml:"HOST"` } type Ganglia struct { XMLNAME xml.Name `xml:"GANGLIA_XML"` Clusters []Cluster `xml:"CLUSTER"` }
{ "content_hash": "b924d00b650c8f03ee27b0c6c98d6b1d", "timestamp": "", "source": "github", "line_count": 74, "max_line_length": 75, "avg_line_length": 29.22972972972973, "alnum_prop": 0.6592695330559408, "repo_name": "kirussel/node_exporter", "id": "92c7b7903e4cc287a182c6678dd78eb86d40de31", "size": "2163", "binary": false, "copies": "10", "ref": "refs/heads/master", "path": "collector/ganglia/format.go", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Go", "bytes": "138336" }, { "name": "Makefile", "bytes": "701" }, { "name": "Shell", "bytes": "2097" } ], "symlink_target": "" }
package org.andengine.entity.sprite.batch; import org.andengine.engine.camera.Camera; import org.andengine.entity.IEntity; import org.andengine.entity.shape.IShape; import org.andengine.entity.shape.Shape; import org.andengine.entity.sprite.Sprite; import org.andengine.entity.sprite.batch.vbo.HighPerformanceSpriteBatchVertexBufferObject; import org.andengine.entity.sprite.batch.vbo.ISpriteBatchVertexBufferObject; import org.andengine.opengl.shader.PositionColorTextureCoordinatesShaderProgram; import org.andengine.opengl.shader.ShaderProgram; import org.andengine.opengl.shader.constants.ShaderProgramConstants; import org.andengine.opengl.texture.ITexture; import org.andengine.opengl.texture.region.ITextureRegion; import org.andengine.opengl.util.GLState; import org.andengine.opengl.vbo.DrawType; import org.andengine.opengl.vbo.VertexBufferObjectManager; import org.andengine.opengl.vbo.attribute.VertexBufferObjectAttributes; import org.andengine.opengl.vbo.attribute.VertexBufferObjectAttributesBuilder; import org.andengine.util.adt.transformation.Transformation; import org.andengine.util.color.ColorUtils; import android.opengl.GLES20; /** * TODO TRY DEGENERATE TRIANGLES! * TODO Check if there is this multiple-of-X-byte(?) alignment optimization? * * (c) 2010 Nicolas Gramlich * (c) 2011 Zynga Inc. * * @author Nicolas Gramlich * @since 11:45:48 - 14.06.2011 */ public class SpriteBatch extends Shape { // =========================================================== // Constants // =========================================================== private static final float[] VERTICES_TMP = new float[8]; private static final Transformation TRANSFORATION_TMP = new Transformation(); public static final int VERTEX_INDEX_X = 0; public static final int VERTEX_INDEX_Y = SpriteBatch.VERTEX_INDEX_X + 1; public static final int COLOR_INDEX = SpriteBatch.VERTEX_INDEX_Y + 1; public static final int TEXTURECOORDINATES_INDEX_U = SpriteBatch.COLOR_INDEX + 1; public static final int TEXTURECOORDINATES_INDEX_V = SpriteBatch.TEXTURECOORDINATES_INDEX_U + 1; public static final int VERTEX_SIZE = 2 + 1 + 2; public static final int VERTICES_PER_SPRITE = 6; public static final int SPRITE_SIZE = SpriteBatch.VERTEX_SIZE * SpriteBatch.VERTICES_PER_SPRITE; public static final VertexBufferObjectAttributes VERTEXBUFFEROBJECTATTRIBUTES_DEFAULT = new VertexBufferObjectAttributesBuilder(3) .add(ShaderProgramConstants.ATTRIBUTE_POSITION_LOCATION, ShaderProgramConstants.ATTRIBUTE_POSITION, 2, GLES20.GL_FLOAT, false) .add(ShaderProgramConstants.ATTRIBUTE_COLOR_LOCATION, ShaderProgramConstants.ATTRIBUTE_COLOR, 4, GLES20.GL_UNSIGNED_BYTE, true) .add(ShaderProgramConstants.ATTRIBUTE_TEXTURECOORDINATES_LOCATION, ShaderProgramConstants.ATTRIBUTE_TEXTURECOORDINATES, 2, GLES20.GL_FLOAT, false) .build(); // =========================================================== // Fields // =========================================================== protected ITexture mTexture; protected final int mCapacity; protected final ISpriteBatchVertexBufferObject mSpriteBatchVertexBufferObject; protected int mIndex; protected int mVertices; // =========================================================== // Constructors // =========================================================== public SpriteBatch(final ITexture pTexture, final int pCapacity, final VertexBufferObjectManager pVertexBufferObjectManager) { this(pTexture, pCapacity, pVertexBufferObjectManager, DrawType.STATIC); } public SpriteBatch(final float pX, final float pY, final ITexture pTexture, final int pCapacity, final VertexBufferObjectManager pVertexBufferObjectManager) { this(pX, pY, pTexture, pCapacity, pVertexBufferObjectManager, DrawType.STATIC); } public SpriteBatch(final ITexture pTexture, final int pCapacity, final VertexBufferObjectManager pVertexBufferObjectManager, final DrawType pDrawType) { this(pTexture, pCapacity, new HighPerformanceSpriteBatchVertexBufferObject(pVertexBufferObjectManager, pCapacity * SpriteBatch.SPRITE_SIZE, pDrawType, true, SpriteBatch.VERTEXBUFFEROBJECTATTRIBUTES_DEFAULT)); } public SpriteBatch(final float pX, final float pY, final ITexture pTexture, final int pCapacity, final VertexBufferObjectManager pVertexBufferObjectManager, final DrawType pDrawType) { this(pX, pY, pTexture, pCapacity, new HighPerformanceSpriteBatchVertexBufferObject(pVertexBufferObjectManager, pCapacity * SpriteBatch.SPRITE_SIZE, pDrawType, true, SpriteBatch.VERTEXBUFFEROBJECTATTRIBUTES_DEFAULT)); } public SpriteBatch(final ITexture pTexture, final int pCapacity, final VertexBufferObjectManager pVertexBufferObjectManager, final ShaderProgram pShaderProgram) { this(pTexture, pCapacity, pVertexBufferObjectManager, DrawType.STATIC, pShaderProgram); } public SpriteBatch(final float pX, final float pY, final ITexture pTexture, final VertexBufferObjectManager pVertexBufferObjectManager, final int pCapacity, final ShaderProgram pShaderProgram) { this(pX, pY, pTexture, pCapacity, pVertexBufferObjectManager, DrawType.STATIC, pShaderProgram); } public SpriteBatch(final ITexture pTexture, final int pCapacity, final VertexBufferObjectManager pVertexBufferObjectManager, final DrawType pDrawType, final ShaderProgram pShaderProgram) { this(pTexture, pCapacity, new HighPerformanceSpriteBatchVertexBufferObject(pVertexBufferObjectManager, pCapacity * SpriteBatch.SPRITE_SIZE, pDrawType, true, SpriteBatch.VERTEXBUFFEROBJECTATTRIBUTES_DEFAULT), pShaderProgram); } public SpriteBatch(final float pX, final float pY, final ITexture pTexture, final int pCapacity, final VertexBufferObjectManager pVertexBufferObjectManager, final DrawType pDrawType, final ShaderProgram pShaderProgram) { this(pX, pY, pTexture, pCapacity, new HighPerformanceSpriteBatchVertexBufferObject(pVertexBufferObjectManager, pCapacity * SpriteBatch.SPRITE_SIZE, pDrawType, true, SpriteBatch.VERTEXBUFFEROBJECTATTRIBUTES_DEFAULT), pShaderProgram); } public SpriteBatch(final ITexture pTexture, final int pCapacity, final ISpriteBatchVertexBufferObject pSpriteBatchVertexBufferObject) { this(pTexture, pCapacity, pSpriteBatchVertexBufferObject, PositionColorTextureCoordinatesShaderProgram.getInstance()); } public SpriteBatch(final float pX, final float pY, final ITexture pTexture, final int pCapacity, final ISpriteBatchVertexBufferObject pSpriteBatchVertexBufferObject) { this(pX, pY, pTexture, pCapacity, pSpriteBatchVertexBufferObject, PositionColorTextureCoordinatesShaderProgram.getInstance()); } public SpriteBatch(final ITexture pTexture, final int pCapacity, final ISpriteBatchVertexBufferObject pSpriteBatchVertexBufferObject, final ShaderProgram pShaderProgram) { this(0, 0, pTexture, pCapacity, pSpriteBatchVertexBufferObject, pShaderProgram); } public SpriteBatch(final float pX, final float pY, final ITexture pTexture, final int pCapacity, final ISpriteBatchVertexBufferObject pSpriteBatchVertexBufferObject, final ShaderProgram pShaderProgram) { super(pX, pY, pShaderProgram); this.mTexture = pTexture; this.mCapacity = pCapacity; this.mSpriteBatchVertexBufferObject = pSpriteBatchVertexBufferObject; this.setBlendingEnabled(true); this.initBlendFunction(this.mTexture); } // =========================================================== // Getter & Setter // =========================================================== public int getIndex() { return this.mIndex; } public ITexture getTexture() { return this.mTexture; } public void setTexture(final ITexture pTexture) { this.mTexture = pTexture; } public void setIndex(final int pIndex) { this.assertCapacity(pIndex); this.mIndex = pIndex; final int bufferDataOffset = pIndex * SpriteBatch.SPRITE_SIZE; this.mSpriteBatchVertexBufferObject.setBufferDataOffset(bufferDataOffset); } // =========================================================== // Methods for/from SuperClass/Interfaces // =========================================================== @Override public ISpriteBatchVertexBufferObject getVertexBufferObject() { return this.mSpriteBatchVertexBufferObject; } @Override public boolean collidesWith(final IShape pOtherShape) { return false; } @Override public boolean contains(final float pX, final float pY) { return false; } @Override protected void onUpdateVertices() { /* Nothing. */ } @Override protected void preDraw(final GLState pGLState, final Camera pCamera) { super.preDraw(pGLState, pCamera); if(this.mBlendingEnabled) { pGLState.enableBlend(); pGLState.blendFunction(this.mBlendFunctionSource, this.mBlendFunctionDestination); } this.mTexture.bind(pGLState); this.mSpriteBatchVertexBufferObject.bind(pGLState, this.mShaderProgram); } @Override protected void draw(final GLState pGLState, final Camera pCamera) { this.begin(); this.mSpriteBatchVertexBufferObject.draw(GLES20.GL_TRIANGLES, this.mVertices); this.end(); } @Override protected void postDraw(final GLState pGLState, final Camera pCamera) { this.mSpriteBatchVertexBufferObject.unbind(pGLState, this.mShaderProgram); if(this.mBlendingEnabled) { pGLState.disableBlend(); } super.postDraw(pGLState, pCamera); } @Override public void reset() { super.reset(); this.initBlendFunction(this.mTexture); } @Override public void dispose() { super.dispose(); if(this.mSpriteBatchVertexBufferObject != null && this.mSpriteBatchVertexBufferObject.isAutoDispose() && !this.mSpriteBatchVertexBufferObject.isDisposed()) { this.mSpriteBatchVertexBufferObject.dispose(); } } // =========================================================== // Methods // =========================================================== protected void begin() { // GLState.disableDepthMask(pGL); // TODO Test effect of this } protected void end() { // GLState.enableDepthMask(pGL); } /** * @see {@link SpriteBatchVertexBufferObject#add(ITextureRegion, float, float, float, float, float, float, float)}. */ public void draw(final ITextureRegion pTextureRegion, final float pX, final float pY, final float pWidth, final float pHeight, final float pRed, final float pGreen, final float pBlue, final float pAlpha) { this.assertCapacity(); this.assertTexture(pTextureRegion); this.add(pTextureRegion, pX, pY, pWidth, pHeight, pRed, pGreen, pBlue, pAlpha); this.mIndex++; } public void drawWithoutChecks(final ITextureRegion pTextureRegion, final float pX, final float pY, final float pWidth, final float pHeight, final float pRed, final float pGreen, final float pBlue, final float pAlpha) { this.add(pTextureRegion, pX, pY, pWidth, pHeight, pRed, pGreen, pBlue, pAlpha); this.mIndex++; } /** * @see {@link SpriteBatchVertexBufferObject#add(ITextureRegion, float, float, float, float, float)}. */ public void draw(final ITextureRegion pTextureRegion, final float pX, final float pY, final float pWidth, final float pHeight, final float pColorABGRPackedInt) { this.assertCapacity(); this.assertTexture(pTextureRegion); this.add(pTextureRegion, pX, pY, pWidth, pHeight, pColorABGRPackedInt); this.mIndex++; } public void drawWithoutChecks(final ITextureRegion pTextureRegion, final float pX, final float pY, final float pWidth, final float pHeight, final float pColorABGRPackedInt) { this.add(pTextureRegion, pX, pY, pWidth, pHeight, pColorABGRPackedInt); this.mIndex++; } /** * @see {@link SpriteBatchVertexBufferObject#add(ITextureRegion, float, float, float, float, float, float, float, float)}. */ public void draw(final ITextureRegion pTextureRegion, final float pX, final float pY, final float pWidth, final float pHeight, final float pRotation, final float pRed, final float pGreen, final float pBlue, final float pAlpha) { this.assertCapacity(); this.assertTexture(pTextureRegion); this.add(pTextureRegion, pX, pY, pWidth, pHeight, pRotation, pRed, pGreen, pBlue, pAlpha); this.mIndex++; } public void drawWithoutChecks(final ITextureRegion pTextureRegion, final float pX, final float pY, final float pWidth, final float pHeight, final float pRotation, final float pRed, final float pGreen, final float pBlue, final float pAlpha) { this.add(pTextureRegion, pX, pY, pWidth, pHeight, pRotation, pRed, pGreen, pBlue, pAlpha); this.mIndex++; } /** * @see {@link SpriteBatchVertexBufferObject#add(ITextureRegion, float, float, float, float, float, float, float, float, float)}. */ public void draw(final ITextureRegion pTextureRegion, final float pX, final float pY, final float pWidth, final float pHeight, final float pScaleX, final float pScaleY, final float pRed, final float pGreen, final float pBlue, final float pAlpha) { this.assertCapacity(); this.assertTexture(pTextureRegion); this.add(pTextureRegion, pX, pY, pWidth, pHeight, pScaleX, pScaleY, pRed, pGreen, pBlue, pAlpha); this.mIndex++; } public void drawWithoutChecks(final ITextureRegion pTextureRegion, final float pX, final float pY, final float pWidth, final float pHeight, final float pScaleX, final float pScaleY, final float pRed, final float pGreen, final float pBlue, final float pAlpha) { this.add(pTextureRegion, pX, pY, pWidth, pHeight, pScaleX, pScaleY, pRed, pGreen, pBlue, pAlpha); this.mIndex++; } /** * @see {@link SpriteBatchVertexBufferObject#add(ITextureRegion, float, float, float, float, float, float, float, float, float, float)}. */ public void draw(final ITextureRegion pTextureRegion, final float pX, final float pY, final float pWidth, final float pHeight, final float pRotation, final float pScaleX, final float pScaleY, final float pRed, final float pGreen, final float pBlue, final float pAlpha) { this.assertCapacity(); this.assertTexture(pTextureRegion); this.add(pTextureRegion, pX, pY, pWidth, pHeight, pRotation, pScaleX, pScaleY, pRed, pGreen, pBlue, pAlpha); this.mIndex++; } public void drawWithoutChecks(final ITextureRegion pTextureRegion, final float pX, final float pY, final float pWidth, final float pHeight, final float pRotation, final float pScaleX, final float pScaleY, final float pRed, final float pGreen, final float pBlue, final float pAlpha) { this.add(pTextureRegion, pX, pY, pWidth, pHeight, pRotation, pScaleX, pScaleY, pRed, pGreen, pBlue, pAlpha); this.mIndex++; } /** * @see {@link SpriteBatchVertexBufferObject#addInner(ITextureRegion, float, float, float, float, float, float, float, float, float, float, float)}. */ public void draw(final ITextureRegion pTextureRegion, final float pX1, final float pY1, final float pX2, final float pY2, final float pX3, final float pY3, final float pX4, final float pY4, final float pRed, final float pGreen, final float pBlue, final float pAlpha) { this.assertCapacity(); this.assertTexture(pTextureRegion); this.addInner(pTextureRegion, pX1, pY1, pX2, pY2, pX3, pY3, pX4, pY4, pRed, pGreen, pBlue, pAlpha); this.mIndex++; } public void drawWithoutChecks(final ITextureRegion pTextureRegion, final float pX1, final float pY1, final float pX2, final float pY2, final float pX3, final float pY3, final float pX4, final float pY4, final float pRed, final float pGreen, final float pBlue, final float pAlpha) { this.addInner(pTextureRegion, pX1, pY1, pX2, pY2, pX3, pY3, pX4, pY4, pRed, pGreen, pBlue, pAlpha); this.mIndex++; } /** * @see {@link SpriteBatchVertexBufferObject#add(ITextureRegion, float, float, float, float, float)} {@link SpriteBatchVertexBufferObject#add(ITextureRegion, float, float, Transformation, float)}. */ public void draw(final Sprite pSprite) { this.draw(pSprite.getTextureRegion(), pSprite, pSprite.getWidth(), pSprite.getHeight(), pSprite.getColor().getABGRPackedFloat()); } public void drawWithoutChecks(final Sprite pSprite) { this.drawWithoutChecks(pSprite.getTextureRegion(), pSprite, pSprite.getWidth(), pSprite.getHeight(), pSprite.getColor().getABGRPackedFloat()); } /** * @see {@link SpriteBatchVertexBufferObject#add(ITextureRegion, float, float, float, float, float, float, float, float)} {@link SpriteBatchVertexBufferObject#add(ITextureRegion, float, float, Transformation, float, float, float, float)}. */ public void draw(final Sprite pSprite, final float pRed, final float pGreen, final float pBlue, final float pAlpha) { this.draw(pSprite.getTextureRegion(), pSprite, pSprite.getWidth(), pSprite.getHeight(), pRed, pGreen, pBlue, pAlpha); } public void drawWithoutChecks(final Sprite pSprite, final float pRed, final float pGreen, final float pBlue, final float pAlpha) { this.drawWithoutChecks(pSprite.getTextureRegion(), pSprite, pSprite.getWidth(), pSprite.getHeight(), pRed, pGreen, pBlue, pAlpha); } /** * @see {@link SpriteBatchVertexBufferObject#add(ITextureRegion, float, float, float, float, float)} {@link SpriteBatchVertexBufferObject#add(ITextureRegion, float, float, Transformation, float, float, float, float)}. */ public void draw(final Sprite pSprite, final float pColorABGRPackedInt) { this.draw(pSprite.getTextureRegion(), pSprite, pSprite.getWidth(), pSprite.getHeight(), pColorABGRPackedInt); } public void drawWithoutChecks(final Sprite pSprite, final float pColorABGRPackedInt) { this.drawWithoutChecks(pSprite.getTextureRegion(), pSprite, pSprite.getWidth(), pSprite.getHeight(), pColorABGRPackedInt); } /** * @see {@link SpriteBatchVertexBufferObject#add(ITextureRegion, float, float, float, float, float)} {@link SpriteBatchVertexBufferObject#add(ITextureRegion, float, float, Transformation, float)}. */ public void draw(final ITextureRegion pTextureRegion, final IEntity pEntity, final float pWidth, final float pHeight) { this.draw(pTextureRegion, pEntity, pWidth, pHeight, pEntity.getColor().getABGRPackedFloat()); } public void drawWithoutChecks(final ITextureRegion pTextureRegion, final IEntity pEntity, final float pWidth, final float pHeight) { this.drawWithoutChecks(pTextureRegion, pEntity, pWidth, pHeight, pEntity.getColor().getABGRPackedFloat()); } /** * @see {@link SpriteBatchVertexBufferObject#add(ITextureRegion, float, float, float, float, float, float, float, float)} {@link SpriteBatchVertexBufferObject#add(ITextureRegion, float, float, Transformation, float, float, float, float)}. */ public void draw(final ITextureRegion pTextureRegion, final IEntity pEntity, final float pWidth, final float pHeight, final float pRed, final float pGreen, final float pBlue, final float pAlpha) { if(pEntity.isVisible()) { this.assertCapacity(); this.assertTexture(pTextureRegion); if(pEntity.isRotatedOrScaledOrSkewed()) { this.add(pTextureRegion, pWidth, pHeight, pEntity.getLocalToParentTransformation(), pRed, pGreen, pBlue, pAlpha); } else { this.add(pTextureRegion, pEntity.getX(), pEntity.getY(), pWidth, pHeight, pRed, pGreen, pBlue, pAlpha); } this.mIndex++; } } public void drawWithoutChecks(final ITextureRegion pTextureRegion, final IEntity pEntity, final float pWidth, final float pHeight, final float pRed, final float pGreen, final float pBlue, final float pAlpha) { if(pEntity.isVisible()) { if(pEntity.isRotatedOrScaledOrSkewed()) { this.add(pTextureRegion, pWidth, pHeight, pEntity.getLocalToParentTransformation(), pRed, pGreen, pBlue, pAlpha); } else { this.add(pTextureRegion, pEntity.getX(), pEntity.getY(), pWidth, pHeight, pRed, pGreen, pBlue, pAlpha); } this.mIndex++; } } /** * @see {@link SpriteBatchVertexBufferObject#add(ITextureRegion, float, float, float, float, float)} {@link SpriteBatchVertexBufferObject#add(ITextureRegion, float, float, Transformation, float, float, float, float)}. */ public void draw(final ITextureRegion pTextureRegion, final IEntity pEntity, final float pWidth, final float pHeight, final float pColorABGRPackedInt) { if(pEntity.isVisible()) { this.assertCapacity(); this.assertTexture(pTextureRegion); if(pEntity.isRotatedOrScaledOrSkewed()) { this.addWithPackedColor(pTextureRegion, pWidth, pHeight, pEntity.getLocalToParentTransformation(), pColorABGRPackedInt); } else { this.addWithPackedColor(pTextureRegion, pEntity.getX(), pEntity.getY(), pWidth, pHeight, pColorABGRPackedInt); } this.mIndex++; } } public void drawWithoutChecks(final ITextureRegion pTextureRegion, final IEntity pEntity, final float pWidth, final float pHeight, final float pColorABGRPackedInt) { if(pEntity.isVisible()) { if(pEntity.isRotatedOrScaledOrSkewed()) { this.addWithPackedColor(pTextureRegion, pWidth, pHeight, pEntity.getLocalToParentTransformation(), pColorABGRPackedInt); } else { this.addWithPackedColor(pTextureRegion, pEntity.getX(), pEntity.getY(), pWidth, pHeight, pColorABGRPackedInt); } this.mIndex++; } } public void submit() { this.onSubmit(); } protected void onSubmit() { this.mVertices = this.mIndex * SpriteBatch.VERTICES_PER_SPRITE; this.mSpriteBatchVertexBufferObject.setDirtyOnHardware(); this.mIndex = 0; this.mSpriteBatchVertexBufferObject.setBufferDataOffset(0); } private void assertCapacity(final int pIndex) { if(pIndex >= this.mCapacity) { throw new IllegalStateException("This supplied pIndex: '" + pIndex + "' is exceeding the capacity: '" + this.mCapacity + "' of this SpriteBatch!"); } } private void assertCapacity() { if(this.mIndex == this.mCapacity) { throw new IllegalStateException("This SpriteBatch has already reached its capacity (" + this.mCapacity + ") !"); } } protected void assertTexture(final ITextureRegion pTextureRegion) { if(pTextureRegion.getTexture() != this.mTexture) { throw new IllegalArgumentException("The supplied Texture does match the Texture of this SpriteBatch!"); } } /** * @param pTextureRegion * @param pX * @param pY * @param pWidth * @param pHeight * @param pRotation around the center (pWidth * 0.5f, pHeight * 0.5f) * @param pRed * @param pGreen * @param pBlue * @param pAlpha */ protected void add(final ITextureRegion pTextureRegion, final float pX, final float pY, final float pWidth, final float pHeight, final float pRotation, final float pRed, final float pGreen, final float pBlue, final float pAlpha) { final float widthHalf = pWidth * 0.5f; final float heightHalf = pHeight * 0.5f; SpriteBatch.TRANSFORATION_TMP.setToIdentity(); SpriteBatch.TRANSFORATION_TMP.postTranslate(-widthHalf, -heightHalf); SpriteBatch.TRANSFORATION_TMP.postRotate(pRotation); SpriteBatch.TRANSFORATION_TMP.postTranslate(widthHalf, heightHalf); SpriteBatch.TRANSFORATION_TMP.postTranslate(pX, pY); this.add(pTextureRegion, pWidth, pHeight, SpriteBatch.TRANSFORATION_TMP, pRed, pGreen, pBlue, pAlpha); } /** * @param pTextureRegion * @param pX * @param pY * @param pWidth * @param pHeight * @param pRotation around the center (pWidth * 0.5f, pHeight * 0.5f) * @param pColorABGRPackedInt */ protected void addWithPackedColor(final ITextureRegion pTextureRegion, final float pX, final float pY, final float pWidth, final float pHeight, final float pRotation, final float pColorABGRPackedInt) { final float widthHalf = pWidth * 0.5f; final float heightHalf = pHeight * 0.5f; SpriteBatch.TRANSFORATION_TMP.setToIdentity(); SpriteBatch.TRANSFORATION_TMP.postTranslate(-widthHalf, -heightHalf); SpriteBatch.TRANSFORATION_TMP.postRotate(pRotation); SpriteBatch.TRANSFORATION_TMP.postTranslate(widthHalf, heightHalf); SpriteBatch.TRANSFORATION_TMP.postTranslate(pX, pY); this.addWithPackedColor(pTextureRegion, pWidth, pHeight, SpriteBatch.TRANSFORATION_TMP, pColorABGRPackedInt); } /** * @param pTextureRegion * @param pX * @param pY * @param pWidth * @param pHeight * @param pRotation around the center (pWidth * 0.5f, pHeight * 0.5f) * @param pScaleX around the center (pWidth * 0.5f, pHeight * 0.5f) * @param pScaleY around the center (pWidth * 0.5f, pHeight * 0.5f) * @param pRed * @param pGreen * @param pBlue * @param pAlpha */ protected void add(final ITextureRegion pTextureRegion, final float pX, final float pY, final float pWidth, final float pHeight, final float pScaleX, final float pScaleY, final float pRed, final float pGreen, final float pBlue, final float pAlpha) { final float widthHalf = pWidth * 0.5f; final float heightHalf = pHeight * 0.5f; SpriteBatch.TRANSFORATION_TMP.setToIdentity(); SpriteBatch.TRANSFORATION_TMP.postTranslate(-widthHalf, -heightHalf); SpriteBatch.TRANSFORATION_TMP.postScale(pScaleX, pScaleY); SpriteBatch.TRANSFORATION_TMP.postTranslate(widthHalf, heightHalf); SpriteBatch.TRANSFORATION_TMP.postTranslate(pX, pY); this.add(pTextureRegion, pWidth, pHeight, SpriteBatch.TRANSFORATION_TMP, pRed, pGreen, pBlue, pAlpha); } /** * @param pTextureRegion * @param pX * @param pY * @param pWidth * @param pHeight * @param pRotation around the center (pWidth * 0.5f, pHeight * 0.5f) * @param pScaleX around the center (pWidth * 0.5f, pHeight * 0.5f) * @param pScaleY around the center (pWidth * 0.5f, pHeight * 0.5f) * @param pColorABGRPackedInt */ protected void addWithPackedColor(final ITextureRegion pTextureRegion, final float pX, final float pY, final float pWidth, final float pHeight, final float pScaleX, final float pScaleY, final float pColorABGRPackedInt) { final float widthHalf = pWidth * 0.5f; final float heightHalf = pHeight * 0.5f; SpriteBatch.TRANSFORATION_TMP.setToIdentity(); SpriteBatch.TRANSFORATION_TMP.postTranslate(-widthHalf, -heightHalf); SpriteBatch.TRANSFORATION_TMP.postScale(pScaleX, pScaleY); SpriteBatch.TRANSFORATION_TMP.postTranslate(widthHalf, heightHalf); SpriteBatch.TRANSFORATION_TMP.postTranslate(pX, pY); this.addWithPackedColor(pTextureRegion, pWidth, pHeight, SpriteBatch.TRANSFORATION_TMP, pColorABGRPackedInt); } /** * @param pTextureRegion * @param pX * @param pY * @param pWidth * @param pHeight * @param pRotation around the center (pWidth * 0.5f, pHeight * 0.5f) * @param pScaleX around the center (pWidth * 0.5f, pHeight * 0.5f) * @param pScaleY around the center (pWidth * 0.5f, pHeight * 0.5f) * @param pRed * @param pGreen * @param pBlue * @param pAlpha */ protected void add(final ITextureRegion pTextureRegion, final float pX, final float pY, final float pWidth, final float pHeight, final float pRotation, final float pScaleX, final float pScaleY, final float pRed, final float pGreen, final float pBlue, final float pAlpha) { final float widthHalf = pWidth * 0.5f; final float heightHalf = pHeight * 0.5f; SpriteBatch.TRANSFORATION_TMP.setToIdentity(); SpriteBatch.TRANSFORATION_TMP.postTranslate(-widthHalf, -heightHalf); SpriteBatch.TRANSFORATION_TMP.postScale(pScaleX, pScaleY); SpriteBatch.TRANSFORATION_TMP.postRotate(pRotation); SpriteBatch.TRANSFORATION_TMP.postTranslate(widthHalf, heightHalf); SpriteBatch.TRANSFORATION_TMP.postTranslate(pX, pY); this.add(pTextureRegion, pWidth, pHeight, SpriteBatch.TRANSFORATION_TMP, pRed, pGreen, pBlue, pAlpha); } /** * @param pTextureRegion * @param pX * @param pY * @param pWidth * @param pHeight * @param pRotation around the center (pWidth * 0.5f, pHeight * 0.5f) * @param pScaleX around the center (pWidth * 0.5f, pHeight * 0.5f) * @param pScaleY around the center (pWidth * 0.5f, pHeight * 0.5f) * @param pColorABGRPackedInt */ protected void addWithPackedColor(final ITextureRegion pTextureRegion, final float pX, final float pY, final float pWidth, final float pHeight, final float pRotation, final float pScaleX, final float pScaleY, final float pColorABGRPackedInt) { final float widthHalf = pWidth * 0.5f; final float heightHalf = pHeight * 0.5f; SpriteBatch.TRANSFORATION_TMP.setToIdentity(); SpriteBatch.TRANSFORATION_TMP.postTranslate(-widthHalf, -heightHalf); SpriteBatch.TRANSFORATION_TMP.postScale(pScaleX, pScaleY); SpriteBatch.TRANSFORATION_TMP.postRotate(pRotation); SpriteBatch.TRANSFORATION_TMP.postTranslate(widthHalf, heightHalf); SpriteBatch.TRANSFORATION_TMP.postTranslate(pX, pY); this.addWithPackedColor(pTextureRegion, pWidth, pHeight, SpriteBatch.TRANSFORATION_TMP, pColorABGRPackedInt); } /** * @param pTextureRegion * @param pWidth * @param pHeight * @param pTransformation * @param pRed * @param pGreen * @param pBlue * @param pAlpha */ protected void add(final ITextureRegion pTextureRegion, final float pWidth, final float pHeight, final Transformation pTransformation, final float pRed, final float pGreen, final float pBlue, final float pAlpha) { SpriteBatch.VERTICES_TMP[0] = 0; SpriteBatch.VERTICES_TMP[1] = 0; SpriteBatch.VERTICES_TMP[2] = 0; SpriteBatch.VERTICES_TMP[3] = pHeight; SpriteBatch.VERTICES_TMP[4] = pWidth; SpriteBatch.VERTICES_TMP[5] = 0; SpriteBatch.VERTICES_TMP[6] = pWidth; SpriteBatch.VERTICES_TMP[7] = pHeight; pTransformation.transform(SpriteBatch.VERTICES_TMP); this.addInner(pTextureRegion, SpriteBatch.VERTICES_TMP[0], SpriteBatch.VERTICES_TMP[1], SpriteBatch.VERTICES_TMP[2], SpriteBatch.VERTICES_TMP[3], SpriteBatch.VERTICES_TMP[4], SpriteBatch.VERTICES_TMP[5], SpriteBatch.VERTICES_TMP[6], SpriteBatch.VERTICES_TMP[7], pRed, pGreen, pBlue, pAlpha); } /** * @param pTextureRegion * @param pWidth * @param pHeight * @param pTransformation * @param pColorABGRPackedInt */ protected void addWithPackedColor(final ITextureRegion pTextureRegion, final float pWidth, final float pHeight, final Transformation pTransformation, final float pColorABGRPackedInt) { SpriteBatch.VERTICES_TMP[0] = 0; SpriteBatch.VERTICES_TMP[1] = 0; SpriteBatch.VERTICES_TMP[2] = 0; SpriteBatch.VERTICES_TMP[3] = pHeight; SpriteBatch.VERTICES_TMP[4] = pWidth; SpriteBatch.VERTICES_TMP[5] = 0; SpriteBatch.VERTICES_TMP[6] = pWidth; SpriteBatch.VERTICES_TMP[7] = pHeight; pTransformation.transform(SpriteBatch.VERTICES_TMP); this.mSpriteBatchVertexBufferObject.addWithPackedColor(pTextureRegion, SpriteBatch.VERTICES_TMP[0], SpriteBatch.VERTICES_TMP[1], SpriteBatch.VERTICES_TMP[2], SpriteBatch.VERTICES_TMP[3], SpriteBatch.VERTICES_TMP[4], SpriteBatch.VERTICES_TMP[5], SpriteBatch.VERTICES_TMP[6], SpriteBatch.VERTICES_TMP[7], pColorABGRPackedInt); } /** * @param pTextureRegion * @param pX * @param pY * @param pWidth * @param pHeight * @param pRed * @param pGreen * @param pBlue * @param pAlpha */ protected void add(final ITextureRegion pTextureRegion, final float pX, final float pY, final float pWidth, final float pHeight, final float pRed, final float pGreen, final float pBlue, final float pAlpha) { this.addInner(pTextureRegion, pX, pY, pX + pWidth, pY + pHeight, pRed, pGreen, pBlue, pAlpha); } /** * @param pTextureRegion * @param pX * @param pY * @param pWidth * @param pHeight * @param pColorABGRPackedInt */ protected void add(final ITextureRegion pTextureRegion, final float pX, final float pY, final float pWidth, final float pHeight, final float pColorABGRPackedInt) { this.mSpriteBatchVertexBufferObject.addWithPackedColor(pTextureRegion, pX, pY, pX + pWidth, pY + pHeight, pColorABGRPackedInt); } /** * @param pTextureRegion * @param pX * @param pY * @param pWidth * @param pHeight * @param pColorABGRPackedInt */ protected void addWithPackedColor(final ITextureRegion pTextureRegion, final float pX, final float pY, final float pWidth, final float pHeight, final float pColorABGRPackedInt) { this.mSpriteBatchVertexBufferObject.addWithPackedColor(pTextureRegion, pX, pY, pX + pWidth, pY + pHeight, pColorABGRPackedInt); } /** * 1-+ * |X| * +-2 */ private void addInner(final ITextureRegion pTextureRegion, final float pX1, final float pY1, final float pX2, final float pY2, final float pRed, final float pGreen, final float pBlue, final float pAlpha) { this.mSpriteBatchVertexBufferObject.addWithPackedColor(pTextureRegion, pX1, pY1, pX2, pY2, ColorUtils.convertRGBAToABGRPackedFloat(pRed, pGreen, pBlue, pAlpha)); } /** * 1-3 * |X| * 2-4 */ private void addInner(final ITextureRegion pTextureRegion, final float pX1, final float pY1, final float pX2, final float pY2, final float pX3, final float pY3, final float pX4, final float pY4, final float pRed, final float pGreen, final float pBlue, final float pAlpha) { this.mSpriteBatchVertexBufferObject.addWithPackedColor(pTextureRegion, pX1, pY1, pX2, pY2, pX3, pY3, pX4, pY4, ColorUtils.convertRGBAToABGRPackedFloat(pRed, pGreen, pBlue, pAlpha)); } // =========================================================== // Inner and Anonymous Classes // =========================================================== }
{ "content_hash": "64b78d717498eb008146da2d0309ffa8", "timestamp": "", "source": "github", "line_count": 757, "max_line_length": 327, "avg_line_length": 44.14134742404227, "alnum_prop": 0.7292234026634745, "repo_name": "alexbuicescu/AndEngine-Android-Studio-Template", "id": "d0dcfc05c9a214278eab91c26210bce60e3c4040", "size": "33415", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "andEngine/src/main/java/org/andengine/entity/sprite/batch/SpriteBatch.java", "mode": "33188", "license": "mit", "language": [ { "name": "Batchfile", "bytes": "108" }, { "name": "C", "bytes": "39906" }, { "name": "C++", "bytes": "540726" }, { "name": "Java", "bytes": "2597661" }, { "name": "Makefile", "bytes": "1525602" }, { "name": "Shell", "bytes": "809" } ], "symlink_target": "" }
pageflow.tooltipContainer = { events: { 'mouseover [data-tooltip]': function(event) { if (!this.tooltip.visible) { var target = $(event.target); var key = target.data('tooltip'); var position; if (target.data('tooltipAlign') === 'bottom left') { position = { left: target.position().left, top: target.position().top + target.outerHeight() }; } else if (target.data('tooltipAlign') === 'bottom right') { position = { left: target.position().left + target.outerWidth(), top: target.position().top + target.outerHeight() }; } else { position = { left: target.position().left + target.outerWidth(), top: target.position().top + target.outerHeight() / 2 }; } this.tooltip.show(I18n.t(key), position, { align: target.data('tooltipAlign') }) } }, 'mouseout [data-tooltip]': function() { this.tooltip.hide(); } }, onRender: function() { this.appendSubview(this.tooltip = new pageflow.TooltipView()); } };
{ "content_hash": "62eab57ffab71740bca1bd771f0fca06", "timestamp": "", "source": "github", "line_count": 42, "max_line_length": 66, "avg_line_length": 28, "alnum_prop": 0.5221088435374149, "repo_name": "tf/pageflow-dependabot-test", "id": "f4b925944aa297fe62a420351d216f236a31984a", "size": "1176", "binary": false, "copies": "4", "ref": "refs/heads/master", "path": "app/assets/javascripts/pageflow/ui/views/mixins/tooltip_container.js", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "286982" }, { "name": "HTML", "bytes": "56989" }, { "name": "JavaScript", "bytes": "1015583" }, { "name": "Ruby", "bytes": "1027419" }, { "name": "Shell", "bytes": "42" } ], "symlink_target": "" }
package softlayer_security_certificate_request_status // DO NOT EDIT. THIS FILE WAS AUTOMATICALLY GENERATED
{ "content_hash": "d64bb0754ea3c7a147153f0259ea1045", "timestamp": "", "source": "github", "line_count": 3, "max_line_length": 53, "avg_line_length": 36.333333333333336, "alnum_prop": 0.8256880733944955, "repo_name": "sudorandom/softlayer-go-gen", "id": "670a34431a378713697c01688c589c96831b3e05", "size": "1239", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "methods/softlayer_security_certificate_request_status/doc.go", "mode": "33188", "license": "mit", "language": [ { "name": "Go", "bytes": "3881979" }, { "name": "Shell", "bytes": "249" } ], "symlink_target": "" }
fn two_args<T>(x: T, y: T) { } fn main() { let a: @mut int = @mut 3; let b: @int = @3; // NOTE: // // The fact that this test fails to compile reflects a known // shortcoming of the current inference algorithm. These errors // are *not* desirable. two_args(a, b); //~ ERROR (values differ in mutability) }
{ "content_hash": "66f45f7beff6900631c997158c0406d0", "timestamp": "", "source": "github", "line_count": 14, "max_line_length": 68, "avg_line_length": 24.428571428571427, "alnum_prop": 0.5789473684210527, "repo_name": "kmcallister/rust", "id": "5c71ae38a64c019525e4f882a03001eff384dc80", "size": "809", "binary": false, "copies": "9", "ref": "refs/heads/master", "path": "src/test/compile-fail/lub-in-args.rs", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Assembly", "bytes": "27165" }, { "name": "C", "bytes": "919927" }, { "name": "C++", "bytes": "349598" }, { "name": "CSS", "bytes": "3307" }, { "name": "Emacs Lisp", "bytes": "20815" }, { "name": "JavaScript", "bytes": "22357" }, { "name": "Perl", "bytes": "173368" }, { "name": "Puppet", "bytes": "5423" }, { "name": "Python", "bytes": "40153" }, { "name": "Rust", "bytes": "9911466" }, { "name": "Shell", "bytes": "10985" }, { "name": "VimL", "bytes": "16591" }, { "name": "XSLT", "bytes": "303" } ], "symlink_target": "" }
#!/usr/bin/env bash # Copyright 2016 The Kubernetes Authors. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # This file creates release artifacts (tar files, container images) that are # ready to distribute to install or distribute to end users. ############################################################################### # Most of the ::release:: namespace functions have been moved to # github.com/kubernetes/release. Have a look in that repo and specifically in # lib/releaselib.sh for ::release::-related functionality. ############################################################################### # This is where the final release artifacts are created locally readonly RELEASE_STAGE="${LOCAL_OUTPUT_ROOT}/release-stage" readonly RELEASE_TARS="${LOCAL_OUTPUT_ROOT}/release-tars" readonly RELEASE_IMAGES="${LOCAL_OUTPUT_ROOT}/release-images" KUBE_BUILD_CONFORMANCE=${KUBE_BUILD_CONFORMANCE:-y} KUBE_BUILD_PULL_LATEST_IMAGES=${KUBE_BUILD_PULL_LATEST_IMAGES:-y} # Validate a ci version # # Globals: # None # Arguments: # version # Returns: # If version is a valid ci version # Sets: (e.g. for '1.2.3-alpha.4.56+abcdef12345678') # VERSION_MAJOR (e.g. '1') # VERSION_MINOR (e.g. '2') # VERSION_PATCH (e.g. '3') # VERSION_PRERELEASE (e.g. 'alpha') # VERSION_PRERELEASE_REV (e.g. '4') # VERSION_BUILD_INFO (e.g. '.56+abcdef12345678') # VERSION_COMMITS (e.g. '56') function kube::release::parse_and_validate_ci_version() { # Accept things like "v1.2.3-alpha.4.56+abcdef12345678" or "v1.2.3-beta.4" local -r version_regex="^v(0|[1-9][0-9]*)\\.(0|[1-9][0-9]*)\\.(0|[1-9][0-9]*)-([a-zA-Z0-9]+)\\.(0|[1-9][0-9]*)(\\.(0|[1-9][0-9]*)\\+[0-9a-f]{7,40})?$" local -r version="${1-}" [[ "${version}" =~ ${version_regex} ]] || { kube::log::error "Invalid ci version: '${version}', must match regex ${version_regex}" return 1 } # The VERSION variables are used when this file is sourced, hence # the shellcheck SC2034 'appears unused' warning is to be ignored. # shellcheck disable=SC2034 VERSION_MAJOR="${BASH_REMATCH[1]}" # shellcheck disable=SC2034 VERSION_MINOR="${BASH_REMATCH[2]}" # shellcheck disable=SC2034 VERSION_PATCH="${BASH_REMATCH[3]}" # shellcheck disable=SC2034 VERSION_PRERELEASE="${BASH_REMATCH[4]}" # shellcheck disable=SC2034 VERSION_PRERELEASE_REV="${BASH_REMATCH[5]}" # shellcheck disable=SC2034 VERSION_BUILD_INFO="${BASH_REMATCH[6]}" # shellcheck disable=SC2034 VERSION_COMMITS="${BASH_REMATCH[7]}" } # --------------------------------------------------------------------------- # Build final release artifacts function kube::release::clean_cruft() { # Clean out cruft find "${RELEASE_STAGE}" -name '*~' -exec rm {} \; find "${RELEASE_STAGE}" -name '#*#' -exec rm {} \; find "${RELEASE_STAGE}" -name '.DS*' -exec rm {} \; } function kube::release::package_tarballs() { # Clean out any old releases rm -rf "${RELEASE_STAGE}" "${RELEASE_TARS}" "${RELEASE_IMAGES}" mkdir -p "${RELEASE_TARS}" kube::release::package_src_tarball & kube::release::package_client_tarballs & kube::release::package_kube_manifests_tarball & kube::util::wait-for-jobs || { kube::log::error "previous tarball phase failed"; return 1; } # _node and _server tarballs depend on _src tarball kube::release::package_node_tarballs & kube::release::package_server_tarballs & kube::util::wait-for-jobs || { kube::log::error "previous tarball phase failed"; return 1; } kube::release::package_final_tarball & # _final depends on some of the previous phases kube::release::package_test_tarballs & # _test doesn't depend on anything kube::util::wait-for-jobs || { kube::log::error "previous tarball phase failed"; return 1; } } # Package the source code we built, for compliance/licensing/audit/yadda. function kube::release::package_src_tarball() { local -r src_tarball="${RELEASE_TARS}/kubernetes-src.tar.gz" kube::log::status "Building tarball: src" if [[ "${KUBE_GIT_TREE_STATE-}" = 'clean' ]]; then git archive -o "${src_tarball}" HEAD else find "${KUBE_ROOT}" -mindepth 1 -maxdepth 1 \ ! \( \ \( -path "${KUBE_ROOT}"/_\* -o \ -path "${KUBE_ROOT}"/.git\* -o \ -path "${KUBE_ROOT}"/.config\* -o \ -path "${KUBE_ROOT}"/.gsutil\* \ \) -prune \ \) -print0 \ | "${TAR}" czf "${src_tarball}" --transform "s|${KUBE_ROOT#/*}|kubernetes|" --null -T - fi } # Package up all of the cross compiled clients. Over time this should grow into # a full SDK function kube::release::package_client_tarballs() { # Find all of the built client binaries local long_platforms=("${LOCAL_OUTPUT_BINPATH}"/*/*) if [[ -n ${KUBE_BUILD_PLATFORMS-} ]]; then read -ra long_platforms <<< "${KUBE_BUILD_PLATFORMS}" fi for platform_long in "${long_platforms[@]}"; do local platform local platform_tag platform=${platform_long##${LOCAL_OUTPUT_BINPATH}/} # Strip LOCAL_OUTPUT_BINPATH platform_tag=${platform/\//-} # Replace a "/" for a "-" kube::log::status "Starting tarball: client $platform_tag" ( local release_stage="${RELEASE_STAGE}/client/${platform_tag}/kubernetes" rm -rf "${release_stage}" mkdir -p "${release_stage}/client/bin" local client_bins=("${KUBE_CLIENT_BINARIES[@]}") if [[ "${platform%/*}" = 'windows' ]]; then client_bins=("${KUBE_CLIENT_BINARIES_WIN[@]}") fi # This fancy expression will expand to prepend a path # (${LOCAL_OUTPUT_BINPATH}/${platform}/) to every item in the # client_bins array. cp "${client_bins[@]/#/${LOCAL_OUTPUT_BINPATH}/${platform}/}" \ "${release_stage}/client/bin/" kube::release::clean_cruft local package_name="${RELEASE_TARS}/kubernetes-client-${platform_tag}.tar.gz" kube::release::create_tarball "${package_name}" "${release_stage}/.." ) & done kube::log::status "Waiting on tarballs" kube::util::wait-for-jobs || { kube::log::error "client tarball creation failed"; exit 1; } } # Package up all of the node binaries function kube::release::package_node_tarballs() { local platform for platform in "${KUBE_NODE_PLATFORMS[@]}"; do local platform_tag local arch platform_tag=${platform/\//-} # Replace a "/" for a "-" arch=$(basename "${platform}") kube::log::status "Building tarball: node $platform_tag" local release_stage="${RELEASE_STAGE}/node/${platform_tag}/kubernetes" rm -rf "${release_stage}" mkdir -p "${release_stage}/node/bin" local node_bins=("${KUBE_NODE_BINARIES[@]}") if [[ "${platform%/*}" = 'windows' ]]; then node_bins=("${KUBE_NODE_BINARIES_WIN[@]}") fi # This fancy expression will expand to prepend a path # (${LOCAL_OUTPUT_BINPATH}/${platform}/) to every item in the # node_bins array. cp "${node_bins[@]/#/${LOCAL_OUTPUT_BINPATH}/${platform}/}" \ "${release_stage}/node/bin/" # TODO: Docker images here # kube::release::create_docker_images_for_server "${release_stage}/server/bin" "${arch}" # Include the client binaries here too as they are useful debugging tools. local client_bins=("${KUBE_CLIENT_BINARIES[@]}") if [[ "${platform%/*}" = 'windows' ]]; then client_bins=("${KUBE_CLIENT_BINARIES_WIN[@]}") fi # This fancy expression will expand to prepend a path # (${LOCAL_OUTPUT_BINPATH}/${platform}/) to every item in the # client_bins array. cp "${client_bins[@]/#/${LOCAL_OUTPUT_BINPATH}/${platform}/}" \ "${release_stage}/node/bin/" cp -R "${KUBE_ROOT}/LICENSES" "${release_stage}/" cp "${RELEASE_TARS}/kubernetes-src.tar.gz" "${release_stage}/" kube::release::clean_cruft local package_name="${RELEASE_TARS}/kubernetes-node-${platform_tag}.tar.gz" kube::release::create_tarball "${package_name}" "${release_stage}/.." done } # Package up all of the server binaries in docker images function kube::release::build_server_images() { # Clean out any old images rm -rf "${RELEASE_IMAGES}" local platform for platform in "${KUBE_SERVER_PLATFORMS[@]}"; do local platform_tag local arch platform_tag=${platform/\//-} # Replace a "/" for a "-" arch=$(basename "${platform}") kube::log::status "Building images: $platform_tag" local release_stage release_stage="${RELEASE_STAGE}/server/${platform_tag}/kubernetes" rm -rf "${release_stage}" mkdir -p "${release_stage}/server/bin" # This fancy expression will expand to prepend a path # (${LOCAL_OUTPUT_BINPATH}/${platform}/) to every item in the # KUBE_SERVER_IMAGE_BINARIES array. cp "${KUBE_SERVER_IMAGE_BINARIES[@]/#/${LOCAL_OUTPUT_BINPATH}/${platform}/}" \ "${release_stage}/server/bin/" kube::release::create_docker_images_for_server "${release_stage}/server/bin" "${arch}" done } # Package up all of the server binaries function kube::release::package_server_tarballs() { kube::release::build_server_images local platform for platform in "${KUBE_SERVER_PLATFORMS[@]}"; do local platform_tag local arch platform_tag=${platform/\//-} # Replace a "/" for a "-" arch=$(basename "${platform}") kube::log::status "Building tarball: server $platform_tag" # NOTE: this directory was setup in kube::release::build_server_images local release_stage release_stage="${RELEASE_STAGE}/server/${platform_tag}/kubernetes" mkdir -p "${release_stage}/addons" # This fancy expression will expand to prepend a path # (${LOCAL_OUTPUT_BINPATH}/${platform}/) to every item in the # KUBE_SERVER_BINARIES array. cp "${KUBE_SERVER_BINARIES[@]/#/${LOCAL_OUTPUT_BINPATH}/${platform}/}" \ "${release_stage}/server/bin/" # Include the client binaries here too as they are useful debugging tools. local client_bins client_bins=("${KUBE_CLIENT_BINARIES[@]}") if [[ "${platform%/*}" = 'windows' ]]; then client_bins=("${KUBE_CLIENT_BINARIES_WIN[@]}") fi # This fancy expression will expand to prepend a path # (${LOCAL_OUTPUT_BINPATH}/${platform}/) to every item in the # client_bins array. cp "${client_bins[@]/#/${LOCAL_OUTPUT_BINPATH}/${platform}/}" \ "${release_stage}/server/bin/" cp -R "${KUBE_ROOT}/LICENSES" "${release_stage}/" cp "${RELEASE_TARS}/kubernetes-src.tar.gz" "${release_stage}/" kube::release::clean_cruft local package_name package_name="${RELEASE_TARS}/kubernetes-server-${platform_tag}.tar.gz" kube::release::create_tarball "${package_name}" "${release_stage}/.." done } function kube::release::md5() { if which md5 >/dev/null 2>&1; then md5 -q "$1" else md5sum "$1" | awk '{ print $1 }' fi } function kube::release::sha1() { if which sha1sum >/dev/null 2>&1; then sha1sum "$1" | awk '{ print $1 }' else shasum -a1 "$1" | awk '{ print $1 }' fi } function kube::release::build_conformance_image() { local -r arch="$1" local -r registry="$2" local -r version="$3" local -r save_dir="${4-}" kube::log::status "Building conformance image for arch: ${arch}" ARCH="${arch}" REGISTRY="${registry}" VERSION="${version}" \ make -C cluster/images/conformance/ build >/dev/null local conformance_tag conformance_tag="${registry}/conformance-${arch}:${version}" if [[ -n "${save_dir}" ]]; then "${DOCKER[@]}" save "${conformance_tag}" > "${save_dir}/conformance-${arch}.tar" fi kube::log::status "Deleting conformance image ${conformance_tag}" "${DOCKER[@]}" rmi "${conformance_tag}" &>/dev/null || true } # This builds all the release docker images (One docker image per binary) # Args: # $1 - binary_dir, the directory to save the tared images to. # $2 - arch, architecture for which we are building docker images. function kube::release::create_docker_images_for_server() { # Create a sub-shell so that we don't pollute the outer environment ( local binary_dir local arch local binaries local images_dir binary_dir="$1" arch="$2" binaries=$(kube::build::get_docker_wrapped_binaries) images_dir="${RELEASE_IMAGES}/${arch}" mkdir -p "${images_dir}" # k8s.gcr.io is the constant tag in the docker archives, this is also the default for config scripts in GKE. # We can use KUBE_DOCKER_REGISTRY to include and extra registry in the docker archive. # If we use KUBE_DOCKER_REGISTRY="k8s.gcr.io", then the extra tag (same) is ignored, see release_docker_image_tag below. local -r docker_registry="k8s.gcr.io" # Docker tags cannot contain '+' local docker_tag="${KUBE_GIT_VERSION/+/_}" if [[ -z "${docker_tag}" ]]; then kube::log::error "git version information missing; cannot create Docker tag" return 1 fi # provide `--pull` argument to `docker build` if `KUBE_BUILD_PULL_LATEST_IMAGES` # is set to y or Y; otherwise try to build the image without forcefully # pulling the latest base image. local docker_build_opts docker_build_opts= if [[ "${KUBE_BUILD_PULL_LATEST_IMAGES}" =~ [yY] ]]; then docker_build_opts='--pull' fi for wrappable in $binaries; do local binary_name=${wrappable%%,*} local base_image=${wrappable##*,} local binary_file_path="${binary_dir}/${binary_name}" local docker_build_path="${binary_file_path}.dockerbuild" local docker_file_path="${docker_build_path}/Dockerfile" local docker_image_tag="${docker_registry}/${binary_name}-${arch}:${docker_tag}" kube::log::status "Starting docker build for image: ${binary_name}-${arch}" ( rm -rf "${docker_build_path}" mkdir -p "${docker_build_path}" ln "${binary_file_path}" "${docker_build_path}/${binary_name}" ln "${KUBE_ROOT}/build/nsswitch.conf" "${docker_build_path}/nsswitch.conf" chmod 0644 "${docker_build_path}/nsswitch.conf" cat <<EOF > "${docker_file_path}" FROM --platform=linux/${arch} ${base_image} COPY ${binary_name} /usr/local/bin/${binary_name} EOF # ensure /etc/nsswitch.conf exists so go's resolver respects /etc/hosts if [[ "${base_image}" =~ busybox ]]; then echo "COPY nsswitch.conf /etc/" >> "${docker_file_path}" fi "${DOCKER[@]}" build ${docker_build_opts:+"${docker_build_opts}"} -q -t "${docker_image_tag}" "${docker_build_path}" >/dev/null # If we are building an official/alpha/beta release we want to keep # docker images and tag them appropriately. local -r release_docker_image_tag="${KUBE_DOCKER_REGISTRY-$docker_registry}/${binary_name}-${arch}:${KUBE_DOCKER_IMAGE_TAG-$docker_tag}" if [[ "${release_docker_image_tag}" != "${docker_image_tag}" ]]; then kube::log::status "Tagging docker image ${docker_image_tag} as ${release_docker_image_tag}" "${DOCKER[@]}" rmi "${release_docker_image_tag}" 2>/dev/null || true "${DOCKER[@]}" tag "${docker_image_tag}" "${release_docker_image_tag}" 2>/dev/null fi "${DOCKER[@]}" save -o "${binary_file_path}.tar" "${docker_image_tag}" "${release_docker_image_tag}" echo "${docker_tag}" > "${binary_file_path}.docker_tag" rm -rf "${docker_build_path}" ln "${binary_file_path}.tar" "${images_dir}/" kube::log::status "Deleting docker image ${docker_image_tag}" "${DOCKER[@]}" rmi "${docker_image_tag}" &>/dev/null || true ) & done if [[ "${KUBE_BUILD_CONFORMANCE}" =~ [yY] ]]; then kube::release::build_conformance_image "${arch}" "${docker_registry}" \ "${docker_tag}" "${images_dir}" & fi kube::util::wait-for-jobs || { kube::log::error "previous Docker build failed"; return 1; } kube::log::status "Docker builds done" ) } # This will pack kube-system manifests files for distros such as COS. function kube::release::package_kube_manifests_tarball() { kube::log::status "Building tarball: manifests" local src_dir="${KUBE_ROOT}/cluster/gce/manifests" local release_stage="${RELEASE_STAGE}/manifests/kubernetes" rm -rf "${release_stage}" local dst_dir="${release_stage}/gci-trusty" mkdir -p "${dst_dir}" cp "${src_dir}/kube-proxy.manifest" "${dst_dir}/" cp "${src_dir}/cluster-autoscaler.manifest" "${dst_dir}/" cp "${src_dir}/etcd.manifest" "${dst_dir}" cp "${src_dir}/kube-scheduler.manifest" "${dst_dir}" cp "${src_dir}/kube-apiserver.manifest" "${dst_dir}" cp "${src_dir}/konnectivity-server.yaml" "${dst_dir}" cp "${src_dir}/abac-authz-policy.jsonl" "${dst_dir}" cp "${src_dir}/kube-controller-manager.manifest" "${dst_dir}" cp "${src_dir}/kube-addon-manager.yaml" "${dst_dir}" cp "${src_dir}/glbc.manifest" "${dst_dir}" find "${src_dir}" -name 'internal-*' -exec cp {} "${dst_dir}" \; cp "${KUBE_ROOT}/cluster/gce/gci/configure-helper.sh" "${dst_dir}/gci-configure-helper.sh" cp "${KUBE_ROOT}/cluster/gce/gci/configure-kubeapiserver.sh" "${dst_dir}/configure-kubeapiserver.sh" if [[ -e "${KUBE_ROOT}/cluster/gce/gci/gke-internal-configure-helper.sh" ]]; then cp "${KUBE_ROOT}/cluster/gce/gci/gke-internal-configure-helper.sh" "${dst_dir}/" fi cp "${KUBE_ROOT}/cluster/gce/gci/health-monitor.sh" "${dst_dir}/health-monitor.sh" # Merge GCE-specific addons with general purpose addons. for d in cluster/addons cluster/gce/addons; do find "${KUBE_ROOT}/${d}" \( \( -name \*.yaml -o -name \*.yaml.in -o -name \*.json \) -a ! \( -name \*demo\* \) \) -print0 | "${TAR}" c --transform "s|${KUBE_ROOT#/*}/${d}||" --null -T - | "${TAR}" x -C "${dst_dir}" done kube::release::clean_cruft local package_name="${RELEASE_TARS}/kubernetes-manifests.tar.gz" kube::release::create_tarball "${package_name}" "${release_stage}/.." } # Builds tarballs for each test platform containing the appropriate binaries. function kube::release::package_test_platform_tarballs() { local platform rm -rf "${RELEASE_STAGE}/test" # KUBE_TEST_SERVER_PLATFORMS is a subset of KUBE_TEST_PLATFORMS, # so process it first. for platform in "${KUBE_TEST_SERVER_PLATFORMS[@]}"; do local platform_tag=${platform/\//-} # Replace a "/" for a "-" local release_stage="${RELEASE_STAGE}/test/${platform_tag}/kubernetes" mkdir -p "${release_stage}/test/bin" # This fancy expression will expand to prepend a path # (${LOCAL_OUTPUT_BINPATH}/${platform}/) to every item in the # KUBE_TEST_SERVER_BINARIES array. cp "${KUBE_TEST_SERVER_BINARIES[@]/#/${LOCAL_OUTPUT_BINPATH}/${platform}/}" \ "${release_stage}/test/bin/" done for platform in "${KUBE_TEST_PLATFORMS[@]}"; do ( local platform_tag=${platform/\//-} # Replace a "/" for a "-" kube::log::status "Starting tarball: test $platform_tag" local release_stage="${RELEASE_STAGE}/test/${platform_tag}/kubernetes" mkdir -p "${release_stage}/test/bin" local test_bins=("${KUBE_TEST_BINARIES[@]}") if [[ "${platform%/*}" = 'windows' ]]; then test_bins=("${KUBE_TEST_BINARIES_WIN[@]}") fi # This fancy expression will expand to prepend a path # (${LOCAL_OUTPUT_BINPATH}/${platform}/) to every item in the # test_bins array. cp "${test_bins[@]/#/${LOCAL_OUTPUT_BINPATH}/${platform}/}" \ "${release_stage}/test/bin/" local package_name="${RELEASE_TARS}/kubernetes-test-${platform_tag}.tar.gz" kube::release::create_tarball "${package_name}" "${release_stage}/.." ) & done kube::log::status "Waiting on test tarballs" kube::util::wait-for-jobs || { kube::log::error "test tarball creation failed"; exit 1; } } # This is the stuff you need to run tests from the binary distribution. function kube::release::package_test_tarballs() { kube::release::package_test_platform_tarballs kube::log::status "Building tarball: test portable" local release_stage="${RELEASE_STAGE}/test/kubernetes" rm -rf "${release_stage}" mkdir -p "${release_stage}" # First add test image files and other portable sources so we can create # the portable test tarball. mkdir -p "${release_stage}/test/images" cp -fR "${KUBE_ROOT}/test/images" "${release_stage}/test/" "${TAR}" c "${KUBE_TEST_PORTABLE[@]}" | "${TAR}" x -C "${release_stage}" kube::release::clean_cruft local portable_tarball_name="${RELEASE_TARS}/kubernetes-test-portable.tar.gz" kube::release::create_tarball "${portable_tarball_name}" "${release_stage}/.." } # This is all the platform-independent stuff you need to run/install kubernetes. # Arch-specific binaries will need to be downloaded separately (possibly by # using the bundled cluster/get-kube-binaries.sh script). # Included in this tarball: # - Cluster spin up/down scripts and configs for various cloud providers # - Tarballs for manifest configs that are ready to be uploaded # - Examples (which may or may not still work) # - The remnants of the docs/ directory function kube::release::package_final_tarball() { kube::log::status "Building tarball: final" # This isn't a "full" tarball anymore, but the release lib still expects # artifacts under "full/kubernetes/" local release_stage="${RELEASE_STAGE}/full/kubernetes" rm -rf "${release_stage}" mkdir -p "${release_stage}" mkdir -p "${release_stage}/client" cat <<EOF > "${release_stage}/client/README" Client binaries are no longer included in the Kubernetes final tarball. Run cluster/get-kube-binaries.sh to download client and server binaries. EOF # We want everything in /cluster. cp -R "${KUBE_ROOT}/cluster" "${release_stage}/" mkdir -p "${release_stage}/server" cp "${RELEASE_TARS}/kubernetes-manifests.tar.gz" "${release_stage}/server/" cat <<EOF > "${release_stage}/server/README" Server binary tarballs are no longer included in the Kubernetes final tarball. Run cluster/get-kube-binaries.sh to download client and server binaries. EOF # Include hack/lib as a dependency for the cluster/ scripts mkdir -p "${release_stage}/hack" cp -R "${KUBE_ROOT}/hack/lib" "${release_stage}/hack/" cp -R "${KUBE_ROOT}/docs" "${release_stage}/" cp "${KUBE_ROOT}/README.md" "${release_stage}/" cp -R "${KUBE_ROOT}/LICENSES" "${release_stage}/" echo "${KUBE_GIT_VERSION}" > "${release_stage}/version" kube::release::clean_cruft local package_name="${RELEASE_TARS}/kubernetes.tar.gz" kube::release::create_tarball "${package_name}" "${release_stage}/.." } # Build a release tarball. $1 is the output tar name. $2 is the base directory # of the files to be packaged. This assumes that ${2}/kubernetes is what is # being packaged. function kube::release::create_tarball() { kube::build::ensure_tar local tarfile=$1 local stagingdir=$2 "${TAR}" czf "${tarfile}" -C "${stagingdir}" kubernetes --owner=0 --group=0 }
{ "content_hash": "1e76b4f40b902daa397512be9a185b6b", "timestamp": "", "source": "github", "line_count": 581, "max_line_length": 218, "avg_line_length": 40.0895008605852, "alnum_prop": 0.641379014253821, "repo_name": "tomzhang/kubernetes", "id": "6b3d45dfbb045c1d0c36b241b8eaa4bbbba97b8d", "size": "23292", "binary": false, "copies": "10", "ref": "refs/heads/master", "path": "build/lib/release.sh", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "CSS", "bytes": "60606" }, { "name": "Go", "bytes": "9813809" }, { "name": "HTML", "bytes": "51577" }, { "name": "Java", "bytes": "3851" }, { "name": "JavaScript", "bytes": "177629" }, { "name": "Makefile", "bytes": "10804" }, { "name": "Nginx", "bytes": "1013" }, { "name": "PHP", "bytes": "736" }, { "name": "Perl", "bytes": "329" }, { "name": "Python", "bytes": "57979" }, { "name": "Ruby", "bytes": "2778" }, { "name": "Scheme", "bytes": "1112" }, { "name": "Shell", "bytes": "614257" } ], "symlink_target": "" }
<?php namespace PhpParser\Node\Expr; use PhpParser\Node\Expr; class BooleanNot extends Expr { /** @var Expr Expression */ public $expr; /** * Constructs a boolean not node. * * @param Expr $expr Expression * @param array $attributes Additional attributes */ public function __construct(Expr $expr, array $attributes = array()) { parent::__construct($attributes); $this->expr = $expr; } public function getSubNodeNames() { return array('expr'); } }
{ "content_hash": "e506ea57d48f36fecf3601629637c811", "timestamp": "", "source": "github", "line_count": 26, "max_line_length": 74, "avg_line_length": 22.153846153846153, "alnum_prop": 0.5590277777777778, "repo_name": "handharbeni/trackmenuapi", "id": "8c84d4ad64efc98eadb81d99ec44e81b47d4d8b6", "size": "576", "binary": false, "copies": "3", "ref": "refs/heads/master", "path": "application/tests/_ci_phpunit_test/patcher/third_party/PHP-Parser/lib/PhpParser/Node/Expr/BooleanNot.php", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "ApacheConf", "bytes": "1116" }, { "name": "HTML", "bytes": "8097" }, { "name": "PHP", "bytes": "2355632" }, { "name": "Roff", "bytes": "268415" } ], "symlink_target": "" }
package org.kiji.schema; import org.kiji.annotations.ApiAudience; import org.kiji.annotations.ApiStability; /** * Exception thrown during a metadata restore operation due to user error. */ @ApiAudience.Public @ApiStability.Stable final class RestoreException extends Exception { /** * Creates a new RestoreException instance, with the specified message. A user-readable * message must be specified with this exception type. * @param msg the message to include. */ RestoreException(String msg) { super(msg); } }
{ "content_hash": "f9867a121663ce32bcfa7b9db07ea52c", "timestamp": "", "source": "github", "line_count": 22, "max_line_length": 89, "avg_line_length": 24.5, "alnum_prop": 0.7458256029684601, "repo_name": "kijiproject/kiji-schema", "id": "0dcc85d725b7f4a1bf2c283fbeb786f6d339ed51", "size": "1255", "binary": false, "copies": "3", "ref": "refs/heads/master", "path": "kiji-schema/src/main/java/org/kiji/schema/RestoreException.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Java", "bytes": "3852630" }, { "name": "Scala", "bytes": "92185" }, { "name": "Shell", "bytes": "31044" } ], "symlink_target": "" }
using System; using System.Drawing; using System.IO; using System.Text.RegularExpressions; using System.Windows.Forms; using System.Xml; #endregion Using Directives namespace ScintillaNET.Configuration { public class Configuration { #region Fields private bool? _autoComplete_AutoHide; private bool? _autoComplete_AutomaticLengthEntered; private bool? _autoComplete_cancelAtStart; private bool? _autoComplete_DropRestOfWord; private string _autoComplete_fillUpCharacters; private char? _autoComplete_ImageSeperator; private bool? _autoComplete_IsCaseSensitive; private string _autoComplete_List; private bool? _autoComplete_ListInherit; private char? _autoComplete_ListSeperator; private int? _autoComplete_MaxHeight; private int? _autoComplete_MaxWidth; private bool? _autoComplete_singleLineAccept; private string _autoComplete_StopCharacters; private Color _callTip_BackColor; private Color _callTip_ForeColor; private Color _callTip_HighlightTextColor; private int? _caret_BlinkRate; private Color _caret_Color; private int? _caret_CurrentLineBackgroundAlpha; private Color _caret_CurrentLineBackgroundColor; private bool? _caret_HighlightCurrentLine; private bool? _caret_IsSticky; private CaretStyle? _caret_Style; private int? _caret_Width; private bool? _clipboard_ConvertLineBreaksOnPaste; private CommandBindingConfigList _commands_KeyBindingList = new CommandBindingConfigList(); private string _dropMarkers_SharedStackName; private bool? _endOfLine_IsVisisble; private EndOfLineMode? _endOfLine_Mode; private FoldFlag? _folding_Flags; private bool? _folding_IsEnabled; private FoldMarkerScheme? _folding_MarkerScheme; private bool? _folding_UseCompactFolding; private bool _hasData = false; private Color _hotspot_ActiveBackColor; private Color _hotspot_ActiveForeColor; private bool? _hotspot_ActiveUnderline; private bool? _hotspot_SingleLine; private bool? _hotspot_UseActiveBackColor; private bool? _hotspot_UseActiveForeColor; private bool? _indentation_BackspaceUnindents; private int? _indentation_IndentWidth; private bool? _indentation_ShowGuides; private SmartIndent? _indentation_SmartIndentType; private bool? _indentation_TabIndents; private int? _indentation_TabWidth; private bool? _indentation_UseTabs; private IndicatorConfigList _indicator_List = new IndicatorConfigList(); private string _language; private KeyWordConfigList _lexing_Keywords = new KeyWordConfigList(); private string _lexing_Language; private string _lexing_LineCommentPrefix; private LexerPropertiesConfig _lexing_Properties = new LexerPropertiesConfig(); private string _lexing_StreamCommentPrefix; private string _lexing_StreamCommentSuffix; private string _lexing_WhitespaceChars; private string _lexing_WordChars; private LineWrappingMode? _lineWrapping_Mode; private LineWrappingIndentMode? _lineWrapping_IndentMode; private int? _lineWrapping_IndentSize; private LineWrappingVisualFlags? _lineWrapping_VisualFlags; private LineWrappingVisualFlagsLocations? _lineWrapping_VisualFlagsLocations; private Color _longLines_EdgeColor; private int? _longLines_EdgeColumn; private EdgeMode? _longLines_EdgeMode; private MarginConfigList _margin_List = new MarginConfigList(); private MarkersConfigList _markers_List; private bool? _scrolling_EndAtLastLine; private int? _scrolling_HorizontalWidth; private ScrollBars? _scrolling_ScrollBars; private int? _scrolling_XOffset; private Color _selection_BackColor; private Color _selection_BackColorUnfocused; private Color _selection_ForeColor; private Color _selection_ForeColorUnfocused; private bool? _selection_Hidden; private bool? _selection_HideSelection; private SelectionMode? _selection_Mode; private SnippetsConfigList _snippetsConfigList = new SnippetsConfigList(); private StyleConfigList _styles = new StyleConfigList(); private bool? _undoRedoIsUndoEnabled; private Color _whitespace_BackColor; private Color _whitespace_ForeColor; private WhitespaceMode? _whitespace_Mode; #endregion Fields #region Methods private bool? getBool(string s) { s = s.ToLower(); switch (s) { case "true": case "t": case "1": case "y": case "yes": return true; case "false": case "f": case "0": case "n": case "no": return false; } return null; } private char? getChar(string s) { if (string.IsNullOrEmpty(s)) return null; return s[0]; } private Color getColor(string s) { return (Color)new ColorConverter().ConvertFromString(s); } private int? getInt(string s) { int i; if (int.TryParse(s, out i)) return i; return null; } private string getString(XmlAttribute a) { if (a == null) return null; return a.Value; } private StyleConfig getStyleConfigFromElement(XmlReader reader) { StyleConfig sc = new StyleConfig(); if (reader.HasAttributes) { while (reader.MoveToNextAttribute()) { string attrName = reader.Name.ToLower(); switch (attrName) { case "name": sc.Name = reader.Value; break; case "number": sc.Number = getInt(reader.Value); break; case "backcolor": sc.BackColor = getColor(reader.Value); break; case "bold": sc.Bold = getBool(reader.Value); break; case "case": sc.Case = (StyleCase)Enum.Parse(typeof(StyleCase), reader.Value, true); break; case "characterset": sc.CharacterSet = (CharacterSet)Enum.Parse(typeof(CharacterSet), reader.Value, true); break; case "fontname": sc.FontName = reader.Value; break; case "forecolor": sc.ForeColor = getColor(reader.Value); break; case "ischangeable": sc.IsChangeable = getBool(reader.Value); break; case "ishotspot": sc.IsHotspot = getBool(reader.Value); break; case "isselectioneolfilled": sc.IsSelectionEolFilled = getBool(reader.Value); break; case "isvisible": sc.IsVisible = getBool(reader.Value); break; case "italic": sc.Italic = getBool(reader.Value); break; case "size": sc.Size = getInt(reader.Value); break; case "underline": sc.Underline = getBool(reader.Value); break; case "inherit": sc.Inherit = getBool(reader.Value); break; } } reader.MoveToElement(); } return sc; } public void Load(TextReader txtReader) { XmlDocument configDocument = new XmlDocument(); configDocument.PreserveWhitespace = true; configDocument.Load(txtReader); Load(configDocument); } public void Load(XmlReader reader) { reader.ReadStartElement(); while (!reader.EOF) { if (reader.Name.Equals("language", StringComparison.OrdinalIgnoreCase) && reader.HasAttributes) { while (reader.MoveToNextAttribute()) { if (reader.Name.Equals("name", StringComparison.OrdinalIgnoreCase) && reader.Value.Equals(_language, StringComparison.OrdinalIgnoreCase)) { ReadLanguage(reader); _hasData = true; } } if (_hasData) reader.Skip(); } else { reader.Skip(); continue; } reader.Read(); } reader.Close(); } public void Load(XmlDocument configDocument) { XmlElement langNode = configDocument.DocumentElement.SelectSingleNode("./Language[@Name='" + _language + "']") as XmlElement; if (langNode == null) return; XmlElement autoCNode = langNode.SelectSingleNode("AutoComplete") as XmlElement; if (autoCNode != null) { _autoComplete_AutoHide = getBool(autoCNode.GetAttribute("AutoHide")); _autoComplete_AutomaticLengthEntered = getBool(autoCNode.GetAttribute("AutomaticLengthEntered")); _autoComplete_cancelAtStart = getBool(autoCNode.GetAttribute("CancelAtStart")); _autoComplete_DropRestOfWord = getBool(autoCNode.GetAttribute("DropRestOfWord")); _autoComplete_fillUpCharacters = getString(autoCNode.GetAttributeNode("FillUpCharacters")); _autoComplete_ImageSeperator = getChar(autoCNode.GetAttribute("AutomaticLengthEntered")); _autoComplete_IsCaseSensitive = getBool(autoCNode.GetAttribute("IsCaseSensitive")); _autoComplete_ListSeperator = getChar(autoCNode.GetAttribute("ListSeperator")); _autoComplete_MaxHeight = getInt(autoCNode.GetAttribute("MaxHeight")); _autoComplete_MaxWidth = getInt(autoCNode.GetAttribute("MaxWidth")); _autoComplete_singleLineAccept = getBool(autoCNode.GetAttribute("SingleLineAccept")); _autoComplete_StopCharacters = getString(autoCNode.GetAttributeNode("StopCharacters")); XmlElement listNode = autoCNode.SelectSingleNode("./List") as XmlElement; if (listNode != null) { _autoComplete_ListInherit = getBool(listNode.GetAttribute("Inherit")); _autoComplete_List = new Regex("\\s+").Replace(listNode.InnerText, " ").Trim(); } } autoCNode = null; XmlElement callTipNode = langNode.SelectSingleNode("CallTip") as XmlElement; if (callTipNode != null) { _callTip_BackColor = getColor(callTipNode.GetAttribute("BackColor")); _callTip_ForeColor = getColor(callTipNode.GetAttribute("ForeColor")); _callTip_HighlightTextColor = getColor(callTipNode.GetAttribute("HighlightTextColor")); } callTipNode = null; XmlElement caretNode = langNode.SelectSingleNode("Caret") as XmlElement; if (caretNode != null) { // This guy is a bit of an oddball becuase null means "I don't Care" // and we need some way of using the OS value. string blinkRate = caretNode.GetAttribute("BlinkRate"); if (blinkRate.ToLower() == "system") _caret_BlinkRate = SystemInformation.CaretBlinkTime; else _caret_BlinkRate = getInt(blinkRate); _caret_Color = getColor(caretNode.GetAttribute("Color")); _caret_CurrentLineBackgroundAlpha = getInt(caretNode.GetAttribute("CurrentLineBackgroundAlpha")); _caret_CurrentLineBackgroundColor = getColor(caretNode.GetAttribute("CurrentLineBackgroundColor")); _caret_HighlightCurrentLine = getBool(caretNode.GetAttribute("HighlightCurrentLine")); _caret_IsSticky = getBool(caretNode.GetAttribute("IsSticky")); try { _caret_Style = (CaretStyle)Enum.Parse(typeof(CaretStyle), caretNode.GetAttribute("Style"), true); } catch (ArgumentException) { } _caret_Width = getInt(caretNode.GetAttribute("Width")); } caretNode = null; XmlElement clipboardNode = langNode.SelectSingleNode("Clipboard") as XmlElement; if (clipboardNode != null) { _clipboard_ConvertLineBreaksOnPaste = getBool(clipboardNode.GetAttribute("ConvertLineBreaksOnPaste")); } clipboardNode = null; _commands_KeyBindingList = new CommandBindingConfigList(); XmlElement commandsNode = langNode.SelectSingleNode("Commands") as XmlElement; if (commandsNode != null) { _commands_KeyBindingList.Inherit = getBool(commandsNode.GetAttribute("Inherit")); _commands_KeyBindingList.AllowDuplicateBindings = getBool(commandsNode.GetAttribute("AllowDuplicateBindings")); foreach (XmlElement el in commandsNode.SelectNodes("./Binding")) { KeyBinding kb = new KeyBinding(); kb.KeyCode = Utilities.GetKeys(el.GetAttribute("Key")); string modifiers = el.GetAttribute("Modifier"); if (modifiers != string.Empty) { foreach (string modifier in modifiers.Split(' ')) kb.Modifiers |= (Keys)Enum.Parse(typeof(Keys), modifier.Trim(), true); } BindableCommand cmd = (BindableCommand)Enum.Parse(typeof(BindableCommand), el.GetAttribute("Command"), true); CommandBindingConfig cfg = new CommandBindingConfig(kb, getBool(el.GetAttribute("ReplaceCurrent")), cmd); _commands_KeyBindingList.Add(cfg); } } commandsNode = null; XmlElement endOfLineNode = langNode.SelectSingleNode("EndOfLine") as XmlElement; if (endOfLineNode != null) { _endOfLine_IsVisisble = getBool(endOfLineNode.GetAttribute("IsVisible")); try { _endOfLine_Mode = (EndOfLineMode)Enum.Parse(typeof(EndOfLineMode), endOfLineNode.GetAttribute("Mode"), true); } catch (ArgumentException) { } } endOfLineNode = null; XmlElement foldingNode = langNode.SelectSingleNode("Folding") as XmlElement; if (foldingNode != null) { string flags = foldingNode.GetAttribute("Flags").Trim(); if (flags != string.Empty) { FoldFlag? ff = null; foreach (string flag in flags.Split(' ')) ff |= (FoldFlag)Enum.Parse(typeof(FoldFlag), flag.Trim(), true); if (ff.HasValue) _folding_Flags = ff; } _folding_IsEnabled = getBool(foldingNode.GetAttribute("IsEnabled")); try { _folding_MarkerScheme = (FoldMarkerScheme)Enum.Parse(typeof(FoldMarkerScheme), foldingNode.GetAttribute("MarkerScheme"), true); } catch (ArgumentException) { } _folding_UseCompactFolding = getBool(foldingNode.GetAttribute("UseCompactFolding")); } foldingNode = null; XmlElement hotSpotNode = langNode.SelectSingleNode("Hotspot") as XmlElement; if (hotSpotNode != null) { _hotspot_ActiveBackColor = getColor(hotSpotNode.GetAttribute("ActiveBackColor")); _hotspot_ActiveForeColor = getColor(hotSpotNode.GetAttribute("ActiveForeColor")); _hotspot_ActiveUnderline = getBool(hotSpotNode.GetAttribute("ActiveUnderline")); _hotspot_SingleLine = getBool(hotSpotNode.GetAttribute("SingleLine")); _hotspot_UseActiveBackColor = getBool(hotSpotNode.GetAttribute("UseActiveBackColor")); _hotspot_UseActiveForeColor = getBool(hotSpotNode.GetAttribute("UseActiveForeColor")); } hotSpotNode = null; XmlElement indentationNode = langNode.SelectSingleNode("Indentation") as XmlElement; if (indentationNode != null) { _indentation_BackspaceUnindents = getBool(indentationNode.GetAttribute("BackspaceUnindents")); _indentation_IndentWidth = getInt(indentationNode.GetAttribute("IndentWidth")); _indentation_ShowGuides = getBool(indentationNode.GetAttribute("ShowGuides")); _indentation_TabIndents = getBool(indentationNode.GetAttribute("TabIndents")); _indentation_TabWidth = getInt(indentationNode.GetAttribute("TabWidth")); _indentation_UseTabs = getBool(indentationNode.GetAttribute("UseTabs")); try { _indentation_SmartIndentType = (SmartIndent)Enum.Parse(typeof(SmartIndent), indentationNode.GetAttribute("SmartIndentType"), true); } catch (ArgumentException) { } } indentationNode = null; XmlElement indicatorNode = langNode.SelectSingleNode("Indicators") as XmlElement; if (indicatorNode != null) { _indicator_List.Inherit = getBool(indicatorNode.GetAttribute("Inherit")); foreach (XmlElement el in indicatorNode.SelectNodes("Indicator")) { IndicatorConfig ic = new IndicatorConfig(); ic.Number = int.Parse(el.GetAttribute("Number")); ic.Color = getColor(el.GetAttribute("Color")); ic.Inherit = getBool(el.GetAttribute("Inherit")); ic.IsDrawnUnder = getBool(el.GetAttribute("IsDrawnUnder")); try { ic.Style = (IndicatorStyle)Enum.Parse(typeof(IndicatorStyle), el.GetAttribute("Style"), true); } catch (ArgumentException) { } _indicator_List.Add(ic); } } _lexing_Properties = new LexerPropertiesConfig(); _lexing_Keywords = new KeyWordConfigList(); XmlElement lexerNode = langNode.SelectSingleNode("Lexer") as XmlElement; if (lexerNode != null) { _lexing_WhitespaceChars = getString(lexerNode.GetAttributeNode("WhitespaceChars")); _lexing_WordChars = getString(lexerNode.GetAttributeNode("WordChars")); _lexing_Language = getString(lexerNode.GetAttributeNode("LexerName")); _lexing_LineCommentPrefix = getString(lexerNode.GetAttributeNode("LineCommentPrefix")); _lexing_StreamCommentPrefix = getString(lexerNode.GetAttributeNode("StreamCommentPrefix")); _lexing_StreamCommentSuffix = getString(lexerNode.GetAttributeNode("StreamCommentSuffix")); XmlElement propNode = lexerNode.SelectSingleNode("Properties") as XmlElement; if (propNode != null) { _lexing_Properties.Inherit = getBool(propNode.GetAttribute("Inherit")); foreach (XmlElement el in propNode.SelectNodes("Property")) _lexing_Properties.Add(el.GetAttribute("Name"), el.GetAttribute("Value")); } foreach (XmlElement el in lexerNode.SelectNodes("Keywords")) _lexing_Keywords.Add(new KeyWordConfig(getInt(el.GetAttribute("List")).Value, el.InnerText.Trim(), getBool(el.GetAttribute("Inherit")))); } lexerNode = null; XmlElement lineWrapNode = langNode.SelectSingleNode("LineWrapping") as XmlElement; if (lineWrapNode != null) { try { _lineWrapping_Mode = (LineWrappingMode)Enum.Parse(typeof(LineWrappingMode), lineWrapNode.GetAttribute("Mode"), true); } catch (ArgumentException) { } _lineWrapping_IndentSize = getInt(lineWrapNode.GetAttribute("IndentSize")); try { _lineWrapping_IndentMode = (LineWrappingIndentMode)Enum.Parse(typeof(LineWrappingIndentMode), lineWrapNode.GetAttribute("IndentMode"), true); } catch (ArgumentException) { } string flags = lineWrapNode.GetAttribute("VisualFlags").Trim(); if (flags != string.Empty) { LineWrappingVisualFlags? wvf = null; foreach (string flag in flags.Split(' ')) wvf |= (LineWrappingVisualFlags)Enum.Parse(typeof(LineWrappingVisualFlags), flag.Trim(), true); if (wvf.HasValue) _lineWrapping_VisualFlags = wvf; } try { _lineWrapping_VisualFlagsLocations = (LineWrappingVisualFlagsLocations)Enum.Parse(typeof(LineWrappingVisualFlagsLocations), lineWrapNode.GetAttribute("VisualFlagsLocations"), true); } catch (ArgumentException) { } } lineWrapNode = null; XmlElement longLinesNode = langNode.SelectSingleNode("LongLines") as XmlElement; if (longLinesNode != null) { _longLines_EdgeColor = getColor(longLinesNode.GetAttribute("EdgeColor")); _longLines_EdgeColumn = getInt(longLinesNode.GetAttribute("EdgeColumn")); try { _longLines_EdgeMode = (EdgeMode)Enum.Parse(typeof(EdgeMode), longLinesNode.GetAttribute("EdgeMode"), true); } catch (ArgumentException) { } } longLinesNode = null; _margin_List = new MarginConfigList(); XmlElement marginNode = langNode.SelectSingleNode("Margins") as XmlElement; if (marginNode != null) { _margin_List.FoldMarginColor = getColor(marginNode.GetAttribute("FoldMarginColor")); _margin_List.FoldMarginHighlightColor = getColor(marginNode.GetAttribute("FoldMarginHighlightColor")); _margin_List.Left = getInt(marginNode.GetAttribute("Left")); _margin_List.Right = getInt(marginNode.GetAttribute("Right")); _margin_List.Inherit = getBool(marginNode.GetAttribute("Inherit")); foreach (XmlElement el in marginNode.SelectNodes("./Margin")) { MarginConfig mc = new MarginConfig(); mc.Number = int.Parse(el.GetAttribute("Number")); mc.Inherit = getBool(el.GetAttribute("Inherit")); mc.AutoToggleMarkerNumber = getInt(el.GetAttribute("AutoToggleMarkerNumber")); mc.IsClickable = getBool(el.GetAttribute("IsClickable")); mc.IsFoldMargin = getBool(el.GetAttribute("IsFoldMargin")); mc.IsMarkerMargin = getBool(el.GetAttribute("IsMarkerMargin")); try { mc.Type = (MarginType)Enum.Parse(typeof(MarginType), el.GetAttribute("Type"), true); } catch (ArgumentException) { } mc.Width = getInt(el.GetAttribute("Width")); _margin_List.Add(mc); } } marginNode = null; XmlElement markersNode = langNode.SelectSingleNode("Markers") as XmlElement; _markers_List = new MarkersConfigList(); if (markersNode != null) { _markers_List.Inherit = getBool(markersNode.GetAttribute("Inherit")); foreach (XmlElement el in markersNode.SelectNodes("Marker")) { MarkersConfig mc = new MarkersConfig(); mc.Alpha = getInt(el.GetAttribute("Alpha")); mc.BackColor = getColor(el.GetAttribute("BackColor")); mc.ForeColor = getColor(el.GetAttribute("ForeColor")); mc.Name = getString(el.GetAttributeNode("Name")); mc.Number = getInt(el.GetAttribute("Number")); mc.Inherit = getBool(el.GetAttribute("Inherit")); try { mc.Symbol = (MarkerSymbol)Enum.Parse(typeof(MarkerSymbol), el.GetAttribute("Symbol"), true); } catch (ArgumentException) { } _markers_List.Add(mc); } } XmlElement scrollingNode = langNode.SelectSingleNode("Scrolling") as XmlElement; if (scrollingNode != null) { _scrolling_EndAtLastLine = getBool(scrollingNode.GetAttribute("EndAtLastLine")); _scrolling_HorizontalWidth = getInt(scrollingNode.GetAttribute("HorizontalWidth")); string flags = scrollingNode.GetAttribute("ScrollBars").Trim(); if (flags != string.Empty) { ScrollBars? sb = null; foreach (string flag in flags.Split(' ')) sb |= (ScrollBars)Enum.Parse(typeof(ScrollBars), flag.Trim(), true); if (sb.HasValue) _scrolling_ScrollBars = sb; } _scrolling_XOffset = getInt(scrollingNode.GetAttribute("XOffset")); } scrollingNode = null; XmlElement selectionNode = langNode.SelectSingleNode("Selection") as XmlElement; if (selectionNode != null) { _selection_BackColor = getColor(selectionNode.GetAttribute("BackColor")); _selection_BackColorUnfocused = getColor(selectionNode.GetAttribute("BackColorUnfocused")); _selection_ForeColor = getColor(selectionNode.GetAttribute("ForeColor")); _selection_ForeColorUnfocused = getColor(selectionNode.GetAttribute("ForeColorUnfocused")); _selection_Hidden = getBool(selectionNode.GetAttribute("Hidden")); _selection_HideSelection = getBool(selectionNode.GetAttribute("HideSelection")); try { _selection_Mode = (SelectionMode)Enum.Parse(typeof(SelectionMode), selectionNode.GetAttribute("Mode"), true); } catch (ArgumentException) { } } selectionNode = null; _snippetsConfigList = new SnippetsConfigList(); XmlElement snippetsNode = langNode.SelectSingleNode("Snippets") as XmlElement; if (snippetsNode != null) { _snippetsConfigList.ActiveSnippetColor = getColor(snippetsNode.GetAttribute("ActiveSnippetColor")); _snippetsConfigList.ActiveSnippetIndicator = getInt(snippetsNode.GetAttribute("ActiveSnippetIndicator")); _snippetsConfigList.InactiveSnippetColor = getColor(snippetsNode.GetAttribute("InactiveSnippetColor")); _snippetsConfigList.InactiveSnippetIndicator = getInt(snippetsNode.GetAttribute("InactiveSnippetIndicator")); try { _snippetsConfigList.ActiveSnippetIndicatorStyle = (IndicatorStyle)Enum.Parse(typeof(IndicatorStyle), snippetsNode.GetAttribute("ActiveSnippetIndicatorStyle"), true); } catch (ArgumentException) { } try { _snippetsConfigList.InactiveSnippetIndicatorStyle = (IndicatorStyle)Enum.Parse(typeof(IndicatorStyle), snippetsNode.GetAttribute("InactiveSnippetIndicatorStyle"), true); } catch (ArgumentException) { } _snippetsConfigList.DefaultDelimeter = getChar(snippetsNode.GetAttribute("DefaultDelimeter")); _snippetsConfigList.IsEnabled = getBool(snippetsNode.GetAttribute("IsEnabled")); _snippetsConfigList.IsOneKeySelectionEmbedEnabled = getBool(snippetsNode.GetAttribute("IsOneKeySelectionEmbedEnabled")); foreach (XmlElement el in snippetsNode.SelectNodes("Snippet")) { SnippetsConfig sc = new SnippetsConfig(); sc.Shortcut = el.GetAttribute("Shortcut"); sc.Code = el.InnerText; sc.Delimeter = getChar(el.GetAttribute("Delimeter")); sc.IsSurroundsWith = getBool(el.GetAttribute("IsSurroundsWith")); _snippetsConfigList.Add(sc); } } snippetsNode = null; _styles = new StyleConfigList(); XmlElement stylesNode = langNode.SelectSingleNode("Styles") as XmlElement; if (stylesNode != null) { _styles.Bits = getInt(stylesNode.GetAttribute("Bits")); foreach (XmlElement el in stylesNode.SelectNodes("Style")) { StyleConfig sc = new StyleConfig(); sc.Name = el.GetAttribute("Name"); sc.Number = getInt(el.GetAttribute("Number")); sc.BackColor = getColor(el.GetAttribute("BackColor")); sc.Bold = getBool(el.GetAttribute("Bold")); try { sc.Case = (StyleCase)Enum.Parse(typeof(StyleCase), el.GetAttribute("Case"), true); } catch (ArgumentException) { } try { sc.CharacterSet = (CharacterSet)Enum.Parse(typeof(CharacterSet), el.GetAttribute("CharacterSet"), true); } catch (ArgumentException) { } sc.FontName = getString(el.GetAttributeNode("FontName")); sc.ForeColor = getColor(el.GetAttribute("ForeColor")); sc.IsChangeable = getBool(el.GetAttribute("IsChangeable")); sc.IsHotspot = getBool(el.GetAttribute("IsHotspot")); sc.IsSelectionEolFilled = getBool(el.GetAttribute("IsSelectionEolFilled")); sc.IsVisible = getBool(el.GetAttribute("IsVisible")); sc.Italic = getBool(el.GetAttribute("Italic")); sc.Size = getInt(el.GetAttribute("Size")); sc.Underline = getBool(el.GetAttribute("Underline")); sc.Inherit = getBool(el.GetAttribute("Inherit")); _styles.Add(sc); } // This is a nifty added on hack made specifically for HTML. // Normally the style config elements are quite managable as there // are typically less than 10 when you don't count common styles. // // However HTML uses 9 different Sub languages that combined make // use of all 128 styles (well there are some small gaps). In order // to make this more managable I did added a SubLanguage element that // basically just prepends the Language's name and "." to the Style // Name definition. // // So for example if you had the following // <Styles> // <SubLanguage Name="ASP JavaScript"> // <Style Name="Keyword" Bold="True" /> // </SubLanguage> // </Styles> // That style's name will get interpreted as "ASP JavaScript.Keyword". // which if you look at the html.txt in LexerStyleNames you'll see it // maps to Style # 62 // Yeah I copied and pasted from above. I know. Feel free to refactor // this and check it in since you're so high and mighty. foreach (XmlElement subLanguage in stylesNode.SelectNodes("SubLanguage")) { string subLanguageName = subLanguage.GetAttribute("Name"); foreach (XmlElement el in subLanguage.SelectNodes("Style")) { StyleConfig sc = new StyleConfig(); sc.Name = subLanguageName + "." + el.GetAttribute("Name"); sc.Number = getInt(el.GetAttribute("Number")); sc.BackColor = getColor(el.GetAttribute("BackColor")); sc.Bold = getBool(el.GetAttribute("Bold")); try { sc.Case = (StyleCase)Enum.Parse(typeof(StyleCase), el.GetAttribute("Case"), true); } catch (ArgumentException) { } try { sc.CharacterSet = (CharacterSet)Enum.Parse(typeof(CharacterSet), el.GetAttribute("CharacterSet"), true); } catch (ArgumentException) { } sc.FontName = getString(el.GetAttributeNode("FontName")); sc.ForeColor = getColor(el.GetAttribute("ForeColor")); sc.IsChangeable = getBool(el.GetAttribute("IsChangeable")); sc.IsHotspot = getBool(el.GetAttribute("IsHotspot")); sc.IsSelectionEolFilled = getBool(el.GetAttribute("IsSelectionEolFilled")); sc.IsVisible = getBool(el.GetAttribute("IsVisible")); sc.Italic = getBool(el.GetAttribute("Italic")); sc.Size = getInt(el.GetAttribute("Size")); sc.Underline = getBool(el.GetAttribute("Underline")); sc.Inherit = getBool(el.GetAttribute("Inherit")); _styles.Add(sc); } } } stylesNode = null; XmlElement undoRedoNode = langNode.SelectSingleNode("UndoRedo") as XmlElement; if (undoRedoNode != null) { _undoRedoIsUndoEnabled = getBool(undoRedoNode.GetAttribute("IsUndoEnabled")); } undoRedoNode = null; XmlElement whitespaceNode = langNode.SelectSingleNode("Whitespace") as XmlElement; if (whitespaceNode != null) { _whitespace_BackColor = getColor(whitespaceNode.GetAttribute("BackColor")); _whitespace_ForeColor = getColor(whitespaceNode.GetAttribute("ForeColor")); _whitespace_Mode = (WhitespaceMode)Enum.Parse(typeof(WhitespaceMode), whitespaceNode.GetAttribute("Mode"), true); } whitespaceNode = null; configDocument = null; } public void Load(string fileName, bool useXmlReader) { if (useXmlReader) { XmlReaderSettings s = new XmlReaderSettings(); s.IgnoreComments = true; s.IgnoreWhitespace = true; Load(XmlReader.Create(fileName, s)); } else { XmlDocument doc = new XmlDocument(); doc.PreserveWhitespace = true; doc.Load(fileName); Load(doc); } } public void Load(Stream inStream, bool useXmlReader) { if (useXmlReader) { XmlReaderSettings s = new XmlReaderSettings(); s.IgnoreComments = true; s.IgnoreWhitespace = true; Load(XmlReader.Create(inStream, s)); } else { XmlDocument doc = new XmlDocument(); doc.PreserveWhitespace = true; doc.Load(inStream); Load(doc); } } private void ReadAutoComplete(XmlReader reader) { if (reader.HasAttributes) { while (reader.MoveToNextAttribute()) { string attrName = reader.Name.ToLower(); switch (attrName) { case "autohide": _autoComplete_AutoHide = getBool(reader.Value); break; case "automaticlengthentered": _autoComplete_AutomaticLengthEntered = getBool(reader.Value); break; case "cancelatstart": _autoComplete_cancelAtStart = getBool(reader.Value); break; case "droprestofword": _autoComplete_DropRestOfWord = getBool(reader.Value); break; case "fillupcharacters": _autoComplete_fillUpCharacters = reader.Value; break; case "imageseperator": _autoComplete_ImageSeperator = getChar(reader.Value); break; case "iscasesensitive": _autoComplete_IsCaseSensitive= getBool(reader.Value); break; case "listseperator": _autoComplete_ListSeperator = getChar(reader.Value); break; case "maxheight": _autoComplete_MaxHeight = getInt(reader.Value); break; case "maxwidth": _autoComplete_MaxWidth = getInt(reader.Value); break; case "singlelineaccept": _autoComplete_singleLineAccept = getBool(reader.Value); break; case "stopcharacters": _autoComplete_StopCharacters = reader.Value; break; } } reader.MoveToElement(); } if (!reader.IsEmptyElement) { while (!(reader.NodeType == XmlNodeType.EndElement && reader.Name.Equals("autocomplete", StringComparison.OrdinalIgnoreCase))) { reader.Read(); if (reader.NodeType == XmlNodeType.Element && reader.Name.Equals("list", StringComparison.OrdinalIgnoreCase)) { if (reader.HasAttributes) { while (reader.MoveToNextAttribute()) if (reader.Name.Equals("inherit", StringComparison.OrdinalIgnoreCase)) _autoComplete_ListInherit = getBool(reader.Value); reader.MoveToElement(); } _autoComplete_List = new Regex("\\s+").Replace(reader.ReadString(), " ").Trim(); } } } reader.Read(); } private void ReadCallTip(XmlReader reader) { if (reader.HasAttributes) { while (reader.MoveToNextAttribute()) { string attrName = reader.Name.ToLower(); switch (attrName) { case "backcolor": _callTip_BackColor = getColor(reader.Value); break; case "forecolor": _callTip_ForeColor = getColor(reader.Value); break; case "highlighttextcolor": _callTip_HighlightTextColor = getColor(reader.Value); break; } } reader.MoveToElement(); } reader.Skip(); } private void ReadCaret(XmlReader reader) { if (reader.HasAttributes) { while (reader.MoveToNextAttribute()) { string attrName = reader.Name.ToLower(); switch (attrName) { case "blinkrate": // This guy is a bit of an oddball becuase null means "I don't Care" // and we need some way of using the OS value. string blinkRate = reader.Value; if (blinkRate.ToLower() == "system") _caret_BlinkRate = SystemInformation.CaretBlinkTime; else _caret_BlinkRate = getInt(blinkRate); break; case "color": _caret_Color = getColor(reader.Value); break; case "currentlinebackgroundalpha": _caret_CurrentLineBackgroundAlpha = getInt(reader.Value); break; case "currentlinebackgroundcolor": _caret_CurrentLineBackgroundColor = getColor(reader.Value); break; case "highlightcurrentline": _caret_HighlightCurrentLine = getBool(reader.Value); break; case "issticky": _caret_IsSticky = getBool(reader.Value); break; case "style": _caret_Style = (CaretStyle)Enum.Parse(typeof(CaretStyle), reader.Value, true); break; case "width": _caret_Width = getInt(reader.Value); break; } } reader.MoveToElement(); } reader.Skip(); } private void ReadClipboard(XmlReader reader) { if (reader.HasAttributes) { while (reader.MoveToNextAttribute()) { string attrName = reader.Name.ToLower(); switch (attrName) { case "convertlinebreaksonpaste": _clipboard_ConvertLineBreaksOnPaste = getBool(reader.Value); break; } } reader.MoveToElement(); } reader.Skip(); } private void ReadCommands(XmlReader reader) { if (reader.HasAttributes) { while (reader.MoveToNextAttribute()) { string attrName = reader.Name.ToLower(); switch (attrName) { case "Inherit": _commands_KeyBindingList.Inherit = getBool(reader.Value); break; case "AllowDuplicateBindings": _commands_KeyBindingList.AllowDuplicateBindings = getBool(reader.Value); break; } } reader.MoveToElement(); } if (!reader.IsEmptyElement) { while (!(reader.NodeType == XmlNodeType.EndElement && reader.Name.Equals("commands", StringComparison.OrdinalIgnoreCase))) { reader.Read(); if (reader.NodeType == XmlNodeType.Element && reader.Name.Equals("binding", StringComparison.OrdinalIgnoreCase)) { if (reader.HasAttributes) { KeyBinding kb = new KeyBinding(); BindableCommand cmd = new BindableCommand(); bool? replaceCurrent = null; while (reader.MoveToNextAttribute()) { string attrName = reader.Name.ToLower(); switch (attrName) { case "key": kb.KeyCode = Utilities.GetKeys(reader.Value); break; case "modifier": if (reader.Value != string.Empty) { foreach (string modifier in reader.Value.Split(' ')) kb.Modifiers |= (Keys)Enum.Parse(typeof(Keys), modifier.Trim(), true); } break; case "command": cmd = (BindableCommand)Enum.Parse(typeof(BindableCommand), reader.Value, true); break; case "replacecurrent": replaceCurrent = getBool(reader.Value); break; } } _commands_KeyBindingList.Add(new CommandBindingConfig(kb, replaceCurrent, cmd)); } reader.MoveToElement(); } } } reader.Read(); } private void ReadEndOfLine(XmlReader reader) { if (reader.HasAttributes) { while (reader.MoveToNextAttribute()) { string attrName = reader.Name.ToLower(); switch (attrName) { case "isvisible": _endOfLine_IsVisisble = getBool(reader.Value); break; case "mode": _endOfLine_Mode = (EndOfLineMode)Enum.Parse(typeof(EndOfLineMode), reader.Value, true); break; } } reader.MoveToElement(); } reader.Skip(); } private void ReadFolding(XmlReader reader) { if (reader.HasAttributes) { while (reader.MoveToNextAttribute()) { string attrName = reader.Name.ToLower(); switch (attrName) { case "flags": string flags = reader.Value.Trim(); if (flags != string.Empty) { FoldFlag? ff = null; foreach (string flag in flags.Split(' ')) ff |= (FoldFlag)Enum.Parse(typeof(FoldFlag), flag.Trim(), true); if (ff.HasValue) _folding_Flags = ff; } break; case "IsEnabled": _folding_MarkerScheme = (FoldMarkerScheme)Enum.Parse(typeof(FoldMarkerScheme), reader.Value, true); break; case "usecompactfolding": _folding_UseCompactFolding = getBool(reader.Value); break; } } reader.MoveToElement(); } reader.Skip(); } private void ReadHotspot(XmlReader reader) { if (reader.HasAttributes) { while (reader.MoveToNextAttribute()) { string attrName = reader.Name.ToLower(); switch (attrName) { case "activebackcolor": _hotspot_ActiveBackColor = getColor(reader.Value); break; case "activeforecolor": _hotspot_ActiveForeColor = getColor(reader.Value); break; case "activeunderline": _hotspot_ActiveUnderline = getBool(reader.Value); break; case "singleline": _hotspot_SingleLine = getBool(reader.Value); break; case "useactivebackcolor": _hotspot_UseActiveBackColor = getBool(reader.Value); break; case "useactiveforecolor": _hotspot_UseActiveForeColor = getBool(reader.Value); break; } } reader.MoveToElement(); } reader.Skip(); } private void ReadIndentation(XmlReader reader) { if (reader.HasAttributes) { while (reader.MoveToNextAttribute()) { string attrName = reader.Name.ToLower(); switch (attrName) { case "backspaceunindents": _indentation_BackspaceUnindents = getBool(reader.Value); break; case "indentwidth": _indentation_IndentWidth = getInt(reader.Value); break; case "showguides": _indentation_ShowGuides = getBool(reader.Value); break; case "tabindents": _indentation_TabIndents = getBool(reader.Value); break; case "tabwidth": _indentation_TabWidth = getInt(reader.Value); break; case "usetabs": _indentation_UseTabs = getBool(reader.Value); break; case "smartindenttype": _indentation_SmartIndentType = (SmartIndent)Enum.Parse(typeof(SmartIndent), reader.Value, true); break; } } reader.MoveToElement(); } reader.Skip(); } private void ReadIndicators(XmlReader reader) { if (reader.HasAttributes) { while (reader.MoveToNextAttribute()) { string attrName = reader.Name.ToLower(); switch (attrName) { case "inherit": _indicator_List.Inherit = getBool(reader.Value); break; } } reader.MoveToElement(); } if (!reader.IsEmptyElement) { while (!(reader.NodeType == XmlNodeType.EndElement && reader.Name.Equals("indicators", StringComparison.OrdinalIgnoreCase))) { reader.Read(); if (reader.NodeType == XmlNodeType.Element && reader.Name.Equals("indicator", StringComparison.OrdinalIgnoreCase)) { if (reader.HasAttributes) { IndicatorConfig ic = new IndicatorConfig(); while (reader.MoveToNextAttribute()) { string attrName = reader.Name.ToLower(); switch (attrName) { case "number": ic.Number = int.Parse(reader.Value); break; case "color": ic.Color = getColor(reader.Value); break; case "inherit": ic.Inherit = getBool(reader.Value); break; case "isdrawnunder": ic.IsDrawnUnder = getBool(reader.Value); break; case "style": ic.Style = (IndicatorStyle)Enum.Parse(typeof(IndicatorStyle), reader.Value, true); break; } } _indicator_List.Add(ic); reader.MoveToElement(); } } } } reader.Read(); } private void ReadLanguage(XmlReader reader) { _commands_KeyBindingList = new CommandBindingConfigList(); _lexing_Properties = new LexerPropertiesConfig(); _lexing_Keywords = new KeyWordConfigList(); _margin_List = new MarginConfigList(); _markers_List = new MarkersConfigList(); _snippetsConfigList = new SnippetsConfigList(); _styles = new StyleConfigList(); reader.Read(); while (reader.NodeType == XmlNodeType.Element) { string elName = reader.Name.ToLower(); switch (elName) { case "autocomplete": ReadAutoComplete(reader); break; case "calltip": ReadCallTip(reader); break; case "caret": ReadCaret(reader); break; case "clipboard": ReadClipboard(reader); break; case "commands": ReadCommands(reader); break; case "endofline": ReadEndOfLine(reader); break; case "folding": ReadFolding(reader); break; case "hotspot": ReadHotspot(reader); break; case "indentation": ReadIndentation(reader); break; case "indicators": ReadIndicators(reader); break; case "lexer": ReadLexer(reader); break; case "linewrapping": ReadLineWrapping(reader); break; case "longlines": ReadLongLines(reader); break; case "margins": ReadMargins(reader); break; case "markers": ReadMarkers(reader); break; case "scrolling": ReadScrolling(reader); break; case "selection": ReadSelection(reader); break; case "snippets": ReadSnippets(reader); break; case "styles": ReadStyles(reader); break; case "undoredo": ReadUndoRedo(reader); break; case "whitespace": ReadWhitespace(reader); break; default: reader.Skip(); break; } } } private void ReadLexer(XmlReader reader) { if (reader.HasAttributes) { while (reader.MoveToNextAttribute()) { string attrName = reader.Name.ToLower(); switch (attrName) { case "whitespacechars": _lexing_WhitespaceChars = reader.Value; break; case "wordchars": _lexing_WordChars = reader.Value; break; case "lexername": _lexing_Language = reader.Value; break; case "linecommentprefix": _lexing_LineCommentPrefix = reader.Value; break; case "streamcommentprefix": _lexing_StreamCommentPrefix = reader.Value; break; case "streamcommentsuffix": _lexing_StreamCommentSuffix = reader.Value; break; } } reader.MoveToElement(); } if (!reader.IsEmptyElement) { reader.Read(); while (!(reader.NodeType == XmlNodeType.EndElement && reader.Name.Equals("lexer", StringComparison.OrdinalIgnoreCase))) { if (reader.NodeType == XmlNodeType.Element) { if (reader.Name.Equals("properties", StringComparison.OrdinalIgnoreCase)) ReadLexerProperties(reader); else if (reader.Name.Equals("keywords", StringComparison.OrdinalIgnoreCase)) ReadLexerKeywords(reader); } } } reader.Read(); } private void ReadLexerKeywords(XmlReader reader) { bool? inherit = null; int? list = null; string keywords = null; if (reader.HasAttributes) { while (reader.MoveToNextAttribute()) { string attrName = reader.Name.ToLower(); switch (attrName) { case "inherit": inherit = getBool(reader.Value); break; case "list": list = getInt(reader.Value); break; } } reader.MoveToElement(); } if (!reader.IsEmptyElement) keywords = reader.ReadString().Trim(); _lexing_Keywords.Add(new KeyWordConfig(list.Value, keywords, inherit)); reader.Read(); } private void ReadLexerProperties(XmlReader reader) { if (reader.HasAttributes) { while (reader.MoveToNextAttribute()) if (reader.Name.ToLower() == "inherit") _lexing_Properties.Inherit = getBool(reader.Value); reader.MoveToElement(); } if (!reader.IsEmptyElement) { while (!(reader.NodeType == XmlNodeType.EndElement && reader.Name.Equals("properties", StringComparison.OrdinalIgnoreCase))) { reader.Read(); if (reader.NodeType == XmlNodeType.Element && reader.Name.Equals("property", StringComparison.OrdinalIgnoreCase)) { if (reader.HasAttributes) { string name = string.Empty; string value = string.Empty; while (reader.MoveToNextAttribute()) { string attrName = reader.Name.ToLower(); switch (attrName) { case "name": name = reader.Value; break; case "value": value = reader.Value; break; } } _lexing_Properties.Add(name, value); reader.MoveToElement(); } } } } reader.Read(); } private void ReadLineWrapping(XmlReader reader) { if (reader.HasAttributes) { while (reader.MoveToNextAttribute()) { string attrName = reader.Name.ToLower(); switch (attrName) { case "mode": _lineWrapping_Mode = (LineWrappingMode)Enum.Parse(typeof(LineWrappingMode), reader.Value, true); break; case "indentsize": _lineWrapping_IndentSize = getInt(reader.Value); break; case "indentmode": _lineWrapping_IndentMode = (LineWrappingIndentMode)Enum.Parse(typeof(LineWrappingIndentMode), reader.Value, true); break; case "visualflags": string flags = reader.Value.Trim(); if (flags != string.Empty) { LineWrappingVisualFlags? wvf = null; foreach (string flag in flags.Split(' ')) wvf |= (LineWrappingVisualFlags)Enum.Parse(typeof(LineWrappingVisualFlags), flag.Trim(), true); if (wvf.HasValue) _lineWrapping_VisualFlags = wvf; } break; case "visualflagslocations": _lineWrapping_VisualFlagsLocations = (LineWrappingVisualFlagsLocations)Enum.Parse(typeof(LineWrappingVisualFlagsLocations), reader.Value, true); break; } } reader.MoveToElement(); } reader.Skip(); } private void ReadLongLines(XmlReader reader) { if (reader.HasAttributes) { while (reader.MoveToNextAttribute()) { string attrName = reader.Name.ToLower(); switch (attrName) { case "edgecolor": _longLines_EdgeColor = getColor(reader.Value); break; case "edgecolumn": _longLines_EdgeColumn = getInt(reader.Value); break; case "edgemode": _longLines_EdgeMode = (EdgeMode)Enum.Parse(typeof(EdgeMode), reader.Value, true); break; } } reader.MoveToElement(); } reader.Skip(); } private void ReadMargins(XmlReader reader) { if (reader.HasAttributes) { while (reader.MoveToNextAttribute()) { string attrName = reader.Name.ToLower(); switch (attrName) { case "foldmargincolor": _margin_List.FoldMarginColor = getColor(reader.Value); break; case "foldmarginhighlightcolor": _margin_List.FoldMarginHighlightColor = getColor(reader.Value); break; case "left": _margin_List.Left = getInt(reader.Value); break; case "right": _margin_List.Right = getInt(reader.Value); break; case "inherit": _margin_List.Inherit = getBool(reader.Value); break; } } reader.MoveToElement(); } if (!reader.IsEmptyElement) { while (!(reader.NodeType == XmlNodeType.EndElement && reader.Name.Equals("margins", StringComparison.OrdinalIgnoreCase))) { reader.Read(); if (reader.NodeType == XmlNodeType.Element && reader.Name.Equals("margin", StringComparison.OrdinalIgnoreCase)) { if (reader.HasAttributes) { MarginConfig mc = new MarginConfig(); while (reader.MoveToNextAttribute()) { string attrName = reader.Name.ToLower(); switch (attrName) { case "number": mc.Number = int.Parse(reader.Value); break; case "inherit": mc.Inherit = getBool(reader.Value); break; case "autotogglemarkernumber": mc.AutoToggleMarkerNumber = getInt(reader.Value); break; case "isclickable": mc.IsClickable = getBool(reader.Value); break; case "isfoldmargin": mc.IsFoldMargin = getBool(reader.Value); break; case "ismarkermargin": mc.IsMarkerMargin = getBool(reader.Value); break; case "type": mc.Type = (MarginType)Enum.Parse(typeof(MarginType), reader.Value, true); break; case "width": mc.Width = getInt(reader.Value); break; } } _margin_List.Add(mc); reader.MoveToElement(); } } } } reader.Read(); } private void ReadMarkers(XmlReader reader) { if (reader.HasAttributes) { while (reader.MoveToNextAttribute()) if(reader.Name.ToLower() == "inherit") _markers_List.Inherit = getBool(reader.Value); reader.MoveToElement(); } if (!reader.IsEmptyElement) { while (!(reader.NodeType == XmlNodeType.EndElement && reader.Name.Equals("markers", StringComparison.OrdinalIgnoreCase))) { reader.Read(); if (reader.NodeType == XmlNodeType.Element && reader.Name.Equals("marker", StringComparison.OrdinalIgnoreCase)) { if (reader.HasAttributes) { MarkersConfig mc = new MarkersConfig(); while (reader.MoveToNextAttribute()) { string attrName = reader.Name.ToLower(); switch (attrName) { case "alpha": mc.Alpha = getInt(reader.Value); break; case "backcolor": mc.BackColor = getColor(reader.Value); break; case "forecolor": mc.ForeColor = getColor(reader.Value); break; case "name": mc.Name = reader.Value; break; case "number": mc.Number = getInt(reader.Value); break; case "inherit": mc.Inherit = getBool(reader.Value); break; case "symbol": mc.Symbol = (MarkerSymbol)Enum.Parse(typeof(MarkerSymbol), reader.Value, true); break; } } reader.MoveToElement(); _markers_List.Add(mc); } } } } reader.Read(); } private void ReadScrolling(XmlReader reader) { if (reader.HasAttributes) { while (reader.MoveToNextAttribute()) { string attrName = reader.Name.ToLower(); switch (attrName) { case "endatlastline": _scrolling_EndAtLastLine = getBool(reader.Value); break; case "horizontalwidth": _scrolling_HorizontalWidth = getInt(reader.Value); break; case "scrollbars": string flags = reader.Value.Trim(); if (flags != string.Empty) { ScrollBars? sb = null; foreach (string flag in flags.Split(' ')) sb |= (ScrollBars)Enum.Parse(typeof(ScrollBars), flag.Trim(), true); if (sb.HasValue) _scrolling_ScrollBars = sb; } break; case "xoffset": _scrolling_XOffset = getInt(reader.Value); break; } } reader.MoveToElement(); } reader.Skip(); } private void ReadSelection(XmlReader reader) { if (reader.HasAttributes) { while (reader.MoveToNextAttribute()) { string attrName = reader.Name.ToLower(); switch (attrName) { case "backcolor": _selection_BackColor = getColor(reader.Value); break; case "backcolorunfocused": _selection_BackColorUnfocused = getColor(reader.Value); break; case "forecolor": _selection_ForeColor = getColor(reader.Value); break; case "forecolorunfocused": _selection_ForeColorUnfocused = getColor(reader.Value); break; case "hidden": _selection_Hidden = getBool(reader.Value); break; case "hideselection": _selection_HideSelection = getBool(reader.Value); break; case "mode": _selection_Mode = (SelectionMode)Enum.Parse(typeof(SelectionMode), reader.Value, true); break; } } reader.MoveToElement(); } reader.Skip(); } private void ReadSnippets(XmlReader reader) { if (reader.HasAttributes) { while (reader.MoveToNextAttribute()) { string attrName = reader.Name.ToLower(); switch (attrName) { case "activesnippetcolor": _snippetsConfigList.ActiveSnippetColor = getColor(reader.Value); break; case "activesnippetindicator": _snippetsConfigList.ActiveSnippetIndicator = getInt(reader.Value); break; case "inactivesnippetcolor": _snippetsConfigList.InactiveSnippetColor = getColor(reader.Value); break; case "inactivesnippetindicator": _snippetsConfigList.InactiveSnippetIndicator = getInt(reader.Value); break; case "activesnippetindicatorstyle": _snippetsConfigList.ActiveSnippetIndicatorStyle = (IndicatorStyle)Enum.Parse(typeof(IndicatorStyle), reader.Value, true); break; case "inactivesnippetindicatorstyle": _snippetsConfigList.InactiveSnippetIndicatorStyle = (IndicatorStyle)Enum.Parse(typeof(IndicatorStyle), reader.Value, true); break; case "defaultdelimeter": _snippetsConfigList.DefaultDelimeter = getChar(reader.Value); break; case "isenabled": _snippetsConfigList.IsEnabled = getBool(reader.Value); break; case "isonekeyselectionembedenabled": _snippetsConfigList.IsOneKeySelectionEmbedEnabled = getBool(reader.Value); break; } } reader.MoveToElement(); } if (!reader.IsEmptyElement) { while (!(reader.NodeType == XmlNodeType.EndElement && reader.Name.Equals("snippets", StringComparison.OrdinalIgnoreCase))) { reader.Read(); if (reader.NodeType == XmlNodeType.Element && reader.Name.Equals("snippet", StringComparison.OrdinalIgnoreCase)) { if (reader.HasAttributes) { SnippetsConfig sc = new SnippetsConfig(); if (reader.HasAttributes) { while (reader.MoveToNextAttribute()) { string attrName = reader.Name.ToLower(); switch (attrName) { case "shortcut": sc.Shortcut = reader.Value; break; case "delimeter": sc.Delimeter = getChar(reader.Value); break; case "issurroundswith": sc.IsSurroundsWith = getBool(reader.Value); break; } } } reader.MoveToElement(); sc.Code = reader.ReadString(); _snippetsConfigList.Add(sc); } } } } reader.Read(); } private void ReadStyles(XmlReader reader) { if (reader.HasAttributes) { while (reader.MoveToNextAttribute()) if (reader.Name.ToLower() == "bits") _undoRedoIsUndoEnabled = getBool(reader.Value); reader.MoveToElement(); } if (!reader.IsEmptyElement) { while (!(reader.NodeType == XmlNodeType.EndElement && reader.Name.Equals("styles", StringComparison.OrdinalIgnoreCase))) { reader.Read(); if (reader.NodeType == XmlNodeType.Element && reader.Name.Equals("style", StringComparison.OrdinalIgnoreCase)) { _styles.Add(getStyleConfigFromElement(reader)); } else if (reader.NodeType == XmlNodeType.Element && reader.Name.Equals("sublanguage", StringComparison.OrdinalIgnoreCase)) { ReadSubLanguage(reader); } } } reader.Read(); } private void ReadSubLanguage(XmlReader reader) { // This is a nifty added on hack made specifically for HTML. // Normally the style config elements are quite managable as there // are typically less than 10 when you don't count common styles. // // However HTML uses 9 different Sub languages that combined make // use of all 128 styles (well there are some small gaps). In order // to make this more managable I did added a SubLanguage element that // basically just prepends the Language's name and "." to the Style // Name definition. // // So for example if you had the following // <Styles> // <SubLanguage Name="ASP JavaScript"> // <Style Name="Keyword" Bold="True" /> // </SubLanguage> // </Styles> // That style's name will get interpreted as "ASP JavaScript.Keyword". // which if you look at the html.txt in LexerStyleNames you'll see it // maps to Style # 62 string subLanguageName = string.Empty; if (reader.HasAttributes) { while (reader.MoveToNextAttribute()) if (reader.Name.ToLower() == "name") subLanguageName = reader.Value; reader.MoveToElement(); } if (!reader.IsEmptyElement) { while (!(reader.NodeType == XmlNodeType.EndElement && reader.Name.Equals("sublanguage", StringComparison.OrdinalIgnoreCase))) { reader.Read(); if (reader.NodeType == XmlNodeType.Element && reader.Name.Equals("style", StringComparison.OrdinalIgnoreCase)) { StyleConfig sc = getStyleConfigFromElement(reader); sc.Name = subLanguageName + "." + sc.Name; _styles.Add(sc); } } } reader.Read(); } private void ReadUndoRedo(XmlReader reader) { if (reader.HasAttributes) { while (reader.MoveToNextAttribute()) if (reader.Name.ToLower() == "isundoenabled") _undoRedoIsUndoEnabled = getBool(reader.Value); reader.MoveToElement(); } reader.Skip(); } private void ReadWhitespace(XmlReader reader) { if (reader.HasAttributes) { while (reader.MoveToNextAttribute()) { string attrName = reader.Name.ToLower(); switch (attrName) { case "backcolor": _whitespace_BackColor = getColor(reader.Value); break; case "forecolor": _whitespace_ForeColor = getColor(reader.Value); break; case "mode": _whitespace_Mode = (WhitespaceMode)Enum.Parse(typeof(WhitespaceMode), reader.Value, true); break; } } } reader.Skip(); } #endregion Methods #region Properties public bool? AutoComplete_AutoHide { get { return _autoComplete_AutoHide; } set { _autoComplete_AutoHide = value; } } public bool? AutoComplete_AutomaticLengthEntered { get { return _autoComplete_AutomaticLengthEntered; } set { _autoComplete_AutomaticLengthEntered = value; } } public bool? AutoComplete_CancelAtStart { get { return _autoComplete_cancelAtStart; } set { _autoComplete_cancelAtStart = value; } } public bool? AutoComplete_DropRestOfWord { get { return _autoComplete_DropRestOfWord; } set { _autoComplete_DropRestOfWord = value; } } public string AutoComplete_FillUpCharacters { get { return _autoComplete_fillUpCharacters; } set { _autoComplete_fillUpCharacters = value; } } public char? AutoComplete_ImageSeperator { get { return _autoComplete_ImageSeperator; } set { _autoComplete_ImageSeperator = value; } } public bool? AutoComplete_IsCaseSensitive { get { return _autoComplete_IsCaseSensitive; } set { _autoComplete_IsCaseSensitive = value; } } public string AutoComplete_List { get { return _autoComplete_List; } set { _autoComplete_List = value; } } public bool? AutoComplete_ListInherits { get { return _autoComplete_ListInherit; } set { _autoComplete_ListInherit = value; } } public char? AutoComplete_ListSeperator { get { return _autoComplete_ListSeperator; } set { _autoComplete_ListSeperator = value; } } public int? AutoComplete_MaxHeight { get { return _autoComplete_MaxHeight; } set { _autoComplete_MaxHeight = value; } } public int? AutoComplete_MaxWidth { get { return _autoComplete_MaxWidth; } set { _autoComplete_MaxWidth = value; } } public bool? AutoComplete_SingleLineAccept { get { return _autoComplete_singleLineAccept; } set { _autoComplete_singleLineAccept = value; } } public string AutoComplete_StopCharacters { get { return _autoComplete_StopCharacters; } set { _autoComplete_StopCharacters = value; } } public Color CallTip_BackColor { get { return _callTip_BackColor; } set { _callTip_BackColor = value; } } public Color CallTip_ForeColor { get { return _callTip_ForeColor; } set { _callTip_ForeColor = value; } } public Color CallTip_HighlightTextColor { get { return _callTip_HighlightTextColor; } set { _callTip_HighlightTextColor = value; } } public int? Caret_BlinkRate { get { return _caret_BlinkRate; } set { _caret_BlinkRate = value; } } public Color Caret_Color { get { return _caret_Color; } set { _caret_Color = value; } } public int? Caret_CurrentLineBackgroundAlpha { get { return _caret_CurrentLineBackgroundAlpha; } set { _caret_CurrentLineBackgroundAlpha = value; } } public Color Caret_CurrentLineBackgroundColor { get { return _caret_CurrentLineBackgroundColor; } set { _caret_CurrentLineBackgroundColor = value; } } public bool? Caret_HighlightCurrentLine { get { return _caret_HighlightCurrentLine; } set { _caret_HighlightCurrentLine = value; } } public bool? Caret_IsSticky { get { return _caret_IsSticky; } set { _caret_IsSticky = value; } } public CaretStyle? Caret_Style { get { return _caret_Style; } set { _caret_Style = value; } } public int? Caret_Width { get { return _caret_Width; } set { _caret_Width = value; } } public bool? Clipboard_ConvertLineBreaksOnPaste { get { return _clipboard_ConvertLineBreaksOnPaste; } set { _clipboard_ConvertLineBreaksOnPaste = value; } } public CommandBindingConfigList Commands_KeyBindingList { get { return _commands_KeyBindingList; } set { _commands_KeyBindingList = value; } } public string DropMarkers_SharedStackName { get { return _dropMarkers_SharedStackName; } set { _dropMarkers_SharedStackName = value; } } public bool? EndOfLine_IsVisisble { get { return _endOfLine_IsVisisble; } set { _endOfLine_IsVisisble = value; } } public EndOfLineMode? EndOfLine_Mode { get { return _endOfLine_Mode; } set { _endOfLine_Mode = value; } } public FoldFlag? Folding_Flags { get { return _folding_Flags; } set { _folding_Flags = value; } } public bool? Folding_IsEnabled { get { return _folding_IsEnabled; } set { _folding_IsEnabled = value; } } public FoldMarkerScheme? Folding_MarkerScheme { get { return _folding_MarkerScheme; } set { _folding_MarkerScheme = value; } } public bool? Folding_UseCompactFolding { get { return _folding_UseCompactFolding; } set { _folding_UseCompactFolding = value; } } public bool HasData { get { return _hasData; } set { _hasData = value; } } public Color Hotspot_ActiveBackColor { get { return _hotspot_ActiveBackColor; } set { _hotspot_ActiveBackColor = value; } } public Color Hotspot_ActiveForeColor { get { return _hotspot_ActiveForeColor; } set { _hotspot_ActiveForeColor = value; } } public bool? Hotspot_ActiveUnderline { get { return _hotspot_ActiveUnderline; } set { _hotspot_ActiveUnderline = value; } } public bool? Hotspot_SingleLine { get { return _hotspot_SingleLine; } set { _hotspot_SingleLine = value; } } public bool? Hotspot_UseActiveBackColor { get { return _hotspot_UseActiveBackColor; } set { _hotspot_UseActiveBackColor = value; } } public bool? Hotspot_UseActiveForeColor { get { return _hotspot_UseActiveForeColor; } set { _hotspot_UseActiveForeColor = value; } } public bool? Indentation_BackspaceUnindents { get { return _indentation_BackspaceUnindents; } set { _indentation_BackspaceUnindents = value; } } public int? Indentation_IndentWidth { get { return _indentation_IndentWidth; } set { _indentation_IndentWidth = value; } } public bool? Indentation_ShowGuides { get { return _indentation_ShowGuides; } set { _indentation_ShowGuides = value; } } public SmartIndent? Indentation_SmartIndentType { get { return _indentation_SmartIndentType; } set { _indentation_SmartIndentType = value; } } public bool? Indentation_TabIndents { get { return _indentation_TabIndents; } set { _indentation_TabIndents = value; } } public int? Indentation_TabWidth { get { return _indentation_TabWidth; } set { _indentation_TabWidth = value; } } public bool? Indentation_UseTabs { get { return _indentation_UseTabs; } set { _indentation_UseTabs = value; } } public IndicatorConfigList Indicator_List { get { return _indicator_List; } set { _indicator_List = value; } } public string Language { get { return _language; } set { _language = value; } } public KeyWordConfigList Lexing_Keywords { get { return _lexing_Keywords; } set { _lexing_Keywords = value; } } public string Lexing_Language { get { return _lexing_Language; } set { _lexing_Language = value; } } public string Lexing_LineCommentPrefix { get { return _lexing_LineCommentPrefix; } set { _lexing_LineCommentPrefix = value; } } public LexerPropertiesConfig Lexing_Properties { get { return _lexing_Properties; } set { _lexing_Properties = value; } } public string Lexing_StreamCommentPrefix { get { return _lexing_StreamCommentPrefix; } set { _lexing_StreamCommentPrefix = value; } } public string Lexing_StreamCommentSuffix { get { return _lexing_StreamCommentSuffix; } set { _lexing_StreamCommentSuffix = value; } } public string Lexing_WhitespaceChars { get { return _lexing_WhitespaceChars; } set { _lexing_WhitespaceChars = value; } } public string Lexing_WordChars { get { return _lexing_WordChars; } set { _lexing_WordChars = value; } } public LineWrappingIndentMode? LineWrapping_IndentMode { get { return _lineWrapping_IndentMode; } set { _lineWrapping_IndentMode = value; } } public int? LineWrapping_IndentSize { get { return _lineWrapping_IndentSize; } set { _lineWrapping_IndentSize = value; } } public LineWrappingMode? LineWrapping_Mode { get { return _lineWrapping_Mode; } set { _lineWrapping_Mode = value; } } public LineWrappingVisualFlags? LineWrapping_VisualFlags { get { return _lineWrapping_VisualFlags; } set { _lineWrapping_VisualFlags = value; } } public LineWrappingVisualFlagsLocations? LineWrapping_VisualFlagsLocations { get { return _lineWrapping_VisualFlagsLocations; } set { _lineWrapping_VisualFlagsLocations = value; } } public Color LongLines_EdgeColor { get { return _longLines_EdgeColor; } set { _longLines_EdgeColor = value; } } public int? LongLines_EdgeColumn { get { return _longLines_EdgeColumn; } set { _longLines_EdgeColumn = value; } } public EdgeMode? LongLines_EdgeMode { get { return _longLines_EdgeMode; } set { _longLines_EdgeMode = value; } } public MarginConfigList Margin_List { get { return _margin_List; } set { _margin_List = value; } } public MarkersConfigList Markers_List { get { return _markers_List; } set { _markers_List = value; } } public bool? Scrolling_EndAtLastLine { get { return _scrolling_EndAtLastLine; } set { _scrolling_EndAtLastLine = value; } } public int? Scrolling_HorizontalWidth { get { return _scrolling_HorizontalWidth; } set { _scrolling_HorizontalWidth = value; } } public ScrollBars? Scrolling_ScrollBars { get { return _scrolling_ScrollBars; } set { _scrolling_ScrollBars = value; } } public int? Scrolling_XOffset { get { return _scrolling_XOffset; } set { _scrolling_XOffset = value; } } public Color Selection_BackColor { get { return _selection_BackColor; } set { _selection_BackColor = value; } } public Color Selection_BackColorUnfocused { get { return _selection_BackColorUnfocused; } set { _selection_BackColorUnfocused = value; } } public Color Selection_ForeColor { get { return _selection_ForeColor; } set { _selection_ForeColor = value; } } public Color Selection_ForeColorUnfocused { get { return _selection_ForeColorUnfocused; } set { _selection_ForeColorUnfocused = value; } } public bool? Selection_Hidden { get { return _selection_Hidden; } set { _selection_Hidden = value; } } public bool? Selection_HideSelection { get { return _selection_HideSelection; } set { _selection_HideSelection = value; } } public SelectionMode? Selection_Mode { get { return _selection_Mode; } set { _selection_Mode = value; } } public SnippetsConfigList SnippetsConfigList { get { return _snippetsConfigList; } set { _snippetsConfigList = value; } } public StyleConfigList Styles { get { return _styles; } set { _styles = value; } } public bool? UndoRedoIsUndoEnabled { get { return _undoRedoIsUndoEnabled; } set { _undoRedoIsUndoEnabled = value; } } public Color Whitespace_BackColor { get { return _whitespace_BackColor; } set { _whitespace_BackColor = value; } } public Color Whitespace_ForeColor { get { return _whitespace_ForeColor; } set { _whitespace_ForeColor = value; } } public WhitespaceMode? Whitespace_Mode { get { return _whitespace_Mode; } set { _whitespace_Mode = value; } } #endregion Properties #region Constructors public Configuration(string language) { _language = language; } public Configuration(XmlDocument configDocument, string language) { _language = language; Load(configDocument); } public Configuration(TextReader txtReader, string language) { _language = language; Load(txtReader); } public Configuration(XmlReader reader, string language) { _language = language; Load(reader); } public Configuration(string fileName, string language, bool useXmlReader) { _language = language; Load(fileName, useXmlReader); } public Configuration(Stream inStream, string language, bool useXmlReader) { _language = language; Load(inStream, useXmlReader); } #endregion Constructors } }
{ "content_hash": "bb4d69801f3c28cb0b9524887f391086", "timestamp": "", "source": "github", "line_count": 3132, "max_line_length": 201, "avg_line_length": 34.23403575989783, "alnum_prop": 0.43897184320235777, "repo_name": "NekoProject/NekoKun", "id": "592d53ee0fe9f9d8f2b78ec3790ae722d11695d0", "size": "107247", "binary": false, "copies": "3", "ref": "refs/heads/master", "path": "ScintillaNET/Configuration/Configuration.cs", "mode": "33188", "license": "bsd-3-clause", "language": [ { "name": "C#", "bytes": "2796879" }, { "name": "Shell", "bytes": "1023" } ], "symlink_target": "" }
// // RKPropertyInspector.h // RestKit // // Created by Blake Watters on 3/4/10. // Copyright (c) 2009-2012 RestKit. All rights reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // #import <Foundation/Foundation.h> @class NSEntityDescription; /** * The object used to store attributes for each property; used as the value in the class dictionary. */ @interface RKPropertyInspectorPropertyInfo : NSObject /** Creates a new RKPropertyInspectorPropertyInfo instance with the given information */ + (id)propertyInfoWithName:(NSString *)name keyValueClass:(Class)kvClass isPrimitive:(BOOL)isPrimitive; /** The name of the property */ @property (nonatomic, copy, readonly) NSString *name; /** The class used for key-value coding access to the property. If the property is an object type, then the class set for this key will be the type of the property. If the property is a primitive, then the class set for the key will be the boxed type used for KVC access to the property. For example, an `NSInteger` property is boxed to an `NSNumber` for KVC purposes. */ @property (nonatomic, strong, readonly) Class keyValueCodingClass; /** A BOOL value that indicates if the property is a primitive (non-object) value. */ @property (nonatomic, readonly) BOOL isPrimitive; @end /** The `RKPropertyInspector` class provides an interface for introspecting the properties and attributes of classes using the reflection capabilities of the Objective-C runtime. Once inspected, the properties inspection details are cached. */ @interface RKPropertyInspector : NSObject ///----------------------------------------------- /// @name Retrieving the Shared Inspector Instance ///----------------------------------------------- /** Returns the shared property inspector singleton instance. @return The shared `RKPropertyInspector` instance. */ + (RKPropertyInspector *)sharedInspector; ///------------------------------------------------------ /// @name Retrieving the Properties and Types for a Class ///------------------------------------------------------ /** Returns a dictionary keyed by property name that includes the key-value coding class of the property and a Boolean indicating if the property is backed by a primitive (non-object) value. The RKPropertyInspectorPropertyInfo object for each property includes details about the key-value coding class representing the property and if the property is backed by a primitive type. @param objectClass The class to inspect the properties of. @return A dictionary keyed by property name that includes details about all declared properties of the class. */ - (NSDictionary *)propertyInspectionForClass:(Class)objectClass; /** Returns the `Class` object specifying the type of the property with given name on a class. @param propertyName The name of the property to retrieve the type of. @param objectClass The class to retrieve the property from. @param isPrimitive A pointer to a Boolean value to set indicating if the specified property is of a primitive (non-object) type. @return A `Class` object specifying the type of the requested property. */ - (Class)classForPropertyNamed:(NSString *)propertyName ofClass:(Class)objectClass isPrimitive:(BOOL *)isPrimitive; @end ///---------------------------- /// @name Convenience Functions ///---------------------------- /** Returns the class of the attribute or relationship property at the key path of the given object. Given a key path to a string property, this will return an `NSString`, etc. @param keyPath The key path to the property to retrieve the class of. @param object The object to evaluate. @return The class of the property at the given key path. */ Class RKPropertyInspectorGetClassForPropertyAtKeyPathOfObject(NSString *keyPath, id object); /** Returns a Boolean value indicating if the property at the specified key path for a given object is modeled by a primitive type. @param keyPath The key path to inspect the property of. @param object The object to evaluate. @return `YES` if the property is a primitive, else `NO`. */ BOOL RKPropertyInspectorIsPropertyAtKeyPathOfObjectPrimitive(NSString *keyPath, id object);
{ "content_hash": "819f3f05a23491ecc1ae774726506032", "timestamp": "", "source": "github", "line_count": 117, "max_line_length": 375, "avg_line_length": 40.23076923076923, "alnum_prop": 0.7248778415126408, "repo_name": "sixoverground/sync-ios", "id": "ba28926dc60cd07cdfca273b5de2b89cebc10d2c", "size": "4707", "binary": false, "copies": "10", "ref": "refs/heads/master", "path": "Pods/RestKit/Code/ObjectMapping/RKPropertyInspector.h", "mode": "33188", "license": "mit", "language": [ { "name": "Objective-C", "bytes": "46820" }, { "name": "Ruby", "bytes": "83" } ], "symlink_target": "" }
namespace SeudoBuild.Pipeline.Modules.UnityBuild { /// <inheritdoc /> /// <summary> /// Configuration values for a build pipeline step that executes an arbitrary /// static method in a Unity editor script. /// </summary> public class UnityExecuteMethodBuildConfig : UnityBuildConfig { public override string Name { get; } = "Unity Execute Method"; /// <summary> /// A static method in the UnityEditor namespace matching this name will be executed. /// </summary> public string MethodName { get; } = ""; } }
{ "content_hash": "b26b53ea4ebb281ab7536d937189bead", "timestamp": "", "source": "github", "line_count": 17, "max_line_length": 93, "avg_line_length": 34.1764705882353, "alnum_prop": 0.6385542168674698, "repo_name": "mstevenson/SeudoBuild", "id": "817ad1713561af046f258735f0dc8b8a763e16da", "size": "583", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "SeudoBuild.Modules/SeudoBuild.Modules.UnityBuild.Shared/UnityExecuteMethodBuildConfig.cs", "mode": "33188", "license": "mit", "language": [ { "name": "C#", "bytes": "246511" } ], "symlink_target": "" }
<?php $language_data = array ( 'LANG_NAME' => 'QML', 'COMMENT_SINGLE' => array(1 => '//'), 'COMMENT_MULTI' => array('/*' => '*/'), 'COMMENT_REGEXP' => array( // comments 2 => "/(?<=[\\s^])(s|tr|y)\\/(?!\*)(?!\s)(?:\\\\.|(?!\n)[^\\/\\\\])+(?<!\s)\\/(?!\s)(?:\\\\.|(?!\n)[^\\/\\\\])*(?<!\s)\\/[msixpogcde]*(?=[\\s$\\.\\;])|(?<=[\\s^(=])(m|q[qrwx]?)?\\/(?!\*)(?!\s)(?:\\\\.|(?!\n)[^\\/\\\\])+(?<!\s)\\/[msixpogc]*(?=[\\s$\\.\\,\\;\\)])/iU", // property binding 3 => "/([a-z][\\w\\.]+)(?=:)/", // TODO: property name (fixed length lookbehind assertion?) 4 => "/(?<=property\\s+\\w+\\s+)(\\w+)/" ), 'CASE_KEYWORDS' => GESHI_CAPS_NO_CHANGE, 'QUOTEMARKS' => array("'", '"'), 'ESCAPE_CHAR' => '\\', 'KEYWORDS' => array( 1 => array( 'as','break','case','catch','continue','const','debugger', 'default','delete','do','else','finally','for','function', 'if','import','in','instanceof','new','on','public','property', 'readonly','return','signal','switch','this','throw','try', 'typeof','while','with' ), 2 => array( 'action','bool','color','date','double','enumeration','font', 'int','list','matrix4x4','point','quaternion','real','rect', 'size','string','time','url','var','variant','vector2d', 'vector3d','vector4d','void' ), // http://qt-project.org/doc/qt-5/qtbluetooth-qmlmodule.html 3 => array( 'BluetoothDiscoveryModel','BluetoothService','BluetoothSocket' ), // http://qt-project.org/doc/qt-5/qtgraphicaleffects-qmlmodule.html 4 => array( 'Blend','BrightnessContrast','ColorOverlay','Colorize', 'ConicalGradient','Desaturate','DirectionalBlur','Displace', 'DropShadow','FastBlur','GammaAdjust','GaussianBlur','Glow', 'HueSaturation','InnerShadow','LevelAdjust','LinearGradient', 'MaskedBlur','OpacityMask','RadialBlur','RadialGradient', 'RectangularGlow','RecursiveBlur','ThresholdMask','ZoomBlur' ), // http://qt-project.org/doc/qt-5/qtaudioengine-qmlmodule.html 5 => array( 'AttenuationModelLinear','AttenuationModelInverse','AudioCategory', 'AudioEngine','AudioListener','AudioSample','PlayVariation', 'Sound','SoundInstance' ), // http://qt-project.org/doc/qt-5/qtmultimedia-qmlmodule.html 6 => array( 'Video','Audio','MediaPlayer','Camera','CameraCapture', 'CameraExposure','CameraFlash','CameraFocus','CameraImageProcessing', 'CameraRecorder','Radio','RadioData','Torch','SoundEffect','VideoOutput' ), // http://qt-project.org/doc/qt-5/qtnfc-qmlmodule.html 7 => array( 'NdefFilter','NdefMimeRecord','NdefTextRecord','NdefUriRecord', 'NearField','NdefRecord' ), // http://qt-project.org/doc/qt-5/qtpositioning-qmlmodule.html 8 => array( 'QtPositioning','CoordinateAnimation','Position','PositionSource', 'Address','Location' ), // http://qt-project.org/doc/qt-5/qtqml-models-qmlmodule.html 9 => array( 'DelegateModel','DelegateModelGroup','ListModel','ListElement','ObjectModel' ), // http://qt-project.org/doc/qt-5/qtqml-qmlmodule.html 10 => array( 'Binding','Component','Connections','Date','Instantiator', 'Locale','Number','Qt','QtObject','String','Timer' ), // http://qt-project.org/doc/qt-5/qt-labs-folderlistmodel-qmlmodule.html 11 => array( 'FolderListModel' ), // http://qt-project.org/doc/qt-5/qtquick-localstorage-qmlmodule.html 12 => array( 'openDatabaseSync' ), // http://qt-project.org/doc/qt-5/qt-labs-settings-qmlmodule.html 13 => array( 'Settings' ), // http://qt-project.org/doc/qt-5/qtquick-window-qmlmodule.html 14 => array( 'Screen','Window','CloseEvent' ), // http://qt-project.org/doc/qt-5/qtquick-xmllistmodel-qmlmodule.html 15 => array( 'XmlRole','XmlListModel' ), // http://qt-project.org/doc/qt-5/qtquick-particles-qmlmodule.html 16 => array( 'Age','AngleDirection','CumulativeDirection','CustomParticle', 'Direction','EllipseShape','Friction','Gravity','GroupGoal', 'ImageParticle','ItemParticle','LineShape','MaskShape','Affector', 'Emitter','Shape','ParticleGroup','ParticlePainter','ParticleSystem', 'Attractor','PointDirection','RectangleShape','SpriteGoal', 'TargetDirection','TrailEmitter','Turbulence','Particle','Wander' ), // http://qt-project.org/doc/qt-5/qttest-qmlmodule.html 17 => array( 'SignalSpy','TestCase' ), // http://qt-project.org/doc/qt-5/qtquick-qmltypereference.html 18 => array( 'Item','Rectangle','Image','BorderImage','AnimatedImage','AnimatedSprite', 'SpriteSequence','Text','Accessible','Gradient','GradientStop','SystemPalette', 'Sprite','FontLoader','Repeater','Loader','Visual Item Transformations','Transform', 'Scale','Rotation','Translate','MouseArea','Keys','KeyNavigation','FocusScope', 'Flickable','PinchArea','MultiPointTouchArea','Drag','DropArea','TextInput', 'TextEdit','IntValidator','DoubleValidator','RegExpValidator','TouchPoint', 'PinchEvent','WheelEvent','MouseEvent','KeyEvent','DragEvent','Positioner', 'Column','Row','Grid','Flow','LayoutMirroring','State','PropertyChanges', 'StateGroup','StateChangeScript','ParentChange','AnchorChanges','Transition', 'ViewTransition','SequentialAnimation','ParallelAnimation','Behavior','PropertyAction', 'PauseAnimation','SmoothedAnimation','SpringAnimation','ScriptAction','PropertyAnimation', 'NumberAnimation','Vector3dAnimation','ColorAnimation','RotationAnimation','ParentAnimation', 'AnchorAnimation','PathAnimation','XAnimator','YAnimator','ScaleAnimator','RotationAnimator', 'OpacityAnimator','UniformAnimator','Lower-level Animation Types','PathInterpolator', 'AnimationController','Path','PathLine','PathQuad','PathCubic','PathArc','PathCurve', 'PathSvg','PathAttribute','PathPercent','VisualItemModel','VisualDataModel','VisualDataGroup', 'ListView','GridView','PathView','Package','Flipable','ShaderEffect','ShaderEffectSource', 'GridMesh','WorkerScript','Canvas','Context2D','CanvasGradient','CanvasPixelArray', 'CanvasImageData','TextMetrics', ), // http://qt-project.org/doc/qt-5/qtquick-controls-qmlmodule.html 19 => array( 'ApplicationWindow','BusyIndicator','Button','Calendar', 'CheckBox','ComboBox','GroupBox','Label','Menu','MenuBar', 'ProgressBar','RadioButton','ScrollView','Slider','SpinBox', 'SplitView','StackView','StackViewDelegate','StatusBar', 'Switch','Tab','TabView','TableView','TableViewColumn', 'TextArea','TextField','ToolBar','ToolButton','Action', 'ExclusiveGroup','MenuSeparator','MenuItem','Stack' ), // http://qt-project.org/doc/qt-5/qtquick-dialogs-qmlmodule.html 20 => array( 'Dialog','ColorDialog','FileDialog','FontDialog','MessageDialog' ), // http://qt-project.org/doc/qt-5/qtquick-layouts-qmlmodule.html 21 => array( 'Layout','RowLayout','ColumnLayout','GridLayout' ), // http://qt-project.org/doc/qt-5/qtsensors-qmlmodule.html 22 => array( 'Accelerometer','AccelerometerReading','Altimeter','AltimeterReading', 'AmbientLightReading','AmbientLightSensor','AmbientTemperatureReading', 'AmbientTemperatureSensor','Compass','CompassReading','Gyroscope', 'GyroscopeReading','HolsterReading','HolsterSensor','IRProximityReading', 'IRProximitySensor','LightReading','LightSensor','Magnetometer', 'MagnetometerReading','OrientationReading','OrientationSensor', 'PressureReading','PressureSensor','ProximityReading','ProximitySensor', 'RotationReading','RotationSensor','SensorGesture','SensorGlobal', 'SensorReading','TapReading','TapSensor','TiltReading','TiltSensor' ), // http://qt-project.org/doc/qt-5/qtwinextras-qmlmodule.html 23 => array( 'JumpListDestination','JumpListLink','JumpListSeparator','DwmFeatures', 'JumpList','JumpListCategory','TaskbarButton','ThumbnailToolBar','ThumbnailToolButton' ), // http://qt-project.org/doc/qt-5/qtwebkit-qmlmodule.html 24 => array( 'WebView','WebLoadRequest' ) ), 'SYMBOLS' => array( '(', ')', '[', ']', '{', '}', '+', '-', '*', '/', '%', '!', '@', '&', '|', '^', '<', '>', '=', ',', ';', '?', ':' ), 'CASE_SENSITIVE' => array( GESHI_COMMENTS => false, 1 => true, 2 => true, 3 => true, 4 => true, 5 => true, 6 => true, 7 => true, 8 => true, 9 => true, 10 => true, 11 => true, 12 => true, 13 => true, 14 => true, 15 => true, 16 => true, 17 => true, 18 => true, 19 => true, 20 => true, 21 => true, 22 => true, 23 => true, 24 => true ), 'STYLES' => array( 'KEYWORDS' => array( 1 => 'color: #808041;', 2 => 'color: #808041;', 3 => 'color: #800780;', 4 => 'color: #800780;', 5 => 'color: #800780;', 6 => 'color: #800780;', 7 => 'color: #800780;', 8 => 'color: #800780;', 9 => 'color: #800780;', 10 => 'color: #800780;', 11 => 'color: #800780;', 12 => 'color: #800780;', 13 => 'color: #800780;', 14 => 'color: #800780;', 15 => 'color: #800780;', 16 => 'color: #800780;', 17 => 'color: #800780;', 18 => 'color: #800780;', 19 => 'color: #800780;', 20 => 'color: #800780;', 21 => 'color: #800780;', 22 => 'color: #800780;', 23 => 'color: #800780;', 24 => 'color: #800780;' ), 'COMMENTS' => array( 1 => 'color: #008025;', 2 => 'color: #008025;', 3 => 'color: #970009;', 4 => 'color: #970009;', 'MULTI' => 'color: #008025;' ), 'ESCAPE_CHAR' => array( 0 => 'color: #000099; font-weight: bold;' ), 'BRACKETS' => array( 0 => 'color: #000000;' ), 'STRINGS' => array( 0 => 'color: #008025;' ), 'NUMBERS' => array( 0 => 'color: #000000;' ), 'METHODS' => array( 1 => 'color: #000000;' ), 'SYMBOLS' => array( 0 => 'color: #000000;' ), 'REGEXPS' => array( ), 'SCRIPT' => array( 0 => '', 1 => '', 2 => '', 3 => '' ) ), 'URLS' => array( 1 => '', 2 => '', 3 => 'http://qt-project.org/doc/qt-5/qml-qtbluetooth-{FNAMEL}.html', 4 => 'http://qt-project.org/doc/qt-5/qml-qtgraphicaleffects-{FNAMEL}.html', 5 => 'http://qt-project.org/doc/qt-5/qml-qtaudioengine-{FNAMEL}.html', 6 => 'http://qt-project.org/doc/qt-5/qml-qtmultimedia-{FNAMEL}.html', 7 => 'http://qt-project.org/doc/qt-5/qml-qtnfc-{FNAMEL}.html', 8 => 'http://qt-project.org/doc/qt-5/qml-qtpositioning-{FNAMEL}.html', 9 => 'http://qt-project.org/doc/qt-5/qml-qtqml-models-{FNAMEL}.html', 10 => 'http://qt-project.org/doc/qt-5/qml-qtqml-{FNAMEL}.html', 11 => 'http://qt-project.org/doc/qt-5/qml-qt-labs-folderlistmodel-{FNAMEL}.html', 12 => 'http://qt-project.org/doc/qt-5/qtquick-localstorage-qmlmodule.html', 13 => 'http://qt-project.org/doc/qt-5/qml-qt-labs-settings-{FNAMEL}.html', 14 => 'http://qt-project.org/doc/qt-5/qml-qtquick-window-{FNAMEL}.html', 15 => 'http://qt-project.org/doc/qt-5/qml-qtquick-xmllistmodel-{FNAMEL}.html', 16 => 'http://qt-project.org/doc/qt-5/qml-qtquick-particles-{FNAMEL}.html', 17 => 'http://qt-project.org/doc/qt-5/qml-qttest-{FNAMEL}.html', 18 => 'http://qt-project.org/doc/qt-5/qml-qtquick-{FNAMEL}.html', 19 => 'http://qt-project.org/doc/qt-5/qml-qtquick-controls-{FNAMEL}.html', 20 => 'http://qt-project.org/doc/qt-5/qml-qtquick-dialogs-{FNAMEL}.html', 21 => 'http://qt-project.org/doc/qt-5/qml-qtquick-layouts-{FNAMEL}.html', 22 => 'http://qt-project.org/doc/qt-5/qml-qtsensors-{FNAMEL}.html', 23 => 'http://qt-project.org/doc/qt-5/qml-qtwinextras-{FNAMEL}.html', 24 => 'http://qt-project.org/doc/qt-5/qml-qtwebkit-{FNAMEL}.html' ), 'OOLANG' => true, 'OBJECT_SPLITTERS' => array( 1 => '.' ), 'REGEXPS' => array( ), 'STRICT_MODE_APPLIES' => GESHI_MAYBE, 'SCRIPT_DELIMITERS' => array( 0 => array( '<script type="text/javascript">' => '</script>' ), 1 => array( '<script language="javascript">' => '</script>' ) ), 'HIGHLIGHT_STRICT_BLOCK' => array( 0 => true, 1 => true ) );
{ "content_hash": "c52faa394eea6efae30d2dc0dea17f11", "timestamp": "", "source": "github", "line_count": 312, "max_line_length": 275, "avg_line_length": 45.10897435897436, "alnum_prop": 0.5241580218843257, "repo_name": "pcon/sticky-notes-quickstart", "id": "1805f341bcc03cfc332bb8ef82e558084d30621f", "size": "15564", "binary": false, "copies": "33", "ref": "refs/heads/master", "path": "vendor/geshi/geshi/qml.php", "mode": "33261", "license": "bsd-2-clause", "language": [ { "name": "CSS", "bytes": "1577" }, { "name": "JavaScript", "bytes": "15049" }, { "name": "PHP", "bytes": "897290" }, { "name": "Shell", "bytes": "142041" } ], "symlink_target": "" }
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <!-- NewPage --> <html lang="en"> <head> <!-- Generated by javadoc (1.8.0_60) on Mon Jan 11 17:03:19 CST 2016 --> <title>com.metova.cappuccino Class Hierarchy (cappuccino 0.2.0 API)</title> <meta name="date" content="2016-01-11"> <link rel="stylesheet" type="text/css" href="../../../stylesheet.css" title="Style"> <script type="text/javascript" src="../../../script.js"></script> </head> <body> <script type="text/javascript"><!-- try { if (location.href.indexOf('is-external=true') == -1) { parent.document.title="com.metova.cappuccino Class Hierarchy (cappuccino 0.2.0 API)"; } } catch(err) { } //--> </script> <noscript> <div>JavaScript is disabled on your browser.</div> </noscript> <!-- ========= START OF TOP NAVBAR ======= --> <div class="topNav"><a name="navbar.top"> <!-- --> </a> <div class="skipNav"><a href="#skip.navbar.top" title="Skip navigation links">Skip navigation links</a></div> <a name="navbar.top.firstrow"> <!-- --> </a> <ul class="navList" title="Navigation"> <li><a href="../../../com/metova/cappuccino/package-summary.html">Package</a></li> <li>Class</li> <li class="navBarCell1Rev">Tree</li> <li><a href="../../../deprecated-list.html">Deprecated</a></li> <li><a href="../../../index-all.html">Index</a></li> <li><a href="../../../help-doc.html">Help</a></li> </ul> </div> <div class="subNav"> <ul class="navList"> <li>Prev</li> <li>Next</li> </ul> <ul class="navList"> <li><a href="../../../index.html?com/metova/cappuccino/package-tree.html" target="_top">Frames</a></li> <li><a href="package-tree.html" target="_top">No&nbsp;Frames</a></li> </ul> <ul class="navList" id="allclasses_navbar_top"> <li><a href="../../../allclasses-noframe.html">All&nbsp;Classes</a></li> </ul> <div> <script type="text/javascript"><!-- allClassesLink = document.getElementById("allclasses_navbar_top"); if(window==top) { allClassesLink.style.display = "block"; } else { allClassesLink.style.display = "none"; } //--> </script> </div> <a name="skip.navbar.top"> <!-- --> </a></div> <!-- ========= END OF TOP NAVBAR ========= --> <div class="header"> <h1 class="title">Hierarchy For Package com.metova.cappuccino</h1> </div> <div class="contentContainer"> <h2 title="Class Hierarchy">Class Hierarchy</h2> <ul> <li type="circle">java.lang.Object <ul> <li type="circle">com.metova.cappuccino.<a href="../../../com/metova/cappuccino/Cappuccino.html" title="class in com.metova.cappuccino"><span class="typeNameLink">Cappuccino</span></a></li> <li type="circle">com.metova.cappuccino.<a href="../../../com/metova/cappuccino/CappuccinoIdlingResource.html" title="class in com.metova.cappuccino"><span class="typeNameLink">CappuccinoIdlingResource</span></a></li> <li type="circle">com.metova.cappuccino.<a href="../../../com/metova/cappuccino/NoOpCappuccinoResourceWatcher.html" title="class in com.metova.cappuccino"><span class="typeNameLink">NoOpCappuccinoResourceWatcher</span></a> (implements com.metova.cappuccino.<a href="../../../com/metova/cappuccino/CappuccinoResourceWatcher.html" title="interface in com.metova.cappuccino">CappuccinoResourceWatcher</a>)</li> <li type="circle">com.metova.cappuccino.<a href="../../../com/metova/cappuccino/OperatingCappuccinoResourceWatcher.html" title="class in com.metova.cappuccino"><span class="typeNameLink">OperatingCappuccinoResourceWatcher</span></a> (implements com.metova.cappuccino.<a href="../../../com/metova/cappuccino/CappuccinoResourceWatcher.html" title="interface in com.metova.cappuccino">CappuccinoResourceWatcher</a>)</li> <li type="circle">java.lang.Throwable (implements java.io.Serializable) <ul> <li type="circle">java.lang.Exception <ul> <li type="circle">java.lang.RuntimeException <ul> <li type="circle">com.metova.cappuccino.<a href="../../../com/metova/cappuccino/CappuccinoException.html" title="class in com.metova.cappuccino"><span class="typeNameLink">CappuccinoException</span></a></li> </ul> </li> </ul> </li> </ul> </li> </ul> </li> </ul> <h2 title="Interface Hierarchy">Interface Hierarchy</h2> <ul> <li type="circle">com.metova.cappuccino.<a href="../../../com/metova/cappuccino/CappuccinoResourceWatcher.html" title="interface in com.metova.cappuccino"><span class="typeNameLink">CappuccinoResourceWatcher</span></a></li> </ul> </div> <!-- ======= START OF BOTTOM NAVBAR ====== --> <div class="bottomNav"><a name="navbar.bottom"> <!-- --> </a> <div class="skipNav"><a href="#skip.navbar.bottom" title="Skip navigation links">Skip navigation links</a></div> <a name="navbar.bottom.firstrow"> <!-- --> </a> <ul class="navList" title="Navigation"> <li><a href="../../../com/metova/cappuccino/package-summary.html">Package</a></li> <li>Class</li> <li class="navBarCell1Rev">Tree</li> <li><a href="../../../deprecated-list.html">Deprecated</a></li> <li><a href="../../../index-all.html">Index</a></li> <li><a href="../../../help-doc.html">Help</a></li> </ul> </div> <div class="subNav"> <ul class="navList"> <li>Prev</li> <li>Next</li> </ul> <ul class="navList"> <li><a href="../../../index.html?com/metova/cappuccino/package-tree.html" target="_top">Frames</a></li> <li><a href="package-tree.html" target="_top">No&nbsp;Frames</a></li> </ul> <ul class="navList" id="allclasses_navbar_bottom"> <li><a href="../../../allclasses-noframe.html">All&nbsp;Classes</a></li> </ul> <div> <script type="text/javascript"><!-- allClassesLink = document.getElementById("allclasses_navbar_bottom"); if(window==top) { allClassesLink.style.display = "block"; } else { allClassesLink.style.display = "none"; } //--> </script> </div> <a name="skip.navbar.bottom"> <!-- --> </a></div> <!-- ======== END OF BOTTOM NAVBAR ======= --> </body> </html>
{ "content_hash": "bbe767345be0448cd6ad5cbb3812bca9", "timestamp": "", "source": "github", "line_count": 149, "max_line_length": 417, "avg_line_length": 39.013422818791945, "alnum_prop": 0.661792533975572, "repo_name": "metova/Cappuccino", "id": "940cdd7b003cdebd084bc017957496ad30b14317", "size": "5813", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "javadoc/com/metova/cappuccino/package-tree.html", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Groovy", "bytes": "6028" }, { "name": "Java", "bytes": "40002" } ], "symlink_target": "" }
cask "displaperture" do version "2.1,1052" sha256 :no_check url "https://manytricks.com/download/displaperture" name "Displaperture" desc "Rounds your display corners" homepage "https://manytricks.com/displaperture/" livecheck do url "https://manytricks.com/displaperture/appcast/" strategy :sparkle end app "Displaperture.app" uninstall quit: "com.manytricks.Displaperture" zap trash: [ "~/Library/Caches/com.manytricks.Displaperture", "~/Library/Containers/com.manytricks.Displaperture", "~/Library/Preferences/com.manytricks.Displaperture.plist", ] end
{ "content_hash": "77078b8c41f95cd6c385a02f3b6da937", "timestamp": "", "source": "github", "line_count": 24, "max_line_length": 63, "avg_line_length": 25.208333333333332, "alnum_prop": 0.7289256198347107, "repo_name": "malob/homebrew-cask", "id": "93b88ce8af37a6518698d893846283ca5d073d58", "size": "605", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "Casks/displaperture.rb", "mode": "33188", "license": "bsd-2-clause", "language": [ { "name": "Dockerfile", "bytes": "249" }, { "name": "Python", "bytes": "3630" }, { "name": "Ruby", "bytes": "2864635" }, { "name": "Shell", "bytes": "32035" } ], "symlink_target": "" }
<h2>Profile</h2> <div id="videoGameProfile" data-ng-controller="ProfileController"> <div class="row-fluid"> <div id="psnProfile" class="span6 videoGameProfile"> <h3>PlayStation Network</h3> <div class="profileDetails"> <div class="pic"><img src="Content/images/psnPic.png" alt="strivinglife" /></div> <div class="profileBasics"> <div class="name">{{psnProfile.Id}}</div> <div>Level: {{psnProfile.Level}} <span class="percent">({{psnProfile.LevelProgress}}%)</span></div> <div>Points: {{psnProfile.Points}} / {{psnProfile.NextLevelPoints}}</div> <div class="psnTrophies"> Trophies: {{psnProfile.Trophies}} <div>Bronze: {{psnProfile.TrophiesBronze}}</div> <div>Silver: {{psnProfile.TrophiesSilver}}</div> <div>Gold: {{psnProfile.TrophiesGold}}</div> <div>Platinum: {{psnProfile.TrophiesPlatinum}}</div> </div> <div> <div>Total games: {{psnProfile.TotalGames}}</div> </div> </div> <div class="pointCompares"> <h4>PlayStation Network Trophies</h4> <div>Points: {{psnProfile.Points}} of {{psnProfile.PossiblePoints}} <span class="percent" data-ng-class="percentClass(psnPointsPercent)">({{psnPointsPercent | number:3}}%)</span></div> <div style="margin-left:2em;"> {{quantityToPercent(psnProfile.Points, psnProfile.PossiblePoints, psnPointsGoal1, "psnPoints")}}<br /> {{quantityToPercent(psnProfile.Points, psnProfile.PossiblePoints, psnPointsGoal2)}}<br /> </div> <div class="psnTrophies"> Trophies: {{psnProfile.Trophies}} of {{psnProfile.PossibleTrophies}} <span class="percent" data-ng-class="percentClass(psnTrophiesPercent)">({{psnTrophiesPercent | number:3}}%)</span> <div style="margin-left:2em;"> {{quantityToPercent(psnProfile.Trophies, psnProfile.PossibleTrophies, psnTrophiesGoal1)}}<br /> {{quantityToPercent(psnProfile.Trophies, psnProfile.PossibleTrophies, psnTrophiesGoal2)}}<br /> </div> <div>Bronze: {{psnProfile.TrophiesBronze}} of {{psnProfile.PossibleTrophiesBronze}} <span class="percent" data-ng-class="percentClass(psnTrophiesBronzePercent)">({{psnTrophiesBronzePercent | number:3}}%)</span></div> <div>Silver: {{psnProfile.TrophiesSilver}} of {{psnProfile.PossibleTrophiesSilver}} <span class="percent" data-ng-class="percentClass(psnTrophiesSilverPercent)">({{psnTrophiesSilverPercent | number:3}}%)</span></div> <div>Gold: {{psnProfile.TrophiesGold}} of {{psnProfile.PossibleTrophiesGold}} <span class="percent" data-ng-class="percentClass(psnTrophiesGoldPercent)">({{psnTrophiesGoldPercent | number:3}}%)</span></div> <div>Platinum: {{psnProfile.TrophiesPlatinum}} of {{psnProfile.PossibleTrophiesPlatinum}} <span class="percent" data-ng-class="percentClass(psnTrophiesPlatinumPercent)">({{psnTrophiesPlatinumPercent | number:3}}%)</span></div> </div> </div> </div> <!--<p><a class="btn" href="#">View details &raquo;</a></p>--> </div> <div id="xblProfile" class="span6 videoGameProfile"> <h3>Xbox Live</h3> <div class="profileDetails"> <div class="pic"><img src="Content/images/xblPic.png" alt="strivinglife" /></div> <div class="profileBasics"> <div class="name">{{xblProfile.Id}}</div> <div>Gamerscore: {{xblProfile.GamerScore}}</div> <div>Achievements: {{xblProfile.Achievements}}</div> <div> <div>Total games: {{xblProfile.TotalGames}}</div> </div> </div> <div class="pointCompares"> <h4>Xbox Live Achievements</h4> <div>Gamerscore: {{xblProfile.GamerScore}} of {{xblProfile.PossibleGamerScore}} <span class="percent" data-ng-class="percentClass(xblPointsPercent)">({{xblPointsPercent | number:3}}%)</span></div> <div style="margin-left:2em;"> {{quantityToPercent(xblProfile.GamerScore, xblProfile.PossibleGamerScore, xblGamerscoreGoal1)}}<br /> {{quantityToPercent(xblProfile.GamerScore, xblProfile.PossibleGamerScore, xblGamerscoreGoal2)}}<br /> </div> <div>Achievements: {{xblProfile.Achievements}} of {{xblProfile.PossibleAchievements}} <span class="percent" data-ng-class="percentClass(xblAchievementsPercent)">({{xblAchievementsPercent | number:3}}%)</span></div> <div style="margin-left:2em;"> {{quantityToPercent(xblProfile.Achievements, xblProfile.PossibleAchievements, xblAchievementsGoal1)}}<br /> {{quantityToPercent(xblProfile.Achievements, xblProfile.PossibleAchievements, xblAchievementsGoal2)}}<br /> </div> </div> </div> <!--<p><a class="btn" href="#">View details &raquo;</a></p>--> </div> </div> </div>
{ "content_hash": "f76fbfd383aa8ce952839766a947d2b6", "timestamp": "", "source": "github", "line_count": 74, "max_line_length": 232, "avg_line_length": 61.932432432432435, "alnum_prop": 0.6895046912502727, "repo_name": "JamesSkemp/VideoGamesSpa", "id": "f0aac7e6766ce1f4f96fbc4471d4f4405c62ada9", "size": "4585", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "SimpleWebsite/app/partials/profile.html", "mode": "33188", "license": "mit", "language": [ { "name": "C#", "bytes": "90485" }, { "name": "CSS", "bytes": "3972" }, { "name": "JavaScript", "bytes": "34454" } ], "symlink_target": "" }
from lib import * #from keras.layers.merge import Concatenate from keras.layers import Merge import copy from collections import Counter from sklearn.metrics import confusion_matrix from sklearn.metrics import f1_score import math word2topic = pickle.load(open("word2topic", "r")) embedding = pickle.load(open("word2topic", "r")) #embedding = pickle.load(open("embedding", "r")) vocab = word2topic.keys() max_words = 25#30 depth_embed = 100#370 depth_distance = 100#368#70#100 flag = 1 ##def getEmbedding_word2vec(sentence, model): # # global max_words, depth, no_features, train_length ## model = model[0] # list = np.array([]) # for word in sentence: # if word in model.wv.vocab: # list = np.append(list, model.wv[word]) # # #print list.size # if(list.size > depth*max_words): # list = list[0:depth*max_words] # #print sentence # pad = np.zeros(depth*max_words - list.size) # list = np.append(list, pad) # #print list.shape # return list def get_topic_rep(topic, word2topic, word2vec): global vocab topics = str(topic).split(' ') v = np.zeros(np.vstack(([word2topic['donald']], [word2vec.wv['donald']])).shape) counter = 0 # if topics[0] in vocab: # v = np.append(v, word#2topic[topics[0]]) ## counter = 0 ## if for counter in range(len(topics)): if topics[counter] in vocab: # print topics[counter] try: v += np.vstack(([word2topic[topics[counter]]], [word2vec.wv[topics[counter]]])) except: v += np.vstack(([word2topic[topics[counter]]], [np.zeros(word2vec.wv['donald'].shape)])) # print counter + 1 v /= (counter + 1) * 1.0 # print type(v) return v def custom_loss(y_true, y_pred): y = K.argmax(y_true, axis=1) print y[0:5] ## y_true = np.array(y_true).astype('int64') ## print y_true[0:5] ## length = y_true.get_shape() ## l = tuple([length[i].value for i in range(0, len(length))])[0] # for i in range(y_pred.get_shape()[0].value): # y_pred[i] = y_pred[i][y[i]] # # y_pred = K.log(y_pred[:, K.constant(y, dtype='int64')]) return K.mean(K.categorical_crossentropy(y_pred[np.where(K.eval(K.equal(y, 0)))[0], :], y_true[np.where(K.eval(K.equal(y, 0)))[0], :]), K.categorical_crossentropy(y_pred[np.where(K.eval(K.equal(y, 1)))[0], :], y_true[np.where(K.eval(K.equal(y, 1)))[0], :]), K.categorical_crossentropy(y_pred[np.where(K.eval(K.equal(y, 2)))[0], :], y_true[np.where(K.eval(K.equal(y, 2)))[0], :])) # return K.sum(K.mean(K.dot(K.equal(y, 0), y_pred)), K.mean(K.dot(K.equal(y, 1), y_pred)), K.mean(K.dot(K.equal(y, 2), y_pred))) def evaluate(y_test, thresholded_pred): print "accuracy", (sum(abs(y_test == thresholded_pred))) / float(len(thresholded_pred)) print Counter(y_test) print Counter(thresholded_pred) print confusion_matrix(y_test, thresholded_pred) print "f1 is", f1_score(y_test, thresholded_pred, average='macro') def distance_embed(sentence): global max_words, depth_distance, word2topic list = np.array([]) for word in sentence: if word in vocab: list = np.append(list, word2topic[word]) #print list.size if(list.size > max_words * depth_distance): list = list[0:max_words * depth_distance] #print sentence pad = np.zeros(max_words * depth_distance - list.size) list = np.append(list, pad) #print list.shape return list def getEmbedding(sentence, word2topic, word2vec): global max_words, depth_embed, embedding, flag#, depth_distance list = np.array([]) for word in sentence: if word in vocab: try: if flag: list = np.vstack(([word2topic[word]], [word2vec.wv[word]])) flag = 0 else: list = np.append(list, np.vstack(([word2topic[word]], [word2vec.wv[word]]))) except: list = np.append(list, np.vstack(([word2topic[word]], [np.zeros(word2vec.wv['donald'].shape)]))) # try: # list = np.append(list, model[word]) ## print "found", word # except: # list = np.append(list, np.zeros(model['donald'].shape)) # print word #print list.size if(list.shape[1] > max_words * depth_embed): list = list[:, 0:max_words * depth_embed] #print sentence pad = np.zeros((2, max_words * depth_embed - list.shape[1])) list = np.concatenate((list, pad), axis=1) #print list.shape return list #def getPOS(sentence): # # global max_words#, depth # all_tags = CMUTweetTagger.runtagger_parse(sentence) # list = np.array([]) # for i in range(len(sentence)): # if sentence[i] in vocab: # list = np.append(list, all_tags[i]) # # #print list.size # if(list.size > max_words): # list = list[0:max_words] # #print sentence # pad = np.zeros(max_words - list.size) # list = np.append(list, pad) # #print list.shape # return list #def getEmbedding(sentence): # global word2topic, vocab # max_words = 30 # list = []#np.array([]) # for word in sentence: # if word in vocab: ## list = np.append(list, word2topic[word]) # list.append(word2topic[word]) ## list = np.array(list) # #print list.size # if(len(list) > max_words): # list = list[0:max_words] # #print sentence # pad = [0] * 100# * (max_words - len(list))#np.zeros(max_words - list.size) # for i in range((max_words - len(list))): # list.append(pad) ## list.append(pad) # #print list.shape # return list #getEmbedding(df['tokenized_sents'][0]) def run_model(): global tech, politics, sports, music, genre, max_words, depth_embed, depth_distance, word2topic, vocab, K # with K.tf.device('/gpu:1'): gpu_options = K.tf.GPUOptions(per_process_gpu_memory_fraction=1.0)#0.8)#0.2) sess = K.tf.Session(config=K.tf.ConfigProto(gpu_options=gpu_options)) # all_topics = np.concatenate((tech, politics, music, sports)) # print "AAAAAAAAAAAAAAAAAAAAA" # print len(all_topics) # print all_topics try: [X, y, df, d] = pickle.load(open("data_rnn", "r")) print d # df = df[df["topic"].isin(all_topics)] except: #filename = "Homework2_data.csv" # word2topic = pickle.load(open("word2topic", "r")) [df, df0, df3] = readData(filename1, filename2) #df = df[df["topic"].isin(all_topics)] df['sentiment'] = pd.to_numeric(df['sentiment'])#, errors='coerce') # df = df.dropna(subset=['sentiment']) # topics_array = np.array(([tech, politics, music, sports])) # print genre # for index, row in df.iterrows(): # tweet_topic = row['topic'] # # print "tweet_topic", tweet_topic # for i in range(len(topics_array)): # if tweet_topic in topics_array[i]: # # print "ta", topics_array[i] # # df["topic"][index] = genre[i] # df.ix[index, 'topic'] = genre[i] # # print "df", df["topic"][index] # break # Remove topics of no interest print "length of df is", len(df) # print "from joined data\n", Counter(list(df["user_id"])).most_common(50) indices = [] # df['tweet'] = df['tweet'].apply(cleanhtml).apply(cleanUrl).apply(removeMention).apply(removeTrailingHash); # df['tweet'] = df['tweet'].apply(cleanhtml).apply(cleanUrl).apply(removeTrailingHash); df['tweet'] = df['tweet'].apply(cleanhtml).apply(cleanUrl)#.apply(removeTrailingHash); df['tweet'] = tokenize_and_stopwords(df['tweet']) # df = df.sample(frac=1).reset_index(drop=True) # df = shuffle(df) print df.size df['tokenized_sents'] = df.apply(lambda row: nltk.word_tokenize(row['tweet']), axis=1) try: word2vec = wv.Word2Vec.load("word2vec") #model.similarity("this", "is") # model.init_sims(replace=True) print "loaded" except: word2vec = wv.Word2Vec(df["tokenized_sents"], size=depth_embed, window=5, min_count=5, workers=4) word2vec.save("word2vec") #X.shape[0]#7349 df['embedding'] = df['tokenized_sents'].apply(getEmbedding, args=(word2topic, word2vec,)) # df['word2vec'] = df['tokenized_sents'].apply(getEmbedding, args=(word2vec.wv,)) X = list(df['embedding']) # X_w = list(df['word2vec']) X = np.reshape(np.ravel(X), (len(X), max_words, 2, depth_embed)) # X_w = np.reshape(np.ravel(X_w), (len(X_w), max_words, depth_embed)) # a = copy.deepcopy(X)#np.array(df['embedding']) df['tweet_rep'] = df['tokenized_sents'].apply(distance_embed) #### a = list(df['tweet_rep']) #### a = np.reshape(np.ravel(a), (len(a), max_words, depth_distance)) df['topic_rep'] = df['topic'].apply(get_topic_rep, args=(word2topic, word2vec,)) d = [] # a = np.reshape(a, ()) #### b = list(df['topic_rep']) #### print b[0] # print b # print b.shape #### b = np.reshape(np.ravel(np.ravel(b)), (X.shape[0], 1, depth_distance)) ##### c = (a - b)**2 ###### d = c ##### for i1 in range(len(c)): ##### for j1 in range(len(c[0])): ##### d.append(abs(sum(c[i1][j1]))) ##### d = np.array(d) ##### d = np.reshape(d, (len(a), max_words)) ##### d[d==0] = 0.1 ##### d = 1.0 / d ##### print "d[0] is !!!", d[0] # df['distance'] = d#1.0 / d#sum(sum(sum(abs(np.array(df['embedding']) - np.array(df['topic_rep']))))) # one_hot = # df['pos'] = df['tweet'].apply(getPOS) # X = np.column_stack((np.array(df['embedding']), np.array(df['pos']))) # for i in range(len(X)): # X[i] = X[i][0:] # B = np.array([]) # np.dstack((X, B)).shape # y = np.array(df['sentiment']) y = np.array(pd.get_dummies(df['sentiment'])) ### No dumping # try: # pickle.dump([X, y, df, d], open("data_rnn", "wb")) # except: # "dumping data failed" print len(X[0]) print len(X) X_train = X[0:12200] X_test = X[12200:] # X_train_w = X_w[0:12200] # X_test_w = X_w[12200:] X_train = np.concatenate((X_train, X_train_w), axis=1) y_train = y[0:12200] y_test = y[12200:] print " Y train!!\n", y_train[0:5] print list(df['sentiment'])[0:5] print y_test[0:5] one_hot = list(df['topic_rep'])#(pd.get_dummies(df['topic'])) one_hot = np.reshape(np.ravel(np.ravel(one_hot)), (len(one_hot), 1, 2, depth_distance)) ## LOAD MODEL try: model = load_model('modelc_rnn_new') except: # Word model model_word = Sequential() model_word.add(Bidirectional(LSTM(3 * max_words, activation='relu', return_sequences=True), input_shape=(max_words, 2, depth_embed))) model_word.add(Dropout(0.2)) model_word.add(Bidirectional(LSTM(2 * max_words, activation='relu', return_sequences=True))) model_word.add(Dropout(0.2)) model_word.add(Bidirectional(LSTM(max_words, activation='tanh', return_sequences=True))) model_word.add(Dropout(0.2)) # model_word_w = Sequential() # model_word_w.add(Bidirectional(LSTM(3 * max_words, activation='relu', return_sequences=True), input_shape=(max_words, depth_embed))) # model_word_w.add(Dropout(0.2)) # model_word_w.add(Bidirectional(LSTM(2 * max_words, activation='relu', return_sequences=True), input_shape=(max_words, depth_embed))) # model_word_w.add(Dropout(0.2)) # model_word_w.add(Bidirectional(LSTM(max_words, activation='tanh', return_sequences=True))) # model_word_w.add(Dropout(0.2)) # model_word.add(Bidirectional(LSTM(max_words, return_sequences=True))) # model_word.add(Dropout(0.2)) # model_word.add(Flatten()) # model_word.add(MaxPooling2D(pool_size=(2, 1))) # model_word.add(Dropout(0.2)) # model_word.add(Dense((max_words), activation="tanh")) ## Reverse # model_word_r = Sequential() # model_word_r.add(LSTM(max_words, input_shape=(max_words, depth), consume_less='gpu', go_backwards=True)) # model_word_r.add(Dropout(0.2)) ## model_word_r.add(LSTM(max_words, input_shape=(max_words, depth), consume_less='gpu', go_backwards=True)) # Topic model print len(set(df['topic'])) print "set is", set(df['topic']) # print "topic rep!! \n", df['topic_rep'] # one_hot = list(df['topic_rep'])#(pd.get_dummies(df['topic'])) ## print df['topic'][0:5] print "init one hot", one_hot[0:2] # # one_hot = one_hot.as_matrix() # ## one_hot = d#df['distance'] # print len(one_hot) # # print len(one_hot[0]) # # print one_hot[0] ### one_hot = np.reshape(one_hot, (one_hot.shape[0], max_words, 1)) ## one_hot = np.reshape(np.ravel(np.ravel(one_hot)), (len(one_hot), depth_distance, 1)) # one_hot = np.reshape(np.ravel(np.ravel(one_hot)), (len(one_hot), 2, depth_distance)) # one_hot_train = one_hot[0:12200] # one_hot_test = one_hot[12200:] print "one hot shape", one_hot.shape model_topic = Sequential() # , return_sequences=True model_topic.add(Bidirectional(LSTM(max_words, activation='tanh', return_sequences=True), input_shape=(1, 2, depth_distance))) model_topic.add(Dropout(0.2)) # model_topic.add(Bidirectional(LSTM(max_words, return_sequences=True))) # model_topic.add(Flatten()) # model_topic.add(MaxPooling2D(pool_size=(2, 1))) # model_topic.add(Dropout(0.2)) # model_topic.add(Dense(4, activation="tanh")) # model_topic.add(Dropout(0.2)) # Merge forward and backward # merged = Merge([model_word_f, model_word_r], mode='concat')#, concat_axis=1) # model_word = Sequential() # model_word.add(merged) # model_word.add(Dropout(0.2)) ## model_word.add(MaxPooling2D(pool_size=(2, 1))) ## model_word.add(Dropout(0.2)) # model_word.add(LSTM(max_words, input_shape=(2*max_words, 1))) # model_word.add(Dropout(0.2)) # Merge merged and topic info # merged2 = Merge([model_word, model_word_w, model_topic], mode='concat', concat_axis=1) merged2 = Merge([model_word, model_topic], mode='concat', concat_axis=1) # merged = Concatenate([model_word, model_topic], axis=-1) model = Sequential() model.add(merged2) # model.add(Dropout(0.2)) # model.add(Bidirectional(LSTM(2*max_words, activation='relu', return_sequences=True)))#))) # model.add(Dropout(0.2)) model.add(Bidirectional(LSTM(max_words, activation='tanh', return_sequences=True))) ## # model.add(Flatten()) model.add(Dropout(0.2)) # model.add(Bidirectional(LSTM(max_words), input_shape=(4 + max_words, 1))) print "added additional Dense, no flatten" ## model.add(Dense(max_words, activation='tanh')) # model.add(Dropout(0.2)) #model.add(Dense(1, activation='linear', W_constraint=maxnorm(3))) # model.add(Bidirectional(LSTM(2*max_words, activation='tanh', return_sequences=True)))#))) # model.add(Dropout(0.2)) # model.add(Bidirectional(LSTM(max_words, activation='tanh', return_sequences=True)))#))) # model.add(Dropout(0.2)) model.add(LSTM(3, activation="softmax")) # model.add(LSTM(1, activation="linear")) # optimizer = RMSprop(lr=0.01) # model.compile(loss='categorical_crossentropy', optimizer=optimizer) adam = Adam(lr=0.0005, beta_1=0.9, beta_2=0.999, epsilon=1e-08) model.compile(loss='categorical_crossentropy', optimizer=adam) print "Custom!!!" # model.compile(loss=custom_loss, optimizer=adam) print "came here saaaaar!!!!!!\n\n" # print X[0:5] # print Y_train[0:5] print "model changedd !!!" model.fit([X_train, one_hot_train], y_train, batch_size=64, epochs=50, validation_split=0.05, callbacks=[history]) model_json = model.to_json() with open("modelc_rnn_new.json", "w") as json_file: json_file.write(model_json) model.save_weights("modelc_rnn_new.h5") print("Saved model to disk") # print(history.History) return [model, X, X_w, y, df, d, one_hot] # print X.shape # print X[0] # print X[0] # for i in X[0]: # print i def load_model(filename): json_file = open(filename+ '.json', 'r') loaded_model_json = json_file.read() json_file.close() model = model_from_json(loaded_model_json) # load weights into new model model.load_weights(filename + ".h5") # [X, y, df, d] = pickle.load(open("data_rnn", "r")) return model#, X, y, df, d] def duplicate_model(filename): global tech, politics, sports, music, genre, max_words, depth, word2topic, vocab, K print "Duplicating!!" # Word model model_word = Sequential() model_word.add(Bidirectional(LSTM(max_words, return_sequences=True), input_shape=(max_words, depth))) model_word.add(Dropout(0.2)) # model_word.add(Flatten()) # model_word.add(MaxPooling2D(pool_size=(2, 1))) # model_word.add(Dropout(0.2)) model_topic = Sequential() model_topic.add(Bidirectional(LSTM(max_words, return_sequences=True), input_shape=(max_words, 1))) model_topic.add(Dropout(0.2)) # model_topic.add(Flatten()) # model_topic.add(MaxPooling2D(pool_size=(2, 1))) # model_topic.add(Dropout(0.2)) merged2 = Merge([model_word, model_topic], mode='concat') model = Sequential() model.add(merged2) model.add(Dropout(0.2)) model.add(Bidirectional(LSTM(max_words, return_sequences=True))) model.add(Dropout(0.2)) model.add(LSTM(max_words)) # model.add(Flatten()) model.add(Dropout(0.2)) # merged = Concatenate([model_word, model_topic], axis=-1) model = Sequential() model.add(merged2) model.add(Dropout(0.2)) model.add(LSTM(max_words)) # model.add(Dropout(0.2)) # print "added additional Dense, no flatten" # model.add(Dense(1, activation='linear', W_constraint=maxnorm(5))) json_file = open(filename+ '.json', 'r') loaded_model_json = json_file.read() json_file.close() model_true = model_from_json(loaded_model_json) # load weights into new model model_true.load_weights(filename + ".h5") model.layers[0].set_weights(model_true.layers[0].get_weights()) model.layers[1].set_weights(model_true.layers[1].get_weights()) model.layers[2].set_weights(model_true.layers[2].get_weights()) model.layers[3].set_weights(model_true.layers[3].get_weights()) try: model.layers[3].set_weights(model_true.layers[3].get_weights()) # model.layers[3].set_weights(model_true.layers[3].get_weights()) print "tried" except: print "excepted" # model.add(Dropout(0.2)) # model.layers[3].set_weights(model_true.layers[3].get_weights()) return model #equal weighted categorical cross entropy def sentiment_classifier(): global max_words, depth_distance, depth_embed print "in senti class, changes, class\n\n" try: assert False print "in try\n\n" [model, X, y, df, d] = load_model('modelc_rnn_new') print "Data found" print "done" except Exception, e: print "Caught an exception\n\n" print "Error is", str(e), "\n\n" [model, X, X_w, y, df, d, one_hot] = run_model() print "length of X is", len(X) X_test = X[12200:] y_test = y[12200:] X_test_w = X_w[12200:] X_train_w = X_w[0:12200] X_train = X[0:12200] y_train = y[0:12200] topics = list(df['topic']) # ____________________________________________________________________________________________________________HERE_________________ # one_hot = d#df['distance'] # one_hot = pd.get_dummies(df['topic']) # one_hot = one_hot.as_matrix() # print len(set(df['topic'])) # print "set is", set(df['topic']) # print len(one_hot) # print len(one_hot[0]) # print one_hot[0] ## print len(all_topics) ## print all_topics # print set(df["topic"]) # one_hot = np.array(df['topic_rep'])#np.array(pd.get_dummies(df['topic'])) # one_hot = np.reshape(one_hot, (X.shape[0], 1, depth_distance)) one_hot_train = one_hot[0:12200] one_hot_test = one_hot[12200:] pred = model.predict([X_test, X_test_w, one_hot_test], batch_size = 64)#, Y_train, batch_size=32, verbose=1, sample_weight=None) print pred[0:5] print y_test[0:5] # pred[:, 0] *= 1.5 # margin = 0.06 # indexes = pred[:, 0] + margin >= pred[:, 1] # print indexes # pred[indexes, 0] = pred[indexes, 1] + 0.01 # print pred[0:5] ##### print "This is the prediction" ###### y[y >= 0.1] = 1 ###### y[y < 0.1] = 0 ##### pred.shape = (pred.shape[0],) ##### print pred[0:20] ##### print "true labels" ##### print y_test[0:20] ###### print sum(sum(y == Y_train)) ###### print (len(X_train) * len(X_train[0])) ##### print (sum(abs(y_test - pred))) / float(len(pred)) ##### thresh1 = 1.5#49#1.8#1.5 ##### thresh2 = 3.9 ##### thresholded_pred = copy.deepcopy(pred) ##### thresholded_pred[(pred > (-thresh1 + 0.0)) & (pred < thresh2)] = 0 ##### thresholded_pred[(pred >= thresh1) & (pred < thresh2)] = 3#1 ##### thresholded_pred[pred >= thresh2] = 5#2 ##### thresholded_pred[(pred > -thresh2) & (pred <= (-thresh1 + 0.0))] = -3#1 ##### thresholded_pred[pred <= -thresh2] = -5#2 ##### thresholded_pred = thresholded_pred.astype('int8') ##### print "Testing" ##### evaluate(y_test, thresholded_pred) ##### ##### y_test[y_test > 0] = 1 ##### y_test[y_test < 0] = -1 ##### ##### thresholded_pred[thresholded_pred > 0] = 1 ##### thresholded_pred[thresholded_pred < 0] = -1 thresholded_pred = pred.argmax(axis=1) y_test = y_test.argmax(axis=1) evaluate(y_test, thresholded_pred) thresholded_pred[thresholded_pred<=1] = -1 thresholded_pred[thresholded_pred==2] = 0 thresholded_pred[thresholded_pred>2] = 1 y_test[y_test<=1] = -1 y_test[y_test==2] = 0 y_test[y_test>2] = 1 evaluate(y_test, thresholded_pred) pred = model.predict([X_train, X_train_w, one_hot_train], batch_size = 64)#, Y_train, batch_size=32, verbose=1, sample_weight=None) print pred[0:5] print y_train[0:5] #pred[:,0] *= 1.5 print "This is the prediction" #### y[y >= 0.1] = 1 #### y[y < 0.1] = 0 #### pred.shape = (pred.shape[0],) #### print pred[0:20] #### print "true labels" #### print y_train[0:20] ##### print sum(sum(y == Y_train)) ##### print (len(X_train) * len(X_train[0])) #### print (sum(abs(y_train - pred))) / float(len(pred)) #### thresh1 = 1.5 #### thresh2 = 3.9 #### thresholded_pred = copy.deepcopy(pred) #### thresholded_pred[(pred > (-thresh1 + 0.0)) & (pred < thresh2)] = 0 #### thresholded_pred[(pred >= thresh1) & (pred < thresh2)] = 3#1 #### thresholded_pred[pred >= thresh2] = 5#2 #### thresholded_pred[(pred > -thresh2) & (pred <= (-thresh1 + 0))] = -3#1 #### thresholded_pred[pred <= -thresh2] = -5#2 #### thresholded_pred = thresholded_pred.astype('int8') #### print "Training" #### evaluate(y_train, thresholded_pred) #### y_train[y_train > 0] = 1 #### y_train[y_train < 0] = -1 #### #### thresholded_pred[thresholded_pred > 0] = 1 #### thresholded_pred[thresholded_pred < 0] = -1 thresholded_pred = pred.argmax(axis=1) y_train = y_train.argmax(axis=1) evaluate(y_train, thresholded_pred) thresholded_pred[thresholded_pred<=1] = -1 thresholded_pred[thresholded_pred==2] = 0 thresholded_pred[thresholded_pred>2] = 1 y_train[y_train<=1] = -1 y_train[y_train==2] = 0 y_train[y_train>2] = 1 evaluate(y_train, thresholded_pred) # model_dup = duplicate_model('modelc_rnn_new') # layer_output = model_dup.predict([X_test, one_hot_test], batch_size = 64) # ### get_last_layer_output = K.function([model.layers[0].input], ### [model.layers[2].output]) ## get_last_layer_output = K.function([model.layers[0].input, K.learning_phase()], ## [model.layers[2].output]) ### output in train mode = 0 ### layer_output = np.array(get_last_layer_output([X_train[0:1200], 0])[0]) ## ### output in train mode = 0 ## ### X = [X_test, one_hot_test] ## print X_test.shape ## print one_hot_test.shape ## print len(X_test) ## print len(one_hot_test) ## ## ## X_2 = np.concatenate((X_test, one_hot_test), axis=2) ## start = 0 ## increment = 100 ## flag = 1 ## print len(X_test) ## print "now!!" ## while start+increment <= len(X_test): ### X = [[X_test[start:start+increment], 1], [one_hot_test[start:start+increment], 1]] ## if flag: ## layer_output = get_last_layer_output([X_2[start:start+increment], 0])[0]#get_last_layer_output([[X_test[start:start+increment], 0], [one_hot_test[:, start:start+increment], 0]])[0] ## flag = 0 ## else: ## layer_output = np.concatenate((layer_output, get_last_layer_output([X_2[start:start+increment], 0])[0])) ## start += increment ## if start != len(X_test): ### X = [X_test[start:start+increment], one_hot_test[start:start+increment]] ## layer_output = np.concatenate((layer_output, get_last_layer_output([X_2[start:start+increment], 0])[0])) # print "length of hidden", len(layer_output[0]) # for iter in range(10): # print df["tweet"][iter], layer_output[iter] sentiment_classifier()
{ "content_hash": "2b21ee35dc79e4d7a7d3b64e18264df7", "timestamp": "", "source": "github", "line_count": 700, "max_line_length": 383, "avg_line_length": 38.92285714285714, "alnum_prop": 0.5525214710416207, "repo_name": "ProjectsUCSC/NLP", "id": "cee880c71cad4665991f33a755343d2f613833bc", "size": "27246", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "User Modelling/rnn_class.py", "mode": "33188", "license": "mit", "language": [ { "name": "Jupyter Notebook", "bytes": "225665" }, { "name": "Python", "bytes": "258827" } ], "symlink_target": "" }
module Graphics.GL.SGIX.TagSampleBuffer ( -- * Extension Support glGetSGIXTagSampleBuffer, gl_SGIX_tag_sample_buffer, -- * Functions glTagSampleBufferSGIX ) where import Graphics.GL.ExtensionPredicates import Graphics.GL.Functions
{ "content_hash": "13bf3a421f1f87366d44cf61bdddf2e4", "timestamp": "", "source": "github", "line_count": 10, "max_line_length": 41, "avg_line_length": 24.2, "alnum_prop": 0.7892561983471075, "repo_name": "haskell-opengl/OpenGLRaw", "id": "2e50627af08d727b0db72fb8fcbcf3c59b72ac85", "size": "631", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/Graphics/GL/SGIX/TagSampleBuffer.hs", "mode": "33188", "license": "bsd-3-clause", "language": [ { "name": "C", "bytes": "3954" }, { "name": "Haskell", "bytes": "5504511" } ], "symlink_target": "" }
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <!--NewPage--> <HTML> <HEAD> <!-- Generated by javadoc (build 1.6.0_03) on Mon Nov 19 21:41:16 CET 2007 --> <TITLE> Uses of Interface org.springframework.beans.factory.xml.DocumentLoader (Spring Framework API 2.5) </TITLE> <META NAME="date" CONTENT="2007-11-19"> <LINK REL ="stylesheet" TYPE="text/css" HREF="../../../../../../stylesheet.css" TITLE="Style"> <SCRIPT type="text/javascript"> function windowTitle() { if (location.href.indexOf('is-external=true') == -1) { parent.document.title="Uses of Interface org.springframework.beans.factory.xml.DocumentLoader (Spring Framework API 2.5)"; } } </SCRIPT> <NOSCRIPT> </NOSCRIPT> </HEAD> <BODY BGCOLOR="white" onload="windowTitle();"> <HR> <!-- ========= START OF TOP NAVBAR ======= --> <A NAME="navbar_top"><!-- --></A> <A HREF="#skip-navbar_top" title="Skip navigation links"></A> <TABLE BORDER="0" WIDTH="100%" CELLPADDING="1" CELLSPACING="0" SUMMARY=""> <TR> <TD COLSPAN=2 BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A NAME="navbar_top_firstrow"><!-- --></A> <TABLE BORDER="0" CELLPADDING="0" CELLSPACING="3" SUMMARY=""> <TR ALIGN="center" VALIGN="top"> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../../overview-summary.html"><FONT CLASS="NavBarFont1"><B>Overview</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../package-summary.html"><FONT CLASS="NavBarFont1"><B>Package</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../../org/springframework/beans/factory/xml/DocumentLoader.html" title="interface in org.springframework.beans.factory.xml"><FONT CLASS="NavBarFont1"><B>Class</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#FFFFFF" CLASS="NavBarCell1Rev"> &nbsp;<FONT CLASS="NavBarFont1Rev"><B>Use</B></FONT>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../package-tree.html"><FONT CLASS="NavBarFont1"><B>Tree</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../../deprecated-list.html"><FONT CLASS="NavBarFont1"><B>Deprecated</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../../index-all.html"><FONT CLASS="NavBarFont1"><B>Index</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../../help-doc.html"><FONT CLASS="NavBarFont1"><B>Help</B></FONT></A>&nbsp;</TD> </TR> </TABLE> </TD> <TD ALIGN="right" VALIGN="top" ROWSPAN=3><EM> <a href="http://www.springframework.org/" target="_top">The Spring Framework</a></EM> </TD> </TR> <TR> <TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2"> &nbsp;PREV&nbsp; &nbsp;NEXT</FONT></TD> <TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2"> <A HREF="../../../../../../index.html?org/springframework/beans/factory/xml/\class-useDocumentLoader.html" target="_top"><B>FRAMES</B></A> &nbsp; &nbsp;<A HREF="DocumentLoader.html" target="_top"><B>NO FRAMES</B></A> &nbsp; &nbsp;<SCRIPT type="text/javascript"> <!-- if(window==top) { document.writeln('<A HREF="../../../../../../allclasses-noframe.html"><B>All Classes</B></A>'); } //--> </SCRIPT> <NOSCRIPT> <A HREF="../../../../../../allclasses-noframe.html"><B>All Classes</B></A> </NOSCRIPT> </FONT></TD> </TR> </TABLE> <A NAME="skip-navbar_top"></A> <!-- ========= END OF TOP NAVBAR ========= --> <HR> <CENTER> <H2> <B>Uses of Interface<br>org.springframework.beans.factory.xml.DocumentLoader</B></H2> </CENTER> <TABLE BORDER="1" WIDTH="100%" CELLPADDING="3" CELLSPACING="0" SUMMARY=""> <TR BGCOLOR="#CCCCFF" CLASS="TableHeadingColor"> <TH ALIGN="left" COLSPAN="2"><FONT SIZE="+2"> Packages that use <A HREF="../../../../../../org/springframework/beans/factory/xml/DocumentLoader.html" title="interface in org.springframework.beans.factory.xml">DocumentLoader</A></FONT></TH> </TR> <TR BGCOLOR="white" CLASS="TableRowColor"> <TD><A HREF="#org.springframework.beans.factory.xml"><B>org.springframework.beans.factory.xml</B></A></TD> <TD>Contains an abstract XML-based <code>BeanFactory</code> implementation, including a standard "spring-beans" DTD.&nbsp;</TD> </TR> </TABLE> &nbsp; <P> <A NAME="org.springframework.beans.factory.xml"><!-- --></A> <TABLE BORDER="1" WIDTH="100%" CELLPADDING="3" CELLSPACING="0" SUMMARY=""> <TR BGCOLOR="#CCCCFF" CLASS="TableHeadingColor"> <TH ALIGN="left" COLSPAN="2"><FONT SIZE="+2"> Uses of <A HREF="../../../../../../org/springframework/beans/factory/xml/DocumentLoader.html" title="interface in org.springframework.beans.factory.xml">DocumentLoader</A> in <A HREF="../../../../../../org/springframework/beans/factory/xml/package-summary.html">org.springframework.beans.factory.xml</A></FONT></TH> </TR> </TABLE> &nbsp; <P> <TABLE BORDER="1" WIDTH="100%" CELLPADDING="3" CELLSPACING="0" SUMMARY=""> <TR BGCOLOR="#CCCCFF" CLASS="TableSubHeadingColor"> <TH ALIGN="left" COLSPAN="2">Classes in <A HREF="../../../../../../org/springframework/beans/factory/xml/package-summary.html">org.springframework.beans.factory.xml</A> that implement <A HREF="../../../../../../org/springframework/beans/factory/xml/DocumentLoader.html" title="interface in org.springframework.beans.factory.xml">DocumentLoader</A></FONT></TH> </TR> <TR BGCOLOR="white" CLASS="TableRowColor"> <TD ALIGN="right" VALIGN="top" WIDTH="1%"><FONT SIZE="-1"> <CODE>&nbsp;class</CODE></FONT></TD> <TD><CODE><B><A HREF="../../../../../../org/springframework/beans/factory/xml/DefaultDocumentLoader.html" title="class in org.springframework.beans.factory.xml">DefaultDocumentLoader</A></B></CODE> <BR> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;The default <A HREF="../../../../../../org/springframework/beans/factory/xml/DocumentLoader.html" title="interface in org.springframework.beans.factory.xml"><CODE>DocumentLoader</CODE></A> implementation.</TD> </TR> </TABLE> &nbsp; <P> <TABLE BORDER="1" WIDTH="100%" CELLPADDING="3" CELLSPACING="0" SUMMARY=""> <TR BGCOLOR="#CCCCFF" CLASS="TableSubHeadingColor"> <TH ALIGN="left" COLSPAN="2">Methods in <A HREF="../../../../../../org/springframework/beans/factory/xml/package-summary.html">org.springframework.beans.factory.xml</A> with parameters of type <A HREF="../../../../../../org/springframework/beans/factory/xml/DocumentLoader.html" title="interface in org.springframework.beans.factory.xml">DocumentLoader</A></FONT></TH> </TR> <TR BGCOLOR="white" CLASS="TableRowColor"> <TD ALIGN="right" VALIGN="top" WIDTH="1%"><FONT SIZE="-1"> <CODE>&nbsp;void</CODE></FONT></TD> <TD><CODE><B>XmlBeanDefinitionReader.</B><B><A HREF="../../../../../../org/springframework/beans/factory/xml/XmlBeanDefinitionReader.html#setDocumentLoader(org.springframework.beans.factory.xml.DocumentLoader)">setDocumentLoader</A></B>(<A HREF="../../../../../../org/springframework/beans/factory/xml/DocumentLoader.html" title="interface in org.springframework.beans.factory.xml">DocumentLoader</A>&nbsp;documentLoader)</CODE> <BR> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;Specify the <A HREF="../../../../../../org/springframework/beans/factory/xml/DocumentLoader.html" title="interface in org.springframework.beans.factory.xml"><CODE>DocumentLoader</CODE></A> to use.</TD> </TR> </TABLE> &nbsp; <P> <HR> <!-- ======= START OF BOTTOM NAVBAR ====== --> <A NAME="navbar_bottom"><!-- --></A> <A HREF="#skip-navbar_bottom" title="Skip navigation links"></A> <TABLE BORDER="0" WIDTH="100%" CELLPADDING="1" CELLSPACING="0" SUMMARY=""> <TR> <TD COLSPAN=2 BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A NAME="navbar_bottom_firstrow"><!-- --></A> <TABLE BORDER="0" CELLPADDING="0" CELLSPACING="3" SUMMARY=""> <TR ALIGN="center" VALIGN="top"> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../../overview-summary.html"><FONT CLASS="NavBarFont1"><B>Overview</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../package-summary.html"><FONT CLASS="NavBarFont1"><B>Package</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../../org/springframework/beans/factory/xml/DocumentLoader.html" title="interface in org.springframework.beans.factory.xml"><FONT CLASS="NavBarFont1"><B>Class</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#FFFFFF" CLASS="NavBarCell1Rev"> &nbsp;<FONT CLASS="NavBarFont1Rev"><B>Use</B></FONT>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../package-tree.html"><FONT CLASS="NavBarFont1"><B>Tree</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../../deprecated-list.html"><FONT CLASS="NavBarFont1"><B>Deprecated</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../../index-all.html"><FONT CLASS="NavBarFont1"><B>Index</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../../help-doc.html"><FONT CLASS="NavBarFont1"><B>Help</B></FONT></A>&nbsp;</TD> </TR> </TABLE> </TD> <TD ALIGN="right" VALIGN="top" ROWSPAN=3><EM> <a href="http://www.springframework.org/" target="_top">The Spring Framework</a></EM> </TD> </TR> <TR> <TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2"> &nbsp;PREV&nbsp; &nbsp;NEXT</FONT></TD> <TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2"> <A HREF="../../../../../../index.html?org/springframework/beans/factory/xml/\class-useDocumentLoader.html" target="_top"><B>FRAMES</B></A> &nbsp; &nbsp;<A HREF="DocumentLoader.html" target="_top"><B>NO FRAMES</B></A> &nbsp; &nbsp;<SCRIPT type="text/javascript"> <!-- if(window==top) { document.writeln('<A HREF="../../../../../../allclasses-noframe.html"><B>All Classes</B></A>'); } //--> </SCRIPT> <NOSCRIPT> <A HREF="../../../../../../allclasses-noframe.html"><B>All Classes</B></A> </NOSCRIPT> </FONT></TD> </TR> </TABLE> <A NAME="skip-navbar_bottom"></A> <!-- ======== END OF BOTTOM NAVBAR ======= --> <HR> <i>Copyright &copy; 2002-2007 <a href=http://www.springframework.org/ target=_top>The Spring Framework</a>.</i> </BODY> </HTML>
{ "content_hash": "9cec3c67a43e718355be60e5c8decc4c", "timestamp": "", "source": "github", "line_count": 197, "max_line_length": 428, "avg_line_length": 51.3502538071066, "alnum_prop": 0.6511466982997232, "repo_name": "mattxia/spring-2.5-analysis", "id": "0f114b1cc49fb3d5d098b0c2d9ea4c231141886f", "size": "10116", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "docs/api/org/springframework/beans/factory/xml/class-use/DocumentLoader.html", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "AspectJ", "bytes": "18516" }, { "name": "CSS", "bytes": "20368" }, { "name": "Groovy", "bytes": "2361" }, { "name": "Java", "bytes": "16366293" }, { "name": "Ruby", "bytes": "623" }, { "name": "Shell", "bytes": "684" }, { "name": "XSLT", "bytes": "2674" } ], "symlink_target": "" }
using base::trace_event::TraceLog; namespace net { namespace { // TraceLog category for NetLog events. const char kNetLogTracingCategory[] = "netlog"; struct TraceEntryInfo { std::string category; std::string id; std::string phase; std::string name; std::string source_type; }; TraceEntryInfo GetTraceEntryInfoFromValue(const base::DictionaryValue& value) { TraceEntryInfo info; EXPECT_TRUE(value.GetString("cat", &info.category)); EXPECT_TRUE(value.GetString("id", &info.id)); EXPECT_TRUE(value.GetString("ph", &info.phase)); EXPECT_TRUE(value.GetString("name", &info.name)); EXPECT_TRUE(value.GetString("args.source_type", &info.source_type)); return info; } class TraceNetLogObserverTest : public testing::Test { public: TraceNetLogObserverTest() { TraceLog* tracelog = TraceLog::GetInstance(); DCHECK(tracelog); DCHECK(!tracelog->IsEnabled()); trace_buffer_.SetOutputCallback(json_output_.GetCallback()); trace_net_log_observer_.reset(new TraceNetLogObserver()); trace_events_.reset(new base::ListValue()); } ~TraceNetLogObserverTest() override { DCHECK(!TraceLog::GetInstance()->IsEnabled()); } void OnTraceDataCollected( base::RunLoop* run_loop, const scoped_refptr<base::RefCountedString>& events_str, bool has_more_events) { DCHECK(trace_events_->empty()); trace_buffer_.Start(); trace_buffer_.AddFragment(events_str->data()); trace_buffer_.Finish(); scoped_ptr<base::Value> trace_value; trace_value = base::JSONReader::Read( json_output_.json_output, base::JSON_PARSE_RFC | base::JSON_DETACHABLE_CHILDREN); ASSERT_TRUE(trace_value) << json_output_.json_output; base::ListValue* trace_events = NULL; ASSERT_TRUE(trace_value->GetAsList(&trace_events)); trace_events_ = FilterNetLogTraceEvents(*trace_events); if (!has_more_events) run_loop->Quit(); } static void EnableTraceLog() { TraceLog::GetInstance()->SetEnabled( base::trace_event::TraceConfig(kNetLogTracingCategory, ""), TraceLog::RECORDING_MODE); } void EndTraceAndFlush() { base::RunLoop run_loop; TraceLog::GetInstance()->SetDisabled(); TraceLog::GetInstance()->Flush( base::Bind(&TraceNetLogObserverTest::OnTraceDataCollected, base::Unretained(this), base::Unretained(&run_loop))); run_loop.Run(); } void set_trace_net_log_observer(TraceNetLogObserver* trace_net_log_observer) { trace_net_log_observer_.reset(trace_net_log_observer); } static scoped_ptr<base::ListValue> FilterNetLogTraceEvents( const base::ListValue& trace_events) { scoped_ptr<base::ListValue> filtered_trace_events(new base::ListValue()); for (size_t i = 0; i < trace_events.GetSize(); i++) { const base::DictionaryValue* dict = NULL; if (!trace_events.GetDictionary(i, &dict)) { ADD_FAILURE() << "Unexpected non-dictionary event in trace_events"; continue; } std::string category; if (!dict->GetString("cat", &category)) { ADD_FAILURE() << "Unexpected item without a category field in trace_events"; continue; } if (category != kNetLogTracingCategory) continue; filtered_trace_events->Append(dict->DeepCopy()); } return filtered_trace_events.Pass(); } base::ListValue* trace_events() const { return trace_events_.get(); } TestNetLog* net_log() { return &net_log_; } TraceNetLogObserver* trace_net_log_observer() const { return trace_net_log_observer_.get(); } private: scoped_ptr<base::ListValue> trace_events_; base::trace_event::TraceResultBuffer trace_buffer_; base::trace_event::TraceResultBuffer::SimpleOutput json_output_; TestNetLog net_log_; scoped_ptr<TraceNetLogObserver> trace_net_log_observer_; }; TEST_F(TraceNetLogObserverTest, TracingNotEnabled) { trace_net_log_observer()->WatchForTraceStart(net_log()); net_log()->AddGlobalEntry(NetLog::TYPE_REQUEST_ALIVE); EndTraceAndFlush(); trace_net_log_observer()->StopWatchForTraceStart(); EXPECT_EQ(0u, trace_events()->GetSize()); } TEST_F(TraceNetLogObserverTest, TraceEventCaptured) { TestNetLogEntry::List entries; net_log()->GetEntries(&entries); EXPECT_TRUE(entries.empty()); trace_net_log_observer()->WatchForTraceStart(net_log()); EnableTraceLog(); BoundNetLog bound_net_log = BoundNetLog::Make(net_log(), net::NetLog::SOURCE_NONE); net_log()->AddGlobalEntry(NetLog::TYPE_CANCELLED); bound_net_log.BeginEvent(NetLog::TYPE_URL_REQUEST_START_JOB); bound_net_log.EndEvent(NetLog::TYPE_REQUEST_ALIVE); net_log()->GetEntries(&entries); EXPECT_EQ(3u, entries.size()); EndTraceAndFlush(); trace_net_log_observer()->StopWatchForTraceStart(); EXPECT_EQ(3u, trace_events()->GetSize()); const base::DictionaryValue* item1 = NULL; ASSERT_TRUE(trace_events()->GetDictionary(0, &item1)); const base::DictionaryValue* item2 = NULL; ASSERT_TRUE(trace_events()->GetDictionary(1, &item2)); const base::DictionaryValue* item3 = NULL; ASSERT_TRUE(trace_events()->GetDictionary(2, &item3)); TraceEntryInfo actual_item1 = GetTraceEntryInfoFromValue(*item1); TraceEntryInfo actual_item2 = GetTraceEntryInfoFromValue(*item2); TraceEntryInfo actual_item3 = GetTraceEntryInfoFromValue(*item3); EXPECT_EQ(kNetLogTracingCategory, actual_item1.category); EXPECT_EQ(base::StringPrintf("0x%d", entries[0].source.id), actual_item1.id); EXPECT_EQ(std::string(1, TRACE_EVENT_PHASE_NESTABLE_ASYNC_INSTANT), actual_item1.phase); EXPECT_EQ(NetLog::EventTypeToString(NetLog::TYPE_CANCELLED), actual_item1.name); EXPECT_EQ(NetLog::SourceTypeToString(entries[0].source.type), actual_item1.source_type); EXPECT_EQ(kNetLogTracingCategory, actual_item2.category); EXPECT_EQ(base::StringPrintf("0x%d", entries[1].source.id), actual_item2.id); EXPECT_EQ(std::string(1, TRACE_EVENT_PHASE_NESTABLE_ASYNC_BEGIN), actual_item2.phase); EXPECT_EQ(NetLog::EventTypeToString(NetLog::TYPE_URL_REQUEST_START_JOB), actual_item2.name); EXPECT_EQ(NetLog::SourceTypeToString(entries[1].source.type), actual_item2.source_type); EXPECT_EQ(kNetLogTracingCategory, actual_item3.category); EXPECT_EQ(base::StringPrintf("0x%d", entries[2].source.id), actual_item3.id); EXPECT_EQ(std::string(1, TRACE_EVENT_PHASE_NESTABLE_ASYNC_END), actual_item3.phase); EXPECT_EQ(NetLog::EventTypeToString(NetLog::TYPE_REQUEST_ALIVE), actual_item3.name); EXPECT_EQ(NetLog::SourceTypeToString(entries[2].source.type), actual_item3.source_type); } TEST_F(TraceNetLogObserverTest, EnableAndDisableTracing) { trace_net_log_observer()->WatchForTraceStart(net_log()); EnableTraceLog(); net_log()->AddGlobalEntry(NetLog::TYPE_CANCELLED); TraceLog::GetInstance()->SetDisabled(); net_log()->AddGlobalEntry(NetLog::TYPE_REQUEST_ALIVE); EnableTraceLog(); net_log()->AddGlobalEntry(NetLog::TYPE_URL_REQUEST_START_JOB); EndTraceAndFlush(); trace_net_log_observer()->StopWatchForTraceStart(); TestNetLogEntry::List entries; net_log()->GetEntries(&entries); EXPECT_EQ(3u, entries.size()); EXPECT_EQ(2u, trace_events()->GetSize()); const base::DictionaryValue* item1 = NULL; ASSERT_TRUE(trace_events()->GetDictionary(0, &item1)); const base::DictionaryValue* item2 = NULL; ASSERT_TRUE(trace_events()->GetDictionary(1, &item2)); TraceEntryInfo actual_item1 = GetTraceEntryInfoFromValue(*item1); TraceEntryInfo actual_item2 = GetTraceEntryInfoFromValue(*item2); EXPECT_EQ(kNetLogTracingCategory, actual_item1.category); EXPECT_EQ(base::StringPrintf("0x%d", entries[0].source.id), actual_item1.id); EXPECT_EQ(std::string(1, TRACE_EVENT_PHASE_NESTABLE_ASYNC_INSTANT), actual_item1.phase); EXPECT_EQ(NetLog::EventTypeToString(NetLog::TYPE_CANCELLED), actual_item1.name); EXPECT_EQ(NetLog::SourceTypeToString(entries[0].source.type), actual_item1.source_type); EXPECT_EQ(kNetLogTracingCategory, actual_item2.category); EXPECT_EQ(base::StringPrintf("0x%d", entries[2].source.id), actual_item2.id); EXPECT_EQ(std::string(1, TRACE_EVENT_PHASE_NESTABLE_ASYNC_INSTANT), actual_item2.phase); EXPECT_EQ(NetLog::EventTypeToString(NetLog::TYPE_URL_REQUEST_START_JOB), actual_item2.name); EXPECT_EQ(NetLog::SourceTypeToString(entries[2].source.type), actual_item2.source_type); } TEST_F(TraceNetLogObserverTest, DestroyObserverWhileTracing) { trace_net_log_observer()->WatchForTraceStart(net_log()); EnableTraceLog(); net_log()->AddGlobalEntry(NetLog::TYPE_CANCELLED); trace_net_log_observer()->StopWatchForTraceStart(); set_trace_net_log_observer(NULL); net_log()->AddGlobalEntry(NetLog::TYPE_REQUEST_ALIVE); EndTraceAndFlush(); TestNetLogEntry::List entries; net_log()->GetEntries(&entries); EXPECT_EQ(2u, entries.size()); EXPECT_EQ(1u, trace_events()->GetSize()); const base::DictionaryValue* item1 = NULL; ASSERT_TRUE(trace_events()->GetDictionary(0, &item1)); TraceEntryInfo actual_item1 = GetTraceEntryInfoFromValue(*item1); EXPECT_EQ(kNetLogTracingCategory, actual_item1.category); EXPECT_EQ(base::StringPrintf("0x%d", entries[0].source.id), actual_item1.id); EXPECT_EQ(std::string(1, TRACE_EVENT_PHASE_NESTABLE_ASYNC_INSTANT), actual_item1.phase); EXPECT_EQ(NetLog::EventTypeToString(NetLog::TYPE_CANCELLED), actual_item1.name); EXPECT_EQ(NetLog::SourceTypeToString(entries[0].source.type), actual_item1.source_type); } TEST_F(TraceNetLogObserverTest, DestroyObserverWhileNotTracing) { trace_net_log_observer()->WatchForTraceStart(net_log()); net_log()->AddGlobalEntry(NetLog::TYPE_CANCELLED); trace_net_log_observer()->StopWatchForTraceStart(); set_trace_net_log_observer(NULL); net_log()->AddGlobalEntry(NetLog::TYPE_REQUEST_ALIVE); net_log()->AddGlobalEntry(NetLog::TYPE_URL_REQUEST_START_JOB); EndTraceAndFlush(); TestNetLogEntry::List entries; net_log()->GetEntries(&entries); EXPECT_EQ(3u, entries.size()); EXPECT_EQ(0u, trace_events()->GetSize()); } TEST_F(TraceNetLogObserverTest, CreateObserverAfterTracingStarts) { set_trace_net_log_observer(NULL); EnableTraceLog(); set_trace_net_log_observer(new TraceNetLogObserver()); trace_net_log_observer()->WatchForTraceStart(net_log()); net_log()->AddGlobalEntry(NetLog::TYPE_CANCELLED); trace_net_log_observer()->StopWatchForTraceStart(); net_log()->AddGlobalEntry(NetLog::TYPE_REQUEST_ALIVE); net_log()->AddGlobalEntry(NetLog::TYPE_URL_REQUEST_START_JOB); EndTraceAndFlush(); TestNetLogEntry::List entries; net_log()->GetEntries(&entries); EXPECT_EQ(3u, entries.size()); EXPECT_EQ(0u, trace_events()->GetSize()); } TEST_F(TraceNetLogObserverTest, EventsWithAndWithoutParameters) { trace_net_log_observer()->WatchForTraceStart(net_log()); EnableTraceLog(); NetLog::ParametersCallback net_log_callback; std::string param = "bar"; net_log_callback = NetLog::StringCallback("foo", &param); net_log()->AddGlobalEntry(NetLog::TYPE_CANCELLED, net_log_callback); net_log()->AddGlobalEntry(NetLog::TYPE_REQUEST_ALIVE); EndTraceAndFlush(); trace_net_log_observer()->StopWatchForTraceStart(); TestNetLogEntry::List entries; net_log()->GetEntries(&entries); EXPECT_EQ(2u, entries.size()); EXPECT_EQ(2u, trace_events()->GetSize()); const base::DictionaryValue* item1 = NULL; ASSERT_TRUE(trace_events()->GetDictionary(0, &item1)); const base::DictionaryValue* item2 = NULL; ASSERT_TRUE(trace_events()->GetDictionary(1, &item2)); TraceEntryInfo actual_item1 = GetTraceEntryInfoFromValue(*item1); TraceEntryInfo actual_item2 = GetTraceEntryInfoFromValue(*item2); EXPECT_EQ(kNetLogTracingCategory, actual_item1.category); EXPECT_EQ(base::StringPrintf("0x%d", entries[0].source.id), actual_item1.id); EXPECT_EQ(std::string(1, TRACE_EVENT_PHASE_NESTABLE_ASYNC_INSTANT), actual_item1.phase); EXPECT_EQ(NetLog::EventTypeToString(NetLog::TYPE_CANCELLED), actual_item1.name); EXPECT_EQ(NetLog::SourceTypeToString(entries[0].source.type), actual_item1.source_type); EXPECT_EQ(kNetLogTracingCategory, actual_item2.category); EXPECT_EQ(base::StringPrintf("0x%d", entries[1].source.id), actual_item2.id); EXPECT_EQ(std::string(1, TRACE_EVENT_PHASE_NESTABLE_ASYNC_INSTANT), actual_item2.phase); EXPECT_EQ(NetLog::EventTypeToString(NetLog::TYPE_REQUEST_ALIVE), actual_item2.name); EXPECT_EQ(NetLog::SourceTypeToString(entries[1].source.type), actual_item2.source_type); std::string item1_params; std::string item2_params; EXPECT_TRUE(item1->GetString("args.params.foo", &item1_params)); EXPECT_EQ("bar", item1_params); EXPECT_TRUE(item2->GetString("args.params", &item2_params)); EXPECT_TRUE(item2_params.empty()); } } // namespace } // namespace net
{ "content_hash": "c426addb1fc4f08f76b967aa4b9a2f98", "timestamp": "", "source": "github", "line_count": 349, "max_line_length": 80, "avg_line_length": 37.26361031518625, "alnum_prop": 0.7071126489811611, "repo_name": "CapOM/ChromiumGStreamerBackend", "id": "4adcd0f7097e7f992007a6508307c0c306667f60", "size": "13805", "binary": false, "copies": "5", "ref": "refs/heads/master", "path": "net/log/trace_net_log_observer_unittest.cc", "mode": "33188", "license": "bsd-3-clause", "language": [ { "name": "AppleScript", "bytes": "6973" }, { "name": "Arduino", "bytes": "464" }, { "name": "Assembly", "bytes": "37073" }, { "name": "Batchfile", "bytes": "8451" }, { "name": "C", "bytes": "9560486" }, { "name": "C++", "bytes": "246838243" }, { "name": "CSS", "bytes": "943687" }, { "name": "DM", "bytes": "60" }, { "name": "Groff", "bytes": "2494" }, { "name": "HTML", "bytes": "27371019" }, { "name": "Java", "bytes": "15348315" }, { "name": "JavaScript", "bytes": "20872607" }, { "name": "Makefile", "bytes": "70983" }, { "name": "Objective-C", "bytes": "2029825" }, { "name": "Objective-C++", "bytes": "10156554" }, { "name": "PHP", "bytes": "97817" }, { "name": "PLpgSQL", "bytes": "182741" }, { "name": "Perl", "bytes": "63937" }, { "name": "Protocol Buffer", "bytes": "494625" }, { "name": "Python", "bytes": "8594611" }, { "name": "Shell", "bytes": "486464" }, { "name": "Standard ML", "bytes": "5106" }, { "name": "XSLT", "bytes": "418" }, { "name": "nesC", "bytes": "18347" } ], "symlink_target": "" }
#pragma once #include <cstddef> #include <osquery/utils/only_movable.h> #include <osquery/utils/status/status.h> #include <osquery/utils/system/system.h> #ifdef WIN32 #pragma warning(push, 3) #pragma warning(disable : 4715) #endif /** * This protects parsing from overflowing the stack. * See http://rapidjson.org/md_doc_features.html for more details. * * This must be defined before including RapidJSON headers. */ #define RAPIDJSON_PARSE_DEFAULT_FLAGS (kParseIterativeFlag) #include <rapidjson/document.h> #include <rapidjson/error/en.h> #include <rapidjson/stringbuffer.h> #include <rapidjson/writer.h> #ifdef WIN32 #pragma warning(pop) #endif namespace osquery { /** * @brief This provides a small wrapper around constructing JSON objects. * * Constructing RapidJSON objects can be slightly tricky. In our original * refactoring we found several opportunities to leak memory and cause faults. * This was mostly causes by setting allocators incorrectly. */ class JSON : private only_movable { private: explicit JSON(rapidjson::Type type); public: enum class ParseMode { Iterative, Recursive }; JSON(); JSON(JSON&&) = default; JSON& operator=(JSON&&) = default; /// Create a JSON wrapper for an Object (map). static JSON newObject(); /// Create a JSON wrapper for an Array (list). static JSON newArray(); /// Create a JSON wrapper from an existing value. static JSON newFromValue(const rapidjson::Value& value); public: /// Make a JSON object (map). rapidjson::Document getObject() const; /// Make a JSON array (list). rapidjson::Document getArray() const; /// Add a JSON object or array to a list. void push(rapidjson::Value& value); /// Add a JSON object or array to a list. void push(rapidjson::Value& value, rapidjson::Value& arr); /// Add a size_t to a JSON array. void push(size_t value); /// Add a size_t to a JSON array. void push(size_t value, rapidjson::Value& arr); /// Add a copy of a string to a JSON array. void pushCopy(const std::string& value); /// Add a reference to a string to a JSON array. void pushCopy(const std::string& value, rapidjson::Value& arr); /** * @brief Add a string value to a JSON object by copying the contents. * * This will add the key and value to an input document. If the key exists * the value will be replaced. * The input document must be an object type. */ void addCopy(const std::string& key, const std::string& value, rapidjson::Value& obj); /** * @brief Add a string value to a JSON object by copying the contents. * * This will add the key and value to the JSON document. If the key exists * the value will be replaced. * The document must be an object type. */ void addCopy(const std::string& key, const std::string& value); /** * @brief Add a string value to a JSON object by referencing the contents. * * The string value must live longer than the document's use. * * This will add the key and value to an input document. If the key exists * the value will be replaced. * The input document must be an object type. */ void addRef(const std::string& key, const std::string& value, rapidjson::Value& obj); /** * @brief Add a string value to a JSON object by referencing the contents. * * The string value must live longer than the document's use. * * This will add the key and value to the JSON document. If the key exists * the value will be replaced. * The input document must be an object type. */ void addRef(const std::string& key, const std::string& value); /** * @brief Add a string value to a JSON object by copying the contents. * * This is basically and alias for addCopy() * * This will add the key and value to an input document. If the key exists * the value will be replaced. * The input document must be an object type. */ void add(const std::string& key, const std::string& value, rapidjson::Value& obj); /** * @brief Add a string value to a JSON object by copying the contents. * * This is basically and alias for addCopy(). * * This will add the key and value to the JSON document. If the key exists * the value will be replaced. * The document must be an object type. */ void add(const std::string& key, const std::string& value); /** * @brief Add a char* value to a JSON object by copying the contents. * * This will add the key and value to an input document. If the key exists * the value will be replaced. * The input document must be an object type. */ void add(const std::string& key, const char* value, rapidjson::Value& obj); /** * @brief Add a char* value to a JSON object by copying the contents. * * This will add the key and value to the JSON document. If the key exists * the value will be replaced. * The document must be an object type. */ void add(const std::string& key, const char* value); /** * @brief Add a int value to a JSON object by copying the contents. * * This will add the key and value to an input document. If the key exists * the value will be replaced. * The input document must be an object type. */ void add(const std::string& key, int value, rapidjson::Value& obj); /** * @brief Add a int value to a JSON object by copying the contents. * * This will add the key and value to the JSON document. If the key exists * the value will be replaced. * The document must be an object type. */ void add(const std::string& key, int value); /** * @brief Add a long value to a JSON object by copying the contents. * * This will add the key and value to an input document. If the key exists * the value will be replaced. * The input document must be an object type. */ void add(const std::string& key, long value, rapidjson::Value& obj); /** * @brief Add a long value to a JSON object by copying the contents. * * This will add the key and value to the JSON document. If the key exists * the value will be replaced. * The document must be an object type. */ void add(const std::string& key, long value); /** * @brief Add a long long to a JSON object by copying the * contents. * * This will add the key and value to an input document. If the key exists * the value will be replaced. * The input document must be an object type. */ void add(const std::string& key, long long value, rapidjson::Value& obj); /** * @brief Add a long long to a JSON object by copying the * contents. * * This will add the key and value to the JSON document. If the key exists * the value will be replaced. * The document must be an object type. */ void add(const std::string& key, long long value); /** * @brief Add an unsigned int value to a JSON object by copying the contents. * * This will add the key and value to an input document. If the key exists * the value will be replaced. * The input document must be an object type. */ void add(const std::string& key, unsigned int value, rapidjson::Value& obj); /** * @brief Add an unsigned int value to a JSON object by copying the contents. * * This will add the key and value to the JSON document. If the key exists * the value will be replaced. * The document must be an object type. */ void add(const std::string& key, unsigned int value); /** * @brief Add an unsigned long value to a JSON object by copying the contents. * * This will add the key and value to an input document. If the key exists * the value will be replaced. * The input document must be an object type. */ void add(const std::string& key, unsigned long value, rapidjson::Value& obj); /** * @brief Add an unsigned long value to a JSON object by copying the contents. * * This will add the key and value to the JSON document. If the key exists * the value will be replaced. * The document must be an object type. */ void add(const std::string& key, unsigned long value); /** * @brief Add an unsigned long long to a JSON object by copying the * contents. * * This will add the key and value to an input document. If the key exists * the value will be replaced. * The input document must be an object type. */ void add(const std::string& key, unsigned long long value, rapidjson::Value& obj); /** * @brief Add an unsigned long long to a JSON object by copying the * contents. * * This will add the key and value to the JSON document. If the key exists * the value will be replaced. * The document must be an object type. */ void add(const std::string& key, unsigned long long value); /** * @brief Add a double value to a JSON object by copying the contents. * * This will add the key and value to an input document. If the key exists * the value will be replaced. * The input document must be an object type. */ void add(const std::string& key, double value, rapidjson::Value& obj); /** * @brief Add an double value to a JSON object by copying the contents. * * This will add the key and value to the JSON document. If the key exists * the value will be replaced. * The document must be an object type. */ void add(const std::string& key, double value); /** * @brief Add a bool value to a JSON object by copying the contents. * * This will add the key and value to an input document. If the key exists * the value will be replaced. * The input document must be an object type. */ void add(const std::string& key, bool value, rapidjson::Value& obj); /** * @brief Add a bool value to a JSON object by copying the contents. * * This will add the key and value to the JSON document. If the key exists * the value will be replaced. * The document must be an object type. */ void add(const std::string& key, bool value); /// Add a JSON document as a member. void add(const std::string& key, const rapidjson::Value& value); /// Add a JSON document as a member of another document. void add(const std::string& key, const rapidjson::Value& value, rapidjson::Value& obj); /** * @brief Copy a JSON object/array into the document. * * The type of the base document may change, be careful. */ void copyFrom(const rapidjson::Value& value, rapidjson::Value& target); /** * @brief Copy a JSON object/array into the document. * * The type of the base document may change, be careful. */ void copyFrom(const rapidjson::Value& value); /// Convert this document to a JSON string. Status toString(std::string& str) const; /// Helper to convert a string into JSON. Status fromString(const std::string& str, ParseMode parse_mode = ParseMode::Recursive); /// Merge members of source into target, must both be objects. void mergeObject(rapidjson::Value& target_obj, rapidjson::Value& source_obj); void mergeArray(rapidjson::Value& target_arr, rapidjson::Value& source_arr); /// Access the internal document containing the allocator. rapidjson::Document& doc(); /// Access the internal document containing the allocator. const rapidjson::Document& doc() const; public: /// Get the value as a 'size' or 0. static std::uint64_t valueToSize(const rapidjson::Value& value); /// Get the value as a 'bool' or false. static bool valueToBool(const rapidjson::Value& value); private: rapidjson::Document doc_; decltype(rapidjson::kObjectType) type_; }; } // namespace osquery
{ "content_hash": "4e1c4219509b54ab97eb9288ce4b52a9", "timestamp": "", "source": "github", "line_count": 370, "max_line_length": 80, "avg_line_length": 31.735135135135135, "alnum_prop": 0.6736501447794243, "repo_name": "hackgnar/osquery", "id": "56216c386806dc476303f618c1339377e9bb5bd9", "size": "11978", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "osquery/utils/json/json.h", "mode": "33188", "license": "bsd-3-clause", "language": [ { "name": "C", "bytes": "38093" }, { "name": "C++", "bytes": "2088263" }, { "name": "CMake", "bytes": "72851" }, { "name": "Makefile", "bytes": "6220" }, { "name": "Objective-C++", "bytes": "62318" }, { "name": "Shell", "bytes": "2038" }, { "name": "Thrift", "bytes": "2969" } ], "symlink_target": "" }
package pongo2 import ( "bytes" ) type NodeWrapper struct { Endtag string nodes []INode } func (wrapper *NodeWrapper) Execute(ctx *ExecutionContext, buffer *bytes.Buffer) *Error { for _, n := range wrapper.nodes { err := n.Execute(ctx, buffer) if err != nil { return err } } return nil }
{ "content_hash": "61175199e783bebf215537291c2edb2a", "timestamp": "", "source": "github", "line_count": 20, "max_line_length": 89, "avg_line_length": 15.35, "alnum_prop": 0.6644951140065146, "repo_name": "insionng/yougam", "id": "9180dc70b2748e79d6a1640acb5d2e8dfac1a7e3", "size": "307", "binary": false, "copies": "7", "ref": "refs/heads/master", "path": "libraries/flosch/pongo2.v3/nodes_wrapper.go", "mode": "33188", "license": "bsd-2-clause", "language": [], "symlink_target": "" }
This is an ESP8266 based Twitter client built with 256x64 OLED (SSD1322 based) display. ESP8266 connects directly to Twitter, so no third-party proxy services are used. Application connects to [user stream](https://dev.twitter.com/streaming/userstreams) and displays all the incoming tweets for that user. This basically means the same tweets the user would see on her Twitter main page. Additionally, a [track](https://dev.twitter.com/streaming/overview/request-parameters#track) parameter can be set to include tweets containing specified keywords. The tweet currently shown on the display can be [retweeted](https://dev.twitter.com/rest/reference/post/statuses/retweet/id), [liked](https://dev.twitter.com/rest/reference/post/favorites/create) and shared by sending link to it in [direct message](https://dev.twitter.com/rest/reference/post/direct_messages/new). This way user can easily access shared tweet on some other device. Application uses Twitter [REST](https://dev.twitter.com/rest/public) and [Streaming](https://dev.twitter.com/streaming/overview) APIs and implements OAuth 1.0a authorization as described [here](https://dev.twitter.com/oauth/overview/authorizing-requests). Unicode is supported. Glyphs for all characters found in Arial Unicode MS font are embedded in the binary. The glyphs are regular and bold variants with the sizes of 10 and 13. The font size is automatically selected based on the length of the tweet. Additionally, word wrapping and keyword (hashtag) highlighting are performed for tweet text. ## Building the hardware Any ESP8266 based module with at least 4 MB flash and SPI pins, such as ESP-12E, can be used. [NodeMCU-DEVKIT](https://github.com/nodemcu/nodemcu-devkit-v1.0) is a good choice since it already contains 3.3 V regulator suitable for powering OLED display. In addition to the display, there's a MPU6500 accelerometer connected on the SPI bus. Accelerometer is used for an automatic screen rotation. Devices on the SPI bus are connected in the following way: | ESP8266 | SSD1322 | MPU6500 | | -------------- | -------------- | -------------- | | GPIO5 | RESET | | | GPIO4 | | CS | | HMISO (GPIO12) | | SDO | | HMOSI (GPIO13) | SDIN (D1) | SDI | | HCS (GPIO15) | CS | | | HSCLK (GPIO14) | SCLK (D0) | SCLK | The SSD1322 based displays are quite common. One can be purchased e.g. from [buydisplay.com](http://www.buydisplay.com/default/oled-3-2-inch-displays-module-companies-with-driver-circuit-blue-on-black) or from AliExpress or eBay. The display's communication mode must be changed to 3-wire SPI in case it is not the default. Refer to the display documentation for the instructions how to change the mode. Usually some R0 resistors must be re-soldered. There are two push buttons used for accessing the device menus. Both buttons are connected to the analog input pin of the ESP8266. Please see [the schematics here](schematics.pdf). ## Building the software [esp-open-sdk](https://github.com/pfalcon/esp-open-sdk) is a preferred toolchain for this project. Other toolchains may work too, but are not tested. After cloning this repository, in the makefile you need to set paths to your SDK installation and set the name of the serial port used for flashing. To build everything, run: `make all`. Due to the limitation of ESP8266 being able to directly access only addresses < 1 MB of the SPI flash, the font data is separated to its own segment and is read indirectly. Slightly modified versions of the linker script and esptool are needed for producing the font segment. Both, the linker script and the esptool, are included in this repository. ### Flashing the binary When flashing for the first time, the font data needs to be flashed. Run `make flashall`. This will flash the application segments and the font segment. The operation takes a few minutes even at the high baud rate, but it only needs to be done once if the font is not changed. From now on, `make flash` can be used. It only flashes the application segments, which is much faster. ## Usage Device settings can be changed through the serial interface (921600/8-N-1). The following syntax should be used: ``` parameter:value<CR> ``` At least the following parameters must be set by the user: - ssid - WiFi SSID - pass - WiFi password - consumer_key - Twitter app Consumer Key (API Key) - consumer_secret - Twitter app Consumer Secret (API Secret) - access_token - Twitter app Access Token - token_secret - Twitter app Access Token Secret In order to obtain Twitter app keys, user must create a new Twitter app with her own account: 1. Go to https://apps.twitter.com/app/new 2. Fill the form (content doesn't matter). 3. When the app is created, go to *Permissions* tab and check that the app has at least *Read and Write* permissions. 4. Go to *Keys and Access Tokens* tab and copy the keys into the device. The device should now be able to login to Twitter with the user's account and display tweets from the user's stream. To include additional tweets into the stream, the following parameters can be used: - [track](https://dev.twitter.com/streaming/overview/request-parameters#track) (must be UTF-8 encoded) - [language](https://dev.twitter.com/streaming/overview/request-parameters#language) - [filter](https://dev.twitter.com/streaming/overview/request-parameters#filter_level) Please see the [config.c](src/config.c) file for additional supported parameters. There are two menus which can be accessed by pressing the device buttons. From the first menu user can share, retweet and like currently shown tweet. From the second menu user can mute the device for a certain period of time or completely turn it off. When the device is muted or turned off, it will not receive any tweets. The menus' logic is as following: When no menu is shown, pressing the button activates the corresponding menu. Pressing the same button again changes the selected action. Pressing another button executes the selected action. If no buttons are pressed for 10 seconds, menu will be hidden automatically. *** [![](http://img.youtube.com/vi/5xc7ObxyhF4/sddefault.jpg)](https://youtu.be/5xc7ObxyhF4)
{ "content_hash": "31c16976e485450242a4e8e830f7d650", "timestamp": "", "source": "github", "line_count": 70, "max_line_length": 450, "avg_line_length": 91.28571428571429, "alnum_prop": 0.7405320813771518, "repo_name": "andrei7c4/esptwitterclient", "id": "e507d20162106b21be522cc0aa5fd8cd2242be0d", "size": "6416", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "README.md", "mode": "33188", "license": "mit", "language": [ { "name": "C", "bytes": "13102392" }, { "name": "C++", "bytes": "4050" }, { "name": "Makefile", "bytes": "7996" }, { "name": "Objective-C", "bytes": "1222" }, { "name": "Python", "bytes": "56087" } ], "symlink_target": "" }
namespace Snittlistan.Web.ViewModels; public class QuillData { public QuillData(string htmlFieldName, string stringFieldName, string placeholder) { HtmlFieldName = htmlFieldName; StringFieldName = stringFieldName; Placeholder = placeholder; } public string HtmlFieldName { get; } public string StringFieldName { get; } public string Placeholder { get; } }
{ "content_hash": "88b19b036f4ef05b24e5701d203f02b2", "timestamp": "", "source": "github", "line_count": 17, "max_line_length": 86, "avg_line_length": 24.058823529411764, "alnum_prop": 0.7017114914425427, "repo_name": "dlidstrom/Snittlistan", "id": "bd11ec3cb7e7ce00b973aad972b3383f0e3d340e", "size": "411", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "Snittlistan.Web/ViewModels/QuillData.cs", "mode": "33188", "license": "mit", "language": [ { "name": "ASP.NET", "bytes": "107" }, { "name": "Batchfile", "bytes": "79" }, { "name": "C#", "bytes": "1550365" }, { "name": "CSS", "bytes": "58717" }, { "name": "F#", "bytes": "1316" }, { "name": "HTML", "bytes": "2380877" }, { "name": "JavaScript", "bytes": "19222" }, { "name": "Less", "bytes": "8308" }, { "name": "PowerShell", "bytes": "9727" }, { "name": "XSLT", "bytes": "9784" } ], "symlink_target": "" }
/** * Performance test application for the primitives. */ package org.onosproject.primitiveperf;
{ "content_hash": "542cb0fb64f62401d4b4ee005f16a2c3", "timestamp": "", "source": "github", "line_count": 6, "max_line_length": 51, "avg_line_length": 16.833333333333332, "alnum_prop": 0.7524752475247525, "repo_name": "LorenzReinhart/ONOSnew", "id": "d9b4faeafcac7ad920f97bdfb3b965e460feadce", "size": "718", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "apps/test/primitive-perf/src/main/java/org/onosproject/primitiveperf/package-info.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "CSS", "bytes": "224030" }, { "name": "HTML", "bytes": "108368" }, { "name": "Java", "bytes": "34148438" }, { "name": "JavaScript", "bytes": "3833411" }, { "name": "Protocol Buffer", "bytes": "13730" }, { "name": "Python", "bytes": "185205" }, { "name": "Shell", "bytes": "2594" } ], "symlink_target": "" }
@interface RoundModal : NSObject @property (strong, nonatomic) NSString *roundtime; @property (nonatomic) NSInteger pointnum; @property (nonatomic) NSInteger homepoint; @property (nonatomic) NSInteger awaypoint; @property (strong, nonatomic) NSMutableArray *homeHistory; @property (strong, nonatomic) NSMutableArray *awayHistory; @end
{ "content_hash": "b2c2276f85447f3c1c4473d4822df8b6", "timestamp": "", "source": "github", "line_count": 10, "max_line_length": 58, "avg_line_length": 33.7, "alnum_prop": 0.8011869436201781, "repo_name": "hmeng22/Huaminton", "id": "49eaa84533eb968afa05348ecfcef76460bd55a0", "size": "503", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "Huaminton/RoundModal.h", "mode": "33188", "license": "mit", "language": [ { "name": "Objective-C", "bytes": "258217" } ], "symlink_target": "" }
package org.opencb.opencga.analysis.wrappers.fastqc; import org.apache.commons.lang3.tuple.ImmutablePair; import org.apache.commons.lang3.tuple.Pair; import org.opencb.opencga.analysis.wrappers.executors.DockerWrapperAnalysisExecutor; import org.opencb.opencga.core.tools.annotations.ToolExecutor; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.util.*; @ToolExecutor(id = FastqcWrapperAnalysisExecutor.ID, tool = FastqcWrapperAnalysis.ID, source = ToolExecutor.Source.STORAGE, framework = ToolExecutor.Framework.LOCAL) public class FastqcWrapperAnalysisExecutor extends DockerWrapperAnalysisExecutor { public final static String ID = FastqcWrapperAnalysis.ID + "-local"; private String study; private String inputFile; private Logger logger = LoggerFactory.getLogger(this.getClass()); @Override protected void run() throws Exception { StringBuilder sb = initCommandLine(); // Append mounts List<Pair<String, String>> inputFilenames = DockerWrapperAnalysisExecutor.getInputFilenames(getInputFile(), FastqcWrapperAnalysis.FILE_PARAM_NAMES, getExecutorParams()); Map<String, String> mountMap = appendMounts(inputFilenames, sb); // Append docker image, version and command appendCommand("fastqc", sb); // Append input file params appendInputFiles(inputFilenames, mountMap, sb); // Append output file params List<Pair<String, String>> outputFilenames = new ArrayList<>(Arrays.asList(new ImmutablePair<>("o", ""))); appendOutputFiles(outputFilenames, sb); // Append other params Set<String> skipParams = new HashSet<>(Arrays.asList("o", "outdir", "d", "dir", "j", "java")); appendOtherParams(skipParams, sb); // Execute command and redirect stdout and stderr to the files logger.info("Docker command line: " + sb.toString()); runCommandLine(sb.toString()); } public String getStudy() { return study; } public FastqcWrapperAnalysisExecutor setStudy(String study) { this.study = study; return this; } public String getInputFile() { return inputFile; } public FastqcWrapperAnalysisExecutor setInputFile(String inputFile) { this.inputFile = inputFile; return this; } }
{ "content_hash": "7678fa65268fcc63a037d505c1fe9d2c", "timestamp": "", "source": "github", "line_count": 70, "max_line_length": 115, "avg_line_length": 34.042857142857144, "alnum_prop": 0.6953420058749475, "repo_name": "opencb/opencga", "id": "e13d9468d138867419578cef38646cc6ca4faecc", "size": "2383", "binary": false, "copies": "1", "ref": "refs/heads/develop", "path": "opencga-analysis/src/main/java/org/opencb/opencga/analysis/wrappers/fastqc/FastqcWrapperAnalysisExecutor.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Dockerfile", "bytes": "13743" }, { "name": "HTML", "bytes": "1001" }, { "name": "Java", "bytes": "18854348" }, { "name": "JavaScript", "bytes": "631302" }, { "name": "Jupyter Notebook", "bytes": "6290799" }, { "name": "Makefile", "bytes": "3567" }, { "name": "Mustache", "bytes": "9851" }, { "name": "Python", "bytes": "599379" }, { "name": "R", "bytes": "430511" }, { "name": "Shell", "bytes": "131224" }, { "name": "Smarty", "bytes": "2215" } ], "symlink_target": "" }
(function(){ //Modeled metrics based on flow model JenScript.AxisMetricsFlow = function(config) { this.___init(config); }; JenScript.Model.inheritPrototype(JenScript.AxisMetricsFlow, JenScript.AxisMetricsPlugin); JenScript.Model.addMethods(JenScript.AxisMetricsFlow, { ___init : function(config){ config = config ||{}; var manager = new JenScript.MetricsManagerFlow(config); config.manager = manager; config.name='AxisMetricsFlow'; JenScript.AxisMetricsPlugin.call(this,config); }, }); })();
{ "content_hash": "347bb415f7635530594184f2b095b1c6", "timestamp": "", "source": "github", "line_count": 18, "max_line_length": 90, "avg_line_length": 29, "alnum_prop": 0.7260536398467433, "repo_name": "sjanaud/jenscript", "id": "cc7f7cd35a4f8f0319f22cf94054860afc087832", "size": "522", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/plugins/metrics/flow-axis-plugin.js", "mode": "33188", "license": "bsd-3-clause", "language": [ { "name": "CSS", "bytes": "22927" }, { "name": "HTML", "bytes": "129408" }, { "name": "JavaScript", "bytes": "4191038" } ], "symlink_target": "" }
package consul import ( "fmt" "io" "log" "os" "path/filepath" "strconv" "strings" "sync" "time" "github.com/hashicorp/consul/agent/metadata" "github.com/hashicorp/consul/agent/pool" "github.com/hashicorp/consul/agent/router" "github.com/hashicorp/consul/agent/structs" "github.com/hashicorp/consul/lib" "github.com/hashicorp/serf/coordinate" "github.com/hashicorp/serf/serf" ) const ( // clientRPCConnMaxIdle controls how long we keep an idle connection // open to a server. 127s was chosen as the first prime above 120s // (arbitrarily chose to use a prime) with the intent of reusing // connections who are used by once-a-minute cron(8) jobs *and* who // use a 60s jitter window (e.g. in vixie cron job execution can // drift by up to 59s per job, or 119s for a once-a-minute cron job). clientRPCConnMaxIdle = 127 * time.Second // clientMaxStreams controls how many idle streams we keep // open to a server clientMaxStreams = 32 // serfEventBacklog is the maximum number of unprocessed Serf Events // that will be held in queue before new serf events block. A // blocking serf event queue is a bad thing. serfEventBacklog = 256 // serfEventBacklogWarning is the threshold at which point log // warnings will be emitted indicating a problem when processing serf // events. serfEventBacklogWarning = 200 ) // Client is Consul client which uses RPC to communicate with the // services for service discovery, health checking, and DC forwarding. type Client struct { config *Config // Connection pool to consul servers connPool *pool.ConnPool // routers is responsible for the selection and maintenance of // Consul servers this agent uses for RPC requests routers *router.Manager // eventCh is used to receive events from the // serf cluster in the datacenter eventCh chan serf.Event // Logger uses the provided LogOutput logger *log.Logger // serf is the Serf cluster maintained inside the DC // which contains all the DC nodes serf *serf.Serf shutdown bool shutdownCh chan struct{} shutdownLock sync.Mutex } // NewClient is used to construct a new Consul client from the // configuration, potentially returning an error func NewClient(config *Config) (*Client, error) { return NewClientLogger(config, nil) } func NewClientLogger(config *Config, logger *log.Logger) (*Client, error) { // Check the protocol version if err := config.CheckProtocolVersion(); err != nil { return nil, err } // Check for a data directory! if config.DataDir == "" { return nil, fmt.Errorf("Config must provide a DataDir") } // Sanity check the ACLs if err := config.CheckACL(); err != nil { return nil, err } // Ensure we have a log output if config.LogOutput == nil { config.LogOutput = os.Stderr } // Create the tls Wrapper tlsWrap, err := config.tlsConfig().OutgoingTLSWrapper() if err != nil { return nil, err } // Create a logger if logger == nil { logger = log.New(config.LogOutput, "", log.LstdFlags) } connPool := &pool.ConnPool{ SrcAddr: config.RPCSrcAddr, LogOutput: config.LogOutput, MaxTime: clientRPCConnMaxIdle, MaxStreams: clientMaxStreams, TLSWrapper: tlsWrap, ForceTLS: config.VerifyOutgoing, } // Create server c := &Client{ config: config, connPool: connPool, eventCh: make(chan serf.Event, serfEventBacklog), logger: logger, shutdownCh: make(chan struct{}), } // Start lan event handlers before lan Serf setup to prevent deadlock go c.lanEventHandler() // Initialize the lan Serf c.serf, err = c.setupSerf(config.SerfLANConfig, c.eventCh, serfLANSnapshot) if err != nil { c.Shutdown() return nil, fmt.Errorf("Failed to start lan serf: %v", err) } // Start maintenance task for servers c.routers = router.New(c.logger, c.shutdownCh, c.serf, c.connPool) go c.routers.Start() return c, nil } // setupSerf is used to setup and initialize a Serf func (c *Client) setupSerf(conf *serf.Config, ch chan serf.Event, path string) (*serf.Serf, error) { conf.Init() conf.NodeName = c.config.NodeName conf.Tags["role"] = "node" conf.Tags["dc"] = c.config.Datacenter conf.Tags["id"] = string(c.config.NodeID) conf.Tags["vsn"] = fmt.Sprintf("%d", c.config.ProtocolVersion) conf.Tags["vsn_min"] = fmt.Sprintf("%d", ProtocolVersionMin) conf.Tags["vsn_max"] = fmt.Sprintf("%d", ProtocolVersionMax) conf.Tags["build"] = c.config.Build conf.MemberlistConfig.LogOutput = c.config.LogOutput conf.LogOutput = c.config.LogOutput conf.Logger = c.logger conf.EventCh = ch conf.SnapshotPath = filepath.Join(c.config.DataDir, path) conf.ProtocolVersion = protocolVersionMap[c.config.ProtocolVersion] conf.RejoinAfterLeave = c.config.RejoinAfterLeave conf.Merge = &lanMergeDelegate{ dc: c.config.Datacenter, nodeID: c.config.NodeID, nodeName: c.config.NodeName, } if err := lib.EnsurePath(conf.SnapshotPath, false); err != nil { return nil, err } return serf.Create(conf) } // Shutdown is used to shutdown the client func (c *Client) Shutdown() error { c.logger.Printf("[INFO] consul: shutting down client") c.shutdownLock.Lock() defer c.shutdownLock.Unlock() if c.shutdown { return nil } c.shutdown = true close(c.shutdownCh) if c.serf != nil { c.serf.Shutdown() } // Close the connection pool c.connPool.Shutdown() return nil } // Leave is used to prepare for a graceful shutdown func (c *Client) Leave() error { c.logger.Printf("[INFO] consul: client starting leave") // Leave the LAN pool if c.serf != nil { if err := c.serf.Leave(); err != nil { c.logger.Printf("[ERR] consul: Failed to leave LAN Serf cluster: %v", err) } } return nil } // JoinLAN is used to have Consul client join the inner-DC pool // The target address should be another node inside the DC // listening on the Serf LAN address func (c *Client) JoinLAN(addrs []string) (int, error) { return c.serf.Join(addrs, true) } // LocalMember is used to return the local node func (c *Client) LocalMember() serf.Member { return c.serf.LocalMember() } // LANMembers is used to return the members of the LAN cluster func (c *Client) LANMembers() []serf.Member { return c.serf.Members() } // RemoveFailedNode is used to remove a failed node from the cluster func (c *Client) RemoveFailedNode(node string) error { return c.serf.RemoveFailedNode(node) } // KeyManagerLAN returns the LAN Serf keyring manager func (c *Client) KeyManagerLAN() *serf.KeyManager { return c.serf.KeyManager() } // Encrypted determines if gossip is encrypted func (c *Client) Encrypted() bool { return c.serf.EncryptionEnabled() } // lanEventHandler is used to handle events from the lan Serf cluster func (c *Client) lanEventHandler() { var numQueuedEvents int for { numQueuedEvents = len(c.eventCh) if numQueuedEvents > serfEventBacklogWarning { c.logger.Printf("[WARN] consul: number of queued serf events above warning threshold: %d/%d", numQueuedEvents, serfEventBacklogWarning) } select { case e := <-c.eventCh: switch e.EventType() { case serf.EventMemberJoin: c.nodeJoin(e.(serf.MemberEvent)) case serf.EventMemberLeave, serf.EventMemberFailed: c.nodeFail(e.(serf.MemberEvent)) case serf.EventUser: c.localEvent(e.(serf.UserEvent)) case serf.EventMemberUpdate: // Ignore case serf.EventMemberReap: // Ignore case serf.EventQuery: // Ignore default: c.logger.Printf("[WARN] consul: unhandled LAN Serf Event: %#v", e) } case <-c.shutdownCh: return } } } // nodeJoin is used to handle join events on the serf cluster func (c *Client) nodeJoin(me serf.MemberEvent) { for _, m := range me.Members { ok, parts := metadata.IsConsulServer(m) if !ok { continue } if parts.Datacenter != c.config.Datacenter { c.logger.Printf("[WARN] consul: server %s for datacenter %s has joined wrong cluster", m.Name, parts.Datacenter) continue } c.logger.Printf("[INFO] consul: adding server %s", parts) c.routers.AddServer(parts) // Trigger the callback if c.config.ServerUp != nil { c.config.ServerUp() } } } // nodeFail is used to handle fail events on the serf cluster func (c *Client) nodeFail(me serf.MemberEvent) { for _, m := range me.Members { ok, parts := metadata.IsConsulServer(m) if !ok { continue } c.logger.Printf("[INFO] consul: removing server %s", parts) c.routers.RemoveServer(parts) } } // localEvent is called when we receive an event on the local Serf func (c *Client) localEvent(event serf.UserEvent) { // Handle only consul events if !strings.HasPrefix(event.Name, "consul:") { return } switch name := event.Name; { case name == newLeaderEvent: c.logger.Printf("[INFO] consul: New leader elected: %s", event.Payload) // Trigger the callback if c.config.ServerUp != nil { c.config.ServerUp() } case isUserEvent(name): event.Name = rawUserEventName(name) c.logger.Printf("[DEBUG] consul: user event: %s", event.Name) // Trigger the callback if c.config.UserEventHandler != nil { c.config.UserEventHandler(event) } default: c.logger.Printf("[WARN] consul: Unhandled local event: %v", event) } } // RPC is used to forward an RPC call to a consul server, or fail if no servers func (c *Client) RPC(method string, args interface{}, reply interface{}) error { server := c.routers.FindServer() if server == nil { return structs.ErrNoServers } // Forward to remote Consul if err := c.connPool.RPC(c.config.Datacenter, server.Addr, server.Version, method, server.UseTLS, args, reply); err != nil { c.routers.NotifyFailedServer(server) c.logger.Printf("[ERR] consul: RPC failed to server %s: %v", server.Addr, err) return err } return nil } // SnapshotRPC sends the snapshot request to one of the servers, reading from // the streaming input and writing to the streaming output depending on the // operation. func (c *Client) SnapshotRPC(args *structs.SnapshotRequest, in io.Reader, out io.Writer, replyFn structs.SnapshotReplyFn) error { // Locate a server to make the request to. server := c.routers.FindServer() if server == nil { return structs.ErrNoServers } // Request the operation. var reply structs.SnapshotResponse snap, err := SnapshotRPC(c.connPool, c.config.Datacenter, server.Addr, server.UseTLS, args, in, &reply) if err != nil { return err } defer func() { if err := snap.Close(); err != nil { c.logger.Printf("[WARN] consul: Failed closing snapshot stream: %v", err) } }() // Let the caller peek at the reply. if replyFn != nil { if err := replyFn(&reply); err != nil { return nil } } // Stream the snapshot. if out != nil { if _, err := io.Copy(out, snap); err != nil { return fmt.Errorf("failed to stream snapshot: %v", err) } } return nil } // Stats is used to return statistics for debugging and insight // for various sub-systems func (c *Client) Stats() map[string]map[string]string { numServers := c.routers.NumServers() toString := func(v uint64) string { return strconv.FormatUint(v, 10) } stats := map[string]map[string]string{ "consul": map[string]string{ "server": "false", "known_servers": toString(uint64(numServers)), }, "serf_lan": c.serf.Stats(), "runtime": runtimeStats(), } return stats } func (c *Client) ServerAddrs() map[string]string { return c.routers.GetServerAddrs() } // GetLANCoordinate returns the network coordinate of the current node, as // maintained by Serf. func (c *Client) GetLANCoordinate() (*coordinate.Coordinate, error) { return c.serf.GetCoordinate() }
{ "content_hash": "7f4052e53bc126b3fd09ebdacf021496", "timestamp": "", "source": "github", "line_count": 422, "max_line_length": 138, "avg_line_length": 27.369668246445496, "alnum_prop": 0.7064069264069264, "repo_name": "Faffnir/vip-manager", "id": "d669100ff7de03f8264669a9855f1e020886d89f", "size": "11550", "binary": false, "copies": "3", "ref": "refs/heads/master", "path": "vendor/github.com/hashicorp/consul/agent/consul/client.go", "mode": "33188", "license": "bsd-2-clause", "language": [ { "name": "Dockerfile", "bytes": "295" }, { "name": "Go", "bytes": "10466" }, { "name": "Makefile", "bytes": "1765" }, { "name": "Shell", "bytes": "4788" } ], "symlink_target": "" }
/* * Attachment code for having the generic console device use the LAMEbus * serial device. */ #include <types.h> #include <lib.h> #include <generic/console.h> #include <lamebus/lser.h> #include "autoconf.h" struct con_softc * attach_con_to_lser(int consno, struct lser_softc *ls) { struct con_softc *cs = kmalloc(sizeof(struct con_softc)); if (cs==NULL) { return NULL; } (void)consno; // unused cs->cs_devdata = ls; cs->cs_send = lser_write; cs->cs_sendpolled = lser_writepolled; ls->ls_devdata = cs; ls->ls_start = con_start; ls->ls_input = con_input; return cs; }
{ "content_hash": "3360769651e37ae30f0bd4d3c328ebe5", "timestamp": "", "source": "github", "line_count": 34, "max_line_length": 72, "avg_line_length": 17.441176470588236, "alnum_prop": 0.6711635750421585, "repo_name": "computist/os161", "id": "c5fdb7a32a1c4ee1417a6e31610387345edcd27a", "size": "2207", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "kern/dev/lamebus/con_lser.c", "mode": "33188", "license": "mit", "language": [ { "name": "Assembly", "bytes": "47292" }, { "name": "C", "bytes": "1821160" }, { "name": "C++", "bytes": "25660" }, { "name": "Makefile", "bytes": "68914" }, { "name": "Objective-C", "bytes": "1666" }, { "name": "Shell", "bytes": "32132" } ], "symlink_target": "" }
require "houston/kanban/railtie" module Houston module Kanban class Engine < ::Rails::Engine isolate_namespace Houston::Kanban # Precompile this modules assets initializer :assets do |config| Rails.application.config.assets.precompile += %w( houston/kanban/application.js houston/kanban/application.css ) end # Include the Engine's migrations with the Application # http://pivotallabs.com/leave-your-migrations-in-your-rails-engines/ initializer :append_migrations do |app| unless app.root.to_s.match root.to_s config.paths["db/migrate"].expanded.each do |expanded_path| app.config.paths["db/migrate"] << expanded_path end end end end end end
{ "content_hash": "de79ce9d8c40586fa9e9404abb3d3f04", "timestamp": "", "source": "github", "line_count": 27, "max_line_length": 75, "avg_line_length": 29, "alnum_prop": 0.6500638569604087, "repo_name": "houstonmc/houston-kanban", "id": "c8756a44a033991485cc1238c69e2f2018bc6aa3", "size": "783", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "lib/houston/kanban/engine.rb", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "5351" }, { "name": "CoffeeScript", "bytes": "9218" }, { "name": "JavaScript", "bytes": "1291" }, { "name": "Ruby", "bytes": "29484" } ], "symlink_target": "" }
NSString *const kTabBarAppearanceBackgroundColor = @"Tab Bar Background Color"; NSString *const kTabBarAppearanceHeight = @"Tab Bar Height"; NSString *const kTabBarAppearanceTint = @"Tab Bar Tint";
{ "content_hash": "1363090019fa774512bb70dae955b754", "timestamp": "", "source": "github", "line_count": 5, "max_line_length": 79, "avg_line_length": 39.8, "alnum_prop": 0.7939698492462312, "repo_name": "hulu001/GGTabBar", "id": "a3f7965c7383f98301685d70c1a158679cf6660d", "size": "377", "binary": false, "copies": "5", "ref": "refs/heads/master", "path": "GGTabBar/GGTabBarAppearanceKeys.m", "mode": "33188", "license": "mit", "language": [ { "name": "Objective-C", "bytes": "36160" }, { "name": "Ruby", "bytes": "999" } ], "symlink_target": "" }
require "rails_helper" describe StyleController do describe "#index" do render_views before do login_as_stub_user get :index end context "loading the page" do it "responds with the correct HTTP status code" do expect(response.status).to be(200) end end end end
{ "content_hash": "7739a9e8ce96cd212e51a32a95975d2a", "timestamp": "", "source": "github", "line_count": 18, "max_line_length": 56, "avg_line_length": 17.77777777777778, "alnum_prop": 0.640625, "repo_name": "alphagov/transition", "id": "c53db5bd8a164cd200092fa6a2f34154fc538238", "size": "320", "binary": false, "copies": "1", "ref": "refs/heads/main", "path": "spec/controllers/style_controller_spec.rb", "mode": "33188", "license": "mit", "language": [ { "name": "Dockerfile", "bytes": "481" }, { "name": "Gherkin", "bytes": "60883" }, { "name": "HTML", "bytes": "106264" }, { "name": "JavaScript", "bytes": "39405" }, { "name": "Procfile", "bytes": "52" }, { "name": "Ruby", "bytes": "515124" }, { "name": "SCSS", "bytes": "25505" } ], "symlink_target": "" }
package com.mmnaseri.cs.clrs.ch02.s1; import java.util.Comparator; /** * @author Mohammad Milad Naseri ([email protected]) * @since 1.0 (8/13/15) */ public class FasterIterativeInsertionSorter<E extends Comparable<E>> extends IterativeInsertionSorter<E> { public FasterIterativeInsertionSorter(Comparator<E> comparator) { super(comparator); } /** * This method tries to cut the running time by a constant factor or offset by treating the edge * cases of when the item is smaller than all items and when the item is larger than all items as * special cases. * * @param items all the items * @param item the item which we want to place * @param length the length of the array which should be visited * @param comparator the comparator * @return the expected position of the item in the given array */ @Override protected int findPlacement(E[] items, E item, int length, Comparator<E> comparator) { return InsertionSortUtils.placementSpecialCaseHandler( items, item, length, comparator, () -> super.findPlacement(items, item, length, comparator)); } }
{ "content_hash": "a7a2dffd70b788073305ea6e755701ef", "timestamp": "", "source": "github", "line_count": 36, "max_line_length": 99, "avg_line_length": 32.111111111111114, "alnum_prop": 0.7041522491349481, "repo_name": "mmnaseri/cs-review", "id": "2acf77dda351267903ddec57b79286f3f872105d", "size": "1156", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "cs-clrs/src/main/java/com/mmnaseri/cs/clrs/ch02/s1/FasterIterativeInsertionSorter.java", "mode": "33188", "license": "mit", "language": [ { "name": "Java", "bytes": "952648" } ], "symlink_target": "" }
// Copyright 2009 the Sputnik authors. All rights reserved. // This code is governed by the BSD license found in the LICENSE file. /** * @name: S8.7.2_A1_T1; * @section: 8.7.2; * @assertion: GetValue(V) mast fail; * @description: Checking if execution of "'litera'=1;" fails; * @negative; */ 'litera'=1;
{ "content_hash": "813d3e9bca1f890a7557a75472eebeef", "timestamp": "", "source": "github", "line_count": 12, "max_line_length": 70, "avg_line_length": 25.583333333333332, "alnum_prop": 0.6775244299674267, "repo_name": "luboid/ES5.Script", "id": "ca5722a9d1b39c813e61461fd4a28dd7bc27c83d", "size": "307", "binary": false, "copies": "7", "ref": "refs/heads/master", "path": "TestScripts/sputniktests/tests/Conformance/08_Types/8.7_The_Reference_Type/S8.7.2_A1_T1.js", "mode": "33188", "license": "bsd-3-clause", "language": [ { "name": "Batchfile", "bytes": "1728" }, { "name": "C#", "bytes": "825380" }, { "name": "CSS", "bytes": "15950" }, { "name": "HTML", "bytes": "426289" }, { "name": "JavaScript", "bytes": "9567963" }, { "name": "Python", "bytes": "29140" } ], "symlink_target": "" }
package org.locationtech.geowave.test.query; import java.io.IOException; import org.geotools.data.DataUtilities; import org.geotools.feature.SchemaException; import org.geotools.feature.simple.SimpleFeatureBuilder; import org.junit.After; import org.junit.AfterClass; import org.junit.Assert; import org.junit.Before; import org.junit.BeforeClass; import org.junit.Test; import org.junit.runner.RunWith; import org.locationtech.geowave.adapter.vector.FeatureDataAdapter; import org.locationtech.geowave.core.geotime.ingest.SpatialDimensionalityTypeProvider; import org.locationtech.geowave.core.geotime.ingest.SpatialOptions; import org.locationtech.geowave.core.geotime.util.GeometryUtils; import org.locationtech.geowave.core.index.StringUtils; import org.locationtech.geowave.core.store.CloseableIterator; import org.locationtech.geowave.core.store.api.DataStore; import org.locationtech.geowave.core.store.api.Index; import org.locationtech.geowave.core.store.api.QueryBuilder; import org.locationtech.geowave.core.store.api.Writer; import org.locationtech.geowave.core.store.cli.remote.options.DataStorePluginOptions; import org.locationtech.geowave.core.store.query.constraints.DataIdQuery; import org.locationtech.geowave.test.GeoWaveITRunner; import org.locationtech.geowave.test.TestUtils; import org.locationtech.geowave.test.annotation.GeoWaveTestStore; import org.locationtech.geowave.test.annotation.GeoWaveTestStore.GeoWaveStoreType; import org.locationtech.geowave.test.basic.AbstractGeoWaveIT; import org.locationtech.jts.geom.Coordinate; import org.locationtech.jts.geom.Geometry; import org.opengis.feature.simple.SimpleFeature; import org.opengis.feature.simple.SimpleFeatureType; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @RunWith(GeoWaveITRunner.class) public class PolygonDataIdQueryIT extends AbstractGeoWaveIT { private static final Logger LOGGER = LoggerFactory.getLogger(PolygonDataIdQueryIT.class); private static SimpleFeatureType simpleFeatureType; private static FeatureDataAdapter dataAdapter; private static final String GEOMETRY_ATTRIBUTE = "geometry"; private static final String DATA_ID = "dataId"; private static Index index = new SpatialDimensionalityTypeProvider().createIndex(new SpatialOptions()); @GeoWaveTestStore({ GeoWaveStoreType.ACCUMULO, GeoWaveStoreType.CASSANDRA, GeoWaveStoreType.HBASE, GeoWaveStoreType.DYNAMODB, GeoWaveStoreType.KUDU, GeoWaveStoreType.REDIS, GeoWaveStoreType.ROCKSDB}) protected DataStorePluginOptions dataStore; @Override protected DataStorePluginOptions getDataStorePluginOptions() { return dataStore; } private static long startMillis; @Test public void testPolygonDataIdQueryResults() { final CloseableIterator<SimpleFeature> matches = (CloseableIterator) dataStore.createDataStore().query( QueryBuilder.newBuilder().addTypeName(dataAdapter.getTypeName()).indexName( TestUtils.DEFAULT_SPATIAL_INDEX.getName()).constraints( new DataIdQuery(StringUtils.stringToBinary(DATA_ID))).build()); int numResults = 0; while (matches.hasNext()) { matches.next(); numResults++; } Assert.assertTrue("Expected 1 result, but returned " + numResults, numResults == 1); } @BeforeClass public static void setupData() throws IOException { simpleFeatureType = getSimpleFeatureType(); dataAdapter = new FeatureDataAdapter(simpleFeatureType); dataAdapter.init(index); startMillis = System.currentTimeMillis(); LOGGER.warn("-----------------------------------------"); LOGGER.warn("* *"); LOGGER.warn("* RUNNING PolygonDataIdQueryIT *"); LOGGER.warn("* *"); LOGGER.warn("-----------------------------------------"); } @AfterClass public static void reportTest() { LOGGER.warn("-----------------------------------------"); LOGGER.warn("* *"); LOGGER.warn("* FINISHED PolygonDataIdQueryIT *"); LOGGER.warn( "* " + ((System.currentTimeMillis() - startMillis) / 1000) + "s elapsed. *"); LOGGER.warn("* *"); LOGGER.warn("-----------------------------------------"); } @Before public void ingestSampleData() throws IOException { final DataStore store = dataStore.createDataStore(); store.addType(dataAdapter, TestUtils.DEFAULT_SPATIAL_INDEX); try (@SuppressWarnings("unchecked") Writer writer = store.createWriter(dataAdapter.getTypeName())) { writer.write( buildSimpleFeature( DATA_ID, GeometryUtils.GEOMETRY_FACTORY.createPolygon( new Coordinate[] { new Coordinate(1.0249, 1.0319), new Coordinate(1.0261, 1.0319), new Coordinate(1.0261, 1.0323), new Coordinate(1.0249, 1.0319)}))); } } @After public void deleteSampleData() throws IOException { LOGGER.info("Deleting canned data..."); TestUtils.deleteAll(dataStore); LOGGER.info("Delete complete."); } private static SimpleFeatureType getSimpleFeatureType() { SimpleFeatureType type = null; try { type = DataUtilities.createType("data", GEOMETRY_ATTRIBUTE + ":Geometry"); } catch (final SchemaException e) { LOGGER.error("Unable to create SimpleFeatureType", e); } return type; } private static SimpleFeature buildSimpleFeature(final String dataId, final Geometry geo) { final SimpleFeatureBuilder builder = new SimpleFeatureBuilder(simpleFeatureType); builder.set(GEOMETRY_ATTRIBUTE, geo); return builder.buildFeature(dataId); } }
{ "content_hash": "346c5cae3f039bcd757206fab7131450", "timestamp": "", "source": "github", "line_count": 149, "max_line_length": 92, "avg_line_length": 39.395973154362416, "alnum_prop": 0.6894378194207836, "repo_name": "spohnan/geowave", "id": "9ac75adecf7406900233e52496c6607b18992d61", "size": "6305", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "test/src/test/java/org/locationtech/geowave/test/query/PolygonDataIdQueryIT.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Dockerfile", "bytes": "3148" }, { "name": "FreeMarker", "bytes": "2879" }, { "name": "Gnuplot", "bytes": "57750" }, { "name": "Groovy", "bytes": "8034" }, { "name": "Java", "bytes": "9654261" }, { "name": "Jupyter Notebook", "bytes": "23088" }, { "name": "Puppet", "bytes": "8850" }, { "name": "Python", "bytes": "230406" }, { "name": "Scheme", "bytes": "20491" }, { "name": "Shell", "bytes": "97476" } ], "symlink_target": "" }
Specs ===== My repository of CocoaPods (cocoapods.org) specifications.
{ "content_hash": "5fe6ff0deea53db778989ee689513944", "timestamp": "", "source": "github", "line_count": 4, "max_line_length": 58, "avg_line_length": 18, "alnum_prop": 0.75, "repo_name": "shadowboy/Specs", "id": "b3611be7ffbf227efe58e002a45f1b25fd007bf1", "size": "72", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "README.md", "mode": "33188", "license": "mit", "language": [ { "name": "Ruby", "bytes": "3130" } ], "symlink_target": "" }
using Microsoft.ApplicationInsights.DataContracts; using Microsoft.VisualStudio.TestTools.UnitTesting; using System; using System.Collections.Generic; using System.ServiceModel.Channels; using System.Text; namespace Microsoft.ApplicationInsights.Wcf.Tests { [TestClass] public class ClientIpTelemetryInitializerTests { [TestMethod] public void SetsClientIpFromWcfContextOnRequest() { const String clientIp = "10.12.32.12"; var context = new MockOperationContext(); context.IncomingProperties.Add( RemoteEndpointMessageProperty.Name, new RemoteEndpointMessageProperty(clientIp, 7656)); var initializer = new ClientIpTelemetryInitializer(); var telemetry = context.Request; initializer.Initialize(telemetry, context); Assert.AreEqual(clientIp, telemetry.Context.Location.Ip); } [TestMethod] public void SetsClientIpFromWcfContextOnOtherEvent() { const String originalIp = "10.12.32.12"; const String newIp = "172.34.12.45"; var context = new MockOperationContext(); context.IncomingProperties.Add( RemoteEndpointMessageProperty.Name, new RemoteEndpointMessageProperty(originalIp, 7656)); var initializer = new ClientIpTelemetryInitializer(); // initialize request with the original IP initializer.Initialize(context.Request, context); // replace IP so that we can tell // it is being picked up from the request // rather than the context context.IncomingProperties.Clear(); context.IncomingProperties.Add( RemoteEndpointMessageProperty.Name, new RemoteEndpointMessageProperty(newIp, 7656)); var telemetry = new EventTelemetry("myevent"); initializer.Initialize(telemetry, context); Assert.AreEqual(originalIp, telemetry.Context.Location.Ip); } } }
{ "content_hash": "9aa9a447b6bef0db88d27dd1949926c1", "timestamp": "", "source": "github", "line_count": 59, "max_line_length": 71, "avg_line_length": 35.54237288135593, "alnum_prop": 0.6461611826418694, "repo_name": "frackleton/ApplicationInsights-SDK-Labs", "id": "ee281ed904094bd2796469b9b4051b2906b65d0b", "size": "2099", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "WCF/Shared.Tests/ClientIpTelemetryInitializerTests.cs", "mode": "33188", "license": "mit", "language": [ { "name": "Batchfile", "bytes": "548" }, { "name": "C#", "bytes": "269742" } ], "symlink_target": "" }
<Alloy> <TableViewRow id="row"> <Label id="title"/> <View id="separator"/> </TableViewRow> </Alloy>
{ "content_hash": "89b6e8f694fe83dec388f67f1b381a46", "timestamp": "", "source": "github", "line_count": 6, "max_line_length": 28, "avg_line_length": 19.166666666666668, "alnum_prop": 0.5739130434782609, "repo_name": "darknos/Memkit", "id": "63d0d4b1447dba7dd74616047f8d7273de131424", "size": "115", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "app/views/menuRow.xml", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "C", "bytes": "147870" }, { "name": "C++", "bytes": "56135" }, { "name": "CSS", "bytes": "35019" }, { "name": "D", "bytes": "832479" }, { "name": "JavaScript", "bytes": "381008" }, { "name": "Objective-C", "bytes": "3397437" }, { "name": "Python", "bytes": "4668" }, { "name": "Shell", "bytes": "450" } ], "symlink_target": "" }
import { is } from 'ramda'; import { Primitive } from 'd3'; export default function functor<Datum>( v: string | ((datum: Datum, index?: number, outerIndex?: number) => string) ): (datum: Datum, index?: number, outerIndex?: number) => string; export default function functor<Datum>( v: | Primitive | ((datum: Datum, index: number, outerIndex?: number) => Primitive) ): (datum: Datum, index?: number, outerIndex?: number) => Primitive; export default function functor<Datum>( v: | Primitive | ((datum: Datum, index: number, outerIndex?: number) => Primitive) ): (datum: Datum, index: number, outerIndex?: number) => Primitive { return is(Function, v) ? (v as (datum: Datum, index: number, outerIndex?: number) => Primitive) : () => v as Primitive; }
{ "content_hash": "0e7be127e48df34f56cc4accb977c9dd", "timestamp": "", "source": "github", "line_count": 20, "max_line_length": 77, "avg_line_length": 39.05, "alnum_prop": 0.6555697823303457, "repo_name": "gaearon/redux-devtools", "id": "b0ba2146540bdce40e0d5507d0c7c40433d4f7d7", "size": "781", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "packages/d3tooltip/src/utils/functor.ts", "mode": "33188", "license": "mit", "language": [ { "name": "JavaScript", "bytes": "7194" } ], "symlink_target": "" }
xLog ==== A simple logger for the Go language. [![Build Status](https://img.shields.io/travis/dulo-tech/xlog/master.svg)](https://travis-ci.org/dulo-tech/xlog) [![GoDoc](https://img.shields.io/badge/godoc-reference-blue.svg)](https://godoc.org/github.com/dulo-tech/xlog) [![MIT license](https://img.shields.io/badge/license-MIT-blue.svg)](https://raw.githubusercontent.com/dulo-tech/xlog/master/LICENSE.md) * [Installation](#installation) * [Examples](#examples) * [Global Logger](#global-logger) * [Custom Formatters](#custom-formatters) * [Loggable Interface](#loggable-interface) * [License](#license) #### Installation Use the go get command to fetch the package. `go get github.com/dulo-tech/xlog` Then use the import statement in your source code to use the package. ```go import "github.com/dulo-tech/xlog" ``` #### Examples ```go package main import ( "os" "github.com/dulo-tech/xlog" ) func main() { // Start by creating a new logger. Each logger needs a name. The name is // usually reflective of the sub-system that will be logging messages. The // name will appear in the logged messages so each message can be linked to // a specific area of your code. logger := xlog.New("testing") // Add files where the logs will be written. You can use a full system path // to a file, or the aliases "stdout", "stderr", and "stdin". Each file you // add is assigned a logging level. The file is written to when a message is // logged to that level or a greater level. The levels are: // // xlog.DebugLevel // xlog.InfoLevel // xlog.NoticeLevel // xlog.WarningLevel // xlog.ErrorLevel // xlog.CriticalLevel // xlog.AlertLevel // xlog.EmergencyLevel // // When you append a file using the xlog.DebugLevel level, the file will be // written to for every level, because every level is greater than xdt.Debug. logger.Append("stdout", xlog.DebugLevel) // For each log level there is a xdt.Loggable method used to write messages // to that level. For example xdt.Loggable.Debug(), xdt.Loggable.Alert(), etc. // There is a formatting method for each level as well. For example // xdt.Loggable.Debugf(), xdt.Loggable.Alertf(), etc. // Outputs: 2014-11-15 09:40:28.693 testing.DEBUG Test debug message. logger.Debug("Test debug message.") // Outputs: 2014-11-15 09:40:28.693 testing.DEBUG Test debug message. logger.Debugf("Test %s message.", "debug") // Outputs: 2014-11-15 09:40:28.701 testing.WARNING Test warning message. logger.Warning("Test warning message.") // Outputs: 2014-11-15 09:40:28.723 testing.INFO Test info message. logger.Infof("Test %s message.", "info") // Any log message with the xlog.WarningLevel level and above will be logged to // stdout. logger = xlog.New("testing") logger.Append("stdout", xlog.WarningLevel) // This doesn't output anything because the xlog.DebugLevel level is lower than // the xlog.WarningLevel level. logger.Debug("Test debug message.") // Outputs: 2014-11-15 09:40:28.701 testing.WARNING Test warning message. logger.Warning("Test warning message.") // This doesn't output anything because the Info level is lower than the // Warning level. logger.Infof("Test %s message.", "info") // Logging can be disabled, and when disabled the calls to the logging // methods will simply be ignored. // Outputs: 2014-11-15 09:40:28.701 testing.NOTICE Test notice message. logger.Notice("Test notice message.") // Now disable logging. logger.Settings.Enabled = false // This doesn't output anything because logging is now disabled, but you // can still call the methods without any errors. logger.Notice("Test notice message.") // You can append as many files as you want. This logs messages to the // xlog.DebugLevel and above to stdout, and messages xlog.ErrorLevel level // and above to a file. // Note, when you have the logger open files, the files need to be closed by // the logger by deferring the defer logger.Close() method. The logger cannot // be used once it's been closed. logger = xlog.New("testing") logger.Append("stdout", xlog.DebugLevel) logger.Append("/var/logs/main-error.log", xlog.ErrorLevel) defer logger.Close() // You can manage the files yourself by using the logger.AppendWriter() // method. fp, err := os.OpenFile( "/var/logs/main-error.log", os.O_RDWR|os.O_CREATE | os.O_APPEND, 0666, ) if err != nil { panic(err) } defer fp.Close() logger.AppendWriter(fp, xlog.DebugLevel) logger.AppendWriter(os.Stderr, xlog.ErrorLevel) // You can append multiple files using xdt.Logger.MultiAppend() and // xdt.Logger.MultiAppendWriter(). logger = xlog.New("testing") logger.MultiAppend( []string{ "stderr", "/var/logs/main-error.log", }, xlog.DebugLevel, ) defer logger.Close() // You can also create the logger with an array of file names or writers. files := []string{ "stderr", "/var/logs/main-error.log", } logger = xlog.NewFiles("testing", files, xdt.Debug) // Change the way the log messages are formatted. The xlog.Formatter interface // requires a format string. The format string defines how the // log messages are formatted. Several placeholders can be used in the format // string, which will be replaced by actual values: // // {date} The datetime when the message was logged. // {name} The name of the logger. // {level} A string representation of the log level. // {message} The message that was logged. logger.Settings.Formatter = xlog.NewDefaultFormatter( "{date} {name} - {level} - {message}", DefaultDateFormat, ) // Outputs: 2014-11-15 09:54:16.278 testing - DEBUG - This is a debug test. logger.Debug("Test debug message.") // Change the way dates are printed using the Go time syntax inside the // {date} placeholder. // See: http://golang.org/pkg/time/#Time.Format logger.Settings.Formatter = xlog.NewDefaultFormatter( "{date|Jan _2 15:04:05} {level} {message}", DefaultDateFormat ) // Outputs: Nov 15 09:56:56 DEBUG Test debug message. logger.Debug("Test debug message.") // Creating a logger with a pre-configured formatter. logger = xlog.New("testing") logger.Append("stdout", xlog.DebugLevel) logger.Settings.formatter = xlog.NewDefaultFormatter( "{date} {name} [{level}] {message}", DefaultDateFormat ) // Outputs: 2014-11-15 09:59:32.427 testing [DEBUG] Test debug message. logger.Debug("Test debug message.") // The message format can be changed without setting a new Formatter. logger.Settings.Formatter.SetMessageFormat("{date} {message}") // In addition to the default placeholders like {date} and {message}, you // can also define your own. The Formatter.PlaceholderFunc() takes the value // for the placeholder, and a function which returns the value. Below we // define the placeholder {hostname} which will be replaced by the OS hostname. logger.Settings.Formatter.PlaceholderFunc("hostname", func(key string) string { h, _ := os.Hostname() return h }) // Creating a "child" logger. In this example the child logger inherits the // settings from the parent logger, but has it's own name. logger = xlog.New("testing") child := logger.New("child") } ``` #### Global Logger You can use the global logger when your application is small, and does not need to log messages from several sub-systems using a different names. The global logger is easy to use, but it's not quite as flexible as using individual logger instances. ```go package main import ( "os" "fmt" "github.com/dulo-tech/xlog" ) func main() { // The global logger has the same methods as a logger // instance (Debug(), Warningf(), Info(), etc), but as exposed functions // in the package scope. // Outputs: 2014-11-15 09:40:28.693 xlog.DEBUG Test debug message. xlog.Debug("Test debug message.") // Outputs: 2014-11-15 09:40:28.693 xlog.DEBUG Test debug message. xlog.Debugf("Test %s message.", "debug") // Outputs: 2014-11-15 09:40:28.701 xlog.WARNING Test warning message. xlog.Warning("Test warning message.") // By default the global logger has the name "xlog", but that can be // changed. xlog.SetName("testing") // Be default the global logger writes messages at xlog.DebugLevel and // above to stdout. That can be changed by appending the files you want // at the level you want. Note that calling any of the global Append // functions removes the default stdout. You'll have to add it back // if you still want to log to stdout. xlog.Append("stderr", xlog.WarningLevel) xlog.Append("stdout", xlog.DebugLevel) xlog.AppendWriter(os.Stdout, xlog.InfoLevel) // Outputs: 2014-11-15 09:40:28.693 testing.DEBUG Test debug message. xlog.Debug("Test debug message.") // Outputs: 2014-11-15 09:40:28.701 testing.WARNING Test warning message. xlog.Warning("Test warning message.") // Just like the logger instances, you need to ensure the global logger // closes any files it opened. You can continue to use the logger after // closing it, but closing the logger resets it's configuration, which // defaults the global logger to the default name and stdout. xlog.Append("/var/log/messages.log", xlog.DebugLevel) defer xlog.Close() // You can disable/enable global logging and test to see if it's enabled. xlog.SetEnabled(false) if !xlog.Enabled() { fmt.Println("Logging is disabled.") } } ``` The `xlog.GetLogger()` function gives you the ease of a global logger, with the flexibility of named loggers. The function acts like a factory and global registry, which is useful when you have hundreds or even thousands of objects that need a logger, but you don't want to create thousands of *DefaultLogger instances. ```go package main import ( "fmt" "github.com/dulo-tech/xlog" ) func main() { // The first call to xlog.GetLogger() with the name "a" creates a // new logger for the name and returns it. The next time you call the // function with the same name, the same *DefaultLogger instance is returned. loggerA := xlog.GetLogger("a") loggerA.Append("stdout", xlog.DebugLevel) if loggerA == xlog.GetLogger("a") { fmt.Println("xlog.GetLogger() returned the same instance for the same name.") } loggerB := xlog.GetLogger("b") loggerB.Append("stdout", xlog.DebugLevel) if loggerB == xlog.GetLogger("b") { fmt.Println("These loggers have the same name, and same instance.") } if xlog.GetLogger("a") != xlog.GetLogger("b") { fmt.Println("These are different instances.") } // Outputs: 2014-11-15 09:40:28.693 a.DEBUG Test debug message. loggerA.Debug("Test debug message.") // Outputs: 2014-11-15 09:40:28.701 b.WARNING Test warning message. loggerB.Warning("Test warning message.") // Outputs: 2014-11-15 c.WARNING Test warning message. loggerC.Warning("Test warning message.") // This doesn't output anything because xlog.WarningLevel was set as the // global default level when loggerD was created. loggerD.Debug("Test debug message.") } ``` #### Custom Formatters You can create your own message formatter by creating a struct that implements the `xlog.Formatter` interface, which has the following signature: ```go type Formatter interface { // SetFormat changes the set message format. SetFormat(format string) // PlaceholderFunc adds a callback function which provides a replacement for key in a string format. PlaceholderFunc(key string, f func(string) string) // Format formats a log message for the given level. Format(name string, level Level, v ...interface{}) string } ``` This example creates a formatter than always formats messages into an empty string. The logger discards empty messages, which means this formatter causes all messages to be discarded. ```go package main import "github.com/dulo-tech/xlog" // NullFormatter implements the xlog.Formatter interface where all // log messages are discarded. type NullFormatter struct { } // SetFormat changes the set message format. func (f *NullFormatter) SetFormat(format string) { } // PlaceholderFunc adds a callback function which provides a replacement for key in a string format. func PlaceholderFunc(key string, f func(string) string) { } // Format formats a log message for the given level. func (f *NullFormatter) Format(name string, level Level, v ...interface{}) string { return "" } func main() { // Creating a logger which discards all messages. logger := xlog.New("testing") logger.Append("stdout", xlog.DebugLevel) logger.Settings.Formatter := &NullFormatter{} // You can also assign the custom formatter to the global logger. xlog.SetFormatter(formatter) } ``` #### Loggable Interface The `xlog.New()` method and other New methods return an instance of the struct `xlog.DefaultLogger`, which implements the `xlog.Loggable` interface. ```go type Loggable interface { Writable() bool Closed() bool Log(level Level, v ...interface{}) Logf(level Level, format string, v ...interface{}) Debug(v ...interface{}) Debugf(format string, v ...interface{}) Info(v ...interface{}) Infof(format string, v ...interface{}) Warning(v ...interface{}) Warningf(format string, v ...interface{}) Error(v ...interface{}) Errorf(format string, v ...interface{}) Critical(v ...interface{}) Criticalf(format string, v ...interface{}) Alert(v ...interface{}) Alertf(format string, v ...interface{}) Emergency(v ...interface{}) Emergencyf(format string, v ...interface{}) Writer(level Level) *LoggerWriter } ``` Note the absence of methods like `Append()`, `MultiAppend()`, `AppendWriter()`, and `Close()`, which are members of the `xlog.DefaultLogger` struct. The `xlog.Loggable` interface does not concern itself for how a logger is configured or it's lifecycle. The `xlog.Loggable` interface only exposes methods for logging messages at various log levels. You are encouraged to reference `xlog.Loggable` instead of `xlog.DefaultLogger` in your code to keep it flexible to future API changes. For example instead of creating a struct using `xlog.DefaultLogger` like this: ```go type WebScraper struct { logger xlog.DefaultLogger } func NewWebScraper(logger *xlog.DefaultLogger) { return &WebScraper{logger} } ``` You should instead use `xlog.Loggable` like this: ```go type WebScraper struct { logger xlog.Loggable } func NewWebScraper(logger *xlog.Loggable) { return &WebScraper{logger} } ``` You should configure your loggers in the main package, and let the rest of your source code deal with the `xlog.Loggable` interface exclusively. #### License xLog is has been released under the MIT license, a copy of which is included in the LICENSE file, which you can find in the source code. You're encouraged to use the xLog source code in any way you want, for whatever reason you want.
{ "content_hash": "f9425bd84d36d042d23ddcbbfda228cb", "timestamp": "", "source": "github", "line_count": 446, "max_line_length": 135, "avg_line_length": 34.7780269058296, "alnum_prop": 0.687254206692025, "repo_name": "dulo-tech/xlog", "id": "ad8b64fb6946db131dc0e1d385bfd32b831d2ff0", "size": "15511", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "README.md", "mode": "33188", "license": "mit", "language": [ { "name": "Go", "bytes": "33412" } ], "symlink_target": "" }
using System; using System.Collections; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; namespace Grabacr07.KanColleViewer.Plugins.ViewModels { public class LogItemCollection : IEnumerable { public List<string> Columns = new List<string>(); public List<string[]> Rows = new List<string[]>(); public IEnumerator GetEnumerator() { return this.Rows.GetEnumerator(); } } }
{ "content_hash": "9d6018678f1c9e61f74ad25fef474d9b", "timestamp": "", "source": "github", "line_count": 19, "max_line_length": 58, "avg_line_length": 24.736842105263158, "alnum_prop": 0.6723404255319149, "repo_name": "bllue78/KanColleViewer", "id": "50059ccecb30854bb02d449b99c3737d819c901a", "size": "472", "binary": false, "copies": "9", "ref": "refs/heads/master", "path": "Plugins/LogViewer/ViewModels/LogItemCollection.cs", "mode": "33188", "license": "mit", "language": [ { "name": "C#", "bytes": "719284" }, { "name": "PowerShell", "bytes": "13055" } ], "symlink_target": "" }
#include <signal.h> #include "imapfilter.h" void signal_handler(int sig); /* * Catch signals that cause program's termination. */ void catch_signals(void) { signal(SIGINT, signal_handler); signal(SIGQUIT, signal_handler); signal(SIGTERM, signal_handler); } /* * Release signals and reset them to default action. */ void release_signals(void) { signal(SIGINT, SIG_DFL); signal(SIGQUIT, SIG_DFL); signal(SIGTERM, SIG_DFL); } /* * Signal handler for signals that cause termination of program. */ void signal_handler(int sig) { release_signals(); fatal(ERROR_SIGNAL, "killed by signal %d\n", sig); }
{ "content_hash": "99510f3744d22a57200bbcbb26ad49e2", "timestamp": "", "source": "github", "line_count": 45, "max_line_length": 64, "avg_line_length": 13.844444444444445, "alnum_prop": 0.6982343499197432, "repo_name": "eliteraspberries/imapfilter", "id": "229a45422fd5f80726d814d787e12a659009a00b", "size": "623", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/signal.c", "mode": "33188", "license": "mit", "language": [ { "name": "C", "bytes": "122492" }, { "name": "Lua", "bytes": "73172" }, { "name": "Makefile", "bytes": "2497" } ], "symlink_target": "" }
from gailtf.baselines.common.mpi_running_mean_std import RunningMeanStd import gailtf.baselines.common.tf_util as U import tensorflow as tf import gym from gailtf.baselines.common.distributions import make_pdtype class CnnPolicy(object): recurrent = False def __init__(self, name, ob_space, ac_space, kind='large'): with tf.variable_scope(name): self._init(ob_space, ac_space, kind) self.scope = tf.get_variable_scope().name def _init(self, ob_space, ac_space, kind): assert isinstance(ob_space, gym.spaces.Box) self.pdtype = pdtype = make_pdtype(ac_space) sequence_length = None ob = U.get_placeholder(name="ob", dtype=tf.float32, shape=[sequence_length] + list(ob_space.shape)) x = ob / 255.0 if kind == 'small': # from A3C paper x = tf.nn.relu(U.conv2d(x, 16, "l1", [8, 8], [4, 4], pad="VALID")) x = tf.nn.relu(U.conv2d(x, 32, "l2", [4, 4], [2, 2], pad="VALID")) x = U.flattenallbut0(x) x = tf.nn.relu(U.dense(x, 256, 'lin', U.normc_initializer(1.0))) elif kind == 'large': # Nature DQN x = tf.nn.relu(U.conv2d(x, 32, "l1", [8, 8], [4, 4], pad="VALID")) x = tf.nn.relu(U.conv2d(x, 64, "l2", [4, 4], [2, 2], pad="VALID")) x = tf.nn.relu(U.conv2d(x, 64, "l3", [3, 3], [1, 1], pad="VALID")) x = U.flattenallbut0(x) x = tf.nn.relu(U.dense(x, 512, 'lin', U.normc_initializer(1.0))) else: raise NotImplementedError logits = U.dense(x, pdtype.param_shape()[0], "logits", U.normc_initializer(0.01)) self.pd = pdtype.pdfromflat(logits) self.vpred = U.dense(x, 1, "value", U.normc_initializer(1.0))[:,0] self.state_in = [] self.state_out = [] stochastic = tf.placeholder(dtype=tf.bool, shape=()) ac = self.pd.sample() # XXX self._act = U.function([stochastic, ob], [ac, self.vpred]) def act(self, stochastic, ob): ac1, vpred1 = self._act(stochastic, ob[None]) return ac1[0], vpred1[0] def get_variables(self): return tf.get_collection(tf.GraphKeys.GLOBAL_VARIABLES, self.scope) def get_trainable_variables(self): return tf.get_collection(tf.GraphKeys.TRAINABLE_VARIABLES, self.scope) def get_initial_state(self): return []
{ "content_hash": "2b01d08a260185eca70d10ebf32f3c2e", "timestamp": "", "source": "github", "line_count": 57, "max_line_length": 107, "avg_line_length": 41.666666666666664, "alnum_prop": 0.5835789473684211, "repo_name": "ryanjulian/gail-tf", "id": "36a01894c8c6239968511b3507ea799acb51fbac", "size": "2375", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "gailtf/baselines/ppo1/cnn_policy.py", "mode": "33188", "license": "mit", "language": [ { "name": "Python", "bytes": "195509" }, { "name": "Shell", "bytes": "123" } ], "symlink_target": "" }
<?php header('Content-Type: text/javascript; charset=UTF-8',true); (@include_once "yeapf.php") or die("yeapf not configured"); /* @OBSOLETE 20170111 $developBase=$yeapfConfig['yeapfPath']."/../develop"; (@include_once "$developBase/yeapf.develop.php") or die ("Error loading 'yeapf.develop.php'"); */ try { yeapfStage("beforeAuthentication"); $userContext=new xUserContext($u); if ($userContext->isValidUser($appFolderRights)) { $userContext->loadUserVars('devSession'); /* @OBSOLETE 20170111 if (isset($devSession)) { _dumpY(256,0,"my devSession is '$devSession'"); $devMsgQueue=new xDevelopMSG($devSession, file_exists('flags/flag.nosharedmem')); $devMsgQueue->sendStagedMessage('busy'); } */ yeapfStage("beforeOutput"); implementation($s, $a, 'r'); yeapfStage("afterOutput"); } else yeapfStage("afterWrongAuthentication"); } catch(Exception $e) { _dump("EXCEPTION: ".$e->getMessage()); /* @OBSOLETE 20170111 if ($devMsgQueue) $devMsgQueue->sendStagedMessage('exception',$e->getMessage()); */ } /* @OBSOLETE 20170111 if ($devMsgQueue) $devMsgQueue->sendStagedMessage('idle'); */ _recordWastedTime("Good bye rest"); ?>
{ "content_hash": "1aa32f57225bf65b6fdd5fd382ca6fc7", "timestamp": "", "source": "github", "line_count": 47, "max_line_length": 96, "avg_line_length": 27.148936170212767, "alnum_prop": 0.6355799373040752, "repo_name": "EDortta/YeAPF", "id": "abd35e045f57ac8d4f77dcb528f297baa2a47543", "size": "1601", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "0.8.56/skel/webApp/rest.php", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "1434759" }, { "name": "HTML", "bytes": "9865143" }, { "name": "JavaScript", "bytes": "43628308" }, { "name": "PHP", "bytes": "32252830" }, { "name": "Shell", "bytes": "216948" } ], "symlink_target": "" }
/** * Created by king on 15-4-10. * * ch06.child_process_fork_main.js */ console.info("------ child_process fork main ------"); console.info(); /** * child_process fork * @type {exports} */ var cp = require('child_process'); // TODO: 引入child_process模块 var n = cp.fork('ch06.child_process_fork_sub.js'); // TODO: fork 子进程 /** * fork message event */ n.on('message', function(m) { console.log('PARENT got message:', m); }); /** * child_process send message */ n.send({ main: 'sub' }); // TODO: send message console.info();
{ "content_hash": "7a67e07ca314c35880f2bc27876882c4", "timestamp": "", "source": "github", "line_count": 24, "max_line_length": 69, "avg_line_length": 22.541666666666668, "alnum_prop": 0.6062846580406654, "repo_name": "0end1/code_base", "id": "ad0bbd4cfbe8e17305f78c2e042a89653b83701c", "size": "555", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "Node.js_Codebase/chapter06/ch06.child_process_fork_main.js", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "CSS", "bytes": "65112" }, { "name": "HTML", "bytes": "3013595" }, { "name": "JavaScript", "bytes": "3238434" }, { "name": "PHP", "bytes": "33205" } ], "symlink_target": "" }
var gulp = require('gulp'), concat = require('gulp-concat'), uglify = require('gulp-uglify'), util = require('gulp-util'), jshint = require('gulp-jshint'), replace = require('gulp-replace'), insert = require('gulp-insert'), inquirer = require('inquirer'), semver = require('semver'), exec = require('child_process').exec, fs = require('fs'), package = require('./package.json'), browserify = require('browserify'), streamify = require('gulp-streamify'), source = require('vinyl-source-stream'), merge = require('merge-stream'); var srcDir = './src/'; var outDir = './'; var header = "\n"; gulp.task('build', buildTask); gulp.task('bump', bumpTask); gulp.task('jshint', jshintTask); function buildTask() { var nonBundled = browserify('./src/chart.zoom.js') .ignore('chart.js') .ignore('hammerjs') .bundle() .pipe(source('chartjs-plugin-zoom.js')) .pipe(insert.prepend(header)) .pipe(streamify(replace('{{ version }}', package.version))) .pipe(gulp.dest(outDir)) .pipe(streamify(uglify({ preserveComments: 'some' }))) .pipe(streamify(concat('chartjs-plugin-zoom.min.js'))) .pipe(gulp.dest(outDir)); return nonBundled; } /* * Usage : gulp bump * Prompts: Version increment to bump * Output: - New version number written into package.json & bower.json */ function bumpTask(complete) { util.log('Current version:', util.colors.cyan(package.version)); var choices = ['major', 'premajor', 'minor', 'preminor', 'patch', 'prepatch', 'prerelease'].map(function(versionType) { return versionType + ' (v' + semver.inc(package.version, versionType) + ')'; }); inquirer.prompt({ type: 'list', name: 'version', message: 'What version update would you like?', choices: choices }, function(res) { var increment = res.version.split(' ')[0], newVersion = semver.inc(package.version, increment); // Set the new versions into the bower/package object package.version = newVersion; bower.version = newVersion; // Write these to their own files, then build the output fs.writeFileSync('package.json', JSON.stringify(package, null, 2)); fs.writeFileSync('bower.json', JSON.stringify(bower, null, 2)); complete(); }); } function jshintTask() { return gulp.src(srcDir + '**/*.js') .pipe(jshint('config.jshintrc')) .pipe(jshint.reporter('jshint-stylish')) .pipe(jshint.reporter('fail')); }
{ "content_hash": "879e8edb989a662b012637d232aca4bb", "timestamp": "", "source": "github", "line_count": 82, "max_line_length": 121, "avg_line_length": 30.23170731707317, "alnum_prop": 0.6434045986284792, "repo_name": "etilextreval/panel_REF", "id": "00069f8cd1fdb75dccc03ef2a5d45ced50ff12cb", "size": "2724", "binary": false, "copies": "4", "ref": "refs/heads/master", "path": "public/javascripts/chartjs-plugin-zoom/gulpfile.js", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "1678" }, { "name": "HTML", "bytes": "63498" }, { "name": "JavaScript", "bytes": "260924" } ], "symlink_target": "" }
// // Copyright (C) OpenSim Ltd. // // This program is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public License // as published by the Free Software Foundation; either version 2 // of the License, or (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU Lesser General Public License for more details. // // You should have received a copy of the GNU Lesser General Public License // along with this program; if not, see <http://www.gnu.org/licenses/>. // #ifndef __INET_IEPENERGYGENERATOR_H #define __INET_IEPENERGYGENERATOR_H #include "inet/power/contract/IEnergyGenerator.h" namespace inet { namespace power { /** * TODO * * See the corresponding NED file for more details. * * @author Levente Meszaros */ class INET_API IEpEnergyGenerator : public virtual IEnergyGenerator { public: /** * The signal that is used to publish power generation changes. */ static simsignal_t powerGenerationChangedSignal; public: /** * Returns the power generation in the range [0, +infinity). */ virtual W getPowerGeneration() const = 0; }; } // namespace power } // namespace inet #endif // ifndef __INET_IEPENERGYGENERATOR_H
{ "content_hash": "5c631001b8654e58d63b7c0b7379b96e", "timestamp": "", "source": "github", "line_count": 54, "max_line_length": 75, "avg_line_length": 26.24074074074074, "alnum_prop": 0.7177134791813691, "repo_name": "LarryNguyen/ECSimpp", "id": "4a3e6c7cfc16836e3b8810004dbfbe3a1de7523c", "size": "1417", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "INET_EC/power/contract/IEpEnergyGenerator.h", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "C", "bytes": "61045" }, { "name": "C++", "bytes": "18067164" }, { "name": "Lex", "bytes": "13424" }, { "name": "Makefile", "bytes": "6640" }, { "name": "Objective-C", "bytes": "4651" }, { "name": "Shell", "bytes": "173" }, { "name": "Yacc", "bytes": "67181" } ], "symlink_target": "" }
import { createBatchResolver, ResolverFunction } from "graphql-resolve-batch"; interface SomeTestSource { someSourceProp: string; } interface SomeTestArgs { someArg: string; } interface SomeTestContext { someContextProp: string; } interface SomeTestResult { someTestResultProp: string; } const withSourceAndResultTyped = createBatchResolver< SomeTestSource, SomeTestResult >((sources, _, __) => { return sources.map(source => { const res: SomeTestResult = { someTestResultProp: "" }; return res; }); }); const withSourceAndResultTypedAsPromise = createBatchResolver< SomeTestSource, SomeTestResult >((sources, _, __) => { // $ExpectType ReadonlyArray<SomeTestSource> const verifySources = sources; return sources.map(source => { return new Promise<SomeTestResult>(resolve => { const res: SomeTestResult = { someTestResultProp: "" }; resolve(res); }); }); }); const withSourceAndArgsAndResultTyped = createBatchResolver< SomeTestSource, SomeTestResult, SomeTestArgs >((sources, args, _) => { // $ExpectType ReadonlyArray<SomeTestSource> const verifySources = sources; // $ExpectType string const verifyArgs = args.someArg; return sources.map(source => { return new Promise<SomeTestResult>(resolve => { const res: SomeTestResult = { someTestResultProp: "" }; resolve(res); }); }); }); const withSourceAndArgsAndContextTyped = createBatchResolver< SomeTestSource, SomeTestResult, SomeTestArgs, SomeTestContext >((sources, args, context) => { // $ExpectType ReadonlyArray<SomeTestSource> const verifySources = sources; // $ExpectType string const verifyArgs = args.someArg; // $ExpectType string const verifyContext = context.someContextProp; return sources.map(source => { return new Promise<SomeTestResult>(resolve => { const res: SomeTestResult = { someTestResultProp: "" }; resolve(res); }); }); });
{ "content_hash": "f23a3799d91f89395a3091c0c43eabd1", "timestamp": "", "source": "github", "line_count": 93, "max_line_length": 78, "avg_line_length": 23.602150537634408, "alnum_prop": 0.6227790432801822, "repo_name": "chrootsu/DefinitelyTyped", "id": "1e9a2395a49db02379aed40036a408124ed5584b", "size": "2195", "binary": false, "copies": "5", "ref": "refs/heads/master", "path": "types/graphql-resolve-batch/graphql-resolve-batch-tests.ts", "mode": "33188", "license": "mit", "language": [ { "name": "JavaScript", "bytes": "6462" }, { "name": "TypeScript", "bytes": "23874586" } ], "symlink_target": "" }
from direct.distributed import DistributedObject from direct.directnotify import DirectNotifyGlobal from toontown.toonbase import ToontownGlobals from pandac.PandaModules import * from math import * import math from direct.fsm.FSM import FSM from toontown.minigame import ArrowKeys from direct.showbase import PythonUtil from direct.task import Task from direct.distributed.ClockDelta import * import BuildGeometry from toontown.golf import GolfGlobals import random, time def scalp(vec, scal): vec0 = vec[0] * scal vec1 = vec[1] * scal vec2 = vec[2] * scal vec = Vec3(vec0, vec1, vec2) def length(vec): return sqrt(vec[0] ** 2 + vec[1] ** 2 + vec[2] ** 2) class PhysicsWorldBase: notify = DirectNotifyGlobal.directNotify.newCategory('DistributedPhysicsWorld') def __init__(self, canRender = 0): self.canRender = canRender self.world = OdeWorld() self.space = OdeSimpleSpace() self.contactgroup = OdeJointGroup() self.bodyList = [] self.geomList = [] self.massList = [] self.rayList = [] self.showContacts = 0 self.jointMarkers = [] self.jointMarkerCount = 64 self.meshDataList = [] self.geomDataList = [] self.commonObjectInfoDict = {} self.maxColCount = 0 if self.canRender: self.odePandaRelationList = self.bodyList self.root = render.attachNewNode('physics root node') else: self.root = NodePath('physics root node') self.placerNode = self.root.attachNewNode('Placer') self.subPlacerNode = self.placerNode.attachNewNode('Placer Sub Node') self.commonObjectDict = {} self.commonId = 0 self.worldAttach = self.root.attachNewNode('physics geom attach point') self.timingCycleLength = 10.0 self.timingCycleOffset = 0.0 self.timingSimTime = 0.0 self.FPS = 90.0 self.refFPS = 60.0 self.DTAStep = 1.0 / self.FPS self.refCon = 1.2 self.collisionEventName = 'ode-collision-%d' % id(self) self.space.setCollisionEvent(self.collisionEventName) self.accept(self.collisionEventName, self.__collisionHandler) def delete(self): self.notify.debug('Max Collision Count was %s' % self.maxColCount) self.stopSim() self.commonObjectDict = None if self.canRender: for pair in self.odePandaRelationList: pair[0].removeNode() pair[1].destroy() self.odePandaRelationList = None else: for body in self.bodyList: body[1].destroy() self.bodyList = None for mass in self.massList: mass = None for geom in self.geomList: geom.destroy() geom = None for ray in self.rayList: ray.destroy() ray = None self.placerNode.removeNode() self.root.removeNode() for marker in self.jointMarkers: marker.removeNode() self.jointMarkers = None for data in self.geomDataList: data.destroy() for data in self.meshDataList: data.destroy() self.floor.destroy() self.floor = None self.contactgroup.empty() self.world.destroy() self.space.destroy() self.world = None self.space = None self.ignore(self.collisionEventName) def setupSimulation(self): self.world.setAutoDisableFlag(0) self.world.setAutoDisableLinearThreshold(0.15) self.world.setAutoDisableAngularThreshold(0.15) self.world.setAutoDisableSteps(2) self.world.setGravity(0, 0, -25) self.world.setErp(0.8) self.world.setCfm(1e-05) self.world.initSurfaceTable(5) self.world.setSurfaceEntry(0, 0, 150, 0.05, 0.1, 0.9, 1e-05, 0.0, 0.4 / self.refCon) self.world.setSurfaceEntry(1, 1, 1500, 0.05, 0.1, 0.9, 1e-05, 0.0, 0.001 / self.refCon) self.world.setSurfaceEntry(2, 2, 150, 0.05, 0.1, 0.9, 1e-05, 0.0, 0.4 / self.refCon) self.world.setSurfaceEntry(0, 2, 150, 0.05, 0.1, 0.9, 1e-05, 0.0, 0.4 / self.refCon) self.world.setSurfaceEntry(0, 3, 150, 0.0, 0.1, 0.9, 1e-05, 0.0, 0.4 / self.refCon) self.world.setSurfaceEntry(1, 3, 150, 0.0, 99.1, 0.9, 1e-05, 0.0, 1.0 / self.refCon) self.world.setSurfaceEntry(2, 3, 150, 0.0, 9.1, 0.9, 1e-05, 0.0, 0.4 / self.refCon) self.world.setSurfaceEntry(3, 3, 150, 0.0, 9.1, 0.9, 1e-05, 0.0, 0.4 / self.refCon) self.world.setSurfaceEntry(4, 4, 150, 0.0, 9.1, 0.9, 1e-05, 0.0, 0.4 / self.refCon) self.world.setSurfaceEntry(1, 4, 150, 0.0, 99.1, 0.9, 1e-05, 0.0, 0.001 / self.refCon) self.world.setSurfaceEntry(pos1=0, pos2=1, mu=80, bounce=0.15, bounce_vel=0.1, soft_erp=0.9, soft_cfm=1e-05, slip=0.0, dampen=0.35 / self.refCon) self.world.setSurfaceEntry(pos1=2, pos2=1, mu=1500, bounce=0.9, bounce_vel=0.01, soft_erp=0.9, soft_cfm=1e-05, slip=0.0, dampen=0.001 / self.refCon) self.floor = OdePlaneGeom(self.space, Vec4(0.0, 0.0, 1.0, -20.0)) self.floor.setCollideBits(BitMask32(0)) self.floor.setCategoryBits(BitMask32(3840)) self.space.setAutoCollideWorld(self.world) self.space.setAutoCollideJointGroup(self.contactgroup) self.world.setQuickStepNumIterations(8) self.DTA = 0.0 self.frameCounter = 0 if self.canRender: for count in xrange(self.jointMarkerCount): testMarker = render.attachNewNode('Joint Marker') ballmodel = loader.loadModel('phase_3/models/misc/sphere') ballmodel.reparentTo(testMarker) ballmodel.setScale(0.1) testMarker.setPos(0.0, 0.0, -100.0) self.jointMarkers.append(testMarker) def setTimingCycleLength(self, time): self.timingCycleLength = time def getTimingCycleLength(self): return self.timingCycleLength def getCycleTime(self, doprint = 0): cycleTime = (globalClock.getRealTime() + self.timingCycleOffset) % self.timingCycleLength if doprint: print 'Get Cycle Time %s' % cycleTime return cycleTime def setTimeIntoCycle(self, time, doprint = 0): trueCycleTime = globalClock.getRealTime() % self.timingCycleLength self.timingCycleOffset = time - trueCycleTime if doprint: self.notify.debug('Set Cycle Time %s' % self.timingCycleOffset) self.notify.debug('SET cycle time %s' % ((globalClock.getRealTime() + self.timingCycleOffset) % self.timingCycleLength)) def getSimCycleTime(self): return return self.timingSimTime % self.timingCycleLength def startSim(self): taskMgr.add(self.__simulationTask, 'simulation task') def stopSim(self): taskMgr.remove('simulation task') def __simulationTask(self, task): self.DTA += globalClock.getDt() self.frameCounter += 1 if self.frameCounter >= 10: self.frameCounter = 0 startTime = globalClock.getRealTime() colCount = 0 while self.DTA >= self.DTAStep: self.DTA -= self.DTAStep self.preStep() self.simulate() self.postStep() if self.canRender: self.placeBodies() if self.frameCounter == 0: endTime = globalClock.getRealTime() - startTime return task.cont def __collisionHandler(self, entry): self.colEntries.append(entry) def simulate(self): self.colEntries = [] self.space.autoCollide() # We need the callbacks processed now, before we try to look at colEntries, so: eventMgr.doEvents() self.colCount = len(self.colEntries) if self.maxColCount < self.colCount: self.maxColCount = self.colCount self.notify.debug('New Max Collision Count %s' % self.maxColCount) self.world.quickStep(self.DTAStep) for bodyPair in self.bodyList: self.world.applyDampening(self.DTAStep, bodyPair[1]) self.contactgroup.empty() self.commonObjectControl() self.timingSimTime = self.timingSimTime + self.DTAStep def placeBodies(self): for pair in self.odePandaRelationList: pandaNodePathGeom = pair[0] odeBody = pair[1] if pandaNodePathGeom: pandaNodePathGeom.setPos(odeBody.getPosition()) rotation = odeBody.getRotation() * (180.0 / math.pi) pandaNodePathGeom.setQuat(Quat(odeBody.getQuaternion()[0], odeBody.getQuaternion()[1], odeBody.getQuaternion()[2], odeBody.getQuaternion()[3])) def preStep(self): pass def postStep(self): if self.showContacts and self.canRender: for count in xrange(self.jointMarkerCount): pandaNodePathGeom = self.jointMarkers[count] if count < self.colCount: pandaNodePathGeom.setPos(self.space.getContactData(count * 3 + 0), self.space.getContactData(count * 3 + 1), self.space.getContactData(count * 3 + 2)) else: pandaNodePathGeom.setPos(0.0, 0.0, -100.0) def commonObjectControl(self): time = self.getCycleTime() for key in self.commonObjectDict: if key not in self.commonObjectInfoDict: self.commonObjectInfoDict[key] = None entry = self.commonObjectDict[key] if entry[1] in [2, 4]: type = entry[1] body = entry[2] motor = entry[3] timeData = entry[4] forceData = entry[5] eventData = entry[6] model = entry[7] force = 0.0 for index in xrange(len(timeData)): if index == len(timeData) - 1 and timeData[index] < time or timeData[index] < time and timeData[index + 1] > time: force = forceData[index] event = eventData[index] if event != self.commonObjectInfoDict[key]: self.commonObjectEvent(key, model, type, force, event) self.commonObjectInfoDict[key] = event motor.setParamVel(force) return def commonObjectEvent(self, key, model, type, force, event): self.notify.debug('commonObjectForceEvent %s %s %s %s %s' % (key, model, type, force, event)) def getCommonObjectData(self): objectStream = [(0, 0, self.getCycleTime(), 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0)] for key in self.commonObjectDict: objectPair = self.commonObjectDict[key] object = objectPair[2] pos3 = object.getPosition() quat4 = object.getQuaternion() anV3 = object.getAngularVel() lnV3 = object.getLinearVel() data = (objectPair[0], objectPair[1], pos3[0], pos3[1], pos3[2], quat4[0], quat4[1], quat4[2], quat4[3], anV3[0], anV3[1], anV3[2], lnV3[0], lnV3[1], lnV3[2]) objectStream.append(data) if len(objectStream) <= 1: data = (0, 99, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0) objectStream.append(data) return objectStream def useCommonObjectData(self, objectData, enable = 1): if not objectData: return if objectData[1][1] == 99: return time = objectData[0] self.setTimeIntoCycle(time[2]) if time[2] > self.timingCycleLength: pass for dataIndex in xrange(1, len(objectData)): data = objectData[dataIndex] commonObject = self.commonObjectDict[data[0]] commonObject[2].setPosition(data[2], data[3], data[4]) commonObject[2].setQuaternion(Quat(data[5], data[6], data[7], data[8])) commonObject[2].setAngularVel(data[9], data[10], data[11]) commonObject[2].setLinearVel(data[12], data[13], data[14]) if enable: commonObject[2].enable() else: commonObject[2].disable() def createCommonObject(self, type, commonId, pos, hpr, sizeX = 0, sizeY = 0, moveDistance = 0): if commonId == None: commonId = self.commonId self.commonId += 1 vPos = Point3(float(pos[0]), float(pos[1]), float(pos[2])) vHpr = Vec3(float(hpr[0]), float(hpr[1]), float(hpr[2])) rHpr = Vec3(float(hpr[0]), float(hpr[1]), float(hpr[2])) self.placerNode.setHpr(vHpr) self.placerNode.setPos(vPos) if type == 0: model, box = self.createBox(self.world, self.space, 10.0, 5.0, 5.0, 5.0) box.setPosition(vPos) self.placerNode.setHpr(vHpr) box.setQuaternion(self.placerNode.getQuat()) self.commonObjectDict[commonId] = (commonId, type, box) elif type == 1: model, cross = self.createCross(self.world, self.space, 1.0, 3.0, 12.0, 2.0, 2) motor = OdeHingeJoint(self.world) cross.setPosition(vPos) cross.setQuaternion(self.placerNode.getQuat()) ourAxis = render.getRelativeVector(self.placerNode, Vec3(0, 0, 1)) motor.setParamVel(1.5) motor.setParamFMax(500000000.0) boxsize = Vec3(1.0, 1.0, 1.0) motor.attach(0, cross) motor.setAnchor(vPos) motor.setAxis(ourAxis) self.cross = cross cross.enable() self.commonObjectDict[commonId] = (commonId, type, cross) elif type == 2: ourAxis = render.getRelativeVector(self.placerNode, Vec3(0, 0, 1)) model, box = self.createBox(self.world, self.space, 10.0, 5.0, 5.0, 5.0, 2) box.setPosition(vPos) box.setQuaternion(self.placerNode.getQuat()) motor = OdeSliderJoint(self.world) motor.attach(box, 0) motor.setAxis(ourAxis) motor.setParamVel(3.0) motor.setParamFMax(5000000.0) motor.setParamHiStop(10.0) motor.setParamLoStop(-10.0) timeData = (0.0, 5.0) forceData = (3.0, -3.0) eventData = (1, 2) self.commonObjectDict[commonId] = (commonId, type, box, motor, timeData, forceData, eventData, model) elif type == 3: vPos = Point3(float(pos[0]), float(pos[1]), float(pos[2])) vHpr = Vec3(float(hpr[0]), float(hpr[1]), float(hpr[2])) self.placerNode.setHpr(vHpr) self.placerNode.setPos(vPos) self.subPlacerNode.setPos(0, 0, 0) if self.canRender: myModel = loader.loadModel('phase_6/models/golf/golf_windmill_b') else: myModel = loader.loadModel('phase_6/models/golf/golf_windmill_b.bam') myModel.reparentTo(self.root) myModel.setPos(vPos) myModel.setHpr(vHpr) millFan = myModel.find('**/windmillFan0') millBase = myModel.find('**/arm') rod = myModel.find('**/rod') rod.wrtReparentTo(millBase) self.windmillFanNodePath = millFan self.windmillBaseNodePath = millBase millData = OdeTriMeshData(millBase) millGeom = OdeTriMeshGeom(self.space, millData) self.meshDataList.append(millData) millGeom.setPosition(self.subPlacerNode.getPos(self.root)) millGeom.setQuaternion(self.subPlacerNode.getQuat()) millGeom.setCollideBits(BitMask32(251658240)) millGeom.setCategoryBits(BitMask32(8388608)) self.space.setCollideId(millGeom, 8) vPos = Point3(float(pos[0]), float(pos[1]), float(pos[2]) + 5) vHpr = Vec3(float(hpr[0]), float(hpr[1] + 90), float(hpr[2]) - 90) self.placerNode.setHpr(vHpr) self.placerNode.setPos(vPos) self.subPlacerNode.setPos(-1, 0, 0.0) model, cross = self.createPinWheel(self.world, self.space, 10.0, 1.6, 4.0, 0.6, 5, 3.7, 1.2, 1, millFan, (0, 0, 90), (-4.6, -0.5, -0.25), 20) self.placerNode.setHpr(vHpr) self.placerNode.setPos(vPos) self.subPlacerNode.setPos(-1, 0, 0.0) motor = OdeHingeJoint(self.world) cross.setPosition(self.subPlacerNode.getPos(self.root)) cross.setQuaternion(self.placerNode.getQuat()) ourAxis = self.root.getRelativeVector(self.subPlacerNode, Vec3(0, 0, 1)) motor.setParamVel(1.0) motor.setParamFMax(50000.0) boxsize = Vec3(1.0, 1.0, 1.0) motor.attach(0, cross) motor.setAnchor(self.subPlacerNode.getPos(self.root)) motor.setAxis(ourAxis) self.cross = cross cross.enable() self.commonObjectDict[commonId] = (commonId, type, cross) elif type == 4: ourAxis = self.root.getRelativeVector(self.placerNode, Vec3(0, 1, 0)) model, box = self.createBox(self.world, self.space, 50.0, sizeX, sizeY, 1.0, 2) box.setPosition(vPos) box.setQuaternion(self.placerNode.getQuat()) motor = OdeSliderJoint(self.world) motor.attach(box, 0) motor.setAxis(ourAxis) motor.setParamVel(moveDistance / 4.0) motor.setParamFMax(25000.0) motor.setParamHiStop(moveDistance) motor.setParamLoStop(0) timeData = (0.0, 1.0, 5.0, 6.0) forceData = (-moveDistance / 4.0, moveDistance / 4.0, moveDistance / 4.0, -moveDistance / 4.0) eventData = (-1, 1, -2, 2) radius = moveDistance + sizeY * 0.5 self.commonObjectDict[commonId] = (commonId, type, box, motor, timeData, forceData, eventData, model, radius) return [type, commonId, (pos[0], pos[1], pos[2]), (hpr[0], hpr[1], hpr[2]), sizeX, sizeY, moveDistance] def createSphere(self, world, space, density, radius, ballIndex = None): self.notify.debug('create sphere index %s' % ballIndex) body = OdeBody(world) M = OdeMass() M.setSphere(density, radius) body.setMass(M) body.setPosition(0, 0, -100) geom = OdeSphereGeom(space, radius) self.space.setSurfaceType(geom, 1) self.notify.debug('collide ID is %s' % self.space.setCollideId(geom, 42)) self.massList.append(M) self.geomList.append(geom) if ballIndex == 1: self.notify.debug('1') geom.setCollideBits(BitMask32(16777215)) geom.setCategoryBits(BitMask32(4278190080L)) elif ballIndex == 2: self.notify.debug('2') geom.setCollideBits(BitMask32(16777215)) geom.setCategoryBits(BitMask32(4278190080L)) elif ballIndex == 3: self.notify.debug('3') geom.setCollideBits(BitMask32(16777215)) geom.setCategoryBits(BitMask32(4278190080L)) elif ballIndex == 4: self.notify.debug('4') geom.setCollideBits(BitMask32(16777215)) geom.setCategoryBits(BitMask32(4278190080L)) else: geom.setCollideBits(BitMask32(4294967295L)) geom.setCategoryBits(BitMask32(4294967295L)) geom.setBody(body) if self.notify.getDebug(): self.notify.debug('golf ball geom id') geom.write() self.notify.debug(' -') self.notify.debug('Collide Bits %s' % geom.getCollideBits()) if self.canRender: testball = render.attachNewNode('Ball Holder') ballmodel = loader.loadModel('phase_6/models/golf/golf_ball') ballmodel.reparentTo(testball) ballmodel.setColor(*GolfGlobals.PlayerColors[ballIndex - 1]) testball.setPos(0, 0, -100) self.odePandaRelationList.append((testball, body)) else: testball = None self.bodyList.append((None, body)) return (testball, body, geom) def createBox(self, world, space, density, lx, ly, lz, colOnlyBall = 0): body = OdeBody(self.world) M = OdeMass() M.setSphere(density, 0.3 * (lx + ly + lz)) body.setMass(M) boxsize = Vec3(lx, ly, lz) geom = OdeBoxGeom(space, boxsize) geom.setBody(body) self.space.setSurfaceType(geom, 0) self.space.setCollideId(geom, 7) self.massList.append(M) self.geomList.append(geom) if colOnlyBall: geom.setCollideBits(BitMask32(251658240)) geom.setCategoryBits(BitMask32(0)) elif colOnlyBall == 2: geom.setCollideBits(BitMask32(0)) geom.setCategoryBits(BitMask32(0)) if self.canRender: color = random.choice([Vec4(1.0, 0.0, 0.5, 1.0), Vec4(0.5, 0.5, 1.0, 1.0), Vec4(0.5, 1.0, 0.5, 1.0)]) boxsize = Vec3(lx, ly, lz) boxNodePathGeom, t1, t2 = BuildGeometry.addBoxGeom(self.worldAttach, lx, ly, lz, color, 1) boxNodePathGeom.setPos(0, 0, -100) self.odePandaRelationList.append((boxNodePathGeom, body)) else: boxNodePathGeom = None self.bodyList.append((None, body)) return (boxNodePathGeom, body) def createCross(self, world, space, density, lx, ly, lz, colOnlyBall = 0, attachedGeo = None, aHPR = None, aPos = None): body = OdeBody(self.world) M = OdeMass() M.setBox(density, lx, ly, lz) body.setMass(M) body.setFiniteRotationMode(1) boxsize = Vec3(lx, ly, lz) boxsize2 = Vec3(ly, lx, lz) geom = OdeBoxGeom(space, boxsize) geom.setBody(body) self.space.setSurfaceType(geom, 0) self.space.setCollideId(geom, 13) geom2 = OdeBoxGeom(space, boxsize2) geom2.setBody(body) self.space.setSurfaceType(geom2, 0) self.space.setCollideId(geom2, 26) self.massList.append(M) self.geomList.append(geom) self.geomList.append(geom2) self.odePandaRelationList.append((boxNodePathGeom, body)) if colOnlyBall == 1: geom.setCollideBits(BitMask32(251658240)) geom.setCategoryBits(BitMask32(0)) geom2.setCollideBits(BitMask32(251658240)) geom2.setCategoryBits(BitMask32(0)) elif colOnlyBall == 2: geom.setCollideBits(BitMask32(0)) geom.setCategoryBits(BitMask32(0)) geom2.setCollideBits(BitMask32(0)) geom2.setCategoryBits(BitMask32(0)) if self.canRender: boxNodePathGeom, t1, t2 = BuildGeometry.addBoxGeom(self.worldAttach, lx, ly, lz, Vec4(1.0, 1.0, 1.0, 1.0), 1) boxNodePathGeom.setPos(0, 0, -100) boxNodePathGeom2, t1, t2 = BuildGeometry.addBoxGeom(boxNodePathGeom, ly, lx, lz, Vec4(1.0, 1.0, 1.0, 1.0), 1) boxNodePathGeom2.setPos(0, 0, 0) if attachedGeo: attachedGeo.reparentTo(boxNodePathGeom) attachedGeo.setHpr(0, 0, 90) attachedGeo.setPos(-4.8, 0, -2.0) self.odePandaRelationList.append((boxNodePathGeom, body)) else: boxNodePathGeom = None self.bodyList.append((None, body)) return (boxNodePathGeom, body) def createCross2(self, world, space, density, lx, ly, lz, latSlide, colOnlyBall = 0, attachedGeo = None, aHPR = None, aPos = None): body = OdeBody(self.world) M = OdeMass() M.setBox(density, lx, ly, lz) body.setMass(M) body.setFiniteRotationMode(1) boxsize = Vec3(lx, ly * 0.5, lz) boxsize2 = Vec3(ly * 0.5, lx, lz) geom = OdeBoxGeom(space, boxsize) geom.setBody(body) geom.setOffsetPosition(-latSlide, ly * 0.25, 0) self.space.setSurfaceType(geom, 0) self.space.setCollideId(geom, 13) geom2 = OdeBoxGeom(space, boxsize2) geom2.setBody(body) geom2.setOffsetPosition(ly * 0.25, latSlide, 0) self.space.setSurfaceType(geom2, 0) self.space.setCollideId(geom2, 13) geom3 = OdeBoxGeom(space, boxsize) geom3.setBody(body) geom3.setOffsetPosition(latSlide, -ly * 0.25, 0) self.space.setSurfaceType(geom3, 0) self.space.setCollideId(geom3, 13) geom4 = OdeBoxGeom(space, boxsize2) geom4.setBody(body) geom4.setOffsetPosition(-ly * 0.25, -latSlide, 0) self.space.setSurfaceType(geom4, 0) self.space.setCollideId(geom4, 13) self.massList.append(M) self.geomList.append(geom) self.geomList.append(geom2) self.geomList.append(geom3) self.geomList.append(geom4) if colOnlyBall == 1: geom.setCollideBits(BitMask32(251658240)) geom.setCategoryBits(BitMask32(0)) geom2.setCollideBits(BitMask32(251658240)) geom2.setCategoryBits(BitMask32(0)) geom3.setCollideBits(BitMask32(251658240)) geom3.setCategoryBits(BitMask32(0)) geom4.setCollideBits(BitMask32(251658240)) geom4.setCategoryBits(BitMask32(0)) elif colOnlyBall == 2: geom.setCollideBits(BitMask32(0)) geom.setCategoryBits(BitMask32(0)) geom2.setCollideBits(BitMask32(0)) geom2.setCategoryBits(BitMask32(0)) geom3.setCollideBits(BitMask32(0)) geom3.setCategoryBits(BitMask32(0)) geom4.setCollideBits(BitMask32(0)) geom4.setCategoryBits(BitMask32(0)) if self.canRender: someNodePathGeom = render.attachNewNode('pinwheel') if attachedGeo: attachedGeo.reparentTo(someNodePathGeom) attachedGeo.setHpr(aHPR[0], aHPR[1], aHPR[2]) attachedGeo.setPos(aPos[0], aPos[1], aPos[2]) boxNodePathGeom, t1, t2 = BuildGeometry.addBoxGeom(someNodePathGeom, lx, ly * 0.5, lz, Vec4(1.0, 1.0, 1.0, 1.0), 1) boxNodePathGeom.setPos(-latSlide, ly * 0.25, 0) boxNodePathGeom2, t1, t2 = BuildGeometry.addBoxGeom(someNodePathGeom, ly * 0.5, lx, lz, Vec4(1.0, 1.0, 1.0, 1.0), 1) boxNodePathGeom2.setPos(ly * 0.25, latSlide, 0) boxNodePathGeom3, t1, t2 = BuildGeometry.addBoxGeom(someNodePathGeom, lx, ly * 0.5, lz, Vec4(1.0, 1.0, 1.0, 1.0), 1) boxNodePathGeom3.setPos(latSlide, -ly * 0.25, 0) boxNodePathGeom4, t1, t2 = BuildGeometry.addBoxGeom(someNodePathGeom, ly * 0.5, lx, lz, Vec4(1.0, 1.0, 1.0, 1.0), 1) boxNodePathGeom4.setPos(-ly * 0.25, -latSlide, 0) self.odePandaRelationList.append((someNodePathGeom, body)) else: someNodePathGeom = None self.bodyList.append((None, body)) return (someNodePathGeom, body) def createPinWheel(self, world, space, density, lx, ly, lz, numBoxes, disV, disH, colOnlyBall = 0, attachedGeo = None, aHPR = None, aPos = None, offRot = 0): body = OdeBody(self.world) M = OdeMass() M.setBox(density, lx, ly, lz) body.setMass(M) body.setFiniteRotationMode(1) boxsize = Vec3(lx, ly * 0.5, lz) boxsize2 = Vec3(ly * 0.5, lx, lz) self.massList.append(M) self.placerNode.setPos(0, 0, 0) self.placerNode.setHpr(0, 0, 0) self.subPlacerNode.setHpr(0, 0, 0) self.subPlacerNode.setPos(disH, disV, 0) if self.canRender: someNodePathGeom = render.attachNewNode('pinwheel') else: someNodePathGeom = self.root.attachNewNode('pinwheel') for num in xrange(numBoxes): spin = 360.0 * float(num) / float(numBoxes) + float(offRot) self.placerNode.setH(spin) geom = OdeBoxGeom(space, boxsize) geom.setBody(body) geom.setOffsetPosition(self.subPlacerNode.getPos(self.root)) geom.setOffsetQuaternion(self.subPlacerNode.getQuat(self.root)) self.geomList.append(geom) self.space.setSurfaceType(geom, 0) self.space.setCollideId(geom, 13) if colOnlyBall == 1: geom.setCollideBits(BitMask32(251658240)) geom.setCategoryBits(BitMask32(0)) elif colOnlyBall == 2: geom.setCollideBits(BitMask32(0)) geom.setCategoryBits(BitMask32(0)) if not attachedGeo: boxNodePathGeom, t1, t2 = BuildGeometry.addBoxGeom(someNodePathGeom, lx, ly * 0.5, lz, Vec4(1.0, 1.0, 1.0, 1.0), 1) boxNodePathGeom.setPos(self.subPlacerNode.getPos(self.root)) boxNodePathGeom.setHpr(self.subPlacerNode.getHpr(self.root)) if attachedGeo and self.canRender: attachedGeo.reparentTo(someNodePathGeom) attachedGeo.setHpr(aHPR[0], aHPR[1], aHPR[2]) attachedGeo.setPos(aPos[0], aPos[1], aPos[2]) if self.canRender: self.odePandaRelationList.append((someNodePathGeom, body)) else: someNodePathGeom = None self.bodyList.append((None, body)) return (someNodePathGeom, body) def attachMarker(self, body): if self.canRender: testMarker = render.attachNewNode('Joint Marker') ballmodel = loader.loadModel('models/misc/sphere') ballmodel.reparentTo(testMarker) ballmodel.setScale(0.25) testMarker.setPos(0.0, 0.0, -100.0) self.odePandaRelationList.append((testMarker, body))
{ "content_hash": "c93b494e620dd39b1b6d77bc102b4a44", "timestamp": "", "source": "github", "line_count": 731, "max_line_length": 170, "avg_line_length": 41.56497948016416, "alnum_prop": 0.5822472353870458, "repo_name": "ToonTownInfiniteRepo/ToontownInfinite", "id": "edc657c96d0a45d6a0761763153f3e97d4bab19e", "size": "30384", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "toontown/golf/PhysicsWorldBase.py", "mode": "33188", "license": "mit", "language": [ { "name": "C", "bytes": "1703277" }, { "name": "C#", "bytes": "9892" }, { "name": "C++", "bytes": "5468044" }, { "name": "Emacs Lisp", "bytes": "210083" }, { "name": "F#", "bytes": "4611" }, { "name": "JavaScript", "bytes": "7003" }, { "name": "Objective-C", "bytes": "23212" }, { "name": "Puppet", "bytes": "5245" }, { "name": "Python", "bytes": "34010215" }, { "name": "Shell", "bytes": "11192" }, { "name": "Tcl", "bytes": "1981257" } ], "symlink_target": "" }
import java.util.ArrayList; import java.util.Collection; import java.util.List; import java.util.PriorityQueue; /** * This class represents worst-fit algorithms for allocating files to disks. * * @author rcd */ public class WorstFitAlgorithm { public static final String WORST_FIT_METHOD = "worst-fit"; private String myDescription; /** * Default constructor */ public WorstFitAlgorithm () { this(WORST_FIT_METHOD); } /** * Create with given descriptor. */ public WorstFitAlgorithm (String description) { myDescription = description; } /** * Allocates given files to the fewest number of disks. * * @param data collection of files to be allocated to disks */ public void fitDisksAndPrint (List<Integer> data, StaticAbstractMultiInheritedGlobalInterface i) { List<Integer> copy = new ArrayList<>(i.operate(data)); // organizeData(copy); Collection<Disk> disks = addFiles(copy); printResults(disks, myDescription); } /** * Arrange given data in preparation for fitting disks. * * @param disks collection of disks to be printed */ protected void organizeData (List<Integer> data) { // by default, do nothing } // add files to the collection of Disks private Collection<Disk> addFiles (List<Integer> data) { PriorityQueue<Disk> pq = new PriorityQueue<>(); pq.add(new Disk()); for (Integer size : data) { Disk d = pq.peek(); if (d.canFit(size)) { pq.poll(); } else { d = new Disk(); } d.add(size); pq.add(d); } return pq; } // print contents of given collection and a header, description private void printResults (Collection<Disk> disks, String description) { System.out.println(); System.out.println("\n" + description + " method"); System.out.println("number of disks used: " + disks.size()); for (Disk d : disks) { System.out.println(d); } } }
{ "content_hash": "1979434461e3ccdf64a31a5c5b8004f4", "timestamp": "", "source": "github", "line_count": 79, "max_line_length": 102, "avg_line_length": 27.29113924050633, "alnum_prop": 0.5913729128014842, "repo_name": "sallymerza/lab_bins", "id": "8718aaf83821a7aaff3d75a19831de7c9cb3d79d", "size": "2156", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/WorstFitAlgorithm.java", "mode": "33188", "license": "mit", "language": [ { "name": "Java", "bytes": "7295" } ], "symlink_target": "" }
FreeCAD add-on for create reinforcing bar in concrete structure ## Rebars in Beam ![screenshot](https://forum.freecadweb.org/download/file.php?id=48134) ![screenshot](https://forum.freecadweb.org/download/file.php?id=48137) ## Rebars in Square Footing
{ "content_hash": "745b981cd2263e0b7a7fb23152f4109a", "timestamp": "", "source": "github", "line_count": 7, "max_line_length": 70, "avg_line_length": 36.285714285714285, "alnum_prop": 0.7755905511811023, "repo_name": "chakkreetiya/FreeCAD-Rebars", "id": "f00c437fc354c3d080ff5ebba0f0353ebc04e2d2", "size": "271", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "README.md", "mode": "33188", "license": "mit", "language": [ { "name": "HTML", "bytes": "176" }, { "name": "Python", "bytes": "37895" } ], "symlink_target": "" }
package net.kuujo.copycat.state; import net.kuujo.copycat.protocol.PingRequest; import net.kuujo.copycat.protocol.PollRequest; import net.kuujo.copycat.protocol.SubmitRequest; import net.kuujo.copycat.protocol.SyncRequest; import net.kuujo.copycat.state.impl.StateLock; import org.vertx.java.core.AsyncResult; import org.vertx.java.core.Handler; import org.vertx.java.core.impl.DefaultFutureResult; import org.vertx.java.core.logging.Logger; import org.vertx.java.core.logging.impl.LoggerFactory; /** * A follower state. * * @author Jordan Halterman */ class Follower extends State { private static final Logger logger = LoggerFactory.getLogger(Follower.class); private long timeoutTimer; private final StateLock lock = new StateLock(); /** * An election timeout handler. */ private final Handler<Long> timeoutHandler = new Handler<Long>() { @Override public void handle(Long timerID) { // If the node has not yet voted for anyone then transition to // candidate and start a new election. if (context.votedFor() == null) { logger.info("Election timed out. Transitioning to candidate."); context.transition(StateType.CANDIDATE); timeoutTimer = 0; } // Otherwise, if the node voted for a candidate then reset the election // timer. else { resetTimer(); } } }; @Override public void startUp(Handler<AsyncResult<Void>> doneHandler) { resetTimer(); new DefaultFutureResult<Void>((Void) null).setHandler(doneHandler); } /** * Resets the internal election timer. */ private void resetTimer() { if (timeoutTimer > 0) { vertx.cancelTimer(timeoutTimer); } // Set the election timeout in a semi-random fashion with the random range // being somewhere between .75 * election timeout and 1.25 * election // timeout. timeoutTimer = vertx.setTimer(context.electionTimeout() - (context.electionTimeout() / 4) + (Math.round(Math.random() * (context.electionTimeout() / 2))), timeoutHandler); } @Override public void ping(PingRequest request) { if (request.term() > context.currentTerm()) { context.currentLeader(request.leader()); context.currentTerm(request.term()); } request.reply(context.currentTerm()); resetTimer(); } @Override public void sync(final SyncRequest request) { // Reset the election timer. resetTimer(); // Acquire a lock that prevents the local log from being modified // during the sync. lock.acquire(new Handler<Void>() { @Override public void handle(Void _) { doSync(request, new Handler<AsyncResult<Boolean>>() { @Override public void handle(AsyncResult<Boolean> result) { // If the request term is greater than the current term then update // the // current leader and term. if (request.term() > context.currentTerm()) { context.currentLeader(request.leader()); context.currentTerm(request.term()); } // Reply to the request. if (result.failed()) { request.error(result.cause()); } else { request.reply(context.currentTerm(), result.result()); } // Reset the election timer again. resetTimer(); // Release the log lock. lock.release(); } }); } }); } @Override public void poll(final PollRequest request) { doPoll(request, new Handler<AsyncResult<Boolean>>() { @Override public void handle(AsyncResult<Boolean> result) { if (result.failed()) { request.error(result.cause()); } else { request.reply(context.currentTerm(), result.result()); } } }); resetTimer(); } @Override public void submit(SubmitRequest request) { // This node should never receive a submit request. All submits should // be automatically forwarded to the leader. request.error("Not a leader."); } @Override public void shutDown(Handler<AsyncResult<Void>> doneHandler) { if (timeoutTimer > 0) { vertx.cancelTimer(timeoutTimer); timeoutTimer = 0; } new DefaultFutureResult<Void>((Void) null).setHandler(doneHandler); } }
{ "content_hash": "aef4c8ce38671b7eebdfa6ffdd39efd4", "timestamp": "", "source": "github", "line_count": 149, "max_line_length": 93, "avg_line_length": 29.395973154362416, "alnum_prop": 0.6360730593607306, "repo_name": "ngbinh/copycat", "id": "45d76a614bb0de5f5acecacd9193fb89c2e1c8c7", "size": "4990", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "src/main/java/net/kuujo/copycat/state/Follower.java", "mode": "33188", "license": "apache-2.0", "language": [], "symlink_target": "" }
define(function(require, exports, module) { describe('my description', function() { beforeEach(function() { loadFixtures('template.html'); }); it('should succeed', function() { var $node = $('#foo'); console.log($node.text()); expect(true).toBe(true); }); }); });
{ "content_hash": "e623d2db6160ae7fdf1563667713f762", "timestamp": "", "source": "github", "line_count": 16, "max_line_length": 43, "avg_line_length": 19.75, "alnum_prop": 0.5506329113924051, "repo_name": "blitzagency/django-chatterbox", "id": "0912db49ca4bd8d4464fdf490c6d8f1bad0ab569", "size": "316", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "chatterbox/static/chatterbox/js/specs/spec-app.js", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "1745" }, { "name": "HTML", "bytes": "10759" }, { "name": "JavaScript", "bytes": "38264" }, { "name": "Makefile", "bytes": "1540" }, { "name": "Python", "bytes": "209440" }, { "name": "Ruby", "bytes": "3342" }, { "name": "SaltStack", "bytes": "2743" }, { "name": "Scheme", "bytes": "615" } ], "symlink_target": "" }
import config from '../../src/scss'; describe('scssConfig', () => { it('should contain scss loader', () => { expect(config.module.rules[0].test).toEqual(/\.scss$/); }); });
{ "content_hash": "65fb0da2779ccc9aeededbd8b69d4094", "timestamp": "", "source": "github", "line_count": 9, "max_line_length": 59, "avg_line_length": 20.444444444444443, "alnum_prop": 0.5706521739130435, "repo_name": "CAAPIM/webpack-config", "id": "0d563b537c8375df52ea6440c0d5bb99bfbda347", "size": "360", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "tests/unit/scss.test.js", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "206" }, { "name": "HTML", "bytes": "241" }, { "name": "JavaScript", "bytes": "24181" } ], "symlink_target": "" }
/* MACHINE GENERATED FILE, DO NOT EDIT */ package org.lwjgl.opengl; import org.lwjgl.*; import java.nio.*; public final class EXTStencilClearTag { /** * Accepted by the &lt;pname&gt; parameter of GetBooleanv, GetIntegerv, * GetFloatv, and GetDoublev. */ public static final int GL_STENCIL_TAG_BITS_EXT = 0x88F2, GL_STENCIL_CLEAR_TAG_VALUE_EXT = 0x88F3; private EXTStencilClearTag() {} /** * Controls the stencil clear tag state. stencilTagBits is a count of * the number of most-significant stencil buffer bits involved in the * stencil clear tag update. */ public static void glStencilClearTagEXT(int stencilTagBits, int stencilClearTag) { ContextCapabilities caps = GLContext.getCapabilities(); long function_pointer = caps.glStencilClearTagEXT; BufferChecks.checkFunctionAddress(function_pointer); nglStencilClearTagEXT(stencilTagBits, stencilClearTag, function_pointer); } static native void nglStencilClearTagEXT(int stencilTagBits, int stencilClearTag, long function_pointer); }
{ "content_hash": "37c1ee209d44f56d0463557d758ab48a", "timestamp": "", "source": "github", "line_count": 31, "max_line_length": 106, "avg_line_length": 35.38709677419355, "alnum_prop": 0.715587967183227, "repo_name": "ThePlexianNetwork/Grumy", "id": "4f35b59a70a966602ddbd9820628f03c0909688f", "size": "1097", "binary": false, "copies": "17", "ref": "refs/heads/development", "path": "lib/lwjgl/jar/src/generated/org/lwjgl/opengl/EXTStencilClearTag.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "C", "bytes": "2271672" }, { "name": "C++", "bytes": "3076" }, { "name": "GLSL", "bytes": "4415" }, { "name": "Java", "bytes": "9012727" }, { "name": "Objective-C", "bytes": "87796" }, { "name": "Shell", "bytes": "155" } ], "symlink_target": "" }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Windows; using System.Windows.Media.Animation; namespace Inbox2.Framework.UI.Animation { public class Animator { #region PennerDoubleAnimation Helpers /// <summary> /// Starts a PennerDoubleAnimation. /// </summary> /// <param name="element">The DependencyObject containing the property to be animated.</param> /// <param name="prop">The DependencyProperty to animate.</param> /// <param name="type">The PennerDoubleAnimation.Equations easing equation to use.</param> /// <param name="to">The target value.</param> /// <param name="durationMS">Duration of the animation, in milliseconds.</param> /// <param name="callbackFunc">Optional method to be called when animation completes.</param> /// <returns>The AnimationClock used to control the animation.</returns> public static AnimationClock AnimatePenner( DependencyObject element, DependencyProperty prop, PennerDoubleAnimation.Equations type, double to, int durationMS, EventHandler callbackFunc) { return AnimatePenner(element, prop, type, null, to, durationMS, callbackFunc); } /// <summary> /// Starts a PennerDoubleAnimation. /// </summary> /// <param name="element">The DependencyObject containing the property to be animated.</param> /// <param name="prop">The DependencyProperty to animate.</param> /// <param name="type">The PennerDoubleAnimation.Equations easing equation to use.</param> /// <param name="from">Optional start value.</param> /// <param name="to">The target value.</param> /// <param name="durationMS">Duration of the animation, in milliseconds.</param> /// <param name="callbackFunc">Optional method to be called when animation completes.</param> /// <returns>The AnimationClock used to control the animation.</returns> public static AnimationClock AnimatePenner( DependencyObject element, DependencyProperty prop, PennerDoubleAnimation.Equations type, double? from, double to, int durationMS, EventHandler callbackFunc) { double defaultFrom = double.IsNaN((double)element.GetValue(prop)) ? 0 : (double)element.GetValue(prop); PennerDoubleAnimation anim = new PennerDoubleAnimation(type, from.GetValueOrDefault(defaultFrom), to); return Animate(element, prop, anim, durationMS, null, null, callbackFunc); } #endregion #region DoubleAnimation Helpers /// <summary> /// Starts a DoubleAnimation. /// </summary> /// <param name="element">The DependencyObject containing the property to be animated.</param> /// <param name="prop">The DependencyProperty to animate.</param> /// <param name="from">Optional start value.</param> /// <param name="to">The target value.</param> /// <param name="durationMS">Duration of the animation, in milliseconds.</param> /// <param name="accel">Optional acceleration value.</param> /// <param name="decel">Optional deceleration value.</param> /// <param name="callbackFunc">Optional method to be called when animation completes.</param> /// <returns>The AnimationClock used to control the animation.</returns> public static AnimationClock AnimateDouble( DependencyObject element, DependencyProperty prop, double? from, double to, int durationMS, double? accel, double? decel, EventHandler callbackFunc) { double defaultFrom = double.IsNaN((double)element.GetValue(prop)) ? 0 : (double)element.GetValue(prop); DoubleAnimation anim = new DoubleAnimation(); anim.From = from.GetValueOrDefault(defaultFrom); anim.To = to; return Animate(element, prop, anim, durationMS, null, null, callbackFunc); } #endregion /// <summary> /// Method to configure and start an animation. /// </summary> private static AnimationClock Animate( DependencyObject animatable, DependencyProperty prop, AnimationTimeline anim, int duration, double? accel, double? decel, EventHandler func ) { anim.AccelerationRatio = accel.GetValueOrDefault(0); anim.DecelerationRatio = decel.GetValueOrDefault(0); anim.Duration = TimeSpan.FromMilliseconds(duration); anim.Freeze(); AnimationClock animClock = anim.CreateClock(); // When animation is complete, remove animation and set the animation's "To" // value as the new value of the property. EventHandler eh = null; eh = delegate(object sender, EventArgs e) { animatable.SetValue(prop, animatable.GetValue(prop)); ((IAnimatable)animatable).ApplyAnimationClock(prop, null); animClock.Completed -= eh; }; animClock.Completed += eh; // assign completed eventHandler, if defined if (func != null) animClock.Completed += func; animClock.Controller.Begin(); // goferit ((IAnimatable)animatable).ApplyAnimationClock(prop, animClock); return animClock; } } }
{ "content_hash": "3d2796c097555a5395a224262aee10e2", "timestamp": "", "source": "github", "line_count": 148, "max_line_length": 114, "avg_line_length": 40.804054054054056, "alnum_prop": 0.5823811889385659, "repo_name": "waseems/inbox2_desktop", "id": "4bd5475db8165b7353a240fc46f48fa321c25073", "size": "6041", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "Code/Client/Inbox2/Framework/UI/Animation/Animator.cs", "mode": "33188", "license": "bsd-3-clause", "language": [ { "name": "C#", "bytes": "8469344" }, { "name": "Python", "bytes": "3201" } ], "symlink_target": "" }
// Copyright (c) 2012 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "content/public/test/test_launcher.h" #include "base/base_paths.h" #include "base/command_line.h" #include "base/i18n/icu_util.h" #include "base/process/memory.h" #include "base/system/sys_info.h" #include "base/test/launcher/test_launcher.h" #include "base/test/test_suite.h" #include "base/test/test_timeouts.h" #include "build/build_config.h" #include "content/public/common/content_switches.h" #include "content/public/test/content_browser_test_shell_main_delegate.h" #include "content/public/test/content_test_suite_base.h" #include "content/shell/common/shell_switches.h" #include "testing/gtest/include/gtest/gtest.h" #include "ui/base/buildflags.h" #include "ui/base/ui_base_switches.h" #if defined(OS_WIN) #include "base/win/win_util.h" #endif // OS_WIN namespace content { class ContentBrowserTestSuite : public ContentTestSuiteBase { public: ContentBrowserTestSuite(int argc, char** argv) : ContentTestSuiteBase(argc, argv) { } ContentBrowserTestSuite(const ContentBrowserTestSuite&) = delete; ContentBrowserTestSuite& operator=(const ContentBrowserTestSuite&) = delete; ~ContentBrowserTestSuite() override {} protected: void Initialize() override { // Browser tests are expected not to tear-down various globals. base::TestSuite::DisableCheckForLeakedGlobals(); ContentTestSuiteBase::Initialize(); #if defined(OS_ANDROID) RegisterInProcessThreads(); #endif } }; class ContentTestLauncherDelegate : public TestLauncherDelegate { public: ContentTestLauncherDelegate() {} ContentTestLauncherDelegate(const ContentTestLauncherDelegate&) = delete; ContentTestLauncherDelegate& operator=(const ContentTestLauncherDelegate&) = delete; ~ContentTestLauncherDelegate() override {} int RunTestSuite(int argc, char** argv) override { return ContentBrowserTestSuite(argc, argv).Run(); } std::string GetUserDataDirectoryCommandLineSwitch() override { return switches::kContentShellDataPath; } protected: #if !defined(OS_ANDROID) ContentMainDelegate* CreateContentMainDelegate() override { return new ContentBrowserTestShellMainDelegate(); } #endif }; } // namespace content int main(int argc, char** argv) { base::CommandLine::Init(argc, argv); size_t parallel_jobs = base::NumParallelJobs(/*cores_per_job=*/2); if (parallel_jobs == 0U) return 1; #if defined(OS_WIN) // Load and pin user32.dll to avoid having to load it once tests start while // on the main thread loop where blocking calls are disallowed. base::win::PinUser32(); #endif // OS_WIN content::ContentTestLauncherDelegate launcher_delegate; return LaunchTests(&launcher_delegate, parallel_jobs, argc, argv); }
{ "content_hash": "10aff0ef4ab18f6df457f1b8e308c1ff", "timestamp": "", "source": "github", "line_count": 95, "max_line_length": 78, "avg_line_length": 30.210526315789473, "alnum_prop": 0.7508710801393729, "repo_name": "ric2b/Vivaldi-browser", "id": "ab354c13fb03d9eade71f1e18235e09087914a7f", "size": "2870", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "chromium/content/test/content_test_launcher.cc", "mode": "33188", "license": "bsd-3-clause", "language": [], "symlink_target": "" }
<?php require_once("dbconnection.php"); require_once("users.php"); require_once("util.php"); require_once("editors.php"); require_once("media.php"); require_once("scenes.php"); require_once("return_package.php"); class games extends dbconnection { //Takes in game JSON, all fields optional except user_id + key public static function createGame($pack) { $pack->auth->permission = "read_write"; if(!users::authenticateUser($pack->auth)) return new return_package(6, NULL, "Failed Authentication"); if (isset($pack->siftr_url) && $pack->siftr_url == '') { // For creation, a siftr_url of undefined, null, or empty string are all the same. // They all become NULL in the db. $pack->siftr_url = null; } $url_result = games::isValidSiftrURL($pack); if ($url_result->returnCode != 0) return $url_result; $game_name = $pack->name; $pack->game_id = dbconnection::queryInsert( "INSERT INTO games (". (isset($pack->name) ? "name," : ""). (isset($pack->description) ? "description," : ""). (isset($pack->icon_media_id) ? "icon_media_id," : ""). (isset($pack->media_id) ? "media_id," : ""). (isset($pack->map_type) ? "map_type," : ""). (isset($pack->map_focus) ? "map_focus," : ""). (isset($pack->map_latitude) ? "map_latitude," : ""). (isset($pack->map_longitude) ? "map_longitude," : ""). (isset($pack->map_zoom_level) ? "map_zoom_level," : ""). (isset($pack->map_show_player) ? "map_show_player," : ""). (isset($pack->map_show_players) ? "map_show_players," : ""). (isset($pack->map_show_labels) ? "map_show_labels," : ""). (isset($pack->map_show_roads) ? "map_show_roads," : ""). (isset($pack->map_offsite_mode) ? "map_offsite_mode," : ""). (isset($pack->notebook_allow_comments) ? "notebook_allow_comments," : ""). (isset($pack->notebook_allow_likes) ? "notebook_allow_likes," : ""). (isset($pack->notebook_trigger_scene_id) ? "notebook_trigger_scene_id," : ""). (isset($pack->notebook_trigger_requirement_root_package_id) ? "notebook_trigger_requirement_root_package_id," : ""). (isset($pack->notebook_trigger_title) ? "notebook_trigger_title," : ""). (isset($pack->notebook_trigger_icon_media_id) ? "notebook_trigger_icon_media_id," : ""). (isset($pack->notebook_trigger_distance) ? "notebook_trigger_distance," : ""). (isset($pack->notebook_trigger_infinite_distance) ? "notebook_trigger_infinite_distance," : ""). (isset($pack->notebook_trigger_wiggle) ? "notebook_trigger_wiggle," : ""). (isset($pack->notebook_trigger_show_title) ? "notebook_trigger_show_title," : ""). (isset($pack->notebook_trigger_hidden) ? "notebook_trigger_hidden," : ""). (isset($pack->notebook_trigger_on_enter) ? "notebook_trigger_on_enter," : ""). (isset($pack->inventory_weight_cap) ? "inventory_weight_cap," : ""). (isset($pack->is_siftr) ? "is_siftr," : ""). (isset($pack->siftr_url) ? "siftr_url," : ""). (isset($pack->published) ? "published," : ""). (isset($pack->type) ? "type," : ""). (isset($pack->intro_scene_id) ? "intro_scene_id," : ""). (isset($pack->latitude) ? "latitude," : ""). (isset($pack->longitude) ? "longitude," : ""). (isset($pack->network_level) ? "network_level," : ""). (isset($pack->allow_download) ? "allow_download," : ""). (isset($pack->preload_media) ? "preload_media," : ""). (isset($pack->ipad_two_x) ? "ipad_two_x," : ""). (isset($pack->moderated) ? "moderated," : ""). (isset($pack->version) ? "version," : ""). (isset($pack->colors_id) ? "colors_id," : ""). (isset($pack->theme_id) ? "theme_id," : ""). (isset($pack->prompt) ? "prompt," : ""). (isset($pack->password) ? "password," : ""). (isset($pack->staff_pick) ? "staff_pick," : ""). "created". ") VALUES (". (isset($pack->name) ? "'".addslashes($pack->name)."'," : ""). (isset($pack->description) ? "'".addslashes($pack->description)."'," : ""). (isset($pack->icon_media_id) ? "'".addslashes($pack->icon_media_id)."'," : ""). (isset($pack->media_id) ? "'".addslashes($pack->media_id)."'," : ""). (isset($pack->map_type) ? "'".addslashes($pack->map_type)."'," : ""). (isset($pack->map_focus) ? "'".addslashes($pack->map_focus)."'," : ""). (isset($pack->map_latitude) ? "'".addslashes($pack->map_latitude)."'," : ""). (isset($pack->map_longitude) ? "'".addslashes($pack->map_longitude)."'," : ""). (isset($pack->map_zoom_level) ? "'".addslashes($pack->map_zoom_level)."'," : ""). (isset($pack->map_show_player) ? "'".addslashes($pack->map_show_player)."'," : ""). (isset($pack->map_show_players) ? "'".addslashes($pack->map_show_players)."'," : ""). (isset($pack->map_show_labels) ? "'".addslashes($pack->map_show_labels)."'," : ""). (isset($pack->map_show_roads) ? "'".addslashes($pack->map_show_roads)."'," : ""). (isset($pack->map_offsite_mode) ? "'".addslashes($pack->map_offsite_mode)."'," : ""). (isset($pack->notebook_allow_comments) ? "'".addslashes($pack->notebook_allow_comments)."'," : ""). (isset($pack->notebook_allow_likes) ? "'".addslashes($pack->notebook_allow_likes)."'," : ""). (isset($pack->notebook_trigger_scene_id) ? "'".addslashes($pack->notebook_trigger_scene_id)."'," : ""). (isset($pack->notebook_trigger_requirement_root_package_id) ? "'".addslashes($pack->notebook_trigger_requirement_root_package_id)."'," : ""). (isset($pack->notebook_trigger_title) ? "'".addslashes($pack->notebook_trigger_title)."'," : ""). (isset($pack->notebook_trigger_icon_media_id) ? "'".addslashes($pack->notebook_trigger_icon_media_id)."'," : ""). (isset($pack->notebook_trigger_distance) ? "'".addslashes($pack->notebook_trigger_distance)."'," : ""). (isset($pack->notebook_trigger_infinite_distance) ? "'".addslashes($pack->notebook_trigger_infinite_distance)."'," : ""). (isset($pack->notebook_trigger_wiggle) ? "'".addslashes($pack->notebook_trigger_wiggle)."'," : ""). (isset($pack->notebook_trigger_show_title) ? "'".addslashes($pack->notebook_trigger_show_title)."'," : ""). (isset($pack->notebook_trigger_hidden) ? "'".addslashes($pack->notebook_trigger_hidden)."'," : ""). (isset($pack->notebook_trigger_on_enter) ? "'".addslashes($pack->notebook_trigger_on_enter)."'," : ""). (isset($pack->inventory_weight_cap) ? "'".addslashes($pack->inventory_weight_cap)."'," : ""). (isset($pack->is_siftr) ? "'".addslashes($pack->is_siftr)."'," : ""). (isset($pack->siftr_url) ? "'".addslashes($pack->siftr_url)."'," : ""). (isset($pack->published) ? "'".addslashes($pack->published)."'," : ""). (isset($pack->type) ? "'".addslashes($pack->type)."'," : ""). (isset($pack->intro_scene_id) ? "'".addslashes($pack->intro_scene_id)."'," : ""). (isset($pack->latitude) ? "'".addslashes($pack->latitude)."'," : ""). (isset($pack->longitude) ? "'".addslashes($pack->longitude)."'," : ""). (isset($pack->network_level) ? "'".addslashes($pack->network_level)."'," : ""). (isset($pack->allow_download) ? "'".addslashes($pack->allow_download)."'," : ""). (isset($pack->preload_media) ? "'".addslashes($pack->preload_media)."'," : ""). (isset($pack->ipad_two_x) ? "'".addslashes($pack->ipad_two_x)."'," : ""). (isset($pack->moderated) ? "'".addslashes($pack->moderated)."'," : ""). (isset($pack->version) ? "'".addslashes($pack->version)."'," : ""). (isset($pack->colors_id) ? "'".addslashes($pack->colors_id)."'," : ""). (isset($pack->theme_id) ? "'".addslashes($pack->theme_id)."'," : ""). (isset($pack->prompt) ? "'".addslashes($pack->prompt)."'," : ""). (isset($pack->password) ? "'".addslashes($pack->password)."'," : ""). (isset($pack->staff_pick) ? "'".addslashes($pack->staff_pick)."'," : ""). "CURRENT_TIMESTAMP". ")" ); dbconnection::queryInsert("INSERT INTO user_games (game_id, user_id, created) VALUES ('{$pack->game_id}','{$pack->auth->user_id}',CURRENT_TIMESTAMP)"); $game_id = intval($pack->game_id); // game_id, type, name, icon, sort, created dbconnection::query("INSERT INTO tabs (game_id, type, name, icon_media_id, sort_index, created) VALUES ('{$game_id}', 'MAP', '', '0', '1', CURRENT_TIMESTAMP)"); dbconnection::query("INSERT INTO tabs (game_id, type, name, icon_media_id, sort_index, created) VALUES ('{$game_id}', 'QUESTS', '', '0', '2', CURRENT_TIMESTAMP)"); dbconnection::query("INSERT INTO tabs (game_id, type, name, icon_media_id, sort_index, created) VALUES ('{$game_id}', 'INVENTORY', '', '0', '3', CURRENT_TIMESTAMP)"); dbconnection::query("INSERT INTO tabs (game_id, type, name, icon_media_id, sort_index, created) VALUES ('{$game_id}', 'SCANNER', '', '0', '4', CURRENT_TIMESTAMP)"); dbconnection::query("INSERT INTO tabs (game_id, type, name, icon_media_id, sort_index, created) VALUES ('{$game_id}', 'DECODER', '', '0', '5', CURRENT_TIMESTAMP)"); dbconnection::query("INSERT INTO tabs (game_id, type, name, icon_media_id, sort_index, created) VALUES ('{$game_id}', 'PLAYER', '', '0', '6', CURRENT_TIMESTAMP)"); dbconnection::query("INSERT INTO tabs (game_id, type, name, icon_media_id, sort_index, created) VALUES ('{$game_id}', 'NOTEBOOK', '', '0', '7', CURRENT_TIMESTAMP)"); mkdir(Config::v2_gamedata_folder."/{$pack->game_id}",0777); $pack->name = "Starting Scene"; $pack->description = ""; scenes::createScene($pack); if (isset($pack->fields)) { foreach ($pack->fields as $field) { $field_id = dbconnection::queryInsert ( "INSERT INTO fields (game_id, field_type, label, required) VALUES (" . intval($pack->game_id) . ",\"" . addslashes($field->field_type) . "\"" . ",\"" . addslashes($field->label) . "\"" . "," . ($field->required ? 1 : 0) . ")" ); if ($field->useAsPin) { dbconnection::query("UPDATE games SET field_id_pin = {$field_id} WHERE game_id = {$game_id}"); } else if ($field->useOnCards) { $col = 'field_id_caption'; if ($field->field_type === 'MEDIA') { $col = 'field_id_preview'; } dbconnection::query("UPDATE games SET {$col} = {$field_id} WHERE game_id = {$game_id}"); } if (isset($field->options)) { foreach ($field->options as $option) { if (isset($option->option)) { $label = $option->option; $color = $option->color; } else { $label = $option; $color = "#000000"; } dbconnection::queryInsert ( "INSERT INTO field_options (field_id, game_id, `option`, color) VALUES (" . intval($field_id) . "," . intval($pack->game_id) . ",\"" . addslashes($label) . "\"" . ",\"" . addslashes($color) . "\"" . ")" ); } } } } if ($pack->is_siftr && intval($pack->auth->user_id) === 788) { $subject = 'Your new Siftr: ' . $game_name; $identifier = ($pack->siftr_url ? $pack->siftr_url : $pack->game_id); $textEmail = "Hello, Look at that! You created a Siftr called \"".$game_name."\". This message is to make sure you have everything you need to find and share your Siftr. First of all, here's the link to your Siftr: https://siftr.org/".$identifier."/ You can share the link with your audience to give them access. Just a few more steps and you'll be ready to start posting! For users who have already downloaded the Siftr app: 1. Click on the link or type the URL into your browser and \"".$game_name."\" will automatically open in the Siftr app. 2. If the Siftr is private, type in \"".$identifier."\" to get access. 3. You will be prompted to sign up or log in. For users who have not downloaded the Siftr app: 1. Click on the link or type the URL into your browser and \"".$game_name."\" will open on the Siftr website in your browser. 2. You will be prompted to download the Siftr app (iOS and Android). 3. In the app, type in \"".$identifier."\" to get access to this Siftr. 4. You will be prompted to sign up or log in. And that's it! From now on, you can easily access \"".$game_name."\" on your Siftr app home screen. Just follow the Siftr by opening the menu (the colored dots icon in the top-right) and selecting \"Follow this Siftr\". Email us about any problems you run into. We're excited to hear your feedback, and your problems will make it onto our fix list. Have fun, David Gagnon Field Day Lab"; $htmlEmail = "<p>Hello,</p> <p>Look at that! You created a Siftr called \"<em>".$game_name."</em>\". This message is to make sure you have everything you need to find and share your Siftr.</p> <p>First of all, here's the link to your Siftr:<br> <a href=\"https://siftr.org/".$identifier."/\">https://siftr.org/".$identifier."/</a><br> You can share the link with your audience to give them access.</p> <p>Just a few more steps and you'll be ready to start posting!</p> <p>For users who have already downloaded the Siftr app:</p> <ol> <li>Click on the link or type the URL into your browser and \"<em>".$game_name."</em>\" will automatically open in the Siftr app.</li> <li>If the Siftr is private, type in \"<em>".$identifier."</em>\" to get access.</li> <li>You will be prompted to sign up or log in.</li> </ol> <p>For users who have not downloaded the Siftr app:</p> <ol> <li>Click on the link or type the URL into your browser and \"<em>".$game_name."</em>\" will open on the Siftr website in your browser.</li> <li>You will be prompted to download the Siftr app (iOS and Android).</li> <li>In the app, type in \"<em>".$identifier."</em>\" to get access to this Siftr.</li> <li>You will be prompted to sign up or log in.</li> </ol> <p>And that's it! From now on, you can easily access \"<em>".$game_name."</em>\" on your Siftr app home screen. Just follow the Siftr by opening the menu (the colored dots icon in the top-right) and selecting \"<em>Follow this Siftr</em>\".</p> <p><img src=\"https://arisgames.org/hosted/siftr-follow.jpg\"></p> <p>Email us about any problems you run into. We're excited to hear your feedback, and your problems will make it onto our fix list.</p> <p>Have fun,</p> <p>David Gagnon<br> Field Day Lab</p>"; $email = dbconnection::queryObject("SELECT email FROM users WHERE user_id = '{$pack->auth->user_id}'")->email; util::sendEmail($email, $subject, $textEmail, $htmlEmail); } return games::getGame($pack); // TODO include password? } //no need for security- just invalidates local game downloads public static function bumpGameVersion($pack) { $game_id = intval($pack->game_id); dbconnection::query("UPDATE games SET version = version+1, last_active = CURRENT_TIMESTAMP WHERE game_id = '{$game_id}';"); } //Takes in game JSON, all fields optional except user_id + key public static function updateGame($pack) { $game_id = intval($pack->game_id); $pack->auth->game_id = $game_id; $pack->auth->permission = "read_write"; if(!users::authenticateUser($pack->auth)) { return new return_package(6, NULL, "Failed Authentication"); } if(!editors::authenticateGameEditor($pack->auth) && intval($pack->auth->user_id) !== 1 && intval($pack->auth->user_id) !== 788) { return new return_package(6, NULL, "Failed Authentication"); } $url_result = games::isValidSiftrURL($pack); if ($url_result->returnCode != 0) return $url_result; // If the URL is an empty string (but NOT undefined or null), that means it is being explicitly set to NULL in db. $unset_url = isset($pack->siftr_url) && $pack->siftr_url == ''; if ($unset_url) unset($pack->siftr_url); //ensure requested scene_id exists, otherwise pick one from list of existing scenes //this is a hack, in case you were wondering... $intro_scene_id = intval($pack->intro_scene_id); $game_id = intval($pack->game_id); if(!dbconnection::queryObject("SELECT * FROM scenes WHERE scene_id = '{$intro_scene_id}' AND game_id = '{$game_id}'")) { $pack->intro_scene_id = 0; //fallback if we can't find a good one $scenes = dbconnection::queryArray("SELECT * FROM scenes WHERE game_id = '{$game_id}'"); if(count($scenes) > 0) $pack->intro_scene_id = $scenes[0]->scene_id; } dbconnection::query( "UPDATE games SET ". (isset($pack->name) ? "name = '".addslashes($pack->name)."', " : ""). (isset($pack->description) ? "description = '".addslashes($pack->description)."', " : ""). (isset($pack->icon_media_id) ? "icon_media_id = '".addslashes($pack->icon_media_id)."', " : ""). (isset($pack->media_id) ? "media_id = '".addslashes($pack->media_id)."', " : ""). (isset($pack->map_type) ? "map_type = '".addslashes($pack->map_type)."', " : ""). (isset($pack->map_focus) ? "map_focus = '".addslashes($pack->map_focus)."', " : ""). (isset($pack->map_latitude) ? "map_latitude = '".addslashes($pack->map_latitude)."', " : ""). (isset($pack->map_longitude) ? "map_longitude = '".addslashes($pack->map_longitude)."', " : ""). (isset($pack->map_zoom_level) ? "map_zoom_level = '".addslashes($pack->map_zoom_level)."', " : ""). (isset($pack->map_show_player) ? "map_show_player = '".intval($pack->map_show_player)."', " : ""). (isset($pack->map_show_players) ? "map_show_players = '".intval($pack->map_show_players)."', " : ""). (isset($pack->map_show_labels) ? "map_show_labels = '".intval($pack->map_show_labels)."', " : ""). (isset($pack->map_show_roads) ? "map_show_roads = '".intval($pack->map_show_roads)."', " : ""). (isset($pack->map_offsite_mode) ? "map_offsite_mode = '".intval($pack->map_offsite_mode)."', " : ""). (isset($pack->notebook_allow_comments) ? "notebook_allow_comments = '".intval($pack->notebook_allow_comments)."', " : ""). (isset($pack->notebook_allow_likes) ? "notebook_allow_likes = '".intval($pack->notebook_allow_likes)."', " : ""). (isset($pack->notebook_trigger_scene_id) ? "notebook_trigger_scene_id = '".addslashes($pack->notebook_trigger_scene_id)."', " : ""). (isset($pack->notebook_trigger_requirement_root_package_id) ? "notebook_trigger_requirement_root_package_id = '".addslashes($pack->notebook_trigger_requirement_root_package_id)."', " : ""). (isset($pack->notebook_trigger_title) ? "notebook_trigger_title = '".addslashes($pack->notebook_trigger_title)."', " : ""). (isset($pack->notebook_trigger_icon_media_id) ? "notebook_trigger_icon_media_id = '".addslashes($pack->notebook_trigger_icon_media_id)."', " : ""). (isset($pack->notebook_trigger_distance) ? "notebook_trigger_distance = '".addslashes($pack->notebook_trigger_distance)."', " : ""). (isset($pack->notebook_trigger_infinite_distance) ? "notebook_trigger_infinite_distance = '".intval($pack->notebook_trigger_infinite_distance)."', " : ""). (isset($pack->notebook_trigger_wiggle) ? "notebook_trigger_wiggle = '".intval($pack->notebook_trigger_wiggle)."', " : ""). (isset($pack->notebook_trigger_show_title) ? "notebook_trigger_show_title = '".intval($pack->notebook_trigger_show_title)."', " : ""). (isset($pack->notebook_trigger_hidden) ? "notebook_trigger_hidden = '".intval($pack->notebook_trigger_hidden)."', " : ""). (isset($pack->notebook_trigger_on_enter) ? "notebook_trigger_on_enter = '".intval($pack->notebook_trigger_on_enter)."', " : ""). (isset($pack->inventory_weight_cap) ? "inventory_weight_cap = '".addslashes($pack->inventory_weight_cap)."', " : ""). (isset($pack->is_siftr) ? "is_siftr = '".intval($pack->is_siftr)."', " : ""). (isset($pack->siftr_url) ? "siftr_url = '".addslashes($pack->siftr_url)."', " : ""). ($unset_url ? "siftr_url = NULL, " : ""). (isset($pack->published) ? "published = '".intval($pack->published)."', " : ""). (isset($pack->type) ? "type = '".addslashes($pack->type)."', " : ""). (isset($pack->intro_scene_id) ? "intro_scene_id = '".addslashes($pack->intro_scene_id)."', " : ""). (isset($pack->latitude) ? "latitude = '".addslashes($pack->latitude)."', " : ""). (isset($pack->longitude) ? "longitude = '".addslashes($pack->longitude)."', " : ""). (isset($pack->network_level) ? "network_level = '".addslashes($pack->network_level)."', " : ""). (isset($pack->allow_download) ? "allow_download = '".intval($pack->allow_download)."', " : ""). (isset($pack->preload_media) ? "preload_media = '".intval($pack->preload_media)."', " : ""). (isset($pack->ipad_two_x) ? "ipad_two_x = '".intval($pack->ipad_two_x)."', " : ""). (isset($pack->moderated) ? "moderated = '".intval($pack->moderated)."', " : ""). (isset($pack->version) ? "version = '".addslashes($pack->version)."', " : ""). (isset($pack->colors_id) ? "colors_id = '".addslashes($pack->colors_id)."', " : ""). (isset($pack->theme_id) ? "theme_id = '".addslashes($pack->theme_id)."', " : ""). (isset($pack->field_id_preview) ? "field_id_preview = '".intval($pack->field_id_preview)."', " : ""). (isset($pack->field_id_pin) ? "field_id_pin = '".intval($pack->field_id_pin)."', " : ""). (isset($pack->field_id_caption) ? "field_id_caption = '".intval($pack->field_id_caption)."', " : ""). (isset($pack->prompt) ? "prompt = '".addslashes($pack->prompt)."', " : ""). (isset($pack->password) ? "password = '".addslashes($pack->password)."', " : ""). (isset($pack->staff_pick) ? "staff_pick = '".addslashes($pack->staff_pick)."', " : ""). "last_active = CURRENT_TIMESTAMP ". "WHERE game_id = '{$game_id}'" ); games::bumpGameVersion($pack); return games::getGame($pack); } public static function gameObjectFromSQL($sql_game) { if(!$sql_game) return $sql_game; $game = new stdClass(); $game->game_id = $sql_game->game_id; $game->name = $sql_game->name; $game->description = $sql_game->description; $game->icon_media_id = $sql_game->icon_media_id; $game->media_id = $sql_game->media_id; $game->map_type = $sql_game->map_type; $game->map_focus = $sql_game->map_focus; $game->map_latitude = $sql_game->map_latitude; $game->map_longitude = $sql_game->map_longitude; $game->map_zoom_level = $sql_game->map_zoom_level; $game->map_show_player = $sql_game->map_show_player; $game->map_show_players = $sql_game->map_show_players; $game->map_show_labels = $sql_game->map_show_labels; $game->map_show_roads = $sql_game->map_show_roads; $game->map_offsite_mode = $sql_game->map_offsite_mode; $game->notebook_allow_comments = $sql_game->notebook_allow_comments; $game->notebook_allow_likes = $sql_game->notebook_allow_likes; $game->notebook_trigger_scene_id = $sql_game->notebook_trigger_scene_id; $game->notebook_trigger_requirement_root_package_id = $sql_game->notebook_trigger_requirement_root_package_id; $game->notebook_trigger_title = $sql_game->notebook_trigger_title; $game->notebook_trigger_icon_media_id = $sql_game->notebook_trigger_icon_media_id; $game->notebook_trigger_distance = $sql_game->notebook_trigger_distance; $game->notebook_trigger_infinite_distance = $sql_game->notebook_trigger_infinite_distance; $game->notebook_trigger_wiggle = $sql_game->notebook_trigger_wiggle; $game->notebook_trigger_show_title = $sql_game->notebook_trigger_show_title; $game->notebook_trigger_hidden = $sql_game->notebook_trigger_hidden; $game->notebook_trigger_on_enter = $sql_game->notebook_trigger_on_enter; $game->inventory_weight_cap = $sql_game->inventory_weight_cap; $game->is_siftr = $sql_game->is_siftr; $game->siftr_url = $sql_game->siftr_url; $game->published = $sql_game->published; $game->type = $sql_game->type; $game->intro_scene_id = $sql_game->intro_scene_id; $game->latitude = $sql_game->latitude; $game->longitude = $sql_game->longitude; $game->network_level = $sql_game->network_level; $game->allow_download = $sql_game->allow_download; $game->preload_media = $sql_game->preload_media; $game->ipad_two_x = $sql_game->ipad_two_x; $game->moderated = $sql_game->moderated; $game->version = $sql_game->version; $game->colors_id = $sql_game->colors_id; $game->theme_id = $sql_game->theme_id; $game->field_id_preview = $sql_game->field_id_preview; $game->field_id_pin = $sql_game->field_id_pin; $game->field_id_caption = $sql_game->field_id_caption; $game->prompt = $sql_game->prompt; $game->staff_pick = $sql_game->staff_pick; $game->created = $sql_game->created; $game->force_new_format = 1; return $game; } public static function gameObjectFromSQLWithPassword($sql_game) { if(!$sql_game) return $sql_game; $game = games::gameObjectFromSQL($sql_game); $game->password = $sql_game->password; return $game; } public static function getGame($pack) { $game_id = intval($pack->game_id); $sql_game = dbconnection::queryObject("SELECT * FROM games WHERE game_id = '{$game_id}' LIMIT 1"); if(!$sql_game) return new return_package(2, NULL, "The game you've requested does not exist"); $is_editor = false; if(isset($pack->auth)) { $pack->auth->game_id = $game_id; if(editors::authenticateGameEditor($pack->auth)) { $is_editor = true; } } if ($is_editor) { return new return_package(0,games::gameObjectFromSQLWithPassword($sql_game)); } else { return new return_package(0,games::gameObjectFromSQL($sql_game)); } } public static function searchSiftrs($pack) { $siftr_url = isset($pack->siftr_url) ? addslashes($pack->siftr_url) : null; $count = isset($pack->count ) ? intval ($pack->count ) : 0 ; $offset = isset($pack->offset ) ? intval ($pack->offset ) : 0 ; $order_by = isset($pack->order_by ) ? $pack->order_by : null; $days = isset($pack->days ) ? intval ($pack->days ) : 30 ; $search = isset($pack->search ) ? addslashes($pack->search ) : null; $q = "SELECT g.* FROM games AS g"; if ($order_by === "recent" || $order_by === "popular") { $q .= " JOIN notes AS n ON g.game_id = n.game_id"; // TODO: also use note_comments? } $q .= " WHERE g.is_siftr"; if ($siftr_url) $q .= " AND g.siftr_url = '".$pack->siftr_url."'"; if (!$siftr_url) $q .= " AND g.published AND (g.password IS NULL OR g.password = '')"; if ($search) { foreach (preg_split('/\s+/', $search) as $word) { if ($word != '') { $q .= " AND (g.name LIKE '%$word%' OR g.description LIKE '%$word%' OR g.siftr_url LIKE '%$word%')"; } } } if ($order_by === "recent") { $q .= " GROUP BY g.game_id"; $q .= " ORDER BY MAX(n.last_active) DESC"; } else if ($order_by === "popular") { $q .= " AND (n.created IS NULL OR DATEDIFF(NOW(), n.created) <= $days)"; $q .= " GROUP BY g.game_id"; $q .= " ORDER BY COUNT(n.note_id) DESC"; } if ($count) { $q .= " LIMIT {$count}"; if ($offset) { $q .= " OFFSET {$offset}"; } } $sql_games = dbconnection::queryArray($q); $games = array(); $auth = (isset($pack->auth) ? $pack->auth : new stdClass()); for($i = 0; $i < count($sql_games); $i++) { $sql_game = $sql_games[$i]; $auth->game_id = $sql_game->game_id; if (editors::authenticateGameEditor($auth)) { if ( $ob = games::gameObjectFromSQLWithPassword($sql_game) ) { $games[] = $ob; } } else { if ( $ob = games::gameObjectFromSQL($sql_game) ) { $games[] = $ob; } } } return new return_package(0, $games); } public static function isValidSiftrURL($pack) { // If URL is undefined, null, or empty string, return true. // (but, these have different meanings in createGame and updateGame, see those fns for details) if (!property_exists($pack, 'siftr_url')) return new return_package(0, true); $url = (string) ($pack->siftr_url); if ($url == '') return new return_package(0, true); $sql_game = dbconnection::queryObject("SELECT * FROM games WHERE siftr_url = '{$url}' LIMIT 1"); if ($sql_game) { if (isset($pack->game_id) && intval($pack->game_id) == intval($sql_game->game_id)) { // all good, we're updating an existing Siftr to have its existing URL } else { return new return_package(2, NULL, "That URL is already taken"); } } if (!preg_match('/[A-Za-z]/', $url)) return new return_package(2, NULL, "The URL must have at least one letter"); if (!preg_match('/^[A-Za-z0-9_-]+$/', $url)) return new return_package(2, NULL, "The URL must consist only of letters, numbers, underscores, and dashes"); if ($url == 'editor') // special case return new return_package(2, NULL, "That URL is already taken"); return new return_package(0, true); } public static function getGamesForUser($pack) { $pack->auth->permission = "read_write"; if(!users::authenticateUser($pack->auth)) return new return_package(6, NULL, "Failed Authentication"); $user_id = intval($pack->auth->user_id); if (isset($pack->order) && $pack->order === 'recent') { $sql_games = dbconnection::queryArray("SELECT games.* FROM user_games LEFT JOIN games ON user_games.game_id = games.game_id LEFT JOIN notes ON games.game_id = notes.game_id AND notes.user_id = '{$user_id}' LEFT JOIN user_log ON user_log.user_id = '{$user_id}' AND games.game_id = user_log.game_id AND user_log.event_type = 'MOVE' WHERE user_games.user_id = '{$user_id}' AND games.game_id IS NOT NULL GROUP BY games.game_id ORDER BY GREATEST(IFNULL(notes.last_active, FROM_UNIXTIME(0)), IFNULL(user_log.created, FROM_UNIXTIME(0))) DESC"); } else { $sql_games = dbconnection::queryArray("SELECT * FROM user_games LEFT JOIN games ON user_games.game_id = games.game_id WHERE user_games.user_id = '{$user_id}' AND games.game_id IS NOT NULL"); } $games = array(); for($i = 0; $i < count($sql_games); $i++) if($ob = games::gameObjectFromSQLWithPassword($sql_games[$i])) $games[] = $ob; return new return_package(0,$games); } public static function getFollowedGamesForUser($pack) { $pack->auth->permission = "read_write"; if(!users::authenticateUser($pack->auth)) return new return_package(6, NULL, "Failed Authentication"); $user_id = intval($pack->auth->user_id); if (isset($pack->order) && $pack->order === 'recent') { $sql_games = dbconnection::queryArray("SELECT games.* FROM game_follows LEFT JOIN games ON game_follows.game_id = games.game_id LEFT JOIN notes ON games.game_id = notes.game_id AND notes.user_id = '{$user_id}' LEFT JOIN user_log ON user_log.user_id = '{$user_id}' AND games.game_id = user_log.game_id AND user_log.event_type = 'MOVE' WHERE game_follows.user_id = '{$user_id}' AND games.game_id IS NOT NULL GROUP BY games.game_id ORDER BY GREATEST(IFNULL(notes.last_active, FROM_UNIXTIME(0)), IFNULL(user_log.created, FROM_UNIXTIME(0))) DESC"); } else { $sql_games = dbconnection::queryArray("SELECT * FROM game_follows LEFT JOIN games ON game_follows.game_id = games.game_id WHERE game_follows.user_id = '{$user_id}' AND games.game_id IS NOT NULL"); } $games = array(); for($i = 0; $i < count($sql_games); $i++) if($ob = games::gameObjectFromSQL($sql_games[$i])) $games[] = $ob; return new return_package(0,$games); } public static function followGame($pack) { $pack->auth->permission = "read_write"; if(!users::authenticateUser($pack->auth)) return new return_package(6, NULL, "Failed Authentication"); $game_id = intval($pack->game_id); $user_id = intval($pack->auth->user_id); dbconnection::queryInsert("INSERT INTO game_follows (game_id, user_id, created) VALUES ('{$game_id}','{$user_id}',CURRENT_TIMESTAMP)"); return new return_package(0); } public static function unfollowGame($pack) { $pack->auth->permission = "read_write"; if(!users::authenticateUser($pack->auth)) return new return_package(6, NULL, "Failed Authentication"); $game_id = intval($pack->game_id); $user_id = intval($pack->auth->user_id); dbconnection::query("DELETE FROM game_follows WHERE user_id = '{$user_id}' AND game_id = '{$game_id}'"); return new return_package(0); } public static function deleteGame($pack) { $pack->auth->game_id = $pack->game_id; $pack->auth->permission = "read_write"; if(!editors::authenticateGameEditor($pack->auth)) return new return_package(6, NULL, "Failed Authentication"); if(!is_numeric($pack->game_id)) return new return_package(1, NULL, "Invalid game ID format"); $tables = array(); $tables[] = "dialog_characters"; $tables[] = "dialog_options"; $tables[] = "dialog_scripts"; $tables[] = "dialogs"; $tables[] = "event_packages"; $tables[] = "events"; $tables[] = "factories"; $tables[] = "fields"; $tables[] = "field_options"; $tables[] = "field_data"; $tables[] = "game_comments"; $tables[] = "instances"; $tables[] = "items"; $tables[] = "media"; $tables[] = "note_comments"; $tables[] = "note_likes"; $tables[] = "notes"; $tables[] = "object_tags"; $tables[] = "overlays"; $tables[] = "plaques"; $tables[] = "quests"; $tables[] = "requirement_and_packages"; $tables[] = "requirement_atoms"; $tables[] = "requirement_root_packages"; $tables[] = "scenes"; $tables[] = "tabs"; $tables[] = "tags"; $tables[] = "triggers"; $tables[] = "user_game_scenes"; $tables[] = "user_games"; $tables[] = "web_hooks"; $tables[] = "web_pages"; dbconnection::query("DELETE FROM games WHERE game_id = '{$pack->game_id}' LIMIT 1"); for($i = 0; $i < count($tables); $i++) dbconnection::query("DELETE FROM {$tables[$i]} WHERE game_id = '{$pack->game_id}'"); $command = 'rm -rf '. Config::v2_gamedata_folder . "/{$pack->game_id}"; exec($command, $output, $return); if($return) return new return_package(4, NULL, "unable to delete game directory"); return new return_package(0); } public static function cleanOrphans($pack) { $tables = array(); $tables[] = "dialog_characters"; $tables[] = "dialog_options"; $tables[] = "dialog_scripts"; $tables[] = "dialogs"; $tables[] = "event_packages"; $tables[] = "events"; $tables[] = "factories"; $tables[] = "fields"; $tables[] = "field_options"; $tables[] = "field_data"; $tables[] = "game_comments"; $tables[] = "instances"; $tables[] = "items"; $tables[] = "media"; $tables[] = "note_comments"; $tables[] = "note_likes"; $tables[] = "notes"; $tables[] = "object_tags"; $tables[] = "overlays"; $tables[] = "plaques"; $tables[] = "quests"; $tables[] = "requirement_and_packages"; $tables[] = "requirement_atoms"; $tables[] = "requirement_root_packages"; $tables[] = "scenes"; $tables[] = "tabs"; $tables[] = "tags"; $tables[] = "triggers"; $tables[] = "user_game_scenes"; $tables[] = "user_games"; $tables[] = "web_hooks"; $tables[] = "web_pages"; for($i = 0; $i < count($tables); $i++) { $arr = dbconnection::queryArray("SELECT {$tables[$i]}.game_id as game_id, games.game_id as n_game_id FROM {$tables[$i]} LEFT JOIN games ON {$tables[$i]}.game_id = games.game_id WHERE games.game_id IS NULL GROUP BY game_id;"); for($j = 0; $j < count($arr); $j++) { if($tables[$i] == "media" && $arr[$j]->game_id == 0) continue; //allow default media if($pack->execute) dbconnection::query("DELETE FROM {$tables[$i]} WHERE game_id = '{$arr[$j]->game_id}';"); else //dry run echo "DELETE FROM {$tables[$i]} WHERE game_id = '{$arr[$j]->game_id}'; (game_id = '{$arr[$j]->game_id}')\n"; } } //instances $types = array(); $tables = array(); $ids = array(); $types[] = "PLAQUE"; $tables[] = "plaques"; $ids[] = "plaque_id"; $types[] = "ITEM"; $tables[] = "items"; $ids[] = "item_id"; $types[] = "DIALOG"; $tables[] = "dialogs"; $ids[] = "dialog_id"; $types[] = "WEB_PAGE"; $tables[] = "web_pages"; $ids[] = "web_page_id"; $types[] = "NOTE"; $tables[] = "notes"; $ids[] = "note_id"; $types[] = "FACTORY"; $tables[] = "factories"; $ids[] = "factory_id"; for($i = 0; $i < count($types); $i++) { $arr = dbconnection::queryArray("SELECT instances.* FROM instances LEFT JOIN {$tables[$i]} ON instances.object_id = {$tables[$i]}.{$ids[$i]} WHERE instances.object_type = '{$types[$i]}' AND {$tables[$i]}.{$ids[$i]} IS NULL;"); for($j = 0; $j < count($arr); $j++) { if($pack->execute) dbconnection::query("DELETE FROM instances WHERE instance_id = '{$arr[$j]->instance_id}';"); else //dry run echo "DELETE FROM instances WHERE instance_id = '{$arr[$j]->instance_id}'; (game_id = '{$arr[$j]->game_id}')\n"; } } //triggers $arr = dbconnection::queryArray("SELECT triggers.* FROM triggers LEFT JOIN instances ON triggers.instance_id = instances.instance_id WHERE instances.instance_id IS NULL;"); for($j = 0; $j < count($arr); $j++) //use '$j' for consistency { if($pack->execute) dbconnection::query("DELETE FROM triggers WHERE trigger_id = '{$arr[$j]->trigger_id}';"); else //dry run echo "DELETE FROM triggers WHERE trigger_id = '{$arr[$j]->trigger_id}'; (game_id = '{$arr[$j]->game_id}')\n"; } //requirements // \/ query to manually see requirement tree in SQL. nice for debugging. //SELECT ratom.requirement_atom_id, rand.requirement_and_package_id, rroot.requirement_root_package_id FROM requirement_atoms as ratom LEFT JOIN requirement_and_packages as rand ON ratom.requirement_and_package_id = rand.requirement_and_package_id LEFT JOIN requirement_root_packages as rroot ON rand.requirement_root_package_id = rroot.requirement_root_package_id WHERE rand.game_id = 3259; $arr = dbconnection::queryArray("SELECT requirement_and_packages.* FROM requirement_and_packages LEFT JOIN requirement_root_packages ON requirement_and_packages.requirement_root_package_id = requirement_root_packages.requirement_root_package_id WHERE requirement_root_packages.requirement_root_package_id IS NULL;"); for($j = 0; $j < count($arr); $j++) //use '$j' for consistency { if($pack->execute) dbconnection::query("DELETE FROM requirement_and_packages WHERE requirement_and_package_id = '{$arr[$j]->requirement_and_package_id}';"); else //dry run echo "DELETE FROM requirement_and_packages WHERE requirement_and_package_id = '{$arr[$j]->requirement_and_package_id}'; (game_id = '{$arr[$j]->game_id}')\n"; } $arr = dbconnection::queryArray("SELECT requirement_atoms.* FROM requirement_atoms LEFT JOIN requirement_and_packages ON requirement_atoms.requirement_and_package_id = requirement_and_packages.requirement_and_package_id WHERE requirement_and_packages.requirement_and_package_id IS NULL;"); for($j = 0; $j < count($arr); $j++) //use '$j' for consistency { if($pack->execute) dbconnection::query("DELETE FROM requirement_atoms WHERE requirement_atom_id = '{$arr[$j]->requirement_atom_id}';"); else //dry run echo "DELETE FROM requirement_atoms WHERE requirement_atom_id = '{$arr[$j]->requirement_atom_id}'; (game_id = '{$arr[$j]->game_id}')\n"; } return new return_package(0); } public static function getFullGame($pack) { $pack->auth->permission = "read_write"; if(!users::authenticateUser($pack->auth)) return new return_package(6, NULL, "Failed Authentication"); $game_id = intval($pack->game_id); $sql_game = dbconnection::queryObject("SELECT * FROM games WHERE game_id = '{$game_id}' LIMIT 1"); if(!$sql_game) return new return_package(2, NULL, "The game you've requested does not exist"); $game = games::getGame($pack)->data; $game->authors = users::getUsersForGame($pack)->data; //pack already has auth and game_id //heres where we just hack the pack for use in other requests without overhead of creating new packs $pack->media_id = $game->media_id; $game->media = media::getMedia($pack)->data; $pack->media_id = $game->icon_media_id; $game->icon_media = media::getMedia($pack)->data; return new return_package(0,$game); } public static function getStaffPicks($pack) { $count = isset($pack->count ) ? intval($pack->count ) : 0; $offset = isset($pack->offset) ? intval($pack->offset) : 0; $q = "SELECT * FROM games WHERE staff_pick != '0000-00-00 00:00:00' ORDER BY staff_pick DESC"; if ($count) { $q .= " LIMIT {$count}"; if ($offset) { $q .= " OFFSET {$offset}"; } } $sql_games = dbconnection::queryArray($q); $games = array(); for ($i = 0; $i < count($sql_games); $i++) { if ($ob = games::gameObjectFromSQL($sql_games[$i])) $games[] = $ob; } return new return_package(0,$games); } } ?>
{ "content_hash": "383d00fe3ddf7b6023784963ad904eae", "timestamp": "", "source": "github", "line_count": 790, "max_line_length": 555, "avg_line_length": 70.58987341772152, "alnum_prop": 0.44667001398701717, "repo_name": "ARISGames/server", "id": "b97f4da0d4cb4cb91dcad7b3adc1a45d1635ab3d", "size": "55766", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "services/v2/games.php", "mode": "33188", "license": "mit", "language": [ { "name": "Awk", "bytes": "137" }, { "name": "CSS", "bytes": "33838" }, { "name": "HTML", "bytes": "37871" }, { "name": "JavaScript", "bytes": "38570" }, { "name": "Makefile", "bytes": "313" }, { "name": "PHP", "bytes": "1116232" }, { "name": "SQLPL", "bytes": "7923" }, { "name": "Shell", "bytes": "381" } ], "symlink_target": "" }
// Copyright 2015 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. /** * @fileoverview * 'settings-site-list' shows a list of Allowed and Blocked sites for a given * category. * * Example: * <settings-site-list prefs="{{prefs}}" * category="[[category]]"> * </settings-site-list> * * @group Chrome Settings Elements * @element settings-site-list */ Polymer({ is: 'settings-site-list', behaviors: [PrefsBehavior, SiteSettingsBehavior], properties: { /** * Preferences state. */ prefs: { type: Object, notify: true, }, /** * The current active route. */ currentRoute: { type: Object, notify: true, }, /** * The origin that was selected by the user in the dropdown list. */ selectedOrigin: { type: String, notify: true, }, /** * Array of sites to display in the widget. */ sites_: { type: Array, value: function() { return []; }, observer: 'onDataChanged_', }, /** * Whether this list is for the All Sites category. */ allSites: { type: Boolean, value: false, }, /** * The type of category this widget is displaying data for. Normally * either ALLOW or BLOCK, representing which sites are allowed or blocked * respectively. */ categorySubtype: { type: Number, value: -1, }, /** * Represents the state of the main toggle shown for the category. For * example, the Location category can be set to Block/Ask so false, in that * case, represents Block and true represents Ask. */ categoryEnabled: { type: Boolean, observer: 'onDataChanged_', value: true, }, /** * Whether to show the Allow action in the action menu. */ showAllowAction_: Boolean, /** * Whether to show the Block action in the action menu. */ showBlockAction_: Boolean, /** * All possible actions in the action menu. */ actions_: { readOnly: true, type: Object, values: { ALLOW: 'Allow', BLOCK: 'Block', RESET: 'Reset', } }, i18n_: { readOnly: true, type: Object, value: function() { return { allowAction: loadTimeData.getString('siteSettingsActionAllow'), blockAction: loadTimeData.getString('siteSettingsActionBlock'), resetAction: loadTimeData.getString('siteSettingsActionReset'), }; }, }, }, observers: [ 'initialize_(prefs.profile.content_settings.exceptions.*,' + 'category, categorySubtype, allSites)' ], /** * One-time initialization routines for this class. * @private */ initialize_: function() { CrSettingsPrefs.initialized.then(function() { this.setUpActionMenu_(); this.ensureOpened_(); }.bind(this)); this.populateList_(); }, /** * Ensures the widget is |opened| when needed when displayed initially. */ ensureOpened_: function() { // Allowed list is always shown opened by default and All Sites is presented // all in one list (nothing closed by default). if (this.allSites || this.categorySubtype == settings.PermissionValues.ALLOW) { this.$.category.opened = true; return; } // Block list should only be shown opened if there is nothing to show in // the allowed list. var pref = this.getPref( this.computeCategoryExceptionsPrefName(this.category)); var sites = pref.value; for (var origin in sites) { var site = /** @type {{setting: number}} */(sites[origin]); if (site.setting == settings.PermissionValues.ALLOW) return; } this.$.category.opened = true; }, /** * Handles the data changing, for example when the category is flipped from * ALLOW to BLOCK or sites are added to the list. * @private */ onDataChanged_: function(newValue, oldValue) { this.$.category.hidden = !this.showSiteList_(this.sites_, this.categoryEnabled); }, /** * Handles the expanding and collapsing of the sites list. * @private */ onToggle_: function(e) { if (this.$.category.opened) this.$.icon.icon = 'icons:expand-less'; else this.$.icon.icon = 'icons:expand-more'; }, /** * Populate the sites list for display. * @private */ populateList_: function() { if (this.allSites) { this.sites_ = this.toSiteArray_(this.getAllSitesList_()); } else { var sites = new Set(); this.sites_ = this.toSiteArray_( this.appendSiteList(sites, this.category, this.categorySubtype)); } }, /** * Retrieves a set of all known sites (any category/setting). * @private */ getAllSitesList_: function() { var sites = new Set(); for (var type in settings.ContentSettingsTypes) { sites = this.appendSiteList(sites, settings.ContentSettingsTypes[type], settings.PermissionValues.ALLOW); sites = this.appendSiteList(sites, settings.ContentSettingsTypes[type], settings.PermissionValues.BLOCK); } return sites; }, /** * Appends to |list| the sites for a given category and subtype. * @param {!Set<string>} list The site list to add to. * @param {number} category The category to look up. * @param {number} categorySubtype The category subtype to look up. * @return {!Set<string>} The list of sites found. */ appendSiteList: function(list, category, categorySubtype) { var pref = this.getPref( this.computeCategoryExceptionsPrefName(category)); var sites = pref.value; for (var origin in sites) { var site = /** @type {{setting: number}} */(sites[origin]); if (site.setting == categorySubtype) { var tokens = origin.split(','); list.add(tokens[0]); } } return list; }, /** * Converts a set of sites to an ordered array, sorted by site name then * protocol. * @param {!Set<string>} sites A set of sites to sort and convert to an array. * @private */ toSiteArray_: function(sites) { var list = [...sites]; list.sort(function(a, b) { var url1 = /** @type {{host: string}} */(new URL(a)); var url2 = /** @type {{host: string}} */(new URL(b)); var result = url1.host.localeCompare(url2.host); if (result == 0) return url1.protocol.localeCompare(url2.protocol); return result; }); return list; }, /** * Setup the values to use for the action menu. * @private */ setUpActionMenu_: function() { this.showAllowAction_ = this.categorySubtype == settings.PermissionValues.BLOCK; this.showBlockAction_ = this.categorySubtype == settings.PermissionValues.ALLOW && this.category != settings.ContentSettingsTypes.FULLSCREEN; }, /** * A handler for selecting a site (by clicking on the origin). * @private */ onOriginTap_: function(event) { this.selectedOrigin = event.model.item; var categorySelected = this.allSites ? 'all-sites' : 'site-settings-category-' + this.computeCategoryTextId(this.category); this.currentRoute = { page: this.currentRoute.page, section: 'privacy', subpage: ['site-settings', categorySelected, 'site-details'], }; }, /** * A handler for activating one of the menu action items. * @param {!{model: !{item: string}, * target: !{selectedItems: !{textContent: string}}}} event * @private */ onActionMenuIronSelect_: function(event) { var origin = event.model.item; var action = event.target.selectedItems[0].textContent; if (action == this.i18n_.resetAction) { this.resetCategoryPermissionForOrigin(origin, this.category); } else { var value = (action == this.i18n_.allowAction) ? settings.PermissionValues.ALLOW : settings.PermissionValues.BLOCK; this.setCategoryPermissionForOrigin(origin, value, this.category); } }, /** * Returns the appropriate header value for display. * @param {Array<string>} siteList The list of all sites to display for this * category subtype. * @param {boolean} toggleState The state of the global toggle for this * category. * @private */ computeSiteListHeader_: function(siteList, toggleState) { if (this.categorySubtype == settings.PermissionValues.ALLOW) { return loadTimeData.getStringF( 'titleAndCount', loadTimeData.getString( toggleState ? 'siteSettingsAllow' : 'siteSettingsExceptions'), siteList.length); } else { return loadTimeData.getStringF( 'titleAndCount', loadTimeData.getString('siteSettingsBlock'), siteList.length); } }, /** * Returns true if this widget is showing the allow list. * @private */ isAllowList_: function() { return this.categorySubtype == settings.PermissionValues.ALLOW; }, /** * Returns whether to show the site list. * @param {Array} siteList The list of all sites to display for this category * subtype. * @param {boolean} toggleState The state of the global toggle for this * category. * @private */ showSiteList_: function(siteList, toggleState) { if (siteList.length == 0) return false; // The Block list is only shown when the category is set to Allow since it // is redundant to also list all the sites that are blocked. if (this.isAllowList_()) return true; return toggleState; }, /** * Returns the icon to use for a given site. * @param {string} url The url of the site to fetch the icon for. * @private */ computeSiteIcon_: function(url) { // TODO(finnur): For now, we're returning a placeholder image for each site // but the actual favicon for each site will need to be returned. return 'communication:message'; }, });
{ "content_hash": "aa3e773c8a49f6793e77ded0a799609d", "timestamp": "", "source": "github", "line_count": 366, "max_line_length": 80, "avg_line_length": 27.94808743169399, "alnum_prop": 0.6120832925994721, "repo_name": "ds-hwang/chromium-crosswalk", "id": "d380c5cb46a8b41b4c53bd00fa12ab090845f7f0", "size": "10229", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "chrome/browser/resources/settings/site_settings/site_list.js", "mode": "33188", "license": "bsd-3-clause", "language": [], "symlink_target": "" }
<?php namespace App\Repositories\Frontend\Bible; use App\Models\Bible\Bible; use App\Repositories\Repository; /** * Class BibleRepository * @package App\Repositories\Frontend\Bible */ class BibleRepository extends Repository { /** * Associated Repository Model */ const MODEL = Bible::class; /** * * @return mixed */ public function findActiveBible() { return $this->query()->whereIn('id', [4, 7])->get(); } }
{ "content_hash": "d44b1981ab3f3f5af48f8a3b9ad60b10", "timestamp": "", "source": "github", "line_count": 27, "max_line_length": 60, "avg_line_length": 17.555555555555557, "alnum_prop": 0.6244725738396625, "repo_name": "linzhengen/kaihua", "id": "ea2283ae88a726204aa4f9071c3d5e5ea2c969e4", "size": "474", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "app/Repositories/Frontend/Bible/BibleRepository.php", "mode": "33188", "license": "mit", "language": [ { "name": "Dockerfile", "bytes": "4540" }, { "name": "HTML", "bytes": "131847" }, { "name": "JavaScript", "bytes": "33961" }, { "name": "PHP", "bytes": "534736" }, { "name": "Shell", "bytes": "5297" }, { "name": "Vue", "bytes": "401" } ], "symlink_target": "" }
<!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> <title>mathcomp-analysis: 18 m 5 s 🏆</title> <link rel="shortcut icon" type="image/png" href="../../../../../favicon.png" /> <link href="../../../../../bootstrap.min.css" rel="stylesheet"> <link href="../../../../../bootstrap-custom.css" rel="stylesheet"> <link href="//maxcdn.bootstrapcdn.com/font-awesome/4.2.0/css/font-awesome.min.css" rel="stylesheet"> <script src="../../../../../moment.min.js"></script> <!-- HTML5 Shim and Respond.js IE8 support of HTML5 elements and media queries --> <!-- WARNING: Respond.js doesn't work if you view the page via file:// --> <!--[if lt IE 9]> <script src="https://oss.maxcdn.com/html5shiv/3.7.2/html5shiv.min.js"></script> <script src="https://oss.maxcdn.com/respond/1.4.2/respond.min.js"></script> <![endif]--> </head> <body> <div class="container"> <div class="navbar navbar-default" role="navigation"> <div class="container-fluid"> <div class="navbar-header"> <a class="navbar-brand" href="../../../../.."><i class="fa fa-lg fa-flag-checkered"></i> Coq bench</a> </div> <div id="navbar" class="collapse navbar-collapse"> <ul class="nav navbar-nav"> <li><a href="../..">clean / released</a></li> <li class="active"><a href="">8.13.1 / mathcomp-analysis - 0.3.13</a></li> </ul> </div> </div> </div> <div class="article"> <div class="row"> <div class="col-md-12"> <a href="../..">« Up</a> <h1> mathcomp-analysis <small> 0.3.13 <span class="label label-success">18 m 5 s 🏆</span> </small> </h1> <p>📅 <em><script>document.write(moment("2022-09-14 21:30:01 +0000", "YYYY-MM-DD HH:mm:ss Z").fromNow());</script> (2022-09-14 21:30:01 UTC)</em><p> <h2>Context</h2> <pre># Packages matching: installed # Name # Installed # Synopsis base-bigarray base base-threads base base-unix base conf-findutils 1 Virtual package relying on findutils conf-gmp 4 Virtual package relying on a GMP lib system installation coq 8.13.1 Formal proof management system num 1.4 The legacy Num library for arbitrary-precision integer and rational arithmetic ocaml 4.08.1 The OCaml compiler (virtual package) ocaml-base-compiler 4.08.1 Official release 4.08.1 ocaml-config 1 OCaml Switch Configuration ocamlfind 1.9.5 A library manager for OCaml zarith 1.12 Implements arithmetic and logical operations over arbitrary-precision integers # opam file: opam-version: &quot;2.0&quot; maintainer: &quot;Reynald Affeldt &lt;[email protected]&gt;&quot; homepage: &quot;https://github.com/math-comp/analysis&quot; dev-repo: &quot;git+https://github.com/math-comp/analysis.git&quot; bug-reports: &quot;https://github.com/math-comp/analysis/issues&quot; license: &quot;CECILL-C&quot; synopsis: &quot;An analysis library for mathematical components&quot; description: &quot;&quot;&quot; This repository contains an experimental library for real analysis for the Coq proof-assistant and using the Mathematical Components library.&quot;&quot;&quot; build: [make &quot;-j%{jobs}%&quot;] install: [make &quot;install&quot;] depends: [ &quot;coq&quot; { (&gt;= &quot;8.13&quot; &amp; &lt; &quot;8.16~&quot;) | (= &quot;dev&quot;) } &quot;coq-mathcomp-ssreflect&quot; { (&gt;= &quot;1.12.0&quot; &amp; &lt; &quot;1.15~&quot;) | (= &quot;dev&quot;) } &quot;coq-mathcomp-fingroup&quot; &quot;coq-mathcomp-algebra&quot; &quot;coq-mathcomp-solvable&quot; &quot;coq-mathcomp-field&quot; &quot;coq-mathcomp-finmap&quot; { (&gt;= &quot;1.5.1&quot; &amp; &lt; &quot;1.6~&quot;) | (= &quot;dev&quot;) } &quot;coq-mathcomp-bigenough&quot; { (&gt;= &quot;1.0.0&quot;) } &quot;coq-hierarchy-builder&quot; { (&gt;= &quot;1.0.0&quot;) } ] tags: [ &quot;category:Mathematics/Real Calculus and Topology&quot; &quot;keyword:analysis&quot; &quot;keyword:topology&quot; &quot;keyword:real numbers&quot; &quot;date:2022-01-24&quot; &quot;logpath:mathcomp.analysis&quot; ] authors: [ &quot;Reynald Affeldt&quot; &quot;Yves Bertot&quot; &quot;Cyril Cohen&quot; &quot;Marie Kerjean&quot; &quot;Assia Mahboubi&quot; &quot;Damien Rouhling&quot; &quot;Pierre Roux&quot; &quot;Kazuhiko Sakaguchi&quot; &quot;Zachary Stone&quot; &quot;Pierre-Yves Strub&quot; &quot;Laurent Théry&quot; ] url { http: &quot;https://github.com/math-comp/analysis/archive/0.3.13.tar.gz&quot; checksum: &quot;sha512=3f508d94166dbf8a35924230fa1c6f2500c7206c77bd0dbd83cae3a9841d94f475706462a73042af573c2e9022b7cfa58856d263c51f94c35ef08650e2bae6d4&quot; }</pre> <h2>Lint</h2> <dl class="dl-horizontal"> <dt>Command</dt> <dd><code>true</code></dd> <dt>Return code</dt> <dd>0</dd> </dl> <h2>Dry install 🏜️</h2> <p>Dry install with the current Coq version:</p> <dl class="dl-horizontal"> <dt>Command</dt> <dd><code>opam install -y --show-action coq-mathcomp-analysis.0.3.13 coq.8.13.1</code></dd> <dt>Return code</dt> <dd>0</dd> </dl> <p>Dry install without Coq/switch base, to test if the problem was incompatibility with the current Coq/OCaml version:</p> <dl class="dl-horizontal"> <dt>Command</dt> <dd><code>true</code></dd> <dt>Return code</dt> <dd>0</dd> </dl> <h2>Install dependencies</h2> <dl class="dl-horizontal"> <dt>Command</dt> <dd><code>opam list; echo; ulimit -Sv 4000000; timeout 4h opam install -y --deps-only coq-mathcomp-analysis.0.3.13 coq.8.13.1</code></dd> <dt>Return code</dt> <dd>0</dd> <dt>Duration</dt> <dd>48 m 51 s</dd> </dl> <h2>Install 🚀</h2> <dl class="dl-horizontal"> <dt>Command</dt> <dd><code>opam list; echo; ulimit -Sv 16000000; timeout 4h opam install -y -v coq-mathcomp-analysis.0.3.13 coq.8.13.1</code></dd> <dt>Return code</dt> <dd>0</dd> <dt>Duration</dt> <dd>18 m 5 s</dd> </dl> <h2>Installation size</h2> <p>Total: 22 M</p> <ul> <li>2 M <code>../ocaml-base-compiler.4.08.1/lib/coq/user-contrib/mathcomp/analysis/ereal.glob</code></li> <li>1 M <code>../ocaml-base-compiler.4.08.1/lib/coq/user-contrib/mathcomp/analysis/topology.vo</code></li> <li>1 M <code>../ocaml-base-compiler.4.08.1/lib/coq/user-contrib/mathcomp/analysis/topology.glob</code></li> <li>1 M <code>../ocaml-base-compiler.4.08.1/lib/coq/user-contrib/mathcomp/analysis/normedtype.glob</code></li> <li>1 M <code>../ocaml-base-compiler.4.08.1/lib/coq/user-contrib/mathcomp/analysis/normedtype.vo</code></li> <li>1 M <code>../ocaml-base-compiler.4.08.1/lib/coq/user-contrib/mathcomp/analysis/ereal.vo</code></li> <li>856 K <code>../ocaml-base-compiler.4.08.1/lib/coq/user-contrib/mathcomp/analysis/derive.vo</code></li> <li>840 K <code>../ocaml-base-compiler.4.08.1/lib/coq/user-contrib/mathcomp/analysis/sequences.vo</code></li> <li>705 K <code>../ocaml-base-compiler.4.08.1/lib/coq/user-contrib/mathcomp/analysis/derive.glob</code></li> <li>674 K <code>../ocaml-base-compiler.4.08.1/lib/coq/user-contrib/mathcomp/analysis/sequences.glob</code></li> <li>572 K <code>../ocaml-base-compiler.4.08.1/lib/coq/user-contrib/mathcomp/analysis/classical_sets.glob</code></li> <li>511 K <code>../ocaml-base-compiler.4.08.1/lib/coq/user-contrib/mathcomp/analysis/landau.vo</code></li> <li>506 K <code>../ocaml-base-compiler.4.08.1/lib/coq/user-contrib/mathcomp/analysis/measure.vo</code></li> <li>486 K <code>../ocaml-base-compiler.4.08.1/lib/coq/user-contrib/mathcomp/analysis/trigo.glob</code></li> <li>426 K <code>../ocaml-base-compiler.4.08.1/lib/coq/user-contrib/mathcomp/analysis/classical_sets.vo</code></li> <li>414 K <code>../ocaml-base-compiler.4.08.1/lib/coq/user-contrib/mathcomp/analysis/landau.glob</code></li> <li>413 K <code>../ocaml-base-compiler.4.08.1/lib/coq/user-contrib/mathcomp/analysis/altreals/realsum.glob</code></li> <li>404 K <code>../ocaml-base-compiler.4.08.1/lib/coq/user-contrib/mathcomp/analysis/measure.glob</code></li> <li>399 K <code>../ocaml-base-compiler.4.08.1/lib/coq/user-contrib/mathcomp/analysis/cardinality.vo</code></li> <li>397 K <code>../ocaml-base-compiler.4.08.1/lib/coq/user-contrib/mathcomp/analysis/altreals/distr.glob</code></li> <li>392 K <code>../ocaml-base-compiler.4.08.1/lib/coq/user-contrib/mathcomp/analysis/trigo.vo</code></li> <li>368 K <code>../ocaml-base-compiler.4.08.1/lib/coq/user-contrib/mathcomp/analysis/cardinality.glob</code></li> <li>357 K <code>../ocaml-base-compiler.4.08.1/lib/coq/user-contrib/mathcomp/analysis/exp.vo</code></li> <li>304 K <code>../ocaml-base-compiler.4.08.1/lib/coq/user-contrib/mathcomp/analysis/altreals/realsum.vo</code></li> <li>301 K <code>../ocaml-base-compiler.4.08.1/lib/coq/user-contrib/mathcomp/analysis/altreals/distr.vo</code></li> <li>298 K <code>../ocaml-base-compiler.4.08.1/lib/coq/user-contrib/mathcomp/analysis/realfun.vo</code></li> <li>283 K <code>../ocaml-base-compiler.4.08.1/lib/coq/user-contrib/mathcomp/analysis/exp.glob</code></li> <li>227 K <code>../ocaml-base-compiler.4.08.1/lib/coq/user-contrib/mathcomp/analysis/topology.v</code></li> <li>217 K <code>../ocaml-base-compiler.4.08.1/lib/coq/user-contrib/mathcomp/analysis/reals.vo</code></li> <li>198 K <code>../ocaml-base-compiler.4.08.1/lib/coq/user-contrib/mathcomp/analysis/reals.glob</code></li> <li>198 K <code>../ocaml-base-compiler.4.08.1/lib/coq/user-contrib/mathcomp/analysis/realfun.glob</code></li> <li>191 K <code>../ocaml-base-compiler.4.08.1/lib/coq/user-contrib/mathcomp/analysis/Rstruct.vo</code></li> <li>168 K <code>../ocaml-base-compiler.4.08.1/lib/coq/user-contrib/mathcomp/analysis/normedtype.v</code></li> <li>160 K <code>../ocaml-base-compiler.4.08.1/lib/coq/user-contrib/mathcomp/analysis/altreals/realseq.vo</code></li> <li>160 K <code>../ocaml-base-compiler.4.08.1/lib/coq/user-contrib/mathcomp/analysis/Rstruct.glob</code></li> <li>157 K <code>../ocaml-base-compiler.4.08.1/lib/coq/user-contrib/mathcomp/analysis/boolp.glob</code></li> <li>148 K <code>../ocaml-base-compiler.4.08.1/lib/coq/user-contrib/mathcomp/analysis/altreals/realseq.glob</code></li> <li>138 K <code>../ocaml-base-compiler.4.08.1/lib/coq/user-contrib/mathcomp/analysis/forms.glob</code></li> <li>136 K <code>../ocaml-base-compiler.4.08.1/lib/coq/user-contrib/mathcomp/analysis/ereal.v</code></li> <li>135 K <code>../ocaml-base-compiler.4.08.1/lib/coq/user-contrib/mathcomp/analysis/forms.vo</code></li> <li>128 K <code>../ocaml-base-compiler.4.08.1/lib/coq/user-contrib/mathcomp/analysis/csum.vo</code></li> <li>117 K <code>../ocaml-base-compiler.4.08.1/lib/coq/user-contrib/mathcomp/analysis/boolp.vo</code></li> <li>114 K <code>../ocaml-base-compiler.4.08.1/lib/coq/user-contrib/mathcomp/analysis/nsatz_realtype.vo</code></li> <li>99 K <code>../ocaml-base-compiler.4.08.1/lib/coq/user-contrib/mathcomp/analysis/csum.glob</code></li> <li>79 K <code>../ocaml-base-compiler.4.08.1/lib/coq/user-contrib/mathcomp/analysis/classical_sets.v</code></li> <li>73 K <code>../ocaml-base-compiler.4.08.1/lib/coq/user-contrib/mathcomp/analysis/sequences.v</code></li> <li>64 K <code>../ocaml-base-compiler.4.08.1/lib/coq/user-contrib/mathcomp/analysis/landau.v</code></li> <li>63 K <code>../ocaml-base-compiler.4.08.1/lib/coq/user-contrib/mathcomp/analysis/derive.v</code></li> <li>56 K <code>../ocaml-base-compiler.4.08.1/lib/coq/user-contrib/mathcomp/analysis/altreals/discrete.vo</code></li> <li>55 K <code>../ocaml-base-compiler.4.08.1/lib/coq/user-contrib/mathcomp/analysis/altreals/xfinmap.vo</code></li> <li>55 K <code>../ocaml-base-compiler.4.08.1/lib/coq/user-contrib/mathcomp/analysis/posnum.vo</code></li> <li>54 K <code>../ocaml-base-compiler.4.08.1/lib/coq/user-contrib/mathcomp/analysis/measure.v</code></li> <li>53 K <code>../ocaml-base-compiler.4.08.1/lib/coq/user-contrib/mathcomp/analysis/cardinality.v</code></li> <li>50 K <code>../ocaml-base-compiler.4.08.1/lib/coq/user-contrib/mathcomp/analysis/nngnum.vo</code></li> <li>47 K <code>../ocaml-base-compiler.4.08.1/lib/coq/user-contrib/mathcomp/analysis/altreals/xfinmap.glob</code></li> <li>46 K <code>../ocaml-base-compiler.4.08.1/lib/coq/user-contrib/mathcomp/analysis/summability.vo</code></li> <li>45 K <code>../ocaml-base-compiler.4.08.1/lib/coq/user-contrib/mathcomp/analysis/altreals/realsum.v</code></li> <li>43 K <code>../ocaml-base-compiler.4.08.1/lib/coq/user-contrib/mathcomp/analysis/trigo.v</code></li> <li>41 K <code>../ocaml-base-compiler.4.08.1/lib/coq/user-contrib/mathcomp/analysis/altreals/distr.v</code></li> <li>39 K <code>../ocaml-base-compiler.4.08.1/lib/coq/user-contrib/mathcomp/analysis/nngnum.glob</code></li> <li>34 K <code>../ocaml-base-compiler.4.08.1/lib/coq/user-contrib/mathcomp/analysis/posnum.glob</code></li> <li>33 K <code>../ocaml-base-compiler.4.08.1/lib/coq/user-contrib/mathcomp/analysis/altreals/discrete.glob</code></li> <li>31 K <code>../ocaml-base-compiler.4.08.1/lib/coq/user-contrib/mathcomp/analysis/prodnormedzmodule.vo</code></li> <li>30 K <code>../ocaml-base-compiler.4.08.1/lib/coq/user-contrib/mathcomp/analysis/reals.v</code></li> <li>26 K <code>../ocaml-base-compiler.4.08.1/lib/coq/user-contrib/mathcomp/analysis/Rstruct.v</code></li> <li>25 K <code>../ocaml-base-compiler.4.08.1/lib/coq/user-contrib/mathcomp/analysis/boolp.v</code></li> <li>24 K <code>../ocaml-base-compiler.4.08.1/lib/coq/user-contrib/mathcomp/analysis/exp.v</code></li> <li>23 K <code>../ocaml-base-compiler.4.08.1/lib/coq/user-contrib/mathcomp/analysis/realfun.v</code></li> <li>22 K <code>../ocaml-base-compiler.4.08.1/lib/coq/user-contrib/mathcomp/analysis/forms.v</code></li> <li>19 K <code>../ocaml-base-compiler.4.08.1/lib/coq/user-contrib/mathcomp/analysis/altreals/realseq.v</code></li> <li>16 K <code>../ocaml-base-compiler.4.08.1/lib/coq/user-contrib/mathcomp/analysis/prodnormedzmodule.glob</code></li> <li>13 K <code>../ocaml-base-compiler.4.08.1/lib/coq/user-contrib/mathcomp/analysis/csum.v</code></li> <li>8 K <code>../ocaml-base-compiler.4.08.1/lib/coq/user-contrib/mathcomp/analysis/posnum.v</code></li> <li>8 K <code>../ocaml-base-compiler.4.08.1/lib/coq/user-contrib/mathcomp/analysis/summability.glob</code></li> <li>7 K <code>../ocaml-base-compiler.4.08.1/lib/coq/user-contrib/mathcomp/analysis/nngnum.v</code></li> <li>7 K <code>../ocaml-base-compiler.4.08.1/lib/coq/user-contrib/mathcomp/analysis/altreals/discrete.v</code></li> <li>7 K <code>../ocaml-base-compiler.4.08.1/lib/coq/user-contrib/mathcomp/analysis/nsatz_realtype.glob</code></li> <li>5 K <code>../ocaml-base-compiler.4.08.1/lib/coq/user-contrib/mathcomp/analysis/altreals/xfinmap.v</code></li> <li>3 K <code>../ocaml-base-compiler.4.08.1/lib/coq/user-contrib/mathcomp/analysis/nsatz_realtype.v</code></li> <li>2 K <code>../ocaml-base-compiler.4.08.1/lib/coq/user-contrib/mathcomp/analysis/prodnormedzmodule.v</code></li> <li>2 K <code>../ocaml-base-compiler.4.08.1/lib/coq/user-contrib/mathcomp/analysis/summability.v</code></li> </ul> <h2>Uninstall 🧹</h2> <dl class="dl-horizontal"> <dt>Command</dt> <dd><code>opam remove -y coq-mathcomp-analysis.0.3.13</code></dd> <dt>Return code</dt> <dd>0</dd> <dt>Missing removes</dt> <dd> none </dd> <dt>Wrong removes</dt> <dd> none </dd> </dl> </div> </div> </div> <hr/> <div class="footer"> <p class="text-center"> Sources are on <a href="https://github.com/coq-bench">GitHub</a> © Guillaume Claret 🐣 </p> </div> </div> <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script> <script src="../../../../../bootstrap.min.js"></script> </body> </html>
{ "content_hash": "8405b79e7063d8c35725c775bc3b7afd", "timestamp": "", "source": "github", "line_count": 263, "max_line_length": 159, "avg_line_length": 67.5551330798479, "alnum_prop": 0.6116958406033658, "repo_name": "coq-bench/coq-bench.github.io", "id": "bcf2e842e9a35a50c4d82341b8f8b09dfbf02396", "size": "17793", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "clean/Linux-x86_64-4.08.1-2.0.5/released/8.13.1/mathcomp-analysis/0.3.13.html", "mode": "33188", "license": "mit", "language": [], "symlink_target": "" }
<?php /* SonataAdminBundle:CRUD:show.html.twig */ class __TwigTemplate_84ec08d2060a6860a71dbd8bb9840c79a8dba26704e828de41cf19074c7b7a86 extends Twig_Template { public function __construct(Twig_Environment $env) { parent::__construct($env); // line 12 try { $this->parent = $this->env->loadTemplate("SonataAdminBundle:CRUD:base_show.html.twig"); } catch (Twig_Error_Loader $e) { $e->setTemplateFile($this->getTemplateName()); $e->setTemplateLine(12); throw $e; } $this->blocks = array( ); } protected function doGetParent(array $context) { return "SonataAdminBundle:CRUD:base_show.html.twig"; } protected function doDisplay(array $context, array $blocks = array()) { $this->parent->display($context, array_merge($this->blocks, $blocks)); } public function getTemplateName() { return "SonataAdminBundle:CRUD:show.html.twig"; } public function isTraitable() { return false; } public function getDebugInfo() { return array ( 11 => 12,); } }
{ "content_hash": "10be0597e11501f756666c3fea592c73", "timestamp": "", "source": "github", "line_count": 48, "max_line_length": 107, "avg_line_length": 24.229166666666668, "alnum_prop": 0.5993121238177128, "repo_name": "orlk/hopitrepo", "id": "5a2e62eb1f798eb4a133d3da462a3dcd98627166", "size": "1163", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "app/cache/prod/twig/84/ec/08d2060a6860a71dbd8bb9840c79a8dba26704e828de41cf19074c7b7a86.php", "mode": "33188", "license": "mit", "language": [ { "name": "ApacheConf", "bytes": "3073" }, { "name": "Batchfile", "bytes": "373" }, { "name": "CSS", "bytes": "102659" }, { "name": "HTML", "bytes": "155478" }, { "name": "JavaScript", "bytes": "130336" }, { "name": "PHP", "bytes": "257295" }, { "name": "Shell", "bytes": "593" } ], "symlink_target": "" }
SCRIPTS_DIR=.. JAR_FILES=$(wildcard java_targets/jar/*.jar) define check_no_diff cmp $(1) $(2) >&2 || \ (printf "ERROR: Output of $(1) differs from $(2)\n" >&2; exit 1) endef default: test-classdump build-targets: make -C java_targets test-classdump: build-targets python3 $(SCRIPTS_DIR)/classdump.py --output $(SCRIPTS_DIR)/test/classdump_out $(JAR_FILES) @$(foreach jarfile,$(notdir $(JAR_FILES)),$(call check_no_diff,$(SCRIPTS_DIR)/test/classdump_out/$(jarfile).classes,$(SCRIPTS_DIR)/test/classdump_exp/$(jarfile).classes.exp);) clean: rm -rf java_targets/jar rm -rf classdump_out
{ "content_hash": "693b8e49215b9cf02f41a849b8fb4dba", "timestamp": "", "source": "github", "line_count": 20, "max_line_length": 176, "avg_line_length": 29.85, "alnum_prop": 0.6968174204355109, "repo_name": "facebook/infer", "id": "886a01652f42b29c70a03e0868a570ad4d3323a8", "size": "775", "binary": false, "copies": "1", "ref": "refs/heads/main", "path": "infer/src/datalog/scripts/test/Makefile", "mode": "33188", "license": "mit", "language": [ { "name": "AL", "bytes": "8678" }, { "name": "Assembly", "bytes": "458" }, { "name": "C", "bytes": "368102" }, { "name": "C++", "bytes": "850420" }, { "name": "CMake", "bytes": "221" }, { "name": "Common Lisp", "bytes": "3958" }, { "name": "Dockerfile", "bytes": "4425" }, { "name": "Emacs Lisp", "bytes": "3422" }, { "name": "Erlang", "bytes": "133088" }, { "name": "Hack", "bytes": "3981" }, { "name": "Java", "bytes": "1208982" }, { "name": "Kotlin", "bytes": "2936" }, { "name": "M4", "bytes": "27010" }, { "name": "Makefile", "bytes": "300000" }, { "name": "OCaml", "bytes": "8120133" }, { "name": "Objective-C", "bytes": "417679" }, { "name": "Objective-C++", "bytes": "26467" }, { "name": "OpenEdge ABL", "bytes": "9970" }, { "name": "Python", "bytes": "7241" }, { "name": "SMT", "bytes": "3037021" }, { "name": "Shell", "bytes": "51138" }, { "name": "Standard ML", "bytes": "390681" }, { "name": "Starlark", "bytes": "3337" } ], "symlink_target": "" }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Linq; using System.Windows; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.ChangeSignature; using Microsoft.CodeAnalysis.Shared.Extensions; namespace Microsoft.VisualStudio.LanguageServices.Implementation.ChangeSignature { internal partial class ChangeSignatureDialogViewModel { public abstract class ParameterViewModel { protected ChangeSignatureDialogViewModel ChangeSignatureDialogViewModel { get; } public abstract Parameter Parameter { get; } public abstract string Type { get; } public abstract string ParameterName { get; } public abstract bool IsRemoved { get; set; } public abstract bool IsDisabled { get; } public abstract string CallSite { get; } public abstract bool IsRequired { get; } public abstract string DefaultValue { get; } public abstract string InitialIndex { get; } public abstract string Modifier { get; } public abstract string Default { get; } public string ModifierAutomationText => ValueOrNone(Modifier); public string DefaultAutomationText => ValueOrNone(Default); public string CallSiteAutomationText => ValueOrNone(CallSite); public ParameterViewModel(ChangeSignatureDialogViewModel changeSignatureDialogViewModel) { ChangeSignatureDialogViewModel = changeSignatureDialogViewModel; } private string ValueOrNone(string value) { return !string.IsNullOrEmpty(value) ? value : ServicesVSResources.None; } public Visibility HasParameterNameConflict { get; set; } public virtual Visibility TypeWarningVisibility => Visibility.Collapsed; public string ShortAutomationText => $"{Type} {ParameterName}"; public virtual string FullAutomationText { get { var text = $"{Modifier} {Type} {ParameterName}"; if (!string.IsNullOrWhiteSpace(Default)) { text += $" = {Default}"; } return text; } } public bool NeedsBottomBorder { get { if (this == ChangeSignatureDialogViewModel._thisParameter) { return true; } if (this == ChangeSignatureDialogViewModel._parametersWithoutDefaultValues.LastOrDefault() && (ChangeSignatureDialogViewModel._parametersWithDefaultValues.Any() || ChangeSignatureDialogViewModel._paramsParameter != null)) { return true; } if (this == ChangeSignatureDialogViewModel._parametersWithDefaultValues.LastOrDefault() && ChangeSignatureDialogViewModel._paramsParameter != null) { return true; } return false; } } public virtual string CallSiteValue => string.Empty; } public class AddedParameterViewModel : ParameterViewModel { public override Parameter Parameter => _addedParameter; private readonly AddedParameter _addedParameter; public AddedParameterViewModel(ChangeSignatureDialogViewModel changeSignatureDialogViewModel, AddedParameter addedParameter) : base(changeSignatureDialogViewModel) { _addedParameter = addedParameter; } public override string Type => _addedParameter.TypeName; public override Visibility TypeWarningVisibility => _addedParameter.TypeBinds ? Visibility.Collapsed : Visibility.Visible; public override string ParameterName => _addedParameter.Name; public override bool IsRemoved { get => false; set => throw new InvalidOperationException(); } public override string FullAutomationText { get { var baseText = base.FullAutomationText; return ServicesVSResources.Added_Parameter + baseText + string.Format(ServicesVSResources.Inserting_call_site_value_0, CallSite); } } public override bool IsDisabled => false; public override string CallSite { get { return _addedParameter.CallSiteKind == CallSiteKind.ValueWithName ? _addedParameter.Name + ": " + _addedParameter.CallSiteValue : _addedParameter.CallSiteValue; } } public override string CallSiteValue => _addedParameter.CallSiteValue; public override string InitialIndex => "+"; // Newly added parameters cannot have modifiers yet public override string Modifier => string.Empty; public override string Default => _addedParameter.DefaultValue; public override bool IsRequired => _addedParameter.IsRequired; public override string DefaultValue => _addedParameter.DefaultValue; } public class ExistingParameterViewModel : ParameterViewModel { public IParameterSymbol ParameterSymbol => _existingParameter.Symbol; private readonly ExistingParameter _existingParameter; public override Parameter Parameter => _existingParameter; public ExistingParameterViewModel(ChangeSignatureDialogViewModel changeSignatureDialogViewModel, ExistingParameter existingParameter, int initialIndex) : base(changeSignatureDialogViewModel) { _existingParameter = existingParameter; InitialIndex = initialIndex.ToString(); } public override string CallSite => string.Empty; public override string InitialIndex { get; } public override string Modifier { get { switch (ParameterSymbol.Language) { case LanguageNames.CSharp: return ModifierText("out", "ref", "in", "params", "this"); case LanguageNames.VisualBasic: return ModifierText(@out: null, "ByRef", @in: null, "ParamArray", "Me"); default: return string.Empty; } string ModifierText(string? @out, string? @ref, string? @in, string? @params, string? @this) { switch (ParameterSymbol.RefKind) { case RefKind.Out: return @out ?? string.Empty; case RefKind.Ref: return @ref ?? string.Empty; case RefKind.In: return @in ?? string.Empty; } if (ParameterSymbol.IsParams) { return @params ?? string.Empty; } if (ChangeSignatureDialogViewModel._thisParameter != null && ParameterSymbol == (ChangeSignatureDialogViewModel._thisParameter as ExistingParameterViewModel).ParameterSymbol) { return @this ?? string.Empty; } return string.Empty; } } } public override string Type => ParameterSymbol.Type.ToDisplayString(s_parameterDisplayFormat); public override string ParameterName => ParameterSymbol.Name; public override string Default { get { if (!ParameterSymbol.HasExplicitDefaultValue) { return string.Empty; } switch (ParameterSymbol.Language) { case LanguageNames.CSharp: return NullText("null", "default"); case LanguageNames.VisualBasic: return NullText("Nothing", "Nothing"); } return string.Empty; string NullText(string @null, string @default) { return ParameterSymbol.ExplicitDefaultValue == null ? (ParameterSymbol.Type.IsReferenceType ? @null : @default) : ParameterSymbol.ExplicitDefaultValue is string ? "\"" + ParameterSymbol.ExplicitDefaultValue.ToString() + "\"" : ParameterSymbol.ExplicitDefaultValue.ToString(); } } } public override bool IsDisabled => ChangeSignatureDialogViewModel.IsDisabled(this); public override bool IsRemoved { get; set; } public override bool IsRequired => !ParameterSymbol.HasExplicitDefaultValue; public override string DefaultValue => Default; } } }
{ "content_hash": "326209424481671ecd2007a4d07762d8", "timestamp": "", "source": "github", "line_count": 254, "max_line_length": 163, "avg_line_length": 39.12204724409449, "alnum_prop": 0.5402032806682098, "repo_name": "gafter/roslyn", "id": "9b6bef8e0b349d6f005f8c0d23aae4f472fbdf06", "size": "9939", "binary": false, "copies": "7", "ref": "refs/heads/master", "path": "src/VisualStudio/Core/Def/Implementation/ChangeSignature/ChangeSignatureDialogViewModel.ParameterViewModels.cs", "mode": "33188", "license": "mit", "language": [ { "name": "1C Enterprise", "bytes": "289100" }, { "name": "Batchfile", "bytes": "9059" }, { "name": "C#", "bytes": "127508767" }, { "name": "C++", "bytes": "5602" }, { "name": "CMake", "bytes": "5469" }, { "name": "Dockerfile", "bytes": "2450" }, { "name": "F#", "bytes": "549" }, { "name": "PowerShell", "bytes": "226728" }, { "name": "Shell", "bytes": "93516" }, { "name": "Visual Basic .NET", "bytes": "70629236" } ], "symlink_target": "" }
var audio = document.getElementById('audioElement'); var searchReusltsArray = []; // Results Array from Last.Fm // Control Buttons var playPauseBtn = document.getElementById('PPBtn'); var nextAudio = document.getElementById('forward'); var prevAudio = document.getElementById('backward'); var audioSlider = document.getElementsByClassName('seekSlider'); // Time Display var curTime = document.getElementsByClassName('currentTime'); var lefTime = document.getElementsByClassName('leftTime'); var prevVolume; // Search Elements var searchBox = document.getElementById('searchInput'); searchBox.addEventListener('keydown', function (keyDownValue) { if (keyDownValue.keyCode === 13) sendData(); }); var submitBtn = document.getElementById('submitBtn'); submitBtn.addEventListener('click', sendData); // Delayed function for Last.Fm request var getTracksFromLastFm = _.debounce(function () { var data = searchBox.value; if (data.trim() === "") return; data = data.replace(/ /g, "%20"); var url = "http://ws.audioscrobbler.com/2.0/?method=track.search&track=" + data + "&api_key=7ede02c397c8cf99bf26e1f8cb9681fa&format=json"; $.ajax({ type: 'GET', contentType: 'application/json', url: url, success: function (data) { searchReusltsArray.length = 0; for (var i = 0; i < data.results.trackmatches.track.length; i++) searchReusltsArray.push(data.results.trackmatches.track[i].name + " - " + data.results.trackmatches.track[i].artist); }, error: function () { console.log("Error Occurred"); } }); }, 250); // AutoCompletion From Results of Last.Fm $("#searchInput").autocomplete({ source: searchReusltsArray }); // Continued Search Elements... var isPlaying = false; searchBox.addEventListener("keyup", getTracksFromLastFm); // Audio Elements var audioImage = document.getElementById('songImage'); audioImage.addEventListener('error', function (event) { var image = event.target; image.src = './../static/Images/brokenalbumart.png'; }); var audioName = document.getElementsByClassName('songName'); function formatTime(time) { var tempTime = time; var minutes = parseInt((tempTime / 60).toString()); var seconds = parseInt((tempTime % 60).toString()); var stringMinutes = minutes < 10 ? "0" + minutes : minutes.toString(); var stringSeconds = seconds < 10 ? "0" + seconds : seconds.toString(); var formattedTime = stringMinutes + ":" + stringSeconds; return formattedTime; } audio.addEventListener('timeupdate', function () { var value = (100 / audio.duration) * audio.currentTime; var i; for (i = 0; i < audioSlider.length; i++) audioSlider[i].value = value.toString(); for (i = 0; i < curTime.length; i++) { curTime[i].innerHTML = formatTime(audio.currentTime); lefTime[i].innerHTML = formatTime(audio.duration - audio.currentTime); } }); playPauseBtn.addEventListener('click', function () { if (isPlaying) { playPauseBtn.innerHTML = 'play_arrow'; audio.pause(); isPlaying = false; } else { playPauseBtn.innerHTML = 'pause'; audio.play(); isPlaying = true; } }); audioSlider[0].addEventListener('change', function () { var time = audio.duration * (parseFloat(audioSlider[0].value) / 100); audio.currentTime = time; }); audioSlider[1].addEventListener('change', function () { var time = audio.duration * (parseFloat(audioSlider[1].value) / 100); audio.currentTime = time; }); audioSlider[0].addEventListener('mousedown', function () { if (isPlaying) audio.pause(); }); audioSlider[1].addEventListener('mousedown', function () { if (isPlaying) audio.pause(); }); audioSlider[0].addEventListener('mouseup', function () { if (isPlaying) audio.play(); }); audioSlider[1].addEventListener('mouseup', function () { if (isPlaying) audio.play(); }); nextAudio.addEventListener('click', function () { // TODO: Change Audio }); prevAudio.addEventListener('click', function () { // TODO: Change Audio }); function sendData() { var data = { 'title': searchBox.value }; $.ajax({ type: 'POST', contentType: 'application/json', data: JSON.stringify(data), url: '/get_video', success: function (data) { if (data.success) { audio.src = data.music.url; audio.play(); isPlaying = true; audioImage.src = data.music.image; audioImage.style.display = 'block'; for (var i = 0; i < audioName.length; i++) audioName[i].innerHTML = data.music.name; playPauseBtn.innerHTML = 'pause'; } else { console.log("Error Occurred"); window.alert("Error Occurred"); } }, error: function () { console.log("Error Occurred"); window.alert("Error Occurred"); } }); }
{ "content_hash": "9926a74287147b9eb7612a7d683a8955", "timestamp": "", "source": "github", "line_count": 164, "max_line_length": 89, "avg_line_length": 31.378048780487806, "alnum_prop": 0.620093276331131, "repo_name": "fumen/gae-fumen", "id": "6283e2d105e4950ad6347bd4d360807cd5d99756", "size": "5310", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "static/javascripts/Script.js", "mode": "33188", "license": "bsd-3-clause", "language": [ { "name": "C", "bytes": "519202" }, { "name": "C++", "bytes": "73693" }, { "name": "CSS", "bytes": "175785" }, { "name": "HTML", "bytes": "16008" }, { "name": "JavaScript", "bytes": "100249" }, { "name": "Python", "bytes": "5388641" }, { "name": "XSLT", "bytes": "152770" } ], "symlink_target": "" }
package org.wikipedia.page; import android.content.Context; import android.view.LayoutInflater; import android.view.View; import android.widget.TextView; import org.wikipedia.R; import org.wikipedia.util.StringUtil; /** * A dialog that displays the currently clicked reference. */ public class ReferenceDialog extends NoDimBottomSheetDialog { public ReferenceDialog(Context context, LinkHandler linkHandler, String html) { super(context); View rootView = LayoutInflater.from(context).inflate(R.layout.dialog_reference, null); setContentView(rootView); TextView referenceText = (TextView) rootView.findViewById(R.id.reference_text); referenceText.setText(StringUtil.fromHtml(html)); referenceText.setMovementMethod(new LinkMovementMethodExt(linkHandler)); } }
{ "content_hash": "569a304a58cba6c2210b46c6260c48dc", "timestamp": "", "source": "github", "line_count": 24, "max_line_length": 94, "avg_line_length": 34.208333333333336, "alnum_prop": 0.761266747868453, "repo_name": "anirudh24seven/apps-android-wikipedia", "id": "b3065fa7e645fce22ecff173f28794673a20b1e5", "size": "821", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "app/src/main/java/org/wikipedia/page/ReferenceDialog.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "CSS", "bytes": "70363" }, { "name": "HTML", "bytes": "2899" }, { "name": "Java", "bytes": "2079682" }, { "name": "JavaScript", "bytes": "125740" }, { "name": "Makefile", "bytes": "531" }, { "name": "Python", "bytes": "23103" }, { "name": "Shell", "bytes": "1637" } ], "symlink_target": "" }
package pkg.xfl.unary; import xfuzzy.lang.*; public class square extends Unary { public square() { super("xfl","square"); Parameter single[] = new Parameter[0]; setSingleParameters(single); } public double compute(double a) { return a*a; } public double derivative(double a) { double deriv; deriv = 2*a; return deriv; } public boolean test () { return true; } public String getJavaCode() { String eol = System.getProperty("line.separator", "\n"); String code = ""; code += " return a*a; "+eol; return code; } public String getCCode() { String eol = System.getProperty("line.separator", "\n"); String code = ""; code += " return a*a; "+eol; return code; } public String getCppCode() { String eol = System.getProperty("line.separator", "\n"); String code = ""; code += " return a*a; "+eol; return code; } }
{ "content_hash": "8159e8abf68a5e70d84d2405aec3deb9", "timestamp": "", "source": "github", "line_count": 47, "max_line_length": 59, "avg_line_length": 20.19148936170213, "alnum_prop": 0.5806111696522656, "repo_name": "dayse/gesplan", "id": "008e4eaea4d543b4abfe5f769aa03cc7b1ab4861", "size": "1120", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/pkg/xfl/unary/square.java", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "12724" }, { "name": "Java", "bytes": "6019521" }, { "name": "JavaScript", "bytes": "261237" }, { "name": "Shell", "bytes": "424" } ], "symlink_target": "" }
package fr.icam.emit.services.clients; import java.io.IOException; import java.net.URI; import java.sql.PreparedStatement; import java.sql.ResultSet; import javax.servlet.ServletException; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import com.github.jeromerocheteau.JdbcUpdateServlet; public class Updater extends JdbcUpdateServlet<Integer> { private static final long serialVersionUID = 201710161616004L; @Override public void doPost(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException { Integer count = this.doProcess(request); this.doWrite(count, response.getWriter()); } @Override public void doFill(PreparedStatement statement, HttpServletRequest request) throws Exception { String uuid = request.getParameter("uuid"); String name = request.getParameter("name"); String broker = URI.create(request.getParameter("broker")).toString(); Boolean open = Boolean.valueOf(request.getParameter("open")); statement.setString(1, name); statement.setString(2, broker); statement.setBoolean(3, open); statement.setString(4, uuid); } @Override protected Integer doMap(HttpServletRequest request, int count, ResultSet resultSet) throws Exception { return count; } }
{ "content_hash": "463858dcd17f927aef097d2e04fc3ae0", "timestamp": "", "source": "github", "line_count": 41, "max_line_length": 116, "avg_line_length": 31.536585365853657, "alnum_prop": 0.7896365042536736, "repo_name": "JeromeRocheteau/emit", "id": "96940e99d004b5140dbfd20ace01477b3d425a71", "size": "1293", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "emit-platform/src/main/java/fr/icam/emit/services/clients/Updater.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "CSS", "bytes": "2147" }, { "name": "HTML", "bytes": "207453" }, { "name": "Java", "bytes": "255103" }, { "name": "JavaScript", "bytes": "29281" } ], "symlink_target": "" }