answer
stringlengths
15
1.25M
#include <assert.h> #include <stdint.h> #include <OpenP2P/Buffer.hpp> #include <OpenP2P/Stream/BinaryStream.hpp> #include <OpenP2P/Event/Source.hpp> #include <OpenP2P/Event/Wait.hpp> #include <OpenP2P/RootNetwork/Endpoint.hpp> #include <OpenP2P/RootNetwork/Packet.hpp> #include <OpenP2P/RootNetwork/PacketSocket.hpp> #include <OpenP2P/RootNetwork/SignedPacket.hpp> namespace OpenP2P { namespace RootNetwork { PacketSocket::PacketSocket(Socket<UDP::Endpoint, Buffer>& udpSocket) : udpSocket_(udpSocket) { } bool PacketSocket::isValid() const { return udpSocket_.isValid(); } Event::Source PacketSocket::eventSource() const { return udpSocket_.eventSource(); } bool PacketSocket::receive(Endpoint& endpoint, SignedPacket& signedPacket) { UDP::Endpoint udpEndpoint; Buffer buffer; if (!udpSocket_.receive(udpEndpoint, buffer)) { return false; } endpoint.kind = Endpoint::UDPIPV6; endpoint.udpEndpoint = udpEndpoint; BufferIterator bufferIterator(buffer); BinaryIStream blockingReader(bufferIterator); signedPacket.packet = ReadPacket(blockingReader); signedPacket.signature = ReadSignature(blockingReader); return true; } bool PacketSocket::send(const Endpoint& endpoint, const SignedPacket& signedPacket) { assert(endpoint.kind == Endpoint::UDPIPV6); Buffer buffer; BufferBuilder bufferBuilder(buffer); BinaryOStream blockingWriter(bufferBuilder); WritePacket(blockingWriter, signedPacket.packet); WriteSignature(blockingWriter, signedPacket.signature); return udpSocket_.send(endpoint.udpEndpoint, buffer); } } }
// Authored by: Malcolm MacLeod (mmacleod@gmx.com) // file COPYING //Workaround braindamaged 'hack' in libtool.m4 that defines DLL_EXPORT when building a dll via libtool (this in turn imports unwanted symbols from e.g. pthread that breaks static pthread linkage) #ifdef DLL_EXPORT #undef DLL_EXPORT #endif // Unity specific includes #include "unity_impl.h" #include "libinit.h" // Standard gulden headers #include "appname.h" #include "clientversion.h" #include "util.h" #include "witnessutil.h" #include "ui_interface.h" #include "unity/appmanager.h" #include "utilmoneystr.h" #include <chain.h> #include "consensus/validation.h" #include "net.h" #include "wallet/mnemonic.h" #include "net_processing.h" #include "wallet/spvscanner.h" #include "sync.h" #include "init.h" // Djinni generated files #include "<API key>.hpp" #include "i_library_listener.hpp" #include "qr_code_record.hpp" #include "balance_record.hpp" #include "uri_record.hpp" #include "uri_recipient.hpp" #include "mutation_record.hpp" #include "input_record.hpp" #include "output_record.hpp" #include "address_record.hpp" #include "peer_record.hpp" #include "block_info_record.hpp" #include "monitor_record.hpp" #include "monitor_listener.hpp" #include "<API key>.hpp" #include "mnemonic_record.hpp" #ifdef __ANDROID__ #include "djinni_support.hpp" #endif // External libraries #include <boost/algorithm/string.hpp> #include <boost/program_options/parsers.hpp> #include <qrencode.h> #include <memory> #include "pow/pow.h" #include <crypto/hash/sigma/sigma.h> #include <algorithm> std::shared_ptr<ILibraryListener> signalHandler; CCriticalSection <API key>; std::set<std::shared_ptr<MonitorListener> > monitoringListeners; boost::asio::io_context ioctx; boost::asio::executor_work_guard<boost::asio::io_context::executor_type> work = boost::asio::make_work_guard(ioctx); boost::thread run_thread(boost::bind(&boost::asio::io_context::run, boost::ref(ioctx))); static const int64_t nClientStartupTime = GetTime(); std::vector<CAccount*> <API key>(CAccount* forAccount) { std::vector<CAccount*> forAccounts; forAccounts.push_back(forAccount); for (const auto& [accountUUID, account] : pactiveWallet->mapAccounts) { (unused) accountUUID; if (account->getParentUUID() == forAccount->getUUID()) { forAccounts.push_back(account); } } return forAccounts; } TransactionStatus <API key>(const CWalletTx* wtx) { TransactionStatus status; int depth = wtx->GetDepthInMainChain(); if (depth < 0) status = TransactionStatus::CONFLICTED; else if (depth == 0) { if (wtx->isAbandoned()) status = TransactionStatus::ABANDONED; else status = TransactionStatus::UNCONFIRMED; } else if (depth < <API key>) { status = TransactionStatus::CONFIRMING; } else { status = TransactionStatus::CONFIRMED; } return status; } std::string <API key>(CAccount* forAccount, CWallet* pWallet, const CWalletTx* wtx, bool isSentByUs) { std::string address = ""; for (const CTxOut& txout: wtx->tx->vout) { bool isMine = false; if (forAccount && IsMine(*forAccount, txout)) { isMine = true; } if (!forAccount && pWallet && IsMine(*pWallet, txout)) { isMine = true; } if ((isSentByUs && !isMine) || (!isSentByUs && isMine)) { CNativeAddress addr; CTxDestination dest; if (!ExtractDestination(txout, dest) && !txout.IsUnspendable()) { dest = CNoDestination(); } if (addr.Set(dest)) { if (!address.empty()) address += ", "; address += addr.ToString(); } } } return address; } void <API key>(const CWalletTx* wtx, std::vector<MutationRecord>& mutations, CAccount* forAccount) { // exclude generated that are orphaned if (wtx->IsCoinBase() && wtx->GetDepthInMainChain() < 1) return; int64_t subtracted = wtx->GetDebit(ISMINE_SPENDABLE, forAccount, true); int64_t added = wtx->GetCredit(ISMINE_SPENDABLE, forAccount, true) + wtx->GetImmatureCredit(false, forAccount, true); uint64_t time = wtx->nTimeSmart; std::string hash = wtx->GetHash().ToString(); TransactionStatus status = <API key>(wtx); int depth = wtx->GetDepthInMainChain(); // if any funds were subtracted the transaction was sent by us if (subtracted > 0) { int64_t fee = subtracted - wtx->tx->GetValueOut(); int64_t change = wtx->GetChange(); std::string recipientAddresses = <API key>(forAccount, pactiveWallet, wtx, true); // detect internal transfer and split it if (subtracted - fee == added) { // amount received mutations.push_back(MutationRecord(added - change, time, hash, recipientAddresses, status, depth)); // amount send including fee mutations.push_back(MutationRecord(change - subtracted, time, hash, recipientAddresses, status, depth)); } else { mutations.push_back(MutationRecord(added - subtracted, time, hash, recipientAddresses, status, depth)); } } else if (added != 0) // nothing subtracted so we received funds { std::string recipientAddresses = <API key>(forAccount, pactiveWallet, wtx, false); mutations.push_back(MutationRecord(added, time, hash, recipientAddresses, status, depth)); } } TransactionRecord <API key>(const CWalletTx& wtx, std::vector<CAccount*>& forAccounts, bool& <API key>) { CWallet* pwallet = pactiveWallet; std::vector<InputRecord> inputs; std::vector<OutputRecord> outputs; int64_t subtracted=0; int64_t added=0; for (const auto& account : forAccounts) { subtracted += wtx.GetDebit(ISMINE_SPENDABLE, account, true); added += wtx.GetCredit(ISMINE_SPENDABLE, account, true); } CAmount fee = 0; // if any funds were subtracted the transaction was sent by us if (subtracted > 0) fee = subtracted - wtx.tx->GetValueOut(); const CTransaction& tx = *wtx.tx; for (const CTxIn& txin: tx.vin) { std::string address; CNativeAddress addr; CTxDestination dest = CNoDestination(); // Try to extract destination, this is not possible in general. Only if the previous // ouput of our input happens to be in our wallet. Which will usually only be the case for // our own transactions. uint256 txHash; if (txin.GetPrevOut().isHash) { txHash = txin.GetPrevOut().getTransactionHash(); } else { if (!pwallet->GetTxHash(txin.GetPrevOut(), txHash)) { LogPrintf("Transaction with no corresponding hash found, txid [%d] [%d]\n", txin.GetPrevOut().<API key>(), txin.GetPrevOut().getTransactionIndex()); continue; } } std::map<uint256, CWalletTx>::const_iterator mi = pwallet->mapWallet.find(txHash); if (mi != pwallet->mapWallet.end()) { const CWalletTx& prev = (*mi).second; if (txin.GetPrevOut().n < prev.tx->vout.size()) { const auto& prevOut = prev.tx->vout[txin.GetPrevOut().n]; if (!ExtractDestination(prevOut, dest) && !prevOut.IsUnspendable()) { LogPrintf("Unknown transaction type found, txid %s\n", wtx.GetHash().ToString()); dest = CNoDestination(); } } } if (addr.Set(dest)) { address = addr.ToString(); } std::string label; std::string description; if (pwallet->mapAddressBook.count(address)) { const auto& data = pwallet->mapAddressBook[address]; label = data.name; description = data.description; } bool isMine = false; for (const auto& account : forAccounts) { if (static_cast<const CExtWallet*>(pwallet)->IsMine(*account, txin)) { isMine = true; <API key> = true; } } inputs.push_back(InputRecord(address, label, description, isMine)); } for (const CTxOut& txout: tx.vout) { std::string address; CNativeAddress addr; CTxDestination dest; if (!ExtractDestination(txout, dest) && !txout.IsUnspendable()) { LogPrintf("Unknown transaction type found, txid %s\n", tx.GetHash().ToString()); dest = CNoDestination(); } if (addr.Set(dest)) { address = addr.ToString(); } std::string label; std::string description; if (pwallet->mapAddressBook.count(address)) { const auto& data = pwallet->mapAddressBook[address]; label = data.name; description = data.description; } bool isMine = false; for (const auto& account : forAccounts) { if (IsMine(*account, txout)) { isMine = true; <API key> = true; } } outputs.push_back(OutputRecord(txout.nValue, address, label, description, isMine)); } TransactionStatus status = <API key>(&wtx); return TransactionRecord(wtx.GetHash().ToString(), wtx.nTimeSmart, added - subtracted, fee, status, wtx.nHeight, wtx.nBlockTime, wtx.GetDepthInMainChain(), inputs, outputs); } // rate limited balance change notifier static CRateLimit<int>* <API key>=nullptr; // rate limited new mutations notifier static CRateLimit<std::pair<uint256, bool>>* <API key>=nullptr; void <API key>() { if (signalHandler) { signalHandler->notifyShutdown(); } // Allow frontend time to clean up and free any references to objects before unloading the library // Otherwise we get a free after close (on macOS at least) while (signalHandler.use_count() > 1) { MilliSleep(50); } signalHandler=nullptr; } #include <boost/chrono/thread_clock.hpp> static float lastProgress=0; void handlePostInitMain() { //fixme: (SIGMA) (PHASE4) Remove this once we have witness-header-sync // Select appropriate verification factor based on devices performance. std::thread([=] { // When available measure thread relative cpu time to avoid effects of thread suspension // which occur when observing system time. #if false && defined(<API key>) && <API key> boost::chrono::time_point tpStart = boost::chrono::thread_clock::now(); #else uint64_t nStart = GetTimeMicros(); #endif // note that measurement is on single thread, which makes the measurement more stable // actual verification might use more threads which helps overall app performance <API key> verify(<API key>, 1); CBlockHeader header; verify.verifyHeader<1>(header); // We want at least 1000 blocks per second #if false && defined(<API key>) && <API key> boost::chrono::microseconds ms = boost::chrono::duration_cast<boost::chrono::microseconds>(boost::chrono::thread_clock::now() - tpStart); uint64_t nTotal = ms.count(); #else uint64_t nTotal = GetTimeMicros() - nStart; #endif uint64_t nPerSec = 1000000/nTotal; if (nPerSec > 1000) // Fast enough to do most the blocks { verifyFactor = 5; } else if(nPerSec > 0) // Slower so reduce the number of blocks { // 2 in verifyFactor chance of verifying. // We verify 2 in verifyFactor blocks - or target_speed/(num_per_sec/2) verifyFactor = 1000/(nPerSec/2.0); verifyFactor = std::max((uint64_t)5, verifyFactor); verifyFactor = std::min((uint64_t)200, verifyFactor); } LogPrintf("unity: selected verification factor %d", verifyFactor); }).detach(); if (signalHandler) { signalHandler->notifyCoreReady(); } // unified progress notification if (!GetBoolArg("-spv", DEFAULT_SPV)) { static bool <API key>=false; static int totalHeaderCount=0; static int startHeight = chainActive.Tip() ? chainActive.Tip()->nHeight : 0; // If tip is relatively recent set progress to "completed" to begin with if (chainActive.Tip() && ((GetTime() - chainActive.Tip()->nTime) < 3600)) { lastProgress = 1.0; } // Weight a full header sync as 20%, blocks as rest uiInterface.<API key>.connect([=](int currentCount, int probableHeight, int headerTipHeight, int64_t headerTipTime) { totalHeaderCount = currentCount; if (currentCount == probableHeight) { <API key> = true; } if (!<API key> && signalHandler && <API key>()) { float progress = ((((float)<API key>)/((float)<API key>))*0.20); if (lastProgress != 1 && (<API key> > 0.02 || progress == 1)) { lastProgress = progress; signalHandler-><API key>(progress); } } }); uiInterface.NotifyBlockTip.connect([=](bool <API key>, const CBlockIndex* pNewTip) { if (<API key> && signalHandler) { float progress = pNewTip->nHeight==totalHeaderCount?1:((0.20+((((float)pNewTip->nHeight-startHeight)/((float)<API key>))*0.80))); if (lastProgress != 1 && (<API key> > 0.02 || progress == 1)) { lastProgress = progress; signalHandler-><API key>(progress); } } }); } else { uiInterface.<API key>.connect([=](float progress) { if (signalHandler) { signalHandler-><API key>(progress); } }); // monitoring listeners notifications uiInterface.<API key>.connect([=](int, int, int, int64_t) { int32_t height, probable_height, offset; { LOCK(cs_main); height = partialChain.Height(); probable_height = GetProbableHeight(); offset = partialChain.HeightOffset(); } LOCK(<API key>); for (const auto &listener: monitoringListeners) { listener->onPartialChain(height, probable_height, offset); } }); uiInterface.NotifySPVPrune.connect([=](int height) { LOCK(<API key>); for (const auto &listener: monitoringListeners) { listener->onPruned(height); } }); uiInterface.NotifySPVProgress.connect([=](int /*start_height*/, int processed_height, int /*probable_height*/) { LOCK(<API key>); for (const auto &listener: monitoringListeners) { listener-><API key>(processed_height); } }); } // Update transaction/balance changes if (pactiveWallet) { // Fire events for transaction depth changes (up to depth 10 only) pactiveWallet-><API key>.connect( [&](CWallet* pwallet, const uint256& hash) { LOCK2(cs_main, pwallet->cs_wallet); if (pwallet->mapWallet.find(hash) != pwallet->mapWallet.end()) { const CWalletTx& wtx = pwallet->mapWallet[hash]; LogPrintf("unity: notify transaction depth changed %s",hash.ToString().c_str()); if (signalHandler) { std::vector<CAccount*> forAccounts = <API key>(pactiveWallet->activeAccount); bool <API key> = false; TransactionRecord walletTransaction = <API key>(wtx, forAccounts, <API key>); if (<API key>) { signalHandler-><API key>(walletTransaction); } } } } ); // Fire events for transaction status changes, or new transactions (this won't fire for simple depth changes) pactiveWallet-><API key>.connect( [&](CWallet* pwallet, const uint256& hash, ChangeType status, bool fSelfComitted) { LOCK2(cs_main, pwallet->cs_wallet); if (pwallet->mapWallet.find(hash) != pwallet->mapWallet.end()) { if (status == CT_NEW) { <API key>->trigger(std::make_pair(hash, fSelfComitted)); } else if (status == CT_UPDATED && signalHandler) { LogPrintf("unity: notify tx updated %s",hash.ToString().c_str()); const CWalletTx& wtx = pwallet->mapWallet[hash]; std::vector<CAccount*> forAccounts = <API key>(pactiveWallet->activeAccount); bool <API key> = false; TransactionRecord walletTransaction = <API key>(wtx, forAccounts, <API key>); if (<API key>) { signalHandler-><API key>(walletTransaction); } } //fixme: (UNITY) - Consider implementing f.e.x if a 0 conf transaction gets deleted... // else if (status == CT_DELETED) } <API key>->trigger(0); }); // Fire once immediately to update with latest on load. <API key>->trigger(0); } } void <API key>() { if (signalHandler) { signalHandler-><API key>(); } AppLifecycleManager::gApp->initialize(); } void <API key>() { signalHandler-><API key>(); } std::string ILibraryController::BuildInfo() { std::string info = <API key>(); #if defined(__aarch64__) info += " aarch64"; #elif defined(__arm__) info += " arm (32bit)"; #elif defined(__x86_64__) info += " x86_64"; #elif defined(__i386__) info += " x86"; #endif return info; } bool ILibraryController::<API key>(const std::string& phrase, const std::string& password) { // Refuse to acknowledge an empty recovery phrase, or one that doesn't pass even the most obvious requirement if (phrase.length() < 16) { return false; } //fixme: (UNITY) (SPV) - Handle all the various birth date (or lack of birthdate) cases here instead of just the one. SecureString phraseOnly; int phraseBirthNumber = 0; AppLifecycleManager::gApp-><API key>(phrase.c_str(), phraseOnly, phraseBirthNumber); if (!checkMnemonic(phraseOnly)) { return false; } // ensure that wallet is initialized with a starting time (else it will start from now and old tx will not be scanned) // Use the hardcoded timestamp 1441212522 of block 250000, we didn't have any recovery phrase style wallets (using current phrase system) before that. if (phraseBirthNumber == 0) phraseBirthNumber = timeToBirthNumber(1441212522L); //fixme: (UNITY) (SPV) - Handle all the various birth date (or lack of birthdate) cases here instead of just the one. AppLifecycleManager::gApp->setRecoveryPhrase(phraseOnly); AppLifecycleManager::gApp-><API key>(phraseBirthNumber); AppLifecycleManager::gApp->setRecoveryPassword(password.c_str()); AppLifecycleManager::gApp->isRecovery = true; AppLifecycleManager::gApp->initialize(); return true; } void DoRescanInternal() { if (pactiveWallet) { <API key>(); } } bool <API key>(const std::string & phrase, SecureString& mnemonic, int& birthNumber) { if (phrase.length() < 16) return false; AppLifecycleManager::gApp-><API key>(phrase.c_str(), mnemonic, birthNumber); return checkMnemonic(mnemonic) && (birthNumber == 0 || <API key>(birthNumber, nullptr)); } bool ILibraryController::<API key>(const std::string& phrase, const std::string& password) { SecureString phraseOnly; int phraseBirthNumber; if (!<API key>(phrase, phraseOnly, phraseBirthNumber)) return false; // ensure that wallet is initialized with a starting time (else it will start from now and old tx will not be scanned) // Use the hardcoded timestamp 1441212522 of block 250000, we didn't have any recovery phrase style wallets (using current phrase system) before that. if (phraseBirthNumber == 0) phraseBirthNumber = timeToBirthNumber(1441212522L); if (!pactiveWallet) { LogPrintf("<API key>: No active wallet"); return false; } LOCK2(cs_main, pactiveWallet->cs_wallet); AppLifecycleManager::gApp->setRecoveryPhrase(phraseOnly); AppLifecycleManager::gApp-><API key>(phraseBirthNumber); AppLifecycleManager::gApp->setRecoveryPassword(password.c_str()); AppLifecycleManager::gApp->isRecovery = true; CWallet::<API key>(pactiveWallet); // Allow update of balance for deleted accounts/transactions LogPrintf("%s: Update balance and rescan", __func__); <API key>->trigger(0); // Rescan for transactions on the linked account DoRescanInternal(); return true; } bool ILibraryController::<API key>(const std::string & phrase) { SecureString dummyMnemonic; int dummyNumber; return <API key>(phrase, dummyMnemonic, dummyNumber); } #include "base58.h" std::string ILibraryController::GenerateGenesisKeys() { std::string address = GetReceiveAddress(); CNativeAddress addr(address); CTxDestination dest = addr.Get(); CPubKey vchPubKeyDevSubsidy; pactiveWallet->GetPubKey(boost::get<CKeyID>(dest), vchPubKeyDevSubsidy); std::string devSubsidyPubKey = HexStr(vchPubKeyDevSubsidy); std::string devSubsidyPubKeyID = boost::get<CKeyID>(dest).GetHex(); CKey key; key.MakeNewKey(true); CPrivKey vchPrivKey = key.GetPrivKey(); CPubKey vchPubKey = key.GetPubKey(); std::string privkey = HexStr<CPrivKey::iterator>(vchPrivKey.begin(), vchPrivKey.end()).c_str(); std::string pubKeyID = vchPubKey.GetID().GetHex(); std::string witnessKeys = <API key>"://witnesskeys?keys=" + CEncodedSecretKey(key).ToString() + strprintf("#%s", GetAdjustedTime()); return "privkey: "+privkey+"\n"+"pubkeyID: "+pubKeyID+"\n"+"witness: "+witnessKeys+"\n"+"dev subsidy addr: "+address+"\n"+"dev subsidy pubkey: "+devSubsidyPubKey+"\n"+"dev subsidy pubkey ID: "+devSubsidyPubKeyID+"\n"; } MnemonicRecord ILibraryController::<API key>() { std::vector<unsigned char> entropy(16); GetStrongRandBytes(&entropy[0], 16); int64_t birthTime = GetAdjustedTime(); SecureString phraseOnly = mnemonicFromEntropy(entropy, entropy.size()*8); return <API key>(phraseOnly.c_str(), birthTime); } MnemonicRecord ILibraryController::<API key>(const std::string & mnemonic, int64_t birthTime) { const auto& result = AppLifecycleManager::<API key>(SecureString(mnemonic), birthTime); return MnemonicRecord(result.first.c_str(), mnemonic.c_str(), result.second); } bool ILibraryController::<API key>(const std::string& linked_uri, const std::string& password) { <API key><CExtKey> linkedKey; if (!linkedKey.fromURIString(linked_uri)) { return false; } AppLifecycleManager::gApp->setLinkKey(linkedKey); AppLifecycleManager::gApp->isLink = true; AppLifecycleManager::gApp->setRecoveryPassword(password.c_str()); AppLifecycleManager::gApp->initialize(); return true; } bool ILibraryController::<API key>(const std::string & linked_uri, const std::string& password) { if (!pactiveWallet) { LogPrintf("%s: No active wallet", __func__); return false; } LOCK2(cs_main, pactiveWallet->cs_wallet); <API key><CExtKey> linkedKey; if (!linkedKey.fromURIString(linked_uri)) { LogPrintf("%s: Failed to parse link URI", __func__); return false; } AppLifecycleManager::gApp->setLinkKey(linkedKey); AppLifecycleManager::gApp->setRecoveryPassword(password.c_str()); AppLifecycleManager::gApp->isLink = true; CWallet::<API key>(pactiveWallet); // Allow update of balance for deleted accounts/transactions LogPrintf("%s: Update balance and rescan", __func__); <API key>->trigger(0); // Rescan for transactions on the linked account DoRescanInternal(); return true; } bool ILibraryController::<API key>(const std::string& linked_uri, const std::string& password) { LOCK2(cs_main, pactiveWallet->cs_wallet); if (!pactiveWallet || !pactiveWallet->activeAccount) { LogPrintf("<API key>: No active wallet"); return false; } // Create ext key for new linked account from parsed data <API key><CExtKey> linkedKey; if (!linkedKey.fromURIString(linked_uri)) { LogPrintf("<API key>: Failed to parse link URI"); return false; } // Ensure we have a valid location to send all the funds CNativeAddress address(linkedKey.getPayAccount()); if (!address.IsValid()) { LogPrintf("<API key>: invalid address %s", linkedKey.getPayAccount().c_str()); return false; } // Empty wallet to target address LogPrintf("<API key>: Empty accounts into linked address"); bool <API key> = true; std::vector<std::tuple<CWalletTx*, CReserveKeyOrScript*>> <API key>; for (const auto& [accountUUID, pAccount] : pactiveWallet->mapAccounts) { CAmount nBalance = pactiveWallet->GetBalance(pAccount, false, true, true); if (nBalance > 0) { LogPrintf("<API key>: Empty account into linked address [%s]", getUUIDAsString(accountUUID).c_str()); std::vector<CRecipient> vecSend; CRecipient recipient = <API key>(address.Get(), nBalance, <API key>, GetPoW2Phase(chainTip())); vecSend.push_back(recipient); CWalletTx* pWallettx = new CWalletTx(); CAmount nFeeRequired; int nChangePosRet = -1; std::string strError; CReserveKeyOrScript* pReserveKey = new CReserveKeyOrScript(pactiveWallet, pAccount, KEYCHAIN_CHANGE); std::vector<CKeyStore*> accountsToTry; for ( const auto& accountPair : pactiveWallet->mapAccounts ) { if(accountPair.second->getParentUUID() == pAccount->getUUID()) { accountsToTry.push_back(accountPair.second); } accountsToTry.push_back(pAccount); } if (!pactiveWallet->CreateTransaction(accountsToTry, vecSend, *pWallettx, *pReserveKey, nFeeRequired, nChangePosRet, strError)) { LogPrintf("<API key>: Failed to create transaction %s [%d]",strError.c_str(), nBalance); return false; } <API key>.push_back(std::tuple(pWallettx, pReserveKey)); } else { LogPrintf("<API key>: Account already empty [%s]", getUUIDAsString(accountUUID).c_str()); } } if (!<API key>()) { LogPrintf("<API key>: Failed to erase seed and accounts"); return false; } AppLifecycleManager::gApp->setLinkKey(linkedKey); AppLifecycleManager::gApp->setRecoveryPassword(password.c_str()); AppLifecycleManager::gApp->isLink = true; CWallet::<API key>(pactiveWallet); for (auto& [pWalletTx, pReserveKey] : <API key>) { CValidationState state; //NB! We delibritely pass nullptr for connman here to prevent transaction from relaying //We allow the relaying to occur inside DoRescan instead if (!pactiveWallet->CommitTransaction(*pWalletTx, *pReserveKey, nullptr, state)) { LogPrintf("<API key>: Failed to commit transaction"); return false; } delete pWalletTx; delete pReserveKey; } // Allow update of balance for deleted accounts/transactions LogPrintf("<API key>: Update balance and rescan"); <API key>->trigger(0); // Rescan for transactions on the linked account DoRescanInternal(); return true; } bool ILibraryController::<API key>() { pactiveWallet-><API key>(); return true; } bool ILibraryController::IsValidLinkURI(const std::string& linked_uri) { <API key><CExtKey> linkedKey; if (!linkedKey.fromURIString(linked_uri)) return false; return true; } bool testnet_; bool spvMode_; std::string extraArgs_; std::string staticFilterPath_; int64_t staticFilterOffset_; int64_t staticFilterLength_; int32_t ILibraryController::InitUnityLib(const std::string& dataDir, const std::string& staticFilterPath, int64_t staticFilterOffset, int64_t staticFilterLength, bool testnet, bool spvMode, const std::shared_ptr<ILibraryListener>& signalHandler_, const std::string& extraArgs) { <API key> = new CRateLimit<int>([](int) { if (pactiveWallet && signalHandler) { WalletBalances balances; pactiveWallet->GetBalances(balances, pactiveWallet->activeAccount, true); signalHandler->notifyBalanceChange(BalanceRecord(balances.<API key>, balances.<API key>, balances.availableLocked, balances.<API key>, balances.<API key>, balances.unconfirmedLocked, balances.<API key>, balances.<API key>, balances.immatureLocked, balances.totalLocked)); } }, std::chrono::milliseconds(<API key>)); <API key> = new CRateLimit<std::pair<uint256, bool>>([](const std::pair<uint256, bool>& txInfo) { if (pactiveWallet && signalHandler) { const uint256& txHash = txInfo.first; const bool fSelfComitted = txInfo.second; LOCK2(cs_main, pactiveWallet->cs_wallet); if (pactiveWallet->mapWallet.find(txHash) != pactiveWallet->mapWallet.end()) { const CWalletTx& wtx = pactiveWallet->mapWallet[txHash]; std::vector<MutationRecord> mutations; <API key>(&wtx, mutations, pactiveWallet->activeAccount); for (auto& m: mutations) { LogPrintf("unity: notify new mutation for tx %s", txHash.ToString().c_str()); signalHandler->notifyNewMutation(m, fSelfComitted); } } } }, std::chrono::milliseconds(<API key>)); // Force the datadir to specific place on e.g. android devices <API key> = dataDir; signalHandler = signalHandler_; testnet_ = testnet; spvMode_ = spvMode; extraArgs_ = extraArgs; staticFilterPath_ = staticFilterPath; staticFilterOffset_ = staticFilterOffset; staticFilterLength_ = staticFilterLength; return InitUnity(); } void <API key>() { if (spvMode_) { // SPV wallets definitely shouldn't be listening for incoming connections at all SoftSetArg("-listen", "0"); // Minimise logging for performance reasons SoftSetArg("-debug", "0"); // Turn SPV mode on SoftSetArg("-fullsync", "0"); SoftSetArg("-spv", "1"); #ifdef DJINNI_NODEJS #ifdef SPV_MULTI_ACCOUNT SoftSetArg("-accountpool", "3"); SoftSetArg("-accountpoolmobi", "1"); SoftSetArg("-accountpoolwitness", "1"); SoftSetArg("-accountpoolmining", "1"); #else SoftSetArg("-accountpool", "0"); SoftSetArg("-accountpoolmobi", "0"); SoftSetArg("-accountpoolwitness", "0"); SoftSetArg("-accountpoolmining", "0"); #endif SoftSetArg("-keypool", "10"); #else // Minimise lookahead size for performance reasons SoftSetArg("-accountpool", "1"); // Minimise background threads and memory consumption SoftSetArg("-par", "-100"); SoftSetArg("-maxsigcachesize", "0"); SoftSetArg("-dbcache", "4"); SoftSetArg("-maxmempool", "5"); SoftSetArg("-maxconnections", "8"); //fixme: (FUT) (UNITY) Reverse headers // Temporarily disable reverse headers for mobile until memory requirements can be reduced. SoftSetArg("-reverseheaders", "false"); #endif } SoftSetArg("-spvstaticfilterfile", staticFilterPath_); SoftSetArg("-<API key>", i64tostr(staticFilterOffset_)); SoftSetArg("-<API key>", i64tostr(staticFilterLength_)); // Change client name #if defined(__APPLE__) && TARGET_OS_IPHONE == 1 SoftSetArg("-clientname", GLOBAL_APPNAME" ios"); #elif defined(__ANDROID__) SoftSetArg("-clientname", GLOBAL_APPNAME" android"); #else SoftSetArg("-clientname", GLOBAL_APPNAME" desktop"); #endif // Testnet if (testnet_) { SoftSetArg("-testnet", "S1595347850:60"); SoftSetArg("-addnode", "178.62.195.19"); } else { SoftSetArg("-addnode", "178.62.195.19"); SoftSetArg("-addnode", "149.210.165.218"); } if (!extraArgs_.empty()) { std::vector<const char*> args; auto splitted = boost::program_options::split_unix(extraArgs_); for(const auto& part: splitted) args.push_back(part.c_str()); gArgs.<API key>(int(args.size()), args.data()); } } void ILibraryController::<API key>(const std::string& dataDir, const std::string& staticFilterPath, int64_t staticFilterOffset, int64_t staticFilterLength, bool testnet, bool spvMode, const std::shared_ptr<ILibraryListener>& signalHandler_, const std::string& extraArgs) { std::thread([=] { InitUnityLib(dataDir, staticFilterPath, staticFilterOffset, staticFilterLength, testnet, spvMode, signalHandler_, extraArgs); }).detach(); } void ILibraryController::TerminateUnityLib() { // Terminate in thread so we don't block interprocess communication std::thread([=] { work.reset(); ioctx.stop(); AppLifecycleManager::gApp->shutdown(); AppLifecycleManager::gApp->waitForShutDown(); run_thread.join(); }).detach(); } QrCodeRecord ILibraryController::QRImageFromString(const std::string& qr_string, int32_t width_hint) { QRcode* code = QRcode_encodeString(qr_string.c_str(), 0, QR_ECLEVEL_L, QR_MODE_8, 1); if (!code) { return QrCodeRecord(0, std::vector<uint8_t>()); } else { const int32_t generatedWidth = code->width; const int32_t finalWidth = (width_hint / generatedWidth) * generatedWidth; const int32_t scaleMultiplier = finalWidth / generatedWidth; std::vector<uint8_t> dataVector; dataVector.reserve(finalWidth*finalWidth); int nIndex=0; for (int nRow=0; nRow<generatedWidth; ++nRow) { for (int nCol=0; nCol<generatedWidth; ++nCol) { dataVector.insert(dataVector.end(), scaleMultiplier, (code->data[nIndex++] & 1) * 255); } for (int i=1; i<scaleMultiplier; ++i) { dataVector.insert(dataVector.end(), dataVector.end()-finalWidth, dataVector.end()); } } QRcode_free(code); return QrCodeRecord(finalWidth, dataVector); } } std::string ILibraryController::GetReceiveAddress() { LOCK2(cs_main, pactiveWallet->cs_wallet); if (!pactiveWallet || !pactiveWallet->activeAccount) return ""; CReserveKeyOrScript* receiveAddress = new CReserveKeyOrScript(pactiveWallet, pactiveWallet->activeAccount, KEYCHAIN_EXTERNAL); CPubKey pubKey; if (receiveAddress->GetReservedKey(pubKey)) { CKeyID keyID = pubKey.GetID(); receiveAddress->ReturnKey(); delete receiveAddress; return CNativeAddress(keyID).ToString(); } else { return ""; } } //fixme: (UNITY) - find a way to use char[] here as well as on the java side. MnemonicRecord ILibraryController::GetRecoveryPhrase() { if (pactiveWallet && pactiveWallet->activeAccount) { LOCK2(cs_main, pactiveWallet->cs_wallet); //WalletModel::UnlockContext ctx(walletModel->requestUnlock()); //if (ctx.isValid()) { int64_t birthTime = pactiveWallet->birthTime(); std::set<SecureString> allPhrases; for (const auto& seedIter : pactiveWallet->mapSeeds) { SecureString phrase = seedIter.second->getMnemonic(); return <API key>(phrase.c_str(), birthTime); } } } return MnemonicRecord("", "", 0); } bool ILibraryController::IsMnemonicWallet() { if (!pactiveWallet || !pactiveWallet->activeAccount) throw std::runtime_error(_("No active internal wallet.")); LOCK2(cs_main, pactiveWallet->cs_wallet); return pactiveWallet->activeSeed != nullptr; } bool ILibraryController::IsMnemonicCorrect(const std::string & phrase) { if (!pactiveWallet || !pactiveWallet->activeAccount) throw std::runtime_error(_("No active internal wallet.")); SecureString mnemonicPhrase; int birthNumber; AppLifecycleManager::<API key>(SecureString(phrase), mnemonicPhrase, birthNumber); LOCK2(cs_main, pactiveWallet->cs_wallet); for (const auto& seedIter : pactiveWallet->mapSeeds) { if (mnemonicPhrase == seedIter.second->getMnemonic()) return true; } return false; } std::vector<std::string> ILibraryController::<API key>() { return <API key>(); } //fixme: (UNITY) HIGH - take a timeout value and always lock again after timeout bool ILibraryController::UnlockWallet(const std::string& password) { if (!pactiveWallet) { LogPrintf("UnlockWallet: No active wallet"); return false; } if (!dynamic_cast<CExtWallet*>(pactiveWallet)->IsCrypted()) { LogPrintf("UnlockWallet: Wallet not encrypted"); return false; } return pactiveWallet->Unlock(password.c_str()); } bool ILibraryController::LockWallet() { if (!pactiveWallet) { LogPrintf("LockWallet: No active wallet"); return false; } if (dynamic_cast<CExtWallet*>(pactiveWallet)->IsLocked()) return true; return dynamic_cast<CExtWallet*>(pactiveWallet)->Lock(); } bool ILibraryController::ChangePassword(const std::string& oldPassword, const std::string& newPassword) { if (!pactiveWallet) { LogPrintf("ChangePassword: No active wallet"); return false; } if (newPassword.length() == 0) { LogPrintf("ChangePassword: Refusing invalid password of length 0"); return false; } return pactiveWallet-><API key>(oldPassword.c_str(), newPassword.c_str()); } bool ILibraryController::<API key>() { if (!pactiveWallet) return true; WalletBalances balances; pactiveWallet->GetBalances(balances, pactiveWallet->activeAccount, true); if (balances.<API key> > 0 || balances.<API key> > 0) { return true; } return false; } int64_t ILibraryController::GetBalance() { if (!pactiveWallet) return 0; WalletBalances balances; pactiveWallet->GetBalances(balances, pactiveWallet->activeAccount, true); return balances.<API key> + balances.<API key> + balances.<API key>; } void ILibraryController::DoRescan() { if (!pactiveWallet) return; // Allocate some extra keys //fixme: Persist this across runs in some way static int32_t extraKeys=0; extraKeys += 5; int nKeyPoolTargetDepth = GetArg("-keypool", <API key>)+extraKeys; pactiveWallet->TopUpKeyPool(nKeyPoolTargetDepth, 0, nullptr, 1); // Do the rescan DoRescanInternal(); } UriRecipient ILibraryController::IsValidRecipient(const UriRecord & request) { // return if URI is not valid or is no Gulden: URI std::string lowerCaseScheme = boost::algorithm::to_lower_copy(request.scheme); if (lowerCaseScheme != "gulden") return UriRecipient(false, "", "", "", 0); if (!CNativeAddress(request.path).IsValid()) return UriRecipient(false, "", "", "", 0); std::string address = request.path; std::string label = ""; std::string description = ""; CAmount amount = 0; if (request.items.find("amount") != request.items.end()) { ParseMoney(request.items.find("amount")->second, amount); } if (pactiveWallet) { LOCK2(cs_main, pactiveWallet->cs_wallet); if (pactiveWallet->mapAddressBook.find(address) != pactiveWallet->mapAddressBook.end()) { const auto& data = pactiveWallet->mapAddressBook[address]; label = data.name; description = data.description; } } return UriRecipient(true, address, label, description, amount); } bool ILibraryController::<API key>(const std::string& address) { CNativeAddress addr(address); return addr.IsValid(); } bool ILibraryController::<API key>(const std::string& address) { CNativeAddress addr(address); return addr.IsValidBitcoin(); } int64_t ILibraryController::feeForRecipient(const UriRecipient & request) { if (!pactiveWallet) throw std::runtime_error(_("No active internal wallet.")); LOCK2(cs_main, pactiveWallet->cs_wallet); CNativeAddress address(request.address); if (!address.IsValid()) { LogPrintf("feeForRecipient: invalid address %s", request.address.c_str()); throw std::runtime_error(_("Invalid address")); } CRecipient recipient = <API key>(address.Get(), std::min(GetBalance(), request.amount), true, GetPoW2Phase(chainTip())); std::vector<CRecipient> vecSend; vecSend.push_back(recipient); CWalletTx wtx; CAmount nFeeRequired; int nChangePosRet = -1; std::string strError; CReserveKeyOrScript reservekey(pactiveWallet, pactiveWallet->activeAccount, KEYCHAIN_CHANGE); std::vector<CKeyStore*> accountsToTry; for ( const auto& accountPair : pactiveWallet->mapAccounts ) { if(accountPair.second->getParentUUID() == pactiveWallet->activeAccount->getUUID()) { accountsToTry.push_back(accountPair.second); } accountsToTry.push_back(pactiveWallet->activeAccount); } if (!pactiveWallet->CreateTransaction(accountsToTry, vecSend, wtx, reservekey, nFeeRequired, nChangePosRet, strError, NULL, false)) { LogPrintf("feeForRecipient: failed to create transaction %s",strError.c_str()); throw std::runtime_error(strprintf(_("Failed to calculate fee\n%s"), strError)); } return nFeeRequired; } PaymentResultStatus ILibraryController::<API key>(const UriRecipient & request, bool substract_fee) { if (!pactiveWallet) throw std::runtime_error(_("No active internal wallet.")); LOCK2(cs_main, pactiveWallet->cs_wallet); CNativeAddress address(request.address); if (!address.IsValid()) { LogPrintf("<API key>: invalid address %s", request.address.c_str()); throw std::runtime_error(_("Invalid address")); } CRecipient recipient = <API key>(address.Get(), request.amount, substract_fee, GetPoW2Phase(chainTip())); std::vector<CRecipient> vecSend; vecSend.push_back(recipient); CWalletTx wtx; CAmount nFeeRequired; int nChangePosRet = -1; std::string strError; CReserveKeyOrScript reservekey(pactiveWallet, pactiveWallet->activeAccount, KEYCHAIN_CHANGE); std::vector<CKeyStore*> accountsToTry; for ( const auto& accountPair : pactiveWallet->mapAccounts ) { if(accountPair.second->getParentUUID() == pactiveWallet->activeAccount->getUUID()) { accountsToTry.push_back(accountPair.second); } accountsToTry.push_back(pactiveWallet->activeAccount); } if (!pactiveWallet->CreateTransaction(accountsToTry, vecSend, wtx, reservekey, nFeeRequired, nChangePosRet, strError)) { if (!substract_fee && request.amount + nFeeRequired > GetBalance()) { return PaymentResultStatus::INSUFFICIENT_FUNDS; } LogPrintf("<API key>: failed to create transaction %s",strError.c_str()); throw std::runtime_error(strprintf(_("Failed to create transaction\n%s"), strError)); } CValidationState state; if (!pactiveWallet->CommitTransaction(wtx, reservekey, g_connman.get(), state)) { strError = strprintf("Error: The transaction was rejected! Reason given: %s", state.GetRejectReason()); LogPrintf("<API key>: failed to commit transaction %s",strError.c_str()); throw std::runtime_error(strprintf(_("Transaction rejected, reason: %s"), state.GetRejectReason())); } // Prevent accidental double spends for (const auto &txin : wtx.tx->vin) { pactiveWallet->LockCoin(txin.GetPrevOut()); } return PaymentResultStatus::SUCCESS; } std::vector<TransactionRecord> <API key>(CAccount* forAccount) { std::vector<TransactionRecord> ret; LOCK2(cs_main, pactiveWallet->cs_wallet); std::vector<CAccount*> forAccounts = <API key>(forAccount); for (const auto& [hash, wtx] : pactiveWallet->mapWallet) { bool <API key> = false; TransactionRecord tx = <API key>(wtx, forAccounts, <API key>); if (<API key>) { ret.push_back(tx); } } std::sort(ret.begin(), ret.end(), [&](TransactionRecord& x, TransactionRecord& y){ return (x.timeStamp > y.timeStamp); }); return ret; } std::vector<TransactionRecord> ILibraryController::<API key>() { if (!pactiveWallet) return std::vector<TransactionRecord>(); return <API key>(pactiveWallet->activeAccount); } TransactionRecord ILibraryController::getTransaction(const std::string& txHash) { if (!pactiveWallet) throw std::runtime_error(strprintf("No active wallet to query tx hash [%s]", txHash)); uint256 hash = uint256S(txHash); LOCK2(cs_main, pactiveWallet->cs_wallet); if (pactiveWallet->mapWallet.find(hash) == pactiveWallet->mapWallet.end()) throw std::runtime_error(strprintf("No transaction found for hash [%s]", txHash)); std::vector<CAccount*> forAccounts = <API key>(pactiveWallet->activeAccount); const CWalletTx& wtx = pactiveWallet->mapWallet[hash]; bool <API key> = false; return <API key>(wtx, forAccounts, <API key>); } std::string ILibraryController::resendTransaction(const std::string& txHash) { if (!pactiveWallet) throw std::runtime_error(strprintf("No active wallet to query tx hash [%s]", txHash)); uint256 hash = uint256S(txHash); LOCK2(cs_main, pactiveWallet->cs_wallet); if (pactiveWallet->mapWallet.find(hash) == pactiveWallet->mapWallet.end()) return ""; const CWalletTx& wtx = pactiveWallet->mapWallet[hash]; CDataStream ssTx(SER_NETWORK, PROTOCOL_VERSION); ssTx << *wtx.tx; std::string strHex = HexStr(ssTx.begin(), ssTx.end()); if(!g_connman) return ""; const uint256& hashTx = wtx.tx->GetHash(); CInv inv(MSG_TX, hashTx); g_connman->ForEachNode([&inv](CNode* pnode) { pnode->PushInventory(inv); }); return strHex; } std::vector<MutationRecord> <API key>(CAccount* forAccount) { std::vector<MutationRecord> ret; LOCK2(cs_main, pactiveWallet->cs_wallet); // wallet transactions in reverse chronological ordering std::vector<const CWalletTx*> vWtx; for (const auto& [hash, wtx] : pactiveWallet->mapWallet) { vWtx.push_back(&wtx); } std::sort(vWtx.begin(), vWtx.end(), [&](const CWalletTx* x, const CWalletTx* y){ return (x->nTimeSmart > y->nTimeSmart); }); // build mutation list based on transactions for (const CWalletTx* wtx : vWtx) { <API key>(wtx, ret, forAccount); } return ret; } std::vector<MutationRecord> ILibraryController::getMutationHistory() { if (!pactiveWallet) return std::vector<MutationRecord>(); return <API key>(pactiveWallet->activeAccount); } std::vector<AddressRecord> ILibraryController::<API key>() { std::vector<AddressRecord> ret; if (pactiveWallet) { LOCK2(cs_main, pactiveWallet->cs_wallet); for(const auto& [address, addressData] : pactiveWallet->mapAddressBook) { ret.emplace_back(AddressRecord(address, addressData.name, addressData.description, addressData.purpose)); } } return ret; } void ILibraryController::<API key>(const AddressRecord& address) { if (pactiveWallet) { pactiveWallet->SetAddressBook(address.address, address.name, address.desc, address.purpose); } } void ILibraryController::<API key>(const AddressRecord& address) { if (pactiveWallet) { pactiveWallet->DelAddressBook(address.address); } } void ILibraryController::<API key>() { <API key>(); } void ILibraryController::<API key>() { CWallet::<API key>(); } float ILibraryController::getUnifiedProgress() { if (!GetBoolArg("-spv", DEFAULT_SPV)) { return lastProgress; } else { return CSPVScanner::<API key>; } } std::vector<BlockInfoRecord> ILibraryController::<API key>() { std::vector<BlockInfoRecord> ret; LOCK(cs_main); int height = partialChain.Height(); while (ret.size() < 32 && height > partialChain.HeightOffset()) { const CBlockIndex* pindex = partialChain[height]; ret.push_back(BlockInfoRecord(pindex->nHeight, pindex->GetBlockTime(), pindex->GetBlockHashPoW2().ToString())); height } return ret; } MonitorRecord ILibraryController::getMonitoringStats() { LOCK(cs_main); int32_t partialHeight_ = partialChain.Height(); int32_t partialOffset_ = partialChain.HeightOffset(); int32_t prunedHeight_ = <API key>; int32_t processedSPVHeight_ = CSPVScanner::getProcessedHeight(); int32_t probableHeight_ = GetProbableHeight(); return MonitorRecord(partialHeight_, partialOffset_, prunedHeight_, processedSPVHeight_, probableHeight_); } void ILibraryController::<API key>(const std::shared_ptr<MonitorListener> & listener) { LOCK(<API key>); monitoringListeners.insert(listener); } void ILibraryController::<API key>(const std::shared_ptr<MonitorListener> & listener) { LOCK(<API key>); monitoringListeners.erase(listener); } std::unordered_map<std::string, std::string> ILibraryController::getClientInfo() { std::unordered_map<std::string, std::string> ret; ret.insert(std::pair("client_version", FormatFullVersion())); ret.insert(std::pair("user_agent", strSubVersion)); ret.insert(std::pair("datadir_path", GetDataDir().string())); std::string logfilePath = (GetDataDir() / "debug.log").string(); ret.insert(std::pair("logfile_path", logfilePath)); ret.insert(std::pair("startup_timestamp", i64tostr(nClientStartupTime))); if (!g_connman->GetNetworkActive()) { ret.insert(std::pair("network_status", "disabled")); ret.insert(std::pair("num_connections_in", "0")); ret.insert(std::pair("num_connections_out", "0")); } else { ret.insert(std::pair("network_status", "enabled")); std::string connectionsIn = i64tostr(g_connman->GetNodeCount(CConnman::NumConnections::CONNECTIONS_IN)); std::string connectionsOut = i64tostr(g_connman->GetNodeCount(CConnman::NumConnections::CONNECTIONS_OUT)); ret.insert(std::pair("num_connections_in", connectionsIn)); ret.insert(std::pair("num_connections_out", connectionsOut)); } if (fSPV) { if (partialChain.Tip()) { ret.insert(std::pair("chain_tip_height", i64tostr(partialChain.Height()))); ret.insert(std::pair("chain_tip_time", i64tostr(partialChain.Tip()->GetBlockTime()))); ret.insert(std::pair("chain_tip_hash", partialChain.Tip()->GetBlockHashPoW2().ToString())); ret.insert(std::pair("chain_offset", i64tostr(partialChain.HeightOffset()))); ret.insert(std::pair("chain_pruned_height", i64tostr(<API key>))); ret.insert(std::pair("<API key>", i64tostr(CSPVScanner::getProcessedHeight()))); ret.insert(std::pair("<API key>", i64tostr(GetProbableHeight()))); } } else if (chainActive.Tip()) { ret.insert(std::pair("chain_tip_height", i64tostr(chainActive.Tip()->nHeight))); ret.insert(std::pair("chain_tip_time", i64tostr(chainActive.Tip()->GetBlockTime()))); ret.insert(std::pair("chain_tip_hash", chainActive.Tip()->GetBlockHashPoW2().ToString())); } ret.insert(std::pair("<API key>", i64tostr(mempool.size()))); ret.insert(std::pair("mempool_memory_size", i64tostr(mempool.GetTotalTxSize()))); return ret; }
#ifndef DBADAPTER_H #define DBADAPTER_H #include <mysql/mysql.h> #include <sqlite3.h> #include <string> #include <vector> #include <list> #include "Logger.h" #define <API key> "defaultSQDB.db" typedef std::vector< std::list< std::string > > SQL_RET_TYPE; class DBAdapter { public: enum db_types_t {MYSQL = 1, ORACLE = 2, SQLITE = 3}; DBAdapter(); //Default constructor explicit DBAdapter(const db_types_t type); //constructor to set db type at initialization, imlicit initialization is not allowed ~DBAdapter(); //Destructor bool setDbType(const int &ty); //function to change db type in runtime, if there is an active connection, this function will not run bool connect (const char *ip, const int port, const char *user, const char *pass, int &errorCode); //connects database and resturns the result bool connect (const char *filename, int &errorCode); //connects database and resturns the result for sqlite bool disconnect (int &errorCode); //disconnect from database and return the result bool selectDB(const std::string &dbName, int &errorCode); //selecting DB to connect //bool execQuery(const string &sql, int &errorCode, char * reason); //execute a specific user written query, also returns a failure reason as set of chars bool execQuery(const std::string &sql, int &errorCode); //overloaded version bool execQuery(const void *sql, const int& querySize, int &errorCode); //overloaded version which accepts binary data bool insertData(const std::string &fields, const std::string& values, const std::string &table, int &errorCode); /*inserts data into specific tables Example usage: insertData("name, surname, age", "'john', 'smith', 52", "users", errorCodeVar); */ bool selectData(const std::string &fields, const std::string& condition, const std::string &table, SQL_RET_TYPE &returnVal, int &errorCode, int appendFlag = 0); /*select data from specific tables Example usage: selecttData("name, surname, age", "name='john' or age < 52", "users", errorCodeVar); */ bool selectData(const std::string &fields, const std::string &table, SQL_RET_TYPE &returnVal, int &errorCode, int appendFlag = 0); //overloaded version of select bool deleteData(const std::string& condition, const std::string &table, int &errorCode); /*delete data from specific tables Example usage: deleteData("name=john and age >= 63", "users", errorCodeVar); */ bool updateData(const std::string &fields, const std::string& values, const std::string &condition, const std::string &table, int &errorCode); /*inserts data to specific tables Example usage updatetData("name, surname, age", "'john', 'smith', 52", "name=john and age >= 63", "users", errorCodeVar); */ bool updateData(const std::string &fields, const std::string& values, const std::string &table, int &errorCode); // overloaded version private: int type; //this variable will hold the type of connection bool isConnected; //holds the status of connection SQL_RET_TYPE *rVal; //MYSQL variables start here ::MYSQL *myConnection, myInit; //used for mysql operations and holds connection, myInit is not a pointer because we don't want to handle memory operations for it - Ozgur //MYSQL_RES *myResult; //holds results of the queries //MYSQL_ROW myRow; //holds rows for each result //ORACLE variables will be here //SQLITE variables will be here sqlite3 *SQlitedb; //Other DB variables will be here //Logger object is here Logger *logger; public: //Here starts special functions friend int callBack(void *data, int argc, char **argv, char **azColName); }; #endif
<div> <a href="#/templates">Go Back</a> <br><br> <div class="col-md-4"> <img class="img-full" src="img/{{mainImage}}"> <div class="row"> <div ng-repeat="image in template.images | limitTo:4"> <div class="col-md-3"> <img class="img-full" ng-src="img/{{image.name}}" ng-click="setImage(image)"> </div> </div> </div> </div> <div class="col-md-8"> <h3>{{template.name}}</h3> <p>{{template.description}}</p> <p>Type: {{template.type}}</p> <h4>{{template.price}}</h4> <form action="https: <!-- Specifies Buy Now Button --> <input type="hidden" name="cmd" value="_xclick"> <!-- PayPal Email --> <input type="hidden" name="business" value="techguyseller@sandbox.com"> <!-- Item Name --> <input type="hidden" name="item_name" value="{{template.name}}"> <!-- Item ID --> <input type="hidden" name="item_number" value="{{template.id}}"> <!-- Currency Code --> <input type="hidden" name="currency_code" value="USD"> <!-- Price --> <input type="hidden" name="amount" value="{{template.price}}"> <!-- Specify Shipping --> <input type='hidden' name='no_shipping' value='1'> <!-- Return method --> <input type='hidden' name='rm' value='2'> <!-- Return URL --> <input type="hidden" name="return" value="http://localhost:8000"> <!-- Cancel Return URL --> <input type="hidden" name="cancel_return" value="http://localhost:8000"> <!-- Button --> <input type="image" src="https: </form> </div> </div>
class <API key> < ActiveRecord::Migration[5.1] def self.up create_table :<API key> do |t| t.string :namespace t.text :body t.string :resource_id, null: false t.string :resource_type, null: false t.references :author, polymorphic: true t.timestamps end add_index :<API key>, [:namespace] add_index :<API key>, [:resource_type, :resource_id] end def self.down drop_table :<API key> end end
namespace _03BarracksFactory.Data { using System; using Contracts; using System.Collections.Generic; using System.Text; class UnitRepository : IRepository { private IDictionary<string, int> amountOfUnits; public UnitRepository() { this.amountOfUnits = new SortedDictionary<string, int>(); } public string Statistics { get { StringBuilder statBuilder = new StringBuilder(); foreach (var entry in amountOfUnits) { string formatedEntry = string.Format("{0} -> {1}", entry.Key, entry.Value); statBuilder.AppendLine(formatedEntry); } return statBuilder.ToString().Trim(); } } public void AddUnit(IUnit unit) { string unitType = unit.GetType().Name; if (!this.amountOfUnits.ContainsKey(unitType)) { this.amountOfUnits.Add(unitType, 0); } this.amountOfUnits[unitType]++; } public void RemoveUnit(string unitType) { if (this.amountOfUnits[unitType] > 0) { this.amountOfUnits[unitType] } else { throw new ArgumentException("Not enought units."); } } } }
@copyright Copyright (C) 2020 Assured Information Security, Inc. @copyright Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: @copyright The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. @copyright THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. #ifndef TLS_T_HPP #define TLS_T_HPP #include <state_save_t.hpp> #include <bsl/array.hpp> #include <bsl/convert.hpp> #include <bsl/cstdint.hpp> #include <bsl/errc_type.hpp> #include <bsl/safe_integral.hpp> #pragma pack(push, 1) namespace mk { @brief defines the size of the reserved1 field in the tls_t constexpr auto <API key>{0x020_umx}; @brief defines the size of the reserved2 field in the tls_t constexpr auto <API key>{0x008_umx}; @brief defines the size of the reserved3 field in the tls_t constexpr auto <API key>{0x007_umx}; @brief defines the size of the reserved4 field in the tls_t constexpr auto <API key>{0x040_umx}; IMPORTANT: - If the size of the TLS is changed, the mk_main_entry will need to be updated to reflect the new size. It might make sense to have a header file that defines a constant that both this code and the assembly logic can share @brief defines the the total size of the TLS block constexpr auto TLS_T_SIZE{0x400_umx}; <!-- description --> @brief Defines the layout of the microkernel's TLS block. This should not be confused with the TLS blocks given to an extension, for which there are two, the TLS block for thread_local and the TLS block provided by the microkernel's ABI. struct tls_t final { Microkernel State @brief stores the value of x18 for the microkernel (0x000) bsl::uintmx mk_x18; @brief stores the value of x19 for the microkernel (0x008) bsl::uintmx mk_x19; @brief stores the value of x20 for the microkernel (0x010) bsl::uintmx mk_x20; @brief stores the value of x21 for the microkernel (0x018) bsl::uintmx mk_x21; @brief stores the value of x22 for the microkernel (0x020) bsl::uintmx mk_x22; @brief stores the value of x23 for the microkernel (0x028) bsl::uintmx mk_x23; @brief stores the value of x24 for the microkernel (0x030) bsl::uintmx mk_x24; @brief stores the value of x25 for the microkernel (0x038) bsl::uintmx mk_x25; @brief stores the value of x26 for the microkernel (0x040) bsl::uintmx mk_x26; @brief stores the value of x27 for the microkernel (0x048) bsl::uintmx mk_x27; @brief stores the value of x28 for the microkernel (0x050) bsl::uintmx mk_x28; @brief stores the value of x29 for the microkernel (0x058) bsl::uintmx mk_x29; @brief stores the value of x30 for the microkernel (0x060) bsl::uintmx mk_x30; Extension State @brief x0, stores the extension's syscall (0x068) bsl::uintmx ext_syscall; @brief x1, stores the value of REG1 for the extension (0x070) bsl::uintmx ext_reg0; @brief x2, stores the value of REG1 for the extension (0x078) bsl::uintmx ext_reg1; @brief x3, stores the value of REG1 for the extension (0x080) bsl::uintmx ext_reg2; @brief x4, stores the value of REG1 for the extension (0x088) bsl::uintmx ext_reg3; @brief x5, stores the value of REG1 for the extension (0x090) bsl::uintmx ext_reg4; @brief x6, stores the value of REG1 for the extension (0x098) bsl::uintmx ext_reg5; @brief x7, stores the value of REG1 for the extension (0x0A0) bsl::uintmx reserved_reg7; @brief x8, stores the value of REG1 for the extension (0x0A8) bsl::uintmx reserved_reg8; @brief x9, stores the value of REG1 for the extension (0x0B0) bsl::uintmx reserved_reg9; @brief x10, stores the value of REG1 for the extension (0x0B8) bsl::uintmx reserved_reg10; @brief x11, stores the value of REG1 for the extension (0x0C0) bsl::uintmx reserved_reg11; @brief x12, stores the value of REG1 for the extension (0x0C8) bsl::uintmx reserved_reg12; @brief x13, stores the value of REG1 for the extension (0x0D0) bsl::uintmx reserved_reg13; @brief x14, stores the value of REG1 for the extension (0x0D8) bsl::uintmx reserved_reg14; @brief x15, stores the value of REG1 for the extension (0x0E0) bsl::uintmx reserved_reg15; @brief x16, stores the value of REG1 for the extension (0x0E8) bsl::uintmx reserved_reg16; @brief x17, stores the value of REG1 for the extension (0x0F0) bsl::uintmx reserved_reg17; @brief x18, stores the value of REG1 for the extension (0x0F8) bsl::uintmx reserved_reg18; @brief x19, stores the value of REG1 for the extension (0x100) bsl::uintmx reserved_reg19; @brief x20, stores the value of REG1 for the extension (0x108) bsl::uintmx reserved_reg20; @brief x21, stores the value of REG1 for the extension (0x110) bsl::uintmx reserved_reg21; @brief x22, stores the value of REG1 for the extension (0x118) bsl::uintmx reserved_reg22; @brief x23, stores the value of REG1 for the extension (0x120) bsl::uintmx reserved_reg23; @brief x24, stores the value of REG1 for the extension (0x128) bsl::uintmx reserved_reg24; @brief x25, stores the value of REG1 for the extension (0x130) bsl::uintmx reserved_reg25; @brief x26, stores the value of REG1 for the extension (0x138) bsl::uintmx reserved_reg26; @brief x27, stores the value of REG1 for the extension (0x140) bsl::uintmx reserved_reg27; @brief x28, stores the value of REG1 for the extension (0x148) bsl::uintmx reserved_reg28; @brief x29, stores the value of REG1 for the extension (0x150) bsl::uintmx reserved_reg29; @brief x30, stores the value of REG1 for the extension (0x158) bsl::uintmx reserved_reg30; ESR State @brief stores the value of x0 for the ESR (0x160) bsl::uintmx esr_x0; @brief stores the value of x1 for the ESR (0x168) bsl::uintmx esr_x1; @brief stores the value of x2 for the ESR (0x170) bsl::uintmx esr_x2; @brief stores the value of x3 for the ESR (0x178) bsl::uintmx esr_x3; @brief stores the value of x4 for the ESR (0x180) bsl::uintmx esr_x4; @brief stores the value of x5 for the ESR (0x188) bsl::uintmx esr_x5; @brief stores the value of x6 for the ESR (0x190) bsl::uintmx esr_x6; @brief stores the value of x7 for the ESR (0x198) bsl::uintmx esr_x7; @brief stores the value of x8 for the ESR (0x1A0) bsl::uintmx esr_x8; @brief stores the value of x9 for the ESR (0x1A8) bsl::uintmx esr_x9; @brief stores the value of x10 for the ESR (0x1B0) bsl::uintmx esr_x10; @brief stores the value of x11 for the ESR (0x1B8) bsl::uintmx esr_x11; @brief stores the value of x12 for the ESR (0x1C0) bsl::uintmx esr_x12; @brief stores the value of x13 for the ESR (0x1C8) bsl::uintmx esr_x13; @brief stores the value of x14 for the ESR (0x1D0) bsl::uintmx esr_x14; @brief stores the value of x15 for the ESR (0x1D8) bsl::uintmx esr_x15; @brief stores the value of x16 for the ESR (0x1E0) bsl::uintmx esr_x16; @brief stores the value of x17 for the ESR (0x1E8) bsl::uintmx esr_x17; @brief stores the value of x18 for the ESR (0x1F0) bsl::uintmx esr_x18; @brief stores the value of x19 for the ESR (0x1F8) bsl::uintmx esr_x19; @brief stores the value of x20 for the ESR (0x200) bsl::uintmx esr_x20; @brief stores the value of x21 for the ESR (0x208) bsl::uintmx esr_x21; @brief stores the value of x22 for the ESR (0x210) bsl::uintmx esr_x22; @brief stores the value of x23 for the ESR (0x218) bsl::uintmx esr_x23; @brief stores the value of x24 for the ESR (0x220) bsl::uintmx esr_x24; @brief stores the value of x25 for the ESR (0x228) bsl::uintmx esr_x25; @brief stores the value of x26 for the ESR (0x230) bsl::uintmx esr_x26; @brief stores the value of x27 for the ESR (0x238) bsl::uintmx esr_x27; @brief stores the value of x28 for the ESR (0x240) bsl::uintmx esr_x28; @brief stores the value of x29 for the ESR (0x248) bsl::uintmx esr_x29; @brief stores the value of x30 for the ESR (0x250) bsl::uintmx esr_x30; @brief stores the value of sp for the ESR (0x258) bsl::uintmx esr_sp; @brief stores the value of ip for the ESR (0x260) bsl::uintmx esr_ip; @brief stores the value of the ESR vector (0x268) bsl::uintmx esr_vector; @brief stores the value of the ESR error code (0x270) bsl::uintmx esr_error_code; @brief stores the value of far for the ESR (0x278) bsl::uintmx esr_pf_addr; @brief stores the value of esr for the ESR (0x280) bsl::uintmx esr_esr; @brief stores the value of SPSR for the ESR (0x288) bsl::uintmx esr_spsr; Fast Fail Information @brief stores the current fast fail address (0x290) bsl::uintmx <API key>; @brief stores the current fast fail stack (0x298) bsl::uintmx <API key>; @brief stores the mk_main fast fail address (0x2A0) bsl::uintmx <API key>; @brief stores the mk_main fast fail stack (0x2A8) bsl::uintmx <API key>; @brief stores the call_ext fast fail address (0x2B0) bsl::uintmx <API key>; @brief stores the call_ext fast fail stack (0x2B8) bsl::uintmx <API key>; @brief stores the dispatch_syscall fast fail address (0x2C0) bsl::uintmx <API key>; @brief stores the dispatch_syscall fast fail stack (0x2C8) bsl::uintmx <API key>; @brief stores the vmexit loop address (0x2D0) bsl::uintmx vmexit_loop_ip; @brief stores the vmexit loop stack (0x2D8) bsl::uintmx vmexit_loop_sp; @brief reserve the rest of the TLS block for later use. bsl::array<bsl::uint8, <API key>.get()> reserved1; Context Information @brief stores the virtual address of this TLS block (0x300) tls_t *self; @brief stores the currently active VMID (0x308) bsl::uint16 ppid; @brief stores the total number of online PPs (0x30A) bsl::uint16 online_pps; @brief reserved (0x30C) bsl::uint16 reserved_padding0; @brief reserved (0x30E) bsl::uint16 reserved_padding1; @brief stores the currently active extension (0x310) void *ext; @brief stores the extension registered for VMExits (0x318) void *ext_vmexit; @brief stores the extension registered for fast fail events (0x320) void *ext_fail; @brief stores the loader provided state for the microkernel (0x328) loader::state_save_t *mk_state; @brief stores the loader provided state for the root VP (0x330) loader::state_save_t *root_vp_state; @brief stores the currently active extension ID (0x338) bsl::uint16 active_extid; @brief stores the currently active VMID (0x33A) bsl::uint16 active_vmid; @brief stores the currently active VPID (0x33C) bsl::uint16 active_vpid; @brief stores the currently active VSID (0x33E) bsl::uint16 active_vsid; @brief stores the sp used by extensions for callbacks (0x340) bsl::uintmx sp; @brief stores the tps used by extensions for callbacks (0x348) bsl::uintmx tp; @brief used to store a return address for unsafe ops (0x350) bsl::uintmx unsafe_rip; @brief reserved (0x358) bsl::uintmx reserved_padding2; @brief reserved (0x360) bsl::uintmx reserved_padding3; @brief stores whether or not the first launch succeeded (0x368) bsl::uintmx <API key>; @brief stores the currently active root page table (0x370) void *active_rpt; @brief reserve the rest of the TLS block for later use. bsl::array<bsl::uint8, <API key>.get()> reserved2; }; @brief make sure the tls_t is the size of a page static_assert(sizeof(tls_t) == TLS_T_SIZE); } #pragma pack(pop) #endif
package com.github.bachelorpraktikum.visualisierbar.model; import com.github.bachelorpraktikum.visualisierbar.model.Element.State; import com.github.bachelorpraktikum.visualisierbar.model.Element.Type; public class <API key> extends <API key> { @Override protected Shapeable<?> getShapeable() { Context context = new Context(); Node node = Node.in(context).create("node", new Coordinates(0, 0)); return Element.in(context).create("element", Type.HauptSignal, node, State.FAHRT); } }
package gb import ( "errors" "fmt" "io" "path/filepath" "reflect" "testing" ) func <API key>(t *testing.T) { tests := []struct { pkg string err error }{{ pkg: "a", err: nil, }, { pkg: "b", // actually command err: nil, }, { pkg: "c", err: nil, }, { pkg: "d.v1", err: nil, }, { pkg: "x", err: errors.New("import cycle detected: x -> y -> x"), }, { pkg: "h", // imports "blank", which is blank, see issue #131 err: fmt.Errorf("no buildable Go source files in %s", filepath.Join(getwd(t), "testdata", "src", "blank")), }} for _, tt := range tests { ctx := testContext(t) pkg, err := ctx.ResolvePackage(tt.pkg) if !sameErr(err, tt.err) { t.Errorf("ctx.ResolvePackage(%v): want %v, got %v", tt.pkg, tt.err, err) continue } if err != nil { continue } action, err := BuildPackages(pkg) if err != nil { t.Errorf("BuildAction(%v): ", tt.pkg, err) continue } if err := Execute(action); !sameErr(err, tt.err) { t.Errorf("Execute(%v): want: %v, got %v", action.Name, tt.err, err) } ctx.Destroy() } } var niltask = TaskFn(func() error { return nil }) var executorTests = []struct { action *Action // root action err error // expected error }{{ action: &Action{ Name: "no error", Task: niltask, }, }, { action: &Action{ Name: "root error", Task: TaskFn(func() error { return io.EOF }), }, err: io.EOF, }, { action: &Action{ Name: "child, child, error", Task: TaskFn(func() error { return fmt.Errorf("I should not have been called") }), Deps: []*Action{&Action{ Name: "child, error", Task: niltask, Deps: []*Action{&Action{ Name: "error", Task: TaskFn(func() error { return io.EOF }), }}, }}, }, err: io.EOF, }, { action: &Action{ Name: "once only", Task: TaskFn(func() error { if c1 != 1 || c2 != 1 || c3 != 1 { return fmt.Errorf("unexpected count, c1: %v, c2: %v, c3: %v", c1, c2, c3) } return nil }), Deps: []*Action{createDag()}, }, }, { action: &Action{ Name: "failure count", Task: TaskFn(func() error { return fmt.Errorf("I should not have been called") }), Deps: []*Action{createFailDag()}, }, err: fmt.Errorf("task3 called 1 time"), }} func createDag() *Action { task1 := TaskFn(func() error { c1++; return nil }) task2 := TaskFn(func() error { c2++; return nil }) task3 := TaskFn(func() error { c3++; return nil }) action1 := Action{Name: "c1", Task: task1} action2 := Action{Name: "c2", Task: task2} action3 := Action{Name: "c3", Task: task3} action1.Deps = append(action1.Deps, &action2, &action3) action2.Deps = append(action2.Deps, &action3) return &action1 } func createFailDag() *Action { task1 := TaskFn(func() error { c1++; return nil }) task2 := TaskFn(func() error { c2++; return fmt.Errorf("task2 called %v time", c2) }) task3 := TaskFn(func() error { c3++; return fmt.Errorf("task3 called %v time", c3) }) action1 := Action{Name: "c1", Task: task1} action2 := Action{Name: "c2", Task: task2} action3 := Action{Name: "c3", Task: task3} action1.Deps = append(action1.Deps, &action2, &action3) action2.Deps = append(action2.Deps, &action3) return &action1 } var c1, c2, c3 int func executeReset() { c1 = 0 c2 = 0 c3 = 0 // reset executor test variables } func TestExecute(t *testing.T) { for _, tt := range executorTests { executeReset() got := Execute(tt.action) if !reflect.DeepEqual(got, tt.err) { t.Errorf("Execute: %v: want err: %v, got err %v", tt.action.Name, tt.err, got) } } } func <API key>(t *testing.T, n int) { for _, tt := range executorTests { executeReset() got := ExecuteConcurrent(tt.action, n) if !reflect.DeepEqual(got, tt.err) { t.Errorf("ExecuteConcurrent(%v): %v: want err: %v, got err %v", n, tt.action.Name, tt.err, got) } } } func <API key>(t *testing.T) { <API key>(t, 1) } func <API key>(t *testing.T) { <API key>(t, 2) } func <API key>(t *testing.T) { <API key>(t, 4) } func <API key>(t *testing.T) { <API key>(t, 7) }
<?php if(filemtime(__FILE__) + 1800 < time())return false; return array ( 'id' => 5553, 'goods' => array ( 'goods_id' => '5553', 'store_id' => '132', 'type' => 'material', 'goods_name' => '100g', 'description' => '<p style="text-align: center;"><img src="http: 'cate_id' => '816', 'cate_name' => ' ', 'brand' => '', 'spec_qty' => '0', 'spec_name_1' => '', 'spec_name_2' => '', 'if_show' => '1', 'if_seckill' => '0', 'closed' => '0', 'close_reason' => NULL, 'add_time' => '1421605662', 'last_update' => '1421605662', 'default_spec' => '5557', 'default_image' => 'data/files/store_132/goods_20/<API key>.jpg', 'recommended' => '0', 'cate_id_1' => '815', 'cate_id_2' => '816', 'cate_id_3' => '0', 'cate_id_4' => '0', 'price' => '19.80', 'tags' => array ( 0 => ' ', ), 'cuxiao_ids' => NULL, 'from_goods_id' => '0', 'quanzhong' => NULL, 'state' => '1', '_specs' => array ( 0 => array ( 'spec_id' => '5557', 'goods_id' => '5553', 'spec_1' => '', 'spec_2' => '', 'color_rgb' => '', 'price' => '19.80', 'stock' => '1000', 'sku' => '6956459400622', ), ), '_images' => array ( 0 => array ( 'image_id' => '5204', 'goods_id' => '5553', 'image_url' => 'data/files/store_132/goods_20/201501191027007132.jpg', 'thumbnail' => 'data/files/store_132/goods_20/<API key>.jpg', 'sort_order' => '1', 'file_id' => '21028', ), 1 => array ( 'image_id' => '5205', 'goods_id' => '5553', 'image_url' => 'data/files/store_132/goods_24/201501191027045479.jpg', 'thumbnail' => 'data/files/store_132/goods_24/<API key>.jpg', 'sort_order' => '255', 'file_id' => '21027', ), 2 => array ( 'image_id' => '5206', 'goods_id' => '5553', 'image_url' => 'data/files/store_132/goods_33/201501191027133651.jpg', 'thumbnail' => 'data/files/store_132/goods_33/<API key>.jpg', 'sort_order' => '255', 'file_id' => '21030', ), ), '_scates' => array ( ), 'views' => '1', 'collects' => '0', 'carts' => '0', 'orders' => '0', 'sales' => '0', 'comments' => '0', 'related_info' => array ( ), ), 'store_data' => array ( 'store_id' => '132', 'store_name' => '', 'owner_name' => '', 'owner_card' => '370832200104057894', 'region_id' => '2213', 'region_name' => ' ', 'address' => '', 'zipcode' => '', 'tel' => '15666660007', 'sgrade' => '', 'apply_remark' => '', 'credit_value' => '0', 'praise_rate' => '0.00', 'domain' => '', 'state' => '1', 'close_reason' => '', 'add_time' => '1418929047', 'end_time' => '0', 'certification' => 'autonym,material', 'sort_order' => '65535', 'recommended' => '0', 'theme' => '', 'store_banner' => NULL, 'store_logo' => 'data/files/store_132/other/store_logo.jpg', 'description' => '', 'image_1' => '', 'image_2' => '', 'image_3' => '', 'im_qq' => '', 'im_ww' => '', 'im_msn' => '', 'hot_search' => '', 'business_scope' => '', 'online_service' => array ( ), 'hotline' => '', 'pic_slides' => '', 'pic_slides_wap' => '{"1":{"url":"data/files/store_132/pic_slides_wap/pic_slides_wap_1.jpg","link":"http: 'enable_groupbuy' => '0', 'enable_radar' => '1', 'waptheme' => '', 'is_open_pay' => '0', 'area_peisong' => NULL, 'power_coupon' => '0', 's_long' => '117.096102', 's_lat' => '36.68974', 'user_name' => 'bq516', 'email' => '111111111@qq.com', 'certifications' => array ( 0 => 'autonym', 1 => 'material', ), 'credit_image' => 'http://wap.bqmart.cn/themes/store/default/styles/default/images/heart_1.gif', 'store_owner' => array ( 'user_id' => '132', 'user_name' => 'bq516', 'email' => '111111111@qq.com', 'password' => '<API key>', 'real_name' => '', 'gender' => '0', 'birthday' => '', 'phone_tel' => NULL, 'phone_mob' => NULL, 'im_qq' => '', 'im_msn' => '', 'im_skype' => NULL, 'im_yahoo' => NULL, 'im_aliww' => NULL, 'reg_time' => '1418928900', 'last_login' => '1421874055', 'last_ip' => '123.233.201.48', 'logins' => '136', 'ugrade' => '0', 'portrait' => NULL, 'outer_id' => '0', 'activation' => NULL, 'feed_config' => NULL, 'uin' => '0', 'parentid' => '0', 'user_level' => '0', 'from_weixin' => '0', 'wx_openid' => NULL, 'wx_nickname' => NULL, 'wx_city' => NULL, 'wx_country' => NULL, 'wx_province' => NULL, 'wx_language' => NULL, 'wx_headimgurl' => NULL, 'wx_subscribe_time' => '0', 'wx_id' => '0', 'from_public' => '0', 'm_storeid' => '0', ), 'store_navs' => array ( ), 'kmenus' => false, 'kmenusinfo' => array ( ), 'radio_new' => 1, 'radio_recommend' => 1, 'radio_hot' => 1, 'goods_count' => '1106', 'store_gcates' => array ( ), 'functions' => array ( 'editor_multimedia' => 'editor_multimedia', 'coupon' => 'coupon', 'groupbuy' => 'groupbuy', 'enable_radar' => 'enable_radar', 'seckill' => 'seckill', ), 'hot_saleslist' => array ( 3043 => array ( 'goods_id' => '3043', 'goods_name' => '480g', 'default_image' => 'data/files/store_132/goods_19/<API key>.gif', 'price' => '15.80', 'sales' => '7', ), 3459 => array ( 'goods_id' => '3459', 'goods_name' => '10', 'default_image' => 'data/files/store_132/goods_110/<API key>.jpg', 'price' => '9.60', 'sales' => '7', ), 3650 => array ( 'goods_id' => '3650', 'goods_name' => '450ml', 'default_image' => 'data/files/store_132/goods_5/<API key>.jpg', 'price' => '3.00', 'sales' => '5', ), 3457 => array ( 'goods_id' => '3457', 'goods_name' => '120g', 'default_image' => 'data/files/store_132/goods_71/<API key>.jpg', 'price' => '2.50', 'sales' => '4', ), 3666 => array ( 'goods_id' => '3666', 'goods_name' => '600ml', 'default_image' => 'data/files/store_132/goods_101/<API key>.jpg', 'price' => '4.00', 'sales' => '3', ), 3660 => array ( 'goods_id' => '3660', 'goods_name' => '330ml', 'default_image' => 'data/files/store_132/goods_150/<API key>.jpg', 'price' => '2.00', 'sales' => '1', ), 3230 => array ( 'goods_id' => '3230', 'goods_name' => '1X12X250ml', 'default_image' => 'data/files/store_132/goods_69/<API key>.jpg', 'price' => '98.00', 'sales' => '1', ), 3708 => array ( 'goods_id' => '3708', 'goods_name' => '+c500ml', 'default_image' => 'data/files/store_132/goods_115/<API key>.jpg', 'price' => '4.00', 'sales' => '1', ), 4012 => array ( 'goods_id' => '4012', 'goods_name' => '39 ', 'default_image' => 'data/files/store_132/goods_186/<API key>.jpg', 'price' => '39.00', 'sales' => '1', ), 3464 => array ( 'goods_id' => '3464', 'goods_name' => '114g', 'default_image' => 'data/files/store_132/goods_79/<API key>.jpg', 'price' => '7.50', 'sales' => '0', ), ), 'collect_goodslist' => array ( 5494 => array ( 'goods_id' => '5494', 'goods_name' => '500ml', 'default_image' => 'data/files/store_42/goods_0/<API key>.jpg', 'price' => '9.80', 'collects' => '1', ), 3570 => array ( 'goods_id' => '3570', 'goods_name' => '490ml', 'default_image' => 'data/files/store_132/goods_10/<API key>.jpg', 'price' => '3.00', 'collects' => '1', ), 3777 => array ( 'goods_id' => '3777', 'goods_name' => '450ml', 'default_image' => 'data/files/store_132/goods_47/<API key>.jpg', 'price' => '6.50', 'collects' => '1', ), 3871 => array ( 'goods_id' => '3871', 'goods_name' => '400g', 'default_image' => 'data/files/store_132/goods_103/<API key>.jpg', 'price' => '11.80', 'collects' => '1', ), 3457 => array ( 'goods_id' => '3457', 'goods_name' => '120g', 'default_image' => 'data/files/store_132/goods_71/<API key>.jpg', 'price' => '2.50', 'collects' => '1', ), 3043 => array ( 'goods_id' => '3043', 'goods_name' => '480g', 'default_image' => 'data/files/store_132/goods_19/<API key>.gif', 'price' => '15.80', 'collects' => '1', ), 3800 => array ( 'goods_id' => '3800', 'goods_name' => '450g', 'default_image' => 'data/files/store_132/goods_12/<API key>.jpg', 'price' => '13.50', 'collects' => '1', ), 3459 => array ( 'goods_id' => '3459', 'goods_name' => '10', 'default_image' => 'data/files/store_132/goods_110/<API key>.jpg', 'price' => '9.60', 'collects' => '1', ), 3130 => array ( 'goods_id' => '3130', 'goods_name' => '25g', 'default_image' => 'data/files/store_132/goods_110/<API key>.jpg', 'price' => '2.50', 'collects' => '1', ), 3464 => array ( 'goods_id' => '3464', 'goods_name' => '114g', 'default_image' => 'data/files/store_132/goods_79/<API key>.jpg', 'price' => '7.50', 'collects' => '0', ), ), 'left_rec_goods' => array ( 3043 => array ( 'goods_name' => '480g', 'default_image' => 'data/files/store_132/goods_19/<API key>.gif', 'price' => '15.80', 'sales' => '7', 'goods_id' => '3043', ), 3457 => array ( 'goods_name' => '120g', 'default_image' => 'data/files/store_132/goods_71/<API key>.jpg', 'price' => '2.50', 'sales' => '4', 'goods_id' => '3457', ), 3459 => array ( 'goods_name' => '10', 'default_image' => 'data/files/store_132/goods_110/<API key>.jpg', 'price' => '9.60', 'sales' => '7', 'goods_id' => '3459', ), 3570 => array ( 'goods_name' => '490ml', 'default_image' => 'data/files/store_132/goods_10/<API key>.jpg', 'price' => '3.00', 'sales' => '0', 'goods_id' => '3570', ), 5494 => array ( 'goods_name' => '500ml', 'default_image' => 'data/files/store_42/goods_0/<API key>.jpg', 'price' => '9.80', 'sales' => '0', 'goods_id' => '5494', ), ), ), 'cur_local' => array ( 0 => array ( 'text' => '', 'url' => 'index.php?app=category', ), 1 => array ( 'text' => '', 'url' => 'index.php?app=search&amp;cate_id=815', ), 2 => array ( 'text' => '', 'url' => 'index.php?app=search&amp;cate_id=816', ), 3 => array ( 'text' => '', ), ), 'share' => array ( 4 => array ( 'title' => '', 'link' => 'http: 'type' => 'share', 'sort_order' => 255, 'logo' => 'data/system/kaixin001.gif', ), 3 => array ( 'title' => 'QQ', 'link' => 'http://shuqian.qq.com/post?from=3&title=%E7%99%BE%E6%9E%A3%E7%BA%B2%E7%9B%AE%E5%A4%B9%E5%BF%83%E6%9E%A3%E6%A0%B8%E6%A1%83100g-%E5%BE%AE%E4%BF%A1%E5%95%86%E5%9F%8E++++++&uri=http%3A%2F%2Fwap.bqmart.cn%2Findex.php%3Fapp%3Dgoods%26id%3D5553&jumpback=2&noui=1', 'type' => 'collect', 'sort_order' => 255, 'logo' => 'data/system/qqshuqian.gif', ), 2 => array ( 'title' => '', 'link' => 'http://share.renren.com/share/buttonshare.do?link=http%3A%2F%2Fwap.bqmart.cn%2Findex.php%3Fapp%3Dgoods%26id%3D5553&title=%E7%99%BE%E6%9E%A3%E7%BA%B2%E7%9B%AE%E5%A4%B9%E5%BF%83%E6%9E%A3%E6%A0%B8%E6%A1%83100g-%E5%BE%AE%E4%BF%A1%E5%95%86%E5%9F%8E', 'type' => 'share', 'sort_order' => 255, 'logo' => 'data/system/renren.gif', ), 1 => array ( 'title' => '', 'link' => 'http://cang.baidu.com/do/add?it=%E7%99%BE%E6%9E%A3%E7%BA%B2%E7%9B%AE%E5%A4%B9%E5%BF%83%E6%9E%A3%E6%A0%B8%E6%A1%83100g-%E5%BE%AE%E4%BF%A1%E5%95%86%E5%9F%8E++++++&iu=http%3A%2F%2Fwap.bqmart.cn%2Findex.php%3Fapp%3Dgoods%26id%3D5553&fr=ien#nw=1', 'type' => 'collect', 'sort_order' => 255, 'logo' => 'data/system/baidushoucang.gif', ), ), ); ?>
# Fetching User Objects Fetching user objects is a simple way to get at specific objects that you know the IDs of or to access all user objects. This does not access objects owned by the application. If you know more detail about the object you are looking for, but do not know the object ids, you might find it easier to use the [Object Search](#/javascript#<API key>) feature instead. If you want to access all objects stored in your logged in user, use `ws.get()`: js // Assuming the ws object is a WebService instance with a logged in user // Lets say you had an object with an id "comedians" an the value of: // { favorite: "Lewis Black", second: "Louis CK" } // and another object with a value of "cheesecake" var response = ws.get(); response.on('success', function(data, response) { // Data returned on success will be keyed by id, unsorted. console.log(data); // comedians: { // favorite: "Lewis Black", // second: "Louis CK" // another_object: "cheesecake", // ... and every other object in your application... }); {{note "Fetch operations are limited to 50 results by default. To retreive more objects you need to specify a limit, or page through results. See Sorting and Paging for more information."}} To fetch application objects while using a logged in WebService instance: js ws.get({applevel: true}).on(function(data, response) { console.log(data); // Contents of data contains all application objects. }); To fetch a single object, simply give the key of the object: js ws.get('comedians').on('success', function(data, response) { // Only the comedians object will be returned, but still keyed by the object id. console.log(data); // comedians: { // favorite: "Lewis Black", // second: "Louis CK" // another_object: "cheesecake", // ... and every other object in your application... }); Or you can give a list of ids to fetch multiple objects: js ws.get(['another_object', 'comedians']).on('success', function(data, response) { console.log(data); // comedians: { // favorite: "Lewis Black", // second: "Louis CK" // another_object: "cheesecake" }); {{caution "Even if you specify a list of more than 50 items, the results will still be limited to the 50 items unless you specify a limit."}} {{jsEvents 'success.ok' 'error.unauthorized.notfound' 'complete'}}
<html dir="rtl"> <head> <title>Testing textpath</title> <style type="text/css"> @import "../../../../../dojo/resources/dojo.css"; @import "../../../../../dijit/tests/css/dijitTests.css"; </style> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <script type="text/javascript" src="../../../../../dojo/dojo.js" djConfig="isDebug: true, gfxRenderer:'canvas'"></script> <script type="text/javascript"> dojo.require("dojox.gfx"); dojo.require("dojox.gfx._gfxBidiSupport"); dojo.require("doh.runner"); var CPD = 30, tp1, tp2, tp3, tp4, tp5, tp6, t1, t2, t3, t4, t5, t6; var g1 = null, g2 = null, g3, g4; var surfaceLTR = null, surfaceRTL = null, surfaceAUTO = null; var placeAnchor = function(surface, x, y){ surface.createLine({x1: x - 2, y1: y, x2: x + 2, y2: y}); surface.createLine({x1: x, y1: y - 2, x2: x, y2: y + 2}); }; var makeText = function(surface, text, font, fill, stroke){ var t = surface.createText(text); if(font) t.setFont(font); if(fill) t.setFill(fill); if(stroke) t.setStroke(stroke); placeAnchor(surface, text.x, text.y); return t; }; makeShapes = function(){ var m = dojox.gfx.matrix; surfaceLTR = dojox.gfx.createSurface("testLTR", 500, 170, "ltr"); console.debug("surfaceLTR created"); var p = surfaceLTR.createPath({}) .moveTo(0, 15) .setAbsoluteMode(false) .curveTo(CPD, 0, 0, 0, 50, 0) ; console.debug("p created"); tp1 = surfaceLTR.createTextPath({ text: "\u05d4\u05ea\u05d7\u05dc\u05d4 end. " , align: "start" }) .moveTo(0, 15) .setAbsoluteMode(false) .curveTo(CPD, 0, 0, 0, 100, 0) .setFont({family: "times", size: "12pt"}) .setFill("blue") ; console.debug("tp1 created"); tp2 = surfaceLTR.createTextPath({ text: "Beginning \u05e1\u05d5\u05e3." , align: "start" }) .moveTo(0, 50) .setAbsoluteMode(false) .curveTo(CPD, 0, 0, 0, 100, 0) .setFont({family: "times", size: "12pt"}) .setFill("blue") ; console.debug("tp2 created"); g1 = surfaceLTR.createGroup(); g1.setTextDir("rtl"); // surfaceLTR.setTextDir("ltr"); t1 = makeText(g1, {id: "t1",x: 0, y: 100, text: "1.) \u05d4\u05ea\u05d7\u05dc\u05d4 end!"}, {family: "Times", size: "18pt"}, "black", "blue") .setTransform(m.rotategAt(0, 250, 150)); t2 = makeText(surfaceLTR, {x: 0, y: 140, text: "1.) Beginning \u05e1\u05d5\u05e3!"}, {family: "Times", size: "18pt"}, "black", "blue") .setTransform(m.rotategAt(0, 250, 100)); surfaceRTL = dojox.gfx.createSurface("testRTL", 500, 170); console.debug("surfaceRTL created"); var p2 = surfaceRTL.createPath({}) .moveTo(0, 15) .setAbsoluteMode(false) .curveTo(CPD, 0, 0, 0, 100, 0) ; console.debug("p2 created"); tp3 = surfaceRTL.createTextPath({ text: "\u05d4\u05ea\u05d7\u05dc\u05d4 end. " , align: "start" //, rotated: true }) .moveTo(0, 15) .setAbsoluteMode(false) .curveTo(CPD, 0, 100 - CPD, 0, 100, 0) .setFont({family: "times", size: "12pt"}) .setFill("red") ; g2 = surfaceRTL.createGroup(); g2.add(tp3); g2.setTextDir("ltr"); g3 = g2.createGroup("rtl"); g4 = surfaceRTL.createGroup("auto"); tp4 = surfaceRTL.createTextPath({ text: "Beginning \u05e1\u05d5\u05e3." , align: "start" //, rotated: true }) //.setShape(p.shape) .moveTo(0, 50) .setAbsoluteMode(false) .curveTo(CPD, 0, 100 - CPD, 0, 100, 0) .setFont({family: "times", size: "12pt"}) .setFill("red") ; console.debug("tp4 created"); t3 = makeText(g3, {id: "t1",x: 0, y: 100, text: "1.) \u05d4\u05ea\u05d7\u05dc\u05d4 end!"}, {family: "Times", size: "18pt"}, "black", "red") .setTransform(m.rotategAt(0, 250, 150)); t4 = makeText(surfaceRTL, {x: 0, y: 140, text: "1.) Beginning \u05e1\u05d5\u05e3!"}, {family: "Times", size: "18pt"}, "black", "red") .setTransform(m.rotategAt(0, 250, 100)); surfaceAUTO = dojox.gfx.createSurface("testAUTO", 500, 170,"auto"); console.debug("surfaceAUTO created"); var p3 = surfaceAUTO.createPath({}) .moveTo(0, 15) .setAbsoluteMode(false) .curveTo(CPD, 0, 0, 0, 100, 0) ; console.debug("p3 created"); tp5 = surfaceAUTO.createTextPath({ text: "\u05d4\u05ea\u05d7\u05dc\u05d4 end. " , align: "start" //, rotated: true }) //.setShape(p.shape) .moveTo(0, 15) .setAbsoluteMode(false) .curveTo(CPD, 0, 100 - CPD, 0, 100, 0) .setFont({family: "times", size: "12pt"}) .setFill("red") ; console.debug("tp5 created"); tp6 = surfaceAUTO.createTextPath({ text: "Beginning \u05e1\u05d5\u05e3." , align: "start" //, rotated: true }) //.setShape(p.shape) .moveTo(0, 50) .setAbsoluteMode(false) .curveTo(CPD, 0, 100 - CPD, 0, 100, 0) .setFont({family: "times", size: "12pt"}) .setFill("blue") ; console.debug("tp6 created"); t5 = makeText(surfaceAUTO, {id: "t1",x: 0, y: 100, text: "1.) \u05d4\u05ea\u05d7\u05dc\u05d4 end!"}, {family: "Times", size: "18pt"}, "black", "red") .setTransform(m.rotategAt(0, 250, 150)); t6 = makeText(surfaceAUTO, {x: 0, y: 140, text: "1.) Beginning \u05e1\u05d5\u05e3!"}, {family: "Times", size: "18pt"}, "black", "blue") .setTransform(m.rotategAt(0, 250, 100)); }; dojo.addOnLoad(function(){ makeShapes(); doh.register("Test inheritance", [ function surfaces_TextDir(){ doh.is("ltr", surfaceLTR.getTextDir(), "surfaceLTR.getTextDir"); doh.is("rtl", surfaceRTL.getTextDir(), "surfaceRTL.getTextDir"); doh.is("auto", surfaceAUTO.getTextDir(), "surfaceAUTO.getTextDir"); }, function groups_TextDir(){ doh.is("rtl", g1.getTextDir(), "g1.getTextDir"); doh.is("ltr", g2.getTextDir(), "g2.getTextDir"); doh.is("rtl", g3.getTextDir(), "g3.getTextDir"); doh.is("auto", g4.getTextDir(), "g4.getTextDir"); }, function gfxText_TextDir(){ doh.is("rtl", t1.textDir, "t1.getTextDir"); doh.is("ltr", t2.textDir, "t2.getTextDir"); doh.is("rtl", t3.textDir, "t3.getTextDir"); doh.is("rtl", t4.textDir, "t4.getTextDir"); doh.is("auto", t5.textDir, "t5.getTextDir"); doh.is("auto", t6.textDir, "t6h.getTextDir"); }, function gfxTextPath_TextDir(){ doh.is("ltr", tp1.textDir, "tp1.getTextDir"); doh.is("ltr", tp2.textDir, "tp2.getTextDir"); doh.is("ltr", tp3.textDir, "tp3.getTextDir"); doh.is("rtl", tp4.textDir, "tp4.getTextDir"); doh.is("auto", tp5.textDir, "tp5.getTextDir"); doh.is("auto", tp6.textDir, "tp6.getTextDir"); }, function <API key>(){ surfaceRTL.setTextDir("ltr"); doh.is("ltr", surfaceRTL.getTextDir(), "surfaceRTL.getTextDir"); doh.is("ltr", g2.getTextDir(), "g2.getTextDir"); doh.is("ltr", g3.getTextDir(), "g3.getTextDir"); doh.is("ltr", g4.getTextDir(), "g4.getTextDir"); doh.is("ltr", t3.textDir, "t3.getTextDir"); doh.is("ltr", t4.textDir, "t4.getTextDir"); doh.is("ltr", tp3.textDir, "tp3.getTextDir"); doh.is("ltr", tp4.textDir, "tp4.getTextDir"); }, function changeGroupTextDir(){ g3.add(tp5); g3.add(t2); g2.setTextDir("rtl"); doh.is("rtl", g2.getTextDir(), "g2.getTextDir"); // son of g2 doh.is("rtl", g3.getTextDir(), "g3.getTextDir"); doh.is("rtl", t2.textDir, "t2.getTextDir"); doh.is("rtl", t3.textDir, "t3.getTextDir"); doh.is("rtl", tp5.textDir, "tp3.getTextDir"); } ]); doh.run(); }); </script> </head> <body> <h1>dojox.gfx Text on a Path test</h1> <h2>LTR TextPath and Text first two are TextPath and two others are Text</h2> <div id="testLTR" style="width: 500px;"></div> <h2>RTL Text Path and Text first two are TextPath and two others are Text</h2> <div id="testRTL" style="width: 500px;"></div> <h2>AUTO Text Path and Text first two are TextPath and two others are Text</h2> <div id="testAUTO" style="width: 500px;"></div> <p>That's all Folks!</p> </body> </html>
package org.jeasy.random; import static org.jeasy.random.FieldPredicates.*; import static org.assertj.core.api.Assertions.assertThat; import java.lang.reflect.Modifier; import java.util.ArrayList; import java.util.List; import org.jeasy.random.api.<API key>; import org.jeasy.random.api.RandomizerContext; import org.jeasy.random.beans.*; import org.jeasy.random.beans.exclusion.A; import org.jeasy.random.beans.exclusion.B; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; import org.mockito.junit.jupiter.MockitoExtension; import org.jeasy.random.beans.exclusion.C; @ExtendWith(MockitoExtension.class) class FieldExclusionTest { private EasyRandom easyRandom; @BeforeEach void setUp() { easyRandom = new EasyRandom(); } @Test void <API key>() { // given <API key> parameters = new <API key>() .excludeField(named("name")); easyRandom = new EasyRandom(parameters); // when Person person = easyRandom.nextObject(Person.class); //then assertThat(person).isNotNull(); assertThat(person.getName()).isNull(); } @Test void <API key>() { // given <API key> parameters = new <API key>() .excludeField(named("name").and(ofType(String.class)).and(inClass(Human.class))); easyRandom = new EasyRandom(parameters); // when Person person = easyRandom.nextObject(Person.class); // then assertThat(person).isNotNull(); assertThat(person.getName()).isNull(); } @Test void <API key>() { // given <API key> parameters = new <API key>().excludeField(named("name")); easyRandom = new EasyRandom(parameters); // when Person person = easyRandom.nextObject(Person.class); // then assertThat(person).isNotNull(); assertThat(person.getAddress()).isNotNull(); assertThat(person.getAddress().getStreet()).isNotNull(); // person.name and street.name should be null assertThat(person.getName()).isNull(); assertThat(person.getAddress().getStreet().getName()).isNull(); } @Test void <API key>() { // given <API key> parameters = new <API key>() .excludeField(named("name").and(inClass(Street.class))); easyRandom = new EasyRandom(parameters); // when Person person = easyRandom.nextObject(Person.class); // then assertThat(person).isNotNull(); assertThat(person.getAddress()).isNotNull(); assertThat(person.getAddress().getStreet()).isNotNull(); assertThat(person.getAddress().getStreet().getName()).isNull(); } @Test void <API key>() { Person person = easyRandom.nextObject(Person.class); assertThat(person).isNotNull(); assertThat(person.getExcluded()).isNull(); } @Test @SuppressWarnings("deprecation") void <API key>() { // given <API key> parameters = new <API key>().excludeField(isAnnotatedWith(Deprecated.class)); easyRandom = new EasyRandom(parameters); // when Website website = easyRandom.nextObject(Website.class); // then assertThat(website).isNotNull(); assertThat(website.getProvider()).isNull(); } @Test void <API key>() { // given <API key> parameters = new <API key>().excludeField(inClass(Address.class)); easyRandom = new EasyRandom(parameters); // when Person person = easyRandom.nextObject(Person.class); // then assertThat(person).isNotNull(); assertThat(person.getAddress()).isNotNull(); // all fields declared in class Address must be null assertThat(person.getAddress().getCity()).isNull(); assertThat(person.getAddress().getStreet()).isNull(); assertThat(person.getAddress().getZipCode()).isNull(); assertThat(person.getAddress().getCountry()).isNull(); } @Test void <API key>() { <API key> parameters = new <API key>() .excludeField(named("b2").and(inClass(C.class))); easyRandom = new EasyRandom(parameters); C c = easyRandom.nextObject(C.class); assertThat(c).isNotNull(); // B1 and its "children" must not be null assertThat(c.getB1()).isNotNull(); assertThat(c.getB1().getA1()).isNotNull(); assertThat(c.getB1().getA1().getS1()).isNotNull(); assertThat(c.getB1().getA1().getS2()).isNotNull(); assertThat(c.getB1().getA2()).isNotNull(); assertThat(c.getB1().getA2().getS1()).isNotNull(); assertThat(c.getB1().getA2().getS2()).isNotNull(); // B2 must be null assertThat(c.getB2()).isNull(); } @Test void <API key>() { // goal: exclude only b2.a2 <API key> parameters = new <API key>() .randomize(ofType(A.class).and(inClass(B.class)), new <API key><A>() { private RandomizerContext context; @Override public void <API key>(RandomizerContext context) { this.context = context; } @Override public A getRandomValue() { if (context.getCurrentField().equals("b2.a2")) { return null; } return new EasyRandom().nextObject(A.class); } }); easyRandom = new EasyRandom(parameters); C c = easyRandom.nextObject(C.class); assertThat(c).isNotNull(); // B1 and its "children" must not be null assertThat(c.getB1()).isNotNull(); assertThat(c.getB1().getA1()).isNotNull(); assertThat(c.getB1().getA1().getS1()).isNotNull(); assertThat(c.getB1().getA1().getS2()).isNotNull(); assertThat(c.getB1().getA2()).isNotNull(); assertThat(c.getB1().getA2().getS1()).isNotNull(); assertThat(c.getB1().getA2().getS2()).isNotNull(); // Only B2.A2 must be null assertThat(c.getB2()).isNotNull(); assertThat(c.getB2().getA1()).isNotNull(); assertThat(c.getB2().getA1().getS1()).isNotNull(); assertThat(c.getB2().getA1().getS2()).isNotNull(); assertThat(c.getB2().getA2()).isNull(); } @Test void <API key>() { // goal: exclude only b2.a2.s2 <API key> parameters = new <API key>() .randomize(FieldPredicates.named("s2").and(inClass(A.class)), new <API key><String>() { private RandomizerContext context; @Override public void <API key>(RandomizerContext context) { this.context = context; } @Override public String getRandomValue() { if (context.getCurrentField().equals("b2.a2.s2")) { return null; } return new EasyRandom().nextObject(String.class); } }); easyRandom = new EasyRandom(parameters); C c = easyRandom.nextObject(C.class); // B1 and its "children" must not be null assertThat(c.getB1()).isNotNull(); assertThat(c.getB1().getA1()).isNotNull(); assertThat(c.getB1().getA1().getS1()).isNotNull(); assertThat(c.getB1().getA1().getS2()).isNotNull(); assertThat(c.getB1().getA2()).isNotNull(); assertThat(c.getB1().getA2().getS1()).isNotNull(); assertThat(c.getB1().getA2().getS2()).isNotNull(); // Only B2.A2.S2 must be null assertThat(c.getB2()).isNotNull(); assertThat(c.getB2().getA1()).isNotNull(); assertThat(c.getB2().getA1().getS1()).isNotNull(); assertThat(c.getB2().getA1().getS2()).isNotNull(); assertThat(c.getB2().getA2().getS1()).isNotNull(); assertThat(c.getB2().getA2().getS2()).isNull(); } @Test void <API key>() { <API key> parameters = new <API key>() .excludeField(FieldPredicates.named("b3").and(inClass(C.class))); easyRandom = new EasyRandom(parameters); C c = easyRandom.nextObject(C.class); assertThat(c).isNotNull(); // B1 and its "children" must not be null assertThat(c.getB1()).isNotNull(); assertThat(c.getB1().getA1()).isNotNull(); assertThat(c.getB1().getA1().getS1()).isNotNull(); assertThat(c.getB1().getA1().getS2()).isNotNull(); assertThat(c.getB1().getA2()).isNotNull(); assertThat(c.getB1().getA2().getS1()).isNotNull(); assertThat(c.getB1().getA2().getS2()).isNotNull(); // B1 and its "children" must not be null assertThat(c.getB2()).isNotNull(); assertThat(c.getB2().getA1()).isNotNull(); assertThat(c.getB2().getA1().getS1()).isNotNull(); assertThat(c.getB2().getA1().getS2()).isNotNull(); assertThat(c.getB2().getA2()).isNotNull(); assertThat(c.getB2().getA2().getS1()).isNotNull(); assertThat(c.getB2().getA2().getS2()).isNotNull(); // B3 must be null assertThat(c.getB3()).isNull(); } @Test void <API key>() { // b3.a2 does not make sense, should be ignored <API key> parameters = new <API key>() .randomize(FieldPredicates.named("a2").and(inClass(B.class)), new <API key><A>() { private RandomizerContext context; @Override public void <API key>(RandomizerContext context) { this.context = context; } @Override public A getRandomValue() { if (context.getCurrentField().equals("b3.a2")) { return null; } return new EasyRandom().nextObject(A.class); } }); easyRandom = new EasyRandom(parameters); C c = easyRandom.nextObject(C.class); assertThat(c).isNotNull(); // B1 and its "children" must not be null assertThat(c.getB1()).isNotNull(); assertThat(c.getB1().getA1()).isNotNull(); assertThat(c.getB1().getA1().getS1()).isNotNull(); assertThat(c.getB1().getA1().getS2()).isNotNull(); assertThat(c.getB1().getA2()).isNotNull(); assertThat(c.getB1().getA2().getS1()).isNotNull(); assertThat(c.getB1().getA2().getS2()).isNotNull(); // B2 and its "children" must not be null assertThat(c.getB2()).isNotNull(); assertThat(c.getB2().getA1()).isNotNull(); assertThat(c.getB2().getA1().getS1()).isNotNull(); assertThat(c.getB2().getA1().getS2()).isNotNull(); assertThat(c.getB2().getA2()).isNotNull(); assertThat(c.getB2().getA2().getS1()).isNotNull(); assertThat(c.getB2().getA2().getS2()).isNotNull(); // B3 must not be null assertThat(c.getB3()).isNotNull(); } @Test void <API key>() { // given <API key> parameters = new <API key>() .excludeField(named("myList").and(ofType(List.class)).and(inClass(<API key>.class))); easyRandom = new EasyRandom(parameters); // when <API key> bean = easyRandom.nextObject(<API key>.class); // then assertThat(bean).isNotNull(); assertThat(bean.getMyList()).isEmpty(); } @Test void whenFieldIsExcluded_thenItsInlineInitializationShouldBeUsedAsIs_EvenIfBeanHasNoPublicConstructor() { // given <API key> parameters = new <API key>() .excludeField(named("myList").and(ofType(List.class)).and(inClass(<API key>.class))); easyRandom = new EasyRandom(parameters); // when <API key> bean = easyRandom.nextObject(<API key>.class); // then assertThat(bean.getMyList()).isEmpty(); } @Test void <API key>() { // given <API key> parameters = new <API key>().excludeField(hasModifiers(Modifier.TRANSIENT)); easyRandom = new EasyRandom(parameters); // when Person person = easyRandom.nextObject(Person.class); // then assertThat(person).isNotNull(); assertThat(person.getEmail()).isNull(); } @Test void <API key>() { // given <API key> parameters = new <API key>().excludeField(hasModifiers(Modifier.TRANSIENT | Modifier.PROTECTED)); easyRandom = new EasyRandom(parameters); // when Person person = easyRandom.nextObject(Person.class); // then assertThat(person).isNotNull(); assertThat(person.getEmail()).isNull(); } @Test void <API key>() { // given <API key> parameters = new <API key>().excludeField(hasModifiers(Modifier.TRANSIENT | Modifier.PUBLIC)); easyRandom = new EasyRandom(parameters); // when Person person = easyRandom.nextObject(Person.class); // then assertThat(person).isNotNull(); assertThat(person.getEmail()).isNotNull(); } public static class <API key> { private List<String> myList = new ArrayList<>(); public List<String> getMyList() { return myList; } public void setMyList(List<String> myList) { this.myList = myList; } } public static class <API key> { private List<String> myList = new ArrayList<>(); public List<String> getMyList() { return myList; } private <API key>() {} } }
__all__ = [] import pkgutil import inspect for loader, name, is_pkg in pkgutil.walk_packages(__path__): module = loader.find_module(name).load_module(name) for name, value in inspect.getmembers(module): if name.startswith('__'): continue globals()[name] = value __all__.append(name)
namespace PInvoke { using System; using System.Diagnostics.CodeAnalysis; using System.Text; using static Kernel32; <content> Methods and nested types that are not strictly P/Invokes but provide a slightly higher level of functionality to ease calling into native code. </content> [SuppressMessage("ReSharper", "InconsistentNaming", Justification = "Functions are named like their native counterparts")] public static partial class Hid { public static Guid HidD_GetHidGuid() { Guid guid; HidD_GetHidGuid(out guid); return guid; } public static HiddAttributes HidD_GetAttributes(SafeObjectHandle hFile) { var result = HiddAttributes.Create(); if (!HidD_GetAttributes(hFile, ref result)) { throw new Win32Exception(); } return result; } public static <API key> <API key>(SafeObjectHandle hDevice) { <API key> preparsedDataHandle; if (!<API key>(hDevice, out preparsedDataHandle)) { throw new Win32Exception(); } return preparsedDataHandle; } public static HidpCaps HidP_GetCaps(<API key> preparsedData) { var hidCaps = default(HidpCaps); var result = HidP_GetCaps(preparsedData, ref hidCaps); switch (result.Value) { case NTSTATUS.Code.HIDP_STATUS_SUCCESS: return hidCaps; case NTSTATUS.Code.<API key>: throw new ArgumentException("The specified preparsed data is invalid.", nameof(preparsedData)); default: result.ThrowOnError(); throw new <API key>("HidP_GetCaps returned an unexpected success value"); } } public static bool <API key>(SafeObjectHandle hidDeviceObject, out string result) { return GrowStringBuffer(sb => <API key>(hidDeviceObject, sb, sb.Capacity), out result); } public static bool <API key>(SafeObjectHandle hidDeviceObject, out string result) { return GrowStringBuffer(sb => <API key>(hidDeviceObject, sb, sb.Capacity), out result); } public static bool <API key>(SafeObjectHandle hidDeviceObject, out string result) { return GrowStringBuffer(sb => <API key>(hidDeviceObject, sb, sb.Capacity), out result); } public static string <API key>(SafeObjectHandle hidDeviceObject) { string result; if (!<API key>(hidDeviceObject, out result)) { throw new Win32Exception(); } return result; } public static string <API key>(SafeObjectHandle hidDeviceObject) { string result; if (!<API key>(hidDeviceObject, out result)) { throw new Win32Exception(); } return result; } public static string <API key>(SafeObjectHandle hidDeviceObject) { string result; if (!<API key>(hidDeviceObject, out result)) { throw new Win32Exception(); } return result; } private static bool GrowStringBuffer(Func<StringBuilder, bool> nativeMethod, out string result) { // USB Hid maximum size is 126 wide chars + '\0' = 254 bytes, allocating 256 bytes we should never grow // until another HID standard decide otherwise. var stringBuilder = new StringBuilder(256); // If we ever resize over this value something got really wrong const int <API key> = 1 * 1024 * 2014; while (stringBuilder.Capacity < <API key>) { if (nativeMethod(stringBuilder)) { result = stringBuilder.ToString(); return true; } if (GetLastError() != Win32ErrorCode.<API key>) { result = null; return false; } stringBuilder.Capacity = stringBuilder.Capacity * 2; } result = null; return false; } } }
var searchData= [ ['player',['player',['../classplayer.html#<API key>',1,'player']]] ];
using System; namespace nanoFramework.Tools.Debugger.Usb { // This class is kept here for reference only. // It was to provide backwards compatibility with NETMF WinUSB devices of v4.4 // In the current nanoFramework implementation USB connection with devices is carried using USB CDC public class STM_Discovery4 { public const UInt16 DeviceVid = 0x0483; public const UInt16 DevicePid = 0xA08F; <summary> USB device interface class GUID. For NETMF debug capable devices this must be {<API key>}. </summary> public static Guid <API key> = new Guid("{<API key>}"); <summary> ID string for the device </summary> public static String IDString { get { return String.Format("VID_{0:X4}&PID_{1:X4}", DeviceVid, DevicePid); } } public static new string ToString() { return "ST Discovery4"; } } }
<?php return unserialize('a:1:{i:0;O:27:"Doctrine\\ORM\\Mapping\\Column":9:{s:4:"name";s:5:"parg4";s:4:"type";s:4:"text";s:6:"length";N;s:9:"precision";i:0;s:5:"scale";i:0;s:6:"unique";b:0;s:8:"nullable";b:1;s:7:"options";a:0:{}s:16:"columnDefinition";N;}}');
Deprecated. Now with Docker-Compose, there is little reason for gobox. # gobox: Golang Process Boxer gobox manages your microservices for testing and production scenarios. ## Motivation **You**... - ...are building a large application with a service-oriented design. - ...have a variety of services that need to be running in order to execute integration tests. - ...really like docker, but due to frequent updates to your service layer, don't like the idea of having to constantly rebuild images. With gobox, you can define a set of processes *and* specify run commands that are to be used in `test` and `production` scenarios. Further, you can define the environment for each scenario at both the process- and global-level. ## Installation Use the Go tool: go get github.com/tristanwietsma/gobox ## Usage bash $ gobox -h Usage of gobox: -config=".gobox.toml": path to gobox config file -prod=false: run in production mode Define a configuration file By default, gobox will look for a `.gobox.toml` file in the current working directory. Alternatively, you can specify the file location. Define global environment settings You can specify environment settings for both production and testing using the `prodenviron` and `testenviron` parameters. prodenviron = ["VAR1=VAL1", "VAR2=VAL2"] testenviron = ["VAR1=X", "VAR2=Z"] Define each processes For each process, define a `proc` block in the toml file. A `proc` definition looks like this: [[proc]] name = "name of the process" priority = 1 prodcommand = "shell command for production use" prodenviron = ["NAME=prod1"] testcommand = "shell command for test use" testenviron = ["NAME=test1"] # Name `name` is purely for logging purposes. # Priority `priority` is an integer the defines the order in which the process should be started relative to other processes in the configuration. Lower numbers have higher priority. Running Test Mode Test mode is the default. Assuming the config file is `.gobox.toml` in the current directory, bash $ gobox Running Production Mode bash $ gobox -prod=true Stopping gobox listens for kill signals and shuts down processes before exiting.
/* dtpicker javascript jQuery */ (function($) { 'use strict'; var pluginName = 'dtpicker'; var PluginClass=T.UI.Controls.DTPicker; var pluginRef = 't-plugin-ref'; $.fn[pluginName] = function(options) { if(typeof options === 'string'){ // 2. API var plugin = this.data(pluginRef); if(!plugin || !plugin[options]){ throw ' ' + options + ' '; } var result = plugin[options].apply(plugin, Array.prototype.slice.call(arguments, 1)); if(options === 'destroy'){ jqElement.removeData(pluginRef); } return result; } this.each(function () { var jqElement=$(this); var plugin = jqElement.data(pluginRef); if(plugin === undefined){ plugin=new PluginClass(this, $.extend(true, {}, options)); jqElement.data(pluginRef, plugin); } else{ plugin.updateOptions || plugin.updateOptions(options); } }); return this; }; })(jQuery); // (function($) { // // 'use strict'; // var dateTimePicker = function (element, options) { // picker.toggle = toggle; // picker.show = show; // picker.hide = hide; // picker.ignoreReadonly = function (ignoreReadonly) { // return options.ignoreReadonly; // if (typeof ignoreReadonly !== 'boolean') { // throw new TypeError('ignoreReadonly () expects a boolean parameter'); // options.ignoreReadonly = ignoreReadonly; // return picker; // picker.options = function (newOptions) { // return $.extend(true, {}, options); // if (!(newOptions instanceof Object)) { // throw new TypeError('options() options parameter should be an object'); // $.extend(true, options, newOptions); // $.each(options, function (key, value) { // if (picker[key] !== undefined) { // picker[key](value); // } else { // throw new TypeError('option ' + key + ' is not recognized!'); // return picker; // picker.date = function (newDate) { // ///<signature helpKeyword="$.fn.datetimepicker.date"> // ///<summary>Returns the component's model current date, a moment object or null if not set.</summary> // ///<returns type="Moment">date.clone()</returns> // ///</signature> // ///<signature> // ///<summary>Sets the components model current moment to it. Passing a null value unsets the components model current moment. Parsing of the newDate parameter is made using moment library with the options.format and options.useStrict components configuration.</summary> // ///<param name="newDate" locid="$.fn.datetimepicker.date_p:newDate">Takes string, Date, moment, null parameter.</param> // ///</signature> // if (unset) { // return null; // return date.clone(); // if (newDate !== null && typeof newDate !== 'string' && !moment.isMoment(newDate) && !(newDate instanceof Date)) { // throw new TypeError('date() parameter must be one of [null, string, moment or Date]'); // return picker; // picker.format = function (newFormat) { // ///<summary>test su</summary> // ///<param name="newFormat">info about para</param> // ///<returns type="string|boolean">returns foo</returns> // return options.format; // if ((typeof newFormat !== 'string') && ((typeof newFormat !== 'boolean') || (newFormat !== false))) { // throw new TypeError('format() expects a sting or boolean:false parameter ' + newFormat); // options.format = newFormat; // if (actualFormat) { // initFormatting(); // reinit formatting // return picker; // picker.timeZone = function (newZone) { // return options.timeZone; // options.timeZone = newZone; // return picker; // picker.dayViewHeaderFormat = function (newFormat) { // return options.dayViewHeaderFormat; // if (typeof newFormat !== 'string') { // throw new TypeError('dayViewHeaderFormat() expects a string parameter'); // options.dayViewHeaderFormat = newFormat; // return picker; // picker.extraFormats = function (formats) { // return options.extraFormats; // if (formats !== false && !(formats instanceof Array)) { // throw new TypeError('extraFormats() expects an array or false parameter'); // options.extraFormats = formats; // if (parseFormats) { // initFormatting(); // reinit formatting // return picker; // picker.disabledDates = function (dates) { // ///<signature helpKeyword="$.fn.datetimepicker.disabledDates"> // ///<summary>Returns an array with the currently set disabled dates on the component.</summary> // ///<returns type="array">options.disabledDates</returns> // ///</signature> // ///<signature> // ///<summary>Setting this takes precedence over options.minDate, options.maxDate configuration. Also calling this function removes the configuration of // ///options.enabledDates if such exist.</summary> // ///<param name="dates" locid="$.fn.datetimepicker.disabledDates_p:dates">Takes an [ string or Date or moment ] of values and allows the user to select only from those days.</param> // ///</signature> // return (options.disabledDates ? $.extend({}, options.disabledDates) : options.disabledDates); // if (!dates) { // options.disabledDates = false; // update(); // return picker; // if (!(dates instanceof Array)) { // throw new TypeError('disabledDates() expects an array parameter'); // options.disabledDates = indexGivenDates(dates); // options.enabledDates = false; // update(); // return picker; // picker.enabledDates = function (dates) { // ///<signature helpKeyword="$.fn.datetimepicker.enabledDates"> // ///<summary>Returns an array with the currently set enabled dates on the component.</summary> // ///<returns type="array">options.enabledDates</returns> // ///</signature> // ///<signature> // ///<summary>Setting this takes precedence over options.minDate, options.maxDate configuration. Also calling this function removes the configuration of options.disabledDates if such exist.</summary> // ///<param name="dates" locid="$.fn.datetimepicker.enabledDates_p:dates">Takes an [ string or Date or moment ] of values and allows the user to select only from those days.</param> // ///</signature> // return (options.enabledDates ? $.extend({}, options.enabledDates) : options.enabledDates); // if (!dates) { // options.enabledDates = false; // update(); // return picker; // if (!(dates instanceof Array)) { // throw new TypeError('enabledDates() expects an array parameter'); // options.enabledDates = indexGivenDates(dates); // options.disabledDates = false; // update(); // return picker; // picker.daysOfWeekDisabled = function (daysOfWeekDisabled) { // return options.daysOfWeekDisabled.splice(0); // options.daysOfWeekDisabled = false; // update(); // return picker; // if (!(daysOfWeekDisabled instanceof Array)) { // throw new TypeError('daysOfWeekDisabled() expects an array parameter'); // options.daysOfWeekDisabled = daysOfWeekDisabled.reduce(function (previousValue, currentValue) { // currentValue = parseInt(currentValue, 10); // if (currentValue > 6 || currentValue < 0 || isNaN(currentValue)) { // return previousValue; // previousValue.push(currentValue); // return previousValue; // }, []).sort(); // if (options.useCurrent && !options.keepInvalid) { // var tries = 0; // while (!isValid(date, 'd')) { // date.add(1, 'd'); // throw 'Tried 7 times to find a valid date'; // tries++; // setValue(date); // update(); // return picker; // picker.maxDate = function (maxDate) { // return options.maxDate ? options.maxDate.clone() : options.maxDate; // options.maxDate = false; // update(); // return picker; // maxDate = getMoment(); // var parsedDate = parseInputDate(maxDate); // if (!parsedDate.isValid()) { // throw new TypeError('maxDate() Could not parse date parameter: ' + maxDate); // if (options.minDate && parsedDate.isBefore(options.minDate)) { // options.maxDate = parsedDate; // if (options.useCurrent && !options.keepInvalid && date.isAfter(maxDate)) { // setValue(options.maxDate); // if (viewDate.isAfter(parsedDate)) { // viewDate = parsedDate.clone().subtract(options.stepping, 'm'); // update(); // return picker; // picker.minDate = function (minDate) { // return options.minDate ? options.minDate.clone() : options.minDate; // options.minDate = false; // update(); // return picker; // minDate = getMoment(); // var parsedDate = parseInputDate(minDate); // if (!parsedDate.isValid()) { // throw new TypeError('minDate() Could not parse date parameter: ' + minDate); // if (options.maxDate && parsedDate.isAfter(options.maxDate)) { // options.minDate = parsedDate; // if (options.useCurrent && !options.keepInvalid && date.isBefore(minDate)) { // setValue(options.minDate); // if (viewDate.isBefore(parsedDate)) { // viewDate = parsedDate.clone().add(options.stepping, 'm'); // update(); // return picker; // picker.defaultDate = function (defaultDate) { // ///<signature helpKeyword="$.fn.datetimepicker.defaultDate"> // ///<summary>Returns a moment with the options.defaultDate option configuration or false if not set</summary> // ///<returns type="Moment">date.clone()</returns> // ///</signature> // ///<signature> // ///<summary>Will set the picker's inital date. If a boolean:false value is passed the options.defaultDate parameter is cleared.</summary> // ///<param name="defaultDate" locid="$.fn.datetimepicker.defaultDate_p:defaultDate">Takes a string, Date, moment, boolean:false</param> // ///</signature> // return options.defaultDate ? options.defaultDate.clone() : options.defaultDate; // if (!defaultDate) { // options.defaultDate = false; // return picker; // defaultDate = getMoment(); // var parsedDate = parseInputDate(defaultDate); // if (!parsedDate.isValid()) { // throw new TypeError('defaultDate() Could not parse date parameter: ' + defaultDate); // if (!isValid(parsedDate)) { // throw new TypeError('defaultDate() date passed is invalid according to component setup validations'); // options.defaultDate = parsedDate; // setValue(options.defaultDate); // return picker; // picker.locale = function (locale) { // return options.locale; // if (!moment.localeData(locale)) { // throw new TypeError('locale() locale ' + locale + ' is not loaded from moment locales!'); // options.locale = locale; // date.locale(options.locale); // viewDate.locale(options.locale); // if (actualFormat) { // initFormatting(); // reinit formatting // if (widget) { // hide(); // show(); // return picker; // picker.stepping = function (stepping) { // return options.stepping; // stepping = parseInt(stepping, 10); // if (isNaN(stepping) || stepping < 1) { // stepping = 1; // options.stepping = stepping; // return picker; // picker.useCurrent = function (useCurrent) { // var useCurrentOptions = ['year', 'month', 'day', 'hour', 'minute']; // return options.useCurrent; // if ((typeof useCurrent !== 'boolean') && (typeof useCurrent !== 'string')) { // throw new TypeError('useCurrent() expects a boolean or string parameter'); // throw new TypeError('useCurrent() expects a string parameter of ' + useCurrentOptions.join(', ')); // options.useCurrent = useCurrent; // return picker; // picker.collapse = function (collapse) { // return options.collapse; // if (typeof collapse !== 'boolean') { // throw new TypeError('collapse() expects a boolean parameter'); // return picker; // options.collapse = collapse; // if (widget) { // hide(); // show(); // return picker; // picker.icons = function (icons) { // return $.extend({}, options.icons); // if (!(icons instanceof Object)) { // throw new TypeError('icons() expects parameter to be an Object'); // $.extend(options.icons, icons); // if (widget) { // hide(); // show(); // return picker; // picker.tooltips = function (tooltips) { // return $.extend({}, options.tooltips); // if (!(tooltips instanceof Object)) { // throw new TypeError('tooltips() expects parameter to be an Object'); // $.extend(options.tooltips, tooltips); // if (widget) { // hide(); // show(); // return picker; // picker.useStrict = function (useStrict) { // return options.useStrict; // if (typeof useStrict !== 'boolean') { // throw new TypeError('useStrict() expects a boolean parameter'); // options.useStrict = useStrict; // return picker; // picker.sideBySide = function (sideBySide) { // return options.sideBySide; // if (typeof sideBySide !== 'boolean') { // throw new TypeError('sideBySide() expects a boolean parameter'); // options.sideBySide = sideBySide; // if (widget) { // hide(); // show(); // return picker; // picker.viewMode = function (viewMode) { // return options.viewMode; // if (typeof viewMode !== 'string') { // throw new TypeError('viewMode() expects a string parameter'); // throw new TypeError('viewMode() parameter must be one of (' + viewModes.join(', ') + ') value'); // options.viewMode = viewMode; // currentViewMode = Math.max(viewModes.indexOf(viewMode), minViewModeNumber); // showMode(); // return picker; // picker.toolbarPlacement = function (toolbarPlacement) { // return options.toolbarPlacement; // if (typeof toolbarPlacement !== 'string') { // throw new TypeError('toolbarPlacement() expects a string parameter'); // throw new TypeError('toolbarPlacement() parameter must be one of (' + toolbarPlacements.join(', ') + ') value'); // options.toolbarPlacement = toolbarPlacement; // if (widget) { // hide(); // show(); // return picker; // picker.widgetPositioning = function (widgetPositioning) { // return $.extend({}, options.widgetPositioning); // if (({}).toString.call(widgetPositioning) !== '[object Object]') { // throw new TypeError('widgetPositioning() expects an object variable'); // if (widgetPositioning.horizontal) { // if (typeof widgetPositioning.horizontal !== 'string') { // throw new TypeError('widgetPositioning() horizontal variable must be a string'); // widgetPositioning.horizontal = widgetPositioning.horizontal.toLowerCase(); // throw new TypeError('widgetPositioning() expects horizontal parameter to be one of (' + horizontalModes.join(', ') + ')'); // options.widgetPositioning.horizontal = widgetPositioning.horizontal; // if (widgetPositioning.vertical) { // if (typeof widgetPositioning.vertical !== 'string') { // throw new TypeError('widgetPositioning() vertical variable must be a string'); // widgetPositioning.vertical = widgetPositioning.vertical.toLowerCase(); // throw new TypeError('widgetPositioning() expects vertical parameter to be one of (' + verticalModes.join(', ') + ')'); // options.widgetPositioning.vertical = widgetPositioning.vertical; // update(); // return picker; // picker.calendarWeeks = function (calendarWeeks) { // return options.calendarWeeks; // if (typeof calendarWeeks !== 'boolean') { // throw new TypeError('calendarWeeks() expects parameter to be a boolean value'); // options.calendarWeeks = calendarWeeks; // update(); // return picker; // picker.showTodayButton = function (showTodayButton) { // return options.showTodayButton; // if (typeof showTodayButton !== 'boolean') { // throw new TypeError('showTodayButton() expects a boolean parameter'); // options.showTodayButton = showTodayButton; // if (widget) { // hide(); // show(); // return picker; // picker.showClear = function (showClear) { // return options.showClear; // if (typeof showClear !== 'boolean') { // throw new TypeError('showClear() expects a boolean parameter'); // options.showClear = showClear; // if (widget) { // hide(); // show(); // return picker; // picker.widgetParent = function (widgetParent) { // return options.widgetParent; // widgetParent = $(widgetParent); // if (widgetParent !== null && (typeof widgetParent !== 'string' && !(widgetParent instanceof $))) { // throw new TypeError('widgetParent() expects a string or a jQuery object parameter'); // options.widgetParent = widgetParent; // if (widget) { // hide(); // show(); // return picker; // picker.keepOpen = function (keepOpen) { // return options.keepOpen; // if (typeof keepOpen !== 'boolean') { // throw new TypeError('keepOpen() expects a boolean parameter'); // options.keepOpen = keepOpen; // return picker; // picker.focusOnShow = function (focusOnShow) { // return options.focusOnShow; // if (typeof focusOnShow !== 'boolean') { // throw new TypeError('focusOnShow() expects a boolean parameter'); // options.focusOnShow = focusOnShow; // return picker; // picker.inline = function (inline) { // return options.inline; // if (typeof inline !== 'boolean') { // throw new TypeError('inline() expects a boolean parameter'); // options.inline = inline; // return picker; // picker.clear = function () { // clear(); // return picker; // picker.keyBinds = function (keyBinds) { // options.keyBinds = keyBinds; // return picker; // picker.getMoment = function (d) { // return this.getMoment(d); // picker.debug = function (debug) { // if (typeof debug !== 'boolean') { // throw new TypeError('debug() expects a boolean parameter'); // options.debug = debug; // return picker; // picker.allowInputToggle = function (allowInputToggle) { // return options.allowInputToggle; // if (typeof allowInputToggle !== 'boolean') { // throw new TypeError('allowInputToggle() expects a boolean parameter'); // options.allowInputToggle = allowInputToggle; // return picker; // picker.showClose = function (showClose) { // return options.showClose; // if (typeof showClose !== 'boolean') { // throw new TypeError('showClose() expects a boolean parameter'); // options.showClose = showClose; // return picker; // picker.keepInvalid = function (keepInvalid) { // return options.keepInvalid; // if (typeof keepInvalid !== 'boolean') { // throw new TypeError('keepInvalid() expects a boolean parameter'); // options.keepInvalid = keepInvalid; // return picker; // picker.datepickerInput = function (datepickerInput) { // return options.datepickerInput; // if (typeof datepickerInput !== 'string') { // throw new TypeError('datepickerInput() expects a string parameter'); // options.datepickerInput = datepickerInput; // return picker; // picker.parseInputDate = function (parseInputDate) { // return options.parseInputDate; // if (typeof parseInputDate !== 'function') { // throw new TypeError('parseInputDate() sholud be as function'); // options.parseInputDate = parseInputDate; // return picker; // picker.<API key> = function (<API key>) { // ///<signature helpKeyword="$.fn.datetimepicker.<API key>"> // ///<summary>Returns an array with the currently set disabled dates on the component.</summary> // ///<returns type="array">options.<API key></returns> // ///</signature> // ///<signature> // ///<summary>Setting this takes precedence over options.minDate, options.maxDate configuration. Also calling this function removes the configuration of // ///options.enabledDates if such exist.</summary> // ///<param name="dates" locid="$.fn.datetimepicker.<API key>:dates">Takes an [ string or Date or moment ] of values and allows the user to select only from those days.</param> // ///</signature> // return (options.<API key> ? $.extend({}, options.<API key>) : options.<API key>); // if (!<API key>) { // options.<API key> = false; // update(); // return picker; // if (!(<API key> instanceof Array)) { // throw new TypeError('<API key>() expects an array parameter'); // options.<API key> = <API key>; // update(); // return picker; // picker.disabledHours = function (hours) { // ///<signature helpKeyword="$.fn.datetimepicker.disabledHours"> // ///<summary>Returns an array with the currently set disabled hours on the component.</summary> // ///<returns type="array">options.disabledHours</returns> // ///</signature> // ///<signature> // ///<summary>Setting this takes precedence over options.minDate, options.maxDate configuration. Also calling this function removes the configuration of // ///options.enabledHours if such exist.</summary> // ///<param name="hours" locid="$.fn.datetimepicker.disabledHours_p:hours">Takes an [ int ] of values and disallows the user to select only from those hours.</param> // ///</signature> // return (options.disabledHours ? $.extend({}, options.disabledHours) : options.disabledHours); // if (!hours) { // options.disabledHours = false; // update(); // return picker; // if (!(hours instanceof Array)) { // throw new TypeError('disabledHours() expects an array parameter'); // options.disabledHours = indexGivenHours(hours); // options.enabledHours = false; // if (options.useCurrent && !options.keepInvalid) { // var tries = 0; // while (!isValid(date, 'h')) { // date.add(1, 'h'); // throw 'Tried 24 times to find a valid date'; // tries++; // setValue(date); // update(); // return picker; // picker.enabledHours = function (hours) { // ///<signature helpKeyword="$.fn.datetimepicker.enabledHours"> // ///<summary>Returns an array with the currently set enabled hours on the component.</summary> // ///<returns type="array">options.enabledHours</returns> // ///</signature> // ///<signature> // ///<summary>Setting this takes precedence over options.minDate, options.maxDate configuration. Also calling this function removes the configuration of options.disabledHours if such exist.</summary> // ///<param name="hours" locid="$.fn.datetimepicker.enabledHours_p:hours">Takes an [ int ] of values and allows the user to select only from those hours.</param> // ///</signature> // return (options.enabledHours ? $.extend({}, options.enabledHours) : options.enabledHours); // if (!hours) { // options.enabledHours = false; // update(); // return picker; // if (!(hours instanceof Array)) { // throw new TypeError('enabledHours() expects an array parameter'); // options.enabledHours = indexGivenHours(hours); // options.disabledHours = false; // if (options.useCurrent && !options.keepInvalid) { // var tries = 0; // while (!isValid(date, 'h')) { // date.add(1, 'h'); // throw 'Tried 24 times to find a valid date'; // tries++; // setValue(date); // update(); // return picker; // picker.viewDate = function (newDate) { // ///<signature helpKeyword="$.fn.datetimepicker.viewDate"> // ///<summary>Returns the component's model current viewDate, a moment object or null if not set.</summary> // ///<returns type="Moment">viewDate.clone()</returns> // ///</signature> // ///<signature> // ///<summary>Sets the components model current moment to it. Passing a null value unsets the components model current moment. Parsing of the newDate parameter is made using moment library with the options.format and options.useStrict components configuration.</summary> // ///<param name="newDate" locid="$.fn.datetimepicker.date_p:newDate">Takes string, viewDate, moment, null parameter.</param> // ///</signature> // return viewDate.clone(); // if (!newDate) { // viewDate = date.clone(); // return picker; // if (typeof newDate !== 'string' && !moment.isMoment(newDate) && !(newDate instanceof Date)) { // throw new TypeError('viewDate() parameter must be one of [string, moment or Date]'); // viewDate = parseInputDate(newDate); // viewUpdate(); // return picker; // })(jQuery);
using <API key>; using RippleDictionary; using RippleScreenApp.Utilities; using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.IO; using System.Linq; using System.Reflection; using System.Speech.Synthesis; using System.Text; using System.Threading.Tasks; using System.Windows; using System.Windows.Controls; using System.Windows.Data; using System.Windows.Documents; using System.Windows.Input; using System.Windows.Media; using System.Windows.Media.Imaging; using System.Windows.Navigation; using System.Windows.Shapes; namespace RippleScreenApp { <summary> Interaction logic for MainWindow.xaml </summary> public partial class ScreenWindow : Window { internal static RippleDictionary.Ripple rippleData; private static TextBlock tbElement = new TextBlock(); private static TextBlock fullScreenTbElement = new TextBlock(); private static Image imgElement = new Image(); private static Image <API key> = new Image(); private static String currentVideoURI = String.Empty; private static RippleDictionary.ContentType <API key> = ContentType.Nothing; private static bool loopVideo = false; private BackgroundWorker myBackgroundWorker; private BackgroundWorker pptWorker; Utilities.ScriptingHelper helper; public System.Windows.Forms.Integration.WindowsFormsHost host; public System.Windows.Forms.WebBrowser browserElement; internal static String personName; private long prevRow; private Tile currentTile = null; private bool StartVideoPlayed = false; public static String sessionGuid = String.Empty; public ScreenWindow() { try { InitializeComponent(); LoadData(); SetObjectProperties(); //Start receiving messages Utilities.MessageReceiver.<API key>(this); } catch (Exception ex) { //Exit and do nothing <API key>.LoggingHelper.LogTrace(1, "Went wrong in Screen {0}", ex.Message); } } private void Window_Loaded(object sender, RoutedEventArgs e) { try { this.WindowState = System.Windows.WindowState.Maximized; ResetUI(); } catch (Exception ex) { <API key>.LoggingHelper.LogTrace(1, "Went wrong in Window Loaded {0}", ex.Message); } } private void SetObjectProperties() { //Initialize video properties this.IntroVideoControl.Source = new Uri(Helper.GetAssetURI(rippleData.Screen.ScreenContents["IntroVideo"].Content)); this.IntroVideoControl.ScrubbingEnabled = true; //Set image elements properties imgElement.Stretch = Stretch.Fill; <API key>.Stretch = Stretch.Fill; //Set text block properties tbElement.FontSize = 50; tbElement.Margin = new Thickness(120, 120, 120, 0); tbElement.TextWrapping = TextWrapping.Wrap; fullScreenTbElement.FontSize = 50; fullScreenTbElement.Margin = new Thickness(120, 120, 120, 0); fullScreenTbElement.TextWrapping = TextWrapping.Wrap; } <summary> Method that loads the configured data for the Screen, right now the Source is XML </summary> private void LoadData() { try { //Loads the local dictionary data from the configuration XML rippleData = RippleDictionary.Dictionary.GetRipple(System.IO.Path.GetDirectoryName(System.Reflection.Assembly.GetEntryAssembly().Location)); } catch (Exception ex) { <API key>.LoggingHelper.LogTrace(1, "Went wrong in Load Data for Screen {0}", ex.Message); throw; } } <summary> Resets the UI to System locked mode. </summary> private void ResetUI() { try { Globals.ResetGlobals(); currentVideoURI = String.Empty; <API key> = ContentType.Nothing; loopVideo = false; StartVideoPlayed = false; sessionGuid = String.Empty; //Pick up content based on the "LockScreen" ID ProjectContent(rippleData.Screen.ScreenContents["LockScreen"]); //Commit the telemetry data Utilities.TelemetryWriter.<API key>(); } catch (Exception ex) { //Do nothing <API key>.LoggingHelper.LogTrace(1, "Went wrong in Reset UI for Screen {0}", ex.Message); } } <summary> Code will receive messages from the floor Invoke appropriate content projection based on the tile ID passed </summary> <param name="val"></param> public void OnMessageReceived(string val) { try { //Check for reset if (val.Equals("Reset")) { //Update the previous entry Utilities.TelemetryWriter.UpdatePreviousEntry(); //Reset the system ResetUI(); } //Check for System start //Check for System start else if (val.StartsWith("System Start")) { //Load the telemetry Data Utilities.TelemetryWriter.<API key>(); //The floor has asked the screen to start the system //Get the User Name Globals.UserName = val.Split(':')[1]; //Get the person identity for the session personName = String.IsNullOrEmpty(Globals.UserName) ? Convert.ToString(Guid.NewGuid()) : Globals.UserName; Utilities.TelemetryWriter.AddTelemetryRow(rippleData.Floor.SetupID, personName, "Unlock", val, "Unlock"); //Set the system state Globals.currentAppState = RippleSystemStates.UserDetected; //Play the Intro Content ProjectIntroContent(rippleData.Screen.ScreenContents["IntroVideo"]); } //Check for gestures else if (val.StartsWith("Gesture")) { OnGestureInput(val.Split(':')[1]); } //Check for HTMl messages else if (val.StartsWith("HTML")) { <API key>(val.Split(':')[1]); } //Check for options- TODO need to figure out else if (val.StartsWith("Option")) { //Do nothing } //Check if a content - tile mapping or in general content tag exists else { if (rippleData.Screen.ScreenContents.ContainsKey(val) && rippleData.Screen.ScreenContents[val].Type != ContentType.Nothing) { //Set the system state Globals.currentAppState = RippleSystemStates.OptionSelected; ProjectContent(rippleData.Screen.ScreenContents[val]); <API key>.LoggingHelper.LogTrace(1, "In Message Received {0} {1}:{2}", Utilities.TelemetryWriter.telemetryData.Tables[0].Rows.Count, Utilities.TelemetryWriter.telemetryData.Tables[0].Rows[Utilities.TelemetryWriter.telemetryData.Tables[0].Rows.Count - 1].ItemArray[6], DateTime.Now); //Update the end time for the previous Utilities.TelemetryWriter.UpdatePreviousEntry(); //Insert the new entry Utilities.TelemetryWriter.AddTelemetryRow(rippleData.Floor.SetupID, personName, ((currentTile = GetFloorTileForID(val))==null)?"Unknown":currentTile.Name, val, (val == "Tile0") ? "Start" : "Option"); } else { //Stop any existing projections <API key>.HelperMethods.StopPresentation(); <API key>.Children.Clear(); ContentGrid.Children.Clear(); //Set focus for screen window also Utilities.Helper.<API key>(); //Stop any existing videos loopVideo = false; VideoControl.Source = null; <API key>.Source = null; //Clean the images <API key>.Source = null; imgElement.Source = null; //Clear the header text TitleLabel.Text = ""; //Dispose the objects if(browserElement != null) browserElement.Dispose(); browserElement = null; if (host != null) host.Dispose(); host = null; if (helper != null) helper.PropertyChanged -= <API key>; helper = null; <API key> = ContentType.Nothing; ShowText("No content available for this option, Please try some other tile option", "No Content"); } } } catch (Exception ex) { //Do nothing <API key>.LoggingHelper.LogTrace(1, "Went wrong in On message received for Screen {0}", ex.Message); } } private void <API key>(string p) { try { if(p.StartsWith("SessionID,")) { sessionGuid = p; return; } if (helper != null && <API key> == ContentType.HTML) { helper.MessageReceived(p); } } catch (Exception ex) { //Do nothing <API key>.LoggingHelper.LogTrace(1, "Went wrong in <API key> received for Screen {0}", ex.Message); } } private void OnGestureInput(string inputGesture) { try { //PPT Mode - left and right swipe if (inputGesture == GestureTypes.LeftSwipe.ToString() && <API key> == ContentType.PPT) { //Acts as previous <API key>.HelperMethods.GotoPrevious(); } else if (inputGesture == GestureTypes.RightSwipe.ToString() && <API key> == ContentType.PPT) { //Check again, Means the presentation ended on clicking next if (!<API key>.HelperMethods.<API key>()) { //Change the screen //ShowText("Your presentation has ended, Select some other option", "Select some other option"); ShowImage(@"\Assets\Images\pptend.png", "Presentation Ended"); //Set focus for screen window also Utilities.Helper.<API key>(); } //Acts as next <API key>.HelperMethods.GotoNext(); //Check again, Means the presentation ended on clicking next if (!<API key>.HelperMethods.<API key>()) { //Change the screen text //ShowText("Your presentation has ended, Select some other option", "Select some other option"); ShowImage(@"\Assets\Images\pptend.png", "Presentation Ended"); //Set focus for screen window also Utilities.Helper.<API key>(); } } //Browser mode else if (<API key> == ContentType.HTML) { <API key>(inputGesture.ToString()); } //Set focus for screen window also //Utilities.Helper.<API key>(); } catch (Exception ex) { //Do nothing <API key>.LoggingHelper.LogTrace(1, "Went wrong in OnGestureInput received for Screen {0}", ex.Message); } } #region Content Projection methods <summary> Identifies the content type and project accordingly </summary> <param name="screenContent"></param> private void ProjectContent(RippleDictionary.ScreenContent screenContent) { try { if (screenContent.Type == ContentType.HTMLMessage) { if (helper != null && <API key> == ContentType.HTML) { helper.MessageReceived(screenContent.Content); return; } } //Stop any existing projections <API key>.HelperMethods.StopPresentation(); <API key>.Children.Clear(); ContentGrid.Children.Clear(); //Set focus for screen window also Utilities.Helper.<API key>(); //Stop any existing videos loopVideo = false; VideoControl.Source = null; <API key>.Source = null; //Clean the images <API key>.Source = null; imgElement.Source = null; //Clear the header text TitleLabel.Text = ""; //Dispose the objects if (browserElement != null) browserElement.Dispose(); browserElement = null; if (host != null) host.Dispose(); host = null; if (helper != null) helper.PropertyChanged -= <API key>; helper = null; <API key> = screenContent.Type; if (screenContent.Id == "Tile0" && StartVideoPlayed) { <API key> = ContentType.Image; ShowImage("\\Assets\\Images\\default_start.png", screenContent.Header); return; } switch (screenContent.Type) { case RippleDictionary.ContentType.HTML: ShowBrowser(screenContent.Content, screenContent.Header); break; case RippleDictionary.ContentType.Image: ShowImage(screenContent.Content, screenContent.Header); break; case RippleDictionary.ContentType.PPT: ShowPPT(screenContent.Content, screenContent.Header); break; case RippleDictionary.ContentType.Text: ShowText(screenContent.Content, screenContent.Header); break; case RippleDictionary.ContentType.Video: loopVideo = (screenContent.LoopVideo == null) ? false : Convert.ToBoolean(screenContent.LoopVideo); if (screenContent.Id == "Tile0") StartVideoPlayed = true; ShowVideo(screenContent.Content, screenContent.Header); break; } } catch (Exception ex) { <API key>.LoggingHelper.LogTrace(1, "Went wrong in ProjectContent Method for screen {0}", ex.Message); } } private void ProjectIntroContent(RippleDictionary.ScreenContent screenContent) { try { //Dispose the previous content //Stop any existing projections <API key>.HelperMethods.StopPresentation(); <API key>.Children.Clear(); ContentGrid.Children.Clear(); //Set focus for screen window also Utilities.Helper.<API key>(); //Stop any existing videos loopVideo = false; VideoControl.Source = null; <API key>.Source = null; //Clean the images <API key>.Source = null; imgElement.Source = null; //Clear the header text TitleLabel.Text = ""; if (browserElement != null) browserElement.Dispose(); browserElement = null; if (host != null) host.Dispose(); host = null; if (helper != null) helper.PropertyChanged -= <API key>; helper = null; //Play the Intro video this.TitleLabel.Text = ""; ContentGrid.Visibility = Visibility.Collapsed; <API key>.Visibility = Visibility.Collapsed; FullScreenVideoGrid.Visibility = Visibility.Collapsed; IntroVideoControl.Visibility = Visibility.Visible; VideoControl.Visibility = Visibility.Collapsed; VideoGrid.Visibility = Visibility.Visible; IntroVideoControl.Play(); this.UpdateLayout(); myBackgroundWorker = new BackgroundWorker(); myBackgroundWorker.DoWork += <API key>; myBackgroundWorker.RunWorkerCompleted += <API key>; myBackgroundWorker.RunWorkerAsync(rippleData.Floor.Start.<API key>); } catch (Exception ex) { <API key>.LoggingHelper.LogTrace(1, "Went wrong in ProjectIntroContent Method for screen {0}", ex.Message); } } private void <API key>(object sender, <API key> e) { //System has been started, it just finished playing the intro video if (Globals.currentAppState == RippleSystemStates.UserDetected) { this.IntroVideoControl.Stop(); //this.IntroVideoControl.Source = null; this.IntroVideoControl.Visibility = System.Windows.Visibility.Collapsed; <API key>(); } } private void <API key>(object sender, DoWorkEventArgs e) { System.Threading.Thread.Sleep(Convert.ToInt16(e.Argument) * 1000); } <summary> Code to project a video If the Header value is not provided, the content is projected in full screen mode </summary> <param name="Content"></param> <param name="header"></param> private void ShowVideo(String Content, String header) { try { //Check if header is null //Null - Show full screen content if (String.IsNullOrEmpty(header)) { //Show the full screen video control currentVideoURI = Helper.GetAssetURI(Content); <API key>.Source = new Uri(currentVideoURI); <API key>.Visibility = Visibility.Collapsed; FullScreenVideoGrid.Visibility = Visibility.Visible; <API key>.Play(); } else { TitleLabel.Text = header; currentVideoURI = Helper.GetAssetURI(Content); VideoControl.Source = new Uri(currentVideoURI); ContentGrid.Visibility = Visibility.Collapsed; <API key>.Visibility = Visibility.Collapsed; FullScreenVideoGrid.Visibility = Visibility.Collapsed; VideoControl.Visibility = Visibility.Visible; VideoGrid.Visibility = Visibility.Visible; VideoControl.Play(); } this.UpdateLayout(); } catch (Exception ex) { <API key>.LoggingHelper.LogTrace(1, "Went wrong in Show Video method {0}", ex.Message); } } <summary> Code to display text If the Header value is not provided, the content is projected in full screen mode </summary> <param name="Content"></param> <param name="header"></param> private void ShowText(String Content, String header) { try { //Check if header is null //Null - Show full screen content if (String.IsNullOrEmpty(header)) { //Show the full screen control with text fullScreenTbElement.Text = Content; <API key>.Children.Clear(); <API key>.Children.Add(fullScreenTbElement); <API key>.Visibility = Visibility.Visible; FullScreenVideoGrid.Visibility = Visibility.Collapsed; } else { TitleLabel.Text = header; tbElement.Text = Content; ContentGrid.Children.Clear(); ContentGrid.Children.Add(tbElement); ContentGrid.Visibility = Visibility.Visible; <API key>.Visibility = Visibility.Collapsed; FullScreenVideoGrid.Visibility = Visibility.Collapsed; VideoGrid.Visibility = Visibility.Collapsed; } this.UpdateLayout(); } catch (Exception ex) { <API key>.LoggingHelper.LogTrace(1, "Went wrong in Show Text method {0}", ex.Message); } } <summary> Code to project a PPT If the Header value is not provided, the content is projected in full screen mode </summary> <param name="Content"></param> <param name="header"></param> private void ShowPPT(String Content, String header) { try { //Check if header is null //Null - Show full screen content if (String.IsNullOrEmpty(header)) { //Show the full screen video control <API key>.Visibility = Visibility.Visible; FullScreenVideoGrid.Visibility = Visibility.Collapsed; } else { TitleLabel.Text = header; ContentGrid.Visibility = Visibility.Visible; <API key>.Visibility = Visibility.Collapsed; FullScreenVideoGrid.Visibility = Visibility.Collapsed; VideoGrid.Visibility = Visibility.Collapsed; } this.UpdateLayout(); <API key>.HelperMethods.StartPresentation(Helper.GetAssetURI(Content)); //ShowText("Please wait while we load your presentation", header); //ShowImage(@"\Assets\Images\loading.png", header); //this.UpdateLayout(); //pptWorker = new BackgroundWorker(); //pptWorker.DoWork += pptWorker_DoWork; //pptWorker.RunWorkerAsync(Content); } catch (Exception ex) { <API key>.LoggingHelper.LogTrace(1, "Went wrong in Show PPT method {0}", ex.Message); } } void pptWorker_DoWork(object sender, DoWorkEventArgs e) { <API key>.HelperMethods.StartPresentation(Helper.GetAssetURI(e.Argument.ToString())); } <summary> Code to project an image If the Header value is not provided, the content is projected in full screen mode </summary> <param name="Content"></param> <param name="header"></param> private void ShowImage(String Content, String header) { try { //Check if header is null //Null - Show full screen content if (String.IsNullOrEmpty(header)) { //Show the full screen control with text <API key>.Source = new BitmapImage(new Uri(Helper.GetAssetURI(Content))); <API key>.Children.Clear(); <API key>.Children.Add(<API key>); <API key>.Visibility = Visibility.Visible; FullScreenVideoGrid.Visibility = Visibility.Collapsed; } else { TitleLabel.Text = header; imgElement.Source = new BitmapImage(new Uri(Helper.GetAssetURI(Content))); ContentGrid.Children.Clear(); ContentGrid.Children.Add(imgElement); ContentGrid.Visibility = Visibility.Visible; <API key>.Visibility = Visibility.Collapsed; FullScreenVideoGrid.Visibility = Visibility.Collapsed; VideoGrid.Visibility = Visibility.Collapsed; } this.UpdateLayout(); } catch (Exception ex) { <API key>.LoggingHelper.LogTrace(1, "Went wrong in Show Image {0}", ex.Message); } } <summary> Code to show browser based content, applicable for URL's If the Header value is not provided, the content is projected in full screen mode </summary> <param name="Content"></param> <param name="header"></param> private void ShowBrowser(String Content, String header) { try { //Check if header is null //Null - Show full screen content if (String.IsNullOrEmpty(header)) { //Show the full screen video control //Display HTML content host = new System.Windows.Forms.Integration.WindowsFormsHost(); browserElement = new System.Windows.Forms.WebBrowser(); browserElement.<API key> = true; helper = new Utilities.ScriptingHelper(this); browserElement.ObjectForScripting = helper; host.Child = browserElement; helper.PropertyChanged += <API key>; <API key>.Children.Clear(); <API key>.Children.Add(host); <API key>.Visibility = Visibility.Visible; FullScreenVideoGrid.Visibility = Visibility.Collapsed; } else { TitleLabel.Text = header; host = new System.Windows.Forms.Integration.WindowsFormsHost(); browserElement = new System.Windows.Forms.WebBrowser(); browserElement.<API key> = true; helper = new Utilities.ScriptingHelper(this); host.Child = browserElement; browserElement.ObjectForScripting = helper; helper.PropertyChanged += <API key>; ContentGrid.Children.Clear(); ContentGrid.Children.Add(host); ContentGrid.Visibility = Visibility.Visible; <API key>.Visibility = Visibility.Collapsed; FullScreenVideoGrid.Visibility = Visibility.Collapsed; VideoGrid.Visibility = Visibility.Collapsed; } String fileLocation = Helper.GetAssetURI(Content); String pageUri = String.Empty; //Local file if (File.Exists(fileLocation)) { String[] PathParts = fileLocation.Split(new char[] { ':' }); pageUri = "file://127.0.0.1/" + PathParts[0] + "$" + PathParts[1]; } //Web hosted file else { pageUri = Content; } browserElement.Navigate(pageUri); this.UpdateLayout(); } catch (Exception ex) { <API key>.LoggingHelper.LogTrace(1, "Went wrong in Show Browser {0}", ex.Message); } } #endregion #region Helpers private Tile GetFloorTileForID(string TileID) { Tile reqdTile = null; try { reqdTile = rippleData.Floor.Tiles[TileID]; } catch (Exception) { try { reqdTile = rippleData.Floor.Tiles[TileID.Substring(0, TileID.LastIndexOf("SubTile"))].SubTiles[TileID]; } catch (Exception) { return null; } } return reqdTile; } #endregion private void <API key>(object sender, RoutedEventArgs e) { if (<API key> == ContentType.Video && loopVideo && (!String.IsNullOrEmpty(currentVideoURI))) { //Replay the video VideoControl.Source = new Uri(currentVideoURI); VideoControl.Play(); } } private void <API key>(object sender, RoutedEventArgs e) { if (<API key> == ContentType.Video && loopVideo && (!String.IsNullOrEmpty(currentVideoURI))) { //Replay the video <API key>.Source = new Uri(currentVideoURI); <API key>.Play(); } } private void <API key>() { //Set the system state Globals.currentAppState = RippleSystemStates.UserWaitToGoOnStart; ProjectContent(rippleData.Screen.ScreenContents["GotoStart"]); } private void <API key>(object sender, RoutedEventArgs e) { //System has been started, it just finished playing the intro video //if (Globals.currentAppState == RippleSystemStates.UserDetected) // this.IntroVideoControl.Stop(); // <API key>(); } private void Window_Closing_1(object sender, CancelEventArgs e) { <API key>.LoggingHelper.StopLogging(); } //Handles messages sent by HTML animations void <API key>(object sender, <API key> e) { try { var scriptingHelper = sender as Utilities.ScriptingHelper; if (scriptingHelper != null) { if (e.PropertyName == "SendMessage") { if ((!String.IsNullOrEmpty(scriptingHelper.SendMessage)) && <API key> == ContentType.HTML) { //Send the screen a message for HTML parameter passing Utilities.MessageReceiver.SendMessage("HTML:" + scriptingHelper.SendMessage); } } } } catch (Exception ex) { <API key>.LoggingHelper.LogTrace(1, "Went wrong in helper property changed event {0}", ex.Message); } } } }
# Note that this is not a valid measurement of tail latency. This uses the execution times we measure because they're convenient, but this does not include queueing time inside BitFunnel nor does it include head-of-line blocking queue waiting time on the queue into BitFunnel. import csv filename = "/tmp/<API key>.csv" times = [] with open(filename) as f: reader = csv.reader(f) header = next(reader) assert header == ['query', 'rows', 'matches', 'quadwords', 'cachelines', 'parse', 'plan', 'match'] for row in reader: total_time = float(row[-1]) + float(row[-2]) + float(row[-3]) times.append(total_time) times.sort(reverse=True) idx_max = len(times) - 1 idx = [round(idx_max / 2), round(idx_max / 10), round(idx_max / 100), round(idx_max / 1000), 0] tails = [times[x] for x in idx] print(tails)
const assert = require('assert'); const md5 = require('blueimp-md5'); const createApp = require('../../lib'); describe('tokenize service', () => { it('tokenizes and stems', () => { const app = createApp(); const text = `what's the weather in vancouver`; const hash = md5(text); return app.service('tokenize').create({ text }).then(data => { assert.equal(data._id, hash, 'id is MD5 hash of the string'); assert.deepEqual(data, { _id: '<API key>', text: 'what\'s the weather in vancouver', tokens: [ 'what', 's', 'the', 'weather', 'in', 'vancouver' ], stems: [ 'what', 's', 'the', 'weather', 'in', 'vancouv' ] }); }); }); });
// AForge Kinect Video Library // AForge.NET framework // contacts@aforgenet.com namespace AForge.Video.Kinect { using System; using System.Collections.Generic; using System.Drawing; using System.Drawing.Imaging; using System.Runtime.InteropServices; using AForge; using AForge.Imaging; using AForge.Video; <summary> Enumeration of video camera modes for the <see cref="KinectVideoCamera"/>. </summary> public enum VideoCameraMode { <summary> 24 bit per pixel RGB mode. </summary> Color, <summary> 8 bit per pixel Bayer mode. </summary> Bayer, <summary> 8 bit per pixel Infra Red mode. </summary> InfraRed } <summary> Video source for Microsoft Kinect's video camera. </summary> <remarks><para>The video source captures video data from Microsoft <a href="http://en.wikipedia.org/wiki/Kinect">Kinect</a> video camera, which is aimed originally as a gaming device for XBox 360 platform.</para> <para><note>Prior to using the class, make sure you've installed Kinect's drivers as described on <a href="http://openkinect.org/wiki/Getting_Started#Windows">Open Kinect</a> project's page.</note></para> <para><note>In order to run correctly the class requires <i>freenect.dll</i> library to be put into solution's output folder. This can be found within the AForge.NET framework's distribution in Externals folder.</note></para> <para>Sample usage:</para> <code> // create video source KinectVideoCamera videoSource = new KinectVideoCamera( 0 ); // set NewFrame event handler videoSource.NewFrame += new <API key>( video_NewFrame ); // start the video source videoSource.Start( ); private void video_NewFrame( object sender, NewFrameEventArgs eventArgs ) { // get new frame Bitmap bitmap = eventArgs.Frame; // process the frame } </code> </remarks> public class KinectVideoCamera : IVideoSource { // Kinect's device ID private int deviceID; // received frames count private int framesReceived; // recieved byte count private long bytesReceived; // camera mode private VideoCameraMode cameraMode = VideoCameraMode.Color; // camera resolution to set private CameraResolution resolution = CameraResolution.Medium; // list of currently running cameras private static List<int> runningCameras = new List<int>( ); // dummy object to lock for synchronization private object sync = new object( ); <summary> New frame event. </summary> <remarks><para>Notifies clients about new available frames from the video source.</para> <para><note>Since video source may have multiple clients, each client is responsible for making a copy (cloning) of the passed video frame, because the video source disposes its own original copy after notifying of clients.</note></para> </remarks> public event <API key> NewFrame; <summary> Video source error event. </summary> <remarks>This event is used to notify clients about any type of errors occurred in video source object, for example internal exceptions.</remarks> public event <API key> VideoSourceError; <summary> Video playing finished event. </summary> <remarks><para>This event is used to notify clients that the video playing has finished.</para> </remarks> public event <API key> PlayingFinished; <summary> Specifies video mode for the camera. </summary> <remarks> <para><note>The property must be set before running the video source to take effect.</note></para> <para>Default value of the property is set to <see cref="VideoCameraMode.Color"/>.</para> </remarks> public VideoCameraMode CameraMode { get { return cameraMode; } set { cameraMode = value; } } <summary> Resolution of video camera to set. </summary> <remarks><para><note>The property must be set before running the video source to take effect.</note></para> <para>Default value of the property is set to <see cref="CameraResolution.Medium"/>.</para> </remarks> public CameraResolution Resolution { get { return resolution; } set { resolution = value; } } <summary> A string identifying the video source. </summary> public virtual string Source { get { return "Kinect:VideoCamera:" + deviceID; } } <summary> State of the video source. </summary> <remarks>Current state of video source object - running or not.</remarks> public bool IsRunning { get { lock ( sync ) { return ( device != null ); } } } <summary> Received bytes count. </summary> <remarks>Number of bytes the video source provided from the moment of the last access to the property. </remarks> public long BytesReceived { get { long bytes = bytesReceived; bytesReceived = 0; return bytes; } } <summary> Received frames count. </summary> <remarks>Number of frames the video source provided from the moment of the last access to the property. </remarks> public int FramesReceived { get { int frames = framesReceived; framesReceived = 0; return frames; } } <summary> Initializes a new instance of the <see cref="KinectVideoCamera"/> class. </summary> <param name="deviceID">Kinect's device ID (index) to connect to.</param> public KinectVideoCamera( int deviceID ) { this.deviceID = deviceID; } <summary> Initializes a new instance of the <see cref="KinectVideoCamera"/> class. </summary> <param name="deviceID">Kinect's device ID (index) to connect to.</param> <param name="resolution">Resolution of video camera to set.</param> public KinectVideoCamera( int deviceID, CameraResolution resolution ) { this.deviceID = deviceID; this.resolution = resolution; } <summary> Initializes a new instance of the <see cref="KinectVideoCamera"/> class. </summary> <param name="deviceID">Kinect's device ID (index) to connect to.</param> <param name="resolution">Resolution of video camera to set.</param> <param name="cameraMode">Sets video camera mode.</param> public KinectVideoCamera( int deviceID, CameraResolution resolution, VideoCameraMode cameraMode ) { this.deviceID = deviceID; this.resolution = resolution; this.cameraMode = cameraMode; } private Kinect device = null; private IntPtr imageBuffer = IntPtr.Zero; private KinectNative.BitmapInfoHeader videoModeInfo; <summary> Start video source. </summary> <remarks>Starts video source and returns execution to caller. Video camera will be started and will provide new video frames through the <see cref="NewFrame"/> event.</remarks> <exception cref="ArgumentException">The specified resolution is not supported for the selected mode of the Kinect video camera.</exception> <exception cref="<API key>">Could not connect to Kinect's video camera.</exception> <exception cref="DeviceBusyException">Another connection to the specified video camera is already running.</exception> public void Start( ) { lock ( sync ) { lock ( runningCameras ) { if ( device == null ) { bool success = false; try { if ( runningCameras.Contains( deviceID ) ) { throw new DeviceBusyException( "Another connection to the specified video camera is already running." ); } // get Kinect device device = Kinect.GetDevice( deviceID ); KinectNative.VideoCameraFormat dataFormat = KinectNative.VideoCameraFormat.RGB; if ( cameraMode == VideoCameraMode.Bayer ) { dataFormat = KinectNative.VideoCameraFormat.Bayer; } else if ( cameraMode == VideoCameraMode.InfraRed ) { dataFormat = KinectNative.VideoCameraFormat.IR8Bit; } // find video format parameters videoModeInfo = KinectNative.<API key>( resolution, dataFormat ); if ( videoModeInfo.IsValid == 0 ) { throw new ArgumentException( "The specified resolution is not supported for the selected mode of the Kinect video camera." ); } // set video format if ( KinectNative.<API key>( device.RawDevice, videoModeInfo ) != 0 ) { throw new VideoException( "Could not switch to the specified video format." ); } // allocate video buffer and provide it freenect imageBuffer = Marshal.AllocHGlobal( (int) videoModeInfo.Bytes ); KinectNative.<API key>( device.RawDevice, imageBuffer ); // set video callback videoCallback = new KinectNative.<API key>( HandleDataReceived ); KinectNative.<API key>( device.RawDevice, videoCallback ); // start the camera if ( KinectNative.<API key>( device.RawDevice ) != 0 ) { throw new <API key>( "Could not start video stream." ); } success = true; runningCameras.Add( deviceID ); device.AddFailureHandler( deviceID, Stop ); } finally { if ( !success ) { if ( device != null ) { device.Dispose( ); device = null; } if ( imageBuffer != IntPtr.Zero ) { Marshal.FreeHGlobal( imageBuffer ); imageBuffer = IntPtr.Zero; } } } } } } } <summary> Signal video source to stop its work. </summary> <remarks><para><note>Calling this method is equivalent to calling <see cref="Stop"/> for Kinect video camera.</note></para></remarks> public void SignalToStop( ) { Stop( ); } <summary> Wait for video source has stopped. </summary> <remarks><para><note>Calling this method is equivalent to calling <see cref="Stop"/> for Kinect video camera.</note></para></remarks> public void WaitForStop( ) { Stop( ); } <summary> Stop video source. </summary> <remarks><para>The method stops the video source, so it no longer provides new video frames and does not consume any resources.</para> </remarks> public void Stop( ) { lock ( sync ) { lock ( runningCameras ) { if ( device != null ) { bool deviceFailed = device.IsDeviceFailed( deviceID ); if ( !deviceFailed ) { KinectNative.freenect_stop_video( device.RawDevice ); } device.Dispose( ); device = null; runningCameras.Remove( deviceID ); if ( PlayingFinished != null ) { PlayingFinished( this, ( !deviceFailed ) ? <API key>.StoppedByUser : <API key>.DeviceLost ); } } if ( imageBuffer != IntPtr.Zero ) { Marshal.FreeHGlobal( imageBuffer ); imageBuffer = IntPtr.Zero; } videoCallback = null; } } } // New video data event handler private KinectNative.<API key> videoCallback = null; private void HandleDataReceived( IntPtr device, IntPtr imageData, UInt32 timeStamp ) { int width = videoModeInfo.Width; int height = videoModeInfo.Height; Bitmap image = null; BitmapData data = null; try { image = ( cameraMode == VideoCameraMode.Color ) ? new Bitmap( width, height, PixelFormat.Format24bppRgb ) : AForge.Imaging.Image.<API key>( width, height ); data = image.LockBits( new Rectangle( 0, 0, width, height ), ImageLockMode.ReadWrite, image.PixelFormat ); unsafe { byte* dst = (byte*) data.Scan0.ToPointer( ); byte* src = (byte*) imageBuffer.ToPointer( ); if ( cameraMode == VideoCameraMode.Color ) { // color RGB 24 mode int offset = data.Stride - width * 3; for ( int y = 0; y < height; y++ ) { for ( int x = 0; x < width; x++, src += 3, dst += 3 ) { dst[0] = src[2]; dst[1] = src[1]; dst[2] = src[0]; } dst += offset; } } else { // infra red mode - grayscale output int stride = data.Stride; if ( stride != width ) { for ( int y = 0; y < height; y++ ) { SystemTools.CopyUnmanagedMemory( dst, src, width ); dst += stride; src += width; } } else { SystemTools.CopyUnmanagedMemory( dst, src, width * height ); } } } image.UnlockBits( data ); framesReceived++; bytesReceived += width * height; } catch ( Exception ex ) { if ( VideoSourceError != null ) { VideoSourceError( this, new <API key>( ex.Message ) ); } if ( image != null ) { if ( data != null ) { image.UnlockBits( data ); } image.Dispose( ); image = null; } } if ( image != null ) { if ( NewFrame != null ) { NewFrame( this, new NewFrameEventArgs( image ) ); } image.Dispose( ); } } } }
namespace DeviceHive.Data.EF.Migrations { using System.Data.Entity.Migrations; public partial class _91 : DbMigration { public override void Up() { CreateTable( "OAuthClient", c => new { ID = c.Int(nullable: false, identity: true), Name = c.String(nullable: false, maxLength: 128), Domain = c.String(nullable: false, maxLength: 128), Subnet = c.String(maxLength: 128), RedirectUri = c.String(nullable: false, maxLength: 128), OAuthID = c.String(nullable: false, maxLength: 32), OAuthSecret = c.String(nullable: false, maxLength: 32), }) .PrimaryKey(t => t.ID) .Index(t => t.OAuthID, unique: true); CreateTable( "OAuthGrant", c => new { ID = c.Int(nullable: false, identity: true), Timestamp = c.DateTime(nullable: false, storeType: "datetime2"), AuthCode = c.Guid(), ClientID = c.Int(nullable: false), UserID = c.Int(nullable: false), AccessKeyID = c.Int(nullable: false), Type = c.Int(nullable: false), AccessType = c.Int(nullable: false), RedirectUri = c.String(maxLength: 128), Scope = c.String(nullable: false, maxLength: 256), NetworkList = c.String(maxLength: 128), }) .PrimaryKey(t => t.ID) .ForeignKey("OAuthClient", t => t.ClientID, cascadeDelete: true) .ForeignKey("User", t => t.UserID, cascadeDelete: true) .ForeignKey("AccessKey", t => t.AccessKeyID, cascadeDelete: false) .Index(t => t.ClientID) .Index(t => t.UserID) .Index(t => t.AccessKeyID); Sql("CREATE UNIQUE NONCLUSTERED INDEX [IX_AuthCode] ON [OAuthGrant] ( [AuthCode] ASC ) WHERE [AuthCode] IS NOT NULL"); } public override void Down() { DropIndex("OAuthGrant", new[] { "AccessKeyID" }); DropIndex("OAuthGrant", new[] { "UserID" }); DropIndex("OAuthGrant", new[] { "ClientID" }); DropIndex("OAuthGrant", new[] { "AuthCode" }); DropForeignKey("OAuthGrant", "AccessKeyID", "AccessKey"); DropForeignKey("OAuthGrant", "UserID", "User"); DropForeignKey("OAuthGrant", "ClientID", "OAuthClient"); DropTable("OAuthGrant"); DropIndex("OAuthClient", new[] { "OAuthID" }); DropTable("OAuthClient"); } } }
require File.dirname(__FILE__) + '/../test_helper' require 'posts_controller' require 'mailing_list_mailer' # Re-raise errors caught by the controller. class PostsController def rescue_action(e) raise e end end # FIXME Navigation tests are weak. Need to do more than just not blow up class PostsControllerTest < ActiveSupport::TestCase def setup @controller = PostsController.new @request = ActionController::TestRequest.new @response = ActionController::TestResponse.new ActionMailer::Base.delivery_method = :test ActionMailer::Base.perform_deliveries = true ActionMailer::Base.deliveries = [] end def test_legacy_routing assert_recognizes( {:controller => "posts", :action => "show", :mailing_list_name => "obrarace", :id => "25621"}, "posts/show/obrarace/25621" ) assert_recognizes( {:controller => "posts", :action => "new", :mailing_list_name => "obra"}, "posts/new/obra" ) end def test_new obra_chat = mailing_lists(:obra_chat) get(:new, :mailing_list_name => obra_chat.name) assert_response(:success) assert_template("posts/new") assert_not_nil(assigns["mailing_list"], "Should assign mailing_list") assert_not_nil(assigns["mailing_list_post"], "Should assign mailing_list_post") mailing_list_post = assigns["mailing_list_post"] assert_equal(obra_chat, mailing_list_post.mailing_list, "Post's mailing list") assert_tag(:tag => "input", :attributes => {:type => "hidden", :name => "mailing_list_post[mailing_list_id]", :value => obra_chat.id}) assert_tag(:tag => "input", :attributes => {:type => "text", :name => "mailing_list_post[subject]"}) assert_tag(:tag => "input", :attributes => {:type => "text", :name => "mailing_list_post[from_email_address]"}) assert_tag(:tag => "input", :attributes => {:type => "text", :name => "mailing_list_post[from_name]"}) assert_tag(:tag => "textarea", :attributes => {:name => "mailing_list_post[body]"}) assert_tag(:tag => "input", :attributes => {:type => "submit", :name => "commit", :value => "Post"}) end def test_new_reply obra_race = mailing_lists(:obra_race) original_post = Post.create({ :mailing_list => obra_race, :subject => "Only OBRA Race Message", :date => Date.today, :from_name => "Scout", :from_email_address => "scout@obra.org", :body => "This is a test message." }) get(:new, :mailing_list_name => obra_race.name, :reply_to => original_post.id) assert_response(:success) assert_template("posts/new") assert_not_nil(assigns["mailing_list"], "Should assign mailing_list") mailing_list_post = assigns["mailing_list_post"] assert_not_nil(mailing_list_post, "Should assign mailing_list_post") assert_equal(original_post, assigns["reply_to"], "Should assign reply_to") assert_equal("Re: Only OBRA Race Message", mailing_list_post.subject, 'Prepopulated subject') assert_equal(obra_race, mailing_list_post.mailing_list, "Post's mailing list") assert_tag(:tag => "input", :attributes => {:type => "hidden", :name => "mailing_list_post[mailing_list_id]", :value => obra_race.id}) assert_tag(:tag => "input", :attributes => {:type => "text", :name => "mailing_list_post[subject]"}) assert_tag(:tag => "input", :attributes => {:type => "text", :name => "mailing_list_post[from_email_address]"}) assert_tag(:tag => "input", :attributes => {:type => "text", :name => "mailing_list_post[from_name]"}) assert_tag(:tag => "textarea", :attributes => {:name => "mailing_list_post[body]"}) assert_tag(:tag => "input", :attributes => {:type => "submit", :name => "commit", :value => "Send"}) end def test_index_routing obra_chat = mailing_lists(:obra_chat) opts = {:controller => "posts", :action => "index", :mailing_list_name => obra_chat.name} assert_routing("posts/obra", opts) end def test_index get(:index, :mailing_list_name => "obrarace") assert_response(:redirect) <API key>( :action => "list", :mailing_list_name => "obrarace", :month => Date.today.month, :year => Date.today.year ) end def test_list obra_chat = mailing_lists(:obra_chat) for index in 1..22 date = Time.now.beginning_of_month + index * 3600 * 24 Post.create({ :mailing_list => obra_chat, :subject => "Subject Test #{index}", :date => date, :from_name => "Scout", :from_email_address => "scout@obra.org", :body => "This is a test message #{index}" }) end obra_race = mailing_lists(:obra_race) Post.create({ :mailing_list => obra_race, :subject => "Only OBRA Race Message", :date => date, :from_name => "Scout", :from_email_address => "scout@obra.org", :body => "This is a test message." }) get(:list, :mailing_list_name => obra_chat.name, :month => Time.now.month, :year => Time.now.year) assert_response(:success) assert_not_nil(assigns["mailing_list"], "Should assign mailing_list") assert_not_nil(assigns["year"], "Should assign month") assert_not_nil(assigns["month"], "Should assign year") assert_not_nil(assigns["posts"], "Should assign posts") assert_equal(22, assigns["posts"].size, "Should show recent posts") assert_equal(Date.today.month, assigns["month"], "Assign month") assert_equal(Date.today.year, assigns["year"], "Assign year") assert_template("posts/list") get(:list, :mailing_list_name => obra_race.name, :month => Time.now.month, :year => Time.now.year) assert_response(:success) assert_not_nil(assigns["mailing_list"], "Should assign mailing_list") assert_not_nil(assigns["year"], "Should assign month") assert_not_nil(assigns["month"], "Should assign year") assert_not_nil(assigns["posts"], "Should assign posts") assert_equal(1, assigns["posts"].size, "Should show recent posts") assert_equal(Date.today.month, assigns["month"], "Assign month") assert_equal(Date.today.year, assigns["year"], "Assign year") assert_template("posts/list") end def test_list_with_date obra_race = mailing_lists(:obra_race) post_2004_12_01 = Post.create({ :mailing_list => obra_race, :subject => "BB 1 Race Results", :date => Date.new(2004, 12, 1), :from_name => "Scout", :from_email_address => "scout@obra.org", :body => "This is a test message." }) post_2004_11_31 = Post.create({ :mailing_list => obra_race, :subject => "Cherry Pie Race Results", :date => Date.new(2004, 11, 30), :from_name => "Scout", :from_email_address => "scout@obra.org", :body => "This is a test message." }) post_2004_12_31 = Post.create({ :mailing_list => obra_race, :subject => "Schedule Changes", :date => Time.local(2004, 12, 31, 23, 59, 59, 999999), :from_name => "Scout", :from_email_address => "scout@obra.org", :body => "This is a test message." }) get(:list, :mailing_list_name => obra_race.name, :year => "2004", :month => "11") assert_response(:success) assert_not_nil(assigns["mailing_list"], "Should assign mailing_list") assert_not_nil(assigns["year"], "Should assign month") assert_not_nil(assigns["month"], "Should assign year") assert_not_nil(assigns["posts"], "Should assign posts") assert_equal(1, assigns["posts"].size, "Should show recent posts") assert_equal(11, assigns["month"], "Assign month") assert_equal(2004, assigns["year"], "Assign year") assert_equal(post_2004_11_31, assigns["posts"].first, "Post") assert_template("posts/list") get(:list, :mailing_list_name => obra_race.name, :year => "2004", :month => "12") assert_response(:success) assert_not_nil(assigns["mailing_list"], "Should assign mailing_list") assert_not_nil(assigns["year"], "Should assign month") assert_not_nil(assigns["month"], "Should assign year") assert_not_nil(assigns["posts"], "Should assign posts") assert_equal(2, assigns["posts"].size, "Should show recent posts") assert_equal(12, assigns["month"], "Assign month") assert_equal(2004, assigns["year"], "Assign year") assert_equal(post_2004_12_31, assigns["posts"].first, "Post") assert_equal(post_2004_12_01, assigns["posts"].last, "Post") assert_template("posts/list") get(:list, :mailing_list_name => obra_race.name, :year => "2004", :month => "10") assert_response(:success) assert_not_nil(assigns["mailing_list"], "Should assign mailing_list") assert_not_nil(assigns["year"], "Should assign month") assert_not_nil(assigns["month"], "Should assign year") assert_not_nil(assigns["posts"], "Should assign posts") assert_equal(10, assigns["month"], "Assign month") assert_equal(2004, assigns["year"], "Assign year") assert(assigns["posts"].empty?, "No posts") assert_template("posts/list") end def <API key> obra_race = mailing_lists(:obra_race) post_2004_12_01 = Post.create({ :mailing_list => obra_race, :subject => "BB 1 Race Results", :date => Date.new(2004, 12, 1), :from_name => "Scout", :from_email_address => "scout@obra.org", :body => "This is a test message." }) post_2004_11_31 = Post.create({ :mailing_list => obra_race, :subject => "Cherry Pie Race Results", :date => Date.new(2004, 11, 30), :from_name => "Scout", :from_email_address => "scout@obra.org", :body => "This is a test message." }) post_2004_12_31 = Post.create({ :mailing_list => obra_race, :subject => "Schedule Changes", :date => Time.local(2004, 12, 31, 23, 59, 59, 999999), :from_name => "Scout", :from_email_address => "scout@obra.org", :body => "This is a test message." }) get(:list, :mailing_list_name => obra_race.name, :year => "2004", :month => "11", :next => "&gt;") assert_response(:redirect) <API key>(:month => 12, :year => 2004) get(:list, :mailing_list_name => obra_race.name, :year => "2004", :month => "12", :next => "&gt;") assert_response(:redirect) <API key>(:month => 1, :year => 2005) get(:list, :mailing_list_name => obra_race.name, :year => "2004", :month => "12", :previous => "&lt;") assert_response(:redirect) <API key>(:month => 11, :year => 2004) end def test_list_routing path = {:controller => "posts", :action => "list", :mailing_list_name => "obra", :year => "2003", :month => "8"} assert_routing("posts/obra/2003/8", path) end def test_post assert(MailingListMailer.deliveries.empty?, "Should have no email deliveries") obra_chat = mailing_lists(:obra_chat) subject = "Spynergy for Sale" from_name = "Tim Schauer" from_email_address = "tim.schauer@butlerpress.com" body = "Barely used" path = {:controller => "posts", :action => "post", :mailing_list_name => 'obra'} assert_routing("posts/obra/post", path) post(:post, :mailing_list_name => obra_chat.name, :reply_to => {:id => ''}, :mailing_list_post => { :mailing_list_id => obra_chat.id, :subject => subject, :from_name => from_name, :from_email_address => from_email_address, :body => body}, :commit => "Post" ) assert(flash.has_key?(:notice)) assert_response(:redirect) <API key>(:action => "confirm", :mailing_list_name => obra_chat.name) assert_equal(1, MailingListMailer.deliveries.size, "Should have one email delivery") delivered_mail = MailingListMailer.deliveries.first assert_equal(subject, delivered_mail.subject, "Subject") assert_equal([from_email_address], delivered_mail.from, "From email") assert_equal(from_name, delivered_mail.friendly_from, "From Name") assert_equal_dates(Date.today, delivered_mail.date, "Date") assert_equal([obra_chat.name], delivered_mail.to, "Recipient") end def test_post_reply assert(MailingListMailer.deliveries.empty?, "Should have no email deliveries") obra_chat = mailing_lists(:obra_chat) subject = "Spynergy for Sale" from_name = "Tim Schauer" from_email_address = "tim.schauer@butlerpress.com" body = "Barely used" reply_to_post = Post.create({ :mailing_list => obra_chat, :subject => "Schedule Changes", :date => Time.local(2004, 12, 31, 23, 59, 59, 999999), :from_name => "Scout", :from_email_address => "scout@obra.org", :body => "This is a test message." }) path = {:controller => "posts", :action => "post", :mailing_list_name => 'obra'} assert_routing("posts/obra/post", path) post(:post, :mailing_list_name => obra_chat.name, :mailing_list_post => { :mailing_list_id => obra_chat.id, :subject => subject, :from_name => from_name, :from_email_address => from_email_address, :body => body}, :reply_to => {:id => reply_to_post.id}, :commit => "Post" ) assert(flash.has_key?(:notice)) assert_response(:redirect) <API key>(:action => "<API key>", :mailing_list_name => obra_chat.name) assert_equal(1, MailingListMailer.deliveries.size, "Should have one email delivery") delivered_mail = MailingListMailer.deliveries.first assert_equal(subject, delivered_mail.subject, "Subject") assert_equal([from_email_address], delivered_mail.from, "From email") assert_equal(from_name, delivered_mail.friendly_from, "From Name") assert_equal_dates(Date.today, delivered_mail.date, "Date") assert_equal(['scout@obra.org'], delivered_mail.to, "Recipient") end def <API key> obra_chat = mailing_lists(:obra_chat) subject = "Spynergy for Sale" from_name = "Tim Schauer" from_email_address = "tim.schauer@butlerpress.com" body = "Barely used" reply_to_post = Post.create!( :mailing_list => obra_chat, :subject => "Schedule Changes", :date => Time.local(2004, 12, 31, 23, 59, 59, 999999), :from_name => "Scout", :from_email_address => "scout@obra.org", :body => "This is a test message." ) post(:post, :mailing_list_name => obra_chat.name, :mailing_list_post => { :mailing_list_id => obra_chat.id, :subject => "Re: #{subject}", :from_name => "", :from_email_address => "", :body => ""}, :reply_to => {:id => reply_to_post.id}, :commit => "Send" ) assert_template("posts/new") assert_not_nil(assigns["mailing_list"], "Should assign mailing_list") mailing_list_post = assigns["mailing_list_post"] assert_not_nil(mailing_list_post, "Should assign mailing_list_post") assert_equal(reply_to_post, assigns["reply_to"], "Should assign reply_to") assert_equal("Re: #{subject}", mailing_list_post.subject, 'Prepopulated subject') assert_equal(obra_chat, mailing_list_post.mailing_list, "Post's mailing list") end def test_confirm obra_race = mailing_lists(:obra_race) path = {:controller => "posts", :action => "confirm", :mailing_list_name => obra_race.name } assert_routing("posts/obrarace/confirm", path) get(:confirm, :mailing_list_name => obra_race.name) assert_response(:success) assert_template("posts/confirm") assert_equal(obra_race, assigns["mailing_list"], 'Should assign mailing list') end def <API key> obra_race = mailing_lists(:obra_race) path = {:controller => "posts", :action => "<API key>", :mailing_list_name => obra_race.name } assert_routing("posts/obrarace/<API key>", path) get(:<API key>, :mailing_list_name => obra_race.name) assert_response(:success) assert_template("posts/<API key>") assert_equal(obra_race, assigns["mailing_list"], 'Should assign mailing list') end def test_show obra_race = mailing_lists(:obra_race) new_post = Post.create({ :mailing_list => obra_race, :subject => "Only OBRA Race Message", :date => Time.now, :from_name => "Scout", :from_email_address => "scout@obra.org", :body => "This is a test message." }) new_post.save! path = {:controller => "posts", :action => "show", :mailing_list_name => obra_race.name, :id => new_post.id.to_s } assert_routing("posts/obrarace/show/#{new_post.id}", path) get(:show, :mailing_list_name => obra_race.name, :id => new_post.id) assert_response(:success) assert_not_nil(assigns["post"], "Should assign post") assert_template("posts/show") end def <API key> # No posts get(:list, :mailing_list_name => "obrarace", :year => "2004", :month => "12") assert_tag(:tag => "div", :attributes => {:class => "archive_navigation"}) # One post obra_race = mailing_lists(:obra_race) new_post = Post.create({ :mailing_list => obra_race, :subject => "Only OBRA Race Message", :date => Time.local(2004, 12, 31, 12, 30), :from_name => "Scout", :from_email_address => "scout@obra.org", :body => "This is a test message." }) get(:list, :mailing_list_name => "obrarace", :year => "2004", :month => "12") assert_tag(:tag => "div", :attributes => {:class => "archive_navigation"}) # Two months obra_race = mailing_lists(:obra_race) new_post = Post.create({ :mailing_list => obra_race, :subject => "Before OBRA Race Message", :date => Time.local(2004, 11, 7), :from_name => "Scout", :from_email_address => "scout@obra.org", :body => "This is a test message." }) get(:list, :mailing_list_name => "obrarace", :year => "2004", :month => "11") assert_tag(:tag => "div", :attributes => {:class => "archive_navigation"}) end def <API key> # One post obra_race = mailing_lists(:obra_race) post_2004_12_31 = Post.create({ :mailing_list => obra_race, :subject => "Only OBRA Race Message", :date => Time.local(2004, 12, 31, 12, 30), :from_name => "Scout", :from_email_address => "scout@obra.org", :body => "This is a test message." }) get(:show, :mailing_list_name => obra_race.name, :id => post_2004_12_31.id) # Two months post_2004_11_07 = Post.create({ :mailing_list => obra_race, :subject => "Before OBRA Race Message", :date => Time.local(2004, 11, 7), :from_name => "Scout", :from_email_address => "scout@obra.org", :body => "This is a test message." }) get(:show, :mailing_list_name => obra_race.name, :id => post_2004_12_31.id) # Three months post_2004_11_03 = Post.create({ :mailing_list => obra_race, :subject => "Before OBRA Race Message", :date => Time.local(2004, 11, 3, 8, 00, 00), :from_name => "Scout", :from_email_address => "scout@obra.org", :body => "This is a test message." }) get(:show, :mailing_list_name => obra_race.name, :id => post_2004_11_07.id) # Another list obra_chat = mailing_lists(:obra_chat) post_other_list = Post.create({ :mailing_list => obra_chat, :subject => "OBRA Chat", :date => Time.local(2004, 11, 3, 21, 00, 00), :from_name => "Scout", :from_email_address => "scout@obra.org", :body => "This is a test message." }) get(:show, :mailing_list_name => obra_race.name, :id => post_2004_11_07.id) assert_tag(:tag => "div", :attributes => {:class => "archive_navigation"}) end def <API key> obra_race = mailing_lists(:obra_race) post_2004_12_01 = Post.create({ :mailing_list => obra_race, :subject => "BB 1 Race Results", :date => Time.local(2004, 12, 1), :from_name => "Scout", :from_email_address => "scout@obra.org", :body => "This is a test message." }) post_2004_11_31 = Post.create({ :mailing_list => obra_race, :subject => "Cherry Pie Race Results", :date => Time.local(2004, 11, 30), :from_name => "Scout", :from_email_address => "scout@obra.org", :body => "This is a test message." }) post_2004_12_31 = Post.create({ :mailing_list => obra_race, :subject => "Schedule Changes", :date => Time.local(2004, 12, 31, 23, 59, 59, 999999), :from_name => "Scout", :from_email_address => "scout@obra.org", :body => "This is a test message." }) get(:show, :mailing_list_name => obra_race.name, :next_id => post_2004_12_31.id, :next => "&gt;") assert_response(:redirect) <API key>(:id => post_2004_12_31.id.to_s) get(:show, :mailing_list_name => obra_race.name, :previous_id => post_2004_11_31.id, :previous => "&lt;") assert_response(:redirect) <API key>(:id => post_2004_11_31.id.to_s) # This part doesn't prove much obra_chat = mailing_lists(:obra_chat) post_other_list = Post.create({ :mailing_list => obra_chat, :subject => "OBRA Chat", :date => Time.local(2004, 12, 31, 12, 00, 00), :from_name => "Scout", :from_email_address => "scout@obra.org", :body => "This is a test message." }) get(:show, :mailing_list_name => obra_race.name, :next_id => post_2004_12_31.id, :next => "&gt;") assert_response(:redirect) <API key>(:id => post_2004_12_31.id.to_s) end def <API key> MailingList.delete_all get(:list, :month => Date.today.month, :year => Date.today.year) assert_response(:success) assert_template('404') assert(!flash.empty?, "Should have flash") end def <API key> get(:list, :month => Date.today.month, :year => Date.today.year, :mailing_list_name => "Masters Racing") assert_response(:success) assert_template('404') assert(!flash.empty?, "Should have flash") end def <API key> get(:list, :month => 14, :year => Date.today.year, :mailing_list_name => mailing_lists(:obra_race).name) <API key>( :action => "list", :mailing_list_name => "obrarace", :month => Date.today.month, :year => Date.today.year ) end def <API key> get(:list, :month => 12, :year => 9_116_560, :mailing_list_name => mailing_lists(:obra_race).name) <API key>( :action => "list", :mailing_list_name => "obrarace", :month => Date.today.month, :year => Date.today.year ) end end
namespace MonoGame.Extended.Collisions { public class CollisionGridCell : ICollidable { private readonly CollisionGrid _parentGrid; public CollisionGridCell(CollisionGrid parentGrid, int column, int row, int data) { _parentGrid = parentGrid; Column = column; Row = row; Data = data; Flag = data == 0 ? <API key>.Empty : <API key>.Solid; } public int Column { get; } public int Row { get; } public int Data { get; private set; } public object Tag { get; set; } public <API key> Flag { get; set; } public RectangleF BoundingBox => _parentGrid.GetCellRectangle(Column, Row).ToRectangleF(); } }
// GPDownloader.h // test #import <Foundation/Foundation.h> @class GPDownloader; typedef NS_ENUM(NSUInteger, GPDownloaderStatus) { <API key>, <API key>, <API key>, <API key>, <API key>, <API key> }; // block typedef void(^StartTaskBlock)(GPDownloader * downloader); typedef void(^ProgressBlock)(unsigned long long currDownloadSize); typedef void(^CompleteBlock)(GPDownloader *downloader); typedef void(^ErrorBlock)(GPDownloader *mdownloader,NSError *error); @protocol <API key> <NSObject> - (void)downloaderDidStart:(GPDownloader *) downloader; - (void)<API key>:(unsigned long long)currDownloadSize; - (void)<API key>:(GPDownloader *) downloader; - (void)downloader:(GPDownloader *)downloader DidDownLoadFail:(NSError *)error; @end @interface GPDownloader : NSObject #pragma mark - + (instancetype)<API key>:(NSString *)urlString downloadRange:(NSRange)downloadRange fileName:(NSString *)fileName; - (instancetype)initWithURLString:(NSString *)urlString downloadRange:(NSRange)downloadRange fileName:(NSString *)fileName; + (instancetype)<API key>:(NSString *)urlString downloadRange:(NSRange)downloadRange startBlock:(StartTaskBlock)startBlock progressBlock:(ProgressBlock)progressBlock completeBlock:(CompleteBlock)completeBlock errorBlock:(ErrorBlock)errorBlock fileName:(NSString *)fileName; - (instancetype)initWithURLString:(NSString *)urlString downloadRange:(NSRange)downloadRange startBlock:(StartTaskBlock)startBlock progressBlock:(ProgressBlock)progressBlock completeBlock:(CompleteBlock)completeBlock errorBlock:(ErrorBlock)errorBlock fileName:(NSString *)fileName; @property (nonatomic,copy) NSString *urlString; @property (nonatomic,assign) NSRange downloadRange; @property (nonatomic,strong) NSString *fileName; @property (nonatomic,assign) NSInteger fileIndex; @property (nonatomic,assign) NSInteger maxRestartCount; @property (nonatomic,assign) unsigned long long currFileSize; @property (nonatomic,weak) id<<API key>> delegate; @property (nonatomic,assign) NSTimeInterval timeOut; /** , GPDownloader */ @property (nonatomic,copy,readonly) NSString *tempFilePath; #pragma mark - //@property (nonatomic,assign) GPDownloaderStatus state; @property (nonatomic,copy) StartTaskBlock startBlock; @property (nonatomic,copy) ProgressBlock progressBlock; @property (nonatomic,copy) CompleteBlock completeBlock; @property (nonatomic,copy) ErrorBlock errorBlock; #pragma mark - - (void)startDownloadTask; - (void)pause; - (void)resume; - (void)stop; - (void)destoryDownloader; @end
.crud-table td{ padding-right: 10px; padding-bottom: 10px; padding-top: 0px; } #Grid{ width: 398px; margin: 0px; padding: 0px; overflow: scroll; overflow-x: hidden; max-height: 500px; } #Grid:after{ content: ''; display: inline-block; width: 100%; } #Grid .mix{ display: none; opacity: 0; vertical-align: top; text-align: center; width: 100px; height: 160px; font-size: 10px; color: #000000; margin-bottom: 10px; margin-left: 18px; } #Grid .mix{ display: none; opacity: 0; vertical-align: top; text-align: center; width: 100px; height: 150px; font-size: 10px; color: #000000; margin-bottom: 10px; margin-left: 18px; } #Grid .mix a{ text-decoration: none; color: #000000; } #Grid .mix a span{ display: inline-block; height: 35px; } #Grid .mix.seleccionado{ background: #3297fd; color: #FFFFFF; outline: 5px solid #3297fd; font-weight: bold; } #Grid .mix.seleccionado a{ color: #FFFFFF; } #Grid .gap{ display: inline-block; width: 200px; } .pPedidoProducto{ width: 800px; } .tProductoPedido td{ vertical-align: top; padding-bottom: 20px; padding-right: 10px; } .tColapse td{ padding: 1px !important; } .tColapse th{ padding: 1px !important; } /* .records_list td:last-child{ text-align: right; } */ .crud-table{ border: 10px solid #eeefff; background-color: #eeefff; } .controlm.selected{ background: #39b3d7; } .cobrosm.selected{ background: #ed9c28; } .produccionm.selected{ background: #47a447; } .tareasm.selected{ background: #6f5499; } .tareasm.selected a, .produccionm.selected a, .cobrosm.selected a, .controlm.selected a{ color: #FFFFFF !important; } /*tr.odd td.highlighted { background-color: #D3D6FF; }*/ tr.even td.highlighted { background-color: #EAEBFF; } .t_control tr.even td, .t_control tr.odd td, table.t_control.dataTable tr.odd td.sorting_1, table.t_control.dataTable tr.even td.sorting_1{ background-color: #DBF7FF; } .t_cobros tr.even td, .t_cobros tr.odd td, table.t_cobros.dataTable tr.odd td.sorting_1, table.t_cobros.dataTable tr.even td.sorting_1{ background-color: #FFE9C9; } .t_produccion tr.even td, .t_produccion tr.odd td, table.t_produccion.dataTable tr.odd td.sorting_1, table.t_produccion.dataTable tr.even td.sorting_1{ background-color: #D6FFD6; } .t_tareas tr.even td, .t_tareas tr.odd td, table.t_tareas.dataTable tr.odd td.sorting_1, table.t_tareas.dataTable tr.even td.sorting_1{ background-color: #EEE3FF; }
'use strict'; var <API key> = require('./templatedStylesheet'), path = require('path'); module.exports = <API key>(path.join(__dirname, '/templates/stylus.tpl'));
import React from 'react' import Icon from 'react-icon-base' const MdTonality = props => ( <Icon viewBox="0 0 40 40" {...props}> <g><path d="m32.9 23.4c0.1-0.6 0.2-1.2 0.3-1.8h-11.6v1.8h11.3z m-2.5 5c0.4-0.6 0.9-1.2 1.2-1.8h-10v1.8h8.8z m-8.8 4.8c1.8-0.2 3.4-0.8 4.9-1.6h-4.9v1.6z m0-16.6v1.8h11.6c-0.1-0.6-0.2-1.2-0.3-1.8h-11.3z m0-5v1.8h10c-0.4-0.6-0.8-1.2-1.2-1.8h-8.8z m0-4.8v1.6h4.9c-1.5-0.8-3.1-1.4-4.9-1.6z m-3.2 26.4v-26.4c-6.6 0.8-11.8 6.4-11.8 13.2s5.2 12.4 11.8 13.2z m1.6-29.8c9.2 0 16.6 7.4 16.6 16.6s-7.4 16.6-16.6 16.6-16.6-7.4-16.6-16.6 7.4-16.6 16.6-16.6z"/></g> </Icon> ) export default MdTonality
<?php namespace Censo\CensoBundle\Entity; use Doctrine\ORM\Mapping as ORM; /** * TipoViviendas * * @ORM\Table(name="tipo_viviendas") * @ORM\Entity */ class TipoViviendas { /** * @var integer * * @ORM\Column(name="id", type="bigint", nullable=false) * @ORM\Id * @ORM\GeneratedValue(strategy="IDENTITY") * @ORM\SequenceGenerator(sequenceName="<API key>", allocationSize=1, initialValue=1) */ private $id; /** * @var string * * @ORM\Column(name="nombre", type="string", length=255, nullable=false) */ private $nombre; /** * Get id * * @return integer */ public function getId() { return $this->id; } /** * Set nombre * * @param string $nombre * @return TipoViviendas */ public function setNombre($nombre) { $this->nombre = $nombre; return $this; } /** * Get nombre * * @return string */ public function getNombre() { return $this->nombre; } public function __toString() { return $this->getNombre(); } }
/* Generated by CIL v. 1.7.0 */ /* print_CIL_Input is false */ struct _IO_FILE; struct timeval; extern float strtof(char const *str , char const *endptr ) ; extern void signal(int sig , void *func ) ; typedef struct _IO_FILE FILE; extern int atoi(char const *s ) ; extern double strtod(char const *str , char const *endptr ) ; extern int fclose(void *stream ) ; extern void *fopen(char const *filename , char const *mode ) ; extern void abort() ; extern void exit(int status ) ; extern int raise(int sig ) ; extern int fprintf(struct _IO_FILE *stream , char const *format , ...) ; extern int strcmp(char const *a , char const *b ) ; extern int rand() ; extern unsigned long strtoul(char const *str , char const *endptr , int base ) ; void RandomFunc(unsigned int input[1] , unsigned int output[1] ) ; extern int strncmp(char const *s1 , char const *s2 , unsigned long maxlen ) ; extern int gettimeofday(struct timeval *tv , void *tz , ...) ; extern int printf(char const *format , ...) ; int main(int argc , char *argv[] ) ; void megaInit(void) ; extern unsigned long strlen(char const *s ) ; extern long strtol(char const *str , char const *endptr , int base ) ; extern unsigned long strnlen(char const *s , unsigned long maxlen ) ; extern void *memcpy(void *s1 , void const *s2 , unsigned long size ) ; struct timeval { long tv_sec ; long tv_usec ; }; extern void *malloc(unsigned long size ) ; extern int scanf(char const *format , ...) ; void megaInit(void) { { } } void RandomFunc(unsigned int input[1] , unsigned int output[1] ) { unsigned int state[1] ; unsigned int local1 ; char copy11 ; unsigned short copy12 ; { state[0UL] = (input[0UL] + 914778474UL) ^ 3462201355U; local1 = 0UL; while (local1 < input[1UL]) { if (state[0UL] > local1) { copy11 = *((char *)(& state[local1]) + 0); *((char *)(& state[local1]) + 0) = *((char *)(& state[local1]) + 1); *((char *)(& state[local1]) + 1) = copy11; copy12 = *((unsigned short *)(& state[0UL]) + 1); *((unsigned short *)(& state[0UL]) + 1) = *((unsigned short *)(& state[0UL]) + 0); *((unsigned short *)(& state[0UL]) + 0) = copy12; } else { state[0UL] |= (state[0UL] & 31U) << 4UL; state[local1] *= state[local1]; } local1 ++; } output[0UL] = state[0UL] << 5U; } } int main(int argc , char *argv[] ) { unsigned int input[1] ; unsigned int output[1] ; int randomFuns_i5 ; unsigned int randomFuns_value6 ; int randomFuns_main_i7 ; { megaInit(); if (argc != 2) { printf("Call this program with %i arguments\n", 1); exit(-1); } else { } randomFuns_i5 = 0; while (randomFuns_i5 < 1) { randomFuns_value6 = (unsigned int )strtoul(argv[randomFuns_i5 + 1], 0, 10); input[randomFuns_i5] = randomFuns_value6; randomFuns_i5 ++; } RandomFunc(input, output); if (output[0] == 460535040U) { printf("You win!\n"); } else { } randomFuns_main_i7 = 0; while (randomFuns_main_i7 < 1) { printf("%u\n", output[randomFuns_main_i7]); randomFuns_main_i7 ++; } } }
#ifndef __NGEN_CALLBACK_HPP #define __NGEN_CALLBACK_HPP #include "Ngen.Delegate.hpp" namespace Ngen { /** @brief A function-call provider primarily used to bind object instances to member delegates before invocation. */ class ngen_api Callback { public: /** @brief Constructor. Default. */ Callback() : mThis(0), mFunc(0) {} /** @brief Constructor. (unknown, Delegate*). */ Callback(unknown _this, Delegate* function) : mThis(_this), mFunc(function) {} /** @brief Constructor. (Delegate*). */ Callback(Delegate* function) : mThis(0), mFunc(function) {} /** @brief Constructor. Copy. */ Callback(const Callback& copy) : mThis(copy.mThis), mFunc(copy.mFunc) {} /** @brief De-constructor. */ ~Callback() { mThis = null; mFunc = null; } /** @brief Determines if the callback is properly configured for an invocation. */ bool IsValid() const { if(!isnull(mFunc)) { if(mFunc->IsMember()) { return !isnull(mThis); } return true; } return false; } /** @brief operator==(const Callback&) */ bool operator==(const Callback& rhs) const { if(!isnull(mThis) && mThis != rhs.mThis) { return false; } return rhs.mFunc->EqualTo(mFunc); } /** @brief operator!=(const Callback&) */ bool operator!=(const Callback& rhs) const { if(!isnull(mThis) && mThis != rhs.mThis) { return true; } return !rhs.mFunc->EqualTo(mFunc); } /** @brief Invokes the callback using the given unknown parameter set. */ unknown Call(unknown* params) { return mFunc->operator()(mThis, params); } void MakeValid(unknown pointer) { mThis = pointer; } Type* ReturnType() const { return mFunc->ReturnType(); } Delegate* Function() const { return mFunc; } protected: unknown mThis; Delegate* mFunc; }; } #endif // __NGEN_CALLBACK_HPP
package logbook.server.proxy; public class Filter { /** Content-Type */ public static final String CONTENT_TYPE_FILTER = "text/plain"; public static final int MAX_POST_FIELD_SIZE = 1024 * 1024; /** setAttribute(Response) */ public static final String RESPONSE_BODY = "res-body"; /** setAttribute(Request) */ public static final String REQUEST_BODY = "req-body"; private static String serverName; /** * * @param name */ public static void setServerName(String name) { serverName = name; } /** * * @param name */ public static String getServerName() { return serverName; } /** * true * * @return true */ public static boolean isServerDetected() { return serverName != null; } /** * <p> * <br> * <br> * true<br> * * @param name * @return */ public static boolean isNeed(String name) { if ((!isServerDetected() || (isServerDetected() && serverName.equals(name)))) { return true; } return false; } /** * <p> * <br> * Content-Type<br> * Content-Type<br> * * @param name * @param contentType Content-Type * @return */ public static boolean isNeed(String name, String contentType) { if ((!isServerDetected() || serverName.equals(name)) && CONTENT_TYPE_FILTER.equals(contentType)) { return true; } return false; } }
// Generated by the protocol buffer compiler. DO NOT EDIT! // source: <API key>.proto package Diadoc.Api.Proto; public final class <API key> { private <API key>() {} public static void <API key>( com.google.protobuf.ExtensionRegistry registry) { } public interface <API key> extends // @@<API key>(interface_extends:Diadoc.Api.Proto.<API key>) com.google.protobuf.MessageOrBuilder { /** * <code>optional .Diadoc.Api.Proto.Timestamp Timestamp = 1;</code> */ boolean hasTimestamp(); /** * <code>optional .Diadoc.Api.Proto.Timestamp Timestamp = 1;</code> */ Diadoc.Api.Proto.TimestampProtos.Timestamp getTimestamp(); /** * <code>optional .Diadoc.Api.Proto.Timestamp Timestamp = 1;</code> */ Diadoc.Api.Proto.TimestampProtos.TimestampOrBuilder <API key>(); /** * <code>optional string ToBoxId = 2;</code> */ boolean hasToBoxId(); /** * <code>optional string ToBoxId = 2;</code> */ java.lang.String getToBoxId(); /** * <code>optional string ToBoxId = 2;</code> */ com.google.protobuf.ByteString getToBoxIdBytes(); } /** * Protobuf type {@code Diadoc.Api.Proto.<API key>} */ public static final class <API key> extends com.google.protobuf.GeneratedMessage implements // @@<API key>(message_implements:Diadoc.Api.Proto.<API key>) <API key> { // Use <API key>.newBuilder() to construct. private <API key>(com.google.protobuf.GeneratedMessage.Builder<?> builder) { super(builder); this.unknownFields = builder.getUnknownFields(); } private <API key>(boolean noInit) { this.unknownFields = com.google.protobuf.UnknownFieldSet.getDefaultInstance(); } private static final <API key> defaultInstance; public static <API key> getDefaultInstance() { return defaultInstance; } public <API key> <API key>() { return defaultInstance; } private final com.google.protobuf.UnknownFieldSet unknownFields; @java.lang.Override public final com.google.protobuf.UnknownFieldSet getUnknownFields() { return this.unknownFields; } private <API key>( com.google.protobuf.CodedInputStream input, com.google.protobuf.<API key> extensionRegistry) throws com.google.protobuf.<API key> { initFields(); int mutable_bitField0_ = 0; com.google.protobuf.UnknownFieldSet.Builder unknownFields = com.google.protobuf.UnknownFieldSet.newBuilder(); try { boolean done = false; while (!done) { int tag = input.readTag(); switch (tag) { case 0: done = true; break; default: { if (!parseUnknownField(input, unknownFields, extensionRegistry, tag)) { done = true; } break; } case 10: { Diadoc.Api.Proto.TimestampProtos.Timestamp.Builder subBuilder = null; if (((bitField0_ & 0x00000001) == 0x00000001)) { subBuilder = timestamp_.toBuilder(); } timestamp_ = input.readMessage(Diadoc.Api.Proto.TimestampProtos.Timestamp.PARSER, extensionRegistry); if (subBuilder != null) { subBuilder.mergeFrom(timestamp_); timestamp_ = subBuilder.buildPartial(); } bitField0_ |= 0x00000001; break; } case 18: { com.google.protobuf.ByteString bs = input.readBytes(); bitField0_ |= 0x00000002; toBoxId_ = bs; break; } } } } catch (com.google.protobuf.<API key> e) { throw e.<API key>(this); } catch (java.io.IOException e) { throw new com.google.protobuf.<API key>( e.getMessage()).<API key>(this); } finally { this.unknownFields = unknownFields.build(); <API key>(); } } public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return Diadoc.Api.Proto.<API key>.<API key>; } protected com.google.protobuf.GeneratedMessage.FieldAccessorTable <API key>() { return Diadoc.Api.Proto.<API key>.<API key> .<API key>( Diadoc.Api.Proto.<API key>.<API key>.class, Diadoc.Api.Proto.<API key>.<API key>.Builder.class); } public static com.google.protobuf.Parser<<API key>> PARSER = new com.google.protobuf.AbstractParser<<API key>>() { public <API key> parsePartialFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.<API key> extensionRegistry) throws com.google.protobuf.<API key> { return new <API key>(input, extensionRegistry); } }; @java.lang.Override public com.google.protobuf.Parser<<API key>> getParserForType() { return PARSER; } private int bitField0_; public static final int <API key> = 1; private Diadoc.Api.Proto.TimestampProtos.Timestamp timestamp_; /** * <code>optional .Diadoc.Api.Proto.Timestamp Timestamp = 1;</code> */ public boolean hasTimestamp() { return ((bitField0_ & 0x00000001) == 0x00000001); } /** * <code>optional .Diadoc.Api.Proto.Timestamp Timestamp = 1;</code> */ public Diadoc.Api.Proto.TimestampProtos.Timestamp getTimestamp() { return timestamp_; } /** * <code>optional .Diadoc.Api.Proto.Timestamp Timestamp = 1;</code> */ public Diadoc.Api.Proto.TimestampProtos.TimestampOrBuilder <API key>() { return timestamp_; } public static final int <API key> = 2; private java.lang.Object toBoxId_; /** * <code>optional string ToBoxId = 2;</code> */ public boolean hasToBoxId() { return ((bitField0_ & 0x00000002) == 0x00000002); } /** * <code>optional string ToBoxId = 2;</code> */ public java.lang.String getToBoxId() { java.lang.Object ref = toBoxId_; if (ref instanceof java.lang.String) { return (java.lang.String) ref; } else { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); if (bs.isValidUtf8()) { toBoxId_ = s; } return s; } } /** * <code>optional string ToBoxId = 2;</code> */ public com.google.protobuf.ByteString getToBoxIdBytes() { java.lang.Object ref = toBoxId_; if (ref instanceof java.lang.String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8( (java.lang.String) ref); toBoxId_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } private void initFields() { timestamp_ = Diadoc.Api.Proto.TimestampProtos.Timestamp.getDefaultInstance(); toBoxId_ = ""; } private byte <API key> = -1; public final boolean isInitialized() { byte isInitialized = <API key>; if (isInitialized == 1) return true; if (isInitialized == 0) return false; if (hasTimestamp()) { if (!getTimestamp().isInitialized()) { <API key> = 0; return false; } } <API key> = 1; return true; } public void writeTo(com.google.protobuf.CodedOutputStream output) throws java.io.IOException { getSerializedSize(); if (((bitField0_ & 0x00000001) == 0x00000001)) { output.writeMessage(1, timestamp_); } if (((bitField0_ & 0x00000002) == 0x00000002)) { output.writeBytes(2, getToBoxIdBytes()); } getUnknownFields().writeTo(output); } private int <API key> = -1; public int getSerializedSize() { int size = <API key>; if (size != -1) return size; size = 0; if (((bitField0_ & 0x00000001) == 0x00000001)) { size += com.google.protobuf.CodedOutputStream .computeMessageSize(1, timestamp_); } if (((bitField0_ & 0x00000002) == 0x00000002)) { size += com.google.protobuf.CodedOutputStream .computeBytesSize(2, getToBoxIdBytes()); } size += getUnknownFields().getSerializedSize(); <API key> = size; return size; } private static final long serialVersionUID = 0L; @java.lang.Override protected java.lang.Object writeReplace() throws java.io.<API key> { return super.writeReplace(); } public static Diadoc.Api.Proto.<API key>.<API key> parseFrom( com.google.protobuf.ByteString data) throws com.google.protobuf.<API key> { return PARSER.parseFrom(data); } public static Diadoc.Api.Proto.<API key>.<API key> parseFrom( com.google.protobuf.ByteString data, com.google.protobuf.<API key> extensionRegistry) throws com.google.protobuf.<API key> { return PARSER.parseFrom(data, extensionRegistry); } public static Diadoc.Api.Proto.<API key>.<API key> parseFrom(byte[] data) throws com.google.protobuf.<API key> { return PARSER.parseFrom(data); } public static Diadoc.Api.Proto.<API key>.<API key> parseFrom( byte[] data, com.google.protobuf.<API key> extensionRegistry) throws com.google.protobuf.<API key> { return PARSER.parseFrom(data, extensionRegistry); } public static Diadoc.Api.Proto.<API key>.<API key> parseFrom(java.io.InputStream input) throws java.io.IOException { return PARSER.parseFrom(input); } public static Diadoc.Api.Proto.<API key>.<API key> parseFrom( java.io.InputStream input, com.google.protobuf.<API key> extensionRegistry) throws java.io.IOException { return PARSER.parseFrom(input, extensionRegistry); } public static Diadoc.Api.Proto.<API key>.<API key> parseDelimitedFrom(java.io.InputStream input) throws java.io.IOException { return PARSER.parseDelimitedFrom(input); } public static Diadoc.Api.Proto.<API key>.<API key> parseDelimitedFrom( java.io.InputStream input, com.google.protobuf.<API key> extensionRegistry) throws java.io.IOException { return PARSER.parseDelimitedFrom(input, extensionRegistry); } public static Diadoc.Api.Proto.<API key>.<API key> parseFrom( com.google.protobuf.CodedInputStream input) throws java.io.IOException { return PARSER.parseFrom(input); } public static Diadoc.Api.Proto.<API key>.<API key> parseFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.<API key> extensionRegistry) throws java.io.IOException { return PARSER.parseFrom(input, extensionRegistry); } public static Builder newBuilder() { return Builder.create(); } public Builder newBuilderForType() { return newBuilder(); } public static Builder newBuilder(Diadoc.Api.Proto.<API key>.<API key> prototype) { return newBuilder().mergeFrom(prototype); } public Builder toBuilder() { return newBuilder(this); } @java.lang.Override protected Builder newBuilderForType( com.google.protobuf.GeneratedMessage.BuilderParent parent) { Builder builder = new Builder(parent); return builder; } /** * Protobuf type {@code Diadoc.Api.Proto.<API key>} */ public static final class Builder extends com.google.protobuf.GeneratedMessage.Builder<Builder> implements // @@<API key>(builder_implements:Diadoc.Api.Proto.<API key>) Diadoc.Api.Proto.<API key>.<API key> { public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return Diadoc.Api.Proto.<API key>.<API key>; } protected com.google.protobuf.GeneratedMessage.FieldAccessorTable <API key>() { return Diadoc.Api.Proto.<API key>.<API key> .<API key>( Diadoc.Api.Proto.<API key>.<API key>.class, Diadoc.Api.Proto.<API key>.<API key>.Builder.class); } // Construct using Diadoc.Api.Proto.<API key>.<API key>.newBuilder() private Builder() { <API key>(); } private Builder( com.google.protobuf.GeneratedMessage.BuilderParent parent) { super(parent); <API key>(); } private void <API key>() { if (com.google.protobuf.GeneratedMessage.<API key>) { <API key>(); } } private static Builder create() { return new Builder(); } public Builder clear() { super.clear(); if (timestampBuilder_ == null) { timestamp_ = Diadoc.Api.Proto.TimestampProtos.Timestamp.getDefaultInstance(); } else { timestampBuilder_.clear(); } bitField0_ = (bitField0_ & ~0x00000001); toBoxId_ = ""; bitField0_ = (bitField0_ & ~0x00000002); return this; } public Builder clone() { return create().mergeFrom(buildPartial()); } public com.google.protobuf.Descriptors.Descriptor <API key>() { return Diadoc.Api.Proto.<API key>.<API key>; } public Diadoc.Api.Proto.<API key>.<API key> <API key>() { return Diadoc.Api.Proto.<API key>.<API key>.getDefaultInstance(); } public Diadoc.Api.Proto.<API key>.<API key> build() { Diadoc.Api.Proto.<API key>.<API key> result = buildPartial(); if (!result.isInitialized()) { throw <API key>(result); } return result; } public Diadoc.Api.Proto.<API key>.<API key> buildPartial() { Diadoc.Api.Proto.<API key>.<API key> result = new Diadoc.Api.Proto.<API key>.<API key>(this); int from_bitField0_ = bitField0_; int to_bitField0_ = 0; if (((from_bitField0_ & 0x00000001) == 0x00000001)) { to_bitField0_ |= 0x00000001; } if (timestampBuilder_ == null) { result.timestamp_ = timestamp_; } else { result.timestamp_ = timestampBuilder_.build(); } if (((from_bitField0_ & 0x00000002) == 0x00000002)) { to_bitField0_ |= 0x00000002; } result.toBoxId_ = toBoxId_; result.bitField0_ = to_bitField0_; onBuilt(); return result; } public Builder mergeFrom(com.google.protobuf.Message other) { if (other instanceof Diadoc.Api.Proto.<API key>.<API key>) { return mergeFrom((Diadoc.Api.Proto.<API key>.<API key>)other); } else { super.mergeFrom(other); return this; } } public Builder mergeFrom(Diadoc.Api.Proto.<API key>.<API key> other) { if (other == Diadoc.Api.Proto.<API key>.<API key>.getDefaultInstance()) return this; if (other.hasTimestamp()) { mergeTimestamp(other.getTimestamp()); } if (other.hasToBoxId()) { bitField0_ |= 0x00000002; toBoxId_ = other.toBoxId_; onChanged(); } this.mergeUnknownFields(other.getUnknownFields()); return this; } public final boolean isInitialized() { if (hasTimestamp()) { if (!getTimestamp().isInitialized()) { return false; } } return true; } public Builder mergeFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.<API key> extensionRegistry) throws java.io.IOException { Diadoc.Api.Proto.<API key>.<API key> parsedMessage = null; try { parsedMessage = PARSER.parsePartialFrom(input, extensionRegistry); } catch (com.google.protobuf.<API key> e) { parsedMessage = (Diadoc.Api.Proto.<API key>.<API key>) e.<API key>(); throw e; } finally { if (parsedMessage != null) { mergeFrom(parsedMessage); } } return this; } private int bitField0_; private Diadoc.Api.Proto.TimestampProtos.Timestamp timestamp_ = Diadoc.Api.Proto.TimestampProtos.Timestamp.getDefaultInstance(); private com.google.protobuf.SingleFieldBuilder< Diadoc.Api.Proto.TimestampProtos.Timestamp, Diadoc.Api.Proto.TimestampProtos.Timestamp.Builder, Diadoc.Api.Proto.TimestampProtos.TimestampOrBuilder> timestampBuilder_; /** * <code>optional .Diadoc.Api.Proto.Timestamp Timestamp = 1;</code> */ public boolean hasTimestamp() { return ((bitField0_ & 0x00000001) == 0x00000001); } /** * <code>optional .Diadoc.Api.Proto.Timestamp Timestamp = 1;</code> */ public Diadoc.Api.Proto.TimestampProtos.Timestamp getTimestamp() { if (timestampBuilder_ == null) { return timestamp_; } else { return timestampBuilder_.getMessage(); } } /** * <code>optional .Diadoc.Api.Proto.Timestamp Timestamp = 1;</code> */ public Builder setTimestamp(Diadoc.Api.Proto.TimestampProtos.Timestamp value) { if (timestampBuilder_ == null) { if (value == null) { throw new <API key>(); } timestamp_ = value; onChanged(); } else { timestampBuilder_.setMessage(value); } bitField0_ |= 0x00000001; return this; } /** * <code>optional .Diadoc.Api.Proto.Timestamp Timestamp = 1;</code> */ public Builder setTimestamp( Diadoc.Api.Proto.TimestampProtos.Timestamp.Builder builderForValue) { if (timestampBuilder_ == null) { timestamp_ = builderForValue.build(); onChanged(); } else { timestampBuilder_.setMessage(builderForValue.build()); } bitField0_ |= 0x00000001; return this; } /** * <code>optional .Diadoc.Api.Proto.Timestamp Timestamp = 1;</code> */ public Builder mergeTimestamp(Diadoc.Api.Proto.TimestampProtos.Timestamp value) { if (timestampBuilder_ == null) { if (((bitField0_ & 0x00000001) == 0x00000001) && timestamp_ != Diadoc.Api.Proto.TimestampProtos.Timestamp.getDefaultInstance()) { timestamp_ = Diadoc.Api.Proto.TimestampProtos.Timestamp.newBuilder(timestamp_).mergeFrom(value).buildPartial(); } else { timestamp_ = value; } onChanged(); } else { timestampBuilder_.mergeFrom(value); } bitField0_ |= 0x00000001; return this; } /** * <code>optional .Diadoc.Api.Proto.Timestamp Timestamp = 1;</code> */ public Builder clearTimestamp() { if (timestampBuilder_ == null) { timestamp_ = Diadoc.Api.Proto.TimestampProtos.Timestamp.getDefaultInstance(); onChanged(); } else { timestampBuilder_.clear(); } bitField0_ = (bitField0_ & ~0x00000001); return this; } /** * <code>optional .Diadoc.Api.Proto.Timestamp Timestamp = 1;</code> */ public Diadoc.Api.Proto.TimestampProtos.Timestamp.Builder getTimestampBuilder() { bitField0_ |= 0x00000001; onChanged(); return <API key>().getBuilder(); } /** * <code>optional .Diadoc.Api.Proto.Timestamp Timestamp = 1;</code> */ public Diadoc.Api.Proto.TimestampProtos.TimestampOrBuilder <API key>() { if (timestampBuilder_ != null) { return timestampBuilder_.getMessageOrBuilder(); } else { return timestamp_; } } /** * <code>optional .Diadoc.Api.Proto.Timestamp Timestamp = 1;</code> */ private com.google.protobuf.SingleFieldBuilder< Diadoc.Api.Proto.TimestampProtos.Timestamp, Diadoc.Api.Proto.TimestampProtos.Timestamp.Builder, Diadoc.Api.Proto.TimestampProtos.TimestampOrBuilder> <API key>() { if (timestampBuilder_ == null) { timestampBuilder_ = new com.google.protobuf.SingleFieldBuilder< Diadoc.Api.Proto.TimestampProtos.Timestamp, Diadoc.Api.Proto.TimestampProtos.Timestamp.Builder, Diadoc.Api.Proto.TimestampProtos.TimestampOrBuilder>( getTimestamp(), <API key>(), isClean()); timestamp_ = null; } return timestampBuilder_; } private java.lang.Object toBoxId_ = ""; /** * <code>optional string ToBoxId = 2;</code> */ public boolean hasToBoxId() { return ((bitField0_ & 0x00000002) == 0x00000002); } /** * <code>optional string ToBoxId = 2;</code> */ public java.lang.String getToBoxId() { java.lang.Object ref = toBoxId_; if (!(ref instanceof java.lang.String)) { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); if (bs.isValidUtf8()) { toBoxId_ = s; } return s; } else { return (java.lang.String) ref; } } /** * <code>optional string ToBoxId = 2;</code> */ public com.google.protobuf.ByteString getToBoxIdBytes() { java.lang.Object ref = toBoxId_; if (ref instanceof String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8( (java.lang.String) ref); toBoxId_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } /** * <code>optional string ToBoxId = 2;</code> */ public Builder setToBoxId( java.lang.String value) { if (value == null) { throw new <API key>(); } bitField0_ |= 0x00000002; toBoxId_ = value; onChanged(); return this; } /** * <code>optional string ToBoxId = 2;</code> */ public Builder clearToBoxId() { bitField0_ = (bitField0_ & ~0x00000002); toBoxId_ = getDefaultInstance().getToBoxId(); onChanged(); return this; } /** * <code>optional string ToBoxId = 2;</code> */ public Builder setToBoxIdBytes( com.google.protobuf.ByteString value) { if (value == null) { throw new <API key>(); } bitField0_ |= 0x00000002; toBoxId_ = value; onChanged(); return this; } // @@<API key>(builder_scope:Diadoc.Api.Proto.<API key>) } static { defaultInstance = new <API key>(true); defaultInstance.initFields(); } // @@<API key>(class_scope:Diadoc.Api.Proto.<API key>) } private static final com.google.protobuf.Descriptors.Descriptor <API key>; private static com.google.protobuf.GeneratedMessage.FieldAccessorTable <API key>; public static com.google.protobuf.Descriptors.FileDescriptor getDescriptor() { return descriptor; } private static com.google.protobuf.Descriptors.FileDescriptor descriptor; static { java.lang.String[] descriptorData = { "\n\<API key>.proto\022\020Diadoc.Api" + ".Proto\032\017Timestamp.proto\"W\n\024ForwardDocume" + "ntEvent\022.\n\tTimestamp\030\001 \001(\0132\033.Diadoc.Api." + "Proto.Timestamp\022\017\n\007ToBoxId\030\002 \001(\tB\034B\032Forw" + "<API key>" }; com.google.protobuf.Descriptors.FileDescriptor.<API key> assigner = new com.google.protobuf.Descriptors.FileDescriptor. <API key>() { public com.google.protobuf.ExtensionRegistry assignDescriptors( com.google.protobuf.Descriptors.FileDescriptor root) { descriptor = root; return null; } }; com.google.protobuf.Descriptors.FileDescriptor .<API key>(descriptorData, new com.google.protobuf.Descriptors.FileDescriptor[] { Diadoc.Api.Proto.TimestampProtos.getDescriptor(), }, assigner); <API key> = getDescriptor().getMessageTypes().get(0); <API key> = new com.google.protobuf.GeneratedMessage.FieldAccessorTable( <API key>, new java.lang.String[] { "Timestamp", "ToBoxId", }); Diadoc.Api.Proto.TimestampProtos.getDescriptor(); } // @@<API key>(outer_class_scope) }
<!DOCTYPE HTML PUBLIC "- <!-- NewPage --> <html lang="en"> <head> <!-- Generated by javadoc (version 1.7.0_55) on Fri Jun 20 06:34:49 EDT 2014 --> <meta http-equiv="Content-Type" content="text/html" charset="utf-8"> <title>Uses of Class org.apache.solr.handler.dataimport.<API key> (Solr 4.9.0 API)</title> <meta name="date" content="2014-06-20"> <link rel="stylesheet" type="text/css" href="../../../../../../stylesheet.css" title="Style"> </head> <body> <script type="text/javascript"><! if (location.href.indexOf('is-external=true') == -1) { parent.document.title="Uses of Class org.apache.solr.handler.dataimport.<API key> (Solr 4.9.0 API)"; } </script> <noscript> <div>JavaScript is disabled on your browser.</div> </noscript> <div class="topNav"><a name="navbar_top"> </a><a href="#skip-navbar_top" title="Skip navigation links"></a><a name="navbar_top_firstrow"> </a> <ul class="navList" title="Navigation"> <li><a href="../../../../../../overview-summary.html">Overview</a></li> <li><a href="../package-summary.html">Package</a></li> <li><a href="../../../../../../org/apache/solr/handler/dataimport/<API key>.html" title="class in org.apache.solr.handler.dataimport">Class</a></li> <li class="navBarCell1Rev">Use</li> <li><a href="../package-tree.html">Tree</a></li> <li><a href="../../../../../../deprecated-list.html">Deprecated</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?org/apache/solr/handler/dataimport/class-use/<API key>.html" target="_top">Frames</a></li> <li><a href="<API key>.html" target="_top">No Frames</a></li> </ul> <ul class="navList" id="<API key>"> <li><a href="../../../../../../allclasses-noframe.html">All Classes</a></li> </ul> <div> <script type="text/javascript"><! allClassesLink = document.getElementById("<API key>"); if(window==top) { allClassesLink.style.display = "block"; } else { allClassesLink.style.display = "none"; } </script> </div> <a name="skip-navbar_top"> </a></div> <div class="header"> <h2 title="Uses of Class org.apache.solr.handler.dataimport.<API key>" class="title">Uses of Class<br>org.apache.solr.handler.dataimport.<API key></h2> </div> <div class="classUseContainer">No usage of org.apache.solr.handler.dataimport.<API key></div> <div class="bottomNav"><a name="navbar_bottom"> </a><a href="#skip-navbar_bottom" title="Skip navigation links"></a><a name="<API key>"> </a> <ul class="navList" title="Navigation"> <li><a href="../../../../../../overview-summary.html">Overview</a></li> <li><a href="../package-summary.html">Package</a></li> <li><a href="../../../../../../org/apache/solr/handler/dataimport/<API key>.html" title="class in org.apache.solr.handler.dataimport">Class</a></li> <li class="navBarCell1Rev">Use</li> <li><a href="../package-tree.html">Tree</a></li> <li><a href="../../../../../../deprecated-list.html">Deprecated</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?org/apache/solr/handler/dataimport/class-use/<API key>.html" target="_top">Frames</a></li> <li><a href="<API key>.html" target="_top">No Frames</a></li> </ul> <ul class="navList" id="<API key>"> <li><a href="../../../../../../allclasses-noframe.html">All Classes</a></li> </ul> <div> <script type="text/javascript"><! allClassesLink = document.getElementById("<API key>"); if(window==top) { allClassesLink.style.display = "block"; } else { allClassesLink.style.display = "none"; } </script> </div> <a name="skip-navbar_bottom"> </a></div> <p class="legalCopy"><small> <i>Copyright &copy; 2000-2014 Apache Software Foundation. All Rights Reserved.</i> <script src='../../../../../../prettify.js' type='text/javascript'></script> <script type='text/javascript'> (function(){ var oldonload = window.onload; if (typeof oldonload != 'function') { window.onload = prettyPrint; } else { window.onload = function() { oldonload(); prettyPrint(); } } })(); </script> </small></p> </body> </html>
package saberapplications.pawpads.databinding; import android.databinding.BaseObservable; import android.databinding.BindingAdapter; import android.databinding.BindingConversion; import android.text.Editable; import android.text.TextWatcher; import android.widget.EditText; import saberapplications.pawpads.R; public class BindableDouble extends BaseObservable { private Double value; private String format="%f"; public Double get() { return value; } public void set(double value) { if (this.value == null || !this.value.equals(value)) { this.value = value; notifyChange(); } } public void setSilent(double value) { if (this.value == null || !this.value.equals(value)) { this.value = value; } } public BindableDouble(double value) { super(); this.value = value; } public BindableDouble() { super(); } @BindingConversion public static String <API key>(BindableDouble value) { if (value != null && value.get()!=null) return String.format(value.getFormat(), value.get()); else { return null; } } @BindingAdapter({"binding2way"}) public static void bindEditText(EditText view, final BindableDouble bindableDouble) { if (view.getTag(R.id.BIND_ID) == null) { view.setTag(R.id.BIND_ID, true); view.<API key>(new TextWatcher() { @Override public void beforeTextChanged(CharSequence s, int start, int count, int after) { } @Override public void onTextChanged(CharSequence s, int start, int before, int count) { try { bindableDouble.setSilent(Double.parseDouble(s.toString())); } catch (Exception e) { } } @Override public void afterTextChanged(Editable s) { } }); } //initial value if (bindableDouble == null) return; Double newValue = bindableDouble.get(); if (newValue == null) return; String strValue= String.format(bindableDouble.getFormat(),newValue); if (!view.getText().toString().equals(strValue) ) { view.setText(strValue); } } /** * Number format to display in text field * @return */ public String getFormat() { return format; } /** *Set number format to display in text field * @param format */ public void setFormat(String format) { this.format = format; } }
using UnityEngine; using System.Collections; public class EnemyDeadInfo { public int score = 0; public Transform transform; public bool headShot = false; }
<?php /** The cron exception. */ class CronException extends Exception {} /** * Initialisation * */ function cron_init() { // Register a pagehandler for cron <API key>('cron','cron_page_handler'); } /** * Cron handler for redirecting pages. * * @param unknown_type $page */ function cron_page_handler($page) { global $CONFIG; if ($page[0]) { switch (strtolower($page[0])) { case 'minute' : case 'fiveminute' : case 'fifteenmin' : case 'halfhour' : case 'hourly' : case 'daily' : case 'weekly' : case 'monthly': case 'yearly' : case 'reboot' : set_input('period', $page[0]); break; default : throw new CronException(sprintf(elgg_echo('CronException:unknownperiod'), $page[0])); } // Include cron handler include($CONFIG->path . "engine/handlers/cron_handler.php"); } else forward(); } // Register a startup event <API key>('init','system','cron_init'); ?>
package types import "gopkg.in/pg.v4/internal/parser" func AppendJSONB(b, jsonb []byte, quote int) []byte { if quote == 1 { b = append(b, '\'') } p := parser.New(jsonb) for p.Valid() { c := p.Read() switch c { case '\'': if quote == 1 { b = append(b, '\'', '\'') } else { b = append(b, '\'') } case '\000': continue case '\\': if p.Got("u0000") { b = append(b, "\\\\u0000"...) } else { b = append(b, '\\') if p.Valid() { b = append(b, p.Read()) } } default: b = append(b, c) } } if quote == 1 { b = append(b, '\'') } return b }
#include <stdio.h> #include <ruby.h> #include <ruby/thread.h> #include <v8.h> #include <libplatform/libplatform.h> #include <ruby/encoding.h> #include <pthread.h> #include <unistd.h> #include <mutex> #include <math.h> using namespace v8; class <API key> : public v8::ArrayBuffer::Allocator { public: virtual void* Allocate(size_t length) { void* data = <API key>(length); return data == NULL ? data : memset(data, 0, length); } virtual void* <API key>(size_t length) { return malloc(length); } virtual void Free(void* data, size_t) { free(data); } }; typedef struct { const char* data; int raw_size; } SnapshotInfo; typedef struct { Isolate* isolate; <API key>* allocator; StartupData* startup_data; bool interrupted; pid_t pid; // how many references to this isolate exist // we can't rely on Ruby's GC for this, because when destroying // objects, Ruby will destroy ruby objects first, then call the // extenstion's deallocators. In this case, that means it would // call `deallocate_isolate` _before_ `deallocate`, causing a segfault int refs_count; } IsolateInfo; typedef struct { IsolateInfo* isolate_info; Persistent<Context>* context; } ContextInfo; typedef struct { bool parsed; bool executed; bool terminated; bool json; Persistent<Value>* value; Persistent<Value>* message; Persistent<Value>* backtrace; } EvalResult; typedef struct { ContextInfo* context_info; Local<String>* eval; useconds_t timeout; EvalResult* result; } EvalParams; static VALUE <API key>; static VALUE rb_eParseError; static VALUE <API key>; static VALUE <API key>; static VALUE rb_eSnapshotError; static VALUE <API key>; static VALUE rb_mJSON; static VALUE <API key>; static VALUE rb_cDateTime = Qnil; static Platform* current_platform = NULL; static std::mutex platform_lock; static VALUE <API key>(VALUE _klass, VALUE flag_as_str) { bool <API key> = false; platform_lock.lock(); if (current_platform == NULL) { V8::SetFlagsFromString(RSTRING_PTR(flag_as_str), (int)RSTRING_LEN(flag_as_str)); } else { <API key> = true; } platform_lock.unlock(); // important to raise outside of the lock if (<API key>) { rb_raise(<API key>, "The V8 platform is already initialized"); } return Qnil; } static void init_v8() { // no need to wait for the lock if already initialized if (current_platform != NULL) return; platform_lock.lock(); if (current_platform == NULL) { V8::InitializeICU(); current_platform = platform::<API key>(); V8::InitializePlatform(current_platform); V8::Initialize(); } platform_lock.unlock(); } void* nogvl_context_eval(void* arg) { EvalParams* eval_params = (EvalParams*)arg; EvalResult* result = eval_params->result; Isolate* isolate = eval_params->context_info->isolate_info->isolate; Isolate::Scope isolate_scope(isolate); HandleScope handle_scope(isolate); TryCatch trycatch(isolate); Local<Context> context = eval_params->context_info->context->Get(isolate); Context::Scope context_scope(context); // in gvl flag isolate->SetData(0, (void*)false); // terminate ASAP isolate->SetData(1, (void*)false); MaybeLocal<Script> parsed_script = Script::Compile(context, *eval_params->eval); result->parsed = !parsed_script.IsEmpty(); result->executed = false; result->terminated = false; result->json = false; result->value = NULL; if (!result->parsed) { result->message = new Persistent<Value>(); result->message->Reset(isolate, trycatch.Exception()); } else { MaybeLocal<Value> maybe_value = parsed_script.ToLocalChecked()->Run(context); result->executed = !maybe_value.IsEmpty(); if (result->executed) { // arrays and objects get converted to json Local<Value> local_value = maybe_value.ToLocalChecked(); if ((local_value->IsObject() || local_value->IsArray()) && !local_value->IsDate() && !local_value->IsFunction()) { Local<Object> JSON = context->Global()->Get( String::NewFromUtf8(isolate, "JSON"))->ToObject(); Local<Function> stringify = JSON->Get(v8::String::NewFromUtf8(isolate, "stringify")) .As<Function>(); Local<Object> object = local_value->ToObject(); const unsigned argc = 1; Local<Value> argv[argc] = { object }; MaybeLocal<Value> json = stringify->Call(JSON, argc, argv); if (json.IsEmpty()) { result->executed = false; } else { result->json = true; Persistent<Value>* persistent = new Persistent<Value>(); persistent->Reset(isolate, json.ToLocalChecked()); result->value = persistent; } } else { Persistent<Value>* persistent = new Persistent<Value>(); persistent->Reset(isolate, local_value); result->value = persistent; } } } if (!result->executed || !result->parsed) { if (trycatch.HasCaught()) { if (!trycatch.Exception()->IsNull()) { result->message = new Persistent<Value>(); Local<Message> message = trycatch.Message(); char buf[1000]; int len; len = snprintf(buf, sizeof(buf), "%s at %s:%i:%i", *String::Utf8Value(message->Get()), *String::Utf8Value(message-><API key>()->ToString()), message->GetLineNumber(), message->GetStartColumn()); Local<String> v8_message = String::NewFromUtf8(isolate, buf, NewStringType::kNormal, (int)len).ToLocalChecked(); result->message->Reset(isolate, v8_message); } else if(trycatch.HasTerminated()) { result->terminated = true; result->message = new Persistent<Value>(); Local<String> tmp = String::NewFromUtf8(isolate, "JavaScript was terminated (either by timeout or explicitly)"); result->message->Reset(isolate, tmp); } if (!trycatch.StackTrace().IsEmpty()) { result->backtrace = new Persistent<Value>(); result->backtrace->Reset(isolate, trycatch.StackTrace()->ToString()); } } } isolate->SetData(0, (void*)true); return NULL; } static VALUE convert_v8_to_ruby(Isolate* isolate, Handle<Value> &value) { Isolate::Scope isolate_scope(isolate); HandleScope scope(isolate); if (value->IsNull() || value->IsUndefined()){ return Qnil; } if (value->IsInt32()) { return INT2FIX(value->Int32Value()); } if (value->IsNumber()) { return rb_float_new(value->NumberValue()); } if (value->IsTrue()) { return Qtrue; } if (value->IsFalse()) { return Qfalse; } if (value->IsArray()) { VALUE rb_array = rb_ary_new(); Local<Array> arr = Local<Array>::Cast(value); for(uint32_t i=0; i < arr->Length(); i++) { Local<Value> element = arr->Get(i); VALUE rb_elem = convert_v8_to_ruby(isolate, element); if (rb_funcall(rb_elem, rb_intern("class"), 0) == <API key>) { return rb_elem; } rb_ary_push(rb_array, rb_elem); } return rb_array; } if (value->IsFunction()){ return rb_funcall(<API key>, rb_intern("new"), 0); } if (value->IsDate()){ double ts = Local<Date>::Cast(value)->ValueOf(); double secs = ts/1000; long nanos = round((secs - floor(secs)) * 1000000); return rb_time_new(secs, nanos); } if (value->IsObject()) { VALUE rb_hash = rb_hash_new(); TryCatch trycatch(isolate); Local<Context> context = Context::New(isolate); Local<Object> object = value->ToObject(); MaybeLocal<Array> maybe_props = object->GetOwnPropertyNames(context); if (!maybe_props.IsEmpty()) { Local<Array> props = maybe_props.ToLocalChecked(); for(uint32_t i=0; i < props->Length(); i++) { Local<Value> key = props->Get(i); VALUE rb_key = convert_v8_to_ruby(isolate, key); Local<Value> value = object->Get(key); // this may have failed due to Get raising if (trycatch.HasCaught()) { // TODO isolate code that translates execption to ruby // exception so we can properly return it return rb_funcall(<API key>, rb_intern("new"), 1, rb_str_new2("")); } VALUE rb_value = convert_v8_to_ruby(isolate, value); rb_hash_aset(rb_hash, rb_key, rb_value); } } return rb_hash; } Local<String> rstr = value->ToString(); return rb_enc_str_new(*String::Utf8Value(rstr), rstr->Utf8Length(), rb_enc_find("utf-8")); } static Handle<Value> convert_ruby_to_v8(Isolate* isolate, VALUE value) { <API key> scope(isolate); Local<Array> array; Local<Object> object; VALUE hash_as_array; VALUE pair; int i; long length; long fixnum; VALUE klass; switch (TYPE(value)) { case T_FIXNUM: fixnum = NUM2LONG(value); if (fixnum > INT_MAX) { return scope.Escape(Number::New(isolate, (double)fixnum)); } return scope.Escape(Integer::New(isolate, (int)fixnum)); case T_FLOAT: return scope.Escape(Number::New(isolate, NUM2DBL(value))); case T_STRING: return scope.Escape(String::NewFromUtf8(isolate, RSTRING_PTR(value), NewStringType::kNormal, (int)RSTRING_LEN(value)).ToLocalChecked()); case T_NIL: return scope.Escape(Null(isolate)); case T_TRUE: return scope.Escape(True(isolate)); case T_FALSE: return scope.Escape(False(isolate)); case T_ARRAY: length = RARRAY_LEN(value); array = Array::New(isolate, (int)length); for(i=0; i<length; i++) { array->Set(i, convert_ruby_to_v8(isolate, rb_ary_entry(value, i))); } return scope.Escape(array); case T_HASH: object = Object::New(isolate); hash_as_array = rb_funcall(value, rb_intern("to_a"), 0); length = RARRAY_LEN(hash_as_array); for(i=0; i<length; i++) { pair = rb_ary_entry(hash_as_array, i); object->Set(convert_ruby_to_v8(isolate, rb_ary_entry(pair, 0)), convert_ruby_to_v8(isolate, rb_ary_entry(pair, 1))); } return scope.Escape(object); case T_SYMBOL: value = rb_funcall(value, rb_intern("to_s"), 0); return scope.Escape(String::NewFromUtf8(isolate, RSTRING_PTR(value), NewStringType::kNormal, (int)RSTRING_LEN(value)).ToLocalChecked()); case T_DATA: klass = rb_funcall(value, rb_intern("class"), 0); if (klass == rb_cTime || klass == rb_cDateTime) { if (klass == rb_cDateTime) { value = rb_funcall(value, rb_intern("to_time"), 0); } value = rb_funcall(value, rb_intern("to_f"), 0); return scope.Escape(Date::New(isolate, NUM2DBL(value) * 1000)); } case T_OBJECT: case T_CLASS: case T_ICLASS: case T_MODULE: case T_REGEXP: case T_MATCH: case T_STRUCT: case T_BIGNUM: case T_FILE: case T_UNDEF: case T_NODE: default: return scope.Escape(String::NewFromUtf8(isolate, "Undefined Conversion")); } } static void unblock_eval(void *ptr) { EvalParams* eval = (EvalParams*)ptr; eval->context_info->isolate_info->interrupted = true; } static VALUE rb_snapshot_size(VALUE self, VALUE str) { SnapshotInfo* snapshot_info; Data_Get_Struct(self, SnapshotInfo, snapshot_info); return INT2NUM(snapshot_info->raw_size); } static VALUE rb_snapshot_load(VALUE self, VALUE str) { SnapshotInfo* snapshot_info; Data_Get_Struct(self, SnapshotInfo, snapshot_info); init_v8(); StartupData startup_data = V8::<API key>(RSTRING_PTR(str)); if (startup_data.data == NULL && startup_data.raw_size == 0) { rb_raise(rb_eSnapshotError, "Could not create snapshot, most likely the source is incorrect"); } snapshot_info->data = startup_data.data; snapshot_info->raw_size = startup_data.raw_size; return Qnil; } static VALUE rb_snapshot_warmup(VALUE self, VALUE str) { SnapshotInfo* snapshot_info; Data_Get_Struct(self, SnapshotInfo, snapshot_info); init_v8(); StartupData cold_startup_data = {snapshot_info->data, snapshot_info->raw_size}; StartupData warm_startup_data = V8::<API key>(cold_startup_data, RSTRING_PTR(str)); if (warm_startup_data.data == NULL && warm_startup_data.raw_size == 0) { rb_raise(rb_eSnapshotError, "Could not warm up snapshot, most likely the source is incorrect"); } else { delete[] snapshot_info->data; snapshot_info->data = warm_startup_data.data; snapshot_info->raw_size = warm_startup_data.raw_size; } return self; } static VALUE <API key>(VALUE self, VALUE snapshot) { IsolateInfo* isolate_info; Data_Get_Struct(self, IsolateInfo, isolate_info); init_v8(); isolate_info->allocator = new <API key>(); isolate_info->interrupted = false; isolate_info->refs_count = 1; Isolate::CreateParams create_params; create_params.<API key> = isolate_info->allocator; StartupData* startup_data = NULL; if (!NIL_P(snapshot)) { SnapshotInfo* snapshot_info; Data_Get_Struct(snapshot, SnapshotInfo, snapshot_info); int raw_size = snapshot_info->raw_size; char* data = new char[raw_size]; memcpy(data, snapshot_info->data, sizeof(char) * raw_size); startup_data = new StartupData; startup_data->data = data; startup_data->raw_size = raw_size; create_params.snapshot_blob = startup_data; } isolate_info->startup_data = startup_data; isolate_info->isolate = Isolate::New(create_params); return Qnil; } static VALUE <API key>(VALUE self, VALUE idle_time_in_ms) { IsolateInfo* isolate_info; Data_Get_Struct(self, IsolateInfo, isolate_info); return isolate_info->isolate->IdleNotification(NUM2INT(idle_time_in_ms)) ? Qtrue : Qfalse; } static VALUE <API key>(VALUE self, VALUE isolate) { ContextInfo* context_info; Data_Get_Struct(self, ContextInfo, context_info); init_v8(); IsolateInfo* isolate_info; Data_Get_Struct(isolate, IsolateInfo, isolate_info); context_info->isolate_info = isolate_info; isolate_info->refs_count++; { Locker lock(isolate_info->isolate); Isolate::Scope isolate_scope(isolate_info->isolate); HandleScope handle_scope(isolate_info->isolate); Local<Context> context = Context::New(isolate_info->isolate); context_info->context = new Persistent<Context>(); context_info->context->Reset(isolate_info->isolate, context); } if (Qnil == rb_cDateTime && rb_funcall(rb_cObject, rb_intern("const_defined?"), 1, rb_str_new2("DateTime")) == Qtrue) { rb_cDateTime = rb_const_get(rb_cObject, rb_intern("DateTime")); } return Qnil; } static VALUE <API key>(VALUE self, VALUE str) { EvalParams eval_params; EvalResult eval_result; ContextInfo* context_info; VALUE result; VALUE message = Qnil; VALUE backtrace = Qnil; Data_Get_Struct(self, ContextInfo, context_info); Isolate* isolate = context_info->isolate_info->isolate; { Locker lock(isolate); Isolate::Scope isolate_scope(isolate); HandleScope handle_scope(isolate); Local<String> eval = String::NewFromUtf8(isolate, RSTRING_PTR(str), NewStringType::kNormal, (int)RSTRING_LEN(str)).ToLocalChecked(); eval_params.context_info = context_info; eval_params.eval = &eval; eval_params.result = &eval_result; eval_params.timeout = 0; VALUE timeout = rb_iv_get(self, "@timeout"); if (timeout != Qnil) { eval_params.timeout = (useconds_t)NUM2LONG(timeout); } eval_result.message = NULL; eval_result.backtrace = NULL; <API key>(nogvl_context_eval, &eval_params, unblock_eval, &eval_params); if (eval_result.message != NULL) { Local<Value> tmp = Local<Value>::New(isolate, *eval_result.message); message = convert_v8_to_ruby(isolate, tmp); eval_result.message->Reset(); delete eval_result.message; } if (eval_result.backtrace != NULL) { Local<Value> tmp = Local<Value>::New(isolate, *eval_result.backtrace); backtrace = convert_v8_to_ruby(isolate, tmp); eval_result.backtrace->Reset(); delete eval_result.backtrace; } } // NOTE: this is very important, we can not do an rb_raise from within // a v8 scope, if we do the scope is never cleaned up properly and we leak if (!eval_result.parsed) { if(TYPE(message) == T_STRING) { rb_raise(rb_eParseError, "%s", RSTRING_PTR(message)); } else { rb_raise(rb_eParseError, "Unknown JavaScript Error during parse"); } } if (!eval_result.executed) { VALUE ruby_exception = rb_iv_get(self, "@current_exception"); if (ruby_exception == Qnil) { ruby_exception = eval_result.terminated ? <API key> : <API key>; // exception report about what happened if(TYPE(backtrace) == T_STRING) { rb_raise(ruby_exception, "%s", RSTRING_PTR(backtrace)); } else if(TYPE(message) == T_STRING) { rb_raise(ruby_exception, "%s", RSTRING_PTR(message)); } else { rb_raise(ruby_exception, "Unknown JavaScript Error during execution"); } } else { VALUE rb_str = rb_funcall(ruby_exception, rb_intern("to_s"), 0); rb_raise(CLASS_OF(ruby_exception), "%s", RSTRING_PTR(rb_str)); } } // New scope for return value { Locker lock(isolate); Isolate::Scope isolate_scope(isolate); HandleScope handle_scope(isolate); Local<Value> tmp = Local<Value>::New(isolate, *eval_result.value); if (eval_result.json) { Local<String> rstr = tmp->ToString(); VALUE json_string = rb_enc_str_new(*String::Utf8Value(rstr), rstr->Utf8Length(), rb_enc_find("utf-8")); result = rb_funcall(rb_mJSON, rb_intern("parse"), 1, json_string); } else { result = convert_v8_to_ruby(isolate, tmp); } eval_result.value->Reset(); delete eval_result.value; } if (rb_funcall(result, rb_intern("class"), 0) == <API key>) { // TODO try to recover stack trace from the conversion error rb_raise(<API key>, "Error converting JS object to Ruby object"); } return result; } typedef struct { VALUE callback; int length; VALUE* args; bool failed; } <API key>; static VALUE protected_callback(VALUE rdata) { <API key>* data = (<API key>*)rdata; VALUE result; if (data->length > 0) { result = rb_funcall2(data->callback, rb_intern("call"), data->length, data->args); } else { result = rb_funcall(data->callback, rb_intern("call"), 0); } return result; } static VALUE rescue_callback(VALUE rdata, VALUE exception) { <API key>* data = (<API key>*)rdata; data->failed = true; return exception; } void* gvl_ruby_callback(void* data) { <API key><Value>* args = (<API key><Value>*)data; VALUE* ruby_args = NULL; int length = args->Length(); VALUE callback; VALUE result; VALUE self; { HandleScope scope(args->GetIsolate()); Handle<External> external = Handle<External>::Cast(args->Data()); VALUE* self_pointer = (VALUE*)(external->Value()); self = *self_pointer; callback = rb_iv_get(self, "@callback"); if (length > 0) { ruby_args = ALLOC_N(VALUE, length); } for (int i = 0; i < length; i++) { Local<Value> value = ((*args)[i]).As<Value>(); ruby_args[i] = convert_v8_to_ruby(args->GetIsolate(), value); } } // may raise exception stay clear of handle scope <API key> callback_data; callback_data.length = length; callback_data.callback = callback; callback_data.args = ruby_args; callback_data.failed = false; if ((bool)args->GetIsolate()->GetData(1) == true) { args->GetIsolate()->ThrowException(String::NewFromUtf8(args->GetIsolate(), "Terminated execution during tansition from Ruby to JS")); V8::TerminateExecution(args->GetIsolate()); return NULL; } result = rb_rescue2((VALUE(*)(...))&protected_callback, (VALUE)(&callback_data), (VALUE(*)(...))&rescue_callback, (VALUE)(&callback_data), rb_eException, (VALUE)0); if(callback_data.failed) { VALUE parent = rb_iv_get(self, "@parent"); rb_iv_set(parent, "@current_exception", result); args->GetIsolate()->ThrowException(String::NewFromUtf8(args->GetIsolate(), "Ruby exception")); } else { HandleScope scope(args->GetIsolate()); Handle<Value> v8_result = convert_ruby_to_v8(args->GetIsolate(), result); args->GetReturnValue().Set(v8_result); } if (length > 0) { xfree(ruby_args); } if ((bool)args->GetIsolate()->GetData(1) == true) { Isolate* isolate = args->GetIsolate(); V8::TerminateExecution(isolate); } return NULL; } static void ruby_callback(const <API key><Value>& args) { bool has_gvl = (bool)args.GetIsolate()->GetData(0); if(has_gvl) { gvl_ruby_callback((void*)&args); } else { <API key>(gvl_ruby_callback, (void*)(&args)); } } static VALUE <API key>(VALUE self) { ContextInfo* context_info; VALUE parent = rb_iv_get(self, "@parent"); VALUE name = rb_iv_get(self, "@name"); VALUE parent_object = rb_iv_get(self, "@parent_object"); VALUE parent_object_eval = rb_iv_get(self, "@parent_object_eval"); bool parse_error = false; bool attach_error = false; Data_Get_Struct(parent, ContextInfo, context_info); Isolate* isolate = context_info->isolate_info->isolate; { Locker lock(isolate); Isolate::Scope isolate_scope(isolate); HandleScope handle_scope(isolate); Local<Context> context = context_info->context->Get(isolate); Context::Scope context_scope(context); Local<String> v8_str = String::NewFromUtf8(isolate, RSTRING_PTR(name), NewStringType::kNormal, (int)RSTRING_LEN(name)).ToLocalChecked(); // copy self so we can access from v8 external VALUE* self_copy; Data_Get_Struct(self, VALUE, self_copy); *self_copy = self; Local<Value> external = External::New(isolate, self_copy); if (parent_object == Qnil) { context->Global()->Set(v8_str, FunctionTemplate::New(isolate, ruby_callback, external)->GetFunction()); } else { Local<String> eval = String::NewFromUtf8(isolate, RSTRING_PTR(parent_object_eval), NewStringType::kNormal, (int)RSTRING_LEN(parent_object_eval)).ToLocalChecked(); MaybeLocal<Script> parsed_script = Script::Compile(context, eval); if (parsed_script.IsEmpty()) { parse_error = true; } else { MaybeLocal<Value> maybe_value = parsed_script.ToLocalChecked()->Run(context); attach_error = true; if (!maybe_value.IsEmpty()) { Local<Value> value = maybe_value.ToLocalChecked(); if (value->IsObject()){ value.As<Object>()->Set(v8_str, FunctionTemplate::New(isolate, ruby_callback, external)->GetFunction()); attach_error = false; } } } } } // always raise out of V8 context if (parse_error) { rb_raise(rb_eParseError, "Invalid object %s", RSTRING_PTR(parent_object)); } if (attach_error) { rb_raise(rb_eParseError, "Was expecting %s to be an object", RSTRING_PTR(parent_object)); } return Qnil; } void <API key>(IsolateInfo* isolate_info) { // an isolate can only be freed if no Isolate or Context (ruby) object // still need it if (isolate_info == NULL || isolate_info->refs_count > 0) { return; } if (isolate_info->isolate) { Locker lock(isolate_info->isolate); } if (isolate_info->isolate) { if (isolate_info->interrupted) { fprintf(stderr, "WARNING: V8 isolate was interrupted by Ruby, it can not be disposed and memory will not be reclaimed till the Ruby process exits.\n"); } else { if (isolate_info->pid != getpid()) { fprintf(stderr, "WARNING: V8 isolate was forked, it can not be disposed and memory will not be reclaimed till the Ruby process exits.\n"); } else { isolate_info->isolate->Dispose(); } } isolate_info->isolate = NULL; } if (isolate_info->startup_data) { delete[] isolate_info->startup_data->data; delete isolate_info->startup_data; } delete isolate_info->allocator; xfree(isolate_info); } void deallocate_isolate(void* data) { IsolateInfo* isolate_info = (IsolateInfo*) data; isolate_info->refs_count <API key>(isolate_info); } void deallocate(void* data) { ContextInfo* context_info = (ContextInfo*)data; IsolateInfo* isolate_info = context_info->isolate_info; if (context_info->context && isolate_info && isolate_info->isolate) { Locker lock(isolate_info->isolate); v8::Isolate::Scope isolate_scope(isolate_info->isolate); context_info->context->Reset(); delete context_info->context; } if (isolate_info) { isolate_info->refs_count <API key>(isolate_info); } } void <API key>(void * data) { xfree(data); } void deallocate_snapshot(void * data) { SnapshotInfo* snapshot_info = (SnapshotInfo*)data; delete[] snapshot_info->data; xfree(snapshot_info); } VALUE <API key>(VALUE klass) { VALUE* self = ALLOC(VALUE); return Data_Wrap_Struct(klass, NULL, <API key>, (void*)self); } VALUE allocate(VALUE klass) { ContextInfo* context_info = ALLOC(ContextInfo); context_info->isolate_info = NULL; context_info->context = NULL; return Data_Wrap_Struct(klass, NULL, deallocate, (void*)context_info); } VALUE allocate_snapshot(VALUE klass) { SnapshotInfo* snapshot_info = ALLOC(SnapshotInfo); snapshot_info->data = NULL; snapshot_info->raw_size = 0; return Data_Wrap_Struct(klass, NULL, deallocate_snapshot, (void*)snapshot_info); } VALUE allocate_isolate(VALUE klass) { IsolateInfo* isolate_info = ALLOC(IsolateInfo); isolate_info->isolate = NULL; isolate_info->allocator = NULL; isolate_info->startup_data = NULL; isolate_info->interrupted = false; isolate_info->refs_count = 0; isolate_info->pid = getpid(); return Data_Wrap_Struct(klass, NULL, deallocate_isolate, (void*)isolate_info); } static VALUE rb_context_stop(VALUE self) { ContextInfo* context_info; Data_Get_Struct(self, ContextInfo, context_info); Isolate* isolate = context_info->isolate_info->isolate; // flag for termination isolate->SetData(1, (void*)true); V8::TerminateExecution(isolate); rb_funcall(self, rb_intern("stop_attached"), 0); return Qnil; } extern "C" { void <API key> ( void ) { VALUE rb_mMiniRacer = rb_define_module("MiniRacer"); VALUE rb_cContext = <API key>(rb_mMiniRacer, "Context", rb_cObject); VALUE rb_cSnapshot = <API key>(rb_mMiniRacer, "Snapshot", rb_cObject); VALUE rb_cIsolate = <API key>(rb_mMiniRacer, "Isolate", rb_cObject); VALUE rb_cPlatform = <API key>(rb_mMiniRacer, "Platform", rb_cObject); VALUE rb_eEvalError = <API key>(rb_mMiniRacer, "EvalError", rb_eStandardError); <API key> = <API key>(rb_mMiniRacer, "<API key>", rb_eEvalError); rb_eParseError = <API key>(rb_mMiniRacer, "ParseError", rb_eEvalError); <API key> = <API key>(rb_mMiniRacer, "RuntimeError", rb_eEvalError); <API key> = <API key>(rb_mMiniRacer, "JavaScriptFunction", rb_cObject); rb_eSnapshotError = <API key>(rb_mMiniRacer, "SnapshotError", rb_eStandardError); <API key> = <API key>(rb_mMiniRacer, "<API key>", rb_eStandardError); <API key> = <API key>(rb_mMiniRacer, "FailedV8Conversion", rb_cObject); rb_mJSON = rb_define_module("JSON"); VALUE <API key> = <API key>(rb_cContext, "ExternalFunction", rb_cObject); rb_define_method(rb_cContext, "stop", (VALUE(*)(...))&rb_context_stop, 0); <API key>(rb_cContext, allocate); <API key>(rb_cSnapshot, allocate_snapshot); <API key>(rb_cIsolate, allocate_isolate); <API key>(rb_cContext, "eval_unsafe",(VALUE(*)(...))&<API key>, 1); <API key>(rb_cContext, "init_with_isolate",(VALUE(*)(...))&<API key>, 1); <API key>(<API key>, "notify_v8", (VALUE(*)(...))&<API key>, 0); <API key>(<API key>, <API key>); rb_define_method(rb_cSnapshot, "size", (VALUE(*)(...))&rb_snapshot_size, 0); rb_define_method(rb_cSnapshot, "warmup!", (VALUE(*)(...))&rb_snapshot_warmup, 1); <API key>(rb_cSnapshot, "load", (VALUE(*)(...))&rb_snapshot_load, 1); rb_define_method(rb_cIsolate, "idle_notification", (VALUE(*)(...))&<API key>, 1); <API key>(rb_cIsolate, "init_with_snapshot",(VALUE(*)(...))&<API key>, 1); <API key>(rb_cPlatform, "set_flag_as_str!", (VALUE(*)(...))&<API key>, 1); } }
'use strict' const dotenv = require('dotenv') const ENV = process.env.NODE_ENV || 'development' if (ENV === 'development') dotenv.load() const config = { ENV: process.env.NODE_ENV, PORT: process.env.PORT, PROXY_URI: process.env.PROXY_URI, WEBHOOK_URL: process.env.WEBHOOK_URL, <API key>: process.env.<API key>, SLACK_TOKEN: process.env.SLACK_TOKEN, ICON_EMOJI: ':passenger_ship:', USERNAME: "Battleship" } module.exports = (key) => { if (!key) return config return config[key] }
SET NOCOUNT ON; SELECT T1.Client_Version0 as VersionNumber, CASE WHEN T1.Client_Version0 = '5.00.7711.0000' THEN 'ConfigMgr 2012 RTM' WHEN T1.Client_Version0 = '5.00.7711.0200' THEN 'ConfigMgr 2012 RTM CU1' WHEN T1.Client_Version0 = '5.00.7711.0301' THEN 'ConfigMgr 2012 RTM CU2' WHEN T1.Client_Version0 = '5.00.7804.1000' THEN 'ConfigMgr 2012 SP1' WHEN T1.Client_Version0 = '5.00.7804.1202' THEN 'ConfigMgr 2012 SP1 CU1' WHEN T1.Client_Version0 = '5.00.7804.1300' THEN 'ConfigMgr 2012 SP1 CU2' WHEN T1.Client_Version0 = '5.00.7804.1400' THEN 'ConfigMgr 2012 SP1 CU3' WHEN T1.Client_Version0 = '5.00.7804.1500' THEN 'ConfigMgr 2012 SP1 CU4' WHEN T1.Client_Version0 = '5.00.7804.1600' THEN 'ConfigMgr 2012 SP1 CU5' WHEN T1.Client_Version0 = '5.00.7958.1000' THEN 'ConfigMgr 2012 R2' WHEN T1.Client_Version0 = '5.00.7958.1101' THEN 'ConfigMgr 2012 R2 with KB290500' WHEN T1.Client_Version0 = '5.00.7958.1203' THEN 'ConfigMgr 2012 R2 CU1' WHEN T1.Client_Version0 = '5.00.7958.1303' THEN 'ConfigMgr 2012 R2 CU2' WHEN T1.Client_Version0 = '5.00.7958.1401' THEN 'ConfigMgr 2012 R2 CU3' WHEN T1.Client_Version0 = '5.00.7958.1501' THEN 'ConfigMgr 2012 R2 CU4' WHEN T1.Client_Version0 = '5.00.7958.1601' THEN 'ConfigMgr 2012 R2 CU5' WHEN T1.Client_Version0 = '5.00.8239.1000' THEN 'ConfigMgr 2012 R2 SP1' WHEN T1.Client_Version0 = '5.00.8239.1203' THEN 'ConfigMgr 2012 R2 SP1 CU1' WHEN T1.Client_Version0 = '5.00.8239.1301' THEN 'ConfigMgr 2012 R2 SP1 CU2' WHEN T1.Client_Version0 = '5.00.8239.1403' THEN 'ConfigMgr 2012 R2 SP1 CU3' WHEN T1.Client_Version0 = '5.00.8325.1000' THEN 'ConfigMgr Update 1511' WHEN T1.Client_Version0 = '5.00.8355.1000' THEN 'ConfigMgr Update 1602' WHEN T1.Client_Version0 = '5.00.8355.1306' THEN 'ConfigMgr Update 1602 UR1' WHEN T1.Client_Version0 = '5.00.8412.1007' THEN 'ConfigMgr Update 1606' WHEN T1.Client_Version0 = '5.00.8412.1307' THEN 'ConfigMgr Update 1606 UR1' ELSE T1.Client_Version0 END as 'Description', COUNT(T1.ResourceID) as 'Total', T1.ResourceID MachineId FROM v_R_System_Valid T1 GROUP BY T1.Client_Version0, T1.ResourceID ORDER BY Total DESC
/* MACHINE GENERATED FILE, DO NOT EDIT */ #include <jni.h> #include "extgl.h" typedef GL_APICALL void (GL_APIENTRY *<API key>) (GLenum target, GLsizei levels, GLenum internalformat, GLsizei width); typedef GL_APICALL void (GL_APIENTRY *<API key>) (GLenum target, GLsizei levels, GLenum internalformat, GLsizei width, GLsizei height); typedef GL_APICALL void (GL_APIENTRY *<API key>) (GLenum target, GLsizei levels, GLenum internalformat, GLsizei width, GLsizei height, GLsizei depth); typedef GL_APICALL void (GL_APIENTRY *<API key>) (GLuint texture, GLenum target, GLsizei levels, GLenum internalformat, GLsizei width); typedef GL_APICALL void (GL_APIENTRY *<API key>) (GLuint texture, GLenum target, GLsizei levels, GLenum internalformat, GLsizei width, GLsizei height); typedef GL_APICALL void (GL_APIENTRY *<API key>) (GLuint texture, GLenum target, GLsizei levels, GLenum internalformat, GLsizei width, GLsizei height, GLsizei depth); static <API key> glTexStorage1DEXT; static <API key> glTexStorage2DEXT; static <API key> glTexStorage3DEXT; static <API key> <API key>; static <API key> <API key>; static <API key> <API key>; static void JNICALL <API key>(JNIEnv *env, jclass clazz, jint target, jint levels, jint internalformat, jint width) { glTexStorage1DEXT(target, levels, internalformat, width); } static void JNICALL <API key>(JNIEnv *env, jclass clazz, jint target, jint levels, jint internalformat, jint width, jint height) { glTexStorage2DEXT(target, levels, internalformat, width, height); } static void JNICALL <API key>(JNIEnv *env, jclass clazz, jint target, jint levels, jint internalformat, jint width, jint height, jint depth) { glTexStorage3DEXT(target, levels, internalformat, width, height, depth); } static void JNICALL <API key>(JNIEnv *env, jclass clazz, jint texture, jint target, jint levels, jint internalformat, jint width) { <API key>(texture, target, levels, internalformat, width); } static void JNICALL <API key>(JNIEnv *env, jclass clazz, jint texture, jint target, jint levels, jint internalformat, jint width, jint height) { <API key>(texture, target, levels, internalformat, width, height); } static void JNICALL <API key>(JNIEnv *env, jclass clazz, jint texture, jint target, jint levels, jint internalformat, jint width, jint height, jint depth) { <API key>(texture, target, levels, internalformat, width, height, depth); } JNIEXPORT void JNICALL <API key>(JNIEnv *env, jclass clazz) { <API key> functions[] = { {"nglTexStorage1DEXT", "(IIII)V", (void *)&<API key>, "glTexStorage1DEXT", (void *)&glTexStorage1DEXT, false}, {"nglTexStorage2DEXT", "(IIIII)V", (void *)&<API key>, "glTexStorage2DEXT", (void *)&glTexStorage2DEXT, false}, {"nglTexStorage3DEXT", "(IIIIII)V", (void *)&<API key>, "glTexStorage3DEXT", (void *)&glTexStorage3DEXT, false}, {"<API key>", "(IIIII)V", (void *)&<API key>, "<API key>", (void *)&<API key>, false}, {"<API key>", "(IIIIII)V", (void *)&<API key>, "<API key>", (void *)&<API key>, false}, {"<API key>", "(IIIIIII)V", (void *)&<API key>, "<API key>", (void *)&<API key>, false} }; int num_functions = NUMFUNCTIONS(functions); <API key>(env, clazz, num_functions, functions); }
package im.actor.core.entity; import com.google.j2objc.annotations.Property; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import java.io.IOException; import java.util.ArrayList; import java.util.List; import im.actor.core.api.ApiAvatar; import im.actor.core.api.ApiBotCommand; import im.actor.core.api.ApiContactRecord; import im.actor.core.api.ApiContactType; import im.actor.core.api.ApiFullUser; import im.actor.core.api.ApiInt32Value; import im.actor.core.api.ApiMapValue; import im.actor.core.api.ApiMapValueItem; import im.actor.core.api.ApiUser; import im.actor.runtime.bser.BserCreator; import im.actor.runtime.bser.BserValues; import im.actor.runtime.bser.BserWriter; import im.actor.runtime.storage.KeyValueItem; // Disabling Bounds checks for speeding up calculations /*-[ #define <API key> 1 ]-*/ public class User extends WrapperExtEntity<ApiFullUser, ApiUser> implements KeyValueItem { private static final int RECORD_ID = 10; private static final int RECORD_FULL_ID = 20; public static BserCreator<User> CREATOR = User::new; @Property("readonly, nonatomic") private int uid; @Property("readonly, nonatomic") private long accessHash; @NotNull @Property("readonly, nonatomic") @SuppressWarnings("NullableProblems") private String name; @Nullable @Property("readonly, nonatomic") private String localName; @Nullable @Property("readonly, nonatomic") private String username; @Nullable @Property("readonly, nonatomic") private String about; @Nullable @Property("readonly, nonatomic") private Avatar avatar; @NotNull @Property("readonly, nonatomic") @SuppressWarnings("NullableProblems") private Sex sex; @Property("readonly, nonatomic") private boolean isBot; @NotNull @Property("readonly, nonatomic") @SuppressWarnings("NullableProblems") private List<ContactRecord> records; @Property("readonly, nonatomic") private boolean isBlocked; @Nullable @Property("readonly, nonatomic") private String timeZone; @Property("readonly, nonatomic") private boolean isVerified; @Property("readonly, nonatomic") private List<BotCommand> commands; @NotNull @Property("readonly, nonatomic") private boolean haveExtension; public User(@NotNull ApiUser wrappedUser, @Nullable ApiFullUser ext) { super(RECORD_ID, RECORD_FULL_ID, wrappedUser, ext); } public User(@NotNull byte[] data) throws IOException { super(RECORD_ID, RECORD_FULL_ID, data); } private User() { super(RECORD_ID, RECORD_FULL_ID); } @NotNull public Peer peer() { return new Peer(PeerType.PRIVATE, uid); } public int getUid() { return uid; } public long getAccessHash() { return accessHash; } @NotNull public String getServerName() { return name; } @Nullable public String getLocalName() { return localName; } @NotNull public String getName() { if (localName == null) { return name; } else { return localName; } } @Nullable public String getNick() { return username; } @Nullable public String getAbout() { return about; } @Nullable public Avatar getAvatar() { return avatar; } @NotNull public Sex getSex() { return sex; } public boolean isHaveExtension() { return haveExtension; } @NotNull public List<ContactRecord> getRecords() { return records; } public boolean isBot() { return isBot; } public List<BotCommand> getCommands() { return commands; } public boolean isBlocked() { return isBlocked; } @Nullable public String getTimeZone() { return timeZone; } public boolean isVerified() { return isVerified; } public User editName(@NotNull String name) { ApiUser w = getWrapped(); ApiUser res = new ApiUser( w.getId(), w.getAccessHash(), name, w.getLocalName(), w.getNick(), w.getSex(), w.getAvatar(), w.isBot(), w.getExt()); res.setUnmappedObjects(w.getUnmappedObjects()); return new User(res, getWrappedExt()); } public User editLocalName(@NotNull String localName) { ApiUser w = getWrapped(); ApiUser res = new ApiUser( w.getId(), w.getAccessHash(), w.getName(), localName, w.getNick(), w.getSex(), w.getAvatar(), w.isBot(), w.getExt()); res.setUnmappedObjects(w.getUnmappedObjects()); return new User(res, getWrappedExt()); } public User editNick(@Nullable String nick) { ApiUser w = getWrapped(); ApiUser res = new ApiUser( w.getId(), w.getAccessHash(), w.getName(), w.getLocalName(), nick, w.getSex(), w.getAvatar(), w.isBot(), w.getExt()); res.setUnmappedObjects(w.getUnmappedObjects()); return new User(res, getWrappedExt()); } public User editExt(@Nullable ApiMapValue ext) { ApiUser w = getWrapped(); ApiUser res = new ApiUser( w.getId(), w.getAccessHash(), w.getName(), w.getLocalName(), w.getNick(), w.getSex(), w.getAvatar(), w.isBot(), ext); res.setUnmappedObjects(w.getUnmappedObjects()); return new User(res, getWrappedExt()); } public User editAvatar(@Nullable ApiAvatar avatar) { ApiUser w = getWrapped(); ApiUser res = new ApiUser( w.getId(), w.getAccessHash(), w.getName(), w.getLocalName(), w.getNick(), w.getSex(), avatar, w.isBot(), w.getExt()); res.setUnmappedObjects(w.getUnmappedObjects()); return new User(res, getWrappedExt()); } public User updateExt(@Nullable ApiFullUser ext) { return new User(getWrapped(), ext); } public User editAbout(@Nullable String about) { ApiFullUser ext = getWrappedExt(); if (ext != null) { ApiFullUser upd = new ApiFullUser( ext.getId(), ext.getContactInfo(), about, ext.<API key>(), ext.getTimeZone(), ext.getBotCommands(), ext.getExt(), ext.isBlocked() ); return new User(getWrapped(), upd); } else { return this; } } public User <API key>(List<String> preferredLanguages) { ApiFullUser ext = getWrappedExt(); if (ext != null) { ApiFullUser upd = new ApiFullUser( ext.getId(), ext.getContactInfo(), ext.getAbout(), preferredLanguages, ext.getTimeZone(), ext.getBotCommands(), ext.getExt(), ext.isBlocked() ); return new User(getWrapped(), upd); } else { return this; } } public User editTimeZone(String timeZone) { ApiFullUser ext = getWrappedExt(); if (ext != null) { ApiFullUser upd = new ApiFullUser( ext.getId(), ext.getContactInfo(), ext.getAbout(), ext.<API key>(), timeZone, ext.getBotCommands(), ext.getExt(), ext.isBlocked() ); return new User(getWrapped(), upd); } else { return this; } } public User editContacts(List<ApiContactRecord> contacts) { ApiFullUser ext = getWrappedExt(); if (ext != null) { ApiFullUser upd = new ApiFullUser( ext.getId(), contacts, ext.getAbout(), ext.<API key>(), ext.getTimeZone(), ext.getBotCommands(), ext.getExt(), ext.isBlocked() ); return new User(getWrapped(), upd); } else { return this; } } public User editBotCommands(List<ApiBotCommand> commands) { ApiFullUser ext = getWrappedExt(); if (ext != null) { ApiFullUser upd = new ApiFullUser( ext.getId(), ext.getContactInfo(), ext.getAbout(), ext.<API key>(), ext.getTimeZone(), commands, ext.getExt(), ext.isBlocked() ); return new User(getWrapped(), upd); } else { return this; } } public User editFullExt(ApiMapValue extv) { ApiFullUser ext = getWrappedExt(); if (ext != null) { ApiFullUser upd = new ApiFullUser( ext.getId(), ext.getContactInfo(), ext.getAbout(), ext.<API key>(), ext.getTimeZone(), ext.getBotCommands(), extv, ext.isBlocked() ); return new User(getWrapped(), upd); } else { return this; } } public User editBlocked(boolean isBlocked) { ApiFullUser ext = getWrappedExt(); if (ext != null) { ApiFullUser upd = new ApiFullUser( ext.getId(), ext.getContactInfo(), ext.getAbout(), ext.<API key>(), ext.getTimeZone(), ext.getBotCommands(), ext.getExt(), isBlocked ); return new User(getWrapped(), upd); } else { return this; } } @Override protected void applyWrapped(@NotNull ApiUser wrapped, @Nullable ApiFullUser ext) { this.uid = wrapped.getId(); this.accessHash = wrapped.getAccessHash(); this.name = wrapped.getName(); this.localName = wrapped.getLocalName(); if (wrapped.getNick() != null && wrapped.getNick().length() > 0) { this.username = wrapped.getNick(); } else { this.username = null; } if (wrapped.getAvatar() != null) { this.avatar = new Avatar(wrapped.getAvatar()); } this.isBot = false; if (wrapped.isBot() != null) { this.isBot = wrapped.isBot(); } this.sex = Sex.UNKNOWN; if (wrapped.getSex() != null) { switch (wrapped.getSex()) { case FEMALE: this.sex = Sex.FEMALE; break; case MALE: this.sex = Sex.MALE; break; } } if (wrapped.getExt() != null) { this.isVerified = true; for (ApiMapValueItem i : wrapped.getExt().getItems()) { if ("is_verified".equals(i.getKey())) { if (i.getValue() instanceof ApiInt32Value) { this.isVerified = ((ApiInt32Value) i.getValue()).getValue() > 0; } } } } // Extension if (ext != null) { this.haveExtension = true; this.records = new ArrayList<>(); this.commands = new ArrayList<BotCommand>(); if (ext.isBlocked() != null) { this.isBlocked = ext.isBlocked(); } else { this.isBlocked = false; } this.timeZone = ext.getTimeZone(); for (ApiContactRecord record : ext.getContactInfo()) { if (record.getType() == ApiContactType.PHONE) { this.records.add(new ContactRecord(ContactRecordType.PHONE, record.getTypeSpec(), "" + record.getLongValue(), record.getTitle(), record.getSubtitle())); } else if (record.getType() == ApiContactType.EMAIL) { this.records.add(new ContactRecord(ContactRecordType.EMAIL, record.getTypeSpec(), record.getStringValue(), record.getTitle(), record.getSubtitle())); } else if (record.getType() == ApiContactType.WEB) { this.records.add(new ContactRecord(ContactRecordType.WEB, record.getTypeSpec(), record.getStringValue(), record.getTitle(), record.getSubtitle())); } else if (record.getType() == ApiContactType.SOCIAL) { this.records.add(new ContactRecord(ContactRecordType.SOCIAL, record.getTypeSpec(), record.getStringValue(), record.getTitle(), record.getSubtitle())); } } //Bot commands for (ApiBotCommand command : ext.getBotCommands()) { commands.add(new BotCommand(command.getSlashCommand(), command.getDescription(), command.getLocKey())); } this.about = ext.getAbout(); } else { this.isBlocked = false; this.haveExtension = false; this.records = new ArrayList<>(); this.commands = new ArrayList<BotCommand>(); this.about = null; this.timeZone = null; } } @Override public void parse(BserValues values) throws IOException { // Is Wrapper Layout if (values.getBool(8, false)) { // Parse wrapper layout super.parse(values); } else { // Convert old layout throw new IOException("Unsupported obsolete format"); } } @Override public void serialize(BserWriter writer) throws IOException { // Mark as wrapper layout writer.writeBool(8, true); // Serialize wrapper layout super.serialize(writer); } @Override public long getEngineId() { return getUid(); } @Override @NotNull protected ApiUser createInstance() { return new ApiUser(); } @Override protected ApiFullUser createExtInstance() { return new ApiFullUser(); } }
<?xml version="1.0" encoding="UTF-8"?> <tileset name="Canalave Gym Set" firstgid="1" tilewidth="16" tileheight="16"> <image source="Canalave Gym Set.png" trans="000000"/> </tileset>
#import "NGLRuntime.h" #import "NGLError.h" #import "NGLIterator.h" /*! * <strong>(Internal only)</strong> An object that holds the array values. * * This structure is used as a fixed pointer to preserve the necessary information/memory * to the array values. * * @var NGLArrayValues::pointers * The pointers array. * * @var NGLArrayValues::count * The count/length of the array. * * @var NGLArrayValues::retainOption * The retain option. This value can't be changed outside the initialization. * * @var NGLArrayValues::iterator * The iterator pointer. * * @var NGLArrayValues::i * The iterator index. */ typedef struct { void **pointers; unsigned int count; unsigned int capacity; BOOL retainOption; void **iterator; unsigned int i; } NGLArrayValues; /*! * Extremelly fast loop to work with NGLArray. This loop is slower than NSFastEnumeration, * about 50% slower. However it accepts mutations during the loop and can work with * any kind of data type (Objective-C or standard C). * * The syntax is a little bit different than the traditional forin loop: * * <pre> * * id variable; * * nglFor (variable, myNGLArray) * { * // Do something... * } * * </pre> * * @param p * A pointer that will receive the values. * * @param a * The NGLArray instance to loop through. */ #define nglFor(p, a)\ for(NGLArrayValues *v = [(((a) != nil) ? (a) : [NGLArray array]) forLoop:(void **)&(p)];\ (*v).i < (*v).count;\ (*v).i++, (p) = *(*v).iterator++) /*! * Checks if a pointer is valid or not, that means, if a pointer is really pointing to * a valid object (not released nor deallocated). * * @param pointer * A C pointer to check. * * @result A BOOL indicating if the pointer is valid or not. */ NGL_API BOOL nglPointerIsValid(void *pointer); /*! * Checks if a pointer is valid for a specific kind of class. * * To check the validation against any kind of classes, use the #nglPointerIsValid#. * * @param pointer * A C pointer to check. * * @param aClass * An Objective-C class. * * @result A BOOL indicating if the pointer is valid or not. */ NGL_API BOOL <API key>(void *pointer, Class aClass); /*! * Checks if a pointer is valid for a specific protocol. * * This function will return NO if the pointer is released, deallocated, or just doesn't * conform to the informed protocol. * * @param pointer * A C pointer to check. * * @param aProtocol * An Objective-C class. * * @result A BOOL indicating if the pointer is valid or not. */ NGL_API BOOL <API key>(void *pointer, Protocol *aProtocol); /*! * Checks if a pointer is valid and responds to a selector. * * This function will return NO if the pointer is released, deallocated, or just doesn't * conform to the informed protocol. * * @param pointer * A C pointer to check. * * @param selector * An Objective-C selector. * * @result A BOOL indicating if the pointer is valid or not. */ NGL_API BOOL <API key>(void *pointer, SEL selector); /*! * This class is a collection that works just like an array, however it's generic for * any kind of data type, including basic C types. NGLArray does not retain * the object. * * This class is faster than the traditional NSArray. Depending on the tasks, NGLArray * can be 50% faster than NSArray, the most expensive task of NGLArray is at least * 15% faster than NSArray, which is "removeAll". Actually, this class is more like a * NSMutableArray, because you can change its collection at any time. This one also has * a "hint" property called capacity, if you already know the maximum number of elements * you can set this property to boost the performance a little bit more. * * By default, every time you try to insert an item in this array and it's capacity is * full, a new block of 10 items will be allocated into this array. * * The reasons that cause this one to be faster than NSArray are: * * - It basically work with pointers and dereference, instead of indices. * - It has an internal iterator loop that manages the enumerations. * - It doesn't have many too checks. NGLArray assumes you know what you're doing. * * The achieve the best performance and still flexible, the NGLArray offers three kind * of loops. Each one has its own cost and benefits: * * - <b>NGLIterator</b>: <i>Loops through 100 millions in 1.5 seg</i>.<br /> * Uses NGLIterator protocol. This loop is good for small array in which you * need to change it's content during the loop or even from another thread. * This routine offers a way to reset the loop at any time by calling the * <code>resetIterator</code> method. * The disadvantage of this routine is that it makes a Objective-C message call * at each loop cycle, so it's a little expensive compared to the other ones. * Its syntax is: * * <pre> * * id variable; * while ((variable = [myNGLArray nextIterator])) * { * // Do something... * } * * </pre> * * - <b>NGLFor</b>: <i>Loops through 100 millions in 0.45 seg</i>.<br /> * Very fast loop using the iterator properties. Can deal with changes during * the loop or even from another thread. * Its disadvantage is that it has a special syntax and just resets the iterator * loop at the beginning. So if you're planning to use the <b>NGLIterator</b> after * use this one, you must call <code>resetIterator</code> before start the * <b>NGLIterator</b>. Its syntax is: * * <pre> * * id variable; * nglFor (variable, myNGLArray) * { * // Do something... * } * * </pre> * * - <b>ForEach</b>: <i>Loops through 100 millions in 0.3 seg</i>.<br /> * Uses NSFastEnumeration protocol (the Cocoa "for in" loop). This loop is the * fastest one. However it's be used only in few situations. * Its disadvantage is that it only work with Objective-C objects and the array * can't be changed during the loop (changing the array during the loop will * result in runtime error). * Its syntax is: * * <pre> * * id variable; * for (variable in myNGLArray) * { * // Do something... * } * * </pre> * * The NGLArray class also provides a pointer to the items and a pointer to the * mutations property. You can use them to implement your own NSFastEnumeration. */ @interface NGLArray : NSObject <NGLIterator, NSFastEnumeration> { @private NGLArrayValues _values; } /*! * The capacity property is not the size/count of the array, it's just a "hint" to optimize * the array manipulation spped. This "hint" is useful for large array (above 10 items). * * The NGLArray will allocate the memory in sets/packages using this "hint" property. */ @property (nonatomic) unsigned int capacity; /*! * Indicates if this array will retain or not the objects in it. This property can't be * changed to ensure the integrity of the items and must be set when initializing this * array. Only Objective-C objects can receive retain messages. */ @property (nonatomic, readonly) BOOL retainOption; /*! * Returns the items pointer. This property is useful if you want to create your own * implementation of NSFastEnumeration but keep using NGLArray as your collection. * * Remember that NSFastEnumeration is exclusive for Objective-C objects. */ @property (nonatomic, readonly) NGL_ARC_ASSIGN id *itemsPointer; /*! * Returns the mutations pointer. This property is useful if you want to create your own * implementation of NSFastEnumeration but keep using NGLArray as your collection. * * Remember that NSFastEnumeration is exclusive for Objective-C objects. */ @property (nonatomic, readonly) unsigned long *mutationsPointer; /*! * <strong>(Internal only)</strong> Returns a pointer to the array values. * You should not call this method directly. */ @property (nonatomic, readonly) NGLArrayValues *values; /*! * Initiates a NGLArray making it a safe collection, that means, it will retain every * pointer that will be added to it. In this case, all pointer must be a subclass * of NSObject. * * The retained objects will receive a release message when they are removed or this * instance of NGLArray is released. * * @result A NGLArray instance. */ - (id) <API key>; /*! * Initiates a NGLArray instance based on another NGLArray. * * This method copies all objects/instances inside the informed NGLArray. * * @param pointers * A NGLArray to serve as base to the new NGLArray. * * @result A NGLArray instance. */ - (id) initWithNGLArray:(NGLArray *)pointers; /*! * Initiates a NGLArray instance based on many object/instances. * * This method doesn't make use of addPointerOnce, that means if a target is informed * more than one time, it will remain duplicated inside this collection. * * @param first * The first object/instance to be added. * * @param ... * A sequence of objects/instances separated by commas. This method must end with * a <code>nil</code> element. * * @result A NGLArray instance. */ - (id) initWithPointers:(void *)first, ... <API key>; /*! * Adds a new object/instance to this collection. If the target already exist in this * collection, it will be added again, resulting in a duplication. * * @param pointer * The target it self. */ - (void) addPointer:(void *)pointer; /*! * Adds a new object/instance to this collection only if the target is not already inside * this collection. If the target already exist, nothing will happen. * * @param pointer * The target it self. */ - (void) addPointerOnce:(void *)pointer; /*! * Adds all object/instance to this collection from another NGLArray. * This method copies all objects/instances inside the informed NGLArray. * * @param pointers * The NGLArray instance to copy pointers from. */ - (void) <API key>:(NGLArray *)pointers; /*! * Returns the index of a target inside this collection. * * @param pointer * The target it self. * * @result Returns the index of the target or NGL_NOT_FOUND if the target was not found. */ - (unsigned int) indexOfPointer:(void *)pointer; /*! * Checks if a target is inside this collection. * * @param pointer * The target it self. * * @result Returns YES (1) if the target is found, otherwise NO (0) will be returned. */ - (BOOL) hasPointer:(void *)pointer; /*! * Removes an object/instance inside this collection. * * @param pointer * The target it self. */ - (void) removePointer:(void *)pointer; /*! * Removes an object/instance in a specific position inside this collection. * * @param index * The index of the target. If the index is out of bounds, nothing will happen. */ - (void) <API key>:(unsigned int)index; /*! * Removes the very first object/instance in this collection. */ - (void) removeFirst; /*! * Removes the very last object/instance in this collection. */ - (void) removeLast; /*! * Removes all the instances inside this library. * * This method makes a clean up inside this library, freeing all allocated * memories to the instances in it. */ - (void) removeAll; /*! * Returns an object/instance in a specific position inside this collection. * * @param index * The index of the target. If the index is out of bounds, NULL will be returned. * * @result A pointer or NULL if no result was found. */ - (void *) pointerAtIndex:(unsigned int)index; /*! * Returns the number of instances in this library at the moment. * * @result An int data type. */ - (unsigned int) count; /*! * <strong>(Internal only)</strong> Prepares this array to work with "nglFor" loop. * You should not call this method directly. * * @param target * A pointer to the target that will receive the items of this array. Inside this * method the target will receive the first item. * * @result A pointer to the values of this array. */ - (NGLArrayValues *) forLoop:(void **)target; /*! * Returns an autoreleased instance of NGLArray. * * @result A NGLArray autoreleased instance. */ + (id) array; @end /*! * A category that extends the default behavior to perform some convenience method which * could help when other classes makes use of this one. */ @interface NGLArray(NGLArrayExtended) - (NSArray *) allPointers; /*! * A convenience method that loops through all objects making them perform a selector. * * IMPORTANT: This method assumes you're sure about this task and no additional check * will be made to identify if the objects can receive such message. So, make sure all * the objects are Objective-C instances and can receive the informed message. * * @param selector * The selector which will be performed on all objects. */ - (void) <API key>:(SEL)selector; @end
package api import ( "errors" "io/ioutil" "log" "net/http" "github.com/bitly/go-simplejson" ) func Request(req *http.Request) (*simplejson.Json, error) { resp, err := http.DefaultClient.Do(req) if err != nil { return nil, err } body, err := ioutil.ReadAll(resp.Body) resp.Body.Close() if err != nil { return nil, err } if resp.StatusCode != 200 { log.Printf("got response code %d - %s", resp.StatusCode, body) return nil, errors.New("api request returned non 200 status code") } data, err := simplejson.NewJson(body) if err != nil { return nil, err } return data, nil } func <API key>(url string, header http.Header) ( response *http.Response, err error) { req, err := http.NewRequest("GET", url, nil) if err != nil { return nil, errors.New("failed building request for " + url + ": " + err.Error()) } req.Header = header httpclient := &http.Client{} if response, err = httpclient.Do(req); err != nil { return nil, errors.New("request failed for " + url + ": " + err.Error()) } return }
md-radio-button.md-THEME_NAME-theme .md-off { border-color: '{{foreground-2}}'; } md-radio-button.md-THEME_NAME-theme .md-on { background-color: '{{accent-color-0.87}}'; } md-radio-button.md-THEME_NAME-theme.md-checked .md-off { border-color: '{{accent-color-0.87}}'; } md-radio-button.md-THEME_NAME-theme.md-checked .md-ink-ripple { color: '{{accent-color-0.87}}'; } md-radio-button.md-THEME_NAME-theme .md-container .md-ripple { color: '{{accent-A700}}'; } md-radio-group.md-THEME_NAME-theme:not([disabled]) .md-primary .md-on, md-radio-group.md-THEME_NAME-theme:not([disabled]).md-primary .md-on, md-radio-button.md-THEME_NAME-theme:not([disabled]) .md-primary .md-on, md-radio-button.md-THEME_NAME-theme:not([disabled]).md-primary .md-on { background-color: '{{primary-color-0.87}}'; } md-radio-group.md-THEME_NAME-theme:not([disabled]) .md-primary .md-checked .md-off, md-radio-group.md-THEME_NAME-theme:not([disabled]) .md-primary.md-checked .md-off, md-radio-group.md-THEME_NAME-theme:not([disabled]).md-primary .md-checked .md-off, md-radio-group.md-THEME_NAME-theme:not([disabled]).md-primary.md-checked .md-off, md-radio-button.md-THEME_NAME-theme:not([disabled]) .md-primary .md-checked .md-off, md-radio-button.md-THEME_NAME-theme:not([disabled]) .md-primary.md-checked .md-off, md-radio-button.md-THEME_NAME-theme:not([disabled]).md-primary .md-checked .md-off, md-radio-button.md-THEME_NAME-theme:not([disabled]).md-primary.md-checked .md-off { border-color: '{{primary-color-0.87}}'; } md-radio-group.md-THEME_NAME-theme:not([disabled]) .md-primary .md-checked .md-ink-ripple, md-radio-group.md-THEME_NAME-theme:not([disabled]) .md-primary.md-checked .md-ink-ripple, md-radio-group.md-THEME_NAME-theme:not([disabled]).md-primary .md-checked .md-ink-ripple, md-radio-group.md-THEME_NAME-theme:not([disabled]).md-primary.md-checked .md-ink-ripple, md-radio-button.md-THEME_NAME-theme:not([disabled]) .md-primary .md-checked .md-ink-ripple, md-radio-button.md-THEME_NAME-theme:not([disabled]) .md-primary.md-checked .md-ink-ripple, md-radio-button.md-THEME_NAME-theme:not([disabled]).md-primary .md-checked .md-ink-ripple, md-radio-button.md-THEME_NAME-theme:not([disabled]).md-primary.md-checked .md-ink-ripple { color: '{{primary-color-0.87}}'; } md-radio-group.md-THEME_NAME-theme:not([disabled]) .md-primary .md-container .md-ripple, md-radio-group.md-THEME_NAME-theme:not([disabled]).md-primary .md-container .md-ripple, md-radio-button.md-THEME_NAME-theme:not([disabled]) .md-primary .md-container .md-ripple, md-radio-button.md-THEME_NAME-theme:not([disabled]).md-primary .md-container .md-ripple { color: '{{primary-600}}'; } md-radio-group.md-THEME_NAME-theme:not([disabled]) .md-warn .md-on, md-radio-group.md-THEME_NAME-theme:not([disabled]).md-warn .md-on, md-radio-button.md-THEME_NAME-theme:not([disabled]) .md-warn .md-on, md-radio-button.md-THEME_NAME-theme:not([disabled]).md-warn .md-on { background-color: '{{warn-color-0.87}}'; } md-radio-group.md-THEME_NAME-theme:not([disabled]) .md-warn .md-checked .md-off, md-radio-group.md-THEME_NAME-theme:not([disabled]) .md-warn.md-checked .md-off, md-radio-group.md-THEME_NAME-theme:not([disabled]).md-warn .md-checked .md-off, md-radio-group.md-THEME_NAME-theme:not([disabled]).md-warn.md-checked .md-off, md-radio-button.md-THEME_NAME-theme:not([disabled]) .md-warn .md-checked .md-off, md-radio-button.md-THEME_NAME-theme:not([disabled]) .md-warn.md-checked .md-off, md-radio-button.md-THEME_NAME-theme:not([disabled]).md-warn .md-checked .md-off, md-radio-button.md-THEME_NAME-theme:not([disabled]).md-warn.md-checked .md-off { border-color: '{{warn-color-0.87}}'; } md-radio-group.md-THEME_NAME-theme:not([disabled]) .md-warn .md-checked .md-ink-ripple, md-radio-group.md-THEME_NAME-theme:not([disabled]) .md-warn.md-checked .md-ink-ripple, md-radio-group.md-THEME_NAME-theme:not([disabled]).md-warn .md-checked .md-ink-ripple, md-radio-group.md-THEME_NAME-theme:not([disabled]).md-warn.md-checked .md-ink-ripple, md-radio-button.md-THEME_NAME-theme:not([disabled]) .md-warn .md-checked .md-ink-ripple, md-radio-button.md-THEME_NAME-theme:not([disabled]) .md-warn.md-checked .md-ink-ripple, md-radio-button.md-THEME_NAME-theme:not([disabled]).md-warn .md-checked .md-ink-ripple, md-radio-button.md-THEME_NAME-theme:not([disabled]).md-warn.md-checked .md-ink-ripple { color: '{{warn-color-0.87}}'; } md-radio-group.md-THEME_NAME-theme:not([disabled]) .md-warn .md-container .md-ripple, md-radio-group.md-THEME_NAME-theme:not([disabled]).md-warn .md-container .md-ripple, md-radio-button.md-THEME_NAME-theme:not([disabled]) .md-warn .md-container .md-ripple, md-radio-button.md-THEME_NAME-theme:not([disabled]).md-warn .md-container .md-ripple { color: '{{warn-600}}'; } md-radio-group.md-THEME_NAME-theme[disabled], md-radio-button.md-THEME_NAME-theme[disabled] { color: '{{foreground-3}}'; } md-radio-group.md-THEME_NAME-theme[disabled] .md-container .md-off, md-radio-button.md-THEME_NAME-theme[disabled] .md-container .md-off { border-color: '{{foreground-3}}'; } md-radio-group.md-THEME_NAME-theme[disabled] .md-container .md-on, md-radio-button.md-THEME_NAME-theme[disabled] .md-container .md-on { border-color: '{{foreground-3}}'; } md-radio-group.md-THEME_NAME-theme .md-checked .md-ink-ripple { color: '{{accent-color-0.26}}'; } md-radio-group.md-THEME_NAME-theme.md-primary .md-checked:not([disabled]) .md-ink-ripple, md-radio-group.md-THEME_NAME-theme .md-checked:not([disabled]).md-primary .md-ink-ripple { color: '{{primary-color-0.26}}'; } md-radio-group.md-THEME_NAME-theme .md-checked.md-primary .md-ink-ripple { color: '{{warn-color-0.26}}'; } md-radio-group.md-THEME_NAME-theme.md-focused:not(:empty) .md-checked .md-container:before { background-color: '{{accent-color-0.26}}'; } md-radio-group.md-THEME_NAME-theme.md-focused:not(:empty).md-primary .md-checked .md-container:before, md-radio-group.md-THEME_NAME-theme.md-focused:not(:empty) .md-checked.md-primary .md-container:before { background-color: '{{primary-color-0.26}}'; } md-radio-group.md-THEME_NAME-theme.md-focused:not(:empty).md-warn .md-checked .md-container:before, md-radio-group.md-THEME_NAME-theme.md-focused:not(:empty) .md-checked.md-warn .md-container:before { background-color: '{{warn-color-0.26}}'; }
require 'net/http' ## monkey-patch Net::HTTP # Certain apple endpoints return 415 responses if a Content-Type is supplied. # Net::HTTP will default a content-type if none is provided by faraday # This monkey-patch allows us to leave out the content-type if we do not specify one. class Net::HTTPGenericRequest def <API key> return if content_type() end end
<?php namespace spec\SensioLabs\Behat\PageObjectExtension\PageObject\Factory; require_once __DIR__.'/Fixtures/ArticleList.php'; use PhpSpec\ObjectBehavior; use Prophecy\Argument; use ProxyManager\Factory\<API key>; use ProxyManager\Proxy\<API key>; use SensioLabs\Behat\PageObjectExtension\PageObject\Element; use SensioLabs\Behat\PageObjectExtension\PageObject\Factory; use SensioLabs\Behat\PageObjectExtension\PageObject\InlineElement; use SensioLabs\Behat\PageObjectExtension\PageObject\Page; use SensioLabs\Behat\PageObjectExtension\PageObject\PageObject; class LazyFactorySpec extends ObjectBehavior { function let(Factory $decoratedFactory) { $this->beConstructedWith($decoratedFactory, new <API key>()); } function <API key>() { $this->shouldHaveType('SensioLabs\Behat\PageObjectExtension\PageObject\Factory'); } function <API key>(Factory $decoratedFactory, Page $page) { $decoratedFactory->createPage('ArticleList')->willReturn($page); $this->createPage('ArticleList')->shouldReturn($page); } function <API key>(Factory $decoratedFactory, Element $element) { $decoratedFactory->createElement('Foo')->willReturn($element); $this->createElement('Foo')->shouldReturn($element); } function <API key>(Factory $decoratedFactory, InlineElement $element) { $decoratedFactory->createInlineElement('.foo')->willReturn($element); $this->createInlineElement('.foo')->shouldReturn($element); } function <API key>() { $this->create('ArticleList')-><API key>('ProxyManager\Proxy\<API key>'); } function <API key>(PageObject $pageObject, Factory $decoratedFactory) { $decoratedFactory->create('ArticleList')->willReturn($pageObject); $this->create('ArticleList')-><API key>('ProxyManager\Proxy\ProxyInterface'); } }
{{ define "main" }} {{ partial "breadcrumbs" . }} <section class="resume-section p-3 p-lg-5 d-flex d-column content"> <div class="my-auto"> <h2 class="mb-0"><span class="text-primary">{{ .Title }}</span></h2> <p><a href="{{ .Params.link }}">Link to full {{ .Params.pubtype }}</a></p> {{ with .Params.image }}<img src="{{ . }}" style="max-height:300px;max-width:30%;" align="right"/>{{ end }} {{ .Content }} <p class="mt-3"> {{ partial "techtags" . }} </p> </div> </section> {{ end }}
{{diagnostic}} <div class="aw-ui-callout aw-ui-callout-info"> <span>Please see below all the price set for various Asha Payment Activities.</span> </div> <form class="form-horizontal" #rulesForm="ngForm" (ngSubmit)="onSubmit(ruleForm.value)" method="POST"> <div> <h2>Maternal Health</h2> <h3>ANC Checkups</h3> <div class="form-group"> <label for="101" class="col-sm-4 control-label">No. of Registration during the first trimester of pregnancy at</label> <div class="col-sm-2"> <div class="input-group"> <span class="input-group-addon" id="addon-101-R"><i class="fa fa-inr"></i></span> <input id="101_R" class="form-control" type="text" aria-describedby="addon-101-R" [(ngModel)]="model.R_101" name="R_101" #name="ngModel"> </div> </div> <div class="col-sm-2"> <div class="input-group"> <span class="input-group-addon" id="addon-101-U"><i class="fa fa-inr"></i></span> <input id="101_U" class="form-control" type="text" aria-describedby="addon-101-U" [(ngModel)]="model.U_101" name="U_101" #name="ngModel"> </div> </div> <div class="col-sm-2"> <textarea id="101_H" class="form-control" row="1" [(ngModel)]="model.H_101" name="H_101" #name="ngModel"></textarea> </div> </div> <div class="form-group"> <label for="102" class="col-sm-4 control-label">No. of 1st check up</label> <div class="col-sm-2"> <div class="input-group"> <span class="input-group-addon" id="addon-102-R"><i class="fa fa-inr"></i></span> <input id="102_R" class="form-control" type="" aria-describedby="addon-102-R" [(ngModel)]="model.R_102" name="R_102" #name="ngModel"> </div> </div> <div class="col-sm-2"> <div class="input-group"> <span class="input-group-addon" id="addon-102-U"><i class="fa fa-inr"></i></span> <input id="102_U" class="form-control" type="" aria-describedby="addon-102-U" [(ngModel)]="model.U_102" name="U_102" #name="ngModel"> </div> </div> <div class="col-sm-2"> <textarea id="102_H" class="form-control" row="1" [(ngModel)]="model.H_102" name="H_102" #name="ngModel"></textarea> </div> </div> <div class="form-group"> <label for="103" class="col-sm-4 control-label">No. of 2 nd check up </label> <div class="col-sm-2"> <div class="input-group"> <span class="input-group-addon" id="addon-103-R"><i class="fa fa-inr"></i></span> <input id="103_R" class="form-control" type="" aria-describedby="addon-103-R" [(ngModel)]="model.R_103" name="R_103" #name="ngModel"> </div> </div> <div class="col-sm-2"> <div class="input-group"> <span class="input-group-addon" id="addon-103-U"><i class="fa fa-inr"></i></span> <input id="103_U" class="form-control" type="" aria-describedby="addon-103-U" [(ngModel)]="model.U_103" name="U_103" #name="ngModel"> </div> </div> <div class="col-sm-2"> <textarea class="form-control" row="1" [(ngModel)]="model.H_103" name="R_102" #name="ngModel"></textarea> </div> </div> <div class="form-group"> <label for="104" class="col-sm-4 control-label">No. of 3 rd check up</label> <div class="col-sm-2"> <div class="input-group"> <span class="input-group-addon" id="addon-104-R"><i class="fa fa-inr"></i></span> <input id="104_R" class="form-control" type="" aria-describedby="addon-104-R"> </div> </div> <div class="col-sm-2"> <div class="input-group"> <span class="input-group-addon" id="addon-104-U"><i class="fa fa-inr"></i></span> <input id="104_U" class="form-control" type="" aria-describedby="addon-104-U"> </div> </div> <div class="col-sm-2"> <textarea class="form-control" row="1"></textarea> </div> </div> <div class="form-group"> <label for="105" class="col-sm-4 control-label">No. of 4 th check up by M.O</label> <div class="col-sm-2"> <div class="input-group"> <span class="input-group-addon" id="addon-105-R"><i class="fa fa-inr"></i></span> <input id="105_R" class="form-control" type="" aria-describedby="addon-105-R"> </div> </div> <div class="col-sm-2"> <div class="input-group"> <span class="input-group-addon" id="addon-105-U"><i class="fa fa-inr"></i></span> <input id="105_U" class="form-control" type="" aria-describedby="addon-105-U"> </div> </div> <div class="col-sm-2"> <textarea class="form-control" row="1"></textarea> </div> </div> <div class="form-group"> <label for="106" class="col-sm-4 control-label">No. of Deliveres conducted in PHC/Institutons</label> <div class="col-sm-2"> <div class="input-group"> <span class="input-group-addon" id="addon-106-R"><i class="fa fa-inr"></i></span> <input id="106_R" class="form-control" type="" aria-describedby="addon-106-R"> </div> </div> <div class="col-sm-2"> <div class="input-group"> <span class="input-group-addon" id="addon-106-U"><i class="fa fa-inr"></i></span> <input id="106_U" class="form-control" type="" aria-describedby="addon-106-U"> </div> </div> <div class="col-sm-2"> <textarea class="form-control" row="1"></textarea> </div> </div> <div class="form-group"> <label for="107" class="col-sm-4 control-label">No. of Maternal Death reported to Sub Centre</label> <div class="col-sm-2"> <div class="input-group"> <span class="input-group-addon" id="addon-107-R"><i class="fa fa-inr"></i></span> <input id="107_R" class="form-control" type="" aria-describedby="addon-107-R"> </div> </div> <div class="col-sm-2"> <div class="input-group"> <span class="input-group-addon" id="addon-107-U"><i class="fa fa-inr"></i></span> <input id="107_U" class="form-control" type="" aria-describedby="addon-107-U"> </div> </div> <div class="col-sm-2"> <textarea class="form-control" row="1"></textarea> </div> </div> </div> <div> <h2>Child Health</h2> <div class="form-group"> <label for="108" class="col-sm-4 control-label">Postnatal Visits (HBNC) (6 visits in Institutional Delivery, 7 Visits in Home Delivery)</label> <div class="col-sm-2"> <div class="input-group"> <span class="input-group-addon" id="addon-108-R"><i class="fa fa-inr"></i></span> <input id="108_R" class="form-control" type="" aria-describedby="addon-108-R"> </div> </div> <div class="col-sm-2"> <div class="input-group"> <span class="input-group-addon" id="addon-108-U"><i class="fa fa-inr"></i></span> <input id="108_U" class="form-control" type="" aria-describedby="addon-108-U"> </div> </div> <div class="col-sm-2"> <textarea class="form-control" row="1"></textarea> </div> </div> <div class="form-group"> <label for="109" class="col-sm-4 control-label">Rreferral & Follow up of SAM Cases to NRC</label> <div class="col-sm-2"> <div class="input-group"> <span class="input-group-addon" id="addon-109-R"><i class="fa fa-inr"></i></span> <input id="109_R" class="form-control" type="" aria-describedby="addon-109-R"> </div> </div> <div class="col-sm-2"> <div class="input-group"> <span class="input-group-addon" id="addon-109-U"><i class="fa fa-inr"></i></span> <input id="109_U" class="form-control" type="" aria-describedby="addon-109-U"> </div> </div> <div class="col-sm-2"> <textarea class="form-control" row="1"></textarea> </div> </div> <div class="form-group"> <label for="110" class="col-sm-4 control-label">Follow up of LBW babies (LBW Low Birth Weight Babies)</label> <div class="col-sm-2"> <div class="input-group"> <span class="input-group-addon" id="addon-110-R"><i class="fa fa-inr"></i></span> <input id="110_R" class="form-control" type="" aria-describedby="addon-110-R"> </div> </div> <div class="col-sm-2"> <div class="input-group"> <span class="input-group-addon" id="addon-110-U"><i class="fa fa-inr"></i></span> <input id="110_U" class="form-control" type="" aria-describedby="addon-110-U"> </div> </div> <div class="col-sm-2"> <textarea class="form-control" row="1"></textarea> </div> </div> <div class="form-group"> <label for="111" class="col-sm-4 control-label">Follow up of SNCU discharge babies</label> <div class="col-sm-2"> <div class="input-group"> <span class="input-group-addon" id="addon-111-R"><i class="fa fa-inr"></i></span> <input id="111_R" class="form-control" type="" aria-describedby="addon-111-R"> </div> </div> <div class="col-sm-2"> <div class="input-group"> <span class="input-group-addon" id="addon-111-U"><i class="fa fa-inr"></i></span> <input id="111_U" class="form-control" type="" aria-describedby="addon-111-U"> </div> </div> <div class="col-sm-2"> <textarea class="form-control" row="1"></textarea> </div> </div> <div class="form-group"> <label for="112" class="col-sm-4 control-label">Infant death reporting to Sub-centre and PHC</label> <div class="col-sm-2"> <div class="input-group"> <span class="input-group-addon" id="addon-112-R"><i class="fa fa-inr"></i></span> <input id="112_R" class="form-control" type="" aria-describedby="addon-112-R"> </div> </div> <div class="col-sm-2"> <div class="input-group"> <span class="input-group-addon" id="addon-112-U"><i class="fa fa-inr"></i></span> <input id="112_U" class="form-control" type="" aria-describedby="addon-112-U"> </div> </div> <div class="col-sm-2"> <textarea class="form-control" row="1"></textarea> </div> </div> <div class="form-group"> <label for="113" class="col-sm-4 control-label">Intesive Diarrhoea Control Programme</label> <div class="col-sm-2"> <div class="input-group"> <span class="input-group-addon" id="addon-113-R"><i class="fa fa-inr"></i></span> <input id="113_R" class="form-control" type="" aria-describedby="addon-113-R"> </div> </div> <div class="col-sm-2"> <div class="input-group"> <span class="input-group-addon" id="addon-113-U"><i class="fa fa-inr"></i></span> <input id="113_U" class="form-control" type="" aria-describedby="addon-113-U"> </div> </div> <div class="col-sm-2"> <textarea class="form-control" row="1"></textarea> </div> </div> </div> <div> <h2>Immunization</h2> <div class="form-group"> <label for="114" class="col-sm-4 control-label">Pulse Polio Booth Mobilization</label> <div class="col-sm-2"> <div class="input-group disabled"> <span class="input-group-addon" id="addon-114-R"><i class="fa fa-inr"></i></span> <input id="114_R" class="form-control" type="" aria-describedby="addon-114-R" disabled> </div> </div> <div class="col-sm-2"> <div class="input-group"> <span class="input-group-addon" id="addon-114-U"><i class="fa fa-inr"></i></span> <input id="114_U" class="form-control" type="" aria-describedby="addon-114-U" disabled> </div> </div> <div class="col-sm-2"> <textarea class="form-control" row="1"></textarea> </div> </div> <h3>Full Immunization</h3> <div class="form-group"> <label for="115" class="col-sm-4 control-label">Complete Immunization in 1st year of age</label> <div class="col-sm-2"> <div class="input-group"> <span class="input-group-addon" id="addon-115-R"><i class="fa fa-inr"></i></span> <input id="115_R" class="form-control" type="" aria-describedby="addon-115-R"> </div> </div> <div class="col-sm-2"> <div class="input-group"> <span class="input-group-addon" id="addon-115-U"><i class="fa fa-inr"></i></span> <input id="115U" class="form-control" type="" aria-describedby="addon-115-U"> </div> </div> <div class="col-sm-2"> <textarea class="form-control" row="1"></textarea> </div> </div> <div class="form-group"> <label for="116" class="col-sm-4 control-label">Full Immunization of 2nd year of age</label> <div class="col-sm-2"> <div class="input-group"> <span class="input-group-addon" id="addon-116-R"><i class="fa fa-inr"></i></span> <input id="116" class="form-control" type="" aria-describedby="addon-116-R"> </div> </div> <div class="col-sm-2"> <div class="input-group"> <span class="input-group-addon" id="addon-116-U"><i class="fa fa-inr"></i></span> <input id="116" class="form-control" type="" aria-describedby="addon-116-U"> </div> </div> <div class="col-sm-2"> <textarea class="form-control" row="1"></textarea> </div> </div> </div> <div> <h2>Family Planning</h2> <div class="form-group"> <label for="117" class="col-sm-4 control-label">No. of Counseling & Motivation of women for Tubectomy</label> <div class="col-sm-2"> <div class="input-group"> <span class="input-group-addon" id="addon-117-R"><i class="fa fa-inr"></i></span> <input id="117" class="form-control" type="" aria-describedby="addon-117-R"> </div> </div> <div class="col-sm-2"> <div class="input-group"> <span class="input-group-addon" id="addon-117-U"><i class="fa fa-inr"></i></span> <input id="117" class="form-control" type="" aria-describedby="addon-117-U"> </div> </div> <div class="col-sm-2"> <textarea class="form-control" row="1"></textarea> </div> </div> <div class="form-group"> <label for="118" class="col-sm-4 control-label">No. of Counseling & Motivation for men of Vasectomy</label> <div class="col-sm-2"> <div class="input-group"> <span class="input-group-addon" id="addon-118-R"><i class="fa fa-inr"></i></span> <input id="118" class="form-control" type="" aria-describedby="addon-118-R"> </div> </div> <div class="col-sm-2"> <div class="input-group"> <span class="input-group-addon" id="addon-118-U"><i class="fa fa-inr"></i></span> <input id="118" class="form-control" type="" aria-describedby="addon-118-U"> </div> </div> <div class="col-sm-2"> <textarea class="form-control" row="1"></textarea> </div> </div> <div class="form-group"> <label for="119" class="col-sm-4 control-label">Accompanying the beneficiary for PPIUCD</label> <div class="col-sm-2"> <div class="input-group"> <span class="input-group-addon" id="addon-119-R"><i class="fa fa-inr"></i></span> <input id="119" class="form-control" type="" aria-describedby="addon-119-R"> </div> </div> <div class="col-sm-2"> <div class="input-group"> <span class="input-group-addon" id="addon-119-U"><i class="fa fa-inr"></i></span> <input id="119" class="form-control" type="" aria-describedby="addon-119-U"> </div> </div> <div class="col-sm-2"> <textarea class="form-control" row="1"></textarea> </div> </div> </div> <div> <h2>RKSK (only for HPDs)</h2> <div class="form-group"> <label for="120" class="col-sm-4 control-label">Support to Peer Educator</label> <div class="col-sm-2"> <div class="input-group"> <span class="input-group-addon" id="addon-120-R"><i class="fa fa-inr"></i></span> <input id="120" class="form-control" type="" aria-describedby="addon-120-R"> </div> </div> <div class="col-sm-2"> <div class="input-group"> <span class="input-group-addon" id="addon-120-U"><i class="fa fa-inr"></i></span> <input id="120" class="form-control" type="" aria-describedby="addon-120-U"> </div> </div> <div class="col-sm-2"> <textarea class="form-control" row="1"></textarea> </div> </div> <div class="form-group"> <label for="121" class="col-sm-4 control-label">Mobilizing Adolescents for AHD</label> <div class="col-sm-2"> <div class="input-group"> <span class="input-group-addon" id="addon-121-R"><i class="fa fa-inr"></i></span> <input id="121" class="form-control" type="" aria-describedby="addon-121-R"> </div> </div> <div class="col-sm-2"> <div class="input-group"> <span class="input-group-addon" id="addon-121-U"><i class="fa fa-inr"></i></span> <input id="121" class="form-control" type="" aria-describedby="addon-121-U"> </div> </div> <div class="col-sm-2"> <textarea class="form-control" row="1"></textarea> </div> </div> </div> <div> <h2>RNTCP</h2> <div class="form-group"> <label for="122" class="col-sm-4 control-label">New TB case Catg.I TB (42 contacts 6-7 months treatment)</label> <div class="col-sm-2"> <div class="input-group"> <span class="input-group-addon" id="addon-122-R"><i class="fa fa-inr"></i></span> <input id="122" class="form-control" type="" aria-describedby="addon-122-R"> </div> </div> <div class="col-sm-2"> <div class="input-group"> <span class="input-group-addon" id="addon-122-U"><i class="fa fa-inr"></i></span> <input id="122" class="form-control" type="" aria-describedby="addon-122-U"> </div> </div> <div class="col-sm-2"> <textarea class="form-control" row="1"></textarea> </div> </div> <div class="form-group"> <label for="123" class="col-sm-4 control-label">Previous treated TB case (57 contacts, catg.II TB 8-9 months treatment</label> <div class="col-sm-2"> <div class="input-group"> <span class="input-group-addon" id="addon-123-R"><i class="fa fa-inr"></i></span> <input id="123" class="form-control" type="" aria-describedby="addon-123-R"> </div> </div> <div class="col-sm-2"> <div class="input-group"> <span class="input-group-addon" id="addon-123-U"><i class="fa fa-inr"></i></span> <input id="123" class="form-control" type="" aria-describedby="addon-123-U"> </div> </div> <div class="col-sm-2"> <textarea class="form-control" row="1"></textarea> </div> </div> <div class="form-group"> <label for="124" class="col-sm-4 control-label">Providing treatment and support to Drug resistant TB patient (MDR)</label> <div class="col-sm-2"> <div class="input-group"> <span class="input-group-addon" id="addon-124-R"><i class="fa fa-inr"></i></span> <input id="124" class="form-control" type="" aria-describedby="addon-124-R"> </div> </div> <div class="col-sm-2"> <div class="input-group"> <span class="input-group-addon" id="addon-124-U"><i class="fa fa-inr"></i></span> <input id="124" class="form-control" type="" aria-describedby="addon-124-U"> </div> </div> <div class="col-sm-2"> <textarea class="form-control" row="1"></textarea> </div> </div> <div class="form-group"> <label for="125" class="col-sm-4 control-label">Identification & Successful completion of DOTS for TB</label> <div class="col-sm-2"> <div class="input-group"> <span class="input-group-addon" id="addon-125-R"><i class="fa fa-inr"></i></span> <input id="125" class="form-control" type="" aria-describedby="addon-125-R"> </div> </div> <div class="col-sm-2"> <div class="input-group"> <span class="input-group-addon" id="addon-125-U"><i class="fa fa-inr"></i></span> <input id="125" class="form-control" type="" aria-describedby="addon-125-U"> </div> </div> <div class="col-sm-2"> <textarea class="form-control" row="1"></textarea> </div> </div> </div> <div> <h2>NLEP</h2> <div class="form-group"> <label for="126" class="col-sm-4 control-label">PB - Referring for Diagnostics + Complete treatment</label> <div class="col-sm-2"> <div class="input-group"> <span class="input-group-addon" id="addon-126-R"><i class="fa fa-inr"></i></span> <input id="126" class="form-control" type="" aria-describedby="addon-126-R"> </div> </div> <div class="col-sm-2"> <div class="input-group"> <span class="input-group-addon" id="addon-126-U"><i class="fa fa-inr"></i></span> <input id="126" class="form-control" type="" aria-describedby="addon-126-U"> </div> </div> <div class="col-sm-2"> <textarea class="form-control" row="1"></textarea> </div> </div> <div class="form-group"> <label for="127" class="col-sm-4 control-label">MB - Dsetection + complete treatment</label> <div class="col-sm-2"> <div class="input-group"> <span class="input-group-addon" id="addon-127-R"><i class="fa fa-inr"></i></span> <input id="127" class="form-control" type="" aria-describedby="addon-127-R"> </div> </div> <div class="col-sm-2"> <div class="input-group"> <span class="input-group-addon" id="addon-127-U"><i class="fa fa-inr"></i></span> <input id="127" class="form-control" type="" aria-describedby="addon-127-U"> </div> </div> <div class="col-sm-2"> <textarea class="form-control" row="1"></textarea> </div> </div> </div> <div> <h2>NVBDC Programme (Srikakulam, Vizianagaram, East Godavari)</h2> <div class="form-group"> <label for="128" class="col-sm-4 control-label">Preparation of Blood Slide </label> <div class="col-sm-2"> <div class="input-group"> <span class="input-group-addon" id="addon-128-R"><i class="fa fa-inr"></i></span> <input id="128" class="form-control" type="" aria-describedby="addon-128-R"> </div> </div> <div class="col-sm-2"> <div class="input-group"> <span class="input-group-addon" id="addon-128-U"><i class="fa fa-inr"></i></span> <input id="128" class="form-control" type="" aria-describedby="addon-128-U"> </div> </div> <div class="col-sm-2"> <textarea class="form-control" row="1"></textarea> </div> </div> <div class="form-group"> <label for="129" class="col-sm-4 control-label">Complete treatment for RDT +ve PF case & complete Radical treatment to +ve PF & PC cases</label> <div class="col-sm-2"> <div class="input-group"> <span class="input-group-addon" id="addon-129-R"><i class="fa fa-inr"></i></span> <input id="129" class="form-control" type="" aria-describedby="addon-129-R"> </div> </div> <div class="col-sm-2"> <div class="input-group"> <span class="input-group-addon" id="addon-129-U"><i class="fa fa-inr"></i></span> <input id="129" class="form-control" type="" aria-describedby="addon-129-U"> </div> </div> <div class="col-sm-2"> <textarea class="form-control" row="1"></textarea> </div> </div> <div class="form-group"> <label for="130" class="col-sm-4 control-label">Lymphatic Filariasis – for One time Line listing of Lymphoedema and Hydrocele cases in non-endemic dist</label> <div class="col-sm-2"> <div class="input-group"> <span class="input-group-addon" id="addon-130-R"><i class="fa fa-inr"></i></span> <input id="130" class="form-control" type="" aria-describedby="addon-130-R"> </div> </div> <div class="col-sm-2"> <div class="input-group"> <span class="input-group-addon" id="addon-130-U"><i class="fa fa-inr"></i></span> <input id="130" class="form-control" type="" aria-describedby="addon-130-U"> </div> </div> <div class="col-sm-2"> <textarea class="form-control" row="1"></textarea> </div> </div> <div class="form-group"> <label for="131" class="col-sm-4 control-label">Line listing of Lymphatic Filariasis</label> <div class="col-sm-2"> <div class="input-group"> <span class="input-group-addon" id="addon-131-R"><i class="fa fa-inr"></i></span> <input id="131" class="form-control" type="" aria-describedby="addon-131-R"> </div> </div> <div class="col-sm-2"> <div class="input-group"> <span class="input-group-addon" id="addon-131-U"><i class="fa fa-inr"></i></span> <input id="131" class="form-control" type="" aria-describedby="addon-131-U"> </div> </div> <div class="col-sm-2"> <textarea class="form-control" row="1"></textarea> </div> </div> <div class="form-group"> <label for="132" class="col-sm-4 control-label">Referral of AES / JE cases to the nearest CHC / DH / Medical College</label> <div class="col-sm-2"> <div class="input-group"> <span class="input-group-addon" id="addon-132-R"><i class="fa fa-inr"></i></span> <input id="132" class="form-control" type="" aria-describedby="addon-132-R"> </div> </div> <div class="col-sm-2"> <div class="input-group"> <span class="input-group-addon" id="addon-132-U"><i class="fa fa-inr"></i></span> <input id="132" class="form-control" type="" aria-describedby="addon-132-U"> </div> </div> <div class="col-sm-2"> <textarea class="form-control" row="1"></textarea> </div> </div> </div> <div> <h2>Routine & Recurrent activities</h2> <div class="form-group"> <label for="133" class="col-sm-4 control-label">Mobilizing & attending VHND in the month</label> <div class="col-sm-2"> <div class="input-group"> <span class="input-group-addon" id="addon-133-R"><i class="fa fa-inr"></i></span> <input id="133" class="form-control" type="" aria-describedby="addon-133-R"> </div> </div> <div class="col-sm-2"> <div class="input-group"> <span class="input-group-addon" id="addon-133-U"><i class="fa fa-inr"></i></span> <input id="133" class="form-control" type="" aria-describedby="addon-133-U"> </div> </div> <div class="col-sm-2"> <textarea class="form-control" row="1"></textarea> </div> </div> <div class="form-group"> <label for="134" class="col-sm-4 control-label">Attending VHSNC meeting</label> <div class="col-sm-2"> <div class="input-group"> <span class="input-group-addon" id="addon-134-R"><i class="fa fa-inr"></i></span> <input id="134" class="form-control" type="" aria-describedby="addon-134-R"> </div> </div> <div class="col-sm-2"> <div class="input-group"> <span class="input-group-addon" id="addon-134-U"><i class="fa fa-inr"></i></span> <input id="134" class="form-control" type="" aria-describedby="addon-134-U"> </div> </div> <div class="col-sm-2"> <textarea class="form-control" row="1"></textarea> </div> </div> <div class="form-group"> <label for="135" class="col-sm-4 control-label">Atttending ASHA Day Meeting</label> <div class="col-sm-2"> <div class="input-group"> <span class="input-group-addon" id="addon-135-R"><i class="fa fa-inr"></i></span> <input id="135" class="form-control" type="" aria-describedby="addon-135-R"> </div> </div> <div class="col-sm-2"> <div class="input-group"> <span class="input-group-addon" id="addon-135-U"><i class="fa fa-inr"></i></span> <input id="135" class="form-control" type="" aria-describedby="addon-135-U"> </div> </div> <div class="col-sm-2"> <textarea class="form-control" row="1"></textarea> </div> </div> <div class="form-group"> <label for="136" class="col-sm-4 control-label">Line listing of households done at beginning of the year and updated after six months</label> <div class="col-sm-2"> <div class="input-group"> <span class="input-group-addon" id="addon-136-R"><i class="fa fa-inr"></i></span> <input id="136" class="form-control" type="" aria-describedby="addon-136-R"> </div> </div> <div class="col-sm-2"> <div class="input-group"> <span class="input-group-addon" id="addon-136-U"><i class="fa fa-inr"></i></span> <input id="136" class="form-control" type="" aria-describedby="addon-136-U"> </div> </div> <div class="col-sm-2"> <textarea class="form-control" row="1"></textarea> </div> </div> <div class="form-group"> <label for="137" class="col-sm-4 control-label">Maintaining village health register and supporting universal registration of births and deaths</label> <div class="col-sm-2"> <div class="input-group"> <span class="input-group-addon" id="addon-137-R"><i class="fa fa-inr"></i></span> <input id="137" class="form-control" type="" aria-describedby="addon-137-R"> </div> </div> <div class="col-sm-2"> <div class="input-group"> <span class="input-group-addon" id="addon-137-U"><i class="fa fa-inr"></i></span> <input id="137" class="form-control" type="" aria-describedby="addon-137-U"> </div> </div> <div class="col-sm-2"> <textarea class="form-control" row="1"></textarea> </div> </div> <div class="form-group"> <label for="138" class="col-sm-4 control-label">Preparation of due list of children to be immunized updated on monthly basis</label> <div class="col-sm-2"> <div class="input-group"> <span class="input-group-addon" id="addon-138-R"><i class="fa fa-inr"></i></span> <input id="138" class="form-control" type="" aria-describedby="addon-138-R"> </div> </div> <div class="col-sm-2"> <div class="input-group"> <span class="input-group-addon" id="addon-138-U"><i class="fa fa-inr"></i></span> <input id="138" class="form-control" type="" aria-describedby="addon-138-U"> </div> </div> <div class="col-sm-2"> <textarea class="form-control" row="1"></textarea> </div> </div> <div class="form-group"> <label for="139" class="col-sm-4 control-label">Preparation of list of ANC beneficiaries to be updated on monthly basis</label> <div class="col-sm-2"> <div class="input-group"> <span class="input-group-addon" id="addon-139-R"><i class="fa fa-inr"></i></span> <input id="139" class="form-control" type="" aria-describedby="addon-139-R"> </div> </div> <div class="col-sm-2"> <div class="input-group"> <span class="input-group-addon" id="addon-139-U"><i class="fa fa-inr"></i></span> <input id="139" class="form-control" type="" aria-describedby="addon-139-U"> </div> </div> <div class="col-sm-2"> <textarea class="form-control" row="1"></textarea> </div> </div> <div class="form-group"> <label for="140" class="col-sm-4 control-label">Preparation of list of eligible couples updated on monthly basis</label> <div class="col-sm-2"> <div class="input-group"> <span class="input-group-addon" id="addon-140-R"><i class="fa fa-inr"></i></span> <input id="140" class="form-control" type="" aria-describedby="addon-140-R"> </div> </div> <div class="col-sm-2"> <div class="input-group"> <span class="input-group-addon" id="addon-140-U"><i class="fa fa-inr"></i></span> <input id="140" class="form-control" type="" aria-describedby="addon-140-U"> </div> </div> <div class="col-sm-2"> <textarea class="form-control" row="1"></textarea> </div> </div> </div> <div> <h2>104 (by state budget)</h2> <div class="form-group"> <label for="141" class="col-sm-4 control-label">No.of ASHA attended 104 Fixed day health services in villages </label> <div class="col-sm-2"> <div class="input-group"> <span class="input-group-addon" id="addon-141-R"><i class="fa fa-inr"></i></span> <input id="141" class="form-control" type="" aria-describedby="addon-141-R"> </div> </div> <div class="col-sm-2"> <div class="input-group"> <span class="input-group-addon" id="addon-141-U"><i class="fa fa-inr"></i></span> <input id="141" class="form-control" type="" aria-describedby="addon-141-U"> </div> </div> <div class="col-sm-2"> <textarea class="form-control" row="1"></textarea> </div> </div> </div> <div> <button type="submit" class="btn btn-primary">Save</button> </div> </form>
// <API key>.h // Pods #import "IMInviteClient.h" #import "<API key>.h" #import "IMViewController.h" @protocol <API key>; @interface <API key> : IMViewController @property (weak, nonatomic) id <<API key>> delegate; @end @protocol <API key> <NSObject> @end
#include "overlapping.hpp" /* TODO: * grow seeds from edges, not nodes. * Why are the results changing? * Then, speed up delV * ZEntropy shouldn't consider the number of groups, that should be taken out to another function. * That factorial expression would be better * Write down some of the stats, and be sure they're correct. * unordered_map for efficiency more often? * a big vector for the comm_count_per_edge? * keep track of frontier properly in growingSeed * type tags for the <API key>, instead of get<1> * random tie-breaking in frontier * update _p_in also. * * PLAN: * Fully abstract interface to grouping * Track count of types of edges. * Varying p_in and p_out * Each edge to know how many communities it's in. * Calculate global objective function every now and then. * More efficient finding of seeds * Random tie breaking * Stop seed growing at first positive? */ /* * Sources of randomness: * 246: Choice of initial edge seed * 249: (arbitrary, not random) Randomized p_in * 459: (arbitrary, not random) Tie breaker in seed expansion */ #include <list> #include <map> #include <algorithm> #include <functional> #include <math.h> #include <string.h> #include <fstream> #include <sstream> #include <float.h> #include <boost/<API key>.hpp> #include <boost/multi_index/ordered_index.hpp> #include <boost/multi_index/hashed_index.hpp> //#include <boost/multi_index/identity.hpp> #include <boost/multi_index/indexed_by.hpp> #include <boost/multi_index/member.hpp> #include <boost/unordered_map.hpp> #include <boost/unordered_set.hpp> #include "iterative.hpp" #include "options.hpp" #include "Range.hpp" #include "grouping.hpp" #include <set> using namespace std; using namespace std::tr1 ; using namespace grouping; char <API key>[1000] = ""; long option_seed = 0; int <API key> = 0; static void runMutual(void) { //system("echo;echo -n \" >> ;${x};${gt};${me}; \" ; bash -c '~/Code/Mutual3/mutual3/mutual \"${x}\"{\"${me}\",\"${gt}\"}' 1>&2 "); } namespace overlapping { bool <API key> = true; template <class N> static void overlappingT(bloomGraph<N> &g); void overlapping(SimpleIntGraph &g) { overlappingT(g); } void overlapping(SimpleStringGraph &g) { overlappingT(g); } void addSeed(Grouping &ging, const set<V> &nodes, bool randomized_p_in); static pair<long double, set<V> > growThisEdge(Grouping &ging, V edgeNumber, const long double &boost, bool randomized_p_in); static void update_p_out(Grouping &ging); static void <API key>(Grouping &ging); long double MOSES_objective(const Grouping &ging); void addSeed(Grouping &ging, const set<V> &nodes, bool randomized_p_in) { assert(nodes.size()>0); Group *g = ging.newG(randomized_p_in); ForeachContainer(V v, nodes) { ging.addV(g, v); } } void <API key>(Grouping &ging, const iterative::Partition &p); template <class N> static void useOneNodeSeeds(Grouping &ging, bloomGraph<N> &g, bool randomize_p_in); template <class N> static void groupStats(const Grouping &ging, bloomGraph<N> &g); template <class N> static void save(Grouping &ging, bloomGraph<N> &g); template <class N> static void louvainStyle(Grouping &ging, bloomGraph<N> &g); static void tryMerges(Grouping &ging); static void tryDeletions(Grouping &ging, bool SaveScores = false); static bool tryAndApplyThisOne(Grouping &ging, V e, bool randomized_p_in); template <class N> static void overlappingT(bloomGraph<N> &g) { printf("env: ALLOW_BOOST000 %s\n", getenv("ALLOW_BOOST000")); printf("env: Lookahead %s\n", getenv("Lookahead")); printf("env: MaxCommSize %s\n", getenv("MaxCommSize")); printf("env: OUTER_ITERS %s\n", getenv("OUTER_ITERS")); printf("env: LOUVAIN_ITERS %s\n", getenv("LOUVAIN_ITERS")); printf("NoBroken\n"); srand48(option_seed); // default seed. Will be changeable by command line arg. /* iterative::Partition p(g); iterative::findPartition(p, g); assert(option_planted[0]==0); strcpy(option_planted, option_overlapping); strcat(option_planted, "_partition"); savePartition(g, p, -1); long double p_in = (long double) p.m_i / p.a; long double p_out; { int64 b = p.N * (p.N-1L) / 2L; int64 m_e = p.m-p.m_i; p_out = (long double) (m_e) / (b - p.a); } PP(p_in); PP(p_out); //Grouping ging(g, p_in, p_out); //<API key>(ging, p); */ Grouping ging(g, option_p_in, option_p_out); <API key>(ging); ging.<API key> = MOSES_objective(ging); //PP(ging._p_in); //PP(ging._p_out); if(<API key>[0]) { // load preexisting grouping Pn("Preloading grouping '%s'", <API key>); ifstream inFile(<API key>); //for (int i=0; i<5; ++i) int lineNo=0; while(inFile.peek()!=EOF) { lineNo ++; string line; getline(inFile, line); if(line.length()==0) break; Group *grp = ging.newG(); istringstream linestream(line); //PP(line);// if(linestream.peek()=='"') { char ch; linestream >> ch; while(linestream.peek() != EOF) { linestream >> ch; if(ch=='"') break; } if(linestream.peek()!='\t') Die("grouping file should have a tab after any \" \". line %d {%d '%c'}", lineNo, (int) ch, ch); } while(linestream >> ws, linestream.peek() != EOF) { N n; linestream >> n; V v = g.key_for_vertexName(n); assert(v>=0); assert(v<g.vcount()); ging.addV(grp, v); } } save(ging, g); } <API key>(ging); groupStats(ging, g); MOSES_objective(ging); if(<API key>) exit(0); const int max_OuterIters = atoi(getenv("OUTER_ITERS") ? : "20"); PP(max_OuterIters); for (int k=0; k<max_OuterIters; k++) { MOSES_objective(ging); const size_t num_groups_before = ging.groups.size(); ostringstream s; s << "Whole outer iter " << k << "/" << max_OuterIters; Timer timer(s.str()); Pn("\ngrow seeds %d/%d", k, max_OuterIters); bool randomize_p_in; if(k < max_OuterIters / 2) { randomize_p_in = true; Pn("Random p_i for each edge that we try"); <API key>(ging); // this is just to estimate p_out useOneNodeSeeds(ging, g, true); <API key>(ging); tryDeletions(ging); } else { randomize_p_in = false; useOneNodeSeeds(ging, g, false); tryDeletions(ging); } groupStats(ging, g); save(ging, g); <API key>(ging); //tryDeletions(ging); //save(ging, g); const size_t num_groups_after = ging.groups.size(); if(!randomize_p_in && /*num_groups_after > 1000 && */ 0.99L * num_groups_after <= num_groups_before) { Pn("breaking after %d growing passes, as VERY FEW more have been found among the most recent subset", k+1); break; } } int louvainStyle_iter=0; const int <API key> = atoi(getenv("LOUVAIN_ITERS") ? : "10"); PP(<API key>); while(louvainStyle_iter != <API key>) { MOSES_objective(ging); Timer timer("Whole Louvain iter"); Pn("\nLouvain-style iteration %d/%d", louvainStyle_iter++, <API key>); louvainStyle(ging, g); tryDeletions(ging, louvainStyle_iter==<API key>); <API key>(ging); groupStats(ging, g); save(ging, g); } if(0) { tryMerges(ging); save(ging, g); groupStats(ging, g); } Pn("\n\nFINAL Grouping"); groupStats(ging, g); <API key>(ging); MOSES_objective(ging); } static bool tryAndApplyThisOne(Grouping &ging, V e, bool randomized_p_in) { static long double boost = 0.0L; if(!getenv("ALLOW_BOOST000")) boost=0.0L; // reset it back to zero unless ALLOW_BOOST000 is defined in the environment pair<long double, set<V> > bestSeed = growThisEdge(ging, e, boost, randomized_p_in); if(bestSeed.first + boost> 0.0L && bestSeed.second.size()>0 ) { addSeed(ging, bestSeed.second, randomized_p_in); boost /= 2.0; // if(boost<0.0L) boost=0.0L; return true; //Pn("Applied best 1-seed. Now returning. %zd nodes (+%Lg). Now there are %zd communities", bestSeed.second.size(), bestSeed.first, ging.groups.size()); // if(bestSeed.second.size() < 20) ForeachContainer (V v, bestSeed.second) { cout << "|" << g.name(v); } P("\n"); } boost += 0.1; return false; } template <class N> static void useOneNodeSeeds(Grouping &ging, bloomGraph<N> &g, bool randomize_p_in) { Timer timer(__FUNCTION__); const int numTries = g.ecount()/5; P(" \n Now just use one-EDGE seeds at a time. Try %d edges\n", numTries); // groupStats(ging, g); for(int x=0; x<numTries; ++x) { if(x && numTries>5 && x%(numTries/5)==0) { PP(x); PP(ging.groups.size()); } // choose an edge at random, but prefer to use it iff it's sharedCommunities score is low. V e = V(drand48() * (2*ging._g.ecount())); assert(e >= 0); assert(e < 2*ging._g.ecount()); if(randomize_p_in) { ging._p_in = 0.01L + 0.98L*drand48(); assert(ging._p_in < 1.0L); } tryAndApplyThisOne(ging, e, randomize_p_in); #if 0 int sharedCommunities = ging.comm_count_per_edge(ging._g.neighbours(0).first[e], &(ging._g.neighbours(0).first[e])); // a little time in here //PP(sharedCommunities); if( (double(rand())/RAND_MAX) < powl(0.5, sharedCommunities)) { //Pn(" X %d", sharedCommunities); tryAndApplyThisOne(ging, e); } else { //Pn(" %d", sharedCommunities); } #endif } } template <class N> static void groupStats(const Grouping &ging, bloomGraph<N> &g) { map<size_t, int> <API key>; map<size_t, int> group_sizes; int64 totalAssignments = 0; // to help calculate average communities per node. ForeachContainer(Group *group, ging.groups) { DYINGWORDS(group->vs.size()>0) { PP(group->vs.size()); } group_sizes[group->vs.size()]++; totalAssignments += group->vs.size(); if(group->_randomized_p_in) <API key>[group->vs.size()]++; } //Perror(" %zd\n", ging.groups.size()); Pn("#groups=%zd. %zd nodes, out of %d, are in at least one community. avgs grps/node=%g", ging.groups.size(), ging.vgroups_size(), g.vcount(), (double) totalAssignments / g.vcount()); pair<size_t, int> group_size; size_t max_group_size = group_sizes.size()==0 ? 0 : group_sizes.rbegin()->first; int entries_per_row = 15; int number_of_rows = (max_group_size / entries_per_row) + 1; for(int r = 0; r<number_of_rows ; r++) { for(size_t c = r; c <= max_group_size; c+=number_of_rows) { if(group_sizes[c]>0) P("%6d{%3zd}", group_sizes[c], c); else P(" "); } P("\n"); } { // now, just the randomized ones size_t max_group_size = <API key>.size()==0 ? 0 : <API key>.rbegin()->first; int entries_per_row = 15; int number_of_rows = (max_group_size / entries_per_row) + 1; for(int r = 0; r<number_of_rows ; r++) { for(size_t c = r; c <= max_group_size; c+=number_of_rows) { if(<API key>[c]>0) P("%6d{%3zd}", <API key>[c], c); else P(" "); } P("\n"); } } #if 0 set<V> <API key>; Group *largestGroup = NULL; ForeachContainer(Group *group, ging.groups) { if(group->vs.size() == max_group_size) { ForeachContainer(V v, group->vs) { P("(%zd)", ging.vgroups(v).size()); if(1 == ging.vgroups(v).size() && 0 == rand()%2) <API key>.insert(v); } P("\n"); largestGroup = group; break; } } #endif { int print_count = 0; for(map<int, V>::const_iterator it = ging.global_edge_counts.begin(); it!=ging.global_edge_counts.end(); ++it) { P("%6d(%3d)", (int) it->second ,(int) it->first); print_count++; if(print_count%15==0) P("\n"); } P("\n"); //if(0) update_p_out(ging); //PP(ging._p_in); //PP(ging._p_out); } } void <API key>(Grouping &ging, const iterative::Partition &p) { for(V c=0; c<p.g.vcount(); ++c) { if(p.p[c].c == c) { // we're at the head node //Pn(" order %d", p.p[c].order); Group *grp = ging.newG(); V v = c; do { assert(c == p.p[v].c); ging.addV(grp, v); //Pn ("%d is in %d", v ,c); v = p.p[v].next; } while (v != c); } } } template <class It> static size_t count_intersection(It it1b, It it1e, It it2b, It it2e) { vector< typename It::value_type > is; set_intersection(it1b, it1e, it2b, it2e, back_inserter(is)); return is.size(); } template <class Container> static size_t count_intersection(const Container &container1, const Container &container2) { return count_intersection( container1.begin() , container1.end() , container2.begin() , container2.end() ); } struct DeltaSeed { const V _v; // for this node const int _group_size_smaller; // ...and this group (which v is NOT currently in) const Grouping &_ging; // what'd be the change in entropy (edge+Z+Q) from joining it? long double <API key>; int <API key>; long double <API key>() const { return <API key> + log2l(1.0L - _ging._p_in) * (_group_size_smaller - <API key>); } explicit DeltaSeed(V v, int group_size_smaller, Grouping &ging) : _v(v), _group_size_smaller(group_size_smaller), _ging(ging), <API key>(0.0L), <API key>(0) { //assert(_grp.vs.count(v)==0); } void addEdge2(V n, const V* edgeVN_ptr) { // n is connected to _v assert(*edgeVN_ptr == n); this->addEdge(n, _ging.comm_count_per_edge(n, edgeVN_ptr)); } void addEdge(V , int sharedCommunities) { // n is connected to _v // TODO: might be quicker to pass in the count of sharedCommunities too //assert(_ging._g.are_connected(_v, n)); // TODO: remove these assertions //assert(_grp.vs.count(n) == 1); //assert(_grp.vs.count(_v) == 0); <API key> ++; <API key> += log2l(1.0L - (1.0L-_ging._p_out)*powl(1.0L - _ging._p_in, 1+sharedCommunities)) - log2l(1.0L - (1.0L-_ging._p_out)*powl(1.0L - _ging._p_in, sharedCommunities)); } void redoEdge(V , int <API key>) { // n is connected to _v // TODO: might be quicker to pass in the count of sharedCommunities too <API key> -=(log2l(1.0L - (1.0L-_ging._p_out)*powl(1.0L - _ging._p_in, 1+<API key>)) - log2l(1.0L - (1.0L-_ging._p_out)*powl(1.0L - _ging._p_in, <API key>))); <API key> += log2l(1.0L - (1.0L-_ging._p_out)*powl(1.0L - _ging._p_in, 2+<API key>)) - log2l(1.0L - (1.0L-_ging._p_out)*powl(1.0L - _ging._p_in, 1+<API key>)); } long double _deltaZentropy() const { const size_t N = _ging._g.vcount(); const size_t x = _group_size_smaller; const size_t x2 = 1+x; return( x2 * log2l(x2) + (N-x2) * log2l(N-x2) -x * log2l(x) - (N-x ) * log2l(N-x ) ); /* (x2 * (log2l(x2)-log2l(N)) + (N-x2) * (log2l(N-x2)-log2l(N)) + log2l(1+ging.groups.size()) - log2l(N)) -(x * (log2l(x) -log2l(N)) + (N-x ) * (log2l(N-x )-log2l(N)) + log2l(1+ging.groups.size()) - log2l(N)) = (x2 * (log2l(x2)-log2l(N)) + (N-x2) * (log2l(N-x2)-log2l(N)) ) -(x * (log2l(x) -log2l(N)) + (N-x ) * (log2l(N-x )-log2l(N)) ) = (x2 * (log2l(x2) ) + (N-x2) * (log2l(N-x2) ) ) -(x * (log2l(x) ) + (N-x ) * (log2l(N-x ) ) ) = x2 * log2l(x2) + (N-x2) * log2l(N-x2) -x * log2l(x) - (N-x ) * log2l(N-x ) */ } long double _deltaTotalentropy() const { return this-><API key>() + this->_deltaZentropy(); } }; struct FrontierNode { FrontierNode(long double &score, V v) : _score(score), _v(v) {} long double _score; V _v; struct Incrementer { long double _x; Incrementer(long double &x) : _x(x) {} void operator() (FrontierNode &fn) const { fn._score += _x; } }; }; using namespace boost::multi_index; struct VertexTag {}; struct Frontier : private <API key> < // TODO: Some sort of binary tree sometime? FrontierNode, indexed_by< ordered_non_unique< member<FrontierNode,long double,&FrontierNode::_score>, greater<long double> >, hashed_unique< tag<VertexTag>, member<FrontierNode,V,&FrontierNode::_v> > > > { // vertices, and their scores. // easy removal of the highest-score vertices. // easy increase of score of arbitrary members, adding them if they don't exist already. public: static long double __attribute__ ((noinline)) calcddEE(const Grouping &ging, int sharedCommunities) { return log2l(1.0L - (1.0L-ging._p_out) * powl(1.0L - ging._p_in, 1+sharedCommunities)) - log2l(1.0L - (1.0L-ging._p_out) * powl(1.0L - ging._p_in, sharedCommunities)) - log2l(1.0L - ging._p_in) + 1e-20L * drand48() // random tie breaking ; } void addNode(const Grouping &ging, V to, const V *edgeFT_ptr) { // to is being added to the frontier, BUT it may already be in the frontier. // from is in the seed. //assert(*edgeFT_ptr == to); int sharedCommunities = ging.comm_count_per_edge(to, edgeFT_ptr); // a little time in here long double <API key> = calcddEE(ging, sharedCommunities ); // a little time in here Frontier::nth_index<1>::type::iterator addOrModifyThis = this->get<1>().find(to); if(addOrModifyThis==this->get<1>().end()) { // TODO: faster if search for to is done just once? this->insert(FrontierNode(<API key>, to)); } else { this->get<1>().modify(addOrModifyThis, FrontierNode::Incrementer(<API key>)); } } void erase_best_node() { Frontier::iterator best_node = this->get<0>().begin(); this->erase(best_node); } int erase_this_node(V to) { return this->get<1>().erase(to); } long double best_node_score() const { Frontier::iterator best_node = this->get<0>().begin(); return best_node -> _score; } V best_node_v() const { Frontier::iterator best_node = this->get<0>().begin(); return best_node -> _v; } bool Empty() const { return this->empty(); } }; static long double logNchoose(int64 N, int64 n_c) { if(n_c==N) return 0; static vector<long double> logNchoose_vector; // static int64 usedN; assert(n_c>0); assert(n_c<=N); if (logNchoose_vector.size()==0) { Timer t("logNchoose Initialization"); logNchoose_vector.resize(N+1); // usedN = N; long double lN = 0.0L; for(int64 x1=1; x1<=N; x1++) { if(x1>1) { int64 i = x1-1; lN += log2l(i) - log2l(N-i); } logNchoose_vector.at(x1) = lN; } } assert(logNchoose_vector.at(0) == 0); // DYINGWORDS(logNchoose_vector.at(N) == 0) { // will never be exactly zero, but it should be, in theory assert(logNchoose_vector.size()>0); // assert(usedN == N); assert( size_t(N+1) == logNchoose_vector.size()); assert( size_t(n_c) < logNchoose_vector.size()); return logNchoose_vector.at(n_c); } pair<long double, set<V> > growingSeed(Grouping &ging, int lookahead , set<V> &seed , pair<long double, set<V> > bestSoFar , long double seedEdgeEntropy , int seed_size , Frontier &frontier , int edges_in_seed , const long double &boost // to allow some negative communities to persist. The deletion phase will fix them later. This is to ensure that we have the best chance of filling the graph up quickly. , bool randomized_p_in ) // Find the expansion among the frontier that best improves the score. Then recurse to it. // Stop growing if dead end is reached (empty frontier) or the seed isn't increasing and we already have at least 5 nodes. // Return the best set of nodes // TODO: Profile, then make this damn efficient { assert((int) seed.size() == seed_size); if(frontier.Empty()) return bestSoFar; const V best_v = frontier.best_node_v(); #if 0 { IteratorRange<const V *> ns(ging._g.neighbours(best_v)); Foreach(V n, ns) { if(1==seed.count(n)) { // This neighbour is already in the seed. That means the count of edges within the seed is about to be increased. Should update randomized p_in in light of this. ++edges_in_seed; } } int64 pairsInSeed = seed_size * (1+seed_size) / 2; long double new_p_in = 1.0L * (2*edges_in_seed+1) / (2 * pairsInSeed + 2) ; if(randomized_p_in) ging._p_in = new_p_in; /* cout << edges_in_seed << "/" << (1+seed_size) << "\t" << 100.0 * edges_in_seed / (seed_size * (1+seed_size) / 2) // << "\t" << ging._p_in << "\t" << randomized_p_in << "\t" << new_p_in << endl; */ assert(edges_in_seed <= (seed_size * (1+seed_size) / 2)); } #endif const long double newseedEdgeEntropy = seedEdgeEntropy + frontier.best_node_score() + log2l(1.0L-ging._p_in) * seed_size; const int N = ging._g.vcount(); //const int x = seed_size; const int x1= 1+seed_size; //long double <API key> = seedEdgeEntropy + x * (log2l(x)-log2l(N)) + (N-x) * (log2l(N-x)-log2l(N)) + log2l(1+ging.groups.size())/*equivalent groupings*/ - log2l(N)/*encoding of size of the group*/; UNUSED int64 q = ging.groups.size(); if (q==0) q=1; UNUSED const int64 q_= 1 + q; const long double logNchoosen = logNchoose(N,x1); const long double <API key> = newseedEdgeEntropy //+ x1 * (log2l(x1)-log2l(N)) + (N-x1) * (log2l(N-x1)-log2l(N)) + logNchoosen - log2l(N+1)/*encoding of size of the group*/ + log2l(1+ging.groups.size())/*equivalent groupings*/ //+ (getenv("UseBroken") ? ( ( q_ * (log2l(q_) - log2l(exp(1))) + log2l(N+1) - log2l(N+1-q_) ) - ( q * (log2l(q ) - log2l(exp(1))) + log2l(N+1) - log2l(N+1-q ) ) ) : 0) ; if(bestSoFar.first < <API key>) { bestSoFar.first = <API key>; bestSoFar.second = seed; bestSoFar.second.insert(best_v); } if( (size_t) seed_size >= lookahead +bestSoFar.second.size() ) // lookahead return bestSoFar; const size_t max_commsize = atoi(getenv("MaxCommSize") ? : "10000000"); if( (size_t) seed_size >= max_commsize ) { // max comm size bestSoFar.first = -10000000; return bestSoFar; } //if( bestSoFar.first > 0.0L) // once positive, return immediately!!!!!!!!!!!!! //return bestSoFar; if( (size_t) seed_size > bestSoFar.second.size() && bestSoFar.first + boost > 0.0L) // once positive, return immediately if it drops. return bestSoFar; //if(bestSoFar.first > 0.0L) //return bestSoFar; // This isn't working so well. Too many communities (I think), and no faster (for Oklahoma at least) frontier.erase_best_node(); IteratorRange<const V *> ns(ging._g.neighbours(best_v)); const V *edgeVN_offset = ging._g.neighbours(best_v).first; Foreach(V n, ns) { assert( *edgeVN_offset == n); //assert(ging._g.neighbours(0).first[ging.<API key>[edgeVN_offset].other_index] == best_v); if(0==seed.count(n)) frontier.addNode(ging, n , edgeVN_offset ); ++edgeVN_offset; } seed.insert(best_v); return growingSeed(ging , lookahead , seed , bestSoFar , newseedEdgeEntropy , 1 + seed_size , frontier , edges_in_seed , boost , randomized_p_in ); } struct ThrowingIterator { struct Dereferenced {}; V & operator *() { throw Dereferenced(); } void operator ++() { throw Dereferenced(); } }; bool emptyIntersection(const pair<const V*, const V*> &l, const pair<const V*, const V*> &r) { try { set_intersection( l.first ,l.second ,r.first ,r.second ,ThrowingIterator() ); } catch (ThrowingIterator::Dereferenced &) { return false; } return true; //inter.empty(); } static pair<long double, set<V> > growThisEdge(Grouping &ging, const V edgeNumber, const long double &boost, bool randomized_p_in) { assert(edgeNumber < 2*ging._g.ecount()); V r = ging._g.neighbours(0).first[edgeNumber]; V l = ging._g.neighbours(0).first[ging.<API key>[edgeNumber].other_index]; // there must be a triangle available if(emptyIntersection(ging._g.neighbours(l),ging._g.neighbours(r))) return make_pair(-1.0L, set<V>()); Frontier frontier; { IteratorRange<const V *> ns(ging._g.neighbours(l)); const V *edgeIN_ptr = ging._g.neighbours(l).first; Foreach(V n, ns) { frontier.addNode(ging, n, edgeIN_ptr); ++edgeIN_ptr; } } //PP(frontier.size()); const int erased = frontier.erase_this_node(r); DYINGWORDS(erased==1) { PP(erased); PP(l); PP(r); //PP(frontier.size()); PP(ging._g.degree(l)); PP(ging._g.degree(r)); IteratorRange<const V *> ns(ging._g.neighbours(l)); Foreach(V n, ns) { PP(n); } } assert(erased==1); { IteratorRange<const V *> ns(ging._g.neighbours(r)); const V *edgeIN_ptr = ging._g.neighbours(r).first; Foreach(V n, ns) { if(n!=l) frontier.addNode(ging, n, edgeIN_ptr); ++edgeIN_ptr; } } set<V> seed; seed.insert(l); seed.insert(r); int sharedCommunities = ging.comm_count_per_edge(r, &(ging._g.neighbours(0).first[edgeNumber])); // a little time in here pair<long double, set<V> > grownSeed = growingSeed(ging , atoi(getenv("Lookahead") ? : "2") , seed , make_pair(-10000000.0L, seed) // This score is too low, but then we don't expect a singleton community to come out best anyway! Only positive scores are used. , log2l(1.0L - (1.0L-ging._p_out) * powl(1.0L - ging._p_in, 1+sharedCommunities)) - log2l(1.0L - (1.0L-ging._p_out) * powl(1.0L - ging._p_in, sharedCommunities)) , 2 , frontier , 1 , boost , randomized_p_in ); return grownSeed; } template <class N> static void save(Grouping &ging, bloomGraph<N> &g) { ofstream saveFile(option_overlapping); ForeachContainer(Group *grp, ging.groups) { bool firstLine = true; if(<API key>) saveFile << '\"' << grp->_id << "\"\t"; ForeachContainer(V v, grp->vs) { saveFile << (firstLine?"":" ") << g.name(v); firstLine = false; } saveFile << endl; } runMutual(); } struct hashGroup { int operator() (Group *grp) const { return grp->_id; } }; typedef boost::unordered_map<Group *, DeltaSeed, hashGroup> SeedDeltasT; template <class N> static void louvainStyle(Grouping &ging, bloomGraph<N> &g) { Timer t(__FUNCTION__); // find a node, isolate it from its communities, Add back one at a time if appropriate. const bool DEBUG_louvainStyle = 0; for(V v=0; v<g.vcount(); v++) { if(0) update_p_out(ging); // if(v%(g.vcount()/20)==0) PP(v); if(DEBUG_louvainStyle) groupStats(ging, g); if(DEBUG_louvainStyle) cout << "removing node in these many groups: " << ging.vgroups(v).size() << endl; ging.isolate(v); SeedDeltasT _seedDeltas; IteratorRange<const V *> ns(ging._g.neighbours(v)); { const V * edgeVN_ptr = ging._g.neighbours(v).first; Foreach(V n, ns) { int sharedCommunities = ging.comm_count_per_edge(n,edgeVN_ptr); // TODO: Could prepare the results for addEdge of v<>n ForeachContainer(Group *grp, ging.vgroups(n)) { _seedDeltas.insert(make_pair(grp, DeltaSeed(v, grp->vs.size(), ging))).first->second.addEdge(n, sharedCommunities); //_seedDeltas.find(grp)->second.addEdge(n, sharedCommunities); } ++edgeVN_ptr; } } for(int addedBack = 0; _seedDeltas.size()>0 ; addedBack++) { // for each neighbouring group, calculate the delta-entropy of expanding back in here. pair<long double, Group *> bestGroup(-LDBL_MAX, (Group*) NULL); int num_positive = 0; for(SeedDeltasT::iterator i = _seedDeltas.begin(); i!=_seedDeltas.end(); ) { if(i->second._deltaTotalentropy()<=0.0L) { i = _seedDeltas.erase(i); continue; } else { long double delta2 = i->second._deltaTotalentropy(); // TODO: Count the positive scores. No point proceeding if there aren't any more positive scores, as they can only decrease if(bestGroup.first < delta2) bestGroup = make_pair(delta2, i->first); if(delta2>0.0L) ++num_positive; } ++i; } if(bestGroup.first > 0.0L) { assert(num_positive>=1); ging.addV(bestGroup.second, v); if(num_positive==1) { // if just one was positive, then there's no point continuing, as the rest will only lose more score. break; } _seedDeltas.erase(bestGroup.second); // the other potential groups on the end of this edge need to have their addEdge undone const V * edgeVN_ptr = ging._g.neighbours(v).first; IteratorRange<const V*> ns(ging._g.neighbours(v)); Foreach(V n, ns) { assert(*edgeVN_ptr == n); if(bestGroup.second->vs.count(n)) { int <API key> = ging.comm_count_per_edge(n, edgeVN_ptr) - 1; ForeachContainer(Group *grp, ging.vgroups(n)) { SeedDeltasT::iterator grpInSeed =_seedDeltas.find(grp); if(grpInSeed != _seedDeltas.end()) { const long double before = grpInSeed->second._deltaTotalentropy(); grpInSeed->second.redoEdge(n, <API key>); const long double after = grpInSeed->second._deltaTotalentropy(); if(after > before) { Perror("%s:%d _deltaTotalentropy %Lg -> %Lg\n", __FILE__, __LINE__, before, after); } } } } ++edgeVN_ptr; } } else break; } } } static void update_p_out(Grouping &ging) { long double new_p_out = 2.0L * ging.global_edge_counts[0] / ging._g.vcount() / (ging._g.vcount()-1) ; if(new_p_out > 0.1L) ging._p_out = 0.1L; else ging._p_out = new_p_out; } struct PairGroupHash { int operator() (const pair<Group*,Group*> &pg) const { return pg.first->_id + pg.second->_id; } }; static void tryMerges(Grouping &ging) { Timer timer(__FUNCTION__); typedef boost::unordered_map< pair<Group*,Group*> , long double, PairGroupHash> MergesT; MergesT proposed_merges; size_t counter=0; for(V e = 0; e < /*100000 */ 2*ging._g.ecount() ; e++) { //if(e % (2*ging._g.ecount()/10) ==0) { PP(e); } V e2 = ging.<API key>[e].other_index; V l = ging._g.neighbours(0).first[e2]; V r = ging._g.neighbours(0).first[e]; if(r<l) continue; // no point considering each edge twice V sharedCommunities = ging.<API key>[e].shared_comms; assert(sharedCommunities == ging.<API key>[e2].shared_comms); //Pn("%d\t%d", l, r); counter++; const set<Group *> &lgrps = ging.vgroups(l); const set<Group *> &rgrps = ging.vgroups(r); //PP(lgrps.size()); //PP(rgrps.size()); vector<Group *> lonly, ronly; set_difference(lgrps.begin(),lgrps.end(),rgrps.begin(),rgrps.end(),back_inserter(lonly)); set_difference(rgrps.begin(),rgrps.end(),lgrps.begin(),lgrps.end(),back_inserter(ronly)); //Pn("# unmatched %zd,%zd", lonly.size(), ronly.size()); ForeachContainer(Group *lg, lonly) { ForeachContainer(Group *rg, ronly) { long double qi = 1.0L - ging._p_in; long double qo = 1.0L - ging._p_out; //const int64 oldQz = ging.groups.size(); Group * lg1 = lg; Group * rg1 = rg; if(lg1 > rg1) swap(lg1, rg1); MergesT::key_type key = make_pair(lg1, rg1); MergesT::iterator pm = proposed_merges.find(key); if(pm == proposed_merges.end()) { const int64 s1 = lg1->vs.size(); const int64 s2 = rg1->vs.size(); vector<V> Union; set_union(lg1->vs.begin(),lg1->vs.end(),rg1->vs.begin(),rg1->vs.end(),back_inserter(Union)); const int64 N = ging._g.vcount(); pm = proposed_merges.insert(make_pair(key, log2l(qi)*0.5L* (long double)( Union.size() * (Union.size()-1) - s1*(s1-1) - s2*(s2-1) ) // + ( (oldQz) *log2l(oldQz-1) + log2l(exp(1)) - log2l(oldQz-2-N) ) // - ( (oldQz+1)*log2l(oldQz ) - log2l(oldQz-1-N) ) + (s1+s2) * (log2l(s1+s2) /*- log2l(N)*/) - (s1 ) * (log2l(s1 ) /*- log2l(N)*/) - (s2 ) * (log2l(s2 ) /*- log2l(N)*/) + log2l(N) // one fewer community whose pi has to be encoded )).first; } pm -> second+= log2l(1.0L - qo * powl(qi, 1+sharedCommunities)) - log2l(1.0L - qo * powl(qi, sharedCommunities)) - log2l(qi) // for a given member of the map, each edge will be found exactly once. So here we cancel the affect of assuming it was disconnected ; } } } for(V e = 0; e < /*100000 */ 2*ging._g.ecount() ; e++) { if(e % (2*ging._g.ecount()/10) ==0) { PP(e); } V e2 = ging.<API key>[e].other_index; V l = ging._g.neighbours(0).first[e2]; V r = ging._g.neighbours(0).first[e]; if(r<l) continue; // no point considering each edge twice V sharedCommunities = ging.<API key>[e].shared_comms; assert(sharedCommunities == ging.<API key>[e2].shared_comms); //Pn("%d\t%d", l, r); counter++; const set<Group *> &lgrps = ging.vgroups(l); const set<Group *> &rgrps = ging.vgroups(r); //PP(lgrps.size()); //PP(rgrps.size()); vector<Group *> inter; set_intersection(lgrps.begin(),lgrps.end(),rgrps.begin(),rgrps.end(),back_inserter(inter)); //Pn("# unmatched %zd,%zd", lonly.size(), ronly.size()); ForeachContainer(Group *lg, inter) { ForeachContainer(Group *rg, inter) { if(lg < rg) { // no point proposing a merge between a group and itself long double qi = 1.0L - ging._p_in; long double qo = 1.0L - ging._p_out; Group * lg1 = lg; Group * rg1 = rg; if(lg1 > rg1) swap(lg1, rg1); MergesT::key_type key = make_pair(lg1, rg1); MergesT::iterator pm = proposed_merges.find(key); if(pm != proposed_merges.end()) pm -> second+= log2l(1.0L - qo * powl(qi, sharedCommunities-1)) - log2l(1.0L - qo * powl(qi, sharedCommunities)) + log2l(qi) // for a given member of the map, each edge will be found exactly once. So here we cancel the affect of assuming it was disconnected ; } } } } int64 merges_accepted = 0; int64 merges_applied = 0; for(MergesT::const_iterator pm = proposed_merges.begin(); pm != proposed_merges.end(); ++pm) { const long double score = pm->second; //const int64 N = ging._g.vcount(); boost::unordered_set<Group *> already_merged; if(score >0.0) { //PP(scoreEdges); //PP(scoreZ); merges_accepted++; MergesT::key_type merge_these = pm->first; if(already_merged.count(merge_these.first)==0 && already_merged.count(merge_these.second)==0) { Group * l = merge_these.first; Group * r = merge_these.second; const set<V> these_nodes(l->vs); // copy them, so as to iterate properly over them. //P(" "); PP(ging.groups.size()); ForeachContainer(V v, these_nodes) { if(r->vs.count(v)==0) { ging.addV(r,v); } assert(r->vs.count(v)==1); //ging.delV(l,v); } //PP(ging.groups.size()); already_merged.insert(merge_these.first); already_merged.insert(merge_these.second); merges_applied++; } } //if(score > -25.0) { printf("merge: %-11.2Lf\n", score); } } PP(proposed_merges.size()); PP(merges_accepted); PP(merges_applied); } static void tryDeletions(Grouping &ging, bool SaveScores /*= true*/) { // delete groups which aren't making a positive contribution any more. Timer timer(__FUNCTION__); typedef boost::unordered_map< Group* , long double, hashGroup> DeletionsT; DeletionsT proposed_deletions; const int64 N = ging._g.vcount(); ForeachContainer(Group *grp, ging.groups) { // preseed with all groups, because we want the groups even that don't have an edge in them! const int64 sz = grp->vs.size(); //int64 q = ging.groups.size() -1; if (q<=0) q=1; //const int64 q_= 1 + q; const long double logNchoosen = logNchoose(N,sz); proposed_deletions.insert(make_pair(grp, log2l(1.0L - ging._p_in)*(sz*(sz-1)/2) + logNchoosen - log2l(N+1)/*encoding of size of the group*/ + log2l(1+ging.groups.size())/*equivalent groupings*/ //+ (getenv("UseBroken") ? ( ( q_ * (log2l(q_) - log2l(exp(1))) + log2l(N+1) - log2l(N+1-q_) ) - ( q * (log2l(q ) - log2l(exp(1))) + log2l(N+1) - log2l(N+1-q ) ) ) : 0) )); } for(V e = 0; e < /*100000 */ 2*ging._g.ecount() ; e++) { /* if(e % (2*ging._g.ecount()/10) ==0) { PP(e); } */ V e2 = ging.<API key>[e].other_index; V sharedCommunities = ging.<API key>[e].shared_comms; assert(sharedCommunities == ging.<API key>[e2].shared_comms); V l = ging._g.neighbours(0).first[e2]; V r = ging._g.neighbours(0).first[e]; if(r<l) continue; // no point considering each edge twice const set<Group *> &lgrps = ging.vgroups(l); const set<Group *> &rgrps = ging.vgroups(r); vector<Group *> sharedComms; set_intersection(lgrps.begin(),lgrps.end(),rgrps.begin(),rgrps.end(),back_inserter(sharedComms)); assert((size_t)sharedCommunities == sharedComms.size()); ForeachContainer(Group *grp, sharedComms) { DeletionsT::iterator pm = proposed_deletions.find(grp); assert(pm != proposed_deletions.end()); pm -> second+= log2l(1.0L - (1.0L-ging._p_out) * powl(1.0L - ging._p_in, sharedCommunities)) - log2l(1.0L - (1.0L-ging._p_out) * powl(1.0L - ging._p_in, sharedCommunities-1)) - log2l(1.0L - ging._p_in) ; } } assert(proposed_deletions.size() <= ging.groups.size()); // maybe some communities didn't have an edge in them V deletions_accepted = 0; map<V, int> deletions_sizes; PP(ging.groups.size()); for(DeletionsT::const_iterator pm = proposed_deletions.begin(); pm != proposed_deletions.end(); ++pm) { const long double score = pm->second; //const int64 N = ging._g.vcount(); if(score < 0.0) { //PP(scoreEdges); //PP(scoreZ); deletions_accepted++; deletions_sizes[pm->first->vs.size()]++; { // delete the group set<V> vs = pm->first->vs; // COPY the vertices in ForeachContainer(V v, vs) { ging.delV(pm->first, v); } // By now, pm->first will be an invalid pointer, as it will be been delete'd } } } P("deletions_accepted: %d\t", deletions_accepted); pair<V, int> delete_size; ForeachContainer(delete_size, deletions_sizes) { P("%d{%d} ", delete_size.second, delete_size.first); } P("\n"); PP(ging.groups.size()); //if(SaveScores && <API key>[0]) Pn("NOT Saving the delta-scores for each comm"); if(SaveScores && <API key>[0]) { Pn("Saving the MOSES delta-score for each community as per the --saveMOSESscores option"); ofstream saveFile(<API key>); ForeachContainer(Group *grp, ging.groups) { // preseed with all groups, because we want the groups even that don't have an edge in them! saveFile << proposed_deletions[grp] << '\t' << grp->vs.size() << endl; } } } long double P_x_given_z(const Grouping &ging, long double p_o, long double p_i, int sigma_shared_Xis1) { const int64 N = ging._g.vcount(); const int64 m = ging._g.ecount() / 2L; long double logP_XgivenZ = 0.0; logP_XgivenZ += log2l(1.0L - p_o) * (N * (N-1) / 2 - m); logP_XgivenZ += log2l(1.0L - p_i) * (ging._sigma_shared - sigma_shared_Xis1); typedef pair <int,V> edge_countT; ForeachContainer(const edge_countT &edge_count, ging.global_edge_counts) { const int64 s = edge_count.first; const int64 m_s = edge_count.second; logP_XgivenZ += log2l(1.0L - (1.0L - p_o)*powl(1.0L - p_i, s)) * m_s; } return logP_XgivenZ; } long double MOSES_objective(const Grouping &ging) { Timer t(__FUNCTION__); // Three components // P(x|z) // product of binomial/N+1 int64 sigma_shared_Xis1 = 0; pair <int,V> edge_count; ForeachContainer(edge_count, ging.global_edge_counts) { sigma_shared_Xis1 += edge_count.first * edge_count.second; } long double Pxz = P_x_given_z(ging, ging._p_out, ging._p_in, sigma_shared_Xis1); long double Pz = 0.0; for (size_t i = 1; i<=ging.groups.size(); i++) { Pz += log2l(i); //+ log2l(1+ging.groups.size())/*equivalent groupings*/ //P(Pz); } // PP(Pz); int64 N = ging._g.vcount(); ForeachContainer(const Group *grp, ging.groups) { long double logNchoosen = logNchoose(N,grp->vs.size()); DYINGWORDS(logNchoosen <= 0.0) { PP(logNchoosen); } assert(logNchoosen <= 0.0); Pz += logNchoosen - log2l(N+1) ; } // PP(Pxz); // PP(Pz); // PP(Pxz + Pz); // PP(ging.<API key>); if(ging.<API key>==1.0) Pn("Compression:\t%Lf\t%Lg\t%Lg", 1.0L ,Pz ,Pxz ); else Pn("Compression:\t%Lf\t%Lg\t%Lg", (Pxz + Pz) / ging.<API key> ,Pz ,Pxz ); return Pxz + Pz; } static void <API key>(Grouping &ging) { Timer t(__FUNCTION__); //PP(ging._sigma_shared); /* int64 _sigma_shared2 = 0; ForeachContainer(const Group *grp, ging.groups) { _sigma_shared2 += int64(grp->vs.size()) * int64(grp->vs.size()-1); } PP(_sigma_shared2/2); assert(_sigma_shared2 = 2 * ging._sigma_shared); */ const int64 N = ging._g.vcount(); const int64 m = ging._g.ecount() / 2L; int64 sigma_shared_Xis1 = 0; pair <int,V> edge_count; ForeachContainer(edge_count, ging.global_edge_counts) { sigma_shared_Xis1 += edge_count.first * edge_count.second; } //PP(sigma_shared_Xis1); map<long double, pair<long double, long double>, greater<long double> > ALLlogP_XgivenZ; for(long double p_i = 0.0L; (p_i+=0.001L) < 1.0L; ) { for(long double p_o = 1e-11L; (p_o*=1.1L) < 1.0L; ) { long double logP_XgivenZ = 0.0; logP_XgivenZ += log2l(1.0L - p_o) * (N * (N-1) / 2 - m); logP_XgivenZ += log2l(1.0L - p_i) * (ging._sigma_shared - sigma_shared_Xis1); ForeachContainer(edge_count, ging.global_edge_counts) { const int64 s = edge_count.first; const int64 m_s = edge_count.second; logP_XgivenZ += log2l(1.0L - (1.0L - p_o)*powl(1.0L - p_i, s)) * m_s; } assert(logP_XgivenZ == P_x_given_z(ging ,p_o ,p_i ,sigma_shared_Xis1)); ALLlogP_XgivenZ[logP_XgivenZ] = make_pair(p_i, p_o); } } pair<long double, pair<long double, long double> > best; ForeachContainer(best, ALLlogP_XgivenZ) { Pn("BEST: %Lg,%Lg -> %9.0Lf ", best.second.first, best.second.second, best.first); ging._p_in = best.second.first; ging._p_out= best.second.second; break; } } } // namespace overlapping
'use strict';var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) { if (typeof Reflect === "object" && typeof Reflect.decorate === "function") return Reflect.decorate(decorators, target, key, desc); switch (arguments.length) { case 2: return decorators.reduceRight(function(o, d) { return (d && d(o)) || o; }, target); case 3: return decorators.reduceRight(function(o, d) { return (d && d(target, key)), void 0; }, void 0); case 4: return decorators.reduceRight(function(o, d) { return (d && d(target, key, o)) || o; }, desc); } }; var __metadata = (this && this.__metadata) || function (k, v) { if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v); }; var collection_1 = require('angular2/src/facade/collection'); var lang_1 = require('angular2/src/facade/lang'); var exceptions_1 = require('angular2/src/facade/exceptions'); var <API key> = (function () { function <API key>() { } <API key>.prototype.supports = function (obj) { return obj instanceof Map || lang_1.isJsObject(obj); }; <API key>.prototype.create = function (cdRef) { return new <API key>(); }; <API key> = __decorate([ lang_1.CONST(), __metadata('design:paramtypes', []) ], <API key>); return <API key>; })(); exports.<API key> = <API key>; var <API key> = (function () { function <API key>() { this._records = new Map(); this._mapHead = null; this._previousMapHead = null; this._changesHead = null; this._changesTail = null; this._additionsHead = null; this._additionsTail = null; this._removalsHead = null; this._removalsTail = null; } Object.defineProperty(<API key>.prototype, "isDirty", { get: function () { return this._additionsHead !== null || this._changesHead !== null || this._removalsHead !== null; }, enumerable: true, configurable: true }); <API key>.prototype.forEachItem = function (fn) { var record; for (record = this._mapHead; record !== null; record = record._next) { fn(record); } }; <API key>.prototype.forEachPreviousItem = function (fn) { var record; for (record = this._previousMapHead; record !== null; record = record._nextPrevious) { fn(record); } }; <API key>.prototype.forEachChangedItem = function (fn) { var record; for (record = this._changesHead; record !== null; record = record._nextChanged) { fn(record); } }; <API key>.prototype.forEachAddedItem = function (fn) { var record; for (record = this._additionsHead; record !== null; record = record._nextAdded) { fn(record); } }; <API key>.prototype.forEachRemovedItem = function (fn) { var record; for (record = this._removalsHead; record !== null; record = record._nextRemoved) { fn(record); } }; <API key>.prototype.diff = function (map) { if (lang_1.isBlank(map)) map = collection_1.MapWrapper.createFromPairs([]); if (!(map instanceof Map || lang_1.isJsObject(map))) { throw new exceptions_1.BaseException("Error trying to diff '" + map + "'"); } if (this.check(map)) { return this; } else { return null; } }; <API key>.prototype.onDestroy = function () { }; <API key>.prototype.check = function (map) { var _this = this; this._reset(); var records = this._records; var oldSeqRecord = this._mapHead; var lastOldSeqRecord = null; var lastNewSeqRecord = null; var seqChanged = false; this._forEach(map, function (value, key) { var newSeqRecord; if (oldSeqRecord !== null && key === oldSeqRecord.key) { newSeqRecord = oldSeqRecord; if (!lang_1.looseIdentical(value, oldSeqRecord.currentValue)) { oldSeqRecord.previousValue = oldSeqRecord.currentValue; oldSeqRecord.currentValue = value; _this._addToChanges(oldSeqRecord); } } else { seqChanged = true; if (oldSeqRecord !== null) { oldSeqRecord._next = null; _this._removeFromSeq(lastOldSeqRecord, oldSeqRecord); _this._addToRemovals(oldSeqRecord); } if (records.has(key)) { newSeqRecord = records.get(key); } else { newSeqRecord = new KVChangeRecord(key); records.set(key, newSeqRecord); newSeqRecord.currentValue = value; _this._addToAdditions(newSeqRecord); } } if (seqChanged) { if (_this._isInRemovals(newSeqRecord)) { _this._removeFromRemovals(newSeqRecord); } if (lastNewSeqRecord == null) { _this._mapHead = newSeqRecord; } else { lastNewSeqRecord._next = newSeqRecord; } } lastOldSeqRecord = oldSeqRecord; lastNewSeqRecord = newSeqRecord; oldSeqRecord = oldSeqRecord === null ? null : oldSeqRecord._next; }); this._truncate(lastOldSeqRecord, oldSeqRecord); return this.isDirty; }; /** @internal */ <API key>.prototype._reset = function () { if (this.isDirty) { var record; // Record the state of the mapping for (record = this._previousMapHead = this._mapHead; record !== null; record = record._next) { record._nextPrevious = record._next; } for (record = this._changesHead; record !== null; record = record._nextChanged) { record.previousValue = record.currentValue; } for (record = this._additionsHead; record != null; record = record._nextAdded) { record.previousValue = record.currentValue; } // todo(vicb) once assert is supported // assert(() { // var r = _changesHead; // while (r != null) { // var nextRecord = r._nextChanged; // r._nextChanged = null; // r = nextRecord; // r = _additionsHead; // while (r != null) { // var nextRecord = r._nextAdded; // r._nextAdded = null; // r = nextRecord; // r = _removalsHead; // while (r != null) { // var nextRecord = r._nextRemoved; // r._nextRemoved = null; // r = nextRecord; // return true; this._changesHead = this._changesTail = null; this._additionsHead = this._additionsTail = null; this._removalsHead = this._removalsTail = null; } }; /** @internal */ <API key>.prototype._truncate = function (lastRecord, record) { while (record !== null) { if (lastRecord === null) { this._mapHead = null; } else { lastRecord._next = null; } var nextRecord = record._next; // todo(vicb) assert // assert((() { // record._next = null; // return true; this._addToRemovals(record); lastRecord = record; record = nextRecord; } for (var rec = this._removalsHead; rec !== null; rec = rec._nextRemoved) { rec.previousValue = rec.currentValue; rec.currentValue = null; this._records.delete(rec.key); } }; /** @internal */ <API key>.prototype._isInRemovals = function (record) { return record === this._removalsHead || record._nextRemoved !== null || record._prevRemoved !== null; }; /** @internal */ <API key>.prototype._addToRemovals = function (record) { // todo(vicb) assert // assert(record._next == null); // assert(record._nextAdded == null); // assert(record._nextChanged == null); // assert(record._nextRemoved == null); // assert(record._prevRemoved == null); if (this._removalsHead === null) { this._removalsHead = this._removalsTail = record; } else { this._removalsTail._nextRemoved = record; record._prevRemoved = this._removalsTail; this._removalsTail = record; } }; /** @internal */ <API key>.prototype._removeFromSeq = function (prev, record) { var next = record._next; if (prev === null) { this._mapHead = next; } else { prev._next = next; } // todo(vicb) assert // assert((() { // record._next = null; // return true; }; /** @internal */ <API key>.prototype._removeFromRemovals = function (record) { // todo(vicb) assert // assert(record._next == null); // assert(record._nextAdded == null); // assert(record._nextChanged == null); var prev = record._prevRemoved; var next = record._nextRemoved; if (prev === null) { this._removalsHead = next; } else { prev._nextRemoved = next; } if (next === null) { this._removalsTail = prev; } else { next._prevRemoved = prev; } record._prevRemoved = record._nextRemoved = null; }; /** @internal */ <API key>.prototype._addToAdditions = function (record) { // todo(vicb): assert // assert(record._next == null); // assert(record._nextAdded == null); // assert(record._nextChanged == null); // assert(record._nextRemoved == null); // assert(record._prevRemoved == null); if (this._additionsHead === null) { this._additionsHead = this._additionsTail = record; } else { this._additionsTail._nextAdded = record; this._additionsTail = record; } }; /** @internal */ <API key>.prototype._addToChanges = function (record) { // todo(vicb) assert // assert(record._nextAdded == null); // assert(record._nextChanged == null); // assert(record._nextRemoved == null); // assert(record._prevRemoved == null); if (this._changesHead === null) { this._changesHead = this._changesTail = record; } else { this._changesTail._nextChanged = record; this._changesTail = record; } }; <API key>.prototype.toString = function () { var items = []; var previous = []; var changes = []; var additions = []; var removals = []; var record; for (record = this._mapHead; record !== null; record = record._next) { items.push(lang_1.stringify(record)); } for (record = this._previousMapHead; record !== null; record = record._nextPrevious) { previous.push(lang_1.stringify(record)); } for (record = this._changesHead; record !== null; record = record._nextChanged) { changes.push(lang_1.stringify(record)); } for (record = this._additionsHead; record !== null; record = record._nextAdded) { additions.push(lang_1.stringify(record)); } for (record = this._removalsHead; record !== null; record = record._nextRemoved) { removals.push(lang_1.stringify(record)); } return "map: " + items.join(', ') + "\n" + "previous: " + previous.join(', ') + "\n" + "additions: " + additions.join(', ') + "\n" + "changes: " + changes.join(', ') + "\n" + "removals: " + removals.join(', ') + "\n"; }; /** @internal */ <API key>.prototype._forEach = function (obj, fn) { if (obj instanceof Map) { obj.forEach(fn); } else { collection_1.StringMapWrapper.forEach(obj, fn); } }; return <API key>; })(); exports.<API key> = <API key>; var KVChangeRecord = (function () { function KVChangeRecord(key) { this.key = key; this.previousValue = null; this.currentValue = null; /** @internal */ this._nextPrevious = null; /** @internal */ this._next = null; /** @internal */ this._nextAdded = null; /** @internal */ this._nextRemoved = null; /** @internal */ this._prevRemoved = null; /** @internal */ this._nextChanged = null; } KVChangeRecord.prototype.toString = function () { return lang_1.looseIdentical(this.previousValue, this.currentValue) ? lang_1.stringify(this.key) : (lang_1.stringify(this.key) + '[' + lang_1.stringify(this.previousValue) + '->' + lang_1.stringify(this.currentValue) + ']'); }; return KVChangeRecord; })(); exports.KVChangeRecord = KVChangeRecord; //# sourceMappingURL=<API key>.js.map
# Makefile for Sphinx documentation # You can set these variables from the command line. SPHINXOPTS = SPHINXBUILD = sphinx-build PAPER = BUILDDIR = build # User-friendly check for sphinx-build ifeq ($(shell which $(SPHINXBUILD) >/dev/null 2>&1; echo $$?), 1) $(error The '$(SPHINXBUILD)' command was not found. Make sure you have Sphinx installed, then set the SPHINXBUILD environment variable to point to the full path of the '$(SPHINXBUILD)' executable. Alternatively you can add the directory with the executable to your PATH. If you don't have Sphinx installed, grab it from http://sphinx-doc.org/) endif # Internal variables. PAPEROPT_a4 = -D latex_paper_size=a4 PAPEROPT_letter = -D latex_paper_size=letter ALLSPHINXOPTS = -d $(BUILDDIR)/doctrees $(PAPEROPT_$(PAPER)) $(SPHINXOPTS) source # the i18n builder cannot share the environment and doctrees with the others I18NSPHINXOPTS = $(PAPEROPT_$(PAPER)) $(SPHINXOPTS) source .PHONY: help clean html dirhtml singlehtml pickle json htmlhelp qthelp devhelp epub latex latexpdf text man changes linkcheck doctest gettext help: @echo "Please use \`make <target>' where <target> is one of" @echo " html to make standalone HTML files" @echo " dirhtml to make HTML files named index.html in directories" @echo " singlehtml to make a single large HTML file" @echo " pickle to make pickle files" @echo " json to make JSON files" @echo " htmlhelp to make HTML files and a HTML help project" @echo " qthelp to make HTML files and a qthelp project" @echo " devhelp to make HTML files and a Devhelp project" @echo " epub to make an epub" @echo " latex to make LaTeX files, you can set PAPER=a4 or PAPER=letter" @echo " latexpdf to make LaTeX files and run them through pdflatex" @echo " latexpdfja to make LaTeX files and run them through platex/dvipdfmx" @echo " text to make text files" @echo " man to make manual pages" @echo " texinfo to make Texinfo files" @echo " info to make Texinfo files and run them through makeinfo" @echo " gettext to make PO message catalogs" @echo " changes to make an overview of all changed/added/deprecated items" @echo " xml to make Docutils-native XML files" @echo " pseudoxml to make pseudoxml-XML files for display purposes" @echo " linkcheck to check all external links for integrity" @echo " doctest to run all doctests embedded in the documentation (if enabled)" clean:
#!/bin/bash fusermount -u ${MNT}/xiaomi
window.hideAlert = function () { $('#alertMessage').addClass("hidden"); $('#alertMessage').text(""); }; window.showAlert = function (msg) { $('#alertMessage').text(msg); $('#alertMessage').addClass("alert-danger"); $('#alertMessage').removeClass("hidden"); $('#alertMessage').fadeOut(100).fadeIn(100).fadeOut(100).fadeIn(100); }; window.showInfo = function (msg) { $('#alertMessage').text(msg); $('#alertMessage').removeClass("alert-danger"); $('#alertMessage').removeClass("hidden"); $('#alertMessage').fadeOut(100).fadeIn(100).fadeOut(100).fadeIn(100); }; window.dataErrorAlert = function (data) { switch (data.idError) { case "InvalidFile": showAlert(Resources["InvalidFile"]); break; case "InvalidReg": showAlert(Resources["WrongRegExpMessage"]); break; case "NotFound": showAlert(Resources["<API key>"]); break; case "InvalidPassword": showAlert(Resources["<API key>"]); break; default: showAlert(data.idError); break; } }; window.handleError = function (xhr, exception) { hideLoader(); $('#workButton').removeClass("hidden"); var msg = ''; if (xhr.status === 0) { msg = 'Not connect.\n Verify Network.'; } else if (xhr.status == 404) { msg = 'Requested page not found. [404]'; } else if (xhr.status == 500) { msg = 'Internal Server Error [500].'; } else if (exception === 'parsererror') { msg = 'Requested JSON parse failed.'; } else if (exception === 'timeout') { msg = 'Time out error.'; } else if (exception === 'abort') { msg = 'Ajax request aborted.'; } else { msg = 'Uncaught Error.\n' + xhr.responseText; } showAlert(msg); };
-- -- ## Project: HUD iLife ## -- ## For MTA: San Andreas ## -- ## Name: <API key>.lua ## -- -- -- -- -- FUNCTIONS / METHODS -- local cFunc = {}; -- Local Functions local cSetting = {}; -- Local Settings <API key> = {}; <API key>.__index = <API key>; ]] -- -- ///// New ////// -- ///// Returns: Object ////// -- function <API key>:New(...) local obj = setmetatable({}, {__index = self}); if obj.Constructor then obj:Constructor(...); end return obj; end -- -- ///// Toggle ////// -- ///// Returns: void ////// -- function <API key>:Toggle(bBool) local component_name = "weapons" if (bBool == nil) then hud.components[component_name].enabled = not (hud.components[component_name].enabled); else hud.components[component_name].enabled = bBool; end end -- -- ///// Render ////// -- ///// Returns: void ////// -- function <API key>:Render() local component_name = "weapons" local x, y = hud.components[component_name].sx, hud.components[component_name].sy; local w, h = hud.components[component_name].width*hud.components[component_name].zoom, hud.components[component_name].height*hud.components[component_name].zoom; local alpha = hud.components[component_name].alpha -- Hintergrund dxDrawImage(x, y, w, h, hud.pfade.images.."component_weapons/background.png", 0, 0, 0, tocolor(0, 134, 134, alpha/1.5)) dxDrawRectangle(x, y, w, h, tocolor(0, 0, 0, alpha/4)); local ammo = getPedAmmoInClip(localPlayer) local weapon = getPedWeapon(localPlayer) local totalammo = getPedTotalAmmo(localPlayer)-ammo; -- Image if(fileExists(hud.pfade.images.."component_weapons/weapons/"..weapon..".png")) then dxDrawImage(x+(5*hud.components[component_name].zoom), y+(5*hud.components[component_name].zoom), (64*1.5)*hud.components[component_name].zoom, (64*1.5)*hud.components[component_name].zoom, hud.pfade.images.."component_weapons/weapons/"..weapon..".png", 0, 0, 0, tocolor(255, 255, 255, alpha)); end dxDrawText(getWeaponNameFromID(weapon), x+5*hud.components[component_name].zoom, y+100*hud.components[component_name].zoom, x+(64*1.5)*hud.components[component_name].zoom, y+(64*1.5)*hud.components[component_name].zoom, tocolor(255, 255, 255, alpha/3), 0.2*hud.components[component_name].zoom, hud.fonts.audirmg, "center", "top", false, true) -- Munition -- Seite 1 local dingerProSeite = math.round(totalammo/2); local offsetX = 0; local addOffsetX = 50; local offsetY = 20; local maxOffsetY = h-10; local addOffsetY = totalammo/ for i = 1, 2, 1 do offsetY = 0; for i = 1, dingerProSeite, 1 do offsetY = offsetY+addOffsetY; end offsetX = offsetX+addOffsetX end]] local addx = (94*1.5)*hud.components[component_name].zoom local addy = 50*hud.components[component_name].zoom dxDrawText(ammo.."\n"..getPedTotalAmmo(localPlayer)-ammo, x+addx, y+addy, x+addx, y+addy, tocolor(255, 255, 255, alpha/3), 0.35*hud.components[component_name].zoom, hud.fonts.audirmg, "center", "top", false, true) -- MaxMuninGraph addx = addx+60*hud.components[component_name].zoom addy = addy-30*hud.components[component_name].zoom local max = 110 -- Hintergrund dxDrawRectangle(x+addx, y+h-32*hud.components[component_name].zoom, 40*hud.components[component_name].zoom, -max*hud.components[component_name].zoom, tocolor(0, 0, 0, alpha/3)) -- Was Vorhanden ist local vorhanden = max/(tonumber(getWeaponProperty(getWeaponNameFromID(weapon), "pro", "maximum_clip_ammo")) or 0)*ammo dxDrawRectangle(x+addx, y+h-32*hud.components[component_name].zoom, 40*hud.components[component_name].zoom, -vorhanden*hud.components[component_name].zoom, tocolor(74, 255, 101, alpha/3)) local prozent = math.round(100/(tonumber(getWeaponProperty(getWeaponNameFromID(weapon), "pro", "maximum_clip_ammo")) or 0)*ammo) if(prozent < 0) then prozent = 0 end dxDrawText(prozent.."%", x+170*hud.components[component_name].zoom, y+135*hud.components[component_name].zoom, x+(64*1.5)*hud.components[component_name].zoom+170*hud.components[component_name].zoom, y+(64*1.5)*hud.components[component_name].zoom+135*hud.components[component_name].zoom, tocolor(255, 255, 255, alpha/3), 0.2*hud.components[component_name].zoom, hud.fonts.audirmg, "center", "top") local ammo = getPedAmmoInClip(localPlayer) local weapon = getPedWeapon(localPlayer) local totalammo = getPedTotalAmmo(localPlayer)-ammo; if(ammo < 10) then ammo = "0"..ammo end if(self.enabled or hud.hudModifier.state == true) then -- Schrift local ammostring = ammo.."/#00B052"..totalammo; dxDrawText(string.rep("0", #string.gsub(ammostring, '#%x%x%x%x%x%x', '')), x, y+20*hud.components[component_name].zoom, x+w, y+h, tocolor(255, 255, 255, alpha/5), 0.5*hud.components[component_name].zoom, hud.fonts.audirmg, "center", "top") dxDrawText(ammostring, x, y+20*hud.components[component_name].zoom, x+w, y+h, tocolor(255, 255, 255, alpha), 0.5*hud.components[component_name].zoom, hud.fonts.audirmg, "center", "top", false, false, false, true) -- Image if(fileExists(hud.pfade.images.."component_weapons/weapons/"..weapon..".png")) then dxDrawImage(x+55*hud.components[component_name].zoom, y+70*hud.components[component_name].zoom, (286/2)*hud.components[component_name].zoom, (106/2)*hud.components[component_name].zoom, hud.pfade.images.."component_weapons/weapons/"..weapon..".png", 0, 0, 0, tocolor(255, 255, 255, 200)); end end]] end -- -- ///// GetTime ////// -- ///// Returns: String ////// -- function <API key>:GetTime() local time = getRealTime() local day = time.monthday local month = time.month+1 local year = time.year+1900 local hour = time.hour local minute = time.minute local second = time.second; if(hour < 10) then hour = "0"..hour; end if(minute < 10) then minute = "0"..minute; end if(second < 10) then second = "0"..second; end return day.."-"..month.."-"..year.." "..hour.."-"..minute.."-"..second; end -- -- ///// ShowComponent ////// -- ///// Returns: String ////// -- function <API key>:ShowComponent(bBool, prevSlot, newSlot) if(isTimer(self.showtimer)) then killTimer(self.showtimer); end self.forceRender = true; self.showtimer = setTimer(function() self.forceRender = false; end, 3000, 1) if(bBool == true) then if(getPedWeapon(getLocalPlayer(),newSlot) == 43) then if(hud) and (hud.enabled) then -- hud:Toggle(false); -- self.showHudAgain = true; -- showChat(false); end elseif(getPedWeapon(getLocalPlayer(),prevSlot) == 43) then if(self.showHudAgain) then if(hud) then -- showChat(true); -- hud:Toggle(true); end end end elseif(bBool == 43) then local x, y = guiGetScreenSize(); local tex = <API key>(x, y); <API key>(tex); -- Screenshots -- local pixels = dxGetTexturePixels(tex); if(pixels) then cancelEvent(); local image = dxConvertPixels(pixels, "png"); local date = "ilife-"..self:GetTime(); local file = fileCreate("screenshots/"..date..".png"); fileWrite(file, image); fileFlush(file); fileClose(file); else showInfoBox("error", "Da du deinen Screenshot Upload deaktiviert hast, wird keine Screenshot in deinem iLife ordner gespeichert!") end destroyElement(tex); end end -- -- ///// Constructor ////// -- ///// Returns: void ////// -- function <API key>:Constructor(...) self.enabled = true; self.forceRender = false; self.showtimer = nil; self.showComponentFunc = function(...) self:ShowComponent(...) end; self.showComponentFunc2 = function(...) self:ShowComponent(true, ...) end; self.showHudAgain = false; -- Events -- addEventHandler("<API key>", getLocalPlayer(),self.showComponentFunc) addEventHandler("<API key>", getLocalPlayer(),self.showComponentFunc) addEventHandler("<API key>", getLocalPlayer(),self.showComponentFunc2) -- outputDebugString("[CALLING] <API key>: Constructor"); end -- EVENT HANDLER --
# Scripts ## HashIncidentsFields - Fixed an issue where custom fields were returned by default as part of the incident object.
weekly_roundup: true title: "Roundup: Agile subway, retrospectives and appreciation, instant GraphQL API, fun counterfeits, less workdays" date: '2018-07-20 13:00:00 BST' authors: - 'Elena Tanasoiu' tags: # (Delete as appropriate) - Culture ## Agile Subway Map - [Richard S](/people#richard-stobart) https: Who knew that there was a Subway (Tube) map of the various Agile practices. _Lobs grenade and ducks for cover_ ## Retrospectives and Appreciation- [Richard S](/people#richard-Stobart) https: We didn't want another minute to go by without giving you a chance to top up your retro-mojo. ## Hasura - An instant GraphQL API on Postgres - [Elena T](/people#elena-tanasoiu) https://github.com/hasura/graphql-engine I love me a well documented tool that you can play around with right away. Docs here: https://docs.hasura.io/1.0/graphql/manual/index.html Main page here: https://hasura.io/ ## A fun teardown of an iPhone X counterfeit - [Elena T](/people#elena-tanasoiu) https://motherboard.vice.com/en_us/article/qvmkdd/<API key> I love the attention to detail put into this. It's even got its own (real!) IMEI number and face recognition (ish!). The notch at the top is re-created by software. Disclaimer: like any good counterfeit, it has backdoors and malicious code. Even so, I would still definitely like to try one for myself. ## Work less, get more: New Zealand firm's four-day week an 'unmitigated success' - [Elena T](/people#elena-tanasoiu) https: Work-life balance makes more progress, this time in New Zealand. ## Track of the Week - [Dawn T](/people#dawn-turner) We're going back in time this week as a result of my recent Netflix Mad Men binge in the coolness of my dark living room (I don't like hot weather). They wrote some good tunes back then, including this one.. enjoy! <iframe width="560" height="315" src="https: [Patti Page - Old Cape Cod](https:
# iTerm2 Puppet Module for Boxen ## Usage puppet # Stable release include iterm2::stable # Dev release include iterm2::dev ## Required Puppet Modules * boxen * stdlib
@font-face { font-family: 'Voltaire'; src: url("assets/Voltaire.eot"); src: url("Voltaire.eot?#iefix") format("embedded-opentype"), url("assets/Voltaire.woff") format("woff"), url("assets/Voltaire.ttf") format("truetype"), url("assets/Voltaire.svg#webfont") format("svg"); }
local pubsub = require "util.pubsub"; local st = require "util.stanza"; local jid_bare = require "util.jid".bare; local usermanager = require "core.usermanager"; local xmlns_pubsub = "http://jabber.org/protocol/pubsub"; local xmlns_pubsub_event = "http://jabber.org/protocol/pubsub#event"; local xmlns_pubsub_owner = "http://jabber.org/protocol/pubsub#owner"; local <API key> = module:get_option_boolean("<API key>", false); local <API key> = module:get_option_boolean("<API key>", false); local pubsub_disco_name = module:get_option("name"); if type(pubsub_disco_name) ~= "string" then pubsub_disco_name = "Prosody PubSub Service"; end local expose_publisher = module:get_option_boolean("expose_publisher", false) local service; local lib_pubsub = module:require "pubsub"; local handlers = lib_pubsub.handlers; local pubsub_error_reply = lib_pubsub.pubsub_error_reply; module:depends("disco"); module:add_identity("pubsub", "service", pubsub_disco_name); module:add_feature("http://jabber.org/protocol/pubsub"); function handle_pubsub_iq(event) local origin, stanza = event.origin, event.stanza; local pubsub = stanza.tags[1]; local action = pubsub.tags[1]; if not action then return origin.send(st.error_reply(stanza, "cancel", "bad-request")); end local handler = handlers[stanza.attr.type.."_"..action.name]; if handler then handler(origin, stanza, action, service); return true; end end function simple_broadcast(kind, node, jids, item, actor) if item then item = st.clone(item); item.attr.xmlns = nil; -- Clear the pubsub namespace if expose_publisher and actor then item.attr.publisher = actor end end local message = st.message({ from = module.host, type = "headline" }) :tag("event", { xmlns = xmlns_pubsub_event }) :tag(kind, { node = node }) :add_child(item); for jid in pairs(jids) do module:log("debug", "Sending notification to %s", jid); message.attr.to = jid; module:send(message); end end module:hook("iq/host/"..xmlns_pubsub..":pubsub", handle_pubsub_iq); module:hook("iq/host/"..xmlns_pubsub_owner..":pubsub", handle_pubsub_iq); local feature_map = { create = { "create-nodes", "instant-nodes", "item-ids" }; retract = { "delete-items", "retract-items" }; purge = { "purge-nodes" }; publish = { "publish", <API key> and "auto-create" }; delete = { "delete-nodes" }; get_items = { "retrieve-items" }; add_subscription = { "subscribe" }; get_subscriptions = { "<API key>" }; set_configure = { "config-node" }; get_default = { "retrieve-default" }; }; local function <API key>(service) for method, features in pairs(feature_map) do if service[method] then for _, feature in ipairs(features) do if feature then module:add_feature(xmlns_pubsub.."#"..feature); end end end end for affiliation in pairs(service.config.capabilities) do if affiliation ~= "none" and affiliation ~= "owner" then module:add_feature(xmlns_pubsub.."#"..affiliation.."-affiliation"); end end end module:hook("<API key>", function (event) local stanza, origin, reply, node = event.stanza, event.origin, event.reply, event.node; local ok, ret = service:get_nodes(stanza.attr.from); if not ok or not ret[node] then return; end event.exists = true; reply:tag("identity", { category = "pubsub", type = "leaf" }); end); module:hook("<API key>", function (event) local stanza, origin, reply, node = event.stanza, event.origin, event.reply, event.node; local ok, ret = service:get_items(node, stanza.attr.from); if not ok then return; end for _, id in ipairs(ret) do reply:tag("item", { jid = module.host, name = id }):up(); end event.exists = true; end); module:hook("host-disco-items", function (event) local stanza, origin, reply = event.stanza, event.origin, event.reply; local ok, ret = service:get_nodes(event.stanza.attr.from); if not ok then return; end for node, node_obj in pairs(ret) do reply:tag("item", { jid = module.host, node = node, name = node_obj.config.name }):up(); end end); local admin_aff = module:get_option_string("<API key>", "owner"); local unowned_aff = module:get_option_string("<API key>"); local function get_affiliation(jid, node) local bare_jid = jid_bare(jid); if bare_jid == module.host or usermanager.is_admin(bare_jid, module.host) then return admin_aff; end if not node then return unowned_aff; end end function set_service(new_service) service = new_service; module.environment.service = service; <API key>(service); end function module.save() return { service = service }; end function module.restore(data) set_service(data.service); end function module.load() if module.reloading then return; end set_service(pubsub.new({ capabilities = { none = { create = false; publish = false; retract = false; get_nodes = true; subscribe = true; unsubscribe = true; get_subscription = true; get_subscriptions = true; get_items = true; subscribe_other = false; unsubscribe_other = false; <API key> = false; <API key> = false; be_subscribed = true; be_unsubscribed = true; set_affiliation = false; }; publisher = { create = false; publish = true; retract = true; get_nodes = true; subscribe = true; unsubscribe = true; get_subscription = true; get_subscriptions = true; get_items = true; subscribe_other = false; unsubscribe_other = false; <API key> = false; <API key> = false; be_subscribed = true; be_unsubscribed = true; set_affiliation = false; }; owner = { create = true; publish = true; retract = true; delete = true; get_nodes = true; configure = true; subscribe = true; unsubscribe = true; get_subscription = true; get_subscriptions = true; get_items = true; subscribe_other = true; unsubscribe_other = true; <API key> = true; <API key> = true; be_subscribed = true; be_unsubscribed = true; set_affiliation = true; }; }; <API key> = <API key>; <API key> = <API key>; broadcaster = simple_broadcast; get_affiliation = get_affiliation; normalize_jid = jid_bare; })); end
#include <rpc/rpc.h>
<?php $mess=array( "Source Viewer" => "Afficheur de sources", "Syntax Highlighter for all major code source files" => "Coloration syntaxique pour la plupart des fichiers de code source", );
// <API key>.h // <API key> #import <UIKit/UIKit.h> //! Project version number for <API key>. FOUNDATION_EXPORT double <API key>; //! Project version string for <API key>. FOUNDATION_EXPORT const unsigned char <API key>[]; // In this header, you should import all the public headers of your framework using statements like #import <<API key>/PublicHeader.h>
// UIDevice+YYAdd.h #import <UIKit/UIKit.h> /** Provides extensions for `UIDevice`. */ @interface UIDevice (YYAdd) #pragma mark - Device Information ============================================================================= @name Device Information ============================================================================= Device system version (e.g. 8.1) + (float)systemVersion; Whether the device is iPad/iPad mini. @property (nonatomic, readonly) BOOL isPad; Whether the device is a simulator. @property (nonatomic, readonly) BOOL isSimulator; Whether the device is jailbroken. @property (nonatomic, readonly) BOOL isJailbroken; Wherher the device can make phone calls. @property (nonatomic, readonly) BOOL canMakePhoneCalls <API key>(""); The device's machine model. e.g. "iPhone6,1" "iPad4,6" @see http://theiphonewiki.com/wiki/Models @property (nonatomic, readonly) NSString *machineModel; The device's machine model name. e.g. "iPhone 5s" "iPad mini 2" @see http://theiphonewiki.com/wiki/Models @property (nonatomic, readonly) NSString *machineModelName; The System's startup time. @property (nonatomic, readonly) NSDate *systemUptime; #pragma mark - Network Information ============================================================================= @name Network Information ============================================================================= WIFI IP address of this device (can be nil). e.g. @"192.168.1.111" @property (nonatomic, readonly) NSString *ipAddressWIFI; Cell IP address of this device (can be nil). e.g. @"10.2.2.222" @property (nonatomic, readonly) NSString *ipAddressCell; #pragma mark - Disk Space ============================================================================= @name Disk Space ============================================================================= Total disk space in byte. (-1 when error occurs) @property (nonatomic, readonly) int64_t diskSpace; Free disk space in byte. (-1 when error occurs) @property (nonatomic, readonly) int64_t diskSpaceFree; Used disk space in byte. (-1 when error occurs) @property (nonatomic, readonly) int64_t diskSpaceUsed; #pragma mark - Memory Information ============================================================================= @name Memory Information ============================================================================= Total physical memory in byte. (-1 when error occurs) @property (nonatomic, readonly) int64_t memoryTotal; Used (active + inactive + wired) memory in byte. (-1 when error occurs) @property (nonatomic, readonly) int64_t memoryUsed; Free memory in byte. (-1 when error occurs) @property (nonatomic, readonly) int64_t memoryFree; Acvite memory in byte. (-1 when error occurs) @property (nonatomic, readonly) int64_t memoryActive; Inactive memory in byte. (-1 when error occurs) @property (nonatomic, readonly) int64_t memoryInactive; Wired memory in byte. (-1 when error occurs) @property (nonatomic, readonly) int64_t memoryWired; Purgable memory in byte. (-1 when error occurs) @property (nonatomic, readonly) int64_t memoryPurgable; #pragma mark - CPU Information ============================================================================= @name CPU Information ============================================================================= Avaliable CPU processor count. @property (nonatomic, readonly) NSUInteger cpuCount; Current CPU usage, 1.0 means 100%. (-1 when error occurs) @property (nonatomic, readonly) float cpuUsage; Current CPU usage per processor (array of NSNumber), 1.0 means 100%. (nil when error occurs) @property (nonatomic, readonly) NSArray *<API key>; @end #ifndef kSystemVersion #define kSystemVersion [UIDevice systemVersion] #endif #ifndef kiOS6Later #define kiOS6Later (kSystemVersion >= 6) #endif #ifndef kiOS7Later #define kiOS7Later (kSystemVersion >= 7) #endif #ifndef kiOS8Later #define kiOS8Later (kSystemVersion >= 8) #endif #ifndef kiOS9Later #define kiOS9Later (kSystemVersion >= 9) #endif
<!DOCTYPE HTML PUBLIC "- <!-- NewPage --> <html lang="en"> <head> <!-- Generated by javadoc (1.8.0_101) on Wed Sep 21 04:14:05 CEST 2016 --> <title>com.snakybo.torch.graphics.shader (Torch Engine 1.0 API)</title> <meta name="date" content="2016-09-21"> <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.snakybo.torch.graphics.shader (Torch Engine 1.0 API)"; } } catch(err) { } </script> <noscript> <div>JavaScript is disabled on your browser.</div> </noscript> <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="../../../../../overview-summary.html">Overview</a></li> <li class="navBarCell1Rev">Package</li> <li>Class</li> <li><a href="package-tree.html">Tree</a></li> <li><a href="../../../../../deprecated-list.html">Deprecated</a></li> <li><a href="../../../../../index-all.html">Index</a></li> <li><a href="../../../../../help-doc.html">Help</a></li> </ul> </div> <div class="subNav"> <ul class="navList"> <li><a href="../../../../../com/snakybo/torch/graphics/renderer/package-summary.html">Prev&nbsp;Package</a></li> <li><a href="../../../../../com/snakybo/torch/graphics/texture/package-summary.html">Next&nbsp;Package</a></li> </ul> <ul class="navList"> <li><a href="../../../../../index.html?com/snakybo/torch/graphics/shader/package-summary.html" target="_top">Frames</a></li> <li><a href="package-summary.html" target="_top">No&nbsp;Frames</a></li> </ul> <ul class="navList" id="<API key>"> <li><a href="../../../../../allclasses-noframe.html">All&nbsp;Classes</a></li> </ul> <div> <script type="text/javascript"><! allClassesLink = document.getElementById("<API key>"); if(window==top) { allClassesLink.style.display = "block"; } else { allClassesLink.style.display = "none"; } </script> </div> <a name="skip.navbar.top"> </a></div> <div class="header"> <h1 title="Package" class="title">Package&nbsp;com.snakybo.torch.graphics.shader</h1> </div> <div class="contentContainer"> <ul class="blockList"> <li class="blockList"> <table class="typeSummary" border="0" cellpadding="3" cellspacing="0" summary="Class Summary table, listing classes, and an explanation"> <caption><span>Class Summary</span><span class="tabEnd">&nbsp;</span></caption> <tr> <th class="colFirst" scope="col">Class</th> <th class="colLast" scope="col">Description</th> </tr> <tbody> <tr class="altColor"> <td class="colFirst"><a href="../../../../../com/snakybo/torch/graphics/shader/Shader.html" title="class in com.snakybo.torch.graphics.shader">Shader</a></td> <td class="colLast"> <div class="block"> The shader class is a direct link to the low-level GLSL shaders.</div> </td> </tr> <tr class="rowColor"> <td class="colFirst"><a href="../../../../../com/snakybo/torch/graphics/shader/ShaderInternal.html" title="class in com.snakybo.torch.graphics.shader">ShaderInternal</a></td> <td class="colLast">&nbsp;</td> </tr> </tbody> </table> </li> </ul> </div> <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="../../../../../overview-summary.html">Overview</a></li> <li class="navBarCell1Rev">Package</li> <li>Class</li> <li><a href="package-tree.html">Tree</a></li> <li><a href="../../../../../deprecated-list.html">Deprecated</a></li> <li><a href="../../../../../index-all.html">Index</a></li> <li><a href="../../../../../help-doc.html">Help</a></li> </ul> </div> <div class="subNav"> <ul class="navList"> <li><a href="../../../../../com/snakybo/torch/graphics/renderer/package-summary.html">Prev&nbsp;Package</a></li> <li><a href="../../../../../com/snakybo/torch/graphics/texture/package-summary.html">Next&nbsp;Package</a></li> </ul> <ul class="navList"> <li><a href="../../../../../index.html?com/snakybo/torch/graphics/shader/package-summary.html" target="_top">Frames</a></li> <li><a href="package-summary.html" target="_top">No&nbsp;Frames</a></li> </ul> <ul class="navList" id="<API key>"> <li><a href="../../../../../allclasses-noframe.html">All&nbsp;Classes</a></li> </ul> <div> <script type="text/javascript"><! allClassesLink = document.getElementById("<API key>"); if(window==top) { allClassesLink.style.display = "block"; } else { allClassesLink.style.display = "none"; } </script> </div> <a name="skip.navbar.bottom"> </a></div> </body> </html>
define('controllers/panel',['require','jquery','backbone','utils/metrics','utils/browser','utils/video-player','utils/pubsub','controllers/panel-display'],function(require) { var $ = require('jquery'), Backbone = require('backbone'), Metrics = require('utils/metrics'), Browser = require('utils/browser'), VideoPlayer = require('utils/video-player'), PubSub = require('utils/pubsub'), PanelDisplay = require('controllers/panel-display') ; var PanelView = Backbone.View.extend({ events: { }, panelOn: false, minWidth: 320, minHeight: 180, leftLimit: 100, topLimit: 100, offset: 10, border: 5, initialize: function() { Browser.<API key>(); this.logger = new eventsCore.util.Logger('PanelView'); this.panel1 = new PanelDisplay({el: '#panel1'}).render(); this.panel2 = new PanelDisplay({el: '#panel2'}).render(); //this.logger.info('initialize - panel1:%o panel2:%o', this.panel1, this.panel2); this.on('route:change', this.checkPage); this.listenTo(PubSub, 'video:playPanel', this.onPlayPanel); this.listenTo(PubSub, 'video:exitPanel', this.onExitPanel); this.listenTo(PubSub, 'video:resetHero', this.onResetHero); this.listenTo(PubSub, 'video:resetVod', this.onResetVod); this.listenTo(VideoPlayer, 'player:play', this.onPlayEvent); this.listenTo(VideoPlayer, 'player:panelOpen', this.onPanelOpenEvent); this.listenTo(VideoPlayer, 'player:panelClosed', this.onPanelClosedEvent); }, render: function() { return this; }, /** * checks state/position of each panel and updates initial mute status * executes on play and route change */ checkVolume: function() { this.logger.info('checkVolume - panel1:%o panel2:%o', this.panel1.state(), this.panel2.state()); if (this.panel1.state() != '' && this.panel2.state() == '') { this.panel1.mute(false); this.panel2.mute(true); } else if (this.panel2.state() != '' && this.panel1.state() == '') { this.panel2.mute(false); this.panel1.mute(true); } else if (this.panel1.state() == 'floatVideo' && this.panel2.state() == 'heroVideo') { this.panel2.mute(false); this.panel1.mute(true); } else if (this.panel1.state() == 'heroVideo' && this.panel2.state() == 'floatVideo') { this.panel1.mute(false); this.panel2.mute(true); } }, /** * close any open hero panel * - used for mobile internal ref to a different watch live channel */ onResetHero: function() { if(this.panel1.state() === 'heroVideo') { this.panel1.onPanelExit(); } else if(this.panel2.state() === 'heroVideo') { this.panel2.onPanelExit(); } }, /** * close any open vod floated panel */ onResetVod: function() { if(this.panel1.state() === 'floatVideo') { this.panel1.onPanelExit(); } else if(this.panel2.state() === 'floatVideo') { this.panel2.onPanelExit(); } }, /** * play video in a panel, check for channel existing in panel first and use existing if playing * @param data - panel video data * @param channel - this live video data * @param options - options to be passed to video player, consisting of: * floated - optional boolean indicating if should start in float mode * vod - indicates if playing a vod */ onPlayPanel: function(data, channel, options) { options = _.extend({ floated: false, vod: false }, options); this.logger.info('onPlayPanel - panel1:%o chan1:%o panel2:%o chan2:%o data:%o', this.panel1.state(), this.panel1.channelId(), this.panel2.state(), this.panel2.channelId(), data); //if panel1 floating and opening the same channel, close to hero (to force back to hero when return to live channel page) // do not close if float is true, call is trying to open same channel in already open float panel if (this.panel1.channelId() == data[0].id) { // if panel has no state, reset it to play channel if(this.panel1.state() === '') { this.panel1.playPanel(data, channel, options); } else if (this.panel1.state() == 'floatVideo' && !options.floated) this.panel1.panelClose(data, false); else this.logger.warn('onPlayPanel - ignoring call, attempted to open same channel already active'); } //if panel2 floating and opening the same channel, close to hero (to force back to hero when return to live channel page) // do not close if float is true, call i trying to open same channel in already open float panel else if (this.panel2.channelId() == data[0].id){ // if panel has no state, reset it to play channel if(this.panel2.state() === '') { this.panel2.playPanel(data, channel, options); } else if (this.panel2.state() == 'floatVideo' && !options.floated) this.panel2.panelClose(data, false); else this.logger.warn('onPlayPanel - ignoring call, attempted to open same channel to floating panel'); } //if panel1 in hero use it, (if not playing this channel) else if ((this.panel1.state() == 'heroVideo' || this.panel1.state() == '') && this.panel1.channelId() != data[0].id) { this.panel1.playPanel(data, channel, options); } //else use panel2 (if not playing this channel) else if (this.panel2.channelId() != data[0].id){ this.panel2.playPanel(data, channel, options); } }, /** * exit video playing in panel, whichever panel is open */ onExitPanel: function() { this.logger.info('onExitPanel - panel1:%o chan1:%o panel2:%o chan2:%o', this.panel1.state(), this.panel1.channelId(), this.panel2.state(), this.panel2.channelId()); // close whichever one is floated if(this.panel1.state() === 'floatVideo') { this.panel1.onPanelExit(); } else if(this.panel2.state() === 'floatVideo') { this.panel2.onPanelExit(); } }, /** * on play, initiates check for setting initial mute * @param data - event data with panel id */ onPlayEvent: function(data) { //this.logger.info('onPlayEvent - data:%o', data.id); if (data.id == 'panel1' || data.id == 'panel2') this.checkVolume(); }, /** * handle panel open event from video player * triggers panel to transition to float state * @param data - event data with panel id */ onPanelOpenEvent: function(data) { this.logger.info('onPanelOpenEvent - panel1:%o panel2:%o id:%o', this.panel1.state(), this.panel2.state(), data.id); if(data.id == 'panel1') { if (this.panel2.state() == 'floatVideo') { this.panel2.panelClose(null, false); } this.panel1.panelOpen(); } else if(data.id == 'panel2') { if (this.panel1.state() == 'floatVideo') { this.panel1.panelClose(null, false); } this.panel2.panelOpen(); } }, /** * handle panel close event from video player * triggers panel to return to hero state * @param data - event data with panel id */ onPanelClosedEvent: function(data) { this.logger.info('onPanelClosedEvent - panel1:%o panel2:%o id:%o', this.panel1.state(), this.panel2.state(), data.id); if(data.id == 'panel1') { this.panel1.panelClose(data, true); if (this.panel2.state() == 'heroVideo') { this.panel2.panelClose(data, false); this.checkVolume(); } } else if(data.id == 'panel2') { this.panel2.panelClose(data, true); if (this.panel1.state() == 'heroVideo') { this.panel1.panelClose(data, false); this.checkVolume(); } } }, /** * initiate page check for closing hero on route change * also check volume on route change */ checkPage: function(){ var route = Backbone.history.getFragment(); this.panel1.checkPage(route); this.panel2.checkPage(route); this.checkVolume(); } }); return PanelView; }) ;
// Design Basic Game Solo Challenge // This is a solo challenge // Your mission description:To complete a line of the same figure, horizontal, diagonal or vertical // Overall mission: To win all the time :) // Goals: make a line of the same kind before computer does // Characters:You and the computer // Objects:tic tac toe // Functions:clear_board, refresh_board, turn // Pseudocode // Make a Tictactoe class // Initialize the instance // Paint the board // Take a turn UNTIL someones win // Check if some one won // Clear the board // Initial Code turns = 0 board_state = [[" "," "," "], [" "," "," "], [" "," "," "]]; var Tictactoe = { take_turn : function(user){ mark = prompt("It is your turn, where do you want to mark?"); horizontal = mark[1]; vertical = mark[0].toUpperCase(); if (vertical == "A"){ vertical = 0 } else if (vertical == "B"){ vertical = 1 } else { vertical = 2 } board_state[horizontal-1][vertical] = user console.log(board_state) }, print_board : function(){ line = "" console.log(" A B C") for (i in board_state){ new_line = "\n \n" for (x in board_state[i]){ ln = parseInt(i); if (x == 0){line = (ln+1)+" "} if (x == 2) { if (i == 2){new_line = "\n"} line += " "+board_state[i][x]+new_line; } else { line += " "+board_state[i][x]+" " } } console.log(line); } } } alert ("Welcome to @cyberpolin's Tic Tac Toe\n So it is the turn of User 1, please select where you want to mark...") Tictactoe.print_board() while (turns < 9){ if (turns%2 == 0){ Tictactoe.take_turn("o"); } else { Tictactoe.take_turn("x"); } Tictactoe.print_board(); turns++; } // RELECTION // What was the most difficult part of this challenge? // Order my toughts to make the code works as i wannted, also as javascript is not a language thinked for terminal it was difficult to figure out how it was going to work. // What did you learn about creating objects and functions that interact with one another? // Is like in ruby, i think of them as just methods // Did you learn about any new built-in methods you could use in your refactored solution? If so, what were they and how do they work? // The only one i used was toUpperCase, ad they are like Ruby methods even tough Javascript have a different syntax. // How can you access and manipulate properties of objects? // like in Ruby object[property] = new_value, or the JS way object.property = new_value // TODO'S // Check if a place is marked already // Check if you have winned // Make it playable with computer // MAKE IT GRAPHICAL!!!!
using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.UI; using System.Web.UI.WebControls; namespace Company { public partial class Site : System.Web.UI.MasterPage { protected void Page_Load(object sender, EventArgs e) { } } }
#if __SC__ || __RCC__ #pragma once #endif #ifndef RC_INVOKED #pragma pack(__DEFALIGN) #endif #include <win32\scdefs.h> #include <win32\LMCONFIG.H> #ifndef RC_INVOKED #pragma pack() #endif
<?php /** * Convert container abstract * * @category Mage * @package Mage_Dataflow * @author Magento Core Team <core@magentocommerce.com> */ abstract class <API key> implements <API key> { protected $_batchParams = array(); protected $_vars; protected $_profile; protected $_action; protected $_data; protected $_position; public function getVar($key, $default=null) { if (!isset($this->_vars[$key]) || (!is_array($this->_vars[$key]) && strlen($this->_vars[$key]) == 0)) { return $default; } return $this->_vars[$key]; } public function getVars() { return $this->_vars; } public function setVar($key, $value=null) { if (is_array($key) && is_null($value)) { $this->_vars = $key; } else { $this->_vars[$key] = $value; } return $this; } public function getAction() { return $this->_action; } public function setAction(<API key> $action) { $this->_action = $action; return $this; } public function getProfile() { return $this->_profile; } public function setProfile(<API key> $profile) { $this->_profile = $profile; return $this; } public function getData() { if (is_null($this->_data) && $this->getProfile()) { $this->_data = $this->getProfile()->getContainer()->getData(); } return $this->_data; } public function setData($data) { if ($this->getProfile()) { $this->getProfile()->getContainer()->setData($data); } $this->_data = $data; return $this; } public function validateDataString($data=null) { if (is_null($data)) { $data = $this->getData(); } if (!is_string($data)) { $this->addException("Invalid data type, expecting string.", <API key>::FATAL); } return true; } public function validateDataArray($data=null) { if (is_null($data)) { $data = $this->getData(); } if (!is_array($data)) { $this->addException("Invalid data type, expecting array.", <API key>::FATAL); } return true; } public function validateDataGrid($data=null) { if (is_null($data)) { $data = $this->getData(); } if (!is_array($data) || !is_array(current($data))) { if (count($data)==0) { return true; } $this->addException("Invalid data type, expecting 2D grid array.", <API key>::FATAL); } return true; } public function getGridFields($grid) { $fields = array(); foreach ($grid as $i=>$row) { foreach ($row as $fieldName=>$data) { if (!in_array($fieldName, $fields)) { $fields[] = $fieldName; } } } return $fields; } public function addException($error, $level=null) { $e = new <API key>($error); $e->setLevel(!is_null($level) ? $level : <API key>::NOTICE); $e->setContainer($this); $e->setPosition($this->getPosition()); if ($this->getProfile()) { $this->getProfile()->addException($e); } return $e; } public function getPosition() { return $this->_position; } public function setPosition($position) { $this->_position = $position; return $this; } public function setBatchParams($data) { if (is_array($data)) { $this->_batchParams = $data; } return $this; } public function getBatchParams($key = null) { if (!empty($key)) { return isset($this->_batchParams[$key]) ? $this->_batchParams[$key] : null; } return $this->_batchParams; } }
package com.microsoft.azure.management.monitor; import com.fasterxml.jackson.annotation.JsonProperty; /** * Part of <API key>. Specifies the settings for a * particular log. */ public class LogSettings { /** * Name of a Diagnostic Log category for a resource type this setting is * applied to. To obtain the list of Diagnostic Log categories for a * resource, first perform a GET diagnostic settings operation. */ @JsonProperty(value = "category") private String category; /** * a value indicating whether this log is enabled. */ @JsonProperty(value = "enabled", required = true) private boolean enabled; /** * the retention policy for this log. */ @JsonProperty(value = "retentionPolicy") private RetentionPolicy retentionPolicy; /** * Get the category value. * * @return the category value */ public String category() { return this.category; } /** * Set the category value. * * @param category the category value to set * @return the LogSettings object itself. */ public LogSettings withCategory(String category) { this.category = category; return this; } /** * Get the enabled value. * * @return the enabled value */ public boolean enabled() { return this.enabled; } /** * Set the enabled value. * * @param enabled the enabled value to set * @return the LogSettings object itself. */ public LogSettings withEnabled(boolean enabled) { this.enabled = enabled; return this; } /** * Get the retentionPolicy value. * * @return the retentionPolicy value */ public RetentionPolicy retentionPolicy() { return this.retentionPolicy; } /** * Set the retentionPolicy value. * * @param retentionPolicy the retentionPolicy value to set * @return the LogSettings object itself. */ public LogSettings withRetentionPolicy(RetentionPolicy retentionPolicy) { this.retentionPolicy = retentionPolicy; return this; } }
// GridFS exports.GridFS = require('./lib/GridFS'); exports.GridStream = require('./lib/GridStream');
// @flow class A { x = [1, 2, 3]; y = 4; foo() { this.x = this.x.map(function (z) { this.y; // error, function has wrong this }); } } class B { x = [1, 2, 3]; y = 4; foo() { this.x = this.x.map(function (z) { this.y; // ok, function gets passed correct this }, this); } } class C { x = [1, 2, 3]; y = 4; foo() { this.x = this.x.map(z => { this.y; // ok, arrow binds surrounding context this }); } }
import collectionClass from "./collections.class"; import collectionColor from "./collections.color"; function <API key>(contentItem) { return ` .${collectionClass(contentItem)} { background-color: #${collectionColor(contentItem)}; } `; } export default <API key>;
<?php if(filemtime(__FILE__) + 600 < time())return false; return array ( 'inbox' => '0', 'outbox' => '0', 'total' => 0, ); ?>
Copyright (c) 2016 Calvin Rose Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. ]] -- A filesystem abstraction on top of luv. Uses non-blocking coroutines -- when available, otherwise uses blocking calls. -- Modified from https://github.com/luvit/lit/blob/master/deps/coro-fs.lua Abstractions around the libuv filesystem. -- @module moonmint.fs -- @author Calvin Rose local uv = require 'luv' local pathJoin = require('moonmint.deps.pathjoin').pathJoin local fs = {} local corunning = coroutine.running local coresume = coroutine.resume local coyield = coroutine.yield local function noop() end local function makeCallback(sync) local thread = corunning() if thread and not sync then -- Non Blocking callback (coroutines) return function (err, value, ...) if err then assert(coresume(thread, nil, err)) else assert(coresume(thread, value == nil and true or value, ...)) end end else -- Blocking callback local context = {} return function (err, first, ...) context.done = true context.err = err context.first = first context.values = {...} end, context end end local unpack = unpack or table.unpack local function tryYield(context) if context then -- Blocking while not context.done do uv.run('once') -- Should we use the default event loop? end local err = context.err local first = context.first if err then return nil, err else return first == nil and true or first, unpack(context.values) end else -- Non blocking return coyield() end end Wrapper around uv.fs_mkdir function fs.mkdir(sync, path, mode) local cb, context = makeCallback(sync) uv.fs_mkdir(path, mode or 511, cb) return tryYield(context) end Wrapper around uv.fs_open function fs.open(sync, path, flags, mode) local cb, context = makeCallback(sync) uv.fs_open(path, flags or "r", mode or 428, cb) return tryYield(context) end Wrapper around uv.fs_unlink function fs.unlink(sync, path) local cb, context = makeCallback(sync) uv.fs_unlink(path, cb) return tryYield(context) end Wrapper around uv.fs_stat function fs.stat(sync, path) local cb, context = makeCallback(sync) uv.fs_stat(path, cb) return tryYield(context) end Wrapper around uv.fs_lstat function fs.lstat(sync, path) local cb, context = makeCallback(sync) uv.fs_lstat(path, cb) return tryYield(context) end Wrapper around uv.fs_fstat function fs.fstat(sync, fd) local cb, context = makeCallback(sync) uv.fs_fstat(fd, cb) return tryYield(context) end Wrapper around uv.fs_chmod function fs.chmod(sync, path) local cb, context = makeCallback(sync) uv.fs_chmod(path, cb) return tryYield(context) end Wrapper around uv.fs_fchmod function fs.fchmod(sync, path) local cb, context = makeCallback(sync) uv.fs_fchmod(path, cb) return tryYield(context) end Wrapper around uv.fs_read function fs.read(sync, fd, length, offset) local cb, context = makeCallback(sync) uv.fs_read(fd, length or 1024 * 48, offset or -1, cb) return tryYield(context) end Wrapper around uv.fs_write function fs.write(sync, fd, data, offset) local cb, context = makeCallback(sync) uv.fs_write(fd, data, offset or -1, cb) return tryYield(context) end Wrapper around uv.fs_close function fs.close(sync, fd) local cb, context = makeCallback(sync) uv.fs_close(fd, cb) return tryYield(context) end Wrapper around uv.fs_symlink function fs.symlink(sync, target, path) local cb, context = makeCallback(sync) uv.fs_symlink(target, path, cb) return tryYield(context) end Wrapper around uv.fs_readlink function fs.readlink(sync, path) local cb, context = makeCallback(sync) uv.fs_readlink(path, cb) return tryYield(context) end Wrapper around uv.fs_access function fs.access(sync, path, flags) local cb, context = makeCallback(sync) uv.fs_access(path, flags or '', cb) return tryYield(context) end Wrapper around uv.fs_rmdir function fs.rmdir(sync, path) local cb, context = makeCallback(sync) uv.fs_rmdir(path, cb) return tryYield(context) end Remove directories recursively like the UNIX command `rm -rf`. function fs.rmrf(sync, path) local success, err = fs.rmdir(sync, path) if success then return success, err end if err:match('^ENOTDIR:') then return fs.unlink(sync, path) end if not err:match('^ENOTEMPTY:') then return success, err end for entry in assert(fs.scandir(sync, path)) do local subPath = pathJoin(path, entry.name) if entry.type == 'directory' then success, err = fs.rmrf(sync, pathJoin(path, entry.name)) else success, err = fs.unlink(sync, subPath) end if not success then return success, err end end return fs.rmdir(sync, path) end Smart wrapper around uv.fs_scandir. -- @treturn function an iterator over file objects -- in a directory. Each file table has a `name` property -- and a `type` property. function fs.scandir(sync, path) local cb, context = makeCallback(sync) uv.fs_scandir(path, cb) local req, err = tryYield(context) if not req then return nil, err end return function () local name, typ = uv.fs_scandir_next(req) if not name then return name, typ end if type(name) == "table" then return name end return { name = name, type = typ } end end Reads a file into a string function fs.readFile(sync, path) local fd, stat, data, err fd, err = fs.open(sync, path) if err then return nil, err end stat, err = fs.fstat(sync, fd) if stat then data, err = fs.read(sync, fd, stat.size) end uv.fs_close(fd, noop) return data, err end Writes a string to a file. Overwrites the file -- if it already exists. function fs.writeFile(sync, path, data, mkdir) local fd, success, err fd, err = fs.open(sync, path, "w") if err then if mkdir and err:match("^ENOENT:") then success, err = fs.mkdirp(sync, pathJoin(path, "..")) if success then return fs.writeFile(sync, path, data) end end return nil, err end success, err = fs.write(sync, fd, data) uv.fs_close(fd, noop) return success, err end Append a string to a file. function fs.appendFile(sync, path, data, mkdir) local fd, success, err fd, err = fs.open(sync, path, "w+") if err then if mkdir and err:match("^ENOENT:") then success, err = fs.mkdirp(sync, pathJoin(path, "..")) if success then return fs.appendFile(sync, path, data) end end return nil, err end success, err = fs.write(sync, fd, data) uv.fs_close(fd, noop) return success, err end Make directories recursively. Similar to the UNIX `mkdir -p`. function fs.mkdirp(sync, path, mode) local success, err = fs.mkdir(sync, path, mode) if success or err:match("^EEXIST") then return true end if err:match("^ENOENT:") then success, err = fs.mkdirp(sync, pathJoin(path, ".."), mode) if not success then return nil, err end return fs.mkdir(sync, path, mode) end return nil, err end -- Make sync and async versions local function makeAliases(module) local ret = {} local ext = {} local sync = {} for k, v in pairs(module) do if type(v) == 'function' then if k == 'chroot' then sync[k], ext[k], ret[k] = v, v, v else sync[k] = function(...) return v(true, ...) end ext[k] = v ret[k] = function(...) return v(false, ...) end end end end ret.s = sync ret.sync = sync ret.ext = ext return ret end Creates a clone of fs, but with a different base directory. function fs.chroot(base) local chroot = { base = base, fstat = fs.fstat, fchmod = fs.fchmod, read = fs.read, write = fs.write, close = fs.close, } local function resolve(path) assert(path, "path missing") return pathJoin(base, pathJoin(path)) end function chroot.mkdir(sync, path, mode) return fs.mkdir(sync, resolve(path), mode) end function chroot.mkdirp(sync, path, mode) return fs.mkdirp(sync, resolve(path), mode) end function chroot.open(sync, path, flags, mode) return fs.open(sync, resolve(path), flags, mode) end function chroot.unlink(sync, path) return fs.unlink(sync, resolve(path)) end function chroot.stat(sync, path) return fs.stat(sync, resolve(path)) end function chroot.lstat(sync, path) return fs.lstat(sync, resolve(path)) end function chroot.symlink(sync, target, path) -- TODO: should we resolve absolute target paths or treat it as opaque data? return fs.symlink(sync, target, resolve(path)) end function chroot.readlink(sync, path) return fs.readlink(sync, resolve(path)) end function chroot.chmod(sync, path, mode) return fs.chmod(sync, resolve(path), mode) end function chroot.access(sync, path, flags) return fs.access(sync, resolve(path), flags) end function chroot.rename(sync, path, newPath) return fs.rename(sync, resolve(path), resolve(newPath)) end function chroot.rmdir(sync, path) return fs.rmdir(sync, resolve(path)) end function chroot.rmrf(sync, path) return fs.rmrf(sync, resolve(path)) end function chroot.scandir(sync, path) return fs.scandir(sync, resolve(path)) end function chroot.readFile(sync, path) return fs.readFile(sync, resolve(path)) end function chroot.writeFile(sync, path, data, mkdir) return fs.writeFile(sync, resolve(path), data, mkdir) end function chroot.appendFile(sync, path, data, mkdir) return fs.appendFile(sync, resolve(path), data, mkdir) end function chroot.chroot(sync, newBase) return fs.chroot(sync, resolve(newBase)) end return makeAliases(chroot) end return makeAliases(fs)
namespace SIM.Tool.Windows.<API key> { using System.Windows; using SIM.Instances; using SIM.Tool.Base; using SIM.Tool.Base.Plugins; using SIM.Tool.Windows.Dialogs; using JetBrains.Annotations; [UsedImplicitly] public class <API key> : IMainWindowButton { #region Public methods public bool IsEnabled(Window mainWindow, Instance instance) { return true; } public void OnClick(Window mainWindow, Instance instance) { if (EnvironmentHelper.CheckSqlServer()) { WindowHelper.ShowDialog(new DatabasesDialog(), mainWindow); } } #endregion } }
package com.xeiam.xchange.lakebtc.marketdata; import static org.fest.assertions.api.Assertions.assertThat; import java.io.IOException; import java.io.InputStream; import java.math.BigDecimal; import org.junit.Test; import com.fasterxml.jackson.databind.ObjectMapper; import com.xeiam.xchange.lakebtc.dto.marketdata.LakeBTCOrderBook; import com.xeiam.xchange.lakebtc.dto.marketdata.LakeBTCTicker; import com.xeiam.xchange.lakebtc.dto.marketdata.LakeBTCTickers; public class <API key> { @Test public void <API key>() throws IOException { // Read in the JSON from the example resources InputStream is = <API key>.class.getResourceAsStream("/marketdata/example-ticker-data.json"); // Use Jackson to parse it ObjectMapper mapper = new ObjectMapper(); LakeBTCTickers tickers = mapper.readValue(is, LakeBTCTickers.class); LakeBTCTicker cnyTicker = tickers.getCny(); assertThat(cnyTicker.getAsk()).isEqualTo("3524.07"); assertThat(cnyTicker.getBid()).isEqualTo("3517.13"); assertThat(cnyTicker.getLast()).isEqualTo("3524.07"); assertThat(cnyTicker.getHigh()).isEqualTo("3584.97"); assertThat(cnyTicker.getLow()).isEqualTo("3480.07"); assertThat(cnyTicker.getVolume()).isEqualTo("5964.7677"); LakeBTCTicker usdTicker = tickers.getUsd(); assertThat(usdTicker.getAsk()).isEqualTo("564.63"); assertThat(usdTicker.getBid()).isEqualTo("564.63"); assertThat(usdTicker.getLast()).isEqualTo("564.4"); assertThat(usdTicker.getHigh()).isEqualTo("573.83"); assertThat(usdTicker.getLow()).isEqualTo("557.7"); assertThat(usdTicker.getVolume()).isEqualTo("3521.2782"); } @Test public void <API key>() throws IOException { // Read in the JSON from the example resources InputStream is = <API key>.class.getResourceAsStream("/marketdata/<API key>.json"); // Use Jackson to parse it ObjectMapper mapper = new ObjectMapper(); LakeBTCOrderBook orderBook = mapper.readValue(is, LakeBTCOrderBook.class); BigDecimal[][] asks = orderBook.getAsks(); assertThat(asks).hasSize(3); assertThat(asks[0][0]).isEqualTo("564.87"); assertThat(asks[0][1]).isEqualTo("22.371"); BigDecimal[][] bids = orderBook.getBids(); assertThat(bids).hasSize(3); assertThat(bids[2][0]).isEqualTo("558.08"); assertThat(bids[2][1]).isEqualTo("0.9878"); } }
using System; using BEPUutilities.DataStructures; namespace BEPUutilities.ResourceManagement { <summary> Uses a spinlock to safely access resources. </summary> <typeparam name="T">Type of object to store in the pool.</typeparam> public class LockingResourcePool<T> : ResourcePool<T> where T : class, new() { private readonly ConcurrentDeque<T> stack; <summary> Constructs a new thread-unsafe resource pool. </summary> <param name="<API key>">Number of resources to include in the pool by default.</param> <param name="initializer">Function to initialize new instances in the resource pool with.</param> public LockingResourcePool(int <API key>, Action<T> initializer) { InstanceInitializer = initializer; stack = new ConcurrentDeque<T>(<API key>); Initialize(<API key>); } <summary> Constructs a new thread-unsafe resource pool. </summary> <param name="<API key>">Number of resources to include in the pool by default.</param> public LockingResourcePool(int <API key>) : this(<API key>, null) { } <summary> Constructs a new thread-unsafe resource pool. </summary> public LockingResourcePool() : this(10) { } <summary> Gets the number of resources in the pool. Even if the resource count hits 0, resources can still be requested; they will be allocated dynamically. </summary> public override int Count { get { return stack.Count; } } <summary> Gives an item back to the resource pool. </summary> <param name="item">Item to return.</param> public override void GiveBack(T item) { stack.Enqueue(item); } <summary> Initializes the pool with some resources. Throws away excess resources. </summary> <param name="<API key>">Number of resources to include.</param> public override void Initialize(int <API key>) { while (stack.Count > <API key>) { T toRemove; stack.<API key>(out toRemove); } int length = stack.lastIndex - stack.firstIndex + 1; //lastIndex is inclusive, so add 1. if (InstanceInitializer != null) for (int i = 0; i < length; i++) { InstanceInitializer(stack.array[(stack.firstIndex + i) % stack.array.Length]); } while (stack.Count < <API key>) { stack.UnsafeEnqueue(CreateNewResource()); } } <summary> Takes an item from the resource pool. </summary> <returns>Item to take.</returns> public override T Take() { T toTake; if (stack.TryDequeueFirst(out toTake)) { return toTake; } return CreateNewResource(); } <summary> Clears out the resource pool. </summary> public override void Clear() { while (stack.Count > 0) { T item; stack.TryDequeueFirst(out item); } } } }
'use strict'; /** * Module dependencies. */ var mongoose = require('mongoose'), CurrentModel = mongoose.model('Attendance'), Schedule = mongoose.model('Schedule'), Group = mongoose.model('Group'), _ = require('lodash'); exports.attendance = function(req, res, next, id) { CurrentModel.load(id, function(err, item) { if (err) return next(err); if (!item) return next(new Error('Failed to load item ' + id)); req.attendance = item; next(); }); }; exports.schedule = function(req, res, next, id) { Schedule.load(id, function(err, item) { if (err) return next(err); if (!item) return next(new Error('Failed to load item ' + id)); req.schedule = item; next(); }); }; exports.group = function(req, res, next, id) { Group.load(id, function(err, item) { if (err) return next(err); if (!item) return next(new Error('Failed to load item ' + id)); req.group = item; next(); }); }; exports.create = function(req, res) { var value = new CurrentModel(req.body); value.group = req.group; value.schedule = req.schedule; value.save(function(err) { if (err) { return res.send('users/signup', { errors: err.errors, object: value }); } else { res.jsonp(value); } }); }; exports.update = function(req, res) { var item = req.attendance; item = _.extend(item, req.body); item.save(function(err) { if (err) { return res.send('users/signup', { errors: err.errors, object: item }); } else { res.jsonp(item); } }); }; exports.destroy = function(req, res) { var item = req.attendance; item.remove(function(err) { if (err) { return res.send('users/signup', { errors: err.errors, object: item }); } else { res.jsonp(item); } }); }; exports.show = function(req, res) { res.jsonp(req.attendance); }; exports.all = function(req, res) { CurrentModel.find({ group: req.group, schedule: req.schedule }).populate('participant', 'name email').exec(function(err, items) { if (err) { res.render('error', { status: 500 }); } else { res.jsonp(items); } }); };
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"> <html><head><title>Plugin</title> <meta http-equiv="Content-Style-Type" content="text/css"> <style type="text/css"><! body { margin: 5px 5px 5px 5px; background-color: #ffffff; } hr { color: #000000} body, table /* Normal text */ { font-size: 10pt; font-family: 'Arial', 'Helvetica', sans-serif; font-style: normal; font-weight: normal; color: #000000; text-decoration: none; } span.rvts1 /* Heading */ { font-weight: bold; color: #0000ff; } span.rvts2 /* Subheading */ { font-weight: bold; color: #000080; } span.rvts3 /* Keywords */ { font-style: italic; color: #800000; } a.rvts4, span.rvts4 /* Jump 1 */ { color: #008000; text-decoration: underline; } a.rvts5, span.rvts5 /* Jump 2 */ { color: #008000; text-decoration: underline; } span.rvts6 /* Font Hint */ { color: #808080; } span.rvts7 /* Font Hint Title */ { font-size: 15pt; font-family: 'Tahoma', 'Geneva', sans-serif; font-weight: bold; color: #404040; } span.rvts8 /* Font Hint Bold */ { font-weight: bold; color: #808080; } span.rvts9 /* Font Hint Italic */ { font-style: italic; color: #808080; } span.rvts10 /* Font Style */ { font-size: 16pt; font-family: 'Tahoma', 'Geneva', sans-serif; color: #ffffff; } span.rvts11 /* Font Style */ { font-family: 'MS Sans Serif', 'Geneva', sans-serif; color: #808080; } span.rvts12 /* Font Style */ { font-family: 'Verdana', 'Geneva', sans-serif; font-style: italic; color: #c0c0c0; } a.rvts13, span.rvts13 /* Font Style */ { font-family: 'Verdana', 'Geneva', sans-serif; font-style: italic; color: #6666ff; text-decoration: underline; } p,ul,ol /* Paragraph Style */ { text-align: left; text-indent: 0px; padding: 0px 0px 0px 0px; margin: 0px 0px 0px 0px; } .rvps1 /* Centered */ { text-align: center; } .rvps2 /* Paragraph Style */ { background: #c0c0c0; margin: 0px 0px 20px 0px; } .rvps3 /* Paragraph Style */ { text-align: center; background: #c0c0c0; margin: 20px 0px 0px 0px; } .rvps4 /* Paragraph Style */ { border-color: #c0c0c0; border-style: solid; border-width: 1px; border-right: none; border-bottom: none; border-left: none; background: #ffffff; padding: 3px 0px 0px 0px; margin: 27px 0px 0px 0px; } --></style> <script type="text/javascript">if(top.frames.length == 0) { top.location.href="../thewebmind.htm?Plugin.html"; }</script> <meta name="generator" content="HelpNDoc Free"></head> <body> <p class=rvps2><span class=rvts10>Plugin</span></p> <p><br></p> <p class=rvps3><span class=rvts11>Copyright © 2009, theWebMind.org</span></p> <p class=rvps4><span class=rvts12>This help file has been generated by the freeware version of </span><a class=rvts13 href="http: </body></html>
#ifndef <API key> #define <API key> class OscOptionalUnpacker { ofxOscMessage & msg; int n; public: OscOptionalUnpacker(ofxOscMessage & m):msg(m),n(0){} OscOptionalUnpacker & operator >> (int & i) { if(n < msg.getNumArgs()) { i = msg.getArgAsInt32( n++ ); } return *this; } OscOptionalUnpacker & operator >> (float & i) { if(n < msg.getNumArgs()) { i = msg.getArgAsFloat( n++ ); } return *this; } OscOptionalUnpacker & operator >> (double & i) { if(n < msg.getNumArgs()) { i = msg.getArgAsFloat( n++ ); } return *this; } OscOptionalUnpacker & operator >> (std::string & i) { if(n < msg.getNumArgs()) { i = msg.getArgAsString( n++ ); } return *this; } bool Eos() { return n >= msg.getNumArgs(); } }; class OscPacker { ofxOscMessage & msg; public: OscPacker(ofxOscMessage & m):msg(m){} OscPacker & operator << (int i) { msg.addIntArg(i); return *this; } OscPacker & operator << (unsigned int i) { msg.addIntArg(i); return *this; } OscPacker & operator << (float i) { msg.addFloatArg(i); return *this; } OscPacker & operator << (const std::string & i) { msg.addStringArg(i); return *this; } }; #endif // <API key>
package org.magcruise.gaming.executor.api.message; import org.magcruise.gaming.lang.Message; import org.magcruise.gaming.lang.SConstructor; public interface <API key> extends Message { @Override public SConstructor<? extends <API key>> toConstructor(ToExpressionStyle style); @Override public default SConstructor<? extends <API key>> toConstructor() { return toConstructor(ToExpressionStyle.DEFAULT); } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using NUnit.Framework; namespace UnitTests { [TestFixture] public class ProjectTests { [TestFixtureSetUp] public void Initialize() { } [Test] public void TestCsvRename() { } } }
import os import re from opsbro.collector import Collector # DMI have lot of useful information that detectors can use to know lot about the platform/hardware class Dmidecode(Collector): def launch(self): logger = self.logger logger.debug('getDmidecode: start') res = {} # Maybe we are in linux and we can directly read the linux_dmi_path = '/sys/class/dmi/id/' if os.path.exists(linux_dmi_path): file_names = os.listdir(linux_dmi_path) for fname in file_names: p = os.path.join(linux_dmi_path, fname) # There can be a link there, skip them if os.path.isfile(p): f = open(p, 'r') buf = f.read() f.close() res[fname] = buf.strip() logger.debug('getdmidecode: completed, returning') return res elif os.name == 'nt': self.set_not_eligible('Windows is currently not managed for DMI informations') return False # Ok not direct access, try to launch with else: # try dmidecode way, if exists res = self.execute_shell('LANG=C dmidecode -s') if res is False: self.set_not_eligible('Cannot read dmi information') return False for p in res.split('\n'): if re.search('^ ', p): buf = self.execute_shell('LANG=C dmidecode -s %s' % p).strip() if 'No such file or directory' in buf: logger.warning('Cannot access to dmi information with dmidecode command, exiting this collector.') self.set_not_eligible('Cannot get DMI informations because the dmidecode command is missing.') return res res[p.replace('-', '_').strip()] = buf logger.debug('getdmidecode: completed, returning') return res
// <auto-generated> // This code was generated by a tool. // Changes to this file may cause incorrect behavior and will be lost if // the code is regenerated. // </auto-generated> namespace It.Uniba.Di.Cdg.SocialTfs.ProxyServer.AdminPanel { public partial class EditService { <summary> ErrorPA control. </summary> <remarks> Auto-generated field. To modify move field declaration from designer file to code-behind file. </remarks> protected global::System.Web.UI.HtmlControls.HtmlGenericControl ErrorPA; <summary> Id control. </summary> <remarks> Auto-generated field. To modify move field declaration from designer file to code-behind file. </remarks> protected global::System.Web.UI.HtmlControls.HtmlInputHidden Id; <summary> DataTable control. </summary> <remarks> Auto-generated field. To modify move field declaration from designer file to code-behind file. </remarks> protected global::System.Web.UI.HtmlControls.HtmlTable DataTable; <summary> ServiceRW control. </summary> <remarks> Auto-generated field. To modify move field declaration from designer file to code-behind file. </remarks> protected global::System.Web.UI.HtmlControls.HtmlTableRow ServiceRW; <summary> ServiceTB control. </summary> <remarks> Auto-generated field. To modify move field declaration from designer file to code-behind file. </remarks> protected global::System.Web.UI.HtmlControls.HtmlInputText ServiceTB; <summary> NameRW control. </summary> <remarks> Auto-generated field. To modify move field declaration from designer file to code-behind file. </remarks> protected global::System.Web.UI.HtmlControls.HtmlTableRow NameRW; <summary> NameTB control. </summary> <remarks> Auto-generated field. To modify move field declaration from designer file to code-behind file. </remarks> protected global::System.Web.UI.HtmlControls.HtmlInputText NameTB; <summary> ErrNameRW control. </summary> <remarks> Auto-generated field. To modify move field declaration from designer file to code-behind file. </remarks> protected global::System.Web.UI.HtmlControls.HtmlTableRow ErrNameRW; <summary> HostRW control. </summary> <remarks> Auto-generated field. To modify move field declaration from designer file to code-behind file. </remarks> protected global::System.Web.UI.HtmlControls.HtmlTableRow HostRW; <summary> HostTB control. </summary> <remarks> Auto-generated field. To modify move field declaration from designer file to code-behind file. </remarks> protected global::System.Web.UI.HtmlControls.HtmlInputText HostTB; <summary> ErrHostRW control. </summary> <remarks> Auto-generated field. To modify move field declaration from designer file to code-behind file. </remarks> protected global::System.Web.UI.HtmlControls.HtmlTableRow ErrHostRW; <summary> ConsumerKeyRW control. </summary> <remarks> Auto-generated field. To modify move field declaration from designer file to code-behind file. </remarks> protected global::System.Web.UI.HtmlControls.HtmlTableRow ConsumerKeyRW; <summary> ConsumerKeyTB control. </summary> <remarks> Auto-generated field. To modify move field declaration from designer file to code-behind file. </remarks> protected global::System.Web.UI.HtmlControls.HtmlInputText ConsumerKeyTB; <summary> ErrConsumerKeyRW control. </summary> <remarks> Auto-generated field. To modify move field declaration from designer file to code-behind file. </remarks> protected global::System.Web.UI.HtmlControls.HtmlTableRow ErrConsumerKeyRW; <summary> ConsumerSecretRW control. </summary> <remarks> Auto-generated field. To modify move field declaration from designer file to code-behind file. </remarks> protected global::System.Web.UI.HtmlControls.HtmlTableRow ConsumerSecretRW; <summary> ConsumerSecretTB control. </summary> <remarks> Auto-generated field. To modify move field declaration from designer file to code-behind file. </remarks> protected global::System.Web.UI.HtmlControls.HtmlInputText ConsumerSecretTB; <summary> ErrConsumerSecretRW control. </summary> <remarks> Auto-generated field. To modify move field declaration from designer file to code-behind file. </remarks> protected global::System.Web.UI.HtmlControls.HtmlTableRow ErrConsumerSecretRW; <summary> GitHubLabelRW control. </summary> <remarks> Auto-generated field. To modify move field declaration from designer file to code-behind file. </remarks> protected global::System.Web.UI.HtmlControls.HtmlTableRow GitHubLabelRW; <summary> GitHubLabelTB control. </summary> <remarks> Auto-generated field. To modify move field declaration from designer file to code-behind file. </remarks> protected global::System.Web.UI.HtmlControls.HtmlInputText GitHubLabelTB; <summary> ErrGitHubLabelRW control. </summary> <remarks> Auto-generated field. To modify move field declaration from designer file to code-behind file. </remarks> protected global::System.Web.UI.HtmlControls.HtmlTableRow ErrGitHubLabelRW; <summary> Submit control. </summary> <remarks> Auto-generated field. To modify move field declaration from designer file to code-behind file. </remarks> protected global::System.Web.UI.HtmlControls.HtmlInputButton Submit; <summary> Reset control. </summary> <remarks> Auto-generated field. To modify move field declaration from designer file to code-behind file. </remarks> protected global::System.Web.UI.HtmlControls.HtmlInputReset Reset; } }
// <API key>.h // Vokoder #import <Foundation/Foundation.h> #import <CoreData/CoreData.h> #import "<API key>.h" #import "<API key>.h" #import "VOKManagedObjectMap.h" <API key> An completion block to run after importing each foreign dictionary. typedef void(^VOKPostImportBlock)(<API key> *inputDict, <API key> *outputObject); A completion block to run after exporting a managed object to a dictionary. typedef void(^VOKPostExportBlock)(<API key> *outputDict, <API key> *inputObject); @interface <API key> : NSObject Used to identify and update NSManagedObjects. Like a "primary key" in databases. @property (nonatomic, copy) NSString * __nullable uniqueComparisonKey; Used internally to filter input data. Updates automatically to match the uniqueComparisonKey. @property (nonatomic, copy) NSString * __nullable <API key>; If set to NO changes are discarded if a local object exists with the same unique comparison key. Defaults to YES. @property (nonatomic, assign) BOOL <API key>; If set to YES remote null/nil values are ignored when updating. Defaults to NO. @property (nonatomic, assign) BOOL <API key>; /** If set to YES, will not warn about incorrect class types when receiving null/nil values for optional properties. Defaults to NO. Note: regardless of the setting of this property, log messages are only output in DEBUG situations. */ @property (nonatomic, assign) BOOL <API key>; An optional completion block to run after importing each foreign dictionary. Defaults to nil. @property (nonatomic, copy) VOKPostImportBlock __nullable <API key>; An optional completion block to run after exporting a managed object to a dictionary. Defaults to nil. @property (nonatomic, copy) VOKPostExportBlock __nullable <API key>; /** Creates a new mapper. @param comparisonKey An NSString to uniquely identify local entities. Can be nil to enable duplicates. @param mapsArray An NSArray of <API key> to corrdinate input data and the Core Data model. @return A new mapper with the given unique key and maps. */ + (instancetype)mapperWithUniqueKey:(nullable NSString *)comparisonKey andMaps:(<API key> *)mapsArray; /** Convenience constructor for default mapper. @return A default mapper wherein the local keys and foreign keys are identical. */ + (instancetype)defaultMapper; /** This override of <API key> returns the foreign key for a local Core Data key. @param key The Core Data key. @return The foreign keypath as a string. */ - (id)<API key>:(id)key; @end <API key>
"use strict"; var <API key> = require("@babel/runtime/helpers/<API key>"); Object.defineProperty(exports, "__esModule", { value: true }); exports.default = void 0; var _createSvgIcon = <API key>(require("./utils/createSvgIcon")); var _jsxRuntime = require("react/jsx-runtime"); var _default = (0, _createSvgIcon.default)( /*#__PURE__*/(0, _jsxRuntime.jsx)("path", { d: "m22 6.92-1.41-1.41-2.85 3.21C15.68 6.4 12.83 5 9.61 5 6.72 5 4.07 6.16 2 8l1.42 1.42C5.12 7.93 7.27 7 9.61 7c2.74 0 5.09 1.26 6.77 3.24l-2.88 3.24-4-4L2 16.99l1.5 1.5 6-6.01 4 4 4.05-4.55c.75 1.35 1.25 2.9 1.44 4.55H21c-.22-2.3-.95-4.39-2.04-6.14L22 6.92z" }), '<API key>'); exports.default = _default;
import dateformat from 'dateformat'; import { map } from "underscore"; import { getAccountById } from 'routes/root/routes/Banking/routes/Accounts/modules/accounts'; import { getCreditCardById, getPrepaidCardById } from 'routes/root/routes/Banking/routes/Cards/modules/cards'; import { getLoanById } from 'routes/root/routes/Banking/routes/Loans/modules/loans'; export const getDebitAccount = (debitAccountType, debitAccountId) => { switch (debitAccountType) { case "isAccount": getAccountById(debitAccountId) break; case "isLoan": getLoanById(debitAccountId) break; case "isCreditCard": getCreditCardById(debitAccountId) break; case "isPrepaidCard": getPrepaidCardById(debitAccountId) break; } } const findDebitAccount = (debitAccountType, debitAccountId, state) => { let debitAccount = {}; switch (debitAccountType) { case "isAccount": debitAccount = state.accounts.accounts.filter((account) => account.id == debitAccountId)[0] break; case "isLoan": debitAccount = state.loans.loans.filter((loan) => loan.id == debitAccountId)[0] break; case "isCreditCard": debitAccount = state.cards.creditCards.filter((creditCard) => creditCard.id == debitAccountId)[0] break; case "isPrepaidCard": debitAccount = state.cards.prepaidCards.filter((prepaidCard) => prepaidCard.id == debitAccountId)[0] break; } return debitAccount; } export const <API key> = (debitAccountType, debitAccountId, state) => { const debitAccount = findDebitAccount(debitAccountType, debitAccountId, state); return <API key>(debitAccount, debitAccountType); } export const <API key> = (debitAccount, debitAccountType) => { let availableBalance = 0; switch (debitAccountType) { case "isAccount": availableBalance = debitAccount.ledgerBalance; break; case "isLoan": case "isCreditCard": case "isPrepaidCard": availableBalance = debitAccount.availableBalance; break; } return availableBalance; } export const <API key> = (debitAccountType, debitAccountId, state) => { return findDebitAccount(debitAccountType, debitAccountId, state).currency; } export const isValidDate = (date) => { return new Date(date).setHours(0,0,0,0) >= new Date(dateformat()).setHours(0,0,0,0) } export const <API key> = (product, amount, availableBalance) => { return amount > 0 && (parseFloat(amount) <= product.<API key> || parseFloat(amount) <= product.debt) && parseFloat(amount) <= availableBalance } export const <API key> = (transactionForm) => { return transactionForm.debitAccount.correct && transactionForm.amount.correct && transactionForm.date.correct } export const getPaymentType = (paymentMethod) => { let paymentType = ''; switch (paymentMethod) { case 'ΚΑΡΤΑ AGILE BANK': paymentType = 'isCreditCardAgile'; break; case 'ΚΑΡΤΑ ΑΛΛΗΣ ΤΡΑΠΕΖΗΣ': paymentType = '<API key>'; break; case 'ΔΑΝΕΙΟ AGILE BANK': paymentType = 'isLoan'; break; default: paymentType = 'thirdPartyPayment'; } return paymentType; } export const getCustomerName = (fullCustomerName) => { return (fullCustomerName.firstName + ' ' + fullCustomerName.lastName) .replace('ά', 'α') .replace('έ', 'ε') .replace('ί', 'ι') .replace('ή', 'η') .replace('ό', 'ο') .replace('ύ', 'υ') .replace('ώ', 'ω'); } export const getActualFullName = (fullName, currentFullName) => { const correctPattern = new RegExp("^[A-Za-zΑ-Ωα-ω ]+$"); return fullName = (correctPattern.test(fullName) || fullName == '' ? fullName : currentFullName).toUpperCase(); } export const isValidFullName = (fullName) => fullName.split(' ').length == 2 export const isValidDebitAmount = (amount, availableBalance) => { return amount > 0 && (parseFloat(amount)) <= availableBalance } export const <API key> = (beneficiary) => { return beneficiary == 'both' || beneficiary == 'sender' || beneficiary == 'beneficiary' } export const findPaymentCharges = (paymentMethods, paymentName) => { return map(paymentMethods, (paymentMethod) => paymentMethod.map(method => method)) .flatMap(paymentMethod => paymentMethod) .filter(payment => payment.name == paymentName)[0].charges } export const findTransferCharges = (beneficiary) => { let charges = 0; switch (beneficiary) { case 'both': charges = 3; break; case 'sender': charges = 6; break; case 'beneficiary': charges = 0; break; } return charges; } export const getImmediateText = (language) => { let immediateText = ''; switch (language) { case 'greek': immediateText = 'ΑΜΕΣΑ'; break; case 'english': immediateText = 'IMMEDIATE'; break; } return immediateText; } export const formatCardNumber = (cardNumber) => { return [...cardNumber].map(((num, key) => key % 4 == 0 && key != 0 ? ' ' + num : num )) }
#include <iostream> #include <map> #include <stdexcept> using namespace std; int main(int argc, char* argv[]){ map<string, int> m; m["bob"] = 56; m["alice"] = 89; m["billy"] = 3; // print it out map<string,int>::iterator i; for(i = m.begin(); i != m.end(); i++){ cout << i->first << ": " << i->second << endl; } cout << "size: " << m.size() << endl << endl; i = m.find("billy"); if(i == m.end()){ cout << "No billy!\n"; }else{ cout << i->first << ": " << i->second << endl; } return 0; }
This directory contains samples for VMC organization APIs: Running the samples $ python <API key>.py -r <refresh_token> * Testbed Requirement: - At least one org associated with the calling user.
var assert = require('assert'); var num = require('../'); test('sub', function() { assert.equal(num.sub(0, 0), '0'); assert.equal(num.sub('0', '-0'), '0'); assert.equal(num.sub('1.0', '-1.0'), '2.0'); assert.equal(num('987654321987654321.12345678901').sub(100.012), '987654321987654221.11145678901'); assert.equal(num(100.012).sub(num('987654321987654321.12345678901')), '-987654321987654221.11145678901'); }); test('sub#constness', function() { var one = num(1.2); var two = num(-1.2); assert.equal(one, '1.2'); assert.equal(two, '-1.2'); one.sub(two); assert.equal(one, '1.2'); assert.equal(two, '-1.2'); two.sub(one); assert.equal(one, '1.2'); assert.equal(two, '-1.2'); });
require File.join(File.dirname(__FILE__), "/../spec_helper") describe "Firefox" do before(:each) do @browser = Firefox.new @url = "http://localhost" end describe "Cross OS Firefox", :shared => true do it "should be supported" do @browser.should be_supported end end describe "Mac OS X" do <API key> "Cross OS Firefox" it "should have a path" do expected = File.expand_path("/Applications/#{@browser.escaped_name}.app") @browser.path.should == expected end it "return name" do @browser.name.should == "Firefox" end it "should visit a given url" do Kernel.expects(:system).with("open -a #{@browser.name} '#{@url}'") @browser.visit(@url) end end if macos? describe "Windows" do <API key> "Cross OS Firefox" it "should have a path" do @browser.path.should == File.join(ENV['ProgramFiles'] || 'c:\Program Files', '\Mozilla Firefox\firefox.exe') end it "return name" do @browser.name.should == "Firefox" end it "should visit a given url" do Kernel.expects(:system).with("#{@browser.path} #{@url}") @browser.visit(@url) end end if windows? describe "Linux" do <API key> "Cross OS Firefox" it "should have a path" do path = "/usr/bin/#{@browser.name}" Firefox.new(path).path.should == path end it "should visit a given url" do Kernel.expects(:system).with("#{@browser.name} #{@url}") @browser.visit(@url) end it "return name" do @browser.name.should == "firefox" end end if linux? end
<?php if (!$loader = @require_once __DIR__ . '/../vendor/autoload.php') { die("You must set up the project dependencies, run the following commands: wget http://getcomposer.org/composer.phar php composer.phar install --dev --prefer-source "); } /* @var $loader \Composer\Autoload\ClassLoader */ $loader->add('Doctrine\Tests', __DIR__.'/../vendor/doctrine/orm/tests');