repo_name
stringlengths
4
116
path
stringlengths
4
379
size
stringlengths
1
7
content
stringlengths
3
1.05M
license
stringclasses
15 values
zr40/steamdisksaver
SteamDiskSaver/CategoryControl.Designer.cs
3664
namespace SteamDiskSaver { internal partial class CategoryControl { /// <summary> /// Required designer variable. /// </summary> private System.ComponentModel.IContainer components = null; /// <summary> /// Clean up any resources being used. /// </summary> /// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param> protected override void Dispose(bool disposing) { if (disposing && (components != null)) { components.Dispose(); } base.Dispose(disposing); } #region Component Designer generated code /// <summary> /// Required method for Designer support - do not modify /// the contents of this method with the code editor. /// </summary> private void InitializeComponent() { this.NameLabel = new System.Windows.Forms.Label(); this.DescriptionLabel = new System.Windows.Forms.Label(); this.checkBox1 = new System.Windows.Forms.CheckBox(); this.SuspendLayout(); // // NameLabel // this.NameLabel.AutoSize = true; this.NameLabel.Dock = System.Windows.Forms.DockStyle.Top; this.NameLabel.Font = new System.Drawing.Font("Segoe UI", 8.25F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.NameLabel.Location = new System.Drawing.Point(0, 0); this.NameLabel.Margin = new System.Windows.Forms.Padding(0, 0, 0, 3); this.NameLabel.Name = "NameLabel"; this.NameLabel.Size = new System.Drawing.Size(38, 13); this.NameLabel.TabIndex = 0; this.NameLabel.Text = "Name"; // // DescriptionLabel // this.DescriptionLabel.AutoSize = true; this.DescriptionLabel.Dock = System.Windows.Forms.DockStyle.Fill; this.DescriptionLabel.Location = new System.Drawing.Point(0, 13); this.DescriptionLabel.Margin = new System.Windows.Forms.Padding(0, 0, 0, 3); this.DescriptionLabel.MaximumSize = new System.Drawing.Size(530, 0); this.DescriptionLabel.Name = "DescriptionLabel"; this.DescriptionLabel.Size = new System.Drawing.Size(66, 13); this.DescriptionLabel.TabIndex = 1; this.DescriptionLabel.Text = "Description"; // // checkBox1 // this.checkBox1.AutoSize = true; this.checkBox1.Dock = System.Windows.Forms.DockStyle.Bottom; this.checkBox1.Location = new System.Drawing.Point(0, 26); this.checkBox1.Margin = new System.Windows.Forms.Padding(3, 0, 3, 0); this.checkBox1.Name = "checkBox1"; this.checkBox1.Padding = new System.Windows.Forms.Padding(3); this.checkBox1.Size = new System.Drawing.Size(66, 23); this.checkBox1.TabIndex = 1; this.checkBox1.Text = "Delete files matching this category"; this.checkBox1.UseVisualStyleBackColor = true; // // CategoryControl // this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F); this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font; this.AutoSize = true; this.AutoSizeMode = System.Windows.Forms.AutoSizeMode.GrowAndShrink; this.Controls.Add(this.DescriptionLabel); this.Controls.Add(this.checkBox1); this.Controls.Add(this.NameLabel); this.Font = new System.Drawing.Font("Segoe UI", 8.25F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.Margin = new System.Windows.Forms.Padding(0, 0, 0, 6); this.Name = "CategoryControl"; this.Size = new System.Drawing.Size(66, 49); this.Load += new System.EventHandler(this.CategoryControl_Load); this.ResumeLayout(false); this.PerformLayout(); } #endregion private System.Windows.Forms.Label NameLabel; private System.Windows.Forms.Label DescriptionLabel; private System.Windows.Forms.CheckBox checkBox1; } }
mit
joemcbride/es-microservice
src/ES.Api/Startup.cs
2399
using System; using System.Collections.Generic; using System.Linq; using System.Runtime.InteropServices; using System.Threading.Tasks; using Microsoft.AspNetCore.Authentication.JwtBearer; using Microsoft.AspNetCore.Builder; using Microsoft.AspNetCore.Hosting; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Logging; using Microsoft.IdentityModel.Tokens; using ES.Api.Identity; namespace ES.Api { public class Startup { public Startup(IHostingEnvironment env) { var builder = new ConfigurationBuilder() .SetBasePath(env.ContentRootPath) .AddJsonFile("appsettings.json", optional: false, reloadOnChange: true) .AddJsonFile($"appsettings.{env.EnvironmentName}.json", optional: true) .AddEnvironmentVariables(); Configuration = builder.Build(); } public IConfigurationRoot Configuration { get; } public void ConfigureServices(IServiceCollection services) { var apiSettings = Configuration.Get<ApiSettings>(); var tokenSettings = Configuration.Get<TokenSettings>(); services.AddSingleton<IConfigurationRoot>(Configuration); services.AddSingleton(tokenSettings); services.AddSingleton<ICertificateLoader, StoreCertificateLoader>(); if(tokenSettings.Mode == "Local") { services.AddSingleton<ICertificateLoader, LocalCertificateLoader>(); } services.AddCors(options => { options.AddPolicy( "Origin", builder => builder .WithOrigins(apiSettings.AllowedOrigins) .AllowAnyHeader() .WithMethods("POST")); }); services .AddAuthorization() .AddMvc(); } public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory) { loggerFactory.AddConsole(Configuration.GetSection("Logging")); loggerFactory.AddDebug(); app.UseCors("Origin"); app.UseJwtAuthentication(app.ApplicationServices.GetService<ICertificateLoader>()); app.UseMvc(); } } }
mit
idekerlab/cxio_python
cxio/element_maker.py
12723
from cxio.element import Element from cxio.aspect_element import AspectElement from cxio.cx_constants import CxConstants class ElementMaker(object): """ Static methods for creating (aspect) element instances. """ @staticmethod def create_nodes_aspect_element(node_id, node_name=None, node_represents=None): """ Convenience method to create a nodes aspect element :rtype: AspectElement """ if node_name is None and node_represents is None: e = {'@id': node_id} elif node_represents is None: e = {'@id': node_id, 'n': node_name} else: e = {'@id': node_id, 'n': node_name, 'r': node_represents} return AspectElement(CxConstants.NODES, e) @staticmethod def create_edges_aspect_element(edge_id, source_id, target_id, interaction): """ :rtype: AspectElement """ e = {'@id': edge_id, 's': source_id, 't': target_id, 'i': interaction } return AspectElement(CxConstants.EDGES, e) @staticmethod def create_cartesian_layout_element(node_id, view_id, x, y, z=None): """ :rtype: AspectElement """ e = {'node': node_id, 'x': x, 'y': y } if view_id: e['view'] = view_id if z: e['z'] = z return AspectElement(CxConstants.CARTESIAN_LAYOUT, e) @staticmethod def create_network_attributes_aspect_element(sub_network_id, name, value, data_type=None): """ :rtype: AspectElement """ e = {'n': name} if isinstance(value, list): if data_type is None: raise IOError('data type missing for (list) network attributes "' + name + '"') if data_type not in CxConstants.LIST_ATTRIBUTE_TYPES: raise IOError('illegal data type for (list) network attributes "' + name + '": ' + data_type) e['d'] = data_type e['v'] = value else: if data_type: if data_type not in CxConstants.SINGLE_ATTRIBUTE_TYPES: raise IOError('illegal data type for (single) network attributes "' + name + '": ' + data_type) if data_type != CxConstants.DATA_TYPE_STRING: e['d'] = data_type e['v'] = str(value) if sub_network_id: e['s'] = sub_network_id return AspectElement(CxConstants.NETWORK_ATTRIBUTES, e) @staticmethod def create_hidden_attributes_aspect_element(sub_network_id, name, value, data_type=None): """ :rtype: AspectElement """ e = {'n': name} if isinstance(value, list): if data_type is None: raise IOError('data type missing for (list) hidden attributes "' + name + '"') if data_type not in CxConstants.LIST_ATTRIBUTE_TYPES: raise IOError('illegal data type for (list) hidden attributes "' + name + '": ' + data_type) e['d'] = data_type e['v'] = value else: if data_type: if data_type not in CxConstants.SINGLE_ATTRIBUTE_TYPES: raise IOError('illegal data type for (single) hidden attributes "' + name + '": ' + data_type) if data_type != CxConstants.DATA_TYPE_STRING: e['d'] = data_type e['v'] = str(value) if sub_network_id: e['s'] = sub_network_id return AspectElement(CxConstants.HIDDEN_ATTRIBUTES, e) @staticmethod def create_edge_attributes_aspect_element(sub_network_id, edge_id, name, value, data_type=None): """ :rtype: AspectElement """ e = {'po': edge_id, 'n': name } if isinstance(value, list): if data_type is None: raise IOError('data type missing for (list) edge attributes "' + name + '"') if data_type not in CxConstants.LIST_ATTRIBUTE_TYPES: raise IOError('illegal data type for (list) edge attributes "' + name + '": ' + data_type) e['d'] = data_type e['v'] = value else: if data_type: if data_type not in CxConstants.SINGLE_ATTRIBUTE_TYPES: raise IOError('illegal data type for (single) edge attributes "' + name + '": ' + data_type) if data_type != CxConstants.DATA_TYPE_STRING: e['d'] = data_type e['v'] = str(value) if sub_network_id: e['s'] = sub_network_id return AspectElement(CxConstants.EDGE_ATTRIBUTES, e) @staticmethod def create_node_attributes_aspect_element(sub_network_id, node_id, name, value, data_type=None): """ :rtype: AspectElement """ e = {'po': node_id, 'n': name } if isinstance(value, list): if data_type is None: raise IOError('data type missing for (list) node attributes "' + name + '"') if data_type not in CxConstants.LIST_ATTRIBUTE_TYPES: raise IOError('illegal data type for (list) node attributes "' + name + '": ' + data_type) e['d'] = data_type e['v'] = value else: if data_type: if data_type not in CxConstants.SINGLE_ATTRIBUTE_TYPES: raise IOError('illegal data type for (single) node attributes "' + name + '": ' + data_type) if data_type != CxConstants.DATA_TYPE_STRING: e['d'] = data_type e['v'] = str(value) if sub_network_id: e['s'] = sub_network_id return AspectElement(CxConstants.NODE_ATTRIBUTES, e) @staticmethod def create_sub_networks_aspect_element(sub_network_id, node_ids, edge_ids): """ :rtype: AspectElement """ e = {'@id': sub_network_id, 'nodes': node_ids, 'edges': edge_ids } return AspectElement(CxConstants.SUB_NETWORKS, e) @staticmethod def create_views_aspect_element(view_id, sub_network_id): """ :rtype: AspectElement """ e = {'@id': view_id, 's': sub_network_id } return AspectElement(CxConstants.VIEWS, e) @staticmethod def create_network_relations_aspect_element(child, parent, relationship=None, name=None): """ :rtype: AspectElement """ e = {'c': child} if parent: e['p'] = parent if relationship: if (relationship != CxConstants.RELATIONSHIP_TYPE_VIEW) and ( relationship != CxConstants.RELATIONSHIP_TYPE_SUBNETWORK): raise IOError('illegal relationship type: ' + relationship) e['r'] = relationship if name: e['name'] = name return AspectElement(CxConstants.NETWORK_RELATIONS, e) @staticmethod def create_groups_aspect_element(group_id, view_id, name, nodes, external_edges, internal_edges): """ :rtype: AspectElement """ e = {'@id': group_id, 'view': view_id, 'name': name, 'nodes': nodes, 'external_edges': external_edges, 'internal_edges': internal_edges } return AspectElement(CxConstants.GROUPS, e) @staticmethod def create_table_column_aspect_element(sub_network, applies_to, name, data_type): """ :rtype: AspectElement """ if (data_type not in CxConstants.SINGLE_ATTRIBUTE_TYPES) and ( data_type not in CxConstants.LIST_ATTRIBUTE_TYPES): raise IOError('illegal data type for "' + name + '": ' + data_type) e = {'s': sub_network, 'n': name, 'applies_to': applies_to, 'd': data_type } return AspectElement(CxConstants.TABLE_COLUMN, e) @staticmethod def create_visual_properties_aspect_element(properties_of, applies_to, view, properties, dependencies=None, mappings=None): """ :rtype: AspectElement """ if properties_of not in CxConstants.VP_PROPERTIES_OF: raise IOError('illegal properties of: ' + properties_of) e = {'properties_of': properties_of, 'applies_to': applies_to, } if view: e['view'] = view if properties: e['properties'] = properties if dependencies: e['dependencies'] = dependencies if mappings: e['mappings'] = mappings return AspectElement(CxConstants.VISUAL_PROPERTIES, e) @staticmethod def create_pre_metadata_element(aspect_name, consistency_group, version, last_update, properties, id_counter, element_count=None): """ :rtype: Element """ e = {'name': str(aspect_name), 'consistencyGroup': consistency_group, 'version': str(version), 'lastUpdate': last_update, 'properties': properties, 'idCounter': id_counter } if element_count: e['elementCount'] = element_count return Element(CxConstants.META_DATA, e) @staticmethod def create_post_metadata_element(aspect_name, id_counter): """ :rtype: Element """ e = {'name': aspect_name, 'idCounter': id_counter, } return Element(CxConstants.META_DATA, e) @staticmethod def create_number_verification_element(): """ Convenience method to create a number verification element :rtype: Element """ e = [dict(longNumber=CxConstants.NUMBER_VERIFICATION_VALUE)] return Element(CxConstants.NUMBER_VERIFICATION, e) @staticmethod def create_status_element(success=True, error_msg=''): """ Convenience method to create a status element :rtype: Element """ e = [{'error': error_msg, 'success': success, }] return Element(CxConstants.STATUS, e) @staticmethod def create_ndex_citation_aspect_element(citation_id, citation_type, title, contributors, identifier, description): """ :rtype: AspectElement """ e = {'@id': citation_id, 'dc:title': title, 'dc:contributor': contributors, 'dc:identifier': identifier, 'dc:type': citation_type, 'dc:description': description, 'attributes': [] } return AspectElement('citations', e) @staticmethod def create_ndex_support_aspect_element(support_id, cx_citation_id, text): """ :rtype: AspectElement """ e = {'@id': support_id, 'citation': cx_citation_id, 'text': text, 'attributes': [] } return AspectElement('supports', e) @staticmethod def create_ndex_function_term_aspect_element(function_term): """ :rtype: AspectElement """ e = {'function_term': function_term} return AspectElement('functionTerms', e) @staticmethod def create_ndex_node_citation_aspect_element(node_id, citation_id): """ :rtype: AspectElement """ e = {'citations': [citation_id], 'po': [node_id] } return AspectElement('nodeCitations', e) @staticmethod def create_ndex_edge_citation_aspect_element(edge_id, citation_id): """ :rtype: AspectElement """ e = {'citations': [citation_id], 'po': [edge_id] } return AspectElement('edgeCitations', e) @staticmethod def create_ndex_node_support_aspect_element(node_id, support_id): """ :rtype: AspectElement """ e = {'supports': [support_id], 'po': [node_id] } return AspectElement('nodeSupports', e) @staticmethod def create_ndex_edge_support_aspect_element(edge_id, support_id): """ :rtype: AspectElement """ e = {'supports': [support_id], 'po': [edge_id] } return AspectElement('edgeSupports', e) @staticmethod def create_ndex_context_element(contexts): """ :rtype: Element """ return Element('@context', contexts)
mit
anonl/tcommon
core/src/main/java/nl/weeaboo/io/RandomAccessInputStream.java
1876
package nl.weeaboo.io; import java.io.IOException; import java.io.InputStream; final class RandomAccessInputStream extends InputStream { private final IRandomAccessFile file; private final long offset; private final long length; private long read; private long mark; public RandomAccessInputStream(IRandomAccessFile file, long offset, long length) { this.file = file; this.offset = offset; this.length = length; } @Override public void close() { //Nothing to do, this is just a view on the file } @Override public synchronized long skip(long s) { long skipped = Math.min(s, length - read); read += skipped; return skipped; } @Override public synchronized int read() throws IOException { if (read >= length) { return -1; } int b = -1; synchronized (file) { if (file.pos() != offset + read) { file.seek(offset + read); } b = file.read(); } read++; return b; } @Override public synchronized int read(byte[] out, int off, int len) throws IOException { if (read >= length) { return (len == 0 ? 0 : -1); } len = (int)Math.min(len, length - read); int r = -1; synchronized (file) { if (file.pos() != offset + read) { file.seek(offset + read); } r = file.read(out, off, len); } if (r > 0) { read += r; } return r; } @Override public boolean markSupported() { return true; } @Override public synchronized void mark(int readLimit) { mark = read; } @Override public synchronized void reset() { read = mark; } }
mit
GetTerminus/terminus-ui
projects/library/input/src/input.module.ts
1377
import { CommonModule } from '@angular/common'; import { NgModule } from '@angular/core'; import { FlexLayoutModule } from '@angular/flex-layout'; import { FormsModule, ReactiveFormsModule, } from '@angular/forms'; import { MAT_DATE_FORMATS, NativeDateModule, } from '@angular/material/core'; import { MatDatepickerModule } from '@angular/material/datepicker'; import { TsFormFieldModule } from '@terminus/ui/form-field'; import { TsIconModule } from '@terminus/ui/icon'; import { TsDatePipe } from '@terminus/ui/pipes'; import { TsValidationMessagesModule } from '@terminus/ui/validation-messages'; import { TsValidatorsService } from '@terminus/ui/validators'; import { TS_DATE_FORMATS } from './date-adapter'; import { TsInputComponent } from './input.component'; export * from './date-adapter'; export * from './input-value-accessor'; export * from './input.component'; @NgModule({ imports: [ CommonModule, FlexLayoutModule, FormsModule, MatDatepickerModule, NativeDateModule, ReactiveFormsModule, TsFormFieldModule, TsIconModule, TsValidationMessagesModule, ], providers: [ TsValidatorsService, TsDatePipe, { provide: MAT_DATE_FORMATS, useValue: TS_DATE_FORMATS, }, ], exports: [ TsInputComponent, ], declarations: [ TsInputComponent, ], }) export class TsInputModule {}
mit
danprince/roguelike
tests/test.js
453
var should = require('should'); describe('Geometry', function() { require('./container.spec.js'); // require('./rectangle.spec.js'); }); describe('Other', function() { require('./bsp.spec.js'); require('./space.spec.js'); require('./util.spec.js'); // require('./walkable.spec.js'); }); describe('Dungeon', function() { }); describe('Engine', function() { }); describe('Game', function() { }); describe('Random', function() { });
mit
cryptofun/honey
src/wallet.cpp
83007
// Copyright (c) 2009-2010 Satoshi Nakamoto // Copyright (c) 2009-2012 The Bitcoin developers // Distributed under the MIT/X11 software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include "wallet.h" #include "arith_uint256.h" #include "base58.h" #include "coincontrol.h" #include "kernel.h" #include "net.h" #include "timedata.h" #include "txdb.h" #include "ui_interface.h" #include "walletdb.h" #include <boost/algorithm/string/replace.hpp> // Settings int64_t nTransactionFee = MIN_TX_FEE; int64_t nReserveBalance = 0; int64_t nMinimumInputValue = 0; static int64_t GetStakeCombineThreshold() { return 500 * COIN; } static int64_t GetStakeSplitThreshold() { return 2 * GetStakeCombineThreshold(); } ////////////////////////////////////////////////////////////////////////////// // // mapWallet // struct CompareValueOnly { bool operator()(const std::pair<int64_t, std::pair<const CWalletTx*, unsigned int> >& t1, const std::pair<int64_t, std::pair<const CWalletTx*, unsigned int> >& t2) const { return t1.first < t2.first; } }; CPubKey CWallet::GenerateNewKey() { AssertLockHeld(cs_wallet); // mapKeyMetadata bool fCompressed = CanSupportFeature(FEATURE_COMPRPUBKEY); // default to compressed public keys if we want 0.6.0 wallets RandAddSeedPerfmon(); CKey secret; secret.MakeNewKey(fCompressed); // Compressed public keys were introduced in version 0.6.0 if (fCompressed) SetMinVersion(FEATURE_COMPRPUBKEY); CPubKey pubkey = secret.GetPubKey(); // Create new metadata int64_t nCreationTime = GetTime(); mapKeyMetadata[pubkey.GetID()] = CKeyMetadata(nCreationTime); if (!nTimeFirstKey || nCreationTime < nTimeFirstKey) nTimeFirstKey = nCreationTime; if (!AddKeyPubKey(secret, pubkey)) throw std::runtime_error("CWallet::GenerateNewKey() : AddKey failed"); return pubkey; } bool CWallet::AddKeyPubKey(const CKey& secret, const CPubKey &pubkey) { AssertLockHeld(cs_wallet); // mapKeyMetadata if (!CCryptoKeyStore::AddKeyPubKey(secret, pubkey)) return false; if (!fFileBacked) return true; if (!IsCrypted()) { return CWalletDB(strWalletFile).WriteKey(pubkey, secret.GetPrivKey(), mapKeyMetadata[pubkey.GetID()]); } return true; } bool CWallet::AddCryptedKey(const CPubKey &vchPubKey, const std::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, mapKeyMetadata[vchPubKey.GetID()]); else return CWalletDB(strWalletFile).WriteCryptedKey(vchPubKey, vchCryptedSecret, mapKeyMetadata[vchPubKey.GetID()]); } return false; } bool CWallet::LoadKeyMetadata(const CPubKey &pubkey, const CKeyMetadata &meta) { AssertLockHeld(cs_wallet); // mapKeyMetadata if (meta.nCreateTime && (!nTimeFirstKey || meta.nCreateTime < nTimeFirstKey)) nTimeFirstKey = meta.nCreateTime; mapKeyMetadata[pubkey.GetID()] = meta; return true; } bool CWallet::LoadCryptedKey(const CPubKey &vchPubKey, const std::vector<unsigned char> &vchCryptedSecret) { return CCryptoKeyStore::AddCryptedKey(vchPubKey, vchCryptedSecret); } bool CWallet::AddCScript(const CScript& redeemScript) { if (!CCryptoKeyStore::AddCScript(redeemScript)) return false; if (!fFileBacked) return true; return CWalletDB(strWalletFile).WriteCScript(Hash160(redeemScript), redeemScript); } // optional setting to unlock wallet for staking only // serves to disable the trivial sendmoney when OS account compromised // provides no real security bool fWalletUnlockStakingOnly = false; bool CWallet::LoadCScript(const CScript& redeemScript) { /* A sanity check was added in pull #3843 to avoid adding redeemScripts * that never can be redeemed. However, old wallets may still contain * these. Do not add them to the wallet and warn. */ if (redeemScript.size() > MAX_SCRIPT_ELEMENT_SIZE) { std::string strAddr = CHoneyAddress(redeemScript.GetID()).ToString(); LogPrintf("%s: Warning: This wallet contains a redeemScript of size %u which exceeds maximum size %i thus can never be redeemed. Do not use address %s.\n", __func__, redeemScript.size(), MAX_SCRIPT_ELEMENT_SIZE, strAddr); return true; } return CCryptoKeyStore::AddCScript(redeemScript); } bool CWallet::Unlock(const SecureString& strWalletPassphrase) { CCrypter crypter; CKeyingMaterial vMasterKey; { LOCK(cs_wallet); BOOST_FOREACH(const MasterKeyMap::value_type& pMasterKey, mapMasterKeys) { if(!crypter.SetKeyFromPassphrase(strWalletPassphrase, pMasterKey.second.vchSalt, pMasterKey.second.nDeriveIterations, pMasterKey.second.nDerivationMethod)) return false; if (!crypter.Decrypt(pMasterKey.second.vchCryptedKey, vMasterKey)) continue; // try another master key if (CCryptoKeyStore::Unlock(vMasterKey)) return true; } } return false; } bool CWallet::ChangeWalletPassphrase(const SecureString& strOldWalletPassphrase, const SecureString& strNewWalletPassphrase) { bool fWasLocked = IsLocked(); { LOCK(cs_wallet); Lock(); CCrypter crypter; CKeyingMaterial vMasterKey; BOOST_FOREACH(MasterKeyMap::value_type& pMasterKey, mapMasterKeys) { if(!crypter.SetKeyFromPassphrase(strOldWalletPassphrase, 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_t nStartTime = GetTimeMillis(); crypter.SetKeyFromPassphrase(strNewWalletPassphrase, pMasterKey.second.vchSalt, pMasterKey.second.nDeriveIterations, pMasterKey.second.nDerivationMethod); pMasterKey.second.nDeriveIterations = pMasterKey.second.nDeriveIterations * (100 / ((double)(GetTimeMillis() - nStartTime))); nStartTime = GetTimeMillis(); crypter.SetKeyFromPassphrase(strNewWalletPassphrase, 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; LogPrintf("Wallet passphrase changed to an nDeriveIterations of %i\n", pMasterKey.second.nDeriveIterations); if (!crypter.SetKeyFromPassphrase(strNewWalletPassphrase, 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); } bool CWallet::SetMinVersion(enum WalletFeature nVersion, CWalletDB* pwalletdbIn, bool fExplicit) { LOCK(cs_wallet); // nWalletVersion 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) pwalletdb->WriteMinVersion(nWalletVersion); if (!pwalletdbIn) delete pwalletdb; } return true; } bool CWallet::SetMaxVersion(int nVersion) { LOCK(cs_wallet); // nWalletVersion, nWalletMaxVersion // 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(WALLET_CRYPTO_KEY_SIZE); RAND_bytes(&vMasterKey[0], WALLET_CRYPTO_KEY_SIZE); CMasterKey kMasterKey(nDerivationMethodIndex); RandAddSeedPerfmon(); kMasterKey.vchSalt.resize(WALLET_CRYPTO_SALT_SIZE); RAND_bytes(&kMasterKey.vchSalt[0], WALLET_CRYPTO_SALT_SIZE); CCrypter crypter; int64_t nStartTime = GetTimeMillis(); crypter.SetKeyFromPassphrase(strWalletPassphrase, kMasterKey.vchSalt, 25000, kMasterKey.nDerivationMethod); kMasterKey.nDeriveIterations = 2500000 / ((double)(GetTimeMillis() - nStartTime)); nStartTime = GetTimeMillis(); crypter.SetKeyFromPassphrase(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; LogPrintf("Encrypting Wallet with an nDeriveIterations of %i\n", kMasterKey.nDeriveIterations); if (!crypter.SetKeyFromPassphrase(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_t CWallet::IncOrderPosNext(CWalletDB *pwalletdb) { AssertLockHeld(cs_wallet); // nOrderPosNext int64_t 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) { AssertLockHeld(cs_wallet); // mapWallet CWalletDB walletdb(strWalletFile); // First: get all CWalletTx and CAccountingEntry into a sorted-by-order std::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 (std::map<uint256, CWalletTx>::iterator it = mapWallet.begin(); it != mapWallet.end(); ++it) { CWalletTx* wtx = &((*it).second); txOrdered.insert(std::make_pair(wtx->nOrderPos, TxPair(wtx, (CAccountingEntry*)0))); } acentries.clear(); walletdb.ListAccountCreditDebit(strAccount, acentries); BOOST_FOREACH(CAccountingEntry& entry, acentries) { txOrdered.insert(std::make_pair(entry.nOrderPos, TxPair((CWalletTx*)0, &entry))); } return txOrdered; } void CWallet::WalletUpdateSpent(const CTransaction &tx, bool fBlock) { // 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) { std::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()) LogPrintf("WalletUpdateSpent: bad wtx %s\n", wtx.GetHash().ToString()); else if (!wtx.IsSpent(txin.prevout.n) && IsMine(wtx.vout[txin.prevout.n])) { LogPrintf("WalletUpdateSpent found spent coin %s HONEY %s\n", FormatMoney(wtx.GetCredit()), wtx.GetHash().ToString()); wtx.MarkSpent(txin.prevout.n); wtx.WriteToDisk(); NotifyTransactionChanged(this, txin.prevout.hash, CT_UPDATED); } } } if (fBlock) { uint256 hash = tx.GetHash(); std::map<uint256, CWalletTx>::iterator mi = mapWallet.find(hash); CWalletTx& wtx = (*mi).second; BOOST_FOREACH(const CTxOut& txout, tx.vout) { if (IsMine(txout)) { wtx.MarkUnspent(&txout - &tx.vout[0]); wtx.WriteToDisk(); NotifyTransactionChanged(this, 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 std::pair<std::map<uint256, CWalletTx>::iterator, bool> ret = mapWallet.insert(std::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_t 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_t 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 LogPrintf("AddToWallet() : found %s in block %s not in index\n", wtxIn.GetHash().ToString(), wtxIn.hashBlock.ToString()); } } 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 LogPrintf("AddToWallet %s %s%s\n", wtxIn.GetHash().ToString(), (fInsertedNew ? "new" : ""), (fUpdated ? "update" : "")); // Write to disk if (fInsertedNew || fUpdated) if (!wtx.WriteToDisk()) return false; if (!fHaveGUI) { // If default receiving address gets used, replace it with a new one if (vchDefaultKey.IsValid()) { CScript scriptDefaultKey; scriptDefaultKey.SetDestination(vchDefaultKey.GetID()); BOOST_FOREACH(const CTxOut& txout, wtx.vout) { if (txout.scriptPubKey == scriptDefaultKey) { CPubKey newDefaultKey; if (GetKeyFromPool(newDefaultKey)) { SetDefaultKey(newDefaultKey); SetAddressBookName(vchDefaultKey.GetID(), ""); } } } } } // since AddToWallet is called directly for self-originating transactions, check for consumption of own coins WalletUpdateSpent(wtx, (wtxIn.hashBlock != 0)); // Notify UI of new or updated transaction NotifyTransactionChanged(this, hash, fInsertedNew ? CT_NEW : CT_UPDATED); // notify an external script when a wallet transaction comes in or is updated std::string strCmd = GetArg("-walletnotify", ""); if ( !strCmd.empty()) { boost::replace_all(strCmd, "%s", wtxIn.GetHash().GetHex()); boost::thread t(runCommand, strCmd); // thread runs free } } 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::AddToWalletIfInvolvingMe(const CTransaction& tx, const CBlock* pblock, bool fUpdate) { 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; } void CWallet::SyncTransaction(const CTransaction& tx, const CBlock* pblock, bool fConnect) { if (!fConnect) { // wallets need to refund inputs when disconnecting coinstake if (tx.IsCoinStake()) { if (IsFromMe(tx)) DisableTransaction(tx); } return; } AddToWalletIfInvolvingMe(tx, pblock, true); } void CWallet::EraseFromWallet(const uint256 &hash) { if (!fFileBacked) return; { LOCK(cs_wallet); if (mapWallet.erase(hash)) CWalletDB(strWalletFile).EraseTx(hash); } return; } bool CWallet::IsMine(const CTxIn &txin) const { { LOCK(cs_wallet); std::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_t CWallet::GetDebit(const CTxIn &txin) const { { LOCK(cs_wallet); std::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 multi-signature-protected 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_t CWalletTx::GetTxTime() const { int64_t 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) { std::map<uint256, int>::const_iterator mi = pwallet->mapRequestCount.find(hashBlock); if (mi != pwallet->mapRequestCount.end()) nRequests = (*mi).second; } } else { // Did anyone request this transaction? std::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) { std::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(std::list<std::pair<CTxDestination, int64_t> >& listReceived, std::list<std::pair<CTxDestination, int64_t> >& listSent, int64_t& nFee, std::string& strSentAccount) const { nFee = 0; listReceived.clear(); listSent.clear(); strSentAccount = strFromAccount; // Compute fee: int64_t nDebit = GetDebit(); if (nDebit > 0) // debit>0 means we signed/sent this transaction { int64_t nValueOut = GetValueOut(); nFee = nDebit - nValueOut; } // Sent/received. BOOST_FOREACH(const CTxOut& txout, vout) { // Skip special stake out if (txout.scriptPubKey.empty()) continue; bool fIsMine; // Only need to handle txouts if AT LEAST one of these is true: // 1) they debit from us (sent) // 2) the output is to us (received) if (nDebit > 0) { // Don't report 'change' txouts if (pwallet->IsChange(txout)) continue; fIsMine = pwallet->IsMine(txout); } else if (!(fIsMine = pwallet->IsMine(txout))) continue; // In either case, we need to get the destination address CTxDestination address; if (!ExtractDestination(txout.scriptPubKey, address) && !txout.IsUnspendable()) { LogPrintf("CWalletTx::GetAmounts: Unknown transaction type found, txid %s\n", this->GetHash().ToString()); address = CNoDestination(); } // If we are debited by the transaction, add the output as a "sent" entry if (nDebit > 0) listSent.push_back(std::make_pair(address, txout.nValue)); // If we are receiving the output, add it as a "received" entry if (fIsMine) listReceived.push_back(std::make_pair(address, txout.nValue)); } } void CWalletTx::GetAccountAmounts(const std::string& strAccount, int64_t& nReceived, int64_t& nSent, int64_t& nFee) const { nReceived = nSent = nFee = 0; int64_t allFee; std::string strSentAccount; std::list<std::pair<CTxDestination, int64_t> > listReceived; std::list<std::pair<CTxDestination, int64_t> > listSent; GetAmounts(listReceived, listSent, allFee, strSentAccount); if (strAccount == strSentAccount) { BOOST_FOREACH(const PAIRTYPE(CTxDestination,int64_t)& s, listSent) nSent += s.second; nFee = allFee; } { LOCK(pwallet->cs_wallet); BOOST_FOREACH(const PAIRTYPE(CTxDestination,int64_t)& r, listReceived) { if (pwallet->mapAddressBook.count(r.first)) { std::map<CTxDestination, std::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::AddSupportingTransactions(CTxDB& txdb) { vtxPrev.clear(); const int COPY_DEPTH = 3; if (SetMerkleBranch() < COPY_DEPTH) { std::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); std::map<uint256, const CMerkleTx*> mapWalletPrev; std::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; std::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 (txdb.ReadDiskTx(hash, tx)) { ; } else { LogPrintf("ERROR: AddSupportingTransactions() : 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::ScanForWalletTransactions(CBlockIndex* pindexStart, bool fUpdate) { int ret = 0; CBlockIndex* pindex = pindexStart; { LOCK2(cs_main, cs_wallet); while (pindex) { // no need to read and scan block, if block was created before // our wallet birthday (as adjusted for block time variability) if (nTimeFirstKey && (pindex->nTime < (nTimeFirstKey - 7200))) { pindex = pindex->pnext; continue; } CBlock block; block.ReadFromDisk(pindex, true); BOOST_FOREACH(CTransaction& tx, block.vtx) { if (AddToWalletIfInvolvingMe(tx, &block, fUpdate)) ret++; } pindex = pindex->pnext; } } return ret; } void CWallet::ReacceptWalletTransactions() { CTxDB txdb("r"); bool fRepeat = true; while (fRepeat) { LOCK2(cs_main, cs_wallet); fRepeat = false; std::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()) { LogPrintf("ERROR: ReacceptWalletTransactions() : txindex.vSpent.size() %u != wtx.vout.size() %u\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) { LogPrintf("ReacceptWalletTransactions found spent coin %s HONEY %s\n", FormatMoney(wtx.GetCredit()), wtx.GetHash().ToString()); wtx.MarkDirty(); wtx.WriteToDisk(); } } else { // Re-accept any txes of ours that aren't already in a block if (!(wtx.IsCoinBase() || wtx.IsCoinStake())) wtx.AcceptWalletTransaction(txdb); } } if (!vMissingTx.empty()) { // TODO: optimize this to scan just part of the block chain? if (ScanForWalletTransactions(pindexGenesisBlock)) fRepeat = true; // Found missing transactions: re-do re-accept. } } } void CWalletTx::RelayWalletTransaction(CTxDB& txdb) { BOOST_FOREACH(const CMerkleTx& tx, vtxPrev) { if (!(tx.IsCoinBase() || tx.IsCoinStake())) { uint256 hash = tx.GetHash(); if (!txdb.ContainsTx(hash)) RelayTransaction((CTransaction)tx, hash); } } if (!(IsCoinBase() || IsCoinStake())) { uint256 hash = GetHash(); if (!txdb.ContainsTx(hash)) { LogPrintf("Relaying wtx %s\n", hash.ToString()); RelayTransaction((CTransaction)*this, hash); } } } void CWalletTx::RelayWalletTransaction() { CTxDB txdb("r"); RelayWalletTransaction(txdb); } void CWallet::ResendWalletTransactions(bool fForce) { if (!fForce) { // Do this infrequently and randomly to avoid giving away // that these are our transactions. static int64_t 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_t nLastTime; if (nTimeBestReceived < nLastTime) return; nLastTime = GetTime(); } // Rebroadcast any of our txes that aren't in a block yet LogPrintf("ResendWalletTransactions()\n"); CTxDB txdb("r"); { LOCK(cs_wallet); // Sort them in chronological order std::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 (fForce || nTimeBestReceived - (int64_t)wtx.nTimeReceived > 5 * 60) mapSorted.insert(std::make_pair(wtx.nTimeReceived, &wtx)); } BOOST_FOREACH(PAIRTYPE(const unsigned int, CWalletTx*)& item, mapSorted) { CWalletTx& wtx = *item.second; if (wtx.CheckTransaction()) wtx.RelayWalletTransaction(txdb); else LogPrintf("ResendWalletTransactions() : CheckTransaction failed for transaction %s\n", wtx.GetHash().ToString()); } } } ////////////////////////////////////////////////////////////////////////////// // // Actions // int64_t CWallet::GetBalance() const { int64_t nTotal = 0; { LOCK2(cs_main, cs_wallet); for (std::map<uint256, CWalletTx>::const_iterator it = mapWallet.begin(); it != mapWallet.end(); ++it) { const CWalletTx* pcoin = &(*it).second; if (pcoin->IsTrusted()) nTotal += pcoin->GetAvailableCredit(); } } return nTotal; } int64_t CWallet::GetUnconfirmedBalance() const { int64_t nTotal = 0; { LOCK2(cs_main, cs_wallet); for (std::map<uint256, CWalletTx>::const_iterator it = mapWallet.begin(); it != mapWallet.end(); ++it) { const CWalletTx* pcoin = &(*it).second; if (!IsFinalTx(*pcoin) || (!pcoin->IsTrusted() && pcoin->GetDepthInMainChain() == 0)) nTotal += pcoin->GetAvailableCredit(); } } return nTotal; } int64_t CWallet::GetImmatureBalance() const { int64_t nTotal = 0; { LOCK2(cs_main, cs_wallet); for (std::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(std::vector<COutput>& vCoins, bool fOnlyConfirmed, const CCoinControl *coinControl) const { vCoins.clear(); { LOCK2(cs_main, cs_wallet); for (std::map<uint256, CWalletTx>::const_iterator it = mapWallet.begin(); it != mapWallet.end(); ++it) { const CWalletTx* pcoin = &(*it).second; if (!IsFinalTx(*pcoin)) continue; if (fOnlyConfirmed && !pcoin->IsTrusted()) continue; if (pcoin->IsCoinBase() && pcoin->GetBlocksToMaturity() > 0) continue; if(pcoin->IsCoinStake() && pcoin->GetBlocksToMaturity() > 0) continue; int nDepth = pcoin->GetDepthInMainChain(); if (nDepth < 0) continue; for (unsigned int i = 0; i < pcoin->vout.size(); i++) if (!(pcoin->IsSpent(i)) && IsMine(pcoin->vout[i]) && pcoin->vout[i].nValue >= nMinimumInputValue && (!coinControl || !coinControl->HasSelected() || coinControl->IsSelected((*it).first, i))) vCoins.push_back(COutput(pcoin, i, nDepth)); } } } void CWallet::AvailableCoinsForStaking(std::vector<COutput>& vCoins) const { vCoins.clear(); { LOCK2(cs_main, cs_wallet); for (std::map<uint256, CWalletTx>::const_iterator it = mapWallet.begin(); it != mapWallet.end(); ++it) { const CWalletTx* pcoin = &(*it).second; int nDepth = pcoin->GetDepthInMainChain(); if (nDepth < 1) continue; if (nDepth < nStakeMinConfirmations) continue; if (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 >= nMinimumInputValue) vCoins.push_back(COutput(pcoin, i, nDepth)); } } } static void ApproximateBestSubset(std::vector<std::pair<int64_t, std::pair<const CWalletTx*,unsigned int> > >vValue, int64_t nTotalLower, int64_t nTargetValue, std::vector<char>& vfBest, int64_t& nBest, int iterations = 1000) { std::vector<char> vfIncluded; vfBest.assign(vValue.size(), true); nBest = nTotalLower; seed_insecure_rand(); for (int nRep = 0; nRep < iterations && nBest != nTargetValue; nRep++) { vfIncluded.assign(vValue.size(), false); int64_t nTotal = 0; bool fReachedTarget = false; for (int nPass = 0; nPass < 2 && !fReachedTarget; nPass++) { for (unsigned int i = 0; i < vValue.size(); i++) { //The solver here uses a randomized algorithm, //the randomness serves no real security purpose but is just //needed to prevent degenerate behavior and it is important //that the rng fast. We do not use a constant random sequence, //because there may be some privacy improvement by making //the selection random. if (nPass == 0 ? insecure_rand()&1 : !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_t CWallet::GetStake() const { int64_t nTotal = 0; LOCK2(cs_main, cs_wallet); for (std::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_t CWallet::GetNewMint() const { int64_t nTotal = 0; LOCK2(cs_main, cs_wallet); for (std::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_t nTargetValue, unsigned int nSpendTime, int nConfMine, int nConfTheirs, std::vector<COutput> vCoins, std::set<std::pair<const CWalletTx*,unsigned int> >& setCoinsRet, int64_t& nValueRet) const { setCoinsRet.clear(); nValueRet = 0; // List of values less than target std::pair<int64_t, std::pair<const CWalletTx*,unsigned int> > coinLowestLarger; coinLowestLarger.first = std::numeric_limits<int64_t>::max(); coinLowestLarger.second.first = NULL; std::vector<std::pair<int64_t, std::pair<const CWalletTx*,unsigned int> > > vValue; int64_t 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; // Follow the timestamp rules if (pcoin->nTime > nSpendTime) continue; int64_t n = pcoin->vout[i].nValue; std::pair<int64_t,std::pair<const CWalletTx*,unsigned int> > coin = std::make_pair(n,std::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()); std::vector<char> vfBest; int64_t nBest; ApproximateBestSubset(vValue, nTotalLower, nTargetValue, vfBest, nBest, 1000); if (nBest != nTargetValue && nTotalLower >= nTargetValue + CENT) ApproximateBestSubset(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; } LogPrint("selectcoins", "SelectCoins() best subset: "); for (unsigned int i = 0; i < vValue.size(); i++) if (vfBest[i]) LogPrint("selectcoins", "%s ", FormatMoney(vValue[i].first)); LogPrint("selectcoins", "total %s\n", FormatMoney(nBest)); } return true; } bool CWallet::SelectCoins(int64_t nTargetValue, unsigned int nSpendTime, std::set<std::pair<const CWalletTx*,unsigned int> >& setCoinsRet, int64_t& nValueRet, const CCoinControl* coinControl) const { std::vector<COutput> vCoins; AvailableCoins(vCoins, true, coinControl); // coin control -> return all selected outputs (we want all selected to go into the transaction for sure) if (coinControl && coinControl->HasSelected()) { BOOST_FOREACH(const COutput& out, vCoins) { nValueRet += out.tx->vout[out.i].nValue; setCoinsRet.insert(std::make_pair(out.tx, out.i)); } return (nValueRet >= nTargetValue); } boost::function<bool (const CWallet*, int64_t, unsigned int, int, int, std::vector<COutput>, std::set<std::pair<const CWalletTx*,unsigned int> >&, int64_t&)> f = &CWallet::SelectCoinsMinConf; return (f(this, nTargetValue, nSpendTime, 1, 10, vCoins, setCoinsRet, nValueRet) || f(this, nTargetValue, nSpendTime, 1, 1, vCoins, setCoinsRet, nValueRet) || f(this, nTargetValue, nSpendTime, 0, 1, vCoins, setCoinsRet, nValueRet)); } // Select some coins without random shuffle or best subset approximation bool CWallet::SelectCoinsForStaking(int64_t nTargetValue, std::set<std::pair<const CWalletTx*,unsigned int> >& setCoinsRet, int64_t& nValueRet) const { std::vector<COutput> vCoins; AvailableCoinsForStaking(vCoins); setCoinsRet.clear(); nValueRet = 0; BOOST_FOREACH(COutput output, vCoins) { const CWalletTx *pcoin = output.tx; int i = output.i; // Stop if we've chosen enough inputs if (nValueRet >= nTargetValue) break; int64_t n = pcoin->vout[i].nValue; std::pair<int64_t,std::pair<const CWalletTx*,unsigned int> > coin = std::make_pair(n,std::make_pair(pcoin, i)); if (n >= nTargetValue) { // If input value is greater or equal to target then simply insert // it into the current subset and exit setCoinsRet.insert(coin.second); nValueRet += coin.first; break; } else if (n < nTargetValue + CENT) { setCoinsRet.insert(coin.second); nValueRet += coin.first; } } return true; } bool CWallet::CreateTransaction(const std::vector<std::pair<CScript, int64_t> >& vecSend, CWalletTx& wtxNew, CReserveKey& reservekey, int64_t& nFeeRet, const CCoinControl* coinControl) { int64_t nValue = 0; BOOST_FOREACH (const PAIRTYPE(CScript, int64_t)& s, vecSend) { if (nValue < 0) return false; nValue += s.second; } if (vecSend.empty() || nValue < 0) return false; wtxNew.BindWallet(this); // Discourage fee sniping. // // However because of a off-by-one-error in previous versions we need to // neuter it by setting nLockTime to at least one less than nBestHeight. // Secondly currently propagation of transactions created for block heights // corresponding to blocks that were just mined may be iffy - transactions // aren't re-accepted into the mempool - we additionally neuter the code by // going ten blocks back. Doesn't yet do anything for sniping, but does act // to shake out wallet bugs like not showing nLockTime'd transactions at // all. if (!IsInitialBlockDownload()) wtxNew.nLockTime = std::max(0, nBestHeight - 10); // Secondly occasionally randomly pick a nLockTime even further back, so // that transactions that are delayed after signing for whatever reason, // e.g. high-latency mix networks and some CoinJoin implementations, have // better privacy. if (GetRandInt(10) == 0) wtxNew.nLockTime = std::max(0, (int)wtxNew.nLockTime - GetRandInt(100)); assert(wtxNew.nLockTime <= (unsigned int)nBestHeight); assert(wtxNew.nLockTime < LOCKTIME_THRESHOLD); { LOCK2(cs_main, cs_wallet); // txdb must be opened before the mapWallet lock CTxDB txdb("r"); { nFeeRet = nTransactionFee; while (true) { wtxNew.vin.clear(); wtxNew.vout.clear(); wtxNew.fFromMe = true; int64_t nTotalValue = nValue + nFeeRet; // vouts to the payees BOOST_FOREACH (const PAIRTYPE(CScript, int64_t)& s, vecSend) wtxNew.vout.push_back(CTxOut(s.second, s.first)); // Choose coins to use std::set<std::pair<const CWalletTx*,unsigned int> > setCoins; int64_t nValueIn = 0; if (!SelectCoins(nTotalValue, wtxNew.nTime, setCoins, nValueIn, coinControl)) return false; int64_t nChange = nValueIn - nValue - nFeeRet; if (nChange > 0) { // Fill a vout to ourself // TODO: pass in scriptChange instead of reservekey so // change transaction isn't always pay-to-honey-address CScript scriptChange; // coin control: send change to custom address if (coinControl && !boost::get<CNoDestination>(&coinControl->destChange)) scriptChange.SetDestination(coinControl->destChange); // no coin control: send change to newly generated address else { // 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; bool ret; ret = reservekey.GetReservedKey(vchPubKey); assert(ret); // should never fail, as we just unlocked scriptChange.SetDestination(vchPubKey.GetID()); } // Insert change txn at random position: std::vector<CTxOut>::iterator position = wtxNew.vout.begin()+GetRandInt(wtxNew.vout.size()+1); wtxNew.vout.insert(position, CTxOut(nChange, scriptChange)); } else reservekey.ReturnKey(); // Fill vin // // Note how the sequence number is set to std::max()-1 so that the // nLockTime set above actually works. BOOST_FOREACH(const PAIRTYPE(const CWalletTx*,unsigned int)& coin, setCoins) wtxNew.vin.push_back(CTxIn(coin.first->GetHash(),coin.second,CScript(), std::numeric_limits<unsigned int>::max()-1)); // 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_STANDARD_TX_SIZE) return false; // Check that enough fee is included int64_t nPayFee = nTransactionFee * (1 + (int64_t)nBytes / 1000); int64_t nMinFee = GetMinFee(wtxNew, 1, GMF_SEND, nBytes); if (nFeeRet < std::max(nPayFee, nMinFee)) { nFeeRet = std::max(nPayFee, nMinFee); continue; } // Fill vtxPrev by copying from previous transactions vtxPrev wtxNew.AddSupportingTransactions(txdb); wtxNew.fTimeReceivedIsTxTime = true; break; } } } return true; } bool CWallet::CreateTransaction(CScript scriptPubKey, int64_t nValue, CWalletTx& wtxNew, CReserveKey& reservekey, int64_t& nFeeRet, const CCoinControl* coinControl) { std::vector< std::pair<CScript, int64_t> > vecSend; vecSend.push_back(std::make_pair(scriptPubKey, nValue)); return CreateTransaction(vecSend, wtxNew, reservekey, nFeeRet, coinControl); } uint64_t CWallet::GetStakeWeight() const { // Choose coins to use int64_t nBalance = GetBalance(); if (nBalance <= nReserveBalance) return 0; std::vector<const CWalletTx*> vwtxPrev; std::set<std::pair<const CWalletTx*,unsigned int> > setCoins; int64_t nValueIn = 0; if (!SelectCoinsForStaking(nBalance - nReserveBalance, setCoins, nValueIn)) return 0; if (setCoins.empty()) return 0; uint64_t nWeight = 0; LOCK2(cs_main, cs_wallet); BOOST_FOREACH(PAIRTYPE(const CWalletTx*, unsigned int) pcoin, setCoins) { if (pcoin.first->GetDepthInMainChain() >= nStakeMinConfirmations) nWeight += pcoin.first->vout[pcoin.second].nValue; } return nWeight; } bool CWallet::CreateCoinStake(const CKeyStore& keystore, unsigned int nBits, int64_t nSearchInterval, int64_t nFees, CTransaction& txNew, CKey& key) { CBlockIndex* pindexPrev = pindexBest; arith_uint256 bnTargetPerCoinDay; bnTargetPerCoinDay.SetCompact(nBits); 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_t nBalance = GetBalance(); if (nBalance <= nReserveBalance) return false; std::vector<const CWalletTx*> vwtxPrev; std::set<std::pair<const CWalletTx*,unsigned int> > setCoins; int64_t nValueIn = 0; // Select coins with suitable depth if (!SelectCoinsForStaking(nBalance - nReserveBalance, setCoins, nValueIn)) return false; if (setCoins.empty()) return false; int64_t nCredit = 0; CScript scriptPubKeyKernel; CTxDB txdb("r"); BOOST_FOREACH(PAIRTYPE(const CWalletTx*, unsigned int) pcoin, setCoins) { static int nMaxStakeSearchInterval = 60; bool fKernelFound = false; for (unsigned int n=0; n<std::min(nSearchInterval,(int64_t)nMaxStakeSearchInterval) && !fKernelFound && pindexPrev == pindexBest; n++) { boost::this_thread::interruption_point(); // Search backward in time from the given txNew timestamp // Search nSearchInterval seconds back up to nMaxStakeSearchInterval COutPoint prevoutStake = COutPoint(pcoin.first->GetHash(), pcoin.second); int64_t nBlockTime; if (CheckKernel(pindexPrev, nBits, txNew.nTime - n, prevoutStake, &nBlockTime)) { // Found a kernel LogPrint("coinstake", "CreateCoinStake : kernel found\n"); std::vector<valtype> vSolutions; txnouttype whichType; CScript scriptPubKeyOut; scriptPubKeyKernel = pcoin.first->vout[pcoin.second].scriptPubKey; if (!Solver(scriptPubKeyKernel, whichType, vSolutions)) { LogPrint("coinstake", "CreateCoinStake : failed to parse kernel\n"); break; } LogPrint("coinstake", "CreateCoinStake : parsed kernel type=%d\n", whichType); if (whichType != TX_PUBKEY && whichType != TX_PUBKEYHASH) { LogPrint("coinstake", "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 if (!keystore.GetKey(uint160(vSolutions[0]), key)) { LogPrint("coinstake", "CreateCoinStake : failed to get key for kernel type=%d\n", whichType); break; // unable to find corresponding public key } scriptPubKeyOut << key.GetPubKey() << OP_CHECKSIG; } if (whichType == TX_PUBKEY) { valtype& vchPubKey = vSolutions[0]; if (!keystore.GetKey(Hash160(vchPubKey), key)) { LogPrint("coinstake", "CreateCoinStake : failed to get key for kernel type=%d\n", whichType); break; // unable to find corresponding public key } if (key.GetPubKey() != vchPubKey) { LogPrint("coinstake", "CreateCoinStake : invalid key for kernel type=%d\n", whichType); break; // keys mismatch } 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)); LogPrint("coinstake", "CreateCoinStake : added kernel type=%d\n", whichType); fKernelFound = true; break; } } if (fKernelFound) 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() >= 10) 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 >= GetStakeCombineThreshold()) continue; txNew.vin.push_back(CTxIn(pcoin.first->GetHash(), pcoin.second)); nCredit += pcoin.first->vout[pcoin.second].nValue; vwtxPrev.push_back(pcoin.first); } } // Calculate reward { int64_t nReward = GetProofOfStakeReward(pindexPrev, 0, nFees); if (nReward <= 0) return false; nCredit += nReward; } if (nCredit >= GetStakeSplitThreshold()) txNew.vout.push_back(CTxOut(0, txNew.vout[1].scriptPubKey)); //split stake // Set output amount if (txNew.vout.size() == 3) { txNew.vout[1].nValue = (nCredit / 2 / CENT) * CENT; txNew.vout[2].nValue = nCredit - txNew.vout[1].nValue; } else txNew.vout[1].nValue = nCredit; // 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"); // 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); LogPrintf("CommitTransaction:\n%s", wtxNew.ToString()); { // 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 std::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(); NotifyTransactionChanged(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(true)) { // This must not fail. The transaction has already been signed and recorded. LogPrintf("CommitTransaction() : Error: Transaction not valid\n"); return false; } wtxNew.RelayWalletTransaction(); } return true; } std::string CWallet::SendMoney(CScript scriptPubKey, int64_t nValue, CWalletTx& wtxNew, bool fAskFee) { CReserveKey reservekey(this); int64_t nFeeRequired; if (IsLocked()) { std::string strError = _("Error: Wallet locked, unable to create transaction!"); LogPrintf("SendMoney() : %s", strError); return strError; } if (fWalletUnlockStakingOnly) { std::string strError = _("Error: Wallet unlocked for staking only, unable to create transaction."); LogPrintf("SendMoney() : %s", strError); return strError; } if (!CreateTransaction(scriptPubKey, nValue, wtxNew, reservekey, nFeeRequired)) { std::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)); else strError = _("Error: Transaction creation failed!"); LogPrintf("SendMoney() : %s\n", strError); 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 ""; } std::string CWallet::SendMoneyToDestination(const CTxDestination& address, int64_t nValue, CWalletTx& wtxNew, bool fAskFee) { // Check amount if (nValue <= 0) return _("Invalid amount"); if (nValue + nTransactionFee > GetBalance()) return _("Insufficient funds"); // Parse Honey 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")) { LOCK(cs_wallet); 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(); return DB_LOAD_OK; } bool CWallet::SetAddressBookName(const CTxDestination& address, const std::string& strName) { bool fUpdated = false; { LOCK(cs_wallet); // mapAddressBook std::map<CTxDestination, std::string>::iterator mi = mapAddressBook.find(address); fUpdated = mi != mapAddressBook.end(); mapAddressBook[address] = strName; } NotifyAddressBookChanged(this, address, strName, ::IsMine(*this, address), (fUpdated ? CT_UPDATED : CT_NEW) ); if (!fFileBacked) return false; return CWalletDB(strWalletFile).WriteName(CHoneyAddress(address).ToString(), strName); } bool CWallet::DelAddressBookName(const CTxDestination& address) { { LOCK(cs_wallet); // mapAddressBook mapAddressBook.erase(address); } NotifyAddressBookChanged(this, address, "", ::IsMine(*this, address), CT_DELETED); if (!fFileBacked) return false; return CWalletDB(strWalletFile).EraseName(CHoneyAddress(address).ToString()); } bool CWallet::SetDefaultKey(const CPubKey &vchPubKey) { if (fFileBacked) { if (!CWalletDB(strWalletFile).WriteDefaultKey(vchPubKey)) return false; } vchDefaultKey = vchPubKey; 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_t nIndex, setKeyPool) walletdb.ErasePool(nIndex); setKeyPool.clear(); if (IsLocked()) return false; int64_t nKeys = std::max(GetArg("-keypool", 100), (int64_t)0); for (int i = 0; i < nKeys; i++) { int64_t nIndex = i+1; walletdb.WritePool(nIndex, CKeyPool(GenerateNewKey())); setKeyPool.insert(nIndex); } LogPrintf("CWallet::NewKeyPool wrote %d new keys\n", nKeys); } return true; } bool CWallet::TopUpKeyPool(unsigned int nSize) { { LOCK(cs_wallet); if (IsLocked()) return false; CWalletDB walletdb(strWalletFile); // Top up key pool unsigned int nTargetSize; if (nSize > 0) nTargetSize = nSize; else nTargetSize = std::max(GetArg("-keypool", 100), (int64_t)0); while (setKeyPool.size() < (nTargetSize + 1)) { int64_t nEnd = 1; if (!setKeyPool.empty()) nEnd = *(--setKeyPool.end()) + 1; if (!walletdb.WritePool(nEnd, CKeyPool(GenerateNewKey()))) throw std::runtime_error("TopUpKeyPool() : writing generated key failed"); setKeyPool.insert(nEnd); LogPrintf("keypool added key %d, size=%u\n", nEnd, setKeyPool.size()); } } return true; } void CWallet::ReserveKeyFromKeyPool(int64_t& 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 std::runtime_error("ReserveKeyFromKeyPool() : read failed"); if (!HaveKey(keypool.vchPubKey.GetID())) throw std::runtime_error("ReserveKeyFromKeyPool() : unknown key in key pool"); assert(keypool.vchPubKey.IsValid()); LogPrintf("keypool reserve %d\n", nIndex); } } int64_t CWallet::AddReserveKey(const CKeyPool& keypool) { { LOCK2(cs_main, cs_wallet); CWalletDB walletdb(strWalletFile); int64_t nIndex = 1 + *(--setKeyPool.end()); if (!walletdb.WritePool(nIndex, keypool)) throw std::runtime_error("AddReserveKey() : writing added key failed"); setKeyPool.insert(nIndex); return nIndex; } return -1; } void CWallet::KeepKey(int64_t nIndex) { // Remove from key pool if (fFileBacked) { CWalletDB walletdb(strWalletFile); walletdb.ErasePool(nIndex); } LogPrintf("keypool keep %d\n", nIndex); } void CWallet::ReturnKey(int64_t nIndex) { // Return to key pool { LOCK(cs_wallet); setKeyPool.insert(nIndex); } LogPrintf("keypool return %d\n", nIndex); } bool CWallet::GetKeyFromPool(CPubKey& result) { int64_t nIndex = 0; CKeyPool keypool; { LOCK(cs_wallet); ReserveKeyFromKeyPool(nIndex, keypool); if (nIndex == -1) { if (IsLocked()) return false; result = GenerateNewKey(); return true; } KeepKey(nIndex); result = keypool.vchPubKey; } return true; } int64_t CWallet::GetOldestKeyPoolTime() { int64_t nIndex = 0; CKeyPool keypool; ReserveKeyFromKeyPool(nIndex, keypool); if (nIndex == -1) return GetTime(); ReturnKey(nIndex); return keypool.nTime; } std::map<CTxDestination, int64_t> CWallet::GetAddressBalances() { std::map<CTxDestination, int64_t> balances; { LOCK(cs_wallet); BOOST_FOREACH(PAIRTYPE(uint256, CWalletTx) walletEntry, mapWallet) { CWalletTx *pcoin = &walletEntry.second; if (!IsFinalTx(*pcoin) || !pcoin->IsTrusted()) 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_t n = pcoin->IsSpent(i) ? 0 : pcoin->vout[i].nValue; if (!balances.count(addr)) balances[addr] = 0; balances[addr] += n; } } } return balances; } std::set< std::set<CTxDestination> > CWallet::GetAddressGroupings() { AssertLockHeld(cs_wallet); // mapWallet std::set< std::set<CTxDestination> > groupings; std::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(); } } std::set< std::set<CTxDestination>* > uniqueGroupings; // a set of pointers to groups of addresses std::map< CTxDestination, std::set<CTxDestination>* > setmap; // map addresses to the unique group containing it BOOST_FOREACH(std::set<CTxDestination> grouping, groupings) { // make a set of all the groups hit by this new group std::set< std::set<CTxDestination>* > hits; std::map< CTxDestination, std::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 std::set<CTxDestination>* merged = new std::set<CTxDestination>(grouping); BOOST_FOREACH(std::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; } std::set< std::set<CTxDestination> > ret; BOOST_FOREACH(std::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_t& nBalanceInQuestion, bool fCheckOnly) { nMismatchFound = 0; nBalanceInQuestion = 0; LOCK(cs_wallet); std::vector<CWalletTx*> vCoins; vCoins.reserve(mapWallet.size()); for (std::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())) { LogPrintf("FixSpentCoins found lost coin %s HONEY %s[%d], %s\n", FormatMoney(pcoin->vout[n].nValue), pcoin->GetHash().ToString(), 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())) { LogPrintf("FixSpentCoins found spent coin %s HONEY %s[%d], %s\n", FormatMoney(pcoin->vout[n].nValue), pcoin->GetHash().ToString(), 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) { std::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(); } } } } bool CReserveKey::GetReservedKey(CPubKey& pubkey) { if (nIndex == -1) { CKeyPool keypool; pwallet->ReserveKeyFromKeyPool(nIndex, keypool); if (nIndex != -1) vchPubKey = keypool.vchPubKey; else { if (pwallet->vchDefaultKey.IsValid()) { LogPrintf("CReserveKey::GetReservedKey(): Warning: Using default key instead of a new key, top up your keypool!"); vchPubKey = pwallet->vchDefaultKey; } else return false; } } assert(vchPubKey.IsValid()); pubkey = vchPubKey; return true; } 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(std::set<CKeyID>& setAddress) const { setAddress.clear(); CWalletDB walletdb(strWalletFile); LOCK2(cs_main, cs_wallet); BOOST_FOREACH(const int64_t& id, setKeyPool) { CKeyPool keypool; if (!walletdb.ReadPool(id, keypool)) throw std::runtime_error("GetAllReserveKeyHashes() : read failed"); assert(keypool.vchPubKey.IsValid()); CKeyID keyID = keypool.vchPubKey.GetID(); if (!HaveKey(keyID)) throw std::runtime_error("GetAllReserveKeyHashes() : 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 std::map<uint256, CWalletTx>::const_iterator mi = mapWallet.find(hashTx); if (mi != mapWallet.end()) NotifyTransactionChanged(this, hashTx, CT_UPDATED); } } void CWallet::GetKeyBirthTimes(std::map<CKeyID, int64_t> &mapKeyBirth) const { AssertLockHeld(cs_wallet); // mapKeyMetadata mapKeyBirth.clear(); // get birth times for keys with metadata for (std::map<CKeyID, CKeyMetadata>::const_iterator it = mapKeyMetadata.begin(); it != mapKeyMetadata.end(); it++) if (it->second.nCreateTime) mapKeyBirth[it->first] = it->second.nCreateTime; // map in which we'll infer heights of other keys CBlockIndex *pindexMax = FindBlockByHeight(std::max(0, nBestHeight - 144)); // the tip can be reorganised; use a 144-block safety margin std::map<CKeyID, CBlockIndex*> mapKeyFirstBlock; std::set<CKeyID> setKeys; GetKeys(setKeys); BOOST_FOREACH(const CKeyID &keyid, setKeys) { if (mapKeyBirth.count(keyid) == 0) mapKeyFirstBlock[keyid] = pindexMax; } setKeys.clear(); // if there are no such keys, we're done if (mapKeyFirstBlock.empty()) return; // find first block that affects those keys, if there are any left std::vector<CKeyID> vAffected; for (std::map<uint256, CWalletTx>::const_iterator it = mapWallet.begin(); it != mapWallet.end(); it++) { // iterate over all wallet transactions... const CWalletTx &wtx = (*it).second; std::map<uint256, CBlockIndex*>::const_iterator blit = mapBlockIndex.find(wtx.hashBlock); if (blit != mapBlockIndex.end() && blit->second->IsInMainChain()) { // ... which are already in a block int nHeight = blit->second->nHeight; BOOST_FOREACH(const CTxOut &txout, wtx.vout) { // iterate over all their outputs ::ExtractAffectedKeys(*this, txout.scriptPubKey, vAffected); BOOST_FOREACH(const CKeyID &keyid, vAffected) { // ... and all their affected keys std::map<CKeyID, CBlockIndex*>::iterator rit = mapKeyFirstBlock.find(keyid); if (rit != mapKeyFirstBlock.end() && nHeight < rit->second->nHeight) rit->second = blit->second; } vAffected.clear(); } } } // Extract block timestamps for those keys for (std::map<CKeyID, CBlockIndex*>::const_iterator it = mapKeyFirstBlock.begin(); it != mapKeyFirstBlock.end(); it++) mapKeyBirth[it->first] = it->second->nTime - 7200; // block times can be 2h off }
mit
uq-eresearch/dataspace
data-registry-webapp/src/main/java/net/metadata/dataspace/data/model/record/Collection.java
1656
package net.metadata.dataspace.data.model.record; import java.util.HashSet; import java.util.Set; import javax.persistence.CascadeType; import javax.persistence.Entity; import javax.persistence.FetchType; import javax.persistence.JoinTable; import javax.persistence.OneToMany; import net.metadata.dataspace.data.model.context.Subject; import net.metadata.dataspace.data.model.version.CollectionVersion; /** * User: alabri * Date: 15/09/2010 * Time: 3:32:27 PM */ @Entity public class Collection extends AbstractRecordEntity<CollectionVersion> { private static final long serialVersionUID = 1L; public enum Type { COLLECTION, DATASET } @OneToMany(cascade = CascadeType.ALL, fetch = FetchType.LAZY) @JoinTable(name = "collection_same_as") private Set<Collection> sameAs = new HashSet<Collection>(); public Collection() { } public Set<Subject> getSubjects() { return getMostRecentVersion().getSubjects(); } public Set<Agent> getCreators() { return getMostRecentVersion().getCreators(); } public Set<Agent> getPublishers() { return getMostRecentVersion().getPublishers(); } public Set<Activity> getOutputOf() { return getMostRecentVersion().getOutputOf(); } public Set<Service> getAccessedVia() { return getMostRecentVersion().getAccessedVia(); } public Set<Collection> getRelations() { return getMostRecentVersion().getRelations(); } public Set<Collection> getSameAs() { return sameAs; } public void setSameAs(Set<Collection> sameAs) { this.sameAs = sameAs; } }
mit
github/codeql
python/ql/test/library-tests/PointsTo/imports/package/x.py
19
from sys import *
mit
BryanDonovan/node-simple-elasticsearch
test/support/random.js
626
var random = { number: function (range) { range = range || 10000; return Math.floor(Math.random() * range); }, string: function (str_len) { str_len = str_len || 8; var chars = "abcdefghiklmnopqrstuvwxyz"; var random_str = ''; for (var i = 0; i < str_len; i++) { var rnum = Math.floor(Math.random() * chars.length); random_str += chars.substring(rnum, rnum + 1); } return random_str; }, email: function () { return this.string() + '+' + this.string() + '@' + 'example.com'; } }; module.exports = random;
mit
leedm777/cls-bcrypt
index.js
841
// Copyright (c) 2015. David M. Lee, II 'use strict'; var shimmer = require('shimmer'); var bcrypt = require('bcrypt'); module.exports = function(ns) { shimmer.wrap(bcrypt, 'genSalt', function(genSalt) { return function(rounds, cb) { // rounds is optional if (typeof rounds === 'function') { rounds = ns.bind(rounds); } if (typeof cb === 'function') { cb = ns.bind(cb); } return genSalt.call(this, rounds, cb); }; }); shimmer.wrap(bcrypt, 'hash', function(hash) { return function(data, salt, cb) { cb = ns.bind(cb); return hash.call(this, data, salt, cb); }; }); shimmer.wrap(bcrypt, 'compare', function(compare) { return function(data, hash, cb) { cb = ns.bind(cb); return compare.call(this, data, hash, cb); }; }); };
mit
haddada/Project
app/cache/dev/twig/1a/2d/dc76af4f75e39955753562e74a50fb2b437ac5e1af6693fd542d6930a298.php
2402
<?php /* base.html.twig */ class __TwigTemplate_1a2ddc76af4f75e39955753562e74a50fb2b437ac5e1af6693fd542d6930a298 extends Twig_Template { public function __construct(Twig_Environment $env) { parent::__construct($env); $this->parent = false; $this->blocks = array( 'title' => array($this, 'block_title'), 'stylesheets' => array($this, 'block_stylesheets'), 'body' => array($this, 'block_body'), 'javascripts' => array($this, 'block_javascripts'), ); } protected function doDisplay(array $context, array $blocks = array()) { // line 1 echo "<!DOCTYPE html> <html> <head> <meta charset=\"UTF-8\" /> <title>"; // line 5 $this->displayBlock('title', $context, $blocks); echo "</title> "; // line 6 $this->displayBlock('stylesheets', $context, $blocks); // line 7 echo " <link href='https://assets-fluc-com.s3.amazonaws.com/assets/c305f24190f031387a5e861b260c3a578eb3e5af/css/external.min.css' media='screen' rel='stylesheet' type='text/css'> <link rel=\"icon\" type=\"image/x-icon\" href=\""; // line 8 echo twig_escape_filter($this->env, $this->env->getExtension('assets')->getAssetUrl("favicon.ico"), "html", null, true); echo "\" /> </head> "; // line 11 $this->displayBlock('body', $context, $blocks); // line 12 echo " "; $this->displayBlock('javascripts', $context, $blocks); // line 13 echo " </html> "; } // line 5 public function block_title($context, array $blocks = array()) { echo "Welcome!"; } // line 6 public function block_stylesheets($context, array $blocks = array()) { } // line 11 public function block_body($context, array $blocks = array()) { } // line 12 public function block_javascripts($context, array $blocks = array()) { } public function getTemplateName() { return "base.html.twig"; } public function isTraitable() { return false; } public function getDebugInfo() { return array ( 71 => 12, 66 => 11, 61 => 6, 55 => 5, 49 => 13, 46 => 12, 44 => 11, 38 => 8, 35 => 7, 33 => 6, 29 => 5, 23 => 1,); } }
mit
ddpro/admin
src/DataTable/DataTable.php
20089
<?php namespace DDPro\Admin\DataTable; use Cartalyst\Sentinel\Laravel\Facades\Sentinel; use DDPro\Admin\Config\ConfigInterface; use DDPro\Admin\DataTable\Columns\Column; use DDPro\Admin\DataTable\Columns\Factory as ColumnFactory; use DDPro\Admin\Fields\Factory as FieldFactory; use DDPro\Admin\Helpers\DateTimeHelper; use DDPro\Admin\Includes\ImageHelper; use Illuminate\Database\DatabaseManager as DB; use Illuminate\Database\Eloquent\Builder as EloquentBuilder; use Illuminate\Database\Eloquent\Collection; use Illuminate\Database\Eloquent\Model; use Illuminate\Database\Query\Builder as QueryBuilder; use Illuminate\Support\Facades\Cache; use Log; use Mockery\CountValidator\Exception; /** * Class DataTable * * This defines the basic operations for a data table based on a Laravel model class, * This includes things like holding the configuration instance (from which the model * class can be determined), the validation instance, the Field Factory, the relationships, * etc. * * The DataTable manages the table view in the model index page. Each column in the * DataTable is represented by a Column object. * * ### Example * * ```php * // Example code goes here * ``` * * @see DDPro\Admin\DataTable\Columns\Factory * @see DDPro\Admin\DataTable\Columns\Column * @link https://github.com/ddpro/admin/blob/master/docs/columns.md */ class DataTable { /** * The config instance * * @var \DDPro\Admin\Config\ConfigInterface */ protected $config; /** * The column factory instance * * @var \DDPro\Admin\DataTable\Columns\Factory */ protected $columnFactory; /** * The field factory instance * * @var \DDPro\Admin\Fields\Factory */ protected $fieldFactory; /** * The column objects * * @var array */ protected $columns; /** * The sort options * * @var array */ protected $sort; /** * The number of rows per page for this data table * * @var int */ protected $rowsPerPage = 100; /** * Create a new action DataTable instance * * @param \DDPro\Admin\Config\ConfigInterface $config * @param \DDPro\Admin\DataTable\Columns\Factory $columnFactory * @param \DDPro\Admin\Fields\Factory $fieldFactory */ public function __construct(ConfigInterface $config, ColumnFactory $columnFactory, FieldFactory $fieldFactory) { // set the config, and then validate it $this->config = $config; $this->columnFactory = $columnFactory; $this->fieldFactory = $fieldFactory; } /** * Builds a results array (with results and pagination info) * * Used for server side DataTable * * @param \Illuminate\Database\DatabaseManager $db * @param array $input * * @return array */ public function getDataTableRows(DB $db, $input) { Log::debug(__CLASS__ . ':' . __TRAIT__ . ':' . __FILE__ . ':' . __LINE__ . ':' . __FUNCTION__ . ':' . 'getDataTableRows, input = ', $input); // prepare the query // Don't use this syntax, only because it makes it impossible for phpStorm to verify the // presence and type of the variables. // extract($this->prepareQuery($db, $page, $sort, $filters)); // This is functionally equivalent. /** @var QueryBuilder $query */ list($query, $querySql, $queryBindings, $countQuery, $sort, $selects) = $this->prepareQuery($db, $input); // run the count query $countResult = $this->performCountQuery($countQuery, $querySql, $queryBindings, 1); // now we need to limit and offset the rows in remembrance of our dear lost friend paginate() if (! empty($input['length'])) { $query->take($input['length']); } if (! empty($input['start'])) { $query->skip($input['start']); } // parse the results $output['recordsTotal'] = $countResult['total']; $output['recordsFiltered'] = $countResult['total']; $output['data'] = $this->parseResults($query->get()); if (! empty($input['draw'])) { $output['draw'] = (integer) $input['draw']; } return $output; } /** * Builds a results array (with results and pagination info) * * @param \Illuminate\Database\DatabaseManager $db * @param array $input * * @return array */ public function prepareQuery(DB $db, $input = []) { Log::debug(__CLASS__ . ':' . __TRAIT__ . ':' . __FILE__ . ':' . __LINE__ . ':' . __FUNCTION__ . ':' . 'prepareQuery, input = ', $input); // grab the model instance /** @var Model $model */ $model = $this->config->getDataModel(); if (! isset($input['columns']) || ! is_array($input['columns'])) { Log::warning(__CLASS__ . ':' . __TRAIT__ . ':' . __FILE__ . ':' . __LINE__ . ':' . __FUNCTION__ . ':' . 'Input array does not contain a columns array, cannot get column options.', $input); } else { // Grab the columns array from the input // We have provided input columns so we can get the sort structure from that. $inputColumns = $input['columns']; } // update the sort options $sort = []; if (isset($input['order']) && is_array($input['order']) && isset($inputColumns)) { // If this is set then it will have this structure: // ['column' => $column_number, 'dir' => 'asc'|'desc'] // Have to find the column name from the column number $inputOrder = $input['order'][0]; $sort = [ 'field' => $inputColumns[$inputOrder['column']]['name'], 'direction' => $inputOrder['dir'], ]; } $this->setSort($sort); $sort = $this->getSort(); // get things going by grouping the set $table = $model->getTable(); $keyName = $model->getKeyName(); /** @var EloquentBuilder $query */ $query = $model->groupBy($table . '.' . $keyName); // get the Illuminate\Database\Query\Builder instance and set up the count query $dbQuery = $query->getQuery(); $countQuery = $dbQuery->getConnection()->table($table)->groupBy($table . '.' . $keyName); // run the supplied query filter for both queries if it was provided $this->config->runQueryFilter($dbQuery); $this->config->runQueryFilter($countQuery); // set up initial array states for the selects $selects = [$table . '.*']; // set the filters if (isset($input['filters'])) { // 'show_deleted' filter is a special filter, it needs to be run at the very first stage of the query builder if (isset($input['filters']['show_deleted']['value'])) { $filterValue = $input['filters']['show_deleted']['value']; if ($filterValue == '') { // Show all $query->withTrashed(); } elseif ($filterValue == 'yes') { // Trash only $query->onlyTrashed(); } } // Unset this filter so that it won't effect later stage unset($input['filters']['show_deleted']); // Unset empty values from array filters foreach ($input['filters'] as $key => &$value) { if (isset($value['value']) && is_array($value['value'])) { foreach ($value['value'] as $key1 => $value1) { if (empty($value1)) { unset($value['value'][$key1]); } } } } Log::debug(__CLASS__ . ':' . __TRAIT__ . ':' . __FILE__ . ':' . __LINE__ . ':' . __FUNCTION__ . ':' . 'input filters = ', $input['filters']); $this->setFilters($input['filters'], $dbQuery, $countQuery, $selects); } // set the selects $dbQuery->select($selects); // determines if the sort should have the table prefixed to it $sortOnTable = true; // get the columns $columns = $this->columnFactory->getColumns(); Log::debug(__CLASS__ . ':' . __TRAIT__ . ':' . __FILE__ . ':' . __LINE__ . ':' . __FUNCTION__ . ':' . 'columns = ', $columns); // iterate over the columns to check if we need to join any values or add any extra columns /** @var Column $column */ foreach ($columns as $column) { // if this is a related column, we'll need to add some selects $column->filterQuery($selects); // if this is a related field or if (($column->getOption('is_related') || $column->getOption('select')) && $column->getOption('column_name') === $sort['field']) { $sortOnTable = false; } } // if the sort is on the model's table, prefix the table name to it if ($sortOnTable) { $sort['field'] = $table . '.' . $sort['field']; } // grab the query sql for later $querySql = $query->toSql(); // order the set by the model table's id $query->orderBy($sort['field'], $sort['direction']); // then retrieve the rows $query->getQuery()->select($selects); // only select distinct rows $query->distinct(); // load the query bindings $queryBindings = $query->getBindings(); // return compact('query', 'querySql', 'queryBindings', 'countQuery', 'sort', 'selects'); return [$query, $querySql, $queryBindings, $countQuery, $sort, $selects]; } /** * Performs the count query and returns info about the pages * * @param \Illuminate\Database\Query\Builder $countQuery * @param string $querySql * @param array $queryBindings * @param int $page * * @return array */ public function performCountQuery(QueryBuilder $countQuery, $querySql, $queryBindings, $page) { Log::debug(__CLASS__ . ':' . __TRAIT__ . ':' . __FILE__ . ':' . __LINE__ . ':' . __FUNCTION__ . ':' . 'performCountQuery, querySql = ' . $querySql); // grab the model instance $model = $this->config->getDataModel(); // then wrap the inner table and perform the count $sql = "SELECT COUNT({$model->getKeyName()}) AS aggregate FROM ({$querySql}) AS agg"; // then perform the count query $results = $countQuery->getConnection()->select($sql, $queryBindings); $numRows = is_array($results[0]) ? $results[0]['aggregate'] : $results[0]->aggregate; $page = (int) $page; $last = (int) ceil($numRows / $this->rowsPerPage); return [ // if the current page is greater than the last page, set the current page to the last page 'page' => $page > $last ? $last : $page, 'last' => $last, 'total' => $numRows, ]; } /** * Sets the query filters when getting the rows * * This takes an array of this structure: * * ```php * [ * 'field_name' => $field_name, * 'value' => $value, * 'min_value' => $min_value, * 'max_value' => $max_value, * ] * ``` * * @param array $filters * @param \Illuminate\Database\Query\Builder $query * @param \Illuminate\Database\Query\Builder $countQuery * @param array $selects */ public function setFilters($filters, QueryBuilder &$query, QueryBuilder &$countQuery, &$selects) { // then we set the filters if ($filters && is_array($filters)) { foreach ($filters as $filter) { // get the field object $fieldObject = $this->fieldFactory->findFilter($filter['field_name']); // set the filter on the object $fieldObject->setFilter($filter); // filter the query objects, only pass in the selects the first time so they aren't added twice $fieldObject->filterQuery($query, $selects); $fieldObject->filterQuery($countQuery); } } } /** * Parses the results of a getRows query and converts it into a manageable array with the proper rendering * * @param Collection|array $rows * * @return array */ public function parseResults($rows) { Log::debug(__CLASS__ . ':' . __TRAIT__ . ':' . __FILE__ . ':' . __LINE__ . ':' . __FUNCTION__ . ':' . 'parseResults'); $results = []; // convert the resulting set into arrays foreach ($rows as $item) { // iterate over the included and related columns $arr = []; $this->parseOnTableColumns($item, $arr); // then grab the computed, unsortable columns $this->parseComputedColumns($item, $arr); $results[] = $arr; } return $results; } /** * Goes through all related columns and sets the proper values for this row * * @param \Illuminate\Database\Eloquent\Model $item * @param array $outputRow * * @return void */ public function parseOnTableColumns($item, array &$outputRow) { Log::debug(__CLASS__ . ':' . __TRAIT__ . ':' . __FILE__ . ':' . __LINE__ . ':' . __FUNCTION__ . ':' . 'About to look at columnFactory, config title = ' . $this->config->getOption('title')); $cache_key = 'datatable_column_names_' . str_slug($this->config->getOption('title')); $columns = $this->columnFactory->getColumns(); // // Cache the column factory results because getEditFields() can take a long time. // if (Cache::has($cache_key)) { Log::debug(__CLASS__ . ':' . __TRAIT__ . ':' . __FILE__ . ':' . __LINE__ . ':' . __FUNCTION__ . ':' . 'Using cached columns'); $allColumns = Cache::get($cache_key); } else { $includedColumns = $this->columnFactory->getIncludedColumns($this->fieldFactory->getEditFields()); $relatedColumns = $this->columnFactory->getRelatedColumns(); $allColumns = array_merge($columns, $includedColumns, $relatedColumns); // Actually we only need to cache the column keys (names), not the actual column data. $allColumns = array_keys($allColumns); Cache::put($cache_key, $allColumns, 60); } // loop over all column names foreach ($allColumns as $field) { if (! isset($columns[$field])) { continue; } // if this column is in our objects array, render the output with the given value /** @var Column $column */ $column = $columns[$field]; $attributeValue = $item->getAttribute($field); #Log::debug(__CLASS__ . ':' . __TRAIT__ . ':' . __FILE__ . ':' . __LINE__ . ':' . __FUNCTION__ . ':' . # "column $field getAttribute = " . print_r($attributeValue, true)); // Various table column mutators, in-built if (! empty($attributeValue)) { switch ($column->getOption('type')) { case 'image': $real_path = ImageHelper::getImageUrl($attributeValue); $attributeValue = '<img src="' . $real_path . '" class="thumbnail" />'; break; case 'date': if ($attributeValue instanceof \DateTime) { $dt = $attributeValue; } else { $dt = new \DateTime($attributeValue); } $attributeValue = $dt->format(config('administrator.format.date_carbon')); break; case 'datetime': $attributeValue = DateTimeHelper::formatDateTime($attributeValue); break; } } $outputRow[] = $column->renderOutput($attributeValue, $item); } } /** * Goes through all computed columns and sets the proper values for this row * * @param \Illuminate\Database\Eloquent\Model $item * @param array $outputRow * * @return void */ public function parseComputedColumns($item, array &$outputRow) { Log::warning(__CLASS__ . ':' . __TRAIT__ . ':' . __FILE__ . ':' . __LINE__ . ':' . __FUNCTION__ . ':' . 'parse computed columns called, this has not been checked'); $columns = $this->columnFactory->getColumns(); $computedColumns = $this->columnFactory->getComputedColumns(); // loop over the computed columns foreach ($computedColumns as $name => $column) { /** @var Column $column */ $column = $columns[$name]; $outputRow[] = $column->renderOutput($item->{$name}, $item); } } /** * Sets up the sort options * * Takes in an array like this: * * ```php * [ * 'field' => $fieldname, * 'direction' => 'asc'|'desc', * ] * ``` * * @param array $sort */ public function setSort($sort = null) { $sort = $sort && is_array($sort) ? $sort : $this->config->getOption('sort'); // set the sort values $this->sort = [ 'field' => isset($sort['field']) ? $sort['field'] : $this->config->getDataModel()->getKeyName(), 'direction' => isset($sort['direction']) ? $sort['direction'] : 'desc', ]; // if the sort direction isn't valid, set it to 'desc' if (! in_array($this->sort['direction'], ['asc', 'desc'])) { $this->sort['direction'] = 'desc'; } } /** * Gets the sort options * * @return array */ public function getSort() { return $this->sort; } /** * Set the number of rows per page for this data table * * @param \Illuminate\Session\Store $session * @param int $globalPerPage * @param int $override // if provided, this will set the session's rows per page value */ public function setRowsPerPage(\Illuminate\Session\Store $session, $globalPerPage, $override = null) { $name = $this->config->getOption('name'); if (empty($name)) { $name = 'global'; } Log::debug(__CLASS__ . ':' . __TRAIT__ . ':' . __FILE__ . ':' . __LINE__ . ':' . __FUNCTION__ . ':' . 'set rows per page handler for ' . $name . ' to ' . $globalPerPage . ' override ' . $override); if ($override) { $perPage = (int) $override; Log::debug(__CLASS__ . ':' . __TRAIT__ . ':' . __FILE__ . ':' . __LINE__ . ':' . __FUNCTION__ . ':' . 'override is set to ' . $perPage . ', store to session'); $session->put('administrator_' . $name . '_rows_per_page', $perPage); } $perPage = $session->get('administrator_' . $name . '_rows_per_page'); Log::debug(__CLASS__ . ':' . __TRAIT__ . ':' . __FILE__ . ':' . __LINE__ . ':' . __FUNCTION__ . ':' . 'session rows per page is ' . $perPage); if (empty($perPage)) { $perPage = (int) $globalPerPage; } $this->rowsPerPage = $perPage; } /** * Gets the rows per page * * @return int */ public function getRowsPerPage() { return $this->rowsPerPage; } }
mit
mrwrob/netfweb
netfweb/content.js
18984
// Runs background script to aquire score from FilmWeb. Adds SPAN and fullfill it with data from storage. /** * Send message to background.js to report the correctness of links to rating websites. * @param {string} idNetflix - title's netflix ID * @param {boolean} ok - true the link correct, otherwise false * @param {string} source - rating website id (fw - Filmweb, me - Metacritic, im - IMDb) */ function reportLinks(idNetflix, ok, source){ chrome.runtime.sendMessage({type: "report", idNetflix: idNetflix, ok: ok, source: source}); } /** * Clears storage entry regarding mapping between given title and website * @param {string} idNetflix - title's netflix ID * @param {string} source - rating website name (filmweb, metacritic, imdb) */ function clearMap(idNetflix, source){ var itemJSON = JSON.stringify({'URL' : ''}); var save = {}; save[source+"_"+idNetflix] = itemJSON; chrome.storage.local.set(save); } /** * Clears storage entry regarding mapping between given title and website * @param {string} data - data read from storage * @return {json} - returns JSON object (with score and URL values) */ function getInfo(data){ if(data){ var infoJSON = JSON.parse(data); if(infoJSON.score == "0" || infoJSON.score == "" || infoJSON.score == undefined) infoJSON.score="?"; return infoJSON; } else { return JSON.parse('{ "score": "?", "URL": ""}'); } } function displayScore(score){ if(score && (score == "?")) return score; if(isNaN(score)) newScore = parseFloat(score.replace(",",".")); else newScore = score; if(newScore < 10) return Math.round(newScore*10)/10 else return Math.round(newScore); } /** * Place title's rating from one selected source on browsing page (that with multiply titles) * @param {string} titleName - title's name * @param {string} idNetflix - title's netflix ID * @param {string} filmBox - jquery object where information will be placed */ function placeScore(titleName, idNetflix, filmBox){ /* Send message to background.js to prepare information about rating of selected title, all=1 - only for one, currently selected source website */ chrome.runtime.sendMessage({type: "getScore", titleName: titleName, idNetflix: idNetflix, all: "1"}); // if(filmBox.find('div.nfw_score').length == 0 || filmBox.find('div.nfw_score').text != '?'){ if(filmBox.find('div.nfw_score').length == 0){ filmBox.append("<div class='nfw_score title_"+idNetflix+"'></div>"); if(!scoreSource) scoreSource='tmdb'; var readStore = scoreSource+"_"+idNetflix; /* Read and place score from storage */ chrome.storage.local.get(readStore, function(data) { colorScore = currScore = displayScore(getInfo(data[readStore]).score); if(displayColors && (colorScore != '?')){ if(colorScore>10) colorScore /= 10; if(colorScore < 5) colorClass = 'red'; else if(colorScore < 6.5) colorClass = 'orange'; else if(colorScore < 8) colorClass = 'yellow'; else colorClass = 'green'; filmBox.find(".nfw_score").addClass('nfw_circle_'+colorClass); } filmBox.find(".nfw_score").html(currScore); }); var readStore_w = "watch_"+idNetflix; /* Read and place score from storage */ chrome.storage.local.get(readStore_w, function(data) { if(data[readStore_w]){ filmBox.css('opacity', '0.3'); } }); } } /** * Place title's ratings from all sources on title's detail page * @param {string} titleName - title's name * @param {string} idNetflix - title's netflix ID * @param {string} filmBox - jquery object where information will be placed */ function placeScoreJaw(titleName, idNetflix, filmBox){ chrome.runtime.sendMessage({type: "getScore", titleName: titleName, idNetflix: idNetflix, all: "0", serviceDisplay: serviceDisplay}); filmBox.before("<div class='nfw_score_jaw'><img class='nfw_wrong' src='"+chrome.extension.getURL("/wrong.png")+"'> <img src='"+chrome.extension.getURL("/star.png")+"'><div id='nfw_report_a'><div id='nfw_report'></div></div> </div>"); filmBox.before("<div class='nfw_related'><a href='https://www.netflix.com/search?q=%20&suggestionId="+idNetflix+"_video'>related titles...</a></div>"); destBox = filmBox.parent().find('.nfw_score_jaw'); /* Reporting information about correctness of links to websites with ratings */ destBox.find(".nfw_wrong").click(function(){ $nfw_report=$(this).parent().find('#nfw_report'); if($nfw_report.html()){ var save = {}; save['clipboard'] = {idNetflix: idNetflix, title: titleName}; chrome.storage.local.set(save); $nfw_report.css("display", "block"); } $(this).remove(); }); var params = {}; if(serviceDisplay["imdb"] != 0) params["imdb"] ={ "URL": "http://www.imdb.com/find?ref_=nv_sr_fn&s=all&q=", "shortcut": "im", "name": "IMDb"}; if(serviceDisplay["tmdb"] != 0) params["tmdb"] = { "URL": "https://www.themoviedb.org/search?query=", "shortcut": "tm", "name": "TheMovieDB"}; if(serviceDisplay["rotten_tomatoes"] != 0) params["rotten_tomatoes"] = { "URL": "https://www.rottentomatoes.com/search?search=", "shortcut": "rt", "name": "Rotten Tomatoes"}; if(serviceDisplay["filmweb"] != 0) params["filmweb"] = { "URL": "https://www.filmweb.pl/search?q=", "shortcut": "fw", "name": "Filmweb"}; if(serviceDisplay["metacritic"] != 0) params["metacritic"] = { "URL": "http://www.metacritic.com/search/all/", "URL2": "/results?cats%5Bmovie%5D=1&cats%5Btv%5D=1&search_type=advanced", "shortcut": "me", "name": "Metacritic"}; if(serviceDisplay["film_affinity"] != 0) params["film_affinity"] = { "URL": "https://www.filmaffinity.com/us/search.php?stext=", "shortcut": "fa", "name": "FilmAffinity"}; if(serviceDisplay["trakt_tv"] != 0) params["trakt_tv"] = { "URL": "https://trakt.tv/search?query=", "shortcut": "tk", "name": "Trakt TV"}; Object.keys(params).forEach(function(source){ var readStore = source+"_"+idNetflix; chrome.storage.local.get(readStore, function(data) { var infoJSON = getInfo(data[readStore]); var watched = infoJSON.seen=='1' ? true : false; var sourceURL = infoJSON.URL; if(!sourceURL) { sourceURL=params[source].URL+encodeURIComponent(titleName).replace("'","%27"); if(params[source].URL2) sourceURL+=params[source].URL2; } destBox.append(" <a target='_blank' class='nfw_jaw_link link_"+readStore+"' href='"+sourceURL+"'>&nbsp;"+params[source].name+"&nbsp;<span class='title_"+readStore+"'>"+displayScore(infoJSON.score) + (watched ? " Watched" : "") +"</span></a>&nbsp;<img src='"+chrome.extension.getURL("/star.png")+"'> "); if(infoJSON.v!=1) { destBox.find('#nfw_report').append("<div id='ntw_"+params[source].shortcut+"_report'>"+params[source].name+"&nbsp;<img id='ntw_"+params[source].shortcut+"_ok' class='nfw_button' src='"+chrome.extension.getURL("/ok.png")+"'>&nbsp;<img id='ntw_"+params[source].shortcut+"_wrong' class='nfw_button' src='"+chrome.extension.getURL("/wrong.png")+"'> </div>"); destBox.find('#ntw_'+params[source].shortcut+'_ok').click(function(){ reportLinks(idNetflix, true, params[source].shortcut); destBox.find('#ntw_'+params[source].shortcut+'_report').remove(); }); destBox.find('#ntw_'+params[source].shortcut+'_wrong').click(function(){ reportLinks(idNetflix, false, params[source].shortcut); clearMap(idNetflix, source); destBox.find('#ntw_'+params[source].shortcut+'_report').remove(); }); } }); }) } /** * Place title's ratings from all sources on title's popup page * @param {string} titleName - title's name * @param {string} idNetflix - title's netflix ID * @param {string} filmBox - jquery object where information will be placed */ function placeScoreBob(titleName, idNetflix, filmBox){ chrome.runtime.sendMessage({type: "getScore", titleName: titleName, idNetflix: idNetflix, all: "0", serviceDisplay: serviceDisplay}); filmBox.append("<div class='nfw_score_bob'></div>"); destBox = filmBox.parent().find('.nfw_score_bob'); var params = {}; if(serviceDisplay["tmdb"] != 0) params["tmdb"] = { "URL": "https://www.themoviedb.org/search?query=", "shortcut": "tm", "name": "TheMovieDB"}; if(serviceDisplay["imdb"] != 0) params["imdb"] ={ "URL": "http://www.imdb.com/find?ref_=nv_sr_fn&s=all&q=", "shortcut": "im", "name": "IMDb"}; if(serviceDisplay["rotten_tomatoes"] != 0) params["rotten_tomatoes"] = { "URL": "https://www.rottentomatoes.com/search?search=", "shortcut": "rt", "name": "Rotten Tomatoes"}; if(serviceDisplay["filmweb"] != 0) params["filmweb"] = { "URL": "https://www.filmweb.pl/search?q=", "shortcut": "fw", "name": "Filmweb"}; if(serviceDisplay["metacritic"] != 0) params["metacritic"] = { "URL": "http://www.metacritic.com/search/all/", "URL2": "/results?cats%5Bmovie%5D=1&cats%5Btv%5D=1&search_type=advanced", "shortcut": "me", "name": "Metacritic"}; if(serviceDisplay["film_affinity"] != 0) params["film_affinity"] = { "URL": "https://www.filmaffinity.com/us/search.php?stext=", "shortcut": "fa", "name": "FilmAffinity"}; if(serviceDisplay["trakt_tv"] != 0) params["trakt_tv"] = { "URL": "https://trakt.tv/search?query=", "shortcut": "tk", "name": "Trakt TV"}; Object.keys(params).forEach(function(source){ var readStore = source+"_"+idNetflix; chrome.storage.local.get(readStore, function(data) { var infoJSON = getInfo(data[readStore]); var sourceURL = infoJSON.URL; var watched = infoJSON.seen=='1' ? true : false; if(!sourceURL) { sourceURL=params[source].URL+encodeURIComponent(titleName).replace("'","%27"); if(params[source].URL2) sourceURL+=params[source].URL2; } destBox.append(" <img src='"+chrome.extension.getURL("/star.png")+"'>&nbsp;<a target='_blank' class='nfw_jaw_link link_"+readStore+"' href='"+sourceURL+"'>&nbsp;"+params[source].name+"&nbsp;<span class='title_"+readStore+"'>"+displayScore(infoJSON.score)+ (watched ? " Watched" : "") +"</span></a>"); if(watched){ box_movie.find(".title-card-container").addClass('nfw_watched'); } }); }); } chrome.runtime.sendMessage({type: "update_token"}); /* * Listens to changes in data storage and changes information about ratings */ chrome.storage.onChanged.addListener(function(changes, namespace) { titleName=score=""; for (key in changes) { if(key.match(/scoreChecked_/)){ serviceDisplay[key.replace(/scoreChecked_/,(""))] = changes[key].newValue.checked; }else if(key!="scoreSource"){ var storageChange = changes[key]; idNetflix=key.replace(scoreSource+"_",""); data=storageChange.newValue; if(key.match(scoreSource)){ $(".title_"+idNetflix).each(function(){ colorScore = currScore = displayScore(getInfo(data).score); $(this).html(currScore); if(displayColors && (colorScore != '?')){ if(colorScore>10) colorScore /= 10; if(colorScore < 5) colorClass = 'red'; else if(colorScore < 6.5) colorClass = 'orange'; else if(colorScore < 8) colorClass = 'yellow'; else colorClass = 'green'; $(this).addClass('nfw_circle_'+colorClass); } }); } if(key.match("watch_")){ idNetflix=key.replace("watch_",""); $(".title_"+idNetflix).each(function(){ $(this).closest('.title-card-container').css('opacity', '0.3'); }); } $(".title_"+key).each(function(){ $(this).html(displayScore(getInfo(data).score)); }); $(".link_"+key).each(function(){ $(this).attr('href',getInfo(data).URL); }); } } }); var scoreSource='tmdb'; // Default ratings source website var readStore = "scoreSource"; var readStore1 = "colorsChecked"; var displayColors=false; chrome.storage.local.get(readStore1, function(data) { if((data !== undefined) && (data[readStore1] !== undefined)) { if(data['colorsChecked']==1) displayColors=true ; } }); chrome.storage.local.get(readStore, function(data) { if((data !== undefined) && (data[readStore] !== undefined)) scoreSource = data[readStore]; // For all displayed titles $('.title-card').each(function(){ titleName = $(this).find('.fallback-text:first').text(); // Gets the title's name idNetflix = $(this).find('a').attr('href').replace(/\/watch\/([0-9]*).*/,"$1"); // Gets the title's netflix ID if(idNetflix){ placeScore(titleName,idNetflix, $(this)); } }); // For selected title (details view) $('.jawBoneContainer').each(function(){ titleName=$(this).find('div.title').text(); if(!titleName){ titleName=$(this).find('img.logo').attr('alt'); } idNetflix = $(this).find('a').attr('href').replace(/\/title\/([0-9]*).*/,"$1"); if(titleName) { if($(this).find('div.meta-lists')) { var filmBox = $(this).find('div.previewModal--detailsMetadata-info'); titleName2=titleName; idNetflix2=idNetflix setTimeout(function(){ placeScoreJaw(titleName2, idNetflix2, filmBox); }, 1000); } else placeScoreJaw(titleName, idNetflix, $(this).find('div.previewModal--detailsMetadata-info')); } }); }); var servicesArray = ["tmdb", "imdb", "rotten_tomatoes", "metacritic", "filmweb", "film_affinity", "trakt_tv"]; var serviceDisplay = {"tmdb": 1, "imdb": 1, "rotten_tomatoes": 1, "metacritic": 1, "filmweb": 1, "film_affinity": 1, "trakt_tv": 1}; for(var service of servicesArray){ chrome.storage.local.get("scoreChecked_"+service, function(data) { if(data !== undefined || data[readStore] !== undefined){ var keyValue = Object.keys(data)[0]; if(keyValue !== undefined){ if(data[keyValue].checked == 0){ serviceDisplay[keyValue.replace(/scoreChecked_/,"")] = 0 } } } }); } // Allows to monitor changes in DOM. var observer = new MutationObserver(function( mutations ) { // based on https://gabrieleromanato.name/jquery-detecting-new-elements-with-the-mutationobserver-object/ mutations.forEach(function( mutation ) { var newNodes = mutation.addedNodes; // DOM NodeList if( newNodes !== null ) { // If there are new nodes added var $nodes = $( newNodes ); // jQuery set $nodes.each(function() { if($(this).attr('class') !== undefined){ // For all displayed titles $(this).find('.title-card-container').each(function(){ titleName = $(this).find('.fallback-text:first').text(); idNetflix = $(this).find('a').attr('href').replace(/\/watch\/([0-9]*).*/,"$1"); if(idNetflix) { placeScore(titleName,idNetflix, $(this)); } }); // For selected title (details view) if($(this).attr('class').match(/focus-trap-wrapper.previewModal--wrapper.detail-modal/)){ if(idNetflix) { detailDialog = $(this).closest('#appMountPoint'); titleName=detailDialog.find('.previewModal--player-titleTreatment-logo').attr('alt'); idNetflix = detailDialog.find('div.ptrack-content').attr('data-ui-tracking-context').replace(/.*%22video_id%22:([0-9]*).*/,"$1"); placeScoreBob(titleName,idNetflix, $(this).find('div.previewModal--detailsMetadata')); } } if($(this).attr('class').match(/bob-card/)){ titleName=$(this).find('.bob-title').text(); idNetflix = $(this).find('div.ptrack-content').attr('data-ui-tracking-context').replace(/.*%22video_id%22:([0-9]*).*/,"$1"); if(idNetflix) { placeScoreBob(titleName,idNetflix, $(this).find('div.previewModal--popup')); } } if($(this).attr('class').match(/focus-trap-wrapper.previewModal--wrapper.mini-modal/)){ titleName=$(this).find('.previewModal--boxart').attr('alt'); idNetflix = $(this).find('div.ptrack-content').attr('data-ui-tracking-context').replace(/.*%22video_id%22:([0-9]*).*/,"$1"); if(idNetflix) { placeScoreBob(titleName,idNetflix, $(this).find('div.previewModal--info')); } } // For the player //tem de guardar na memoria o que esta a ver (UNIQUE) //limpa ao para //se não limpar tem de limpar antes de entrar outro if($(this).attr('class').match(/svg-icon-nfplayerPlay/)){ idNetflix = window.location.pathname.replace("/watch/",""); chrome.runtime.sendMessage({type: "watch", idNetflix: idNetflix, mode: "pause"}); console.log("Is paused"); } if($(this).attr('class').match(/svg-icon-nfplayerPause/)){ idNetflix = window.location.pathname.replace("/watch/",""); chrome.runtime.sendMessage({type: "watch", idNetflix: idNetflix, mode: "play"}); console.log("Is playing"); } if($(this).attr('class').match(/touchable.PlayerControls--control-element.nfp-popup-control.nfp-popup-control--static-position/)){ idNetflix = window.location.pathname.replace("/watch/",""); chrome.runtime.sendMessage({type: "watch", idNetflix: idNetflix, mode: "start"}); console.log("Start"); } if($(this).attr('class').match(/ptrack-container.fill-container.OriginalsPostPlay-BackgroundTrailer/)){ idNetflix = window.location.pathname.replace("/watch/",""); chrome.runtime.sendMessage({type: "watch", idNetflix: idNetflix, mode: "end"}); console.log("End"); } } }); } }); }); // Configuration of the MutationObserver: var config = { childList: true, subtree: true, characterData: true }; // Pass in the target node, as well as the observer options var target = $('#appMountPoint')[0]; observer.observe(target, config);
mit
maland/orders_tracker
lib/orders_tracker/version.rb
45
module OrdersTracker VERSION = "0.0.1" end
mit
ajames72/MovieDBReact
src/components/search/movies/MoviePage.test.js
1223
import React from 'react'; import { Provider } from 'react-redux'; import configureStore from 'redux-mock-store'; import thunk from 'redux-thunk'; import expect from 'expect'; import { mount } from 'enzyme'; import MoviePage from './MoviePage'; import * as TestData from '../../../../test/TestData'; describe('MoviePage', () => { //Fake Store and Middleware const middlewares = [ thunk ]; const mockStore = configureStore(middlewares); const initialState = { languages: TestData.languages, countries: TestData.countries, config: TestData.tmdb_configuration, searchResults: {results: []}, sectionAttributes: { 'section': "movies", 'title': "Movie Search" } }; describe('Component Structure', () => { let moviePage; beforeEach(() => { let store = mockStore(initialState); moviePage = mount( <Provider store={store}> <MoviePage /> </Provider> ); }); it('should display the search box', () => { expect(moviePage.find('.tmdb-searchbox').length).toEqual(1); }); it('should display the search options', () => { expect(moviePage.find('.tmdb-searchoptions').length).toEqual(1); }); }); });
mit
Sunderous/lupine
modules/brewing/server/controllers/brewing.server.controller.js
2480
'use strict'; /** * Module dependencies */ var path = require('path'), mongoose = require('mongoose'), Sensor = mongoose.model('Sensor'), errorHandler = require(path.resolve('./modules/core/server/controllers/errors.server.controller')); /** * Create a sensor */ exports.create = function(req, res) { var sensor = new Sensor(req.body); sensor.updated = Date.now; sensor.save(function(err) { if (err) { return res.status(422).send({ message: errorHandler.getErrorMessage(err) }); } else { res.json(sensor); } }); }; /** * Show the current sensor */ exports.read = function(req, res) { // convert mongoose document to JSON var sensor = req.sensor ? req.sensor.toJSON() : {}; res.json(sensor); }; /** * Update a sensor */ exports.update = function(req, res) { var sensor = req.sensor; sensor.value = req.body.value; sensor.updated = Date.now(); sensor.save(function(err) { if (err) { return res.status(422).send({ message: errorHandler.getErrorMessage(err) }); } else { // Need socket.io logic here for realtime updates var io = req.app.get('socketio'); io.sockets.emit('sensor.updated', sensor); res.json(sensor); } }); }; /** * Delete a sensor */ exports.delete = function(req, res) { var sensor = req.sensor; sensor.remove(function(err) { if (err) { return res.status(422).send({ message: errorHandler.getErrorMessage(err) }); } else { res.json(sensor); } }); }; /** * List of Sensors */ exports.list = function(req, res) { Sensor.find().sort('+sensorId').exec(function(err, sensors) { if (err) { return res.status(422).send({ message: errorHandler.getErrorMessage(err) }); } else { res.json(sensors); } }); }; /** * Sensor middleware */ exports.sensorByID = function(req, res, next, id) { Sensor.findOne({ 'sensorId': id }).exec(function(err, sensor) { if (err) { return next(err); } else if (!sensor) { return res.status(404).send({ message: 'No sensor with that identifier has been found' }); } req.sensor = sensor; next(); }); };
mit
iefserge/eshttp
test/index.js
174
'use strict'; require('../lib/backend').setBackend(require('../backend/backend-node')); require('./headers'); require('./parser'); require('./request'); require('./server');
mit
jiunjiun/redesign
app/controllers/projects/editors_controller.rb
503
class Projects::EditorsController < Projects::AccessController before_action :set_project before_action :project_data def index end def update redirect_to project_path(params[:username], params[:project_name]) if @project.update(project_params) end private def set_project @project = Project.find_by({user: @current_page_user, name: params[:project_name]}) end def project_params params.require(:project).permit(style_attributes: [:stylesheet]) end end
mit
madvas/node-randombase64
lib/randombase64.js
1884
var Canvas = require('canvas'); function getRandomArbitrary(min, max) { return Math.floor(Math.random() * (max - min + 1) + min); } exports.generate = function(options, callback) { var canvas = new Canvas() , ctx = canvas.getContext('2d') , x, y , unitSize , opacity , width, height , getRgb; options = options || {}; unitSize = options.unitSize || 3; opacity = options.opacity || 1; options.type = options.type || 'image/png'; if (options.width) { width = options.width; } else if (options.minWidth && options.maxWidth) { width = getRandomArbitrary(options.minWidth, options.maxWidth); } else { width = 300; } if (options.height) { height = options.height; } else if (options.minHeight && options.maxHeight) { height = getRandomArbitrary(options.minHeight, options.maxHeight); } else { height = 300; } if (options.blackAndWhite) { getRgb = function() { var color = Math.round(Math.random()) * 255; return [color, color, color] } } else { getRgb = function() { return [getRandomArbitrary(0, 255), getRandomArbitrary(0, 255), getRandomArbitrary(0, 255)] } } canvas.width = width; canvas.height = height; for (x = 0; x < width; x += unitSize) { for (y = 0; y < height; y += unitSize) { var rgb = getRgb(); ctx.fillStyle = "rgba(" + rgb[0] + "," + rgb[1] + "," + rgb[2] + "," + opacity + ")"; ctx.fillRect(x, y, unitSize, unitSize); } } if (!options.withPrefix) { var prefix = 'data:' + options.type + ';base64,'; if (callback) { var callbackWrap = function(err, str) { callback(err, str.replace(prefix, '')); }; return canvas.toDataURL(options.type, callbackWrap); } return canvas.toDataURL(options.type).replace(prefix, ''); } return canvas.toDataURL(options.type, callback); };
mit
sikuli/sikuli-slides
jruby/lib/sikuli-slides/exception.rb
64
module Sikuli class TargetNotFound < StandardError end end
mit
royriojas/mac-scripts
scripts/app.py
1402
#!/usr/bin/env python # # simle'n'stupid vhost "parser" # # Usage: ./vhosts-reader.py FILE # FILE is a apache config file import re import sys import os.path if len(sys.argv) != 2: sys.exit('Usage: %s FILE' % sys.argv[0]) FILE = sys.argv[1] if not os.path.isfile(FILE): sys.exit('Unknown file %s' % FILE) f = open(FILE, 'r') data_all = f.readlines() f.close() data = filter( lambda i: re.search('^((?!#).)*$', i), data_all) ID = 0 enable = False result = {} vhost = [] while len(data) > 0: out = data.pop(0) # start of VirtualHost if "<VirtualHost" in out: ip_port = out.split()[1] ip, port = ip_port.split(':') port = port.replace('>', '') vhost.append(ip) vhost.append(port) enable = True continue if "</VirtualHost>" in out: result[ID] = vhost ID+=1 enable = False vhost = [] continue if enable: vhost.append(out) continue for i in result: # result[i][0] is an IP # result[i][1] is a port # another list items are lines in vhost, grep them all for line in result[i]: if "ServerName" in line: servername = line.split()[1] continue if "DocumentRoot" in line: documentroot = line.split()[1] continue print "--> %s: ==> %s" % (servername, documentroot)
mit
CoderAllan/SqlServerSearcher
src/Model/EventArgs/BaseFormEventArgs.cs
287
namespace SQLServerSearcher.Model.EventArgs { using System; using System.Drawing; public class BaseFormEventArgs : EventArgs { public int Width { get; set; } public int Height { get; set; } public Point Location { get; set; } } }
mit
ModusCreateOrg/budgeting-sample-app-webpack2
app/components/Field/index.js
2633
// @flow import * as React from 'react'; import isObject from 'utils/isObject'; import consumeContextBroadcast from 'utils/consumeContextBroadcast'; import type { FormData } from 'components/Form'; type FieldProps = { component?: React.ElementType, name: string, handleRef?: (ref: ?React.ElementRef<any>) => void, formData: FormData, }; /** * `Field` component. * * Used to connect any form field to the form data generated by the Form component. * * The prop `component` can be a Component, a stateless function component, or * a string for DOM form fields (`input`, `select`). This is the component that will * be rendered. */ export class Field extends React.Component<FieldProps> { static defaultProps = { component: 'input', handleRef: null, }; /** * Return a field value from a SyntheticEvent or a value */ getValue = (eventOrValue: SyntheticEvent<HTMLInputElement>) => { if (!isObject(eventOrValue)) return eventOrValue; const target = eventOrValue.currentTarget; if (target) { const type = { target }; if (type === 'checkbox') { return target.checked || ''; } return target.value; } return eventOrValue; }; getFieldData = () => { const { name, formData } = this.props; return formData.fields[name]; }; /** * Handle change from the underlying component */ handleChange = (eventOrValue: SyntheticEvent<HTMLInputElement> | mixed) => { const field = this.getFieldData(); if (field) { // $FlowFixMe const value = this.getValue(eventOrValue); field.onChange(value); } }; render() { const { component, name, handleRef, formData, ...otherProps } = this.props; const field = this.getFieldData(); // form-related props const customProps = { name, value: typeof field.value !== 'undefined' ? field.value : '', onChange: this.handleChange, onBlur: field.onBlur, ref: handleRef, }; // form-related props that might cause an "unknown prop" warnings const extraProps = { blurred: field.blurred, error: field.error, initialValue: field.initialValue, }; if (typeof component === 'string') { // don't pass extra props if component is a string, because // it can trigger "unknown prop" warnings return React.createElement(component, { ...otherProps, ...customProps }); } if (component) { return React.createElement(component, { ...otherProps, ...customProps, ...extraProps }); } return null; } } export default consumeContextBroadcast('formData')(Field);
mit
fabrikagency/auto_html
test/fixtures/schema.rb
316
ActiveRecord::Schema.define do create_table "articles", :force => true do |t| t.column "title", :string t.column "body", :text t.column "body_html", :text t.column "body_htmlized", :text t.column "created_at", :datetime t.column "updated_at", :datetime end end
mit
jeremykenedy/laravel_frozennode_cms
app/views/admin/elements/forms/login/login-form6.blade.php
2023
<style type="text/css"> body{ background: url(http://mymaplist.com/img/parallax/back.png); background-color: #444; background: url(http://mymaplist.com/img/parallax/pinlayer2.png),url(http://mymaplist.com/img/parallax/pinlayer1.png),url(http://mymaplist.com/img/parallax/back.png); } .vertical-offset-100{ padding-top:100px; } </style> <script src="http://mymaplist.com/js/vendor/TweenLite.min.js"></script> <!-- This is a very simple parallax effect achieved by simple CSS 3 multiple backgrounds, made by http://twitter.com/msurguy --> <script type="text/javascript"> $(document).ready(function(){ $(document).mousemove(function(e){ TweenLite.to($('body'), .5, { css: { backgroundPosition: ""+ parseInt(event.pageX/8) + "px "+parseInt(event.pageY/'12')+"px, "+parseInt(event.pageX/'15')+"px "+parseInt(event.pageY/'15')+"px, "+parseInt(event.pageX/'30')+"px "+parseInt(event.pageY/'30')+"px" } }); }); }); </script> <div class="container"> <div class="row vertical-offset-100"> <div class="col-md-4 col-md-offset-4"> <div class="panel panel-default"> <div class="panel-heading"> <h3 class="panel-title">Please sign in</h3> </div> <div class="panel-body"> <form accept-charset="UTF-8" role="form"> <fieldset> <div class="form-group"> <input class="form-control" placeholder="E-mail" name="email" type="text"> </div> <div class="form-group"> <input class="form-control" placeholder="Password" name="password" type="password" value=""> </div> <div class="checkbox"> <label> <input name="remember" type="checkbox" value="Remember Me"> Remember Me </label> </div> <input class="btn btn-lg btn-success btn-block" type="submit" value="Login"> </fieldset> </form> </div> </div> </div> </div> </div>
mit
musicmunky/publify-core
app/models/post_type.rb
368
# coding: utf-8 class PostType < ActiveRecord::Base validates :name, uniqueness: true validates :name, presence: true validate :name_is_not_read before_save :sanitize_title def name_is_not_read errors.add(:name, I18n.t('errors.article_type_already_exist')) if name == 'read' end def sanitize_title self.permalink = name.to_permalink end end
mit
okunishinishi/kurokawa
routes/validations/serverside.js
1790
/** * serverside validation * @param clientside * @param validations */ var tek = require('tek'), define = tek['meta']['define'], JobQueue = tek['JobQueue']; exports = module.exports = define({ init: function () { var s = this; s._asyncConforms = {}; }, attrAccessor: 'clientside'.split(','), properties: { asyncConform: function (propertyName, conform) { var s = this; s._asyncConforms[propertyName] = conform; return s; }, _asyncConforms: {}, _clientside: [], validate: function (values, callback) { var s = this, schema = s._clientside.clone(); var queue = new JobQueue; Object.keys(s._asyncConforms).forEach(function (propertyName) { var asyncConform = s._asyncConforms[propertyName]; if (!asyncConform) return; queue.push(function (next) { asyncConform.call(s, values[propertyName], function (valid, message) { var properties = schema.properties; if (message)properties[propertyName].message = message; properties[propertyName].conform = function () { return valid; } }); next(); }) }); queue.execute(function () { var result = schema.validate(values); callback && callback(result.valid, result.errors); }); } } }); exports.extend = function (clientside) { return define({ prototype: exports, properties: { _clientside: clientside } }); };
mit
KyleCe/MyTestApplication
app/src/main/java/com/ce/game/myapplication/view/ShowcasePinCode.java
3704
package com.ce.game.myapplication.view; import android.content.Context; import android.text.TextUtils; import android.util.AttributeSet; import android.widget.FrameLayout; import android.widget.ImageView; import com.ce.game.myapplication.R; import java.util.ArrayList; import java.util.List; /** * Created by KyleCe on 2016/8/10. * * @author: KyleCe */ public class ShowcasePinCode extends FrameLayout implements NumberButtonClickInterface { protected Context mContext; private final int DEFAULT_PIN_CODE_LEN = 4; private final int DEFAULT_BUTTON_NUMBER = 10; List<NumberKeyboardSingleButton> mButtonList; List<ImageView> mPinCodeRoundList; public ShowcasePinCode(Context context) { this(context, null); } public ShowcasePinCode(Context context, AttributeSet attrs) { this(context, attrs, 0); } public ShowcasePinCode(Context context, AttributeSet attrs, int defStyleAttr) { super(context, attrs, defStyleAttr); mContext = context; inflate(context, R.layout.first_anim_showcase_password_pin_code, this); init(); } protected void init() { mPinCodeRoundList = new ArrayList<>(DEFAULT_PIN_CODE_LEN); mPinCodeRoundList.add(0, (ImageView) findViewById(R.id.pin_image_0)); mPinCodeRoundList.add(1, (ImageView) findViewById(R.id.pin_image_1)); mPinCodeRoundList.add(2, (ImageView) findViewById(R.id.pin_image_2)); mPinCodeRoundList.add(3, (ImageView) findViewById(R.id.pin_image_3)); mButtonList = new ArrayList<>(DEFAULT_BUTTON_NUMBER); mButtonList.add(0, (NumberKeyboardSingleButton) findViewById(R.id.number_keyboard_0)); mButtonList.add(1, (NumberKeyboardSingleButton) findViewById(R.id.number_keyboard_1)); mButtonList.add(2, (NumberKeyboardSingleButton) findViewById(R.id.number_keyboard_2)); mButtonList.add(3, (NumberKeyboardSingleButton) findViewById(R.id.number_keyboard_3)); mButtonList.add(4, (NumberKeyboardSingleButton) findViewById(R.id.number_keyboard_4)); mButtonList.add(5, (NumberKeyboardSingleButton) findViewById(R.id.number_keyboard_5)); mButtonList.add(6, (NumberKeyboardSingleButton) findViewById(R.id.number_keyboard_6)); mButtonList.add(7, (NumberKeyboardSingleButton) findViewById(R.id.number_keyboard_7)); mButtonList.add(8, (NumberKeyboardSingleButton) findViewById(R.id.number_keyboard_8)); mButtonList.add(9, (NumberKeyboardSingleButton) findViewById(R.id.number_keyboard_9)); } int mLenCount = 0; @Override public void onNumberClick(String str) { if (TextUtils.isEmpty(str)) return; char[] chars = str.toCharArray(); int len = chars.length; if (len <= 0) return; int index; for (int i = 0; i < len; i++) { index = chars[i] - '0'; onNumberClick(index); } } @Override public void onNumberClick(int index) { if (index < 0 || index >= DEFAULT_BUTTON_NUMBER) return; mButtonList.get(index).callOnClick(); mLenCount++; refreshPinCodeRound(mLenCount); } @Override public void onHold() { } @Override public void onReset() { for (NumberKeyboardSingleButton b : mButtonList) b.onReset(); mLenCount = 0; refreshPinCodeRound(mLenCount); } private void refreshPinCodeRound(int len) { for (int i = 0; i < DEFAULT_PIN_CODE_LEN; i++) mPinCodeRoundList.get(i).setImageResource(i < len ? R.drawable.unlockscreen_icon_enter : R.drawable.unlockscreen_icon_noenter); } }
mit
Aney44/test_mgg
src/Rest/UsersBundle/Exception/InvalidFormException.php
372
<?php namespace Rest\UsersBundle\Exception; class InvalidFormException extends \RuntimeException { protected $form; public function __construct($message, $form = null) { parent::__construct($message); $this->form = $form; } /** * @return array|null */ public function getForm() { return $this->form; } }
mit
valentinivanov/swisstalk
code/Platform/Unity3d/DI/Prefabs/PrefabDIFactoryBuilderExtensions.cs
382
using System; using Swisstalk.DI; namespace Swisstalk.Platform.Unity3d.DI.Prefabs { public static class PrefabDIFactoryBuilderExtensions { public static DICollectionBuilder ForComponentInPrefab<T>(this PrefabDIFactoryBuilder builder, string prefabKey) { return builder.ForKey(new PrefabComponentKey(prefabKey, typeof(T))); } } }
mit
hajerk/jci.com
app/cache/dev/twig/52/d3/6a600aeabb8ad00d1e1b88c63584f53a88f126bdff0b8171f1037e420409.php
6444
<?php /* @WebProfiler/Profiler/toolbar_js.html.twig */ class __TwigTemplate_52d36a600aeabb8ad00d1e1b88c63584f53a88f126bdff0b8171f1037e420409 extends Twig_Template { public function __construct(Twig_Environment $env) { parent::__construct($env); $this->parent = false; $this->blocks = array( ); } protected function doDisplay(array $context, array $blocks = array()) { // line 1 echo "<div id=\"sfwdt"; echo twig_escape_filter($this->env, (isset($context["token"]) ? $context["token"] : $this->getContext($context, "token")), "html", null, true); echo "\" class=\"sf-toolbar\" style=\"display: none\"></div> "; // line 2 $this->env->loadTemplate("@WebProfiler/Profiler/base_js.html.twig")->display($context); // line 3 echo "<script>/*<![CDATA[*/ (function () { "; // line 5 if (("top" == (isset($context["position"]) ? $context["position"] : $this->getContext($context, "position")))) { // line 6 echo " var sfwdt = document.getElementById('sfwdt"; echo twig_escape_filter($this->env, (isset($context["token"]) ? $context["token"] : $this->getContext($context, "token")), "html", null, true); echo "'); document.body.insertBefore( document.body.removeChild(sfwdt), document.body.firstChild ); "; } // line 12 echo " Sfjs.load( 'sfwdt"; // line 14 echo twig_escape_filter($this->env, (isset($context["token"]) ? $context["token"] : $this->getContext($context, "token")), "html", null, true); echo "', '"; // line 15 echo twig_escape_filter($this->env, $this->env->getExtension('routing')->getPath("_wdt", array("token" => (isset($context["token"]) ? $context["token"] : $this->getContext($context, "token")))), "html", null, true); echo "', function(xhr, el) { el.style.display = -1 !== xhr.responseText.indexOf('sf-toolbarreset') ? 'block' : 'none'; if (el.style.display == 'none') { return; } if (Sfjs.getPreference('toolbar/displayState') == 'none') { document.getElementById('sfToolbarMainContent-"; // line 24 echo twig_escape_filter($this->env, (isset($context["token"]) ? $context["token"] : $this->getContext($context, "token")), "html", null, true); echo "').style.display = 'none'; document.getElementById('sfToolbarClearer-"; // line 25 echo twig_escape_filter($this->env, (isset($context["token"]) ? $context["token"] : $this->getContext($context, "token")), "html", null, true); echo "').style.display = 'none'; document.getElementById('sfMiniToolbar-"; // line 26 echo twig_escape_filter($this->env, (isset($context["token"]) ? $context["token"] : $this->getContext($context, "token")), "html", null, true); echo "').style.display = 'block'; } else { document.getElementById('sfToolbarMainContent-"; // line 28 echo twig_escape_filter($this->env, (isset($context["token"]) ? $context["token"] : $this->getContext($context, "token")), "html", null, true); echo "').style.display = 'block'; document.getElementById('sfToolbarClearer-"; // line 29 echo twig_escape_filter($this->env, (isset($context["token"]) ? $context["token"] : $this->getContext($context, "token")), "html", null, true); echo "').style.display = 'block'; document.getElementById('sfMiniToolbar-"; // line 30 echo twig_escape_filter($this->env, (isset($context["token"]) ? $context["token"] : $this->getContext($context, "token")), "html", null, true); echo "').style.display = 'none'; } Sfjs.renderAjaxRequests(); /* Handle toolbar-info position */ var toolbarBlocks = document.getElementsByClassName('sf-toolbar-block'); for (var i = 0; i < toolbarBlocks.length; i += 1) { toolbarBlocks[i].onmouseover = function () { var toolbarInfo = this.getElementsByClassName('sf-toolbar-info')[0]; var pageWidth = document.body.clientWidth; var elementWidth = toolbarInfo.offsetWidth; var leftValue = (elementWidth + this.offsetLeft) - pageWidth; var rightValue = (elementWidth + (pageWidth - this.offsetLeft)) - pageWidth; /* Reset right and left value, useful on window resize */ toolbarInfo.style.right = ''; toolbarInfo.style.left = ''; if (leftValue > 0 && rightValue > 0) { toolbarInfo.style.right = (rightValue * -1) + 'px'; } else if (leftValue < 0) { toolbarInfo.style.left = 0; } else { toolbarInfo.style.right = '-1px'; } }; } }, function(xhr) { if (xhr.status !== 0) { confirm('An error occurred while loading the web debug toolbar (' + xhr.status + ': ' + xhr.statusText + ').\\n\\nDo you want to open the profiler?') && (window.location = '"; // line 61 echo twig_escape_filter($this->env, $this->env->getExtension('routing')->getPath("_profiler", array("token" => (isset($context["token"]) ? $context["token"] : $this->getContext($context, "token")))), "html", null, true); echo "'); } }, {'maxTries': 5} ); })(); /*]]>*/</script> "; } public function getTemplateName() { return "@WebProfiler/Profiler/toolbar_js.html.twig"; } public function isTraitable() { return false; } public function getDebugInfo() { return array ( 117 => 61, 83 => 30, 79 => 29, 75 => 28, 70 => 26, 66 => 25, 62 => 24, 50 => 15, 46 => 14, 42 => 12, 32 => 6, 30 => 5, 26 => 3, 24 => 2, 19 => 1,); } }
mit
jollopre/mps
ui/src/components/customers/inputText.js
1254
import React, { Component } from 'react'; import PropTypes from 'prop-types'; import { debounce } from '../../utils/debounce'; export default class InputText extends Component { constructor(props) { super(props); this.onChangeHandler = this.onChangeHandler.bind(this); this.state = { value: this.props.value }; this.deferredChange = debounce(this.deferredChange.bind(this), 2000); } onChangeHandler(e) { const value = e.target.value; this.setState({ value }, this.deferredChange); } deferredChange() { const { onChange, id } = this.props; const { value } = this.state; onChange({ [id]: value }); } render() { const { label, id } = this.props; const { value } = this.state; return ( <div className="form-group"> <label htmlFor={id}> {label} </label> <input type="text" className="form-control" id={id} value={value} placeholder={label} onChange={this.onChangeHandler}></input> </div> ); } } InputText.propTypes = { label: PropTypes.string.isRequired, id: PropTypes.string.isRequired, value: PropTypes.string.isRequired, onChange: PropTypes.func.isRequired }
mit
dapplo/Dapplo.Log
src/Dapplo.Log/ILoggerConfiguration.cs
1336
// Copyright (c) Dapplo and contributors. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using System.ComponentModel; namespace Dapplo.Log { /// <summary> /// Interface for the LoggerConfiguration /// </summary> public interface ILoggerConfiguration { /// <summary> /// The LogLevels enum a logger uses /// </summary> [DefaultValue(LogLevels.Info)] LogLevels LogLevel { get; set; } /// <summary> /// Defines if the Source is written like d.l.LoggerTest (default) or Dapplo.Log.LoggerTest /// </summary> [DefaultValue(true)] bool UseShortSource { get; set; } /// <summary> /// Timestamp format which is used in the output, when outputting the LogInfo details /// </summary> [DefaultValue("yyyy-MM-dd HH:mm:ss.fff")] string DateTimeFormat { get; set; } /// <summary> /// Default line format for loggers which use the DefaultFormatter. /// The first argument is the LogInfo, the second the message + parameters formatted /// </summary> [DefaultValue("{0} - {1}")] string LogLineFormat { get; set; } } }
mit
trshafer/angular
packages/compiler-cli/src/ngcc/src/host/decorated_file.ts
588
/** * @license * Copyright Google Inc. All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.io/license */ import * as ts from 'typescript'; import {DecoratedClass} from './decorated_class'; /** * Information about a source file that contains decorated exported classes. */ export class DecoratedFile { /** * The decorated exported classes that have been found in the file. */ public decoratedClasses: DecoratedClass[] = []; constructor(public sourceFile: ts.SourceFile) {} }
mit
ExilantTechnologies/ExilityCore-5.0.0
data/com/exilant/exility/core/DataGroup.java
2008
/* ******************************************************************************************************* Copyright (c) 2015 EXILANT Technologies Private Limited Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. ******************************************************************************************************** */ package com.exilant.exility.core; import java.util.HashMap; /*** * represents a data group, which is an Exility design entity * */ public class DataGroup { /*** * name of the group, that has to be unique across the dictionary. All * elements within this group may have to be prefixed with this name + '_' * if project does not use uniqueNameAcrtossGroups */ String name; /*** * English label,in case this is to be rendered */ String label; /*** * documentation */ String businessDescription; /*** * documentation */ String technicalDescription; /*** * all data elements within this group */ HashMap<String, DataElement> elements = new HashMap<String, DataElement>(); }
mit
Jovtcho/JavaFundamentals
JavaOOP Advanced/Exam2017-05-12-Cresla/main/java/cresla/Main.java
912
package cresla; import cresla.core.ManagerImpl; import cresla.engine.Engine; import cresla.entities.IdentifiableImpl; import cresla.interfaces.*; import cresla.io.ConsoleInputReader; import cresla.io.ConsoleOutputWriter; import cresla.repository.ReactorRepository; import java.io.BufferedReader; import java.io.InputStreamReader; public class Main { public static void main(String[] args) { BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(System.in)); InputReader reader = new ConsoleInputReader(bufferedReader); OutputWriter writer = new ConsoleOutputWriter(); Identifiable identifiable = new IdentifiableImpl(); Repository reactorRepository = new ReactorRepository(); Manager manager = new ManagerImpl(identifiable, reactorRepository); Runnable engine = new Engine(reader, writer, manager); engine.run(); } }
mit
atomic-labs/mixpanel-cli
setup.py
511
#!/usr/bin/env python from setuptools import setup from pip.req import parse_requirements install_reqs = parse_requirements("REQUIREMENTS.txt") reqs = [str(ir.req) for ir in install_reqs] setup( name = "mixpanel-cli", version = "0.1.0", author = "Atomic Labs, LLC", author_email = "[email protected]", description = ("Command line tool for querying the Mixpanel API"), license = "MIT", url = "http://www.atomicmgmt.com", packages=["mixpanel_cli"], install_requires=reqs )
mit
mongodb/mongoid
spec/support/models/writer.rb
233
# frozen_string_literal: true class Writer include Mongoid::Document field :speed, type: Integer, default: 0 embedded_in :canvas def write; end end require "support/models/pdf_writer" require "support/models/html_writer"
mit
Airtnp/SuperNaiveCppLib
src/sn_TypeTraits/type_traits_addon.hpp
5699
#ifndef SN_TYPETRAITS_TYPE_TRAITS #define SN_TYPETRAITS_TYPE_TRAITS #include "../sn_CommonHeader.h" namespace sn_TypeTraits { template <bool v> struct bool_constant_dispatch { using type = std::true_type; }; template <> struct bool_constant_dispatch<false> { using type = std::false_type; }; template <bool v> using bcd_t = typename bool_constant_dispatch<v>::type; struct is_functor_impl { template <typename T> static std::true_type check(decltype(&T::operator())*); template <typename T> static std::false_type check(...); }; template <typename T> using is_functor = decltype(is_functor_impl::template check<T>(nullptr)); template <typename T, bool = std::is_function<std::remove_pointer_t<T>>::value || is_functor<T>::value> struct is_closure_impl {}; template <typename T> struct is_closure_impl<T, true> : std::true_type {}; template <typename T> struct is_closure_impl<T, false> : std::false_type {}; template <typename T> struct is_closure : is_closure_impl<std::decay_t<T>> {}; template <typename T> inline const T* addressofex(const T* t) { return t; } template <typename T> inline T* addressofex(T* t) { return t; } template <typename T> inline const T* addressofex(const T& t) { return std::addressof(t); } template <typename T> inline T* addressofex(T& t) { return std::addressof(t); } // This is just llvm (remember the dynamic_cast) template<typename T> char & is_polymorphic_impl( std::enable_if_t< sizeof( (T*) dynamic_cast<const volatile void*> (std::declval<T*>()) ) != 0, int> ); template<typename T> int &is_polymorphic_impl(...); template <class T> struct is_polymorphic : public std::integral_constant<bool, sizeof(is_polymorphic_impl<T>(0)) == 1> {}; template <typename T> struct is_class_or_union { template <typename U> static int check(void(U::*)(void)); static char check(...); static const bool value = sizeof(check<T>(0)) == sizeof(int); }; template<typename> struct is_decomposable : std::false_type {}; template<template<typename...> class _gOp, typename... _types> struct is_decomposable<_gOp<_types...>> : std::true_type {}; template <typename T, typename ... V> /* inline */ constexpr auto is_brace_constructible_(T*) -> decltype(T{std::declval<V>()...}, std::true_type{}) { return {}; } template <typename T, typename ... V> /* inline */ constexpr std::false_type is_brace_constructible_(...) { return {}; } template <typename T, typename ... V> /* inline */ constexpr auto is_brace_constructible() -> decltype(is_brace_constructible_<T, V...>(nullptr)) { return {}; } template <typename T, typename ... V> /* inline */ constexpr auto is_paren_constructible_(T*) -> decltype(T(std::declval<V>()...), std::true_type{}) { return {}; } template <typename T, typename ... V> /* inline */ constexpr std::false_type is_paren_constructible_(...) { return {}; } template <typename T, typename ... V> /* inline */ constexpr auto is_paren_constructible() -> decltype(is_paren_constructible_<T, V...>(nullptr)) { return {}; } // the ternary operator deduces its type as most specialized type common to both arguments template <typename ...Args> struct common_type {}; template <typename T> struct common_type<T> { using type = T; }; template <typename T, typename U> struct common_type<T, U> { using type = decltype(true ? std::declval<T>() : std::declval<U>()); }; template <typename T, typename U, typename ...Ts> struct common_type<T, U, Ts...> { using type = typename common_type<typename common_type<T, U>::type, Ts...>::type; }; template <typename ...Args> using common_type_t = typename common_type<Args...>::type; template <typename T, typename It> using is_iterator = bcd_t<std::is_same<T, std::decay_t<decltype(*std::declval<It>())>>::value>; namespace detail { template <typename B, typename D> struct Host { operator B*() const; operator D*() const; }; } // @ref: https://stackoverflow.com/questions/2910979/how-does-is-base-of-work // Complex overload resolution. Actually if B is base of D, 3/4 will cause same result for 1/2==2 // Another implementation // @ref: http://en.cppreference.com/w/cpp/types/is_base_of template <typename B, typename D> struct is_base_of { using Accept_t = int; using Reject_t = char; template <typename T> static Accept_t check(D*, T); static Reject_t check(B*, int); constexpr static const bool value = sizeof(check(detail::Host<B, D>{}, int{})) == sizeof(Accept_t); }; template <typename T> struct is_function : std::integral_constant<bool, !std::is_object<T>::value && // Or: std::is_const<T const> !std::is_void<T>::value && // libcxx: is_class || is_union || is_void || is_reference || is_nullptr_t !std::is_reference<T>::value > {}; template<class T> struct remove_cvref { typedef std::remove_cv_t<std::remove_reference_t<T>> type; }; template <class T> using remove_cvref_t = typename remove_cvref<T>::type; template <typename ...Args> struct all_same; template <typename T, typename U, typename ...Ts> struct all_same<T, U, Ts...> : std::conditional_t< std::is_same_v<T, U>, all_same<U, Ts...>, std::false_type > {}; template <typename T, typename U> struct all_same<T, U> : std::is_same<T, U> {}; template <typename ...Args> inline constexpr bool all_same_v = all_same<Args...>::value; } #endif
mit
my-zhang/courses
nwu-eecs-339-db/btree-lab/btree_ds.cc
7019
#include <new> #include <iostream> #include <assert.h> #include <string.h> #include "btree_ds.h" #include "buffercache.h" #include "btree.h" using namespace std; SIZE_T NodeMetadata::GetNumDataBytes() const { SIZE_T n=blocksize-sizeof(*this); return n; } SIZE_T NodeMetadata::GetNumSlotsAsInterior() const { return (GetNumDataBytes()-sizeof(SIZE_T))/(keysize+sizeof(SIZE_T)); // floor intended } SIZE_T NodeMetadata::GetNumSlotsAsLeaf() const { return (GetNumDataBytes()-sizeof(SIZE_T))/(keysize+valuesize); // floor intended } ostream & NodeMetadata::Print(ostream &os) const { os << "NodeMetaData(nodetype="<<(nodetype==BTREE_UNALLOCATED_BLOCK ? "UNALLOCATED_BLOCK" : nodetype==BTREE_SUPERBLOCK ? "SUPERBLOCK" : nodetype==BTREE_ROOT_NODE ? "ROOT_NODE" : nodetype==BTREE_INTERIOR_NODE ? "INTERIOR_NODE" : nodetype==BTREE_LEAF_NODE ? "LEAF_NODE" : "UNKNOWN_TYPE") << ", keysize="<<keysize<<", valuesize="<<valuesize<<", blocksize="<<blocksize << ", rootnode="<<rootnode<<", freelist="<<freelist<<", numkeys="<<numkeys<<")"; return os; } BTreeNode::BTreeNode() { info.nodetype=BTREE_UNALLOCATED_BLOCK; data=0; } BTreeNode::~BTreeNode() { if (data) { delete [] data; } data=0; info.nodetype=BTREE_UNALLOCATED_BLOCK; } BTreeNode::BTreeNode(int node_type, SIZE_T key_size, SIZE_T value_size, SIZE_T block_size) { info.nodetype=node_type; info.keysize=key_size; info.valuesize=value_size; info.blocksize=block_size; info.rootnode=0; info.freelist=0; info.numkeys=0; data=0; if (info.nodetype!=BTREE_UNALLOCATED_BLOCK && info.nodetype!=BTREE_SUPERBLOCK) { data = new char [info.GetNumDataBytes()]; memset(data,0,info.GetNumDataBytes()); } } BTreeNode::BTreeNode(const BTreeNode &rhs) { info.nodetype=rhs.info.nodetype; info.keysize=rhs.info.keysize; info.valuesize=rhs.info.valuesize; info.blocksize=rhs.info.blocksize; info.rootnode=rhs.info.rootnode; info.freelist=rhs.info.freelist; info.numkeys=rhs.info.numkeys; data=0; if (rhs.data) { data=new char [info.GetNumDataBytes()]; memcpy(data,rhs.data,info.GetNumDataBytes()); } } BTreeNode & BTreeNode::operator=(const BTreeNode &rhs) { return *(new (this) BTreeNode(rhs)); } ERROR_T BTreeNode::Serialize(BufferCache *b, const SIZE_T blocknum) const { assert((unsigned)info.blocksize==b->GetBlockSize()); Block block(sizeof(info)+info.GetNumDataBytes()); memcpy(block.data,&info,sizeof(info)); if (info.nodetype!=BTREE_UNALLOCATED_BLOCK && info.nodetype!=BTREE_SUPERBLOCK) { memcpy(block.data+sizeof(info),data,info.GetNumDataBytes()); } return b->WriteBlock(blocknum,block); } ERROR_T BTreeNode::Unserialize(BufferCache *b, const SIZE_T blocknum) { Block block; ERROR_T rc; rc=b->ReadBlock(blocknum,block); if (rc!=ERROR_NOERROR) { return rc; } memcpy(&info,block.data,sizeof(info)); if (data) { delete [] data; data=0; } assert(b->GetBlockSize()==(unsigned)info.blocksize); if (info.nodetype!=BTREE_UNALLOCATED_BLOCK && info.nodetype!=BTREE_SUPERBLOCK) { data = new char [info.GetNumDataBytes()]; memcpy(data,block.data+sizeof(info),info.GetNumDataBytes()); } return ERROR_NOERROR; } char * BTreeNode::ResolveKey(const SIZE_T offset) const { switch (info.nodetype) { case BTREE_INTERIOR_NODE: case BTREE_ROOT_NODE: assert(offset<info.numkeys); return data+sizeof(SIZE_T)+offset*(sizeof(SIZE_T)+info.keysize); break; case BTREE_LEAF_NODE: assert(offset<info.numkeys); return data+sizeof(SIZE_T)+offset*(info.keysize+info.valuesize); break; default: return 0; } } char * BTreeNode::ResolvePtr(const SIZE_T offset) const { switch (info.nodetype) { case BTREE_INTERIOR_NODE: case BTREE_ROOT_NODE: assert(offset<=info.numkeys); return data+offset*(sizeof(SIZE_T)+info.keysize); break; case BTREE_LEAF_NODE: assert(offset==0); return data; break; default: return 0; } } char * BTreeNode::ResolveVal(const SIZE_T offset) const { switch (info.nodetype) { case BTREE_LEAF_NODE: assert(offset<info.numkeys); return data+sizeof(SIZE_T)+offset*(info.keysize+info.valuesize)+info.keysize; break; default: return 0; } } char * BTreeNode::ResolveKeyVal(const SIZE_T offset) const { return ResolveKey(offset); } ERROR_T BTreeNode::GetKey(const SIZE_T offset, KEY_T &k) const { char *p=ResolveKey(offset); if (p==0) { return ERROR_NOMEM; } k.Resize(info.keysize,false); memcpy(k.data,p,info.keysize); return ERROR_NOERROR; } ERROR_T BTreeNode::GetPtr(const SIZE_T offset, SIZE_T &ptr) const { char *p=ResolvePtr(offset); if (p==0) { return ERROR_NOMEM; } memcpy(&ptr,p,sizeof(SIZE_T)); return ERROR_NOERROR; } ERROR_T BTreeNode::GetVal(const SIZE_T offset, VALUE_T &v) const { char *p=ResolveVal(offset); if (p==0) { return ERROR_NOMEM; } v.Resize(info.valuesize,false); memcpy(v.data,p,info.valuesize); return ERROR_NOERROR; } ERROR_T BTreeNode::GetKeyVal(const SIZE_T offset, KeyValuePair &p) const { ERROR_T rc= GetKey(offset,p.key); if (rc!=ERROR_NOERROR) { return rc; } else { return GetVal(offset,p.value); } } ERROR_T BTreeNode::SetKey(const SIZE_T offset, const KEY_T &k) { char *p=ResolveKey(offset); if (p==0) { return ERROR_NOMEM; } memcpy(p,k.data,info.keysize); return ERROR_NOERROR; } ERROR_T BTreeNode::SetPtr(const SIZE_T offset, const SIZE_T &ptr) { char *p=ResolvePtr(offset); if (p==0) { return ERROR_NOMEM; } memcpy(p,&ptr,sizeof(SIZE_T)); return ERROR_NOERROR; } ERROR_T BTreeNode::SetVal(const SIZE_T offset, const VALUE_T &v) { char *p=ResolveVal(offset); if (p==0) { return ERROR_NOMEM; } memcpy(p,v.data,info.valuesize); return ERROR_NOERROR; } ERROR_T BTreeNode::SetKeyVal(const SIZE_T offset, const KeyValuePair &p) { ERROR_T rc=SetKey(offset,p.key); if (rc!=ERROR_NOERROR) { return rc; } else { return SetVal(offset,p.value); } } ostream & BTreeNode::Print(ostream &os) const { os << "BTreeNode(info="<<info; if (info.nodetype!=BTREE_UNALLOCATED_BLOCK && info.nodetype!=BTREE_SUPERBLOCK) { os <<", "; if (info.nodetype==BTREE_INTERIOR_NODE || info.nodetype==BTREE_ROOT_NODE) { SIZE_T ptr; KEY_T key; os << "pointers_and_values=("; if (info.numkeys>0) { // ==0 implies an empty root node for (SIZE_T i=0;i<info.numkeys;i++) { GetPtr(i,ptr); os<<ptr<<", "; GetKey(i,key); os<<key<<", "; } GetPtr(info.numkeys,ptr); os <<ptr; } os << ")"; } if (info.nodetype==BTREE_LEAF_NODE) { KEY_T key; VALUE_T val; os << "keys_and_values=("; for (SIZE_T i=0;i<info.numkeys;i++) { if (i>0) { os<<", "; } GetKey(i,key); os<<key<<", "; GetVal(i,val); os<<val; } os <<")"; } } os <<")"; return os; }
mit
iguanatool/iguana
src/main/java/org/iguanatool/testobject/structure/ConnectedNode.java
1502
package org.iguanatool.testobject.structure; import java.io.Serializable; public class ConnectedNode implements Comparable<ConnectedNode>, Serializable { private static final long serialVersionUID = -4327291223748021793L; public CFGNode node; public Boolean edge; public ConnectedNode(CFGNode node) { this.node = node; this.edge = null; } public ConnectedNode(CFGNode node, boolean edge) { this.node = node; this.edge = edge; } public ConnectedNode(CFGNode node, Boolean edge) { this.node = node; this.edge = edge; } public ConnectedNode(CFGNode node, boolean edge, boolean hasEdge) { this.node = node; if (hasEdge) { this.edge = edge; } else { this.edge = null; } } public int compareTo(ConnectedNode connectedNode) { int nodeCompare = node.compareTo(connectedNode.node); if (nodeCompare == 0) { if (edge != null && connectedNode.edge != null) { return edge.compareTo(connectedNode.edge); } else if (edge == null) { return -1; } else if (connectedNode.edge == null) { return 1; } return 0; } else { return nodeCompare; } } public String toString() { String string = "CFGNode: " + node; if (edge != null) string += " edge:" + edge; return string; } }
mit
BenVuti/DataStructures
DataStructures/DataStructures/Properties/AssemblyInfo.cs
1399
using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; // General Information about an assembly is controlled through the following // set of attributes. Change these attribute values to modify the information // associated with an assembly. [assembly: AssemblyTitle("DataStructures")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("DataStructures")] [assembly: AssemblyCopyright("Copyright © 2017")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. [assembly: ComVisible(false)] // The following GUID is for the ID of the typelib if this project is exposed to COM [assembly: Guid("f1359677-1a95-4d30-bcb7-dad2315673a5")] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Build and Revision Numbers // by using the '*' as shown below: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("1.0.0.0")] [assembly: AssemblyFileVersion("1.0.0.0")]
mit
budgetinsight/budgea-clients
BudgeaAPI.php
12835
<?php /* * MIT License * * Copyright (c) 2014-2020 Budget Insight * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ namespace Budgea; /** * Class Client * v 2.1.0 - 2019-12-01 * @package Budgea */ class Client { protected $settings; protected $access_token; protected $access_token_type = 'Bearer'; protected $access_token_param_name = 'token'; public function __construct($domain, $settings = []) { $this->settings = [ 'base_url' => 'https://' . $domain . '/2.0', 'endpoints' => [ 'authorization' => '/auth/share/', 'token' => '/auth/token/access', 'code' => '/auth/token/code' ], 'client_id' => NULL, 'client_secret' => NULL, 'http_headers' => [], ]; $this->settings = array_merge($this->settings, $settings); if (isset($settings['webview']) && $settings['webview'] == 'v2'): $this->settings['endpoints']['connect'] = '/auth/webview/connect/'; $this->settings['endpoints']['manage'] = '/auth/webview/manage'; $this->settings['endpoints']['transfer'] = '/auth/webview/transfer'; endif; } /** * @param $client_id */ public function setClientId($client_id) { $this->settings['client_id'] = $client_id; } /** * @param $client_secret */ public function setClientSecret($client_secret) { $this->settings['client_secret'] = $client_secret; } /** * @param $token */ public function setAccessToken($token) { $this->access_token = $token; } /** * @return mixed */ public function getAccessToken() { return $this->access_token; } /** * @param $resource_url * @param array $params * @return array * @throws AuthRequired * @throws InvalidAccessTokenType */ public function get($resource_url, $params = []) { return $this->fetch($resource_url, $params); } /** * @param $url * @return string */ public function absurl($url) { $url = $url[0] == '/' ? $this->settings['base_url'] . $url : $url; return $url; } /** * @param null $state * @return bool * @throws AuthFailed * @throws ConnectionError * @throws StateInvalid */ public function handleCallback($state = NULL) { if (isset($_GET['error'])) throw new AuthFailed($_GET['error']); if (!isset($_GET['code'])) return FALSE; if ($state !== NULL && (!isset($_GET['state']) || $_GET['state'] != $state)) throw new StateInvalid(); $params = ['code' => $_GET['code'], 'client_id' => $this->settings['client_id'], 'client_secret' => $this->settings['client_secret']]; if (isset($this->settings['redirect_uri'])) $params['redirect_uri'] = $this->settings['redirect_uri']; $http_headers = []; $response = $this->executeRequest($this->settings['endpoints']['token'], $params, 'POST', $http_headers); if (isset($response['result']['error'])) throw new AuthFailed($response['result']['error']); $this->access_token = $response['result']['access_token']; $this->acess_token_type = strtolower($response['result']['token_type']); return $state || TRUE; } /** * @param string $text * @param string $state * @return string */ public function getConnectButton($text, $state = '') { $button = ' <a href="' . $this->getConnectUrl($state) . '" style="display: inline-block; background: #ff6100; padding: 8px 16px; border-radius: 4px; color: white; text-decoration: none; font: 12pt/14pt \'Roboto\', sans-serif"> ' . htmlentities($text) . ' </a>'; return $button; } /** * Compatibility alias for getConnectButton() */ public function getAuthenticationButton($text = 'Partager ses comptes', $state = '') { return $this->getConnectButton($text, $state); } /** * @param string $text * @param string $state * @return string */ public function getManageButton($text, $state = '') { $button = ' <a href="' . htmlentities($this->getManageUrl($state)) . '" style="display: inline-block; background: #ff6100; padding: 8px 16px; border-radius: 4px; color: white; text-decoration: none; font: 12pt/14pt \'Roboto\', sans-serif"> ' . htmlentities($text) . ' </a>'; return $button; } /** * Compatibility alias for getManageButton() */ public function getSettingsButton($text = 'Modifier ses comptes', $state = '') { return $this->getManageButton($text, $state); } /** * @param string $state * @param string $connectorCapabilities * @return string */ public function getConnectUrl($state = '', $connectorCapabilities = 'bank') { $params = [ 'response_type' => 'code', 'client_id' => $this->settings['client_id'], 'state' => $state, 'connector_capabilities' => $connectorCapabilities, ]; !isset($this->settings['redirect_uri']) ?: $params['redirect_uri'] = $this->settings['redirect_uri']; return $this->absurl($this->settings['endpoints']['connect'] . '?' . http_build_query($params, NULL, '&')); } /** * Compatibility alias for getConnectUrl() */ public function getAuthenticationUrl($state = '', $connectorCapabilities = 'bank') { return $this->getConnectUrl($state, $connectorCapabilities); } /** * @param string $state * @return string * @throws AuthRequired * @throws InvalidAccessTokenType */ public function getManageUrl($state = '') { $response = $this->fetch($this->settings['endpoints']['code']); $params = [ 'response_type' => 'code', 'client_id' => $this->settings['client_id'], 'state' => $state ]; !isset($this->settings['redirect_uri']) ?: $params['redirect_uri'] = $this->settings['redirect_uri']; if (isset($this->settings['endpoints']['manage']) && $this->settings['endpoints']['manage'] != NULL): return $this->absurl($this->settings['endpoints']['manage'] . '?' . http_build_query($params, NULL, '&') . '#' . $response['code']); else: return $this->absurl($this->settings['endpoints']['connect'] . '?' . http_build_query($params, NULL, '&') . '#' . $response['code']); endif; } /** * Compatibility alias for getManageUrl() */ public function getSettingsUrl($state = '') { return $this->getManageUrl($state); } /** * @param string $state * @return string * @throws AuthRequired * @throws InvalidAccessTokenType */ public function getTransferUrl($state = '') { $response = $this->fetch($this->settings['endpoints']['code']); $params = [ 'state' => $state ]; !isset($this->settings['transfer_redirect_uri']) ?: $params['redirect_uri'] = $this->settings['transfer_redirect_uri']; return $this->absurl($this->settings['endpoints']['transfer'] . '?' . http_build_query($params, NULL, '&') . '#' . $response['code']); } /** * Compatibility alias for getTransferUrl() */ public function getTransfersUrl($state = '') { return $this->getTransferUrl($state); } /** * @param string $expand * @return mixed */ public function getAccounts($expand = '') { $expandArray = !empty($expand) ? ['expand' => $expand] : []; $res = $this->get('/users/me/accounts', $expandArray); return $res['accounts']; } /** * @param string $account_id * @return mixed */ public function getTransactions($account_id = '') { if ($account_id) $res = $this->get('/users/me/accounts/' . $account_id . '/transactions', ['expand' => 'category']); else $res = $this->get('/users/me/transactions', ['expand' => 'category']); return $res['transactions']; } /** * @param $protected_resource_url * @param array $params * @param string $http_method * @param array $http_headers * @return array * @throws AuthRequired * @throws ConnectionError * @throws InvalidAccessTokenType */ public function fetch($protected_resource_url, $params = [], $http_method = 'GET', $http_headers = []) { $http_headers = array_merge($this->settings['http_headers'], $http_headers); $protected_resource_url = $this->absurl($protected_resource_url); if ($this->access_token): switch ($this->access_token_type): case 'url': if (is_array($params)) $params[$this->access_token_param_name] = $this->access_token; else throw new RequireParamsAsArray('You need to give parameters as array if you want to give the token within the URI.'); break; case 'Bearer': $http_headers['Authorization'] = 'Bearer ' . $this->access_token; break; case 'oauth': $http_headers['Authorization'] = 'OAuth ' . $this->access_token; default: throw new InvalidAccessTokenType(); break; endswitch; endif; $r = $this->executeRequest($protected_resource_url, $params, $http_method, $http_headers); switch ($r['code']): case 200: return $r['result']; break; case 401: case 403: throw new AuthRequired(); break; endswitch; return $r; } /** * @param $url * @param array $params * @param string $http_method * @param array $http_headers * @return array * @throws ConnectionError */ private function executeRequest($url, $params = [], $http_method = 'GET', array $http_headers = []) { $curl_options = [ CURLOPT_RETURNTRANSFER => true, CURLOPT_SSL_VERIFYPEER => true, CURLOPT_CUSTOMREQUEST => $http_method ]; $url = $this->absurl($url); switch ($http_method): case 'POST': $curl_options[CURLOPT_POST] = TRUE; case 'PUT': case 'PATCH': /** * Passing an array to CURLOPT_POSTFIELDS will encode the data as multipart/form-data, * while passing a URL-encoded string will encode the data as application/x-www-form-urlencoded. * http://php.net/manual/en/function.curl-setopt.php */ if (is_array($params)) $params = http_build_query($params, NULL, '&'); $curl_options[CURLOPT_POSTFIELDS] = $params; break; case 'HEAD': $curl_options[CURLOPT_NOBODY] = TRUE; case 'DELETE': case 'GET': !$params ?: $url .= '?' . (is_array($params) ? http_build_query($params, NULL, '&') : $params); default: break; endswitch; $curl_options[CURLOPT_URL] = $url; if (is_array($http_headers)) { $header = []; foreach ($http_headers as $key => $value) $header[] = "$key: $value"; $curl_options[CURLOPT_HTTPHEADER] = $header; } $ch = curl_init(); curl_setopt_array($ch, $curl_options); curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, TRUE); curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 2); $result = curl_exec($ch); $http_code = curl_getinfo($ch, CURLINFO_HTTP_CODE); $content_type = curl_getinfo($ch, CURLINFO_CONTENT_TYPE); if ($curl_error = curl_error($ch)) throw new ConnectionError($curl_error); else $decode = json_decode($result, TRUE); curl_close($ch); return [ 'result' => (NULL == $decode) ? $result : $decode, 'code' => $http_code, 'content_type' => $content_type, ]; } } class Exception extends \Exception { } class ConnectionError extends Exception { } class InvalidAccessTokenType extends Exception { } class NoPermission extends Exception { } class AuthRequired extends Exception { } class AuthFailed extends Exception { } class StateInvalid extends Exception { } class RequireParamsAsArray extends \InvalidArgumentException { } ?>
mit
MatthijsKamstra/haxejava
04lwjgl/code/lwjgl/org/lwjgl/opengles/OESVertexArrayObject.java
4104
/* * Copyright LWJGL. All rights reserved. * License terms: http://lwjgl.org/license.php * MACHINE GENERATED FILE, DO NOT EDIT */ package org.lwjgl.opengles; import java.nio.*; import org.lwjgl.system.*; import static org.lwjgl.system.Checks.*; import static org.lwjgl.system.JNI.*; import static org.lwjgl.system.MemoryStack.*; import static org.lwjgl.system.MemoryUtil.*; /** * Native bindings to the <a href="https://www.khronos.org/registry/gles/extensions/OES/OES_vertex_array_object.txt">OES_vertex_array_object</a> extension. * * <p>This extension introduces vertex array objects which encapsulate vertex array states on the server side (vertex buffer objects). These objects aim to * keep pointers to vertex data and to provide names for different sets of vertex data. Therefore applications are allowed to rapidly switch between * different sets of vertex array state, and to easily return to the default vertex array state.</p> */ public class OESVertexArrayObject { /** Accepted by the {@code pname} parameter of GetBooleanv, GetIntegerv, GetFloatv. */ public static final int GL_VERTEX_ARRAY_BINDING_OES = 0x85B5; protected OESVertexArrayObject() { throw new UnsupportedOperationException(); } static boolean isAvailable(GLESCapabilities caps) { return checkFunctions( caps.glBindVertexArrayOES, caps.glDeleteVertexArraysOES, caps.glGenVertexArraysOES, caps.glIsVertexArrayOES ); } // --- [ glBindVertexArrayOES ] --- public static void glBindVertexArrayOES(int array) { long __functionAddress = GLES.getCapabilities().glBindVertexArrayOES; if ( CHECKS ) checkFunctionAddress(__functionAddress); callV(__functionAddress, array); } // --- [ glDeleteVertexArraysOES ] --- public static void nglDeleteVertexArraysOES(int n, long arrays) { long __functionAddress = GLES.getCapabilities().glDeleteVertexArraysOES; if ( CHECKS ) checkFunctionAddress(__functionAddress); callPV(__functionAddress, n, arrays); } public static void glDeleteVertexArraysOES(IntBuffer arrays) { nglDeleteVertexArraysOES(arrays.remaining(), memAddress(arrays)); } public static void glDeleteVertexArraysOES(int array) { MemoryStack stack = stackGet(); int stackPointer = stack.getPointer(); try { IntBuffer arrays = stack.ints(array); nglDeleteVertexArraysOES(1, memAddress(arrays)); } finally { stack.setPointer(stackPointer); } } // --- [ glGenVertexArraysOES ] --- public static void nglGenVertexArraysOES(int n, long arrays) { long __functionAddress = GLES.getCapabilities().glGenVertexArraysOES; if ( CHECKS ) checkFunctionAddress(__functionAddress); callPV(__functionAddress, n, arrays); } public static void glGenVertexArraysOES(IntBuffer arrays) { if ( CHECKS ) checkBuffer(arrays, 1); nglGenVertexArraysOES(arrays.remaining(), memAddress(arrays)); } public static int glGenVertexArraysOES() { MemoryStack stack = stackGet(); int stackPointer = stack.getPointer(); try { IntBuffer arrays = stack.callocInt(1); nglGenVertexArraysOES(1, memAddress(arrays)); return arrays.get(0); } finally { stack.setPointer(stackPointer); } } // --- [ glIsVertexArrayOES ] --- public static boolean glIsVertexArrayOES(int array) { long __functionAddress = GLES.getCapabilities().glIsVertexArrayOES; if ( CHECKS ) checkFunctionAddress(__functionAddress); return callZ(__functionAddress, array); } /** Array version of: {@link #glDeleteVertexArraysOES DeleteVertexArraysOES} */ public static void glDeleteVertexArraysOES(int[] arrays) { long __functionAddress = GLES.getCapabilities().glDeleteVertexArraysOES; if ( CHECKS ) checkFunctionAddress(__functionAddress); callPV(__functionAddress, arrays.length, arrays); } /** Array version of: {@link #glGenVertexArraysOES GenVertexArraysOES} */ public static void glGenVertexArraysOES(int[] arrays) { long __functionAddress = GLES.getCapabilities().glGenVertexArraysOES; if ( CHECKS ) { checkFunctionAddress(__functionAddress); checkBuffer(arrays, 1); } callPV(__functionAddress, arrays.length, arrays); } }
mit
RainerAtSpirit/hapi-plugin-djStatic
lib/index.js
281
exports.register = function( plugin, options, next ) { plugin.expose('path', plugin.path); plugin.route({ method: 'GET', path: '/{path*}', handler: { directory: { path: './public' } } }); next(); };
mit
leonardo2204/Flow1.0.0-alphaExample
app/src/main/java/leonardo2204/com/br/flowtests/presenter/NavigationPresenter.java
358
package leonardo2204.com.br.flowtests.presenter; import android.support.design.widget.NavigationView; import android.view.Menu; import mortar.ViewPresenter; /** * Created by Leonardo on 18/03/2016. */ public class NavigationPresenter extends ViewPresenter<NavigationView> { public Menu setupMenuItem() { return getView().getMenu(); } }
mit
nailsapp/common
src/Common/Traits/Model/Nestable.php
9796
<?php namespace Nails\Common\Traits\Model; use Nails\Common\Service\Database; use Nails\Common\Resource; use Nails\Factory; /** * Trait Nestable * * @package Nails\Common\Traits\Model */ trait Nestable { /** * Returns the column name for specific columns of interest * * @param string $sColumn The column to query * @param string|null $sDefault The default value if not defined * * @return string */ abstract public function getColumn($sColumn, $sDefault = null); // -------------------------------------------------------------------------- /** * Returns protected property $table * * @param bool $bIncludePrefix Whether to include the table's alias * * @return string */ abstract public function getTableName($bIncludePrefix = false); // -------------------------------------------------------------------------- /** * Fetch an object by it's ID * * @param int $iId The ID of the object to fetch * @param mixed $aData Any data to pass to getCountCommon() * * @return Resource|false */ abstract public function getById($iId, array $aData = []); // -------------------------------------------------------------------------- /** * Returns the column to save breadcrumbs * * @return string */ public function getBreadcrumbsColumn() { return $this->getColumn('breadcrumbs', 'breadcrumbs'); } // -------------------------------------------------------------------------- /** * Returns the column to save the hierarchy * * @return string */ public function getOrderColumn() { return $this->getColumn('order', 'order'); } // -------------------------------------------------------------------------- /** * Returns the column to save the parent ID * * @return string */ public function getParentIdColumn() { return $this->getColumn('parentId', 'parent_id'); } // -------------------------------------------------------------------------- /** * Generates breadcrumbs after creating an object * * @param array $aData Data to create the item with * @param bool $bReturnObject Whether to return an object or not * * @return mixed */ public function create(array $aData = [], $bReturnObject = false) { $mResult = parent::create($aData, $bReturnObject); if ($mResult) { $this->saveBreadcrumbs($bReturnObject ? $mResult->id : $mResult); $this->saveOrder(); // Refresh object to get updated breadcrumbs/URL if ($bReturnObject) { $mResult = $this->getById($mResult->id); } } return $mResult; } // -------------------------------------------------------------------------- /** * Generates breadcrumbs after updating an object * * @param array|integer $mIds The ID(s) to update * @param array $aData Data to update the items with¬ * * @return mixed */ public function update($mIds, array $aData = []): bool { $mResult = parent::update($mIds, $aData); if ($mResult) { $aIds = (array) $mIds; foreach ($aIds as $iId) { $this->saveBreadcrumbs($iId); } $this->saveOrder(); } return $mResult; } // -------------------------------------------------------------------------- /** * Generates breadcrumbs for the item * * @param integer $iItemId The item's ID */ protected function saveBreadcrumbs($iItemId) { // @todo (Pablo - 2018-07-01) - protect against infinite loops $oItem = $this->getById($iItemId); if (!empty($oItem)) { $aBreadcrumbs = []; $iParentId = (int) $oItem->parent_id; while ($iParentId) { $oParentItem = $this->getById($iParentId); if ($oParentItem) { $iParentId = $oParentItem->parent_id; array_unshift( $aBreadcrumbs, (object) array_filter([ 'id' => $oParentItem->id, 'label' => !empty($oParentItem->label) ? $oParentItem->label : null, 'slug' => !empty($oParentItem->slug) ? $oParentItem->slug : null, 'url' => !empty($oParentItem->url) ? $oParentItem->url : null, ]) ); } else { $iParentId = null; } } // Save breadcrumbs to the current item parent::update( $iItemId, [ $this->getBreadcrumbsColumn() => json_encode($aBreadcrumbs), ] ); // Save breadcrumbs of all children $oDb = Factory::service('Database'); $oDb->where('parent_id', $iItemId); $aChildren = $oDb->get($this->getTableName())->result(); foreach ($aChildren as $oItem) { $this->saveBreadcrumbs($oItem->id); } } } // -------------------------------------------------------------------------- protected function saveOrder() { /** * If the model also uses the Sortable trait then let that handle sorting */ if (!classUses($this, Sortable::class)) { /** @var Database $oDb */ $oDb = Factory::service('Database'); $oDb->select([ $this->getColumn('id'), $this->getColumn('parent_id', 'parent_id'), ]); if (!$this->isDestructiveDelete()) { $oDb->where($this->getColumn('deleted'), false); } $oDb->order_by($this->getColumn('label')); $aItems = $oDb->get($this->getTableName())->result(); $iIndex = 0; $aItems = $this->flattenTree( $this->buildTree($aItems) ); foreach ($aItems as $oItem) { $oDb->set($this->getOrderColumn(), ++$iIndex); $oDb->where($this->getColumn('id'), $oItem->id); $oDb->update($this->getTableName()); } } } // -------------------------------------------------------------------------- /** * Builds a tree of objects * * This will only return complete trees beginning with the supplied $iParentId * * @param array $aItems The items to sort * @param int $iParentId The parent ID to sort on * * @return array * @todo (Pablo - 2019-05-10) - Support building partial trees */ public function buildTree(array $aItems, int $iParentId = null): array { $aTemp = []; $sIdColumn = $this->getColumn('id'); $sParentColumn = $this->getColumn('parent_id', 'parent_id'); foreach ($aItems as $oItem) { if ($oItem->{$sParentColumn} == $iParentId) { $oItem->children = $this->buildTree($aItems, $oItem->{$sIdColumn}); $aTemp[] = $oItem; } } return $aTemp; } // -------------------------------------------------------------------------- /** * Flattens a tree of objects * * @param array $aItems The items to flatten * @param array $aOutput The array to write to * * @return array */ public function flattenTree(array $aItems, &$aOutput = []): array { foreach ($aItems as $oItem) { $aOutput[] = $oItem; $this->flattenTree($oItem->children, $aOutput); unset($oItem->children); } return $aOutput; } // -------------------------------------------------------------------------- /** * Generates the URL for nestable objects; optionally place under a URL namespace * * @param Resource $oObj The object to generate the URL for * * @return string|null */ public function generateUrl(Resource $oObj) { if (empty($oObj->breadcrumbs)) { return null; } $aBreadcrumbs = json_decode($oObj->breadcrumbs); if (is_null($aBreadcrumbs)) { return null; } $aUrl = arrayExtractProperty($aBreadcrumbs, 'slug'); $aUrl[] = $oObj->slug; $sUrl = implode('/', $aUrl); $sNamespace = defined('static::NESTED_URL_NAMESPACE') ? addTrailingSlash(static::NESTED_URL_NAMESPACE) : ''; return $sNamespace . $sUrl; } // -------------------------------------------------------------------------- /** * Retrieves the immediate children of an item * * @param integer $iId The ID of the item * @param bool $bRecursive Whetehr to recursively fetch children * @param array $aData Any additional data to pass to the `getAll()` method * * @return mixed */ public function getChildren($iId, $bRecursive = false, array $aData = []) { $aQueryData = $aData; if (!array_key_exists('where', $aQueryData)) { $aQueryData['where'] = []; } $aQueryData['where'][] = ['parent_id', $iId]; $aChildren = $this->getAll($aQueryData); foreach ($aChildren as $oChild) { if ($bRecursive) { $oChild->children = $this->getChildren($oChild->id, $bRecursive, $aData); } } return $aChildren; } }
mit
apergy/imify
client/apps/message/views/Messages.js
419
'use strict'; var Marionette = require('backbone.marionette'); module.exports = Marionette.CollectionView.extend({ /** * @type {String} */ className: 'messages', /** * @type {Marionette.ItemView} */ childView: require('./Message'), /** * Scrolls the container to the latest message */ onAddChild: function () { this.$el.parent().animate({ scrollTop: this.$el.height() }); }, });
mit
wtgtybhertgeghgtwtg/redux-modules
flow-typed/npm/prettier_vx.x.x.js
2138
// flow-typed signature: 2accf0e2123c0f379379269c7bb9a463 // flow-typed version: <<STUB>>/prettier_v^1.7.3/flow_v0.55.0 /** * This is an autogenerated libdef stub for: * * 'prettier' * * Fill this stub out by replacing all the `any` types. * * Once filled out, we encourage you to share your work with the * community by sending a pull request to: * https://github.com/flowtype/flow-typed */ declare module 'prettier' { declare module.exports: any; } /** * We include stubs for each file inside this npm package in case you need to * require those files directly. Feel free to delete any files that aren't * needed. */ declare module 'prettier/bin/prettier' { declare module.exports: any; } declare module 'prettier/parser-babylon' { declare module.exports: any; } declare module 'prettier/parser-flow' { declare module.exports: any; } declare module 'prettier/parser-graphql' { declare module.exports: any; } declare module 'prettier/parser-parse5' { declare module.exports: any; } declare module 'prettier/parser-postcss' { declare module.exports: any; } declare module 'prettier/parser-typescript' { declare module.exports: any; } // Filename aliases declare module 'prettier/bin/prettier.js' { declare module.exports: $Exports<'prettier/bin/prettier'>; } declare module 'prettier/index' { declare module.exports: $Exports<'prettier'>; } declare module 'prettier/index.js' { declare module.exports: $Exports<'prettier'>; } declare module 'prettier/parser-babylon.js' { declare module.exports: $Exports<'prettier/parser-babylon'>; } declare module 'prettier/parser-flow.js' { declare module.exports: $Exports<'prettier/parser-flow'>; } declare module 'prettier/parser-graphql.js' { declare module.exports: $Exports<'prettier/parser-graphql'>; } declare module 'prettier/parser-parse5.js' { declare module.exports: $Exports<'prettier/parser-parse5'>; } declare module 'prettier/parser-postcss.js' { declare module.exports: $Exports<'prettier/parser-postcss'>; } declare module 'prettier/parser-typescript.js' { declare module.exports: $Exports<'prettier/parser-typescript'>; }
mit
rahavMatan/react-phonecat
src/reducers/index.js
243
import { combineReducers } from 'redux'; import listReducer from './list-reducer'; import phoneReducer from './phone-reducer'; const rootReducer = combineReducers({ filtered:listReducer, phone:phoneReducer }); export default rootReducer;
mit
kiswanij/jk-util
src/main/java/com/jk/util/validation/builtin/SplitStringValidator.java
2102
/* * Copyright 2002-2018 Jalal Kiswani. * E-mail: [email protected] * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.jk.util.validation.builtin; import com.jk.util.validation.Problems; import com.jk.util.validation.Validator; // TODO: Auto-generated Javadoc /** * A validator of strings that first splits the string in question using the * passed regular expression, and then runs another validator over each * component string. * * @author Tim Boudreau */ final class SplitStringValidator implements Validator<String> { /** The regexp. */ private final String regexp; /** The other. */ private final Validator<String> other; /** * Instantiates a new split string validator. * * @param regexp the regexp * @param other the other */ public SplitStringValidator(final String regexp, final Validator<String> other) { this.regexp = regexp; this.other = other; } /* * (non-Javadoc) * * @see java.lang.Object#toString() */ @Override public String toString() { return "SplitStringValidator for " + this.other; // NOI18N } /* * (non-Javadoc) * * @see * com.fs.commons.desktop.validation.Validator#validate(com.fs.commons.desktop. * validation.Problems, java.lang.String, java.lang.Object) */ @Override public boolean validate(final Problems problems, final String compName, final String model) { final String[] components = model.split(this.regexp); boolean result = true; for (final String component : components) { result &= this.other.validate(problems, compName, component); } return result; } }
mit
christianwade/BismNormalizer
BismNormalizer/TabularCompare/UI/SynchronizedScrollRichTextBox.cs
1267
using System; using System.Windows.Forms; namespace BismNormalizer.TabularCompare.UI { public class SynchronizedScrollRichTextBox : RichTextBox { [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1009:DeclareEventHandlersCorrectly")] public event vScrollEventHandler vScroll; public delegate void vScrollEventHandler(Message message); public const int WM_VSCROLL = 0x115; public const int WM_HSCROLL = 0x114; public const int WM_MOUSEWHEEL = 0x020A; //public const int WM_COMMAND = 0x111; //public const int WM_KEYUP = 0x0101; //List of windows message codes: https://www.autoitscript.com/autoit3/docs/appendix/WinMsgCodes.htm protected override void WndProc(ref Message message) { if (message.Msg == WM_VSCROLL || message.Msg == WM_HSCROLL || message.Msg == WM_MOUSEWHEEL ) { if (vScroll != null) { vScroll(message); } } base.WndProc(ref message); } public void PubWndProc(ref Message message) { base.WndProc(ref message); } } }
mit
Javier-Solis/admin-project
app/Validation/Exceptions/SubdivisionCode/CySubdivisionCodeException.php
812
<?php /* * This file is part of App/Validation. * * (c) Alexandre Gomes Gaigalas <[email protected]> * * For the full copyright and license information, please view the "LICENSE.md" * file that was distributed with this source code. */ namespace App\Validation\Exceptions\SubdivisionCode; use App\Validation\Exceptions\SubdivisionCodeException; /** * Exception class for Cyprus subdivision code. * * ISO 3166-1 alpha-2: CY */ class CySubdivisionCodeException extends SubdivisionCodeException { public static $defaultTemplates = [ self::MODE_DEFAULT => [ self::STANDARD => '{{name}} must be a subdivision code of Cyprus', ], self::MODE_NEGATIVE => [ self::STANDARD => '{{name}} must not be a subdivision code of Cyprus', ], ]; }
mit
adewynter/Tools
Algorithms/dataStructures/suffixTree.py
1637
# Implementation of a suffix tree # Adrian deWynter, 2017 class suffixTree(object): class Node(object): def __init__(self,label): self.label = label self.children = {} def __init__(self, s): s = s + "$" self.root = self.Node(None) self.root.children(s[0]) =self.Node(s) for i in xrange(1,len(s)): thisNode = self.root j = i while j < len(s): if s[j] in thisNode.children: child = thisNode.children[s[j]] label = child.label k = j + 1 while k - j < len(label) and s[k] == label[k - j]: k = k + 1 if k - j == len(label): thisNode = child j = k else: e,n = label[k-j],s[k] newNode = self.Node(label[:k-j]) newNode.children[n] = self.Node(s[k:]) newNode.children[e] = child child.label = label[k - j:] thisNode.children[s[j]] = newNode else: thisNode.children[s[j]] = self.Node(s[j:]) def traverse(self,s): thisNode = self.root i = 0 while i < len(s): c = s[i] if c not in thisNode.children: return (None,None) child = thisNode.children[s[i]] label = child.label j = j + 1 while j-i < len(label) and j < len(s) and s[j] == label[j-1]: j = j +1 if j - i == len(label): thisNode = child i = j elif j == len(s): return (child,j-i) else: return (None,None) return thisNode,None def hasSubstring(self,s): node, off = self.traverse(s) return node is not None def hasSuffix(self,s): node,off = self.traverse(s) if node is None: return False if off is None: return '$' in node.children return node.label[off] == "$"
mit
creynders/keystone
test/e2e/adminUI/tests/group002Home/uxTestHomeView.js
3468
module.exports = { before: function (browser) { browser.app = browser.page.app(); browser.signinScreen = browser.page.signin(); browser.homeScreen = browser.page.home(); browser.initialFormScreen = browser.page.initialForm(); browser.listScreen = browser.page.list(); browser.deleteConfirmationScreen = browser.page.deleteConfirmation(); browser.app .gotoHomeScreen() .waitForSigninScreen(); browser.signinScreen.signin(); browser.app.waitForHomeScreen(); }, after: function (browser) { browser.app.signout(); browser.end(); }, 'Home view should allow clicking a nav menu item such as Access and Fields to show the list of items': function (browser) { browser.app .gotoHomeScreen() .waitForHomeScreen() .click('@accessMenu') .waitForListScreen() .gotoHomeScreen() .waitForHomeScreen() .click('@fieldListsMenu') .waitForListScreen(); }, 'Home view should allow clicking a card list item such as Users to should show the list of those items': function (browser) { browser.app .gotoHomeScreen() .waitForHomeScreen(); browser.homeScreen.section.accessGroup.section.users .click('@label'); browser.app .waitForListScreen(); }, 'Home view should allow an admin to create a new list item such as a user': function (browser) { browser.app .gotoHomeScreen() .waitForHomeScreen(); browser.homeScreen.section.accessGroup.section.users .click('@plusIconLink'); browser.initialFormScreen.section.form .waitForElementVisible('@createButton'); }, 'Home view should allow an admin to create a new list item and increment the item count': function (browser) { browser.app .gotoHomeScreen() .waitForHomeScreen(); browser.homeScreen.section.fieldsGroup.section.names .expect.element('@itemCount').text.to.equal('0 Items'); browser.homeScreen.section.fieldsGroup.section.names .click('@plusIconLink'); browser.initialFormScreen.section.form .waitForElementVisible('@createButton'); browser.initialFormScreen.section.form.section.nameList.section.name .fillInput({value: 'Name Field Test'}); browser.initialFormScreen.section.form.section.nameList.section.fieldA .fillInput({firstName: 'First', lastName: 'Last'}); browser.initialFormScreen.section.form .click('@createButton'); browser.app .waitForItemScreen() .gotoHomeScreen() .waitForHomeScreen(); browser.homeScreen.section.fieldsGroup.section.names .expect.element('@itemCount').text.to.equal('1 Item'); }, 'Home view should be accessible from any other non-modal view by clicking the Home link': function (browser) { browser.app .gotoHomeScreen() .waitForHomeScreen(); browser.homeScreen.section.accessGroup.section.users .click('@label'); browser.app .waitForListScreen(); browser.app .click('@homeIconLink') .waitForHomeScreen(); }, // UNDO ANY STATE CHANGES -- THIS TEST SHOULD RUN LAST 'Home view ... undoing any state changes': function (browser) { // Delete the Name Field added browser.app .gotoHomeScreen() .waitForHomeScreen(); browser.app .click('@fieldListsMenu') .waitForListScreen(); browser.app .click('@nameListSubmenu') .waitForListScreen(); browser.listScreen .click('@singleItemDeleteIcon'); browser.deleteConfirmationScreen .waitForElementVisible('@deleteButton'); browser.deleteConfirmationScreen .click('@deleteButton'); browser.app.waitForListScreen(); }, };
mit
char-lie/react-vouchers
app/reducers/vouchersReducer.js
2218
import { ACTIONS } from '../actions'; const initialState = Object.freeze({ vouchers: [], }); const EDITABLE_KEYS = ['brand_name', 'cvv', 'notes', 'paper_voucher', 'seller', 'serial_number', 'status']; function replaceVoucher(vouchers, voucherIndex, vaucherPatch) { return voucherIndex === -1 || typeof voucherIndex !== 'number' ? vouchers : Object.assign([], vouchers, { [voucherIndex]: vaucherPatch }); } function isNotEditable(voucher, key) { return EDITABLE_KEYS.indexOf(key) === -1 || (voucher.paper_voucher && key === 'cvv') || (voucher.status !== null && key === 'status'); } function editVoucher(voucher, newValues) { const values = 'paper_voucher' in newValues && 'paper_voucher' in newValues ? Object.assign({}, newValues, { cvv: null }) : newValues; const acceptedNewValues = Object.keys(values) .reduce((acc, key) => (isNotEditable(voucher, key) ? acc : Object.assign(acc, { [key]: values[key] }) ), {}); return Object.assign({}, voucher, acceptedNewValues); } function editAndReplaceVoucher(vouchers, vaucherPatch) { const voucherIndex = vouchers.findIndex(voucher => voucher.id === vaucherPatch.id); return voucherIndex === -1 ? vouchers : replaceVoucher(vouchers, voucherIndex, editVoucher(vouchers[voucherIndex], vaucherPatch)); } export default (state = initialState, action) => { switch (action.type) { case `${ACTIONS.FETCH_VOUCHERS}_FULFILLED`: return Object.assign({}, state, { vouchers: action.payload, }); case `${ACTIONS.FETCH_VOUCHER}_FULFILLED`: return Object.assign({}, state, { voucher: action.payload, }); case ACTIONS.EDIT_VOUCHER: return Object.assign({}, state, { vouchers: editAndReplaceVoucher(state.vouchers, action.payload), }); case ACTIONS.EDIT_VOUCHER_LOCALLY: if (action.payload.id !== state.voucher.id) { return state; } return Object.assign({}, state, { voucher: editVoucher(state.voucher, action.payload), }); case ACTIONS.SAVE_VOUCHER_CHANGES: return Object.assign({}, state, { voucher: {}, }); default: return state; } };
mit
eklavyamirani/vscode
src/vs/workbench/parts/debug/electron-browser/repl.ts
12844
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ import 'vs/css!./../browser/media/repl'; import nls = require('vs/nls'); import uri from 'vs/base/common/uri'; import {wireCancellationToken} from 'vs/base/common/async'; import {TPromise} from 'vs/base/common/winjs.base'; import errors = require('vs/base/common/errors'); import lifecycle = require('vs/base/common/lifecycle'); import actions = require('vs/base/common/actions'); import builder = require('vs/base/browser/builder'); import dom = require('vs/base/browser/dom'); import platform = require('vs/base/common/platform'); import {CancellationToken} from 'vs/base/common/cancellation'; import {KeyCode} from 'vs/base/common/keyCodes'; import tree = require('vs/base/parts/tree/browser/tree'); import treeimpl = require('vs/base/parts/tree/browser/treeImpl'); import {IEditorOptions, IReadOnlyModel, EditorContextKeys, ICommonCodeEditor} from 'vs/editor/common/editorCommon'; import {Position} from 'vs/editor/common/core/position'; import * as modes from 'vs/editor/common/modes'; import {editorAction, ServicesAccessor, EditorAction} from 'vs/editor/common/editorCommonExtensions'; import {IModelService} from 'vs/editor/common/services/modelService'; import {CodeEditor} from 'vs/editor/browser/codeEditor'; import {ServiceCollection} from 'vs/platform/instantiation/common/serviceCollection'; import {IContextKeyService} from 'vs/platform/contextkey/common/contextkey'; import {ITelemetryService} from 'vs/platform/telemetry/common/telemetry'; import {IContextViewService, IContextMenuService} from 'vs/platform/contextview/browser/contextView'; import {IInstantiationService, createDecorator} from 'vs/platform/instantiation/common/instantiation'; import {IWorkspaceContextService} from 'vs/platform/workspace/common/workspace'; import {IStorageService, StorageScope} from 'vs/platform/storage/common/storage'; import viewer = require('vs/workbench/parts/debug/electron-browser/replViewer'); import debug = require('vs/workbench/parts/debug/common/debug'); import debugactions = require('vs/workbench/parts/debug/browser/debugActions'); import replhistory = require('vs/workbench/parts/debug/common/replHistory'); import {Panel} from 'vs/workbench/browser/panel'; import {IThemeService} from 'vs/workbench/services/themes/common/themeService'; import {IPanelService} from 'vs/workbench/services/panel/common/panelService'; const $ = dom.$; const replTreeOptions: tree.ITreeOptions = { indentPixels: 8, twistiePixels: 20, paddingOnRow: false, ariaLabel: nls.localize('replAriaLabel', "Read Eval Print Loop Panel") }; const HISTORY_STORAGE_KEY = 'debug.repl.history'; const IPrivateReplService = createDecorator<IPrivateReplService>('privateReplService'); export interface IPrivateReplService { _serviceBrand: any; navigateHistory(previous: boolean): void; acceptReplInput(): void; } export class Repl extends Panel implements IPrivateReplService { public _serviceBrand: any; private static HALF_WIDTH_TYPICAL = 'n'; private static HISTORY: replhistory.ReplHistory; private static REFRESH_DELAY = 500; // delay in ms to refresh the repl for new elements to show private toDispose: lifecycle.IDisposable[]; private tree: tree.ITree; private renderer: viewer.ReplExpressionsRenderer; private characterWidthSurveyor: HTMLElement; private treeContainer: HTMLElement; private replInput: CodeEditor; private replInputContainer: HTMLElement; private refreshTimeoutHandle: number; private actions: actions.IAction[]; private dimension: builder.Dimension; constructor( @debug.IDebugService private debugService: debug.IDebugService, @IContextMenuService private contextMenuService: IContextMenuService, @IWorkspaceContextService private contextService: IWorkspaceContextService, @ITelemetryService telemetryService: ITelemetryService, @IInstantiationService private instantiationService: IInstantiationService, @IContextViewService private contextViewService: IContextViewService, @IStorageService private storageService: IStorageService, @IPanelService private panelService: IPanelService, @IThemeService private themeService: IThemeService, @IModelService private modelService: IModelService, @IContextKeyService private contextKeyService: IContextKeyService ) { super(debug.REPL_ID, telemetryService); this.toDispose = []; this.registerListeners(); } private registerListeners(): void { this.toDispose.push(this.debugService.getModel().onDidChangeReplElements(() => { this.onReplElementsUpdated(); })); this.toDispose.push(this.panelService.onDidPanelOpen(panel => { if (panel.getId() === debug.REPL_ID) { const elements = this.debugService.getModel().getReplElements(); if (elements.length > 0) { return this.tree.reveal(elements[elements.length - 1]); } } })); this.toDispose.push(this.themeService.onDidColorThemeChange(e => this.replInput.updateOptions(this.getReplInputOptions()))); } private onReplElementsUpdated(): void { if (this.tree) { if (this.refreshTimeoutHandle) { return; // refresh already triggered } this.refreshTimeoutHandle = setTimeout(() => { this.refreshTimeoutHandle = null; this.tree.refresh().done(() => this.tree.setScrollPosition(1), errors.onUnexpectedError); }, Repl.REFRESH_DELAY); } } public create(parent: builder.Builder): TPromise<void> { super.create(parent); const container = dom.append(parent.getHTMLElement(), $('.repl')); this.treeContainer = dom.append(container, $('.repl-tree')); this.replInputContainer = dom.append(container, $('.repl-input-wrapper')); const scopedContextKeyService = this.contextKeyService.createScoped(this.replInputContainer); this.toDispose.push(scopedContextKeyService); debug.CONTEXT_IN_DEBUG_REPL.bindTo(scopedContextKeyService).set(true); const scopedInstantiationService = this.instantiationService.createChild(new ServiceCollection( [IContextKeyService, scopedContextKeyService], [IPrivateReplService, this])); this.replInput = scopedInstantiationService.createInstance(CodeEditor, this.replInputContainer, this.getReplInputOptions()); const model = this.modelService.createModel('', null, uri.parse(`${debug.DEBUG_SCHEME}:input`)); this.replInput.setModel(model); modes.SuggestRegistry.register({ scheme: debug.DEBUG_SCHEME }, { triggerCharacters: ['.'], provideCompletionItems: (model: IReadOnlyModel, position: Position, token: CancellationToken): Thenable<modes.ISuggestResult> => { const word = this.replInput.getModel().getWordAtPosition(position); const text = this.replInput.getModel().getLineContent(position.lineNumber); return wireCancellationToken(token, this.debugService.completions(text, position).then(suggestions => ({ currentWord: word ? word.word : '', suggestions }))); } }, true ); this.toDispose.push(this.replInput.onDidScrollChange(e => { if (!e.scrollHeightChanged) { return; } this.layout(this.dimension, Math.min(170, e.scrollHeight)); })); this.toDispose.push(dom.addStandardDisposableListener(this.replInputContainer, dom.EventType.FOCUS, () => dom.addClass(this.replInputContainer, 'synthetic-focus'))); this.toDispose.push(dom.addStandardDisposableListener(this.replInputContainer, dom.EventType.BLUR, () => dom.removeClass(this.replInputContainer, 'synthetic-focus'))); this.characterWidthSurveyor = dom.append(container, $('.surveyor')); this.characterWidthSurveyor.textContent = Repl.HALF_WIDTH_TYPICAL; for (let i = 0; i < 10; i++) { this.characterWidthSurveyor.textContent += this.characterWidthSurveyor.textContent; } this.characterWidthSurveyor.style.fontSize = platform.isMacintosh ? '12px' : '14px'; this.renderer = this.instantiationService.createInstance(viewer.ReplExpressionsRenderer); this.tree = new treeimpl.Tree(this.treeContainer, { dataSource: new viewer.ReplExpressionsDataSource(this.debugService), renderer: this.renderer, accessibilityProvider: new viewer.ReplExpressionsAccessibilityProvider(), controller: new viewer.ReplExpressionsController(this.debugService, this.contextMenuService, new viewer.ReplExpressionsActionProvider(this.instantiationService), this.replInput, false) }, replTreeOptions); if (!Repl.HISTORY) { Repl.HISTORY = new replhistory.ReplHistory(JSON.parse(this.storageService.get(HISTORY_STORAGE_KEY, StorageScope.WORKSPACE, '[]'))); } return this.tree.setInput(this.debugService.getModel()); } public navigateHistory(previous: boolean): void { const historyInput = previous ? Repl.HISTORY.previous() : Repl.HISTORY.next(); if (historyInput) { Repl.HISTORY.remember(this.replInput.getValue(), previous); this.replInput.setValue(historyInput); // always leave cursor at the end. this.replInput.setPosition({ lineNumber: 1, column: historyInput.length + 1 }); } } public acceptReplInput(): void { this.debugService.addReplExpression(this.replInput.getValue()); Repl.HISTORY.evaluated(this.replInput.getValue()); this.replInput.setValue(''); // Trigger a layout to shrink a potential multi line input this.layout(this.dimension); } public layout(dimension: builder.Dimension, replInputHeight = 22): void { this.dimension = dimension; if (this.tree) { this.renderer.setWidth(dimension.width - 25, this.characterWidthSurveyor.clientWidth / this.characterWidthSurveyor.textContent.length); const treeHeight = dimension.height - replInputHeight; this.treeContainer.style.height = `${treeHeight}px`; this.tree.layout(treeHeight); } this.replInputContainer.style.height = `${replInputHeight}px`; this.replInput.layout({ width: dimension.width - 20, height: replInputHeight }); } public focus(): void { this.replInput.focus(); } public getActions(): actions.IAction[] { if (!this.actions) { this.actions = [ this.instantiationService.createInstance(debugactions.ClearReplAction, debugactions.ClearReplAction.ID, debugactions.ClearReplAction.LABEL) ]; this.actions.forEach(a => { this.toDispose.push(a); }); } return this.actions; } public shutdown(): void { this.storageService.store(HISTORY_STORAGE_KEY, JSON.stringify(Repl.HISTORY.save()), StorageScope.WORKSPACE); } private getReplInputOptions(): IEditorOptions { return { wrappingColumn: 0, overviewRulerLanes: 0, glyphMargin: false, lineNumbers: false, folding: false, selectOnLineNumbers: false, selectionHighlight: false, scrollbar: { horizontal: 'hidden', vertical: 'hidden' }, lineDecorationsWidth: 0, scrollBeyondLastLine: false, lineHeight: 21, theme: this.themeService.getColorTheme() }; } public dispose(): void { this.replInput.destroy(); this.toDispose = lifecycle.dispose(this.toDispose); super.dispose(); } } @editorAction class ReplHistoryPreviousAction extends EditorAction { constructor() { super({ id: 'repl.action.historyPrevious', label: nls.localize('actions.repl.historyPrevious', "History Previous"), alias: 'History Previous', precondition: debug.CONTEXT_IN_DEBUG_REPL, kbOpts: { kbExpr: EditorContextKeys.TextFocus, primary: KeyCode.UpArrow, weight: 50 }, menuOpts: { group: 'debug' } }); } public run(accessor: ServicesAccessor, editor: ICommonCodeEditor): void | TPromise<void> { accessor.get(IPrivateReplService).navigateHistory(true); } } @editorAction class ReplHistoryNextAction extends EditorAction { constructor() { super({ id: 'repl.action.historyNext', label: nls.localize('actions.repl.historyNext', "History Next"), alias: 'History Next', precondition: debug.CONTEXT_IN_DEBUG_REPL, kbOpts: { kbExpr: EditorContextKeys.TextFocus, primary: KeyCode.DownArrow, weight: 50 }, menuOpts: { group: 'debug' } }); } public run(accessor: ServicesAccessor, editor: ICommonCodeEditor): void | TPromise<void> { accessor.get(IPrivateReplService).navigateHistory(false); } } @editorAction class AcceptReplInputAction extends EditorAction { constructor() { super({ id: 'repl.action.acceptInput', label: nls.localize('actions.repl.acceptInput', "REPL Accept Input"), alias: 'REPL Accept Input', precondition: debug.CONTEXT_IN_DEBUG_REPL, kbOpts: { kbExpr: EditorContextKeys.TextFocus, primary: KeyCode.Enter, weight: 50 } }); } public run(accessor: ServicesAccessor, editor: ICommonCodeEditor): void | TPromise<void> { accessor.get(IPrivateReplService).acceptReplInput(); } }
mit
VeganCoin/VeganCoin
src/qt/sendcoinsentry.cpp
4337
#include "sendcoinsentry.h" #include "ui_sendcoinsentry.h" #include "guiutil.h" #include "bitcoinunits.h" #include "addressbookpage.h" #include "walletmodel.h" #include "optionsmodel.h" #include "addresstablemodel.h" #include <QApplication> #include <QClipboard> SendCoinsEntry::SendCoinsEntry(QWidget *parent) : QFrame(parent), ui(new Ui::SendCoinsEntry), model(0) { ui->setupUi(this); #ifdef Q_OS_MAC ui->payToLayout->setSpacing(4); #endif #if QT_VERSION >= 0x040700 /* Do not move this to the XML file, Qt before 4.7 will choke on it */ ui->addAsLabel->setPlaceholderText(tr("Enter a label for this address to add it to your address book")); ui->payTo->setPlaceholderText(tr("Enter a VeganCoin address (e.g. 1NS17iag9jJgTHD1VXjvLCEnZuQ3rJDE9L)")); #endif setFocusPolicy(Qt::TabFocus); setFocusProxy(ui->payTo); GUIUtil::setupAddressWidget(ui->payTo, this); } SendCoinsEntry::~SendCoinsEntry() { delete ui; } void SendCoinsEntry::on_pasteButton_clicked() { // Paste text from clipboard into recipient field ui->payTo->setText(QApplication::clipboard()->text()); } void SendCoinsEntry::on_addressBookButton_clicked() { if(!model) return; AddressBookPage dlg(AddressBookPage::ForSending, AddressBookPage::SendingTab, this); dlg.setModel(model->getAddressTableModel()); if(dlg.exec()) { ui->payTo->setText(dlg.getReturnValue()); ui->payAmount->setFocus(); } } void SendCoinsEntry::on_payTo_textChanged(const QString &address) { if(!model) return; // Fill in label from address book, if address has an associated label QString associatedLabel = model->getAddressTableModel()->labelForAddress(address); if(!associatedLabel.isEmpty()) ui->addAsLabel->setText(associatedLabel); } void SendCoinsEntry::setModel(WalletModel *model) { this->model = model; if(model && model->getOptionsModel()) connect(model->getOptionsModel(), SIGNAL(displayUnitChanged(int)), this, SLOT(updateDisplayUnit())); clear(); } void SendCoinsEntry::setRemoveEnabled(bool enabled) { ui->deleteButton->setEnabled(enabled); } void SendCoinsEntry::clear() { ui->payTo->clear(); ui->addAsLabel->clear(); ui->payAmount->clear(); ui->payTo->setFocus(); // update the display unit, to not use the default ("BTC") updateDisplayUnit(); } void SendCoinsEntry::on_deleteButton_clicked() { emit removeEntry(this); } bool SendCoinsEntry::validate() { // Check input validity bool retval = true; if(!ui->payAmount->validate()) { retval = false; } else { if(ui->payAmount->value() <= 0) { // Cannot send 0 coins or less ui->payAmount->setValid(false); retval = false; } } if(!ui->payTo->hasAcceptableInput() || (model && !model->validateAddress(ui->payTo->text()))) { ui->payTo->setValid(false); retval = false; } return retval; } SendCoinsRecipient SendCoinsEntry::getValue() { SendCoinsRecipient rv; rv.address = ui->payTo->text(); rv.label = ui->addAsLabel->text(); rv.amount = ui->payAmount->value(); return rv; } QWidget *SendCoinsEntry::setupTabChain(QWidget *prev) { QWidget::setTabOrder(prev, ui->payTo); QWidget::setTabOrder(ui->payTo, ui->addressBookButton); QWidget::setTabOrder(ui->addressBookButton, ui->pasteButton); QWidget::setTabOrder(ui->pasteButton, ui->deleteButton); QWidget::setTabOrder(ui->deleteButton, ui->addAsLabel); return ui->payAmount->setupTabChain(ui->addAsLabel); } void SendCoinsEntry::setValue(const SendCoinsRecipient &value) { ui->payTo->setText(value.address); ui->addAsLabel->setText(value.label); ui->payAmount->setValue(value.amount); } void SendCoinsEntry::setAddress(const QString &address) { ui->payTo->setText(address); ui->payAmount->setFocus(); } bool SendCoinsEntry::isClear() { return ui->payTo->text().isEmpty(); } void SendCoinsEntry::setFocus() { ui->payTo->setFocus(); } void SendCoinsEntry::updateDisplayUnit() { if(model && model->getOptionsModel()) { // Update payAmount with the current unit ui->payAmount->setDisplayUnit(model->getOptionsModel()->getDisplayUnit()); } }
mit
hail-is/hail
hail/python/hail/ir/blockmatrix_ir.py
13458
import hail as hl from hail.expr.blockmatrix_type import tblockmatrix from hail.expr.types import tarray from .blockmatrix_reader import BlockMatrixReader from .base_ir import BlockMatrixIR, IR from hail.typecheck import typecheck_method, sequenceof from hail.utils.misc import escape_id from hail.utils.java import Env class BlockMatrixRead(BlockMatrixIR): @typecheck_method(reader=BlockMatrixReader) def __init__(self, reader): super().__init__() self.reader = reader def head_str(self): return f'"{self.reader.render()}"' def _eq(self, other): return self.reader == other.reader def _compute_type(self): self._type = Env.backend().blockmatrix_type(self) class BlockMatrixMap(BlockMatrixIR): @typecheck_method(child=BlockMatrixIR, name=str, f=IR, needs_dense=bool) def __init__(self, child, name, f, needs_dense): super().__init__(child, f) self.child = child self.name = name self.f = f self.needs_dense = needs_dense def _compute_type(self): self._type = self.child.typ def head_str(self): return escape_id(self.name) + " " + str(self.needs_dense) def bindings(self, i: int, default_value=None): if i == 1: value = self.child.typ.element_type if default_value is None else default_value return {self.name: value} else: return {} def binds(self, i): return {self.name} if i == 1 else {} class BlockMatrixMap2(BlockMatrixIR): @typecheck_method(left=BlockMatrixIR, right=BlockMatrixIR, left_name=str, right_name=str, f=IR, sparsity_strategy=str) def __init__(self, left, right, left_name, right_name, f, sparsity_strategy): super().__init__(left, right, f) self.left = left self.right = right self.left_name = left_name self.right_name = right_name self.f = f self.sparsity_strategy = sparsity_strategy def _compute_type(self): self.right.typ # Force self._type = self.left.typ def head_str(self): return escape_id(self.left_name) + " " + escape_id(self.right_name) + " " + self.sparsity_strategy def bindings(self, i: int, default_value=None): if i == 2: if default_value is None: l_value = self.left.typ.element_type r_value = self.right.typ.element_type else: (l_value, r_value) = (default_value, default_value) return {self.left_name: l_value, self.right_name: r_value} else: return {} def binds(self, i): return {self.left_name, self.right_name} if i == 2 else {} class BlockMatrixDot(BlockMatrixIR): @typecheck_method(left=BlockMatrixIR, right=BlockMatrixIR) def __init__(self, left, right): super().__init__(left, right) self.left = left self.right = right def _compute_type(self): l_rows, l_cols = tensor_shape_to_matrix_shape(self.left) r_rows, r_cols = tensor_shape_to_matrix_shape(self.right) assert l_cols == r_rows tensor_shape, is_row_vector = _matrix_shape_to_tensor_shape(l_rows, r_cols) self._type = tblockmatrix(self.left.typ.element_type, tensor_shape, is_row_vector, self.left.typ.block_size) class BlockMatrixBroadcast(BlockMatrixIR): @typecheck_method(child=BlockMatrixIR, in_index_expr=sequenceof(int), shape=sequenceof(int), block_size=int) def __init__(self, child, in_index_expr, shape, block_size): super().__init__(child) self.child = child self.in_index_expr = in_index_expr self.shape = shape self.block_size = block_size def head_str(self): return '{} {} {}'.format(_serialize_list(self.in_index_expr), _serialize_list(self.shape), self.block_size) def _eq(self, other): return self.in_index_expr == other.in_index_expr and \ self.shape == other.shape and \ self.block_size == other.block_size def _compute_type(self): assert len(self.shape) == 2 tensor_shape, is_row_vector = _matrix_shape_to_tensor_shape(self.shape[0], self.shape[1]) self._type = tblockmatrix(self.child.typ.element_type, tensor_shape, is_row_vector, self.block_size) class BlockMatrixAgg(BlockMatrixIR): @typecheck_method(child=BlockMatrixIR, out_index_expr=sequenceof(int)) def __init__(self, child, out_index_expr): super().__init__(child) self.child = child self.out_index_expr = out_index_expr def head_str(self): return _serialize_list(self.out_index_expr) def _eq(self, other): return self.out_index_expr == other.out_index_expr def _compute_type(self): child_matrix_shape = tensor_shape_to_matrix_shape(self.child) if self.out_index_expr == [0, 1]: is_row_vector = False shape = [] elif self.out_index_expr == [0]: is_row_vector = True shape = [child_matrix_shape[1]] elif self.out_index_expr == [1]: is_row_vector = False shape = [child_matrix_shape[0]] else: raise ValueError("Invalid out_index_expr") self._type = tblockmatrix(self.child.typ.element_type, shape, is_row_vector, self.child.typ.block_size) class BlockMatrixFilter(BlockMatrixIR): @typecheck_method(child=BlockMatrixIR, indices_to_keep=sequenceof(sequenceof(int))) def __init__(self, child, indices_to_keep): super().__init__(child) self.child = child self.indices_to_keep = indices_to_keep def head_str(self): return _serialize_list([_serialize_list(idxs) for idxs in self.indices_to_keep]) def _eq(self, other): return self.indices_to_keep == other.indices_to_keep def _compute_type(self): assert len(self.indices_to_keep) == 2 child_tensor_shape = self.child.typ.shape child_ndim = len(child_tensor_shape) if child_ndim == 1: if self.child.typ.is_row_vector: child_matrix_shape = [1, child_tensor_shape[0]] else: child_matrix_shape = [child_tensor_shape[0], 1] else: child_matrix_shape = child_tensor_shape matrix_shape = [len(idxs) if len(idxs) != 0 else child_matrix_shape[i] for i, idxs in enumerate(self.indices_to_keep)] tensor_shape, is_row_vector = _matrix_shape_to_tensor_shape(matrix_shape[0], matrix_shape[1]) self._type = tblockmatrix(self.child.typ.element_type, tensor_shape, is_row_vector, self.child.typ.block_size) class BlockMatrixDensify(BlockMatrixIR): @typecheck_method(child=BlockMatrixIR) def __init__(self, child): super().__init__(child) self.child = child def _compute_type(self): self._type = self.child.typ class BlockMatrixSparsifier(object): def head_str(self): return '' def __repr__(self): head_str = self.head_str() if head_str != '': head_str = f' {head_str}' return f'(Py{self.__class__.__name__}{head_str})' def _eq(self, other): return True def __eq__(self, other): return isinstance(other, self.__class__) and self._eq(other) class BandSparsifier(BlockMatrixSparsifier): @typecheck_method(blocks_only=bool) def __init__(self, blocks_only): self.blocks_only = blocks_only def head_str(self): return str(self.blocks_only) def _eq(self, other): return self.blocks_only == other.blocks_only class RowIntervalSparsifier(BlockMatrixSparsifier): @typecheck_method(blocks_only=bool) def __init__(self, blocks_only): self.blocks_only = blocks_only def head_str(self): return str(self.blocks_only) def _eq(self, other): return self.blocks_only == other.blocks_only class _RectangleSparsifier(BlockMatrixSparsifier): def __init__(self): pass def __repr__(self): return '(PyRectangleSparsifier)' RectangleSparsifier = _RectangleSparsifier() class PerBlockSparsifier(BlockMatrixSparsifier): def __init__(self): pass def __repr__(self): return '(PyPerBlockSparsifier)' class BlockMatrixSparsify(BlockMatrixIR): @typecheck_method(child=BlockMatrixIR, value=IR, sparsifier=BlockMatrixSparsifier) def __init__(self, child, value, sparsifier): super().__init__(value, child) self.child = child self.value = value self.sparsifier = sparsifier def head_str(self): return str(self.sparsifier) def _eq(self, other): return self.sparsifier == other.sparsifier def _compute_type(self): self._type = self.child.typ class BlockMatrixSlice(BlockMatrixIR): @typecheck_method(child=BlockMatrixIR, slices=sequenceof(slice)) def __init__(self, child, slices): super().__init__(child) self.child = child self.slices = slices def head_str(self): return '{}'.format(_serialize_list([f'({s.start} {s.stop} {s.step})' for s in self.slices])) def _eq(self, other): return self.slices == other.slices def _compute_type(self): assert len(self.slices) == 2 matrix_shape = [1 + (s.stop - s.start - 1) // s.step for s in self.slices] tensor_shape, is_row_vector = _matrix_shape_to_tensor_shape(matrix_shape[0], matrix_shape[1]) self._type = tblockmatrix(self.child.typ.element_type, tensor_shape, is_row_vector, self.child.typ.block_size) class ValueToBlockMatrix(BlockMatrixIR): @typecheck_method(child=IR, shape=sequenceof(int), block_size=int) def __init__(self, child, shape, block_size): super().__init__(child) self.child = child self.shape = shape self.block_size = block_size def head_str(self): return '{} {}'.format(_serialize_list(self.shape), self.block_size) def _eq(self, other): return self.shape == other.shape and \ self.block_size == other.block_size def _compute_type(self): child_type = self.child.typ if isinstance(child_type, tarray): element_type = child_type._element_type else: element_type = child_type assert len(self.shape) == 2 tensor_shape, is_row_vector = _matrix_shape_to_tensor_shape(self.shape[0], self.shape[1]) self._type = tblockmatrix(element_type, tensor_shape, is_row_vector, self.block_size) class BlockMatrixRandom(BlockMatrixIR): @typecheck_method(seed=int, gaussian=bool, shape=sequenceof(int), block_size=int) def __init__(self, seed, gaussian, shape, block_size): super().__init__() self.seed = seed self.gaussian = gaussian self.shape = shape self.block_size = block_size def head_str(self): return '{} {} {} {}'.format(self.seed, self.gaussian, _serialize_list(self.shape), self.block_size) def _eq(self, other): return self.seed == other.seed and \ self.gaussian == other.gaussian and \ self.shape == other.shape and \ self.block_size == other.block_size def _compute_type(self): assert len(self.shape) == 2 tensor_shape, is_row_vector = _matrix_shape_to_tensor_shape(self.shape[0], self.shape[1]) self._type = tblockmatrix(hl.tfloat64, tensor_shape, is_row_vector, self.block_size) class JavaBlockMatrix(BlockMatrixIR): def __init__(self, jbm): super().__init__() self.jir = Env.hail().expr.ir.BlockMatrixLiteral(jbm) def render_head(self, r): return f'(JavaBlockMatrix {r.add_jir(self.jir)}' def _compute_type(self): self._type = tblockmatrix._from_java(self.jir.typ()) def tensor_shape_to_matrix_shape(bmir): shape = bmir.typ.shape is_row_vector = bmir.typ.is_row_vector assert len(shape) <= 2 if len(shape) == 0: return (1, 1) elif len(shape) == 1: length = shape[0] return (1, length) if is_row_vector else (length, 1) else: return tuple(shape) def _serialize_list(xs): return "(" + ' '.join([str(x) for x in xs]) + ")" def _matrix_shape_to_tensor_shape(n_rows, n_cols): if n_rows == 1 and n_cols == 1: return [], False elif n_rows == 1: return [n_cols], True elif n_cols == 1: return [n_rows], False else: return [n_rows, n_cols], False
mit
ecommerce-utilities/php-countries
codes/et_EE/icu-countries.php
49
<?php require __DIR__.'/../et/icu-countries.php';
mit
zettajs/zrx
zrx.js
4373
var Rx = require('rx'); var siren = require('siren'); var Device = require('./device'); var Zrx = module.exports = function(current) { if (!(this instanceof Zrx)) { return new Zrx(current); } this.client = siren(current); }; Zrx.prototype.load = function(uri) { this.client.load(uri); return this; }; Zrx.prototype.server = Zrx.prototype.servers = Zrx.prototype.peer = Zrx.prototype.peers = function(name) { var subject = new Rx.ReplaySubject(); this.client.subscribe(subject); var server = siren(subject) .link('http://rels.zettajs.io/server', name) .catch(Rx.Observable.empty()); return new Zrx(server); }; Zrx.prototype.query = function(ql) { return this.transition('query-devices', function(t) { t.set('ql', ql); return t.submit(); }).devices(); }; Zrx.prototype.device = Zrx.prototype.devices = function(filter) { var client; if (typeof filter === 'string') { client = this.client.entity(function(entity) { var device = new Device(entity); return device.type === filter; }); } else { client = this.client.entity(function(entity) { var device = new Device(entity); if (!filter) { return device; } else { return filter(device); } }); } return new Zrx(client); }; Zrx.prototype.toDevice = function() { var client = this.client .map(function(env) { return new Device(env.response.body); }); return new Zrx(client); }; Zrx.prototype.transition = function(name, cb) { var client = this.client.action(name, cb); return new Zrx(client); }; // binary streams are not yet supported Zrx.prototype.stream = function(name) { var client = this.client .link('http://rels.zettajs.io/object-stream', name) .monitor() .map(JSON.parse); return new Zrx(client); }; var subscriptionFns = ['subscribe', 'subscribeOnNext', 'subscribeOnError', 'subscribeOnCompleted', 'subscribeOn']; subscriptionFns.forEach(function(m) { Zrx.prototype[m] = function() { var args = Array.prototype.slice.call(arguments); return this.client[m].apply(this.client, args); } }); var operators = [ 'amb', 'and', 'asObservable', 'average', 'buffer', 'bufferWithCount', 'bufferWithTime', 'bufferWithTimeOrCount', 'catch', 'catchError', 'combineLatest', 'concat', 'concatAll', 'concatMap', 'concatMapObserver', 'connect', 'contains', 'controlled', 'count', 'debounce', 'debounceWithSelector', 'defaultIfEmpty', 'delay', 'delayWithSelector', 'dematerialize', 'distinct', 'distinctUntilChanged', 'do', 'doOnNext', 'doOnError', 'doOnCompleted', 'doWhile', 'elementAt', 'elementAtOrDefault', 'every', 'expand', 'filter', 'finally', 'ensure', 'find', 'findIndex', 'first', 'firstOrDefault', 'flatMap', 'flatMapObserver', 'flatMapLatest', 'forkJoin', 'groupBy', 'groupByUntil', 'groupJoin', 'ignoreElements', 'indexOf', 'isEmpty', 'join', 'jortSort', 'jortSortUntil', 'last', 'lastOrDefault', 'let', 'letBind', 'manySelect', 'map', 'max', 'maxBy', 'merge', 'mergeAll', 'min', 'minBy', 'multicast', 'observeOn', 'onErrorResumeNext', 'pairwise', 'partition', 'pausable', 'pausableBuffered', 'pluck', 'publish', 'publishLast', 'publishValue', 'share', 'shareReplay', 'shareValue', 'refCount', 'reduce', 'repeat', 'replay', 'retry', 'sample', 'scan', 'select', 'selectConcat', 'selectConcatObserver', 'selectMany', 'selectManyObserver', 'selectSwitch', 'sequenceEqual', 'single', 'singleOrDefault', 'skip', 'skipLast', 'skipLastWithTime', 'skipUntil', 'skipUntilWithTime', 'skipWhile', 'some', 'startWith', /*'subscribe', 'subscribeOnNext', 'subscribeOnError', 'subscribeOnCompleted', 'subscribeOn', */ 'sum', 'switch', 'switchLatest', 'take', 'takeLast', 'takeLastBuffer', 'takeLastBufferWithTime', 'takeLastWithTime', 'takeUntil', 'takeUntilWithTime', 'takeWhile', 'tap', 'tapOnNext', 'tapOnError', 'tapOnCompleted', 'throttleFirst', 'throttleWithTimeout', 'timeInterval', 'timeout', 'timeoutWithSelector', 'timestamp', 'toArray', 'toMap', 'toSet', 'transduce', 'where', 'window', 'windowWithCount', 'windowWithTime', 'windowWithTimeOrCount', 'zip' ] operators.forEach(function(m) { Zrx.prototype[m] = function() { var args = Array.prototype.slice.call(arguments); var client = this.client[m].apply(this.client, args); return new Zrx(client); }; });
mit
Curiosity-Education/curiosity-v.1.0
public/packages/assets/js/config/request/dist/request-dist.js
2239
'use strict'; var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }(); function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } var Request = function () { function Request() { _classCallCheck(this, Request); } _createClass(Request, null, [{ key: 'send', value: function send(method, path, callback, data) { var xhttp = new XMLHttpRequest(); xhttp.onreadystatechange = function () { if (this.readyState == 4 && this.status == 200) { if (this.responseText != '') var response = JSON.parse(this.responseText); var status = this.status; callback(response, status, this); } }; xhttp.open(method, path, true); if (data != null) { try { data.append('tryalUndefined', null); $.ajax({ url: path, method: method, data: data, processData: false, contentType: false }).done(function (response) { callback(response); }).fail(function (error) { callback(error); }); } catch (e) { xhttp.setRequestHeader("Content-Type", "application/json;charset=UTF-8"); xhttp.send(JSON.stringify(data)); } } else { xhttp.send(); } } }]); return Request; }();
mit
mpieces/Rails-Estates-to-Date-WIP
db/migrate/20151213233725_create_favorites.rb
363
class CreateFavorites < ActiveRecord::Migration def change create_table :favorites do |t| t.references :favorited, polymorphic: true, index: true # t. references :estatesale, index: true t.references :user, index: true t.references :shopper, index: true # t.text_area :notes t.timestamps null: false end end end
mit
VoRDKW/kw_smart
application/views/users/user_view.php
184
<script> jQuery(document).ready(function ($) { $("#menu-top li").removeAttr('class'); }); </script> <div class="container-fluid" style="min-height: 800px;"> </div>
mit
leevilehtonen/cook-a-gram
src/main/java/com/leevilehtonen/cookagram/CookAGramApplication.java
502
package com.leevilehtonen.cookagram; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; /** * Spring Boot application starter class * * @author lleevi */ @SpringBootApplication public class CookAGramApplication { /** * Application main method * * @param args commandline arguments */ public static void main(String[] args) { SpringApplication.run(CookAGramApplication.class, args); } }
mit
protofuture/dashing
app/models/item.rb
979
# == Schema Information # # Table name: items # # id :integer not null, primary key # private_path :string(255) # user_id :integer # shared :boolean # created_at :datetime # updated_at :datetime # class Item < ActiveRecord::Base attr_accessor :file attr_accessible :shared, :file, :private_path belongs_to :user validates :user_id, :presence => true # validates :shared, :presence => true validates :file, :presence => true, :on =>:create default_scope :order => 'items.created_at DESC' def create #set the file path set_path #save the uploaded file file_save super end def destroy File.delete(full_path) if File.file?(full_path) super end def file_save # write the file File.open(full_path, "wb") { |f| f.write(file.read) } end def set_path self.private_path = file.original_filename end def full_path File.join(self.user.share_path,private_path) end end
mit
theroot79/angularJSproject
app/js/controllers/AdminUsersListController.js
902
'use strict'; appAngularJS.controller('AdminUsersListController',['$scope','adminServices','filters', function ($scope, adminServices, filters) { $scope.currentPage = 1; $scope.startPage = 1; $scope.itemsPerPage = 10; $scope.SortBy = 'UserName'; $scope.reverseSort = false; function loadAdminUsers(params){ var paramsSend = params || {}; adminServices.getAdminUsers(paramsSend,function (resp) { $scope.allUsers = resp; }); } $scope.sortBy = function(sortByStr){ filters.sortBy(sortByStr); loadAdminUsers(filters.getParams()); $scope.reverseSort = $scope.reverseSort == false; }; filters.setPage($scope.currentPage,$scope.itemsPerPage); filters.sortBy('UserName'); loadAdminUsers(filters.getParams()); $scope.pageChanged = function(){ filters.setPage($scope.currentPage,$scope.itemsPerPage); loadAdminUsers(filters.getParams()); }; } ]);
mit
askehansen/redactor_s3
spec/dummy/config/routes.rb
83
Rails.application.routes.draw do mount RedactorS3::Engine => "/redactor_s3" end
mit
Domiii/smart-video-2013
MyPlayer/src/main.cpp
694
#include <cstdio> #include <iostream> #include <opencv2/highgui/highgui.hpp> #include "MyPlayer.h" using namespace std; using namespace cv; using namespace mp; PlayerConfig Config; std::unique_ptr<Player> p; int main(int argc, char* argv[]) { Config.CfgFolder = ".."; Config.CfgFile = "config.json"; if (!Config.InitializeConfig() || Config.ClipEntries.size() == 0){ cerr << "ERROR: Invalid config or clip list file - " << Config.ClipListFile; cerr << "Press ENTER to exit." << endl; cin.get(); exit(EXIT_FAILURE); } p = std::unique_ptr<Player>(new Player(Config)); for (auto clip : Config.ClipEntries){ p->initPlayer(clip); } return 0; }
mit
jribeiro/storybook
app/react-native/src/server/config/babel.js
1404
/** * Copyright (c) 2015-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. */ module.exports = { // Don't try to find .babelrc because we want to force this configuration. babelrc: false, presets: [ // let, const, destructuring, classes, modules require.resolve('babel-preset-es2015'), // exponentiation require.resolve('babel-preset-es2016'), // JSX, Flow require.resolve('babel-preset-react'), ], plugins: [ // function x(a, b, c,) { } require.resolve('babel-plugin-syntax-trailing-function-commas'), // await fetch() require.resolve('babel-plugin-syntax-async-functions'), // class { handleClick = () => { } } require.resolve('babel-plugin-transform-class-properties'), // { ...todo, completed: true } require.resolve('babel-plugin-transform-object-rest-spread'), // function* () { yield 42; yield 43; } require.resolve('babel-plugin-transform-regenerator'), // Polyfills the runtime needed for async/await and generators [ require.resolve('babel-plugin-transform-runtime'), { helpers: true, polyfill: true, regenerator: true, }, ], ], };
mit
tilleryj/rio
public/javascripts/components/base.js
1022
rio.components.Base = rio.Component.create("Base", { attrReaders: [ ["className", ""], ["seleniumId", ""] ], styles: ["position", "top", "right", "bottom", "left", "display"], methods: { html: function() { if (!this._html) { this._html = this.buildHtml(); this._html.addClassName(this.getClassName()); if (rio.environment.supportSelenium) { this._html.id = this.getSeleniumId(); } this._html.applyStyle({ position: this.position, top: this.top, right: this.right, bottom: this.bottom, left: this.left, display: this.display }); } return this._html; }, addClassName: function(className) { this.html().addClassName(className); this._className = this.html().className; }, removeClassName: function(className) { this.html().removeClassName(className); this._className = this.html().className; }, show: function() { this.setDisplay(""); }, hide: function() { this.setDisplay("none"); } } });
mit
khenidak/Router
src/RouterLib/MatchingFrx/Context/ContextContainsKeyMatcher.cs
1729
using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Text; using System.Threading.Tasks; namespace RouterLib { public class ContextContainsKeyMatcher : MatcherBase { public string KeyName { get; set; } public StringMatchType MatchType { get; set; } = StringMatchType.Exact; public ContextContainsKeyMatcher() { } public ContextContainsKeyMatcher(string keyName) : this(keyName, StringMatchType.Exact) { } public ContextContainsKeyMatcher(string keyName, StringMatchType matchType ) { KeyName = keyName; MatchType = matchType; } public async override Task<bool> MatchAsync(RoutingContextBase routingContext, string sAddress, IDictionary<string, object> Context, Stream Body) { if (string.IsNullOrEmpty(KeyName)) throw new ArgumentNullException("KeyName"); if (false == await base.MatchAsync(routingContext, sAddress, Context, Body)) return false; // short circut, if comparison is exact check that the dictionary // contains exact key & we are done. if (MatchType == StringMatchType.Exact) return Context.ContainsKey(KeyName); foreach (var key in Context.Keys) { if (MatchString(key,KeyName, MatchType)) return true; } return false; } } }
mit
pballart/Memorize4me
app/src/main/java/com/best/memorize4me/util/DateUtils.java
590
package com.best.memorize4me.util; import java.text.SimpleDateFormat; import java.util.Date; /** * Created by konstantin.bogdanov on 08.07.2015. */ public class DateUtils { public static String dateToString(Date date) { SimpleDateFormat simpleDateFormat = new SimpleDateFormat("dd/MM/yyyy"); return simpleDateFormat.format(date); } public static String dateToString(long longDate) { Date date = new Date(longDate); SimpleDateFormat simpleDateFormat = new SimpleDateFormat("dd/MM/yyyy"); return simpleDateFormat.format(date); } }
mit
lucionei/chamadotecnico
chamadosTecnicosFinal-app/node_modules/date-fns/fp/isSameSecondWithOptions/index.js
627
'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); var _index = require('../../isSameSecond/index.js'); var _index2 = _interopRequireDefault(_index); var _index3 = require('../_lib/convertToFP/index.js'); var _index4 = _interopRequireDefault(_index3); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } // This file is generated automatically by `scripts/build/fp.js`. Please, don't change it. var isSameSecondWithOptions = (0, _index4.default)(_index2.default, 3); exports.default = isSameSecondWithOptions; module.exports = exports['default'];
mit
ruvents/ruvents-form-wizard-bundle
DependencyInjection/RuventsFormWizardExtension.php
992
<?php declare(strict_types=1); namespace Ruvents\FormWizardBundle\DependencyInjection; use Ruvents\FormWizardBundle\Type\StepTypeInterface; use Ruvents\FormWizardBundle\Type\WizardTypeInterface; use Symfony\Component\Config\FileLocator; use Symfony\Component\DependencyInjection\ContainerBuilder; use Symfony\Component\DependencyInjection\Extension\Extension; use Symfony\Component\DependencyInjection\Loader\PhpFileLoader; class RuventsFormWizardExtension extends Extension { /** * {@inheritdoc} */ public function load(array $configs, ContainerBuilder $container) { (new PhpFileLoader($container, new FileLocator(__DIR__.'/../Resources/config'))) ->load('services.php'); $container->registerForAutoconfiguration(WizardTypeInterface::class) ->addTag('ruvents_form_wizard.wizard_type'); $container->registerForAutoconfiguration(StepTypeInterface::class) ->addTag('ruvents_form_wizard.step_type'); } }
mit
niromon/votvot
gutils/src/main/java/com/deguet/gutils/permutation/PrimeBase.java
6152
package com.deguet.gutils.permutation; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.List; /** * Helps represent a set of positive Integer with one using the uniqueness of prime decomposition. * 4 ::: [0, 2] as 1^0 * 2^2 * 3 ::: [0, 0, 1] as 1^0 * 2^0 * 3^1 * 2 ::: [0, 1] * 1 ::: [1] * 0 ::: [] * each number in the array corresponds to the exponent of the corresponding prime number * * @author joris * */ public class PrimeBase { public int[] to(long source){ //System.out.println("====================================== "+source); if (source == 0) return new int[]{}; if (source == 1) return new int[]{1}; long n = source; List<Integer> factors = new ArrayList<Integer>(); for (int i = 2; i <= n; i++) { while (n % i == 0) { factors.add(i); n = n / i; } } //System.out.println("List " + factors); int maxFactor = Collections.max(factors).intValue(); int size = primeIndex(maxFactor); //System.out.println("size " + size); int[] result = new int[size]; for (int f = 0 ; f < size ; f++){ int prime = nthPrime(f+1); //System.out.println("Prime is "+prime); result[f] = Collections.frequency(factors, prime); } return result; } private int primeIndex(int prime){ if (!isPrime(prime)) throw new IllegalArgumentException(); if (prime == 1) return 1; if (prime == 2) return 2; int i = 0 ; while(true){ int p = nthPrime(i); if (prime == p) return i; i++; } } /** * Converts a prime base code (exponents for given positions) into its long value. */ public long from(int[] digits){ if (digits.length == 0 ) return 0; if (Arrays.equals(digits, new int[]{1})) return 1; long result = 1; for (int i = 0; i < digits.length; i++) { int prime = nthPrime(i+1); int expon = (int)digits[i]; //System.out.println("Res " + result +" prime " + prime+" exp " +expon); result *= Math.pow(prime, expon); } return result; } // Count number of set bits in an int private static int popCount(int n) { n -= (n >>> 1) & 0x55555555; n = ((n >>> 2) & 0x33333333) + (n & 0x33333333); n = ((n >> 4) & 0x0F0F0F0F) + (n & 0x0F0F0F0F); return (n * 0x01010101) >> 24; } private int nthPrime(int n){ if (n==1) return 1; if (n==2) return 2; return nthprime(n-1); } /** * https://bitbucket.org/dafis/javaprimes * @param n * @return */ private int nthprime(int n) { if (n < 2) return 2; if (n == 2) return 3; if (n == 3) return 5; int limit, root, count = 2; limit = (int)(n*(Math.log(n) + Math.log(Math.log(n)))) + 3; root = (int)Math.sqrt(limit); switch(limit%6) { case 0: limit = 2*(limit/6) - 1; break; case 5: limit = 2*(limit/6) + 1; break; default: limit = 2*(limit/6); } switch(root%6) { case 0: root = 2*(root/6) - 1; break; case 5: root = 2*(root/6) + 1; break; default: root = 2*(root/6); } int dim = (limit+31) >> 5; int[] sieve = new int[dim]; for(int i = 0; i < root; ++i) { if ((sieve[i >> 5] & (1 << (i&31))) == 0) { int start, s1, s2; if ((i & 1) == 1) { start = i*(3*i+8)+4; s1 = 4*i+5; s2 = 2*i+3; } else { start = i*(3*i+10)+7; s1 = 2*i+3; s2 = 4*i+7; } for(int j = start; j < limit; j += s2) { sieve[j >> 5] |= 1 << (j&31); j += s1; if (j >= limit) break; sieve[j >> 5] |= 1 << (j&31); } } } int i; for(i = 0; count < n; ++i) { count += popCount(~sieve[i]); } --i; int mask = ~sieve[i]; int p; for(p = 31; count >= n; --p) { count -= (mask >> p) & 1; } return 3*(p+(i<<5))+7+(p&1); } private static final int[] TEST_BASE = { 2, 7, 61 }; private static final int NUM_BASES = 3; private static boolean isPrime(int n) { if ((n & 1) == 0) return n == 2; if (n % 3 == 0) return n == 3; int step = 4, m; boolean onlyTD; if (n < 40000) { m = (int)Math.sqrt(n) + 1; onlyTD = true; } else { m = 100; onlyTD = false; } for(int i = 5; i < m; step = 6-step, i += step) { if (n % i == 0) { return false; } } if (onlyTD) { return true; } long md = n, n1 = n-1, exp = n-1; int s = 0; do { ++s; exp >>= 1; }while((exp & 1) == 0); // now n-1 = 2^s * exp for(int i = 0; i < NUM_BASES; ++i) { long r = modPow(TEST_BASE[i],exp,md); if (r == 1) continue; int j; for(j = s; j > 0; --j){ if (r == n1) break; r = (r * r) % md; } if (j == 0) return false; } return true; } private static long modPow(long base, long exponent, long modulus) { if (exponent == 0) return 1; if (exponent < 0) throw new IllegalArgumentException("Can't handle negative exponents"); if (modulus < 0) modulus = -modulus; base %= modulus; if (base < 0) base += modulus; long aux = 1; while(exponent > 1) { if ((exponent & 1) == 1) { aux = (aux * base) % modulus; } base = (base * base) % modulus; exponent >>= 1; } return (aux * base) % modulus; } }
mit
xsoameix/utfconv
utfconv.go
822
package utfconv import ( "unicode/utf16" "unicode/utf8" "encoding/binary" ) const ( replacementChar = '\uFFFD' ) func Read(charset string, data []byte) string { switch charset { case "utf8": var runes []rune for i := 0; i < len(data); { r,size := utf8.DecodeRune(data[i:]) if r != utf8.RuneError { runes = append(runes, r) i += size } } return string(runes) case "utf16le": uint16s := make([]uint16, len(data)/2) for i := 0; i < len(uint16s); i++ { uint16s[i] = binary.LittleEndian.Uint16(data[i*2:]) } return string(utf16.Decode(uint16s)) case "utf16be": uint16s := make([]uint16, len(data)/2) for i := 0; i < len(uint16s); i++ { uint16s[i] = binary.BigEndian.Uint16(data[i*2:]) } return string(utf16.Decode(uint16s)) } return string([]rune{replacementChar}) }
mit
robbytobby/kavau
spec/policies/string_setting_policy_spec.rb
599
require 'rails_helper' RSpec.describe StringSettingPolicy do subject { StringSettingPolicy.new(user, setting) } let(:setting) { create(:string_setting) } context "for an Admin" do let(:user){ create :admin } permits :all, except: [:show, :new, :edit, :create] end [:accountant, :user].each do |role| context "for a #{role}" do let(:user){ create role } permits :none end end describe "permitted params" do let(:user){ create :admin } it "premitted params are [:value]" do expect(subject.permitted_params).to eq [:value] end end end
mit
Tjoosten/dbutil-package
src/Controllers/DbUtilFunctions.php
2290
<?php namespace Hopp\DbUtil\Controllers; class DbUtilFunctions { /** * Drop a table. * * @param string $table * @return void */ public static function drop($table, $connection = null) { \DB::connection($connection)->getPdo()->query('drop table '.$table); } /** * Truncate a table. * * @param string $table * @return void */ public static function truncate($table, $connection = null) { \DB::connection($connection)->getPdo()->query('truncate '.$table); } /** * Optimize a table. * * @param string $table * @return void */ public static function optimize($table, $connection = null) { \DB::connection($connection)->getPdo()->query('optimize table '.$table); } /** * Get array of tables columns. * * @param string $table * @param string $connection * @return array */ public static function columns($table, $connection = null) { // query the pdo $result = \DB::connection($connection)->getPdo()->query('show columns from '.$table); // build array $columns = array(); while ($row = $result->fetch(\PDO::FETCH_NUM)) { $columns[] = $row[0]; } // return return $columns; } /** * Get array of database tables. * * @param string $connection * @return array */ public static function tables($connection = null) { // capture pdo $pdo = \DB::connection($connection)->getPdo(); // run query $result = $pdo->query('show tables'); // build array $tables = array(); while ($row = $result->fetch(\PDO::FETCH_NUM)) { $tables[] = $row[0]; } // return return $tables; } /** * Repair table. */ public static function repaire($table) { \DB::connection($connection)->getPdo()->query('repair table '.$table); } /** * Check if table exists. * * @param string $table * @return boolean */ public static function exists($table) { return in_array($table, static::tables()); } }
mit
jwoertink/jko_api
lib/jko_api/responder.rb
1618
module JkoApi class Responder < ActionController::Responder protected def display(model, *args) options[:user] ||= controller.current_user options[:wrap] ||= controller.wrap options[:representer] ||= controller.representer if first_model = Array.wrap(model).first options[:wrap] ||= first_model.class.table_name end options[:wrap] || raise('set the `wrap` in the controller') representer = options[:representer] || first_model.representer if Array === model || ActiveRecord::Relation === model representer = representer.for_collection end super representer.prepare(model), *args end def api_behavior raise MissingRenderer.new(format) unless has_renderer? if put? display resource, status: :ok, location: api_location elsif delete? display resource, status: :ok else super end end def api_location if !options[:location] && controller.controller_name.starts_with?('user_') options[:location] = user_resource_api_location else super end end def user_resource_api_location url_helpers = Rails.application.routes.url_helpers url_method = controller.controller_name url_method = url_method.singularize unless resources.many? url_method = url_method + '_url' if resources.many? url_helpers.public_send url_method else url_helpers.public_send url_method, resource end end def json_resource_errors resource.errors end end end
mit
swimlane/ngx-ui
src/app/forms/toggle-page/toggle-page.component.ts
378
import { ChangeDetectionStrategy, Component } from '@angular/core'; @Component({ selector: 'app-toggle-page', templateUrl: './toggle-page.component.html', changeDetection: ChangeDetectionStrategy.OnPush }) export class TogglePageComponent { toggleChk = true; onToggleChange(event) { // eslint-disable-next-line no-console console.log('check?', event); } }
mit
Deathangel908/djangochat
frontend/src/ts/classes/DefaultStore.ts
29832
import Vue from 'vue'; import Vuex from 'vuex'; import loggerFactory from '@/ts/instances/loggerFactory'; import { ChannelModel, ChannelsDictModel, ChannelsDictUIModel, ChannelUIModel, CurrentUserInfoModel, CurrentUserInfoWoImage, CurrentUserSettingsModel, EditingMessage, GrowlModel, GrowlType, IncomingCallModel, Location, MessageModel, MessageStatus, PastingTextAreaElement, ReceivingFile, RoomDictModel, RoomModel, RoomSettingsModel, SendingFile, SendingFileTransfer, SexModelString, UserDictModel, UserModel } from '@/ts/types/model'; import { AddMessagesDTO, AddSendingFileTransfer, BooleanIdentifier, IStorage, LiveConnectionLocation, MarkMessageAsRead, MediaIdentifier, MessagesLocation, NumberIdentifier, PrivateRoomsIds, RemoveMessageProgress, RoomLogEntry, RoomMessageIds, RoomMessagesIds, SetCallOpponent, SetDevices, SetFileIdsForMessage, SetMessageProgress, SetMessageProgressError, SetOpponentAnchor, SetOpponentVoice, SetReceivingFileStatus, SetReceivingFileUploaded, SetRoomsUsers, SetSearchStateTo, SetSearchTextTo, SetSendingFileStatus, SetSendingFileUploaded, SetUploadProgress, SetUploadXHR, ShareIdentifier, StringIdentifier } from '@/ts/types/types'; import { SetStateFromStorage, SetStateFromWS } from '@/ts/types/dto'; import {encodeHTML} from '@/ts/utils/htmlApi'; import { ACTIVE_ROOM_ID_LS_NAME, ALL_ROOM_ID, SHOW_I_TYPING_INTERVAL } from '@/ts/utils/consts'; import { Action, Module, Mutation, VuexModule } from 'vuex-module-decorators'; const logger = loggerFactory.getLogger('store'); Vue.use(Vuex); function sleep(ms: number) { return new Promise((resolve) => setTimeout(resolve, ms)); } const mediaLinkIdGetter: Function = (function () { let i = 0; return function () { return String(i++); }; })(); export const vueStore = new Vuex.Store({ state: {}, mutations: {}, actions: {} }); function Validate(target: unknown, propertyKey: string, descriptor: PropertyDescriptor) { const original = descriptor.value; descriptor.value = function (...args: unknown[]) { try { original.apply(this, args); } catch (e) { logger.warn(`Invalid temporal store structure.${propertyKey} {} {}`, args, JSON.parse(JSON.stringify(this)) )(); } }; } const SHOW_I_TYPING_INTERVAL_SHOW = SHOW_I_TYPING_INTERVAL * 1.5; @Module({ dynamic: true, namespaced: true, name: 'default', store: vueStore }) export class DefaultStore extends VuexModule { public storage!: IStorage; // We proxy this as soon as we created Storage public isOnline: boolean = false; public growls: GrowlModel[] = []; public pastingTextAreaQueue: PastingTextAreaElement[] = []; public incomingCall: IncomingCallModel | null = null; public microphones: { [id: string]: string } = {}; public speakers: { [id: string]: string } = {}; public webcams: { [id: string]: string } = {}; public activeRoomId: number | null = null; public userInfo: CurrentUserInfoModel | null = null; public userSettings: CurrentUserSettingsModel | null = null; public allUsersDict: UserDictModel = {}; public regHeader: string | null = null; public onlineDict: Record<string, string[]> = {}; public roomsDict: RoomDictModel = {}; public channelsDict: ChannelsDictModel = {}; public mediaObjects: { [id: string]: MediaStream } = {}; public isCurrentWindowActive: boolean = true; public currentChatPage: 'rooms' | 'chat' = 'chat'; public get getStorage() { // not reactive state is not available outside return this.storage; } get userName(): (id: number) => string { return (id: number): string => this.allUsersDict[id].user; } get privateRooms(): RoomModel[] { const roomModels: RoomModel[] = this.roomsArray.filter(r => !r.name && !r.channelId); logger.debug('privateRooms {} ', roomModels)(); return roomModels; } get online(): number[] { return Object.keys(this.onlineDict).map(a => parseInt(a, 10)); } get calculatedMessagesForRoom() : (roomId: number) => any[] { return (roomId: number): any[] => { let room = this.roomsDict[roomId]; let roomLog = room.roomLog; if (!this.userSettings?.onlineChangeSound) { roomLog = roomLog.filter(l => l.action !== 'appeared online' && l.action !== 'gone offline') } let newArray: any[] = roomLog.map(value => ({ isUserAction: true, ...value })); newArray.push(...room.changeName.map(value => ({isChangeName: true, ...value}))); let dates: {[id: string]: boolean} = {}; let messageDict: Record<number, {parent?: MessageModel, messages: (MessageModel|ReceivingFile|SendingFile)[]}> = {}; for (let m in room.messages) { let message = room.messages[m]; if (message.parentMessage) { if (!messageDict[message.parentMessage]) { messageDict[message.parentMessage] = {messages: []} } messageDict[message.parentMessage].messages.push(message) } else { if (!messageDict[message.id]) { messageDict[message.id] = {messages: []} } messageDict[message.id].parent = message; let d = new Date(message.time).toDateString(); if (!dates[d]) { dates[d] = true; newArray.push({fieldDay: d, time: Date.parse(d)}); } } } for (let m in room.sendingFiles) { let sendingFile: SendingFile = room.sendingFiles[m]; if (sendingFile.threadId) { if (messageDict[sendingFile.threadId]) { messageDict[sendingFile.threadId].messages.push(sendingFile); } else { logger.warn(`Receiving file {} won't be dispayed as thread ${sendingFile.threadId} is not loaded yet`)(); } } else { newArray.push(sendingFile); } } for (let m in room.receivingFiles) { let receivingFile: ReceivingFile = room.receivingFiles[m]; if (receivingFile.threadId) { if (messageDict[receivingFile.threadId]) { messageDict[receivingFile.threadId].messages.push(receivingFile); } else { logger.warn(`Receiving file {} won't be displayed as thread ${receivingFile.threadId} is not loaded yet`)(); } } else { newArray.push(receivingFile); } } Object.values(messageDict).forEach(v => { if (v.messages.length || v.parent?.isThreadOpened || (v.parent && v.parent.threadMessagesCount > 0)) { if (v.parent) { v.messages.sort((a, b) => a.time > b.time ? 1 : a.time < b.time ? -1 : 0); newArray.push({parent: v.parent, thread: true, messages: v.messages, time: v.parent.time}); } else { logger.warn(`Skipping rendering messages ${v.messages.map(m => (m as MessageModel).id)} as parent is not loaded yet`)() } } else { newArray.push(v.parent) } }); newArray.sort((a, b) => a.time > b.time ? 1 : a.time < b.time ? -1 : 0); logger.debug("Reevaluating messages in room #{}: {}", room.id, newArray)(); return newArray; } } get channelsDictUI(): ChannelsDictUIModel { let result : ChannelsDictUIModel = this.roomsArray.reduce((dict, current: RoomModel) => { let channelId = current.channelId; if (channelId) { if (!dict[channelId]) { let channel = this.channelsDict[channelId]; if (!channel) { throw Error(`Unknown channel ${channelId}`) } dict[channelId] = { id: channel.id, expanded: channel.expanded, rooms: [], mainRoom: null!, name: channel.name, creator: channel.creator, }; } if (current.isMainInChannel) { dict[channelId].mainRoom = current; // TODO throw error on invalid structure } else { dict[channelId].rooms.push(current); } } return dict; } , {} as ChannelsDictUIModel) const allChannels: ChannelsDictUIModel = Object.keys(this.channelsDict) .filter(k => !result[k]).reduce(((previousValue, currentValue) => { previousValue[currentValue] = { ...this.channelsDict[currentValue], rooms: [], mainRoom: null!, }; return previousValue; }), result); logger.debug('Channels dict {} ', allChannels)(); return allChannels; } get channels(): ChannelUIModel[] { return Object.values(this.channelsDictUI); } get myId(): number | null { return this.userInfo?.userId ?? null; } get privateRoomsUsersIds(): PrivateRoomsIds { const roomUsers: { [id: number]: number } = {}; const userRooms: { [id: number]: number } = {}; if (this.userInfo) { const myId = this.myId; this.privateRooms.forEach((r: RoomModel) => { const anotherUId = myId === r.users[0] && r.users.length === 2 ? r.users[1] : r.users[0]; roomUsers[r.id] = anotherUId; userRooms[anotherUId] = r.id; }); } return {roomUsers, userRooms}; } get roomsArray(): RoomModel[] { const anies = Object.values(this.roomsDict); logger.debug('roomsArray {}', anies)(); return anies; } get usersArray(): UserModel[] { const res: UserModel[] = Object.values(this.allUsersDict); logger.debug('usersArray {}', res)(); return res; } get activeRoom(): RoomModel | null { if (this.activeRoomId && this.roomsDict) { return this.roomsDict[this.activeRoomId]; } else { return null; } } get activeRoomOnline(): string[] { let online: string[] = []; if (this.activeRoom) { this.activeRoom.users.forEach(u => { if (this.onlineDict[u]) { online.push(...this.onlineDict[u]); } }); } return online; } @Mutation public setMessageProgress(payload: SetMessageProgress) { const transfer = this.roomsDict[payload.roomId].messages[payload.messageId].transfer; if (transfer && transfer.upload) { transfer.upload.uploaded = payload.uploaded; } else { throw Error(`Transfer upload doesn't exist ${JSON.stringify(this.state)} ${JSON.stringify(payload)}`); } } @Mutation public setCurrentChatPage(currentChatPage: 'rooms' | 'chat') { this.currentChatPage = currentChatPage; } @Mutation public markMessageAsRead(payload: MarkMessageAsRead) { this.roomsDict[payload.roomId].messages[payload.messageId].isHighlighted = false; } @Mutation public setStorage(payload: IStorage) { this.storage = payload; } @Mutation public setUploadXHR(payload: SetUploadXHR) { const message = this.roomsDict[payload.roomId].messages[payload.messageId]; if (message.transfer) { message.transfer.xhr = payload.xhr; } else { throw Error(`Transfer upload doesn't exist ${JSON.stringify(this.state)} ${JSON.stringify(payload)}`); } } @Mutation public setUploadProgress(payload: SetUploadProgress) { const message = this.roomsDict[payload.roomId].messages[payload.messageId]; if (message.transfer) { message.transfer.upload = payload.upload; } else { throw Error(`Transfer upload doesn't exist ${JSON.stringify(this.state)} ${JSON.stringify(payload)}`); } } @Mutation public setIncomingCall(payload: IncomingCallModel | null) { this.incomingCall = payload; } @Mutation @Validate public setCallOpponent(payload: SetCallOpponent) { if (payload.callInfoModel) { Vue.set(this.roomsDict[payload.roomId].callInfo.calls, payload.opponentWsId, payload.callInfoModel); } else { Vue.delete(this.roomsDict[payload.roomId].callInfo.calls, payload.opponentWsId); } } @Mutation @Validate public setOpponentVoice(payload: SetOpponentVoice) { this.roomsDict[payload.roomId].callInfo.calls[payload.opponentWsId].opponentCurrentVoice = payload.voice; } @Mutation public setOpponentAnchor(payload: SetOpponentAnchor) { let key = null; for (let k in this.mediaObjects) { if (this.mediaObjects[k] === payload.anchor) { key = k; } } if (!key) { // TODO do we need to fire watch if track added but stream hasn't changed? let key = mediaLinkIdGetter(); this.roomsDict[payload.roomId].callInfo.calls[payload.opponentWsId].mediaStreamLink = key; Vue.set(this.mediaObjects, key, payload.anchor); } } @Mutation public addSendingFile(payload: SendingFile) { Vue.set(this.roomsDict[payload.roomId].sendingFiles, payload.connId, payload); } @Mutation public expandChannel(channelid: number) { this.channelsDict[channelid].expanded = !this.channelsDict[channelid].expanded; } @Mutation public setCurrentMicLevel(payload: NumberIdentifier) { this.roomsDict[payload.id].callInfo.currentMicLevel = payload.state; } @Mutation public setCurrentMic(payload: StringIdentifier) { this.roomsDict[payload.id].callInfo.currentMic = payload.state; } @Mutation public setIsCurrentWindowActive(payload: boolean) { this.isCurrentWindowActive = payload; } @Mutation public setCurrentSpeaker(payload: StringIdentifier) { this.roomsDict[payload.id].callInfo.currentSpeaker = payload.state; } @Mutation public setCurrentWebcam(payload: StringIdentifier) { this.roomsDict[payload.id].callInfo.currentWebcam = payload.state; } @Mutation public setMicToState(payload: BooleanIdentifier) { this.roomsDict[payload.id].callInfo.showMic = payload.state; } @Mutation public setVideoToState(payload: ShareIdentifier) { const ci = this.roomsDict[payload.id].callInfo; ci.shareScreen = false; ci.sharePaint = false; ci.showVideo = false; if (payload.type === 'desktop') { ci.shareScreen = payload.state; } else if (payload.type === 'webcam') { ci.showVideo = payload.state; } else if (payload.type === 'paint') { ci.sharePaint = payload.state; } } @Mutation public setDevices(payload: SetDevices) { this.microphones = payload.microphones; this.webcams = payload.webcams; this.speakers = payload.speakers; if (this.roomsDict[payload.roomId].callInfo) { if (Object.keys(payload.microphones).length === 0) { this.roomsDict[payload.roomId].callInfo.showMic = false; } if (Object.keys(payload.webcams).length === 0) { this.roomsDict[payload.roomId].callInfo.showVideo = false; } } } @Mutation public setCallActiveToState(payload: BooleanIdentifier) { this.roomsDict[payload.id].callInfo.callActive = payload.state; } @Mutation @Validate public setLocalStreamSrc(payload: MediaIdentifier) { const key: string = mediaLinkIdGetter(); Vue.set(this.mediaObjects, key, payload.media); this.roomsDict[payload.id].callInfo.mediaStreamLink = key; } @Mutation public addReceivingFile(payload: ReceivingFile) { Vue.set(this.roomsDict[payload.roomId].receivingFiles, payload.connId, payload); } @Mutation @Validate public addSendingFileTransfer(payload: AddSendingFileTransfer) { Vue.set(this.roomsDict[payload.roomId].sendingFiles[payload.connId].transfers, payload.transferId, payload.transfer); } @Mutation public setReceivingFileStatus(payload: SetReceivingFileStatus) { const receivingFile: ReceivingFile = this.roomsDict[payload.roomId].receivingFiles[payload.connId]; receivingFile.status = payload.status; if (payload.error !== undefined) { receivingFile.error = payload.error; } if (payload.anchor !== undefined) { receivingFile.anchor = payload.anchor; } } @Mutation @Validate public setSendingFileStatus(payload: SetSendingFileStatus) { const transfer: SendingFileTransfer = this.roomsDict[payload.roomId].sendingFiles[payload.connId].transfers[payload.transfer]; transfer.status = payload.status; if (payload.error !== undefined) { transfer.error = payload.error; } } @Mutation public setSendingFileUploaded(payload: SetSendingFileUploaded) { const transfer: SendingFileTransfer = this.roomsDict[payload.roomId].sendingFiles[payload.connId].transfers[payload.transfer]; transfer.upload.uploaded = payload.uploaded; } @Mutation public setReceivingFileUploaded(payload: SetReceivingFileUploaded) { const transfer: ReceivingFile = this.roomsDict[payload.roomId].receivingFiles[payload.connId]; transfer.upload.uploaded = payload.uploaded; } @Mutation public setMessagesStatus( { roomId, messagesIds, status, }: { roomId: number; messagesIds: number[]; status: MessageStatus; } ) { let ids = Object.values(this.roomsDict[roomId].messages) .filter(m => messagesIds.includes(m.id)) .map(m => { m.status = status; return m.id; }); if (ids.length) { this.storage.setMessagesStatus(ids, status); } } // resetNewMessagesCount(roomId: number) { // this.roomsDict[roomId].newMessagesCount = 0; // } @Mutation public removeMessageProgress(payload: RemoveMessageProgress) { const message: MessageModel = this.roomsDict[payload.roomId].messages[payload.messageId]; message.transfer!.upload = null; } @Mutation public setMessageProgressError(payload: SetMessageProgressError) { const mm: MessageModel = this.roomsDict[payload.roomId].messages[payload.messageId]; mm.transfer!.error = payload.error; } @Mutation public setMessageFileIds(payload: SetFileIdsForMessage) { const mm: MessageModel = this.roomsDict[payload.roomId].messages[payload.messageId]; if (!mm.files) { throw Error(`Message ${payload.messageId} in room ${payload.roomId} doesn't have files`); } Object.keys(payload.fileIds).forEach(symb => { mm.files![symb].fileId = payload.fileIds[symb].fileId || null; mm.files![symb].previewFileId = payload.fileIds[symb].previewFileId || null; }); this.storage.updateFileIds(payload); } @Mutation public addMessage(m: MessageModel) { const om: { [id: number]: MessageModel } = this.roomsDict[m.roomId].messages; // if this message is in thread // and parent message already loaded (so its threadMessageId is not actualanymore) // and this message is a new one (not syncing current message) if (m.parentMessage && om[m.parentMessage] && !om[m.id] // and this message is not from us (otherwise we already increased message count when sending it and storing in store) && !(m.userId === this.userInfo?.userId && m.id > 0)) { om[m.parentMessage].threadMessagesCount++; this.storage.setThreadMessageCount(m.parentMessage, om[m.parentMessage].threadMessagesCount); } Vue.set(om, String(m.id), m); this.storage.saveMessage(m); } // we're saving it to database, we restored this message from. // seems like we can't split 2 methods, since 1 should be in actions // and one in mutation, but storage is not available in actions @Mutation public addMessageWoDB(m: MessageModel) { // calling mutation from another mutation is not allowed in vuex // https://github.com/championswimmer/vuex-module-decorators/issues/363 const om: { [id: number]: MessageModel } = this.roomsDict[m.roomId].messages; Vue.set(om, String(m.id), m); } @Mutation public addLiveConnectionToRoom(m: LiveConnectionLocation) { if (this.roomsDict[m.roomId].p2pInfo.liveConnections.indexOf(m.connection) >= 0) { throw Error('This connection is already here'); } this.roomsDict[m.roomId].p2pInfo.liveConnections.push(m.connection); } @Mutation public removeLiveConnectionToRoom(m: LiveConnectionLocation) { let indexOf = this.roomsDict[m.roomId].p2pInfo.liveConnections.indexOf(m.connection); if (indexOf < 0) { throw Error('This connection is not present'); } this.roomsDict[m.roomId].p2pInfo.liveConnections.splice(indexOf, 1); } @Mutation public markMessageAsSent(m: RoomMessagesIds) { let markSendingIds: number[] = [] m.messagesId.forEach(messageId => { let message = this.roomsDict[m.roomId].messages[messageId]; if (message.status === 'sending') { message.status = 'on_server'; markSendingIds.push(messageId); } }); this.storage.markMessageAsSent(markSendingIds); } @Mutation public deleteMessage(rm: RoomMessageIds) { let messages = this.roomsDict[rm.roomId].messages; Vue.delete(messages, String(rm.messageId)); Object.values(messages) .filter(m => m.parentMessage === rm.messageId) .forEach(a => a.parentMessage = rm.newMessageId); this.storage.deleteMessage(rm.messageId, rm.newMessageId); } @Mutation public addMessages(ml: AddMessagesDTO) { const om: { [id: number]: MessageModel } = this.roomsDict[ml.roomId].messages; if (ml.syncingThreadMessageRequired) { const messageWithParent: Record<string, number> = {}; ml.messages.filter(m => m.parentMessage && !om[m.id] && om[m.parentMessage]).forEach(m => { if (!messageWithParent[m.parentMessage!]) { messageWithParent[m.parentMessage!] = 0; } messageWithParent[m.parentMessage!]++; }) Object.entries(messageWithParent).forEach(([parentRoomId, amountNewmessages]) => { const roomId = parseInt(parentRoomId); om[roomId].threadMessagesCount += amountNewmessages; this.storage.setThreadMessageCount(roomId, om[roomId].threadMessagesCount); }) } ml.messages.forEach(m => { Vue.set(om, String(m.id), m); }); this.storage.saveMessages(ml.messages); } @Mutation public addSearchMessages(ml: MessagesLocation) { const om: Record<number, MessageModel> = this.roomsDict[ml.roomId].search.messages; ml.messages.forEach(m => { Vue.set(om, String(m.id), m); }); } @Mutation public setSearchTextTo(ml: SetSearchTextTo) { this.roomsDict[ml.roomId].search.messages = []; this.roomsDict[ml.roomId].search.searchText = ml.searchText; this.roomsDict[ml.roomId].search.locked = false; } @Mutation public setEditedMessage(editedMessage: EditingMessage) { this.roomsDict[editedMessage.roomId].messages[editedMessage.messageId].isEditingActive = editedMessage.isEditingNow; } @Mutation public setCurrentThread(editingThread: EditingMessage) { let m: MessageModel = this.roomsDict[editingThread.roomId].messages[editingThread.messageId]; m.isThreadOpened = editingThread.isEditingNow; } @Mutation public setSearchStateTo(payload: SetSearchStateTo) { this.roomsDict[payload.roomId].search.locked = payload.lock; } @Mutation public toogleSearch(roomId: number) { this.roomsDict[roomId].search.searchActive = !this.roomsDict[roomId].search.searchActive; } @Mutation public setAllLoaded(roomId: number) { this.roomsDict[roomId].allLoaded = true; } @Mutation public setRoomSettings(srm: RoomSettingsModel) { const room = this.roomsDict[srm.id]; if (room.name !== srm.name) { room.changeName.push({ newName: srm.name, oldName: room.name, time: Date.now() }); } room.notifications = srm.notifications; room.volume = srm.volume; room.name = srm.name; room.p2p = srm.p2p; room.channelId = srm.channelId; room.isMainInChannel = srm.isMainInChannel; this.storage.updateRoom(srm); } @Mutation public clearMessages() { for (const m in this.roomsDict) { this.roomsDict[m].messages = {}; this.roomsDict[m].allLoaded = false; } this.storage.clearMessages(); } @Mutation public deleteRoom(roomId: number) { Vue.delete(this.roomsDict, String(roomId)); this.storage.deleteRoom(roomId); } @Mutation public setRoomsUsers(ru: SetRoomsUsers) { this.roomsDict[ru.roomId].users = ru.users; this.storage.saveRoomUsers(ru); } @Mutation public setIsOnline(isOnline: boolean) { this.isOnline = isOnline; } @Mutation public addGrowl(growlModel: GrowlModel) { this.growls.push(growlModel); } @Mutation public removeGrowl(growlModel: GrowlModel) { const index = this.growls.indexOf(growlModel, 0); if (index > -1) { this.growls.splice(index, 1); } } @Mutation public setActiveRoomId(id: number) { this.activeRoomId = id; localStorage.setItem(ACTIVE_ROOM_ID_LS_NAME, String(id)); } @Mutation public setRegHeader(regHeader: string) { this.regHeader = regHeader; } @Mutation public addUser(u: UserModel) { Vue.set(this.allUsersDict, String(u.id), u); this.storage.saveUser(u); } @Mutation public addRoomLog(payload: RoomLogEntry) { payload.roomIds.forEach(r => { this.roomsDict[r].roomLog.push(payload.roomLog); }); } @Mutation public setCallActiveButNotJoinedYet(payload: BooleanIdentifier) { this.roomsDict[payload.id].callInfo.callActiveButNotJoinedYet = payload.state; } @Mutation public setOnline(ids: Record<string, string[]>) { Object.keys(ids).forEach(k => { if (ids[k].length === 0) { delete ids[k]; } }); this.onlineDict = ids; } @Mutation public setUser(user: {id: number; sex: SexModelString; user: string; image: string}) { this.allUsersDict[user.id].user = user.user; this.allUsersDict[user.id].sex = user.sex; this.allUsersDict[user.id].image = user.image; this.storage.saveUser(this.allUsersDict[user.id]); } @Mutation public setUserInfo(userInfo: CurrentUserInfoWoImage) { let image: string|null = this.userInfo?.image || null; let newUserInfo: CurrentUserInfoModel= {...userInfo, image} this.userInfo = newUserInfo; this.storage.setUserProfile(this.userInfo); } @Mutation public setUserSettings(userInfo: CurrentUserSettingsModel) { this.userSettings = userInfo; this.storage.setUserSettings(userInfo); } @Mutation public setUserImage(image: string) { this.userInfo!.image = image; this.storage.setUserProfile(this.userInfo!); } @Mutation public setPastingQueue(ids: PastingTextAreaElement[]) { this.pastingTextAreaQueue = ids; } @Mutation public setStateFromWS(state: SetStateFromWS) { logger.debug('init store from WS')(); this.roomsDict = state.roomsDict; this.channelsDict = state.channelsDict; this.allUsersDict = state.allUsersDict; this.storage.setChannels(Object.values(this.channelsDict)); this.storage.setRooms(Object.values(this.roomsDict )); this.storage.setUsers(Object.values(this.allUsersDict)); } @Mutation public setCountryCode(locations: Record<string, Location>) { Object.values(this.allUsersDict).forEach(u => { if (locations[u.id]) { u.location = locations[u.id]; } }) this.storage.setUsers(Object.values(this.allUsersDict)); } @Mutation // called while restoring from db public setStateFromStorage(setRooms: SetStateFromStorage) { logger.debug('init store from database')(); this.roomsDict = setRooms.roomsDict; this.userInfo = setRooms.profile; this.userSettings = setRooms.settings; this.allUsersDict = setRooms.allUsersDict; this.channelsDict = setRooms.channelsDict; } @Mutation public addRoom(room: RoomModel) { Vue.set(this.roomsDict, String(room.id), room); this.storage.saveRoom(room); } @Mutation public addChannel(channel: ChannelModel) { Vue.set(this.channelsDict, String(channel.id), channel); this.storage.saveChannel(channel); } @Mutation public deleteChannel(channelId: number) { Vue.delete(this.channelsDict, String(channelId)); this.storage.deleteChannel(channelId); } @Mutation public setShowITypingUser({userId, roomId, date}: {userId: number; roomId: number; date: number}) { if (date === 0) { Vue.delete(this.roomsDict[roomId].usersTyping, userId); } else { Vue.set(this.roomsDict[roomId].usersTyping, userId, date); } } @Mutation public clearGrowls() { this.growls = []; } @Mutation public logout() { this.userInfo = null; this.userSettings = null; this.roomsDict = {}; this.allUsersDict = {}; this.onlineDict = {}; this.activeRoomId = null; localStorage.clear(); // remove LAST_SYNC, serviceWorkerUrl, sessionId, smileyRecent and other trash this.storage.clearStorage(); } @Action public async showGrowl({html, type, time}: { html: string; type: GrowlType; time: number }) { const growl: GrowlModel = {id: Date.now(), html, type}; this.addGrowl(growl); await sleep(time); this.removeGrowl(growl); } @Action public async showUserIsTyping({userId, roomId}: {userId: number; roomId: number}) { let date = Date.now(); this.setShowITypingUser({userId, roomId, date}); await sleep(SHOW_I_TYPING_INTERVAL_SHOW); // lets say 1 second ping if (this.roomsDict[roomId].usersTyping[userId] === date) { this.setShowITypingUser({userId, roomId, date: 0}); } } @Action public async growlErrorRaw(html: string) { await this.showGrowl({html, type: GrowlType.ERROR, time: 6000}); } @Action public async growlError(title: string) { await this.showGrowl({html: encodeHTML(title), type: GrowlType.ERROR, time: 6000}); } @Action public async growlInfo(title: string) { await this.showGrowl({html: encodeHTML(title), type: GrowlType.INFO, time: 5000}); } @Action public async growlSuccess(title: string) { await this.showGrowl({html: encodeHTML(title), type: GrowlType.SUCCESS, time: 4000}); } }
mit
gilramir/argparse
v2/examples/example1/main.go
1363
// Copyright (c) 2021 by Gilbert Ramirez <[email protected]> package main import ( "fmt" "time" "github.com/gilramir/argparse/v2" ) type MyOptions struct { Count int Expiration time.Duration Verbose bool Names []string } func main() { opts := &MyOptions{} ap := argparse.New(&argparse.Command{ Name: "Example 1", Description: "This is an example program", Values: opts, }) // These are switch arguments ap.Add(&argparse.Argument{ Switches: []string{"--count"}, MetaVar: "N", Help: "How many items", }) ap.Add(&argparse.Argument{ Switches: []string{"--expiration", "-x"}, Help: "How long: #(h|m|s|ms|us|ns)", }) ap.Add(&argparse.Argument{ Switches: []string{"-v", "--verbose"}, Help: "Set verbose mode", }) // This is a positional argument ap.Add(&argparse.Argument{ Name: "names", Help: "Some names passed into the program", // We require one or more names NumArgsGlob: "+", }) // The library handles errors, and -h/--help ap.Parse() fmt.Printf("Verbose is %t\n", opts.Verbose) fmt.Printf("Count is %d\n", opts.Count) if ap.Root.Seen["Expiration"] { fmt.Printf("Expiration: %s\n", opts.Expiration.String()) } fmt.Printf("Number of names: %d\n", len(opts.Names)) for i := 0; i < len(opts.Names); i++ { fmt.Printf("%d. %s\n", i+1, opts.Names[i]) } }
mit
majestrate/nyaa
utils/validator/torrent/helpers.go
1064
package torrentValidator import ( "net/url" "strings" ) // CheckTrackers : Check if there is good trackers in torrent func CheckTrackers(trackers []string) []string { // TODO: move to runtime configuration var deadTrackers = []string{ // substring matches! "://open.nyaatorrents.info:6544", "://tracker.openbittorrent.com:80", "://tracker.publicbt.com:80", "://stats.anisource.net:2710", "://exodus.desync.com", "://open.demonii.com:1337", "://tracker.istole.it:80", "://tracker.ccc.de:80", "://bt2.careland.com.cn:6969", "://announce.torrentsmd.com:8080", "://open.demonii.com:1337", "://tracker.btcake.com", "://tracker.prq.to", "://bt.rghost.net"} var trackerRet []string for _, t := range trackers { urlTracker, err := url.Parse(t) if err == nil { good := true for _, check := range deadTrackers { if strings.Contains(t, check) { good = false break // No need to continue the for loop } } if good { trackerRet = append(trackerRet, urlTracker.String()) } } } return trackerRet }
mit
hhatfield/php-contact-api
vendor/zfcampus/zf-apigility-admin/asset/src/zf-apigility-admin/js/controllers/content-negotiation.js
3588
(function() { 'use strict'; angular.module('ag-admin').controller( 'ContentNegotiationController', function ($scope, $state, $stateParams, $modal, flash, selectors, ContentNegotiationResource, agFormHandler) { var newSelector = { content_name: '', viewModel: '', selectors: {} }; $scope.activeSelector = $stateParams.selector ? $stateParams.selector : ''; $scope.inEdit = !!$stateParams.edit; $scope.showNewSelectorForm = false; $scope.newSelector = JSON.parse(JSON.stringify(newSelector)); $scope.selectors = JSON.parse(JSON.stringify(selectors)); $scope.help = function() { $modal.open({ templateUrl: 'html/modals/help-content-negotiation.html', keyboard: true }); }; $scope.resetNewSelectorForm = function() { agFormHandler.resetForm($scope); $scope.showNewSelectorForm = false; $scope.newSelector = JSON.parse(JSON.stringify(newSelector)); }; $scope.addViewModel = function (viewModel, selector) { selector.selectors[viewModel] = []; $scope.newSelector.viewModel = ''; }; $scope.removeViewModel = function (viewModel, selector) { delete selector.selectors[viewModel]; }; $scope.resetSelectorForm = function (selector) { agFormHandler.resetForm($scope); /* Reset to original values */ var name = selector.content_name; var originalSelector; angular.forEach(selectors, function (value) { if (originalSelector || value.content_name !== name) { return; } originalSelector = value; }); if (! originalSelector) { return; } angular.forEach($scope.selectors, function (value, key) { if (value.content_name !== originalSelector.content_name) { return; } $scope.selectors[key] = originalSelector; }); }; $scope.createSelector = function() { delete $scope.newSelector.viewModel; ContentNegotiationResource.createSelector($scope.newSelector).then( function (selector) { selectors.push(selector); $scope.selectors.push(selector); flash.success = 'New selector created'; $scope.resetNewSelectorForm(); }, function (error) { agFormHandler.reportError(error, $scope); } ); }; $scope.updateSelector = function (selector) { delete selector.viewModel; ContentNegotiationResource.updateSelector(selector).then( function (updated) { agFormHandler.resetForm($scope); /* Update original selector on success, so that view matches */ var updatedSelector = false; angular.forEach(selectors, function (value, key) { if (updatedSelector || value.content_name !== updated.content_name) { return; } selectors[key] = updated; updatedSelector = true; }); flash.success = 'Selector updated'; }, function (error) { agFormHandler.reportError(error, $scope); } ); }; $scope.removeSelector = function (selectorName) { ContentNegotiationResource.removeSelector(selectorName).then(function () { flash.success = 'Selector removed'; ContentNegotiationResource.getList(true).then(function (updatedSelectors) { $state.go($state.current, {}, { reload: true, inherit: true, notify: true }); }); }); }; } ); })();
mit
wolfdale/Spaghetti-code
Golang/2020Go/avg.go
390
package main import "fmt" func main() { var size int fmt.Println("Enter the size of array: ") fmt.Scan(&size) fmt.Println("Enter the array elements: ") // Create the array using make array := make([]int, size) sum := 0 for i := 0; i < size; i++ { fmt.Scan(&array[i]) sum = sum + array[i] } avg := float64(sum) / float64(size) fmt.Printf("\nAverage is : %f \n", avg) }
mit
codem4ster/molecule
app/controllers/molecule_controller.rb
670
# This is the main Controller for molecule it handles SPA requests class MoleculeController < ApplicationController BOTS = %w[Applebot baiduspider Bingbot Googlebot ia_archiver msnbot Naverbot seznambot Slurp teoma Twitterbot Yandex Yeti].freeze def spa return render 'molecule/non-bots' unless bot? Molecule::Session.instance(cookies['_sid']) find_route render 'molecule/bots' end private def bot? request.user_agent =~ /(#{BOTS.join('|')})/ end def find_route router = Router.new router.routes @parts = router.route_store[request.path] raise 'Route cannot found:' + request.path unless @parts end end
mit
Ahmed--Mohsen/leetcode
Median_of_Two_Sorted_Arrays.py
1198
""" There are two sorted arrays nums1 and nums2 of size m and n respectively. Find the median of the two sorted arrays. The overall run time complexity should be O(log (m+n)). """ class Solution: # @return a float def findMedianSortedArrays(self, A, B): m = len(A); n = len(B) # even merged ... take average of middle elements if (m + n) % 2 == 0: return ( self.get_at_k(A, B, (m + n) / 2) + self.get_at_k(A, B, (m + n) / 2 + 1) ) / 2.0 # odd take the middle else: return self.get_at_k(A, B, (m + n) / 2 + 1) #gets the element at position k in the merged array A nad B def get_at_k(self, A, B, k): m = len(A); n = len(B) # the kth element is in place inside b if m == 0: return B[k-1] # the kth element is in place inside a if n == 0: return A[k-1] # kth element is the first in either if k == 1: return min(A[0], B[0]) i = min(m, k / 2) j = min(n, k / 2) # increase B median if A[i-1] > B[j-1]: return self.get_at_k(A[:k-j], B[j:], k - j) # increase A median else: return self.get_at_k(A[i:], B[:k-i], k - i) return 0 s = Solution() print s.findMedianSortedArrays([1], [2,3,4,5,6,7,8])
mit
srpanwar/graph
omukcontrols/Properties/AssemblyInfo.cs
1400
using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; // General Information about an assembly is controlled through the following // set of attributes. Change these attribute values to modify the information // associated with an assembly. [assembly: AssemblyTitle("omukcontrols")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("omukcontrols")] [assembly: AssemblyCopyright("Copyright © 2009")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. [assembly: ComVisible(false)] // The following GUID is for the ID of the typelib if this project is exposed to COM [assembly: Guid("4ba5c51f-422b-44b2-b941-bb48c18787ff")] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Build and Revision Numbers // by using the '*' as shown below: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("1.0.0.0")] [assembly: AssemblyFileVersion("1.0.0.0")]
mit
simosabba/alaska
src/foundation/Alaska.Foundation.Core/Caching/Interfaces/ICacheItemInfo.cs
330
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Alaska.Foundation.Core.Caching.Interfaces { public interface ICacheItemInfo { string Key { get; } TimeSpan Expiration { get; } DateTime ExpirationTime { get; } } }
mit
doctrine/mongodb-odm
tests/Doctrine/ODM/MongoDB/Tests/Functional/FilterTest.php
9746
<?php declare(strict_types=1); namespace Doctrine\ODM\MongoDB\Tests\Functional; use Doctrine\ODM\MongoDB\DocumentNotFoundException; use Doctrine\ODM\MongoDB\Query\FilterCollection; use Doctrine\ODM\MongoDB\Tests\BaseTest; use Documents\Group; use Documents\Profile; use Documents\User; use function sort; class FilterTest extends BaseTest { /** @var array<string, string> */ private $ids; /** @var FilterCollection */ private $fc; public function setUp(): void { parent::setUp(); $this->ids = []; $groupA = new Group('groupA'); $groupB = new Group('groupB'); $profile = new Profile(); $profile->setFirstName('Timothy'); $tim = new User(); $tim->setUsername('Tim'); $tim->setHits(10); $tim->addGroup($groupA); $tim->addGroup($groupB); $tim->setProfile($profile); $this->dm->persist($tim); $john = new User(); $john->setUsername('John'); $john->setHits(10); $this->dm->persist($john); $this->dm->flush(); $this->dm->clear(); $this->ids['tim'] = $tim->getId(); $this->ids['john'] = $john->getId(); $this->fc = $this->dm->getFilterCollection(); } protected function enableUserFilter(): void { $this->fc->enable('testFilter'); $testFilter = $this->fc->getFilter('testFilter'); $testFilter->setParameter('class', User::class); $testFilter->setParameter('field', 'username'); $testFilter->setParameter('value', 'Tim'); } protected function enableGroupFilter(): void { $this->fc->enable('testFilter'); $testFilter = $this->fc->getFilter('testFilter'); $testFilter->setParameter('class', Group::class); $testFilter->setParameter('field', 'name'); $testFilter->setParameter('value', 'groupA'); } protected function enableProfileFilter(): void { $this->fc->enable('testFilter'); $testFilter = $this->fc->getFilter('testFilter'); $testFilter->setParameter('class', Profile::class); $testFilter->setParameter('field', 'firstname'); $testFilter->setParameter('value', 'Something Else'); } public function testRepositoryFind(): void { $this->assertEquals(['John', 'Tim'], $this->getUsernamesWithFind()); $this->enableUserFilter(); $this->dm->clear(); $this->assertEquals(['Tim'], $this->getUsernamesWithFind()); $this->fc->disable('testFilter'); $this->dm->clear(); $this->assertEquals(['John', 'Tim'], $this->getUsernamesWithFind()); } protected function getUsernamesWithFind(): array { $repository = $this->dm->getRepository(User::class); $tim = $repository->find($this->ids['tim']); $john = $repository->find($this->ids['john']); $usernames = []; if (isset($tim)) { $usernames[] = $tim->getUsername(); } if (isset($john)) { $usernames[] = $john->getUsername(); } sort($usernames); return $usernames; } public function testRepositoryFindBy(): void { $this->assertEquals(['John', 'Tim'], $this->getUsernamesWithFindBy()); $this->enableUserFilter(); $this->dm->clear(); $this->assertEquals(['Tim'], $this->getUsernamesWithFindBy()); $this->fc->disable('testFilter'); $this->dm->clear(); $this->assertEquals(['John', 'Tim'], $this->getUsernamesWithFindBy()); } protected function getUsernamesWithFindBy(): array { $all = $this->dm->getRepository(User::class)->findBy(['hits' => 10]); $usernames = []; foreach ($all as $user) { $usernames[] = $user->getUsername(); } sort($usernames); return $usernames; } public function testRepositoryFindOneBy(): void { $this->assertEquals('John', $this->getJohnsUsernameWithFindOneBy()); $this->enableUserFilter(); $this->dm->clear(); $this->assertEquals(null, $this->getJohnsUsernameWithFindOneBy()); $this->fc->disable('testFilter'); $this->dm->clear(); $this->assertEquals('John', $this->getJohnsUsernameWithFindOneBy()); } protected function getJohnsUsernameWithFindOneBy(): ?string { $john = $this->dm->getRepository(User::class)->findOneBy(['id' => $this->ids['john']]); return isset($john) ? $john->getUsername() : null; } public function testRepositoryFindAll(): void { $this->assertEquals(['John', 'Tim'], $this->getUsernamesWithFindAll()); $this->enableUserFilter(); $this->dm->clear(); $this->assertEquals(['Tim'], $this->getUsernamesWithFindAll()); $this->fc->disable('testFilter'); $this->dm->clear(); $this->assertEquals(['John', 'Tim'], $this->getUsernamesWithFindAll()); } protected function getUsernamesWithFindAll(): array { $all = $this->dm->getRepository(User::class)->findAll(); $usernames = []; foreach ($all as $user) { $usernames[] = $user->getUsername(); } sort($usernames); return $usernames; } public function testReferenceMany(): void { $this->assertEquals(['groupA', 'groupB'], $this->getGroupsByReference()); $this->enableGroupFilter(); $this->dm->clear(); $this->assertEquals(['groupA'], $this->getGroupsByReference()); $this->fc->disable('testFilter'); $this->dm->clear(); $this->assertEquals(['groupA', 'groupB'], $this->getGroupsByReference()); } protected function getGroupsByReference(): array { $tim = $this->dm->getRepository(User::class)->find($this->ids['tim']); $groupnames = []; foreach ($tim->getGroups() as $group) { try { $groupnames[] = $group->getName(); } catch (DocumentNotFoundException $e) { //Proxy object filtered } } sort($groupnames); return $groupnames; } public function testReferenceOne(): void { $this->assertEquals('Timothy', $this->getProfileByReference()); $this->enableProfileFilter(); $this->dm->clear(); $this->assertEquals(null, $this->getProfileByReference()); $this->fc->disable('testFilter'); $this->dm->clear(); $this->assertEquals('Timothy', $this->getProfileByReference()); } protected function getProfileByReference(): ?string { $tim = $this->dm->getRepository(User::class)->find($this->ids['tim']); $profile = $tim->getProfile(); try { return $profile->getFirstname(); } catch (DocumentNotFoundException $e) { //Proxy object filtered return null; } } public function testDocumentManagerRef(): void { $this->assertEquals(['John', 'Tim'], $this->getUsernamesWithDocumentManager()); $this->enableUserFilter(); $this->dm->clear(); $this->assertEquals(['Tim'], $this->getUsernamesWithDocumentManager()); $this->fc->disable('testFilter'); $this->dm->clear(); $this->assertEquals(['John', 'Tim'], $this->getUsernamesWithDocumentManager()); } protected function getUsernamesWithDocumentManager(): array { $tim = $this->dm->getReference(User::class, $this->ids['tim']); $john = $this->dm->getReference(User::class, $this->ids['john']); $usernames = []; try { $usernames[] = $tim->getUsername(); } catch (DocumentNotFoundException $e) { //Proxy object filtered } try { $usernames[] = $john->getUsername(); } catch (DocumentNotFoundException $e) { //Proxy object filtered } sort($usernames); return $usernames; } public function testQuery(): void { $this->assertEquals(['John', 'Tim'], $this->getUsernamesWithQuery()); $this->enableUserFilter(); $this->dm->clear(); $this->assertEquals(['Tim'], $this->getUsernamesWithQuery()); $this->fc->disable('testFilter'); $this->dm->clear(); $this->assertEquals(['John', 'Tim'], $this->getUsernamesWithQuery()); } protected function getUsernamesWithQuery(): array { $qb = $this->dm->createQueryBuilder(User::class); $query = $qb->getQuery(); $all = $query->execute(); $usernames = []; foreach ($all as $user) { $usernames[] = $user->getUsername(); } sort($usernames); return $usernames; } public function testMultipleFiltersOnSameField(): void { $this->fc->enable('testFilter'); $testFilter = $this->fc->getFilter('testFilter'); $testFilter->setParameter('class', User::class); $testFilter->setParameter('field', 'username'); $testFilter->setParameter('value', 'Tim'); $this->fc->enable('testFilter2'); $testFilter2 = $this->fc->getFilter('testFilter2'); $testFilter2->setParameter('class', User::class); $testFilter2->setParameter('field', 'username'); $testFilter2->setParameter('value', 'John'); /* These two filters will merge and create a query that requires the * username to equal both "Tim" and "John", which is impossible for a * non-array, string field. No results should be returned. */ $this->assertCount(0, $this->getUsernamesWithFindAll()); } }
mit
almeida-fogo/laravel-modules
src/Modulos/Usuarios/Simples/Views/login.blade.php
1450
@extends("Roots_Templates.master") @section("titulo") LOGIN @endsection @section("css") @endsection @section("conteudo") <form id="loginform" class="form-horizontal form" role="form" action="{{action("UsuarioController@postLogin")}}" method="POST"> {!!csrf_field()!!} @if ($errors->has("email")) <div class="alert alert-danger">{{$errors->first("email")}}</div> @endif <label class="sr-only" for="email">E-mail</label> <div style="margin-bottom: 25px" class="input-group"> <span class="input-group-addon"><i class="glyphicon glyphicon-globe"></i></span> <input class="form-control" type="text" name="email" id="email" value="{{old("email")}}" placeholder="E-mail"/> </div> @if ($errors->has("senha")) <div class="alert alert-danger">{{$errors->first("senha")}}</div> @endif <label class="sr-only" for="senha">Senha</label> <div style="margin-bottom: 25px" class="input-group"> <span class="input-group-addon"><i class="glyphicon icon-lock"></i></span> <input class="form-control senha-input" type="password" name="senha" id="senha" value="{{old("senha")}}" placeholder="Senha"/> <span class="input-group-addon"><input class="senha-check" name="senha_checked" type="checkbox" checked/></span> </div> <div id="btn-form" class="form-group"> <div class="container"> <input class="btn btn-success" type="submit" value="Login"/> </div> </div> </form> @endsection @section("js") @endsection
mit
mmeents/DataMattei
C0DEC0RE/Backup/IReflectionMemberInfo.cs
1564
//=============================================================================== // Microsoft patterns & practices // Object Builder Application Block //=============================================================================== // Copyright © Microsoft Corporation. All rights reserved. // THIS CODE AND INFORMATION IS PROVIDED "AS IS" WITHOUT WARRANTY // OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT // LIMITED TO THE IMPLIED WARRANTIES OF MERCHANTABILITY AND // FITNESS FOR A PARTICULAR PURPOSE. //=============================================================================== using System; using System.Reflection; namespace SiteCore { /// <summary> /// Interface used by the <see cref="ReflectionStrategy{T}"/> base class to encapsulate the information /// required from members that use the strategy. This interface is required because direct access to /// the <see cref="MemberInfo"/> object may not give the desired results. /// </summary> public interface IReflectionMemberInfo<TMemberInfo> { /// <summary> /// Gets the original member info object. /// </summary> TMemberInfo MemberInfo { get; } /// <summary> /// Gets the name of the member. /// </summary> string Name { get; } /// <summary> /// Gets the custom attributes of the member. /// </summary> /// <returns></returns> object[] GetCustomAttributes(Type attributeType, bool inherit); /// <summary> /// Gets the parameters to be passed to the member. /// </summary> /// <returns></returns> ParameterInfo[] GetParameters(); } }
mit
curvedmark/tree-transformer
test/test.js
3546
var assert = require('assert'); var Transformer = require('..'); describe('Transformer', function () { describe('transform a single node', function () { it('should return returned value', function () { var node = { type: 'number', value: 1 }; function MyTransformer() {} MyTransformer.prototype = new Transformer(); MyTransformer.prototype.visit_number = function () { return 1; }; var ret = new MyTransformer().visit(node); assert.equal(ret, 1); }); it('should return null', function () { var node = { type: 'number', value: 1 }; function MyTransformer() {} MyTransformer.prototype = new Transformer(); MyTransformer.prototype.visit_number = function () { return null; }; var ret = new MyTransformer().visit(node); assert.strictEqual(ret, null); }); it('should ignore undefined', function () { var node = { type: 'number', value: 1 }; function MyTransformer() {} MyTransformer.prototype = new Transformer(); MyTransformer.prototype.visit_number = function () {}; var ret = new MyTransformer().visit(node); assert.equal(ret, node); }); }); describe('transform an array of nodes', function () { it('should replace node', function () { var nodes = [ { type: 'number', value: 1 }, { type: 'string', value: 'abc' } ]; function MyTransformer() {} MyTransformer.prototype = new Transformer(); MyTransformer.prototype.visit_node = function (node) { return node.value; }; var ret = new MyTransformer().visit(nodes); assert.deepEqual(ret, [1, 'abc']); }); it('should flatten result array', function () { var nodes = [ { type: 'number', value: 1 }, { type: 'number', value: 3 } ]; function MyTransformer() {} MyTransformer.prototype = new Transformer(); MyTransformer.prototype.visit_number = function (number) { return [number.value, number.value + 1]; }; var ret = new MyTransformer().visit(nodes); assert.deepEqual(ret, [1, 2, 3, 4]); }); it('should remove node when null is returned', function () { var nodes = [ { type: 'number', value: 1 }, { type: 'string', value: 'abc' } ]; function MyTransformer() {} MyTransformer.prototype = new Transformer(); MyTransformer.prototype.visit_number = function () { return null; }; var ret = new MyTransformer().visit(nodes); assert.deepEqual(ret, [{ type: 'string', value: 'abc' }]); }); it('should not remove node if it is null', function () { var nodes = [ null, { type: 'number', value: 1 } ]; function MyTransformer() {} MyTransformer.prototype = new Transformer(); MyTransformer.prototype.visit_number = function () { return null; }; var ret = new MyTransformer().visit(nodes); assert.deepEqual(ret, [null]); }); it('should return node if undefined is returned', function () { var nodes = [ { type: 'number', value: 1 }, { type: 'string', value: 'abc' } ]; function MyTransformer() {} MyTransformer.prototype = new Transformer(); MyTransformer.prototype.visit_number = function () {}; var ret = new MyTransformer().visit(nodes); assert.deepEqual(ret, [ { type: 'number', value: 1 }, { type: 'string', value: 'abc' } ]); }); it('should return node if no corresponding method found', function () { var nodes = [ { type: 'number', value: 1 }, { type: 'string', value: 'abc' } ]; var ret = new Transformer().visit(nodes); assert.equal(ret, nodes); }); }); });
mit
brewdente/AutoWebPerf
MasterDevs.ChromeDevTools/Protocol/CSS/GetMatchedStylesForNodeCommand.cs
749
using MasterDevs.ChromeDevTools; using Newtonsoft.Json; using System.Collections.Generic; namespace MasterDevs.ChromeDevTools.Protocol.CSS { /// <summary> /// Returns requested styles for a DOM node identified by <code>nodeId</code>. /// </summary> [Command(ProtocolName.CSS.GetMatchedStylesForNode)] public class GetMatchedStylesForNodeCommand { /// <summary> /// Gets or sets NodeId /// </summary> public long NodeId { get; set; } /// <summary> /// Gets or sets Whether to exclude pseudo styles (default: false). /// </summary> public bool ExcludePseudo { get; set; } /// <summary> /// Gets or sets Whether to exclude inherited styles (default: false). /// </summary> public bool ExcludeInherited { get; set; } } }
mit
binidini/mstock
members/payments_paypalpro.php
8914
<? $site="paypalpro"; include("../admin/function/db.php"); include("payments_settings.php"); if(!isset($_POST["product_id"]) or !isset($_POST["product_name"]) or !isset($_POST["product_total"]) or !isset($_POST["product_type"])) { exit(); } ?> <?include("../inc/header.php");?> <h1><?=word_lang("payment")?> - Paypal Pro</h1> <? $product_id=(int)$_POST["product_id"]; $product_name=result($_POST["product_name"]); $product_total=$_POST["product_total"]; $product_type=result($_POST["product_type"]); $buyer_info=array(); get_buyer_info($_SESSION["people_id"],$product_id,$product_type); $order_info=array(); get_order_info($product_id,$product_type); //Check if Total is correct if(!check_order_total($product_total,$product_type,$product_id)) { //exit(); } // Sandbox (Test) Mode Trigger $sandbox = true; if(isset($_SERVER["HTTPS"]) and $_SERVER["HTTPS"]=="on") { $sandbox =false; } // PayPal API Credentials $api_username = $sandbox ? 'sales_1312489240_biz_api1.cmsaccount.com' : $site_paypalpro_account; $api_password = $sandbox ? '1312489287' : $site_paypalpro_password; $api_signature = $sandbox ? 'Ai1PaghZh5FmBLCDCTQpwG8jB264AdEdsXj.KitFPISMbvOxfQFeUdj.' : $site_paypalpro_signature; require_once('../admin/plugins/paypal/paypal.nvp.class.php'); // Setup PayPal object $PayPalConfig = array('Sandbox' => $sandbox, 'APIUsername' => $api_username, 'APIPassword' => $api_password, 'APISignature' => $api_signature); $PayPal = new PayPal($PayPalConfig); // Populate data arrays with order data. $DPFields = array( 'paymentaction' => 'Sale', // How you want to obtain payment. Authorization indidicates the payment is a basic auth subject to settlement with Auth & Capture. Sale indicates that this is a final sale for which you are requesting payment. Default is Sale. 'ipaddress' => $_SERVER['REMOTE_ADDR'], // Required. IP address of the payer's browser. 'returnfmfdetails' => '1' // Flag to determine whether you want the results returned by FMF. 1 or 0. Default is 0. ); $CCDetails = array( 'creditcardtype' => result($_POST["card_type"]), // Required. Type of credit card. Visa, MasterCard, Discover, Amex, Maestro, Solo. If Maestro or Solo, the currency code must be GBP. In addition, either start date or issue number must be specified. 'acct' => result($_POST["card_number"]), // Required. Credit card number. No spaces or punctuation. 'expdate' => result($_POST["card_month"]).result($_POST["card_year"]), // Required. Credit card expiration date. Format is MMYYYY 'cvv2' => result($_POST["cvv"]), // Requirements determined by your PayPal account settings. Security digits for credit card. 'startdate' => '', // Month and year that Maestro or Solo card was issued. MMYYYY 'issuenumber' => '' // Issue number of Maestro or Solo card. Two numeric digits max. ); $PayerInfo = array( 'email' => $buyer_info["email"], // Email address of payer. 'payerid' => '', // Unique PayPal customer ID for payer. 'payerstatus' => '', // Status of payer. Values are verified or unverified 'business' => $buyer_info["company"] // Payer's business name. ); $PayerName = array( 'salutation' => '', // Payer's salutation. 20 char max. 'firstname' => $buyer_info["name"], // Payer's first name. 25 char max. 'middlename' => '', // Payer's middle name. 25 char max. 'lastname' => $buyer_info["lastname"], // Payer's last name. 25 char max. 'suffix' => '' // Payer's suffix. 12 char max. ); $BillingAddress = array( 'street' => $buyer_info["billing_address"], // Required. First street address. 'street2' => '', // Second street address. 'city' => $buyer_info["billing_city"], // Required. Name of City. 'state' => '', // Required. Name of State or Province. 'countrycode' => $mcountry_code[$buyer_info["billing_country"]], // Required. Country code. 'zip' => $buyer_info["billing_zipcode"], // Required. Postal code of payer. 'phonenum' => $buyer_info["telephone"] // Phone Number of payer. 20 char max. ); $ShippingAddress = array( 'shiptoname' => $buyer_info["shipping_name"]." ".$buyer_info["shipping_lastname"], // Required if shipping is included. Person's name associated with this address. 32 char max. 'shiptostreet' => $buyer_info["shipping_address"], // Required if shipping is included. First street address. 100 char max. 'shiptostreet2' => '', // Second street address. 100 char max. 'shiptocity' => $buyer_info["shipping_city"], // Required if shipping is included. Name of city. 40 char max. 'shiptostate' => '', // Required if shipping is included. Name of state or province. 40 char max. 'shiptozip' => $buyer_info["shipping_zipcode"], // Required if shipping is included. Postal code of shipping address. 20 char max. 'shiptocountrycode' => $mcountry_code[$buyer_info["shipping_country"]], // Required if shipping is included. Country code of shipping address. 2 char max. 'shiptophonenum' => $buyer_info["telephone"] // Phone number for shipping address. 20 char max. ); $PaymentDetails = array( 'amt' => $order_info["product_total"], // Required. Total amount of order, including shipping, handling, and tax. 'currencycode' => $currency_code1, // Required. Three-letter currency code. Default is USD. 'itemamt' => $order_info["product_subtotal"], // Required if you include itemized cart details. (L_AMTn, etc.) Subtotal of items not including S&H, or tax. 'shippingamt' => $order_info["product_shipping"], // Total shipping costs for the order. If you specify shippingamt, you must also specify itemamt. 'handlingamt' => '', // Total handling costs for the order. If you specify handlingamt, you must also specify itemamt. 'taxamt' => $order_info["product_tax"], // Required if you specify itemized cart tax details. Sum of tax for all items on the order. Total sales tax. 'desc' => '', // Description of the order the customer is purchasing. 127 char max. 'custom' => '', // Free-form field for your own use. 256 char max. 'invnum' => $product_id, // Your own invoice or tracking number 'BUTTONSOURCE' => 'CMSaccount_SP', 'notifyurl' => surl.site_root."/members/payments_process.php?mode=notification&product_type=".$product_type."&processor=paypal" // URL for receiving Instant Payment Notifications. This overrides what your profile is set to use. ); // Wrap all data arrays into a single, "master" array which will be passed into the class function. $PayPalRequestData = array( 'DPFields' => $DPFields, 'CCDetails' => $CCDetails, 'PayerName' => $PayerName, 'PayerInfo' => $PayerInfo, 'BillingAddress' => $BillingAddress, 'PaymentDetails' => $PaymentDetails ); // Pass the master array into the PayPal class function $PayPalResult = $PayPal->DoDirectPayment($PayPalRequestData); // Display results //echo '<pre />'; //print_r($PayPalResult); if($PayPalResult["ACK"]=="Success") { $transaction_id=transaction_add("paypal",$PayPalResult["TRANSACTIONID"],$_POST["product_type"],$_POST["product_id"]); if($_POST["product_type"]=="credits") { credits_approve($_POST["product_id"],$transaction_id); send_notification('credits_to_user',$_POST["product_id"]); send_notification('credits_to_admin',$_POST["product_id"]); } if($_POST["product_type"]=="subscription") { subscription_approve($_POST["product_id"]); send_notification('subscription_to_user',$_POST["product_id"]); send_notification('subscription_to_admin',$_POST["product_id"]); } if($_POST["product_type"]=="order") { order_approve($_POST["product_id"]); commission_add($_POST["product_id"]); coupons_add(order_user($_POST["product_id"])); send_notification('neworder_to_user',$_POST["product_id"]); send_notification('neworder_to_admin',$_POST["product_id"]); } echo("<p>Thank you! Your transaction has been sent successfully.</p>"); } else { echo($PayPalResult["ERRORS"][0]["L_SEVERITYCODE"]." ".$PayPalResult["ERRORS"][0]["L_ERRORCODE"]."<br>".$PayPalResult["ERRORS"][0]["L_SHORTMESSAGE"]."<br>".$PayPalResult["ERRORS"][0]["L_LONGMESSAGE"]."<br>"); } ?> <br><br> <? if(isset($_POST["product_id"]) and isset($_POST["product_type"])) { $_GET["product_id"]=$_POST["product_id"]; $_GET["product_type"]=$_POST["product_type"]; $_GET["print"]=1; include("payments_statement.php"); } ?> <?include("../inc/footer.php");?>
mit
emmellsoft/RPi.SenseHat
RPi.SenseHat/RTIMULibCS/Devices/LSM9DS1/AccelSampleRate.cs
1469
//////////////////////////////////////////////////////////////////////////// // // This file is part of RTIMULibCS // // Copyright (c) 2015, richards-tech, LLC // // Permission is hereby granted, free of charge, to any person obtaining a copy of // this software and associated documentation files (the "Software"), to deal in // the Software without restriction, including without limitation the rights to use, // copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the // Software, and to permit persons to whom the Software is furnished to do so, // subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all // copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, // INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A // PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT // HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE // SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. namespace RTIMULibCS.Devices.LSM9DS1 { public enum AccelSampleRate { Freq10Hz = 1, Freq50Hz = 2, Freq119Hz = 3, Freq238Hz = 4, Freq476Hz = 5, Freq952Hz = 6 } }
mit
yimlu/testSuite
testSuite.js
2616
var https = require('https'); var querystring = require('querystring'); var fs = require('fs'); var colors = require('colors/safe'); var caseBuilder = (function(){ var CaseBuilder = { "build":function(globConfig,options){ return { "name":options.name, "host":globConfig.host, "port":globConfig.port, "url":options.url, "method":options.method, "loginRequired":options.loginRequired || false, "data":JSON.stringify(options.data), "asserts":options.asserts, "callBack":options.callBack } } }; return CaseBuilder; })(); var testRunner = (function(){ function error(message){ console.log(colors.red(message)); } function success(message){ console.log(colors.green(message)); } function warning(message){ console.log(colors.yellow(message)); } function runAsserts(asserts,res){ //convert string to json object var json = eval("(" + res + ")"); var ret = {}; ret.success = true; ret.brokenRules = []; if(asserts == null || asserts.length == 0) return ret; for(var i = 0;i<asserts.length;i++){ if(asserts[i] == null){ throw "Illegle assert object"; } var result = asserts[i].fn(json); ret.success = ret.success && result; if(!result){ ret.brokenRules.push({ "message":asserts[i].message }); } } return ret; } var run = function(testCase){ var requestOptions = { "host":testCase.host, "port":testCase.port, "path":testCase.url, "method":testCase.method, "headers":{ "Content-Type":"application/json", "Content-Length":Buffer.byteLength(testCase.data) } }; var req = https.request(requestOptions,function(response){ response.setEncoding('utf8'); response.on("data",function(d){ //run asserts var assertResult = runAsserts(testCase.asserts,d); if(response.statusCode >= 200 && response.statusCode<= 299 && assertResult.success){ success("[PASS] "+testCase.name+"\n"); } else{ error("[FAIL] "+testCase.name+"\n"); warning("The response data is:\n"); process.stdout.write(colors.yellow(d)); if(assertResult.brokenRules != null && assertResult.brokenRules.length>0){ warning("\n\nBroken rules:\n"); for(var i=0;i<assertResult.brokenRules.length;i++){ warning(assertResult.brokenRules[i].message + "\n"); } } } }); }); req.write(testCase.data); req.end(); }; var TestRunner = { "run":run } return TestRunner; })(); exports.caseBuilder = caseBuilder; exports.testRunner = testRunner;
mit
bugsnag/bugsnag-js
examples/ts/angular/src/app/app.component.ts
1425
import { Component } from '@angular/core'; import Bugsnag from '@bugsnag/js'; @Component({ selector: 'app-root', templateUrl: './app.component.html', styleUrls: ['./app.component.css'] }) export class AppComponent { title = 'app'; doARenderError = false; doAHandledError = false; // this function is triggered by the 'unhandled' button in app.component.html triggerUnhandledError() { throw new Error('Oh no') } // this function is triggered by the 'handled' button in app.component.html triggerHandledError() { this.doAHandledError = true; try { // potentially buggy code goes here var niceCode = "Everything is fine here."; throw("Bad thing!"); } catch (e) { // below modifies the handled error, and then sends it to your dashboard. Bugsnag.notify(e, function (event) { event.context = 'Don\'t worry - I handled it!' }); } // resets the button setTimeout(function () { this.doAHandledError = false; }.bind(this), 1000); } // this function is triggered by the 'render error' button in app.component.html triggerRenderError() { // the below line causes an unhandled exception in the html itself, which will then be reported to your dashboard automatically. this.doARenderError = true; // resets the button setTimeout(function () { this.doARenderError = false; }.bind(this), 1000); } }
mit