code
stringlengths
3
1.05M
repo_name
stringlengths
4
116
path
stringlengths
4
991
language
stringclasses
9 values
license
stringclasses
15 values
size
int32
3
1.05M
package com.mercangel.LifeTimer; import android.app.*; import android.os.*; import java.util.*; import android.widget.*; public class DatePickerFragment extends DialogFragment implements DatePickerDialog.OnDateSetListener { public DatePickerDialog.OnDateSetListener Listener = null; @Override public Dialog onCreateDialog(Bundle savedInstanceState) { // Use the current date as the default date in the picker final Calendar c = Calendar.getInstance(); int year = c.get(Calendar.YEAR); int month = c.get(Calendar.MONTH); int day = c.get(Calendar.DAY_OF_MONTH); // Create a new instance of DatePickerDialog and return it return new DatePickerDialog(getActivity(), this, year, month, day); } public void onDateSet(DatePicker view, int year, int month, int day) { if (Listener != null){ Listener.onDateSet(view, year, month, day); } } }
gngable/LifeTimer
LifeTimer/app/src/main/java/com/mercangel/LifeTimer/DatePickerFragment.java
Java
mit
927
<?php /* * This file is part of the PHPExifTool package. * * (c) Alchemy <support@alchemy.fr> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace PHPExiftool\Driver\Tag\Composite; use JMS\Serializer\Annotation\ExclusionPolicy; use PHPExiftool\Driver\AbstractTag; /** * @ExclusionPolicy("all") */ class Lens35efl extends AbstractTag { protected $Id = 'Lens35efl'; protected $Name = 'Lens35efl'; protected $FullName = 'Composite'; protected $GroupName = 'Composite'; protected $g0 = 'Composite'; protected $g1 = 'Composite'; protected $g2 = 'Other'; protected $Type = '?'; protected $Writable = false; protected $Description = 'Lens'; protected $local_g2 = 'Camera'; }
bburnichon/PHPExiftool
lib/PHPExiftool/Driver/Tag/Composite/Lens35efl.php
PHP
mit
824
var SafeObject = require('../../dist/SafeObject.js'); function Human(name) { SafeObject.call(this); this.name = name; } Human.prototype = Object.create(SafeObject && SafeObject.prototype, { constructor: { value: Human, enumerable: false, writable: true, configurable: true } }); Human.INSTANCE_PROPERTIES = { leftArm: null, rightArm: null, leftLeg: null, rightLeg: null, isHuman: new SafeObject.PropertyDescriptor(true, true, false, false) }; module.exports = Human;
Kelgors/SafeObject.js
tests/things/Human.js
JavaScript
mit
495
package br.com.estocandowebjava.bean; import java.sql.SQLException; import java.util.ArrayList; import javax.annotation.PostConstruct; import javax.faces.bean.ManagedBean; import javax.faces.bean.ViewScoped; import br.com.estocandowebjava.dao.SetorDAO; import br.com.estocandowebjava.domain.Setor; import br.com.estocandowebjava.util.JSFUtil; @ManagedBean(name = "MBSetor") @ViewScoped public class SetorBean { private Setor setor; private ArrayList<Setor> itens; private ArrayList<Setor> itensFiltrados; public Setor getSetor() { return setor; } public void setSetor(Setor setor) { this.setor = setor; } public ArrayList<Setor> getItens() { return itens; } public void setItens(ArrayList<Setor> itens) { this.itens = itens; } public ArrayList<Setor> getItensFiltrados() { return itensFiltrados; } public void setItensFiltrados(ArrayList<Setor> itensFiltrados) { this.itensFiltrados = itensFiltrados; } @PostConstruct public void prepararPesquisaSetor() { try { SetorDAO dao = new SetorDAO(); itens = dao.listar(); } catch (SQLException ex) { ex.printStackTrace(); JSFUtil.adicionarMensagemErro(ex.getMessage()); } } public void prepararNovoSetor() { setor = new Setor(); } public void novoSetor() { try { SetorDAO dao = new SetorDAO(); dao.salvarSetor(setor); itens = dao.listar(); JSFUtil.adicionarMensagemSucesso("Dados salvos com sucesso"); } catch (SQLException ex) { ex.printStackTrace(); JSFUtil.adicionarMensagemErro(ex.getMessage()); } } // CARREGA OS DADOS DA TABELA QUE SERÃO EXCLUIDOS public void excluirSetor() { try { SetorDAO dao = new SetorDAO(); dao.excluirSetor(setor); itens = dao.listar(); JSFUtil.adicionarMensagemSucesso("Dados removidos com sucesso"); } catch (SQLException ex) { ex.printStackTrace(); JSFUtil.adicionarMensagemErro(ex.getMessage()); } } // CARREGA OS DADOS DA TABELA QUE SERÃO EDITADOS public void editarSetor() { try { SetorDAO dao = new SetorDAO(); dao.editarSetor(setor); itens = dao.listar(); JSFUtil.adicionarMensagemSucesso("Dados editados com sucesso."); } catch (SQLException ex) { ex.printStackTrace(); JSFUtil.adicionarMensagemErro(ex.getMessage()); } } }
suelbercosta/EstocandoWebJava
src/br/com/estocandowebjava/bean/SetorBean.java
Java
mit
2,274
package lezchap.ttcore.asm; import java.io.File; import java.util.Map; import lezchap.ttcore.TTCore; import cpw.mods.fml.relauncher.IFMLLoadingPlugin.MCVersion; @MCVersion(value = "1.6.4") public class FishHookFMLLoadingPlugin implements cpw.mods.fml.relauncher.IFMLLoadingPlugin { //declare a placeholder for the name and location of the jar public static File location; @Override public String[] getASMTransformerClass() { return new String[]{FishHookClassTransformer.class.getName()}; } @Override public void injectData(Map<String, Object> data) { //This will return the jar file of this mod location = (File) data.get("coremodLocation"); } @Override public String[] getLibraryRequestClass() { // TODO Auto-generated method stub return null; } @Override public String getModContainerClass() { return null; } @Override public String getSetupClass() { // TODO Auto-generated method stub return null; } }
LezChap/Thaumic-Tools
lezchap/ttcore/asm/FishHookFMLLoadingPlugin.java
Java
mit
995
""" Module for adding stimulations to networks """ from __future__ import print_function from __future__ import unicode_literals from __future__ import division from __future__ import absolute_import from future import standard_library standard_library.install_aliases() from numbers import Number try: basestring except NameError: basestring = str # ----------------------------------------------------------------------------- # Add stims # ----------------------------------------------------------------------------- def addStims(self): """ Function for/to <short description of `netpyne.network.stim.addStims`> Parameters ---------- self : <type> <Short description of self> **Default:** *required* """ from .. import sim sim.timing('start', 'stimsTime') if self.params.stimSourceParams and self.params.stimTargetParams: if sim.rank==0: print('Adding stims...') if sim.nhosts > 1: # Gather tags from all cells allCellTags = sim._gatherAllCellTags() else: allCellTags = {cell.gid: cell.tags for cell in self.cells} # allPopTags = {i: pop.tags for i,pop in enumerate(self.pops)} # gather tags from pops so can connect NetStim pops sources = self.params.stimSourceParams for targetLabel, target in self.params.stimTargetParams.items(): # for each target parameter set if 'sec' not in target: target['sec'] = None # if section not specified, make None (will be assigned to first section in cell) if 'loc' not in target: target['loc'] = None # if location not specified, make None source = sources.get(target['source']) postCellsTags = allCellTags for condKey,condValue in target['conds'].items(): # Find subset of cells that match postsyn criteria if condKey in ['x','y','z','xnorm','ynorm','znorm']: postCellsTags = {gid: tags for (gid,tags) in postCellsTags.items() if condValue[0] <= tags.get(condKey, None) < condValue[1]} # dict with post Cell objects} # dict with pre cell tags elif condKey == 'cellList': pass elif isinstance(condValue, list): postCellsTags = {gid: tags for (gid,tags) in postCellsTags.items() if tags.get(condKey, None) in condValue} # dict with post Cell objects else: postCellsTags = {gid: tags for (gid,tags) in postCellsTags.items() if tags.get(condKey, None) == condValue} # dict with post Cell objects # subset of cells from selected pops (by relative indices) if 'cellList' in target['conds']: orderedPostGids = sorted(postCellsTags.keys()) gidList = [orderedPostGids[i] for i in target['conds']['cellList']] postCellsTags = {gid: tags for (gid,tags) in postCellsTags.items() if gid in gidList} # initialize randomizer in case used in string-based function (see issue #89 for more details) self.rand.Random123(sim.hashStr('stim_'+source['type']), sim.hashList(sorted(postCellsTags)), sim.cfg.seeds['stim']) # calculate params if string-based funcs strParams = self._stimStrToFunc(postCellsTags, source, target) # loop over postCells and add stim target for postCellGid in postCellsTags: # for each postsyn cell if postCellGid in self.gid2lid: # check if postsyn is in this node's list of gids postCell = self.cells[sim.net.gid2lid[postCellGid]] # get Cell object # stim target params params = {} params['label'] = targetLabel params['source'] = target['source'] params['sec'] = strParams['secList'][postCellGid] if 'secList' in strParams else target['sec'] params['loc'] = strParams['locList'][postCellGid] if 'locList' in strParams else target['loc'] if source['type'] == 'NetStim': # for NetStims add weight+delay or default values params['weight'] = strParams['weightList'][postCellGid] if 'weightList' in strParams else target.get('weight', 1.0) params['delay'] = strParams['delayList'][postCellGid] if 'delayList' in strParams else target.get('delay', 1.0) params['synsPerConn'] = strParams['synsPerConnList'][postCellGid] if 'synsPerConnList' in strParams else target.get('synsPerConn', 1) params['synMech'] = target.get('synMech', None) for p in ['Weight', 'Delay', 'loc']: if 'synMech'+p+'Factor' in target: params['synMech'+p+'Factor'] = target.get('synMech'+p+'Factor') if 'originalFormat' in source and source['originalFormat'] == 'NeuroML2': if 'weight' in target: params['weight'] = target['weight'] for sourceParam in source: # copy source params params[sourceParam] = strParams[sourceParam+'List'][postCellGid] if sourceParam+'List' in strParams else source.get(sourceParam) if source['type'] == 'NetStim': self._addCellStim(params, postCell) # call method to add connections (sort out synMechs first) else: postCell.addStim(params) # call cell method to add connection print((' Number of stims on node %i: %i ' % (sim.rank, sum([len(cell.stims) for cell in self.cells])))) sim.pc.barrier() sim.timing('stop', 'stimsTime') if sim.rank == 0 and sim.cfg.timing: print((' Done; cell stims creation time = %0.2f s.' % sim.timingData['stimsTime'])) return [cell.stims for cell in self.cells] # ----------------------------------------------------------------------------- # Set parameters and add stim # ----------------------------------------------------------------------------- def _addCellStim(self, stimParam, postCell): # convert synMech param to list (if not already) if not isinstance(stimParam.get('synMech'), list): stimParam['synMech'] = [stimParam.get('synMech')] # generate dict with final params for each synMech paramPerSynMech = ['weight', 'delay', 'loc'] finalParam = {} for i, synMech in enumerate(stimParam.get('synMech')): for param in paramPerSynMech: finalParam[param+'SynMech'] = stimParam.get(param) if len(stimParam['synMech']) > 1: if isinstance (stimParam.get(param), list): # get weight from list for each synMech finalParam[param+'SynMech'] = stimParam[param][i] elif 'synMech'+param.title()+'Factor' in stimParam: # adapt weight for each synMech finalParam[param+'SynMech'] = stimParam[param] * stimParam['synMech'+param.title()+'Factor'][i] params = {k: stimParam.get(k) for k,v in stimParam.items()} params['synMech'] = synMech params['loc'] = finalParam['locSynMech'] params['weight'] = finalParam['weightSynMech'] params['delay'] = finalParam['delaySynMech'] postCell.addStim(params=params) # ----------------------------------------------------------------------------- # Convert stim param string to function # ----------------------------------------------------------------------------- def _stimStrToFunc(self, postCellsTags, sourceParams, targetParams): # list of params that have a function passed in as a string #params = sourceParams+targetParams params = sourceParams.copy() params.update(targetParams) paramsStrFunc = [param for param in self.stimStringFuncParams+self.connStringFuncParams if param in params and isinstance(params[param], basestring) and params[param] not in ['variable']] # dict to store correspondence between string and actual variable dictVars = {} dictVars['post_x'] = lambda postConds: postConds['x'] dictVars['post_y'] = lambda postConds: postConds['y'] dictVars['post_z'] = lambda postConds: postConds['z'] dictVars['post_xnorm'] = lambda postConds: postConds['xnorm'] dictVars['post_ynorm'] = lambda postConds: postConds['ynorm'] dictVars['post_znorm'] = lambda postConds: postConds['znorm'] dictVars['rand'] = lambda unused1: self.rand # add netParams variables for k,v in self.params.__dict__.items(): if isinstance(v, Number): dictVars[k] = v # for each parameter containing a function, calculate lambda function and arguments strParams = {} for paramStrFunc in paramsStrFunc: strFunc = params[paramStrFunc] # string containing function for randmeth in self.stringFuncRandMethods: strFunc = strFunc.replace(randmeth, 'rand.'+randmeth) # append rand. to h.Random() methods strVars = [var for var in list(dictVars.keys()) if var in strFunc and var+'norm' not in strFunc] # get list of variables used (eg. post_ynorm or dist_xyz) lambdaStr = 'lambda ' + ','.join(strVars) +': ' + strFunc # convert to lambda function lambdaFunc = eval(lambdaStr) # store lambda function and func vars in connParam (for weight, delay and synsPerConn since only calculated for certain conns) params[paramStrFunc+'Func'] = lambdaFunc params[paramStrFunc+'FuncVars'] = {strVar: dictVars[strVar] for strVar in strVars} # replace lambda function (with args as dict of lambda funcs) with list of values strParams[paramStrFunc+'List'] = {postGid: params[paramStrFunc+'Func'](**{k:v if isinstance(v, Number) else v(postCellTags) for k,v in params[paramStrFunc+'FuncVars'].items()}) for postGid,postCellTags in sorted(postCellsTags.items())} return strParams
Neurosim-lab/netpyne
netpyne/network/stim.py
Python
mit
10,067
require 'spec_helper' describe Yapfac::Apache::Scope do subject { Yapfac::Apache::Scope } before(:all) do @scope = Yapfac::Apache::Scope.new("VirtualHost", "*:80") @scope.add_directive Yapfac::Apache::Directive.parse("DocumentRoot /test") @scope.add_directive "Order", "allow,deny" @scope.add_scope Yapfac::Apache::Scope.new("Directory", "/test") @scope.add_scope "Directory", "/other" end it { expect(@scope).to respond_to :scopes } it { expect(@scope).to respond_to :params } it { expect(@scope).to respond_to :name } it { expect(@scope).to respond_to :directives } it { expect(@scope).to respond_to :name= } it { expect(@scope).to respond_to :params= } it { expect(@scope).to_not respond_to :directives= } it { expect(@scope).to_not respond_to :scopes= } context "when adding itsself as scope" do it { expect { @scope.add_scope @scope }.to raise_error RuntimeError } end describe "#scopes" do subject { @scope.scopes } it { is_expected.to be_kind_of Array } it { is_expected.to have_at_least(2).items } it { expect(@scope.scopes.first.name).to eq "Directory" } it { expect(@scope.scopes.last.name).to eq "Directory" } it { expect(@scope.scopes.first.params).to include("/test") } it { expect(@scope.scopes.last.params).to include("/other") } end describe "#directives" do subject { @scope.directives } it { is_expected.to be_kind_of Array } it { is_expected.to have_at_least(2).items } it { expect(@scope.directives.first.name).to eq "DocumentRoot" } it { expect(@scope.directives.last.name).to eq "Order" } end describe "#name" do subject { @scope.name } it { is_expected.to be_kind_of String } it { is_expected.to eq "VirtualHost" } end describe "#params" do subject { @scope.params } it { is_expected.to be_kind_of Array } it { is_expected.to have_at_least(1).items } it { is_expected.to include("*:80") } end describe "#to_h" do subject { @scope.to_h } it { is_expected.to be_kind_of Hash } it { expect(subject.keys).to include(:name, :params, :scopes, :directives) } describe ":name" do subject { @scope.to_h[:name] } it { is_expected.to eq "VirtualHost" } end describe ":params" do subject { @scope.to_h[:params] } it { is_expected.to have_at_least(1).items } it { is_expected.to include("*:80") } end describe ":scopes" do subject { @scope.to_h[:scopes] } it { is_expected.to include(@scope.scopes.first.to_h) } end describe ":directives" do subject { @scope.to_h[:directives] } it { is_expected.to include(@scope.directives.first.to_h) } end end describe "#to_s" do subject { @scope.to_s } it { is_expected.to be_kind_of String } it { is_expected.to match /<VirtualHost \*:80>/ } it { is_expected.to match /DocumentRoot \/test/ } it { is_expected.to match /<\/VirtualHost>/ } end end
eiwi1101/yapfac
spec/scope_spec.rb
Ruby
mit
2,981
hackApp.service( 'ApiService', [ '$resource', function ( $resource ) { return $resource('http://74.208.124.117/www/api/apiIndex.php/', {}, { login : { url : 'http://74.208.124.117/www/api/apiIndex.php/login', method : 'POST', params : { }, transformRequest : function ( data ) { var info = { token : data.token }; return angular.toJson( info ); }, isArray : true }, listServers : { url : 'http://74.208.124.117/www/api/apiIndex.php/servers', method : 'GET', params : { }, transformRequest : function ( data ) { var info = { }; return angular.toJson( info ); }, isArray : true, ignoreLoadingBar: true }, restartServer : { url : 'http://74.208.124.117/www/api/apiIndex.php/servers/:id/restart', method : 'PUT', params : { id : '@id' }, transformRequest : function ( data ) { var info = { action: 'restart' }; return angular.toJson( info ); }, isArray : false }, listLoadBalancers : { url : 'http://74.208.124.117/www/api/apiIndex.php/load_balancers', method : 'GET', params : { }, transformRequest : function ( data ) { var info = { }; return angular.toJson( info ); }, isArray : true }, listFirewallPolicies : { url : 'http://74.208.124.117/www/api/apiIndex.php/firewall_policies', method : 'GET', params : { }, transformRequest : function ( data ) { var info = { }; return angular.toJson( info ); }, isArray : true }, listSharedStorage : { url : 'http://74.208.124.117/www/api/apiIndex.php/shared_storages', method : 'GET', params : { }, transformRequest : function ( data ) { var info = { }; return angular.toJson( info ); }, isArray : true }, callMethod : { url : 'http://74.208.124.117/www/api/apiIndex.php/login', method : 'POST', params : { }, transformRequest : function ( data ) { var info = { token : data.token }; return angular.toJson( info ); }, isArray : true } } ); } ] ); // hackApp.service( 'ApiService', [ '$resource', function ( $resource ) { // return $resource( // 'user_logs', {}, { // query : { // url : 'user_logs', // method : 'GET', // params : { // }, // isArray : true // }, // get : { // url : 'user_logs/:id', // method : 'GET', // params : { // id : '@id' // }, // isArray : false // } // } // ); // } ] );
vilazae/ngcs-hack
www/app/common/services/apiServices.js
JavaScript
mit
3,398
<?php namespace Anax\Request; use PHPUnit\Framework\TestCase; /** * Fail testing of Request. */ class RequestFailTest extends TestCase { /** * Properties */ private $request; /** * Set up a request object * * @return void */ public function setUp() : void { $this->request = new Request(); } /** * Send incorrect JSON as part of body. */ public function testGetBodyAsJson() { $this->expectException("\JsonException"); $exp = "[1 2]"; $this->request->setBody($exp); $this->request->getBodyAsJson(); } }
canax/request
test/Request/RequestFailTest.php
PHP
mit
634
import src.executor as executor import src.dqn as dqn import src.game_data as game_data import src.graph as graph import src.environment as environment import numpy as np import unittest class TestIntegration(unittest.TestCase): def setUp(self): self.executor = executor.Executor() self.dqn = dqn.Agent() self.game_data = game_data.GameBatchData() self.graph = graph.Graph() self.environment = environment.GymEnvironment('Pong-vo') def test_integration_game_data_and_executor(self): print("Integration testing of game data and executor module") self.executor.new_game(11111) self.executor.add_screenshots(np.array([[100, 100], [100, 100]])) self.executor._generate_gif(np.array([[100, 100], [100, 100]])) self.executor.write_csv(['h1', 'h2'], [[1, 2], [2, 3]], [1, 2]) print("Successful Integration testing of game data and executor module") def test_integration_environment_and_graph_execution(self): print("Integration testing of game data and executor module") self.environment.actions() self.environment.action_space() self.environment.make() self.environment.render() self.environment.step(0) s, q_values, model = self.agent.build_network() self.trainable_weights = model.trainable_weights a, y, loss, grads_update = self.agent.build_training_op(self.trainable_weights) stack = self.agent.get_initial_state(np.array([[100, 100], [100, 100]])) action, action_value = self.agent.get_action(np.array([[100, 100], [100, 100]])) summary_placeholders, update_ops, summary_op = self.agent.setup_summary() self.agent.load_network() stack = dqn.preprocess(np.array([100,100]),np.array([[100, 100], [100, 100]])) print(s) print(q_values) print(model) print(a) print(y) print(loss) print(grads_update) print(stack) print(action) print(action_value) print(summary_placeholders) print(update_ops) print(summary_op) print(stack) print("Successful Integration testing of game data and executor module") if __name__ == '__main__': unittest.main()
escoboard/dqn
test/test_integration.py
Python
mit
2,279
using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; // アセンブリに関する一般情報は以下の属性セットをとおして制御されます。 // アセンブリに関連付けられている情報を変更するには、 // これらの属性値を変更してください。 [assembly: AssemblyTitle("C31Q3")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("C31Q3")] [assembly: AssemblyCopyright("Copyright © 2017")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // ComVisible を false に設定すると、このアセンブリ内の型は COM コンポーネントから // 参照できなくなります。COM からこのアセンブリ内の型にアクセスする必要がある場合は、 // その型の ComVisible 属性を true に設定してください。 [assembly: ComVisible(false)] // このプロジェクトが COM に公開される場合、次の GUID が typelib の ID になります [assembly: Guid("c91a54cd-858f-44a5-91b3-90a6c0ae903d")] // アセンブリのバージョン情報は次の 4 つの値で構成されています: // // メジャー バージョン // マイナー バージョン // ビルド番号 // Revision // // すべての値を指定するか、次を使用してビルド番号とリビジョン番号を既定に設定できます // 既定値にすることができます: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("1.0.0.0")] [assembly: AssemblyFileVersion("1.0.0.0")]
autumn009/TanoCSharpSamples
Chap31/C31Q3/C31Q3/Properties/AssemblyInfo.cs
C#
mit
1,656
/** * Copyright (c) 2018 mol* contributors, licensed under MIT, See LICENSE file for more info. * * @author Alexander Rose <alexander.rose@weirdbyte.de> */ import * as CCP4 from '../ccp4/parser'; function createCcp4Data() { const data = new Uint8Array(4 * 256 + 6); const dv = new DataView(data.buffer); dv.setInt8(52 * 4, 'M'.charCodeAt(0)); dv.setInt8(52 * 4 + 1, 'A'.charCodeAt(0)); dv.setInt8(52 * 4 + 2, 'P'.charCodeAt(0)); dv.setInt8(52 * 4 + 3, ' '.charCodeAt(0)); dv.setUint8(53 * 4, 17); dv.setUint8(53 * 4 + 1, 17); dv.setInt32(0 * 4, 1); // NC dv.setInt32(1 * 4, 2); // NR dv.setInt32(2 * 4, 3); // NS dv.setInt32(3 * 4, 0); // MODE return data; } describe('ccp4 reader', () => { it('basic', async () => { const data = createCcp4Data(); const parsed = await CCP4.parse(data, 'test.ccp4').run(); if (parsed.isError) { throw new Error(parsed.message); } const ccp4File = parsed.result; const { header } = ccp4File; expect(header.NC).toBe(1); expect(header.NR).toBe(2); expect(header.NS).toBe(3); }); });
molstar/molstar
src/mol-io/reader/_spec/ccp4.spec.ts
TypeScript
mit
1,173
require 'rails/generators/named_base' module ActiveRedis module Generators class Base < ::Rails::Generators::NamedBase def self.source_root @_rspec_source_root ||= File.expand_path(File.join(File.dirname(__FILE__), 'active_redis', generator_name, 'templates')) end end end end
sergio1990/active_redis
lib/generators/active_redis.rb
Ruby
mit
311
/* _ _ _ __ _(_)___(_) ___ _ __ | |__ _ __ _ __ \ \ / / / __| |/ _ \| '_ \ | '_ \| '_ \| '_ \ \ V /| \__ \ | (_) | | | |_| | | | |_) | |_) | \_/ |_|___/_|\___/|_| |_(_)_| |_| .__/| .__/ |_| |_| */ /* Copyright (c) 2014 AVBotz * * 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. * ========================================================================== */ #ifndef VISION_H__ #define VISION_H__ #include <libconfig.h++> #include "threadimpl.hpp" #include "types.hpp" #include "timer.hpp" #include "log.hpp" #include "threadpool/pool.hpp" #include <opencv/cxcore.h> #include <opencv/highgui.h> #include <cv.h> #include <array> #include <algorithm> #include <queue> #include <tuple> class Vision { public: Vision(libconfig::Config* conf); ~Vision(); virtual void visionProcess() = 0; virtual void saveFrame(int cam, const cv::Mat img); virtual void waitForImage() volatile; cv::Mat i_front, i_down; cv::Mat raw_front, raw_down; volatile int requestImage; // use the camera id to request the image bool snapshotEnable; int snapshotTime; int skippedFrames; std::queue<std::tuple<std::string, cv::Mat> > imagesToSave; private: virtual void storeImage(HARDWARE cam) = 0; void yuv2rgb(int start, int end, unsigned char* img_data, unsigned char* filt_data, int width, int height, void* buffer); void getColorExtremes(int width, int height, unsigned char* data, int offset, int interval, unsigned char* table); // result is an array of size six in it go the results // in order b005, g005, r005, b995, g995, r995 // where 005 refers to the .5 percentile and 995 to the 99.5 percentile int height, width; ThreadImpl* timpl; threadpool::pool pool; int picIndex; cv::Mat filter; }; #endif
avbotz/eva-public
src/vision.hpp
C++
mit
2,848
var immediateAuth = false; var Neutron = { gdrive_api_loaded: false, authorized: false, authorizer: null, OAuth: null, UserId: null, parent: null, origin: null, id: null, init_token: null, share: null }; Neutron.auth_init = function (setkey, force_slow) { if (setkey) { gapi.client.setApiKey(GOOGLE_KEY); } if (!Neutron.parent) { setTimeout(Neutron.auth_init, 300); return 0; } if (!Neutron.gdrive_api_loaded) { gapi.client.load('drive', 'v2', function () { Neutron.gdrive_api_loaded = true; Neutron.auth_init(); }); return 0; } if (Neutron.authorizer) { clearTimeout(Neutron.authorizer); Neutron.authorizer = null; } var options = { client_id: GOOGLE_CLIENT_ID, immediate: immediateAuth, scope: [ 'https://www.googleapis.com/auth/drive', 'https://www.googleapis.com/auth/drive.scripts', 'https://www.googleapis.com/auth/userinfo.profile', 'https://www.googleapis.com/auth/drive.install', 'https://www.googleapis.com/auth/drive.file' ] }; if (Neutron.UserId) { options.user_id = Neutron.UserId; } if (force_slow) { options.immediate = false; } gapi.auth.authorize(options, Neutron.auth_callback); }; Neutron.auth_callback = function (OAuth) { Neutron.parent.postMessage({'task': 'close-popup', id: Neutron.id}, Neutron.origin); if (OAuth && OAuth.error) { Neutron.auth_init(false, true); return null; } if (OAuth && OAuth.expires_in) { try { gapi.drive.realtime.setServerAddress('https://docs.google.com/otservice/'); } catch (e) { setTimeout(Neutron.auth_init, 300); return 0; } Neutron.OAuth = OAuth; Neutron.authorizer = setTimeout(Neutron.auth_init, 60 * 25 * 1000); Neutron.authorized = true; oauth = { access_token: OAuth.access_token, expires_at: OAuth.expires_at }; gapi.client.load('oauth2', 'v2', function() { gapi.client.oauth2.userinfo.get().execute(function (resp) { oauth.user_id = resp.id; Neutron.UserId = resp.id; var request = gapi.client.drive.about.get(); request.execute(function (response) { document.querySelector("#email").innerHTML = 'Account: ' + response.user.emailAddress; immediateAuth = true; Neutron.parent.postMessage({ task: 'token', oauth: oauth, email: response.user.emailAddress, id: Neutron.id }, Neutron.origin); }); }); }); } }; Neutron.pick_folder = function () { var docsView = new google.picker.DocsView(). setIncludeFolders(true). setMimeTypes('application/vnd.google-apps.folder'). setSelectFolderEnabled(true); var picker = new google.picker.PickerBuilder(). addView(docsView). setOAuthToken(Neutron.OAuth.access_token). setDeveloperKey(GOOGLE_KEY). setCallback(Neutron.pick_folder_callback). build(); picker.setVisible(true); }; Neutron.pick_folder_callback = function (data) { if (data[google.picker.Response.ACTION] == google.picker.Action.PICKED) { var doc = data[google.picker.Response.DOCUMENTS][0]; var id = doc[google.picker.Document.ID]; Neutron.parent.postMessage({'task': 'folder-picked', id: Neutron.id, folderId: id}, Neutron.origin); } else if (data[google.picker.Response.ACTION] == google.picker.Action.CANCEL) { Neutron.parent.postMessage({'task': 'hide-webview', id: Neutron.id}, Neutron.origin); } }; Neutron.receive_message = function (event) { if (event.data && event.data.task) { if (event.data.task === 'handshake') { if (!Neutron.parent) { Neutron.parent = event.source; Neutron.origin = event.origin; Neutron.id = event.data.id; if (event.data.oauth) { document.querySelector("#email").innerHTML = 'Initializing Account: ' + event.data.email; gapi.load('auth:client,drive-realtime,drive-share,picker', function () { gapi.auth.setToken({ access_token: event.data.oauth.access_token }); Neutron.UserId = event.data.oauth.user_id; Neutron.auth_init(true); }); } else { gapi.load('auth:client,drive-realtime,drive-share,picker', function () { Neutron.auth_init(true); }); } } } else if (event.data.task === 'reauth') { Neutron.auth_init(true); } else if (event.data.task === 'pick-folder') { Neutron.pick_folder(); } else if (Drive[event.data.task]) { Drive[event.data.task](event.data, function (result) { Neutron.parent.postMessage({ 'task': event.data.task, id: Neutron.id, result: result, pid: event.data.pid }, Neutron.origin); }); } } }; window.addEventListener("message", Neutron.receive_message, false); function report_error (error, data) { var post_data = { error: JSON.stringify(error), data: JSON.stringify(data), apikey: 'errors-are-a-bitch', username: 'GDrive-' + document.querySelector("#email").innerHTML }; var xmlhttp = new XMLHttpRequest(); xmlhttp.open("POST", '/editor/error', true); xmlhttp.send(JSON.stringify(post_data)); } window.onerror = function (msg, url, line) { report_error(msg, {url: url, line: line}); };
pizzapanther/Super-Neutron-Drive
server/ndrive/static/js/neutron.js
JavaScript
mit
5,469
require 'spec_helper' describe ContextPresenter do context 'context_summary' do let(:graph) { TestFactories::Graph.full } let(:context) { graph.to_a[0..1] } let(:context_presenter) { described_class.new(context: context) } it '#context_summary returns the context_summuary' do context_presenter.context_summary.should == 'public 2013-10-13' end context 'raises when new is not given all arguments' do it 'without context' do lambda{ described_class.new({}) }.should raise_error end end end end
petervandenabeele/dbd_data_engine
spec/presenters/context_presenter/context_summary_spec.rb
Ruby
mit
556
using System.Management.Automation; namespace Codeless.SharePoint.PowerShell { [Cmdlet(VerbsCommon.Get, "SPModelManager")] public class CmdletGetSPModelManager : CmdletBaseSPModel { protected override void ProcessRecord() { base.ProcessRecord(); WriteObject(this.Manager); } } }
misonou/codeless
src/Codeless.SharePoint.PowerShell/CmdletGetSPModelManager.cs
C#
mit
309
import Form from './Form'; import CheckboxList from './CheckboxList'; import RadioList from './RadioList'; import Select from './Select'; import TextInput from './TextInput'; Form.CheckboxList = CheckboxList; Form.RadioList = RadioList; Form.Select = Select; Form.TextInput = TextInput; export default Form;
e1-bsd/omni-common-ui
src/components/Form/index.js
JavaScript
mit
310
import { COLUMN_NAMES, COLUMNS } from './table.constant' export function format(columnName, contents) { switch (columnName) { case COLUMN_NAMES.NUMBER: return contents.slice(0, 2) + '-' + contents.slice(2) default: return contents } } export function generateComparisonFunction(sortingOrder, i) { const key = COLUMNS[i] return (a, b) => sortingOrder * (a[key] > b[key] ? 1 : a[key] < b[key] ? -1 : 0) }
gchatterjee/cit-gened-finder
ui/src/components/table/table.action.js
JavaScript
mit
448
/** * * * * */ import {Component} from 'angular2/core'; import {ROUTER_DIRECTIVES} from 'angular2/router'; import {DrupalService} from './drupal.service'; import 'rxjs/Rx'; @Component({ selector: 'app-home', templateUrl: './views/home.html', providers: [DrupalService], directives: [ROUTER_DIRECTIVES] }) export class HomeComponent { };
ndavison/drupalauthor
app/home.component.ts
TypeScript
mit
370
<?php namespace AmsterdamPHP\JobBundle\Form; use AmsterdamPHP\JobBundle\Form\ChoiceList\ContractType; use Symfony\Component\Form\AbstractType; use Symfony\Component\Form\FormBuilderInterface; use Symfony\Component\OptionsResolver\OptionsResolverInterface; class JobType extends AbstractType { public function buildForm(FormBuilderInterface $builder, array $options) { $builder ->add('title') ->add('languageOfAd', 'choice', array( 'label' => 'Language', 'choices' => array('en' => 'English', 'nl' => 'Dutch') )) ->add('description', 'ckeditor', array( 'config' => array( 'toolbar' => array( array( 'name' => 'basicstyles', 'items' => array('Bold', 'Italic', 'Underline', 'Strike', '-', 'RemoveFormat') ), array( 'name' => 'paragraph', 'items' => array('NumberedList', 'BulletedList', '-','Outdent','Indent') ), array( 'name' => 'links', 'items' => array('Link', 'Unlink') ) ), ) )) ->add('contractType', 'choice', array( 'label' => 'Type of contract', 'choice_list' => new ContractType() )) ->add('location') ->add('salary', 'text', array( 'required' => false )) ->add('url', 'url', array( 'required' => false )) ->add('expires', 'date', array( 'data' => new \DateTime("+1 month"))) ; } public function setDefaultOptions(OptionsResolverInterface $resolver) { $resolver->setDefaults(array( 'data_class' => 'AmsterdamPHP\JobBundle\Entity\Job' )); } public function getName() { return 'amsterdamphp_jobbundle_jobtype'; } }
AmsterdamPHP/job-board
src/AmsterdamPHP/JobBundle/Form/JobType.php
PHP
mit
2,149
namespace OmniXaml.Typing { using System; using System.Collections.Generic; using System.Reflection; using Glass.Core; public class MetadataProvider { private readonly IDictionary<string, AutoKeyDictionary<Type, object>> lookupDictionaries = new Dictionary<string, AutoKeyDictionary<Type, object>>(); public void Register(Type type, Metadata medataData) { foreach (var propertyInfo in medataData.GetType().GetRuntimeProperties()) { var dic = GetDictionary(propertyInfo.Name); var value = propertyInfo.GetValue(medataData); if (value != null) { dic.Add(type, value); } } } private AutoKeyDictionary<Type, object> GetDictionary(string name) { AutoKeyDictionary<Type, object> dic; var hadValue = lookupDictionaries.TryGetValue(name, out dic); if (hadValue) { return dic; } var autoKeyDictionary = new AutoKeyDictionary<Type, object>(t => t.GetTypeInfo().BaseType, t => t != null); lookupDictionaries.Add(name, autoKeyDictionary); return autoKeyDictionary; } public Metadata Get(Type type) { var metadata = new Metadata(); foreach (var prop in MedataProperties) { AutoKeyDictionary<Type, object> dic; var hadDictionary = lookupDictionaries.TryGetValue(prop.Name, out dic); if (hadDictionary) { object value; var hadValue = dic.TryGetValue(type, out value); if (hadValue) { prop.SetValue(metadata, value); } else { prop.SetValue(metadata, null); } } else { prop.SetValue(metadata, null); } } return metadata; } private static IEnumerable<PropertyInfo> MedataProperties => typeof(Metadata).GetRuntimeProperties(); } }
Perspex/OmniXAML
Source/OmniXaml/Typing/MetadataProvider.cs
C#
mit
2,302
/**************************************************************************** ** Copyright (c) quickfixengine.org All rights reserved. ** ** This file is part of the QuickFIX FIX Engine ** ** This file may be distributed under the terms of the quickfixengine.org ** license as defined by quickfixengine.org and appearing in the file ** LICENSE included in the packaging of this file. ** ** This file is provided AS IS with NO WARRANTY OF ANY KIND, INCLUDING THE ** WARRANTY OF DESIGN, MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. ** ** See http://www.quickfixengine.org/LICENSE for licensing information. ** ** Contact ask@quickfixengine.org if any conditions of this licensing are ** not clear to you. ** ****************************************************************************/ #include "stdafx.h" #include "Log.h" namespace FIX { Mutex ScreenLog::s_mutex; Log* ScreenLogFactory::create() { bool incoming, outgoing, event; init( m_settings.get(), incoming, outgoing, event ); return new ScreenLog( incoming, outgoing, event ); } Log* ScreenLogFactory::create( const SessionID& sessionID ) { Dictionary settings; if( m_settings.has(sessionID) ) settings = m_settings.get( sessionID ); bool incoming, outgoing, event; init( settings, incoming, outgoing, event ); return new ScreenLog( sessionID, incoming, outgoing, event ); } void ScreenLogFactory::init( const Dictionary& settings, bool& incoming, bool& outgoing, bool& event ) { if( m_useSettings ) { incoming = true; outgoing = true; event = true; if( settings.has(SCREEN_LOG_SHOW_INCOMING) ) incoming = settings.getBool(SCREEN_LOG_SHOW_INCOMING); if( settings.has(SCREEN_LOG_SHOW_OUTGOING) ) outgoing = settings.getBool(SCREEN_LOG_SHOW_OUTGOING); if( settings.has(SCREEN_LOG_SHOW_EVENTS) ) event = settings.getBool(SCREEN_LOG_SHOW_EVENTS); } else { incoming = m_incoming; outgoing = m_outgoing; event = m_event; } } void ScreenLogFactory::destroy( Log* pLog ) { delete pLog; } } //namespace FIX
SoftFx/FDK
FDK/QuickFix/Log.cpp
C++
mit
2,071
# -*- coding: utf-8 -*- ''' canteen model tests ~~~~~~~~~~~~~~~~~~~ tests canteen's data modelling layer. :author: Sam Gammon <sam@keen.io> :copyright: (c) Keen IO, 2013 :license: This software makes use of the MIT Open Source License. A copy of this license is included as ``LICENSE.md`` in the root of the project. ''' # stdlib import os # canteen tests from canteen.test import FrameworkTest ## ModelExportTests class ModelExportTests(FrameworkTest): ''' Tests objects exported by `model`. ''' def test_concrete(self): ''' Test that we can import concrete classes. ''' try: from canteen import model from canteen.model import Key from canteen.model import Model from canteen.model import Property from canteen.model import AbstractKey from canteen.model import AbstractModel except ImportError: # pragma: no cover return self.fail("Failed to import concrete classes exported by Model.") else: self.assertTrue(Key) # must export Key self.assertTrue(Model) # must export Model self.assertTrue(Property) # must export Property self.assertTrue(AbstractKey) # must export AbstractKey self.assertTrue(AbstractModel) # must export AbstractModel self.assertIsInstance(model, type(os)) # must be a module (lol)
mindis/canteen
canteen_tests/test_model/__init__.py
Python
mit
1,361
// -------------------------------------------- // Copyright KAPSARC. Open source MIT License. // -------------------------------------------- // The MIT License (MIT) // // Copyright (c) 2015 King Abdullah Petroleum Studies and Research Center // // 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. // -------------------------------------------- // // Demonstrate a very basic, but highly parameterizable, model of committee selection // // -------------------------------------------- #include <cstdio> #include <string> #include <vector> #include "kutils.h" #include "kmatrix.h" #include "prng.h" #include "kmodel.h" #include "smp.h" #include "comsel.h" #include "democomsel.h" using namespace std; using KBase::VUI; using KBase::PRNG; using KBase::KMatrix; using KBase::Actor; using KBase::Model; using KBase::Position; using KBase::State; using KBase::VotingRule; namespace DemoComSel { using std::function; using std::get; using std::string; using KBase::ReportingLevel; using KBase::MtchPstn; using ComSelLib::CSModel; using ComSelLib::CSActor; using ComSelLib::CSState; using ComSelLib::intToVB; using ComSelLib::vbToInt; // ------------------------------------------------- // like printVUI, but with range-checking and boolean output string printCS(const VUI& v) { unsigned int n = v.size(); string cs("[CS "); for (unsigned int i = 0; i < n; i++) { switch (v[i]) { case 0: cs += "-"; break; case 1: cs += "+"; break; default: LOG(INFO) << "printCS:: unrecognized case"; exit(-1); break; } } cs += "]"; return cs; } void demoActorUtils(const uint64_t s, PRNG* rng) { LOG(INFO) << KBase::getFormattedString("Using PRNG seed: %020llu", s); rng->setSeed(s); return; } void demoCSC(unsigned int numA, unsigned int nDim, bool cpP, bool siP, const uint64_t s) { // need a template for ... // position type (each is a committee) // utility to an actor of a position (committee) // getting actor's scalar capability LOG(INFO) << KBase::getFormattedString("Using PRNG seed: %020llu", s); auto trng = new PRNG(); trng->setSeed(s); if (0 == numA) { numA = 2 + (trng->uniform() % 4); } // i.e. [2,6] inclusive if (0 == nDim) { nDim = 1 + (trng->uniform() % 7); } // i.e. [1,7] inclusive LOG(INFO) << "Num parties:" << numA; LOG(INFO) << "Num dimensions:" << nDim; unsigned int numItm = numA; unsigned int numCat = 2; // out or in, respectively unsigned int numPos = exp2(numA); // i.e. numCat ^^ numItm vector<VUI> positions = {}; for (unsigned int i = 0; i < numPos; i++) { const VUI vbi = intToVB(i, numA); const unsigned int j = vbToInt(vbi); assert(j == i); const VUI vbj = intToVB(j, numA); assert(vbj == vbi); positions.push_back(vbi); } assert(numPos == positions.size()); LOG(INFO) << "Num positions:" << numPos; auto ndfn = [](string ns, unsigned int i) { auto ali = KBase::newChars(10 + ((unsigned int)(ns.length()))); std::sprintf(ali, "%s%i", ns.c_str(), i); auto s = string(ali); delete ali; ali = nullptr; return s; }; // create a model to hold some random actors auto csm = new CSModel(nDim, "csm0", s); LOG(INFO) << "Configuring actors: randomizing"; for (unsigned int i = 0; i < numA; i++) { auto ai = new CSActor(ndfn("csa-", i), ndfn("csaDesc-", i), csm); ai->randomize(csm->rng, nDim); csm->addActor(ai); } assert(csm->numAct == numA); csm->numItm = numA; assert(csm->numCat == 2); if ((9 == numA) && (2 == nDim)) { for (unsigned int i = 0; i < 3; i++) { auto ci = KMatrix::uniform(csm->rng, nDim, 1, 0.1, 0.9); for (unsigned int j = 0; j < 3; j++) { auto ej = KMatrix::uniform(csm->rng, nDim, 1, -0.05, +0.05); const KMatrix pij = clip(ci + ej, 0.0, 1.0); unsigned int n = (3 * i) + j; auto an = ((CSActor *)(csm->actrs[n])); an->vPos = VctrPstn(pij); } } } LOG(INFO) << "Scalar positions of actors (fixed) ..."; for (auto a : csm->actrs) { auto csa = ((CSActor*)a); LOG(INFO) << csa->name << "v-position:"; trans(csa->vPos).mPrintf(" %5.2f"); LOG(INFO) << a->name << "v-salience:"; trans(csa->vSal).mPrintf(" %5.2f"); } LOG(INFO) << "Getting scalar strength of actors ..."; KMatrix aCap = KMatrix(1, csm->numAct); for (unsigned int i = 0; i < csm->numAct; i++) { auto ai = ((const CSActor *)(csm->actrs[i])); aCap(0, i) = ai->sCap; } aCap = (100.0 / sum(aCap)) * aCap; LOG(INFO) << "Scalar strengths:"; for (unsigned int i = 0; i < csm->numAct; i++) { auto ai = ((CSActor *)(csm->actrs[i])); ai->sCap = aCap(0, i); LOG(INFO) << KBase::getFormattedString("%3i %6.2f", i, ai->sCap); } LOG(INFO) << "Computing utilities of positions ... "; for (unsigned int i = 0; i < numA; i++) { // (0,0) causes computation of entire table double uii = csm->getActorCSPstnUtil(i, i); } // At this point, we have almost a generic enumerated model, // so much of the code below should be easily adaptable to EModel. // rows are actors, columns are all possible position KMatrix uij = KMatrix(numA, numPos); LOG(INFO) << "Complete (normalized) utility matrix of all possible positions (rows)" <<" versus actors (columns)"; string utilMtx; for (unsigned int pj = 0; pj < numPos; pj++) { utilMtx += std::to_string(pj) + " "; auto pstn = positions[pj]; utilMtx += printCS(pstn) + " "; for (unsigned int ai = 0; ai < numA; ai++) { const double uap = csm->getActorCSPstnUtil(ai, pj); uij(ai, pj) = uap; utilMtx += KBase::getFormattedString("%6.4f, ", uap); } } LOG(INFO) << utilMtx; LOG(INFO) << "Computing best position for each actor"; vector<VUI> bestAP = {}; // list of each actor's best position (followed by CP) for (unsigned int ai = 0; ai < numA; ai++) { unsigned int bestJ = 0; double bestV = 0; for (unsigned int pj = 0; pj < numPos; pj++) { if (bestV < uij(ai, pj)) { bestJ = pj; bestV = uij(ai, pj); } } LOG(INFO) << "Best for" << ai << "is" << bestJ << " " << printCS(positions[bestJ]); bestAP.push_back(positions[bestJ]); } trans(aCap).mPrintf("%5.2f "); // which happens to indicate the PCW *if* proportional voting, // when we actually use PropBin LOG(INFO) << "Computing zeta ... "; KMatrix zeta = aCap * uij; assert((1 == zeta.numR()) && (numPos == zeta.numC())); LOG(INFO) << "Sorting positions from most to least net support ..."; auto betterPR = [](tuple<unsigned int, double, VUI> pr1, tuple<unsigned int, double, VUI> pr2) { double v1 = get<1>(pr1); double v2 = get<1>(pr2); bool better = (v1 > v2); return better; }; auto pairs = vector<tuple<unsigned int, double, VUI>>(); for (unsigned int i = 0; i < numPos; i++) { auto pri = tuple<unsigned int, double, VUI>(i, zeta(0, i), positions[i]); pairs.push_back(pri); } sort(pairs.begin(), pairs.end(), betterPR); const unsigned int maxDisplayed = 256; unsigned int numPr = (pairs.size() < maxDisplayed) ? pairs.size() : maxDisplayed; LOG(INFO) << "Displaying highest " << numPr; for (unsigned int i = 0; i < numPr; i++) { auto pri = pairs[i]; unsigned int ni = get<0>(pri); double zi = get<1>(pri); VUI pi = get<2>(pri); LOG(INFO) << KBase::getFormattedString(" %3u: %4u %7.2f ", i, ni, zi) << printCS(pi); } VUI bestCS = get<2>(pairs[0]); bestAP.push_back(bestCS); // last one is the CP auto css0 = new CSState(csm); csm->addState(css0); assert(numA == css0->pstns.size()); // pre-allocated by constructor, all nullptr's // Either start them all at the CP or have each choose an initial position which // maximizes their direct utility, regardless of expected utility. for (unsigned int i = 0; i < numA; i++) { auto pi = new MtchPstn(); pi->numCat = numCat; pi->numItm = numItm; if (cpP) { pi->match = bestCS; } if (siP) { pi->match = bestAP[i]; } css0->pstns[i] = pi; assert(numA == css0->pstns.size()); // must be invariant } css0->step = [css0]() { return css0->stepSUSN(); }; unsigned int maxIter = 1000; csm->stop = [maxIter, csm](unsigned int iter, const KBase::State * s) { bool doneP = iter > maxIter; if (doneP) { LOG(INFO) << "Max iteration limit of" << maxIter << "exceeded"; } auto s2 = ((const CSState *)(csm->history[iter])); for (unsigned int i = 0; i < iter; i++) { auto s1 = ((const CSState *)(csm->history[i])); if (CSModel::equivStates(s1, s2)) { doneP = true; LOG(INFO) << "State number" << iter << "matched state number" << i; } } return doneP; }; css0->setUENdx(); csm->run(); return; } } // end of namespace int main(int ac, char **av) { using std::string; using KBase::dSeed; el::Configurations confFromFile("./comsel-logger.conf"); el::Loggers::reconfigureAllLoggers(confFromFile); auto sTime = KBase::displayProgramStart(DemoComSel::appName, DemoComSel::appVersion); uint64_t seed = dSeed; // arbitrary bool run = true; bool cpP = false; bool siP = true; auto showHelp = []() { printf("\n"); printf("Usage: specify one or more of these options\n"); printf("--cp start each actor from the central position \n"); printf("--si start each actor from their most self-interested position \n"); printf(" If neither cp nor si are specified, it will use si \n"); printf(" If both cp and si are specified, it will use the second specified \n"); printf("--help print this message \n"); printf("--seed <n> set a 64bit seed \n"); printf(" 0 means truly random \n"); printf(" default: %020llu \n", dSeed); }; // tmp args // seed = 0; if (ac > 1) { for (int i = 1; i < ac; i++) { if (strcmp(av[i], "--seed") == 0) { i++; seed = std::stoull(av[i]); } else if (strcmp(av[i], "--cp") == 0) { siP = false; cpP = true; } else if (strcmp(av[i], "--si") == 0) { cpP = false; siP = true; } else if (strcmp(av[i], "--help") == 0) { run = false; } else { run = false; printf("Unrecognized argument %s\n", av[i]); } } } if (!run) { showHelp(); return 0; } if (0 == seed) { PRNG * rng = new PRNG(); seed = rng->setSeed(0); // 0 == get a random number delete rng; rng = nullptr; } LOG(INFO) << KBase::getFormattedString("Using PRNG seed: %020llu", seed); LOG(INFO) << KBase::getFormattedString("Same seed in hex: 0x%016llX", seed); LOG(INFO) << "Creating objects from SMPLib ... "; auto sm = new SMPLib::SMPModel("", seed); // , "SMPScen-010101" auto sa = new SMPLib::SMPActor("Bob", "generic spatial actor"); delete sm; sm = nullptr; delete sa; sa = nullptr; LOG(INFO) << "Done creating objects from SMPLib."; // note that we reset the seed every time, so that in case something // goes wrong, we need not scroll back too far to find the // seed required to reproduce the bug. DemoComSel::demoCSC(9, // actors trying to get onto committee 2, // issues to be addressed by the committee cpP, siP, seed); KBase::displayProgramEnd(sTime); return 0; } // -------------------------------------------- // Copyright KAPSARC. Open source MIT License. // --------------------------------------------
ambah/KTAB
examples/comsel/src/democomsel.cpp
C++
mit
13,110
<?php /** * Copyright (c) 2004, 2011 Martin Takáč * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2, or (at your option) * any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * @author Martin Takáč <taco@taco-beru.name> */ require_once 'phing/BuildFileTest.php'; /** * HgUpdateTaskTest * * Loads a (text) filenames between two revision of hg. * Supports filterchains. * * @call phpunit --bootstrap ../../../bootstrap.php Tests_Unit_Phing_Tasks_Taco_Hg_HgTagTaskTest HgTagTaskTest.php */ class Tests_Unit_Phing_Tasks_Taco_Hg_HgTagTaskTest extends BuildFileTest { private $task; public function setUp() { $this->task = new HgTagTask(); } /** * Povinný přiřazení repoisitroy */ public function _testFailRepositorySet() { $this->setExpectedException('BuildException', '"repository" is required parameter'); $this->task ->main(); } /** * Povinný přiřazení repoisitroy */ public function _testRepositorySet() { $mock = $this->getMock('Taco\Utils\Process\Exec', array('setWorkDirectory', 'arg'), array('hg')); $mock->expects($this->at(0)) ->method('setWorkDirectory') ->will($this->returnSelf()); $mock->expects($this->never()) ->method('arg'); $this->task ->setExec($mock) ->setRepository(new PhingFile($this->getTempDir())) ->main(); } /** * Povinný přiřazení repoisitroy */ public function testWithArgumentsFail() { $this->setExpectedException('BuildException', 'Task exited with code: 42 and output: none'); $mock = $this->getMock('Taco\Utils\Process\Exec', array('setWorkDirectory', 'arg', 'run'), array('hg')); $mock->expects($this->at(0)) ->method('setWorkDirectory') ->will($this->returnSelf()); $mock->expects($this->at(1)) ->method('arg') ->with("-b def") ->will($this->returnSelf()); $mock->expects($this->at(2)) ->method('run') ->will($this->returnValue((object) array( 'code' => 42, 'content' => array('none') ))); $this->task ->setExec($mock) ->setRepository(new PhingFile($this->getTempDir())); $this->task->createArg()->setName('b')->setValue('def'); $this->task->main(); } /** * Povinný přiřazení repoisitroy */ public function testWithArguments() { $mock = $this->getMock('Taco\Utils\Process\Exec', array('setWorkDirectory', 'arg', 'run'), array('hg')); $mock->expects($this->at(0)) ->method('setWorkDirectory') ->will($this->returnSelf()); $mock->expects($this->at(1)) ->method('arg') ->with("-b def") ->will($this->returnSelf()); $mock->expects($this->at(2)) ->method('run') ->will($this->returnValue((object) array( 'code' => 0, 'content' => array('none') ))); $this->task ->setExec($mock) ->setRepository(new PhingFile($this->getTempDir())) ->setProject($this->getMockProject()); $this->task->createArg()->setName('b')->setValue('def'); $this->task->main(); } /** * @return string */ public function getTempDir() { return realpath(__dir__ . '/../../../../../temp'); } /** * @return mock */ public function getMockProject() { $mock = $this->getMock('Project', array('logObject')); return $mock; } }
tacoberu/phing-tasks
source/tests/tasks/taco/hg/HgTagTaskTest.php
PHP
mit
3,849
/* * This file is part of Flow Engine, licensed under the MIT License (MIT). * * Copyright (c) 2013 Spout LLC <http://www.spout.org/> * * 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.flowpowered.engine.network.handler; import com.flowpowered.api.Server; import com.flowpowered.engine.network.FlowSession; import com.flowpowered.networking.Message; import com.flowpowered.networking.MessageHandler; public class FlowMessageHandler<T extends Message> implements MessageHandler<FlowSession, T> { @Override public void handle(FlowSession session, T message) { if (session.getEngine().get(Server.class) != null) { handle0(session, message, true); } else { handle0(session, message, false); } } public void handle0(FlowSession session, T message, boolean server) { if (session.getPlayer() == null) { switch (requiresPlayer()) { case ERROR: throw new UnsupportedOperationException("Handler " + getClass() + " requires a player, but it was null!"); case IGNORE: System.out.println("Ignoring handler b/c no player"); return; } } if (server) { handleServer(session, message); } else { handleClient(session, message); } } public void handleServer(FlowSession session, T message) { throw new UnsupportedOperationException("This handler cannot handle on the server!"); } public void handleClient(FlowSession session, T message) { throw new UnsupportedOperationException("This handler cannot handle on the client!"); } public PlayerRequirement requiresPlayer() { return PlayerRequirement.NO; } public enum PlayerRequirement { NO, IGNORE, ERROR } }
flow/engine
src/main/java/com/flowpowered/engine/network/handler/FlowMessageHandler.java
Java
mit
2,915
package com.joao.pedro.nardari.locationstrategysampleproject; import android.app.AlarmManager; import android.app.PendingIntent; import android.content.Context; import android.content.Intent; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.view.View; import android.widget.Toast; import java.util.Calendar; public class MainActivity extends AppCompatActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); } public void scheduleTask(View v) { // Set time to alert user Calendar calendar = Calendar.getInstance(); calendar.setTimeInMillis(System.currentTimeMillis()); calendar.set(Calendar.HOUR_OF_DAY, 7); calendar.set(Calendar.MINUTE, 0); calendar.set(Calendar.SECOND, 0); calendar.set(Calendar.MILLISECOND, 0); // Create Intent Intent intentAlarm = new Intent(this, AlarmReceiver.class); PendingIntent pendingIntent = PendingIntent.getBroadcast(this, 1, intentAlarm, PendingIntent.FLAG_UPDATE_CURRENT); // Register AlarmManager alarmManager = (AlarmManager) getSystemService(Context.ALARM_SERVICE); alarmManager.setRepeating(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(), AlarmManager.INTERVAL_DAY, pendingIntent ); Toast.makeText(this, "Task Scheduled!",Toast.LENGTH_LONG).show(); } }
joaopedronardari/LocationStrategySampleProject
app/src/main/java/com/joao/pedro/nardari/locationstrategysampleproject/MainActivity.java
Java
mit
1,526
namespace InControl { using System; using System.IO; using UnityEngine; public class MouseBindingSource : BindingSource { public Mouse Control { get; protected set; } public static float ScaleX = 0.05f; public static float ScaleY = 0.05f; public static float ScaleZ = 0.05f; internal MouseBindingSource() { } public MouseBindingSource( Mouse mouseControl ) { Control = mouseControl; } // Unity doesn't allow mouse buttons above certain numbers on // some platforms. For example, the limit on Windows 7 appears // to be 6. internal static bool SafeGetMouseButton( int button ) { try { return Input.GetMouseButton( button ); } catch (ArgumentException) { } return false; } // This is necessary to maintain backward compatibility. :( readonly static int[] buttonTable = new[] { -1, 0, 1, 2, -1, -1, -1, -1, -1, -1, 3, 4, 5, 6, 7, 8 }; internal static bool ButtonIsPressed( Mouse control ) { var button = buttonTable[(int) control]; if (button >= 0) { return SafeGetMouseButton( button ); } return false; } public override float GetValue( InputDevice inputDevice ) { var button = buttonTable[(int) Control]; if (button >= 0) { return SafeGetMouseButton( button ) ? 1.0f : 0.0f; } switch (Control) { case Mouse.NegativeX: return -Mathf.Min( Input.GetAxisRaw( "mouse x" ) * ScaleX, 0.0f ); case Mouse.PositiveX: return Mathf.Max( 0.0f, Input.GetAxisRaw( "mouse x" ) * ScaleX ); case Mouse.NegativeY: return -Mathf.Min( Input.GetAxisRaw( "mouse y" ) * ScaleY, 0.0f ); case Mouse.PositiveY: return Mathf.Max( 0.0f, Input.GetAxisRaw( "mouse y" ) * ScaleY ); case Mouse.NegativeScrollWheel: return -Mathf.Min( Input.GetAxisRaw( "mouse z" ) * ScaleZ, 0.0f ); case Mouse.PositiveScrollWheel: return Mathf.Max( 0.0f, Input.GetAxisRaw( "mouse z" ) * ScaleZ ); } return 0.0f; } public override bool GetState( InputDevice inputDevice ) { return Utility.IsNotZero( GetValue( inputDevice ) ); } public override string Name { get { return Control.ToString(); } } public override string DeviceName { get { return "Mouse"; } } public override bool Equals( BindingSource other ) { if (other == null) { return false; } var bindingSource = other as MouseBindingSource; if (bindingSource != null) { return Control == bindingSource.Control; } return false; } public override bool Equals( object other ) { if (other == null) { return false; } var bindingSource = other as MouseBindingSource; if (bindingSource != null) { return Control == bindingSource.Control; } return false; } public override int GetHashCode() { return Control.GetHashCode(); } public override BindingSourceType BindingSourceType { get { return BindingSourceType.MouseBindingSource; } } internal override void Save( BinaryWriter writer ) { writer.Write( (int) Control ); } internal override void Load( BinaryReader reader ) { Control = (Mouse) reader.ReadInt32(); } } }
Hekaton/SolarWind
Assets/InControl/Source/Binding/MouseBindingSource.cs
C#
mit
3,202
package com.github.kennedyoliveira.asteriskjava.khomp.manager.event; import org.asteriskjava.manager.event.ManagerEvent; /** * Reports the detection of a {@code Collect Call}. * * @author kennedy */ public class CollectCallEvent extends ManagerEvent { private String channel; public CollectCallEvent(Object source) { super(source); } /** * @return The channel name in the format {@code Khomp/BxCy} where {@code x} is the Device ID and {@code y} is the Channel Number. */ public String getChannel() { return channel; } /** * Internal use. * * @param channel The channel name in the format {@code Khomp/BxCy} where {@code x} is the Device ID and {@code y} is the Channel Number. */ public void setChannel(String channel) { this.channel = channel; } }
kennedyoliveira/asterisk-java-khomp
src/main/java/com/github/kennedyoliveira/asteriskjava/khomp/manager/event/CollectCallEvent.java
Java
mit
807
/** * @author Gabriel Dodan , gabriel.dodan@gmail.com * @copyright Copyright (c) 2012 Gabriel Dodan * @license The MIT License http://www.opensource.org/licenses/mit-license.php , see LICENSE.txt file also */ /** @DEPENDENCIES = ["FORMS_LIB/controls/ListControl.js"]; */ /* wrapper for <select> tag */ Pd.Forms.Select = Pd.Forms.ListControl.extend({ init: function(name, config) { this._super(name, config); }, content : function() { var defaultAttrs = { id : this.id, name : (this.config.multipleSelect ? this.name + "[]" : this.name) }; if ( this.config.multipleSelect ) { defaultAttrs.multiple="multiple"; } var excludeAttrs = Pd.Forms.propsToArray(defaultAttrs); excludeAttrs.push("multiple"); var val, label; for(var i=0; i<this.config.dataSet.length; i++) { val = this.config.dataSet[i][0]; label = this.config.dataSet[i][1]; this.items.push( new Pd.Forms.SelectItem(val, label, Pd.Forms.inArray(val, this.config.selectedValues)) ); } var content = '' + '<select ' + Pd.Forms.objAsAttrs(defaultAttrs) + ' ' + Pd.Forms.objAsAttrs(this.config.attrs, excludeAttrs) + '>\n' + (this.config.itemsRenderer != null ? this.config.itemsRenderer(this) : this.defaultItemsRenderer(this) ) + '\n' + '</select>' ; return content + Pd.Forms.codeForBinds(this.id, this.config.binds); }, defaultItemsRenderer : function(control) { var content = []; for (var i=0; i<control.items.length; i++) { content.push( control.items[i].content() ); } return content.join("\n"); }, getValue : function() { return $("#" + this.id).val(); }, getSelectedValues : function() { return this.getValue(); } }); /* wrapper for <option> tag */ Pd.Forms.SelectItem = Pd.Forms.ListControlItem.extend({ init:function(value, label, isSelected) { this._super(value, label, isSelected); }, content:function() { var defaultAttrs = { value:this.value }; if ( this.isSelected ) { defaultAttrs.selected="selected"; } var excludeAttrs = Pd.Forms.propsToArray(defaultAttrs); excludeAttrs.push("selected"); return '<option ' + Pd.Forms.objAsAttrs(defaultAttrs) + ' ' + Pd.Forms.objAsAttrs(this.attrs, excludeAttrs) + '>' + Pd.Forms.escape(this.label) + '</option>'; } }); /* config = { name:"name", dataSet:[], selectedValues:[], multipleSelect:true|false, itemsRenderer:function(control){}, attrs:{ }, binds:{ }, validators:{ } } */
gabrieldodan/php-dancer
system/libraries/Forms/controls/Select.js
JavaScript
mit
2,461
using AppCampus.Domain.Interfaces.Repositories; using System; using System.ComponentModel.DataAnnotations; namespace AppCampus.PortalApi.Validation.ValidationAttributes { public sealed class UniqueCompanyIdAttribute : ValidationAttribute { public ICompanyRepository CompanyRepository { get; set; } public UniqueCompanyIdAttribute() : base("Company Id does not exist.") { CompanyRepository = (ICompanyRepository)Startup.HttpConfiguration.DependencyResolver.GetService(typeof(ICompanyRepository)); } public override bool IsValid(object value) { return CompanyRepository.Find(Guid.Parse(value.ToString())) == null; } } }
hendrikdelarey/appcampus
AppCampus.PortalApi/Validation/ValidationAttributes/UniqueCompanyIdAttribute.cs
C#
mit
727
'use strict'; (function(module) { const repos = {}; repos.all = []; repos.requestRepos = function(callback) { $.get('/github/user/repos') .then(data => repos.all = data, err => console.error(err)) .then(callback(repos)); }; repos.with = attr => repos.all.filter(repo => repo[attr]); module.repos = repos; })(window);
Jamesbillard12/jamesPortfolio
public/js/repo.js
JavaScript
mit
347
using System.Collections; using System.Collections.Generic; using UnityEngine; public class GameScene : MonoBehaviour { void Start () { GameController gameController = GameController.Instance; ItemSpawnManager itemSpawnManager = ItemSpawnManager.Instance; RespawnManager respawnManager = RespawnManager.Instance; gameController.BeginGame(); } void Update () { } }
sasvdw/LD37
Unity/LD37/Assets/Scripts/Scenes/GameScene.cs
C#
mit
411
import { Injectable } from '@angular/core'; import { Http, Headers, Response, RequestOptions } from '@angular/http'; import { Observable } from 'rxjs/Observable'; import { AuthenticationService, AlertService } from '../services'; import { DttType } from '../models'; import 'rxjs/add/operator/map' @Injectable() export class DttTypeService { constructor(private http: Http, private authService: AuthenticationService) { } private apiEndpointUrl: string = '/api/dttTypes'; create(dttType: DttType) { // add authorization header with jwt token let headers = new Headers({ 'Authorization': this.authService.token }); let options = new RequestOptions({ headers: headers }); return this.http.post(this.apiEndpointUrl, dttType, options) .map((response: Response) => { // login successful if there's a jwt token in the response let dttType = response.json(); if (dttType) { return dttType; } }); } update(dttType: DttType) { // add authorization header with jwt token let headers = new Headers({ 'Authorization': this.authService.token }); let options = new RequestOptions({ headers: headers }); return this.http.put(this.apiEndpointUrl + '/' + dttType._id, dttType, options) .map((response: Response) => { // update successful - return dttType let dttType = response.json(); if (dttType) { return dttType; } }); } list(query:string) { // add authorization header with jwt token let headers = new Headers({ 'Authorization': this.authService.token }); let options = new RequestOptions({ headers: headers }); query = query && query.length > 0 ? '?' + query : ''; return this.http.get(this.apiEndpointUrl + query, options) .map((response: Response) => { // login successful if there's a jwt token in the response let dttTypes = response.json() as Array<DttType>; return dttTypes; }); } get(id: string) { // add authorization header with jwt token let headers = new Headers({ 'Authorization': this.authService.token }); let options = new RequestOptions({ headers: headers }); return this.http.get(this.apiEndpointUrl + '/' + id, options) .map((response: Response) => { // login successful if there's a jwt token in the response let dttType = response.json() as DttType; return dttType; }); } delete(id: string) { // add authorization header with jwt token let headers = new Headers({ 'Authorization': this.authService.token }); let options = new RequestOptions({ headers: headers }); return this.http.delete(this.apiEndpointUrl + '/' + id, options) .map((response: Response) => { let dttType = response.json() as DttType; return dttType; }); } }
manuelnelson/patient-pal
src/client/services/dtt-type.service.ts
TypeScript
mit
3,176
<?php namespace Tangent\Bundle\BookTrackerBundle\Controller; use Symfony\Bundle\FrameworkBundle\Controller\Controller; class DefaultController extends Controller { public function indexAction($name) { return $this->render('TangentBookTrackerBundle:Default:index.html.twig', array('name' => $name)); } }
gump/book-tracker
src/Tangent/Bundle/BookTrackerBundle/Controller/DefaultController.php
PHP
mit
332
package com.grapapp.grapapp.adapter; import android.content.Context; import android.content.Intent; import android.os.Bundle; import android.support.v7.widget.RecyclerView; import android.util.Log; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.TextView; import com.grapapp.grapapp.R; import com.grapapp.grapapp.activity.TupianBaseActivity; import com.grapapp.grapapp.models.TupianTitleModel; import java.util.List; import butterknife.Bind; import butterknife.ButterKnife; import butterknife.OnClick; /** * Created by ian on 16/4/16. */ public class TupianTitleAdapter extends RecyclerView.Adapter<TupianTitleAdapter.NormalTextViewHolder> { private final LayoutInflater mLayoutInflater; private final Context mContext; private final List<TupianTitleModel> list; public TupianTitleAdapter(Context context, List<TupianTitleModel> list1) { mContext = context; this.list = list1; mLayoutInflater = LayoutInflater.from(context); } @Override public NormalTextViewHolder onCreateViewHolder(ViewGroup parent, int viewType) { return new NormalTextViewHolder(mLayoutInflater.inflate(R.layout.adapter_tupiantitle_line, parent, false)); } @Override public void onBindViewHolder(NormalTextViewHolder holder, int position) { holder.mTextView.setText(list.get(position).getTitle()); holder.mTextView.setTag(list.get(position).getPath().toString()); } @Override public int getItemCount() { return list == null ? 0 : list.size(); } public class NormalTextViewHolder extends RecyclerView.ViewHolder { @Bind(R.id.text_view) TextView mTextView; NormalTextViewHolder(View view) { super(view); ButterKnife.bind(this, view); } @OnClick(R.id.text_view) void titleClick(View view) { // TODO call server... Log.d("NormalTextViewHolder", "onClick--> position = " + getPosition()); String path = view.getTag().toString(); Bundle b = new Bundle(); b.putString("path",path); Intent i=new Intent(); i.setClass(mContext, TupianBaseActivity.class); i.putExtras(b); mContext.startActivity(i); } } }
Hz-Ryze/GrapApp
app/src/main/java/com/grapapp/grapapp/adapter/TupianTitleAdapter.java
Java
mit
2,351
require_relative 'gluey/base/version' require_relative 'gluey/base/exceptions' # environments require_relative 'gluey/base/environment' require_relative 'gluey/workshop/workshop' require_relative 'gluey/warehouse/warehouse' # addons require_relative 'gluey/base/rack_mountable'
doooby/gluey
lib/gluey.rb
Ruby
mit
281
<?php namespace Somnambulist\Tenancy\Tests\Stubs\Providers; use Illuminate\Support\ServiceProvider; class AppServiceProvider extends ServiceProvider { /** * Register any application services. * * @return void */ public function register() { $this->app->singleton('em', function ($app) { return new class { function getClassMetadata() { return []; } }; }); } /** * Bootstrap any application services. * * @return void */ public function boot() { // } }
dave-redfern/laravel-doctrine-tenancy
tests/Stubs/Providers/AppServiceProvider.php
PHP
mit
644
<?php namespace SiteBundle\Repository; /** * TagRepository * * This class was generated by the Doctrine ORM. Add your own custom * repository methods below. */ class UserGroupRepository extends \Doctrine\ORM\EntityRepository { }
firestorm23/gyrolab-ste
src/SiteBundle/Repository/UserGroupRepository.php
PHP
mit
236
<table > <?php $rq = "SELECT acquisto,utente,colloquio FROM acquisti_aperti join utenti using(utente)"; $trs = $db -> query($rq) -> fetchAll(PDO::FETCH_ASSOC); ?> <?php foreach ($trs as $k => $q) { echo "<td style=\"width:1em\" > <form name=input action=\"cassa.php\" method=POST> <input type = hidden name= acquisto value={$q['acquisto']}> <button type=submit value=\"" ; echo "{$q['colloquio']}/{$q['utente']}"; echo "\">"; echo "{$q['colloquio']} / {$q['utente']}"; echo "</button> </form></td>" ; } if ($_SESSION['acquisto'] == "") { $_SESSION['acquisto'] = $trs[0]['acquisto']; $_SESSION['utenteacquisto'] =$trs[0]['utente']; } ?> </table>
paolino/emporio
selezioneacquisto.php
PHP
mit
702
package com.swallow.core.dom; import org.w3c.dom.Element; /** * Swallow 2017-03-10 15:33 */ public interface ElementUtil { static String getAttributeValue(Element element, String name, String defaultValue) { String value = element.getAttribute(name); if (!(value == null || "".equals(value))) { return value; } return defaultValue; } static Integer getAttributeValue(Element element, String name, Integer defaultValue) { String value = element.getAttribute(name); if (!(value == null || "".equals(value))) { return Integer.parseInt(value); } return defaultValue; } }
zhuzaixiaoshulin/swallow
src/main/java/com/swallow/core/dom/ElementUtil.java
Java
mit
676
using System.Collections.Generic; namespace Magnesium.OpenGL.Internals { public class GLNextPipelineLayout : IGLPipelineLayout { public GLUniformBinding[] Bindings { get; private set; } public int NoOfBindingPoints { get; private set; } public IDictionary<int, GLBindingPointOffsetInfo> Ranges { get; private set; } public uint NoOfStorageBuffers { get; private set; } public uint NoOfExpectedDynamicOffsets { get; private set; } public GLDynamicOffsetInfo[] OffsetDestinations { get; private set; } public GLNextPipelineLayout(MgPipelineLayoutCreateInfo pCreateInfo) { if (pCreateInfo.SetLayouts.Length == 1) { var layout = (IGLDescriptorSetLayout)pCreateInfo.SetLayouts[0]; Bindings = layout.Uniforms; } else { Bindings = new GLUniformBinding[0]; } NoOfBindingPoints = 0; NoOfStorageBuffers = 0; NoOfExpectedDynamicOffsets = 0; Ranges = new SortedDictionary<int, GLBindingPointOffsetInfo>(); OffsetDestinations = ExtractBindingsInformation(); SetupOffsetRangesByBindings(); } private GLDynamicOffsetInfo[] ExtractBindingsInformation() { var signPosts = new List<GLDynamicOffsetInfo>(); // build flat slots array for uniforms foreach (var desc in Bindings) { if (desc.DescriptorType == MgDescriptorType.UNIFORM_BUFFER || desc.DescriptorType == MgDescriptorType.UNIFORM_BUFFER_DYNAMIC) { NoOfBindingPoints += (int) desc.DescriptorCount; Ranges.Add((int) desc.Binding, new GLBindingPointOffsetInfo { Binding = desc.Binding, First = 0, Last = (int) desc.DescriptorCount - 1 }); if (desc.DescriptorType == MgDescriptorType.UNIFORM_BUFFER_DYNAMIC) { signPosts.Add(new GLDynamicOffsetInfo { Target = GLBufferRangeTarget.UNIFORM_BUFFER, DstIndex = NoOfExpectedDynamicOffsets, }); NoOfExpectedDynamicOffsets += desc.DescriptorCount; } } else if (desc.DescriptorType == MgDescriptorType.STORAGE_BUFFER || desc.DescriptorType == MgDescriptorType.STORAGE_BUFFER_DYNAMIC) { NoOfStorageBuffers += desc.DescriptorCount; if (desc.DescriptorType == MgDescriptorType.STORAGE_BUFFER_DYNAMIC) { signPosts.Add(new GLDynamicOffsetInfo { Target = GLBufferRangeTarget.STORAGE_BUFFER, DstIndex = desc.Binding, }); NoOfExpectedDynamicOffsets += desc.DescriptorCount; } } } return signPosts.ToArray(); } void SetupOffsetRangesByBindings() { var startingOffset = 0; foreach (var g in Ranges.Values) { g.First += startingOffset; g.Last += startingOffset; startingOffset = g.Last + 1; } } public bool Equals(IGLPipelineLayout other) { if (other == null) return false; if (ReferenceEquals(this, other)) return true; if (NoOfBindingPoints != other.NoOfBindingPoints) return false; if (NoOfExpectedDynamicOffsets != other.NoOfExpectedDynamicOffsets) return false; if (NoOfStorageBuffers != other.NoOfStorageBuffers) return false; if (Bindings != null && other.Bindings == null) return false; if (Bindings == null && other.Bindings != null) return false; if (OffsetDestinations != null && other.OffsetDestinations == null) return false; if (OffsetDestinations == null && other.OffsetDestinations != null) return false; if (Ranges != null && other.Ranges == null) return false; if (Ranges == null && other.Ranges != null) return false; if (Bindings.Length != other.Bindings.Length) return false; { var count = Bindings.Length; for (var i = 0; i < count; i += 1) { var left = Bindings[i]; var right = other.Bindings[i]; if (!left.Equals(right)) return false; } } if (OffsetDestinations.Length != other.OffsetDestinations.Length) return false; { var count = OffsetDestinations.Length; for (var i = 0; i < count; i += 1) { var left = OffsetDestinations[i]; var right = other.OffsetDestinations[i]; if (!left.Equals(right)) return false; } } if (Ranges.Count != other.Ranges.Count) return false; return Ranges.Equals(other.Ranges); } #region IMgPipelineLayout implementation private bool mIsDisposed = false; public void DestroyPipelineLayout(IMgDevice device, IMgAllocationCallbacks allocator) { if (mIsDisposed) return; mIsDisposed = true; } #endregion } }
tgsstdio/Mg
Magnesium.OpenGL/DescriptorSets/GLNextPipelineLayout.cs
C#
mit
4,510
'use strict' const sprockets = require( __dirname + '/../../src/sprockets' ) const mkdir = require( __dirname + '/../../utils/mkdir' ) const fs = require( 'fs' ) let input = './src/index.html' let output = './build/index.html' sprockets.add( 'index', ( done ) => { mkdir( output ) fs.createReadStream( input ) .on( 'end', function () { done() } ) .pipe( fs.createWriteStream( output ) ) } )
vladfilipro/sprockets
tasks/compile/index.js
JavaScript
mit
417
/** * */ package net.caiban.auth.dashboard.dao.bs.impl; import java.util.HashMap; import java.util.List; import java.util.Map; import javax.annotation.Resource; import net.caiban.auth.dashboard.dao.BaseDao; import net.caiban.auth.dashboard.dao.bs.BsDao; import net.caiban.auth.dashboard.domain.bs.Bs; import net.caiban.auth.dashboard.domain.staff.Dept; import net.caiban.auth.dashboard.domain.staff.Staff; import net.caiban.auth.dashboard.dto.PageDto; import net.caiban.auth.dashboard.dto.staff.StaffDto; import org.springframework.context.MessageSource; import org.springframework.stereotype.Component; /** * @author root * */ @Component("bsDao") public class BsDaoImpl extends BaseDao implements BsDao { final static String SQL_PREFIX="bs"; @Resource private MessageSource messageSource; @Override public Integer countBsOfDept(Integer deptId, String projectCode) { // Assert.notNull(deptId, messageSource.getMessage("assert.notnull", new String[] { "deptId" }, null)); Map<String, Object> root = new HashMap<String, Object>(); root.put("deptId", deptId); root.put("code", projectCode); return (Integer) getSqlMapClientTemplate().queryForObject(buildId(SQL_PREFIX, "countBsOfDept"), root); } @Override public Integer countBsOfStaff(Integer staffId, String projectCode) { // Assert.notNull(staffId, messageSource.getMessage("assert.notnull", new String[] { "staffId" }, null)); Map<String,Object> root =new HashMap<String,Object>(); root.put("staffId", staffId); root.put("code", projectCode); return (Integer)getSqlMapClientTemplate().queryForObject(buildId(SQL_PREFIX, "countBsOfStaff"),root); } @SuppressWarnings("unchecked") @Override public List<Bs> queryBsOfDept(Integer deptId, String types) { // Assert.notNull(deptId, messageSource.getMessage("assert.notnull", new String[] { "deptId" }, null)); Map<String,Object> root=new HashMap<String,Object>(); root.put("deptId", deptId); root.put("types",types); return getSqlMapClientTemplate().queryForList(buildId(SQL_PREFIX,"queryBsOfDept"),root); } @SuppressWarnings("unchecked") @Override public List<Bs> queryBsOfStaff(Integer staffId, String types) { // Assert.notNull(staffId, messageSource.getMessage("assert.notnull", new String[] { "staffId" }, null)); Map<String,Object> root=new HashMap<String,Object>(); root.put("staffId", staffId); root.put("types", types); return getSqlMapClientTemplate().queryForList(buildId(SQL_PREFIX,"queryBsOfStaff"),root); } @Override public String queryRightCodeOfBs(String projectCode) { // Assert.notNull(projectCode, messageSource.getMessage("assert.notnull", new String[] { "projectCode" }, null)); return (String)getSqlMapClientTemplate().queryForObject(buildId(SQL_PREFIX,"queryRightCodeOfBs"),projectCode); } @Override public String queryPasswordOfBs(String pcode) { return (String) getSqlMapClientTemplate().queryForObject(buildId(SQL_PREFIX, "queryPasswordOfBs"), pcode); } @Override public Integer insertBs(Bs bs) { return (Integer) getSqlMapClientTemplate().insert(buildId(SQL_PREFIX, "insertBs"), bs); } @Override public Integer deleteBs(Integer id) { return getSqlMapClientTemplate().delete(buildId(SQL_PREFIX, "deleteBs"), id); } @Override public Integer updateBs(Bs bs) { return getSqlMapClientTemplate().update(buildId(SQL_PREFIX, "updateBs"),bs); } @SuppressWarnings("unchecked") @Override public List<Bs> queryBs(Bs bs, PageDto<Bs> page) { Map<String, Object> root=new HashMap<String,Object>(); root.put("bs", bs); root.put("page", page); return getSqlMapClientTemplate().queryForList(buildId(SQL_PREFIX,"queryBs"),root); } @Override public Integer queryBsCount(Bs bs) { Map<String,Object> root=new HashMap<String,Object>(); root.put("bs", bs); return (Integer) getSqlMapClientTemplate().queryForObject(buildId(SQL_PREFIX, "queryBsCount"),root); } @Override public Bs queryOneBs(Integer id) { return (Bs) getSqlMapClientTemplate().queryForObject(buildId(SQL_PREFIX, "queryOneBs"), id); } @SuppressWarnings("unchecked") @Override public List<Staff> queryStaffByBs(Integer id, String types) { Map<String,Object> root=new HashMap<String,Object>(); root.put("id", id); root.put("types", types); return getSqlMapClientTemplate().queryForList(buildId(SQL_PREFIX, "queryStaffByBs"), root); } @SuppressWarnings("unchecked") @Override public List<Dept> queryDeptByBs(Integer id, String types) { Map<String,Object> root=new HashMap<String,Object>(); root.put("id", id); root.put("types", types); return getSqlMapClientTemplate().queryForList(buildId(SQL_PREFIX, "queryDeptByBs"),root); } @SuppressWarnings("unchecked") @Override public List<Integer> queryDeptIdByBsId(Integer bsId) { return getSqlMapClientTemplate().queryForList(buildId(SQL_PREFIX, "queryDeptIdByBsId"), bsId); } @SuppressWarnings("unchecked") @Override public List<StaffDto> queryBsStaff(Integer bsId) { return getSqlMapClientTemplate().queryForList(buildId(SQL_PREFIX, "queryBsStaff"), bsId); } @Override public Integer insertBsStaff(Integer bsId, Integer staffId) { Map<String, Object> root=new HashMap<String, Object>(); root.put("bsId", bsId); root.put("staffId", staffId); return (Integer) getSqlMapClientTemplate().insert(buildId(SQL_PREFIX, "insertBsStaff"),root); } @Override public Integer deleteBsStaff(Integer bsId, Integer staffId) { Map<String, Object> root=new HashMap<String, Object>(); root.put("bsId", bsId); root.put("staffId", staffId); return (Integer) getSqlMapClientTemplate().delete(buildId(SQL_PREFIX, "deleteBsStaff"),root); } @Override public Integer deleteBsDept(Integer bsId, Integer deptId) { Map<String, Object> root=new HashMap<String, Object>(); root.put("bsId", bsId); root.put("deptId", deptId); return getSqlMapClientTemplate().delete(buildId(SQL_PREFIX, "deleteBsDept"), root); } @Override public Integer insertBsDept(Integer bsId, Integer deptId) { Map<String, Object> root=new HashMap<String, Object>(); root.put("bsId", bsId); root.put("deptId", deptId); return (Integer) getSqlMapClientTemplate().insert(buildId(SQL_PREFIX, "insertBsDept"), root); } @Override public Integer deleteBsDept(Integer bsId) { return getSqlMapClientTemplate().delete(buildId(SQL_PREFIX, "deleteBsDeptByBsId"), bsId); } @Override public Integer deleteBsStaff(Integer bsId) { return getSqlMapClientTemplate().delete(buildId(SQL_PREFIX, "deleteBsStaffByBsId"), bsId); } @Override public String queryUrl(String key) { return (String) getSqlMapClientTemplate().queryForObject(SQL_PREFIX, "queryUrl"); } /***************************/ /* public Integer countPageBs(Bs bs) { Assert.notNull(bs, "bs is not null"); return (Integer) getSqlMapClientTemplate().queryForObject( "bs.countPageBs", bs); } @SuppressWarnings("unchecked") public List<Bs> queryMyBsByStaffId(Integer staffId, String types) { Assert.notNull(staffId, "staffId is not null"); Map<String, Object> root = new HashMap<String, Object>(); root.put("staffId", staffId); root.put("types", types); return getSqlMapClientTemplate().queryForList(buildId(SQL_PREFIX, "queryMyBsByStaffId"), root); } @SuppressWarnings("unchecked") public List<Bs> queryMyBsByDeptId(Integer deptId, String types) { Assert.notNull(deptId, "deptId is not null"); Map<String, Object> root = new HashMap<String, Object>(); root.put("deptId", deptId); root.put("types", types); return getSqlMapClientTemplate().queryForList("bs.queryMyBsByDeptId", root); } public Integer insertBs(Bs bs) { Assert.notNull(bs, "bs is not null"); return (Integer) getSqlMapClientTemplate().insert("bs.insertBs", bs); } public Integer updateBs(Bs bs) { Assert.notNull(bs, "bs is not null"); return getSqlMapClientTemplate().update("bs.updateBs", bs); } @SuppressWarnings("unchecked") public List<BsDto> pageBsByBsDo(Bs bs, PageDto page) { Assert.notNull(bs, "bs is not null"); Assert.notNull(page, "page is not null"); Map<String, Object> map = new HashMap<String, Object>(); map.put("bs", bs); map.put("page", page); return getSqlMapClientTemplate().queryForList("bs.pageBsByBsDo", map); } */ }
yysoft/yy-auth
auth-dashboard/src/main/java/net/caiban/auth/dashboard/dao/bs/impl/BsDaoImpl.java
Java
mit
8,217
package demo.rest; import demo.domain.RunningInfo; import demo.service.RunningInfoService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.data.domain.Page; import org.springframework.data.domain.PageRequest; import org.springframework.http.HttpStatus; import org.springframework.web.bind.annotation.*; import java.util.List; @RestController public class RunningInfoRestController { private RunningInfoService runningInfoService; @Autowired public RunningInfoRestController(RunningInfoService runningInfoService){ this.runningInfoService = runningInfoService; } @RequestMapping(value = "/upload", method = RequestMethod.POST) @ResponseStatus(HttpStatus.CREATED) public void upload(@RequestBody List<RunningInfo> runningInfos){ this.runningInfoService.saveRunningInfos(runningInfos); } @RequestMapping(value = "/delete/all", method = RequestMethod.POST) public void purge() { this.runningInfoService.deleteAll(); } @RequestMapping(value = "/search/pagingByWarning", method = RequestMethod.GET) Page<RunningInfo> findAllByOrderByHealthWarningLevelDescHeartRateDesc(@RequestParam(name = "page") int page){ return this.runningInfoService.findAllByOrderByHealthWarningLevelDescHeartRateDesc(new PageRequest(page,2)); } @RequestMapping(value = "/delete/{runningId}", method = RequestMethod.POST) public void deleteByRunningId(@PathVariable String runningId) { this.runningInfoService.deleteByRunningId(runningId); } }
zjxjasper/running-info-service
src/main/java/demo/rest/RunningInfoRestController.java
Java
mit
1,573
import {Injectable, EventEmitter, Inject, ElementRef, Renderer, Renderer2} from '@angular/core'; import { DOCUMENT } from '@angular/platform-browser'; import { Router } from '@angular/router'; import { MetaModel } from './meta.model'; export class MetaService { public url: EventEmitter<string> = new EventEmitter<string>(); public _url: string; public _safeurl: string; private _r: Renderer; private _document: any; private headElement: any;//HTMLElement; private ogTitle: HTMLElement; private ogType: HTMLElement; private ogUrl: HTMLElement; private ogImage: HTMLElement; private ogDescription: HTMLElement; private description: HTMLElement; private canonical: HTMLElement; private router: Router; constructor(renderer: Renderer, router: Router) { this._r = renderer; this._document = document; this.headElement = this._document.head; this.router = router; this.ogTitle = this.getOrCreateMetaElement('og:title', 'property'); this.ogImage = this.getOrCreateMetaElement('og:image', 'property'); this.ogDescription = this.getOrCreateMetaElement('og:description', 'property'); this.ogUrl = this.getOrCreateMetaElement('og:url', 'property'); this.description = this.getOrCreateMetaElement('description', 'name'); this.canonical = this.getOrCreateCanonical(); } public set(model: MetaModel) { this.setTitle(model.title, "Lego Dimensions Builder"); this.setAttr(this.description, model.description); this.setAttr(this.ogTitle, model.title); this.setAttr(this.ogDescription, model.description); if (model.image) { this.setAttr(this.ogImage, 'http://dimensions-builder.com' + model.image); } else { this.setAttr(this.ogImage, 'http://dimensions-builder.com/assets/images/lego-dimensions.jpg'); } if (model.canonical !== undefined) { this._url = 'http://dimensions-builder.com' + model.canonical; } else { this._url = 'http://dimensions-builder.com' + this.router.url; } this._safeurl = this._url.replace(':', '%3A'); this.setAttr(this.ogUrl, this._url); this.setAttr(this.canonical, this._url, 'href'); this.url.emit(this._url); } public setTitle(siteTitle = '', pageTitle ='', separator = ' - '){ let title = siteTitle; if (!title) { title = pageTitle + separator + 'All about abilities, characters, levels and more'; } else { if (pageTitle != '') { title += separator + pageTitle; } } this._document.title = title; } private getOrCreateMetaElement(name: string,attr: string): HTMLElement { let el: HTMLElement; var prop = ((attr != null)? attr : 'name'); el = this._r.createElement(this.headElement, 'meta'); this._r.setElementAttribute(el, prop, name); return el; } private getOrCreateCanonical(): HTMLElement { let el: HTMLElement; el = this._r.createElement(this.headElement, 'link'); this._r.setElementAttribute(el, 'rel', 'canonical'); return el; } private setAttr(el: HTMLElement, value: string, property: string = 'content') { this._r.setElementAttribute(el, property, value); } }
schmist/dimensions-builder
src/app/meta/meta.service.ts
TypeScript
mit
3,420
const create = require('./create') const geom2 = require('../geometry/geom2') const fromPoints = points => { const geometry = geom2.fromPoints(points) const newShape = create() newShape.geometry = geometry return newShape } module.exports = fromPoints
jscad/csg.js
src/core/shape2/fromPoints.js
JavaScript
mit
262
package com.plexobject.rx.util; import java.util.Spliterator; import java.util.function.Consumer; public class ArraySpliterator<T> implements Spliterator<T> { private final Object[] array; private int origin; // current index, advanced on split or traversal private final int fence; // one past the greatest index public ArraySpliterator(Object[] array, int origin, int fence) { this.array = array; this.origin = origin; this.fence = fence; } @SuppressWarnings("unchecked") public void forEachRemaining(Consumer<? super T> action) { for (; origin < fence; origin++) action.accept((T) array[origin]); } @SuppressWarnings("unchecked") public boolean tryAdvance(Consumer<? super T> action) { if (origin < fence) { action.accept((T) array[origin]); origin++; return true; } else // cannot advance return false; } public Spliterator<T> trySplit() { int lo = origin; // divide range in half int mid = ((lo + fence) >>> 1) & ~1; // force midpoint to be even if (lo < mid) { // split out left half origin = mid; // reset this Spliterator's origin return new ArraySpliterator<>(array, lo, mid); } else // too small to split return null; } public long estimateSize() { return (long) (fence - origin); } public int characteristics() { return ORDERED | SIZED | IMMUTABLE | SUBSIZED; } }
bhatti/RxJava8
src/test/java/com/plexobject/rx/util/ArraySpliterator.java
Java
mit
1,567
/**************************************************************************** Copyright (c) 2010-2011 cocos2d-x.org Copyright (c) 2008-2010 Ricardo Quesada http://www.cocos2d-x.org 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. ****************************************************************************/ #include "CCScene.h" #include "CCPointExtension.h" #include "CCDirector.h" namespace cocos2d { CCScene::CCScene() { m_bIsRelativeAnchorPoint = false; m_tAnchorPoint = ccp(0.5f, 0.5f); m_eSceneType = ccNormalScene; } CCScene::~CCScene() { } bool CCScene::init() { bool bRet = false; do { CCDirector * pDirector; CC_BREAK_IF( ! (pDirector = CCDirector::sharedDirector()) ); this->setContentSize(pDirector->getWinSize()); // success bRet = true; } while (0); return bRet; } CCScene *CCScene::node() { CCScene *pRet = new CCScene(); if (pRet && pRet->init()) { pRet->autorelease(); return pRet; } else { CC_SAFE_DELETE(pRet) return NULL; } } }//namespace cocos2d
DmitriyKirakosyan/testNinjaX
libs/cocos2dx/layers_scenes_transitions_nodes/CCScene.cpp
C++
mit
2,012
<?php namespace Fallen\FallenBundle\Form; use Symfony\Component\Form\AbstractType; use Symfony\Component\Form\FormBuilderInterface; class ContactType extends AbstractType { public function buildForm(FormBuilderInterface $builder, array $options) { $builder->add('email', 'email', array('attr'=>array('class'=>'form-control'))); $builder->add('sujet', 'text', array('attr'=>array('class'=>'form-control'))); $builder->add('message', 'textarea', array('attr'=>array('class'=>'form-control'))); $builder->add('captcha', 'genemu_recaptcha',array('mapped'=>false)); } public function getName() { return 'contact'; } }
laureenw/Projet-Symfony2
src/Fallen/FallenBundle/Form/ContactType.php
PHP
mit
681
using UnityEngine; using System.Collections; using System.Collections.Generic; // source: https://forum.unity3d.com/threads/a-free-simple-smooth-mouselook.73117/#post-3101292 // added: lockCursor namespace UnityLibrary { public class SmoothMouseLookAveraged : MonoBehaviour { [Header("Info")] private List<float> _rotArrayX = new List<float>(); // TODO: could use fixed array, or queue private List<float> _rotArrayY = new List<float>(); private float rotAverageX; private float rotAverageY; private float mouseDeltaX; private float mouseDeltaY; [Header("Settings")] public float _sensitivityX = 1.5f; public float _sensitivityY = 1.5f; [Tooltip("The more steps, the smoother it will be.")] public int _averageFromThisManySteps = 3; public bool lockCursor = false; [Header("References")] [Tooltip("Object to be rotated when mouse moves left/right.")] public Transform _playerRootT; [Tooltip("Object to be rotated when mouse moves up/down.")] public Transform _cameraT; //============================================ // FUNCTIONS (UNITY) //============================================ void Start() { Cursor.visible = !lockCursor; } void Update() { HandleCursorLock(); MouseLookAveraged(); } //============================================ // FUNCTIONS (CUSTOM) //============================================ void HandleCursorLock() { // pressing esc toggles between hide/show and lock/unlock cursor if (Input.GetKeyDown(KeyCode.Escape)) { lockCursor = !lockCursor; } // Ensure the cursor is always locked when set Cursor.lockState = lockCursor ? CursorLockMode.Locked : CursorLockMode.None; Cursor.visible = !lockCursor; } void MouseLookAveraged() { rotAverageX = 0f; rotAverageY = 0f; mouseDeltaX = 0f; mouseDeltaY = 0f; mouseDeltaX += Input.GetAxis("Mouse X") * _sensitivityX; mouseDeltaY += Input.GetAxis("Mouse Y") * _sensitivityY; // Add current rot to list, at end _rotArrayX.Add(mouseDeltaX); _rotArrayY.Add(mouseDeltaY); // Reached max number of steps? Remove oldest from list if (_rotArrayX.Count >= _averageFromThisManySteps) _rotArrayX.RemoveAt(0); if (_rotArrayY.Count >= _averageFromThisManySteps) _rotArrayY.RemoveAt(0); // Add all of these rotations together for (int i_counterX = 0; i_counterX < _rotArrayX.Count; i_counterX++) rotAverageX += _rotArrayX[i_counterX]; for (int i_counterY = 0; i_counterY < _rotArrayY.Count; i_counterY++) rotAverageY += _rotArrayY[i_counterY]; // Get average rotAverageX /= _rotArrayX.Count; rotAverageY /= _rotArrayY.Count; // Apply _playerRootT.Rotate(0f, rotAverageX, 0f, Space.World); _cameraT.Rotate(-rotAverageY, 0f, 0f, Space.Self); } } }
UnityCommunity/UnityLibrary
Assets/Scripts/Camera/SmoothMouseLookAveraged.cs
C#
mit
3,365
<?php declare(strict_types=1); namespace WyriHaximus\Travis\Resource\Sync; use ApiClients\Foundation\Hydrator\CommandBus\Command\BuildAsyncFromSyncCommand; use Rx\React\Promise; use WyriHaximus\Travis\Resource\Repository as BaseRepository; use WyriHaximus\Travis\Resource\RepositoryInterface; use WyriHaximus\Travis\Resource\RepositoryKeyInterface; use WyriHaximus\Travis\Resource\SettingsInterface; use function React\Promise\resolve; class Repository extends BaseRepository { /** * @return array */ public function builds(): array { return $this->wait( $this->handleCommand( new BuildAsyncFromSyncCommand(self::HYDRATE_CLASS, $this) )->then(function (RepositoryInterface $repository) { return Promise::fromObservable($repository->builds()->toArray()); }) ); } /** * @param int $id * @return Build */ public function build(int $id): Build { return $this->wait( $this->handleCommand( new BuildAsyncFromSyncCommand(self::HYDRATE_CLASS, $this) )->then(function (RepositoryInterface $repository) use ($id) { return $repository->build($id); }) ); } /** * @return array */ public function commits(): array { return $this->wait( $this->handleCommand( new BuildAsyncFromSyncCommand(self::HYDRATE_CLASS, $this) )->then(function (RepositoryInterface $repository) { return Promise::fromObservable($repository->commits()->toArray()); }) ); } /** * @return SettingsInterface */ public function settings(): SettingsInterface { return $this->wait( $this->handleCommand( new BuildAsyncFromSyncCommand(self::HYDRATE_CLASS, $this) )->then(function (RepositoryInterface $repository) { return $repository->settings(); }) ); } /** * @return bool */ public function isActive(): bool { return $this->wait( $this->handleCommand( new BuildAsyncFromSyncCommand(self::HYDRATE_CLASS, $this) )->then(function (RepositoryInterface $repository) { return $repository->isActive(); })->otherwise(function (bool $state) { return resolve($state); }) ); } /** * @return Repository */ public function enable(): Repository { return $this->wait( $this->handleCommand( new BuildAsyncFromSyncCommand(self::HYDRATE_CLASS, $this) )->then(function (RepositoryInterface $repository) { return $repository->enable(); }) ); } /** * @return Repository */ public function disable(): Repository { return $this->wait( $this->handleCommand( new BuildAsyncFromSyncCommand(self::HYDRATE_CLASS, $this) )->then(function (RepositoryInterface $repository) { return $repository->disable(); }) ); } /** * @return array */ public function branches(): array { return $this->wait( $this->handleCommand( new BuildAsyncFromSyncCommand(self::HYDRATE_CLASS, $this) )->then(function (RepositoryInterface $repository) { return Promise::fromObservable($repository->branches()->toArray()); }) ); } /** * @return array */ public function vars(): array { return $this->wait( $this->handleCommand( new BuildAsyncFromSyncCommand(self::HYDRATE_CLASS, $this) )->then(function (RepositoryInterface $repository) { return Promise::fromObservable($repository->vars()->toArray()); }) ); } /** * @return array */ public function caches(): array { return $this->wait( $this->handleCommand( new BuildAsyncFromSyncCommand(self::HYDRATE_CLASS, $this) )->then(function (RepositoryInterface $repository) { return Promise::fromObservable($repository->caches()->toArray()); }) ); } /** * @return RepositoryKeyInterface */ public function key(): RepositoryKeyInterface { return $this->wait( $this->handleCommand( new BuildAsyncFromSyncCommand(self::HYDRATE_CLASS, $this) )->then(function (RepositoryInterface $repository) { return $repository->key(); }) ); } /** * @return Repository */ public function refresh() : Repository { return $this->wait( $this->handleCommand( new BuildAsyncFromSyncCommand(self::HYDRATE_CLASS, $this) )->then(function (RepositoryInterface $repository) { return $repository->refresh(); }) ); } }
WyriHaximus/php-travis-client
src/Resource/Sync/Repository.php
PHP
mit
5,196
namespace EnergyTrading.MDM.Test.Services { using System.Collections.Generic; using NUnit.Framework; using Moq; using EnergyTrading.Data; using EnergyTrading.Mapping; using EnergyTrading.Search; using EnergyTrading.Validation; using EnergyTrading.MDM.Services; [TestFixture] public class SourceSystemCreateFixture { [Test] [ExpectedException(typeof(ValidationException))] public void NullContractInvalid() { // Arrange var validatorFactory = new Mock<IValidatorEngine>(); var mappingEngine = new Mock<IMappingEngine>(); var repository = new Mock<IRepository>(); var searchCache = new Mock<ISearchCache>(); var service = new SourceSystemService(validatorFactory.Object, mappingEngine.Object, repository.Object, searchCache.Object); validatorFactory.Setup(x => x.IsValid(It.IsAny<object>(), It.IsAny<IList<IRule>>())).Returns(false); // Act service.Create(null); } [Test] [ExpectedException(typeof(ValidationException))] public void InvalidContractNotSaved() { // Arrange var validatorFactory = new Mock<IValidatorEngine>(); var mappingEngine = new Mock<IMappingEngine>(); var repository = new Mock<IRepository>(); var searchCache = new Mock<ISearchCache>(); var service = new SourceSystemService(validatorFactory.Object, mappingEngine.Object, repository.Object, searchCache.Object); var contract = new EnergyTrading.Mdm.Contracts.SourceSystem(); validatorFactory.Setup(x => x.IsValid(It.IsAny<object>(), It.IsAny<IList<IRule>>())).Returns(false); // Act service.Create(contract); } [Test] public void ValidContractIsSaved() { // Arrange var validatorFactory = new Mock<IValidatorEngine>(); var mappingEngine = new Mock<IMappingEngine>(); var repository = new Mock<IRepository>(); var searchCache = new Mock<ISearchCache>(); var service = new SourceSystemService(validatorFactory.Object, mappingEngine.Object, repository.Object, searchCache.Object); var sourcesystem = new SourceSystem(); var contract = new EnergyTrading.Mdm.Contracts.SourceSystem(); validatorFactory.Setup(x => x.IsValid(It.IsAny<EnergyTrading.Mdm.Contracts.SourceSystem>(), It.IsAny<IList<IRule>>())).Returns(true); mappingEngine.Setup(x => x.Map<EnergyTrading.Mdm.Contracts.SourceSystem, SourceSystem>(contract)).Returns(sourcesystem); // Act var expected = service.Create(contract); // Assert Assert.AreSame(expected, sourcesystem, "SourceSystem differs"); repository.Verify(x => x.Add(sourcesystem)); repository.Verify(x => x.Flush()); } } }
RWE-Nexus/EnergyTrading-MDM-Sample
Code/Service/MDM.UnitTest.Sample/Services/SourceSystemCreateFixture.cs
C#
mit
2,997
//////////////////////////////////////////////////////////////////////////////// // // keytreeutil.h // // Copyright (c) 2013-2014 Tim Lee // // 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. #include "keytreeutil.h" #include <sstream> namespace KeyTreeUtil { uchar_vector extKeyBase58OrHexToBytes(const std::string& extKey) { uchar_vector extendedKey; if (isBase58CheckValid(extKey)) extendedKey = fromBase58ExtKey(extKey); else if (StringUtils::isHex(extKey)) extendedKey = uchar_vector(extKey); else throw std::runtime_error("Invalid extended key. Extended key must be in base58 or hex form."); return extendedKey; } uchar_vector fromBase58ExtKey(const std::string& extKey) { static unsigned int dummy = 0; uchar_vector fillKey; fromBase58Check(extKey, fillKey, dummy); static const std::string VERSION_BYTE("04"); return uchar_vector(VERSION_BYTE+fillKey.getHex()); //append VERSION_BYTE to begining } TreeChains parseChainString(const std::string& chainStr, bool isPrivate) { TreeChains treeChains; const std::string s = StringUtils::split(chainStr)[0]; //trim trailing whitespaces std::deque<std::string> splitChain = StringUtils::split(s, '/'); if (splitChain[0] != "m") throw std::runtime_error("Invalid Chain string."); //account for root node treeChains.push_back(IsPrivateNPathRange(true , Range(NODE_IDX_M, NODE_IDX_M))); if (splitChain.back() == "") splitChain.pop_back(); // happens if chainStr has '/' at end splitChain.pop_front(); for (std::string& node : splitChain) { if (node.back() == '\'') { if (! isPrivate) throw std::runtime_error("Invalid chain "+ chainStr+ ", not private extended key."); node = node.substr(0,node.length()-1); if (node.front() == '(' && node.back() == ')') { IsPrivateNPathRange range = parseRange(node, true); treeChains.push_back(range); } else { uint32_t num = toPrime(std::stoi(node)); if (num == NODE_IDX_M) throw std::invalid_argument("Invalid arguments. Invalid Range: " + std::to_string(num)); treeChains.push_back(IsPrivateNPathRange(true , Range(num, num))); } } else { if (node.front() == '(' && node.back() == ')') { IsPrivateNPathRange range = parseRange(node, false); treeChains.push_back(range); } else { uint32_t num = std::stoi(node); if (num == NODE_IDX_M) throw std::invalid_argument("Invalid arguments. Invalid Range: " + std::to_string(num)); treeChains.push_back(IsPrivateNPathRange(false , Range(num, num))); } } } return treeChains; } IsPrivateNPathRange parseRange(const std::string node, bool isPrivate) { //node must be like (123-9345) const std::string minMaxString = node.substr(1,node.length()-2); const std::deque<std::string> minMaxPair = StringUtils::split(minMaxString, '-'); if (minMaxPair.size() != 2) throw std::invalid_argument("Invalid arguments."); uint32_t min = std::stoi(minMaxPair[0]); uint32_t max = std::stoi(minMaxPair[1]); if (min == NODE_IDX_M) throw std::invalid_argument("Invalid arguments. Invalid Range: " + std::to_string(min)); if (max == NODE_IDX_M) throw std::invalid_argument("Invalid arguments. Invalid Range: " + std::to_string(max)); if (isPrivate) { return IsPrivateNPathRange(true, Range(min, max)); } else { return IsPrivateNPathRange(false, Range(min, max)); } } std::string iToString(uint32_t i) { std::stringstream ss; ss << (0x7fffffff & i); if (isPrime(i)) { ss << "'"; } return ss.str(); } }
stequald/KeyTree-qt
keytree-qt/keytreeutil.cpp
C++
mit
5,198
'use strict'; var users = require('../../app/controllers/users.server.controller'), streams = require('../../app/controllers/streams.server.controller'); module.exports = function(app){ app.route('/api/streams') .get(streams.list) .post(users.requiresLogin, streams.create); app.route('/api/streams/:streamId') .get(streams.read) .put(users.requiresLogin, streams.hasAuthorization, streams.update) .delete(users.requiresLogin, streams.hasAuthorization, streams.delete); app.param('streamId', streams.streamByID); };
plonsker/onetwo
app/routes/streams.server.routes.js
JavaScript
mit
599
import Reflux from 'reflux'; //TODO: recheck the flow of these actions 'cause it doesn't seem to be OK export default Reflux.createActions([ 'eventPartsReady', 'eventPartsUpdate' ]);
fk1blow/repeak
src/client/actions/event-part-actions.js
JavaScript
mit
188
import { ConfigParams } from './ConfigParams'; /** * Interface that can be implemented by classes that need to read ConfigParams from a certain * source. Contains the abstract method {@link #readConfig}, which, upon implementation, should contain * the logic necessary for reading and parsing ConfigParams. * * @see ConfigReader */ export interface IConfigReader { /** * Abstract method that will contain the logic of reading and parsing ConfigParams * in classes that implement this abstract class. * * @param correlationId unique business transaction id to trace calls across components. * @param parameters ConfigParams to read. * @param callback callback function that will be called with an error or with the * ConfigParams that were read. */ readConfig(correlationId: string, parameters: ConfigParams, callback: (err: any, config: ConfigParams) => void): void; }
pip-services/pip-services-commons-node
src/config/IConfigReader.ts
TypeScript
mit
1,008
<?php namespace ProductBundle\Form; use Symfony\Component\Form\AbstractType; use Symfony\Component\Form\FormBuilderInterface; use Symfony\Component\OptionsResolver\OptionsResolverInterface; class SausHotType extends AbstractType { /** * @param FormBuilderInterface $builder * @param array $options */ public function buildForm(FormBuilderInterface $builder, array $options) { $builder ->add('name') ->add('available') ; } /** * @param OptionsResolverInterface $resolver */ public function setDefaultOptions(OptionsResolverInterface $resolver) { $resolver->setDefaults(array( 'data_class' => 'ProductBundle\Entity\SausHot' )); } /** * @return string */ public function getName() { return 'productbundle_saushot'; } }
Kelevari/webshop-opdracht
src/ProductBundle/Form/SausHotType.php
PHP
mit
884
// ReSharper disable All using System; using System.Configuration; using System.Diagnostics; using System.Net.Http; using System.Runtime.Caching; using System.Web.Http; using System.Web.Http.Controllers; using System.Web.Http.Dispatcher; using System.Web.Http.Hosting; using System.Web.Http.Routing; using Xunit; namespace Frapid.Config.Api.Tests { public class AppRouteTests { [Theory] [InlineData("/api/{apiVersionNumber}/config/app/delete/{appName}", "DELETE", typeof(AppController), "Delete")] [InlineData("/api/config/app/delete/{appName}", "DELETE", typeof(AppController), "Delete")] [InlineData("/api/{apiVersionNumber}/config/app/edit/{appName}", "PUT", typeof(AppController), "Edit")] [InlineData("/api/config/app/edit/{appName}", "PUT", typeof(AppController), "Edit")] [InlineData("/api/{apiVersionNumber}/config/app/count-where", "POST", typeof(AppController), "CountWhere")] [InlineData("/api/config/app/count-where", "POST", typeof(AppController), "CountWhere")] [InlineData("/api/{apiVersionNumber}/config/app/get-where/{pageNumber}", "POST", typeof(AppController), "GetWhere")] [InlineData("/api/config/app/get-where/{pageNumber}", "POST", typeof(AppController), "GetWhere")] [InlineData("/api/{apiVersionNumber}/config/app/add-or-edit", "POST", typeof(AppController), "AddOrEdit")] [InlineData("/api/config/app/add-or-edit", "POST", typeof(AppController), "AddOrEdit")] [InlineData("/api/{apiVersionNumber}/config/app/add/{app}", "POST", typeof(AppController), "Add")] [InlineData("/api/config/app/add/{app}", "POST", typeof(AppController), "Add")] [InlineData("/api/{apiVersionNumber}/config/app/bulk-import", "POST", typeof(AppController), "BulkImport")] [InlineData("/api/config/app/bulk-import", "POST", typeof(AppController), "BulkImport")] [InlineData("/api/{apiVersionNumber}/config/app/meta", "GET", typeof(AppController), "GetEntityView")] [InlineData("/api/config/app/meta", "GET", typeof(AppController), "GetEntityView")] [InlineData("/api/{apiVersionNumber}/config/app/count", "GET", typeof(AppController), "Count")] [InlineData("/api/config/app/count", "GET", typeof(AppController), "Count")] [InlineData("/api/{apiVersionNumber}/config/app/all", "GET", typeof(AppController), "GetAll")] [InlineData("/api/config/app/all", "GET", typeof(AppController), "GetAll")] [InlineData("/api/{apiVersionNumber}/config/app/export", "GET", typeof(AppController), "Export")] [InlineData("/api/config/app/export", "GET", typeof(AppController), "Export")] [InlineData("/api/{apiVersionNumber}/config/app/1", "GET", typeof(AppController), "Get")] [InlineData("/api/config/app/1", "GET", typeof(AppController), "Get")] [InlineData("/api/{apiVersionNumber}/config/app/get?appNames=1", "GET", typeof(AppController), "Get")] [InlineData("/api/config/app/get?appNames=1", "GET", typeof(AppController), "Get")] [InlineData("/api/{apiVersionNumber}/config/app", "GET", typeof(AppController), "GetPaginatedResult")] [InlineData("/api/config/app", "GET", typeof(AppController), "GetPaginatedResult")] [InlineData("/api/{apiVersionNumber}/config/app/page/1", "GET", typeof(AppController), "GetPaginatedResult")] [InlineData("/api/config/app/page/1", "GET", typeof(AppController), "GetPaginatedResult")] [InlineData("/api/{apiVersionNumber}/config/app/count-filtered/{filterName}", "GET", typeof(AppController), "CountFiltered")] [InlineData("/api/config/app/count-filtered/{filterName}", "GET", typeof(AppController), "CountFiltered")] [InlineData("/api/{apiVersionNumber}/config/app/get-filtered/{pageNumber}/{filterName}", "GET", typeof(AppController), "GetFiltered")] [InlineData("/api/config/app/get-filtered/{pageNumber}/{filterName}", "GET", typeof(AppController), "GetFiltered")] [InlineData("/api/config/app/first", "GET", typeof(AppController), "GetFirst")] [InlineData("/api/config/app/previous/1", "GET", typeof(AppController), "GetPrevious")] [InlineData("/api/config/app/next/1", "GET", typeof(AppController), "GetNext")] [InlineData("/api/config/app/last", "GET", typeof(AppController), "GetLast")] [InlineData("/api/{apiVersionNumber}/config/app/custom-fields", "GET", typeof(AppController), "GetCustomFields")] [InlineData("/api/config/app/custom-fields", "GET", typeof(AppController), "GetCustomFields")] [InlineData("/api/{apiVersionNumber}/config/app/custom-fields/{resourceId}", "GET", typeof(AppController), "GetCustomFields")] [InlineData("/api/config/app/custom-fields/{resourceId}", "GET", typeof(AppController), "GetCustomFields")] [InlineData("/api/{apiVersionNumber}/config/app/meta", "HEAD", typeof(AppController), "GetEntityView")] [InlineData("/api/config/app/meta", "HEAD", typeof(AppController), "GetEntityView")] [InlineData("/api/{apiVersionNumber}/config/app/count", "HEAD", typeof(AppController), "Count")] [InlineData("/api/config/app/count", "HEAD", typeof(AppController), "Count")] [InlineData("/api/{apiVersionNumber}/config/app/all", "HEAD", typeof(AppController), "GetAll")] [InlineData("/api/config/app/all", "HEAD", typeof(AppController), "GetAll")] [InlineData("/api/{apiVersionNumber}/config/app/export", "HEAD", typeof(AppController), "Export")] [InlineData("/api/config/app/export", "HEAD", typeof(AppController), "Export")] [InlineData("/api/{apiVersionNumber}/config/app/1", "HEAD", typeof(AppController), "Get")] [InlineData("/api/config/app/1", "HEAD", typeof(AppController), "Get")] [InlineData("/api/{apiVersionNumber}/config/app/get?appNames=1", "HEAD", typeof(AppController), "Get")] [InlineData("/api/config/app/get?appNames=1", "HEAD", typeof(AppController), "Get")] [InlineData("/api/{apiVersionNumber}/config/app", "HEAD", typeof(AppController), "GetPaginatedResult")] [InlineData("/api/config/app", "HEAD", typeof(AppController), "GetPaginatedResult")] [InlineData("/api/{apiVersionNumber}/config/app/page/1", "HEAD", typeof(AppController), "GetPaginatedResult")] [InlineData("/api/config/app/page/1", "HEAD", typeof(AppController), "GetPaginatedResult")] [InlineData("/api/{apiVersionNumber}/config/app/count-filtered/{filterName}", "HEAD", typeof(AppController), "CountFiltered")] [InlineData("/api/config/app/count-filtered/{filterName}", "HEAD", typeof(AppController), "CountFiltered")] [InlineData("/api/{apiVersionNumber}/config/app/get-filtered/{pageNumber}/{filterName}", "HEAD", typeof(AppController), "GetFiltered")] [InlineData("/api/config/app/get-filtered/{pageNumber}/{filterName}", "HEAD", typeof(AppController), "GetFiltered")] [InlineData("/api/config/app/first", "HEAD", typeof(AppController), "GetFirst")] [InlineData("/api/config/app/previous/1", "HEAD", typeof(AppController), "GetPrevious")] [InlineData("/api/config/app/next/1", "HEAD", typeof(AppController), "GetNext")] [InlineData("/api/config/app/last", "HEAD", typeof(AppController), "GetLast")] [InlineData("/api/{apiVersionNumber}/config/app/custom-fields", "HEAD", typeof(AppController), "GetCustomFields")] [InlineData("/api/config/app/custom-fields", "HEAD", typeof(AppController), "GetCustomFields")] [InlineData("/api/{apiVersionNumber}/config/app/custom-fields/{resourceId}", "HEAD", typeof(AppController), "GetCustomFields")] [InlineData("/api/config/app/custom-fields/{resourceId}", "HEAD", typeof(AppController), "GetCustomFields")] [Conditional("Debug")] public void TestRoute(string url, string verb, Type type, string actionName) { //Arrange url = url.Replace("{apiVersionNumber}", this.ApiVersionNumber); url = Host + url; //Act HttpRequestMessage request = new HttpRequestMessage(new HttpMethod(verb), url); IHttpControllerSelector controller = this.GetControllerSelector(); IHttpActionSelector action = this.GetActionSelector(); IHttpRouteData route = this.Config.Routes.GetRouteData(request); request.Properties[HttpPropertyKeys.HttpRouteDataKey] = route; request.Properties[HttpPropertyKeys.HttpConfigurationKey] = this.Config; HttpControllerDescriptor controllerDescriptor = controller.SelectController(request); HttpControllerContext context = new HttpControllerContext(this.Config, route, request) { ControllerDescriptor = controllerDescriptor }; var actionDescriptor = action.SelectAction(context); //Assert Assert.NotNull(controllerDescriptor); Assert.NotNull(actionDescriptor); Assert.Equal(type, controllerDescriptor.ControllerType); Assert.Equal(actionName, actionDescriptor.ActionName); } #region Fixture private readonly HttpConfiguration Config; private readonly string Host; private readonly string ApiVersionNumber; public AppRouteTests() { this.Host = ConfigurationManager.AppSettings["HostPrefix"]; this.ApiVersionNumber = ConfigurationManager.AppSettings["ApiVersionNumber"]; this.Config = GetConfig(); } private HttpConfiguration GetConfig() { if (MemoryCache.Default["Config"] == null) { HttpConfiguration config = new HttpConfiguration(); config.MapHttpAttributeRoutes(); config.Routes.MapHttpRoute("VersionedApi", "api/" + this.ApiVersionNumber + "/{schema}/{controller}/{action}/{id}", new { id = RouteParameter.Optional }); config.Routes.MapHttpRoute("DefaultApi", "api/{schema}/{controller}/{action}/{id}", new { id = RouteParameter.Optional }); config.EnsureInitialized(); MemoryCache.Default["Config"] = config; return config; } return MemoryCache.Default["Config"] as HttpConfiguration; } private IHttpControllerSelector GetControllerSelector() { if (MemoryCache.Default["ControllerSelector"] == null) { IHttpControllerSelector selector = this.Config.Services.GetHttpControllerSelector(); return selector; } return MemoryCache.Default["ControllerSelector"] as IHttpControllerSelector; } private IHttpActionSelector GetActionSelector() { if (MemoryCache.Default["ActionSelector"] == null) { IHttpActionSelector selector = this.Config.Services.GetActionSelector(); return selector; } return MemoryCache.Default["ActionSelector"] as IHttpActionSelector; } #endregion } }
nubiancc/frapid
src/Frapid.Web/Areas/Frapid.Config/WebApi/Tests/AppRouteTests.cs
C#
mit
11,134
/** * @license Angular v5.2.2 * (c) 2010-2018 Google, Inc. https://angular.io/ * License: MIT */ import { EventEmitter, Injectable } from '@angular/core'; import { __extends } from 'tslib'; import { LocationStrategy } from '@angular/common'; /** * @fileoverview added by tsickle * @suppress {checkTypes} checked by tsc */ /** * @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 */ /** * A spy for {\@link Location} that allows tests to fire simulated location events. * * \@experimental */ var SpyLocation = /** @class */ (function () { function SpyLocation() { this.urlChanges = []; this._history = [new LocationState('', '')]; this._historyIndex = 0; /** * \@internal */ this._subject = new EventEmitter(); /** * \@internal */ this._baseHref = ''; /** * \@internal */ this._platformStrategy = /** @type {?} */ ((null)); } /** * @param {?} url * @return {?} */ SpyLocation.prototype.setInitialPath = /** * @param {?} url * @return {?} */ function (url) { this._history[this._historyIndex].path = url; }; /** * @param {?} url * @return {?} */ SpyLocation.prototype.setBaseHref = /** * @param {?} url * @return {?} */ function (url) { this._baseHref = url; }; /** * @return {?} */ SpyLocation.prototype.path = /** * @return {?} */ function () { return this._history[this._historyIndex].path; }; /** * @param {?} path * @param {?=} query * @return {?} */ SpyLocation.prototype.isCurrentPathEqualTo = /** * @param {?} path * @param {?=} query * @return {?} */ function (path, query) { if (query === void 0) { query = ''; } var /** @type {?} */ givenPath = path.endsWith('/') ? path.substring(0, path.length - 1) : path; var /** @type {?} */ currPath = this.path().endsWith('/') ? this.path().substring(0, this.path().length - 1) : this.path(); return currPath == givenPath + (query.length > 0 ? ('?' + query) : ''); }; /** * @param {?} pathname * @return {?} */ SpyLocation.prototype.simulateUrlPop = /** * @param {?} pathname * @return {?} */ function (pathname) { this._subject.emit({ 'url': pathname, 'pop': true, 'type': 'popstate' }); }; /** * @param {?} pathname * @return {?} */ SpyLocation.prototype.simulateHashChange = /** * @param {?} pathname * @return {?} */ function (pathname) { // Because we don't prevent the native event, the browser will independently update the path this.setInitialPath(pathname); this.urlChanges.push('hash: ' + pathname); this._subject.emit({ 'url': pathname, 'pop': true, 'type': 'hashchange' }); }; /** * @param {?} url * @return {?} */ SpyLocation.prototype.prepareExternalUrl = /** * @param {?} url * @return {?} */ function (url) { if (url.length > 0 && !url.startsWith('/')) { url = '/' + url; } return this._baseHref + url; }; /** * @param {?} path * @param {?=} query * @return {?} */ SpyLocation.prototype.go = /** * @param {?} path * @param {?=} query * @return {?} */ function (path, query) { if (query === void 0) { query = ''; } path = this.prepareExternalUrl(path); if (this._historyIndex > 0) { this._history.splice(this._historyIndex + 1); } this._history.push(new LocationState(path, query)); this._historyIndex = this._history.length - 1; var /** @type {?} */ locationState = this._history[this._historyIndex - 1]; if (locationState.path == path && locationState.query == query) { return; } var /** @type {?} */ url = path + (query.length > 0 ? ('?' + query) : ''); this.urlChanges.push(url); this._subject.emit({ 'url': url, 'pop': false }); }; /** * @param {?} path * @param {?=} query * @return {?} */ SpyLocation.prototype.replaceState = /** * @param {?} path * @param {?=} query * @return {?} */ function (path, query) { if (query === void 0) { query = ''; } path = this.prepareExternalUrl(path); var /** @type {?} */ history = this._history[this._historyIndex]; if (history.path == path && history.query == query) { return; } history.path = path; history.query = query; var /** @type {?} */ url = path + (query.length > 0 ? ('?' + query) : ''); this.urlChanges.push('replace: ' + url); }; /** * @return {?} */ SpyLocation.prototype.forward = /** * @return {?} */ function () { if (this._historyIndex < (this._history.length - 1)) { this._historyIndex++; this._subject.emit({ 'url': this.path(), 'pop': true }); } }; /** * @return {?} */ SpyLocation.prototype.back = /** * @return {?} */ function () { if (this._historyIndex > 0) { this._historyIndex--; this._subject.emit({ 'url': this.path(), 'pop': true }); } }; /** * @param {?} onNext * @param {?=} onThrow * @param {?=} onReturn * @return {?} */ SpyLocation.prototype.subscribe = /** * @param {?} onNext * @param {?=} onThrow * @param {?=} onReturn * @return {?} */ function (onNext, onThrow, onReturn) { return this._subject.subscribe({ next: onNext, error: onThrow, complete: onReturn }); }; /** * @param {?} url * @return {?} */ SpyLocation.prototype.normalize = /** * @param {?} url * @return {?} */ function (url) { return /** @type {?} */ ((null)); }; SpyLocation.decorators = [ { type: Injectable }, ]; /** @nocollapse */ SpyLocation.ctorParameters = function () { return []; }; return SpyLocation; }()); var LocationState = /** @class */ (function () { function LocationState(path, query) { this.path = path; this.query = query; } return LocationState; }()); /** * @fileoverview added by tsickle * @suppress {checkTypes} checked by tsc */ /** * @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 */ /** * A mock implementation of {\@link LocationStrategy} that allows tests to fire simulated * location events. * * \@stable */ var MockLocationStrategy = /** @class */ (function (_super) { __extends(MockLocationStrategy, _super); function MockLocationStrategy() { var _this = _super.call(this) || this; _this.internalBaseHref = '/'; _this.internalPath = '/'; _this.internalTitle = ''; _this.urlChanges = []; /** * \@internal */ _this._subject = new EventEmitter(); return _this; } /** * @param {?} url * @return {?} */ MockLocationStrategy.prototype.simulatePopState = /** * @param {?} url * @return {?} */ function (url) { this.internalPath = url; this._subject.emit(new _MockPopStateEvent(this.path())); }; /** * @param {?=} includeHash * @return {?} */ MockLocationStrategy.prototype.path = /** * @param {?=} includeHash * @return {?} */ function (includeHash) { if (includeHash === void 0) { includeHash = false; } return this.internalPath; }; /** * @param {?} internal * @return {?} */ MockLocationStrategy.prototype.prepareExternalUrl = /** * @param {?} internal * @return {?} */ function (internal) { if (internal.startsWith('/') && this.internalBaseHref.endsWith('/')) { return this.internalBaseHref + internal.substring(1); } return this.internalBaseHref + internal; }; /** * @param {?} ctx * @param {?} title * @param {?} path * @param {?} query * @return {?} */ MockLocationStrategy.prototype.pushState = /** * @param {?} ctx * @param {?} title * @param {?} path * @param {?} query * @return {?} */ function (ctx, title, path, query) { this.internalTitle = title; var /** @type {?} */ url = path + (query.length > 0 ? ('?' + query) : ''); this.internalPath = url; var /** @type {?} */ externalUrl = this.prepareExternalUrl(url); this.urlChanges.push(externalUrl); }; /** * @param {?} ctx * @param {?} title * @param {?} path * @param {?} query * @return {?} */ MockLocationStrategy.prototype.replaceState = /** * @param {?} ctx * @param {?} title * @param {?} path * @param {?} query * @return {?} */ function (ctx, title, path, query) { this.internalTitle = title; var /** @type {?} */ url = path + (query.length > 0 ? ('?' + query) : ''); this.internalPath = url; var /** @type {?} */ externalUrl = this.prepareExternalUrl(url); this.urlChanges.push('replace: ' + externalUrl); }; /** * @param {?} fn * @return {?} */ MockLocationStrategy.prototype.onPopState = /** * @param {?} fn * @return {?} */ function (fn) { this._subject.subscribe({ next: fn }); }; /** * @return {?} */ MockLocationStrategy.prototype.getBaseHref = /** * @return {?} */ function () { return this.internalBaseHref; }; /** * @return {?} */ MockLocationStrategy.prototype.back = /** * @return {?} */ function () { if (this.urlChanges.length > 0) { this.urlChanges.pop(); var /** @type {?} */ nextUrl = this.urlChanges.length > 0 ? this.urlChanges[this.urlChanges.length - 1] : ''; this.simulatePopState(nextUrl); } }; /** * @return {?} */ MockLocationStrategy.prototype.forward = /** * @return {?} */ function () { throw 'not implemented'; }; MockLocationStrategy.decorators = [ { type: Injectable }, ]; /** @nocollapse */ MockLocationStrategy.ctorParameters = function () { return []; }; return MockLocationStrategy; }(LocationStrategy)); var _MockPopStateEvent = /** @class */ (function () { function _MockPopStateEvent(newUrl) { this.newUrl = newUrl; this.pop = true; this.type = 'popstate'; } return _MockPopStateEvent; }()); /** * @fileoverview added by tsickle * @suppress {checkTypes} checked by tsc */ /** * @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 */ /** * @fileoverview added by tsickle * @suppress {checkTypes} checked by tsc */ /** * @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 */ /** * @module * @description * Entry point for all public APIs of this package. */ // This file only reexports content of the `src` folder. Keep it that way. /** * @fileoverview added by tsickle * @suppress {checkTypes} checked by tsc */ /** * Generated bundle index. Do not edit. */ export { SpyLocation, MockLocationStrategy }; //# sourceMappingURL=testing.js.map
RJ15/FixIt
badminton/node_modules/@angular/common/esm5/testing.js
JavaScript
mit
11,979
package de.helwich.junit; import static java.lang.annotation.ElementType.TYPE; import static java.lang.annotation.RetentionPolicy.RUNTIME; import java.lang.annotation.Retention; import java.lang.annotation.Target; /** * Annotation used to configure jasmine test runner. * * @author Hendrik Helwich */ @Target(TYPE) @Retention(RUNTIME) public @interface JasmineTest { String srcDir() default "/src/main/js"; String testDir() default "/src/test/js"; String fileSuffix() default ".js"; String[] src() default {}; String[] test(); boolean browser() default false; boolean classPathJsResources() default false; }
dddpaul/junit-jasmine-runner
src/main/java/de/helwich/junit/JasmineTest.java
Java
mit
651
import javafx.application.Application; // Scene import javafx.fxml.FXMLLoader; import javafx.scene.Parent; import javafx.scene.Scene; // Stage import javafx.stage.Stage; public class ChessApp extends Application { public static void main(String[] args) { launch(args); } @Override public void start(Stage stage) throws Exception { Parent root = FXMLLoader.load(getClass().getResource("ChessViewer-2.1.fxml")); stage.setTitle("Chess Viewer 2.1"); stage.setScene(new Scene(root, 1200, 720)); stage.show(); } }
tlee753/chess-visualizer
src/ChessApp.java
Java
mit
574
function router(handle, pathname, res, postdata) { console.log('into the router request for->'+pathname); // var newpathname = pathname; // var newpostdata = postdata; // console.log(pathname.lastIndexOf('.')); var extendNM = pathname.substr(pathname.lastIndexOf('.')+1); // console.log(extendNM); // var cssFileRegex = new RegExp('^/css/.*css?$'); // if (cssFileRegex.test(pathname)) { // newpathname = 'css'; // newpostdata = pathname; // } if (typeof handle[extendNM] === 'function') { handle[extendNM](res, postdata, pathname); } else { console.log('no request handle found for->'+pathname); res.writeHead(404, {'Content-Type':'text/plain'}); res.write('404 not found!'); res.end(); } } exports.router = router;
noprettyboy/my_portal_page
serverjs/router.js
JavaScript
mit
744
require 'fog/core/model' module Fog module Brightbox class Compute class LoadBalancer < Fog::Model identity :id attribute :url attribute :name attribute :status attribute :resource_type attribute :nodes attribute :policy attribute :healthcheck attribute :listeners attribute :account def ready? status == 'active' end def save requires :nodes, :listeners, :healthcheck options = { :nodes => nodes, :listeners => listeners, :healthcheck => healthcheck, :policy => policy, :name => name }.delete_if {|k,v| v.nil? || v == "" } data = connection.create_load_balancer(options) merge_attributes(data) true end def destroy requires :identity connection.destroy_load_balancer(identity) true end end end end end
jbenjore/JPs-love-project
annotate-models/ruby/1.9.1/gems/fog-0.8.1/lib/fog/compute/models/brightbox/load_balancer.rb
Ruby
mit
1,025
ENV["RAILS_ENV"] ||= 'test' require 'simplecov' SimpleCov.start do add_filter '/spec' end require File.expand_path("../../config/environment", __FILE__) require 'rspec/rails' require 'capybara/rails' Dir[Rails.root.join("spec/support/**/*.rb")].each { |f| require f } RSpec.configure do |config| config.fixture_path = "#{::Rails.root}/spec/fixtures" config.use_transactional_fixtures = true config.infer_base_class_for_anonymous_controllers = false config.order = "random" config.include FactoryGirl::Syntax::Methods config.include ApiHelper config.before(:suite) do DatabaseCleaner.strategy = :transaction DatabaseCleaner.clean_with(:truncation) end config.before(:each) do DatabaseCleaner.start end config.after(:each) do DatabaseCleaner.clean end end
7maples/backchannel-questions
spec/spec_helper.rb
Ruby
mit
803
package com.eway.payment.sdk.android.entities; import com.eway.payment.sdk.android.beans.CodeDetail; import java.util.ArrayList; public class CodeLookupResponse { private String Language; private ArrayList<CodeDetail> CodeDetails; private String Errors; public CodeLookupResponse(String errors, String language, ArrayList<CodeDetail> codeDetails) { Language = language; CodeDetails = codeDetails; Errors = errors; } public CodeLookupResponse() { } public String getLanguage() { return Language; } public void setLanguage(String language) { Language = language; } public ArrayList<CodeDetail> getCodeDetails() { return CodeDetails; } public void setCodeDetails(ArrayList<CodeDetail> codeDetails) { CodeDetails = codeDetails; } public String getErrors() { return Errors; } public void setErrors(String errors) { Errors = errors; } }
eWAYPayment/eway-rapid-android
sdk/src/main/java/com/eway/payment/sdk/android/entities/CodeLookupResponse.java
Java
mit
991
from bibliopixel import * from bibliopixel.animation import BaseAnimation, AnimationQueue, OffAnim from util import * from static_objects import * import loader import config import status import traceback import globals class BPManager: def __init__(self, off_timeout): self.driver = [] self._driverCfg = None self.led = None self._ledCfg = None self.anim = None self._animCfg = None self.drivers = {} self._driverClasses = {} self._driverNames = {} self.controllers = {} self._contClasses = {} self._contNames = {} self.anims = {} self._animClasses = {} self._animParams = {} self._animNames = {} self._preConfigs = {} self._preNames = {} self.animRunParams = BaseAnimation.RUN_PARAMS self._off_timeout = off_timeout self._offAnim = None self.__loadFuncs = { "driver": self.__loadDriverDef, "controller": self.__loadControllerDef, "animation": self.__loadAnimDef, "preset": self.__loadPresetDef } config.initConfig() def __genModObj(self, config): if "desc" not in config: config.desc = "" if "presets" not in config: config.presets = [] if "params" not in config: config.params = [] for p in config.presets: p.id = config.id c = { "display": config.display, "desc": config.desc, "params": config.params, "presets": config.presets, } c = d(c) if config.type == "controller" or (config.type == "preset" and config.preset_type == "controller"): c.control_type = config.control_type return c def __loadDriverDef(self, config): config = d(config) self._driverClasses[config.id] = config['class'] self.drivers[config.id] = self.__genModObj(config) self._driverNames[config.id] = config.display def __loadControllerDef(self, config): config = d(config) self._contClasses[config.id] = config['class'] self.controllers[config.id] = self.__genModObj(config) self._contNames[config.id] = config.display def __addToAnims(self, config, c): cont = config.controller for p in c.presets: p.type = cont p.locked = True if not cont in self.anims: self.anims[cont] = {} self.anims[cont][config.id] = c self._animNames[config.id] = config.display params = {} for p in config.params: params[p.id] = p self._animParams[config.id] = params def __loadAnimDef(self, config): config = d(config) self._animClasses[config.id] = config['class'] self.__addToAnims(config, self.__genModObj(config)) def __loadPresetDef(self, config): config = d(config) config.id = "*!#_" + config.id config.display = "* " + config.display self._preConfigs[config.id] = { "class": config['class'], "preconfig": config.preconfig } self._preNames[config.id] = config.display c = self.__genModObj(config) if config.preset_type == "driver": self.drivers[config.id] = c self._driverNames[config.id] = config.display elif config.preset_type == "controller": self.controllers[config.id] = c self._contNames[config.id] = config.display elif config.preset_type == "animation": self.__addToAnims(config, c) else: return # TODO: Add check for required fields for better errors def loadModules(self, mods): for m in mods: if hasattr(m, 'MANIFEST'): status.pushStatus("Loading: {}".format(m.__file__)) for ref in m.MANIFEST: ref = d(ref) if ref.type in self.__loadFuncs: try: self.__loadFuncs[ref.type](ref) except: status.pushStatus( "Load module failure: {} - {}".format(m.__file__, traceback.format_exc())) def loadBaseMods(self): self.loadModules(moduleList) def loadMods(self): mod_dirs = globals._server_config.mod_dirs for d in (mod_dirs + globals._bpa_dirs): self.loadModules(loader.load_folder(d)) def __getInstance(self, config, inst_type): config = d(config) params = d(config.config) result = None obj = None preconfig = None if config.id in self._preConfigs: p = self._preConfigs[config.id] obj = p['class'] preconfig = p['preconfig'] else: if inst_type == "driver": if config.id in self._driverClasses: obj = self._driverClasses[config.id] elif inst_type == "controller": if config.id in self._contClasses: obj = self._contClasses[config.id] elif inst_type == "animation": if config.id in self._animClasses: obj = self._animClasses[config.id] if not obj: raise Exception("Invalid " + inst_type) if preconfig: if hasattr(preconfig, '__call__'): preconfig = preconfig() params.upgrade(preconfig) return (obj, params) def _startOffAnim(self): if self._off_timeout > 0: if self._offAnim == None and self.led != None: self._offAnim = OffAnim(self.led) self.anim = OffAnim(self.led, timeout=self._off_timeout) self.anim.run(threaded=True) def startConfig(self, driverConfig, ledConfig): self.stopConfig() self._driverCfg = driverConfig self._ledCfg = d(ledConfig) ctype = "" if self._ledCfg.id in self.controllers: ctype = self.controllers[self._ledCfg.id].control_type self._ledCfg.control_type = ctype config.writeConfig("current_setup", self._driverCfg, "driver") config.writeConfig("current_setup", self._ledCfg, "controller") try: status.pushStatus("Starting config...") self.driver = [] for drv in self._driverCfg: obj, params = self.__getInstance(d(drv), "driver") self.driver.append(obj(**(params))) obj, params = self.__getInstance(self._ledCfg, "controller") params['driver'] = self.driver self.led = obj(**(params)) self._startOffAnim() status.pushStatus("Config start success!") return success() except Exception, e: self.stopConfig() status.pushError("Config start failure! {}".format( traceback.format_exc())) return fail(str(e), error=ErrorCode.BP_ERROR, data=None) def getConfig(self): setup = d(config.readConfig("current_setup")) # setup = d({ # "driver": self._driverCfg, # "controller": self._ledCfg # }) if not ("driver" in setup): setup.driver = None if not ("controller" in setup): setup.controller = None setup.running = self.led != None and len(self.driver) > 0 return setup def stopConfig(self): status.pushStatus("Stopping current config") self.stopAnim(doOff=False) if len(self.driver) > 0: for drv in self.driver: drv.cleanup() self.driver = [] self._driverCfg = None if self.led: self.led.cleanup() self.led = None self._ledCfg = None self._offAnim = None def stopAnim(self, doOff=True): if self.anim: try: self.anim.cleanup() except Exception, e: status.pushError(e) self.anim = None self._animCfg = None if doOff: self._startOffAnim() def startAnim(self, config): def getAnim(c): cfg = d(c['config']) run = d(c['run']) cfg.led = self.led c['config'] = cfg p = self._animParams[c.id] for k in cfg: if k in p: pd = p[k] if pd.type == "color": cfg[k] = tuple(cfg[k]) elif pd.type == "multi_tuple" or pd.type == "multi": if isinstance(pd.controls, list): for i in range(len(pd.controls)): if pd.controls[i].type == "color": cfg[k][i] == tuple(cfg[k][i]) elif isinstance(pd.controls, dict): if pd.controls.type == "color": temp = [] for x in cfg[k]: temp.append(tuple(x)) cfg[k] = temp if pd.type == "multi_tuple": cfg[k] = tuple(cfg[k]) obj, params = self.__getInstance(c, "animation") anim = obj(**(params)) return anim, d(run) try: if not(self.led != None and len(self.driver) > 0): return fail(msg="Output config not started! Please start first.") self.stopAnim(doOff=False) self._animCfg = config if('queue' in config): q = config['queue'] run = d(config['run']) run.threaded = True self.anim = AnimationQueue(self.led) for a in q: anim, r = getAnim(a) self.anim.addAnim( anim=anim, amt=r.amt, fps=r.fps, max_steps=r.max_steps, untilComplete=r.untilComplete, max_cycles=r.max_cycles, seconds=r.seconds) status.pushStatus("Starting Animation Queue") self.anim.run(**(run)) return success() else: self.anim, run = getAnim(config) run.threaded = True status.pushStatus("Starting Animation: {}".format( self._animNames[config.id])) self.anim.run(**(run)) return success() except Exception, e: status.pushError(traceback.format_exc()) return fail("Failure starting animation: " + str(e), error=ErrorCode.BP_ERROR, data=None)
ManiacalLabs/PixelWeb
pixelweb/bpmanager.py
Python
mit
11,336
from django.db import models from django.utils.encoding import python_2_unicode_compatible @python_2_unicode_compatible class TModel(models.Model): name = models.CharField(max_length=200) test = models.OneToOneField( 'self', null=True, blank=True, related_name='related_test_models' ) for_inline = models.ForeignKey( 'self', null=True, blank=True, related_name='inline_test_models' ) def __str__(self): return self.name class TestModel(models.Model): name = models.CharField(max_length=200) def __str__(self): return self.name
shubhamdipt/django-autocomplete-light
test_project/select2_one_to_one/models.py
Python
mit
647
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("_16.LongSequence")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("Microsoft")] [assembly: AssemblyProduct("_16.LongSequence")] [assembly: AssemblyCopyright("Copyright © Microsoft 2016")] [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("68d8028d-7e4d-4919-b932-9f5cf2760d26")] // 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")]
dobri19/OldRepos
Telerik/01-Programming-with-C#/01-C#-Fundamentals-2016-October/01-Intro-Programming/16.LongSequence/Properties/AssemblyInfo.cs
C#
mit
1,426
package main import ( "flag" "runtime" "testing" "time" ) var ( serverPort = flag.String("port", "8080", "port to use for benchmarks") clientType = flag.String("client-type", "fasthttp", "client to use in benchmarks") ) var ( longDuration = 9001 * time.Hour highRate = uint64(1000000) ) func BenchmarkBombardierSingleReqPerf(b *testing.B) { addr := "localhost:" + *serverPort benchmarkFireRequest(config{ numConns: defaultNumberOfConns, numReqs: nil, duration: &longDuration, url: "http://" + addr, headers: new(headersList), timeout: defaultTimeout, method: "GET", body: "", printLatencies: false, clientType: clientTypeFromString(*clientType), }, b) } func BenchmarkBombardierRateLimitPerf(b *testing.B) { addr := "localhost:" + *serverPort benchmarkFireRequest(config{ numConns: defaultNumberOfConns, numReqs: nil, duration: &longDuration, url: "http://" + addr, headers: new(headersList), timeout: defaultTimeout, method: "GET", body: "", printLatencies: false, rate: &highRate, clientType: clientTypeFromString(*clientType), }, b) } func benchmarkFireRequest(c config, bm *testing.B) { b, e := newBombardier(c) if e != nil { bm.Error(e) } b.disableOutput() bm.SetParallelism(int(defaultNumberOfConns) / runtime.NumCPU()) bm.ResetTimer() bm.RunParallel(func(pb *testing.PB) { done := b.barrier.done() for pb.Next() { b.ratelimiter.pace(done) b.performSingleRequest() } }) }
codesenberg/bombardier
bombardier_performance_test.go
GO
mit
1,610
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("WorldBankBBS.WCF.Data")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("WorldBankBBS.WCF.Data")] [assembly: AssemblyCopyright("Copyright © 2016")] [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("25f3699d-4ec4-45b2-8b08-ec78e1d9bca3")] // 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 Revision and Build Numbers // by using the '*' as shown below: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("1.0.0.0")] [assembly: AssemblyFileVersion("1.0.0.0")]
sharpninja/WorldBankBBS
WorldBankBBS.WCF.Data/Properties/AssemblyInfo.cs
C#
mit
1,418
"use strict" class Compress extends R.Compressor{ /** * * */ run(R,compressor){ this.compressBackbone(true); } } module.exports=Compress;
williamamed/Raptor.js
@raptorjs-development/raptor-panel/Compressor/Compress.js
JavaScript
mit
154
# requires all of the integrators at the end of the file class Metriculator @@integrations = {} @parsed, @db_stored, @finished = false, false, false # integration points are: @@names = [:on_db_store, :on_finish, :on_metric_parse] @@names.each {|name| @@integrations[name] = [] } class << self ## Takes procs to run them at the specified integration time. def integration(name, &block) if @@names.include? name @@integrations[name] << block end end # Calls stored procs at the database storage moment in msruninfo.rb def on_db_store(msrun) return if on_db_store? @@integrations[:on_db_store].each {|block| block.call msrun } @db_stored = true end # Calls stored procs after everything is done in bin/metriculator (after messaging system) def on_finish(msrun) return if on_finish? @@integrations[:on_finish].each {|block| block.call msrun } @finished = true end # calls stored procs after the parsing is done in metrics.rb, hands back the metric object def on_metric_parse(metric) return if on_metric_parse? @@integrations[:on_metric_parse].each { |block| block.call metric } @on_parsed = true end def on_metric_parse? @parsed end def on_finish? @finished end def on_db_store? @db_stored end end # class << self end Dir.glob(File.join(File.dirname(__FILE__), "integrators", "*.rb")).each do |integrator_file| require_relative integrator_file end
princelab/metriculator
lib/integrators.rb
Ruby
mit
1,530
var parserx = require('parse-regexp') var EventEmitter = require('events').EventEmitter var MuxDemux = require('mux-demux') var remember = require('remember') var idle = require('idle') var timestamp = require('monotonic-timestamp') var from = require('from') var sync = require('./state-sync') module.exports = Rumours //THIS IS STRICTLY FOR DEBUGGING var ids = 'ABCDEFHIJKLMNOP' function createId () { var id = ids[0] ids = ids.substring(1) return id } function Rumours (schema) { var emitter = new EventEmitter() //DEBUG emitter.id = createId() var rules = [] var live = {} var locals = {} /* schema must be of form : { '/regexp/g': function (key) { //must return a scuttlebutt instance //regexes must match from the first character. //[else madness would ensue] } } */ for (var p in schema) { rules.push({rx: parserx(p) || p, fn: schema[p]}) } function match (key) { for (var i in rules) { var r = rules[i] var m = key.match(r.rx) if(m && m.index === 0) return r.fn } } //OPEN is a much better verb than TRANSCIEVE emitter.open = emitter.transceive = emitter.trx = function (key, local, cb) { if(!cb && 'function' === typeof local) cb = local, local = true local = (local !== false) //default to true if(local) locals[key] = true if(live[key]) return live[key] //if we havn't emitted ready, emit it now, //can deal with the rest of the updates later... if(!emitter.ready) { emitter.ready = true emitter.emit('ready') } var fn = match(key) if(!fn) throw new Error('no schema for:'+key) var doc = fn(key) //create instance. doc.key = key live[key] = doc //remeber what is open. emitter.emit('open', doc, local) //attach to any open streams. emitter.emit('trx', doc, local) doc.once('dispose', function () { delete locals[doc.key] delete live[doc.key] }) if(cb) doc.once('sync', cb) return doc } //CLOSE(doc) emitter.close = emitter.untransceive = emitter.untrx = function (doc) { doc.dispose() emitter.emit('untrx', doc) emitter.emit('close', doc) return this } /* so the logic here: if open a doc, RTR over stream; if idle close stream if change reopen stream */ function activations (listen) { emitter.on('open', onActive) for(var key in live) { (onActive)(live[key]) } function onActive (doc, local) { local = (local !== false) var up = true function onUpdate (u) { if(up) return up = true listen(doc, true) } function onIdle () { up = false listen(doc, false) } //call onIdle when _update hasn't occured within ms... idle(doc, '_update', 1e3, onIdle) doc.once('dispose', function () { if(up) { up = false listen(doc, false) } doc.removeListener('_update', onIdle) doc.removeListener('_update', onUpdate) }) doc.on('_update', onUpdate) listen(doc, true) } } var state = {} var syncState = sync(emitter, state) //a better name for this? function onReadyOrNow (cb) { process.nextTick(function () { if(emitter.ready) return cb() emitter.once('ready', cb) }) } emitter.createStream = function (mode) { var streams = {} var mx = MuxDemux(function (stream) { if(/^__state/.test(stream.meta.key)) { return stateStream(stream) } if(_stream = streams[stream.meta.key]) { if(_stream.meta.ts > stream.meta.ts) return _stream.end() else stream.end(), stream = _stream } streams[stream.meta.key] = stream //this will trigger connectIf emitter.open(stream.meta.key, false) }) function connectIf(doc) { var stream = streams[doc.key] if(!stream) { streams[doc.key] = stream = mx.createStream({key: doc.key, ts: timestamp()}) } stream.pipe(doc.createStream({wrapper:'raw', tail: true})).pipe(stream) stream.once('close', function () { delete streams[doc.key] }) } //replicate all live documents. process.nextTick(function () { activations(function (doc, up) { if(up) { process.nextTick(function () { connectIf(doc) }) } else { if(streams[doc.key]) streams[doc.key].end() if(!locals[doc.key]) doc.dispose() } }) }) function stateStream (stream) { stream.on('data', function (ary) { var key = ary.shift() var hash = ary.shift() if(state[key] !== hash && !live[key]) { //(_, false) means close this again after it stops changing... emitter.open(key, false) } }) } //wait untill is ready, if not yet ready... onReadyOrNow(function () { from( Object.keys(state).map(function (k) { return [k, state[k]] }) ) .pipe(mx.createStream({key: '__state'})) /*.on('data', function (data) { var key = data.shift() var hash = data.shift() //just have to open the document, //and it will be replicated to the remote. if(state[key] !== hash) emitter.open(key) })*/ }) return mx } //inject kv object used to persist everything. emitter.persist = function (kv) { var sync = remember(kv) function onActive (doc) { sync(doc) } //check if any docs are already active. //start persisting them. for (var k in live) { onActive(live[k]) } emitter.on('trx', onActive) //load the state - this is the hash of the documents! syncState(kv) return emitter } return emitter }
dominictarr/rumours_
index.js
JavaScript
mit
6,007
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace BlackHole.Entity { public class UserInfo { } public class BasicUserInfo { /// <summary>唯一识别码 /// /// </summary> public string UserGUID { get; set; } /// <summary> /// /// </summary> public string CardNo { get; set; } public string NewName { get; set; } public string OleName { get; set; } public int Age { get; set; } public int Sex { get; set; } public DateTime BirthDate { get; set; } public string Img { get; set; } } }
1024home/BlackHole
BlackHole/BlackHole.Entity/UserInfo.cs
C#
mit
711
'use strict'; var xpath = require('xpath'); var dom = require('xmldom').DOMParser; module.exports = function (grunt) { var xml = grunt.file.read(__dirname + '/../pom.xml'); var doc = new dom().parseFromString(xml); var select = xpath.useNamespaces({"xmlns": "http://maven.apache.org/POM/4.0.0"}); var version = select("/xmlns:project/xmlns:version/text()", doc).toString().split( /-/ )[0]; var repository = select("/xmlns:project/xmlns:url/text()", doc).toString(); require('load-grunt-tasks')(grunt); grunt.initConfig({ changelog: { options: { version: version, repository: repository, dest: '../CHANGELOG.md' } }, }); grunt.registerTask('default', ['changelog']); };
bheiskell/HungerRain
changelog/Gruntfile.js
JavaScript
mit
800
/* The MIT License (MIT) Copyright (c) 2013-2015 winlin 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. */ #ifndef SRS_RTMP_PROTOCOL_IO_HPP #define SRS_RTMP_PROTOCOL_IO_HPP /* #include <srs_rtmp_io.hpp> */ #include <srs_core.hpp> // for srs-librtmp, @see https://github.com/winlinvip/simple-rtmp-server/issues/213 #ifndef _WIN32 #include <sys/uio.h> #endif /** * the system io reader/writer architecture: +---------------+ +--------------------+ +---------------+ | IBufferReader | | IStatistic | | IBufferWriter | +---------------+ +--------------------+ +---------------+ | + read() | | + get_recv_bytes() | | + write() | +------+--------+ | + get_recv_bytes() | | + writev() | / \ +---+--------------+-+ +-------+-------+ | / \ / \ / \ | | | | +------+------------------+-+ +-----+----------------+--+ | IProtocolReader | | IProtocolWriter | +---------------------------+ +-------------------------+ | + readfully() | | + set_send_timeout() | | + set_recv_timeout() | +-------+-----------------+ +------------+--------------+ / \ / \ | | | +--+-----------------------------+-+ | IProtocolReaderWriter | +----------------------------------+ | + is_never_timeout() | +----------------------------------+ */ /** * the reader for the buffer to read from whatever channel. */ class ISrsBufferReader { public: ISrsBufferReader(); virtual ~ISrsBufferReader(); // for protocol/amf0/msg-codec public: virtual int read(void* buf, size_t size, ssize_t* nread) = 0; }; /** * the writer for the buffer to write to whatever channel. */ class ISrsBufferWriter { public: ISrsBufferWriter(); virtual ~ISrsBufferWriter(); // for protocol public: /** * write bytes over writer. * @nwrite the actual written bytes. NULL to ignore. */ virtual int write(void* buf, size_t size, ssize_t* nwrite) = 0; /** * write iov over writer. * @nwrite the actual written bytes. NULL to ignore. */ virtual int writev(const iovec *iov, int iov_size, ssize_t* nwrite) = 0; }; /** * get the statistic of channel. */ class ISrsProtocolStatistic { public: ISrsProtocolStatistic(); virtual ~ISrsProtocolStatistic(); // for protocol public: /** * get the total recv bytes over underlay fd. */ virtual int64_t get_recv_bytes() = 0; /** * get the total send bytes over underlay fd. */ virtual int64_t get_send_bytes() = 0; }; /** * the reader for the protocol to read from whatever channel. */ class ISrsProtocolReader : public virtual ISrsBufferReader, public virtual ISrsProtocolStatistic { public: ISrsProtocolReader(); virtual ~ISrsProtocolReader(); // for protocol public: /** * set the recv timeout in us, recv will error when timeout. * @remark, if not set, use ST_UTIME_NO_TIMEOUT, never timeout. */ virtual void set_recv_timeout(int64_t timeout_us) = 0; /** * get the recv timeout in us. */ virtual int64_t get_recv_timeout() = 0; // for handshake. public: /** * read specified size bytes of data * @param nread, the actually read size, NULL to ignore. */ virtual int read_fully(void* buf, size_t size, ssize_t* nread) = 0; }; /** * the writer for the protocol to write to whatever channel. */ class ISrsProtocolWriter : public virtual ISrsBufferWriter, public virtual ISrsProtocolStatistic { public: ISrsProtocolWriter(); virtual ~ISrsProtocolWriter(); // for protocol public: /** * set the send timeout in us, send will error when timeout. * @remark, if not set, use ST_UTIME_NO_TIMEOUT, never timeout. */ virtual void set_send_timeout(int64_t timeout_us) = 0; /** * get the send timeout in us. */ virtual int64_t get_send_timeout() = 0; }; /** * the reader and writer. */ class ISrsProtocolReaderWriter : public virtual ISrsProtocolReader, public virtual ISrsProtocolWriter { public: ISrsProtocolReaderWriter(); virtual ~ISrsProtocolReaderWriter(); // for protocol public: /** * whether the specified timeout_us is never timeout. */ virtual bool is_never_timeout(int64_t timeout_us) = 0; }; #endif
Akagi201/srs-librtmp
src/protocol/srs_rtmp_io.hpp
C++
mit
5,514
using Newtonsoft.Json; using System.Collections.Generic; namespace WizBot.Common.Pokemon { public class SearchPokemon { public class GenderRatioClass { public float M { get; set; } public float F { get; set; } } public class BaseStatsClass { public int HP { get; set; } public int ATK { get; set; } public int DEF { get; set; } public int SPA { get; set; } public int SPD { get; set; } public int SPE { get; set; } public override string ToString() => $@"💚**HP:** {HP,-4} ⚔**ATK:** {ATK,-4} 🛡**DEF:** {DEF,-4} ✨**SPA:** {SPA,-4} 🎇**SPD:** {SPD,-4} 💨**SPE:** {SPE,-4}"; } [JsonProperty("num")] public int Id { get; set; } public string Species { get; set; } public string[] Types { get; set; } public GenderRatioClass GenderRatio { get; set; } public BaseStatsClass BaseStats { get; set; } public Dictionary<string, string> Abilities { get; set; } public float HeightM { get; set; } public float WeightKg { get; set; } public string Color { get; set; } public string[] Evos { get; set; } public string[] EggGroups { get; set; } } }
Wizkiller96/WizBot
src/WizBot/Common/Pokemon/SearchPokemon.cs
C#
mit
1,319
package com.tomogle.iemclient.requests; /** * Represents a type of request in the IEM API. * According to the IEM API docs, it represents the 'name of the API file in question'. * * We ignore the Java uppercase enum naming convention for ease of use. */ public enum RequestType { subscribers, authentication, lists, stats }
tom-ogle/InterspireEmailMarketerClient
src/main/java/com/tomogle/iemclient/requests/RequestType.java
Java
mit
338
import Class from '../mixin/class'; import Media from '../mixin/media'; import {$, addClass, after, Animation, assign, attr, css, fastdom, hasClass, isNumeric, isString, isVisible, noop, offset, offsetPosition, query, remove, removeClass, replaceClass, scrollTop, toFloat, toggleClass, toPx, trigger, within} from 'uikit-util'; export default { mixins: [Class, Media], props: { top: null, bottom: Boolean, offset: String, animation: String, clsActive: String, clsInactive: String, clsFixed: String, clsBelow: String, selTarget: String, widthElement: Boolean, showOnUp: Boolean, targetOffset: Number }, data: { top: 0, bottom: false, offset: 0, animation: '', clsActive: 'uk-active', clsInactive: '', clsFixed: 'uk-sticky-fixed', clsBelow: 'uk-sticky-below', selTarget: '', widthElement: false, showOnUp: false, targetOffset: false }, computed: { offset({offset}) { return toPx(offset); }, selTarget({selTarget}, $el) { return selTarget && $(selTarget, $el) || $el; }, widthElement({widthElement}, $el) { return query(widthElement, $el) || this.placeholder; }, isActive: { get() { return hasClass(this.selTarget, this.clsActive); }, set(value) { if (value && !this.isActive) { replaceClass(this.selTarget, this.clsInactive, this.clsActive); trigger(this.$el, 'active'); } else if (!value && !hasClass(this.selTarget, this.clsInactive)) { replaceClass(this.selTarget, this.clsActive, this.clsInactive); trigger(this.$el, 'inactive'); } } } }, connected() { this.placeholder = $('+ .uk-sticky-placeholder', this.$el) || $('<div class="uk-sticky-placeholder"></div>'); this.isFixed = false; this.isActive = false; }, disconnected() { if (this.isFixed) { this.hide(); removeClass(this.selTarget, this.clsInactive); } remove(this.placeholder); this.placeholder = null; this.widthElement = null; }, events: [ { name: 'load hashchange popstate', el: window, handler() { if (!(this.targetOffset !== false && location.hash && window.pageYOffset > 0)) { return; } const target = $(location.hash); if (target) { fastdom.read(() => { const {top} = offset(target); const elTop = offset(this.$el).top; const elHeight = this.$el.offsetHeight; if (this.isFixed && elTop + elHeight >= top && elTop <= top + target.offsetHeight) { scrollTop(window, top - elHeight - (isNumeric(this.targetOffset) ? this.targetOffset : 0) - this.offset); } }); } } } ], update: [ { read({height}, type) { if (this.isActive && type !== 'update') { this.hide(); height = this.$el.offsetHeight; this.show(); } height = !this.isActive ? this.$el.offsetHeight : height; this.topOffset = offset(this.isFixed ? this.placeholder : this.$el).top; this.bottomOffset = this.topOffset + height; const bottom = parseProp('bottom', this); this.top = Math.max(toFloat(parseProp('top', this)), this.topOffset) - this.offset; this.bottom = bottom && bottom - height; this.inactive = !this.matchMedia; return { lastScroll: false, height, margins: css(this.$el, ['marginTop', 'marginBottom', 'marginLeft', 'marginRight']) }; }, write({height, margins}) { const {placeholder} = this; css(placeholder, assign({height}, margins)); if (!within(placeholder, document)) { after(this.$el, placeholder); attr(placeholder, 'hidden', ''); } // ensure active/inactive classes are applied this.isActive = this.isActive; }, events: ['resize'] }, { read({scroll = 0}) { this.width = (isVisible(this.widthElement) ? this.widthElement : this.$el).offsetWidth; this.scroll = window.pageYOffset; return { dir: scroll <= this.scroll ? 'down' : 'up', scroll: this.scroll, visible: isVisible(this.$el), top: offsetPosition(this.placeholder)[0] }; }, write(data, type) { const {initTimestamp = 0, dir, lastDir, lastScroll, scroll, top, visible} = data; const now = performance.now(); data.lastScroll = scroll; if (scroll < 0 || scroll === lastScroll || !visible || this.disabled || this.showOnUp && type !== 'scroll') { return; } if (now - initTimestamp > 300 || dir !== lastDir) { data.initScroll = scroll; data.initTimestamp = now; } data.lastDir = dir; if (this.showOnUp && Math.abs(data.initScroll - scroll) <= 30 && Math.abs(lastScroll - scroll) <= 10) { return; } if (this.inactive || scroll < this.top || this.showOnUp && (scroll <= this.top || dir === 'down' || dir === 'up' && !this.isFixed && scroll <= this.bottomOffset) ) { if (!this.isFixed) { if (Animation.inProgress(this.$el) && top > scroll) { Animation.cancel(this.$el); this.hide(); } return; } this.isFixed = false; if (this.animation && scroll > this.topOffset) { Animation.cancel(this.$el); Animation.out(this.$el, this.animation).then(() => this.hide(), noop); } else { this.hide(); } } else if (this.isFixed) { this.update(); } else if (this.animation) { Animation.cancel(this.$el); this.show(); Animation.in(this.$el, this.animation).catch(noop); } else { this.show(); } }, events: ['resize', 'scroll'] } ], methods: { show() { this.isFixed = true; this.update(); attr(this.placeholder, 'hidden', null); }, hide() { this.isActive = false; removeClass(this.$el, this.clsFixed, this.clsBelow); css(this.$el, {position: '', top: '', width: ''}); attr(this.placeholder, 'hidden', ''); }, update() { const active = this.top !== 0 || this.scroll > this.top; let top = Math.max(0, this.offset); if (this.bottom && this.scroll > this.bottom - this.offset) { top = this.bottom - this.scroll; } css(this.$el, { position: 'fixed', top: `${top}px`, width: this.width }); this.isActive = active; toggleClass(this.$el, this.clsBelow, this.scroll > this.bottomOffset); addClass(this.$el, this.clsFixed); } } }; function parseProp(prop, {$props, $el, [`${prop}Offset`]: propOffset}) { const value = $props[prop]; if (!value) { return; } if (isNumeric(value) && isString(value) && value.match(/^-?\d/)) { return propOffset + toPx(value); } else { return offset(value === true ? $el.parentNode : query(value, $el)).bottom; } }
RadialDevGroup/rails-uikit-sass
vendor/assets/js/core/sticky.js
JavaScript
mit
8,774
const fs = require('fs') const getLanguages = require('./private/getLanguages') const checkExistance = require('./private/checkExistance') const getThisDir = require('./private/getThisDir') const thisDir = getThisDir(module.parent.filename) const configDir = thisDir + '/i18n-tracker.config.json' const config = JSON.parse(fs.readFileSync(configDir, 'utf8')) function getTranslations() { const translations = getLanguages(config.translations) const baseExist = checkExistance(thisDir,[config.base]) const allExist = checkExistance(thisDir, translations) let returnObj = {} if(allExist && baseExist){ const base = require(`${thisDir}\\${config.base[0]}`) returnObj[config.base[0]] = base translations.forEach((translation) => { const thisTrans = require(`${thisDir}\\${translation[0]}`) returnObj[translation[0]] = thisTrans }) } return returnObj } module.exports = { getTranslations: getTranslations }
kesupile/I18n-tracker
index.js
JavaScript
mit
953
// app/models/article.js var Mongoose = require('mongoose'); // define article schema var articleSchema = Mongoose.Schema({ url: { type: String, required: true }, tags: [String], userId: { type: String, required: true }, meta: { title: String, author: String, readTime: String, summary: String, domain: String, createdAt: { type: Date, default: Date.now }, starred: { type: Boolean, default: false }, archived: { type: Boolean, default: false } }, content: { html: String, text: String } }); module.exports = Mongoose.model('Article', articleSchema);
isaacev/Ink
app/models/article.js
JavaScript
mit
615
#include "ReadAlignChunk.h" #include "Parameters.h" #include "OutSJ.h" #include <limits.h> #include "ErrorWarning.h" int compareUint(const void* i1, const void* i2) {//compare uint arrays uint s1=*( (uint*)i1 ); uint s2=*( (uint*)i2 ); if (s1>s2) { return 1; } else if (s1<s2) { return -1; } else { return 0; }; }; void outputSJ(ReadAlignChunk** RAchunk, Parameters& P) {//collapses junctions from all therads/chunks; outputs junctions to file Junction oneSJ(RAchunk[0]->RA->genOut); char** sjChunks = new char* [P.runThreadN+1]; #define OUTSJ_limitScale 5 OutSJ allSJ (P.limitOutSJcollapsed*OUTSJ_limitScale,P,RAchunk[0]->RA->genOut); if (P.outFilterBySJoutStage!=1) {//chunkOutSJ for (int ic=0;ic<P.runThreadN;ic++) {//populate sjChunks with links to data sjChunks[ic]=RAchunk[ic]->chunkOutSJ->data; memset(sjChunks[ic]+RAchunk[ic]->chunkOutSJ->N*oneSJ.dataSize,255,oneSJ.dataSize);//mark the junction after last with big number }; } else {//chunkOutSJ1 for (int ic=0;ic<P.runThreadN;ic++) {//populate sjChunks with links to data sjChunks[ic]=RAchunk[ic]->chunkOutSJ1->data; memset(sjChunks[ic]+RAchunk[ic]->chunkOutSJ1->N*oneSJ.dataSize,255,oneSJ.dataSize);//mark the junction after last with big number }; }; while (true) { int icOut=-1;//chunk from which the junction is output for (int ic=0;ic<P.runThreadN;ic++) {//scan through all chunks, find the "smallest" junction if ( *(uint*)(sjChunks[ic])<ULONG_MAX && (icOut==-1 ||compareSJ((void*) sjChunks[ic], (void*) sjChunks[icOut])<0 ) ) { icOut=ic; }; }; if (icOut<0) break; //no more junctions to output for (int ic=0;ic<P.runThreadN;ic++) {//scan through all chunks, find the junctions equal to icOut-junction if (ic!=icOut && compareSJ((void*) sjChunks[ic], (void*) sjChunks[icOut])==0) { oneSJ.collapseOneSJ(sjChunks[icOut],sjChunks[ic],P);//collapse ic-junction into icOut sjChunks[ic] += oneSJ.dataSize;//shift ic-chunk by one junction }; }; //write out the junction oneSJ.junctionPointer(sjChunks[icOut],0);//point to the icOut junction //filter the junction bool sjFilter; sjFilter=*oneSJ.annot>0 \ || ( ( *oneSJ.countUnique>=(uint) P.outSJfilterCountUniqueMin[(*oneSJ.motif+1)/2] \ || (*oneSJ.countMultiple+*oneSJ.countUnique)>=(uint) P.outSJfilterCountTotalMin[(*oneSJ.motif+1)/2] )\ && *oneSJ.overhangLeft >= (uint) P.outSJfilterOverhangMin[(*oneSJ.motif+1)/2] \ && *oneSJ.overhangRight >= (uint) P.outSJfilterOverhangMin[(*oneSJ.motif+1)/2] \ && ( (*oneSJ.countMultiple+*oneSJ.countUnique)>P.outSJfilterIntronMaxVsReadN.size() || *oneSJ.gap<=(uint) P.outSJfilterIntronMaxVsReadN[*oneSJ.countMultiple+*oneSJ.countUnique-1]) ); if (sjFilter) {//record the junction in all SJ memcpy(allSJ.data+allSJ.N*oneSJ.dataSize,sjChunks[icOut],oneSJ.dataSize); allSJ.N++; if (allSJ.N == P.limitOutSJcollapsed*OUTSJ_limitScale ) { ostringstream errOut; errOut <<"EXITING because of fatal error: buffer size for SJ output is too small\n"; errOut <<"Solution: increase input parameter --limitOutSJcollapsed\n"; exitWithError(errOut.str(),std::cerr, P.inOut->logMain, EXIT_CODE_INPUT_FILES, P); }; }; sjChunks[icOut] += oneSJ.dataSize;//shift icOut-chunk by one junction }; bool* sjFilter=new bool[allSJ.N]; if (P.outFilterBySJoutStage!=2) { //filter non-canonical junctions that are close to canonical uint* sjA = new uint [allSJ.N*3]; for (uint ii=0;ii<allSJ.N;ii++) {//scan through all junctions, filter by the donor ditance to a nearest donor, fill acceptor array oneSJ.junctionPointer(allSJ.data,ii); sjFilter[ii]=false; uint x1=0, x2=-1; if (ii>0) x1=*( (uint*)(allSJ.data+(ii-1)*oneSJ.dataSize) ); //previous junction donor if (ii+1<allSJ.N) x2=*( (uint*)(allSJ.data+(ii+1)*oneSJ.dataSize) ); //next junction donor uint minDist=min(*oneSJ.start-x1, x2-*oneSJ.start); sjFilter[ii]= minDist >= (uint) P.outSJfilterDistToOtherSJmin[(*oneSJ.motif+1)/2]; sjA[ii*3]=*oneSJ.start+(uint)*oneSJ.gap;//acceptor sjA[ii*3+1]=ii; if (*oneSJ.annot==0) { sjA[ii*3+2]=*oneSJ.motif; } else { sjA[ii*3+2]=SJ_MOTIF_SIZE+1; }; }; qsort((void*) sjA, allSJ.N, sizeof(uint)*3, compareUint); for (uint ii=0;ii<allSJ.N;ii++) {// if (sjA[ii*3+2]==SJ_MOTIF_SIZE+1) {//no filtering for annotated junctions sjFilter[sjA[ii*3+1]]=true; } else { uint x1=0, x2=-1; if (ii>0) x1=sjA[ii*3-3]; //previous junction donor if (ii+1<allSJ.N) x2=sjA[ii*3+3]; //next junction donor uint minDist=min(sjA[ii*3]-x1, x2-sjA[ii*3]); sjFilter[sjA[ii*3+1]] = sjFilter[sjA[ii*3+1]] && ( minDist >= (uint) P.outSJfilterDistToOtherSJmin[(sjA[ii*3+2]+1)/2] ); }; }; }; //output junctions P.sjAll[0].reserve(allSJ.N); P.sjAll[1].reserve(allSJ.N); if (P.outFilterBySJoutStage!=1) {//output file ofstream outSJfileStream((P.outFileNamePrefix+"SJ.out.tab").c_str()); ofstream outSJtmpStream((P.outFileTmp+"SJ.start_gap.tsv").c_str()); for (uint ii=0;ii<allSJ.N;ii++) {//write to file if ( P.outFilterBySJoutStage==2 || sjFilter[ii] ) { oneSJ.junctionPointer(allSJ.data,ii); oneSJ.outputStream(outSJfileStream);//write to file outSJtmpStream << *oneSJ.start <<'\t'<< *oneSJ.gap <<'\n'; P.sjAll[0].push_back(*oneSJ.start); P.sjAll[1].push_back(*oneSJ.gap); }; }; outSJfileStream.close(); } else {//make sjNovel array in P P.sjNovelN=0; for (uint ii=0;ii<allSJ.N;ii++) {//count novel junctions if (sjFilter[ii]) {//only those passing filter oneSJ.junctionPointer(allSJ.data,ii); if (*oneSJ.annot==0) P.sjNovelN++; }; }; P.sjNovelStart = new uint [P.sjNovelN]; P.sjNovelEnd = new uint [P.sjNovelN]; P.inOut->logMain <<"Detected " <<P.sjNovelN<<" novel junctions that passed filtering, will proceed to filter reads that contained unannotated junctions"<<endl; uint isj=0; for (uint ii=0;ii<allSJ.N;ii++) {//write to file if (sjFilter[ii]) { oneSJ.junctionPointer(allSJ.data,ii); if (*oneSJ.annot==0) {//unnnotated only P.sjNovelStart[isj]=*oneSJ.start; P.sjNovelEnd[isj]=*oneSJ.start+(uint)(*oneSJ.gap)-1; isj++; }; }; }; }; };
alexdobin/STAR
source/outputSJ.cpp
C++
mit
7,239
package sc_zap import ( "crypto/sha256" "encoding/base32" "errors" "github.com/watermint/toolbox/essentials/log/esl" "github.com/watermint/toolbox/infra/app" "github.com/watermint/toolbox/infra/control/app_control" "github.com/watermint/toolbox/infra/control/app_resource" "github.com/watermint/toolbox/infra/security/sc_obfuscate" "io/ioutil" "os" "path/filepath" "strconv" "strings" "time" ) func Unzap(ctl app_control.Control) (b []byte, err error) { tas, err := app_resource.Bundle().Keys().Bytes("toolbox.appkeys.secret") if err != nil { return nil, err } return sc_obfuscate.Deobfuscate(ctl.Log(), []byte(app.BuildInfo.Zap), tas) } var ( keyEnvNames = []string{ "HOME", "HOSTNAME", "CI_BUILD_REF", "CI_JOB_ID", "CIRCLE_BUILD_NUM", "CIRCLE_NODE_INDEX", } ) var ( ErrorObfuscateFailure = errors.New("obfuscation failure") ErrorCantFileWrite = errors.New("cant write file") ) func NewZap(extraSeed string) string { seeds := make([]byte, 0) seeds = strconv.AppendInt(seeds, time.Now().Unix(), 16) seeds = append(seeds, app.BuildId...) seeds = append(seeds, extraSeed...) for _, k := range keyEnvNames { if v, ok := os.LookupEnv(k); ok { seeds = append(seeds, k...) seeds = append(seeds, v...) } } hash := make([]byte, 32) sha2 := sha256.Sum256(seeds) copy(hash[:], sha2[:]) b32 := base32.StdEncoding.WithPadding('_').EncodeToString(hash) return strings.ReplaceAll(b32, "_", "") } func Zap(zap string, prjRoot string, data []byte) error { secretPath := filepath.Join(prjRoot, "resources/keys/toolbox.appkeys.secret") l := esl.Default() b, err := sc_obfuscate.Obfuscate(l, []byte(zap), data) if err != nil { return ErrorObfuscateFailure } if err := ioutil.WriteFile(secretPath, b, 0600); err != nil { return ErrorCantFileWrite } return nil }
watermint/toolbox
infra/security/sc_zap/zap.go
GO
mit
1,823
using System; using Xamarin.Forms; namespace people { public partial class NewItemPage : ContentPage { public Item Item { get; set; } public NewItemPage() { InitializeComponent(); Item = new Item { Text = "Item name", Description = "This is an item description." }; BindingContext = this; } async void Save_Clicked(object sender, EventArgs e) { MessagingCenter.Send(this, "AddItem", Item); await Navigation.PopToRootAsync(); } } }
pjsamuel3/xPlatformDotNet
mac_app/people/Views/NewItemPage.xaml.cs
C#
mit
624
using Abstraction; using System; namespace CohesionAndCoupling { public static class PointUtils { public static double CalcDistance2D(Point3D first, Point3D second) { double distanceX = (second.X - first.X) * (second.X - first.X); double distanceY = (second.Y - first.Y) * (second.Y - first.Y); double distance = Math.Sqrt(distanceX + distanceY); return distance; } public static double CalcDistance3D(Point3D first, Point3D second) { double distance = first.DistanceTo(second); return distance; } } }
dobri19/OldRepos
Telerik/01-Programming-with-C#/03-HighQualityCode01-2016-August/08-HighClasses/Cohesion-and-Coupling/PointUtils.cs
C#
mit
642
<?php /* |-------------------------------------------------------------------------- | Application Routes |-------------------------------------------------------------------------- | | Here is where you can register all of the routes for an application. | It's a breeze. Simply tell Laravel the URIs it should respond to | and give it the controller to call when that URI is requested. | */ Route::get('/', 'ArticlesController@index'); //Route::get('contact', 'WelcomeController@contact'); // //Route::get('home', 'HomeController@index'); Route::resource('articles', 'ArticlesController'); Route::get('tags/{tags}', 'TagsController@show'); Route::controllers(['auth' => 'Auth\AuthController', 'password' => 'Auth\PasswordController',]);
bionikspoon/playing-with-laravel-5---getting-up-to-speed
app/Http/routes.php
PHP
mit
768
module Fontello module Rails class Engine < ::Rails::Engine end end end
blackxored/fontello-rails
lib/fontello-rails/engine.rb
Ruby
mit
84
const webModel = require('../webModel'); const webModelFunctions = require('../webModelFunctions'); const robotModel = require('../robotModel'); const getCmdVelIdleTime = require('../getCmdVelIdleTime'); const WayPoints = require('../WayPoints.js'); const wayPointEditor = new WayPoints(); function pickRandomWaypoint() { if (webModel.debugging && webModel.logBehaviorMessages) { const message = ' - Checking: Random Waypoint Picker'; console.log(message); webModelFunctions.scrollingStatusUpdate(message); } if ( webModel.ROSisRunning && webModel.wayPoints.length > 1 && // If we only have 1, it hardly works. webModel.mapName !== '' && !webModel.pluggedIn && !webModel.wayPointNavigator.goToWaypoint && !robotModel.goToWaypointProcess.started && getCmdVelIdleTime() > 2 // TODO: Set this time in a config or something. // TODO: Also make it 5 once we are done debugging. ) { if (webModel.debugging && webModel.logBehaviorMessages) { console.log(` - Picking a random waypoint!`); } if (robotModel.randomWaypointList.length === 0) { robotModel.randomWaypointList = [...webModel.wayPoints]; } // Remove most recent waypoint from list in case this was a list reload. if (robotModel.randomWaypointList.length > 1) { const lastWaypointEntry = robotModel.randomWaypointList.indexOf( webModel.wayPointNavigator.wayPointName, ); if (lastWaypointEntry > -1) { robotModel.randomWaypointList.splice(lastWaypointEntry, 1); } } // Pick a random entry from the list. const randomEntryIndex = Math.floor( Math.random() * robotModel.randomWaypointList.length, ); // Set this as the new waypoint, just like user would via web site, // and remove it from our list. if (webModel.debugging && webModel.logBehaviorMessages) { console.log(` - ${robotModel.randomWaypointList[randomEntryIndex]}`); } wayPointEditor.goToWaypoint( robotModel.randomWaypointList[randomEntryIndex], ); robotModel.randomWaypointList.splice(randomEntryIndex, 1); // Preempt remaining functions, as we have an action to take now. return false; } // This behavior is idle, allow behave loop to continue to next entry. return true; } module.exports = pickRandomWaypoint;
chrisl8/ArloBot
node/behaviors/pickRandomWaypoint.js
JavaScript
mit
2,341
/** * Created by zhibo on 15-8-20. */ /* * 上传图片插件改写 * @author: * @data: 2013年2月17日 * @version: 1.0 * @rely: jQuery */ $(function(){ /* * 参数说明 * baseUrl: 【字符串】表情路径的基地址 */ var lee_pic = { uploadTotal : 0, uploadLimit : 8, //最多传多少张 uploadify:function(){ //文件上传测试 $('#file').uploadify({ swf : 'http://ln.localhost.com/static/uploadify/uploadify.swf', uploader : '', width : 120, height : 30, fileTypeDesc : '图片类型', buttonCursor:'pointer', buttonText:'上传图片', fileTypeExts : '*.jpeg; *.jpg; *.png; *.gif', fileSizeLimit : '1MB', overrideEvents : ['onSelectError','onSelect','onDialogClose'], //错误替代 onSelectError : function (file, errorCode, errorMsg) { switch (errorCode) { case -110 : $('#error').dialog('open').html('超过1024KB...'); setTimeout(function () { $('#error').dialog('close').html('...'); }, 1000); break; } }, //开始上传前 onUploadStart : function () { if (lee_pic.uploadTotal == 8) { $('#file').uploadify('stop'); $('#file').uploadify('cancel'); $('#error').dialog('open').html('限制为8张...'); setTimeout(function () { $('#error').dialog('close').html('...'); }, 1000); } else { $('.weibo_pic_list').append('<div class="weibo_pic_content"><span class="remove"></span><span class="text">删除</span><img src="' + ThinkPHP['IMG'] + '/loading_100.png" class="weibo_pic_img"></div>'); } }, //上传成功后的函数 onUploadSuccess : function (file, data, response) { // alert(data); //打印出返回的数据 $('.weibo_pic_list').append('<input type="hidden" name="images" value='+ data +'> ') var imageUrl= $.parseJSON(data); /* data是返回的回调信息alert file上传的图片信息 用console.log(file);测试 response上传成功与否 alert alert(response); alert(data); $('.weibo_pic_list').append('<div class="weibo_pic_content"><span class="remove"></span><span class="text">删除</span><img src="' + ThinkPHP['IMG'] + '/loading_100.png" class="weibo_pic_img"></div>'); //把上传的图片返回的缩略图结果写入html页面中 */ lee_pic.thumb(imageUrl['thumb']); //执行缩略图显示问题 lee_pic.hover(); lee_pic.remove(); //共 0 张,还能上传 8 张(按住ctrl可选择多张 lee_pic.uploadTotal++; lee_pic.uploadLimit--; $('.weibo_pic_total').text(lee_pic.uploadTotal); $('.weibo_pic_limit').text(lee_pic.uploadLimit); } }); }, hover:function(){ //上传图片鼠标经过显示删除按扭 var content=$('.weibo_pic_content'); var len=content.length; $(content[len - 1]).hover(function(){ $(this).find('.remove').show(); $(this).find('.text').show(); },function(){ $(this).find('.remove').hide(); $(this).find('.text').hide(); }); }, remove:function(){ //删除上传的图片操作 var remove=$('.weibo_pic_content .text'); var removelen=remove.length; $(remove[removelen-1]).on('click',function(){ $(this).parent('.weibo_pic_content').next('input[name="images"]').remove(); $(this).parents('.weibo_pic_content').remove(); //共 0 张,还能上传 8 张(按住ctrl可选择多张 lee_pic.uploadTotal--; lee_pic.uploadLimit++; $('.weibo_pic_total').text(lee_pic.uploadTotal); $('.weibo_pic_limit').text(lee_pic.uploadLimit); }); }, thumb : function (src) { /*调节缩略图显示问题-即不以中心点为起点显示*/ var img = $('.weibo_pic_img'); var len = img.length; //alert(src); $(img[len - 1]).attr('src', ThinkPHP['LOCALNAME']+src).hide(); setTimeout(function () { if ($(img[len - 1]).width() > 100) { $(img[len - 1]).css('left', -($(img[len - 1]).width() - 100) / 2); } if ($(img[len - 1]).height() > 100) { $(img[len - 1]).css('top', -($(img[len - 1]).height() - 100) / 2); } //记图片淡入淡出 $(img[len - 1]).attr('src', ThinkPHP['LOCALNAME']+src).fadeIn(); }, 50); }, init:function(){ /*绑定上传图片弹出按钮响应,初始化。*/ //绑定uploadify函数 lee_pic.uploadify(); /*绑定关闭按钮*/ $('#pic_box a.close').on('click',function(){ $('#pic_box').hide(); $('.pic_arrow_top').hide(); }); /*绑定document点击事件,对target不在上传图片弹出框上时执行引藏事件 //由于鼠标离开窗口就会关闭,影响使用,所以取消 $(document).on('click',function(e){ var target = $(e.target); if( target.closest("#pic_btn").length == 1 || target.closest(".weibo_pic_content .text").length == 1) return; if( target.closest("#pic_box").length == 0 ){ $('#pic_box').hide(); $('.pic_arrow_top').hide(); } }); */ } }; lee_pic.init(); //调用初始化函数。 window.uploadCount = { clear : function () { lee_pic.uploadTotal = 0; lee_pic.uploadLimit = 8; } }; });
zl0314/ruida
static/js/lee_pic.js
JavaScript
mit
6,916
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed'); class Cart extends CI_Controller { private $data; public function __construct() { parent::__construct(); $this->load->library('cart'); $this->load->model("cart_model"); $this->load->model("product_model"); } public function index(){ if(!$this->session->userdata('s_uid') || $this->session->userdata('s_uid')==''){ $user_type = 'Guest'; $user_id = $this->session->userdata('__ci_last_regenerate'); }else{ $user_type = 'Member'; $user_id = $this->session->userdata('s_uid'); } $cart_arr = array(); if(isset($_POST['remove-item'])){ $this->cart_model->remove_cart_product($_POST); } if(isset($_GET['quantity'])){ $this->cart_model->update_cart_qty($_GET); exit; } $cart = $this->cart_model->get_cart_items($user_id); if(!empty($cart)){ $cart_arr = $cart; //For Promo Code $get_promo_code = $this->cart_model->get_promo_code($user_id); if(!empty($get_promo_code)){ array_push($cart_arr,$get_promo_code); $this->data['coupon_code'] = $get_promo_code; } //Get cart data and cart total $data = $this->get_showcart_details($cart_arr,$user_id,$user_type); } else { //Used when cart_detail is empty for user_id and cart_mast have data for that user_id then remove cart_mast detail $this->cart_model->delete_cart_mast($user_id); $data = ''; } /*echo "<pre>"; print_r($data); exit;*/ $this->data['cart_data'] = $data; $view_file_name = 'cart_view'; $this->data['view_file_name'] = $view_file_name; $this->data['user_id'] = $user_id; $this->data['user_type'] = $user_type; $this->template->load_cart_view($view_file_name , $this->data); }//End of index public function proceed_checkout(){ /*$this->form_validation->set_message('dwfrm_login_username_d0jbuwnvxveb','Please enter valid email;'); $view_file_name = 'proceed_checkout'; $data = ''; $data['view_file_name'] = $view_file_name; $this->load->view($view_file_name , $data);*/ $this->load->view('proceed_checkout'); } public function checkout_signin(){ $view_file_name = 'checkout_signin'; $data['view_file_name'] = $view_file_name; $this->template->load_info_view($view_file_name , $data); } public function get_showcart_details($cart,$user_id,$user_type){ if(!empty($cart)){ $data = $this->cart_api($cart,$user_id); if(!empty($data)){ $cart_total = $data['cart_total']; $total_discount = $data['total_discount']; $freight_charges = $data['freight_charges'];//Freight charges get from xml response $cart_mast_arr = array( 'cart_total' => $cart_total, 'freight_charges' => $freight_charges, //'total_discount' => $total_discount, 'original_cart_total' => $data['original_cart_total'] ); //Insert or update cart_mast $insert_total = $this->cart_model->insert_cart_total($user_id,$cart_mast_arr); $cart_details = $data['cart_detail']; if(!empty($cart_details)){ foreach ($cart_details as $item){ if (!empty($item['Price']) && $item['Price'] != 0) { if(!empty($item['Discounts'])){ $discounts = (array)$item['Discounts']; $discount = (array)$discounts['Discount']; $discounts_xml = " <Discounts> <Discount> <Id>".$discount['Id']."</Id> <ParentId>".$discount['ParentId']."</ParentId> <DiscountType>".$discount['DiscountType']."</DiscountType> <DiscountTypeId>".$discount['DiscountTypeId']."</DiscountTypeId> <PromoId>".$discount['PromoId']."</PromoId> <LoyaltyId /> <Sequence>".$discount['Sequence']."</Sequence> <Description>".$discount['Description']."</Description> <Percentage>".$discount['Percentage']."</Percentage> <Value>".$discount['Value']."</Value> <TaxPercent>".$discount['TaxPercent']."</TaxPercent> </Discount> </Discounts> "; $discount_percentage = $discount['Percentage']; }else{ $discounts_xml = ''; $discount_percentage =''; } $update_data = array( 'user_id' => $user_id, 'user_type' => $user_type, 'cart_id' => $item['cart_id'], 'product_id' => $item['ProductId'], 'sku' => $item['SkuId'], 'barcode' => $item['barcode'], 'style' => $item['style'], 'color' => $item['color'], 'size' => $item['SizeCode'], 'length' => $item['length'], 'qty' => $item['Quantity'], 'discount_xml' => $discounts_xml, 'discount_percentage' => $discount_percentage, 'discount_price'=> $item['Value'], 'price_sale' => $item['price_sale'], 'unit_price' => $item['Price'], 'original_price'=> $item['original_price'], 'category'=> $item['category'], 'gender'=> $item['gender'], 'operation' => 'update' ); //Update value from xml into cart_detail $returnVal = $this->cart_model->insert_into_cart_details($update_data); }// end of (!empty($item['Price']) && $item['Price'] != 0 }// end of foreach $cart_details }// end of (!empty($cart_details) $return_data['cart_xml'] = $data['cart_xml']; $return_data['cart_api'] = $data['cart_api']; $return_data['cart_detail'] = $this->cart_model->get_cart_items($user_id); $return_data['cart_total'] = $cart_total; } else { //When API call not get connected directaly call from table $return_data['cart_detail'] = $this->cart_model->get_cart_items($user_id); $cart_total = $this->cart_model->get_cart_total($user_id); if (!empty($cart_total)) { $return_data['cart_total'] = $cart_total; } else { $return_data['cart_total'] = 0; } } } else { $return_data = ''; } return $return_data; } //End of get showcart details public function cart_api($cart,$user_id){ $data=''; if(!empty($cart)){ $cart_xml="<Cart> <PersonId>115414</PersonId> <Contacts> </Contacts> <CartDetails>\n\t"; foreach ($cart as $item) { $sku = $item['sku']; $qty = $item['qty']; $cart_xml.=" <CartDetail> <SkuId>$sku</SkuId> <Quantity>$qty</Quantity> </CartDetail>\n\t"; } $cart_xml.="</CartDetails> </Cart>"; // $data['cart_xml']=$cart_xml; /*echo "<pre>"; print_r($cart_xml); exit;*/ $URL = APP21_URL."/Carts/1234?countryCode=".COUNTRY_CODE; $ch = curl_init($URL); curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0); curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0); curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "PUT"); curl_setopt($ch, CURLOPT_HEADER, false); curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: text/xml,Accept: version_2.0')); curl_setopt($ch, CURLOPT_POSTFIELDS, "$cart_xml"); curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); curl_setopt($ch, CURLOPT_HEADER, 0); $output = curl_exec($ch); if ( curl_errno($ch) ) { $result = 'cURL ERROR -> ' . curl_errno($ch) . ': ' . curl_error($ch); $curl_errno = curl_errno($ch); $returnVal = false; $syncproduct_data = array( 'curl_error_no' => $curl_errno, 'url' => $URL, 'curl_result' => $result, 'error_text' => 'Cart Error' ); //add alert here } else { $returnCode = (int)curl_getinfo($ch, CURLINFO_HTTP_CODE); switch($returnCode){ case 200: $xml = simplexml_load_string($output); /*echo "<pre>"; print_r($xml); exit();*/ $cartdetail_arr=array(); foreach ($xml->CartDetails->CartDetail as $curr_detail) { $temp = (array) $curr_detail; $sku = $curr_detail->SkuId; if(!empty($curr_detail->Price)){ $result = $this->cart_model->get_cart_details($sku,$user_id); $temp['cart_id']= $result->cart_id; $temp['original_price']= $result->original_price; $temp['style']= $result->style;//Style $temp['price_sale']= $result->price_sale; $temp['barcode']= $result->barcode; $temp['color'] = $result->color; $temp['length'] = $result->length; $temp['category'] = $result->category; $temp['gender'] = $result->gender; } $cartdetail_arr[] = $temp; } $freight_charges = $xml->SelectedFreightOption->Value;//Freight chareges $total_due = (array)$xml->TotalDue; $cart_total = $total_due[0];//Cart total $total_disc = (array)$xml->TotalDiscount; $total_discount = $total_disc[0];//Cart total $data['cart_api'] = $xml; $data['cart_detail']= $cartdetail_arr; $data['cart_total'] = $cart_total - $freight_charges; $data['original_cart_total'] = $cart_total; $data['total_discount'] = $total_discount; $data['freight_charges'] = $freight_charges; break; default: $result = 'HTTP ERROR -> ' . $returnCode ."<br>".$data; $return_value = false; $syncproduct_data = array( 'curl_error_no' => $returnCode, 'url' => $URL, 'curl_result' => $result, 'error_text' => 'Cart Error' ); //add alert here break; } } curl_close($ch); return $data; } }//End of cart api public function add($type = '') { //retrieve all the post data. /*echo "<pre>"; print_r($_POST);*/ //exit(); $color = $this->input->post('color'); $style = $this->input->post('style'); $prod_qty = $this->input->post('qty'); $barcode = $this->input->post('barcode'); $size = $this->input->post('size'); $length = $this->input->post('length'); $cart_id = $this->input->post('cart_id'); $seo_category = $this->input->post('seo_category'); $cat_result = $this->product_model->get_product_category($style); switch($cat_result){ case "t-shirts-and-tops": $category_result = 't-shirt'; break; case "pants": $category_result = 'pant'; break; case "sweat-shirts": $category_result = 'sweat shirt'; break; case "wallets-and-small-goods": $category_result = 'wallet'; break; default: $category_result = $cat_result; } if(!$this->session->userdata('s_uid') || $this->session->userdata('s_uid')==''){ $user_type = 'Guest'; $user_id = $this->session->userdata('__ci_last_regenerate'); }else{ $user_type = 'Member'; $user_id = $this->session->userdata('s_uid'); } // check if the products exists in database $prod = $this->cart_model->check_product($barcode); /*echo "<pre>"; print_r($prod); exit();*/ if(!empty($prod)){ $data = array( 'user_id' => $user_id, 'user_type' => $user_type, 'product_id' => $prod['product_mast_id'], 'category' => $seo_category, //$prod['productGroup'], 'gender' => $prod['gender'], 'sku' => $prod['sku_idx'], //sku 'barcode' => $barcode, //barcode 'style' => $style, //barcode 'color' => $color, 'size' => $size, 'length' => $length, 'qty' => $prod_qty, 'discount_xml' => '', 'discount_percentage' =>'', 'discount_price' => $prod['price'], 'price_sale' => (!empty($prod['price_sale']))? $prod['price_sale']:0, 'unit_price' => $prod['price'], 'original_price' => $prod['price'], 'created_dt' => date('Y-m-d H:i:s') ); if($type == 'ajax'){ $data['operation'] = 'insert'; } elseif ($cart_id == null) { $data['operation'] = 'insert'; } else { echo $data['operation'] = 'update'; $data['cart_id'] = $cart_id; } $this->cart_model->insert_into_cart_details($data); $flag = TRUE; /*if($data['operation'] == 'update'): redirect(base_url()."cart"); endif;*/ } else { $flag = FALSE; } echo $flag; }// end of add method public function ajax_cart(){ if(!$this->session->userdata('s_uid') || $this->session->userdata('s_uid')==''){ $user_id = $this->session->userdata('__ci_last_regenerate'); }else{ $user_id = $this->session->userdata('s_uid'); } $carts = $this->cart_model->get_cart_items($user_id); echo json_encode($carts); } // end of ajax cart method public function remove_item(){ $this->cart_model->delete_cart_item($_GET); }//end of remove_item public function show_product($cat="",$prod_name="",$style="",$color="",$barcode="",$cart_id="",$quantity=""){ /*echo "$cat<br/>"; echo "$prod_name<br/>"; echo "$style<br/>"; echo "$color<br/>"; echo "$barcode<br/>"; exit();*/ $data = ''; $this->data['title']=""; $this->data['category'] = $cat; if($barcode != ""){ $this->data['prod_barcode_details'] = $this->product_model->get_prod_barcode_details($barcode); } if($style != '' && $color != '') { $this->data['prod_arr'] = $this->product_model->get_showproduct_detail($style,$color); $this->data['size'] = $this->product_model->get_size($style,$color); $this->data['length'] = $this->product_model->get_length($style,$color); $this->data['color'] = $this->product_model->get_color_new($style); $count = sizeof($this->data['color']); $this->data['count_color'] = $count; $this->data['prod_image_arr'] = $this->product_model->get_prod_images($style,$color); $this->data['count_image'] = sizeof($this->data['prod_image_arr']); } $this->data['cat'] = $cat; $this->data['prod_name'] = $prod_name; $this->data['cart_id'] = $cart_id; $this->data['product_color'] = $color; $this->data['quantity'] = $quantity; /*echo "<pre>"; print_r($this->data); exit();*/ $this->data['view_file_name'] = 'quickview_product'; $this->load->view('quickview_product',$this->data); } public function checkout_view(){ $data['view_file_name'] = 'checkout_view'; //$data['curr_page_shoppingcart']= 'selected'; $this->template->load_info_view('cart/checkout_view',$data); } public function couponvalidate(){ //echo "Hi";exit; $promotion = array(); $coupon_code = $_POST['promo_code']; $email_id = $_POST['email_id']; //echo "CC :".$coupon_code." email : ".$email_id;exit; if(!$this->session->userdata('s_uid') || $this->session->userdata('s_uid')==''){ $user_type = 'Guest'; $user_id = $this->session->userdata('__ci_last_regenerate'); }else{ $user_type = 'Member'; $user_id = $this->session->userdata('s_uid'); } if(isset($coupon_code) && $coupon_code != ''){ $result = $this->cart_model->check_coupon_code($coupon_code); if($result){ if($result == 'exp'){ $promotion ['result'] = 'fail'; $promotion['msg'] = 'Promotion code expired'; $promotion['redirect'] = 0; } else { $check_email = $this->cart_model->check_coupon_emailuser($coupon_code,$email_id); if($check_email){ if($check_email == 'used'){ $promotion ['result'] = 'fail'; $promotion['msg'] = 'Whoops, you have used this promotion code already'; $promotion['redirect'] = 0; } else { $promotion ['result'] = 'success'; $promotion['msg'] = 'Valid Code'; $promotion['url'] = base_url('cart'); $promotion['redirect'] = 1; $cart_mast = array( 'user_id' => $user_id, 'promo_code' => $result->promo_code, 'promo_string' => $result->promo_string, 'sku' => $result->skuidx, ); $this->cart_model->insert_cart_mast($cart_mast); } }else{ $promotion ['result'] = 'fail'; $promotion['msg'] = 'Please enter the email address you have used to register with, if you have not yet - register here'; $promotion['redirect'] = 0; } } } else{ $promotion ['result'] = 'fail'; $promotion['msg'] = 'Discount Code is not valid'; $promotion['redirect'] = 0; } } else { $promotion ['result'] = 'fail'; $promotion['msg'] = 'Please enter Discount Code'; $promotion['redirect'] = 0; } echo json_encode($promotion); //echo $promotion; }//end of couponvalidate public function removecoupon($promo_code) { if(!$this->session->userdata('s_uid') || $this->session->userdata('s_uid')==''){ $user_type = 'Guest'; $user_id = $this->session->userdata('__ci_last_regenerate'); }else{ $user_type = 'Member'; $user_id = $this->session->userdata('s_uid'); } if (isset($promo_code)) { $promotion = $this->cart_model->deleteCoupon($user_id,$promo_code); } redirect('cart'); }//end of removecoupon } // end of class
sygcom/diesel_2016
application/controllers/Cart_2016_09_28.php
PHP
mit
17,322
module Fintech class Stat attr_accessor :date, :previous, :rate, :installment, :payments, :fees_assessed def initialize(attrs = {}) attrs.each { |k, v| send("#{k}=", v) if respond_to?("#{k}=") } end def scheduled_payment_cents @scheduled_payment_cents ||= if payments.any? [payments.map(&:amount_cents).reduce(:+), remaining_balance].min.truncate else 0 end end def payment_cents @payment_cents ||= scheduled_payment_cents - apply_to_future_credits_applied end def payment_dollars @payment_dollars ||= payment_cents / 100.0 end def remaining_balance @remaining_balance ||= beginning_principal + beginning_interest + beginning_fees + fees_assessed end # apply to future def beginning_apply_to_future_credits @beginning_apply_to_future_credits ||= previous.ending_apply_to_future_credits end def apply_to_future_credits_earned @apply_to_future_credits_earned ||= payments.inject(0) do |memo, payment| memo += (payment.apply_to_future ? payment.amount_cents : 0) end end def apply_to_future_credits_applied @apply_to_future_credits_applied ||= if installment [scheduled_payment_cents, beginning_apply_to_future_credits].min else 0 end end def ending_apply_to_future_credits @ending_apply_to_future_credits ||= beginning_apply_to_future_credits + apply_to_future_credits_earned - apply_to_future_credits_applied end # principal def beginning_principal @beginning_principal ||= previous.ending_principal end def ending_principal @ending_principal ||= beginning_principal - principal end def principal @principal ||= payment_cents - fees_paid - interest_paid end def principal_due @principal_due ||= installment ? installment.principal : 0 end def total_principal_due @total_principal_due ||= previous.total_principal_due + principal_due end def total_principal_paid @total_principal_paid ||= previous.total_principal_paid + principal end def principal_receivable @principal_receivable ||= total_principal_due - total_principal_paid end # interest def beginning_interest @beginning_interest ||= previous.ending_interest end def interest_paid @interest_paid ||= [payment_cents - fees_paid, beginning_interest].min end def interest_accrued @interest_accrued ||= [ending_principal, 0].max * rate.daily end def ending_interest @ending_interest ||= beginning_interest + interest_accrued - interest_paid end def total_interest_income @total_interest_income ||= previous.total_interest_income + interest_accrued end def total_interest_due @total_interest_due ||= if installment previous.total_interest_income else previous.total_interest_due end end def total_interest_paid @total_interest_paid ||= previous.total_interest_paid + interest_paid end def interest_receivable @interest_receivable ||= total_interest_due - total_interest_paid end # fees def beginning_fees @beginning_fees ||= previous.ending_fees end def fees_paid @fees_paid ||= [[beginning_fees + fees_assessed, payment_cents].min, 0].max end def ending_fees @ending_fees ||= beginning_fees + fees_assessed - fees_paid end def accounts_receivable @accounts_receivable ||= principal_receivable + interest_receivable end def inspect "<Fintech::Stat date: #{date}, ending_principal: #{ending_principal.truncate}>" end end end
dvanderbeek/fintech
lib/fintech/stat.rb
Ruby
mit
3,844
<?php namespace Numa\DOAApiBundle\Controller; use Symfony\Bundle\FrameworkBundle\Controller\Controller; class DefaultController extends Controller { public function indexAction($name) { return $this->render('NumaDOAApiBundle:Default:index.html.twig', array('name' => $name)); } }
genjerator13/doa
src/Numa/DOAApiBundle/Controller/DefaultController.php
PHP
mit
303
import pytest from aiohttp_json_api.common import JSONAPI_CONTENT_TYPE class TestDocumentStructure: """Document Structure""" @pytest.mark.parametrize( 'resource_type', ('authors', 'books', 'chapters', 'photos', 'stores') ) async def test_response_by_json_schema(self, fantasy_client, jsonapi_validator, resource_type): response = await fantasy_client.get(f'/api/{resource_type}') json = await response.json(content_type=JSONAPI_CONTENT_TYPE) assert jsonapi_validator.is_valid(json)
vovanbo/aiohttp_json_api
tests/integration/test_document_structure.py
Python
mit
587
from collections import defaultdict from collections import namedtuple from itertools import izip from enum import Enum from tilequeue.process import Source def namedtuple_with_defaults(name, props, defaults): t = namedtuple(name, props) t.__new__.__defaults__ = defaults return t class LayerInfo(namedtuple_with_defaults( 'LayerInfo', 'min_zoom_fn props_fn shape_types', (None,))): def allows_shape_type(self, shape): if self.shape_types is None: return True typ = shape_type_lookup(shape) return typ in self.shape_types class ShapeType(Enum): point = 1 line = 2 polygon = 3 # aliases, don't use these directly! multipoint = 1 linestring = 2 multilinestring = 2 multipolygon = 3 @classmethod def parse_set(cls, inputs): outputs = set() for value in inputs: t = cls[value.lower()] outputs.add(t) return outputs or None # determine the shape type from the raw WKB bytes. this means we don't have to # parse the WKB, which can be an expensive operation for large polygons. def wkb_shape_type(wkb): reverse = ord(wkb[0]) == 1 type_bytes = map(ord, wkb[1:5]) if reverse: type_bytes.reverse() typ = type_bytes[3] if typ == 1 or typ == 4: return ShapeType.point elif typ == 2 or typ == 5: return ShapeType.line elif typ == 3 or typ == 6: return ShapeType.polygon else: assert False, 'WKB shape type %d not understood.' % (typ,) def deassoc(x): """ Turns an array consisting of alternating key-value pairs into a dictionary. Osm2pgsql stores the tags for ways and relations in the planet_osm_ways and planet_osm_rels tables in this format. Hstore would make more sense now, but this encoding pre-dates the common availability of hstore. Example: >>> from raw_tiles.index.util import deassoc >>> deassoc(['a', 1, 'b', 'B', 'c', 3.14]) {'a': 1, 'c': 3.14, 'b': 'B'} """ pairs = [iter(x)] * 2 return dict(izip(*pairs)) # fixtures extend metadata to include ways and relations for the feature. # this is unnecessary for SQL, as the ways and relations tables are # "ambiently available" and do not need to be passed in arguments. class Metadata(object): def __init__(self, source, ways, relations): assert source is None or isinstance(source, Source) self.source = source and source.name self.ways = ways self.relations = relations class Table(namedtuple('Table', 'source rows')): def __init__(self, source, rows): super(Table, self).__init__(source, rows) assert isinstance(source, Source) def shape_type_lookup(shape): typ = shape.geom_type if typ.startswith('Multi'): typ = typ[len('Multi'):] return typ.lower() # list of road types which are likely to have buses on them. used to cut # down the number of queries the SQL used to do for relations. although this # isn't necessary for fixtures, we replicate the logic to keep the behaviour # the same. BUS_ROADS = set([ 'motorway', 'motorway_link', 'trunk', 'trunk_link', 'primary', 'primary_link', 'secondary', 'secondary_link', 'tertiary', 'tertiary_link', 'residential', 'unclassified', 'road', 'living_street', ]) class Relation(object): def __init__(self, obj): self.id = obj['id'] self.tags = deassoc(obj['tags']) way_off = obj['way_off'] rel_off = obj['rel_off'] self.node_ids = obj['parts'][0:way_off] self.way_ids = obj['parts'][way_off:rel_off] self.rel_ids = obj['parts'][rel_off:] def mz_is_interesting_transit_relation(tags): public_transport = tags.get('public_transport') typ = tags.get('type') return public_transport in ('stop_area', 'stop_area_group') or \ typ in ('stop_area', 'stop_area_group', 'site') # starting with the IDs in seed_relations, recurse up the transit relations # of which they are members. returns the set of all the relation IDs seen # and the "root" relation ID, which was the "furthest" relation from any # leaf relation. def mz_recurse_up_transit_relations(seed_relations, osm): root_relation_ids = set() root_relation_level = 0 all_relations = set() for rel_id in seed_relations: front = set([rel_id]) seen = set([rel_id]) level = 0 if root_relation_level == 0: root_relation_ids.add(rel_id) while front: new_rels = set() for r in front: new_rels |= osm.transit_relations(r) new_rels -= seen level += 1 if new_rels and level > root_relation_level: root_relation_ids = new_rels root_relation_level = level elif new_rels and level == root_relation_level: root_relation_ids |= new_rels front = new_rels seen |= front all_relations |= seen root_relation_id = min(root_relation_ids) if root_relation_ids else None return all_relations, root_relation_id # extract a name for a transit route relation. this can expand comma # separated lists and prefers to use the ref rather than the name. def mz_transit_route_name(tags): # prefer ref as it's less likely to contain the destination name name = tags.get('ref') if not name: name = tags.get('name') if name: name = name.strip() return name def is_station_or_stop(fid, shape, props): 'Returns true if the given (point) feature is a station or stop.' return ( props.get('railway') in ('station', 'stop', 'tram_stop') or props.get('public_transport') in ('stop', 'stop_position', 'tram_stop') ) def is_station_or_line(fid, shape, props): """ Returns true if the given (line or polygon from way) feature is a station or transit line. """ railway = props.get('railway') return railway in ('subway', 'light_rail', 'tram', 'rail') Transit = namedtuple( 'Transit', 'score root_relation_id ' 'trains subways light_rails trams railways') def mz_calculate_transit_routes_and_score(osm, node_id, way_id, rel_id): candidate_relations = set() if node_id: candidate_relations.update(osm.relations_using_node(node_id)) if way_id: candidate_relations.update(osm.relations_using_way(way_id)) if rel_id: candidate_relations.add(rel_id) seed_relations = set() for rel_id in candidate_relations: rel = osm.relation(rel_id) if rel and mz_is_interesting_transit_relation(rel.tags): seed_relations.add(rel_id) del candidate_relations # this complex query does two recursive sweeps of the relations # table starting from a seed set of relations which are or contain # the original station. # # the first sweep goes "upwards" from relations to "parent" relations. if # a relation R1 is a member of relation R2, then R2 will be included in # this sweep as long as it has "interesting" tags, as defined by the # function mz_is_interesting_transit_relation. # # the second sweep goes "downwards" from relations to "child" relations. # if a relation R1 has a member R2 which is also a relation, then R2 will # be included in this sweep as long as it also has "interesting" tags. all_relations, root_relation_id = mz_recurse_up_transit_relations( seed_relations, osm) del seed_relations # collect all the interesting nodes - this includes the station node (if # any) and any nodes which are members of found relations which have # public transport tags indicating that they're stations or stops. stations_and_stops = set() for rel_id in all_relations: rel = osm.relation(rel_id) if not rel: continue for node_id in rel.node_ids: node = osm.node(node_id) if node and is_station_or_stop(*node): stations_and_stops.add(node_id) if node_id: stations_and_stops.add(node_id) # collect any physical railway which includes any of the above # nodes. stations_and_lines = set() for node_id in stations_and_stops: for way_id in osm.ways_using_node(node_id): way = osm.way(way_id) if way and is_station_or_line(*way): stations_and_lines.add(way_id) if way_id: stations_and_lines.add(way_id) # collect all IDs together in one array to intersect with the parts arrays # of route relations which may include them. all_routes = set() for lookup, ids in ((osm.relations_using_node, stations_and_stops), (osm.relations_using_way, stations_and_lines), (osm.relations_using_rel, all_relations)): for i in ids: for rel_id in lookup(i): rel = osm.relation(rel_id) if rel and \ rel.tags.get('type') == 'route' and \ rel.tags.get('route') in ('subway', 'light_rail', 'tram', 'train', 'railway'): all_routes.add(rel_id) routes_lookup = defaultdict(set) for rel_id in all_routes: rel = osm.relation(rel_id) if not rel: continue route = rel.tags.get('route') if route: route_name = mz_transit_route_name(rel.tags) routes_lookup[route].add(route_name) trains = list(sorted(routes_lookup['train'])) subways = list(sorted(routes_lookup['subway'])) light_rails = list(sorted(routes_lookup['light_rail'])) trams = list(sorted(routes_lookup['tram'])) railways = list(sorted(routes_lookup['railway'])) del routes_lookup # if a station is an interchange between mainline rail and subway or # light rail, then give it a "bonus" boost of importance. bonus = 2 if trains and (subways or light_rails) else 1 score = (100 * min(9, bonus * len(trains)) + 10 * min(9, bonus * (len(subways) + len(light_rails))) + min(9, len(trams) + len(railways))) return Transit(score=score, root_relation_id=root_relation_id, trains=trains, subways=subways, light_rails=light_rails, railways=railways, trams=trams) _TAG_NAME_ALTERNATES = ( 'name', 'int_name', 'loc_name', 'nat_name', 'official_name', 'old_name', 'reg_name', 'short_name', 'name_left', 'name_right', 'name:short', ) _ALT_NAME_PREFIX_CANDIDATES = ( 'name:left:', 'name:right:', 'name:', 'alt_name:', 'old_name:' ) # given a dictionary of key-value properties, returns a list of all the keys # which represent names. this is used to assign all the names to a single # layer. this makes sure that when we generate multiple features from a single # database record, only one feature gets named and labelled. def name_keys(props): name_keys = [] for k in props.keys(): is_name_key = k in _TAG_NAME_ALTERNATES if not is_name_key: for prefix in _ALT_NAME_PREFIX_CANDIDATES: if k.startswith(prefix): is_name_key = True break if is_name_key: name_keys.append(k) return name_keys _US_ROUTE_MODIFIERS = set([ 'Business', 'Spur', 'Truck', 'Alternate', 'Bypass', 'Connector', 'Historic', 'Toll', 'Scenic', ]) # properties for a feature (fid, shape, props) in layer `layer_name` at zoom # level `zoom`. also takes an `osm` parameter, which is an object which can # be used to look up nodes, ways and relations and the relationships between # them. def layer_properties(fid, shape, props, layer_name, zoom, osm): layer_props = props.copy() # drop the 'source' tag, if it exists. we override it anyway, and it just # gets confusing having multiple source tags. in the future, we may # replace the whole thing with a separate 'meta' for source. layer_props.pop('source', None) # need to make sure that the name is only applied to one of # the pois, landuse or buildings layers - in that order of # priority. if layer_name in ('pois', 'landuse', 'buildings'): for key in name_keys(layer_props): layer_props.pop(key, None) # urgh, hack! if layer_name == 'water' and shape.geom_type == 'Point': layer_props['label_placement'] = True if shape.geom_type in ('Polygon', 'MultiPolygon'): layer_props['area'] = shape.area if layer_name == 'roads' and \ shape.geom_type in ('LineString', 'MultiLineString') and \ fid >= 0: mz_networks = [] mz_cycling_networks = set() mz_is_bus_route = False for rel_id in osm.relations_using_way(fid): rel = osm.relation(rel_id) if not rel: continue typ, route, network, ref, modifier = [rel.tags.get(k) for k in ( 'type', 'route', 'network', 'ref', 'modifier')] # the `modifier` tag gives extra information about the route, but # we want that information to be part of the `network` property. if network and modifier: modifier = modifier.capitalize() us_network = network.startswith('US:') us_route_modifier = modifier in _US_ROUTE_MODIFIERS # don't want to add the suffix if it's already there. suffix = ':' + modifier needs_suffix = suffix not in network if us_network and us_route_modifier and needs_suffix: network += suffix if route and (network or ref): mz_networks.extend([route, network, ref]) if typ == 'route' and \ route in ('hiking', 'foot', 'bicycle') and \ network in ('icn', 'ncn', 'rcn', 'lcn'): mz_cycling_networks.add(network) if typ == 'route' and route in ('bus', 'trolleybus'): mz_is_bus_route = True mz_cycling_network = None for cn in ('icn', 'ncn', 'rcn', 'lcn'): if layer_props.get(cn) == 'yes' or \ ('%s_ref' % cn) in layer_props or \ cn in mz_cycling_networks: mz_cycling_network = cn break if mz_is_bus_route and \ zoom >= 12 and \ layer_props.get('highway') in BUS_ROADS: layer_props['is_bus_route'] = True layer_props['mz_networks'] = mz_networks if mz_cycling_network: layer_props['mz_cycling_network'] = mz_cycling_network is_poi = layer_name == 'pois' is_railway_station = props.get('railway') == 'station' is_point_or_poly = shape.geom_type in ( 'Point', 'MultiPoint', 'Polygon', 'MultiPolygon') if is_poi and is_railway_station and \ is_point_or_poly: node_id = None way_id = None rel_id = None if shape.geom_type in ('Point', 'MultiPoint'): node_id = fid elif fid >= 0: way_id = fid else: rel_id = -fid transit = mz_calculate_transit_routes_and_score( osm, node_id, way_id, rel_id) layer_props['mz_transit_score'] = transit.score layer_props['mz_transit_root_relation_id'] = ( transit.root_relation_id) layer_props['train_routes'] = transit.trains layer_props['subway_routes'] = transit.subways layer_props['light_rail_routes'] = transit.light_rails layer_props['tram_routes'] = transit.trams return layer_props
tilezen/tilequeue
tilequeue/query/common.py
Python
mit
15,803
require File.expand_path(File.join(File.dirname(__FILE__), '..', 'spec_helper')) module AliasMethodChainSpec # namespacing describe "alias method chain" do module ModifiedAliasMethodChain # From Tammo Freese's patch: # https://rails.lighthouseapp.com/projects/8994/tickets/285-alias_method_chain-limits-extensibility def alias_method_chain(target, feature) punctuation = nil with_method, without_method = "#{target}_with_#{feature}#{punctuation}", "#{target}_without_#{feature}#{punctuation}" method_defined_here = (instance_methods(false) + private_instance_methods(false)).include?(RUBY_VERSION < '1.9' ? target.to_s : target) unless method_defined_here module_eval <<-EOS def #{target}(*args, &block) super end EOS end alias_method without_method, target # alias_method target, with_method target_method_exists = (instance_methods + private_instance_methods).include?(RUBY_VERSION < '1.9' ? with_method : with_method.to_sym) raise NameError unless target_method_exists module_eval <<-EOS def #{target}(*args, &block) self.__send__(:'#{with_method}', *args, &block) end EOS end end module BasicAliasMethodChain def alias_method_chain(target, feature) punctuation = nil with_method, without_method = "#{target}_with_#{feature}#{punctuation}", "#{target}_without_#{feature}#{punctuation}" alias_method without_method, target alias_method target, with_method end end module Bar def bar 'bar' end end module Baz def baz 'baz' end end module BazWithLess def self.included(base) base.alias_method_chain :baz, :less end def baz_with_less baz_without_less + ' less' end end class Foo extend ModifiedAliasMethodChain include Bar def foo_with_more foo_without_more + ' more' end def foo 'foo' end alias_method_chain :foo, :more def bar_with_less bar_without_less + ' less' end alias_method_chain :bar, :less include Baz include BazWithLess end class FooBasic extend BasicAliasMethodChain include Bar def foo_with_more foo_without_more + ' more' end def foo 'foo' end alias_method_chain :foo, :more def bar_with_less bar_without_less + ' less' end alias_method_chain :bar, :less include Baz include BazWithLess end it "test modified alias method chain" do f = Foo.new f.foo.should == 'foo more' f.foo_without_more.should == 'foo' f.foo_with_more.should == 'foo more' f.bar.should == 'bar less' f.bar_without_less.should == 'bar' f.bar_with_less.should == 'bar less' f.baz.should == 'baz less' f.baz_without_less.should == 'baz' f.baz_with_less.should == 'baz less' Bar.class_eval do def bar 'new bar' end end f.bar.should == 'new bar less' f.bar_without_less.should == 'new bar' f.bar_with_less.should == 'new bar less' Foo.class_eval do def baz_with_less 'lesser' end end f.baz_without_less.should == 'baz' f.baz_with_less.should == 'lesser' f.baz.should == 'lesser' end it "test basic alias method chain" do f = FooBasic.new f.foo.should == 'foo more' f.foo_without_more.should == 'foo' f.foo_with_more.should == 'foo more' f.bar.should == 'bar less' f.bar_without_less.should == 'bar' f.bar_with_less.should == 'bar less' Bar.class_eval do def bar 'new bar' end end # no change f.bar.should == 'bar less' f.bar_without_less.should == 'bar' f.bar_with_less.should == 'bar less' Foo.class_eval do def baz_with_less raise end end # no error f.baz_without_less.should == 'baz' f.baz_with_less.should == 'baz less' f.baz.should == 'baz less' end end end
jpartlow/graph_mediator
spec/investigation/alias_method_chain_spec.rb
Ruby
mit
4,078
'use strict'; $(function() { $('a.page-scroll').bind('click', function(event) { var $anchor = $(this); $('html, body').stop().animate({ scrollTop: $($anchor.attr('href')).offset().top }, 1750, 'easeInOutSine'); event.preventDefault(); }); });
mskalandunas/parcel
app/js/lib/smooth_scroll.js
JavaScript
mit
270
// @flow import React, { Component } from 'react' import Carousel, { Modal, ModalGateway } from '../../../../src/components' import { videos } from './data' import { Poster, Posters } from './Poster' import View from './View' import { Code, Heading } from '../../components' type Props = {} type State = { currentModal: number | null } export default class AlternativeMedia extends Component<Props, State> { state = { currentModal: null } toggleModal = (index: number | null = null) => { this.setState({ currentModal: index }) } render() { const { currentModal } = this.state return ( <div> <Heading source="/CustomComponents/AlternativeMedia/index.js">Alternative Media</Heading> <p> In this example the data passed to <Code>views</Code> contains source and poster information. The <Code>&lt;View /&gt;</Code> component has been replaced to render an HTML5 video tag and custom controls. </p> <p> Videos courtesy of{' '} <a href="https://peach.blender.org/" target="_blank"> "Big Buck Bunny" </a>{' '} and{' '} <a href="https://durian.blender.org/" target="_blank"> "Sintel" </a> </p> <Posters> {videos.map((vid, idx) => ( <Poster key={idx} data={vid} onClick={() => this.toggleModal(idx)} /> ))} </Posters> <ModalGateway> {Number.isInteger(currentModal) ? ( <Modal allowFullscreen={false} closeOnBackdropClick={false} onClose={this.toggleModal}> <Carousel currentIndex={currentModal} components={{ Footer: null, View }} views={videos} /> </Modal> ) : null} </ModalGateway> </div> ) } }
jossmac/react-images
docs/pages/CustomComponents/AlternativeMedia/index.js
JavaScript
mit
1,796
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package net.maizegenetics.util; import net.maizegenetics.dna.snp.GenotypeTable; /** * * @author qs24 */ public class VCFUtil { // variables for calculating OS and PL for VCF, might not be in the correct class private static double error; private static double v1; private static double v2; private static double v3; private static int[][][] myGenoScoreMap; public static final int VCF_DEFAULT_MAX_NUM_ALLELES = 3; static { error = 0.001; //TODO this seems low, is this the standard v1 = Math.log10(1.0 - error * 3.0 /4.0); v2 = Math.log10(error/4); v3 = Math.log10(0.5 - (error/4.0)); myGenoScoreMap = new int[128][128][]; for (int i = 0; i < 128; i++) { for (int j = 0; j < 128; j++) { myGenoScoreMap[i][j]= calcScore(i, j); } } } private VCFUtil () { } public static int[] getScore(int i, int j) { if(i>127 || j>127) return calcScore(i,j); return myGenoScoreMap[i][j]; } // Calculate QS and PL for VCF might not be in the correct class private static int[] calcScore (int a, int b) { int[] results= new int[4]; int n = a + b; int m = a; if (b > m) { m = b; } double fact = 0; if (n > m) { for (int i = n; i > m; i--) { fact += Math.log10(i); } for (int i = 1; i <= (n - m); i++){ fact -= Math.log10(i); } } double aad = Math.pow(10, fact + (double)a * v1 + (double)b * v2); double abd = Math.pow(10, fact + (double)n * v3); double bbd = Math.pow(10, fact + (double)b * v1 + (double)a * v2); double md = aad; if (md < abd) { md = abd; } if (md < bbd) { md = bbd; } int gq = 0; if ((aad + abd + bbd) > 0) { gq = (int)(md / (aad + abd + bbd) * 100); } int aa =(int) (-10 * (fact + (double)a * v1 + (double)b * v2)); int ab =(int) (-10 * (fact + (double)n * v3)); int bb =(int) (-10 * (fact + (double)b * v1 + (double)a * v2)); m = aa; if (m > ab) { m = ab; } if (m>bb) { m = bb; } aa -= m; ab -= m; bb -= m; results[0] = aa > 255 ? 255 : aa; results[1] = ab > 255 ? 255 : ab; results[2] = bb > 255 ? 255 : bb; results[3] = gq; return results; } public static byte resolveVCFGeno(byte[] alleles, int[][] allelesInTaxa, int tx) { int[] alleleDepth = new int[allelesInTaxa.length]; for (int i=0; i<allelesInTaxa.length; i++) { alleleDepth[i] = allelesInTaxa[i][tx]; } return resolveVCFGeno(alleles, alleleDepth); } public static byte resolveVCFGeno(byte[] alleles, int[] alleleDepth) { int depth = 0; for (int i = 0; i < alleleDepth.length; i++) { depth += alleleDepth[i]; } if (depth == 0) { return (byte)((GenotypeTable.UNKNOWN_ALLELE << 4) | GenotypeTable.UNKNOWN_ALLELE); } int max = 0; byte maxAllele = GenotypeTable.UNKNOWN_ALLELE; int nextMax = 0; byte nextMaxAllele = GenotypeTable.UNKNOWN_ALLELE; for (int i = 0; i < alleles.length; i++) { if (alleleDepth[i] > max) { nextMax = max; nextMaxAllele = maxAllele; max = alleleDepth[i]; maxAllele = alleles[i]; } else if (alleleDepth[i] > nextMax) { nextMax = alleleDepth[i]; nextMaxAllele = alleles[i]; } } if (alleles.length == 1) { return (byte)((alleles[0] << 4) | alleles[0]); } else { max = (max > 127) ? 127 : max; nextMax = (nextMax > 127) ? 127 : nextMax; int[] scores = getScore(max, nextMax); if ((scores[1] <= scores[0]) && (scores[1] <= scores[2])) { return (byte)((maxAllele << 4) | nextMaxAllele); } else if ((scores[0] <= scores[1]) && (scores[0] <= scores[2])) { return (byte)((maxAllele << 4) | maxAllele); } else { return (byte)((nextMaxAllele << 4) | nextMaxAllele); } } } }
yzhnasa/TASSEL-iRods
src/net/maizegenetics/util/VCFUtil.java
Java
mit
4,777