answer
stringlengths
15
1.25M
Rails.application.routes.draw do get 'weddings/index' get 'weddings/map' # The priority is based upon order of creation: first created -> highest priority. # See how all your routes lay out with "rake routes". # You can have the root of your site routed with "root" resources :weddings root 'weddings#index' # Example of regular route: # get 'products/:id' => 'catalog#view' # Example of named route that can be invoked with purchase_url(id: product.id) # get 'products/:id/purchase' => 'catalog#purchase', as: :purchase # Example resource route (maps HTTP verbs to controller actions automatically): # resources :products # Example resource route with options: # resources :products do # member do # get 'short' # post 'toggle' # end # collection do # get 'sold' # end # end # Example resource route with sub-resources: # resources :products do # resources :comments, :sales # resource :seller # end # Example resource route with more complex sub-resources: # resources :products do # resources :comments # resources :sales do # get 'recent', on: :collection # end # end # Example resource route with concerns: # concern :toggleable do # post 'toggle' # end # resources :posts, concerns: :toggleable # resources :photos, concerns: :toggleable # Example resource route within a namespace: # namespace :admin do
// @Author Fathurahman <ipat.bogor@gmail.com> @ipatizer #pragma once #include "GUIWidget.h" #include "GUIScreen.generated.h" UCLASS(Blueprintable) class GAMEUI_API UGUIScreen : public UGUIWidget { GENERATED_BODY() <API key>(FOnOpenScreen); <API key>(FOnCloseScreen, FString, Result); public: friend class <API key>; int32 ZOrder; UPROPERTY(BlueprintAssignable, Category = "GUI Screen") FOnOpenScreen OnOpenScreen; UPROPERTY(BlueprintAssignable, Category = "GUI Screen") FOnCloseScreen OnCloseScreen; UGUIScreen(const FObjectInitializer& ObjectInitializer); UFUNCTION(BlueprintPure, Category="GUI Screen") bool GetIsActive() const; FORCEINLINE bool <API key>() const { return bPauseGame; } FORCEINLINE bool GetShouldShowCursor() const { return bShowCursor; } FORCEINLINE bool GetIsModal() const { return bIsModal; } FORCEINLINE bool GetIsRoot() const { return bIsRoot; } FORCEINLINE bool GetIsUnique() const { return bIsRoot || bIsUnique; } FORCEINLINE bool GetIgnoreMoveInput() const { return bIsModal || bIgnoreMoveInput; } FORCEINLINE bool GetIgnoreLookInput() const { return bIsModal || bIgnoreLookInput; } virtual void Open() override; virtual void Close(FString Result = FString()) override; virtual void NativeConstruct() override; void SetIsActive(bool bFlag); protected: void NativeOpen(); void NativeClose(FString Result); /** Should the game be paused when this screen is opened. */ UPROPERTY(EditAnywhere, Category="GUI Screen") bool bPauseGame = false; /** Whether to consume input key even if the input key event is not handled. */ UPROPERTY(EditAnywhere, Category="GUI Screen") bool bIsModal = false; UPROPERTY(EditAnywhere, Category="GUI Screen", meta=(EditCondition="!bIsModal")) bool bIgnoreMoveInput = false; UPROPERTY(EditAnywhere, Category="GUI Screen", meta=(EditCondition="!bIsModal")) bool bIgnoreLookInput = false; /** Should the game show cursor or not when this screen is opened. */ UPROPERTY(EditAnywhere, Category="GUI Screen") bool bShowCursor = false; UPROPERTY(EditAnywhere, Category="GUIScreen", meta=(EditCondition="bShowCursor")) bool <API key> = false; /** Whether this is a root screen that always placed at the bottom of the screen stack. */ UPROPERTY(EditAnywhere, Category="GUI Screen") bool bIsRoot = false; /** Whether there can be more than one screen with this class opened at the same time. Root screen is always unique */ UPROPERTY(EditAnywhere, Category="GUI Screen", meta=(EditCondition="!bIsRoot")) bool bIsUnique = false; UPROPERTY() bool bIsActive = false; UFUNCTION(<API key>, Category="GUI Screen|Event") void OnActive(); UFUNCTION(<API key>, Category="GUI Screen|Event") void OnInactive(); UFUNCTION() void HandleOnOpenClose(bool bIsOpen ); UFUNCTION() void <API key>(bool bIsOpen); // Begin Native event handlers, don't forget to call super method if you override these handlers. virtual void NativeOnActive(); virtual void NativeOnInactive(); // End Native event handlers private: FString CloseResult; };
describe('Tywin Lannister (LoCR)', function() { integration(function() { beforeEach(function() { const deck1 = this.buildDeck('lannister', [ 'Sneak Attack', 'Tywin Lannister (LoCR)', 'Cersei Lannister (Core)', 'Hedge Knight' ]); const deck2 = this.buildDeck('lannister', [ 'Sneak Attack', 'The Tickler', 'The Reader (TRtW)', 'Cersei Lannister (Core)', 'Hedge Knight' ]); this.player1.selectDeck(deck1); this.player2.selectDeck(deck2); this.startGame(); this.keepStartingHands(); this.player1.clickCard('Tywin Lannister', 'hand'); this.player2.clickCard('The Tickler', 'hand'); this.player2.clickCard('The Reader', 'hand'); this.completeSetup(); this.selectFirstPlayer(this.player1); // Move remaining cards back to draw deck so we have something to discard for(const card of this.player1Object.hand) { this.player1Object.moveCard(card, 'draw deck'); } for(const card of this.player2Object.hand) { this.player2Object.moveCard(card, 'draw deck'); } }); describe('when a single card discard occurs', function() { beforeEach(function() { this.cersei = this.player1.findCardByName('Cersei Lannister'); this.knight = this.player1.findCardByName('Hedge Knight'); this.player1.<API key>('dominance', true); this.<API key>(); this.<API key>(); this.player2.clickMenu('The Tickler', 'Discard opponents top card'); }); it('should allow Tywin to choose to trigger', function() { this.player1.triggerAbility('Tywin Lannister'); this.player1.clickPrompt('Hedge Knight'); expect(this.cersei.location).toBe('draw deck'); expect(this.knight.location).toBe('discard pile'); }); }); describe('when a multiple card discard occurs', function() { beforeEach(function() { this.cersei = this.player1.findCardByName('Cersei Lannister'); this.knight = this.player1.findCardByName('Hedge Knight'); this.<API key>(); // Challenge prompt for Player 1 this.player1.clickPrompt('Done'); // Challenge prompt for Player 2 this.player2.clickPrompt('Power'); this.player2.clickCard('The Reader', 'play area'); this.player2.clickPrompt('Done'); this.skipActionWindow(); // Player 1 does not oppose this.player1.clickPrompt('Done'); this.skipActionWindow(); // Trigger The Reader this.player2.triggerAbility('The Reader'); this.player2.clickPrompt('Discard 3 cards'); }); it('should not allow Tywin to choose to trigger', function() { expect(this.player1).not.<API key>('Tywin Lannister'); }); }); describe('when pillage occurs', function() { beforeEach(function() { this.cersei = this.player2.findCardByName('Cersei Lannister'); this.knight = this.player2.findCardByName('Hedge Knight'); this.<API key>(); // Challenge prompt for Player 1 this.player1.clickPrompt('Power'); this.player1.clickCard('Tywin Lannister', 'play area'); this.player1.clickPrompt('Done'); this.skipActionWindow(); // Player 2 does not oppose this.player2.clickPrompt('Done'); this.skipActionWindow(); this.player1.clickPrompt('Apply Claim'); }); it('should allow Tywin to choose to trigger', function() { this.player1.triggerAbility('Tywin Lannister'); this.player1.clickPrompt('Hedge Knight'); expect(this.cersei.location).toBe('draw deck'); expect(this.knight.location).toBe('discard pile'); }); }); }); });
#include "udf.h" #include "sg.h" #define r 2.0e-5 //reaction probability (-) #define v 360.0 //Boltzmann velocity (m/s) #define vs (r*v/4) //surface uptake velocity (m/s) #define Dm 1.82e-5 //diffusion coefficient of ozone in air (m2/s) #define rho 1.205 //density of air (kg/m3) #define kb 5111.111 //second order rate constant for ozone (s-1) (convert from 0.0184ppb-1h-1) #define B_source 5.25e-10 //source of B (kg/m2s) (convert from 1.89mg/m2h) DEFINE_SOURCE(ozone_sink_udf,c,t,dS,eqn) { face_t f; Thread *tf; int n; real NV_VEC(A); real xc[ND_ND], xf[ND_ND],y0[ND_ND]; real source,depo_rate; real dy0; C_CENTROID(xc,c,t); source=kb*C_YI(c,t,1)*rho; //ozone sink of indoor air owning to chemical reaction c_face_loop (c,t,n) { f=C_FACE(c,t,n); tf=C_FACE_THREAD(c,t,n); F_CENTROID(xf,f,tf); if (THREAD_TYPE(tf)==THREAD_F_WALL) { NV_VV(y0,=,xc,-,xf); dy0=NV_MAG(y0); F_AREA(A,f,tf); depo_rate=vs/(1+vs*dy0/Dm)*NV_MAG(A)/C_VOLUME(c,t); //ozone sink of surface deposition of the whole indoor walls source+=depo_rate; } } source=-rho*source; dS[eqn]=source; source*=C_YI(c,t,0); return source; } DEFINE_SOURCE(B_source_sink_udf,c,t,dS,eqn) { face_t f; Thread *tf; int n; real NV_VEC(A); real source; real sourceB; real xf[ND_ND]; source=-kb*C_YI(c,t,0)*rho*C_YI(c,t,1)*rho; //B sink of indoor air owning to chemical reaction c_face_loop (c,t,n) { f=C_FACE(c,t,n); tf=C_FACE_THREAD(c,t,n); F_CENTROID(xf,f,tf); if (THREAD_TYPE(tf)==THREAD_F_WALL && xf[1]==0.0) //get the faces belong to floor surface (y coordinate equals 0) { F_AREA(A,f,tf); sourceB=B_source*NV_MAG(A)/C_VOLUME(c,t); //B source from floor surface source+=sourceB; } } dS[eqn]=-kb*C_YI(c,t,0)*rho*rho; return source; } DEFINE_SOURCE(P_source_udf,c,t,dS,eqn) { face_t f; Thread *tf; real source; source=kb*C_YI(c,t,0)*rho*C_YI(c,t,1)*rho; //P source of chemical reaction dS[eqn]=0; return source; }
# CryptoFire-Chat A simple chat application [demo](https://chat-a9892.firebaseapp.com/) demonstrating end-to-end encryption where the content of messages is completely hidden from the sever. ## General This is a weekend project that is meant to test the WebCryptoAPI and Firebase. Messages are end-to-end encrypted between the users. Furthermore, messages are destroyed on the server as soon as they reach their destination. The app is based on the Firebase Friendly Chat starter project. Conversations are organized into chat rooms. Each room is identified by a unique name in the URL that can be shared with another person to start a conversation. Each room supports (for now) 2 users: * Host: Creates the room, with a unique id. * Guest: Joins a room after receiving a room id (or stumbling onto one). ## Firebase I have picked Firebase as a backend for this app because it offered a simple integration for user profiles and a real-time database to exchange messages. I used to be a Parse fanboy for a long time, and Firebase seemed lacking before, but I'm starting to see its appeal. However, the plan is to move away from centralized solutions to a p22p one (WebRTC maybe, if I ever manage to get it to work). Why login with Google? I needed a way to uniquely identify users, Google is the default integration with Firebase but I will add other providers like Github, Twitter and Facebook. The chat can function purely on usernames but that would be done later. ## Can I use this? Use it for fun, experiments and break it! This is **NOT** meant for any serious use! This is just an experiment. If you find a bug, open an issue or send an email : [raed.chammam@gmail.com](mailto:raed.chammam@gmail.com).
#include "bitcoin_txdb.h" #include "bitcoin_core.h" #include "uint256.h" #include <stdint.h> using namespace std; const unsigned char <API key>::COIN_KEY = 'c'; const unsigned char <API key>::BEST_CHAIN_KEY = 'B'; void <API key>::BatchWriteCoins(CLevelDBBatch &batch, const uint256 &hash, const Bitcoin_CCoins &coins) { if (coins.IsPruned()) batch.Erase(make_pair(COIN_KEY, hash)); else batch.Write(make_pair(COIN_KEY, hash), coins); } void <API key>::<API key>(CLevelDBBatch &batch, const uint256 &hash) { batch.Write(BEST_CHAIN_KEY, hash); } bool <API key>::GetCoins(const uint256 &txid, Bitcoin_CCoins &coins) { return db.Read(make_pair(COIN_KEY, txid), coins); } bool <API key>::SetCoins(const uint256 &txid, const Bitcoin_CCoins &coins) { CLevelDBBatch batch; BatchWriteCoins(batch, txid, coins); return db.WriteBatch(batch); } bool <API key>::HaveCoins(const uint256 &txid) { return db.Exists(make_pair(COIN_KEY, txid)); } uint256 <API key>::GetBestBlock() { uint256 hashBestChain; if (!db.Read(BEST_CHAIN_KEY, hashBestChain)) return uint256(0); return hashBestChain; } bool <API key>::SetBestBlock(const uint256 &hashBlock) { CLevelDBBatch batch; <API key>(batch, hashBlock); return db.WriteBatch(batch); } bool <API key>::BatchWrite(const std::map<uint256, Bitcoin_CCoins> &mapCoins, const uint256 &hashBlock) { LogPrint("coindb", "Committing %u changed transactions to coin database...\n", (unsigned int)mapCoins.size()); CLevelDBBatch batch; for (std::map<uint256, Bitcoin_CCoins>::const_iterator it = mapCoins.begin(); it != mapCoins.end(); it++) BatchWriteCoins(batch, it->first, it->second); if (hashBlock != uint256(0)) <API key>(batch, hashBlock); return db.WriteBatch(batch); } bool <API key>::GetStats(Bitcoin_CCoinsStats &stats) { leveldb::Iterator *pcursor = db.NewIterator(); pcursor->SeekToFirst(); CHashWriter ss(SER_GETHASH, <API key>); stats.hashBlock = GetBestBlock(); ss << stats.hashBlock; int64_t nTotalAmount = 0; while (pcursor->Valid()) { boost::this_thread::interruption_point(); try { leveldb::Slice slKey = pcursor->key(); CDataStream ssKey(slKey.data(), slKey.data()+slKey.size(), SER_DISK, Bitcoin_Params().ClientVersion()); char chType; ssKey >> chType; if (chType == COIN_KEY) { leveldb::Slice slValue = pcursor->value(); CDataStream ssValue(slValue.data(), slValue.data()+slValue.size(), SER_DISK, Bitcoin_Params().ClientVersion()); Bitcoin_CCoins coins; ssValue >> coins; uint256 txhash; ssKey >> txhash; ss << txhash; ss << VARINT(coins.nVersion); ss << (coins.fCoinBase ? 'c' : 'n'); ss << VARINT(coins.nHeight); stats.nTransactions++; for (unsigned int i=0; i<coins.vout.size(); i++) { const CTxOut &out = coins.vout[i]; if (!out.IsNull()) { stats.nTransactionOutputs++; ss << VARINT(i+1); ss << out; nTotalAmount += out.nValue; } } stats.nSerializedSize += 32 + slValue.size(); ss << VARINT(0); } pcursor->Next(); } catch (std::exception &e) { return error("<API key>: %s : Deserialize or I/O error - %s", __func__, e.what()); } } delete pcursor; stats.nHeight = <API key>.find(GetBestBlock())->second->nHeight; stats.hashSerialized = ss.GetHash(); stats.nTotalAmount = nTotalAmount; return true; } <API key>::<API key>(size_t nCacheSize, bool fMemory, bool fWipe) : db(GetDataDir() / "bitcoin_chainstate", nCacheSize, fMemory, fWipe) { } <API key>::<API key>(size_t nCacheSize, bool fMemory, bool fWipe) : CLevelDBWrapper(GetDataDir() / "bitcoin_blocks" / "index", nCacheSize, fMemory, fWipe) { } bool <API key>::WriteBlockIndex(const <API key>& blockindex) { return Write(make_pair('b', blockindex.GetBlockHash()), blockindex); } bool <API key>::<API key>(std::vector<<API key>> &vblockindexes) { CLevelDBBatch batch; for (unsigned int i = 0; i < vblockindexes.size(); i++) { <API key> &blockindex = vblockindexes[i]; batch.Write(make_pair('b', blockindex.GetBlockHash()), blockindex); } return WriteBatch(batch); } bool <API key>::WriteBlockFileInfo(int nFile, const CBlockFileInfo &info) { return Write(make_pair('f', nFile), info); } bool <API key>::ReadBlockFileInfo(int nFile, CBlockFileInfo &info) { return Read(make_pair('f', nFile), info); } bool <API key>::WriteLastBlockFile(int nFile) { return Write('l', nFile); } bool <API key>::WriteTrimToTime(int nTrimToTime) { return Write('T', nTrimToTime); } bool <API key>::ReadTrimToTime(int &nTrimToTime) { return Read('T', nTrimToTime); } bool <API key>::WriteReindexing(bool fReindexing) { if (fReindexing) return Write('R', '1'); else return Erase('R'); } bool <API key>::ReadReindexing(bool &fReindexing) { fReindexing = Exists('R'); return true; } bool <API key>::ReadLastBlockFile(int &nFile) { return Read('l', nFile); } bool <API key>::ReadTxIndex(const uint256 &txid, CDiskTxPos &pos) { return Read(make_pair('t', txid), pos); } bool <API key>::WriteTxIndex(const std::vector<std::pair<uint256, CDiskTxPos> >&vect) { CLevelDBBatch batch; for (std::vector<std::pair<uint256,CDiskTxPos> >::const_iterator it=vect.begin(); it!=vect.end(); it++) batch.Write(make_pair('t', it->first), it->second); return WriteBatch(batch); } bool <API key>::WriteFlag(const std::string &name, bool fValue) { return Write(std::make_pair('F', name), fValue ? '1' : '0'); } bool <API key>::ReadFlag(const std::string &name, bool &fValue) { char ch; if (!Read(std::make_pair('F', name), ch)) return false; fValue = ch == '1'; return true; } Bitcoin_CBlockIndex * <API key>::InsertBlockIndex(uint256 hash) { if (hash == 0) return NULL; // Return existing map<uint256, Bitcoin_CBlockIndex*>::iterator mi = <API key>.find(hash); if (mi != <API key>.end()) return (*mi).second; // Create new Bitcoin_CBlockIndex* pindexNew = new Bitcoin_CBlockIndex(); if (!pindexNew) throw runtime_error("LoadBlockIndex() : new CBlockIndex failed"); mi = <API key>.insert(make_pair(hash, pindexNew)).first; pindexNew->phashBlock = &((*mi).first); return pindexNew; } bool <API key>::LoadBlockIndexGuts() { leveldb::Iterator *pcursor = NewIterator(); CDataStream ssKeySet(SER_DISK, Bitcoin_Params().ClientVersion()); ssKeySet << make_pair('b', uint256(0)); pcursor->Seek(ssKeySet.str()); // Load mapBlockIndex while (pcursor->Valid()) { boost::this_thread::interruption_point(); try { leveldb::Slice slKey = pcursor->key(); CDataStream ssKey(slKey.data(), slKey.data()+slKey.size(), SER_DISK, Bitcoin_Params().ClientVersion()); char chType; ssKey >> chType; if (chType == 'b') { leveldb::Slice slValue = pcursor->value(); CDataStream ssValue(slValue.data(), slValue.data()+slValue.size(), SER_DISK, Bitcoin_Params().ClientVersion()); <API key> diskindex; ssValue >> diskindex; // Construct block index object Bitcoin_CBlockIndex* pindexNew = InsertBlockIndex(diskindex.GetBlockHash()); pindexNew->pprev = InsertBlockIndex(diskindex.hashPrev); pindexNew->nHeight = diskindex.nHeight; pindexNew->nFile = diskindex.nFile; pindexNew->nDataPos = diskindex.nDataPos; pindexNew->nCompressedPos = diskindex.nCompressedPos; pindexNew->nUndoPos = diskindex.nUndoPos; pindexNew->nUndoPosClaim = diskindex.nUndoPosClaim; pindexNew->nVersion = diskindex.nVersion; pindexNew->hashMerkleRoot = diskindex.hashMerkleRoot; pindexNew->nTime = diskindex.nTime; pindexNew->nBits = diskindex.nBits; pindexNew->nNonce = diskindex.nNonce; pindexNew->nStatus = diskindex.nStatus; pindexNew->nTx = diskindex.nTx; if (!pindexNew->CheckIndex()) return error("LoadBlockIndex() : CheckIndex failed: %s", pindexNew->ToString()); pcursor->Next(); } else { break; // if shutdown requested or finished loading block index } } catch (std::exception &e) { return error("<API key>: %s : Deserialize or I/O error - %s", __func__, e.what()); } } delete pcursor; return true; }
<?xml version="1.0" encoding="UTF-8" standalone="no"?> <!DOCTYPE html PUBLIC "- <html xmlns="http: <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" /> <title>set_lk_max_locks</title> <link rel="stylesheet" href="apiReference.css" type="text/css" /> <meta name="generator" content="DocBook XSL Stylesheets V1.73.2" /> <link rel="start" href="index.html" title="Berkeley DB C API Reference" /> <link rel="up" href="<API key>.html" title="Appendix D. DB_CONFIG Parameter Reference" /> <link rel="prev" href="<API key>.html" title="set_lk_max_lockers" /> <link rel="next" href="<API key>.html" title="set_lk_max_objects" /> </head> <body> <div xmlns="" class="navheader"> <div class="libver"> <p>Library Version 11.2.5.3</p> </div> <table width="100%" summary="Navigation header"> <tr> <th colspan="3" align="center">set_lk_max_locks</th> </tr> <tr> <td width="20%" align="left"><a accesskey="p" href="<API key>.html">Prev</a> </td> <th width="60%" align="center">Appendix D. DB_CONFIG Parameter Reference</th> <td width="20%" align="right"> <a accesskey="n" href="<API key>.html">Next</a></td> </tr> </table> <hr /> </div> <div class="sect1" lang="en" xml:lang="en"> <div class="titlepage"> <div> <div> <h2 class="title" style="clear: both"><a id="<API key>"></a>set_lk_max_locks</h2> </div> </div> </div> <p> Sets the maximum number of locks supported by the Berkeley DB environment. This value is used to estimate how much space to allocate for various lock-table data structures. When using the DB, the default value is 1000 locks. When using the BDB SQL interface, the default value is 10,000 locks. </p> <p> The syntax of this parameter in the <a href="../../<API key>/env_db_config.html#env_db_config.DB_CONFIG" class="olink">DB_CONFIG</a> file is a single line with the string <code class="literal">set_lk_max_locks</code>, one or more whitespace characters, and the number of locks. </p> <p> If the database environment already exists when this parameter is changed, it is ignored. To change this value after the environment has been created, re-create your environment. </p> <p>For more information, see <a class="xref" href="envset_lk_max_locks.html" title="DB_ENV-&gt;set_lk_max_locks()">DB_ENV-&gt;set_lk_max_locks()</a>. </p> </div> <div class="navfooter"> <hr /> <table width="100%" summary="Navigation footer"> <tr> <td width="40%" align="left"><a accesskey="p" href="<API key>.html">Prev</a> </td> <td width="20%" align="center"> <a accesskey="u" href="<API key>.html">Up</a> </td> <td width="40%" align="right"> <a accesskey="n" href="<API key>.html">Next</a></td> </tr> <tr> <td width="40%" align="left" valign="top">set_lk_max_lockers </td> <td width="20%" align="center"> <a accesskey="h" href="index.html">Home</a> </td> <td width="40%" align="right" valign="top"> set_lk_max_objects</td> </tr> </table> </div> </body> </html>
package com.yesco.android.core.parsing; /** * Class description. * * @author <a href="mailto:vmfo@xpand-it.com">vmfo</a> * @version $Revision: 666 $ * */ public interface ParsingTaskMethods { // return the parsed object public Object parsingMethod(); // receives the parsed object public void parsingFinishMethod(Object result); }
"use strict"; var core = require("flax/core"); class Server extends events.EventEmitter { constructor() { super(); this.domainRoutes = {}; this.globalRoutes = {matchRoutes: {}, exactRoutes: {}}; this.addExactRoute({ route: '/showRoutes', fn : function(req, res) { res.textOut('<pre>' + JSON.stringify({domainRoutes : this.domainRoutes, global : this.globalRoutes}, null,4) + '</pre>'); } }); } setupClient(domain, route) { route = route || '/client'; this.mapDirectory(core.path + '/client', route, domain); } /** * * @param conf - requires properties : route, domain , fn */ addMatchRoute(conf) { conf.type =conf.type || 'function'; if(conf.hasOwnProperty('domain')) { var routes = this._getDomainRoutes(conf.domain); } else { var routes = this.globalRoutes; } routes.matchRoutes[conf.route] = conf; } /** * * @param conf - requires properties : route, domain , fn */ addExactRoute(conf) { conf.type =conf.type || 'function'; if(conf.hasOwnProperty('domain')) { var routes = this._getDomainRoutes(conf.domain); } else { var routes = this.globalRoutes; } routes.exactRoutes[conf.route] = conf; } /** * * @param conf - requires properties : route, domain , fn */ addDefaultRoute(conf) { if(conf.hasOwnProperty('domain')) { var routes = this._getDomainRoutes(conf.domain); } else { var routes = this.globalRoutes; } routes.default = conf.fn; } mapDirectory(path, route, domain) { var conf = {path : path, route: route, type: 'path' }; if(domain) { conf.domain = domain; } this.addMatchRoute(conf); } mapFile(path, route, domain) { var conf = {path : path, route: route, type: 'path' }; if(domain) { conf.domain = domain; } this.addExactRoute(conf); } /** * initializes if not initialized already and returns * @param domain * @returns object * @private */ _getDomainRoutes(domain) { if (!this.domainRoutes.hasOwnProperty(domain)) { this.domainRoutes[domain] = {matchRoutes: {}, exactRoutes: {}}; } return this.domainRoutes[domain]; } initServer() { var srvContrainer = this; this.server = require('http').createServer(function (req, res) { var respWrapper = new ResponseWrapper(res); var reqWrapper = new RequestWrapper(req); var domain = reqWrapper.getDomain(); if (srvContrainer.domainRoutes.hasOwnProperty(domain)) { if(false !== srvContrainer._handleRoutes(srvContrainer.domainRoutes[domain], reqWrapper, respWrapper)) { return; } } if(false !== srvContrainer._handleRoutes(srvContrainer.globalRoutes, reqWrapper, respWrapper)) { return; } }); } _handleRoutes(routes, req, res) { var path = req.getPath(); if(routes.exactRoutes.hasOwnProperty(path)) { var routeConf = routes.exactRoutes[path]; var context = routeConf.context || this; switch(routeConf.type) { case 'function': routeConf.fn.apply(context, [req, res]); break; case 'path': var filepath = routeConf.path; require('fs').readFile(filepath, {}, function (err, content) { if(!err) { res.textOut(content, 200, req.getMime()); } else { res.textOut('resource not found', 404); } }); break; default: throw "unknown route type: " +routeConf.type; } return true; } for (var route in routes.matchRoutes) { var reg = '^' + route; if (path.match(new RegExp(reg))) { var routeConf = routes.matchRoutes[route]; var context = routeConf.context || this; switch(routes.matchRoutes[route].type) { case 'function': routeConf.fn.apply(context, [req, res]); break; case 'path': var filepath = routeConf.path + req.parsedQuery.href.substr(route.length); require('fs').readFile(filepath, {}, function (err, content) { if(!err) { res.textOut(content, 200, req.getMime()); } else { res.textOut('resource not found', 404); } }); break; default: throw "unknown route type: " +routeConf.type; } return true; } } if (routes.hasOwnProperty('default')) { routes.default.apply(this, [req, res]); return true; } return false; } listen(port) { this.server.listen(port); } } class ResponseWrapper extends events.EventEmitter { constructor(res) { super(); this.res = res; } textOut(text, code , mime) { mime = mime || 'text/html'; code = code || 200; this.res.writeHead(code, { 'Content-Type': mime }); this.res.end(text); } } class RequestWrapper extends events.EventEmitter { constructor(req) { super(); this.req = req; this.domain = this.req.headers.host.split(':')[0]; this.parsedQuery = require('url').parse(this.req.url); } getDomain() { return this.domain; } getPath() { return this.parsedQuery.pathname; } getMime() { var ext = this.parsedQuery.href.split('.').pop().toLowerCase(); var mime = 'text/html'; switch(ext) { case 'png': case 'jpg': case 'jpeg': case 'gif': case 'giff': case 'tiff': mime = 'image/' + ext; break; case 'svg': mime = 'image/svg+xml'; break; case 'js': mime = 'application/javascript'; break; case 'css': mime = 'text/css'; break; } return mime; } } exports.Server = Server;
angular.module('myapp', [ 'templates-app', 'templates-common', 'ui.router' ]).run(function () { }); angular.element(document).ready(function() { angular.bootstrap(document, ['myapp']); });
<!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> <title>euler-formula: Not compatible</title> <link rel="shortcut icon" type="image/png" href="../../../../../favicon.png" /> <link href="../../../../../bootstrap.min.css" rel="stylesheet"> <link href="../../../../../bootstrap-custom.css" rel="stylesheet"> <link href="//maxcdn.bootstrapcdn.com/font-awesome/4.2.0/css/font-awesome.min.css" rel="stylesheet"> <script src="../../../../../moment.min.js"></script> <!-- HTML5 Shim and Respond.js IE8 support of HTML5 elements and media queries --> <!-- WARNING: Respond.js doesn't work if you view the page via file: <!--[if lt IE 9]> <script src="https://oss.maxcdn.com/html5shiv/3.7.2/html5shiv.min.js"></script> <script src="https://oss.maxcdn.com/respond/1.4.2/respond.min.js"></script> <![endif] </head> <body> <div class="container"> <div class="navbar navbar-default" role="navigation"> <div class="container-fluid"> <div class="navbar-header"> <a class="navbar-brand" href="../../../../.."><i class="fa fa-lg fa-flag-checkered"></i> Coq bench</a> </div> <div id="navbar" class="collapse navbar-collapse"> <ul class="nav navbar-nav"> <li><a href="../..">clean / released</a></li> <li class="active"><a href="">8.8.2 / euler-formula - 8.9.0</a></li> </ul> </div> </div> </div> <div class="article"> <div class="row"> <div class="col-md-12"> <a href="../..">« Up</a> <h1> euler-formula <small> 8.9.0 <span class="label label-info">Not compatible</span> </small> </h1> <p><em><script>document.write(moment("2020-03-05 01:02:10 +0000", "YYYY-MM-DD HH:mm:ss Z").fromNow());</script> (2020-03-05 01:02:10 UTC)</em><p> <h2>Context</h2> <pre># Packages matching: installed # Name # Installed # Synopsis base-bigarray base base-threads base base-unix base camlp5 7.11 <API key> of OCaml conf-findutils 1 Virtual package relying on findutils conf-m4 1 Virtual package relying on m4 coq 8.8.2 Formal proof management system. num 1.3 The legacy Num library for arbitrary-precision integer and rational arithmetic ocaml 4.09.0 The OCaml compiler (virtual package) ocaml-base-compiler 4.09.0 Official release 4.09.0 ocaml-config 1 OCaml Switch Configuration ocamlfind 1.8.1 A library manager for OCaml # opam file: opam-version: &quot;2.0&quot; maintainer: &quot;Hugo.Herbelin@inria.fr&quot; homepage: &quot;https://github.com/coq-contribs/euler-formula&quot; license: &quot;LGPL&quot; build: [make &quot;-j%{jobs}%&quot;] install: [make &quot;install&quot;] remove: [&quot;rm&quot; &quot;-R&quot; &quot;%{lib}%/coq/user-contrib/EulerFormula&quot;] depends: [ &quot;ocaml&quot; &quot;coq&quot; {&gt;= &quot;8.9&quot; &amp; &lt; &quot;8.10~&quot;} ] tags: [ &quot;keyword: polyhedron&quot; &quot;keyword: hypermap&quot; &quot;keyword: genus&quot; &quot;keyword: Euler formula&quot; &quot;keyword: assisted proofs&quot; &quot;category: Mathematics/Geometry/See also&quot; &quot;date: 2006-09&quot; ] authors: [ &quot;Jean-François Dufourd &lt;dufourd@dpt-info.u-strasbg.fr&gt; [http://dpt-info.u-strasbg.fr/~jfd/]&quot; ] bug-reports: &quot;https://github.com/coq-contribs/euler-formula/issues&quot; dev-repo: &quot;git+https://github.com/coq-contribs/euler-formula.git&quot; synopsis: &quot;Hypermaps, Genus Theorem and Euler Formula&quot; description: &quot;&quot;&quot; This library formalizes the combinatorial hypermaps and their properties in a constructive way. It gives the proofs of the Genus Theorem and of the Euler Formula for the polyhedra.&quot;&quot;&quot; flags: light-uninstall url { src: &quot;https://github.com/coq-contribs/euler-formula/archive/v8.9.0.tar.gz&quot; checksum: &quot;md5=<API key>&quot; } </pre> <h2>Lint</h2> <dl class="dl-horizontal"> <dt>Command</dt> <dd><code>true</code></dd> <dt>Return code</dt> <dd>0</dd> </dl> <h2>Dry install</h2> <p>Dry install with the current Coq version:</p> <dl class="dl-horizontal"> <dt>Command</dt> <dd><code>opam install -y --show-action coq-euler-formula.8.9.0 coq.8.8.2</code></dd> <dt>Return code</dt> <dd>5120</dd> <dt>Output</dt> <dd><pre>[NOTE] Package coq is already installed (current version is 8.8.2). The following dependencies couldn&#39;t be met: - coq-euler-formula -&gt; coq &gt;= 8.9 Your request can&#39;t be satisfied: - No available version of coq satisfies the constraints No solution found, exiting </pre></dd> </dl> <p>Dry install without Coq/switch base, to test if the problem was incompatibility with the current Coq/OCaml version:</p> <dl class="dl-horizontal"> <dt>Command</dt> <dd><code>opam remove -y coq; opam install -y --show-action --unlock-base coq-euler-formula.8.9.0</code></dd> <dt>Return code</dt> <dd>0</dd> </dl> <h2>Install dependencies</h2> <dl class="dl-horizontal"> <dt>Command</dt> <dd><code>true</code></dd> <dt>Return code</dt> <dd>0</dd> <dt>Duration</dt> <dd>0 s</dd> </dl> <h2>Install</h2> <dl class="dl-horizontal"> <dt>Command</dt> <dd><code>true</code></dd> <dt>Return code</dt> <dd>0</dd> <dt>Duration</dt> <dd>0 s</dd> </dl> <h2>Installation size</h2> <p>No files were installed.</p> <h2>Uninstall</h2> <dl class="dl-horizontal"> <dt>Command</dt> <dd><code>true</code></dd> <dt>Return code</dt> <dd>0</dd> <dt>Missing removes</dt> <dd> none </dd> <dt>Wrong removes</dt> <dd> none </dd> </dl> </div> </div> </div> <hr/> <div class="footer"> <p class="text-center"> <small>Sources are on <a href="https: </p> </div> </div> <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script> <script src="../../../../../bootstrap.min.js"></script> </body> </html>
import json from accelerator.models import CriterionOptionSpec from impact.v1.views.utils import valid_keys_note from impact.v1.helpers.validators import <API key> from impact.tests.api_test_case import APITestCase from impact.tests.utils import <API key> from impact.tests.factories import ( <API key>, CriterionFactory, ) from impact.v1.views import <API key> from django.urls import reverse class <API key>(APITestCase): view = <API key> def test_get(self): CriterionOptionSpec.objects.all().delete() option_specs = <API key>.create_batch(5) with self.login(email=self.basic_user().email): url = reverse(self.view.view_name) response = self.client.get(url) data = json.loads(response.content) results = {result['id']: result for result in data['results']} for spec in option_specs: assert results[spec.id]['option'] == spec.option def <API key>(self): criterion = CriterionFactory() data = {'option': 'Posted Option', 'weight': 1.5, 'count': 1, 'criterion_id': criterion.id} with self.login(email=self.basic_user().email): url = reverse(self.view.view_name) response = self.client.post(url, data) option_spec_id = json.loads(response.content)['id'] option_spec = CriterionOptionSpec.objects.get(id=option_spec_id) <API key>(data, option_spec) def <API key>(self): data = {'option': 'Posted Option', 'weight': 1.5, 'count': 1, 'bad_key': 'B flat minor'} with self.login(email=self.basic_user().email): url = reverse(self.view.view_name) response = self.client.post(url, data) note = valid_keys_note(self.view.helper_class.INPUT_KEYS) assert note in str(response.content) def <API key>(self): criterion = CriterionFactory() data = {'option': 'Posted Option', 'weight': 1.5, 'count': 'one', 'criterion_id': criterion.id} with self.login(email=self.basic_user().email): url = reverse(self.view.view_name) response = self.client.post(url, data) error = <API key>.format(field='count', value='one') assert error in str(response.content) def test_post_options(self): post_options = {"option": {"type": "string", "required": True}, "weight": {"type": "number"}, "count": {"type": "integer"}, "criterion_id": {"type": "integer", "required": True}} self.<API key>("POST", post_options) def <API key>(self): option_spec = <API key>() judging_round_id = option_spec.criterion.judging_round_id with self.login(email=self.basic_user().email): url = reverse(self.view.view_name) url += "?judging_round_id={}".format(judging_round_id) response = self.client.get(url) results = json.loads(response.content)['results'] self.assertEqual(len(results), 1) for key, val in results[0].items(): self.assertEqual(val, getattr(option_spec, key)) def <API key>(self): option_spec = <API key>() criterion_id = option_spec.criterion.id with self.login(email=self.basic_user().email): url = reverse(self.view.view_name) url += "?criterion_id={}".format(criterion_id) response = self.client.get(url) results = json.loads(response.content)['results'] self.assertEqual(len(results), 1) for key, val in results[0].items(): self.assertEqual(val, getattr(option_spec, key))
# builder image FROM golang as builder RUN go get github.com/onsi/ginkgo/ginkgo@v1.8.0 # final image # TODO get rid of python dependencies # * wait-for-update.py FROM registry.opensource.zalan.do/library/python-3.9-slim:latest RUN apt-get update && DEBIAN_FRONTEND=noninteractive apt-get install -y \ bc \ curl \ git \ jq \ pwgen \
using System.Collections.Generic; using System.Linq; using Moq; using NUnit.Framework; [TestFixture] public class <API key> { [Test] public void Simple() { var mock = new Mock<Processor>(); mock.Setup(x => x.<API key>("ModuleWeaver")) .Returns(true); mock.CallBase = true; var processor = mock.Object; processor.WeaverAssemblyPath = "Path"; processor.<API key> = true; processor.Weavers = new List<WeaverEntry>(); processor.Logger = new Mock<BuildLogger>().Object; processor.<API key>(); var weaverEntry = processor.Weavers.First(); Assert.AreEqual("ModuleWeaver",weaverEntry.TypeName); Assert.AreEqual("Path",weaverEntry.AssemblyPath); mock.Verify(); } }
# nf-iot-end What is this? ``nf-iot-end`` is part of nf-iot framework which consist of : - ``nf-iot-end``, running on a raspberry pi device - ``nf-iot-middleware``, running on a virtual private server - ``nf-iot-ng``, running on browser or as hybrid mobile app. <pre> <--socket.io nf-iot-end nf-iot-middleware nf-iot-ng socket.io </pre> Requirements - A raspberry pi (B, B+) - node v4.x - ``root`` user in Rasbian. - DHT11 Sensor, two resistor and a LED (optional) Prepare - Run a ``nf-iot-middleware`` instance on somewhere. For example, it running on ``10.0.0.1`` (hostname) and port ``2999``. - Download ``bcm2835`` source code from http: - Clone to raspberry pi side, ``git clone https://github.com/herpiko/nf-iot-end.git`` - ``cd nf-iot-end`` - ``npm install`` Run - ``HOST=10.0.0.1 PORT=2999 node index.js`` Basic Schematic ``nf-iot-end`` provide basic code example in ``index.js`` that follow the schematic bellow. <img src="https://raw.githubusercontent.com/herpiko/nf-iot-end/master/schematic.png"> License MIT See also - https://github.com/herpiko/nf-iot-middleware - https://github.com/herpiko/nf-iot-ng
# Make Fibonacci From the Udacity version of Make 2048. # Make 2048 A Udacity version of Gabriele Cirulli's [original 2048](http://gabrielecirulli.github.io/2048/). The original version is a small clone of [1024](https: Notes for the Udacity version We're using this version as the recommended fork to avoid potential learning issues as the original source changes (and the Udacity videos don't update). You can [fork the original repo as well](https://github.com/gabrielecirulli/2048) 2048 is licensed under the [MIT license.](https: ## Donations Gabriele made this in his spare time, and it's hosted on GitHub (which means I don't have any hosting costs), but if you enjoyed the game and feel like buying him coffee, you can donate at his BTC address: `<API key>`.
using System; namespace Marten.Services { public class <API key> : Exception { public <API key>(int expected, int actual) : base($"Unexpected MAX(id) for event stream, expected {expected} but got {actual}") { } } }
from PyQt4 import QtGui, QtCore from shapely.geometry import Point from shapely import affinity from math import sqrt import FlatCAMApp from GUIElements import * from FlatCAMObj import FlatCAMGerber, FlatCAMExcellon class FlatCAMTool(QtGui.QWidget): toolName = "FlatCAM Generic Tool" def __init__(self, app, parent=None): """ :param app: The application this tool will run in. :type app: App :param parent: Qt Parent :return: FlatCAMTool """ QtGui.QWidget.__init__(self, parent) # self.setSizePolicy(QtGui.QSizePolicy.Maximum, QtGui.QSizePolicy.Maximum) self.layout = QtGui.QVBoxLayout() self.setLayout(self.layout) self.app = app self.menuAction = None def install(self): self.menuAction = self.app.ui.menutool.addAction(self.toolName) self.menuAction.triggered.connect(self.run) def run(self): # Remove anything else in the GUI self.app.ui.tool_scroll_area.takeWidget() # Put ourself in the GUI self.app.ui.tool_scroll_area.setWidget(self) # Switch notebook to tool page self.app.ui.notebook.setCurrentWidget(self.app.ui.tool_tab) self.show() class DblSidedTool(FlatCAMTool): toolName = "Double-Sided PCB Tool" def __init__(self, app): FlatCAMTool.__init__(self, app) ## Title title_label = QtGui.QLabel("<font size=4><b>%s</b></font>" % self.toolName) self.layout.addWidget(title_label) ## Form Layout form_layout = QtGui.QFormLayout() self.layout.addLayout(form_layout) ## Layer to mirror self.object_combo = QtGui.QComboBox() self.object_combo.setModel(self.app.collection) form_layout.addRow("Bottom Layer:", self.object_combo) ## Axis self.mirror_axis = RadioSet([{'label': 'X', 'value': 'X'}, {'label': 'Y', 'value': 'Y'}]) form_layout.addRow("Mirror Axis:", self.mirror_axis) ## Axis Location self.axis_location = RadioSet([{'label': 'Point', 'value': 'point'}, {'label': 'Box', 'value': 'box'}]) form_layout.addRow("Axis Location:", self.axis_location) ## Point/Box self.point_box_container = QtGui.QVBoxLayout() form_layout.addRow("Point/Box:", self.point_box_container) self.point = EvalEntry() self.point_box_container.addWidget(self.point) self.box_combo = QtGui.QComboBox() self.box_combo.setModel(self.app.collection) self.point_box_container.addWidget(self.box_combo) self.box_combo.hide() ## Alignment holes self.alignment_holes = EvalEntry() form_layout.addRow("Alignment Holes:", self.alignment_holes) ## Drill diameter for alignment holes self.drill_dia = LengthEntry() form_layout.addRow("Drill diam.:", self.drill_dia) ## Buttons hlay = QtGui.QHBoxLayout() self.layout.addLayout(hlay) hlay.addStretch() self.<API key> = QtGui.QPushButton("Create Alignment Drill") self.<API key> = QtGui.QPushButton("Mirror Object") hlay.addWidget(self.<API key>) hlay.addWidget(self.<API key>) self.layout.addStretch() ## Signals self.<API key>.clicked.connect(self.<API key>) self.<API key>.clicked.connect(self.on_mirror) self.axis_location.group_toggle_fn = self.on_toggle_pointbox ## Initialize form self.mirror_axis.set_value('X') self.axis_location.set_value('point') def <API key>(self): axis = self.mirror_axis.get_value() mode = self.axis_location.get_value() if mode == "point": px, py = self.point.get_value() else: selection_index = self.box_combo.currentIndex() bb_obj = self.app.collection.object_list[selection_index] # TODO: Direct access?? xmin, ymin, xmax, ymax = bb_obj.bounds() px = 0.5*(xmin+xmax) py = 0.5*(ymin+ymax) xscale, yscale = {"X": (1.0, -1.0), "Y": (-1.0, 1.0)}[axis] dia = self.drill_dia.get_value() tools = {"1": {"C": dia}} holes = self.alignment_holes.get_value() drills = [] for hole in holes: point = Point(hole) point_mirror = affinity.scale(point, xscale, yscale, origin=(px, py)) drills.append({"point": point, "tool": "1"}) drills.append({"point": point_mirror, "tool": "1"}) def obj_init(obj_inst, app_inst): obj_inst.tools = tools obj_inst.drills = drills obj_inst.create_geometry() self.app.new_object("excellon", "Alignment Drills", obj_init) def on_mirror(self): selection_index = self.object_combo.currentIndex() fcobj = self.app.collection.object_list[selection_index] # For now, lets limit to Gerbers and Excellons. # assert isinstance(gerb, FlatCAMGerber) if not isinstance(fcobj, FlatCAMGerber) and not isinstance(fcobj, FlatCAMExcellon): self.info("ERROR: Only Gerber and Excellon objects can be mirrored.") return axis = self.mirror_axis.get_value() mode = self.axis_location.get_value() if mode == "point": px, py = self.point.get_value() else: selection_index = self.box_combo.currentIndex() bb_obj = self.app.collection.object_list[selection_index] # TODO: Direct access?? xmin, ymin, xmax, ymax = bb_obj.bounds() px = 0.5*(xmin+xmax) py = 0.5*(ymin+ymax) fcobj.mirror(axis, [px, py]) fcobj.plot() def on_toggle_pointbox(self): if self.axis_location.get_value() == "point": self.point.show() self.box_combo.hide() else: self.point.hide() self.box_combo.show() class Measurement(FlatCAMTool): toolName = "Measurement Tool" def __init__(self, app): FlatCAMTool.__init__(self, app) # self.setContentsMargins(0, 0, 0, 0) self.layout.setMargin(0) self.layout.setContentsMargins(0, 0, 3, 0) self.setSizePolicy(QtGui.QSizePolicy.Ignored, QtGui.QSizePolicy.Maximum) self.point1 = None self.point2 = None self.label = QtGui.QLabel("Click on a reference point ...") self.label.setFrameStyle(QtGui.QFrame.StyledPanel | QtGui.QFrame.Plain) self.label.setMargin(3) self.layout.addWidget(self.label) # self.layout.setMargin(0) self.setVisible(False) self.click_subscription = None self.move_subscription = None def install(self): FlatCAMTool.install(self) self.app.ui.right_layout.addWidget(self) self.app.plotcanvas.mpl_connect('key_press_event', self.on_key_press) def run(self): self.toggle() def on_click(self, event): if self.point1 is None: self.point1 = (event.xdata, event.ydata) else: self.point2 = copy(self.point1) self.point1 = (event.xdata, event.ydata) self.on_move(event) def on_key_press(self, event): if event.key == 'm': self.toggle() def toggle(self): if self.isVisible(): self.setVisible(False) self.app.plotcanvas.mpl_disconnect(self.move_subscription) self.app.plotcanvas.mpl_disconnect(self.click_subscription) else: self.setVisible(True) self.move_subscription = self.app.plotcanvas.mpl_connect('motion_notify_event', self.on_move) self.click_subscription = self.app.plotcanvas.mpl_connect('button_press_event', self.on_click) def on_move(self, event): if self.point1 is None: self.label.setText("Click on a reference point...") else: try: dx = event.xdata - self.point1[0] dy = event.ydata - self.point1[1] d = sqrt(dx**2 + dy**2) self.label.setText("D = %.4f D(x) = %.4f D(y) = %.4f" % (d, dx, dy)) except TypeError: pass if self.update is not None: self.update()
package aes.motive.gui; import aes.gui.core.GuiDialog; public class GuiBreaker extends GuiDialog { @Override protected void createGui() { } @Override public void initGui() { super.initGui(276, 166); } @Override protected void revalidateGui() { super.revalidateGui(); } @Override protected void update() { } }
<?php namespace Anla\Skipper\Http\Controllers; use Illuminate\Foundation\Auth\AuthenticatesUsers; use Illuminate\Http\Request; class <API key> extends Controller { use AuthenticatesUsers; public function login(Request $request) { return view('skipper::login'); } public function postLogin(Request $request) { $this->validateLogin($request); // If the class is using the ThrottlesLogins trait, we can automatically throttle // the login attempts for this application. We'll key this by the username and // the IP address of the client making these requests into this application. if ($this-><API key>($request)) { $this->fireLockoutEvent($request); return $this->sendLockoutResponse($request); } $credentials = $this->credentials($request); if ($this->guard()->attempt($credentials, $request->has('remember'))) { return $this->sendLoginResponse($request); } // If the login attempt was unsuccessful we will increment the number of attempts // to login and redirect the user back to the login form. Of course, when this // user surpasses their maximum number of attempts they will get locked out. $this-><API key>($request); return $this-><API key>($request); } public function redirectPath() { return route('skipper.dashboard'); } }
<?php return array ( 'id' => 'mot_v820_ver1', 'fallback' => 'opwv_v62_generic', 'capabilities' => array ( 'model_name' => 'V820', 'brand_name' => 'Motorola', 'midi_monophonic' => 'true', 'midi_polyphonic' => 'true', 'colors' => '262144', 'wallpaper_png' => 'true', 'ringtone_mp3' => 'true', 'ringtone_voices' => '64', 'wallpaper' => 'true', 'wallpaper_colors' => '18', '<API key>' => 'true', '<API key>' => '128', 'wallpaper_jpg' => 'true', '<API key>' => '128', 'wallpaper_gif' => 'true', '<API key>' => 'true', 'max_image_width' => '168', 'resolution_height' => '220', 'resolution_width' => '176', 'max_image_height' => '180', '<API key>' => 'none', ), );
/* jshint node: true */ 'use strict'; module.exports = { name: 'ember-sanctify' };
define(function (require, exports, module) { 'use strict'; var TR = require('gui/GuiTR'); var GuiCamera = function (guiParent, ctrlGui) { this._main = ctrlGui._main; // main application this._menu = null; // ui menu this._camera = this._main.getCamera(); // the camera this._cameraTimer = -1; // interval id (used for zqsd/wasd/arrow moves) this._cbTranslation = this.cbOnTranslation.bind(this); this.init(guiParent); }; GuiCamera.prototype = { /** Initialize */ init: function (guiParent) { var camera = this._camera; // Camera fold var menu = this._menu = guiParent.addMenu(TR('cameraTitle')); // reset camera menu.addTitle(TR('cameraReset')); menu.addDualButton(TR('cameraCenter'), TR('cameraFront'), this.resetCamera.bind(this), this.resetFront.bind(this)); menu.addDualButton(TR('cameraLeft'), TR('cameraTop'), this.resetLeft.bind(this), this.resetTop.bind(this)); // camera type var optionsType = {}; menu.addTitle(TR('cameraProjection')); optionsType.PERSPECTIVE = TR('cameraPerspective'); optionsType.ORTHOGRAPHIC = TR('cameraOrthographic'); menu.addCombobox('', camera.getProjectionType(), this.onCameraTypeChange.bind(this), optionsType); // camera fov this._ctrlFov = menu.addSlider(TR('cameraFov'), camera.getFov(), this.onFovChange.bind(this), 10, 90, 1); this._ctrlFov.setVisibility(camera.getProjectionType() === 'PERSPECTIVE'); // camera mode var optionsMode = {}; menu.addTitle(TR('cameraMode')); optionsMode.ORBIT = TR('cameraOrbit'); optionsMode.SPHERICAL = TR('cameraSpherical'); optionsMode.PLANE = TR('cameraPlane'); menu.addCombobox('', camera.getMode(), this.onCameraModeChange.bind(this), optionsMode); menu.addCheckbox(TR('cameraPivot'), camera.getUsePivot(), this.onPivotChange.bind(this)); }, onCameraModeChange: function (value) { this._camera.setMode(value); this._main.render(); }, onCameraTypeChange: function (value) { this._camera.setProjectionType(value); this._ctrlFov.setVisibility(value === 'PERSPECTIVE'); this._main.render(); }, onFovChange: function (value) { this._camera.setFov(value); this._main.render(); }, onKeyDown: function (event) { if (event.handled === true) return; event.stopPropagation(); if (this._main._focusGui) return; event.preventDefault(); var key = event.which; var main = this._main; var camera = main.getCamera(); event.handled = true; if (event.shiftKey && main._action === 'CAMERA_ROTATE') { camera.snapClosestRotation(); main.render(); } switch (key) { case 37: // LEFT camera._moveX = -1; break; case 39: // RIGHT camera._moveX = 1; break; case 38: camera._moveZ = -1; break; case 40: // DOWN camera._moveZ = 1; break; default: event.handled = false; } if (event.handled === true && this._cameraTimer === -1) { this._cameraTimer = window.setInterval(this._cbTranslation, 16.6); } }, cbOnTranslation: function () { var main = this._main; main.getCamera().updateTranslation(); main.render(); }, /** Key released event */ onKeyUp: function (event) { if (event.handled === true) return; event.stopPropagation(); if (this._main._focusGui) return; event.preventDefault(); event.handled = true; var key = event.which; var camera = this._camera; switch (key) { case 37: // LEFT case 39: // RIGHT camera._moveX = 0; break; case 38: case 40: // DOWN camera._moveZ = 0; break; case 32: // SPACE this.resetCamera(); break; case 70: this.resetFront(); break; case 84: this.resetTop(); break; case 76: this.resetLeft(); break; } if (this._cameraTimer !== -1 && camera._moveX === 0 && camera._moveZ === 0) { clearInterval(this._cameraTimer); this._cameraTimer = -1; } }, resetCamera: function () { this._camera.resetView(); this._main.render(); }, resetFront: function () { this._camera.toggleViewFront(); this._main.render(); }, resetLeft: function () { this._camera.toggleViewLeft(); this._main.render(); }, resetTop: function () { this._camera.toggleViewTop(); this._main.render(); }, onPivotChange: function () { this._camera.toggleUsePivot(); this._main.render(); } }; module.exports = GuiCamera; });
package org.piwik.sdk.extra; import android.content.Context; import android.content.SharedPreferences; import android.content.pm.ApplicationInfo; import android.content.pm.PackageInfo; import android.content.pm.PackageManager; import org.junit.Before; import org.junit.Test; import org.mockito.ArgumentCaptor; import org.mockito.Mock; import org.mockito.MockitoAnnotations; import org.piwik.sdk.Piwik; import org.piwik.sdk.QueryParams; import org.piwik.sdk.TrackMe; import org.piwik.sdk.Tracker; import org.piwik.sdk.testhelper.TestPreferences; import java.io.File; import java.io.FileOutputStream; import java.util.UUID; import java.util.regex.Matcher; import java.util.regex.Pattern; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertTrue; import static org.mockito.ArgumentMatchers.anyInt; import static org.mockito.ArgumentMatchers.anyString; import static org.mockito.Mockito.times; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; public class DownloadTrackerTest { ArgumentCaptor<TrackMe> mCaptor = ArgumentCaptor.forClass(TrackMe.class); @Mock Tracker mTracker; @Mock Piwik mPiwik; @Mock Context mContext; @Mock PackageManager mPackageManager; SharedPreferences mSharedPreferences = new TestPreferences(); private PackageInfo mPackageInfo; @Before public void setup() throws PackageManager.<API key> { MockitoAnnotations.initMocks(this); when(mTracker.getPreferences()).thenReturn(mSharedPreferences); when(mTracker.getPiwik()).thenReturn(mPiwik); when(mPiwik.getContext()).thenReturn(mContext); when(mContext.getPackageManager()).thenReturn(mPackageManager); when(mContext.getPackageName()).thenReturn("package"); mPackageInfo = new PackageInfo(); mPackageInfo.versionCode = 123; mPackageInfo.packageName = "package"; //noinspection WrongConstant when(mPackageManager.getPackageInfo(anyString(), anyInt())).thenReturn(mPackageInfo); when(mPackageManager.<API key>("package")).thenReturn("installer"); } @Test public void <API key>() throws Exception { DownloadTracker downloadTracker = new DownloadTracker(mTracker); downloadTracker.trackOnce(new TrackMe(), new DownloadTracker.Extra.None()); verify(mTracker).track(mCaptor.capture()); checkNewAppDownload(mCaptor.getValue()); // track only once downloadTracker.trackOnce(new TrackMe(), new DownloadTracker.Extra.None()); verify(mTracker, times(1)).track(mCaptor.capture()); } @Test public void testTrackIdentifier() throws Exception { ApplicationInfo applicationInfo = new ApplicationInfo(); mPackageInfo.applicationInfo = applicationInfo; applicationInfo.sourceDir = UUID.randomUUID().toString(); final byte[] FAKE_APK_DATA = "this is an apk, awesome right?".getBytes(); final String FAKE_APK_DATA_MD5 = "<API key>"; try { FileOutputStream out = new FileOutputStream(applicationInfo.sourceDir); out.write(FAKE_APK_DATA); out.close(); } catch (java.io.IOException e) { e.printStackTrace(); } DownloadTracker downloadTracker = new DownloadTracker(mTracker); downloadTracker.trackNewAppDownload(new TrackMe(), new DownloadTracker.Extra.ApkChecksum(mContext)); Thread.sleep(100); // APK checksum happens off thread verify(mTracker).track(mCaptor.capture()); checkNewAppDownload(mCaptor.getValue()); Matcher m = REGEX_DOWNLOADTRACK.matcher(mCaptor.getValue().get(QueryParams.DOWNLOAD)); assertTrue(m.matches()); assertEquals("package", m.group(1)); assertEquals(123, Integer.parseInt(m.group(2))); assertEquals(FAKE_APK_DATA_MD5, m.group(3)); assertEquals("http://installer", mCaptor.getValue().get(QueryParams.REFERRER)); downloadTracker.trackNewAppDownload(new TrackMe(), new DownloadTracker.Extra.None()); verify(mTracker, times(2)).track(mCaptor.capture()); checkNewAppDownload(mCaptor.getValue()); String downloadParams = mCaptor.getValue().get(QueryParams.DOWNLOAD); m = REGEX_DOWNLOADTRACK.matcher(downloadParams); assertTrue(downloadParams, m.matches()); assertEquals(3, m.groupCount()); assertEquals("package", m.group(1)); assertEquals(123, Integer.parseInt(m.group(2))); assertEquals(null, m.group(3)); assertEquals("http://installer", mCaptor.getValue().get(QueryParams.REFERRER)); //noinspection <API key> new File(applicationInfo.sourceDir).delete(); } private final Pattern REGEX_DOWNLOADTRACK = Pattern.compile("(?:https?:\\/\\/)([\\w.]+)(?::)([\\d]+)(?:(?:\\/)([\\W\\w]+))?"); @Test public void testTrackReferrer() throws Exception { DownloadTracker downloadTracker = new DownloadTracker(mTracker); downloadTracker.trackNewAppDownload(new TrackMe(), new DownloadTracker.Extra.None()); verify(mTracker).track(mCaptor.capture()); checkNewAppDownload(mCaptor.getValue()); String downloadParams = mCaptor.getValue().get(QueryParams.DOWNLOAD); Matcher m = REGEX_DOWNLOADTRACK.matcher(downloadParams); assertTrue(downloadParams, m.matches()); assertEquals(3, m.groupCount()); assertEquals("package", m.group(1)); assertEquals(123, Integer.parseInt(m.group(2))); assertEquals(null, m.group(3)); assertEquals("http://installer", mCaptor.getValue().get(QueryParams.REFERRER)); when(mPackageManager.<API key>(anyString())).thenReturn(null); downloadTracker.trackNewAppDownload(new TrackMe(), new DownloadTracker.Extra.None()); verify(mTracker, times(2)).track(mCaptor.capture()); checkNewAppDownload(mCaptor.getValue()); m = REGEX_DOWNLOADTRACK.matcher(mCaptor.getValue().get(QueryParams.DOWNLOAD)); assertTrue(m.matches()); assertEquals(3, m.groupCount()); assertEquals("package", m.group(1)); assertEquals(123, Integer.parseInt(m.group(2))); assertEquals(null, m.group(3)); assertEquals(null, mCaptor.getValue().get(QueryParams.REFERRER)); } @Test public void <API key>() throws Exception { DownloadTracker downloadTracker = new DownloadTracker(mTracker); downloadTracker.setVersion("2"); downloadTracker.trackOnce(new TrackMe(), new DownloadTracker.Extra.None()); verify(mTracker).track(mCaptor.capture()); checkNewAppDownload(mCaptor.getValue()); Matcher m = REGEX_DOWNLOADTRACK.matcher(mCaptor.getValue().get(QueryParams.DOWNLOAD)); assertTrue(m.matches()); assertEquals("package", m.group(1)); assertEquals("2", m.group(2)); assertEquals("2", downloadTracker.getVersion()); assertEquals("http://installer", mCaptor.getValue().get(QueryParams.REFERRER)); downloadTracker.trackOnce(new TrackMe(), new DownloadTracker.Extra.None()); verify(mTracker, times(1)).track(mCaptor.capture()); downloadTracker.setVersion(null); downloadTracker.trackOnce(new TrackMe(), new DownloadTracker.Extra.None()); verify(mTracker, times(2)).track(mCaptor.capture()); checkNewAppDownload(mCaptor.getValue()); m = REGEX_DOWNLOADTRACK.matcher(mCaptor.getValue().get(QueryParams.DOWNLOAD)); assertTrue(m.matches()); assertEquals("package", m.group(1)); assertEquals(123, Integer.parseInt(m.group(2))); assertEquals("http://installer", mCaptor.getValue().get(QueryParams.REFERRER)); } private boolean checkNewAppDownload(TrackMe trackMe) { assertTrue(trackMe.get(QueryParams.DOWNLOAD).length() > 0); assertTrue(trackMe.get(QueryParams.URL_PATH).length() > 0); assertEquals(trackMe.get(QueryParams.EVENT_CATEGORY), "Application"); assertEquals(trackMe.get(QueryParams.EVENT_ACTION), "downloaded"); assertEquals(trackMe.get(QueryParams.ACTION_NAME), "application/downloaded"); return true; } }
// This file auto generated by plugin for ida pro. Generated code only for x64. Please, dont change manually #pragma once #include <common/common.h> #include <$<API key>.hpp> START_ATF_NAMESPACE struct DelayLoadProc { int fImportByName; $<API key> ___u1; }; END_ATF_NAMESPACE
#include <windows.h> #include <tchar.h> // Global Variables: BOOL fDraw = FALSE; POINT ptPrevious; HINSTANCE hInst; // current instance TCHAR szTitle[]="l8"; // The title bar text TCHAR szWindowClass[]="WinApp"; // the class name COLORREF Color[]={RGB(255,0,0),RGB(0,255,0),RGB(0,0,255),RGB(0,0,0)}; int Index=3; // Foward declarations of functions included in this code module: ATOM MyRegisterClass(HINSTANCE hInstance); BOOL InitInstance(HINSTANCE, int); LRESULT CALLBACK WndProc(HWND, UINT, WPARAM, LPARAM); void Marker(LONG x, LONG y,int Index, HWND hwnd); int APIENTRY WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, LPSTR lpCmdLine, int nCmdShow) { // TODO: Place code here. MSG msg; // Register Class MyRegisterClass(hInstance); // Perform application initialization: if (!InitInstance (hInstance, nCmdShow)) { return FALSE; } // Main message loop: while (GetMessage(&msg, NULL, 0, 0)) { TranslateMessage(&msg); DispatchMessage(&msg); } return msg.wParam; } // FUNCTION: MyRegisterClass() // PURPOSE: Registers the window class. // COMMENTS: // This function and its usage is only necessary if you want this code // to be compatible with Win32 systems prior to the 'RegisterClassEx' // function that was added to Windows 95. ATOM MyRegisterClass(HINSTANCE hInstance) { WNDCLASSEX wcex; wcex.cbSize = sizeof(WNDCLASSEX); wcex.style = CS_HREDRAW | CS_VREDRAW; wcex.lpfnWndProc = (WNDPROC)WndProc; wcex.cbClsExtra = 0; wcex.cbWndExtra = 0; wcex.hInstance = hInstance; wcex.hIcon = LoadIcon (NULL, IDI_APPLICATION); wcex.hCursor = LoadCursor(NULL, IDC_ARROW); wcex.hbrBackground = (HBRUSH)(COLOR_WINDOW+1); wcex.lpszMenuName = NULL; wcex.lpszClassName = szWindowClass; wcex.hIconSm = LoadIcon (NULL, IDI_APPLICATION); return RegisterClassEx(&wcex); } // FUNCTION: InitInstance(HANDLE, int) // PURPOSE: Saves instance handle and creates main window // COMMENTS: // In this function, we save the instance handle in a global variable and // create and display the main program window. BOOL InitInstance(HINSTANCE hInstance, int nCmdShow) { HWND hWnd; hInst = hInstance; // Store instance handle in our global variable hWnd = CreateWindow(szWindowClass, szTitle, WS_OVERLAPPEDWINDOW, CW_USEDEFAULT, 0, CW_USEDEFAULT, 0, NULL, NULL, hInstance, NULL); if (!hWnd) { return FALSE; } ShowWindow(hWnd, nCmdShow); UpdateWindow(hWnd); return TRUE; } // FUNCTION: WndProc(HWND, unsigned, WORD, LONG) // PURPOSE: Processes messages for the main window. // WM_COMMAND - process the application menu // WM_PAINT - Paint the main window // WM_DESTROY - post a quit message and return LRESULT CALLBACK WndProc(HWND hWnd, UINT message, WPARAM wParam, LPARAM lParam) { PAINTSTRUCT ps; HDC hdc; RECT rt; char szHello[]="Hello, C-Free!"; switch (message) { case WM_KEYDOWN: switch (wParam) { case VK_LEFT: // Process the LEFT ARROW key. if(Index<4) { Index++; }else { Index=0; } // InvalidateRect(hWnd, NULL, TRUE); // default: break; } break; case WM_LBUTTONDOWN: fDraw = TRUE; ptPrevious.x = LOWORD(lParam); ptPrevious.y = HIWORD(lParam); return 0L; case WM_LBUTTONUP: if (fDraw) { hdc = GetDC(hWnd); MoveToEx(hdc, ptPrevious.x, ptPrevious.y, NULL); LineTo(hdc, LOWORD(lParam), HIWORD(lParam)); ReleaseDC(hWnd, hdc); } fDraw = FALSE; return 0L; case WM_MOUSEMOVE: if (fDraw) { hdc = GetDC(hWnd); MoveToEx(hdc, ptPrevious.x, ptPrevious.y, NULL); LineTo(hdc, ptPrevious.x = LOWORD(lParam), ptPrevious.y = HIWORD(lParam)); ReleaseDC(hWnd, hdc); } return 0L; case WM_PAINT: hdc = BeginPaint(hWnd, &ps); // TODO: Add any drawing code here... GetClientRect(hWnd, &rt); DrawText(hdc, szHello, strlen(szHello), &rt, DT_CENTER); Marker(100,100,Index,hWnd); EndPaint(hWnd, &ps); break; case WM_CLOSE: DestroyWindow(hWnd); break; case WM_DESTROY: PostQuitMessage(0); break; default: return DefWindowProc(hWnd, message, wParam, lParam); } return 0; } void Marker(LONG x, LONG y,int Index, HWND hwnd) { HDC hdc; HPEN hPen; hdc = GetDC(hwnd); // hPen = CreatePen(PS_DASH,5,RGB(0,255,0)); hPen = CreatePen(PS_DOT,1,Color[Index]); SelectObject(hdc, hPen); MoveToEx(hdc, (int) x - 10, (int) y, (LPPOINT) NULL); LineTo(hdc, (int) x + 100, (int) y); MoveToEx(hdc, (int) x, (int) y - 100, (LPPOINT) NULL); LineTo(hdc, (int) x, (int) y + 100); DeleteObject(hPen); ReleaseDC(hwnd, hdc); }
import { CommonModule } from '@angular/common'; import { NgModule } from '@angular/core'; import { <API key> } from '@angular/material/slide-toggle'; import { SharedModule } from '../../shared-module/shared-module.module'; import { <API key> } from './landing-dialog.component'; @NgModule({ declarations: [<API key>], imports: [CommonModule, SharedModule, <API key>], exports: [<API key>], }) export class LandingDialogModule {}
ActiveRecord::Schema.define(:version => 1) do create_table :people do |t| t.string :first_name, :last_name, :occupation t.integer :age, :phone, :favorite_number end end
// <auto-generated> // This code was generated from a template. // Manual changes to this file may cause unexpected behavior in your application. // Manual changes to this file will be overwritten if the code is regenerated. // </auto-generated> namespace ClubChallengeBeta.App_Data { using System; using System.Collections.Generic; public partial class Club { [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2214:<API key>")] public Club() { this.AspNetUsers = new HashSet<AspNetUser>(); this.ClubImages = new HashSet<ClubImage>(); } public int ClubId { get; set; } public string OwnerId { get; set; } public string Name { get; set; } public string Text { get; set; } public byte[] ImageData { get; set; } public string ImageMimeType { get; set; } [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2227:<API key>")] public virtual ICollection<AspNetUser> AspNetUsers { get; set; } public virtual AspNetUser AspNetUser { get; set; } [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2227:<API key>")] public virtual ICollection<ClubImage> ClubImages { get; set; } } }
<!DOCTYPE html PUBLIC "- <html xmlns="http: <head> <meta http-equiv="Content-Type" content="text/xhtml;charset=UTF-8"/> <meta http-equiv="X-UA-Compatible" content="IE=9"/> <meta name="generator" content="Doxygen 1.8.11"/> <title>V8 API Reference Guide for node.js v6.10.0: Member List</title> <link href="tabs.css" rel="stylesheet" type="text/css"/> <script type="text/javascript" src="jquery.js"></script> <script type="text/javascript" src="dynsections.js"></script> <link href="search/search.css" rel="stylesheet" type="text/css"/> <script type="text/javascript" src="search/searchdata.js"></script> <script type="text/javascript" src="search/search.js"></script> <script type="text/javascript"> $(document).ready(function() { init_search(); }); </script> <link href="doxygen.css" rel="stylesheet" type="text/css" /> </head> <body> <div id="top"><!-- do not remove this div, it is closed by doxygen! --> <div id="titlearea"> <table cellspacing="0" cellpadding="0"> <tbody> <tr style="height: 56px;"> <td id="projectalign" style="padding-left: 0.5em;"> <div id="projectname">V8 API Reference Guide for node.js v6.10.0 </div> </td> </tr> </tbody> </table> </div> <!-- end header part --> <!-- Generated by Doxygen 1.8.11 --> <script type="text/javascript"> var searchBox = new SearchBox("searchBox", "search",false,'Search'); </script> <div id="navrow1" class="tabs"> <ul class="tablist"> <li><a href="index.html"><span>Main&#160;Page</span></a></li> <li><a href="namespaces.html"><span>Namespaces</span></a></li> <li class="current"><a href="annotated.html"><span>Classes</span></a></li> <li><a href="files.html"><span>Files</span></a></li> <li><a href="examples.html"><span>Examples</span></a></li> <li> <div id="MSearchBox" class="MSearchBoxInactive"> <span class="left"> <img id="MSearchSelect" src="search/mag_sel.png" onmouseover="return searchBox.OnSearchSelectShow()" onmouseout="return searchBox.OnSearchSelectHide()" alt=""/> <input type="text" id="MSearchField" value="Search" accesskey="S" onfocus="searchBox.OnSearchFieldFocus(true)" onblur="searchBox.OnSearchFieldFocus(false)" onkeyup="searchBox.OnSearchFieldChange(event)"/> </span><span class="right"> <a id="MSearchClose" href="javascript:searchBox.CloseResultsWindow()"><img id="MSearchCloseImg" border="0" src="search/close.png" alt=""/></a> </span> </div> </li> </ul> </div> <div id="navrow2" class="tabs2"> <ul class="tablist"> <li><a href="annotated.html"><span>Class&#160;List</span></a></li> <li><a href="classes.html"><span>Class&#160;Index</span></a></li> <li><a href="inherits.html"><span>Class&#160;Hierarchy</span></a></li> <li><a href="functions.html"><span>Class&#160;Members</span></a></li> </ul> </div> <!-- window showing the filter options --> <div id="MSearchSelectWindow" onmouseover="return searchBox.OnSearchSelectShow()" onmouseout="return searchBox.OnSearchSelectHide()" onkeydown="return searchBox.OnSearchSelectKey(event)"> </div> <!-- iframe showing the search results (closed by default) --> <div id="<API key>"> <iframe src="javascript:void(0)" frameborder="0" name="MSearchResults" id="MSearchResults"> </iframe> </div> <div id="nav-path" class="navpath"> <ul> <li class="navelem"><a class="el" href="namespacev8.html">v8</a></li><li class="navelem"><a class="el" href="<API key>.html"><API key></a></li> </ul> </div> </div><!-- top --> <div class="header"> <div class="headertitle"> <div class="title">v8::<API key> Member List</div> </div> </div><!--header <div class="contents"> <p>This is the complete list of members for <a class="el" href="<API key>.html">v8::<API key></a>, including all inherited members.</p> <table class="directory"> <tr bgcolor="#f0f0f0" class="even"><td class="entry"><b><API key></b>(Persistent&lt; Value &gt; *value, uint16_t class_id) (defined in <a class="el" href="<API key>.html">v8::<API key></a>)</td><td class="entry"><a class="el" href="<API key>.html">v8::<API key></a></td><td class="entry"><span class="mlabel">inline</span><span class="mlabel">virtual</span></td></tr> <tr bgcolor="#f0f0f0"><td class="entry"><b>~<API key></b>() (defined in <a class="el" href="<API key>.html">v8::<API key></a>)</td><td class="entry"><a class="el" href="<API key>.html">v8::<API key></a></td><td class="entry"><span class="mlabel">inline</span><span class="mlabel">virtual</span></td></tr> </table></div><!-- contents --> <!-- start footer part --> <hr class="footer"/><address class="footer"><small> Generated by & <img class="footer" src="doxygen.png" alt="doxygen"/> </a> 1.8.11 </small></address> </body> </html>
/** * This code was auto-generated by a Codezu. * * Changes to this file may cause incorrect behavior and will be lost if * the code is regenerated. */ package com.mozu.api.clients.commerce; import java.util.List; import java.util.ArrayList; import com.mozu.api.MozuClient; import com.mozu.api.MozuClientFactory; import com.mozu.api.MozuUrl; import com.mozu.api.Headers; import org.joda.time.DateTime; import com.mozu.api.AsyncCallback; import java.util.concurrent.CountDownLatch; import com.mozu.api.security.AuthTicket; import org.apache.commons.lang.StringUtils; /** <summary> * Use the Channel Groups resource to manage groups of channels with common information. * </summary> */ public class ChannelGroupClient { /** * Retrieves a list of defined channel groups according to any filter and sort criteria specified in the request. * <p><pre><code> * MozuClient<com.mozu.api.contracts.commerceruntime.channels.<API key>> mozuClient=<API key>(); * client.setBaseAddress(url); * client.executeRequest(); * <API key> <API key> = client.Result(); * </code></pre></p> * @return Mozu.Api.MozuClient <com.mozu.api.contracts.commerceruntime.channels.<API key>> * @see com.mozu.api.contracts.commerceruntime.channels.<API key> */ public static MozuClient<com.mozu.api.contracts.commerceruntime.channels.<API key>> <API key>() throws Exception { return <API key>( null, null, null, null, null); } /** * Retrieves a list of defined channel groups according to any filter and sort criteria specified in the request. * <p><pre><code> * MozuClient<com.mozu.api.contracts.commerceruntime.channels.<API key>> mozuClient=<API key>( startIndex, pageSize, sortBy, filter, responseFields); * client.setBaseAddress(url); * client.executeRequest(); * <API key> <API key> = client.Result(); * </code></pre></p> * @param filter A set of expressions that consist of a field, operator, and value and represent search parameter syntax when filtering results of a query. Valid operators include equals (eq), does not equal (ne), greater than (gt), less than (lt), greater than or equal to (ge), less than or equal to (le), starts with (sw), or contains (cont). For example - "filter=IsDisplayed+eq+true" * @param pageSize The number of results to display on each page when creating paged results from a query. The maximum value is 200. * @param responseFields Use this field to include those fields which are not included by default. * @param sortBy The property by which to sort results and whether the results appear in ascending (a-z) order, represented by ASC or in descending (z-a) order, represented by DESC. The sortBy parameter follows an available property. For example: "sortBy=productCode+asc" * @param startIndex When creating paged results from a query, this value indicates the zero-based offset in the complete result set where the returned entities begin. For example, with a PageSize of 25, to get the 51st through the 75th items, use startIndex=3. * @return Mozu.Api.MozuClient <com.mozu.api.contracts.commerceruntime.channels.<API key>> * @see com.mozu.api.contracts.commerceruntime.channels.<API key> */ public static MozuClient<com.mozu.api.contracts.commerceruntime.channels.<API key>> <API key>(Integer startIndex, Integer pageSize, String sortBy, String filter, String responseFields) throws Exception { MozuUrl url = com.mozu.api.urls.commerce.ChannelGroupUrl.getChannelGroupsUrl(filter, pageSize, responseFields, sortBy, startIndex); String verb = "GET"; Class<?> clz = com.mozu.api.contracts.commerceruntime.channels.<API key>.class; MozuClient<com.mozu.api.contracts.commerceruntime.channels.<API key>> mozuClient = (MozuClient<com.mozu.api.contracts.commerceruntime.channels.<API key>>) MozuClientFactory.getInstance(clz); mozuClient.setVerb(verb); mozuClient.setResourceUrl(url); return mozuClient; } /** * Retrieves the details of a defined channel group. * <p><pre><code> * MozuClient<com.mozu.api.contracts.commerceruntime.channels.ChannelGroup> mozuClient=<API key>( code); * client.setBaseAddress(url); * client.executeRequest(); * ChannelGroup channelGroup = client.Result(); * </code></pre></p> * @param code User-defined code that uniqely identifies the channel group. * @return Mozu.Api.MozuClient <com.mozu.api.contracts.commerceruntime.channels.ChannelGroup> * @see com.mozu.api.contracts.commerceruntime.channels.ChannelGroup */ public static MozuClient<com.mozu.api.contracts.commerceruntime.channels.ChannelGroup> <API key>(String code) throws Exception { return <API key>( code, null); } /** * Retrieves the details of a defined channel group. * <p><pre><code> * MozuClient<com.mozu.api.contracts.commerceruntime.channels.ChannelGroup> mozuClient=<API key>( code, responseFields); * client.setBaseAddress(url); * client.executeRequest(); * ChannelGroup channelGroup = client.Result(); * </code></pre></p> * @param code User-defined code that uniqely identifies the channel group. * @param responseFields Use this field to include those fields which are not included by default. * @return Mozu.Api.MozuClient <com.mozu.api.contracts.commerceruntime.channels.ChannelGroup> * @see com.mozu.api.contracts.commerceruntime.channels.ChannelGroup */ public static MozuClient<com.mozu.api.contracts.commerceruntime.channels.ChannelGroup> <API key>(String code, String responseFields) throws Exception { MozuUrl url = com.mozu.api.urls.commerce.ChannelGroupUrl.getChannelGroupUrl(code, responseFields); String verb = "GET"; Class<?> clz = com.mozu.api.contracts.commerceruntime.channels.ChannelGroup.class; MozuClient<com.mozu.api.contracts.commerceruntime.channels.ChannelGroup> mozuClient = (MozuClient<com.mozu.api.contracts.commerceruntime.channels.ChannelGroup>) MozuClientFactory.getInstance(clz); mozuClient.setVerb(verb); mozuClient.setResourceUrl(url); return mozuClient; } /** * Creates a new group of channels with common information. * <p><pre><code> * MozuClient<com.mozu.api.contracts.commerceruntime.channels.ChannelGroup> mozuClient=<API key>( channelGroup); * client.setBaseAddress(url); * client.executeRequest(); * ChannelGroup channelGroup = client.Result(); * </code></pre></p> * @param channelGroup Properties of a group of channels that share common information. * @return Mozu.Api.MozuClient <com.mozu.api.contracts.commerceruntime.channels.ChannelGroup> * @see com.mozu.api.contracts.commerceruntime.channels.ChannelGroup * @see com.mozu.api.contracts.commerceruntime.channels.ChannelGroup */ public static MozuClient<com.mozu.api.contracts.commerceruntime.channels.ChannelGroup> <API key>(com.mozu.api.contracts.commerceruntime.channels.ChannelGroup channelGroup) throws Exception { return <API key>( channelGroup, null); } /** * Creates a new group of channels with common information. * <p><pre><code> * MozuClient<com.mozu.api.contracts.commerceruntime.channels.ChannelGroup> mozuClient=<API key>( channelGroup, responseFields); * client.setBaseAddress(url); * client.executeRequest(); * ChannelGroup channelGroup = client.Result(); * </code></pre></p> * @param responseFields Use this field to include those fields which are not included by default. * @param channelGroup Properties of a group of channels that share common information. * @return Mozu.Api.MozuClient <com.mozu.api.contracts.commerceruntime.channels.ChannelGroup> * @see com.mozu.api.contracts.commerceruntime.channels.ChannelGroup * @see com.mozu.api.contracts.commerceruntime.channels.ChannelGroup */ public static MozuClient<com.mozu.api.contracts.commerceruntime.channels.ChannelGroup> <API key>(com.mozu.api.contracts.commerceruntime.channels.ChannelGroup channelGroup, String responseFields) throws Exception { MozuUrl url = com.mozu.api.urls.commerce.ChannelGroupUrl.<API key>(responseFields); String verb = "POST"; Class<?> clz = com.mozu.api.contracts.commerceruntime.channels.ChannelGroup.class; MozuClient<com.mozu.api.contracts.commerceruntime.channels.ChannelGroup> mozuClient = (MozuClient<com.mozu.api.contracts.commerceruntime.channels.ChannelGroup>) MozuClientFactory.getInstance(clz); mozuClient.setVerb(verb); mozuClient.setResourceUrl(url); mozuClient.setBody(channelGroup); return mozuClient; } /** * Updates one or more properties of a defined channel group. * <p><pre><code> * MozuClient<com.mozu.api.contracts.commerceruntime.channels.ChannelGroup> mozuClient=<API key>( channelGroup, code); * client.setBaseAddress(url); * client.executeRequest(); * ChannelGroup channelGroup = client.Result(); * </code></pre></p> * @param code User-defined code that uniqely identifies the channel group. * @param channelGroup Properties of a group of channels that share common information. * @return Mozu.Api.MozuClient <com.mozu.api.contracts.commerceruntime.channels.ChannelGroup> * @see com.mozu.api.contracts.commerceruntime.channels.ChannelGroup * @see com.mozu.api.contracts.commerceruntime.channels.ChannelGroup */ public static MozuClient<com.mozu.api.contracts.commerceruntime.channels.ChannelGroup> <API key>(com.mozu.api.contracts.commerceruntime.channels.ChannelGroup channelGroup, String code) throws Exception { return <API key>( channelGroup, code, null); } /** * Updates one or more properties of a defined channel group. * <p><pre><code> * MozuClient<com.mozu.api.contracts.commerceruntime.channels.ChannelGroup> mozuClient=<API key>( channelGroup, code, responseFields); * client.setBaseAddress(url); * client.executeRequest(); * ChannelGroup channelGroup = client.Result(); * </code></pre></p> * @param code User-defined code that uniqely identifies the channel group. * @param responseFields Use this field to include those fields which are not included by default. * @param channelGroup Properties of a group of channels that share common information. * @return Mozu.Api.MozuClient <com.mozu.api.contracts.commerceruntime.channels.ChannelGroup> * @see com.mozu.api.contracts.commerceruntime.channels.ChannelGroup * @see com.mozu.api.contracts.commerceruntime.channels.ChannelGroup */ public static MozuClient<com.mozu.api.contracts.commerceruntime.channels.ChannelGroup> <API key>(com.mozu.api.contracts.commerceruntime.channels.ChannelGroup channelGroup, String code, String responseFields) throws Exception { MozuUrl url = com.mozu.api.urls.commerce.ChannelGroupUrl.<API key>(code, responseFields); String verb = "PUT"; Class<?> clz = com.mozu.api.contracts.commerceruntime.channels.ChannelGroup.class; MozuClient<com.mozu.api.contracts.commerceruntime.channels.ChannelGroup> mozuClient = (MozuClient<com.mozu.api.contracts.commerceruntime.channels.ChannelGroup>) MozuClientFactory.getInstance(clz); mozuClient.setVerb(verb); mozuClient.setResourceUrl(url); mozuClient.setBody(channelGroup); return mozuClient; } /** * Deletes a defined group of channels, which removes the group association with each channel in the group but does not delete the channel definitions themselves. * <p><pre><code> * MozuClient mozuClient=<API key>( code); * client.setBaseAddress(url); * client.executeRequest(); * </code></pre></p> * @param code User-defined code that uniqely identifies the channel group. * @return Mozu.Api.MozuClient */ public static MozuClient <API key>(String code) throws Exception { MozuUrl url = com.mozu.api.urls.commerce.ChannelGroupUrl.<API key>(code); String verb = "DELETE"; MozuClient mozuClient = (MozuClient) MozuClientFactory.getInstance(); mozuClient.setVerb(verb); mozuClient.setResourceUrl(url); return mozuClient; } }
layout: post date: 2011-07-07 18:00:00 title: Another delightful baby.... tags: [archived-posts] categories: archives permalink: /:categories/:year/:month/:day/:title/ Yesterday I posted the pictures of a little one at home...here's a little one who came and unabashedly looked up at me in Des Peres Creek, in Forest Park! <a href="http: That's the <a href="http://en.wikipedia.org/wiki/American_Mink"> American Mink </a> Danny Brown had introduced me to the place on Des Peres Creek where I could sit patiently and wait for the family of minks to appear; I think it's a mother (and a father, I'm not sure!) and a litter of 3 or 4 babies. I was very lucky indeed to have this curious little one come out, and here's a video of it going along the river bank: <lj-embed id="708"/> It's been very hot and muggy and I have not been able to spend a lot of time wandering around Forest Park as I can do at other times of the year! But the mink area is a usual part of my morning walk these days...some lovely birds to see, even if the minks are elusive!
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN"> <html xmlns="http: <head> <title>datasheet for <API key></title> <style type="text/css"> body { font-family:arial ;} a { text-decoration:underline ; color:#003000 ;} a:hover { text-decoration:underline ; color:0030f0 ;} td { padding : 5px ;} table.topTitle { width:100% ;} table.topTitle td.l { text-align:left ; font-weight: bold ; font-size:30px ;} table.topTitle td.r { text-align:right ; font-weight: bold ; font-size:16px ;} table.blueBar { width : 100% ; border-spacing : 0px ;} table.blueBar td { background:#0036ff ; font-size:12px ; color : white ; text-align : left ; font-weight : bold ;} table.blueBar td.l { text-align : left ;} table.blueBar td.r { text-align : right ;} table.items { width:100% ; border-collapse:collapse ;} table.items td.label { font-weight:bold ; font-size:16px ; vertical-align:top ;} table.items td.mono { font-family:courier ; font-size:12px ; white-space:pre ;} div.label { font-weight:bold ; font-size:16px ; vertical-align:top ; text-align:center ;} table.grid { border-collapse:collapse ;} table.grid td { border:1px solid #bbb ; font-size:12px ;} body { font-family:arial ;} table.x { font-family:courier ; border-collapse:collapse ; padding:2px ;} table.x td { border:1px solid #bbb ;} td.tableTitle { font-weight:bold ; text-align:center ;} table.grid { border-collapse:collapse ;} table.grid td { border:1px solid #bbb ;} table.grid td.tableTitle { font-weight:bold ; text-align:center ;} table.mmap { border-collapse:collapse ; text-size:11px ; border:1px solid #d8d8d8 ;} table.mmap td { border-color:#d8d8d8 ; border-width:1px ; border-style:solid ;} table.mmap td.empty { border-style:none ; background-color:#f0f0f0 ;} table.mmap td.slavemodule { text-align:left ; font-size:11px ; border-style:solid solid none solid ;} table.mmap td.slavem { text-align:right ; font-size:9px ; font-style:italic ; border-style:none solid none solid ;} table.mmap td.slaveb { text-align:right ; font-size:9px ; font-style:italic ; border-style:none solid solid solid ;} table.mmap td.mastermodule { text-align:center ; font-size:11px ; border-style:solid solid none solid ;} table.mmap td.masterlr { text-align:center ; font-size:9px ; font-style:italic ; border-style:none solid solid solid ;} table.mmap td.masterl { text-align:center ; font-size:9px ; font-style:italic ; border-style:none none solid solid ;} table.mmap td.masterm { text-align:center ; font-size:9px ; font-style:italic ; border-style:none none solid none ;} table.mmap td.masterr { text-align:center ; font-size:9px ; font-style:italic ; border-style:none solid solid none ;} table.mmap td.addr { font-family:courier ; font-size:9px ; text-align:right ;} table.connectionboxes { border-collapse:separate ; border-spacing:0px ; font-family:arial ;} table.connectionboxes td.from { border-bottom:1px solid black ; font-size:9px ; font-style:italic ; vertical-align:bottom ; text-align:left ;} table.connectionboxes td.to { font-size:9px ; font-style:italic ; vertical-align:top ; text-align:right ;} table.connectionboxes td.lefthandwire { border-bottom:1px solid black ; font-size:9px ; font-style:italic ; vertical-align:bottom ; text-align:right ;} table.connectionboxes td.righthandwire { border-bottom:1px solid black ; font-size:9px ; font-style:italic ; vertical-align:bottom ; text-align:left ;} table.connectionboxes td.righthandlabel { font-size:11px ; vertical-align:bottom ; text-align:left ;} table.connectionboxes td.neighbor { padding:3px ; border:1px solid black ; font-size: 11px ; background:#e8e8e8 ; vertical-align:center ; text-align:center ;} table.connectionboxes td.main { padding:8px ; border:1px solid black ; font-size: 14px ; font-weight:bold ; background:#ffffff ; vertical-align:center ; text-align:center ;} .parametersbox { border:1px solid #d0d0d0 ; display:inline-block ; max-height:160px ; overflow:auto ; width:360px ; font-size:10px ;} .flowbox { display:inline-block ;} .parametersbox table { font-size:10px ;} td.parametername { font-style:italic ;} td.parametervalue { font-weight:bold ;} div.greydiv { vertical-align:top ; text-align:center ; background:#eeeeee ; border-top:1px solid #707070 ; border-bottom:1px solid #707070 ; padding:20px ; margin:20px ; width:auto ;}</style> </head> <body> <table class="topTitle"> <tr> <td class="l"><API key></td> <td class="r"> <br/> <br/> </td> </tr> </table> <table class="blueBar"> <tr> <td class="l">2018.01.09.14:30:40</td> <td class="r">Datasheet</td> </tr> </table> <div style="width:100% ; height:10px"> </div> <div class="label">Overview</div> <div class="greydiv"> <div style="display:inline-block ; text-align:left"> <table class="connectionboxes"> <tr style="height:6px"> <td></td> </tr> </table> </div><span style="display:inline-block ; width:28px"> </span> <div style="display:inline-block ; text-align:left"><span> <br/></span> </div> </div> <div style="width:100% ; height:10px"> </div> <div class="label">Memory Map</div> <table class="mmap"> <tr> <td class="empty" rowspan="2"></td> </tr> </table> <a name="module_rst_in"> </a> <div> <hr/> <h2>rst_in</h2>altera_reset_bridge v17.1 <br/> <br/> <br/> <table class="flowbox"> <tr> <td class="parametersbox"> <h2>Parameters</h2> <table> <tr> <td class="parametername">ACTIVE_LOW_RESET</td> <td class="parametervalue">1</td> </tr> <tr> <td class="parametername">SYNCHRONOUS_EDGES</td> <td class="parametervalue">deassert</td> </tr> <tr> <td class="parametername">NUM_RESET_OUTPUTS</td> <td class="parametervalue">1</td> </tr> <tr> <td class="parametername">USE_RESET_REQUEST</td> <td class="parametervalue">0</td> </tr> <tr> <td class="parametername">deviceFamily</td> <td class="parametervalue">UNKNOWN</td> </tr> <tr> <td class="parametername">generateLegacySim</td> <td class="parametervalue">false</td> </tr> </table> </td> </tr> </table>&#160;&#160; <table class="flowbox"> <tr> <td class="parametersbox"> <h2>Software Assignments</h2>(none)</td> </tr> </table> </div> <table class="blueBar"> <tr> <td class="l">generation took 0.00 seconds</td> <td class="r">rendering took 0.00 seconds</td> </tr> </table> </body> </html>
#include "stdafx.h" #include "MainDlg.h" #include "<API key>.h" int APIENTRY _tWinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, LPTSTR lpCmdLine, int nCmdShow) { <API key>(hPrevInstance); <API key>(lpCmdLine); InitCommonControls(); DialogBox(hInstance, MAKEINTRESOURCE(IDD_MAIN), NULL, Main_Proc); return 0; }
<!DOCTYPE html> <html> <head> <meta charset="utf-8" /> <meta name="viewport" content="width=device-width, initial-scale=1"> <link rel="stylesheet" href="https://apps.bdimg.com/libs/jquerymobile/1.4.5/jquery.mobile-1.4.5.min.css"> <script src="https://apps.bdimg.com/libs/jquery/1.10.2/jquery.min.js"></script> <script src="https://apps.bdimg.com/libs/jquerymobile/1.4.5/jquery.mobile-1.4.5.min.js"></script> <title>OA</title> </head> <body> <div data-role="page" id="pageone" style='background:#BBBBBB'> <div data-role="header"> <h1></h1> </div> <div data-role="main" class="ui-content"> <form method="post" action="user_login.php"> <div class="ui-field-contain"> <label for="fullname"></label> <input type="text" name="fullname" id="fullname" placeholder=" <label for="bday"></label>   <input type="password" name="bday" id="bday"> </div> <input type="submit" data-inline="true" value=""> <a href="tz.html" data-transition="slide">...</a> </form> </div> <div data-role="footer"> <h1>tinyOA v0.01 2016.12.17</h1> </div> </div> </body> </html>
'use strict'; // Service for running code in the context of the application being debugged angular.module('ngDependencyGraph') .factory('appContext', function(chromeExtension, Const) { // Public API return { refresh: function(cb) { chromeExtension.eval(function(window) { window.document.location.reload(); }, cb); }, // takes a bool setDebug: function(setting) { if (setting === true) { chromeExtension.eval(function(window) { window.document.cookie = '__ngDependencyGraph=true;'; window.document.location.reload(); }); } else { chromeExtension.eval(function(window) { window.document.cookie = '__ngDependencyGraph=false;'; window.document.location.reload(); }); } }, getDebug: function(cb) { chromeExtension.eval(function(window) { return document.cookie.indexOf('__ngDependencyGraph=true') !== -1; }, cb); }, // takes a bool setLog: function(setting) { setting = !!setting; chromeExtension.eval('function (window) {' + 'window.__ngDependencyGraph.log = ' + setting.toString() + ';' + '}'); }, // Registering events // TODO: depreciate this; only poll from now on? // There are some cases where you need to gather data on a once-per-bootstrap basis, for // instance getting the version of AngularJS // TODO: move to chromeExtension? watchRefresh: function(cb) { var port = chrome.extension.connect(); port.postMessage({ action: 'register', inspectedTabId: chrome.devtools.inspectedWindow.tabId }); port.onMessage.addListener(function(msg) { if (msg.action === 'refresh' && msg.changeInfo.status === 'complete') { cb(msg.changeInfo); } }); port.onDisconnect.addListener(function(a) { console.log(a); }); } }; });
# encoding: utf-8 require File.expand_path('../../../spec_helper.rb', __FILE__) module Backup describe Syncer::Cloud::LocalFile do describe '.find' do before do @tmpdir = Dir.mktmpdir('backup_spec') SandboxFileUtils.activate!(@tmpdir) FileUtils.mkdir_p File.join(@tmpdir, 'sync_dir/sub_dir') Utilities.unstub(:utility) end after do FileUtils.rm_r(@tmpdir, :force => true, :secure => true) end it 'returns an empty hash if no files are found' do expect( described_class.find(@tmpdir) ).to eq({}) end context 'with test files' do let(:test_files) { { 'sync_dir/one.file' => '<API key>', 'sync_dir/two.file' => '<API key>', 'sync_dir/sub_dir/three.file' => '<API key>', 'base_dir.file' => '<API key>' } } before do test_files.each_key do |path| File.open(File.join(@tmpdir, path), 'w') {|file| file.write path } end end # for more information. it 'returns a Hash of LocalFile objects, keyed by relative path', :pending => RUBY_PLATFORM =~ /darwin/ do Dir.chdir(@tmpdir) do bad_file = "sync_dir/bad\xFFfile" sanitized_bad_file = "sync_dir/bad\xEF\xBF\xBDfile" FileUtils.touch bad_file Logger.expects(:warn).with( "\s\s[skipping] #{ File.expand_path(sanitized_bad_file) }\n" + "\s\sPath Contains Invalid UTF-8 byte sequences" ) local_files = described_class.find('sync_dir') expect( local_files.keys.count ).to be 3 local_files.each do |relative_path, local_file| expect( local_file.path ).to eq( File.expand_path("sync_dir/#{ relative_path }") ) expect( local_file.md5 ).to eq( test_files["sync_dir/#{ relative_path }"] ) end end end it 'ignores excluded files' do expect( described_class.find(@tmpdir, ['**/two.*', /sub|base_dir/]).keys ).to eq(['sync_dir/one.file']) end it 'follows symlinks' do FileUtils.ln_s File.join(@tmpdir, 'base_dir.file'), File.join(@tmpdir, 'sync_dir/link') found = described_class.find(@tmpdir) expect( found.keys ).to include('sync_dir/link') expect( found['sync_dir/link'].md5 ).to eq(test_files['base_dir.file']) end end end end end
<!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> <title>dep-map: 22 s</title> <link rel="shortcut icon" type="image/png" href="../../../../../favicon.png" /> <link href="../../../../../bootstrap.min.css" rel="stylesheet"> <link href="../../../../../bootstrap-custom.css" rel="stylesheet"> <link href="//maxcdn.bootstrapcdn.com/font-awesome/4.2.0/css/font-awesome.min.css" rel="stylesheet"> <script src="../../../../../moment.min.js"></script> <!-- HTML5 Shim and Respond.js IE8 support of HTML5 elements and media queries --> <!-- WARNING: Respond.js doesn't work if you view the page via file: <!--[if lt IE 9]> <script src="https://oss.maxcdn.com/html5shiv/3.7.2/html5shiv.min.js"></script> <script src="https://oss.maxcdn.com/respond/1.4.2/respond.min.js"></script> <![endif] </head> <body> <div class="container"> <div class="navbar navbar-default" role="navigation"> <div class="container-fluid"> <div class="navbar-header"> <a class="navbar-brand" href="../../../../.."><i class="fa fa-lg fa-flag-checkered"></i> Coq bench</a> </div> <div id="navbar" class="collapse navbar-collapse"> <ul class="nav navbar-nav"> <li><a href="../..">clean / released</a></li> <li class="active"><a href="">8.8.2 / dep-map - 8.8.0</a></li> </ul> </div> </div> </div> <div class="article"> <div class="row"> <div class="col-md-12"> <a href="../..">« Up</a> <h1> dep-map <small> 8.8.0 <span class="label label-success">22 s</span> </small> </h1> <p><em><script>document.write(moment("2020-09-04 23:50:27 +0000", "YYYY-MM-DD HH:mm:ss Z").fromNow());</script> (2020-09-04 23:50:27 UTC)</em><p> <h2>Context</h2> <pre># Packages matching: installed # Name # Installed # Synopsis base-bigarray base base-num base Num library distributed with the OCaml compiler base-threads base base-unix base camlp5 7.12 <API key> of OCaml conf-findutils 1 Virtual package relying on findutils conf-m4 1 Virtual package relying on m4 coq 8.8.2 Formal proof management system. num 0 The Num library for arbitrary-precision integer and rational arithmetic ocaml 4.05.0 The OCaml compiler (virtual package) ocaml-base-compiler 4.05.0 Official 4.05.0 release ocaml-config 1 OCaml Switch Configuration ocamlfind 1.8.1 A library manager for OCaml # opam file: opam-version: &quot;2.0&quot; maintainer: &quot;Hugo.Herbelin@inria.fr&quot; homepage: &quot;https://github.com/coq-contribs/dep-map&quot; license: &quot;CeCILL-B&quot; build: [make &quot;-j%{jobs}%&quot;] install: [make &quot;install&quot;] remove: [&quot;rm&quot; &quot;-R&quot; &quot;%{lib}%/coq/user-contrib/DepMap&quot;] depends: [ &quot;ocaml&quot; &quot;coq&quot; {&gt;= &quot;8.8&quot; &amp; &lt; &quot;8.9~&quot;} ] tags: [ &quot;keyword: Maps&quot; &quot;keyword: Dependent maps&quot; &quot;keyword: domain&quot; &quot;category: Computer Science/Data Types and Data Structures&quot; ] authors: [ &quot;Lionel Rieg &lt;lionel.rieg@college-de-france.fr&gt;&quot; ] bug-reports: &quot;https://github.com/coq-contribs/dep-map/issues&quot; dev-repo: &quot;git+https://github.com/coq-contribs/dep-map.git&quot; synopsis: &quot;Dependent Maps&quot; description: &quot;A rudimentary library for dependent maps that contain their domain in the type.&quot; flags: light-uninstall url { src: &quot;https://github.com/coq-contribs/dep-map/archive/v8.8.0.tar.gz&quot; checksum: &quot;md5=<API key>&quot; } </pre> <h2>Lint</h2> <dl class="dl-horizontal"> <dt>Command</dt> <dd><code>true</code></dd> <dt>Return code</dt> <dd>0</dd> </dl> <h2>Dry install</h2> <p>Dry install with the current Coq version:</p> <dl class="dl-horizontal"> <dt>Command</dt> <dd><code>opam install -y --show-action coq-dep-map.8.8.0 coq.8.8.2</code></dd> <dt>Return code</dt> <dd>0</dd> </dl> <p>Dry install without Coq/switch base, to test if the problem was incompatibility with the current Coq/OCaml version:</p> <dl class="dl-horizontal"> <dt>Command</dt> <dd><code>true</code></dd> <dt>Return code</dt> <dd>0</dd> </dl> <h2>Install dependencies</h2> <dl class="dl-horizontal"> <dt>Command</dt> <dd><code>opam list; echo; ulimit -Sv 4000000; timeout 2h opam install -y --deps-only coq-dep-map.8.8.0 coq.8.8.2</code></dd> <dt>Return code</dt> <dd>0</dd> <dt>Duration</dt> <dd>6 s</dd> </dl> <h2>Install</h2> <dl class="dl-horizontal"> <dt>Command</dt> <dd><code>opam list; echo; ulimit -Sv 16000000; timeout 2h opam install -y -v coq-dep-map.8.8.0 coq.8.8.2</code></dd> <dt>Return code</dt> <dd>0</dd> <dt>Duration</dt> <dd>22 s</dd> </dl> <h2>Installation size</h2> <p>Total: 2 M</p> <ul> <li>776 K <code>../ocaml-base-compiler.4.05.0/lib/coq/user-contrib/DepMap/<API key>.vo</code></li> <li>242 K <code>../ocaml-base-compiler.4.05.0/lib/coq/user-contrib/DepMap/<API key>.vo</code></li> <li>198 K <code>../ocaml-base-compiler.4.05.0/lib/coq/user-contrib/DepMap/DepMap.vo</code></li> <li>128 K <code>../ocaml-base-compiler.4.05.0/lib/coq/user-contrib/DepMap/<API key>.glob</code></li> <li>115 K <code>../ocaml-base-compiler.4.05.0/lib/coq/user-contrib/DepMap/<API key>.vo</code></li> <li>97 K <code>../ocaml-base-compiler.4.05.0/lib/coq/user-contrib/DepMap/<API key>.glob</code></li> <li>88 K <code>../ocaml-base-compiler.4.05.0/lib/coq/user-contrib/DepMap/DepMapInterface.vo</code></li> <li>40 K <code>../ocaml-base-compiler.4.05.0/lib/coq/user-contrib/DepMap/<API key>.glob</code></li> <li>29 K <code>../ocaml-base-compiler.4.05.0/lib/coq/user-contrib/DepMap/DepMapInterface.glob</code></li> <li>29 K <code>../ocaml-base-compiler.4.05.0/lib/coq/user-contrib/DepMap/<API key>.v</code></li> <li>21 K <code>../ocaml-base-compiler.4.05.0/lib/coq/user-contrib/DepMap/Coqlib.vo</code></li> <li>15 K <code>../ocaml-base-compiler.4.05.0/lib/coq/user-contrib/DepMap/<API key>.v</code></li> <li>6 K <code>../ocaml-base-compiler.4.05.0/lib/coq/user-contrib/DepMap/DepMapInterface.v</code></li> <li>6 K <code>../ocaml-base-compiler.4.05.0/lib/coq/user-contrib/DepMap/<API key>.v</code></li> <li>4 K <code>../ocaml-base-compiler.4.05.0/lib/coq/user-contrib/DepMap/Coqlib.glob</code></li> <li>2 K <code>../ocaml-base-compiler.4.05.0/lib/coq/user-contrib/DepMap/Coqlib.v</code></li> <li>1 K <code>../ocaml-base-compiler.4.05.0/lib/coq/user-contrib/DepMap/DepMap.glob</code></li> <li>1 K <code>../ocaml-base-compiler.4.05.0/lib/coq/user-contrib/DepMap/DepMap.v</code></li> </ul> <h2>Uninstall</h2> <dl class="dl-horizontal"> <dt>Command</dt> <dd><code>opam remove -y coq-dep-map.8.8.0</code></dd> <dt>Return code</dt> <dd>0</dd> <dt>Missing removes</dt> <dd> none </dd> <dt>Wrong removes</dt> <dd> none </dd> </dl> </div> </div> </div> <hr/> <div class="footer"> <p class="text-center"> <small>Sources are on <a href="https: </p> </div> </div> <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script> <script src="../../../../../bootstrap.min.js"></script> </body> </html>
<!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> <title>ltac2: Not compatible </title> <link rel="shortcut icon" type="image/png" href="../../../../../favicon.png" /> <link href="../../../../../bootstrap.min.css" rel="stylesheet"> <link href="../../../../../bootstrap-custom.css" rel="stylesheet"> <link href="//maxcdn.bootstrapcdn.com/font-awesome/4.2.0/css/font-awesome.min.css" rel="stylesheet"> <script src="../../../../../moment.min.js"></script> <!-- HTML5 Shim and Respond.js IE8 support of HTML5 elements and media queries --> <!-- WARNING: Respond.js doesn't work if you view the page via file: <!--[if lt IE 9]> <script src="https://oss.maxcdn.com/html5shiv/3.7.2/html5shiv.min.js"></script> <script src="https://oss.maxcdn.com/respond/1.4.2/respond.min.js"></script> <![endif] </head> <body> <div class="container"> <div class="navbar navbar-default" role="navigation"> <div class="container-fluid"> <div class="navbar-header"> <a class="navbar-brand" href="../../../../.."><i class="fa fa-lg fa-flag-checkered"></i> Coq bench</a> </div> <div id="navbar" class="collapse navbar-collapse"> <ul class="nav navbar-nav"> <li><a href="../..">clean / released</a></li> <li class="active"><a href="">8.7.0 / ltac2 - 0.3</a></li> </ul> </div> </div> </div> <div class="article"> <div class="row"> <div class="col-md-12"> <a href="../..">« Up</a> <h1> ltac2 <small> 0.3 <span class="label label-info">Not compatible </span> </small> </h1> <p> <em><script>document.write(moment("2022-02-06 09:22:26 +0000", "YYYY-MM-DD HH:mm:ss Z").fromNow());</script> (2022-02-06 09:22:26 UTC)</em><p> <h2>Context</h2> <pre># Packages matching: installed # Name # Installed # Synopsis base-bigarray base base-num base Num library distributed with the OCaml compiler base-threads base base-unix base camlp5 7.14 <API key> of OCaml conf-findutils 1 Virtual package relying on findutils conf-perl 2 Virtual package relying on perl coq 8.7.0 Formal proof management system num 0 The Num library for arbitrary-precision integer and rational arithmetic ocaml 4.04.2 The OCaml compiler (virtual package) ocaml-base-compiler 4.04.2 Official 4.04.2 release ocaml-config 1 OCaml Switch Configuration ocamlfind 1.9.3 A library manager for OCaml # opam file: opam-version: &quot;2.0&quot; name: &quot;coq-ltac2&quot; maintainer: &quot;Pierre-Marie Pédrot &lt;pierre-marie.pedrot@irif.fr&gt;&quot; license: &quot;LGPL 2.1&quot; homepage: &quot;https://github.com/coq/ltac2&quot; dev-repo: &quot;git+https://github.com/coq/ltac2.git&quot; bug-reports: &quot;https://github.com/coq/ltac2/issues&quot; build: [ [make &quot;COQBIN=\&quot;\&quot;&quot; &quot;-j%{jobs}%&quot;] ] install: [make &quot;install&quot;] depends: [ &quot;ocaml&quot; &quot;coq&quot; {&gt;= &quot;8.10&quot; &amp; &lt; &quot;8.11~&quot;} ] synopsis: &quot;A tactic language for Coq&quot; authors: &quot;Pierre-Marie Pédrot &lt;pierre-marie.pedrot@irif.fr&gt;&quot; url { src: &quot;https://github.com/coq/ltac2/archive/0.3.tar.gz&quot; checksum: &quot;sha256=<SHA256-like>&quot; } </pre> <h2>Lint</h2> <dl class="dl-horizontal"> <dt>Command</dt> <dd><code>true</code></dd> <dt>Return code</dt> <dd>0</dd> </dl> <h2>Dry install </h2> <p>Dry install with the current Coq version:</p> <dl class="dl-horizontal"> <dt>Command</dt> <dd><code>opam install -y --show-action coq-ltac2.0.3 coq.8.7.0</code></dd> <dt>Return code</dt> <dd>5120</dd> <dt>Output</dt> <dd><pre>[NOTE] Package coq is already installed (current version is 8.7.0). The following dependencies couldn&#39;t be met: - coq-ltac2 -&gt; coq &gt;= 8.10 -&gt; ocaml &gt;= 4.05.0 base of this switch (use `--unlock-base&#39; to force) No solution found, exiting </pre></dd> </dl> <p>Dry install without Coq/switch base, to test if the problem was incompatibility with the current Coq/OCaml version:</p> <dl class="dl-horizontal"> <dt>Command</dt> <dd><code>opam remove -y coq; opam install -y --show-action --unlock-base coq-ltac2.0.3</code></dd> <dt>Return code</dt> <dd>0</dd> </dl> <h2>Install dependencies</h2> <dl class="dl-horizontal"> <dt>Command</dt> <dd><code>true</code></dd> <dt>Return code</dt> <dd>0</dd> <dt>Duration</dt> <dd>0 s</dd> </dl> <h2>Install </h2> <dl class="dl-horizontal"> <dt>Command</dt> <dd><code>true</code></dd> <dt>Return code</dt> <dd>0</dd> <dt>Duration</dt> <dd>0 s</dd> </dl> <h2>Installation size</h2> <p>No files were installed.</p> <h2>Uninstall 🧹</h2> <dl class="dl-horizontal"> <dt>Command</dt> <dd><code>true</code></dd> <dt>Return code</dt> <dd>0</dd> <dt>Missing removes</dt> <dd> none </dd> <dt>Wrong removes</dt> <dd> none </dd> </dl> </div> </div> </div> <hr/> <div class="footer"> <p class="text-center"> Sources are on <a href="https: </p> </div> </div> <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script> <script src="../../../../../bootstrap.min.js"></script> </body> </html>
<!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> <title>qarith: 23 s </title> <link rel="shortcut icon" type="image/png" href="../../../../../favicon.png" /> <link href="../../../../../bootstrap.min.css" rel="stylesheet"> <link href="../../../../../bootstrap-custom.css" rel="stylesheet"> <link href="//maxcdn.bootstrapcdn.com/font-awesome/4.2.0/css/font-awesome.min.css" rel="stylesheet"> <script src="../../../../../moment.min.js"></script> <!-- HTML5 Shim and Respond.js IE8 support of HTML5 elements and media queries --> <!-- WARNING: Respond.js doesn't work if you view the page via file: <!--[if lt IE 9]> <script src="https://oss.maxcdn.com/html5shiv/3.7.2/html5shiv.min.js"></script> <script src="https://oss.maxcdn.com/respond/1.4.2/respond.min.js"></script> <![endif] </head> <body> <div class="container"> <div class="navbar navbar-default" role="navigation"> <div class="container-fluid"> <div class="navbar-header"> <a class="navbar-brand" href="../../../../.."><i class="fa fa-lg fa-flag-checkered"></i> Coq bench</a> </div> <div id="navbar" class="collapse navbar-collapse"> <ul class="nav navbar-nav"> <li><a href="../..">clean / released</a></li> <li class="active"><a href="">8.8.2 / qarith - 8.8.0</a></li> </ul> </div> </div> </div> <div class="article"> <div class="row"> <div class="col-md-12"> <a href="../..">« Up</a> <h1> qarith <small> 8.8.0 <span class="label label-success">23 s </span> </small> </h1> <p> <em><script>document.write(moment("2022-01-27 23:25:13 +0000", "YYYY-MM-DD HH:mm:ss Z").fromNow());</script> (2022-01-27 23:25:13 UTC)</em><p> <h2>Context</h2> <pre># Packages matching: installed # Name # Installed # Synopsis base-bigarray base base-num base Num library distributed with the OCaml compiler base-ocamlbuild base OCamlbuild binary and libraries distributed with the OCaml compiler base-threads base base-unix base camlp5 7.14 <API key> of OCaml conf-findutils 1 Virtual package relying on findutils conf-perl 2 Virtual package relying on perl coq 8.8.2 Formal proof management system num 0 The Num library for arbitrary-precision integer and rational arithmetic ocaml 4.02.3 The OCaml compiler (virtual package) ocaml-base-compiler 4.02.3 Official 4.02.3 release ocaml-config 1 OCaml Switch Configuration ocamlfind 1.9.2 A library manager for OCaml # opam file: opam-version: &quot;2.0&quot; maintainer: &quot;Hugo.Herbelin@inria.fr&quot; homepage: &quot;https://github.com/coq-contribs/qarith&quot; license: &quot;LGPL 2.1&quot; build: [make &quot;-j%{jobs}%&quot;] install: [make &quot;install&quot;] remove: [&quot;rm&quot; &quot;-R&quot; &quot;%{lib}%/coq/user-contrib/QArith&quot;] depends: [ &quot;ocaml&quot; &quot;coq&quot; {&gt;= &quot;8.8&quot; &amp; &lt; &quot;8.9~&quot;} ] tags: [ &quot;keyword: Q&quot; &quot;keyword: arithmetic&quot; &quot;keyword: rational numbers&quot; &quot;keyword: setoid&quot; &quot;keyword: ring&quot; &quot;category: Mathematics/Arithmetic and Number Theory/Rational numbers&quot; &quot;category: Miscellaneous/Extracted Programs/Arithmetic&quot; ] authors: [ &quot;Pierre Letouzey&quot; ] bug-reports: &quot;https://github.com/coq-contribs/qarith/issues&quot; dev-repo: &quot;git+https://github.com/coq-contribs/qarith.git&quot; synopsis: &quot;A Library for Rational Numbers (QArith)&quot; description: &quot;&quot;&quot; This contribution is a proposition of a library formalizing rational number in Coq.&quot;&quot;&quot; flags: light-uninstall url { src: &quot;https://github.com/coq-contribs/qarith/archive/v8.8.0.tar.gz&quot; checksum: &quot;md5=<API key>&quot; } </pre> <h2>Lint</h2> <dl class="dl-horizontal"> <dt>Command</dt> <dd><code>true</code></dd> <dt>Return code</dt> <dd>0</dd> </dl> <h2>Dry install </h2> <p>Dry install with the current Coq version:</p> <dl class="dl-horizontal"> <dt>Command</dt> <dd><code>opam install -y --show-action coq-qarith.8.8.0 coq.8.8.2</code></dd> <dt>Return code</dt> <dd>0</dd> </dl> <p>Dry install without Coq/switch base, to test if the problem was incompatibility with the current Coq/OCaml version:</p> <dl class="dl-horizontal"> <dt>Command</dt> <dd><code>true</code></dd> <dt>Return code</dt> <dd>0</dd> </dl> <h2>Install dependencies</h2> <dl class="dl-horizontal"> <dt>Command</dt> <dd><code>opam list; echo; ulimit -Sv 4000000; timeout 4h opam install -y --deps-only coq-qarith.8.8.0 coq.8.8.2</code></dd> <dt>Return code</dt> <dd>0</dd> <dt>Duration</dt> <dd>12 s</dd> </dl> <h2>Install </h2> <dl class="dl-horizontal"> <dt>Command</dt> <dd><code>opam list; echo; ulimit -Sv 16000000; timeout 4h opam install -y -v coq-qarith.8.8.0 coq.8.8.2</code></dd> <dt>Return code</dt> <dd>0</dd> <dt>Duration</dt> <dd>23 s</dd> </dl> <h2>Installation size</h2> <p>Total: 429 K</p> <ul> <li>310 K <code>../ocaml-base-compiler.4.02.3/lib/coq/user-contrib/QArith/Sqrt2/Reals.vo</code></li> <li>69 K <code>../ocaml-base-compiler.4.02.3/lib/coq/user-contrib/QArith/Sqrt2/Reals.glob</code></li> <li>29 K <code>../ocaml-base-compiler.4.02.3/lib/coq/user-contrib/QArith/Sqrt2/nat_log.vo</code></li> <li>15 K <code>../ocaml-base-compiler.4.02.3/lib/coq/user-contrib/QArith/Sqrt2/Reals.v</code></li> <li>4 K <code>../ocaml-base-compiler.4.02.3/lib/coq/user-contrib/QArith/Sqrt2/nat_log.glob</code></li> <li>2 K <code>../ocaml-base-compiler.4.02.3/lib/coq/user-contrib/QArith/Sqrt2/nat_log.v</code></li> </ul> <h2>Uninstall 🧹</h2> <dl class="dl-horizontal"> <dt>Command</dt> <dd><code>opam remove -y coq-qarith.8.8.0</code></dd> <dt>Return code</dt> <dd>0</dd> <dt>Missing removes</dt> <dd> none </dd> <dt>Wrong removes</dt> <dd> none </dd> </dl> </div> </div> </div> <hr/> <div class="footer"> <p class="text-center"> Sources are on <a href="https: </p> </div> </div> <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script> <script src="../../../../../bootstrap.min.js"></script> </body> </html>
using System; using NetRuntimeSystem = System; using System.ComponentModel; using NetOffice.Attributes; namespace NetOffice.MSHTMLApi { <summary> DispatchInterface IHTMLRectCollection SupportByVersion MSHTML, 4 </summary> [SupportByVersion("MSHTML", 4)] [EntityType(EntityType.IsDispatchInterface)] public class IHTMLRectCollection : COMObject { #pragma warning disable #region Type Information <summary> Instance Type </summary> [EditorBrowsable(<API key>.Advanced), Browsable(false), Category("NetOffice"), CoreOverridden] public override Type InstanceType { get { return <API key>; } } private static Type _type; [EditorBrowsable(<API key>.Never), Browsable(false)] public static Type <API key> { get { if (null == _type) _type = typeof(IHTMLRectCollection); return _type; } } #endregion #region Ctor <param name="factory">current used factory core</param> <param name="parentObject">object there has created the proxy</param> <param name="proxyShare">proxy share instead if com proxy</param> public IHTMLRectCollection(Core factory, ICOMObject parentObject, COMProxyShare proxyShare) : base(factory, parentObject, proxyShare) { } <param name="factory">current used factory core</param> <param name="parentObject">object there has created the proxy</param> <param name="comProxy">inner wrapped COM proxy</param> public IHTMLRectCollection(Core factory, ICOMObject parentObject, object comProxy) : base(factory, parentObject, comProxy) { } <param name="parentObject">object there has created the proxy</param> <param name="comProxy">inner wrapped COM proxy</param> [EditorBrowsable(<API key>.Never), Browsable(false)] public IHTMLRectCollection(ICOMObject parentObject, object comProxy) : base(parentObject, comProxy) { } <param name="factory">current used factory core</param> <param name="parentObject">object there has created the proxy</param> <param name="comProxy">inner wrapped COM proxy</param> <param name="comProxyType">Type of inner wrapped COM proxy"</param> [EditorBrowsable(<API key>.Never), Browsable(false)] public IHTMLRectCollection(Core factory, ICOMObject parentObject, object comProxy, NetRuntimeSystem.Type comProxyType) : base(factory, parentObject, comProxy, comProxyType) { } <param name="parentObject">object there has created the proxy</param> <param name="comProxy">inner wrapped COM proxy</param> <param name="comProxyType">Type of inner wrapped COM proxy"</param> [EditorBrowsable(<API key>.Never), Browsable(false)] public IHTMLRectCollection(ICOMObject parentObject, object comProxy, NetRuntimeSystem.Type comProxyType) : base(parentObject, comProxy, comProxyType) { } <param name="replacedObject">object to replaced. replacedObject are not usable after this action</param> [EditorBrowsable(<API key>.Never), Browsable(false)] public IHTMLRectCollection(ICOMObject replacedObject) : base(replacedObject) { } [EditorBrowsable(<API key>.Never), Browsable(false)] public IHTMLRectCollection() : base() { } <param name="progId">registered progID</param> [EditorBrowsable(<API key>.Never), Browsable(false)] public IHTMLRectCollection(string progId) : base(progId) { } #endregion #region Properties <summary> SupportByVersion MSHTML 4 Get </summary> [SupportByVersion("MSHTML", 4)] public Int32 length { get { return Factory.<API key>(this, "length"); } } <summary> SupportByVersion MSHTML 4 Get Unknown COM Proxy </summary> [SupportByVersion("MSHTML", 4), ProxyResult] [EditorBrowsable(<API key>.Never), Browsable(false)] public object _newEnum { get { return Factory.<API key>(this, "_newEnum"); } } #endregion #region Methods <summary> SupportByVersion MSHTML 4 </summary> <param name="pvarIndex">object pvarIndex</param> [SupportByVersion("MSHTML", 4)] public object item(object pvarIndex) { return Factory.<API key>(this, "item", pvarIndex); } #endregion #pragma warning restore } }
/* TEMPLATE GENERATED TESTCASE FILE Filename: <API key>.cpp Label Definition File: <API key>.strings.label.xml Template File: sources-sink-84_bad.tmpl.cpp */ /* * @description * CWE: 78 OS Command Injection * BadSource: file Read input from a file * GoodSource: Fixed string * Sinks: execlp * BadSink : execute command with wexeclp * Flow Variant: 84 Data flow: data passed to class constructor and destructor by declaring the class object on the heap and deleting it after use * * */ #ifndef OMITBAD #include "std_testcase.h" #include "<API key>.h" #ifdef _WIN32 #define FILENAME "C:\\temp\\file.txt" #else #define FILENAME "/tmp/file.txt" #endif #ifdef _WIN32 #include <process.h> #define EXECLP _wexeclp #else /* NOT _WIN32 */ #define EXECLP execlp #endif namespace <API key> { <API key>::<API key>(wchar_t * dataCopy) { data = dataCopy; { /* Read input from a file */ size_t dataLen = wcslen(data); FILE * pFile; /* if there is room in data, attempt to read the input from a file */ if (100-dataLen > 1) { pFile = fopen(FILENAME, "r"); if (pFile != NULL) { /* POTENTIAL FLAW: Read data from a file */ if (fgetws(data+dataLen, (int)(100-dataLen), pFile) == NULL) { printLine("fgetws() failed"); /* Restore NUL terminator if fgetws fails */ data[dataLen] = L'\0'; } fclose(pFile); } } } } <API key>::~<API key>() { /* wexeclp - searches for the location of the command among * the directories specified by the PATH environment variable */ /* POTENTIAL FLAW: Execute command without validating input possibly leading to command injection */ EXECLP(COMMAND_INT, COMMAND_INT, COMMAND_ARG1, COMMAND_ARG2, COMMAND_ARG3, NULL); } } #endif /* OMITBAD */
package main import ( "encoding/json" "io/ioutil" ) type configRepo struct { Url string `json:"url"` Directory string `json:"directory"` Hidden bool `json:"hidden"` Type string `json:"type"` Command CommandInfo `json:"command"` } type Config struct { Repos map[string]Repo } func ParseConfig(file string) (*Config, error) { data, err := ioutil.ReadFile(file) if err != nil { return nil, err } config := Config{Repos: make(map[string]Repo)} // Temporary variable so we can unmarshal correctly. var c struct { Repos []configRepo `json:"repos"` } if err = json.Unmarshal(data, &c); err != nil { return nil, err } for _, repo := range c.Repos { // TODO: switch repo.Type -> not just Git support. r := Git{ Url: repo.Url, directory: repo.Directory, Hidden: repo.Hidden, Command: repo.Command, } owner, name := r.Name() config.Repos[owner+"/"+name] = r } return &config, nil }
# Change Log All notable changes to this project will be documented in this file. This project adheres to [Semantic Versioning](http://semver.org/). ## 0.3.0 (2016-02-25) Added - Prompt user for the grunt command ## 0.2.0 (2016-02-23) Added - Run grunt command after scaffolding and installing dependencies ## 0.1.3 (2016-02-23) Added - CHANGELOG.md Enhancements Implemented - Clean up _package.json - Update README.md ## 0.1.2 (2015-09-23) Enhancements - Use process.env.PORT for Express server if set ## 0.1.1 (2015-09-22) Merged pull requests - Fix for package.json [\ ## 0.1.0 (2015-04-06) Added - Initial Release
import angular from '<API key>'; import commonjs from '<API key>'; import nodeResolve from '<API key>'; import typescript from '<API key>'; import uglify from '<API key>'; import { minify } from 'uglify-es'; // <API key> addons import sass from 'node-sass'; import CleanCSS from 'clean-css'; import { minify as minifyHtml } from 'html-minifier'; const cssmin = new CleanCSS(); const htmlminOpts = { caseSensitive: true, collapseWhitespace: true, removeComments: true, }; export default { input: 'dist/index.js', output: { // core output options file: 'dist/bundle.umd.js', // required format: 'umd', // required name: 'ngx-markdown.core', // advanced output options // paths: , // banner: , // footer: , // intro:, // outro: , sourcemap: true, // true | inline // sourcemapFile: , // interop: , // danger zone exports: 'named', // amd: , // indent: , // strict: }, onwarn, plugins: [ angular({ preprocessors: { template: template => minifyHtml(template, htmlminOpts), style: scss => { const css = sass.renderSync({ data: scss }).css; return cssmin.minify(css).styles; }, } }), commonjs(), nodeResolve({ // use "module" field for ES6 module if possible module: true, // Default: true // use "jsnext:main" if possible jsnext: true, // Default: false // use "main" field or index.js, even if it's not an ES6 module // (needs to be converted from CommonJS to ES6 main: true, // Default: true // some package.json files have a `browser` field which // specifies alternative files to load for people bundling // for the browser. If that's you, use this option, otherwise // pkg.browser will be ignored browser: true, // Default: false // not all files you want to resolve are .js files extensions: [ '.js', '.json' ], // Default: ['.js'] // whether to prefer built-in modules (e.g. `fs`, `path`) or // local ones with the same names preferBuiltins: true, // Default: true // Lock the module search in this path (like a chroot). Module defined // outside this path will be mark has external jail: '/', // Default: '/' // If true, inspect resolved files to check that they are // ES2015 modules modulesOnly: false, // Default: false // Any additional options that should be passed through // to node-resolve <API key>: {} }), typescript({ typescript: require('./node_modules/typescript') }), uglify({}, minify) ] }; function onwarn(message) { const suppressed = [ 'UNRESOLVED_IMPORT', 'THIS_IS_UNDEFINED' ]; if (!suppressed.find(code => message.code === code)) { return console.warn(message.message); } }
using System; public class Test { static readonly int a = 5; static readonly int b = 6; public static int Main (string[] args) { int repeat = 1; if (args.Length == 1) repeat = Convert.ToInt32 (args [0]); Console.WriteLine ("Repeat = " + repeat); for (int i = 0; i < repeat*3; i++) { for (int j = 0; j < 100000000; j++) { if ((a != 5) || (b != 6)) return 1; } } return 0; } }
'use strict'; angular.module('myApp.CleanCut', ['ngRoute']) .config(['$routeProvider', function ($routeProvider) { $routeProvider.when('/', { templateUrl: 'views/split-costs/main.html', controller: 'CleanCutCtrl' }); }]) .controller('CleanCutCtrl', ['$scope', function ($scope) { var init = function () { $scope.expenses = []; $scope.contributors = []; $scope.recalculateDebts(); }; var addContributor = function (name) { $scope.contributors.push({ name: name, totalExpense: 0 }); }; var clearAddexpenseForm = function () { $scope.newExpName = ""; $scope.newexpenseAmount = ""; }; $scope.tempContr; $scope.addCtor = function () { addContributor($scope.newCtorName, 0); $scope.newCtorName = ""; }; $scope.addExpense = function () { var valid = true; if ($scope.tempShares.length === 0) { valid = false; } if (valid) { $scope.expenses.push({ ownerName: $scope.newOwnContrib.name, expName: $scope.newExpName, expAmount: $scope.newExpenseAmount, share: $scope.tempShares.slice(0) }); clearAddexpenseForm(); $scope.recalculateDebts(); } }; $scope.tempShares = []; var assignExpenses = function (name, allExpenses) { var associateExpenses = []; for (var i = 0; i < allExpenses.length; i++) { if (allExpenses[i].ownerName === name) { associateExpenses.push(JSON.parse(JSON.stringify(allExpenses[i]))); } else { if (allExpenses[i].share.indexOf(name) !== -1) { associateExpenses.push(JSON.parse(JSON.stringify(allExpenses[i]))); } } } return associateExpenses; } $scope.recalculateDebts = function () { if ($scope.contributors.length > 1 && $scope.expenses.length > 0) { //add my expenses for (var i = 0; i < $scope.contributors.length; i++) { $scope.contributors[i].totalExpense = 0; $scope.contributors[i].myShare = 0; //take associate expenses $scope.contributors[i].expenses = assignExpenses($scope.contributors[i].name, $scope.expenses); for (var j = 0; j < $scope.contributors[i].expenses.length; j++) { $scope.contributors[i].expenses[j].relations = []; if ($scope.contributors[i].expenses[j].ownerName === $scope.contributors[i].name) { $scope.contributors[i].totalExpense += $scope.contributors[i].expenses[j].expAmount; $scope.contributors[i].myShare += $scope.contributors[i].expenses[j].expAmount / $scope.contributors[i].expenses[j].share.length; for (var k = 0; k < $scope.contributors[i].expenses[j].share.length; k++) { if ($scope.contributors[i].expenses[j].share[k] !== $scope.contributors[i].name) { $scope.contributors[i].expenses[j].relations.push({ person: $scope.contributors[i].expenses[j].share[k], amount: $scope.contributors[i].expenses[j].expAmount / $scope.contributors[i].expenses[j].share.length }); } } } else { for (var k = 0; k < $scope.contributors[i].expenses[j].share.length; k++) { if ($scope.contributors[i].expenses[j].share[k] === $scope.contributors[i].name) { $scope.contributors[i].expenses[j].relations.push({ person: $scope.contributors[i].expenses[j].ownerName, amount: ($scope.contributors[i].expenses[j].expAmount / $scope.contributors[i].expenses[j].share.length) * (-1) }); } } } } } //sum up per person for (var i = 0; i < $scope.contributors.length; i++) { $scope.contributors[i].sum = [] for (var j = 0; j < $scope.contributors[i].expenses.length; j++) { for (var k = 0; k < $scope.contributors[i].expenses[j].relations.length; k++) { if ($scope.contributors[i].sum.length === 0) { $scope.contributors[i].sum.push({ person: $scope.contributors[i].expenses[j].relations[k].person, amount: $scope.contributors[i].expenses[j].relations[k].amount }) } else { var found = false; for (var s = 0; s < $scope.contributors[i].sum.length; s++) { if ($scope.contributors[i].sum[s].person === $scope.contributors[i].expenses[j].relations[k].person) { $scope.contributors[i].sum[s].amount += $scope.contributors[i].expenses[j].relations[k].amount; found = true; break; } } if (!found) { $scope.contributors[i].sum.push({ person: $scope.contributors[i].expenses[j].relations[k].person, amount: $scope.contributors[i].expenses[j].relations[k].amount }) } } } } } } console.log($scope.contributors); } $scope.abs = function (num) { return Math.abs(num); } init(); }]);
<?php namespace ashrafakl\localization; use yii\base\Component; use Yii; /** * Locale class represents the data relevant to a locale such as countries, languages, and orientation, * this class uses and depend on the PHP intl extension. * @author ashrafakl@yahoo.com */ class Locale extends Component { private $locales; private $countries; private $languages; private $rtlLanguages = ['ar', 'dv', 'fa', 'he', 'ks', 'ku', 'ps', 'syr', 'ur']; private static $relativeLanguages = null; public $bundlename = ''; /** * Initializes Local. */ public function init() { if ($this->locales === null) { $this->locales = \ResourceBundle::getLocales($this->bundlename); } if (self::$relativeLanguages === null) { foreach ($this->locales as $locale) { self::$relativeLanguages[\Locale::getPrimaryLanguage($locale)] = \Locale::getDisplayLanguage($locale, $locale); } } parent::init(); } /** * Get Countries list * @param string $inLocale format locale to use to display the regions names, default to current yii language * @return array */ public function getCountries($inLocale = null) { if (!$inLocale) { $inLocale = Yii::$app->language; } $key = strtolower($inLocale); if (!isset($this->countries[$key])) { foreach ($this->locales as $locale) { $countryName = \Locale::getDisplayRegion($locale, $inLocale); if ($countryName) { $territoryId = \Locale::getRegion($locale); if (!is_numeric($territoryId)) { $this->countries[$key][strtolower($territoryId)] = $countryName; } } } } return $this->countries[$key]; } /** * Get contry code for the given [[code]] * @param string $code country code * @param string $inLocale format locale to use to display the regions names, default to current yii language * @return array */ public function getCountry($code, $inLocale = null) { if (!$inLocale) { $inLocale = Yii::$app->language; } $this->getCountries($inLocale); $key = strtolower($inLocale); if (isset($this->countries[$key][$code])) { return $this->countries[$key][$code]; } } /** * Get languages list relative to its locale * @param array $allowLanguages * @return array */ public function <API key>($allowLanguages = []) { if ($allowLanguages) { $relativeLanguages = []; foreach ($allowLanguages as $language) { if (array_key_exists($language, self::$relativeLanguages)) { $relativeLanguages[$language] = self::$relativeLanguages[$language]; } } return $relativeLanguages; } else { return self::$relativeLanguages; } } /** * Get languages list * @param string $inLocale format locale to use to display the languages names, default to current yii language * @return array */ public function getPrimaryLanguages($inLocale = null) { if (!$inLocale) { $inLocale = Yii::$app->language; } $key = strtolower($inLocale); if (!isset($this->languages[$key])) { foreach ($this->locales as $locale) { $this->languages[$key][\Locale::getPrimaryLanguage($locale)] = \Locale::getDisplayLanguage($locale, $inLocale); } } return $this->languages[$key]; } /** * Get characters orientation, which is either 'ltr' (left-to-right) or 'rtl' (right-to-left) * @param string $inLocale format locale to use to gets the orientation, default to current yii language * @return string */ public function getOrientation($inLocale = null) { if (!$inLocale) { $inLocale = Yii::$app->language; } return in_array(\Locale::getPrimaryLanguage($inLocale), $this->rtlLanguages) ? 'rtl' : 'ltr'; } }
Pattern: Use of insecure TLS policy for Google Compute Issue: - ## Description TLS versions prior to 1.2 are outdated and insecure. You should use 1.2 as minimum version. **Resolution**: Enforce a minimum TLS version of 1.2. ## Examples Example of **incorrect** code: terraform resource "<API key>" "bad_example" { name = "<API key>" profile = "MODERN" min_tls_version = "TLS_1_1" } Example of **correct** code: terraform resource "<API key>" "good_example" { name = "<API key>" profile = "MODERN" min_tls_version = "TLS_1_2" }
module.exports = {"PortLligatSans":{"normal":"<API key>.ttf","bold":"<API key>.ttf","italics":"<API key>.ttf","bolditalics":"<API key>.ttf"}};
using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.UI; using System.Web.UI.WebControls; using PettyCash_C; using System.Data; using System.IO; using System.Net; namespace PettyCashApp.user { public partial class WebForm2 : System.Web.UI.Page { petty_cash_Con bus = new petty_cash_Con(); string ty; int chk = 1; double amt_edit; WebClient client = new WebClient(); protected void Page_Load(object sender, EventArgs e) { if (!IsPostBack) { checklogin(); txtdate.Attributes.Add("readonly", "readonly"); } } protected void checklogin() { if (Session["is_login"] != null) { if (Session["is_login"].ToString() == "t") { ty = Session["ty"].ToString(); if (ty == "Deposit") { iname.Attributes["class"] = "hidden"; price.Attributes["class"] = "hidden"; desc.Attributes["class"] = "hidden"; } else if (ty == "Withdraw") { amnt.Attributes["class"] = "hidden"; } edit_journal(); } else { Response.Redirect("~/unauthorised.aspx"); } } else { Response.Redirect("~/Login.aspx"); } } public void edit_journal() { bus.id = int.Parse(Session["id"].ToString()); string type = Session["ty"].ToString(); DataTable dt = bus.edit_journal(); if (dt.Rows.Count > 0) { txtdate.Text = dt.Rows[0][0].ToString(); txtrcpt.Text = dt.Rows[0][1].ToString(); type_lbl.Text = dt.Rows[0][2].ToString(); if (type_lbl.Text == "Deposit") { txtamount.Text = dt.Rows[0][4].ToString(); } else if (type_lbl.Text == "Withdraw") { item_name1.Text = dt.Rows[0][3].ToString(); qty.Text = dt.Rows[0][6].ToString(); price1.Text = dt.Rows[0][4].ToString(); desc1.Text = dt.Rows[0][5].ToString(); } } vhr_vew(); } protected void <API key>(object sender, EventArgs e) { int res; ty = Session["ty"].ToString(); amt_edit = double.Parse(Session["amt_edit"].ToString()); if (ty == "Deposit") { if (txtdate.Text != "" && txtrcpt.Text != "" && txtamount.Text != "") { if (bill_new.Checked && vhr_new.Checked) { if (bill_upload.HasFile && vhr_upload.HasFile) { string ext_bill = System.IO.Path.GetExtension(bill_upload.FileName); string ext_vhr = System.IO.Path.GetExtension(vhr_upload.FileName); if (ext_bill == ".pdf" && ext_vhr == ".pdf") { if (bill_upload.PostedFile.ContentLength < 3145728 && vhr_upload.PostedFile.ContentLength < 3145728) { FileInfo file_bill = new System.IO.FileInfo(bill_upload.PostedFile.FileName); string fname_bill = file_bill.Name.Remove((file_bill.Name.Length - file_bill.Extension.Length)); fname_bill = fname_bill + "_" + txtrcpt.Text + "_b" + file_bill.Extension; // renaming file uploads string filename_bill = Path.Combine(HttpContext.Current.Server.MapPath("~/Uploads/Bill_uploads/"), fname_bill); string filename_vir_bill = Path.Combine("~/Uploads/Bill_uploads/", fname_bill); FileInfo file_vhr = new System.IO.FileInfo(vhr_upload.PostedFile.FileName); string fname_vhr = file_vhr.Name.Remove((file_vhr.Name.Length - file_vhr.Extension.Length)); fname_vhr = fname_vhr + "_" + txtrcpt.Text + "_v" + file_vhr.Extension; // renaming file uploads string filename_vhr = Path.Combine(HttpContext.Current.Server.MapPath("~/Uploads/Voucher_uploads/"), fname_vhr); string filename_vir_vhr = Path.Combine("~/Uploads/Voucher_uploads/", fname_vhr); bus.id = int.Parse(Session["id"].ToString()); bus.type = ty; bus.sdate = DateTime.Parse(txtdate.Text); bus.rno = txtrcpt.Text; bus.item = ""; bus.amt = double.Parse(txtamount.Text); bus.amt_edit = amt_edit; bus.bill_upload = filename_vir_bill; bus.voucher_upload = filename_vir_vhr; bus.description = ""; res = bus.update_addentry(); if (res == 1) // Success { bill_upload.SaveAs(filename_bill); vhr_upload.SaveAs(filename_vhr); } else // Fail { chk = 0; } if (chk == 1) { ScriptManager.<API key>(this, GetType(), "displayalertmessage", "success_update();", true); } else { ScriptManager.<API key>(this, GetType(), "displayalertmessage", "error_update();", true); clearfields(); } } else { //Error... Size should be less than 3mb ScriptManager.<API key>(this, GetType(), "displayalertmessage", "error_size();", true); } } else { //Error... Extension should be PDF ScriptManager.<API key>(this, GetType(), "displayalertmessage", "error_ext();", true); } } else { //Upload Files Error vhr_new.Checked = false; bill_new.Checked = false; ScriptManager.<API key>(this, GetType(), "displayalertmessage", "error_nofile();", true); } } else if (bill_new.Checked) { if (bill_upload.HasFile) { string ext_bill = System.IO.Path.GetExtension(bill_upload.FileName); if (ext_bill == ".pdf") { if (bill_upload.PostedFile.ContentLength < 3145728) { FileInfo file_bill = new System.IO.FileInfo(bill_upload.PostedFile.FileName); string fname_bill = file_bill.Name.Remove((file_bill.Name.Length - file_bill.Extension.Length)); fname_bill = fname_bill + "_" + txtrcpt.Text + "_b" + file_bill.Extension; // renaming file uploads string filename_bill = Path.Combine(HttpContext.Current.Server.MapPath("~/Uploads/Bill_uploads/"), fname_bill); string filename_vir_bill = Path.Combine("~/Uploads/Bill_uploads/", fname_bill); bus.id = int.Parse(Session["id"].ToString()); bus.type = ty; bus.sdate = DateTime.Parse(txtdate.Text); bus.rno = txtrcpt.Text; bus.item = ""; bus.amt = double.Parse(txtamount.Text); bus.amt_edit = amt_edit; bus.bill_upload = filename_vir_bill; bus.voucher_upload = ""; bus.description = ""; res = bus.update_addentry(); if (res == 1) // Success { bill_upload.SaveAs(filename_bill); } else // Fail { chk = 0; } if (chk == 1) { ScriptManager.<API key>(this, GetType(), "displayalertmessage", "success_update();", true); } else { clearfields(); ScriptManager.<API key>(this, GetType(), "displayalertmessage", "error_update();", true); } } else { //Error... Size should be less than 3mb ScriptManager.<API key>(this, GetType(), "displayalertmessage", "error_size();", true); } } else { //Error... Extension should be PDF ScriptManager.<API key>(this, GetType(), "displayalertmessage", "error_ext();", true); } } else { //No file present vhr_new.Checked = false; bill_new.Checked = false; ScriptManager.<API key>(this, GetType(), "displayalertmessage", "error_nofile();", true); } } else if (vhr_new.Checked) { if (vhr_upload.HasFile) { string ext_vhr = System.IO.Path.GetExtension(vhr_upload.FileName); if (ext_vhr == ".pdf") { if (vhr_upload.PostedFile.ContentLength < 3145728) { FileInfo file_vhr = new System.IO.FileInfo(vhr_upload.PostedFile.FileName); string fname_vhr = file_vhr.Name.Remove((file_vhr.Name.Length - file_vhr.Extension.Length)); fname_vhr = fname_vhr + "_" + txtrcpt.Text + "_v" + file_vhr.Extension; // renaming file uploads string filename_vhr = Path.Combine(HttpContext.Current.Server.MapPath("~/Uploads/Voucher_uploads/"), fname_vhr); string filename_vir_vhr = Path.Combine("~/Uploads/Voucher_uploads/", fname_vhr); bus.id = int.Parse(Session["id"].ToString()); bus.type = ty; bus.sdate = DateTime.Parse(txtdate.Text); bus.rno = txtrcpt.Text; bus.item = ""; bus.amt = double.Parse(txtamount.Text); bus.amt_edit = amt_edit; bus.bill_upload = "";// check here later bus.voucher_upload = filename_vir_vhr; bus.description = ""; res = bus.update_addentry(); if (res == 1) // Success { vhr_upload.SaveAs(filename_vhr); } else // Fail { chk = 0; } if (chk == 1) { ScriptManager.<API key>(this, GetType(), "displayalertmessage", "success_update();", true); } else { clearfields(); ScriptManager.<API key>(this, GetType(), "displayalertmessage", "error_update();", true); } } else { //Error... Size should be less than 3mb ScriptManager.<API key>(this, GetType(), "displayalertmessage", "error_size();", true); } } else { //Error... Extension should be PDF ScriptManager.<API key>(this, GetType(), "displayalertmessage", "error_ext();", true); } } else { //No file present vhr_new.Checked = false; bill_new.Checked = false; ScriptManager.<API key>(this, GetType(), "displayalertmessage", "error_nofile();", true); } } else { //No bill and Voucher.. bus.id = int.Parse(Session["id"].ToString()); bus.type = ty; bus.sdate = DateTime.Parse(txtdate.Text); bus.rno = txtrcpt.Text; bus.item = ""; bus.amt = double.Parse(txtamount.Text); bus.amt_edit = amt_edit; bus.bill_upload = ""; bus.voucher_upload = ""; bus.description = ""; res = bus.update_addentry(); if (res == 1) // Success { ScriptManager.<API key>(this, GetType(), "displayalertmessage", "success_update();", true); } else // Fail { clearfields(); ScriptManager.<API key>(this, GetType(), "displayalertmessage", "error_update();", true); } } } else { Response.Redirect("~/unauthorised.aspx"); } } else if (ty == "Withdraw") { if (txtdate.Text != "" && txtrcpt.Text != "" && item_name1.Text != "" && price1.Text != "" && qty.Text != "") { if (bill_new.Checked && vhr_new.Checked) { if (bill_upload.HasFile && vhr_upload.HasFile) { string ext_bill = System.IO.Path.GetExtension(bill_upload.FileName); string ext_vhr = System.IO.Path.GetExtension(vhr_upload.FileName); if (ext_bill == ".pdf" && ext_vhr == ".pdf") { if (bill_upload.PostedFile.ContentLength < 3145728 && vhr_upload.PostedFile.ContentLength < 3145728) { FileInfo file_bill = new System.IO.FileInfo(bill_upload.PostedFile.FileName); string fname_bill = file_bill.Name.Remove((file_bill.Name.Length - file_bill.Extension.Length)); fname_bill = fname_bill + "_" + txtrcpt.Text + "_b" + file_bill.Extension; // renaming file uploads string filename_bill = Path.Combine(HttpContext.Current.Server.MapPath("~/Uploads/Bill_uploads/"), fname_bill); string filename_vir_bill = Path.Combine("~/Uploads/Bill_uploads/", fname_bill); FileInfo file_vhr = new System.IO.FileInfo(vhr_upload.PostedFile.FileName); string fname_vhr = file_vhr.Name.Remove((file_vhr.Name.Length - file_vhr.Extension.Length)); fname_vhr = fname_vhr + "_" + txtrcpt.Text + "_v" + file_vhr.Extension; // renaming file uploads string filename_vhr = Path.Combine(HttpContext.Current.Server.MapPath("~/Uploads/Voucher_uploads/"), fname_vhr); string filename_vir_vhr = Path.Combine("~/Uploads/Voucher_uploads/", fname_vhr); bus.id = int.Parse(Session["id"].ToString()); bus.type = ty; bus.sdate = DateTime.Parse(txtdate.Text); bus.rno = txtrcpt.Text; bus.item = item_name1.Text; bus.qty = int.Parse(qty.Text); bus.amt = double.Parse(price1.Text); bus.amt_edit = amt_edit; bus.bill_upload = filename_vir_bill; bus.voucher_upload = filename_vir_vhr; bus.description = desc1.Text; res = bus.update_addentry(); if (res == 1) // Success { bill_upload.SaveAs(filename_bill); vhr_upload.SaveAs(filename_vhr); } else // Fail { chk = 0; } if (chk == 1) { ScriptManager.<API key>(this, GetType(), "displayalertmessage", "success_update();", true); } else { clearfields(); ScriptManager.<API key>(this, GetType(), "displayalertmessage", "error_update();", true); } } else { //Error... Size should be less than 3mb ScriptManager.<API key>(this, GetType(), "displayalertmessage", "error_size();", true); } } else { //Error... Extension should be PDF ScriptManager.<API key>(this, GetType(), "displayalertmessage", "error_ext();", true); } } else { //Upload Files Error vhr_new.Checked = false; bill_new.Checked = false; ScriptManager.<API key>(this, GetType(), "displayalertmessage", "error_nofile();", true); } } else if (bill_new.Checked) { if (bill_upload.HasFile) { string ext_bill = System.IO.Path.GetExtension(bill_upload.FileName); if (ext_bill == ".pdf") { if (bill_upload.PostedFile.ContentLength < 3145728) { FileInfo file_bill = new System.IO.FileInfo(bill_upload.PostedFile.FileName); string fname_bill = file_bill.Name.Remove((file_bill.Name.Length - file_bill.Extension.Length)); fname_bill = fname_bill + "_" + txtrcpt.Text + "_b" + file_bill.Extension; // renaming file uploads string filename_bill = Path.Combine(HttpContext.Current.Server.MapPath("~/Uploads/Bill_uploads/"), fname_bill); string filename_vir_bill = Path.Combine("~/Uploads/Bill_uploads/", fname_bill); bus.id = int.Parse(Session["id"].ToString()); bus.type = ty; bus.sdate = DateTime.Parse(txtdate.Text); bus.rno = txtrcpt.Text; bus.item = item_name1.Text; bus.qty = int.Parse(qty.Text); bus.amt = double.Parse(price1.Text); bus.amt_edit = amt_edit; bus.bill_upload = filename_vir_bill; bus.voucher_upload = ""; bus.description = desc1.Text; res = bus.update_addentry(); if (res == 1) // Success { bill_upload.SaveAs(filename_bill); } else // Fail { chk = 0; } if (chk == 1) { ScriptManager.<API key>(this, GetType(), "displayalertmessage", "success_update();", true); } else { clearfields(); ScriptManager.<API key>(this, GetType(), "displayalertmessage", "error_update();", true); } } else { //Error... Size should be less than 3mb ScriptManager.<API key>(this, GetType(), "displayalertmessage", "error_size();", true); } } else { //Error... Extension should be PDF ScriptManager.<API key>(this, GetType(), "displayalertmessage", "error_ext();", true); } } else { //No file present vhr_new.Checked = false; bill_new.Checked = false; ScriptManager.<API key>(this, GetType(), "displayalertmessage", "error_nofile();", true); } } else if (vhr_new.Checked) { if (vhr_upload.HasFile) { string ext_vhr = System.IO.Path.GetExtension(vhr_upload.FileName); if (ext_vhr == ".pdf") { if (vhr_upload.PostedFile.ContentLength < 3145728) { FileInfo file_vhr = new System.IO.FileInfo(vhr_upload.PostedFile.FileName); string fname_vhr = file_vhr.Name.Remove((file_vhr.Name.Length - file_vhr.Extension.Length)); fname_vhr = fname_vhr + "_" + txtrcpt.Text + "_v" + file_vhr.Extension; // renaming file uploads string filename_vhr = Path.Combine(HttpContext.Current.Server.MapPath("~/Uploads/Voucher_uploads/"), fname_vhr); string filename_vir_vhr = Path.Combine("~/Uploads/Voucher_uploads/", fname_vhr); bus.id = int.Parse(Session["id"].ToString()); bus.type = ty; bus.sdate = DateTime.Parse(txtdate.Text); bus.rno = txtrcpt.Text; bus.item = item_name1.Text; bus.qty = int.Parse(qty.Text); bus.amt = double.Parse(price1.Text); bus.amt_edit = amt_edit; bus.bill_upload = ""; bus.voucher_upload = filename_vir_vhr; bus.description = desc1.Text; res = bus.update_addentry(); if (res == 1) // Success { vhr_upload.SaveAs(filename_vhr); } else // Fail { chk = 0; } if (chk == 1) { ScriptManager.<API key>(this, GetType(), "displayalertmessage", "success_update();", true); } else { clearfields(); ScriptManager.<API key>(this, GetType(), "displayalertmessage", "error_update();", true); } } else { //Error... Size should be less than 3mb ScriptManager.<API key>(this, GetType(), "displayalertmessage", "error_size();", true); } } else { //Error... Extension should be PDF ScriptManager.<API key>(this, GetType(), "displayalertmessage", "error_ext();", true); } } else { //No file present vhr_new.Checked = false; bill_new.Checked = false; ScriptManager.<API key>(this, GetType(), "displayalertmessage", "error_nofile();", true); } } else { //No bill and Voucher.. bus.id = int.Parse(Session["id"].ToString()); bus.type = ty; bus.sdate = DateTime.Parse(txtdate.Text); bus.rno = txtrcpt.Text; bus.item = item_name1.Text; bus.qty = int.Parse(qty.Text); bus.amt = double.Parse(price1.Text); bus.amt_edit = amt_edit; bus.bill_upload = ""; bus.voucher_upload = ""; bus.description = desc1.Text; res = bus.update_addentry(); if(res == 1) { ScriptManager.<API key>(this, GetType(), "displayalertmessage", "success_update();", true); bill_new.Checked = false; vhr_new.Checked = false; } else { ScriptManager.<API key>(this, GetType(), "displayalertmessage", "error_update();", true); } } } } } public void clearfields() { txtdate.Text = ""; txtrcpt.Text = ""; txtamount.Text = ""; item_name1.Text = ""; price1.Text = ""; desc1.Text = ""; bill_new.Checked = false; vhr_new.Checked = false; } protected void bill_upld_Click(object sender, EventArgs e) { LinkButton lnk = sender as LinkButton; GridViewRow row = lnk.NamingContainer as GridViewRow; bus.id = int.Parse(Session["id"].ToString()); DataTable dt = bus.bill_path(); string bill_half = dt.Rows[0][0].ToString(); string bill_path = Server.MapPath(bill_half); Byte[] buffer = client.DownloadData(bill_path); if (buffer != null) { Response.ContentType = "application/pdf"; Response.AddHeader("content-length", buffer.Length.ToString()); Response.BinaryWrite(buffer); } } public void vhr_vew() { string vhr_name = Session["vhr_name"].ToString(); if(vhr_name == "No") { vhr_upld.Visible = false; } else { vhr_upld.Visible = true; } } protected void vhr_upld_Click(object sender, EventArgs e) { string vhr_name = Session["vhr_name"].ToString(); LinkButton lnk = sender as LinkButton; GridViewRow row = lnk.NamingContainer as GridViewRow; bus.id = int.Parse(Session["id"].ToString()); DataTable dt = bus.vhr_path(); string vhr_half = dt.Rows[0][0].ToString(); string vhr_path = Server.MapPath(vhr_half); Byte[] buffer = client.DownloadData(vhr_path); if (buffer != null) { Response.ContentType = "application/pdf"; Response.AddHeader("content-length", buffer.Length.ToString()); Response.BinaryWrite(buffer); } } } }
describe("GUI base class", function() { var SubClass; beforeEach(function() { SubClass = GUI.extend(Function.empty); }); describe("Method render", function() { var spy1 = new Spy(); SubClass.prototype.render_ = spy1.spy; it("should call subclass render_ method", function() { var sub = new SubClass(); sub.render(); expect(spy1.callCount).toBe(1); }); it("should change isRendered property to true", function() { var sub = new SubClass(); expect(sub.isRendered()).toBe(false); sub.render(); expect(sub.isRendered()).toBe(true); }); }); describe("Method destroy", function() { var spy1 = new Spy(); SubClass.prototype.destroy_ = spy1.spy; it("should call subclass destroy_ method", function() { var sub = new SubClass(); sub.destroy(); expect(spy1.callCount).toBe(1); }); }); }, true);
var path_1 = require('path'); var workflow_config_1 = require('../workflow.config'); module.exports = function tslint(gulp, plugins) { return function () { return gulp.src([ path_1.join(workflow_config_1.PATH.src.all, '**/*.ts'), path_1.join(workflow_config_1.PATH.src.all, '../gulpfile.ts'), path_1.join(workflow_config_1.PATH.src.all, '../tools*.ts'), '!' + path_1.join(workflow_config_1.PATH.src.all, '**/*.d.ts'), '!' + path_1.join(workflow_config_1.PATH.src.all, '../tools*.d.ts') ]) .pipe(plugins.tslint()) .pipe(plugins.tslint.report(plugins.tslintStylish, { emitError: false, sort: true, bell: true })); }; }; //# sourceMappingURL=tslint.js.map
<HTML><HEAD> <TITLE>Review for Silence of the Lambs, The (1991)</TITLE> <LINK REL="STYLESHEET" TYPE="text/css" HREF="/ramr.css"> </HEAD> <BODY BGCOLOR="#FFFFFF" TEXT="#000000"> <H1 ALIGN="CENTER" CLASS="title"><A HREF="/Title?0102926">Silence of the Lambs, The (1991)</A></H1><H3 ALIGN=CENTER>reviewed by<BR><A HREF="/ReviewsBy?Mark+R.+Leeper">Mark R. Leeper</A></H3><HR WIDTH="40%" SIZE="4"> <PRE> THE SILENCE OF THE LAMBS A film review by Mark R. Leeper Copyright 1991 Mark R. Leeper</PRE> <PRE> Capsule review: A dark and fascinating thriller that is a genuine departure in the depiction of the psychopathic killer on the screen. Hannibal Lecter is a screen villain as memorable as Norman Bates. Rating: high +2 (-4 to +4).</PRE> <P> Since 1959 the psychopathic killer has, perhaps unfortunately, become a staple of popular film. Most films that had psychopaths before that point really blurred the distinction between your garden variety murderer and the actual psychopath. Perhaps one notable exception was THE BAD SEED, which suggested that there could be something like a "congenital evil." Extreme criminality and madness were very much equated. That was very much what was meant with "mad scientists" of the old horror films. There was an urge to deny the existence of evil or to relegate it to the supernatural. How many people even today deny the culpability of Adolf Hitler and say instead that he was simply mad. There were some films that suggested that there was something more to criminal insanity than just extreme criminality, but it was Alfred Hitchcock's PSYCHO that turned the cinematic view around. Norman Bates was himself a victim as well as the perpetrator of his acts. Bates was a normal person twisted by his past and driven by forces he could not control. This is a marvelously egalitarian view of the criminally insane. It assumes that all men (and women) are created equal. This is probably an equally invalid view of the criminally insane. When John Hurt played Caligula in I, CLAUDIUS, he described his character as "congenitally bonkers." In all probability that was fairly accurate. It is at least my belief that Caligula was genuinely insane and Hitler was not. This view of the pitiful victim-psychopath became the dominant view in films with PSYCHO and it has remained dominant. With John Carpenter's HALLOWEEN (1978) there was a new view, or perhaps an old view harkening back to medieval beliefs, that the psychopathic killer is a supernatural force. Fortunately, few films have picked up on this idea and most that have have large Roman numerals in their titles.</P> <P> Thomas Harris has a different concept of the psychopathic killer which, if no more credible than the supernatural force, s at least more intriguing. He created the idea in his novel RED DRAGON, which Michael Mann adapted into his 1986 film MANHUNTER. The idea was expanded in his SILENCE OF THE LAMBS, which has been adapted into a film by Jonathan Demme. Harris's concept is that psychopaths have a distinctly different form of intelligence. Their reasoning power is consistent and logical, but alien to our own. If you cannot bridge the gap and think like a psychopath, you are at a distinct disadvantage in dealing with them. In addition, the psychopath often has superhuman sensory powers. For example, Harris's Hannibal Lecter, in addition to a super-intellect, apparently has a heightened sense of smell. I believe these are ideas that owe their origin more to Poe's "Tell-Tale Heart" than to actual case histories. But where Harris is really superb is in being able to make Lecter's reasoning really seem brilliant. It is extremely difficult to write a character who is supposed to be brilliant. To see how poorly it can be done, try going back and listening to Lex Luthor's reasoning about Kryptonite in SUPERMAN (1978). Lecter's reasoning is at once perverted and brilliant.</P> <P> MANHUNTER and THE SILENCE OF THE LAMBS are two of what have to be at least four stories involving Hannibal Lecter. And they are probably the two least interesting. When RED DRAGON begins, Lecter has already been captured by Will Graham, who made himself into a psychopath in order to catch Lecter in the first place. Graham needs Lecter's help to capture another psychopath. In THE SILENCE OF THE LAMBS, fledging FBI agent Clarice Starling (no pun intended) (played by Jodie Foster) similarly must enlist Lecter's (Anthony Hopkins's) help to find a killer. This time, however, Lecter thinks he can work his own deal. While this story does conclude, there is still a major loose end that really demands yet another story.</P> <P> In this story the primary villain is a killer whom the press has dubbed Buffalo Bill. The killer not only murders his victims, he later skins them. Starling is chosen to talk to Dr.~Lecter about the crimes with an eye toward getting his unique insight into how to capture Buffalo Bill. Starling, however, has her own personal demons inside and Lecter is just the person to turn those demons against her. In the book the main story is how Starling catches the killer, with the Lecter story being a major subplot. The film reverses the importance of the two plots by leaving the Lecter plot intact, if not actually expanded, and cutting drastically the Buffalo Bill plot.</P> <P> The character of Lecter seems calculated to play off every anti- intellectual prejudice in the audience. The man is an ice-cold, emotionless intellect. He listens to ice-cold, emotionless music. Even when he kills we are told that he is ice-cold and emotionless. In one chilling detail the character is defined. We are told that he attacked and partially ate a victim without his pulse ever going over 80.</P> <P> Stylistically the film is well handled generally. At times the music is a bit overly dramatic in underscoring the mood as if Howard Shore, the composer, did not trust Hopkins's acting to convey a mood of menace. If that was the case, the composer was misguided, since Harris's villain will probably be as memorable as Norman Bates and Michael Meyers. The photography uses a filter to subdue the colors. If that was not downbeat enough, Starling is really the only sympathetic character in the whole story. She seems to go from one man to the next who tries to bed her.</P> <P> For the sake of completeness at least two nits should be mentioned. Starling is first seen climbing a steep hill in the rigorous FBI training school. When we see her in close-up, she is wearing earrings. For her own safety, at least, you would think they would insist on no jewelry. Also, certain scenes are supposedly seen through an infra-red snooperscope and at least one time the subject is in total darkness. As seen through the scope, even items that do not emit heat are easily seen. In the total darkness scene the subject can not only be seen, but also to be seen is the subject's sharp shadow on the wall.</P> <P> THE SILENCE OF THE LAMBS is as unpleasant and hypnotic as watching a cobra. This is one heavy thriller. I give it a high +2 on the -4 to +4 scale.</P> <PRE> Mark R. Leeper att!mtgzy!leeper <A HREF="mailto:leeper@mtgzy.att.com">leeper@mtgzy.att.com</A> . </PRE> <HR><P CLASS=flush><SMALL>The review above was posted to the <A HREF="news:rec.arts.movies.reviews">rec.arts.movies.reviews</A> newsgroup (<A HREF="news:de.rec.film.kritiken">de.rec.film.kritiken</A> for German reviews).<BR> The Internet Movie Database accepts no responsibility for the contents of the review and has no editorial control. Unless stated otherwise, the copyright belongs to the author.<BR> Please direct comments/criticisms of the review to relevant newsgroups.<BR> Broken URLs inthe reviews are the responsibility of the author.<BR> The formatting of the review is likely to differ from the original due to ASCII to HTML conversion. </SMALL></P> <P ALIGN=CENTER>Related links: <A HREF="/Reviews/">index of all rec.arts.movies.reviews reviews</A></P> </P></BODY></HTML>
<!DOCTYPE HTML PUBLIC "- <!-- NewPage --> <html lang="en"> <head> <!-- Generated by javadoc (1.8.0_31) on Tue Mar 24 15:37:01 MDT 2015 --> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <title>Uses of Interface IRedisSortedSet (redis-java 0.0.4 Test API)</title> <meta name="date" content="2015-03-24"> <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="Uses of Interface IRedisSortedSet (redis-java 0.0.4 Test 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="../package-summary.html">Package</a></li> <li><a href="../IRedisSortedSet.html" title="interface in &lt;Unnamed&gt;">Class</a></li> <li class="navBarCell1Rev">Use</li> <li><a href="../overview-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>Prev</li> <li>Next</li> </ul> <ul class="navList"> <li><a href="../index.html?class-use/IRedisSortedSet.html" target="_top">Frames</a></li> <li><a href="IRedisSortedSet.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"> <h2 title="Uses of Interface IRedisSortedSet" class="title">Uses of Interface<br>IRedisSortedSet</h2> </div> <div class="classUseContainer">No usage of IRedisSortedSet</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="../package-summary.html">Package</a></li> <li><a href="../IRedisSortedSet.html" title="interface in &lt;Unnamed&gt;">Class</a></li> <li class="navBarCell1Rev">Use</li> <li><a href="../overview-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>Prev</li> <li>Next</li> </ul> <ul class="navList"> <li><a href="../index.html?class-use/IRedisSortedSet.html" target="_top">Frames</a></li> <li><a href="IRedisSortedSet.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> <p class="legalCopy"><small>Copyright & </body> </html>
module Examples.EX3 where import Control.Lens import Control.Lens.Setter import Control.Monad (void) import Control.Monad.Trans.Class (lift) import Data.List (intersperse, isPrefixOf) import Data.Time.LocalTime import Data.Maybe (catMaybes) import Twilio.Key import Twilio.IVR data User = User { lastname :: String, firstname :: String, extension :: Maybe String } deriving (Show) users = [ User "Smith" "Joe" $ Just "7734", User "Doe" "Jane" $ Just "1556", User "Doe" "Linda" Nothing, User "Samson" "Tina" $ Just "3443", User "O'Donald" "Jack" $ Just "5432", User "Sam-son" "Tony" $ Nothing ] -- | match last name by removing non-keypad characters matchingUsers :: [User] -> [Key] -> [User] matchingUsers ux kx = filter (\u -> let lnky = catMaybes $ map letterToKey (lastname u) in isPrefixOf kx lnky) ux describeUser :: User -> TwilioIVRCoroutine () describeUser u = do say (firstname u) say (lastname u) case extension u of (Just x) -> say $ "Phone extension " ++ (intersperse ' ' x) Nothing -> return () search :: Call -> TwilioIVRCoroutine () search _ = do say "Welcome." name <- gather "Please enter the last name of the person you wish to find. You do not have to enter the entire name. Finish with the pound key." ((finishOnKey .~ Just KPound).(timeout .~ 30)) case matchingUsers users name of [] -> say "Sorry, no matching results found." [x] -> describeUser x xs -> do say $ "We found "++(show $ length xs)++" matching users." mapM_ describeUser xs say "Have a nice day."
package com.xplus.commons.pattern.creational.builder; public class Client { public static void main(String[] args) { Builder builder = new ConcreteBuilder(); Director director = new Director(builder); director.construct(); Product product = director.getProduct(); System.out.println("Product:" + product); } }
'use strict'; module.exports = function (grunt) { grunt.initConfig({ jscs: { src: './lib/components*.jsx', options: { config: '.jscsrc', esnext: true, fix: true } }, babel: { components: { options: { presets: ['es2015', 'react'], compact: false }, files: [{ src: ['./dist/components.jsx'], dest: './dist/components.js' }] } }, concat: { components: { src: ['./lib/utils/*.js', './lib/components/**/*.jsx'], dest: './dist/components.jsx' }, distribute: { src: [ './node_modules/moment/moment.js', './node_modules/moment/locale/pt-br.js', './node_modules/classnames/index.js', './node_modules/<API key>/index.js', './dist/components.js', './node_modules/react-datepicker/dist/react-datepicker.js' ], dest: './dist/uimmutable.js' } }, uglify: { distribute: { src: './dist/uimmutable.js', dest: './dist/uimmutable.min.js' } }, watch: { development: { files: ['lib*.*'], tasks: [ 'distribute' ], options: { spawn: false } } } }); grunt.loadNpmTasks('grunt-jscs'); grunt.loadNpmTasks('grunt-babel'); grunt.loadNpmTasks('grunt-contrib-watch'); grunt.loadNpmTasks('<API key>'); grunt.loadNpmTasks('<API key>'); grunt.registerTask('development', [ 'concat:components', 'babel:components', 'concat:distribute' ]); grunt.registerTask('distribute', [ 'concat:components', 'babel:components', 'concat:distribute', 'uglify:distribute' ]); grunt.registerTask('default', [ 'distribute' ]); };
/*Problem 1. School classes We are given a school. In the school there are classes of students. Each class has a set of teachers. Each teacher teaches a set of disciplines. Students have name and unique class number. Classes have unique text identifier. Teachers have name. Disciplines have name, number of lectures and number of exercises. Both teachers and students are people. Students, classes, teachers and disciplines could have optional comments (free text block). Your task is to identify the classes (in terms of OOP) and their attributes and operations, encapsulate their fields, define the class hierarchy and create a class diagram with Visual Studio. */ namespace SchoolClasses { using System; using System.Text; internal class SchoolTest { public static void Main() { School school = LoadSchool(); Console.WriteLine(PrintSchoolInfo(school)); } private static School LoadSchool() { School school = new School("Geo Milev"); Class eightA = new Class("8a"); eightA.Comment = "Will participate in the school project."; Class eightB = new Class("8b"); Student pesho = new Student("Pesho"); pesho.Comment = "Call the parents."; Student ivan = new Student("Ivan"); Discipline math = new Discipline("Math", 8, 8); Discipline physics = new Discipline("Physics", 6, 6); Teacher petrova = new Teacher("Petrova"); Teacher ivanova = new Teacher("Ivanova"); ivanova.Comment = "Agreed to show the kids the NASA shuttle."; petrova.AddDiscipline(math); ivanova.AddDiscipline(physics); eightA.AddStudent(pesho); eightA.AddTeacher(petrova); eightB.AddStudent(ivan); eightB.AddTeacher(ivanova); school.AddClass(eightA); school.AddClass(eightB); return school; } private static string PrintSchoolInfo(School school) { StringBuilder builder = new StringBuilder(school.Name).AppendLine(); foreach (Class @class in school.Classes) { builder.AppendLine(@class.TextID + " // " + @class.Comment); foreach (Teacher teacher in @class.Teachers) { builder.AppendLine(" " + teacher.ToString() + " // " + teacher.Comment); } foreach (Student student in @class.Students) { builder.AppendLine(" " + student.ToString() + " // " + student.Comment); } } return builder.ToString(); } } }
'use strict'; describe('cashewApp.version module', function() { beforeEach(module('cashewApp.version')); describe('version service', function() { it('should return current version', inject(function(version) { expect(version).toEqual('1.1.4'); })); }); });
<?php defined('BASEPATH') OR exit('No direct script access allowed'); class Welcome extends CI_Controller { public function index() { $family = "Bostick"; $this->db->select('family'); $this->db->select('relationship'); $this->db->select('COUNT(relationship) AS Total'); $this->db->where("family", $family); $this->db->group_by('relationship'); $this->db->order_by('Total', 'desc'); $query = $this->db->get('primary'); $data['bosgrand'] = $query->result(); $tmpl = array ( 'table_open' => '<table width="100%"', 'cell_start' => '<td class="center">', 'cell_end' => '</td>', 'cell_alt_start' => '<td class="center">', 'table_close' => '</table>' ); $this->table->set_template($tmpl); $this->table->set_heading('Relatonship', 'Total' ); $data['title'] = "Sass Page 1"; $data['head'] = "Sass Page 1"; $this->load->view("pages/includes/head", $data); $this->load->view('welcome_message', $data); } public function page() { $data['title'] = "Sass Page 2"; $data['head'] = "Sass Page 2"; $this->load->view("pages/includes/head", $data); $this->load->view('pages/page2', $data); } public function page3() { $data['head'] = "Sass Page 3"; $data['title'] = "Sass Page 3"; $this->load->view("pages/includes/head", $data); $this->load->view('pages/page3', $data); } /** * undocumented function * * @return void * @author **/ public function notes () { $data['title'] = "Notes"; $data['head'] = "Notes"; $this->load->view("pages/includes/head", $data); $this->load->view('modules', $data); } public function skel() { $data['title'] = "Notes"; $data['head'] = "Skeleton Flesh"; $this->load->view("pages/includes/head", $data); $this->load->view("skeleton.html", $data); } /* End of file Welcome.php */ /* Location: ./application/controllers/Welcome.php */ }
-- MySQL dump 10.13 Distrib 5.6.24, for osx10.8 (x86_64) -- Host: 127.0.0.1 Database: boughtonimpulse -- Server version 5.5.42 /*!40101 SET @<API key>=@@<API key> */; /*!40101 SET @<API key>=@@<API key> */; /*!40101 SET @<API key>=@@<API key> */; /*!40101 SET NAMES utf8 */; /*!40103 SET @OLD_TIME_ZONE=@@TIME_ZONE */; /*!40103 SET TIME_ZONE='+00:00' */; /*!40014 SET @OLD_UNIQUE_CHECKS=@@UNIQUE_CHECKS, UNIQUE_CHECKS=0 */; /*!40014 SET @<API key>=@@FOREIGN_KEY_CHECKS, FOREIGN_KEY_CHECKS=0 */; /*!40101 SET @OLD_SQL_MODE=@@SQL_MODE, SQL_MODE='<API key>' */; /*!40111 SET @OLD_SQL_NOTES=@@SQL_NOTES, SQL_NOTES=0 */; -- Table structure for table `products` DROP TABLE IF EXISTS `products`; /*!40101 SET @saved_cs_client = @@<API key> */; /*!40101 SET <API key> = utf8 */; CREATE TABLE `products` ( `id` int(11) NOT NULL AUTO_INCREMENT, `name` varchar(255) DEFAULT NULL, `description` varchar(255) DEFAULT NULL, `price` float DEFAULT NULL, `created_at` datetime DEFAULT NULL, `updated_at` datetime DEFAULT NULL, PRIMARY KEY (`id`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8; /*!40101 SET <API key> = @saved_cs_client */; -- Dumping data for table `products` LOCK TABLES `products` WRITE; /*!40000 ALTER TABLE `products` DISABLE KEYS */; /*!40000 ALTER TABLE `products` ENABLE KEYS */; UNLOCK TABLES; /*!40103 SET TIME_ZONE=@OLD_TIME_ZONE */; /*!40101 SET SQL_MODE=@OLD_SQL_MODE */; /*!40014 SET FOREIGN_KEY_CHECKS=@<API key> */; /*!40014 SET UNIQUE_CHECKS=@OLD_UNIQUE_CHECKS */; /*!40101 SET <API key>=@<API key> */; /*!40101 SET <API key>=@<API key> */; /*!40101 SET <API key>=@<API key> */; /*!40111 SET SQL_NOTES=@OLD_SQL_NOTES */; -- Dump completed on 2015-10-29 18:05:30
const setupRoutes = require('../utils/setupRoutes.js'); const graphql = require('../routes/api/graphql/api.graphql.route'); const graphiql = require('../routes/api/graphiql/api.graphiql.route'); module.exports = () => setupRoutes([ graphql, graphiql, ]);
* { margin: 0; padding: 0; outline: none; border: none; } html, body { height: 100%; width: 930px; text-align: center; margin: auto; } .menu { display: inline; margin-left:0; margin-top: 50px; } hr { border: none; background-color: #ababab; color: #ababab; height: 1px; } .lin1 { margin-bottom: 15px; margin-top: 100px; } .lin2 { margin-top: 15px; } ul { display: inline; } li { display: inline; } a { font-family: Arial; font-size: 18px; color: #6b6b6b; text-decoration: none; margin-right: 70px; margin-bottom: 15px; }
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http: <html> <head> <meta HTTP-EQUIV=CONTENT-TYPE CONTENT="text/html; charset=utf-8"> <title>Slide 2</title> </head> <body text="#000080" bgcolor="#F7F9FC" link="#000080" vlink="#0000CC" alink="#000080"> <center> <a href="text0.html">First page</a> <a href="text0.html">Back</a> <a href="text2.html">Continue</a> <a href="text19.html">Last page</a> <a href="dectalk.html">Overview</a> <a href="img1.html">Graphics</a></center><br> <h1 style="direction:ltr;"></h1> <h2 style="direction:ltr;"><font color="#280099">What's A Decorator?</font> <h2 style="direction:ltr;"><font color="#280099"></font> <h2 style="direction:ltr;"><font color="#280099">A design choice to separate two concepts, when one concept modifies when or why the other concept will execute</font> </body> </html>
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package br.uff.ic.oceano.ostra.dao.impl; import br.uff.ic.oceano.core.dao.controle.JPAUtil; import br.uff.ic.oceano.core.dao.controle.anotations.MetodoRecuperaLista; import br.uff.ic.oceano.core.dao.generics.JPADaoGenerico; import br.uff.ic.oceano.core.exception.<API key>; import br.uff.ic.oceano.core.model.Metric; import br.uff.ic.oceano.core.model.Revision; import br.uff.ic.oceano.util.NumberUtil; import br.uff.ic.oceano.ostra.dao.<API key>; import br.uff.ic.oceano.ostra.model.Item; import br.uff.ic.oceano.ostra.model.<API key>; import java.util.List; import javax.persistence.Query; /** * * @author DanCastellani */ public class <API key> extends JPADaoGenerico<<API key>, Long> implements <API key> { public <API key>() { super(<API key>.class); } public long <API key>(Revision revision, Metric metric) { final String strQuery = "select count( distinct vimv.id ) " + "from <API key> vimv " + "join ostra_VersionedItem vi on vi.id = vimv.idVersionedItem " + "join revision r on r.id = vi.idRevision " + "where r.idproject = ? and r.number = ? and vimv.idMetric = ?"; Query query = JPAUtil.getEntityManager().createNativeQuery(strQuery); query.setParameter(1, revision.getProject().getId()); query.setParameter(2, revision.getNumber()); query.setParameter(3, metric.getId()); return NumberUtil.longValueOf(query.getSingleResult()); } @MetodoRecuperaLista public List<<API key>> <API key>(Revision revision, Metric metric) { throw new <API key>(); } @MetodoRecuperaLista public List<<API key>> getByRevision(Revision revision) { throw new <API key>(); } // @<API key> public <API key> <API key>(Item item, Metric metric, Long revisionNumber) { // throw new <API key>(); final String strQuery = "select vimv " + " from <API key> vimv " + " where vimv.versionedItem.item = ? " + " and vimv.metric = ? " + " and vimv.versionedItem.revision.number <= ? " + " order by vimv.versionedItem.revision.number desc"; Query query = JPAUtil.getEntityManager().createQuery(strQuery); query.setParameter(1, item); query.setParameter(2, metric); query.setParameter(3, revisionNumber); List resultList = query.getResultList(); return (<API key>) (resultList == null || resultList.isEmpty() ? null : resultList.get(0)); } }
import React from 'react'; import { Theme, ThemeProvider, useTheme, createMuiTheme } from '@material-ui/core/styles'; import useMediaQuery from '@material-ui/core/useMediaQuery'; import { Breakpoint } from '@material-ui/core/styles/createBreakpoints'; type BreakpointOrNull = Breakpoint | null; function useWidth() { const theme: Theme = useTheme(); const keys: Breakpoint[] = [...theme.breakpoints.keys].reverse(); return ( keys.reduce((output: BreakpointOrNull, key: Breakpoint) => { // <API key> react-hooks/rules-of-hooks const matches = useMediaQuery(theme.breakpoints.up(key)); return !output && matches ? key : output; }, null) || 'xs' ); } function MyComponent() { const width = useWidth(); return <span>{`width: ${width}`}</span>; } const theme = createMuiTheme(); export default function UseWidth() { return ( <ThemeProvider theme={theme}> <MyComponent /> </ThemeProvider> ); }
import sublime import sublime_plugin import json import os import traceback from threading import Thread from subprocess import PIPE, Popen dirtyFiles = [] pluginSettings = None <API key> = None <API key> = None <API key> = None pluginPath = None userPath = None <API key> = False def getPluginPath(appendPath = None): global pluginPath if not pluginPath: pluginPath = os.path.dirname(__file__); if appendPath: return os.sep.join([pluginPath, appendPath]) return pluginPath def getUserPath(appendPath = None): global userPath if not userPath: userPath = os.sep.join([os.path.dirname(getPluginPath()), "User"]) if appendPath: return os.sep.join([userPath, appendPath]) return userPath def logError(errorMessage): # outputPanel = sublime.active_window().create_output_panel("sasscompile") # outputPanelEdit = outputPanel.begin_edit() # outputPanel.insert(outputPanelEdit, outputPanel.size(), "SassCompile Encountered an Error:\n") print("Sass Compile Encountered an Error:") # outputPanel.insert(outputPanelEdit, outputPanel.size(), err + "\n") # outputPanel.end_edit(outputPanelEdit) print(errorMessage) # outputPanel. # sublime.active_window().run_command("show_panel", {"panel": "output.sasscompile"}) def wasDirty(filePath): return filePath in dirtyFiles def getPluginSettings(): global pluginSettings if not pluginSettings: pluginSettings = sublime.load_settings("SassCompile.sublime-settings") return pluginSettings def <API key>(useUserDefaults = False): global <API key> if not <API key>: with open(getPluginPath("SassCompile.settings")) as <API key>: <API key> = json.load(<API key>) if useUserDefaults: <API key> = <API key>() for setting in <API key>: setting["default"] = <API key>[setting["name"]] return <API key>.copy() def <API key>(useUserDefaults = False): global <API key> if not <API key>: <API key> = [] for setting in <API key>(useUserDefaults): if not setting["advanced"]: <API key>.append(setting) return <API key>.copy() def <API key>(): global <API key> if not <API key>: <API key> = {} for setting in <API key>(): <API key>[setting["name"]] = setting["default"] return <API key>.copy() def <API key>(): <API key> = <API key>() <API key> = getUserPath("SassCompile.default-config") userDefaultSettings = None if os.path.isfile(<API key>): with open(<API key>) as <API key>: userDefaultSettings = json.load(<API key>) for settingName, defaultValue in userDefaultSettings.items(): if settingName in <API key>: <API key>[settingName] = defaultValue if not userDefaultSettings or set(userDefaultSettings) ^ set(<API key>): with open(<API key>, "w") as <API key>: json.dump(<API key>, <API key>, indent=4) return <API key> def <API key>(promptLevel = 0): if promptLevel == 0: <API key>() elif promptLevel > 0: if promptLevel == 1: promptSettings = <API key>(True) elif promptLevel == 2: promptSettings = <API key>(True) UserInputList(promptSettings, <API key>, <API key>) def <API key>(answers = None): initialSettings = <API key>() if answers: for name, answer in answers.items(): initialSettings[name] = answer setProjectSetting(initialSettings) sublime.status_message("Sass Compile is now enabled for this project.") def <API key>(question, type): if type == UserInputList.QUICK_PANEL: return [question["title"] + " (" + question["name"] + ")", question["question"]] elif type == UserInputList.INPUT_PANEL: return question["title"] + " (" + question["name"] + ") - " + question["question"] def <API key>(): projectData = sublime.active_window().project_data() projectData["settings"].pop("sasscompile") if len(projectData["settings"]) == 0: projectData.pop("settings") sublime.active_window().set_project_data(projectData) sublime.status_message("Sass Compile has been disabled for this project.") def getProjectSetting(name = None): projectData = sublime.active_window().project_data() <API key>(projectData["settings"]["sasscompile"]) if name != None: return projectData["settings"]["sasscompile"][name] return projectData["settings"]["sasscompile"].copy() def setProjectSetting(name, value = None): projectData = sublime.active_window().project_data() if "settings" not in projectData: projectData["settings"] = {} if "sasscompile" not in projectData["settings"]: projectData["settings"]["sasscompile"] = {} if value != None: projectData["settings"]["sasscompile"][name] = value else: projectData["settings"]["sasscompile"] = name sublime.active_window().set_project_data(projectData) def <API key>(projectSettings): global <API key> if not <API key>: <API key> = <API key>() if set(projectSettings) ^ set(<API key>): for setting in <API key>: if setting in projectSettings: <API key>[setting] = projectSettings[setting] setProjectSetting(<API key>) <API key> = True def <API key>(): if sublime.active_window().project_file_name(): projectData = sublime.active_window().project_data() if "settings" in projectData.keys(): if "sasscompile" in projectData["settings"].keys(): return True return False def isSassFile(filePath): if os.path.splitext(filePath)[1][1:] == getProjectSetting("syntax"): return True return False def getFilesToCompile(filePath): if os.path.basename(filePath).startswith("_"): return getImportParents(filePath) return [filePath] def getImportParents(filePath): importName = os.path.basename(filePath).split(".")[0][1:] cmd = "grep -E '@import.*{0}' * -l".format(importName) proc = Popen(cmd, shell=True, cwd=os.path.dirname(filePath), stdout=PIPE, stderr=PIPE) out, err = proc.communicate() if err: logError(err) return if not out: return files = [] out = out.decode("utf8") for parentFileName in out.split(): if isSassFile(parentFileName): files.extend(getFilesToCompile(os.sep.join([os.path.dirname(filePath), parentFileName]))) return files def compileOnThread(filesToCompile, originalFile): compileThread = Thread(target=compile, args=(filesToCompile, originalFile)) compileThread.start() def compile(filesToCompile, originalFile): compiled_files = [] filesToCompile = list(set(filesToCompile)) for filePath in filesToCompile: settings = getProjectSetting() compileName = os.path.basename(filePath).replace(os.path.splitext(filePath)[1], ".css") if os.path.isabs(settings["css-location"]): compilePath = os.path.join(settings["css-location"], compileName) else: compilePath = os.path.normpath(os.sep.join([os.path.dirname(filePath), settings["css-location"], compileName])) rules = ["--trace", "--stop-on-error", "--style {0}".format(settings["style"])] if originalFile not in dirtyFiles: rules.append("--force") if not settings["cache"]: rules.append("--no-cache") if settings["debug-info"]: rules.append("--debug-info") if settings["line-numbers"]: rules.append("--line-numbers") if settings["cache-location"]: rules.append("--cache-location \'{0}\'".format(settings["cache-location"])) if not settings["sourcemap"]: rules.append("--sourcemap=none") cmd = "{0} {1} \'{2}\' \'{3}\'".format(getPluginSettings().get("sass_path"), " ".join(rules), filePath, compilePath) proc = Popen(cmd, shell=True, cwd=os.path.dirname(filePath), stdout=PIPE, stderr=PIPE) out, err = proc.communicate() if err: logError(err) return compiled_files.append(filePath) sublime.status_message("{0} SASS file(s) compiled.".format(len(compiled_files))) if originalFile in dirtyFiles: dirtyFiles.remove(originalFile) class <API key>(sublime_plugin.WindowCommand): def run(self): self.window.show_quick_panel([["Use Default Settings", "All settings will be initialized using the current defaults."], ["Customize Settings (Basic)", "Choose custom values for the most common settings."], ["Specify All Settings (Advanced)", "Choose custom values for all of the available settings."]], <API key>) # <API key>() def is_visible(self): return not <API key>() class <API key>(sublime_plugin.WindowCommand): def run(self): <API key>() def is_visible(self): return <API key>() class <API key>(sublime_plugin.WindowCommand): def run(self): setProjectSetting("compile-on-save", True) def is_visible(self): return <API key>() and not getProjectSetting("compile-on-save") class <API key>(sublime_plugin.WindowCommand): def run(self): setProjectSetting("compile-on-save", False) def is_visible(self): return <API key>() and getProjectSetting("compile-on-save") class <API key>(sublime_plugin.WindowCommand): def run(self): compileOnThread(getFilesToCompile(self.window.active_view().file_name()), self.window.active_view().file_name()) def is_visible(self): return <API key>() and isSassFile(self.window.active_view().file_name()) class SassCompileCommand(sublime_plugin.EventListener): def on_pre_save(self, view): if <API key>() and isSassFile(view.file_name()) and view.is_dirty(): dirtyFiles.append(view.file_name()) def on_post_save(self, view): if <API key>() and getProjectSetting("compile-on-save") and isSassFile(view.file_name()) and wasDirty(view.file_name()): compileOnThread(getFilesToCompile(view.file_name()), view.file_name()) class <API key>(sublime_plugin.WindowCommand): def run(self): <API key>() self.window.open_file(getUserPath("SassCompile.default-config")) class UserInputList(): QUICK_PANEL = 0 INPUT_PANEL = 1 questions = None questionIndex = 0 completeCallback = None <API key> = None cancelCallback = None answers = {} resetIndex = False def __init__(self, questions, completeCallback, <API key> = None, cancelCallback = None): self.questions = questions self.completeCallback = completeCallback self.<API key> = <API key> self.promptQuestion(False) def promptQuestion(self, delayed = True, resetIndex = False): currentQuestion = self.questions[self.questionIndex] if currentQuestion["type"] == "boolean" or type(currentQuestion["type"]) is list: if delayed: if self.<API key>: choices = [self.<API key>(currentQuestion, self.QUICK_PANEL)] else: choices = [currentQuestion["question"]] if currentQuestion["type"] == "boolean": choices.extend(["Yes", "No"]) if currentQuestion["default"] == True: defaultIndex = 1 else: defaultIndex = 2 elif type(currentQuestion["type"]) is list: choices.extend(currentQuestion["type"]) defaultIndex = currentQuestion["type"].index(currentQuestion["default"]) + 1 if self.resetIndex: self.resetIndex = False defaultIndex = 1 sublime.active_window().show_quick_panel(choices, self.recordAnswer, 0, defaultIndex) else: if resetIndex: self.resetIndex = True sublime.set_timeout(self.promptQuestion, 100) elif currentQuestion["type"] == "text": if self.<API key>: caption = self.<API key>(currentQuestion, self.INPUT_PANEL) else: caption = currentQuestion["question"] default = currentQuestion["default"] if currentQuestion["default"] else "" sublime.active_window().show_input_panel(caption, default, self.recordAnswer, None, self.cancelCallback) def recordAnswer(self, answer): currentQuestion = self.questions[self.questionIndex] if currentQuestion["type"] == "boolean" or type(currentQuestion["type"]) is list: if answer == -1: if self.cancelCallback: self.cancelCallback() return elif answer == 0: self.promptQuestion(False, True) return else: if currentQuestion["type"] == "boolean": if answer == 1: currentAnswer = True elif answer == 2: currentAnswer = False elif type(currentQuestion["type"]) is list: currentAnswer = currentQuestion["type"][answer - 1] elif currentQuestion["type"] == "text": if answer == -1: return else: currentAnswer = answer self.answers[currentQuestion["name"]] = currentAnswer self.questionIndex += 1 if self.questionIndex == len(self.questions): self.completeCallback(self.answers) else: self.promptQuestion(False)
/* * <API key>.java * */ package de.uni_stuttgart.vis.vowl.owl2vowl.constants; import org.codehaus.jackson.annotate.JsonValue; public enum <API key> { TITLE("title"), VERSION("versionInfo"), AUTHOR("creator"); private final String value; <API key>(String value) { this.value = value; } @JsonValue public String getValue() { return value; } }
angular.module("ui.rCalendar.tpls", ["templates/rcalendar/calendar.html","templates/rcalendar/day.html","templates/rcalendar/displayEvent.html","templates/rcalendar/month.html","templates/rcalendar/<API key>.html","templates/rcalendar/<API key>.html","templates/rcalendar/week.html"]); angular.module( 'ui.rCalendar', [] ) .constant( 'calendarConfig', { formatDay: 'dd', formatDayHeader: 'EEE', formatDayTitle: 'MMMM dd, yyyy', formatWeekTitle: 'MMMM yyyy, Week w', formatMonthTitle: 'MMMM yyyy', <API key>: 'EEE d', formatHourColumn: 'ha', calendarMode: 'month', showEventDetail: true, startingDayMonth: 0, startingDayWeek: 0, allDayLabel: 'all day', noEventsLabel: 'No Events', eventPeriod: { start: new Date(), end: new Date() }, scrollTo: 'hour-1', scrollCallBack: function () {}, eventSource: null, queryMode: 'local', step: 60, autoSelect: true, <API key>: 'templates/rcalendar/<API key>.html', <API key>: 'templates/rcalendar/<API key>.html', <API key>: 'templates/rcalendar/displayEvent.html', <API key>: 'templates/rcalendar/displayEvent.html', <API key>: 'templates/rcalendar/displayEvent.html', <API key>: 'templates/rcalendar/displayEvent.html' } ) .controller( 'ui.rCalendar.CalendarController', [ '$scope', '$attrs', '$parse', '$interpolate', '$log', 'dateFilter', 'calendarConfig', '$timeout', '$<API key>', '$ionicScrollDelegate', '$ionicPosition', function ( $scope, $attrs, $parse, $interpolate, $log, dateFilter, calendarConfig, $timeout, $<API key>, $ionicScrollDelegate, $ionicPosition ) { 'use strict'; var self = this, ngModelCtrl = { $setViewValue: angular.noop }; // nullModelCtrl; // Configuration attributes angular.forEach( [ 'formatDay', 'formatDayHeader', 'formatDayTitle', 'formatWeekTitle', 'formatMonthTitle', '<API key>', 'formatHourColumn', 'allDayLabel', 'noEventsLabel', 'eventPeriod', 'scrollTo', 'scrollCallBack' ], function ( key, index ) { self[ key ] = angular.isDefined( $attrs[ key ] ) ? $interpolate( $attrs[ key ] )( $scope.$parent ) : calendarConfig[ key ]; } ); angular.forEach( [ 'showEventDetail', '<API key>', '<API key>', '<API key>', '<API key>', '<API key>', '<API key>', 'eventSource', 'queryMode', 'step', 'startingDayMonth', 'startingDayWeek', 'autoSelect' ], function ( key, index ) { self[ key ] = angular.isDefined( $attrs[ key ] ) ? ( $scope.$parent.$eval( $attrs[ key ] ) ) : calendarConfig[ key ]; } ); self.hourParts = 1; if ( self.step === 60 || self.step === 30 || self.step === 15 ) { self.hourParts = Math.floor( 60 / self.step ); } else { throw new Error( 'Invalid step parameter: ' + self.step ); } var unregisterFn = $scope.$parent.$watch( $attrs.eventSource, function ( value ) { self.<API key>( value ); } ); $scope.$on( '$destroy', unregisterFn ); function scrollToFnc() { $timeout( function () { var slides = document.<API key>( 'ion-slide' ); //this will work becouse the index is starting from 0 if index starts from 1 then it has to be modified var selectedElem = slides[ $<API key>.currentIndex() ].querySelector( '#' + $scope.scrollTo ); $ionicScrollDelegate.scrollTo( 0, $ionicPosition.position( angular.element( selectedElem ) ).top, true ); }, 500 ); } $scope.calendarMode = $scope.calendarMode || calendarConfig.calendarMode; $scope.eventPeriod = $scope.eventPeriod || calendarConfig.eventPeriod; $scope.scrollCallBack = $scope.scrollCallBack || scrollToFnc; if ( angular.isDefined( $attrs.initDate ) ) { self.currentCalendarDate = $scope.$parent.$eval( $attrs.initDate ); } if ( !self.currentCalendarDate ) { self.currentCalendarDate = new Date(); if ( $attrs.ngModel && !$scope.$parent.$eval( $attrs.ngModel ) ) { $parse( $attrs.ngModel ).assign( $scope.$parent, self.currentCalendarDate ); } } function overlap( event1, event2 ) { var earlyEvent = event1, lateEvent = event2; if ( event1.startIndex > event2.startIndex || ( event1.startIndex === event2.startIndex && event1.startOffset > event2.startOffset ) ) { earlyEvent = event2; lateEvent = event1; } if ( earlyEvent.endIndex <= lateEvent.startIndex ) { return false; } else { return !( earlyEvent.endIndex - lateEvent.startIndex === 1 && earlyEvent.endOffset + lateEvent.startOffset > self.hourParts ); } } function calculatePosition( events ) { var i, j, len = events.length, maxColumn = 0, col, isForbidden = new Array( len ); for ( i = 0; i < len; i += 1 ) { for ( col = 0; col < maxColumn; col += 1 ) { isForbidden[ col ] = false; } for ( j = 0; j < i; j += 1 ) { if ( overlap( events[ i ], events[ j ] ) ) { isForbidden[ events[ j ].position ] = true; } } for ( col = 0; col < maxColumn; col += 1 ) { if ( !isForbidden[ col ] ) { break; } } if ( col < maxColumn ) { events[ i ].position = col; } else { events[ i ].position = maxColumn++; } } } function calculateWidth( orderedEvents ) { var cells = new Array( 24 ), event, index, i, j, len, eventCountInCell, currentEventInCell; //sort by position in descending order, the right most columns should be calculated first orderedEvents.sort( function ( eventA, eventB ) { return eventB.position - eventA.position; } ); for ( i = 0; i < 24; i += 1 ) { cells[ i ] = { calculated: false, events: [] }; } len = orderedEvents.length; for ( i = 0; i < len; i += 1 ) { event = orderedEvents[ i ]; index = event.startIndex; while ( index < event.endIndex ) { cells[ index ].events.push( event ); index += 1; } } i = 0; while ( i < len ) { event = orderedEvents[ i ]; if ( !event.overlapNumber ) { var overlapNumber = event.position + 1; event.overlapNumber = overlapNumber; var eventQueue = [ event ]; while ( ( event = eventQueue.shift() ) ) { index = event.startIndex; while ( index < event.endIndex ) { if ( !cells[ index ].calculated ) { cells[ index ].calculated = true; if ( cells[ index ].events ) { eventCountInCell = cells[ index ].events.length; for ( j = 0; j < eventCountInCell; j += 1 ) { currentEventInCell = cells[ index ].events[ j ]; if ( !currentEventInCell.overlapNumber ) { currentEventInCell.overlapNumber = overlapNumber; eventQueue.push( currentEventInCell ); } } } } index += 1; } } } i += 1; } } function <API key>( currentCalendarDate, direction ) { var step = self.mode.step, <API key> = new Date( currentCalendarDate ), year = <API key>.getFullYear() + direction * ( step.years || 0 ), month = <API key>.getMonth() + direction * ( step.months || 0 ), date = <API key>.getDate() + direction * ( step.days || 0 ), firstDayInNextMonth; <API key>.setFullYear( year, month, date ); if ( $scope.calendarMode === 'month' ) { firstDayInNextMonth = new Date( year, month + 1, 1 ); if ( firstDayInNextMonth.getTime() <= <API key>.getTime() ) { <API key> = new Date( firstDayInNextMonth - 24 * 60 * 60 * 1000 ); } } return <API key>; } self.init = function ( ngModelCtrl_ ) { ngModelCtrl = ngModelCtrl_; ngModelCtrl.$render = function () { self.render(); }; }; self.render = function () { if ( ngModelCtrl.$modelValue ) { var date = new Date( ngModelCtrl.$modelValue ), isValid = !isNaN( date ); if ( isValid ) { this.currentCalendarDate = date; } else { $log.error( '"ng-model" value must be a Date object, a number of milliseconds since 01.01.1970 or a string representing an RFC2822 or ISO 8601 date.' ); } ngModelCtrl.$setValidity( 'date', isValid ); } this.refreshView(); }; self.refreshView = function () { if ( this.mode ) { this.range = this._getRange( this.currentCalendarDate ); if ( $scope.titleChanged ) { $scope.titleChanged( { title: self._getTitle() } ); } this._refreshView(); this.rangeChanged(); } }; // Split array into smaller arrays self.split = function ( arr, size ) { var arrays = []; while ( arr.length > 0 ) { arrays.push( arr.splice( 0, size ) ); } return arrays; }; self.<API key> = function ( value ) { self.eventSource = value; if ( self._onDataLoaded ) { self._onDataLoaded(); } }; self.<API key> = function ( direction ) { var <API key> = <API key>( self.currentCalendarDate, direction ); return self._getRange( <API key> ).startTime; }; self.move = function ( direction ) { self.direction = direction; if ( !self.moveOnSelected ) { self.currentCalendarDate = <API key>( self.currentCalendarDate, direction ); } ngModelCtrl.$setViewValue( self.currentCalendarDate ); self.refreshView(); self.direction = 0; self.moveOnSelected = false; }; self.rangeChanged = function () { if ( self.queryMode === 'local' ) { if ( self.eventSource && self._onDataLoaded ) { self._onDataLoaded(); } } else if ( self.queryMode === 'remote' ) { if ( $scope.rangeChanged ) { $scope.rangeChanged( { startTime: this.range.startTime, endTime: this.range.endTime } ); } } }; self.<API key> = function ( scope, callback ) { scope.currentViewIndex = 0; scope.slideChanged = function ( $index ) { $timeout( function () { var currentViewIndex = scope.currentViewIndex, direction = 0; if ( $index - currentViewIndex === 1 || ( $index === 0 && currentViewIndex === 2 ) ) { direction = 1; } else if ( currentViewIndex - $index === 1 || ( $index === 2 && currentViewIndex === 0 ) ) { direction = -1; } currentViewIndex = $index; scope.currentViewIndex = currentViewIndex; self.move( direction ); scope.$digest(); if ( callback ) { callback(); } else { scrollToFnc(); } }, 200 ); }; }; self.<API key> = function ( scope ) { var <API key>, currentViewData, toUpdateViewIndex, currentViewIndex = scope.currentViewIndex, getViewData = this._getViewData; if ( self.direction === 1 ) { <API key> = self.<API key>( 1 ); toUpdateViewIndex = ( currentViewIndex + 1 ) % 3; angular.copy( getViewData( <API key> ), scope.views[ toUpdateViewIndex ] ); } else if ( self.direction === -1 ) { <API key> = self.<API key>( -1 ); toUpdateViewIndex = ( currentViewIndex + 2 ) % 3; angular.copy( getViewData( <API key> ), scope.views[ toUpdateViewIndex ] ); } else { if ( !scope.views ) { currentViewData = []; <API key> = self.range.startTime; currentViewData.push( getViewData( <API key> ) ); <API key> = self.<API key>( 1 ); currentViewData.push( getViewData( <API key> ) ); <API key> = self.<API key>( -1 ); currentViewData.push( getViewData( <API key> ) ); scope.views = currentViewData; } else { <API key> = self.range.startTime; angular.copy( getViewData( <API key> ), scope.views[ currentViewIndex ] ); <API key> = self.<API key>( -1 ); toUpdateViewIndex = ( currentViewIndex + 2 ) % 3; angular.copy( getViewData( <API key> ), scope.views[ toUpdateViewIndex ] ); <API key> = self.<API key>( 1 ); toUpdateViewIndex = ( currentViewIndex + 1 ) % 3; angular.copy( getViewData( <API key> ), scope.views[ toUpdateViewIndex ] ); } } }; self.placeEvents = function ( orderedEvents ) { calculatePosition( orderedEvents ); calculateWidth( orderedEvents ); }; self.placeAllDayEvents = function ( orderedEvents ) { calculatePosition( orderedEvents ); }; self.slideView = function ( direction ) { var slideHandle = $<API key>.$getByHandle( $scope.calendarMode + 'view-slide' ); if ( slideHandle ) { if ( direction === 1 ) { slideHandle.next(); } else if ( direction === -1 ) { slideHandle.previous(); } } }; } ] ) .directive( 'calendar', function () { 'use strict'; return { restrict: 'EA', replace: true, templateUrl: 'templates/rcalendar/calendar.html', scope: { eventPeriod: '=?eventPeriod', scrollTo: '=?scrollTo', scrollCallBack: '=?scrollCallBack', calendarMode: '=', rangeChanged: '&', eventSelected: '&', timeSelected: '&', titleChanged: '&', isDateDisabled: '&' }, require: [ 'calendar', '?^ngModel' ], controller: 'ui.rCalendar.CalendarController', link: function ( scope, element, attrs, ctrls ) { var calendarCtrl = ctrls[ 0 ], ngModelCtrl = ctrls[ 1 ]; if ( ngModelCtrl ) { calendarCtrl.init( ngModelCtrl ); } function isToday( date ) { var now = new Date(); if ( date.setHours( 0, 0, 0, 0 ) === now.setHours( 0, 0, 0, 0 ) ) { return true; } } function isPassedOrFuture( date ) { var now = new Date(); if ( date.setHours( 0, 0, 0, 0 ) > now.setHours( 0, 0, 0, 0 ) ) { return 'future'; } if ( date.setHours( 0, 0, 0, 0 ) < now.setHours( 0, 0, 0, 0 ) ) { return 'past'; } } scope.isToday = isToday; scope.isPassedOrFuture = isPassedOrFuture; scope.$on( 'changeDate', function ( event, direction ) { calendarCtrl.slideView( direction ); } ); scope.$on( 'eventSourceChanged', function ( event, value ) { calendarCtrl.<API key>( value ); } ); } }; } ) .directive( 'monthview', [ 'dateFilter', function ( dateFilter ) { 'use strict'; return { restrict: 'EA', replace: true, templateUrl: 'templates/rcalendar/month.html', require: [ '^calendar', '?^ngModel' ], link: function ( scope, element, attrs, ctrls ) { var ctrl = ctrls[ 0 ], ngModelCtrl = ctrls[ 1 ]; scope.showEventDetail = ctrl.showEventDetail; scope.formatDayHeader = ctrl.formatDayHeader; scope.autoSelect = ctrl.autoSelect; ctrl.mode = { step: { months: 1 } }; scope.noEventsLabel = ctrl.noEventsLabel; scope.<API key> = ctrl.<API key>; scope.<API key> = ctrl.<API key>; function getDates( startDate, n ) { var dates = new Array( n ), current = new Date( startDate ), i = 0; current.setHours( 12 ); // Prevent repeated dates because of timezone bug while ( i < n ) { dates[ i++ ] = new Date( current ); current.setDate( current.getDate() + 1 ); } return dates; } function createDateObject( date, format ) { var dateObject = { date: date, label: dateFilter( date, format ) }; if ( scope.isDateDisabled ) { dateObject.disabled = scope.isDateDisabled( { date: date } ); } return dateObject; } function updateCurrentView( <API key>, view ) { var currentCalendarDate = ctrl.currentCalendarDate, today = new Date(), oneDay = 86400000, r, <API key> = Math.floor( ( currentCalendarDate.getTime() - <API key>.getTime() ) / oneDay ), <API key> = Math.floor( ( today.getTime() - <API key>.getTime() ) / oneDay ); for ( r = 0; r < 42; r += 1 ) { view.dates[ r ].selected = false; } if ( <API key> >= 0 && <API key> < 42 && ( scope.autoSelect || ctrl.moveOnSelected ) ) { view.dates[ <API key> ].selected = true; scope.selectedDate = view.dates[ <API key> ]; } else { scope.selectedDate = { events: [] }; } if ( <API key> >= 0 && <API key> < 42 ) { view.dates[ <API key> ].current = true; } } function compareEvent( event1, event2 ) { if ( event1.allDay ) { return 1; } else if ( event2.allDay ) { return -1; } else { return ( event1.startTime.getTime() - event2.startTime.getTime() ); } } scope.select = function ( viewDate ) { var selectedDate = viewDate.date, events = viewDate.events, views = scope.views, dates, r; if ( views ) { dates = views[ scope.currentViewIndex ].dates; var currentCalendarDate = ctrl.currentCalendarDate; var currentMonth = currentCalendarDate.getMonth(); var currentYear = currentCalendarDate.getFullYear(); var selectedMonth = selectedDate.getMonth(); var selectedYear = selectedDate.getFullYear(); var direction = 0; if ( currentYear === selectedYear ) { if ( currentMonth !== selectedMonth ) { direction = currentMonth < selectedMonth ? 1 : -1; } } else { direction = currentYear < selectedYear ? 1 : -1; } ctrl.currentCalendarDate = selectedDate; if ( direction === 0 ) { if ( ngModelCtrl ) { ngModelCtrl.$setViewValue( selectedDate ); } var <API key> = ctrl.range.startTime, oneDay = 86400000, <API key> = Math.floor( ( selectedDate.getTime() - <API key>.getTime() ) / oneDay ); for ( r = 0; r < 42; r += 1 ) { dates[ r ].selected = false; } if ( <API key> >= 0 && <API key> < 42 ) { dates[ <API key> ].selected = true; scope.selectedDate = dates[ <API key> ]; } } else { ctrl.moveOnSelected = true; ctrl.slideView( direction ); } if ( scope.timeSelected ) { scope.timeSelected( { selectedTime: selectedDate, events: events, disabled: viewDate.disabled || false } ); } } }; scope.getHighlightClass = function ( date ) { var className = ''; if ( date.hasEvent ) { if ( date.secondary ) { className = '<API key>'; } else { className = '<API key>'; } } if ( date.selected ) { if ( className ) { className += ' '; } className += 'monthview-selected'; } if ( date.current ) { if ( className ) { className += ' '; } className += 'monthview-current'; } if ( date.secondary ) { if ( className ) { className += ' '; } className += 'text-muted'; } if ( date.disabled ) { if ( className ) { className += ' '; } className += 'monthview-disabled'; } return className; }; ctrl._getTitle = function () { var <API key> = ctrl.range.startTime, date = <API key>.getDate(), month = ( <API key>.getMonth() + ( date !== 1 ? 1 : 0 ) ) % 12, year = <API key>.getFullYear() + ( date !== 1 && month === 0 ? 1 : 0 ), headerDate = new Date( year, month, 1 ); return dateFilter( headerDate, ctrl.formatMonthTitle ); }; ctrl._getViewData = function ( startTime ) { var startDate = startTime, date = startDate.getDate(), month = ( startDate.getMonth() + ( date !== 1 ? 1 : 0 ) ) % 12; var days = getDates( startDate, 42 ); for ( var i = 0; i < 42; i++ ) { days[ i ] = angular.extend( createDateObject( days[ i ], ctrl.formatDay ), { secondary: days[ i ].getMonth() !== month } ); } return { dates: days }; }; ctrl._refreshView = function () { ctrl.<API key>( scope ); updateCurrentView( ctrl.range.startTime, scope.views[ scope.currentViewIndex ] ); }; ctrl._onDataLoaded = function () { var eventSource = ctrl.eventSource, len = eventSource ? eventSource.length : 0, startTime = ctrl.range.startTime, endTime = ctrl.range.endTime, utcStartTime = new Date( Date.UTC( startTime.getFullYear(), startTime.getMonth(), startTime.getDate() ) ), utcEndTime = new Date( Date.UTC( endTime.getFullYear(), endTime.getMonth(), endTime.getDate() ) ), currentViewIndex = scope.currentViewIndex, dates = scope.views[ currentViewIndex ].dates, oneDay = 86400000, eps = 0.001; for ( var r = 0; r < 42; r += 1 ) { if ( dates[ r ].hasEvent ) { dates[ r ].hasEvent = false; dates[ r ].events = []; } } for ( var i = 0; i < len; i += 1 ) { var event = eventSource[ i ]; var eventStartTime = new Date( event.startTime ); var eventEndTime = new Date( event.endTime ); var st; var et; if ( event.allDay ) { if ( eventEndTime <= utcStartTime || eventStartTime >= utcEndTime ) { continue; } else { st = utcStartTime; et = utcEndTime; } } else { if ( eventEndTime <= startTime || eventStartTime >= endTime ) { continue; } else { st = startTime; et = endTime; } } var timeDiff; var timeDifferenceStart; if ( eventStartTime <= st ) { timeDifferenceStart = 0; } else { timeDiff = eventStartTime - st; if ( !event.allDay ) { timeDiff = timeDiff - ( eventStartTime.getTimezoneOffset() - st.getTimezoneOffset() ) * 60000; } timeDifferenceStart = timeDiff / oneDay; } var timeDifferenceEnd; if ( eventEndTime >= et ) { timeDiff = et - st; if ( !event.allDay ) { timeDiff = timeDiff - ( et.getTimezoneOffset() - st.getTimezoneOffset() ) * 60000; } timeDifferenceEnd = timeDiff / oneDay; } else { timeDiff = eventEndTime - st; if ( !event.allDay ) { timeDiff = timeDiff - ( eventEndTime.getTimezoneOffset() - st.getTimezoneOffset() ) * 60000; } timeDifferenceEnd = timeDiff / oneDay; } var index = Math.floor( timeDifferenceStart ); var eventSet; while ( index < timeDifferenceEnd - eps ) { dates[ index ].hasEvent = true; eventSet = dates[ index ].events; if ( eventSet ) { eventSet.push( event ); } else { eventSet = []; eventSet.push( event ); dates[ index ].events = eventSet; } index += 1; } } for ( r = 0; r < 42; r += 1 ) { if ( dates[ r ].hasEvent ) { dates[ r ].events.sort( compareEvent ); } } if ( scope.autoSelect ) { var findSelected = false; for ( r = 0; r < 42; r += 1 ) { if ( dates[ r ].selected ) { scope.selectedDate = dates[ r ]; findSelected = true; break; } if ( findSelected ) { break; } } } }; ctrl._getRange = function getRange( currentDate ) { var year = currentDate.getFullYear(), month = currentDate.getMonth(), firstDayOfMonth = new Date( year, month, 1 ), difference = ctrl.startingDayMonth - firstDayOfMonth.getDay(), <API key> = ( difference > 0 ) ? 7 - difference : -difference, startDate = new Date( firstDayOfMonth ), endDate; if ( <API key> > 0 ) { startDate.setDate( -<API key> + 1 ); } endDate = new Date( startDate ); endDate.setDate( endDate.getDate() + 42 ); return { startTime: startDate, endTime: endDate }; }; ctrl.<API key>( scope, scope.$parent.scrollCallBack( scope.$parent.scrollTo ) ); ctrl.refreshView(); } }; } ] ) .directive( 'weekview', [ 'dateFilter', function ( dateFilter ) { 'use strict'; return { restrict: 'EA', replace: true, templateUrl: 'templates/rcalendar/week.html', require: '^calendar', link: function ( scope, element, attrs, ctrl ) { scope.<API key> = ctrl.<API key>; scope.formatHourColumn = ctrl.formatHourColumn; scope.eventPeriod = scope.$parent.eventPeriod; scope.isToday = scope.$parent.isToday; scope.isPassedOrFuture = scope.$parent.isPassedOrFuture; ctrl.mode = { step: { days: 7 } }; scope.allDayLabel = ctrl.allDayLabel; scope.hourParts = ctrl.hourParts; scope.<API key> = ctrl.<API key>; scope.<API key> = ctrl.<API key>; function toDate( string ) { var result = new Date( string ); result.setDate( result.getDate() + 1 ); return result; } scope.toDate = toDate; function getDates( startTime, n ) { var dates = new Array( n ), current = new Date( startTime ), i = 0; current.setHours( 12 ); // Prevent repeated dates because of timezone bug while ( i < n ) { dates[ i++ ] = { date: new Date( current ) }; current.setDate( current.getDate() + 1 ); } return dates; } function createDateObjects( startTime ) { var times = [], row, time, currentHour = startTime.getHours(), currentDate = startTime.getDate(); for ( var hour = 0; hour < 24; hour += 1 ) { row = []; for ( var day = 0; day < 7; day += 1 ) { time = new Date( startTime.getTime() ); time.setHours( currentHour + hour ); time.setDate( currentDate + day ); row.push( { time: time } ); } times.push( row ); } return times; } function <API key>( eventA, eventB ) { return eventA.startOffset - eventB.startOffset; } //This can be decomissioned when upgrade to Angular 1.3 function <API key>( date ) { var checkDate = new Date( date ); checkDate.setDate( checkDate.getDate() + 4 - ( checkDate.getDay() || 7 ) ); // Thursday var time = checkDate.getTime(); checkDate.setMonth( 0 ); // Compare with Jan 1 checkDate.setDate( 1 ); return Math.floor( Math.round( ( time - checkDate ) / 86400000 ) / 7 ) + 1; } ctrl._getTitle = function () { var firstDayOfWeek = ctrl.range.startTime, weekNumberIndex, weekFormatPattern = 'w', title; weekNumberIndex = ctrl.formatWeekTitle.indexOf( weekFormatPattern ); title = dateFilter( firstDayOfWeek, ctrl.formatWeekTitle ); if ( weekNumberIndex !== -1 ) { title = title.replace( weekFormatPattern, <API key>( firstDayOfWeek ) ); } return title; }; scope.select = function ( selectedTime, events ) { if ( scope.timeSelected ) { var disabled; if ( scope.isDateDisabled ) { disabled = scope.isDateDisabled( { date: selectedTime } ); } scope.timeSelected( { selectedTime: selectedTime, events: events, disabled: disabled || false } ); } }; ctrl._getViewData = function ( startTime ) { return { rows: createDateObjects( startTime ), dates: getDates( startTime, 7 ) }; }; ctrl._refreshView = function () { ctrl.<API key>( scope ); }; ctrl._onDataLoaded = function () { var eventSource = ctrl.eventSource, i, day, hour, len = eventSource ? eventSource.length : 0, startTime = ctrl.range.startTime, endTime = ctrl.range.endTime, utcStartTime = new Date( Date.UTC( startTime.getFullYear(), startTime.getMonth(), startTime.getDate() ) ), utcEndTime = new Date( Date.UTC( endTime.getFullYear(), endTime.getMonth(), endTime.getDate() ) ), currentViewIndex = scope.currentViewIndex, rows = scope.views[ currentViewIndex ].rows, dates = scope.views[ currentViewIndex ].dates, oneHour = 3600000, oneDay = 86400000, //add allday eps eps = 0.016, eventSet, allDayEventInRange = false, normalEventInRange = false; for ( i = 0; i < 7; i += 1 ) { dates[ i ].events = []; } for ( day = 0; day < 7; day += 1 ) { for ( hour = 0; hour < 24; hour += 1 ) { rows[ hour ][ day ].events = []; } } for ( i = 0; i < len; i += 1 ) { var event = eventSource[ i ]; var eventStartTime = new Date( event.startTime ); var eventEndTime = new Date( event.endTime ); if ( event.allDay ) { if ( eventEndTime <= utcStartTime || eventStartTime >= utcEndTime ) { continue; } else { allDayEventInRange = true; var allDayStartIndex; if ( eventStartTime <= utcStartTime ) { allDayStartIndex = 0; } else { allDayStartIndex = Math.floor( ( eventStartTime - utcStartTime ) / oneDay ); } var allDayEndIndex; if ( eventEndTime >= utcEndTime ) { allDayEndIndex = Math.ceil( ( utcEndTime - utcStartTime ) / oneDay ); } else { allDayEndIndex = Math.ceil( ( eventEndTime - utcStartTime ) / oneDay ); } var displayAllDayEvent = { event: event, startIndex: allDayStartIndex, endIndex: allDayEndIndex }; eventSet = dates[ allDayStartIndex ].events; if ( eventSet ) { eventSet.push( displayAllDayEvent ); } else { eventSet = []; eventSet.push( displayAllDayEvent ); dates[ allDayStartIndex ].events = eventSet; } } } else { if ( eventEndTime <= startTime || eventStartTime >= endTime ) { continue; } else { normalEventInRange = true; var timeDiff; var timeDifferenceStart; if ( eventStartTime <= startTime ) { timeDifferenceStart = 0; } else { timeDiff = eventStartTime - startTime - ( eventStartTime.getTimezoneOffset() - startTime.getTimezoneOffset() ) * 60000; timeDifferenceStart = timeDiff / oneHour; } var timeDifferenceEnd; if ( eventEndTime >= endTime ) { timeDiff = endTime - startTime - ( endTime.getTimezoneOffset() - startTime.getTimezoneOffset() ) * 60000; timeDifferenceEnd = timeDiff / oneHour; } else { timeDiff = eventEndTime - startTime - ( eventEndTime.getTimezoneOffset() - startTime.getTimezoneOffset() ) * 60000; timeDifferenceEnd = timeDiff / oneHour; } var startIndex = Math.floor( timeDifferenceStart ); var endIndex = Math.ceil( timeDifferenceEnd - eps ); var startRowIndex = startIndex % 24; var dayIndex = Math.floor( startIndex / 24 ); var endOfDay = dayIndex * 24; var endRowIndex; var startOffset = 0; var endOffset = 0; if ( ctrl.hourParts !== 1 ) { startOffset = Math.floor( ( timeDifferenceStart - startIndex ) * ctrl.hourParts ); } do { endOfDay += 24; if ( endOfDay <= endIndex ) { endRowIndex = 24; } else { endRowIndex = endIndex % 24; if ( ctrl.hourParts !== 1 ) { endOffset = Math.floor( ( endIndex - timeDifferenceEnd ) * ctrl.hourParts ); } } var displayEvent = { event: event, startIndex: startRowIndex, endIndex: endRowIndex, startOffset: startOffset, endOffset: endOffset }; eventSet = rows[ startRowIndex ][ dayIndex ].events; if ( eventSet ) { eventSet.push( displayEvent ); } else { eventSet = []; eventSet.push( displayEvent ); rows[ startRowIndex ][ dayIndex ].events = eventSet; } startRowIndex = 0; startOffset = 0; dayIndex += 1; } while ( endOfDay < endIndex ); } } } if ( normalEventInRange ) { for ( day = 0; day < 7; day += 1 ) { var orderedEvents = []; for ( hour = 0; hour < 24; hour += 1 ) { if ( rows[ hour ][ day ].events ) { rows[ hour ][ day ].events.sort( <API key> ); orderedEvents = orderedEvents.concat( rows[ hour ][ day ].events ); } } if ( orderedEvents.length > 0 ) { ctrl.placeEvents( orderedEvents ); } } } if ( allDayEventInRange ) { var orderedAllDayEvents = []; for ( day = 0; day < 7; day += 1 ) { if ( dates[ day ].events ) { orderedAllDayEvents = orderedAllDayEvents.concat( dates[ day ].events ); } } if ( orderedAllDayEvents.length > 0 ) { ctrl.placeAllDayEvents( orderedAllDayEvents ); } } }; ctrl._getRange = function getRange( currentDate ) { var year = currentDate.getFullYear(), month = currentDate.getMonth(), date = currentDate.getDate(), day = currentDate.getDay(), difference = day - ctrl.startingDayWeek, firstDayOfWeek, endTime; if ( difference < 0 ) { difference += 7; } firstDayOfWeek = new Date( year, month, date - difference ); endTime = new Date( year, month, date - difference + 7 ); return { startTime: firstDayOfWeek, endTime: endTime }; }; ctrl.<API key>( scope, scope.$parent.scrollCallBack( scope.$parent.scrollTo ) ); ctrl.refreshView(); } }; } ] ) .directive( 'dayview', [ 'dateFilter', function ( dateFilter ) { 'use strict'; return { restrict: 'EA', replace: true, templateUrl: 'templates/rcalendar/day.html', require: '^calendar', link: function ( scope, element, attrs, ctrl ) { scope.formatHourColumn = ctrl.formatHourColumn; ctrl.mode = { step: { days: 1 } }; scope.allDayLabel = ctrl.allDayLabel; scope.hourParts = ctrl.hourParts; scope.<API key> = ctrl.<API key>; scope.<API key> = ctrl.<API key>; function createDateObjects( startTime ) { var rows = [], time, currentHour = startTime.getHours(), currentDate = startTime.getDate(); for ( var hour = 0; hour < 24; hour += 1 ) { time = new Date( startTime.getTime() ); time.setHours( currentHour + hour ); time.setDate( currentDate ); rows.push( { time: time } ); } return rows; } function <API key>( eventA, eventB ) { return eventA.startOffset - eventB.startOffset; } scope.select = function ( selectedTime, events ) { if ( scope.timeSelected ) { var disabled; if ( scope.isDateDisabled ) { disabled = scope.isDateDisabled( { date: selectedTime } ); } scope.timeSelected( { selectedTime: selectedTime, events: events, disabled: disabled || false } ); } }; ctrl._onDataLoaded = function () { var eventSource = ctrl.eventSource, hour, len = eventSource ? eventSource.length : 0, startTime = ctrl.range.startTime, endTime = ctrl.range.endTime, utcStartTime = new Date( Date.UTC( startTime.getFullYear(), startTime.getMonth(), startTime.getDate() ) ), utcEndTime = new Date( Date.UTC( endTime.getFullYear(), endTime.getMonth(), endTime.getDate() ) ), currentViewIndex = scope.currentViewIndex, rows = scope.views[ currentViewIndex ].rows, allDayEvents = scope.views[ currentViewIndex ].allDayEvents = [], oneHour = 3600000, eps = 0.016, eventSet, normalEventInRange = false; for ( hour = 0; hour < 24; hour += 1 ) { rows[ hour ].events = []; } for ( var i = 0; i < len; i += 1 ) { var event = eventSource[ i ]; var eventStartTime = new Date( event.startTime ); var eventEndTime = new Date( event.endTime ); if ( event.allDay ) { if ( eventEndTime <= utcStartTime || eventStartTime >= utcEndTime ) { continue; } else { allDayEvents.push( { event: event } ); } } else { if ( eventEndTime <= startTime || eventStartTime >= endTime ) { continue; } else { normalEventInRange = true; } var timeDiff; var timeDifferenceStart; if ( eventStartTime <= startTime ) { timeDifferenceStart = 0; } else { timeDiff = eventStartTime - startTime - ( eventStartTime.getTimezoneOffset() - startTime.getTimezoneOffset() ) * 60000; timeDifferenceStart = timeDiff / oneHour; } var timeDifferenceEnd; if ( eventEndTime >= endTime ) { timeDiff = endTime - startTime - ( endTime.getTimezoneOffset() - startTime.getTimezoneOffset() ) * 60000; timeDifferenceEnd = timeDiff / oneHour; } else { timeDiff = eventEndTime - startTime - ( eventEndTime.getTimezoneOffset() - startTime.getTimezoneOffset() ) * 60000; timeDifferenceEnd = timeDiff / oneHour; } var startIndex = Math.floor( timeDifferenceStart ); var endIndex = Math.ceil( timeDifferenceEnd - eps ); var startOffset = 0; var endOffset = 0; if ( ctrl.hourParts !== 1 ) { startOffset = Math.floor( ( timeDifferenceStart - startIndex ) * ctrl.hourParts ); endOffset = Math.floor( ( endIndex - timeDifferenceEnd ) * ctrl.hourParts ); } var displayEvent = { event: event, startIndex: startIndex, endIndex: endIndex, startOffset: startOffset, endOffset: endOffset }; eventSet = rows[ startIndex ].events; if ( eventSet ) { eventSet.push( displayEvent ); } else { eventSet = []; eventSet.push( displayEvent ); rows[ startIndex ].events = eventSet; } } } if ( normalEventInRange ) { var orderedEvents = []; for ( hour = 0; hour < 24; hour += 1 ) { if ( rows[ hour ].events ) { rows[ hour ].events.sort( <API key> ); orderedEvents = orderedEvents.concat( rows[ hour ].events ); } } if ( orderedEvents.length > 0 ) { ctrl.placeEvents( orderedEvents ); } } }; ctrl._refreshView = function () { ctrl.<API key>( scope ); }; ctrl._getTitle = function () { var startingDate = ctrl.range.startTime; return dateFilter( startingDate, ctrl.formatDayTitle ); }; ctrl._getViewData = function ( startTime ) { return { rows: createDateObjects( startTime ), allDayEvents: [] }; }; ctrl._getRange = function getRange( currentDate ) { var year = currentDate.getFullYear(), month = currentDate.getMonth(), date = currentDate.getDate(), startTime = new Date( year, month, date ), endTime = new Date( year, month, date + 1 ); return { startTime: startTime, endTime: endTime }; }; ctrl.<API key>( scope, scope.$parent.scrollCallBack( scope.$parent.scrollTo ) ); ctrl.refreshView(); } }; } ] ); angular.module("templates/rcalendar/calendar.html", []).run(["$templateCache", function($templateCache) { $templateCache.put("templates/rcalendar/calendar.html", "<div class=\"calendar-container\" ng-switch=\"calendarMode\">\n" + " <dayview ng-switch-when=\"day\"></dayview>\n" + " <monthview ng-switch-when=\"month\"></monthview>\n" + " <weekview ng-switch-when=\"week\"></weekview>\n" + "</div>"); }]); angular.module("templates/rcalendar/day.html", []).run(["$templateCache", function($templateCache) { $templateCache.put("templates/rcalendar/day.html", "<div class=\"dayview\">\n" + " <ion-slide-box class=\"dayview-slide\" on-slide-changed=\"slideChanged($index)\" does-continue=\"true\"\n" + " show-pager=\"false\" delegate-handle=\"dayview-slide\">\n" + " <ion-slide ng-repeat=\"view in views track by $index\">\n" + " <div class=\"<API key>\">\n" + " <div class=\"<API key>\" ng-bind=\"::allDayLabel\"></div>\n" + " <ion-content class=\"<API key>\" has-bouncing=\"false\" overflow-scroll=\"false\">\n" + " <table class=\"table table-bordered <API key>\">\n" + " <tbody>\n" + " <tr>\n" + " <td class=\"calendar-cell\" ng-class=\"{'calendar-event-wrap':view.allDayEvents.length>0}\"\n" + " ng-if=\"$index===currentViewIndex\" ng-style=\"{height: 25*view.allDayEvents.length+'px'}\">\n" + " <div ng-repeat=\"displayEvent in view.allDayEvents\" class=\"calendar-event\"\n" + " ng-click=\"eventSelected({event:displayEvent.event})\"\n" + " ng-style=\"{top: 25*$index+'px',width: '100%',height:'25px'}\"\n" + " ng-include=\"::<API key>\">\n" + " </div>\n" + " </td>\n" + " <td class=\"calendar-cell\" ng-if=\"$index!==currentViewIndex\">\n" + " </td>\n" + " </tr>\n" + " </tbody>\n" + " </table>\n" + " </ion-content>\n" + " </div>\n" + " <ion-content class=\"<API key>\" has-bouncing=\"false\" overflow-scroll=\"false\">\n" + " <table class=\"table table-bordered table-fixed <API key>\"\n" + " ng-if=\"$index===currentViewIndex\">\n" + " <tbody>\n" + " <tr ng-repeat=\"tm in view.rows track by $index\">\n" + " <td class=\"<API key> text-center\">\n" + " {{::tm.time | date: formatHourColumn}}\n" + " </td>\n" + " <td class=\"calendar-cell\" ng-click=\"select(tm.time, tm.events)\">\n" + " <div ng-class=\"{'calendar-event-wrap': tm.events}\" ng-if=\"tm.events\">\n" + " <div ng-repeat=\"displayEvent in tm.events\" class=\"calendar-event\"\n" + " ng-click=\"eventSelected({event:displayEvent.event})\"\n" + " ng-style=\"{top: (111*displayEvent.startOffset/hourParts)+'px', left: 100/displayEvent.overlapNumber*displayEvent.position+'%', width: 100/displayEvent.overlapNumber+'%', height: 111*(displayEvent.endIndex -displayEvent.startIndex - (displayEvent.endOffset + displayEvent.startOffset)/hourParts)+'px'}\"\n" + " ng-include=\"::<API key>\">\n" + " </div>\n" + " </div>\n" + " </td>\n" + " </tr>\n" + " </tbody>\n" + " </table>\n" + " <table class=\"table table-bordered table-fixed <API key>\"\n" + " ng-if=\"$index!==currentViewIndex\">\n" + " <tbody>\n" + " <tr ng-repeat=\"tm in view.rows track by $index\">\n" + " <td class=\"<API key> text-center\">\n" + " {{::tm.time | date: formatHourColumn}}\n" + " </td>\n" + " <td class=\"calendar-cell\">\n" + " </td>\n" + " </tr>\n" + " </tbody>\n" + " </table>\n" + " </ion-content>\n" + " </ion-slide>\n" + " </ion-slide-box>\n" + "</div>\n" + ""); }]); angular.module("templates/rcalendar/displayEvent.html", []).run(["$templateCache", function($templateCache) { $templateCache.put("templates/rcalendar/displayEvent.html", "<div class=\"<API key>\">{{displayEvent.event.title}}</div>"); }]); angular.module("templates/rcalendar/month.html", []).run(["$templateCache", function($templateCache) { $templateCache.put("templates/rcalendar/month.html", "<div>\n" + " <ion-slide-box class=\"monthview-slide\" on-slide-changed=\"slideChanged($index)\" does-continue=\"true\"\n" + " show-pager=\"false\" delegate-handle=\"monthview-slide\">\n" + " <ion-slide ng-repeat=\"view in views track by $index\">\n" + " <table ng-if=\"$index===currentViewIndex\" class=\"table table-bordered table-fixed monthview-datetable\">\n" + " <thead>\n" + " <tr>\n" + " <th ng-repeat=\"day in view.dates.slice(0,7) track by day.date\">\n" + " <small>{{::day.date | date: formatDayHeader}}</small>\n" + " </th>\n" + " </tr>\n" + " </thead>\n" + " <tbody>\n" + " <tr ng-repeat=\"row in [0,1,2,3,4,5]\">\n" + " <td ng-repeat=\"col in [0,1,2,3,4,5,6]\" ng-click=\"select(view.dates[row*7+col])\"\n" + " ng-class=\"getHighlightClass(view.dates[row*7+col])\" ng-include=\"::<API key>\">\n" + " </td>\n" + " </tr>\n" + " </tbody>\n" + " </table>\n" + " <table ng-if=\"$index!==currentViewIndex\" class=\"table table-bordered table-fixed monthview-datetable\">\n" + " <thead>\n" + " <tr class=\"text-center\">\n" + " <th ng-repeat=\"day in view.dates.slice(0,7) track by day.date\">\n" + " <small>{{::day.date | date: formatDayHeader}}</small>\n" + " </th>\n" + " </tr>\n" + " </thead>\n" + " <tbody>\n" + " <tr ng-repeat=\"row in [0,1,2,3,4,5]\">\n" + " <td ng-repeat=\"col in [0,1,2,3,4,5,6]\">{{view.dates[row*7+col].label}}\n" + " </td>\n" + " </tr>\n" + " </tbody>\n" + " </table>\n" + " </ion-slide>\n" + " </ion-slide-box>\n" + " <div ng-include=\"::<API key>\"></div>\n" + "</div>\n" + ""); }]); angular.module("templates/rcalendar/<API key>.html", []).run(["$templateCache", function($templateCache) { $templateCache.put("templates/rcalendar/<API key>.html", "{{view.dates[row*7+col].label}}"); }]); angular.module("templates/rcalendar/<API key>.html", []).run(["$templateCache", function($templateCache) { $templateCache.put("templates/rcalendar/<API key>.html", "<ion-content class=\"<API key>\" has-bouncing=\"false\" ng-show=\"showEventDetail\" overflow-scroll=\"false\">\n" + " <table class=\"table table-bordered table-striped table-fixed event-detail-table\">\n" + " <tr ng-repeat=\"event in selectedDate.events\" ng-click=\"eventSelected({event:event})\">\n" + " <td ng-if=\"!event.allDay\" class=\"<API key>\">{{::event.startTime|date: 'HH:mm'}}\n" + " -\n" + " {{::event.endTime|date: 'HH:mm'}}\n" + " </td>\n" + " <td ng-if=\"event.allDay\" class=\"<API key>\">All day</td>\n" + " <td class=\"event-detail\">{{::event.title}}</td>\n" + " </tr>\n" + " <tr ng-if=\"!selectedDate.events\">\n" + " <td class=\"no-event-label\" ng-bind=\"::noEventsLabel\"></td>\n" + " </tr>\n" + " </table>\n" + "</ion-content>"); }]); angular.module("templates/rcalendar/week.html", []).run(["$templateCache", function($templateCache) { $templateCache.put("templates/rcalendar/week.html", "<div class=\"weekview\">\n" + " <ion-slide-box class=\"weekview-slide\" on-slide-changed=\"slideChanged($index)\" does-continue=\"true\"\n" + " show-pager=\"false\" delegate-handle=\"weekview-slide\">\n" + " <ion-slide ng-repeat=\"view in views track by $index\">\n" + " <table class=\"table table-bordered table-fixed weekview-header\">\n" + " <thead>\n" + " <tr>\n" + " <th class=\"<API key>\"></th>\n" + " <th class=\"weekview-header text-center\" ng-repeat=\"dt in view.dates\" data-ng-class=\"{'day-disabled':eventPeriod.start > dt.date || toDate(eventPeriod.end) < dt.date, 'today': isToday(dt.date), 'days-pased':isPassedOrFuture(dt.date)==='past', 'future':isPassedOrFuture(dt.date)==='future' }\" >\n" + " <p>{{::dt.date| date:<API key>}}\n" + " <span>{{::dt.date| date: 'd'}}</span>\n" + " {{::dt.date| date: 'MMMM'}}\n" + " </p>\n" + " </th>\n" + " </tr>\n" + " </thead>\n" + " </table>\n" + " <div ng-if=\"$index===currentViewIndex\">\n" + " <div class=\"<API key>\">\n" + " <div class=\"<API key>\" ng-bind=\"::allDayLabel\">\n" + " </div>\n" + " <ion-content class=\"<API key>\" has-bouncing=\"false\" overflow-scroll=\"false\">\n" + " <table class=\"table table-fixed <API key>\">\n" + " <tbody>\n" + " <tr>\n" + " <td ng-repeat=\"day in view.dates track by day.date\" data-ng-class=\"{'day-disabled':eventPeriod.start > day.date || toDate(eventPeriod.end) < day.date}\" class=\"calendar-cell\">\n" + " <div ng-class=\"{'calendar-event-wrap': day.events}\" ng-if=\"day.events\"\n" + " ng-style=\"{height: 56*day.events.length+'px'}\">\n" + " <div ng-repeat=\"displayEvent in day.events\" class=\"calendar-event\"\n" + " ng-click=\"eventSelected({event:displayEvent.event})\"\n" + " ng-style=\"{top: 56*displayEvent.position+'px', width: 100*(displayEvent.<API key>.startIndex)+'%', height: '56px'}\"\n" + " ng-include=\"::<API key>\">\n" + " </div>\n" + " </div>\n" + " </td>\n" + " </tr>\n" + " </tbody>\n" + " </table>\n" + " </ion-content>\n" + " </div>\n" + " <ion-content class=\"<API key>\" has-bouncing=\"false\" overflow-scroll=\"false\">\n" + " <table class=\"table table-bordered table-fixed <API key>\">\n" + " <tbody>\n" + " <tr ng-repeat=\"row in view.rows track by $index\">\n" + " <td class=\"<API key> text-center\" id=\"hour-{{::row[0].time | date: formatHourColumn}}\">\n" + " {{::row[0].time | date: formatHourColumn}}:00\n" + " </td>\n" + " <td ng-repeat=\"tm in row track by tm.time\" class=\"calendar-cell\" data-ng-class=\"{'day-disabled':eventPeriod.start > tm.time || toDate(eventPeriod.end) < tm.time}\" ng-click=\"select(tm.time, tm.events)\">\n" + " <div ng-class=\"{'calendar-event-wrap': tm.events}\" ng-if=\"tm.events\">\n" + " <div ng-repeat=\"displayEvent in tm.events\" class=\"calendar-event\"\n" + " ng-click=\"eventSelected({event:displayEvent.event})\"\n" + " ng-style=\"{top: (111*displayEvent.startOffset/hourParts)+'px',left: 100/displayEvent.overlapNumber*displayEvent.position+'%', width: 100/displayEvent.overlapNumber+'%', height: 111*(displayEvent.endIndex -displayEvent.startIndex - (displayEvent.endOffset + displayEvent.startOffset)/hourParts)+'px'}\"\n" + " ng-include=\"::<API key>\">\n" + " </div>\n" + " </div>\n" + " </td>\n" + " </tr>\n" + " </tbody>\n" + " </table>\n" + " </ion-content>\n" + " </div>\n" + " <div ng-if=\"$index!==currentViewIndex\">\n" + " <div class=\"<API key>\">\n" + " <div class=\"<API key>\" ng-bind=\"::allDayLabel\"></div>\n" + " <ion-content class=\"<API key>\" has-bouncing=\"false\" overflow-scroll=\"false\">\n" + " <table class=\"table table-fixed <API key>\">\n" + " <tbody>\n" + " <tr>\n" + " <td ng-repeat=\"day in view.dates track by day.date\" class=\"calendar-cell\">\n" + " </td>\n" + " </tr>\n" + " </tbody>\n" + " </table>\n" + " </ion-content>\n" + " </div>\n" + " <ion-content class=\"<API key>\" has-bouncing=\"false\" overflow-scroll=\"false\">\n" + " <table class=\"table table-bordered table-fixed <API key>\">\n" + " <tbody>\n" + " <tr ng-repeat=\"row in view.rows track by $index\">\n" + " <td class=\"<API key> text-center\" id=\"hour-{{::row[0].time | date: formatHourColumn}}\">\n" + " {{::row[0].time | date: formatHourColumn}}:00\n" + " </td>\n" + " <td ng-repeat=\"tm in row track by tm.time\" class=\"calendar-cell\">\n" + " </td>\n" + " </tr>\n" + " </tbody>\n" + " </table>\n" + " </ion-content>\n" + " </div>\n" + " </ion-slide>\n" + " </ion-slide-box>\n" + "</div>\n" + ""); }]);
package strlit import ( "testing" ) func <API key>(t *testing.T) { var err error = <API key>{} // THIS IS WHAT ACTUALLY MATTERS! if nil == err { t.Error("This should never happen.") } } func <API key>(t *testing.T) { var complainer NotLiteral = <API key>{} // THIS IS WHAT ACTUALLY MATTERS! if nil == complainer { t.Error("This should never happen.") } }
# Change Log Notable changes for the [gmusicapi-wrapper](https: [Commits](https://github.com/thebigmunch/gmusicapi-wrapper/compare/0.5.1...0.5.2) Fixed * Update album artist field name for mutagen change. [Commits](https://github.com/thebigmunch/gmusicapi-wrapper/compare/0.5.0...0.5.1) Fixed * Fix undefined variable ('dirname') in MusicManagerWrapper._download. [Commits](https://github.com/thebigmunch/gmusicapi-wrapper/compare/0.4.0...0.5.0) Added * Add <API key> utility function. Changed * Refactor <API key> utility function. [Commits](https://github.com/thebigmunch/gmusicapi-wrapper/compare/0.3.0...0.4.0) Added * Add is_authenticated property to wrapper classes. * Add is_subscribed property to MobileClientWrapper. * Add exception handling to local file handlers. Changed * A lot of refactoring. * Check all metadata field values for local files when filtering. Mutagen returns list values; previously only the first item in the list was checked. * Use wrapt module for decorators. * Change return of MusicManagerWrapper.download method. Fixed * Fix code error in MusicManagerWrapper.upload that caused an error on failed uploads. * Fix %suggested% in template assigning same name to each song on multiple song downloads. [Commits](https://github.com/thebigmunch/gmusicapi-wrapper/compare/0.2.1...0.3.0) Added * Add get_local_playlists method to wrapper base class. * Add <API key> method to wrapper base class. * Add paramaters to MusicManagerWrapper.get_google_songs to enable/disable uploaded/purchased songs from being returned. * Add get_google_playlist method to MobileClientWrapper. * Add <API key> method to MobileClientWrapper. * Add exclude_filepaths utility function. * Add <API key> utility function. Removed * Remove exclude_path utility function. Changed * Change log parameter to enable_logging in login methods. * Change return value of MusicManagerWrapper.upload method. * Change signature of walk_depth utility function. * Remove formats parameter from get_local_* methods in favor of top-level constants. * Remove recursive parameter from get_local_* methods. max-depth=0 serves the same purpose. [Commits](https://github.com/thebigmunch/gmusicapi-wrapper/compare/0.2.0...0.2.1) Fixed * Fix delete on success check. [Commits](https://github.com/thebigmunch/gmusicapi-wrapper/compare/0.1.0...0.2.0) Added * Python 3 support. Remove * Python 2 support. Changed * Port to Python 3. Python 2 is no longer supported. * Add Google Music id to output for songs that already exist. Fixed * Handle split number metadata fields for templates. [Commits](https://github.com/thebigmunch/gmusicapi-wrapper/compare/<SHA1-like>...0.1.0) * First package release for PyPi.
#[doc = "Register `GPR1` reader"] pub struct R(crate::R<GPR1_SPEC>); impl core::ops::Deref for R { type Target = crate::R<GPR1_SPEC>; #[inline(always)] fn deref(&self) -> &Self::Target { &self.0 } } impl From<crate::R<GPR1_SPEC>> for R { #[inline(always)] fn from(reader: crate::R<GPR1_SPEC>) -> Self { R(reader) } } #[doc = "Register `GPR1` writer"] pub struct W(crate::W<GPR1_SPEC>); impl core::ops::Deref for W { type Target = crate::W<GPR1_SPEC>; #[inline(always)] fn deref(&self) -> &Self::Target { &self.0 } } impl core::ops::DerefMut for W { #[inline(always)] fn deref_mut(&mut self) -> &mut Self::Target { &mut self.0 } } impl From<crate::W<GPR1_SPEC>> for W { #[inline(always)] fn from(writer: crate::W<GPR1_SPEC>) -> Self { W(writer) } } #[doc = "Field `DAT` reader - User Data"] pub struct DAT_R(crate::FieldReader<u32, u32>); impl DAT_R { pub(crate) fn new(bits: u32) -> Self { DAT_R(crate::FieldReader::new(bits)) } } impl core::ops::Deref for DAT_R { type Target = crate::FieldReader<u32, u32>; #[inline(always)] fn deref(&self) -> &Self::Target { &self.0 } } #[doc = "Field `DAT` writer - User Data"] pub struct DAT_W<'a> { w: &'a mut W, } impl<'a> DAT_W<'a> { #[doc = r"Writes raw bits to the field"] #[inline(always)] pub unsafe fn bits(self, value: u32) -> &'a mut W { self.w.bits = (self.w.bits & !0xffff_ffff) | (value as u32 & 0xffff_ffff); self.w } } impl R { #[doc = "Bits 0:31 - User Data"] #[inline(always)] pub fn dat(&self) -> DAT_R { DAT_R::new((self.bits & 0xffff_ffff) as u32) } } impl W { #[doc = "Bits 0:31 - User Data"] #[inline(always)] pub fn dat(&mut self) -> DAT_W { DAT_W { w: self } } #[doc = "Writes raw bits to the register."] #[inline(always)] pub unsafe fn bits(&mut self, bits: u32) -> &mut Self { self.0.bits(bits); self } } pub struct GPR1_SPEC; impl crate::RegisterSpec for GPR1_SPEC { type Ux = u32; } #[doc = "`read()` method returns [gpr1::R](R) reader structure"] impl crate::Readable for GPR1_SPEC { type Reader = R; } #[doc = "`write(|w| ..)` method takes [gpr1::W](W) writer structure"] impl crate::Writable for GPR1_SPEC { type Writer = W; } #[doc = "`reset()` method sets GPR1 to value 0"] impl crate::Resettable for GPR1_SPEC { #[inline(always)] fn reset_value() -> Self::Ux { 0 } }
#!/bin/sh set -e echo "mkdir -p ${<API key>}/${<API key>}" mkdir -p "${<API key>}/${<API key>}" SWIFT_STDLIB_PATH="${DT_TOOLCHAIN_DIR}/usr/lib/swift/${PLATFORM_NAME}" install_framework() { local source="${BUILT_PRODUCTS_DIR}/Pods-Ravelry_Tests/$1" local destination="${<API key>}/${<API key>}" if [ -L "${source}" ]; then echo "Symlinked..." source=$(readlink "${source}") fi # use filter instead of exclude so missing patterns dont' throw errors echo "rsync -av --filter "- CVS/" --filter "- .svn/" --filter "- .git/" --filter "- .hg/" --filter "- Headers/" --filter "- PrivateHeaders/" --filter "- Modules/" ${source} ${destination}" rsync -av --filter "- CVS/" --filter "- .svn/" --filter "- .git/" --filter "- .hg/" --filter "- Headers/" --filter "- PrivateHeaders/" --filter "- Modules/" "${source}" "${destination}" # Resign the code if required by the build settings to avoid unstable apps if [ "${<API key>}" == "YES" ]; then code_sign "${destination}/$1" fi # Embed linked Swift runtime libraries local basename basename=$(echo $1 | sed -E s/\\..+// && exit ${PIPESTATUS[0]}) local swift_runtime_libs swift_runtime_libs=$(xcrun otool -LX "${<API key>}/${<API key>}/$1/${basename}" | grep --color=never @rpath/libswift | sed -E s/@rpath\\/\(.+dylib\).*/\\1/g | uniq -u && exit ${PIPESTATUS[0]}) for lib in $swift_runtime_libs; do echo "rsync -auv \"${SWIFT_STDLIB_PATH}/${lib}\" \"${destination}\"" rsync -auv "${SWIFT_STDLIB_PATH}/${lib}" "${destination}" if [ "${<API key>}" == "YES" ]; then code_sign "${destination}/${lib}" fi done } # Signs a framework with the provided identity code_sign() { # Use the current code_sign_identitiy echo "Code Signing $1 with Identity ${<API key>}" echo "/usr/bin/codesign --force --sign ${<API key>} --preserve-metadata=identifier,entitlements $1" /usr/bin/codesign --force --sign ${<API key>} --preserve-metadata=identifier,entitlements "$1" } if [[ "$CONFIGURATION" == "Debug" ]]; then install_framework 'Passenger.framework' install_framework 'Wildcard.framework' fi if [[ "$CONFIGURATION" == "Release" ]]; then install_framework 'Passenger.framework' install_framework 'Wildcard.framework' fi
Pattern: Disabled temporary file logging for Google SQL Issue: - ## Description **Resolution**: Enable temporary file logging for all files. ## Examples Example of **incorrect** code: terraform resource "<API key>" "db" { name = "db" database_version = "POSTGRES_12" region = "us-central1" } Example of **correct** code: terraform resource "<API key>" "db" { name = "db" database_version = "POSTGRES_12" region = "us-central1" settings { database_flags { name = "log_temp_files" value = "0" } } }
import os basedir = os.path.abspath(os.path.dirname(__file__)) # if you have postgres use this uri: <API key> = "postgresql://rehub:rehub@localhost/rehub" # if you want to use sqlite, use this one: # <API key> = 'sqlite:///' + os.path.join(basedir, 'rehub.db') <API key> = os.path.join(basedir, 'db_repository') DEBUG=True DATABASE=os.path.join(basedir, 'rehub.db') USERNAME='admin' PASSWORD='admin' SECRET_KEY='$cippalippa!' CSRF_ENABLED=True
<!DOCTYPE html> <html lang="vi"> <head> <meta charset="utf-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1"> <title>QUản Lý Phòng Khám Trí Hùng</title> <!-- Bootstrap Core CSS --> <link href="<?php echo MY_URL; ?>/GUI/bower_components/bootstrap/dist/css/bootstrap.min.css" rel="stylesheet"> <!-- MetisMenu CSS --> <link href="<?php echo MY_URL; ?>/GUI/bower_components/metisMenu/dist/metisMenu.min.css" rel="stylesheet"> <!-- Custom CSS --> <link href="<?php echo MY_URL; ?>/GUI/dist/css/sb-admin-2.css" rel="stylesheet"> <!-- Custom Fonts --> <link href="<?php echo MY_URL; ?>/GUI/bower_components/font-awesome/css/font-awesome.min.css" rel="stylesheet" type="text/css"> <!-- DataTables CSS --> <link href="<?php echo MY_URL; ?>/GUI/bower_components/datatables-plugins/integration/bootstrap/3/dataTables.bootstrap.css" rel="stylesheet"> <!-- DataTables Responsive CSS --> <link href="<?php echo MY_URL; ?>/GUI/bower_components/<API key>/css/dataTables.responsive.css" rel="stylesheet"> </head> <body> <div id="wrapper"> <!-- Navigation --> <nav class="navbar navbar-default navbar-static-top" role="navigation" style="margin-bottom: 0"> <div class="navbar-header"> <button type="button" class="navbar-toggle" data-toggle="collapse" data-target=".navbar-collapse"> <span class="sr-only">Toggle navigation</span> <span class="icon-bar"></span> <span class="icon-bar"></span> <span class="icon-bar"></span> </button> <a class="navbar-brand" href="<?php echo MY_URL; ?>">Quản Lý Phòng Khám Trí Hùng</a> </div> <!-- /.navbar-header --> <ul class="nav navbar-top-links navbar-right"> <!-- /.dropdown --> <li class="dropdown"> <a class="dropdown-toggle" data-toggle="dropdown" href=" <i class="fa fa-user fa-fw"></i> <i class="fa fa-caret-down"></i> </a> <ul class="dropdown-menu dropdown-user"> <li><a href=" </li> <li class="divider"></li> <li><a href="login.html"><i class="fa fa-sign-out fa-fw"></i> Đăng Xuất</a> </li> </ul> <!-- /.dropdown-user --> </li> <!-- /.dropdown --> </ul> <!-- /.navbar-top-links --> <div class="navbar-default sidebar" role="navigation"> <div class="sidebar-nav navbar-collapse"> <ul class="nav" id="side-menu"> <li class="sidebar-search"> <div class="input-group custom-search-form"> <input type="text" class="form-control" placeholder="Search..."> <span class="input-group-btn"> <button class="btn btn-default" type="button"> <i class="fa fa-search"></i> </button> </span> </div> <!-- /input-group --> </li> <li> <a href="<?php echo MY_URL; ?>"><i class="fa fa-dashboard fa-fw"></i> Dashboard</a> </li> <li> <a href=" <ul class="nav nav-second-level"> <li> <a href="<?php echo MY_URL; ?>/BLL/benhnhan/ListBN.php">Danh Sách Bệnh Nhân</a> </li> <li> <a href="<?php echo MY_URL; ?>/BLL/benhnhan/AddBN.php">Thêm Bệnh Nhân</a> </li> </ul> <!-- /.nav-second-level --> </li> <li> <a href=" <ul class="nav nav-second-level"> <li> <a href="<?php echo MY_URL; ?>/BLL/phieukham/ListPK.php">Danh Sách Phiếu Khám</a> </li> <li> <a href="<?php echo MY_URL; ?>/BLL/phieukham/AddPK.php">Thêm Phiếu Khám</a> </li> </ul> <!-- /.nav-second-level --> </li> <li> <a href=" <ul class="nav nav-second-level"> <li> <a href="<?php echo MY_URL; ?>/BLL/thuoc/ListThuoc.php">Danh Sách Thuốc</a> </li> <li> <a href="<?php echo MY_URL; ?>/BLL/thuoc/AddThuoc.php">Thêm Thuốc</a> </li> </ul> <!-- /.nav-second-level --> </li> <li> <a href=" <ul class="nav nav-second-level"> <li> <a href="<?php echo MY_URL; ?>/BLL/toathuoc/ListToaThuoc.php">Danh Sách Toa Thuốc</a> </li> <li> <a href="<?php echo MY_URL; ?>/BLL/toathuoc/AddToaThuoc.php">Lập Toa Thuốc</a> </li> </ul> <!-- /.nav-second-level --> </li> <li> <a href=" <ul class="nav nav-second-level"> <li> <a href="<?php echo MY_URL; ?>/BLL/chitiettoathuoc/ListCTTT.php">Danh Sách Chi Tiết Toa Thuốc</a> </li> <li> <a href="<?php echo MY_URL; ?>/BLL/chitiettoathuoc/AddCTTT.php">Lập Chi Tiết Toa Thuốc</a> </li> </ul> <!-- /.nav-second-level --> </li> <li> <a href=" <ul class="nav nav-second-level"> <li> <a href="<?php echo MY_URL; ?>/BLL/hoadon/ListHoaDon.php">Danh Sách Hóa Đơn</a> </li> <li> <a href="<?php echo MY_URL; ?>/BLL/hoadon/AddHoaDon.php">Lập Hóa Đơn</a> </li> </ul> <!-- /.nav-second-level --> </li> <li> <a href=" <ul class="nav nav-second-level"> <li> <a href="<?php echo MY_URL; ?>/BLL/baocao/DoanhThu.php">Doanh Thu</a> </li> </ul> <!-- /.nav-second-level --> </li> </ul> </div> <!-- /.sidebar-collapse --> </div> <!-- /.navbar-static-side --> </nav> <!-- Page Content --> <div id="page-wrapper"> <div class="container-fluid"> <div class="row"> <div class="col-lg-12"> <h1 class="page-header"><small>Sửa </small> Phiếu Khám </h1> </div> <!-- /.col-lg-12 --> <div class="col-lg-7" style="padding-bottom:120px;"> <?php if (isset($result)) echo '<div class="alert alert-danger alert-dismissible" role="alert"><button type="button" class="close" data-dismiss="alert" aria-label="Close"><span aria-hidden="true">&times;</span></button><strong>Cảnh báo!</strong> '.$result.'</div>'; ?> <form action="" method="POST"> <div class="form-group"> <label>Mã phiếu khám</label> <input type="text" maxlength="5" Class="form-control" name="MaPK" style="width: 40%" value="<?php echo ((isset($_POST['MaPK'])) ? $_POST['MaPK'] : $pk['MAPK']); ?>" readonly tabindex="1" required/> </div> <div class="form-group"> <label>Bệnh nhân</label> <select name="MaBN" class="form-control" style="width: 50%;" readonly tabindex="2" required> <?php foreach ($ListBN as $bn){ ?> <option value="<?php echo $bn['MABN']; ?>" <?php echo (($pk['MABN']==$bn['MABN']) ? 'selected' : ''); ?>> <?php echo $bn['MABN']; ?> - <?php echo $bn['HOTEN']; ?> </option> <?php } ?> </select> </div> <div class="form-group"> <label>Ngày khám</label> <input type="date" name="NgayKham" Class="form-control" style="width: 50%" value="<?php echo ((isset($_POST['NgayKham'])) ? $_POST['NgayKham'] : $pk['NGAYKHAM']); ?>" tabindex="3" required /> </div> <div class="form-group"> <label>Số thứ tự</label> <input type="number" maxlength="5" id="sdt" Class="form-control" name="STT" style="width: 40%" value="<?php echo ((isset($_POST['STT'])) ? $_POST['STT'] : $pk['STT']); ?>" tabindex="4" required/> </div> <div class="form-group"> <label>Triệu chứng</label> <textarea name="TrieuChung" Class="form-control" rows="5" style="width: 80%" tabindex="5" required><?php echo ((isset($_POST['TrieuChung'])) ? $_POST['TrieuChung'] : $pk['TRIEUCHUNG']); ?></textarea> </div> <div class="form-group"> <label>Chuẩn đoán</label> <textarea name="ChuanDoan" Class="form-control" rows="5" style="width: 80%" tabindex="6" required><?php echo ((isset($_POST['ChuanDoan'])) ? $_POST['ChuanDoan'] : $pk['CHUANDOAN']); ?></textarea> </div> <div class="modal-footer"> <input type="submit" class="btn btn-success" name="btnEditPK" value="Xác nhận" tabindex="7" required/> <input type="reset" class="btn btn-primary" value="Làm mới" /> </div> <form> </div> </div> <!-- /.row --> </div> <!-- /.container-fluid --> </div> <!-- /#page-wrapper --> </div> <!-- /#wrapper --> <!-- jQuery --> <script src="<?php echo MY_URL; ?>/GUI/bower_components/jquery/dist/jquery.min.js"></script> <!-- Bootstrap Core JavaScript --> <script src="<?php echo MY_URL; ?>/GUI/bower_components/bootstrap/dist/js/bootstrap.min.js"></script> <!-- Metis Menu Plugin JavaScript --> <script src="<?php echo MY_URL; ?>/GUI/bower_components/metisMenu/dist/metisMenu.min.js"></script> <!-- Custom Theme JavaScript --> <script src="<?php echo MY_URL; ?>/GUI/dist/js/sb-admin-2.js"></script> <!-- DataTables JavaScript --> <script src="<?php echo MY_URL; ?>/GUI/bower_components/DataTables/media/js/jquery.dataTables.min.js"></script> <script src="<?php echo MY_URL; ?>/GUI/bower_components/datatables-plugins/integration/bootstrap/3/dataTables.bootstrap.min.js"></script> <!-- Page-Level Demo Scripts - Tables - Use for reference --> <script> $(document).ready(function() { $('#dataTables-example').DataTable({ responsive: true }); }); </script> <script type="text/javascript"> $(document).ready(function() { $('#sdt').blur(function(e) { if (validatePhone('sdt')) { sdt.setCustomValidity(''); } else { sdt.setCustomValidity("Số thứ tự không hợp lệ"); } }); }); function validatePhone(sdt) { var sdt = document.getElementById(sdt).value; var filter = /^[0-9-+]+$/; if (filter.test(sdt)) { return true; } else { return false; } } </script> </body> </html>
package org.melvinwm.circlefractal.javafx.drawer; import static org.junit.jupiter.api.Assertions.assertThrows; import java.util.function.Consumer; import org.junit.jupiter.api.Test; public class <API key> { private final static double centerX = 100; private final static double centerY = 100; @Test public void validInitialization() { final int validIterationCount = 5; final int validDivisionFactor = 2; final double <API key> = 30; final double basicCutOff = 0.01; // Testing valid iteration counts. { for (int validIC : new int[] { 0, 1, 2, 5, 11 }) { new <API key>(centerX, centerY, validIC, <API key>, validDivisionFactor, basicCutOff); } } // Testing valid division factors. { for (int validDF : new int[] { 2, 3, 5, 10 }) { new <API key>(centerX, centerY, validIterationCount, <API key>, validDF, basicCutOff); } } // Testing valid maximum distance and cut-off combinations. { final double[] cutOffs = new double[] { 0.0, 0.01, 0.0, 40.0 }; final double[] maximumDistances = new double[] { 2.0, 2.0, 500.0, 50.0 }; for (int i = 0; i < cutOffs.length; i++) { final int ii = i; new <API key>(centerX, centerY, validIterationCount, maximumDistances[ii], validDivisionFactor, cutOffs[ii]); } } } @Test public void <API key>() { final int validIterationCount = 5; final int validDivisionFactor = 2; final double <API key> = 30; final double basicCutOff = 0.01; // Testing invalid iteration counts. { for (int invalidIC : new int[] { -100, -1 }) { assertThrows(<API key>.class, () -> new <API key>(centerX, centerY, invalidIC, <API key>, validDivisionFactor, basicCutOff)); } } // Testing invalid division factors. { for (int invalidDF : new int[] { -1, 0, 1 }) { assertThrows(<API key>.class, () -> new <API key>(centerX, centerY, validIterationCount, <API key>, invalidDF, basicCutOff)); } } // Testing invalid maximum distance and cut-off combinations. { final double[] cutOffs = new double[] { 0.0, 10.0, -1.0, -1.0 }; final double[] maximumDistances = new double[] { 0.0, 10.0, -2.0, 10.0 }; for (int i = 0; i < cutOffs.length; i++) { final int ii = i; assertThrows(<API key>.class, () -> new <API key>(centerX, centerY, validIterationCount, maximumDistances[ii], validDivisionFactor, cutOffs[ii])); } } } @Test public void <API key>() { // Test for a few different points. final Consumer<<API key>> testFun = (<API key> calc) -> { for (int x = -100; x <= 100; x += 100) { for (int y = -100; y <= 100; y += 100) { calc.getColor(x, y); } } }; testFun.accept(new <API key>(centerX, centerY, 2, 50.0, 2, 0.0)); testFun.accept(new <API key>(centerX, centerY, 2, 50.0, 2, 0.01)); testFun.accept(new <API key>(centerX, centerY, 2, 50.0, 2, 0.1)); testFun.accept(new <API key>(centerX, centerY, 2, 10.0, 2, 0.1)); testFun.accept(new <API key>(centerX, centerY, 0, 10.0, 2, 0.1)); testFun.accept(new <API key>(centerX, centerY, 11, 10.0, 2, 0.1)); testFun.accept(new <API key>(centerX, centerY, 5, 10.0, 3, 0.1)); testFun.accept(new <API key>(centerX, centerY, 5, 10.0, 10, 0.1)); testFun.accept(new <API key>(centerX, centerY, 5, 20.0, 10, 10.0)); } }
package gipf; import java.sql.Connection; import java.sql.SQLException; import java.util.List; import java.util.Optional; public class Joueur { /** * Construit un joueur avec tous ses attributs * * @param login * @param email * @param password * @param elo */ public Joueur(String login, String email, String password, double elo) { super(); throw new NotImplementedError(); } /** * @return le score ELO du joueur */ public double getElo() { throw new NotImplementedError(); } public void addElo(double elo) { throw new NotImplementedError(); } /** * @return le login du joueur */ public String getLogin() { throw new NotImplementedError(); } /** * Modifie le mot de passe du joueur * * @param s */ public void setPassword(String s) { throw new NotImplementedError(); } /** * Modifie l'adresse mail du joueur * * @param s */ public void setEmail(String s) { throw new NotImplementedError(); } @Override public String toString() { return String.format("Joueur [login=%s, elo=%.0f]", getLogin(), getElo()); } /** * Sauvegarde un joueur (ELO, mot de passe et email) * * @param con * @throws SQLException */ public void save(Connection con) throws SQLException { throw new NotImplementedError(); } public static Joueur inscrire(String login, String password, String email, Connection con) throws SQLException, <API key> { throw new NotImplementedError(); } public static Optional<Joueur> load(String login, Connection con) throws SQLException { throw new NotImplementedError(); } public static List<Joueur> loadByElo(Connection con) throws SQLException { throw new NotImplementedError(); } /** * @return l'email du joueur */ public String getEmail() { throw new NotImplementedError(); } public boolean checkPassword(String p) { throw new NotImplementedError(); } @Override public boolean equals(Object o) { if (o instanceof Joueur) { return getLogin().equals(((Joueur) o).getLogin()); } else { return false; } } @Override public int hashCode() { return getLogin().hashCode(); } }
<?php namespace Star\Component\State\Callbacks; use Star\Component\State\<API key>; use Star\Component\State\StateMachine; use Webmozart\Assert\Assert; final class <API key> implements TransitionCallback { /** * @var string */ private $to; /** * @param string $to */ public function __construct($to) { Assert::string($to); $this->to = $to; } /** * @param mixed $context * @param StateMachine $machine */ public function beforeStateChange($context, StateMachine $machine) { } /** * @param mixed $context * @param StateMachine $machine */ public function afterStateChange($context, StateMachine $machine) { } /** * @param <API key> $exception * @param mixed $context * @param StateMachine $machine * * @return string */ public function onFailure(<API key> $exception, $context, StateMachine $machine) { return $this->to; } }
import * as mobx from 'mobx'; import Task from './Task'; class TaskList { constructor(title = 'New Task List', tasks = []) { mobx.extendObservable(this, { title: title, tasks: tasks, sortTasks: mobx.action.bound(function (priorityTask = null) { if (priorityTask) { // no task has same index as priority for (let i = 0; i < this.tasks.length; i++) { if (this.tasks[i] != priorityTask && this.tasks[i].index == priorityTask.index) { if (i < (this.tasks.length - 1)) { this.tasks[i].index++; } else { this.tasks[i].index } } } } // no task has same indexes for (let i = 0; i < (this.tasks.length - 1); i++) { if (this.tasks[i].index == this.tasks[i+1].index) { this.tasks[i+1].index++; i } } // sort tasks let sortedTasks = this.tasks.sort((task1, task2) => { if(task1.index < task2.index) { return -1; } else if (task1.index > task2.index) { return 1; } return 0; }); // reindex for (let i = 0; i < sortedTasks.length; i++) { sortedTasks[i].index = i; } this.tasks = sortedTasks; }), newTask: mobx.action.bound(function () { let maxIndex = this.tasks.reduce((maxIndex, task) => { return maxIndex < task.index ? task.index : maxIndex; }, -1); this.tasks.push(new Task(maxIndex+1)); this.sortTasks(); }), deleteTask: mobx.action.bound(function (task) { let newTasks = []; for (let i = 0; i < this.tasks.length; i++) { if (this.tasks[i] != task) { newTasks.push(this.tasks[i]); } } this.tasks = mobx.observable(newTasks); this.sortTasks(); }) }) } } export default TaskList;
require 'date' require 'bigdecimal' require 'bigdecimal/util' require 'active_support/core_ext/big_decimal/conversions' require 'active_support/core_ext/string/conversions' module ActiveGraph::Shared class Boolean; end module TypeConverters CONVERTERS = {} class Boolean; end class BaseConverter class << self def converted?(value) value.is_a?(db_type) end end def supports_array? false end end class IntegerConverter < BaseConverter NEO4J_LARGEST_INT = 9223372036854775807 NEO4J_SMALLEST_INT = -9223372036854775808 class << self def converted?(value) false end def convert_type Integer end def db_type Integer end def to_db(value) val = value.to_i val > NEO4J_LARGEST_INT || val < NEO4J_SMALLEST_INT ? val.to_s : val end def to_ruby(value) value.to_i end end end class FloatConverter < BaseConverter class << self def convert_type Float end def db_type Float end def to_db(value) value.to_f end alias to_ruby to_db end end class BigDecimalConverter < BaseConverter class << self def convert_type BigDecimal end def db_type String end def to_db(value) case value when Rational value.to_f.to_d when respond_to?(:to_d) value.to_d else BigDecimal(value.to_s) end.to_s end def to_ruby(value) value.to_d end end end class StringConverter < BaseConverter class << self def convert_type String end def db_type String end def to_db(value) value.to_s end alias to_ruby to_db end end # Converts Java long types to Date objects. Must be timezone UTC. class DateConverter < BaseConverter class << self def convert_type Date end def db_type Date end def to_ruby(value) value.respond_to?(:to_date) ? value.to_date : Time.at(value).utc.to_date end alias to_db to_ruby end end # Converts DateTime objects to and from Java long types. Must be timezone UTC. class DateTimeConverter < BaseConverter class << self def convert_type DateTime end def db_type Integer end # Converts the given DateTime (UTC) value to an Integer. # DateTime values are automatically converted to UTC. def to_db(value) value = value.new_offset(0) if value.respond_to?(:new_offset) args = [value.year, value.month, value.day] args += (value.class == Date ? [0, 0, 0] : [value.hour, value.min, value.sec]) Time.utc(*args).to_i end def to_ruby(value) return value if value.is_a?(DateTime) t = case value when Time return value.to_datetime.utc when Integer Time.at(value).utc when String return value.to_datetime else fail ArgumentError, "Invalid value type for DateType property: #{value.inspect}" end DateTime.civil(t.year, t.month, t.day, t.hour, t.min, t.sec) end end end class TimeConverter < BaseConverter class << self def convert_type Time end def db_type Time end def to_ruby(value) value.respond_to?(:to_time) ? value.to_time : Time.at(value).utc end alias to_db to_ruby end end class BooleanConverter < BaseConverter FALSE_VALUES = %w(n N no No NO false False FALSE off Off OFF f F).to_set class << self def converted?(value) converted_values.include?(value) end def converted_values [true, false] end def db_type ActiveGraph::Shared::Boolean end alias convert_type db_type def to_db(value) return false if FALSE_VALUES.include?(value) case value when TrueClass, FalseClass value when Numeric, /^\-?[0-9]/ !value.to_f.zero? else value.present? end end alias to_ruby to_db end end # Converts hash to/from YAML class YAMLConverter < BaseConverter class << self def convert_type Hash end def db_type String end def to_db(value) Psych.dump(value) end def to_ruby(value) value.is_a?(Hash) ? value : Psych.load(value) end end end # Converts hash to/from JSON class JSONConverter < BaseConverter class << self def converted?(_value) false end def convert_type JSON end def db_type String end def to_db(value) value.to_json end def to_ruby(value) JSON.parse(value, quirks_mode: true) end end end class EnumConverter def initialize(enum_keys, options) @enum_keys = enum_keys @options = options return unless @options[:case_sensitive].nil? @options[:case_sensitive] = ActiveGraph::Config.<API key> end def converted?(value) value.is_a?(db_type) end def supports_array? true end def db_type Integer end def convert_type Symbol end def to_ruby(value) @enum_keys.key(value) unless value.nil? end alias call to_ruby def to_db(value) if value.is_a?(Array) value.map(&method(:to_db)) elsif @options[:case_sensitive] @enum_keys[value.to_s.to_sym] || fail(ActiveGraph::Shared::Enum::<API key>, 'Value passed to an enum property must match one of the enum keys') else @enum_keys[value.to_s.downcase.to_sym] || fail(ActiveGraph::Shared::Enum::<API key>, 'Case-insensitive (downcased) value passed to an enum property must match one of the enum keys') end end end class ObjectConverter < BaseConverter class << self def convert_type Object end def to_ruby(value) value end end end # Modifies a hash's values to be of types acceptable to Neo4j or matching what the user defined using `type` in property definitions. # @param [ActiveGraph::Shared::Property] obj A node or rel that mixes in the Property module # @param [Symbol] medium Indicates the type of conversion to perform. # @param [Hash] properties A hash of symbol-keyed properties for conversion. def <API key>(obj, medium, properties) direction = medium == :ruby ? :to_ruby : :to_db properties.to_h.each_pair do |key, value| next if skip_conversion?(obj, key, value) converted_value = convert_property(key, value, direction) if properties.is_a?(ActiveGraph::AttributeSet) properties.write_cast_value(key, converted_value) else properties[key] = converted_value end end end # Converts a single property from its current format to its db- or Ruby-expected output type. # @param [Symbol] key A property declared on the model # @param value The value intended for conversion # @param [Symbol] direction Either :to_ruby or :to_db, indicates the type of conversion to perform def convert_property(key, value, direction) converted_property(primitive_type(key.to_sym), value, direction) end def supports_array?(key) type = primitive_type(key.to_sym) type.respond_to?(:supports_array?) && type.supports_array? end def typecaster_for(value) ActiveGraph::Shared::TypeConverters.typecaster_for(value) end def typecast_attribute(typecaster, value) ActiveGraph::Shared::TypeConverters.typecast_attribute(typecaster, value) end private def converted_property(type, value, direction) return nil if value.nil? CONVERTERS[type] || type.respond_to?(:db_type) ? TypeConverters.to_other(direction, value, type) : value end # If the attribute is to be typecast using a custom converter, which converter should it use? If no, returns the type to find a native serializer. def primitive_type(attr) case when <API key>.include?(attr) <API key>[attr] when <API key>.include?(attr) <API key>[attr] else <API key>(attr) end end # Returns true if the property isn't defined in the model or if it is nil def skip_conversion?(obj, attr, value) value.nil? || !obj.class.attributes.key?(attr) end class << self def included(_) ActiveGraph::Shared::TypeConverters.constants.each do |constant_name| constant = ActiveGraph::Shared::TypeConverters.const_get(constant_name) register_converter(constant) if constant.respond_to?(:convert_type) end end def typecast_attribute(typecaster, value) fail ArgumentError, "A typecaster must be given, #{typecaster} is invalid" unless typecaster.respond_to?(:to_ruby) return value if value.nil? typecaster.to_ruby(value) end def typecaster_for(primitive_type) return nil if primitive_type.nil? CONVERTERS[primitive_type] end # @param [Symbol] direction either :to_ruby or :to_other def to_other(direction, value, type) fail "Unknown direction given: #{direction}" unless direction == :to_ruby || direction == :to_db found_converter = converter_for(type) return value unless found_converter return value if direction == :to_db && formatted_for_db?(found_converter, value) found_converter.send(direction, value) end def converter_for(type) type.respond_to?(:db_type) ? type : CONVERTERS[type] end # Attempts to determine whether conversion should be skipped because the object is already of the anticipated output type. # @param [#convert_type] found_converter An object that responds to #convert_type, hinting that it is a type converter. # @param value The value for conversion. def formatted_for_db?(found_converter, value) return false unless found_converter.respond_to?(:db_type) found_converter.respond_to?(:converted?) ? found_converter.converted?(value) : value.is_a?(found_converter.db_type) end def register_converter(converter) CONVERTERS[converter.convert_type] = converter end end end end
<div class="commune_descr limited"> <p> Herblay est une ville géographiquement positionnée dans le département de Val-d'Oise en Île-de-France. Elle comptait 25&nbsp;824 habitants en 2008.</p> <p>À Herblay, le prix moyen à la vente d'un appartement se situe à 3&nbsp;725 &euro; du m² en vente. la valorisation moyenne d'une maison à l'achat se situe à 3&nbsp;469 &euro; du m². À la location la valeur moyenne se situe à 16,46 &euro; du m² mensuel.</p> <p>Le parc d'habitations, à Herblay, était réparti en 2011 en 3&nbsp;691 appartements et 6&nbsp;548 maisons soit un marché plutôt équilibré.</p> <p>Herblay est localisé à seulement 11 km de Nanterre, les élèves qui voudrons se loger à pas cher pourront envisager de prendre un logement à Herblay. Herblay est également un bon placement locatif du fait de sa proximité de Nanterre et de ses Universités. Il sera facile de trouver un logement à acheter. </p> <p> La commune est équipée concernant la formation de trois collèges et deux lycées. Pour les plus petits d'entre nous, la commune est pourvue pour le bien être de sa population de sept maternelles et neuf écoles primaires. Herblay propose les équipements éducatifs facilitant une bonne prise en charge des jeunes. Lors d'un projet de transaction immobilière à Herblay, il est intéressant d' regarder la qualité des équipements éducatifs</p> <p>À Herblay le salaire moyen mensuel par personne se situe à approximativement 2&nbsp;620 &euro; net. Ceci est supérieur à la moyenne du pays.</p> <p>À proximité de Herblay sont positionnées géographiquement les communes de <a href="{{VLROOT}}/immobilier/franconville_95252/">Franconville</a> localisée à 4&nbsp;km, 32&nbsp;988 habitants, <a href="{{VLROOT}}/immobilier/pierrelaye_95488/">Pierrelaye</a> à 3&nbsp;km, 7&nbsp;322 habitants, <a href="{{VLROOT}}/immobilier/<API key>/">Montigny-lès-Cormeilles</a> à 2&nbsp;km, 18&nbsp;935 habitants, <a href="{{VLROOT}}/immobilier/sartrouville_78586/">Sartrouville</a> située à 5&nbsp;km, 51&nbsp;600 habitants, <a href="{{VLROOT}}/immobilier/<API key>/"><API key></a> localisée à 3&nbsp;km, 21&nbsp;503 habitants, <a href="{{VLROOT}}/immobilier/taverny_95607/">Taverny</a> située à 5&nbsp;km, 26&nbsp;436 habitants, entre autres. De plus, Herblay est située à seulement 20&nbsp;km de <a href="{{VLROOT}}/immobilier/paris_75056/">Paris</a>.</p> <p> Herblay apparait comme une commune où sont installés de nombreux commerces. Il y a à Herblay six supermarchés et six supérettes. Herblay apparait comme une commune intéressante pour se lancer dans un placement immobilier. lors d'un achat immobilier la proximité des commerces est très importante</p> <p>La commune compte de nombreux équipements sportifs, elle dispose, entre autres, de un bassin de natation, deux terrains de tennis, trois centres d'équitation et un équipement de roller/skate.</p> </div>
/* * RTL Style Sheet */ .wk-slideshow-tabs .nav, .wk-slideshow-tabs .nav li, .wk-slideshow-tabs .nav span { float: right; } .wk-slideshow-tabs .nav li { margin-left: 0; margin-right: 5px; } .wk-slideshow-tabs .nav li:first-child { margin-right: 0; } /* Left */ .wk-slideshow-tabs .nav-left + .slides-container { <API key>: 0; <API key>: 5px; } /* Center */ .wk-slideshow-tabs .nav-center { left: auto; right: 50%; } .wk-slideshow-tabs .nav-center .nav li { left: auto; right: -50%; } /* Right */ .wk-slideshow-tabs .nav-right .nav { float: left; } .wk-slideshow-tabs .nav-right + .slides-container { <API key>: 0; <API key>: 5px; }
'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); exports.requiredParam = requiredParam; /** * Gets called if a required parameter is missing and the expression * specifying the default value is evaluated. * @param {string} parameter name * @throws {Error} */ function requiredParam(parameter) { let message = 'Missing parameter'; if (parameter) { message += `: ${parameter}`; } throw new Error(message); }
// <API key>.h // <API key> #import <Foundation/Foundation.h> #import <UIKit/UIKit.h> @class <API key>; @class <API key>; @class <API key>; <API key> /** * The `<API key>` protocol is adopted by classes that act as the delegate of a `<API key>`. */ @protocol <API key> <NSObject> @optional /** * Tells the delegate that a specified content controller is about to be displayed. * * @param controller The profile view controller that is showing the content controller. * @prarm controllerIndex The index locating the content controller in the profile view controller. */ - (void)<API key>:(<API key> *)controller <API key>:(NSInteger)controllerIndex; /** * Tells the delegate that a specified content controller is now displayed. * * @param controller The profile view controller that is showing the content controller. * @prarm controllerIndex The index locating the content controller in the profile view controller. */ - (void)<API key>:(<API key> *)controller <API key>:(NSInteger)controllerIndex; /** * Tells the delegate that the user has triggered a pull-to-refresh. * * @param controller The profile view controller that triggered a pull-to-refresh. * @prarm controllerIndex The index locating the content controller in the profile view controller. */ - (void)<API key>:(<API key> *)controller <API key>:(NSInteger)controllerIndex; /** * Asks the delegate for the size of the accessory view kind. * * @param controller The profile view controller that unhighlighted the accessory view. * @param accessoryViewKind A string that identifies the type of the accessory view * * @return The size of the header. */ - (CGSize)<API key>:(<API key> *)controller <API key>:(NSString *)accessoryViewKind; /** * Tells the delegate that the accessory view has been long pressed. * * @param controller The profile view controller where the event occurred. * @prarm accessoryView The accessoryView view that received a long press. * @param accessoryViewKind A string that identifies the type of the accessory view */ - (void)<API key>:(<API key> *)controller <API key>:(__kindof <API key> *)accessoryView ofKind:(NSString *)accessoryViewKind; /** * Tells the delegate that the accessory view has been tapped. * * @param controller The profile view controller where the event occurred. * @prarm accessoryView The accessoryView view that was tapped. * @param accessoryViewKind A string that identifies the type of the accessory view */ - (void)<API key>:(<API key> *)controller didTapAccessoryView:(__kindof <API key> *)accessoryView ofKind:(NSString *)accessoryViewKind; /** * Tells the delegate that the accessory view was highlighted. * * @param controller The profile view controller where the event occurred. * @prarm accessoryView The accessoryView view that was highlighted. * @param accessoryViewKind A string that identifies the type of the accessory view */ - (void)<API key>:(<API key> *)controller <API key>:(__kindof <API key> *)accessoryView ofKind:(NSString *)accessoryViewKind; /** * Tells the delegate that the accessory view was unhighlighted. * * @param controller The profile view controller where the event occurred. * @prarm accessoryView The accessoryView view that was unhighlighted. * @param accessoryViewKind A string that identifies the type of the accessory view */ - (void)<API key>:(<API key> *)controller <API key>:(__kindof <API key> *)accessoryView ofKind:(NSString *)accessoryViewKind; /** * Asks the delegate if the accessory view should be highlighted during tracking. * * @param controller The profile view controller where the event occurred. * @prarm accessoryView The accessoryView view that should be highlighted. * @param accessoryViewKind A string that identifies the type of the accessory view * * @return YES if the accessory view should be highlighted during tracking, NO otherwise */ - (BOOL)<API key>:(<API key> *)controller <API key>:(__kindof <API key> *)accessoryView ofKind:(NSString *)accessoryViewKind; @end <API key>
<!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> <title><API key>: Not compatible </title> <link rel="shortcut icon" type="image/png" href="../../../../../favicon.png" /> <link href="../../../../../bootstrap.min.css" rel="stylesheet"> <link href="../../../../../bootstrap-custom.css" rel="stylesheet"> <link href="//maxcdn.bootstrapcdn.com/font-awesome/4.2.0/css/font-awesome.min.css" rel="stylesheet"> <script src="../../../../../moment.min.js"></script> <!-- HTML5 Shim and Respond.js IE8 support of HTML5 elements and media queries --> <!-- WARNING: Respond.js doesn't work if you view the page via file: <!--[if lt IE 9]> <script src="https://oss.maxcdn.com/html5shiv/3.7.2/html5shiv.min.js"></script> <script src="https://oss.maxcdn.com/respond/1.4.2/respond.min.js"></script> <![endif] </head> <body> <div class="container"> <div class="navbar navbar-default" role="navigation"> <div class="container-fluid"> <div class="navbar-header"> <a class="navbar-brand" href="../../../../.."><i class="fa fa-lg fa-flag-checkered"></i> Coq bench</a> </div> <div id="navbar" class="collapse navbar-collapse"> <ul class="nav navbar-nav"> <li><a href="../..">clean / extra-dev</a></li> <li class="active"><a href="">8.11.dev / <API key> - 8.5.0</a></li> </ul> </div> </div> </div> <div class="article"> <div class="row"> <div class="col-md-12"> <a href="../..">« Up</a> <h1> <API key> <small> 8.5.0 <span class="label label-info">Not compatible </span> </small> </h1> <p> <em><script>document.write(moment("2020-08-11 05:14:42 +0000", "YYYY-MM-DD HH:mm:ss Z").fromNow());</script> (2020-08-11 05:14:42 UTC)</em><p> <h2>Context</h2> <pre># Packages matching: installed # Name # Installed # Synopsis base-bigarray base base-threads base base-unix base conf-findutils 1 Virtual package relying on findutils conf-m4 1 Virtual package relying on m4 coq 8.11.dev Formal proof management system num 1.3 The legacy Num library for arbitrary-precision integer and rational arithmetic ocaml 4.08.1 The OCaml compiler (virtual package) ocaml-base-compiler 4.08.1 Official release 4.08.1 ocaml-config 1 OCaml Switch Configuration ocamlfind 1.8.1 A library manager for OCaml # opam file: opam-version: &quot;2.0&quot; maintainer: &quot;matej.kosik@inria.fr&quot; homepage: &quot;https://github.com/coq-contribs/<API key>&quot; license: &quot;Proprietary&quot; build: [make &quot;-j%{jobs}%&quot;] install: [make &quot;install&quot;] remove: [&quot;rm&quot; &quot;-R&quot; &quot;%{lib}%/coq/user-contrib/PersistentUnionFind&quot;] depends: [ &quot;ocaml&quot; &quot;coq&quot; {&gt;= &quot;8.5&quot; &amp; &lt; &quot;8.6~&quot;} ] tags: [ &quot;keyword:program verification&quot; &quot;keyword:union find&quot; &quot;keyword:data structures&quot; &quot;keyword:tarjan&quot; &quot;category:Computer Science/Decision Procedures and Certified Algorithms/Correctness proofs of algorithms&quot; ] authors: [ &quot;Jean-Christophe Filliâtre &lt;&gt;&quot; ] bug-reports: &quot;https://github.com/coq-contribs/<API key>/issues&quot; dev-repo: &quot;git+https://github.com/coq-contribs/<API key>.git&quot; synopsis: &quot;Persistent Union Find&quot; description: &quot;&quot;&quot; Correctness proof of the Ocaml implementation of a persistent union-find data structure. See http: flags: light-uninstall url { src: &quot;https://github.com/coq-contribs/<API key>/archive/v8.5.0.tar.gz&quot; checksum: &quot;md5=<API key>&quot; } </pre> <h2>Lint</h2> <dl class="dl-horizontal"> <dt>Command</dt> <dd><code>true</code></dd> <dt>Return code</dt> <dd>0</dd> </dl> <h2>Dry install </h2> <p>Dry install with the current Coq version:</p> <dl class="dl-horizontal"> <dt>Command</dt> <dd><code>opam install -y --show-action <API key>.8.5.0 coq.8.11.dev</code></dd> <dt>Return code</dt> <dd>5120</dd> <dt>Output</dt> <dd><pre>[NOTE] Package coq is already installed (current version is 8.11.dev). The following dependencies couldn&#39;t be met: - <API key> -&gt; coq &lt; 8.6~ -&gt; ocaml &lt; 4.06.0 base of this switch (use `--unlock-base&#39; to force) Your request can&#39;t be satisfied: - No available version of coq satisfies the constraints No solution found, exiting </pre></dd> </dl> <p>Dry install without Coq/switch base, to test if the problem was incompatibility with the current Coq/OCaml version:</p> <dl class="dl-horizontal"> <dt>Command</dt> <dd><code>opam remove -y coq; opam install -y --show-action --unlock-base <API key>.8.5.0</code></dd> <dt>Return code</dt> <dd>0</dd> </dl> <h2>Install dependencies</h2> <dl class="dl-horizontal"> <dt>Command</dt> <dd><code>true</code></dd> <dt>Return code</dt> <dd>0</dd> <dt>Duration</dt> <dd>0 s</dd> </dl> <h2>Install </h2> <dl class="dl-horizontal"> <dt>Command</dt> <dd><code>true</code></dd> <dt>Return code</dt> <dd>0</dd> <dt>Duration</dt> <dd>0 s</dd> </dl> <h2>Installation size</h2> <p>No files were installed.</p> <h2>Uninstall 🧹</h2> <dl class="dl-horizontal"> <dt>Command</dt> <dd><code>true</code></dd> <dt>Return code</dt> <dd>0</dd> <dt>Missing removes</dt> <dd> none </dd> <dt>Wrong removes</dt> <dd> none </dd> </dl> </div> </div> </div> <hr/> <div class="footer"> <p class="text-center"> Sources are on <a href="https: </p> </div> </div> <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script> <script src="../../../../../bootstrap.min.js"></script> </body> </html>
#include "wallet.h" #include "walletdb.h" #include "crypter.h" #include "ui_interface.h" #include "base58.h" #include "kernel.h" using namespace std; extern int nStakeMaxAge; // mapWallet struct CompareValueOnly { bool operator()(const pair<int64, pair<const CWalletTx*, unsigned int> >& t1, const pair<int64, pair<const CWalletTx*, unsigned int> >& t2) const { return t1.first < t2.first; } }; CPubKey CWallet::GenerateNewKey() { bool fCompressed = CanSupportFeature(FEATURE_COMPRPUBKEY); // default to compressed public keys if we want 0.6.0 wallets RandAddSeedPerfmon(); CKey key; key.MakeNewKey(fCompressed); // Compressed public keys were introduced in version 0.6.0 if (fCompressed) SetMinVersion(FEATURE_COMPRPUBKEY); if (!AddKey(key)) throw std::runtime_error("CWallet::GenerateNewKey() : AddKey failed"); return key.GetPubKey(); } bool CWallet::AddKey(const CKey& key) { if (!CCryptoKeyStore::AddKey(key)) return false; if (!fFileBacked) return true; if (!IsCrypted()) return CWalletDB(strWalletFile).WriteKey(key.GetPubKey(), key.GetPrivKey()); return true; } bool CWallet::AddCryptedKey(const CPubKey &vchPubKey, const vector<unsigned char> &vchCryptedSecret) { if (!CCryptoKeyStore::AddCryptedKey(vchPubKey, vchCryptedSecret)) return false; if (!fFileBacked) return true; { LOCK(cs_wallet); if (pwalletdbEncryption) return pwalletdbEncryption->WriteCryptedKey(vchPubKey, vchCryptedSecret); else return CWalletDB(strWalletFile).WriteCryptedKey(vchPubKey, vchCryptedSecret); } return false; } bool CWallet::AddCScript(const CScript& redeemScript) { if (!CCryptoKeyStore::AddCScript(redeemScript)) return false; if (!fFileBacked) return true; return CWalletDB(strWalletFile).WriteCScript(Hash160(redeemScript), redeemScript); } // ppcoin: optional setting to unlock wallet for block minting only; // serves to disable the trivial sendmoney when OS account compromised bool <API key> = false; bool CWallet::Unlock(const SecureString& strWalletPassphrase) { if (!IsLocked()) return false; CCrypter crypter; CKeyingMaterial vMasterKey; { LOCK(cs_wallet); BOOST_FOREACH(const MasterKeyMap::value_type& pMasterKey, mapMasterKeys) { if(!crypter.<API key>(strWalletPassphrase, pMasterKey.second.vchSalt, pMasterKey.second.nDeriveIterations, pMasterKey.second.nDerivationMethod)) return false; if (!crypter.Decrypt(pMasterKey.second.vchCryptedKey, vMasterKey)) return false; if (CCryptoKeyStore::Unlock(vMasterKey)) return true; } } return false; } bool CWallet::<API key>(const SecureString& <API key>, const SecureString& <API key>) { bool fWasLocked = IsLocked(); { LOCK(cs_wallet); Lock(); CCrypter crypter; CKeyingMaterial vMasterKey; BOOST_FOREACH(MasterKeyMap::value_type& pMasterKey, mapMasterKeys) { if(!crypter.<API key>(<API key>, pMasterKey.second.vchSalt, pMasterKey.second.nDeriveIterations, pMasterKey.second.nDerivationMethod)) return false; if (!crypter.Decrypt(pMasterKey.second.vchCryptedKey, vMasterKey)) return false; if (CCryptoKeyStore::Unlock(vMasterKey)) { int64 nStartTime = GetTimeMillis(); crypter.<API key>(<API key>, pMasterKey.second.vchSalt, pMasterKey.second.nDeriveIterations, pMasterKey.second.nDerivationMethod); pMasterKey.second.nDeriveIterations = pMasterKey.second.nDeriveIterations * (100 / ((double)(GetTimeMillis() - nStartTime))); nStartTime = GetTimeMillis(); crypter.<API key>(<API key>, pMasterKey.second.vchSalt, pMasterKey.second.nDeriveIterations, pMasterKey.second.nDerivationMethod); pMasterKey.second.nDeriveIterations = (pMasterKey.second.nDeriveIterations + pMasterKey.second.nDeriveIterations * 100 / ((double)(GetTimeMillis() - nStartTime))) / 2; if (pMasterKey.second.nDeriveIterations < 25000) pMasterKey.second.nDeriveIterations = 25000; printf("Wallet passphrase changed to an nDeriveIterations of %i\n", pMasterKey.second.nDeriveIterations); if (!crypter.<API key>(<API key>, pMasterKey.second.vchSalt, pMasterKey.second.nDeriveIterations, pMasterKey.second.nDerivationMethod)) return false; if (!crypter.Encrypt(vMasterKey, pMasterKey.second.vchCryptedKey)) return false; CWalletDB(strWalletFile).WriteMasterKey(pMasterKey.first, pMasterKey.second); if (fWasLocked) Lock(); return true; } } } return false; } void CWallet::SetBestChain(const CBlockLocator& loc) { CWalletDB walletdb(strWalletFile); walletdb.WriteBestBlock(loc); } // This class implements an addrIncoming entry that causes pre-0.4 // clients to crash on startup if reading a <API key> wallet. class CCorruptAddress { public: IMPLEMENT_SERIALIZE ( if (nType & SER_DISK) READWRITE(nVersion); ) }; bool CWallet::SetMinVersion(enum WalletFeature nVersion, CWalletDB* pwalletdbIn, bool fExplicit) { if (nWalletVersion >= nVersion) return true; // when doing an explicit upgrade, if we pass the max version permitted, upgrade all the way if (fExplicit && nVersion > nWalletMaxVersion) nVersion = FEATURE_LATEST; nWalletVersion = nVersion; if (nVersion > nWalletMaxVersion) nWalletMaxVersion = nVersion; if (fFileBacked) { CWalletDB* pwalletdb = pwalletdbIn ? pwalletdbIn : new CWalletDB(strWalletFile); if (nWalletVersion >= 40000) { // Versions prior to 0.4.0 did not support the "minversion" record. // Use a CCorruptAddress to make them crash instead. CCorruptAddress corruptAddress; pwalletdb->WriteSetting("addrIncoming", corruptAddress); } if (nWalletVersion > 40000) pwalletdb->WriteMinVersion(nWalletVersion); if (!pwalletdbIn) delete pwalletdb; } return true; } bool CWallet::SetMaxVersion(int nVersion) { // cannot downgrade below current version if (nWalletVersion > nVersion) return false; nWalletMaxVersion = nVersion; return true; } bool CWallet::EncryptWallet(const SecureString& strWalletPassphrase) { if (IsCrypted()) return false; CKeyingMaterial vMasterKey; RandAddSeedPerfmon(); vMasterKey.resize(<API key>); RAND_bytes(&vMasterKey[0], <API key>); CMasterKey kMasterKey; RandAddSeedPerfmon(); kMasterKey.vchSalt.resize(<API key>); RAND_bytes(&kMasterKey.vchSalt[0], <API key>); CCrypter crypter; int64 nStartTime = GetTimeMillis(); crypter.<API key>(strWalletPassphrase, kMasterKey.vchSalt, 25000, kMasterKey.nDerivationMethod); kMasterKey.nDeriveIterations = 2500000 / ((double)(GetTimeMillis() - nStartTime)); nStartTime = GetTimeMillis(); crypter.<API key>(strWalletPassphrase, kMasterKey.vchSalt, kMasterKey.nDeriveIterations, kMasterKey.nDerivationMethod); kMasterKey.nDeriveIterations = (kMasterKey.nDeriveIterations + kMasterKey.nDeriveIterations * 100 / ((double)(GetTimeMillis() - nStartTime))) / 2; if (kMasterKey.nDeriveIterations < 25000) kMasterKey.nDeriveIterations = 25000; printf("Encrypting Wallet with an nDeriveIterations of %i\n", kMasterKey.nDeriveIterations); if (!crypter.<API key>(strWalletPassphrase, kMasterKey.vchSalt, kMasterKey.nDeriveIterations, kMasterKey.nDerivationMethod)) return false; if (!crypter.Encrypt(vMasterKey, kMasterKey.vchCryptedKey)) return false; { LOCK(cs_wallet); mapMasterKeys[++nMasterKeyMaxID] = kMasterKey; if (fFileBacked) { pwalletdbEncryption = new CWalletDB(strWalletFile); if (!pwalletdbEncryption->TxnBegin()) return false; pwalletdbEncryption->WriteMasterKey(nMasterKeyMaxID, kMasterKey); } if (!EncryptKeys(vMasterKey)) { if (fFileBacked) pwalletdbEncryption->TxnAbort(); exit(1); //We now probably have half of our keys encrypted in memory, and half not...die and let the user reload their unencrypted wallet. } // Encryption was introduced in version 0.4.0 SetMinVersion(FEATURE_WALLETCRYPT, pwalletdbEncryption, true); if (fFileBacked) { if (!pwalletdbEncryption->TxnCommit()) exit(1); //We now have keys encrypted in memory, but no on disk...die to avoid confusion and let the user reload their unencrypted wallet. delete pwalletdbEncryption; pwalletdbEncryption = NULL; } Lock(); Unlock(strWalletPassphrase); NewKeyPool(); Lock(); // Need to completely rewrite the wallet file; if we don't, bdb might keep // bits of the unencrypted private key in slack space in the database file. CDB::Rewrite(strWalletFile); } NotifyStatusChanged(this); return true; } int64 CWallet::IncOrderPosNext(CWalletDB *pwalletdb) { int64 nRet = nOrderPosNext++; if (pwalletdb) { pwalletdb->WriteOrderPosNext(nOrderPosNext); } else { CWalletDB(strWalletFile).WriteOrderPosNext(nOrderPosNext); } return nRet; } CWallet::TxItems CWallet::OrderedTxItems(std::list<CAccountingEntry>& acentries, std::string strAccount) { CWalletDB walletdb(strWalletFile); // First: get all CWalletTx and CAccountingEntry into a sorted-by-order multimap. TxItems txOrdered; // Note: maintaining indices in the database of (account,time) --> txid and (account, time) --> acentry // would make this much faster for applications that do this a lot. for (map<uint256, CWalletTx>::iterator it = mapWallet.begin(); it != mapWallet.end(); ++it) { CWalletTx* wtx = &((*it).second); txOrdered.insert(make_pair(wtx->nOrderPos, TxPair(wtx, (CAccountingEntry*)0))); } acentries.clear(); walletdb.<API key>(strAccount, acentries); BOOST_FOREACH(CAccountingEntry& entry, acentries) { txOrdered.insert(make_pair(entry.nOrderPos, TxPair((CWalletTx*)0, &entry))); } return txOrdered; } void CWallet::WalletUpdateSpent(const CTransaction &tx) { // Anytime a signature is successfully verified, it's proof the outpoint is spent. // Update the wallet spent flag if it doesn't know due to wallet.dat being // restored from backup or the user making copies of wallet.dat. { LOCK(cs_wallet); BOOST_FOREACH(const CTxIn& txin, tx.vin) { map<uint256, CWalletTx>::iterator mi = mapWallet.find(txin.prevout.hash); if (mi != mapWallet.end()) { CWalletTx& wtx = (*mi).second; if (txin.prevout.n >= wtx.vout.size()) printf("WalletUpdateSpent: bad wtx %s\n", wtx.GetHash().ToString().c_str()); else if (!wtx.IsSpent(txin.prevout.n) && IsMine(wtx.vout[txin.prevout.n])) { printf("WalletUpdateSpent found spent coin %snvc %s\n", FormatMoney(wtx.GetCredit()).c_str(), wtx.GetHash().ToString().c_str()); wtx.MarkSpent(txin.prevout.n); wtx.WriteToDisk(); <API key>(this, txin.prevout.hash, CT_UPDATED); } } } } } void CWallet::MarkDirty() { { LOCK(cs_wallet); BOOST_FOREACH(PAIRTYPE(const uint256, CWalletTx)& item, mapWallet) item.second.MarkDirty(); } } bool CWallet::AddToWallet(const CWalletTx& wtxIn) { uint256 hash = wtxIn.GetHash(); { LOCK(cs_wallet); // Inserts only if not already there, returns tx inserted or tx found pair<map<uint256, CWalletTx>::iterator, bool> ret = mapWallet.insert(make_pair(hash, wtxIn)); CWalletTx& wtx = (*ret.first).second; wtx.BindWallet(this); bool fInsertedNew = ret.second; if (fInsertedNew) { wtx.nTimeReceived = GetAdjustedTime(); wtx.nOrderPos = IncOrderPosNext(); wtx.nTimeSmart = wtx.nTimeReceived; if (wtxIn.hashBlock != 0) { if (mapBlockIndex.count(wtxIn.hashBlock)) { unsigned int latestNow = wtx.nTimeReceived; unsigned int latestEntry = 0; { // Tolerate times up to the last timestamp in the wallet not more than 5 minutes into the future int64 latestTolerated = latestNow + 300; std::list<CAccountingEntry> acentries; TxItems txOrdered = OrderedTxItems(acentries); for (TxItems::reverse_iterator it = txOrdered.rbegin(); it != txOrdered.rend(); ++it) { CWalletTx *const pwtx = (*it).second.first; if (pwtx == &wtx) continue; CAccountingEntry *const pacentry = (*it).second.second; int64 nSmartTime; if (pwtx) { nSmartTime = pwtx->nTimeSmart; if (!nSmartTime) nSmartTime = pwtx->nTimeReceived; } else nSmartTime = pacentry->nTime; if (nSmartTime <= latestTolerated) { latestEntry = nSmartTime; if (nSmartTime > latestNow) latestNow = nSmartTime; break; } } } unsigned int& blocktime = mapBlockIndex[wtxIn.hashBlock]->nTime; wtx.nTimeSmart = std::max(latestEntry, std::min(blocktime, latestNow)); } else printf("AddToWallet() : found %s in block %s not in index\n", wtxIn.GetHash().ToString().substr(0,10).c_str(), wtxIn.hashBlock.ToString().c_str()); } } bool fUpdated = false; if (!fInsertedNew) { // Merge if (wtxIn.hashBlock != 0 && wtxIn.hashBlock != wtx.hashBlock) { wtx.hashBlock = wtxIn.hashBlock; fUpdated = true; } if (wtxIn.nIndex != -1 && (wtxIn.vMerkleBranch != wtx.vMerkleBranch || wtxIn.nIndex != wtx.nIndex)) { wtx.vMerkleBranch = wtxIn.vMerkleBranch; wtx.nIndex = wtxIn.nIndex; fUpdated = true; } if (wtxIn.fFromMe && wtxIn.fFromMe != wtx.fFromMe) { wtx.fFromMe = wtxIn.fFromMe; fUpdated = true; } fUpdated |= wtx.UpdateSpent(wtxIn.vfSpent); } / debug print printf("AddToWallet %s %s%s\n", wtxIn.GetHash().ToString().substr(0,10).c_str(), (fInsertedNew ? "new" : ""), (fUpdated ? "update" : "")); // Write to disk if (fInsertedNew || fUpdated) if (!wtx.WriteToDisk()) return false; #ifndef QT_GUI // If default receiving address gets used, replace it with a new one CScript scriptDefaultKey; scriptDefaultKey.SetDestination(vchDefaultKey.GetID()); BOOST_FOREACH(const CTxOut& txout, wtx.vout) { if (txout.scriptPubKey == scriptDefaultKey) { CPubKey newDefaultKey; if (GetKeyFromPool(newDefaultKey, false)) { SetDefaultKey(newDefaultKey); SetAddressBookName(vchDefaultKey.GetID(), ""); } } } #endif // since AddToWallet is called directly for self-originating transactions, check for consumption of own coins WalletUpdateSpent(wtx); // Notify UI of new or updated transaction <API key>(this, hash, fInsertedNew ? CT_NEW : CT_UPDATED); } return true; } // Add a transaction to the wallet, or update it. // pblock is optional, but should be provided if the transaction is known to be in a block. // If fUpdate is true, existing transactions will be updated. bool CWallet::<API key>(const CTransaction& tx, const CBlock* pblock, bool fUpdate, bool fFindBlock) { uint256 hash = tx.GetHash(); { LOCK(cs_wallet); bool fExisted = mapWallet.count(hash); if (fExisted && !fUpdate) return false; if (fExisted || IsMine(tx) || IsFromMe(tx)) { CWalletTx wtx(this,tx); // Get merkle branch if transaction was found in a block if (pblock) wtx.SetMerkleBranch(pblock); return AddToWallet(wtx); } else WalletUpdateSpent(tx); } return false; } bool CWallet::EraseFromWallet(uint256 hash) { if (!fFileBacked) return false; { LOCK(cs_wallet); if (mapWallet.erase(hash)) CWalletDB(strWalletFile).EraseTx(hash); } return true; } bool CWallet::IsMine(const CTxIn &txin) const { { LOCK(cs_wallet); map<uint256, CWalletTx>::const_iterator mi = mapWallet.find(txin.prevout.hash); if (mi != mapWallet.end()) { const CWalletTx& prev = (*mi).second; if (txin.prevout.n < prev.vout.size()) if (IsMine(prev.vout[txin.prevout.n])) return true; } } return false; } int64 CWallet::GetDebit(const CTxIn &txin) const { { LOCK(cs_wallet); map<uint256, CWalletTx>::const_iterator mi = mapWallet.find(txin.prevout.hash); if (mi != mapWallet.end()) { const CWalletTx& prev = (*mi).second; if (txin.prevout.n < prev.vout.size()) if (IsMine(prev.vout[txin.prevout.n])) return prev.vout[txin.prevout.n].nValue; } } return 0; } bool CWallet::IsChange(const CTxOut& txout) const { CTxDestination address; // TODO: fix handling of 'change' outputs. The assumption is that any // payment to a TX_PUBKEYHASH that is mine but isn't in the address book // is change. That assumption is likely to break when we implement multisignature // wallets that return change back into a <API key> address; // a better way of identifying which outputs are 'the send' and which are // 'the change' will need to be implemented (maybe extend CWalletTx to remember // which output, if any, was change). if (ExtractDestination(txout.scriptPubKey, address) && ::IsMine(*this, address)) { LOCK(cs_wallet); if (!mapAddressBook.count(address)) return true; } return false; } int64 CWalletTx::GetTxTime() const { int64 n = nTimeSmart; return n ? n : nTimeReceived; } int CWalletTx::GetRequestCount() const { // Returns -1 if it wasn't being tracked int nRequests = -1; { LOCK(pwallet->cs_wallet); if (IsCoinBase() || IsCoinStake()) { // Generated block if (hashBlock != 0) { map<uint256, int>::const_iterator mi = pwallet->mapRequestCount.find(hashBlock); if (mi != pwallet->mapRequestCount.end()) nRequests = (*mi).second; } } else { // Did anyone request this transaction? map<uint256, int>::const_iterator mi = pwallet->mapRequestCount.find(GetHash()); if (mi != pwallet->mapRequestCount.end()) { nRequests = (*mi).second; // How about the block it's in? if (nRequests == 0 && hashBlock != 0) { map<uint256, int>::const_iterator mi = pwallet->mapRequestCount.find(hashBlock); if (mi != pwallet->mapRequestCount.end()) nRequests = (*mi).second; else nRequests = 1; // If it's in someone else's block it must have got out } } } } return nRequests; } void CWalletTx::GetAmounts(int64& nGeneratedImmature, int64& nGeneratedMature, list<pair<CTxDestination, int64> >& listReceived, list<pair<CTxDestination, int64> >& listSent, int64& nFee, string& strSentAccount) const { nGeneratedImmature = nGeneratedMature = nFee = 0; listReceived.clear(); listSent.clear(); strSentAccount = strFromAccount; if (IsCoinBase() || IsCoinStake()) { if (GetBlocksToMaturity() > 0) nGeneratedImmature = pwallet->GetCredit(*this); else nGeneratedMature = GetCredit(); return; } // Compute fee: int64 nDebit = GetDebit(); if (nDebit > 0) // debit>0 means we signed/sent this transaction { int64 nValueOut = GetValueOut(); nFee = nDebit - nValueOut; } // Sent/received. BOOST_FOREACH(const CTxOut& txout, vout) { CTxDestination address; vector<unsigned char> vchPubKey; if (!ExtractDestination(txout.scriptPubKey, address)) { printf("CWalletTx::GetAmounts: Unknown transaction type found, txid %s\n", this->GetHash().ToString().c_str()); } // Don't report 'change' txouts if (nDebit > 0 && pwallet->IsChange(txout)) continue; if (nDebit > 0) listSent.push_back(make_pair(address, txout.nValue)); if (pwallet->IsMine(txout)) listReceived.push_back(make_pair(address, txout.nValue)); } } void CWalletTx::GetAccountAmounts(const string& strAccount, int64& nGenerated, int64& nReceived, int64& nSent, int64& nFee) const { nReceived = nSent = nFee = 0; int64 <API key>, allGeneratedMature, allFee; string strSentAccount; list<pair<CTxDestination, int64> > listReceived; list<pair<CTxDestination, int64> > listSent; GetAmounts(<API key>, allGeneratedMature, listReceived, listSent, allFee, strSentAccount); if (strAccount == "") nGenerated = allGeneratedMature; if (strAccount == strSentAccount) { BOOST_FOREACH(const PAIRTYPE(CTxDestination,int64)& s, listSent) nSent += s.second; nFee = allFee; } { LOCK(pwallet->cs_wallet); BOOST_FOREACH(const PAIRTYPE(CTxDestination,int64)& r, listReceived) { if (pwallet->mapAddressBook.count(r.first)) { map<CTxDestination, string>::const_iterator mi = pwallet->mapAddressBook.find(r.first); if (mi != pwallet->mapAddressBook.end() && (*mi).second == strAccount) nReceived += r.second; } else if (strAccount.empty()) { nReceived += r.second; } } } } void CWalletTx::<API key>(CTxDB& txdb) { vtxPrev.clear(); const int COPY_DEPTH = 3; if (SetMerkleBranch() < COPY_DEPTH) { vector<uint256> vWorkQueue; BOOST_FOREACH(const CTxIn& txin, vin) vWorkQueue.push_back(txin.prevout.hash); // This critsect is OK because txdb is already open { LOCK(pwallet->cs_wallet); map<uint256, const CMerkleTx*> mapWalletPrev; set<uint256> setAlreadyDone; for (unsigned int i = 0; i < vWorkQueue.size(); i++) { uint256 hash = vWorkQueue[i]; if (setAlreadyDone.count(hash)) continue; setAlreadyDone.insert(hash); CMerkleTx tx; map<uint256, CWalletTx>::const_iterator mi = pwallet->mapWallet.find(hash); if (mi != pwallet->mapWallet.end()) { tx = (*mi).second; BOOST_FOREACH(const CMerkleTx& txWalletPrev, (*mi).second.vtxPrev) mapWalletPrev[txWalletPrev.GetHash()] = &txWalletPrev; } else if (mapWalletPrev.count(hash)) { tx = *mapWalletPrev[hash]; } else if (!fClient && txdb.ReadDiskTx(hash, tx)) { ; } else { printf("ERROR: <API key>() : unsupported transaction\n"); continue; } int nDepth = tx.SetMerkleBranch(); vtxPrev.push_back(tx); if (nDepth < COPY_DEPTH) { BOOST_FOREACH(const CTxIn& txin, tx.vin) vWorkQueue.push_back(txin.prevout.hash); } } } } reverse(vtxPrev.begin(), vtxPrev.end()); } bool CWalletTx::WriteToDisk() { return CWalletDB(pwallet->strWalletFile).WriteTx(GetHash(), *this); } // Scan the block chain (starting in pindexStart) for transactions // from or to us. If fUpdate is true, found transactions that already // exist in the wallet will be updated. int CWallet::<API key>(CBlockIndex* pindexStart, bool fUpdate) { int ret = 0; CBlockIndex* pindex = pindexStart; { LOCK(cs_wallet); while (pindex) { CBlock block; block.ReadFromDisk(pindex, true); BOOST_FOREACH(CTransaction& tx, block.vtx) { if (<API key>(tx, &block, fUpdate)) ret++; } pindex = pindex->pnext; } } return ret; } int CWallet::<API key>(const uint256& hashTx) { CTransaction tx; tx.ReadFromDisk(COutPoint(hashTx, 0)); if (<API key>(tx, NULL, true, true)) return 1; return 0; } void CWallet::<API key>() { CTxDB txdb("r"); bool fRepeat = true; while (fRepeat) { LOCK(cs_wallet); fRepeat = false; vector<CDiskTxPos> vMissingTx; BOOST_FOREACH(PAIRTYPE(const uint256, CWalletTx)& item, mapWallet) { CWalletTx& wtx = item.second; if ((wtx.IsCoinBase() && wtx.IsSpent(0)) || (wtx.IsCoinStake() && wtx.IsSpent(1))) continue; CTxIndex txindex; bool fUpdated = false; if (txdb.ReadTxIndex(wtx.GetHash(), txindex)) { // Update fSpent if a tx got spent somewhere else by a copy of wallet.dat if (txindex.vSpent.size() != wtx.vout.size()) { printf("ERROR: <API key>() : txindex.vSpent.size() %"PRIszu" != wtx.vout.size() %"PRIszu"\n", txindex.vSpent.size(), wtx.vout.size()); continue; } for (unsigned int i = 0; i < txindex.vSpent.size(); i++) { if (wtx.IsSpent(i)) continue; if (!txindex.vSpent[i].IsNull() && IsMine(wtx.vout[i])) { wtx.MarkSpent(i); fUpdated = true; vMissingTx.push_back(txindex.vSpent[i]); } } if (fUpdated) { printf("<API key> found spent coin %snvc %s\n", FormatMoney(wtx.GetCredit()).c_str(), wtx.GetHash().ToString().c_str()); wtx.MarkDirty(); wtx.WriteToDisk(); } } else { // Re-accept any txes of ours that aren't already in a block if (!(wtx.IsCoinBase() || wtx.IsCoinStake())) wtx.<API key>(txdb, false); } } if (!vMissingTx.empty()) { // TODO: optimize this to scan just part of the block chain? if (<API key>(pindexGenesisBlock)) fRepeat = true; // Found missing transactions: re-do re-accept. } } } void CWalletTx::<API key>(CTxDB& txdb) { BOOST_FOREACH(const CMerkleTx& tx, vtxPrev) { if (!(tx.IsCoinBase() || tx.IsCoinStake())) { uint256 hash = tx.GetHash(); if (!txdb.ContainsTx(hash)) RelayMessage(CInv(MSG_TX, hash), (CTransaction)tx); } } if (!(IsCoinBase() || IsCoinStake())) { uint256 hash = GetHash(); if (!txdb.ContainsTx(hash)) { printf("Relaying wtx %s\n", hash.ToString().substr(0,10).c_str()); RelayMessage(CInv(MSG_TX, hash), (CTransaction)*this); } } } void CWalletTx::<API key>() { CTxDB txdb("r"); <API key>(txdb); } void CWallet::<API key>() { // Do this infrequently and randomly to avoid giving away // that these are our transactions. static int64 nNextTime; if (GetTime() < nNextTime) return; bool fFirst = (nNextTime == 0); nNextTime = GetTime() + GetRand(30 * 60); if (fFirst) return; // Only do it if there's been a new block since last time static int64 nLastTime; if (nTimeBestReceived < nLastTime) return; nLastTime = GetTime(); // Rebroadcast any of our txes that aren't in a block yet printf("<API key>()\n"); CTxDB txdb("r"); { LOCK(cs_wallet); // Sort them in chronological order multimap<unsigned int, CWalletTx*> mapSorted; BOOST_FOREACH(PAIRTYPE(const uint256, CWalletTx)& item, mapWallet) { CWalletTx& wtx = item.second; // Don't rebroadcast until it's had plenty of time that // it should have gotten in already by now. if (nTimeBestReceived - (int64)wtx.nTimeReceived > 5 * 60) mapSorted.insert(make_pair(wtx.nTimeReceived, &wtx)); } BOOST_FOREACH(PAIRTYPE(const unsigned int, CWalletTx*)& item, mapSorted) { CWalletTx& wtx = *item.second; if (wtx.CheckTransaction()) wtx.<API key>(txdb); else printf("<API key>() : CheckTransaction failed for transaction %s\n", wtx.GetHash().ToString().c_str()); } } } // Actions int64 CWallet::GetBalance() const { int64 nTotal = 0; { LOCK(cs_wallet); for (map<uint256, CWalletTx>::const_iterator it = mapWallet.begin(); it != mapWallet.end(); ++it) { const CWalletTx* pcoin = &(*it).second; if (pcoin->IsFinal() && pcoin->IsConfirmed()) nTotal += pcoin->GetAvailableCredit(); } } return nTotal; } int64 CWallet::<API key>() const { int64 nTotal = 0; { LOCK(cs_wallet); for (map<uint256, CWalletTx>::const_iterator it = mapWallet.begin(); it != mapWallet.end(); ++it) { const CWalletTx* pcoin = &(*it).second; if (!pcoin->IsFinal() || !pcoin->IsConfirmed()) nTotal += pcoin->GetAvailableCredit(); } } return nTotal; } int64 CWallet::GetImmatureBalance() const { int64 nTotal = 0; { LOCK(cs_wallet); for (map<uint256, CWalletTx>::const_iterator it = mapWallet.begin(); it != mapWallet.end(); ++it) { const CWalletTx& pcoin = (*it).second; if (pcoin.IsCoinBase() && pcoin.GetBlocksToMaturity() > 0 && pcoin.IsInMainChain()) nTotal += GetCredit(pcoin); } } return nTotal; } // populate vCoins with vector of spendable COutputs void CWallet::AvailableCoins(vector<COutput>& vCoins, bool fOnlyConfirmed) const { vCoins.clear(); { LOCK(cs_wallet); for (map<uint256, CWalletTx>::const_iterator it = mapWallet.begin(); it != mapWallet.end(); ++it) { const CWalletTx* pcoin = &(*it).second; if (!pcoin->IsFinal()) continue; if (fOnlyConfirmed && !pcoin->IsConfirmed()) continue; if (pcoin->IsCoinBase() && pcoin->GetBlocksToMaturity() > 0) continue; if(pcoin->IsCoinStake() && pcoin->GetBlocksToMaturity() > 0) continue; for (unsigned int i = 0; i < pcoin->vout.size(); i++) if (!(pcoin->IsSpent(i)) && IsMine(pcoin->vout[i]) && pcoin->vout[i].nValue > 0) vCoins.push_back(COutput(pcoin, i, pcoin->GetDepthInMainChain())); } } } static void <API key>(vector<pair<int64, pair<const CWalletTx*,unsigned int> > >vValue, int64 nTotalLower, int64 nTargetValue, vector<char>& vfBest, int64& nBest, int iterations = 1000) { vector<char> vfIncluded; vfBest.assign(vValue.size(), true); nBest = nTotalLower; for (int nRep = 0; nRep < iterations && nBest != nTargetValue; nRep++) { vfIncluded.assign(vValue.size(), false); int64 nTotal = 0; bool fReachedTarget = false; for (int nPass = 0; nPass < 2 && !fReachedTarget; nPass++) { for (unsigned int i = 0; i < vValue.size(); i++) { if (nPass == 0 ? rand() % 2 : !vfIncluded[i]) { nTotal += vValue[i].first; vfIncluded[i] = true; if (nTotal >= nTargetValue) { fReachedTarget = true; if (nTotal < nBest) { nBest = nTotal; vfBest = vfIncluded; } nTotal -= vValue[i].first; vfIncluded[i] = false; } } } } } } // ppcoin: total coins staked (non-spendable until maturity) int64 CWallet::GetStake() const { int64 nTotal = 0; LOCK(cs_wallet); for (map<uint256, CWalletTx>::const_iterator it = mapWallet.begin(); it != mapWallet.end(); ++it) { const CWalletTx* pcoin = &(*it).second; if (pcoin->IsCoinStake() && pcoin->GetBlocksToMaturity() > 0 && pcoin->GetDepthInMainChain() > 0) nTotal += CWallet::GetCredit(*pcoin); } return nTotal; } int64 CWallet::GetNewMint() const { int64 nTotal = 0; LOCK(cs_wallet); for (map<uint256, CWalletTx>::const_iterator it = mapWallet.begin(); it != mapWallet.end(); ++it) { const CWalletTx* pcoin = &(*it).second; if (pcoin->IsCoinBase() && pcoin->GetBlocksToMaturity() > 0 && pcoin->GetDepthInMainChain() > 0) nTotal += CWallet::GetCredit(*pcoin); } return nTotal; } bool CWallet::SelectCoinsMinConf(int64 nTargetValue, unsigned int nSpendTime, int nConfMine, int nConfTheirs, vector<COutput> vCoins, set<pair<const CWalletTx*,unsigned int> >& setCoinsRet, int64& nValueRet) const { setCoinsRet.clear(); nValueRet = 0; // List of values less than target pair<int64, pair<const CWalletTx*,unsigned int> > coinLowestLarger; coinLowestLarger.first = std::numeric_limits<int64>::max(); coinLowestLarger.second.first = NULL; vector<pair<int64, pair<const CWalletTx*,unsigned int> > > vValue; int64 nTotalLower = 0; random_shuffle(vCoins.begin(), vCoins.end(), GetRandInt); BOOST_FOREACH(COutput output, vCoins) { const CWalletTx *pcoin = output.tx; if (output.nDepth < (pcoin->IsFromMe() ? nConfMine : nConfTheirs)) continue; int i = output.i; if (pcoin->nTime > nSpendTime) continue; // ppcoin: timestamp must not exceed spend time int64 n = pcoin->vout[i].nValue; pair<int64,pair<const CWalletTx*,unsigned int> > coin = make_pair(n,make_pair(pcoin, i)); if (n == nTargetValue) { setCoinsRet.insert(coin.second); nValueRet += coin.first; return true; } else if (n < nTargetValue + CENT) { vValue.push_back(coin); nTotalLower += n; } else if (n < coinLowestLarger.first) { coinLowestLarger = coin; } } if (nTotalLower == nTargetValue) { for (unsigned int i = 0; i < vValue.size(); ++i) { setCoinsRet.insert(vValue[i].second); nValueRet += vValue[i].first; } return true; } if (nTotalLower < nTargetValue) { if (coinLowestLarger.second.first == NULL) return false; setCoinsRet.insert(coinLowestLarger.second); nValueRet += coinLowestLarger.first; return true; } // Solve subset sum by stochastic approximation sort(vValue.rbegin(), vValue.rend(), CompareValueOnly()); vector<char> vfBest; int64 nBest; <API key>(vValue, nTotalLower, nTargetValue, vfBest, nBest, 1000); if (nBest != nTargetValue && nTotalLower >= nTargetValue + CENT) <API key>(vValue, nTotalLower, nTargetValue + CENT, vfBest, nBest, 1000); // If we have a bigger coin and (either the stochastic approximation didn't find a good solution, // or the next bigger coin is closer), return the bigger coin if (coinLowestLarger.second.first && ((nBest != nTargetValue && nBest < nTargetValue + CENT) || coinLowestLarger.first <= nBest)) { setCoinsRet.insert(coinLowestLarger.second); nValueRet += coinLowestLarger.first; } else { for (unsigned int i = 0; i < vValue.size(); i++) if (vfBest[i]) { setCoinsRet.insert(vValue[i].second); nValueRet += vValue[i].first; } if (fDebug && GetBoolArg("-printpriority")) { / debug print printf("SelectCoins() best subset: "); for (unsigned int i = 0; i < vValue.size(); i++) if (vfBest[i]) printf("%s ", FormatMoney(vValue[i].first).c_str()); printf("total %s\n", FormatMoney(nBest).c_str()); } } return true; } bool CWallet::SelectCoins(int64 nTargetValue, unsigned int nSpendTime, set<pair<const CWalletTx*,unsigned int> >& setCoinsRet, int64& nValueRet) const { vector<COutput> vCoins; AvailableCoins(vCoins); return (SelectCoinsMinConf(nTargetValue, nSpendTime, 1, 6, vCoins, setCoinsRet, nValueRet) || SelectCoinsMinConf(nTargetValue, nSpendTime, 1, 1, vCoins, setCoinsRet, nValueRet) || SelectCoinsMinConf(nTargetValue, nSpendTime, 0, 1, vCoins, setCoinsRet, nValueRet)); } bool CWallet::CreateTransaction(const vector<pair<CScript, int64> >& vecSend, CWalletTx& wtxNew, CReserveKey& reservekey, int64& nFeeRet) { int64 nValue = 0; BOOST_FOREACH (const PAIRTYPE(CScript, int64)& s, vecSend) { if (nValue < 0) return false; nValue += s.second; } if (vecSend.empty() || nValue < 0) return false; wtxNew.BindWallet(this); { LOCK2(cs_main, cs_wallet); // txdb must be opened before the mapWallet lock CTxDB txdb("r"); { nFeeRet = nTransactionFee; loop { wtxNew.vin.clear(); wtxNew.vout.clear(); wtxNew.fFromMe = true; int64 nTotalValue = nValue + nFeeRet; double dPriority = 0; // vouts to the payees BOOST_FOREACH (const PAIRTYPE(CScript, int64)& s, vecSend) wtxNew.vout.push_back(CTxOut(s.second, s.first)); // Choose coins to use set<pair<const CWalletTx*,unsigned int> > setCoins; int64 nValueIn = 0; if (!SelectCoins(nTotalValue, wtxNew.nTime, setCoins, nValueIn)) return false; BOOST_FOREACH(PAIRTYPE(const CWalletTx*, unsigned int) pcoin, setCoins) { int64 nCredit = pcoin.first->vout[pcoin.second].nValue; dPriority += (double)nCredit * pcoin.first->GetDepthInMainChain(); } int64 nChange = nValueIn - nValue - nFeeRet; // if sub-cent change is required, the fee must be raised to at least MIN_TX_FEE // or until nChange becomes zero // NOTE: this depends on the exact behaviour of GetMinFee if (nFeeRet < MIN_TX_FEE && nChange > 0 && nChange < CENT) { int64 nMoveToFee = min(nChange, MIN_TX_FEE - nFeeRet); nChange -= nMoveToFee; nFeeRet += nMoveToFee; } // ppcoin: sub-cent change is moved to fee if (nChange > 0 && nChange < MIN_TXOUT_AMOUNT) { nFeeRet += nChange; nChange = 0; } if (nChange > 0) { // Note: We use a new key here to keep it from being obvious which side is the change. // The drawback is that by not reusing a previous key, the change may be lost if a // backup is restored, if the backup doesn't have the new private key for the change. // If we reused the old key, it would be possible to add code to look for and // rediscover unknown transactions that were written with keys of ours to recover // post-backup change. // Reserve a new key pair from key pool CPubKey vchPubKey = reservekey.GetReservedKey(); // assert(mapKeys.count(vchPubKey)); // Fill a vout to ourself // TODO: pass in scriptChange instead of reservekey so // change transaction isn't always <API key> CScript scriptChange; scriptChange.SetDestination(vchPubKey.GetID()); // Insert change txn at random position: vector<CTxOut>::iterator position = wtxNew.vout.begin()+GetRandInt(wtxNew.vout.size()); wtxNew.vout.insert(position, CTxOut(nChange, scriptChange)); } else reservekey.ReturnKey(); // Fill vin BOOST_FOREACH(const PAIRTYPE(const CWalletTx*,unsigned int)& coin, setCoins) wtxNew.vin.push_back(CTxIn(coin.first->GetHash(),coin.second)); // Sign int nIn = 0; BOOST_FOREACH(const PAIRTYPE(const CWalletTx*,unsigned int)& coin, setCoins) if (!SignSignature(*this, *coin.first, wtxNew, nIn++)) return false; // Limit size unsigned int nBytes = ::GetSerializeSize(*(CTransaction*)&wtxNew, SER_NETWORK, PROTOCOL_VERSION); if (nBytes >= MAX_BLOCK_SIZE_GEN/5) return false; dPriority /= nBytes; // Check that enough fee is included int64 nPayFee = nTransactionFee * (1 + (int64)nBytes / 1000); int64 nMinFee = wtxNew.GetMinFee(1, false, GMF_SEND); if (nFeeRet < max(nPayFee, nMinFee)) { nFeeRet = max(nPayFee, nMinFee); continue; } // Fill vtxPrev by copying from previous transactions vtxPrev wtxNew.<API key>(txdb); wtxNew.<API key> = true; break; } } } return true; } bool CWallet::CreateTransaction(CScript scriptPubKey, int64 nValue, CWalletTx& wtxNew, CReserveKey& reservekey, int64& nFeeRet) { vector< pair<CScript, int64> > vecSend; vecSend.push_back(make_pair(scriptPubKey, nValue)); return CreateTransaction(vecSend, wtxNew, reservekey, nFeeRet); } // ppcoin: create coin stake transaction bool CWallet::CreateCoinStake(const CKeyStore& keystore, unsigned int nBits, int64 nSearchInterval, CTransaction& txNew) { // The following split & combine thresholds are important to security // Should not be adjusted if you don't understand the consequences static unsigned int nStakeSplitAge = (60 * 60 * 24 * 90); int64 nCombineThreshold = <API key>(GetLastBlockIndex(pindexBest, false)->nBits, GetLastBlockIndex(pindexBest, false)->nHeight) / 3; CBigNum bnTargetPerCoinDay; bnTargetPerCoinDay.SetCompact(nBits); LOCK2(cs_main, cs_wallet); txNew.vin.clear(); txNew.vout.clear(); // Mark coin stake transaction CScript scriptEmpty; scriptEmpty.clear(); txNew.vout.push_back(CTxOut(0, scriptEmpty)); // Choose coins to use int64 nBalance = GetBalance(); int64 nReserveBalance = 0; if (mapArgs.count("-reservebalance") && !ParseMoney(mapArgs["-reservebalance"], nReserveBalance)) return error("CreateCoinStake : invalid reserve balance amount"); if (nBalance <= nReserveBalance) return false; set<pair<const CWalletTx*,unsigned int> > setCoins; vector<const CWalletTx*> vwtxPrev; int64 nValueIn = 0; if (!SelectCoins(nBalance - nReserveBalance, txNew.nTime, setCoins, nValueIn)) return false; if (setCoins.empty()) return false; int64 nCredit = 0; CScript scriptPubKeyKernel; BOOST_FOREACH(PAIRTYPE(const CWalletTx*, unsigned int) pcoin, setCoins) { CTxDB txdb("r"); CTxIndex txindex; if (!txdb.ReadTxIndex(pcoin.first->GetHash(), txindex)) continue; // Read block header CBlock block; if (!block.ReadFromDisk(txindex.pos.nFile, txindex.pos.nBlockPos, false)) continue; static int <API key> = 60; if (block.GetBlockTime() + nStakeMinAge > txNew.nTime - <API key>) continue; // only count coins meeting min age requirement bool fKernelFound = false; for (unsigned int n=0; n<min(nSearchInterval,(int64)<API key>) && !fKernelFound && !fShutdown; n++) { // Search backward in time from the given txNew timestamp // Search nSearchInterval seconds back up to <API key> uint256 hashProofOfStake = 0; COutPoint prevoutStake = COutPoint(pcoin.first->GetHash(), pcoin.second); if (<API key>(nBits, block, txindex.pos.nTxPos - txindex.pos.nBlockPos, *pcoin.first, prevoutStake, txNew.nTime - n, hashProofOfStake)) { // Found a kernel if (fDebug && GetBoolArg("-printcoinstake")) printf("CreateCoinStake : kernel found\n"); vector<valtype> vSolutions; txnouttype whichType; CScript scriptPubKeyOut; scriptPubKeyKernel = pcoin.first->vout[pcoin.second].scriptPubKey; if (!Solver(scriptPubKeyKernel, whichType, vSolutions)) { if (fDebug && GetBoolArg("-printcoinstake")) printf("CreateCoinStake : failed to parse kernel\n"); break; } if (fDebug && GetBoolArg("-printcoinstake")) printf("CreateCoinStake : parsed kernel type=%d\n", whichType); if (whichType != TX_PUBKEY && whichType != TX_PUBKEYHASH) { if (fDebug && GetBoolArg("-printcoinstake")) printf("CreateCoinStake : no support for kernel type=%d\n", whichType); break; // only support pay to public key and pay to address } if (whichType == TX_PUBKEYHASH) // pay to address type { // convert to pay to public key type CKey key; if (!keystore.GetKey(uint160(vSolutions[0]), key)) { if (fDebug && GetBoolArg("-printcoinstake")) printf("CreateCoinStake : failed to get key for kernel type=%d\n", whichType); break; // unable to find corresponding public key } scriptPubKeyOut << key.GetPubKey() << OP_CHECKSIG; } else scriptPubKeyOut = scriptPubKeyKernel; txNew.nTime -= n; txNew.vin.push_back(CTxIn(pcoin.first->GetHash(), pcoin.second)); nCredit += pcoin.first->vout[pcoin.second].nValue; vwtxPrev.push_back(pcoin.first); txNew.vout.push_back(CTxOut(0, scriptPubKeyOut)); if (block.GetBlockTime() + nStakeSplitAge > txNew.nTime) txNew.vout.push_back(CTxOut(0, scriptPubKeyOut)); //split stake if (fDebug && GetBoolArg("-printcoinstake")) printf("CreateCoinStake : added kernel type=%d\n", whichType); fKernelFound = true; break; } } if (fKernelFound || fShutdown) break; // if kernel is found stop searching } if (nCredit == 0 || nCredit > nBalance - nReserveBalance) return false; BOOST_FOREACH(PAIRTYPE(const CWalletTx*, unsigned int) pcoin, setCoins) { // Attempt to add more inputs // Only add coins of the same key/address as kernel if (txNew.vout.size() == 2 && ((pcoin.first->vout[pcoin.second].scriptPubKey == scriptPubKeyKernel || pcoin.first->vout[pcoin.second].scriptPubKey == txNew.vout[1].scriptPubKey)) && pcoin.first->GetHash() != txNew.vin[0].prevout.hash) { // Stop adding more inputs if already too many inputs if (txNew.vin.size() >= 100) break; // Stop adding more inputs if value is already pretty significant if (nCredit > nCombineThreshold) break; // Stop adding inputs if reached reserve limit if (nCredit + pcoin.first->vout[pcoin.second].nValue > nBalance - nReserveBalance) break; // Do not add additional significant input if (pcoin.first->vout[pcoin.second].nValue > nCombineThreshold) continue; // Do not add input that is still too young if (pcoin.first->nTime + nStakeMaxAge > txNew.nTime) continue; txNew.vin.push_back(CTxIn(pcoin.first->GetHash(), pcoin.second)); nCredit += pcoin.first->vout[pcoin.second].nValue; vwtxPrev.push_back(pcoin.first); } } // Calculate coin age reward { uint64 nCoinAge; CTxDB txdb("r"); if (!txNew.GetCoinAge(txdb, nCoinAge)) return error("CreateCoinStake : failed to calculate coin age"); nCredit += <API key>(nCoinAge, nBits, txNew.nTime); } int64 nMinFee = 0; loop { // Set output amount if (txNew.vout.size() == 3) { if( GetLastBlockIndex(pindexBest, false)->nHeight > 106750 ) // Fix rounded txNew.vout[1].nValue = ((nCredit - nMinFee) / 2 ); else txNew.vout[1].nValue = ((nCredit - nMinFee) / 2 / CENT ) * CENT; txNew.vout[2].nValue = nCredit - nMinFee - txNew.vout[1].nValue; } else txNew.vout[1].nValue = nCredit - nMinFee; // Sign int nIn = 0; BOOST_FOREACH(const CWalletTx* pcoin, vwtxPrev) { if (!SignSignature(*this, *pcoin, txNew, nIn++)) return error("CreateCoinStake : failed to sign coinstake"); } // Limit size unsigned int nBytes = ::GetSerializeSize(txNew, SER_NETWORK, PROTOCOL_VERSION); if (nBytes >= MAX_BLOCK_SIZE_GEN/5) return error("CreateCoinStake : exceeded coinstake size limit"); // Check enough fee is paid if (nMinFee < txNew.GetMinFee() - MIN_TX_FEE) { nMinFee = txNew.GetMinFee() - MIN_TX_FEE; continue; // try signing again } else { if (fDebug && GetBoolArg("-printfee")) printf("CreateCoinStake : fee for coinstake %s\n", FormatMoney(nMinFee).c_str()); break; } } // Successfully generated coinstake return true; } // Call after CreateTransaction unless you want to abort bool CWallet::CommitTransaction(CWalletTx& wtxNew, CReserveKey& reservekey) { { LOCK2(cs_main, cs_wallet); printf("CommitTransaction:\n%s", wtxNew.ToString().c_str()); { // This is only to keep the database open to defeat the auto-flush for the // duration of this scope. This is the only place where this optimization // maybe makes sense; please don't do it anywhere else. CWalletDB* pwalletdb = fFileBacked ? new CWalletDB(strWalletFile,"r") : NULL; // Take key pair from key pool so it won't be used again reservekey.KeepKey(); // Add tx to wallet, because if it has change it's also ours, // otherwise just for transaction history. AddToWallet(wtxNew); // Mark old coins as spent set<CWalletTx*> setCoins; BOOST_FOREACH(const CTxIn& txin, wtxNew.vin) { CWalletTx &coin = mapWallet[txin.prevout.hash]; coin.BindWallet(this); coin.MarkSpent(txin.prevout.n); coin.WriteToDisk(); <API key>(this, coin.GetHash(), CT_UPDATED); } if (fFileBacked) delete pwalletdb; } // Track how many getdata requests our transaction gets mapRequestCount[wtxNew.GetHash()] = 0; // Broadcast if (!wtxNew.AcceptToMemoryPool()) { // This must not fail. The transaction has already been signed and recorded. printf("CommitTransaction() : Error: Transaction not valid"); return false; } wtxNew.<API key>(); } return true; } string CWallet::SendMoney(CScript scriptPubKey, int64 nValue, CWalletTx& wtxNew, bool fAskFee) { CReserveKey reservekey(this); int64 nFeeRequired; if (IsLocked()) { string strError = _("Error: Wallet locked, unable to create transaction "); printf("SendMoney() : %s", strError.c_str()); return strError; } if (<API key>) { string strError = _("Error: Wallet unlocked for block minting only, unable to create transaction."); printf("SendMoney() : %s", strError.c_str()); return strError; } if (!CreateTransaction(scriptPubKey, nValue, wtxNew, reservekey, nFeeRequired)) { string strError; if (nValue + nFeeRequired > GetBalance()) strError = strprintf(_("Error: This transaction requires a transaction fee of at least %s because of its amount, complexity, or use of recently received funds "), FormatMoney(nFeeRequired).c_str()); else strError = _("Error: Transaction creation failed "); printf("SendMoney() : %s", strError.c_str()); return strError; } if (fAskFee && !uiInterface.ThreadSafeAskFee(nFeeRequired, _("Sending..."))) return "ABORTED"; if (!CommitTransaction(wtxNew, reservekey)) return _("Error: The transaction was rejected. This might happen if some of the coins in your wallet were already spent, such as if you used a copy of wallet.dat and coins were spent in the copy but not marked as spent here."); return ""; } string CWallet::<API key>(const CTxDestination& address, int64 nValue, CWalletTx& wtxNew, bool fAskFee) { // Check amount if (nValue <= 0) return _("Invalid amount"); if (nValue + nTransactionFee > GetBalance()) return _("Insufficient funds"); // Parse Bitcoin address CScript scriptPubKey; scriptPubKey.SetDestination(address); return SendMoney(scriptPubKey, nValue, wtxNew, fAskFee); } DBErrors CWallet::LoadWallet(bool& fFirstRunRet) { if (!fFileBacked) return DB_LOAD_OK; fFirstRunRet = false; DBErrors nLoadWalletRet = CWalletDB(strWalletFile,"cr+").LoadWallet(this); if (nLoadWalletRet == DB_NEED_REWRITE) { if (CDB::Rewrite(strWalletFile, "\x04pool")) { setKeyPool.clear(); // Note: can't top-up keypool here, because wallet is locked. // User will be prompted to unlock wallet the next operation // the requires a new key. } } if (nLoadWalletRet != DB_LOAD_OK) return nLoadWalletRet; fFirstRunRet = !vchDefaultKey.IsValid(); NewThread(ThreadFlushWalletDB, &strWalletFile); return DB_LOAD_OK; } bool CWallet::SetAddressBookName(const CTxDestination& address, const string& strName) { std::map<CTxDestination, std::string>::iterator mi = mapAddressBook.find(address); mapAddressBook[address] = strName; <API key>(this, address, strName, ::IsMine(*this, address), (mi == mapAddressBook.end()) ? CT_NEW : CT_UPDATED); if (!fFileBacked) return false; return CWalletDB(strWalletFile).WriteName(CBitcoinAddress(address).ToString(), strName); } bool CWallet::DelAddressBookName(const CTxDestination& address) { mapAddressBook.erase(address); <API key>(this, address, "", ::IsMine(*this, address), CT_DELETED); if (!fFileBacked) return false; return CWalletDB(strWalletFile).EraseName(CBitcoinAddress(address).ToString()); } void CWallet::PrintWallet(const CBlock& block) { { LOCK(cs_wallet); if (block.IsProofOfWork() && mapWallet.count(block.vtx[0].GetHash())) { CWalletTx& wtx = mapWallet[block.vtx[0].GetHash()]; printf(" mine: %d %d %"PRI64d"", wtx.GetDepthInMainChain(), wtx.GetBlocksToMaturity(), wtx.GetCredit()); } if (block.IsProofOfStake() && mapWallet.count(block.vtx[1].GetHash())) { CWalletTx& wtx = mapWallet[block.vtx[1].GetHash()]; printf(" stake: %d %d %"PRI64d"", wtx.GetDepthInMainChain(), wtx.GetBlocksToMaturity(), wtx.GetCredit()); } } printf("\n"); } bool CWallet::GetTransaction(const uint256 &hashTx, CWalletTx& wtx) { { LOCK(cs_wallet); map<uint256, CWalletTx>::iterator mi = mapWallet.find(hashTx); if (mi != mapWallet.end()) { wtx = (*mi).second; return true; } } return false; } bool CWallet::SetDefaultKey(const CPubKey &vchPubKey) { if (fFileBacked) { if (!CWalletDB(strWalletFile).WriteDefaultKey(vchPubKey)) return false; } vchDefaultKey = vchPubKey; return true; } bool GetWalletFile(CWallet* pwallet, string &strWalletFileOut) { if (!pwallet->fFileBacked) return false; strWalletFileOut = pwallet->strWalletFile; return true; } // Mark old keypool keys as used, // and generate all new keys bool CWallet::NewKeyPool() { { LOCK(cs_wallet); CWalletDB walletdb(strWalletFile); BOOST_FOREACH(int64 nIndex, setKeyPool) walletdb.ErasePool(nIndex); setKeyPool.clear(); if (IsLocked()) return false; int64 nKeys = max(GetArg("-keypool", 100), (int64)0); for (int i = 0; i < nKeys; i++) { int64 nIndex = i+1; walletdb.WritePool(nIndex, CKeyPool(GenerateNewKey())); setKeyPool.insert(nIndex); } printf("CWallet::NewKeyPool wrote %"PRI64d" new keys\n", nKeys); } return true; } bool CWallet::TopUpKeyPool() { { LOCK(cs_wallet); if (IsLocked()) return false; CWalletDB walletdb(strWalletFile); // Top up key pool unsigned int nTargetSize = max(GetArg("-keypool", 100), 0LL); while (setKeyPool.size() < (nTargetSize + 1)) { int64 nEnd = 1; if (!setKeyPool.empty()) nEnd = *(--setKeyPool.end()) + 1; if (!walletdb.WritePool(nEnd, CKeyPool(GenerateNewKey()))) throw runtime_error("TopUpKeyPool() : writing generated key failed"); setKeyPool.insert(nEnd); printf("keypool added key %"PRI64d", size=%"PRIszu"\n", nEnd, setKeyPool.size()); } } return true; } void CWallet::<API key>(int64& nIndex, CKeyPool& keypool) { nIndex = -1; keypool.vchPubKey = CPubKey(); { LOCK(cs_wallet); if (!IsLocked()) TopUpKeyPool(); // Get the oldest key if(setKeyPool.empty()) return; CWalletDB walletdb(strWalletFile); nIndex = *(setKeyPool.begin()); setKeyPool.erase(setKeyPool.begin()); if (!walletdb.ReadPool(nIndex, keypool)) throw runtime_error("<API key>() : read failed"); if (!HaveKey(keypool.vchPubKey.GetID())) throw runtime_error("<API key>() : unknown key in key pool"); assert(keypool.vchPubKey.IsValid()); if (fDebug && GetBoolArg("-printkeypool")) printf("keypool reserve %"PRI64d"\n", nIndex); } } int64 CWallet::AddReserveKey(const CKeyPool& keypool) { { LOCK2(cs_main, cs_wallet); CWalletDB walletdb(strWalletFile); int64 nIndex = 1 + *(--setKeyPool.end()); if (!walletdb.WritePool(nIndex, keypool)) throw runtime_error("AddReserveKey() : writing added key failed"); setKeyPool.insert(nIndex); return nIndex; } return -1; } void CWallet::KeepKey(int64 nIndex) { // Remove from key pool if (fFileBacked) { CWalletDB walletdb(strWalletFile); walletdb.ErasePool(nIndex); } if(fDebug) printf("keypool keep %"PRI64d"\n", nIndex); } void CWallet::ReturnKey(int64 nIndex) { // Return to key pool { LOCK(cs_wallet); setKeyPool.insert(nIndex); } if(fDebug) printf("keypool return %"PRI64d"\n", nIndex); } bool CWallet::GetKeyFromPool(CPubKey& result, bool fAllowReuse) { int64 nIndex = 0; CKeyPool keypool; { LOCK(cs_wallet); <API key>(nIndex, keypool); if (nIndex == -1) { if (fAllowReuse && vchDefaultKey.IsValid()) { result = vchDefaultKey; return true; } if (IsLocked()) return false; result = GenerateNewKey(); return true; } KeepKey(nIndex); result = keypool.vchPubKey; } return true; } int64 CWallet::<API key>() { int64 nIndex = 0; CKeyPool keypool; <API key>(nIndex, keypool); if (nIndex == -1) return GetTime(); ReturnKey(nIndex); return keypool.nTime; } std::map<CTxDestination, int64> CWallet::GetAddressBalances() { map<CTxDestination, int64> balances; { LOCK(cs_wallet); BOOST_FOREACH(PAIRTYPE(uint256, CWalletTx) walletEntry, mapWallet) { CWalletTx *pcoin = &walletEntry.second; if (!pcoin->IsFinal() || !pcoin->IsConfirmed()) continue; if ((pcoin->IsCoinBase() || pcoin->IsCoinStake()) && pcoin->GetBlocksToMaturity() > 0) continue; int nDepth = pcoin->GetDepthInMainChain(); if (nDepth < (pcoin->IsFromMe() ? 0 : 1)) continue; for (unsigned int i = 0; i < pcoin->vout.size(); i++) { CTxDestination addr; if (!IsMine(pcoin->vout[i])) continue; if(!ExtractDestination(pcoin->vout[i].scriptPubKey, addr)) continue; int64 n = pcoin->IsSpent(i) ? 0 : pcoin->vout[i].nValue; if (!balances.count(addr)) balances[addr] = 0; balances[addr] += n; } } } return balances; } set< set<CTxDestination> > CWallet::GetAddressGroupings() { set< set<CTxDestination> > groupings; set<CTxDestination> grouping; BOOST_FOREACH(PAIRTYPE(uint256, CWalletTx) walletEntry, mapWallet) { CWalletTx *pcoin = &walletEntry.second; if (pcoin->vin.size() > 0 && IsMine(pcoin->vin[0])) { // group all input addresses with each other BOOST_FOREACH(CTxIn txin, pcoin->vin) { CTxDestination address; if(!ExtractDestination(mapWallet[txin.prevout.hash].vout[txin.prevout.n].scriptPubKey, address)) continue; grouping.insert(address); } // group change with input addresses BOOST_FOREACH(CTxOut txout, pcoin->vout) if (IsChange(txout)) { CWalletTx tx = mapWallet[pcoin->vin[0].prevout.hash]; CTxDestination txoutAddr; if(!ExtractDestination(txout.scriptPubKey, txoutAddr)) continue; grouping.insert(txoutAddr); } groupings.insert(grouping); grouping.clear(); } // group lone addrs by themselves for (unsigned int i = 0; i < pcoin->vout.size(); i++) if (IsMine(pcoin->vout[i])) { CTxDestination address; if(!ExtractDestination(pcoin->vout[i].scriptPubKey, address)) continue; grouping.insert(address); groupings.insert(grouping); grouping.clear(); } } set< set<CTxDestination>* > uniqueGroupings; // a set of pointers to groups of addresses map< CTxDestination, set<CTxDestination>* > setmap; // map addresses to the unique group containing it BOOST_FOREACH(set<CTxDestination> grouping, groupings) { // make a set of all the groups hit by this new group set< set<CTxDestination>* > hits; map< CTxDestination, set<CTxDestination>* >::iterator it; BOOST_FOREACH(CTxDestination address, grouping) if ((it = setmap.find(address)) != setmap.end()) hits.insert((*it).second); // merge all hit groups into a new single group and delete old groups set<CTxDestination>* merged = new set<CTxDestination>(grouping); BOOST_FOREACH(set<CTxDestination>* hit, hits) { merged->insert(hit->begin(), hit->end()); uniqueGroupings.erase(hit); delete hit; } uniqueGroupings.insert(merged); // update setmap BOOST_FOREACH(CTxDestination element, *merged) setmap[element] = merged; } set< set<CTxDestination> > ret; BOOST_FOREACH(set<CTxDestination>* uniqueGrouping, uniqueGroupings) { ret.insert(*uniqueGrouping); delete uniqueGrouping; } return ret; } // ppcoin: check 'spent' consistency between wallet and txindex // ppcoin: fix wallet spent state according to txindex void CWallet::FixSpentCoins(int& nMismatchFound, int64& nBalanceInQuestion, bool fCheckOnly) { nMismatchFound = 0; nBalanceInQuestion = 0; LOCK(cs_wallet); vector<CWalletTx*> vCoins; vCoins.reserve(mapWallet.size()); for (map<uint256, CWalletTx>::iterator it = mapWallet.begin(); it != mapWallet.end(); ++it) vCoins.push_back(&(*it).second); CTxDB txdb("r"); BOOST_FOREACH(CWalletTx* pcoin, vCoins) { // Find the corresponding transaction index CTxIndex txindex; if (!txdb.ReadTxIndex(pcoin->GetHash(), txindex)) continue; for (unsigned int n=0; n < pcoin->vout.size(); n++) { if (IsMine(pcoin->vout[n]) && pcoin->IsSpent(n) && (txindex.vSpent.size() <= n || txindex.vSpent[n].IsNull())) { printf("FixSpentCoins found lost coin %sppc %s[%d], %s\n", FormatMoney(pcoin->vout[n].nValue).c_str(), pcoin->GetHash().ToString().c_str(), n, fCheckOnly? "repair not attempted" : "repairing"); nMismatchFound++; nBalanceInQuestion += pcoin->vout[n].nValue; if (!fCheckOnly) { pcoin->MarkUnspent(n); pcoin->WriteToDisk(); } } else if (IsMine(pcoin->vout[n]) && !pcoin->IsSpent(n) && (txindex.vSpent.size() > n && !txindex.vSpent[n].IsNull())) { printf("FixSpentCoins found spent coin %sppc %s[%d], %s\n", FormatMoney(pcoin->vout[n].nValue).c_str(), pcoin->GetHash().ToString().c_str(), n, fCheckOnly? "repair not attempted" : "repairing"); nMismatchFound++; nBalanceInQuestion += pcoin->vout[n].nValue; if (!fCheckOnly) { pcoin->MarkSpent(n); pcoin->WriteToDisk(); } } } } } // ppcoin: disable transaction (only for coinstake) void CWallet::DisableTransaction(const CTransaction &tx) { if (!tx.IsCoinStake() || !IsFromMe(tx)) return; // only disconnecting coinstake requires marking input unspent LOCK(cs_wallet); BOOST_FOREACH(const CTxIn& txin, tx.vin) { map<uint256, CWalletTx>::iterator mi = mapWallet.find(txin.prevout.hash); if (mi != mapWallet.end()) { CWalletTx& prev = (*mi).second; if (txin.prevout.n < prev.vout.size() && IsMine(prev.vout[txin.prevout.n])) { prev.MarkUnspent(txin.prevout.n); prev.WriteToDisk(); } } } } CPubKey CReserveKey::GetReservedKey() { if (nIndex == -1) { CKeyPool keypool; pwallet-><API key>(nIndex, keypool); if (nIndex != -1) vchPubKey = keypool.vchPubKey; else { printf("CReserveKey::GetReservedKey(): Warning: Using default key instead of a new key, top up your keypool!"); vchPubKey = pwallet->vchDefaultKey; } } assert(vchPubKey.IsValid()); return vchPubKey; } void CReserveKey::KeepKey() { if (nIndex != -1) pwallet->KeepKey(nIndex); nIndex = -1; vchPubKey = CPubKey(); } void CReserveKey::ReturnKey() { if (nIndex != -1) pwallet->ReturnKey(nIndex); nIndex = -1; vchPubKey = CPubKey(); } void CWallet::GetAllReserveKeys(set<CKeyID>& setAddress) { setAddress.clear(); CWalletDB walletdb(strWalletFile); LOCK2(cs_main, cs_wallet); BOOST_FOREACH(const int64& id, setKeyPool) { CKeyPool keypool; if (!walletdb.ReadPool(id, keypool)) throw runtime_error("<API key>() : read failed"); assert(keypool.vchPubKey.IsValid()); CKeyID keyID = keypool.vchPubKey.GetID(); if (!HaveKey(keyID)) throw runtime_error("<API key>() : unknown key in key pool"); setAddress.insert(keyID); } } void CWallet::UpdatedTransaction(const uint256 &hashTx) { { LOCK(cs_wallet); // Only notify UI if this transaction is in this wallet map<uint256, CWalletTx>::const_iterator mi = mapWallet.find(hashTx); if (mi != mapWallet.end()) <API key>(this, hashTx, CT_UPDATED); } }
# <API key>: true email_name_format = 'urn:oasis:names:tc:SAML:1.1:nameid-format:emailAddress' saml_options = { <API key>: ENV['SAML_REDIRECT_URL'], issuer: ENV['SAML_ISSUER'], idp_sso_target_url: ENV['SAML_SIGNIN_URL'], <API key>: ENV['SAML_FINGERPRINT'], <API key>: ENV['SAML_NAME_FORMAT'] || email_name_format } dev_options = { fields: [:name, :first_name, :last_name, :email], uid_field: :email } Rails.application.config.middleware.use OmniAuth::Builder do auth_provider = ENV['AUTH_PROVIDER'] || 'google_oauth2' google_id = ENV['GOOGLE_CLIENT_ID'] google_secret = ENV['<API key>'] provider :developer, dev_options if Rails.env.development? && auth_provider == 'developer' provider :google_oauth2, google_id, google_secret if auth_provider == 'google_oauth2' provider :saml, saml_options if auth_provider == 'saml' end
/* global describe it before beforeEach afterEach */ /* eslint no-new: 0 */ var chai = require('chai') var async = require('async') var bitcore = require('bitcore-lib') var extend = require('shallow-extend') var factories = require('../test/factories/factories') var messages = require('../lib/messages') var drivers = require('../lib/drivers') var globals = require('./fixtures/globals') var txDecoder = require('../lib/tx_decoder') var expect = chai.expect var Item = messages.Item var Transaction = bitcore.Transaction var TxDecoder = txDecoder.TxDecoder factories.dz(chai) describe('Item', function () { var connection = null before(function (next) { connection = new drivers.FakeChain({ blockHeight: messages.<API key>}, next) }) afterEach(function (next) { connection.clearTransactions(next) }) it('has accessors', function () { var item = chai.factory.create('item', connection) expect(item.description).to.equal('Item Description') expect(item.priceCurrency).to.equal('BTC') expect(item.priceInUnits).to.equal(100000000) expect(item.expirationIn).to.equal(6) expect(item.latitude).to.equal(51.500782) expect(item.longitude).to.equal(-0.124669) expect(item.radius).to.equal(1000) expect(item.receiverAddr).to.equal('<API key>') expect(item.senderAddr).to.be.undefined }) describe('burn addresses', function () { it('supports 6 digit distances', function () { [90, 0, -90, 51.500782, -51.500782].forEach(function (lat) { [90, 0, -90, 51.500782, -51.500782].forEach(function (lon) { [9, 8, 5, 2, 0, 101, 11010, 999999, 100000].forEach(function (radius) { var addr = chai.factory.create('item', connection, {radius: radius, latitude: lat, longitude: lon}).receiverAddr expect(addr.length).to.equal(34) var parts = /^mfZ([0-9X]{9})([0-9X]{9})([0-9X]{6})/.exec(addr) parts = parts.map(function (p) { return parseInt(p.replace(/X/g, 0), 10) }) expect(parts[1]).to.equal(Math.floor((lat + 90) * 1000000)) expect(parts[2]).to.equal(Math.floor((lon + 180) * 1000000)) expect(parts[3]).to.equal(radius) }) }) }) }) }) describe('serialization', function () { it('serializes toTransaction', function () { expect(chai.factory.create('item', connection).toTransaction()).to.eql( {tip: 40000, receiverAddr: '<API key>', data: new Buffer([73, 84, 67, 82, 84, 69, 1, 100, 16, 73, 116, 101, 109, 32, 68, 101, 115, 99, 114, 105, 112, 116, 105, 111, 110, 1, 99, 3, 66, 84, 67, 1, 112, 254, 0, 225, 245, 5, 1, 101, 6])}) }) }) describe('#save() and #find()', function () { it('persists and loads', function (next) { chai.factory.create('item', connection).save(globals.testerPrivateKey, function (err, createItem) { if (err) throw err expect(createItem.txid).to.be.a('string') expect(createItem.description).to.equal('Item Description') expect(createItem.priceCurrency).to.equal('BTC') expect(createItem.priceInUnits).to.equal(100000000) expect(createItem.expirationIn).to.equal(6) expect(createItem.latitude).to.equal(51.500782) expect(createItem.longitude).to.equal(-0.124669) expect(createItem.radius).to.equal(1000) expect(createItem.receiverAddr).to.equal('<API key>') expect(createItem.senderAddr).to.equal(globals.testerPublicKey) Item.find(connection, createItem.txid, function (err, findItem) { if (err) throw err expect(findItem.txid).to.be.a('string') expect(findItem.description).to.equal('Item Description') expect(findItem.priceCurrency).to.equal('BTC') expect(findItem.priceInUnits).to.equal(100000000) expect(findItem.expirationIn).to.equal(6) expect(findItem.latitude).to.equal(51.500782) expect(findItem.longitude).to.equal(-0.124669) expect(findItem.radius).to.equal(1000) expect(findItem.receiverAddr).to.equal('<API key>') expect(findItem.senderAddr).to.equal(globals.testerPublicKey) next() }) }) }) it('updates must be addressed to self', function (nextSpec) { var createTxid var updateTxid async.series([ function (next) { chai.factory.create('item', connection).save(globals.testerPrivateKey, function (err, createItem) { if (err) throw err createTxid = createItem.txid next() }) }, function (next) { new Item(connection, {createTxid: createTxid, description: 'xyz'}).save(globals.testerPrivateKey, function (err, updateItem) { if (err) throw err updateTxid = updateItem.txid next() }) }, function (next) { Item.find(connection, updateTxid, function (err, findItem) { if (err) throw err expect(findItem.txid).to.be.a('string') expect(findItem.description).to.equal('xyz') expect(findItem.messageType).to.equal('ITUPDT') expect(findItem.receiverAddr).to.equal(globals.testerPublicKey) expect(findItem.senderAddr).to.equal(globals.testerPublicKey) next() }) } ], nextSpec) }) }) describe('validations', function () { it('validates default build', function (nextSpec) { chai.factory.create('item', connection).isValid( function (err, res) { if (err) throw err expect(res).to.be.null nextSpec() }) }) it('validates minimal item', function (nextSpec) { new Item(connection, {radius: 1, latitude: 51.500782, longitude: -0.124669}).isValid( function (err, res) { if (err) throw err expect(res).to.be.null nextSpec() }) }) it('requires output address', function (nextSpec) { new Item(connection, {description: 'Item Description', priceCurrency: 'BTC', priceInUnits: 100000000, expirationIn: 6}).isValid( function (err, res) { if (err) throw err expect(res.errors.length).to.equal(4) expect(res.errors[0].message).to.equal('receiverAddr is required') nextSpec() }) }) it('requires latitude', function (nextSpec) { chai.factory.create('item', connection, {latitude: null}).isValid( function (err, res) { if (err) throw err expect(res.errors.length).to.equal(2) expect(res.errors[0].message).to.equal('receiverAddr is required') expect(res.errors[1].message).to.equal( 'latitude is required in a newly created item') nextSpec() }) }) it('requires latitude is gte -90', function (nextSpec) { chai.factory.create('item', connection, {latitude: -90.000001}).isValid( function (err, res) { if (err) throw err expect(res.errors.length).to.equal(1) expect(res.errors[0].message).to.equal( 'latitude must be between -90 and 90') nextSpec() }) }) it('requires latitude is lte 90', function (nextSpec) { chai.factory.create('item', connection, {latitude: 90.000001}).isValid( function (err, res) { if (err) throw err expect(res.errors.length).to.equal(1) expect(res.errors[0].message).to.equal( 'latitude must be between -90 and 90') nextSpec() }) }) it('requires longitude', function (nextSpec) { chai.factory.create('item', connection, {longitude: null}).isValid( function (err, res) { if (err) throw err expect(res.errors.length).to.equal(2) expect(res.errors[0].message).to.equal('receiverAddr is required') expect(res.errors[1].message).to.equal( 'longitude is required in a newly created item') nextSpec() }) }) it('requires longitude is gte -180', function (nextSpec) { chai.factory.create('item', connection, {longitude: -180.000001}).isValid( function (err, res) { if (err) throw err expect(res.errors.length).to.equal(1) expect(res.errors[0].message).to.equal( 'longitude must be between -180 and 180') nextSpec() }) }) it('requires longitude is lte 180', function (nextSpec) { chai.factory.create('item', connection, {longitude: 180.000001}).isValid( function (err, res) { if (err) throw err expect(res.errors.length).to.equal(1) expect(res.errors[0].message).to.equal( 'longitude must be between -180 and 180') nextSpec() }) }) it('requires radius', function (nextSpec) { chai.factory.create('item', connection, {radius: null}).isValid( function (err, res) { if (err) throw err expect(res.errors.length).to.equal(2) expect(res.errors[0].message).to.equal('receiverAddr is required') expect(res.errors[1].message).to.equal( 'radius is required in a newly created item') nextSpec() }) }) it('requires radius is gte 0', function (nextSpec) { chai.factory.create('item', connection, {radius: -1}).isValid( function (err, res) { if (err) throw err expect(res.errors.length).to.equal(1) expect(res.errors[0].message).to.equal( 'radius must be between 0 and 999999') nextSpec() }) }) it('requires radius is lt 1000000', function (nextSpec) { chai.factory.create('item', connection, {radius: 1000000}).isValid( function (err, res) { if (err) throw err expect(res.errors.length).to.equal(1) expect(res.errors[0].message).to.equal( 'radius must be between 0 and 999999') nextSpec() }) }) it('descriptions must be text', function (nextSpec) { chai.factory.create('item', connection, {description: 5}).isValid( function (err, res) { if (err) throw err expect(res.errors.length).to.equal(1) expect(res.errors[0].message).to.equal( 'description is not a string') nextSpec() }) }) it('priceInUnits must be numeric', function (nextSpec) { chai.factory.create('item', connection, {priceInUnits: 'abc', priceCurrency: 'USD'}).isValid( function (err, res) { if (err) throw err expect(res.errors.length).to.equal(1) expect(res.errors[0].message).to.equal( 'priceInUnits is not an integer') nextSpec() }) }) it('expirationIn must be numeric', function (nextSpec) { chai.factory.create('item', connection, {expirationIn: 'abc'}).isValid( function (err, res) { if (err) throw err expect(res.errors.length).to.equal(1) expect(res.errors[0].message).to.equal( 'expirationIn is not an integer') nextSpec() }) }) it('price_currency must be present if price is present', function (nextSpec) { chai.factory.create('item', connection, {priceInUnits: 100, priceCurrency: undefined}).isValid( function (err, res) { if (err) throw err expect(res.errors.length).to.equal(1) expect(res.errors[0].message).to.equal( 'priceCurrency is required if priceInUnits is provided') nextSpec() }) }) }) describe('distance calculations', function () { it('calculates distance in meters between two points', function () { var nycToLondon = Item.distanceBetween(40.712784, -74.005941, 51.507351, -0.127758) var texas = Item.distanceBetween(31.428663, -99.096680, 36.279707, -102.568359) var hongKong = Item.distanceBetween(22.396428, 114.109497, 22.408489, 113.906937) expect(Math.round(nycToLondon)).to.equal(5570224) expect(Math.round(texas)).to.equal(627363) expect(Math.round(hongKong)).to.equal(20867) }) }) describe('distance calculations', function () { beforeEach(function (nextSpec) { var idFuchu async.series([ function (next) { // < 20 km from shinjuku chai.factory.create('item', connection, { description: 'Fuchu', radius: 20000, latitude: 35.688533, longitude: 139.471436 }).save(globals.testerPrivateKey, function (err, fuchu) { if (err) throw err idFuchu = fuchu.txid next() }) }, function (next) { // 36 km from shinjuku connection.<API key>() chai.factory.create('item', connection, {description: 'Abiko', radius: 20000, latitude: 35.865683, longitude: 140.031738 }).save(globals.tester2PrivateKey, next) }, function (next) { // 3 km from shinjuku chai.factory.create('item', connection, {description: 'Nakano', radius: 20000, latitude: 35.708050, longitude: 139.664383 }).save(globals.tester2PrivateKey, next) }, function (next) { connection.<API key>() // 38.5 km from shinjuku chai.factory.create('item', connection, {description: 'Chiba', radius: 20000, latitude: 35.604835, longitude: 140.105209 }).save(globals.testerPrivateKey, next) }, function (next) { // This shouldn't actually be returned, since it's an update, and // <API key> only looks for creates: chai.factory.create('item', connection, {description: 'xyz', createTxid: idFuchu }).save(globals.testerPrivateKey, next) }], nextSpec) }) it('.<API key>()', function (nextSpec) { Item.<API key>(connection, connection.blockHeight, 2, function (err, items) { if (err) throw err expect(items.length).to.equal(4) expect(items.map(function (i) { return i.description })).to.deep.equal( ['Chiba', 'Nakano', 'Abiko', 'Fuchu']) nextSpec() }) }) it('.find_in_radius()', function (nextSpec) { Item.findInRadius(connection, connection.blockHeight, 2, 35.689487, 139.691706, 20000, function (err, items) { if (err) throw err expect(items.length).to.equal(2) expect(items.map(function (i) { return i.description })).to.deep.equal( ['Nakano', 'Fuchu']) nextSpec() }) }) }) describe('problematic decodes', function () { // @Junseth Issue // txid: <SHA256-like> it('Fails to decode invalid radius transaction', function (nextSpec) { var txId = '<SHA256-like>' var txHex = '<API key>' + '<API key>' + '<API key>' + '<API key>' + '<API key>' + '<API key>' + '<API key>' + '<API key>' + '<API key>' + '<API key>' + '<API key>' + '<API key>' + '<API key>' + '<API key>' + '<API key>' + '<API key>' + '<API key>' var record = new TxDecoder(new Transaction(txHex), {prefix: 'DZ'}) var item = new Item(connection, {data: record.data, txid: txId, receiverAddr: record.receiverAddr, senderAddr: record.senderAddr}) item.isValid(function (err, res) { if (err) throw err expect(res.errors.length).to.equal(3) expect(res.errors[0].message).to.equal( 'latitude is required in a newly created item') expect(res.errors[1].message).to.equal( 'longitude is required in a newly created item') expect(res.errors[2].message).to.equal( 'radius is required in a newly created item') nextSpec() }) }) }) describe('versioning', function () { var connection = null before(function (next) { connection = new drivers.FakeChain({ blockHeight: messages.<API key>, isMutable: false}, next) }) afterEach(function (next) { connection.clearTransactions(next) }) var ITEM_UPDATE_ATTRS = { description: 'xyz', createTxid: '<SHA256-like>'} /* The max specification encoded transaction ID's as hex-strings which was * a poor use of space, and confusing. Nonetheless, legacy data should be * supported: */ it('encodes v0 items with string transaction ids', function () { var blockHeight = 389557 var item = new Item(connection, extend(ITEM_UPDATE_ATTRS, {blockHeight: blockHeight})) var data = item.toTransaction().data expect(data.toString('utf8', 0, 6)).to.equal('ITUPDT') expect(data.toString('utf8', 6, 8)).to.equal('\u0001d') expect(data.toString('utf8', 8, 12)).to.equal('\u0003xyz') // This was the problem (at 64 bytes instead of 32): expect(data.toString('utf8', 12, 15)).to.equal('\u0001t@') expect(data.toString('utf8', 15, data.length)).to.equal( ITEM_UPDATE_ATTRS.createTxid) // Now decode this item: item = new Item(connection, {data: data, blockHeight: blockHeight, receiverAddr: ITEM_UPDATE_ATTRS.receiverAddr}) expect(item.description).to.equal(ITEM_UPDATE_ATTRS.description) expect(item.invoiceTxid).to.equal(ITEM_UPDATE_ATTRS.invoiceTxid) expect(item.receiverAddr).to.equal(ITEM_UPDATE_ATTRS.receiverAddr) }) it('encodes v1 items with string transaction ids', function () { var item = new Item(connection, ITEM_UPDATE_ATTRS) var data = item.toTransaction().data expect(data.toString('utf8', 0, 6)).to.equal('ITUPDT') expect(data.toString('utf8', 6, 8)).to.equal('\u0001d') expect(data.toString('utf8', 8, 12)).to.equal('\u0003xyz') // This was the problem (at 64 bytes instead of 32): expect(data.toString('utf8', 12, 15)).to.equal('\u0001t ') expect(data.toString('hex', 15, data.length)).to.equal( ITEM_UPDATE_ATTRS.createTxid) // Now decode this item: item = new Item(connection, {data: data, receiverAddr: ITEM_UPDATE_ATTRS.receiverAddr}) expect(item.description).to.equal(ITEM_UPDATE_ATTRS.description) expect(item.invoiceTxid).to.equal(ITEM_UPDATE_ATTRS.invoiceTxid) expect(item.receiverAddr).to.equal(ITEM_UPDATE_ATTRS.receiverAddr) }) }) })
(function( window, undefined ) { var Globalize; if ( typeof require !== "undefined" && typeof exports !== "undefined" && typeof module !== "undefined" ) { // Assume CommonJS Globalize = require( "globalize" ); } else { // Global variable Globalize = window.Globalize; } Globalize.addCultureInfo( "cs-CZ", "default", { name: "cs-CZ", englishName: "Czech (Czech Republic)", nativeName: "čeština (Česká republika)", language: "cs", numberFormat: { ",": " ", ".": ",", NaN: "Není číslo", negativeInfinity: "-nekonečno", positiveInfinity: "+nekonečno", percent: { pattern: ["-n%","n%"], ",": " ", ".": "," }, currency: { pattern: ["-n $","n $"], ",": " ", ".": ",", symbol: "Kč" } }, calendars: { standard: { "/": ".", firstDay: 1, days: { names: ["neděle","pondělí","úterý","středa","čtvrtek","pátek","sobota"], namesAbbr: ["ne","po","út","st","čt","pá","so"], namesShort: ["ne","po","út","st","čt","pá","so"] }, months: { names: ["leden","únor","březen","duben","květen","červen","červenec","srpen","září","říjen","listopad","prosinec",""], namesAbbr: ["1","2","3","4","5","6","7","8","9","10","11","12",""] }, monthsGenitive: { names: ["ledna","února","března","dubna","května","června","července","srpna","září","října","listopadu","prosince",""], namesAbbr: ["1","2","3","4","5","6","7","8","9","10","11","12",""] }, AM: ["dop.","dop.","DOP."], PM: ["odp.","odp.","ODP."], eras: [{"name":"n. l.","start":null,"offset":0}], patterns: { d: "d.M.yyyy", D: "d. MMMM yyyy", t: "H:mm", T: "H:mm:ss", f: "d. MMMM yyyy H:mm", F: "d. MMMM yyyy H:mm:ss", M: "dd MMMM", Y: "MMMM yyyy" } } } }); }( this ));
{ "file": "documon/index.js", "filename": "index.js", "package": "root", "docfile": "root.html", "id": "root", "prettyLangs": [], "projectName": "Documon", "projectVersion": "0.0.1", "search": {} }
# Spreading Udaciousness # One of our modest goals is to teach everyone in the world to program and # understand computer science. To estimate how long this will take we have # developed a (very flawed!) model: # Everyone answering this question will convince a number, spread, (input to # the model) of their friends to take the course next offering. This will # continue, so that all of the newly recruited students, as well as the original # students, will convince spread of their # friends to take the following offering of the course. # recruited friends are unique, so there is no duplication among the newly # recruited students. Define a procedure, <API key>(n, spread, # target), that takes three inputs: the starting number of Udacians, the spread # rate (how many new friends each Udacian convinces to join each hexamester), # and the target number, and outputs the number of hexamesters needed to reach # (or exceed) the target. # For credit, your procedure must not use: while, for, or import math. def <API key>(n, spread, target): if n >= target: return 0 else: return 1 + <API key>((n + (n * spread)), spread, target) # 0 more needed, since n already exceeds target print(<API key>(100000, 2, 36230)) # after 1 hexamester, there will be 50000 + (50000 * 2) Udacians print(<API key>(50000, 2, 150000)) # need to match or exceed the target print(<API key>(50000, 2, 150001)) # only 12 hexamesters (2 years) to world domination! print(<API key>(20000, 2, 7 * 10 ** 9)) # more friends means faster world domination! print(<API key>(15000, 3, 7 * 10 ** 9))
from django.contrib import admin from metadata.models import * # Register your models here. admin.site.register(TanitJobsCategory) admin.site.register(KeeJobsCategory)
package main; import org.omg.CORBA.DATA_CONVERSION; import java.util.ArrayList; import java.util.Arrays; public class ClassList { public int dataset_size; public double[] label; public TreeNode[] <API key>; public double[] pred; public double[] grad; public double[] hess; public ClassList(TrainData data){ this.dataset_size = data.dataset_size; this.label = data.label; this.pred = new double[dataset_size]; this.grad = new double[dataset_size]; this.hess = new double[dataset_size]; this.<API key> = new TreeNode[dataset_size]; } public void initialize_pred(double first_round_pred){ Arrays.fill(pred, first_round_pred); } public void update_pred(double eta){ for(int i=0;i<dataset_size;i++){ pred[i] += eta * <API key>[i].leaf_score; } } public void update_grad_hess(Loss loss,double scale_pos_weight){ grad = loss.grad(pred,label); hess = loss.hess(pred,label); if(scale_pos_weight != 1.0){ for(int i=0;i<dataset_size;i++){ if(label[i]==1){ grad[i] *= scale_pos_weight; hess[i] *= scale_pos_weight; } } } } public void sampling(ArrayList<Double> row_mask){ for(int i=0;i<dataset_size;i++){ grad[i] *= row_mask.get(i); hess[i] *= row_mask.get(i); } } //TODO //parallel each col's calculation public void <API key>(int[][] <API key>){ for(int col=0;col<<API key>.length;col++){ for(int i:<API key>[col]){ TreeNode treenode = <API key>[i]; if(!treenode.is_leaf){ treenode.Grad_missing[col] += grad[i]; treenode.Hess_missing[col] += hess[i]; } } } } public void <API key>(){ for(int i=0;i<dataset_size;i++){ TreeNode treenode = <API key>[i]; if(!treenode.is_leaf){ treenode.Grad_add(grad[i]); treenode.Hess_add(hess[i]); treenode.num_sample_add(1); } } } public void <API key>(AttributeList attribute_list){ for(int i=0;i<dataset_size;i++){ TreeNode treenode = <API key>[i]; if(!treenode.is_leaf){ int split_feature = treenode.split_feature; double nan_go_to = treenode.nan_go_to; double val = attribute_list.origin_feature[i][split_feature]; //consider categorical feature if(attribute_list.cat_features_cols.contains(split_feature)){ ArrayList<Double> left_child_catvalue = treenode.<API key>; if(val==Data.NULL){ if(nan_go_to==0){ <API key>[i] = treenode.nan_child; }else if(nan_go_to==1){ <API key>[i] = treenode.left_child; }else { <API key>[i] = treenode.right_child; } }else if(left_child_catvalue.contains(val)){ <API key>[i] = treenode.left_child; }else { <API key>[i] = treenode.right_child; } }else { double split_threshold = treenode.split_threshold; if(val== Data.NULL){ if(nan_go_to==0){ <API key>[i] = treenode.nan_child; }else if(nan_go_to==1){ <API key>[i] = treenode.left_child; }else { <API key>[i] = treenode.right_child; } }else if(val<=split_threshold){ <API key>[i] = treenode.left_child; }else { <API key>[i] = treenode.right_child; } } } } } }
MIME-Version: 1.0 Server: CERN/3.0 Date: Sunday, 01-Dec-96 19:02:37 GMT Content-Type: text/html Content-Length: 14145 Last-Modified: Thursday, 02-May-96 10:38:48 GMT <!DOCTYPE HTML PUBLIC "-//IETF//DTD HTML 2.0//EN"> <!-- cs674 Final Project Short Report 5/1/96 --> <!-- Alfred Hong --> <head> <title>Regular Language to SQL Query Translation</title> </head> <body> <p align=center> <h2 align=center> Translation of Regular Questions into SQL Constructs<br> </h2> <h4 align=center> <small>COM S 674 Final Project Report - Spring 1996 </small><br><p> Alfred Hong<br> May 1, 1996<br></h4> <hr> <h3><a name="Contents">Table of Contents </a><br></h3> <ul> <li><a href="#Description">Problem Description </a> <li><a href="#Approach">General Approach </a> <li><a href="#Results">Results and Evaluation </a> <li><a href="#Discussion">Discussion, Conclusion, and Future/a> <li><a href="#Refs">References</a> </ul> <hr> <h3><a name="Description">Problem Description</a></h3><p> Web sites today that provide a query front-end to a backend database are done mostly via keyword or categorical search forms. These search parameters are preselected and usually "inhuman." Since the query parameters are preselected, the answers are fixed and static to the user. Replacing these fixed query forms with a natural language query front-end could make things more human, more natural, and more flexible. A "middleware" mechanism that converts a natural language question into the backend database language to perform the user's query request might do the job. Since relational databases are very popular, SQL will be the target database language for conversion. <p> <a href="#Contents"><i>-->Table of Contents </i></a><p> <hr> <h3><a name="Approach">General Approach</a></h3><p> The approach in general involves: <p> <ol> <li><a href="#app1">Identifying a target domain </a> for testing of concepts, <li><a href="#app2">Researching possible techniques</a> for dealing with the problem, <li>Implementation using questions the author came up with, <li><a href="#Results">Testing out implementations</a>, and <li>Refinement and retesting</a>. </ol> <p> <p> <h4><a name="app1">Identifying Target Domain </h4><p> Natural language processing is a difficult subject. To tackle the focus of this project, a specific domain is chosen for ideas and code-testing. The domain of querying for flight schedules is thus chosen. <p> Using sample schedule information from USAir's flight schedule database, the following relational database table definition and record shows the type of information that is dealt with. <p> <code> FLTS( toCity, fromCity, beginDate, endDate, leaveTime, arriveTime, flightNum, frequency, stops, stopCities, meals, fare ) <p> ( "San Francisco, CA", Ithaca, NY", "052396", "062296", "635A", "1159A", "E5361/63", "X7", 1, "PHL", "B", 524 ) </code> <p> <a name="assumptions"> With the domain specified, certain assumptions are made to simplify the task of natural language question to SQL construct translation: </a><p> <ul> <li><b>Focus on simple queries</b>: user's usually do not ask complex SQL queries that involve not exists or groupings for instance <li><b>Time and dates</b>: these need special treatment because of the variety and complexity of formats used <li><b>Query against one database table only</b>: dealing with multiple tables is a complex task because of ambiguity resolution difficulties with table joins <li><b>Punctuations</b>: not dealt with <li><b>One sentence questions only</b> </ul> <p> <h4><a name="app2">Techniques Researched </h4><p> Several possible concepts/techniques to tackle the problem were looked at: <p> <ol> <li>WH-, GAP, and semantic features; <li>Bottom-up chart-parsing with semantic features; <li>Procedural semantics and question answering, conversational agents; <li>Information retrieval concepts; and <li>Template matching. </ol> <p> Of these techniques, although some tests were initially done with using WH- and GAP features (not with flight schedules), the extra WH- and GAP features are really not necessary for the problem. Simple bottom-up chart-parsing with semantic features suffice. <p> The idea of using some combination of question answering, conversational agents, information retrieval concepts, and template matching came about from the realization that the number of synonyms and phrasings possible for asking for a flight schedule is actually quite diverse, requiring a rather large lexicon for a small domain. <p> <p> <a href="#Contents"><i>-->Table of Contents </i></a><p> <hr> <h3><a name="Results">Results and Evaluation</a></h3><p> <h4>Bottom-Up Chart-Parsing with Semantic Features</h4><p> Because of the nice structured format of SQL queries, flight schedule questions can be directly mapped to that of parts of SQL queries. As shown in Table 1, <i>for San Francisco</i> can be mapped to the <i>WHERE destCity = "San Francisco"</i> construct, and <i>for May 28</i> can be mapped to the <i>WHERE departDate = "0528"</i> construct. <p> <TABLE BORDER> <CAPTION>Table 1. Translation Mapping for the Sentence <i>What flights are available for San Francisco from Ithaca for May 28?</i></CAPTION> <TR><TH>Sentence<TH>SQL <TR><TH ALIGN=LEFT>What flights are available<TD>SELECT flights <TR><TH ALIGN=LEFT><TD>FROM schedules <TR><TH ALIGN=LEFT>for San Francisco<TD>WHERE destCity = "San Francisco" AND <TR><TH ALIGN=LEFT>from Ithaca<TD>departCity = "Ithaca" AND <TR><TH ALIGN=LEFT>for May 28<TD>departDate = "0528" </TABLE> <p> The following is the result from parsing the sentence "What are the departure times for houston tomorrow": <p> <pre> S176:&lt;S(((<b>SELECT</b>(((<b>TIME</b> ?V18) ?V25 <b>DEPART</b>) ((<b>TOMORROW</b> ?V18) ?V25 <b>IAH</b>)))) (1 WH-PRO116) (2 VP175))&gt; from 0 to 8 <p> </pre> <p> Sample questions for testing were solicited from users given that they need to purchase a ticket to San Francisco tomorrow from Ithaca. The following are example questions. <p> <code> 1. What are the available arrival times for Miami for tomorrow? <p> 2. What are the departure times for Houston for tomorrow? <p> 3. How many stops are there to San Francisco for flight 400? <p> 4. When does flight E5361 arrive in Orlando today? <p> 5. What is the cheapest flight available to San Francisco tomorrow? <p> 6. Can you book me the cheapest flight I can take to San Francisco tomorrow? <p> 7. Do I need to stay a Saturday night to get the lowest fares? <p> 8. How many flights do you have available going to San Francisco tomorrow? <p> 9. Can you check tomorrow's flight schedule to San Francisco for me? <p> 10. I need to fly to San Francisco tomorrow. Is there any flights available? <p> </code> <p> Question types 1-5 can be parsed, but not the others for reasons mainly of not anticipating certain words and different sentential structures. For results, see the <a href="output">results documentation</a> and <a href="newlex">grammar+lexicon code</a>. <p> As a note, questions 5 and 6 involve the realization that the "cheap" concept means a SELECT MIN(FARE) operation is needed. Question 7 is a yes/no type question. Question 8 involves a COUNT operation, and question 10 has 2 sentences that violates the <a href="#assumptions">defined assumptions</a>. <p> <h4>Question Answering + Conversational Agents + Information Retrieval + Template Matching</h4><p> The results of the bottom-up chart-parsing method could be improved with further refinement as non-anticipated sentential constructs are discovered. This is not ideal, however, which motivates the search for other means of tackling the problem. <p> Questions are often asked in bits and pieces; this is quite true for querying flight schedules. This requires the flight schedule answering system to be aware of what has been asked in a session, then results can be further refined by the user with several questions. Viewed in this way, multiple sentences would not be a major problem since it is allowed. <p> Even though the number of synonyms required are quite large, a lexicon need to exhaustively cover all possibilities that the user may present to the system. For example, "flight", "flight schedule", "schedule", "reservation" refer to the same thing; other inferences are possible through other combinations of words with helper words and different word arrangements. For instance, "to go to miami" in the context of flight schedules implies flying to miami. To parse all possible combinations of questions also require a large number of rules. <p> The sentences <i>I need to fly to San Francisco tomorrow. Is there any flight available?</i> and the sentence <i>Is there any flight available to San Francisco tomorrow?</i> are the same queries. Notice, however, that key phrases are the same: <i>to San Francisco</i>, <i>tomorrow</i>, and <i>any flight</i>. The idea is that if these can be identified, then maybe sentence boundaries and syntactic structure are not as important, and the lexicon need to concentrate only on key words/phrases. <p> <img src="interface.gif" align=middle><p> Fig. 1. Interface of Flight Schedule Query Application <p> To test the idea out, a Tcl/TK application has been written (Fig. 1). <p> As shown, there are several parts to the interface. The user inputs queries, clicks on the <i>Analyze</i> button, and key words/phrases are extracted from the input and stored. Extraction of key concepts is done by regular expression matching with a built-in lexicon that ignores irrelevant words (akin to <i>stop-lists</i> in information extraction) in the context of flight schedule query. In the figure, the history text box shows that the concepts <i>flights</i>, <i>atlanta</i>, and <i>tomorrow</i> are extracted from the Q1 sentence which is shown directly under the Q1 line. (Actually, the extraction of <i>to atlanta</i> instead of just <i>atlanta</i> would be better for indicating atlanta as a destination city.) Q2 is a followup question that requests for flights to <i>houston</i> instead. The extracted information then is used to do template matching to SQL syntax (this has not been implemented yet). <p> The user can input successively to refine or change their queries until the <i>Reset</i> button is chosen to restart a new session. Using Tcl/TK also makes it easy to interface to a Web page with a backend relational database engine<a href="#ref2">[2]</a>. <p> Evaluation of this application can not be done since it has not been completely developed yet. However, the pattern matching and key concept extraction component certainly show promise at this point. <p> Thus with a combination of question answering, conversational agents, information retrieval, and template matching techniques, maybe the flight schedule query problem can be dealt with feasibly. <p> <a href="#Contents"><i>-->Table of Contents </i></a><p> <hr> <h3><a name="Discussion">Discussion, Conclusion, and Future </a></h3><p> There are other problems that were overlooked. What if the user mistype their questions? What if the user does not follow correct English grammar rules? In this case, current forms-based methods of flight-schedule query on the Web are definitely at an advantage. Then again, these Web sites are limited and return relatively large sets of data that require further interpretation on the part of the user. </p> In general, natural language processing is a difficult subject. Even with a specific domain chosen, problems are abound. In terms of the bottom-up chart-parser method, if<p> <ul> <li>a lexicon that deals with all possible flight schedule scenarios is used; <li>dates, times, and flight numbers are given special identification parameters; <li>city names with multiple words are given special treatment; and <li>grammar rules are refined by repeated testing; </ul> <p> then a full-proof flight-schedule query system could be possible. <p> However, even if the sentences could be parsed, the parsed result can not be used readily; integrating such a system with a web front-end is not straightforward because of the resident LISP back-end used for the chart-parsing. Even if it is done, it is rather resource intensive. This led to researching other possible ways to make it more feasible. Hopefully the alternative method embodied by the Tcl/TK application as discussed in the previous section will prove to be promising. <p> <h4>Future Work</h4><p> <ul> <li>Interface LISP and the grammar+lexicon to a web page, <li>Continue work on Tcl/TK application over the summer. </ul> <p> <a href="#Contents"><i>-->Table of Contents </i></a><p> <hr> <h3><a name="Refs">References </a></h3><p> <dl> <dt><a name="ref1">[1]</a> <dd>Allen, James. <i>Natural Language Understanding</i>. 2nd ed. Benjamin/Cummings, Redwood City, CA. 1995. <dt><a name="ref2">[2]</a> <dd>Almasi, G., et al. "Web* -- A Technology to Make Information Available on the Web." In <i>Proceedings of the Fourth Workshop on Enabling Technologies: Infrastructure for Collaborative Enterprises (WET ICE '95) (Apr. 20-22, 1995, Berkeley Springs, West Virginia)</i>. IEEE Computer Society Press, Los Alamitos, CA, pp. 147-153. </dl> <a href="#Contents"><i>-->Table of Contents </i></a><p> </body> </html>
# Contributing Thanks for your interest in contributing to the JavaScript Air website! Join [gitter](https://gitter.im/javascriptair/site) channel for discussion. ## Setup Note: This project requires [Node.js v6](https: but all of the `yarn` commands on this page should work with [`npm`](https: 1. Fork the repo 2. Clone your fork 3. Make a branch for your feature/bugfix/new episode/etc. 4. Run `yarn install` (make sure you have node and npm installed first) 5. Run `yarn start validate` to get everything built for the first bit. (If this doesn't work, please file an issue with your node/npm versions and the error message). 6. Run `yarn start server` and open `localhost:8080` in a browser 7. If you experience any issues up to this point, please file an issue! 8. Run the dev script(s) (in separate terminal tabs/windows) relevant for the changes you're making (see below), make your changes, and refresh your browser to see them 9. Run `yarn start build` again to make sure you wont break the build 10. Commit your changes and reference the issue you're addressing (for example: `git commit -am 'Your descriptive message. Closes 11. Push your branch to your fork 12. Create a pull request from your branch on your fork to master on this repo 13. Get merged! Add yourself to the contributors page Even for minimal changes, I'd love it if you add yourself to the official [JavaScript Air contributors page](https://javascriptair.com/contributors) for your first contribution. Please download your photo and use `yarn start compress-image /path/to/the/image` to compress your photo (more info below). Put the resulting image in the `data/contributors` directory. Then add an entry for yourself to `data/contributors/index.js`. That's it! Thanks! ## npm scripts Most of everything you do with the website you can do with the npm scripts you find in the `package.json` file. I recommend you look at the scripts that start with `dev` which will watch the filesystem for changes and re-run the build for that page while you're developing. If you want, you can just run `yarn start dev`. That effectively rebuilds everything anytime you change a file. This takes a second, but it works :-) ## CSS CSS is currently being migrated to [`aphrodite`](https://npmjs.com/package/aphrodite). This means you don't need to do anything special from a build perspective for most stuff. For some of the older stuff, here's what you've gotta do: CSS is processed using [postcss](https://github.com/postcss/postcss) and you need to build it (it's `.gitignored`). To do this, run `yarn start build.css`. If you're going to work on the css, you can run `yarn start dev.css` and it will watch the file for changes and rebuild. ## Episodes I've hacked together a pretty crazy way to build these files. I'm sure there's a much better way to do this. But what we've got works pretty well. If you're working on a specific episode (for example, the first episode), simply run: yarn start dev:episode episodes/2015-12-09 This will start nodemon watching your file system for changes and recompiling your page on changes. No hot reloading or anything. Yes, I have no idea what I'm doing. (protip, you may also want to look into [npm-quick-run](npm.im/npm-quick-run)) I've added a [plop](http://npm.im/plop) generator for adding new episodes. In the root directory, simply enter plop episode Follow the prompts and it will generate the episode file for you. ## Podbean description You can generate the description for the podbean podcast like so: yarn start description episodes/2015-12-09 `pbcopy` is available on OSX if you want to pipe the output to your clipboard (recommended) ## Images Pretty much all images should be `180x180` and compressed. We've automated this pretty well to make it simple to do. To do this we're using [imagina](http://npm.im/imagina). Check out the `imagina` docs to see how to set it up to work on your machine. Simply run: yarn start compress-image /path/to/the/image And you'll get a compressed, resized, and converted (if needed) image to use for the site. This image will have the original filename, but will end with "resized.png". Before committing, make sure to replace your original image with the compressed one by deleting the original and renaming the compressed one to the original's filename. ## Deploying We deploy with [surge.sh](https://surge.sh) automatically with [travis-ci](https://travis-ci.org/javascriptair/site). Once stuff gets into master, travis builds it and deploys it to surge. That's it! It's magic!
layout: post date: 2016-09-18 title: "Luna novias TAURO 2016" category: Luna novias tags: [Luna novias,2016] Luna novias TAURO Just **$349.99** 2016 <table><tr><td>BRANDS</td><td>Luna novias</td></tr><tr><td>Years</td><td>2016</td></tr></table> <a href="https: <!-- break --><a href="https: Buy it: [https:
import React, { Component, PropTypes } from 'react'; import { <API key> } from 'reselect'; import { connect } from 'react-redux'; import { browserHistory } from 'react-router'; import marked from 'marked'; import hljs from 'highlight.js'; marked.setOptions({ renderer: new marked.Renderer(), gfm: true, tables: true, breaks: false, pedantic: false, sanitize: true, smartLists: true, smartypants: false, highlight: (code) => hljs.highlightAuto(code).value, }); import { ArticleContainer, Article, Titlt, ArticleContent, ReviewCon, LoadingCon, ReviewItem, ReviewTit, ReviewAuth, AuthContent, ReviewAuthTime, ReviewTime, EnterComment, CommentArea, SubmitBtn, InputBox, SingleInput, LinkUrl, Paper, PageJump, PageBtn, NoData, Nocomment, LoadTitlt, } from './styledComponents'; import { <API key>, selectRequesting, selectComment, selectComments, selectMetaData, } from './selector'; import { fetchArticleContent, <API key>, changeCommentInfo, submitComment, fetchCommentsList, } from './actions'; import styles from './styles.css'; import BlogFooter from 'components/BlogFooter'; // socket.on('3q', function(msg) { // console.log(msg); class SingleArticle extends Component { componentDidMount() { const id = this.props.params.articleID; this.props.<API key>({ id }); this.props.<API key>(); this.props.onFetchComments(); } componentDidUpdate(prevProps) { if (prevProps.location.pathname !== this.props.location.pathname && this.props.params.articleID) { const id = this.props.params.articleID; this.props.<API key>({ id }); this.props.<API key>(); this.props.onFetchComments(); } } getTime = (time) => { if (time) { const date = new Date(Number(time) * 1000); return `${date.getFullYear()}-${date.getMonth() + 1}-${date.getDate()}`; } return false; }; handleSubmitComment = () => { this.props.onCommentSubmit(); // socket.emit('message', ''); } handleJumpPage = (title, id) => { browserHistory.push(`/article/${id}`); this.props.<API key>({ id, title }); this.props.<API key>(); this.props.onFetchComments(); } <API key> = () => <LoadingCon> <LoadTitlt width="50%" /> <LoadTitlt width="70%" /> <LoadTitlt width="60%" /> <LoadTitlt width="80%" /> <LoadTitlt width="60%" /> <LoadTitlt width="70%" /> </LoadingCon> renderCommentsList = (list) => { if (list.length === 0) { return <Nocomment>!</Nocomment>; } return ( list.map((item, index) => <ReviewItem key={index}> <ReviewAuthTime> <ReviewAuth title={item.nickname}> <LinkUrl target="_Blank" href={item.personalWebsite} > {item.nickname} </LinkUrl> </ReviewAuth> <ReviewTime>{this.getTime(item.createAt)}</ReviewTime> </ReviewAuthTime> <AuthContent>{item.commentContent}</AuthContent> </ReviewItem> ) ); } render() { const { currentArticle, requesting, comment, onCommentsChange, comments, metaData, } = this.props; return ( <ArticleContainer> { requesting ? this.<API key>() : <Article> <Titlt>{currentArticle.title}</Titlt> <ArticleContent> <div className={styles.output} <API key>={{ __html: marked(currentArticle.content) }} > </div> </ArticleContent> </Article> } <Paper> <PageJump> {metaData.prev === null ? <NoData></NoData> : <PageBtn onClick={() => this.handleJumpPage(metaData.prev.title, metaData.prev.id)} > {metaData.prev.title} </PageBtn>} </PageJump> <PageJump> {metaData.next === null ? <NoData></NoData> : <PageBtn onClick={() => this.handleJumpPage(metaData.next.title, metaData.next.id)} > {metaData.next.title} </PageBtn>} </PageJump> </Paper> <ReviewCon> <ReviewTit>{comments.length}</ReviewTit> {this.renderCommentsList(comments)} <EnterComment> <InputBox> <SingleInput type="text" placeholder="NickName" value={comment.nickname} onChange={(e) => onCommentsChange({ nickname: e.target.value })} /> <SingleInput type="text" placeholder="Github" value={comment.personalWebsite} onChange={(e) => onCommentsChange({ personalWebsite: e.target.value })} /> </InputBox> <CommentArea placeholder="Post your opinion" value={comment.commentContent} onChange={(e) => onCommentsChange({ commentContent: e.target.value })} /> <SubmitBtn onClick={this.handleSubmitComment} > </SubmitBtn> </EnterComment> </ReviewCon> <BlogFooter /> </ArticleContainer> ); } } SingleArticle.propTypes = { currentArticle: PropTypes.object, requesting: PropTypes.bool, <API key>: PropTypes.func, <API key>: PropTypes.func, params: PropTypes.object, onCommentsChange: PropTypes.func, comment: PropTypes.object, onCommentSubmit: PropTypes.func, onFetchComments: PropTypes.func, comments: PropTypes.array, metaData: PropTypes.object, }; const mapStateToProps = <API key>({ currentArticle: <API key>(), requesting: selectRequesting(), comment: selectComment(), comments: selectComments(), metaData: selectMetaData(), }); function mapDispatchToProps(dispatch) { return { <API key>: (val) => dispatch(<API key>(val)), <API key>: () => dispatch(fetchArticleContent()), onCommentsChange: (val) => dispatch(changeCommentInfo(val)), onCommentSubmit: () => dispatch(submitComment()), onFetchComments: () => dispatch(fetchCommentsList()), }; } export default connect(mapStateToProps, mapDispatchToProps)(SingleArticle);
// <API key>.h // MapKit #import <MapKit/MKFoundation.h> #import <MapKit/MKOverlayRenderer.h> #if TARGET_OS_IPHONE #import <UIKit/UIKit.h> #else #import <AppKit/AppKit.h> #endif <API key> MK_CLASS_AVAILABLE(10_9, 7_0) __TVOS_AVAILABLE(9_2) <API key> @interface <API key> : MKOverlayRenderer #if TARGET_OS_IPHONE @property (strong, nullable) UIColor *fillColor; @property (strong, nullable) UIColor *strokeColor; #else @property (strong, nullable) NSColor *fillColor; @property (strong, nullable) NSColor *strokeColor; #endif @property CGFloat lineWidth; // defaults to 0, which is <API key>(currentZoomScale) @property CGLineJoin lineJoin; // defaults to kCGLineJoinRound @property CGLineCap lineCap; // defaults to kCGLineCapRound @property CGFloat miterLimit; // defaults to 10 @property CGFloat lineDashPhase; // defaults to 0 @property (copy, nullable) NSArray<NSNumber *> *lineDashPattern; // defaults to nil // subclassers should override this to create a path and then set it on // themselves with self.path = newPath; - (void)createPath; // returns cached path or calls createPath if path has not yet been created @property (null_resettable) CGPathRef path; // path will be retained - (void)invalidatePath; // subclassers may override these - (void)<API key>:(CGContextRef)context atZoomScale:(MKZoomScale)zoomScale; - (void)<API key>:(CGContextRef)context atZoomScale:(MKZoomScale)zoomScale; - (void)strokePath:(CGPathRef)path inContext:(CGContextRef)context; - (void)fillPath:(CGPathRef)path inContext:(CGContextRef)context; @end <API key>