repo_name
stringlengths
4
116
path
stringlengths
4
379
size
stringlengths
1
7
content
stringlengths
3
1.05M
license
stringclasses
15 values
abscondite/quickblox_api
lib/quickblox_api.rb
443
require 'hmac-sha1' require 'faraday' require 'quickblox_api/version' require 'quickblox_api/encoder' require 'quickblox_api/helpers' require 'quickblox_api/config' require 'quickblox_api/base_client' require 'quickblox_api/client' require 'quickblox_api/user_client' module QuickbloxApi def self.client(opts) QuickbloxApi::Client.new(secrets: opts) end def self.user_client(opts) QuickbloxApi::UserClient.new(opts) end end
mit
sunny-g/node-ddp-client
index.js
10251
"use strict"; var _ = require('underscore'); var minimongo = require('minimongo-cache'); var EventEmitter = require('events').EventEmitter; var EJSON = require("ejson"); class DDPClient extends EventEmitter{ constructor(opts) { super(); var self = this; opts = opts || {}; // backwards compatibility if ("use_ssl" in opts) opts.ssl = opts.use_ssl; if ("auto_reconnect" in opts) opts.autoReconnect = opts.auto_reconnect; if ("auto_reconnect_timer" in opts) opts.autoReconnectTimer = opts.auto_reconnect_timer; if ("maintain_collections" in opts) opts.maintainCollections = opts.maintain_collections; if ("ddp_version" in opts) opts.ddpVersion = opts.ddp_version; // default arguments self.host = opts.host || "localhost"; self.port = opts.port || 3000; self.path = opts.path; self.ssl = opts.ssl || self.port === 443; self.tlsOpts = opts.tlsOpts || {}; self.autoReconnect = ("autoReconnect" in opts) ? opts.autoReconnect : true; self.autoReconnectTimer = ("autoReconnectTimer" in opts) ? opts.autoReconnectTimer : 500; self.maintainCollections = ("maintainCollections" in opts) ? opts.maintainCollections : true; self.url = opts.url; self.socketConstructor = opts.socketContructor || WebSocket; // support multiple ddp versions self.ddpVersion = ("ddpVersion" in opts) ? opts.ddpVersion : "1"; self.supportedDdpVersions = ["1", "pre2", "pre1"]; // Expose EJSON object, so client can use EJSON.addType(...) self.EJSON = EJSON; // very very simple collections (name -> [{id -> document}]) if (self.maintainCollections) { self.collections = new minimongo(); } // internal stuff to track callbacks self._isConnecting = false; self._isReconnecting = false; self._nextId = 0; self._callbacks = {}; self._updatedCallbacks = {}; self._pendingMethods = {}; } _prepareHandlers() { var self = this; self.socket.onopen = function() { // just go ahead and open the connection on connect self._send({ msg : "connect", version : self.ddpVersion, support : self.supportedDdpVersions }); }; self.socket.onerror = function(error) { // error received before connection was established if (self._isConnecting) { self.emit("failed", error.message); } self.emit("socket-error", error); }; self.socket.onclose = function(event) { self.emit("socket-close", event.code, event.reason); self._endPendingMethodCalls(); self._recoverNetworkError(); }; self.socket.onmessage = function(event) { self._message(event.data); self.emit("message", event.data); }; } _clearReconnectTimeout() { var self = this; if (self.reconnectTimeout) { clearTimeout(self.reconnectTimeout); self.reconnectTimeout = null; } } _recoverNetworkError() { var self = this; if (self.autoReconnect && ! self._connectionFailed && ! self._isClosing) { self._clearReconnectTimeout(); self.reconnectTimeout = setTimeout(function() { self.connect(); }, self.autoReconnectTimer); self._isReconnecting = true; } } /////////////////////////////////////////////////////////////////////////// // RAW, low level functions _send(data) { var self = this; self.socket.send( EJSON.stringify(data) ); } // handle a message from the server _message(data) { var self = this; data = EJSON.parse(data); // TODO: 'addedBefore' -- not yet implemented in Meteor // TODO: 'movedBefore' -- not yet implemented in Meteor if (!data.msg) { return; } else if (data.msg === "failed") { if (self.supportedDdpVersions.indexOf(data.version) !== -1) { self.ddpVersion = data.version; self.connect(); } else { self.autoReconnect = false; self.emit("failed", "Cannot negotiate DDP version"); } } else if (data.msg === "connected") { self.session = data.session; self.emit("connected"); // method result } else if (data.msg === "result") { var cb = self._callbacks[data.id]; if (cb) { cb(data.error, data.result); delete self._callbacks[data.id]; } // method updated } else if (data.msg === "updated") { _.each(data.methods, function (method) { var cb = self._updatedCallbacks[method]; if (cb) { cb(); delete self._updatedCallbacks[method]; } }); // missing subscription } else if (data.msg === "nosub") { var cb = self._callbacks[data.id]; if (cb) { cb(data.error); delete self._callbacks[data.id]; } // add document to collection } else if (data.msg === "added") { if (self.maintainCollections && data.collection) { var name = data.collection, id = data.id; var item = { "_id": id }; if (data.fields) { _.each(data.fields, function(value, key) { item[key] = value; }) } if (! self.collections[name]) { self.collections.addCollection(name); } self.collections[name].upsert(item); } // remove document from collection } else if (data.msg === "removed") { if (self.maintainCollections && data.collection) { self.collections[name].remove({"_id": id}); } // change document in collection } else if (data.msg === "changed") { if (self.maintainCollections && data.collection) { var name = data.collection, id = data.id; var item = { "_id": id }; if (data.fields) { _.each(data.fields, function(value, key) { item[key] = value; }); } self.collections[name].upsert(item); } // subscriptions ready } else if (data.msg === "ready") { _.each(data.subs, function(id) { var cb = self._callbacks[id]; if (cb) { cb(); delete self._callbacks[id]; } }); // minimal heartbeat response for ddp pre2 } else if (data.msg === "ping") { self._send( _.has(data, "id") ? { msg : "pong", id : data.id } : { msg : "pong" } ); } } _getNextId() { var self = this; return (self._nextId += 1).toString(); } ////////////////////////////////////////////////////////////////////////// // USER functions -- use these to control the client /* open the connection to the server * * connected(): Called when the 'connected' message is received * If autoReconnect is true (default), the callback will be * called each time the connection is opened. */ connect(connected) { var self = this; self._isConnecting = true; self._connectionFailed = false; self._isClosing = false; if (connected) { self.addListener("connected", function() { self._clearReconnectTimeout(); connected(undefined, self._isReconnecting); self._isConnecting = false; self._isReconnecting = false; }); self.addListener("failed", function(error) { self._isConnecting = false; self._connectionFailed = true; connected(error, self._isReconnecting); }); } var url = self._buildWsUrl(); self._makeWebSocketConnection(url); } _endPendingMethodCalls() { var self = this; var ids = _.keys(self._pendingMethods); self._pendingMethods = {}; ids.forEach(function (id) { if (self._callbacks[id]) { self._callbacks[id](new Error("DDPClient: Disconnected from DDP server")); delete self._callbacks[id]; } if (self._updatedCallbacks[id]) { self._updatedCallbacks[id](); delete self._updatedCallbacks[id]; } }); } _buildWsUrl(path) { var self = this; var url; path = path || self.path || "websocket"; var protocol = self.ssl ? "wss://" : "ws://"; if (self.url) { url = self.url; } else { url = protocol + self.host + ":" + self.port; url += (path.indexOf("/") === 0)? path : "/" + path; } return url; } _makeWebSocketConnection(url) { var self = this; self.socket = new self.socketConstructor(url); self._prepareHandlers(); } close() { var self = this; self._isClosing = true; self.socket.close(); self.removeAllListeners("connected"); self.removeAllListeners("failed"); } // call a method on the server, // // callback = function(err, result) call(name, params, callback, updatedCallback) { var self = this; var id = self._getNextId(); self._callbacks[id] = function () { delete self._pendingMethods[id]; if (callback) { callback.apply(this, arguments); } }; self._updatedCallbacks[id] = function () { delete self._pendingMethods[id]; if (updatedCallback) { updatedCallback.apply(this, arguments); } }; self._pendingMethods[id] = true; self._send({ msg : "method", id : id, method : name, params : params }); } callWithRandomSeed(name, params, randomSeed, callback, updatedCallback) { var self = this; var id = self._getNextId(); if (callback) { self._callbacks[id] = callback; } if (updatedCallback) { self._updatedCallbacks[id] = updatedCallback; } self._send({ msg : "method", id : id, method : name, randomSeed : randomSeed, params : params }); } // open a subscription on the server, callback should handle on ready and nosub subscribe(name, params, callback) { var self = this; var id = self._getNextId(); if (callback) { self._callbacks[id] = callback; } self._send({ msg : "sub", id : id, name : name, params : params }); return id; } unsubscribe(id) { var self = this; self._send({ msg : "unsub", id : id }); } } module.exports = DDPClient;
mit
MarcLoupias/RandomDNAselector
src/main/java/org/dnaselector/fasta/FastaLineReader.java
2112
package org.dnaselector.fasta; public class FastaLineReader { public static FastaLine readLine(String fastaFilePath, Integer lineNumber, String lineContent) throws FastaLineReaderException { if(lineContent == null) { throw new FastaLineReaderException(fastaFilePath, lineNumber, "Line content is null"); } if(lineContent.isEmpty()) { throw new FastaLineReaderException(fastaFilePath, lineNumber, "Line content is empty"); } if(!lineContent.startsWith(">")) { throw new FastaLineReaderException( fastaFilePath, lineNumber, "Line first char is not > but " + lineContent.substring(0, 1) ); } String[] lineStrings = lineContent.split(" "); if(lineStrings == null) { throw new FastaLineReaderException( fastaFilePath, lineNumber, "Line split result with space separator is null" ); } if(lineStrings.length != 5) { throw new FastaLineReaderException( fastaFilePath, lineNumber, "Column number should be 5 instead of " + lineStrings.length ); } String[] subLineStrings = lineStrings[0].split("_"); if(subLineStrings == null) { throw new FastaLineReaderException( fastaFilePath, lineNumber, "Sub-line split result with underscore separator is null" ); } if(subLineStrings.length != 2) { throw new FastaLineReaderException( fastaFilePath, lineNumber, "Sub-line split length should be 2 instead of " + subLineStrings.length ); } String country = subLineStrings[0].substring(1); if(country == null) { throw new FastaLineReaderException(fastaFilePath, lineNumber, "Country name is null"); } if(country.isEmpty()) { throw new FastaLineReaderException(fastaFilePath, lineNumber, "Country name is empty"); } return new FastaLine(lineContent, country); } }
mit
uniquetree/jquery-tablelock
dist/scripts/jquery.tablelock.js
3257
/** * jquery-tablelock - A jquery plugin to lock the table's row or column * @author 郑树聪 * @version 1.0.0 * @link https://github.com/uniquetree/jquery-tablelock#readme * @license MIT */ ;(function($) { // 插件全局变量,此处全局this指向当前调用此插件的DOM的jquery对象, var thisTable; function _TableLock(options){ this.options = $.extend({}, $.fn.TableLock.defaults, options); } _TableLock.prototype.load = function(){ thisTable.wrap('<div class="lock-table-box clearfix"></div>'); $('.lock-table-box').css({ 'width': this.options.width, 'height': this.options.height }); this.lockRow(); this.lockCol(); this.addEvents(); }; // 锁定行 _TableLock.prototype.lockRow = function(){ var tr; // 锁定行tr,tr包括thead和tbody下的所有tr for(var row = 0; row < this.options.lockRowNum; row++) { tr = thisTable.find('tr:eq(' + row + ')'); tr.find('th, td').addClass('lock-row').css('backgroundColor', this.options.backgroundColor); // 锁定行列交叉处,若锁定的列数也大于0,则行列交叉处进行再次锁定 for(var col = 0; col < this.options.lockColNum; col++ ){ if(tr){ tr.find('th:eq( ' + col + ' ), td:eq(' + col + ')').addClass('lock-col lock-cross'); } } } }; // 锁定列 _TableLock.prototype.lockCol = function(){ var that = this; // 遍历所有行tr,tr下既包括th也包括td thisTable.find('tr').each(function(index, val){ // 锁定列 for(var col = 0; col < that.options.lockColNum; col++) { $(this).find('th:eq( ' + col + ' ), td:eq(' + col + ')').addClass('lock-col') .css('backgroundColor', that.options.backgroundColor); } }); }; // 添加事件 _TableLock.prototype.addEvents = function(){ $('.lock-table-box').scroll(function(){ $('.lock-row').css('top', $(this).scrollTop()); $('.lock-col').css('left', $(this).scrollLeft()); }); }; var methods = { init: function (options) { return this.each(function(){ var TableLock = new _TableLock(options); TableLock.load(); }) } }; $.fn.TableLock = function(method) { thisTable = this; // 方法调用 if (methods[method]) { return methods[method].apply(this, Array.prototype.slice.call(arguments, 1)); } else if (typeof method === 'object' || !method) { return methods['init'].apply(this, arguments); } else { $.error('Method' + method + 'does not exist on jQuery.TableLock'); } }; //定义默认参数 $.fn.TableLock.defaults = { lockRowNum:1, //锁定的行数,默认1行 lockColNum:1, //锁定的列数,默认1列 width: '100%', //表格宽度,默认为400px height: '100%', //表格高度,默认为200px backgroundColor: '#fff' }; }(jQuery));
mit
Azure/azure-sdk-for-java
sdk/avs/azure-resourcemanager-avs/src/samples/java/com/azure/resourcemanager/avs/generated/ScriptCmdletsGetSamples.java
868
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. // Code generated by Microsoft (R) AutoRest Code Generator. package com.azure.resourcemanager.avs.generated; import com.azure.core.util.Context; /** Samples for ScriptCmdlets Get. */ public final class ScriptCmdletsGetSamples { /* * x-ms-original-file: specification/vmware/resource-manager/Microsoft.AVS/stable/2021-12-01/examples/ScriptCmdlets_Get.json */ /** * Sample code: ScriptCmdlets_Get. * * @param manager Entry point to AvsManager. */ public static void scriptCmdletsGet(com.azure.resourcemanager.avs.AvsManager manager) { manager .scriptCmdlets() .getWithResponse( "group1", "{privateCloudName}", "{scriptPackageName}", "New-ExternalSsoDomain", Context.NONE); } }
mit
peer23peer/pymech
pymech/fluid/Pipe.py
4562
import math import pymech.materials as mat from pymech.units.SI import * from pymech.fluid.Component import Component from pymech.fluid.Point import Point from pymech.fluid.Core import flowrate, Regime, Reynolds, Darcy, flowregime, HagenPoiseuille, friction, fluidspeed, \ hydrostatic_headloss, I_m, hl_to_dp from pymech.fluid.Bingham import Reynolds_B class Pipe(Component): L = 0. * ureg['m'] # Length of pipe _D_out = 0. * ureg['m'] # Diameter outer _wt = 0. * ureg['m'] # wall thickness of pipe material = mat.Steel() # Material of pipe Standard = "ASME B36.10" # Standard norm used From = Point() To = Point() fluid = mat.Fluid() def __init__(self, ID=None, L=None, D_out=None, wt=None, material=None, fluid=None): Component.__init__(self, ID) if L is not None and D_out is not None and wt is not None: self.L = L self.D_out = D_out self.wt = wt if material is not None: self.set_material(material=material) if fluid is not None: self.fluid = fluid else: self.fluid = mat.Fluid() def __repr__(self): return Component.__repr__(self) + repr([self.L, self.D_out, self.wt, self.hl]) def Pipe_to_builtin(u): return ( Component.Component_to_builtin(u), u.L, u._D_out, u._wt, u.material, u.Standard, u.From, u.To, u.fluid) def Pipe_from_builtin(c): pipe = Pipe() pipe.ID = c[0][0] pipe._P = c[0][1] pipe._A = c[0][2] pipe._Q = c[0][3] pipe._v = c[0][4] pipe.L = c[1] pipe._D_out = c[2] pipe._wt = c[3] pipe.material = c[4] pipe.Standard = c[5] pipe.From = c[6] pipe.To = c[7] pipe.fluid = c[8] return pipe def load(self, filename, ID=None, L=None, fluid=None, From=None, To=None): data = serialize_load(filename, fmt='yaml') if ID is None: self.ID = data.ID else: self.ID = ID self._P = data._P self._A = data._A self._Q = data._Q self._v = data._v if L is None: self.L = data.L else: self.L = L self._D_out = data._D_out self._wt = data._wt self.material = data.material self.Standard = data.Standard if fluid is None: self.fluid = data.fluid else: self.fluid = fluid if From is None and To is None: self.From = data.From self.To = data.To else: self.From = From self.To = To def set_route(self, From, To): self.From = From self.To = To def set_material(self, material=None): self.material = material @property def Re(self): if issubclass(type(self.fluid), mat.BinghamFluid): return Reynolds_B(fluid=self.fluid, pipe=self) return Reynolds(v=abs(self.v), D=self.D_in, fluid=self.fluid) def headloss(self, dP=False, pretty=False): hl = 0. # Calc energyloss due to friction f = friction(Re=self.Re, D=self.D_in, eps=self.material.epsilon) hl = Darcy(f=f, L=self.L, D=self.D_in, v=abs(self.v), fluid=self.fluid, dP=dP, pretty=pretty) # Calc energyloss due to height hl += hydrostatic_headloss(z_from=self.From.Height, z_to=self.To.Height, fluid=self.fluid, dP=dP, pretty=pretty) # set pressure at point 1 if dP: self.P1 = self.P0 - hl else: self.P1 = self.P0 - hl_to_dp(hl, fluid=self.fluid, pretty=pretty) return hl @property def D_out(self): return self._D_out @D_out.setter def D_out(self, value): self._D_out = value.to('m') @property def r_out(self): return self.D_out / 2 @r_out.setter def r_out(self, value): self.D_out = value * 2 @property def wt(self): return self._wt @wt.setter def wt(self, value): self._wt = value.to('m') @property def r_in(self): return self.r_out - self.wt @r_in.setter def r_in(self, value): self.wt = self.r_out - value @property def D_in(self): return self.D_out - 2 * self.wt @D_in.setter def D_in(self, value): self.wt = (self.D_out - value) / 2 @property def LD(self): return self.L / self.D_in @property def A(self): return (math.pi / 4) * self.D_in ** 2
mit
luthraG/node-validate
test/isTitleCase.js
3102
var isTitleCase = require('../validate.js').isTitleCase, expect = require('chai').expect; describe('isTitleCase API Tests', function () { describe('Valid tests for isTitleCase API', function () { it('Gaurav is a valid title case value', function () { expect(isTitleCase('Gaurav')).to.be.true; }); it('Gaurav Luthra is a valid title case value', function () { expect(isTitleCase('Gaurav Luthra')).to.be.true; }); it('Gaurav This Is Really Awesome is a valid title case value', function () { expect(isTitleCase('Gaurav This Is Really Awesome')).to.be.true; }); it('Luthra is a valid title case value', function () { expect(isTitleCase('Luthra')).to.be.true; }); it('gaurav is not a title case value', function () { expect(isTitleCase('gaurav')).to.be.false; }); it('gauraV is not a title case value', function () { expect(isTitleCase('gauraV')).to.be.false; }); it('A is a valid title case value', function () { expect(isTitleCase('A')).to.be.true; }); it('### is a valid title case value', function () { expect(isTitleCase('###')).to.be.true; }); it('string value 12 is a valid title case value', function () { expect(isTitleCase('12')).to.be.true; }); it('empty string is a valid title case value', function () { expect(isTitleCase('')).to.be.true; }); it('no parameter to method is not a valid title case value', function () { expect(isTitleCase()).to.be.false; }); }); describe('Invalid tests for isTitleCase API', function () { it('Date.now() is not a valid title case value', function () { expect(isTitleCase(Date.now())).to.be.false; }); it('Date.UTC() is not a valid title case value', function () { expect(isTitleCase(Date.UTC())).to.be.false; }); it('Boolean true is not a valid title case value', function () { expect(isTitleCase(true)).to.be.false; }); it('undefined is not a valid title case value', function () { expect(isTitleCase(undefined)).to.be.false; }); it('null is a valid title case value', function () { expect(isTitleCase(null)).to.be.false; }); it('new Number(5) does not return a valid title case value', function () { expect(isTitleCase(new Number(5))).to.be.false; }); it('new Array("hellow") does not return a valid title case value', function () { expect(isTitleCase(new Array('hellow'))).to.be.false; }); it('["hello", "world", 1, 2, 3] is not a valid title case value value', function () { expect(isTitleCase(["hello", "world", 1, 2, 3])).to.be.false; }); it('Number 12 is not a valid title case value', function () { expect(isTitleCase(12)).to.be.false; }); }); });
mit
stierma1/pouch-pid
tests/lib/initialize.spec.js
3223
var chai = require("chai"); var expect = chai.expect; var System = require("pid-system"); var path = require("path"); var testModulePath = path.join(process.cwd(), "./lib/initialize.js"); var mockMessages = path.join(process.cwd(), "tests", "mock-messages", "./lib/initialize.js"); var echoPid = path.join(process.cwd(), "./tests/echo-pid.js"); function mockClosure (cleanUpPids){ return function (options){ return System.spawn(testModulePath, "main", options).then(function(pid){ cleanUpPids.push(pid); return pid; }); } } function echoPidClosure (cleanUpPids){ return async function (){ var pid = await System.spawn(echoPid, "main").then(function(pid){ cleanUpPids.push(pid); return pid; }) var res_ var prom = new Promise(function(res, rej){ res_ = res; }) System.send(pid,[res_]); return {pid:pid, prom:prom}; } } describe("#initialize", function(){ var cleanUpPids = []; var mock = mockClosure(cleanUpPids); var echoPid = echoPidClosure(cleanUpPids); beforeEach(function(){ cleanUpPids.map(function(pid){ System.exit(pid); }); cleanUpPids = []; }); it("should add a pouchModules key to config", async function(){ var c = System.getConfig(); c.pouchEraseEnabled = true; System.setConfig(c); var pid = await mock(); expect(System.getConfig()).to.have.property("pouchModules"); }) it("should add a pouchModules.ERASE_HANDLER_PATH key to config if eraseEnabled is set", async function(){ //it was set in previous test var pid = await mock(); expect(System.getConfig().pouchModules).to.have.property("ERASE_HANDLER_PATH"); }) it("should return dbPid", async function(){ var echo = await echoPid(); var pid = await mock(); System.send(pid, [{name:"stuff"}, {db:require("memdown")}, echo.pid]); var message = await echo.prom; expect(message[0]).to.equal("OK"); expect(message[1]).to.not.be.undefined; expect(message[2]).to.be.null; cleanUpPids.push(message[1]); //expect(System.getConfig()).to.have.property("pouchModules"); }) it("should return when synced dbPid and syncHandler", async function(){ var echo = await echoPid(); var pid = await mock(); System.send(pid, [{name:"stuff", type:"synced", sync:{remote:{url:"http://www.fake.com"}}}, {db:require("memdown")}, echo.pid]); var message = await echo.prom; expect(message[0]).to.equal("OK"); expect(message[1]).to.not.be.undefined; expect(message[2]).to.not.be.null; message[2].cancel(); cleanUpPids.push(message[1]); //expect(System.getConfig()).to.have.property("pouchModules"); }) it("should return when fully-synced dbPid and syncHandler", async function(){ var echo = await echoPid(); var pid = await mock(); System.send(pid, [{name:"stuff", type:"fully-synced", sync:{remote:{url:"http://www.fake.com"}}}, {db:require("memdown")}, echo.pid]); var message = await echo.prom; expect(message[0]).to.equal("OK"); expect(message[1]).to.not.be.undefined; expect(message[2]).to.not.be.null; cleanUpPids.push(message[1]); //expect(System.getConfig()).to.have.property("pouchModules"); }) });
mit
nivinjoseph/n-web
dist/view.d.ts
129
import "reflect-metadata"; export declare const viewSymbol: unique symbol; export declare function view(file: string): Function;
mit
hovsepm/azure-libraries-for-net
src/ResourceManagement/Network/Domain/InterfaceImpl/NetworkSecurityGroupImpl.cs
5112
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. See License.txt in the project root for license information. namespace Microsoft.Azure.Management.Network.Fluent { using System.Threading; using System.Threading.Tasks; using Microsoft.Azure.Management.Network.Fluent.NetworkSecurityGroup.Definition; using Microsoft.Azure.Management.Network.Fluent.NetworkSecurityGroup.Update; using Microsoft.Azure.Management.Network.Fluent.NetworkSecurityRule.Definition; using Microsoft.Azure.Management.Network.Fluent.NetworkSecurityRule.Update; using Microsoft.Azure.Management.Network.Fluent.NetworkSecurityRule.UpdateDefinition; using Microsoft.Azure.Management.Network.Fluent.Models; using Microsoft.Azure.Management.ResourceManager.Fluent.Core; using Microsoft.Azure.Management.ResourceManager.Fluent.Core.ResourceActions; using System.Collections.Generic; internal partial class NetworkSecurityGroupImpl { /// <summary> /// Refreshes the resource to sync with Azure. /// </summary> /// <return>The Observable to refreshed resource.</return> async Task<Microsoft.Azure.Management.Network.Fluent.INetworkSecurityGroup> Microsoft.Azure.Management.ResourceManager.Fluent.Core.ResourceActions.IRefreshable<Microsoft.Azure.Management.Network.Fluent.INetworkSecurityGroup>.RefreshAsync(CancellationToken cancellationToken) { return await this.RefreshAsync(cancellationToken); } /// <summary> /// Gets default security rules associated with this network security group, indexed by their name. /// </summary> System.Collections.Generic.IReadOnlyDictionary<string, Microsoft.Azure.Management.Network.Fluent.INetworkSecurityRule> Microsoft.Azure.Management.Network.Fluent.INetworkSecurityGroup.DefaultSecurityRules { get { return this.DefaultSecurityRules(); } } /// <summary> /// Gets security rules associated with this network security group, indexed by their names. /// </summary> System.Collections.Generic.IReadOnlyDictionary<string, Microsoft.Azure.Management.Network.Fluent.INetworkSecurityRule> Microsoft.Azure.Management.Network.Fluent.INetworkSecurityGroup.SecurityRules { get { return this.SecurityRules(); } } /// <summary> /// Gets the IDs of the network interfaces associated with this network security group. /// </summary> System.Collections.Generic.ISet<string> Microsoft.Azure.Management.Network.Fluent.INetworkSecurityGroup.NetworkInterfaceIds { get { return this.NetworkInterfaceIds(); } } /// <summary> /// Starts the definition of a new security rule. /// </summary> /// <param name="name">The name for the new security rule.</param> /// <return>The first stage of the security rule definition.</return> NetworkSecurityRule.Definition.IBlank<NetworkSecurityGroup.Definition.IWithCreate> NetworkSecurityGroup.Definition.IWithRule.DefineRule(string name) { return this.DefineRule(name); } /// <summary> /// Begins the definition of a new security rule to be added to this network security group. /// </summary> /// <param name="name">The name of the new security rule.</param> /// <return>The first stage of the new security rule definition.</return> NetworkSecurityRule.UpdateDefinition.IBlank<NetworkSecurityGroup.Update.IUpdate> NetworkSecurityGroup.Update.IWithRule.DefineRule(string name) { return this.DefineRule(name); } /// <summary> /// Removes an existing security rule. /// </summary> /// <param name="name">The name of the security rule to remove.</param> /// <return>The next stage of the network security group description.</return> NetworkSecurityGroup.Update.IUpdate NetworkSecurityGroup.Update.IWithRule.WithoutRule(string name) { return this.WithoutRule(name); } /// <summary> /// Begins the description of an update of an existing security rule of this network security group. /// </summary> /// <param name="name">The name of an existing security rule.</param> /// <return>The first stage of the security rule update description.</return> NetworkSecurityRule.Update.IUpdate NetworkSecurityGroup.Update.IWithRule.UpdateRule(string name) { return this.UpdateRule(name); } /// <return>List of subnets associated with this resource.</return> System.Collections.Generic.IReadOnlyList<Microsoft.Azure.Management.Network.Fluent.ISubnet> Microsoft.Azure.Management.Network.Fluent.IHasAssociatedSubnets.ListAssociatedSubnets() { return this.ListAssociatedSubnets(); } } }
mit
wmira/react-icons-kit
src/fa/rupee.js
480
export const rupee = {"viewBox":"0 0 898 1792","children":[{"name":"path","attribs":{"d":"M898 470v102q0 14-9 23t-23 9h-168q-23 144-129 234t-276 110q167 178 459 536 14 16 4 34-8 18-29 18h-195q-16 0-25-12-306-367-498-571-9-9-9-22v-127q0-13 9.5-22.5t22.5-9.5h112q132 0 212.5-43t102.5-125h-427q-14 0-23-9t-9-23v-102q0-14 9-23t23-9h413q-57-113-268-113h-145q-13 0-22.5-9.5t-9.5-22.5v-133q0-14 9-23t23-9h832q14 0 23 9t9 23v102q0 14-9 23t-23 9h-233q47 61 64 144h171q14 0 23 9t9 23z"}}]};
mit
bing-ads-sdk/BingAds-Java-SDK
proxies/com/microsoft/bingads/v12/campaignmanagement/Adapter9.java
635
package com.microsoft.bingads.v12.campaignmanagement; import java.util.Collection; import javax.xml.bind.annotation.adapters.XmlAdapter; public class Adapter9 extends XmlAdapter<String, Collection<MediaEnabledEntityFilter>> { public Collection<MediaEnabledEntityFilter> unmarshal(String value) { return (com.microsoft.bingads.v12.campaignmanagement.MediaEnabledEntityFilterConverter.convertToList(value)); } public String marshal(Collection<MediaEnabledEntityFilter> value) { return (com.microsoft.bingads.v12.campaignmanagement.MediaEnabledEntityFilterConverter.convertToString(value)); } }
mit
skank/skankydev
vendor/skank/SkankyDev/Utilities/Traits/StringFacility.php
758
<?php /** * Copyright (c) 2015 SCHENCK Simon * * Licensed under The MIT License * For full copyright and license information, please see the LICENSE.txt * Redistributions of files must retain the above copyright notice. * * @license http://www.opensource.org/licenses/mit-license.php MIT License * @copyright Copyright (c) SCHENCK Simon * */ namespace SkankyDev\Utilities\Traits; trait StringFacility { public function toDash($string){ $string = preg_replace('/[A-Z]/',"-$0",$string); $string = strtolower($string); return trim($string,' -'); } public function toCap($string){ $string = str_replace('-', ' ', $string); $string = ucwords($string); $string = str_replace(' ', '', $string); return trim($string); } }
mit
sheilanasimiyu/ADTPro
application/helpers/my_api_helper.php
411
<?php //video 009 function remove_unknown_fields($raw_data, $expected_fields) { $new_data=array(); //consists of rows removed from the $raw_data array if they were not found in the $expected_fields array. foreach($raw_data as $field_name=>$field_value) { if($field_value!="" && in_array($field_name,array_values($expected_fields))) { $new_data[$field_name]=$field_value; } } return $new_data; } ?>
mit
cenkalti/kuyruk
example/tasks.py
100
from kuyruk import Kuyruk kuyruk = Kuyruk() @kuyruk.task() def echo(message): print(message)
mit
Alerion/shopping-helper
src/templates/utils/forms.py
711
from django.forms.formsets import BaseFormSet from django.utils.encoding import force_unicode class AjaxForm(object): def get_form_errors(self, form): output = {} for name, value in form.errors.items(): if form.prefix: key = '%s-%s' % (form.prefix, name) else: key = name output[key] = '/n'.join([force_unicode(i) for i in value]) return output def get_errors(self): if isinstance(self, BaseFormSet): errors = {} for form in self: errors.update(self.get_form_errors(form)) return errors else: return self.get_form_errors(self)
mit
saxsir/showgi
db/migrate/20130102041448_add_csa_to_kifus.rb
104
class AddCsaToKifus < ActiveRecord::Migration def change add_column :kifus, :csa, :text end end
mit
mind0n/hive
Cache/Libs/net46/wpf/src/Core/CSharp/System/Windows/Media/Imaging/WmpBitmapDecoder.cs
3847
//------------------------------------------------------------------------------ // Microsoft Avalon // Copyright (c) Microsoft Corporation, All Rights Reserved // // File: WmpBitmapDecoder.cs // //------------------------------------------------------------------------------ using System; using System.IO; using System.Collections; using System.Security; using System.Security.Permissions; using System.ComponentModel; using System.ComponentModel.Design.Serialization; using System.Reflection; using Microsoft.Win32.SafeHandles; using MS.Internal; using System.Diagnostics; using System.Windows.Media; using System.Globalization; using System.Runtime.InteropServices; namespace System.Windows.Media.Imaging { #region WmpBitmapDecoder /// <summary> /// The built-in Microsoft Wmp (Bitmap) Decoder. /// </summary> public sealed class WmpBitmapDecoder : BitmapDecoder { /// <summary> /// Don't allow construction of a decoder with no params /// </summary> private WmpBitmapDecoder() { } /// <summary> /// Create a WmpBitmapDecoder given the Uri /// </summary> /// <param name="bitmapUri">Uri to decode</param> /// <param name="createOptions">Bitmap Create Options</param> /// <param name="cacheOption">Bitmap Caching Option</param> /// <SecurityNote> /// Critical - access critical resource /// PublicOk - inputs verified or safe /// </SecurityNote> [SecurityCritical] public WmpBitmapDecoder( Uri bitmapUri, BitmapCreateOptions createOptions, BitmapCacheOption cacheOption ) : base(bitmapUri, createOptions, cacheOption, MILGuidData.GUID_ContainerFormatWmp) { } /// <summary> /// If this decoder cannot handle the bitmap stream, it will throw an exception. /// </summary> /// <param name="bitmapStream">Stream to decode</param> /// <param name="createOptions">Bitmap Create Options</param> /// <param name="cacheOption">Bitmap Caching Option</param> /// <SecurityNote> /// Critical - access critical resource /// PublicOk - inputs verified or safe /// </SecurityNote> [SecurityCritical] public WmpBitmapDecoder( Stream bitmapStream, BitmapCreateOptions createOptions, BitmapCacheOption cacheOption ) : base(bitmapStream, createOptions, cacheOption, MILGuidData.GUID_ContainerFormatWmp) { } /// <summary> /// Internal Constructor /// </summary> /// <SecurityNote> /// Critical: Uses a SafeFileHandle, which is a SecurityCritical type (in v4). /// Calls SecurityCritical base class constructor. /// </SecurityNote> [SecurityCritical] internal WmpBitmapDecoder( SafeMILHandle decoderHandle, BitmapDecoder decoder, Uri baseUri, Uri uri, Stream stream, BitmapCreateOptions createOptions, BitmapCacheOption cacheOption, bool insertInDecoderCache, bool originalWritable, Stream uriStream, UnmanagedMemoryStream unmanagedMemoryStream, SafeFileHandle safeFilehandle ) : base(decoderHandle, decoder, baseUri, uri, stream, createOptions, cacheOption, insertInDecoderCache, originalWritable, uriStream, unmanagedMemoryStream, safeFilehandle) { } #region Internal Abstract /// Need to implement this to derive from the "sealed" object internal override void SealObject() { throw new NotImplementedException(); } #endregion } #endregion }
mit
Association-Merci-Edgar/Merci-Edgar
app/controllers/contacts_controller.rb
6300
class ContactsController < ApplicationController def bulk @contact_ids = params[:contact_ids] case params[:bulk_action] when "delete" Contact.where(id: params[:contact_ids]).find_each do |contact| unless contact.fine_model.destroy @error_message = "Une erreur est survenue lors de la suppression du contact #{contact.name}" render "bulk_error" return end end redirect_to contacts_path, notice: "Les contacts ont été supprimés" when "add_custom_tags" if params[:bulk_value].present? @contacts = Contact.where(id: params[:contact_ids]) @contacts.each do |contact| contact.add_custom_tags(TagHelper.clean(params[:bulk_value])) unless contact.save @error_message = "Une erreur est survenue lors de la modificaton du contact #{contact.name}" render "bulk_error" return end end render "bulk_add_custom_tags" else @error_message = "Vous n'avez renseigné aucun tag personnalisé !" render "bulk_error" end end end def autocomplete contacts = Contact.order(:name).where("lower(contacts.name) LIKE ?", "%#{params[:term].downcase}%").limit(10) json=[] contacts.each do |c| fm = c.fine_model link = send(fm.class.name.underscore + "_path", fm) kind = I18n.t(fm.class.name.underscore, scope: "activerecord.models") json.push({value:c.name, label:c.name, new: "false", link: link, avatar: c.avatar_url(:thumb), kind: kind}) end unless contacts.map(&:name).map(&:downcase).include?(params[:term].downcase) json.push({value:params[:term], label: "Créer la structure : " + params[:term], new:"true", link: new_structure_path(name: params[:term]) }) json.push({value:params[:term], label: "Créer la personne : " + params[:term], new:"true", link: new_person_path(name: params[:term]) }) end render json: json end def index if Contact.count == 0 render "empty" return end if params[:address].present? radius = params[:radius].present? ? params[:radius] : 100 addresses = Address.near(params[:address], radius, units: :km).where(account_id: Account.current_id) end if params[:commit] == "show map" addresses = Address.where(account_id: Account.current_id) unless addresses.present? contact_ids = Contact.advanced_search(params).pluck(:id) addresses = addresses.where(contact_id: contact_ids) @contacts_json = addresses.to_gmaps4rails do |address, marker| contact = address.contact marker.infowindow render_to_string(:partial => "contacts/infowindow_venue", :locals => { :contact => contact}) marker.title address.contact.name end if addresses.present? render "show_map" else @contacts = Contact.advanced_search(params) @contacts = @contacts.where(id: addresses.map(&:contact_id)) if addresses if params[:imported_at].present? @nb_imported_contacts, @nb_duplicates = ContactsImport.get_payload(params[:imported_at]) @imported_at = params[:imported_at].to_i @test = @imported_at == current_account.test_imported_at end @contacts = @contacts.page params[:page] if params[:category].present? raise "Invalid Parameter" if %w(venues festivals show_buyers structures people).include?(params[:category]) == false @label_category = params[:category] end end end def show_map if params[:address].present? radius = params[:radius] || 100 contacts = Address.where(account_id: Account.current_id).near(params[:address], radius, units: :km) else contacts = Address.where(account_id: Account.current_id) end @contacts_json = contacts.to_gmaps4rails do |address, marker| model = address.contact.fine_model marker.infowindow render_to_string(:partial => "contacts/infowindow_#{model.class.name.downcase}", :locals => { :model => model}) marker.title address.contact.name end if contacts.present? end def only @no_paging = false @contacts = case params[:filter] when "favorites" then current_user.favorites.page params[:page] when "contacted" then Contact.with_reportings.page params[:page] when "recently_created" then @no_paging = true Contact.send(params[:filter]) when "recently_updated" then @no_paging = true Contact.send(params[:filter]) when 'style' then @param_filter = params[:name] Kaminari.paginate_array(Contact.by_style(params[:name])).page params[:page] when 'network' then @param_filter = params[:name] Contact.by_network(params[:name]).page params[:page] when 'custom' then @param_filter = params[:name] Contact.by_custom(params[:name]).page params[:page] when 'contract' then @param_filter = params[:name] Kaminari.paginate_array(Contact.by_contract(params[:name])).page params[:page] when "dept" then @param_filter = params[:no] Contact.by_department(params[:no]).page params[:page] when "capacities_less_than" then @param_filter = params[:nb] Venue.capacities_less_than(params[:nb]).page params[:page] when "capacities_more_than" then @param_filter = params[:nb] Venue.capacities_more_than(params[:nb]).page params[:page] when "capacities_between" then @param_filter = [params[:nb1],params[:nb2]].join(" => ") Venue.capacities_between(params[:nb1],params[:nb2]).page params[:page] else redirect_to contacts_path return end @filtered_by = t(params[:filter], scope:"filters") render "index" end def add_to_favorites @contact = Contact.find(params[:id]) if @contact current_user.add_to_favorites(@contact) if current_user.save render "add_to_favorites" end end end def remove_to_favorites @contact = Contact.find(params[:id]) if @contact current_user.remove_to_favorites(@contact) if current_user.save render "remove_to_favorites" end end end end
mit
michalbe/turbulenz_engine
samples/tsscripts/benchmarks/turbulenz/js/inline_functions.ts
8599
// Copyright (c) 2010-2011 Turbulenz Limited /*global BF: false*/ declare var BF; // // Inline functions vs non-inline functions // // // Inline function: Call an inline version of a math function // class InlineFunction { // Settings n = 10000; // Number of times to call the function array: any[]; init() { var n = this.n; var array = []; var angle = Math.PI / 6; var inc = (Math.PI * 2) / n; // n increments for (var i = 0; i < n; i += 1) { // Constant angle so the execution route is the same for all calculations var theta = (i * inc); var thetaAngle = theta + angle; array[i] = { j1: [theta, theta, theta, theta], j2: [thetaAngle, thetaAngle, thetaAngle, thetaAngle], quatRes: [] }; } this.array = array; }; run() { var array = this.array; var n = this.n; // Constants var delta = 0.1; var cosMinSlerpAngle = Math.cos(Math.PI / 40.0); var sqrt = Math.sqrt; var sin = Math.sin; var acos = Math.acos; for (var i = 0; i < n; i += 1) { var obj = array[i]; var j1 = obj.j1; var j2 = obj.j2; // // INLINED: var quatResult = VMath.quatslerp(j1[0..3], j2[0..3], delta); // // A version of quatslerp from VMath library // var t = delta; var q1x = j1[0]; var q1y = j1[1]; var q1z = j1[2]; var q1w = j1[3]; var q2x = j2[0]; var q2y = j2[1]; var q2z = j2[2]; var q2w = j2[3]; var dotq1q2 = (q1x * q2x) + (q1y * q2y) + (q1z * q2z) + (q1w * q2w); var cosom = dotq1q2; if (cosom < 0.0) { q1x = -q1x; q1y = -q1y; q1z = -q1z; q1w = -q1w; cosom = -cosom; } if (cosom > cosMinSlerpAngle) { if (dotq1q2 <= 0.0) { t = -t; } var qrx = ((q2x - q1x) * t) + q1x; var qry = ((q2y - q1y) * t) + q1y; var qrz = ((q2z - q1z) * t) + q1z; var qrw = ((q2w - q1w) * t) + q1w; var mag = sqrt((qrx * qrx) + (qry * qry) + (qrz * qrz) + (qrw * qrw)); var recip = 1.0 / mag; obj.quatRes = [qrx * recip, qry * recip, qrz * recip, qrw * recip]; } else { var omega = acos(cosom); var inv_sin_omega = 1.0 / sin(omega); var scalar = sin((1.0 - t) * omega) * inv_sin_omega; q1x = q1x * scalar; q1y = q1y * scalar; q1z = q1z * scalar; q1w = q1w * scalar; scalar = sin(t * omega) * inv_sin_omega; q2x = q2x * scalar; q2y = q2y * scalar; q2z = q2z * scalar; q2w = q2w * scalar; obj.quatRes = [q1x + q2x, q1y + q2y, q1z + q2z, q1w + q2w]; } } }; destroy() { var n = this.n; var array = this.array; for (var i = 0; i < n; i += 1) { delete array[i]; } delete this.array; }; // Constructor function static create() { var a = new InlineFunction(); a.array = []; return a; }; }; // // Non-inline function: Call the non-inline version of a math function // class NonInlineFunction { // Settings n = 10000; // Number of times to call the function array: any[]; init() { var n = this.n; var array = []; var angle = Math.PI / 6; var inc = (Math.PI * 2) / n; // n increments for (var i = 0; i < n; i += 1) { // Constant angle so the execution route is the same for all calculations var theta = (i * inc); var thetaAngle = theta + angle; array[i] = { j1: [theta, theta, theta, theta], j2: [thetaAngle, thetaAngle, thetaAngle, thetaAngle], quatRes: [] }; } this.array = array; }; run() { var array = this.array; var n = this.n; // Constants var delta = 0.1; var cosMinSlerpAngle = Math.cos(Math.PI / 40.0); var sqrt = Math.sqrt; var sin = Math.sin; var acos = Math.acos; // Non-inline function var quatslerp = function quatslerpFn(j1, j2, delta) { // // A version of quatslerp from VMath library // var t = delta; var q1x = j1[0]; var q1y = j1[1]; var q1z = j1[2]; var q1w = j1[3]; var q2x = j2[0]; var q2y = j2[1]; var q2z = j2[2]; var q2w = j2[3]; var dotq1q2 = (q1x * q2x) + (q1y * q2y) + (q1z * q2z) + (q1w * q2w); var cosom = dotq1q2; if (cosom < 0.0) { q1x = -q1x; q1y = -q1y; q1z = -q1z; q1w = -q1w; cosom = -cosom; } if (cosom > cosMinSlerpAngle) { if (dotq1q2 <= 0.0) { t = -t; } var qrx = ((q2x - q1x) * t) + q1x; var qry = ((q2y - q1y) * t) + q1y; var qrz = ((q2z - q1z) * t) + q1z; var qrw = ((q2w - q1w) * t) + q1w; var mag = sqrt((qrx * qrx) + (qry * qry) + (qrz * qrz) + (qrw * qrw)); var recip = 1.0 / mag; return [qrx * recip, qry * recip, qrz * recip, qrw * recip]; } else { var omega = acos(cosom); var inv_sin_omega = 1.0 / sin(omega); var scalar = sin((1.0 - t) * omega) * inv_sin_omega; q1x = q1x * scalar; q1y = q1y * scalar; q1z = q1z * scalar; q1w = q1w * scalar; scalar = sin(t * omega) * inv_sin_omega; q2x = q2x * scalar; q2y = q2y * scalar; q2z = q2z * scalar; q2w = q2w * scalar; return [q1x + q2x, q1y + q2y, q1z + q2z, q1w + q2w]; } }; for (var i = 0; i < n; i += 1) { var obj = array[i]; var j1 = obj.j1; var j2 = obj.j2; obj.quatRes = quatslerp(j1, j2, delta); } }; destroy() { var n = this.n; var array = this.array; for (var i = 0; i < n; i += 1) { delete array[i]; } delete this.array; }; // Constructor function static create() { var a = new NonInlineFunction(); a.array = []; return a; }; }; var inlineFunction = InlineFunction.create(); var nonInlineFunction = NonInlineFunction.create(); BF.register({ name: "InlineFunction", path: "scripts/benchmarks/turbulenz/js/inline_functions.js", description: [ "Stores n objects containing a unique pair of quaternions each.", "For each object runs an inline version of quatSlerp function on the arguments and assigns the result to the object." ], init: function () { return inlineFunction.init(); }, run: function () { return inlineFunction.run(); }, destroy: function () { return inlineFunction.destroy(); }, targetMean: 0.00177, version: 1.1 }); BF.register({ name: "NonInlineFunctions", path: "scripts/benchmarks/turbulenz/js/inline_functions.js", description: [ "Stores n objects containing a unique pair of quaternions each.", "For each object calls a non-inlined version of the quatSlerp function on the arguments and assigns the returned result to the object." ], init: function () { return nonInlineFunction.init(); }, run: function () { return nonInlineFunction.run(); }, destroy: function () { return nonInlineFunction.destroy(); }, targetMean: 0.00201, version: 1.1 });
mit
saeeiabping/project1
application/config/config.php
17729
<?php defined('BASEPATH') OR exit('No direct script access allowed'); /* |-------------------------------------------------------------------------- | Base Site URL |-------------------------------------------------------------------------- | | URL to your CodeIgniter root. Typically this will be your base URL, | WITH a trailing slash: | | http://example.com/ | | If this is not set then CodeIgniter will try guess the protocol, domain | and path to your installation. However, you should always configure this | explicitly and never rely on auto-guessing, especially in production | environments. | */ $config['base_url'] = 'http://localhost/project1/'; /* |-------------------------------------------------------------------------- | Index File |-------------------------------------------------------------------------- | | Typically this will be your index.php file, unless you've renamed it to | something else. If you are using mod_rewrite to remove the page set this | variable so that it is blank. | */ $config['index_page'] = ''; /* |-------------------------------------------------------------------------- | URI PROTOCOL |-------------------------------------------------------------------------- | | This item determines which server global should be used to retrieve the | URI string. The default setting of 'REQUEST_URI' works for most servers. | If your links do not seem to work, try one of the other delicious flavors: | | 'REQUEST_URI' Uses $_SERVER['REQUEST_URI'] | 'QUERY_STRING' Uses $_SERVER['QUERY_STRING'] | 'PATH_INFO' Uses $_SERVER['PATH_INFO'] | | WARNING: If you set this to 'PATH_INFO', URIs will always be URL-decoded! */ $config['uri_protocol'] = 'REQUEST_URI'; /* |-------------------------------------------------------------------------- | URL suffix |-------------------------------------------------------------------------- | | This option allows you to add a suffix to all URLs generated by CodeIgniter. | For more information please see the user guide: | | http://codeigniter.com/user_guide/general/urls.html */ $config['url_suffix'] = ''; /* |-------------------------------------------------------------------------- | Default Language |-------------------------------------------------------------------------- | | This determines which set of language files should be used. Make sure | there is an available translation if you intend to use something other | than english. | */ $config['language'] = 'english'; /* |-------------------------------------------------------------------------- | Default Character Set |-------------------------------------------------------------------------- | | This determines which character set is used by default in various methods | that require a character set to be provided. | | See http://php.net/htmlspecialchars for a list of supported charsets. | */ $config['charset'] = 'UTF-8'; /* |-------------------------------------------------------------------------- | Enable/Disable System Hooks |-------------------------------------------------------------------------- | | If you would like to use the 'hooks' feature you must enable it by | setting this variable to TRUE (boolean). See the user guide for details. | */ $config['enable_hooks'] = FALSE; /* |-------------------------------------------------------------------------- | Class Extension Prefix |-------------------------------------------------------------------------- | | This item allows you to set the filename/classname prefix when extending | native libraries. For more information please see the user guide: | | http://codeigniter.com/user_guide/general/core_classes.html | http://codeigniter.com/user_guide/general/creating_libraries.html | */ $config['subclass_prefix'] = 'MY_'; /* |-------------------------------------------------------------------------- | Composer auto-loading |-------------------------------------------------------------------------- | | Enabling this setting will tell CodeIgniter to look for a Composer | package auto-loader script in application/vendor/autoload.php. | | $config['composer_autoload'] = TRUE; | | Or if you have your vendor/ directory located somewhere else, you | can opt to set a specific path as well: | | $config['composer_autoload'] = '/path/to/vendor/autoload.php'; | | For more information about Composer, please visit http://getcomposer.org/ | | Note: This will NOT disable or override the CodeIgniter-specific | autoloading (application/config/autoload.php) */ $config['composer_autoload'] = FALSE; /* |-------------------------------------------------------------------------- | Allowed URL Characters |-------------------------------------------------------------------------- | | This lets you specify which characters are permitted within your URLs. | When someone tries to submit a URL with disallowed characters they will | get a warning message. | | As a security measure you are STRONGLY encouraged to restrict URLs to | as few characters as possible. By default only these are allowed: a-z 0-9~%.:_- | | Leave blank to allow all characters -- but only if you are insane. | | The configured value is actually a regular expression character group | and it will be executed as: ! preg_match('/^[<permitted_uri_chars>]+$/i | | DO NOT CHANGE THIS UNLESS YOU FULLY UNDERSTAND THE REPERCUSSIONS!! | */ $config['permitted_uri_chars'] = 'a-z 0-9~%.:_\-'; /* |-------------------------------------------------------------------------- | Enable Query Strings |-------------------------------------------------------------------------- | | By default CodeIgniter uses search-engine friendly segment based URLs: | example.com/who/what/where/ | | By default CodeIgniter enables access to the $_GET array. If for some | reason you would like to disable it, set 'allow_get_array' to FALSE. | | You can optionally enable standard query string based URLs: | example.com?who=me&what=something&where=here | | Options are: TRUE or FALSE (boolean) | | The other items let you set the query string 'words' that will | invoke your controllers and its functions: | example.com/index.php?c=controller&m=function | | Please note that some of the helpers won't work as expected when | this feature is enabled, since CodeIgniter is designed primarily to | use segment based URLs. | */ $config['allow_get_array'] = TRUE; $config['enable_query_strings'] = FALSE; $config['controller_trigger'] = 'c'; $config['function_trigger'] = 'm'; $config['directory_trigger'] = 'd'; /* |-------------------------------------------------------------------------- | Error Logging Threshold |-------------------------------------------------------------------------- | | You can enable error logging by setting a threshold over zero. The | threshold determines what gets logged. Threshold options are: | | 0 = Disables logging, Error logging TURNED OFF | 1 = Error Messages (including PHP errors) | 2 = Debug Messages | 3 = Informational Messages | 4 = All Messages | | You can also pass an array with threshold levels to show individual error types | | array(2) = Debug Messages, without Error Messages | | For a live site you'll usually only enable Errors (1) to be logged otherwise | your log files will fill up very fast. | */ $config['log_threshold'] = 0; /* |-------------------------------------------------------------------------- | Error Logging Directory Path |-------------------------------------------------------------------------- | | Leave this BLANK unless you would like to set something other than the default | application/logs/ directory. Use a full server path with trailing slash. | */ $config['log_path'] = ''; /* |-------------------------------------------------------------------------- | Log File Extension |-------------------------------------------------------------------------- | | The default filename extension for log files. The default 'php' allows for | protecting the log files via basic scripting, when they are to be stored | under a publicly accessible directory. | | Note: Leaving it blank will default to 'php'. | */ $config['log_file_extension'] = ''; /* |-------------------------------------------------------------------------- | Log File Permissions |-------------------------------------------------------------------------- | | The file system permissions to be applied on newly created log files. | | IMPORTANT: This MUST be an integer (no quotes) and you MUST use octal | integer notation (i.e. 0700, 0644, etc.) */ $config['log_file_permissions'] = 0644; /* |-------------------------------------------------------------------------- | Date Format for Logs |-------------------------------------------------------------------------- | | Each item that is logged has an associated date. You can use PHP date | codes to set your own date formatting | */ $config['log_date_format'] = 'Y-m-d H:i:s'; /* |-------------------------------------------------------------------------- | Error Views Directory Path |-------------------------------------------------------------------------- | | Leave this BLANK unless you would like to set something other than the default | application/views/errors/ directory. Use a full server path with trailing slash. | */ $config['error_views_path'] = ''; /* |-------------------------------------------------------------------------- | Cache Directory Path |-------------------------------------------------------------------------- | | Leave this BLANK unless you would like to set something other than the default | application/cache/ directory. Use a full server path with trailing slash. | */ $config['cache_path'] = ''; /* |-------------------------------------------------------------------------- | Cache Include Query String |-------------------------------------------------------------------------- | | Whether to take the URL query string into consideration when generating | output cache files. Valid options are: | | FALSE = Disabled | TRUE = Enabled, take all query parameters into account. | Please be aware that this may result in numerous cache | files generated for the same page over and over again. | array('q') = Enabled, but only take into account the specified list | of query parameters. | */ $config['cache_query_string'] = FALSE; /* |-------------------------------------------------------------------------- | Encryption Key |-------------------------------------------------------------------------- | | If you use the Encryption class, you must set an encryption key. | See the user guide for more info. | | http://codeigniter.com/user_guide/libraries/encryption.html | */ $config['encryption_key'] = ''; /* |-------------------------------------------------------------------------- | Session Variables |-------------------------------------------------------------------------- | | 'sess_driver' | | The storage driver to use: files, database, redis, memcached | | 'sess_cookie_name' | | The session cookie name, must contain only [0-9a-z_-] characters | | 'sess_expiration' | | The number of SECONDS you want the session to last. | Setting to 0 (zero) means expire when the browser is closed. | | 'sess_save_path' | | The location to save sessions to, driver dependent. | | For the 'files' driver, it's a path to a writable directory. | WARNING: Only absolute paths are supported! | | For the 'database' driver, it's a table name. | Please read up the manual for the format with other session drivers. | | IMPORTANT: You are REQUIRED to set a valid save path! | | 'sess_match_ip' | | Whether to match the user's IP address when reading the session data. | | 'sess_time_to_update' | | How many seconds between CI regenerating the session ID. | | 'sess_regenerate_destroy' | | Whether to destroy session data associated with the old session ID | when auto-regenerating the session ID. When set to FALSE, the data | will be later deleted by the garbage collector. | | Other session cookie settings are shared with the rest of the application, | except for 'cookie_prefix' and 'cookie_httponly', which are ignored here. | */ $config['sess_driver'] = 'files'; $config['sess_cookie_name'] = 'ci_session'; $config['sess_expiration'] = 7200; $config['sess_save_path'] = NULL; $config['sess_match_ip'] = FALSE; $config['sess_time_to_update'] = 300; $config['sess_regenerate_destroy'] = FALSE; /* |-------------------------------------------------------------------------- | Cookie Related Variables |-------------------------------------------------------------------------- | | 'cookie_prefix' = Set a cookie name prefix if you need to avoid collisions | 'cookie_domain' = Set to .your-domain.com for site-wide cookies | 'cookie_path' = Typically will be a forward slash | 'cookie_secure' = Cookie will only be set if a secure HTTPS connection exists. | 'cookie_httponly' = Cookie will only be accessible via HTTP(S) (no javascript) | | Note: These settings (with the exception of 'cookie_prefix' and | 'cookie_httponly') will also affect sessions. | */ $config['cookie_prefix'] = ''; $config['cookie_domain'] = ''; $config['cookie_path'] = '/'; $config['cookie_secure'] = FALSE; $config['cookie_httponly'] = FALSE; /* |-------------------------------------------------------------------------- | Standardize newlines |-------------------------------------------------------------------------- | | Determines whether to standardize newline characters in input data, | meaning to replace \r\n, \r, \n occurrences with the PHP_EOL value. | | This is particularly useful for portability between UNIX-based OSes, | (usually \n) and Windows (\r\n). | */ $config['standardize_newlines'] = FALSE; /* |-------------------------------------------------------------------------- | Global XSS Filtering |-------------------------------------------------------------------------- | | Determines whether the XSS filter is always active when GET, POST or | COOKIE data is encountered | | WARNING: This feature is DEPRECATED and currently available only | for backwards compatibility purposes! | */ $config['global_xss_filtering'] = FALSE; /* |-------------------------------------------------------------------------- | Cross Site Request Forgery |-------------------------------------------------------------------------- | Enables a CSRF cookie token to be set. When set to TRUE, token will be | checked on a submitted form. If you are accepting user data, it is strongly | recommended CSRF protection be enabled. | | 'csrf_token_name' = The token name | 'csrf_cookie_name' = The cookie name | 'csrf_expire' = The number in seconds the token should expire. | 'csrf_regenerate' = Regenerate token on every submission | 'csrf_exclude_uris' = Array of URIs which ignore CSRF checks */ $config['csrf_protection'] = FALSE; $config['csrf_token_name'] = 'csrf_test_name'; $config['csrf_cookie_name'] = 'csrf_cookie_name'; $config['csrf_expire'] = 7200; $config['csrf_regenerate'] = TRUE; $config['csrf_exclude_uris'] = array(); /* |-------------------------------------------------------------------------- | Output Compression |-------------------------------------------------------------------------- | | Enables Gzip output compression for faster page loads. When enabled, | the output class will test whether your server supports Gzip. | Even if it does, however, not all browsers support compression | so enable only if you are reasonably sure your visitors can handle it. | | Only used if zlib.output_compression is turned off in your php.ini. | Please do not use it together with httpd-level output compression. | | VERY IMPORTANT: If you are getting a blank page when compression is enabled it | means you are prematurely outputting something to your browser. It could | even be a line of whitespace at the end of one of your scripts. For | compression to work, nothing can be sent before the output buffer is called | by the output class. Do not 'echo' any values with compression enabled. | */ $config['compress_output'] = FALSE; /* |-------------------------------------------------------------------------- | Master Time Reference |-------------------------------------------------------------------------- | | Options are 'local' or any PHP supported timezone. This preference tells | the system whether to use your server's local time as the master 'now' | reference, or convert it to the configured one timezone. See the 'date | helper' page of the user guide for information regarding date handling. | */ $config['time_reference'] = 'local'; /* |-------------------------------------------------------------------------- | Rewrite PHP Short Tags |-------------------------------------------------------------------------- | | If your PHP installation does not have short tag support enabled CI | can rewrite the tags on-the-fly, enabling you to utilize that syntax | in your view files. Options are TRUE or FALSE (boolean) | | Note: You need to have eval() enabled for this to work. | */ $config['rewrite_short_tags'] = FALSE; /* |-------------------------------------------------------------------------- | Reverse Proxy IPs |-------------------------------------------------------------------------- | | If your server is behind a reverse proxy, you must whitelist the proxy | IP addresses from which CodeIgniter should trust headers such as | HTTP_X_FORWARDED_FOR and HTTP_CLIENT_IP in order to properly identify | the visitor's IP address. | | You can use both an array or a comma-separated list of proxy addresses, | as well as specifying whole subnets. Here are a few examples: | | Comma-separated: '10.0.1.200,192.168.5.0/24' | Array: array('10.0.1.200', '192.168.5.0/24') */ $config['proxy_ips'] = '';
mit
JohanLarsson/Gu.State
Gu.State/Internals/Collections/ReferenceComparer.cs
925
namespace Gu.State { using System.Collections.Generic; internal sealed class ReferenceComparer : IEqualityComparer<object> { internal static readonly ReferenceComparer Default = new ReferenceComparer(); private ReferenceComparer() { } bool IEqualityComparer<object>.Equals(object x, object y) { var xPair = x as ReferencePair; var yPair = y as ReferencePair; if (xPair != null && yPair != null) { return Equals(xPair, (ReferencePair)y); } return ReferenceEquals(x, y); } int IEqualityComparer<object>.GetHashCode(object obj) { return obj.GetHashCode(); } private static bool Equals(ReferencePair x, ReferencePair y) { return ReferenceEquals(x.X, y.X) && ReferenceEquals(x.Y, y.Y); } } }
mit
kormoc/xattr
xattr_test.go
1234
package xattr import "io/ioutil" import "os" import "reflect" import "testing" func TestHas(t *testing.T) { var test_xattrName = "user.xattr.test" var test_xattrValue = []byte{11,22,33,44,55,66,77,88,99} tmpfile, err := ioutil.TempFile("", "xattr_Test") if err != nil { t.Fatal(err) } defer os.Remove(tmpfile.Name()) if has, err := Has(tmpfile.Name(), test_xattrName); has != false || err != nil { t.Fatalf("Has failed: %v\n", err) } if err := SetBytes(tmpfile.Name(), test_xattrName, test_xattrValue); err != nil { t.Fatalf("SetBytes failed: %v\n", err) } if has, err := Has(tmpfile.Name(), test_xattrName); has != true || err != nil { t.Fatalf("Has failed: %v\n", err) } if value, err := GetBytes(tmpfile.Name(), test_xattrName); !reflect.DeepEqual(value, test_xattrValue) { t.Fatalf("GetBytes failed: %v\n\tExpected: '%v'\n\tFound: '%v'\n", err, test_xattrValue, value) } if err := Remove(tmpfile.Name(), test_xattrName); err != nil { t.Fatalf("Remove failed: %v\n", err) } if has, err := Has(tmpfile.Name(), test_xattrName); has != false || err != nil { t.Fatalf("Has failed: %v\n", err) } }
mit
moyuyc/isomorphic-blog
frontend/src/router.js
1366
/** * Created by moyu on 2017/2/8. */ import React from "react"; import {Router, browserHistory, Route, Redirect, IndexRoute} from "react-router"; import App from "./App"; export const routerForSiteMap = ( <Router history={ browserHistory }> <Route path="/"> <IndexRoute/> <Route path="posts(/:page)"></Route> <Route path="article/:hrefTitle"></Route> <Route path="tags/:tagName" ></Route> <Route path="tags/pages/(:page)" ></Route> <Route path="archive(/:searchKey)"></Route> <Redirect path="*" to="/" /> </Route> </Router> ) if (typeof require.ensure !== 'function') { require.ensure = (d, c) => c(require); } export const routes = { path: '/', component: App, childRoutes: [ require('./routers/PostsRouter').default, require('./routers/ArchiveRouter').default, require('./routers/ArticleRouter').default, require('./routers/TagRouter').default, require('./routers/TagsRouter').default, { path: '*', onEnter(nextState, replace) { replace('/'); } } ], indexRoute: { getComponent: require('./routers/PostsRouter').default.getComponent } } export default <Router history={ browserHistory } routes={routes}/>
mit
nathanntg/arctic-api
examples/invoice_transaction_insert.php
824
<?php // set directory chdir(__DIR__); require 'init.i.php'; // load invoice by ID (if invoice number is P185, the ID is 185) try { $invoice = \Arctic\Model\Invoice\Invoice::load(185); } catch (\Arctic\Exception $e) { // invoice not found or communication error die('Unable to load invoice.'); } // create transaction $transaction = new \Arctic\Model\Invoice\Transaction(); $transaction->type = \Arctic\Model\Invoice\Transaction::TYPE_PAYMENT; $transaction->description = 'Online Payment'; $transaction->amount = '100.00'; // amount of payment $transaction->time = date('Y-m-d H:i:s'); // current date and time // inserted simply by adding it to the reference array, saved upon insertion into the array $invoice->transactions[] = $transaction; // refresh invoice balance due and payment details $invoice->refresh();
mit
MSNexploder/mapper
lib/mapper/visitors/sql.js
12200
var util = require('util'); var _ = require('underscore'); var Visitor = require('./visitor'); var SelectStatement = require('../nodes/select_statement'); var In = require('../nodes/in'); var SQL = function() { Visitor.call(this); this.class_name = 'SQL'; }; util.inherits(SQL, Visitor); module.exports = SQL; SQL.prototype.visitSelectStatementNode = function(object) { var self = this; var orders = _.map(object.orders, function(val) { if (!_.isString(val)) { val = self.visit(val); } return val; }); return _.compact([ this.visit(object.core), (!_.isEmpty(orders)) ? 'ORDER BY ' + orders.join(', ') : undefined, (!_.isEmpty(object.limit)) ? this.visit(object.limit) : undefined, (!_.isEmpty(object.offset)) ? this.visit(object.offset) : undefined, (!_.isEmpty(object.lock)) ? this.visit(object.lock) : undefined, ]).join(' '); }; SQL.prototype.visitDeleteStatementNode = function(object) { var self = this; var wheres = _.map(object.wheres, function(val) { return self.visit(val); }); return _.compact([ 'DELETE FROM ' + this.visit(object.relation), (!_.isEmpty(wheres)) ? 'WHERE ' + wheres.join(' AND ') : undefined, ]).join(' '); }; SQL.prototype.visitUpdateStatementNode = function(object) { var self = this; var tmp_wheres; if ((_.isEmpty(object.orders)) && (_.isEmpty(object.limit))) { tmp_wheres = object.wheres; } else { var stmt = new SelectStatement(); stmt.core.froms = object.relation; stmt.core.projections = [object.key]; stmt.limit = object.limit; stmt.orders = object.orders; tmp_wheres = [new In(object.key, [stmt])]; } var values = _.map(object.values, function(val) { return self.visit(val); }); var wheres = _.map(tmp_wheres, function(val) { return self.visit(val); }); return _.compact([ 'UPDATE ' + this.visit(object.relation), (!_.isEmpty(values)) ? 'SET ' + values.join(', ') : undefined, (!_.isEmpty(wheres)) ? 'WHERE ' + wheres.join(' AND ') : undefined, ]).join(' '); }; SQL.prototype.visitInsertStatementNode = function(object) { var self = this; var columns = _.map(object.columns, function(val) { return self.quoteColumnName(val.right); }); return _.compact([ 'INSERT INTO ' + this.visit(object.relation), (!_.isEmpty(columns)) ? '(' + columns.join(', ') + ')' : undefined, (!_.isEmpty(object.values)) ? this.visit(object.values) : undefined, ]).join(' '); }; SQL.prototype.visitSelectCoreNode = function(object) { var self = this; var projections = _.map(object.projections, function(val) { if (!_.isString(val)) { val = self.visit(val); } return val; }); var wheres = _.map(object.wheres, function(val) { return self.visit(val); }); var groups = _.map(object.groups, function(val) { if (!_.isString(val)) { val = self.visit(val); } return val; }); return _.compact([ (!_.isEmpty(projections)) ? 'SELECT ' + projections.join(', ') : 'SELECT', this.visit(object.source), (!_.isEmpty(wheres)) ? 'WHERE ' + wheres.join(' AND ') : undefined, (!_.isEmpty(groups)) ? 'GROUP BY ' + groups.join(', ') : undefined, (!_.isEmpty(object.having)) ? this.visit(object.having) : undefined, ]).join(' '); }; SQL.prototype.visitHavingNode = function(object) { var self = this; return 'HAVING ' + _.map(object.expr, function(expr) { if (!_.isString(expr)) { expr = self.visit(expr); } return expr; }).join(', '); }; SQL.prototype.visitOffsetNode = function(object) { return 'OFFSET ' + this.visit(object.expr); }; // implemented in subclasses SQL.prototype.visitLockNode = function(object) { return undefined; }; SQL.prototype.visitValuesNode = function(object) { var self = this; var columns = _.map(_.zip(object.left, object.right), function(val) { return self.quote(val[0], val[1] && self.columnFor(val[1])); }); return 'VALUES (' + columns.join(', ') + ')'; }; SQL.prototype.visitInNode = function(object) { return this.visit(object.left) + ' IN ' + this.visit(object.right); }; SQL.prototype.visitNotInNode = function(object) { return this.visit(object.left) + ' NOT IN ' + this.visit(object.right); }; SQL.prototype.visitAttributeNode = function(object) { var column; if (_.isString(object.right)) { column = this.quoteColumnName(object.right); } else { column = this.visit(object.right); } var join_name = object.left.left || object.left.name; return this.quoteTableName(join_name) + '.' + column; }; SQL.prototype.visitJoinSourceNode = function(object) { var self = this; return _.compact([ (!_.isEmpty(object.left)) ? 'FROM ' + this.visit(object.left) : undefined, _.map(object.right, function(val) { return self.visit(val); }).join(' '), ]).join(' '); }; SQL.prototype.visitSqlLiteralNode = function(object) { return object.val; }; SQL.prototype.visitTableNode = function(object) { if (object.table_alias) { return this.quoteTableName(object.name) + ' ' + this.quoteTableName(object.table_alias); } else { return this.quoteTableName(object.name); } }; SQL.prototype.visitAsNode = function(object) { return this.visit(object.left) + ' AS ' + this.visit(object.right); }; SQL.prototype.visitBetweenNode = function(object) { return this.visit(object.left) + ' BETWEEN ' + this.visit(object.right); }; SQL.prototype.visitDoesNotMatchNode = function(object) { return this.visit(object.left) + ' NOT LIKE ' + this.visit(object.right); }; SQL.prototype.visitMatchesNode = function(object) { return this.visit(object.left) + ' LIKE ' + this.visit(object.right); }; SQL.prototype.visitGreaterThanNode = function(object) { return this.visit(object.left) + ' > ' + this.visit(object.right); }; SQL.prototype.visitGreaterThanOrEqualNode = function(object) { return this.visit(object.left) + ' >= ' + this.visit(object.right); }; SQL.prototype.visitLessThanNode = function(object) { return this.visit(object.left) + ' < ' + this.visit(object.right); }; SQL.prototype.visitLessThanOrEqualNode = function(object) { return this.visit(object.left) + ' <= ' + this.visit(object.right); }; SQL.prototype.visitLimitNode = function(object) { return 'LIMIT ' + this.visit(object.expr); }; SQL.prototype.visitNotEqualNode = function(object) { if (_.isNull(object.right) || _.isUndefined(object.right)) { return this.visit(object.left) + ' IS NOT NULL'; } else { return this.visit(object.left) + ' != ' + this.visit(object.right); } }; SQL.prototype.visitEqualityNode = function(object) { if (_.isNull(object.right) || _.isUndefined(object.right)) { return this.visit(object.left) + ' IS NULL'; } else { return this.visit(object.left) + ' = ' + this.visit(object.right); } }; SQL.prototype.visitNotNode = function(object) { return 'NOT (' + this.visit(object.expr) + ')'; }; SQL.prototype.visitAndNode = function(object) { var self = this; return _.map(object.children, function(val) { return self.visit(val); }).join(' AND '); }; SQL.prototype.visitOrNode = function(object) { var self = this; return _.map(object.children, function(val) { return self.visit(val); }).join(' OR '); }; SQL.prototype.visitOrderingNode = function(object) { return this.visit(object.left) + ' ' + object.right; }; SQL.prototype.visitGroupingNode = function(object) { return '(' + this.visit(object.expr) + ')'; }; SQL.prototype.visitGroupNode = function(object) { return this.visit(object.expr); }; SQL.prototype.visitOnNode = function(object) { return 'ON ' + this.visit(object.expr); }; SQL.prototype.visitUnqualifiedColumnNode = function(object) { return this.quoteColumnName(object.expr.right); }; SQL.prototype.visitStringJoinNode = function(object) { return this.visit(object.left); }; SQL.prototype.visitExistsNode = function(object) { var alias = object.alias ? ' AS ' + this.visit(object.alias) : ''; return 'EXISTS(' + this.visit(object.expr) + ')' + alias; }; SQL.prototype.visitSumNode = function(object) { var alias = object.alias ? ' AS ' + this.visit(object.alias) : ''; return 'SUM(' + this.visit(object.expr) + ')' + alias; }; SQL.prototype.visitMaxNode = function(object) { var alias = object.alias ? ' AS ' + this.visit(object.alias) : ''; return 'MAX(' + this.visit(object.expr) + ')' + alias; }; SQL.prototype.visitMinNode = function(object) { var alias = object.alias ? ' AS ' + this.visit(object.alias) : ''; return 'MIN(' + this.visit(object.expr) + ')' + alias; }; SQL.prototype.visitAvgNode = function(object) { var alias = object.alias ? ' AS ' + this.visit(object.alias) : ''; return 'AVG(' + this.visit(object.expr) + ')' + alias; }; SQL.prototype.visitOuterJoinNode = function(object) { return 'LEFT OUTER JOIN ' + this.visit(object.left) + ' ' + this.visit(object.right); }; SQL.prototype.visitInnerJoinNode = function(object) { return _.compact([ 'INNER JOIN', this.visit(object.left), (!_.isEmpty(object.right)) ? this.visit(object.right) : undefined, ]).join(' '); }; SQL.prototype.visitNamedFunctionNode = function(object) { var distinct = object.distinct ? 'DISTINCT ' : ''; var alias = object.alias ? ' AS ' + this.visit(object.alias) : ''; var expressions = this.visit(object.expr); return object.name + '(' + distinct + expressions + ')' + alias; }; SQL.prototype.visitCountNode = function(object) { var distinct = object.distinct ? 'DISTINCT ' : ''; var alias = object.alias ? ' AS ' + this.visit(object.alias) : ''; var expressions = this.visit(object.expr); return 'COUNT(' + distinct + expressions + ')' + alias; }; SQL.prototype.visitTableAliasNode = function(object) { return this.visit(object.right) + ' ' + this.quoteTableName(object.left); }; SQL.prototype.visitAssignmentNode = function(object) { return this.visit(object.left) + ' = ' + this.quote(object.right, this.columnFor(object.left)); }; // TODO maybe be smarter about given object // used for "simple" objects without 'class_name' attribute SQL.prototype.visitundefinedNode = function(object) { var self = this; switch (typeof(object)) { case 'boolean': return object ? this.quoteString('t') : this.quoteString('f'); case 'number': if (parseFloat(object) != parseInt(object, 10)) { return this.quoteString(object.toString()); } return object; case 'string': return this.quoteString(object); case 'undefined': return 'NULL'; case 'object': if (_.isArray(object)) { if (_.isEmpty(object)) { return 'NULL'; } else { return _.map(object, function(val) { return self.visit(val); }).join(', '); } } else if (_.isDate(object)) { return this.quoteString(object.toUTCString()); } else if (_.isNull(object)) { return 'null'; } return object.toString(); case 'function': return object(); default: return object; } }; SQL.prototype.quoteTableName = function(name) { return this.quoteColumnName(name); }; SQL.prototype.quoteColumnName = function(column) { if (column.class_name == column) { return column; } else { return '"' + column + '"'; } }; SQL.prototype.columnFor = function(attr) { // TODO // needed real quoting in every visitor return attr; }; SQL.prototype.quote = function(value, column) { // TODO // needed real quoting in every visitor return this.visit(value); }; SQL.prototype.quoteString = function(string) { return "'" + string.replace(/\\/g, '\\\\').replace(/'/g, "''") + "'"; };
mit
php-quartz/quartz-dev
pkg/quartz/Core/SchedulerFactory.php
235
<?php namespace Quartz\Core; interface SchedulerFactory { /** * <p> * Returns a client-usable handle to a <code>Scheduler</code>. * </p> * * @return Scheduler */ public function getScheduler(); }
mit
thebakeryio/openmic
internals/webpack/webpack.dev.babel.js
2133
/** * DEVELOPMENT WEBPACK CONFIGURATION */ const path = require('path'); const webpack = require('webpack'); const HtmlWebpackPlugin = require('html-webpack-plugin'); // PostCSS plugins const cssnext = require('postcss-cssnext'); const postcssFocus = require('postcss-focus'); const postcssReporter = require('postcss-reporter'); const postcssSprites = require('postcss-sprites').default; module.exports = require('./webpack.base.babel')({ // Add hot reloading in development entry: [ 'eventsource-polyfill', // Necessary for hot reloading with IE 'webpack-hot-middleware/client', path.join(process.cwd(), 'app/app.js'), // Start with js/app.js ], // Don't use hashes in dev mode for better performance output: { filename: '[name].js', chunkFilename: '[name].chunk.js', }, // Load the CSS in a style tag in development cssLoaders: ['style-loader', 'css-loader', 'postcss-loader', 'sass-loader'], // Process the CSS with PostCSS postcssPlugins: [ postcssFocus(), // Add a :focus to every :hover cssnext({ // Allow future CSS features to be used, also auto-prefixes the CSS... browsers: ['last 2 versions', 'IE > 10'], // ...based on this browser list }), postcssReporter({ // Posts messages from plugins to the terminal clearMessages: true, }), postcssSprites({ stylesheetPath: './app/styles', spritePath: './app/images/', retina: true, filterBy: (image) => { // only sprite buttons if (!/buttons/.test(image.url)) { return Promise.reject(); } return Promise.resolve(); }, }), ], // Add hot reloading plugins: [ new webpack.HotModuleReplacementPlugin(), // Tell webpack we want hot reloading new webpack.NoErrorsPlugin(), new HtmlWebpackPlugin({ template: 'app/index.html', inject: true, // Inject all files that are generated by webpack, e.g. bundle.js }), ], // Tell babel that we want to hot-reload babelQuery: { presets: ['react-hmre'], }, // Emit a source map for easier debugging devtool: 'inline-source-map', });
mit
GICodeWarrior/authlogic_facebook
spec/spec_helper.rb
220
$LOAD_PATH.unshift(File.dirname(__FILE__)) $LOAD_PATH.unshift(File.join(File.dirname(__FILE__), '..', 'lib')) require 'authlogic_facebook' require 'spec' require 'spec/autorun' Spec::Runner.configure do |config| end
mit
piotrwitek/typesafe-actions
src/index.ts
1045
/** * @name typesafe-actions * @author Piotr Witek <[email protected]> (http://piotrwitek.github.io) * @copyright Copyright (c) 2017 Piotr Witek * @license MIT */ /** Public API */ // action-creators export { action } from './action'; export { createAction } from './create-action'; export { createCustomAction } from './create-custom-action'; export { createAsyncAction } from './create-async-action'; export { createReducer } from './create-reducer'; // action-helpers export { getType } from './get-type'; export { isOfType } from './is-of-type'; export { isActionOf } from './is-action-of'; // type-helpers export { Types, ActionType, StateType, TypeConstant, Action, Reducer, EmptyAction, PayloadAction, PayloadMetaAction, ActionCreator, EmptyActionCreator, PayloadActionCreator, PayloadMetaActionCreator, ActionCreatorTypeMetadata, ActionBuilder, ActionCreatorBuilder, AsyncActionCreatorBuilder, } from './type-helpers'; // deprecated export { default as deprecated } from './deprecated';
mit
andmilj/vip-transfers
src/utils/Format.utils.js
1637
import cityTypes from '../db/constants/cityTypes'; import { pick, find } from 'lodash'; export function cityName(_city, _type) { let city = _city; let type = _type; if (!type) { city = _city.split('_')[0]; type = _city.split('_')[1]; } const suffix = type === cityTypes.AIRPORT ? ' ' + cityTypes.AIRPORT : ''; return city + suffix; } export function isAirport(_city, _type) { let type = _type; if (!type) { type = _city.split('_')[1]; } return type === cityTypes.AIRPORT; } export function timestampToDate(timestamp) { return new Date(parseInt(timestamp, 10)); } export function pickDetails(state) { return pick(state, 'passengerDetails', 'addressDetailsOneWay', 'addressDetailsReturn'); } function findDestination(collection, cityWithType) { const _cityWithType = cityWithType.split('_'); const result = find(collection, {city: _cityWithType[0], type: _cityWithType[1]}); return pick(result, 'city', 'type'); } function findPrice(collection, vehicleType) { return pick(find(collection, { vehicleType }), 'price', 'vehicleType'); } export function constructReservation({ passengerDetails, addressDetailsOneWay, addressDetailsReturn, price, returnDate, extrasReturn, extrasDeparture, vehicleType}, {from, to, persons, date}, destinations, prices) { return { passengerDetails, addressDetailsOneWay, addressDetailsReturn, extrasReturn, extrasDeparture, returnDate, persons, totalPrice: price, date: timestampToDate(date), from: findDestination(destinations, from), to: findDestination(destinations, to), price: findPrice(prices, vehicleType), }; }
mit
apiaryio/dredd-hooks-python
dredd_hooks/__main__.py
225
#!/usr/bin/env python # -*- coding: utf-8 -*- # # Copyright (c) 2015, 2016 Apiary Czech Republic, s.r.o. # License: MIT # def main(): from dredd_hooks import cli cli.main() if __name__ == '__main__': main()
mit
topameng/tolua
Assets/ToLua/Lua/UnityEngine/Ray.lua
1480
-------------------------------------------------------------------------------- -- Copyright (c) 2015 - 2016 , 蒙占志(topameng) [email protected] -- All rights reserved. -- Use, modification and distribution are subject to the "MIT License" -------------------------------------------------------------------------------- local rawget = rawget local setmetatable = setmetatable local Vector3 = Vector3 local Ray = { direction = Vector3.zero, origin = Vector3.zero, } local get = tolua.initget(Ray) Ray.__index = function(t,k) local var = rawget(Ray, k) if var == nil then var = rawget(get, k) if var ~= nil then return var(t) end end return var end Ray.__call = function(t, direction, origin) return Ray.New(direction, origin) end function Ray.New(direction, origin) local ray = {} ray.direction = direction:Normalize() ray.origin = origin setmetatable(ray, Ray) return ray end function Ray:GetPoint(distance) local dir = self.direction * distance dir:Add(self.origin) return dir end function Ray:Get() local o = self.origin local d = self.direction return o.x, o.y, o.z, d.x, d.y, d.z end Ray.__tostring = function(self) return string.format("Origin:(%f,%f,%f),Dir:(%f,%f, %f)", self.origin.x, self.origin.y, self.origin.z, self.direction.x, self.direction.y, self.direction.z) end UnityEngine.Ray = Ray setmetatable(Ray, Ray) return Ray
mit
efleurine/alumnus
api/libs/logger.js
268
/** * A logger service -TO BE update to use a more reliable solution like morgan or other * this should only be use on the server side and not in the browser * */ function Logger(msg) { // eslint-disable-next-line console.log(msg) } module.exports = Logger
mit
teayudope/laweb
web/bower_components/tiny-slider/src/helpers/removeAttrs.js
362
import { isNodeList } from "./isNodeList"; export function removeAttrs(els, attrs) { els = (isNodeList(els) || els instanceof Array) ? els : [els]; attrs = (attrs instanceof Array) ? attrs : [attrs]; var attrLength = attrs.length; for (var i = els.length; i--;) { for (var j = attrLength; j--;) { els[i].removeAttribute(attrs[j]); } } }
mit
twoolie/Minecraft-Tools
src/minecraft/mcproxy.py
10446
#!/usr/bin/env python2.7 from test.test_telnetlib import EOF_sigil __VERSION__ = ('0','5') __AUTHOR__ = ('gm_stack', 'twoolie', 'kleinig') import os.path, sys; sys.path.insert(0,os.path.dirname(os.path.abspath(__file__))) import socket, struct, time, sys, traceback, argparse, logging from Queue import Queue from threading import Thread, RLock from binascii import hexlify from conf import settings #---------- Arguments ---------- if __name__== '__main__': class BetterArgParser(argparse.ArgumentParser): def convert_arg_line_to_args(self, arg_line): for arg in arg_line.split(): if not arg.strip(): continue yield arg parser = BetterArgParser( description=""" =========================================================================== | MCProxy minecraft hax server v%s by %s. =========================================================================== """%(".".join(__VERSION__), ". ".join(__AUTHOR__)), epilog="See included documentation for licensing, blackhats.net.au for info about the people.", fromfile_prefix_chars='@', # allow loading config from a file e.g. `mcproxy.py @stackunderflow` ) parser.add_argument("server", help="The server to connect clients to.") parser.add_argument('-L',"--local-port", dest='local_port', default=25565, help="The local port mcproxy listens on (default: %(default)s") parser.add_argument('-m',"--modules", dest='modules', default=['all'], nargs='+', metavar='MODULE', help="Which modules should be activated by default. e.g \"-m all -troll\" or \"-m default troll.Entomb\"") parser.add_argument("--no-console", dest='console', action='store_false', help="Do not start an interactive console.") parser.add_argument('-c',"--metachar", dest='metachar', default=settings.metachar, metavar='META', help="The metachar that prefixes mcproxy chat commands. (default: %(default)s)") parser.add_argument('-C', "--chat-color", dest='chat_color', default=settings.chat_color, metavar='COLORCODE', help="The colorcode for default chat color from mcproxy [values: 1-f]. (default: %(default)s)") parser.add_argument('-l', '--logevel', dest='log_level', default=settings.log_level, metavar='LEVEL', help="Set the loglevel seen in the console. (default: %(default)s)") parser.add_argument("--debug", action="store_true", default=False, help="Enables advanced debugging.") settings = parser.parse_args(namespace=settings) #--------- Init Systems --------- import mcpackets, nbt, hooks, items, modules, log logging.root.level = logging.DEBUG server_log = logging.getLogger("SERVER") #--------- Threads ---------- def startNetworkSockets(settings): #====================================================================================# # server <---------- serversocket | mcproxy | clientsocket ----------> minecraft.jar # #====================================================================================# while True: try: # Client Socket listensocket = socket.socket(socket.AF_INET, socket.SOCK_STREAM) listensocket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) listensocket.bind(('127.0.0.1', 25565)) # 25565 listensocket.listen(1) server_log.info("Waiting for connection...") clientsocket, addr = listensocket.accept() server_log.info("Connection accepted from %s" % str(addr)) # Server Socket #preserv = "70.138.82.67" #preserv = "craft.minestick.com" #preserv = "mccloud.is-a-chef.com" #preserv = "60.226.115.245" #preserv = 'simplicityminecraft.com' host = settings.server if ":" in host: host, port = host.split(":") port = int(port) else: port = 25565 server_log.info("Connecting to %s...", host) serversocket = socket.socket(socket.AF_INET, socket.SOCK_STREAM) serversocket.connect((host,port)) session = Session() settings.session = session session.comms.clientqueue = Queue() session.comms.serverqueue = Queue() session.comms.clientsocket = clientsocket session.comms.serversocket = serversocket #start processing threads serverthread = Thread(target=sock_foward, name=str(id(session))+"-ClientToServer", args=("c2s", clientsocket, serversocket, session.comms.serverqueue, settings)) serverthread.setDaemon(True) serverthread.start() clientthread = Thread(target=sock_foward, name=str(id(session))+"-ServerToClient", args=("s2c", serversocket, clientsocket, session.comms.clientqueue, settings)) clientthread.setDaemon(True) clientthread.start() #playerMessage.printToPlayer(session,"MCProxy active. %shelp for commands."%settings.metachar) #wait for something bad to happen :( serverthread.join() clientthread.join() server_log.info("Session(%s) exited cleanly.", id(session)) except Exception as e: server_log.error("Something went wrong with Session(%s). (%s)", id(session), e ) def sock_foward(dir, insocket, outsocket, outqueue, settings): buff = FowardingBuffer(insocket, outsocket) session = settings.session try: while True: #decode packet buff.packet_start() packetid = struct.unpack("!B", buff.read(1))[0] if packetid in session.protocol.packets.keys(): packet = session.protocol.decode(dir, buff, packetid) if packetid==0x01 and dir=='c2s': if packet['protoversion'] in mcpackets.supported_protocols.keys(): session.comms.protocol = mcpackets.supported_protocols[packet['protoversion']]() else: server_log.critical("unknown packet 0x%2X from %s", packetid, {'c2s':'client', 's2c':'server'}[dir]) buff.packet_end() raise Exception("Unknown Packet 0x%2X"%packetid) #playerMessage.printToPlayer(session,("unknown packet 0x%2X from" % packetid) + {'c2s':'client', 's2c':'server'}[dir]) packetbytes = buff.packet_end() modpacket = run_hooks(packetid, packet, session) if modpacket == None: # if run_hooks returns none, the packet was not modified packet_info(packetid, packet, buff, session) buff.write(packetbytes) elif modpacket == {}: # if an empty dict, drop the packet pass else: packet_info(packetid, modpacket, buff, session) buff.write(session.comms.protocol.encode(dir,packetid,modpacket)) #send all items in the outgoing queue while not outqueue.empty(): task = outqueue.get() buff.write(task) outqueue.task_done() except socket.error, e: server_log.error("%s connection quit unexpectedly: %s", {'s2c':'server', 'c2s':'client'}[dir], e) finally: insocket.close() outsocket.close() return #does not currently run def ishell(settings): while True: try: command = raw_input("> ") except EOFError: server_log.info("Quit Shell!") break command = command.split(" ") try: modules.commands.runCommand(settings.session, command) except Exception as e: traceback.print_exc() print "error in command", command[0] #--------- utility --------------- class FowardingBuffer(): def __init__(self, insocket, outsocket, *args, **kwargs): self.inbuff = insocket.makefile('rb', 4096) self.outsock = outsocket self.lastpack = "" def read(self, nbytes): #stack = traceback.extract_stack() bytes = self.inbuff.read(nbytes) if len(bytes) != nbytes: raise socket.error("Socket has collapsed, unknown error") self.lastpack += bytes #self.outsock.send(bytes) return bytes def write(self, bytes): self.outsock.send(bytes) def packet_start(self): self.lastpack = "" def packet_end(self): return self.lastpack def render_last_packet(self): rpack = self.lastpack truncate = False if len(rpack) > 512: rpack = rpack[:32] truncate = True rpack = " ".join([hexlify(byte) for byte in rpack]) if truncate: rpack += " ..." return rpack #will not run yet def run_hooks(packetid, packet, session): ret = None hooks = session.protocol.packets[packetid]['hooks'] if hooks: for hook in hooks: try: retpacket = hook(packetid,packet,session) if retpacket != None: packet = retpacket ret = packet except Exception as e: traceback.print_exc() print('Hook "%s" crashed!' % modules.hook_to_name[hook]) #: File:%s, line %i in %s (%s)" % (execption[0], execption[1], execption[2], execption[3])) session.protocol.packets[packetid]['hooks'].remove(hook) # #FIXME: make this report what happened return ret def packet_info(packetid, packet, buff, session): if settings.dump_packets: if not settings.dumpfilter or (packetid in settings.filterlist): print packet['dir'], "->", session.protocol.packets[packetid]['name'], ":", packet if settings.hexdump: print buff.render_last_packet() #storage class for a session with the server class Session(): def __init__(self): self.dump_packets = True self.dumpfilter = True self.filterlist = [0x01, 0x02, 0xFF] self.hexdump = False self.screen = None self.detect = False self.playerdata = {} self.playerdata_lock = RLock() self.players = {} self.gui = {} self.waypoint = {} self.currentwp = "" class comms: clientqueue = None serverqueue = None protocol = mcpackets.BaseProtocol() if __name__ == "__main__": #====================================================================================# # server <---------- serversocket | mcproxy | clientsocket ----------> minecraft.jar # #====================================================================================# #---------- Spool up server threads ------------ server_log.info("Server starting up on port %d", settings.local_port) sd = Thread(name="ServerDispatch", target=startNetworkSockets, args=(settings, )) sd.setDaemon(True) sd.start() #--------- Start interactive console ---------- if settings.console: shell = Thread(name="InteractiveShell", target=ishell, args=(settings, )) shell.setDaemon(True) shell.start() while 1: try: time.sleep(1) except KeyboardInterrupt: if hasattr(settings, 'session'): if settings.session.comms.serversocket is not None: try: settings.session.comms.serversocket.shutdown() except: settings.session.comms.serversocket.close() if settings.session.comms.clientsocket is not None: try: settings.session.comms.clientsocket.shutdown() except: settings.session.comms.clientsocket.close() server_log.warn("Server Shutdown.") break #import gui #gui.start_gui(serverprops) #app should exit here, and threads should terminate
mit
ghiscoding/Aurelia-Bootstrap-Plugins
aurelia-bootstrap-select/dist/es2015/util-service.js
1240
export let UtilService = class UtilService { isArrayEqual(a, b) { if (a === b) return true; if (a === null || b === null) return false; if (a.length !== b.length) return false; for (let i = 0; i < a.length; i++) { let aExistsInb = false; for (let j = 0; j < b.length && !aExistsInb; j++) { if (a[i] === b[j]) { aExistsInb = true; } } if (!aExistsInb) { return false; } } return true; } isEqual(a, b) { if (Array.isArray(a) && Array.isArray(b)) { return this.isArrayEqual(a.sort(), b.sort()); } return a === b; } isObjectArray(inputArrray) { return Array.isArray(inputArrray) && inputArrray.length > 0 && typeof inputArrray[0] === 'object'; } isObject(arg) { return typeof arg === 'object'; } isString(arg) { return typeof arg === 'string' || arg instanceof String; } isStringArray(inputArrray) { return Array.isArray(inputArrray) && inputArrray.length > 0 && typeof inputArrray[0] === 'string'; } parseBool(value) { return (/^(true|1)$/i.test(value) ); } parseBoolOrTrueOnEmpty(value) { return value === undefined || value === '' ? true : this.parseBool(value); } };
mit
kodazzi/amazonas
system/bundles/Dinnovos/Users/config/routes.cf.php
3096
<?php /* * This file is part of the Kodazzi Framework. * * (c) Jorge Gaitan <[email protected]> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ use Symfony\Component\Routing\Route; $routes->add( 'user-registration', new Route('/registro-usuario', array('controller' => 'Dinnovos\Users:Registration:step1')) ); $routes->add( 'user-successful-registration', new Route('/registro-exitoso', array('controller' => 'Dinnovos\Users:Registration:successful')) ); $routes->add( 'user-registration-fails', new Route('/registro-fallido', array('controller' => 'Dinnovos\Users:Registration:fails')) ); $routes->add( 'user-token-confirmation-email', new Route('/registro/confirmacion/{token}', array('controller' => 'Dinnovos\Users:Registration:confirmationEmail'), array('token' => '^[a-zA-Z0-9]+$')) ); //---------------------------------------------------------------------------------------------------------------------- $routes->add( 'user-login', new Route('/iniciar-sesion', array('controller' => 'Dinnovos\Users:Session:login')) ); $routes->add( 'user-logout', new Route('/salir-sesion', array('controller' => 'Dinnovos\Users:Session:logout')) ); $routes->add( 'user-forgotten-password', new Route('/olvido-clave', array('controller' => 'Dinnovos\Users:Session:forgottenPassword')) ); $routes->add( 'user-not-approved', new Route('/usuario/cuenta-no-aprobada', array('controller' => 'Dinnovos\Users:Session:notApproved')) ); $routes->add( 'user-invalid-account', new Route('/usuario/cuenta-no-valida', array('controller' => 'Dinnovos\Users:Session:invalidAccount')) ); $routes->add( 'user-dashboard', new Route('/usuario/escritorio', array('controller' => 'Dinnovos\Users:dashboard:index')) ); // Para los usuarios que no ha confirmado la cuenta de correo. $routes->add( 'user-unconfirme-email', new Route('/invalido/email', array('controller' => 'Dinnovos\Users:Session:unconfirmeEmail')) ); // Envia email para confirmar correo $routes->add( 'user-send-confirmation-email', new Route('/invalido/enviar-confirmacion-email', array('controller' => 'Dinnovos\Users:Session:sendConfirmationEmail')) ); // Permite acceder al formulario para cambiar la clave. $routes->add( 'user-modify-password', new Route('/usuario/modificar-clave/{token}', array('controller' => 'Dinnovos\Users:Session:modifyPassword'), array('token' => '^[a-zA-Z0-9]+$')) ); $routes->add( 'user-dashboard', new Route('/usuario/escritorio', array('controller' => 'Dinnovos\Users:dashboard:index')) ); //---------------------------------------------------------------------------------------------------------------------- $routes->add( '@default-admin-user', new Route( '/panel-users/{controller}/{action}/{param1}/{param2}/{param3}/{param4}/{param5}', array('_bundle' => 'Dinnovos\Users', 'param1' => null, 'param2' => null, 'param3' => null, 'param4' => null, 'param5' => null) ) );
mit
sergey-dryabzhinsky/dedupsqlfs
dedupsqlfs/db/sqlite/table/block.py
1972
# -*- coding: utf8 -*- __author__ = 'sergey' from sqlite3 import Binary from dedupsqlfs.db.sqlite.table import Table class TableBlock( Table ): _table_name = "block" def create( self ): c = self.getCursor() # Create table c.execute( "CREATE TABLE IF NOT EXISTS `%s` (" % self._table_name+ "hash_id INTEGER PRIMARY KEY, "+ "data BLOB NOT NULL"+ ");" ) return def insert( self, hash_id, data): """ :param data: bytes :return: int """ self.startTimer() cur = self.getCursor() bdata = Binary(data) cur.execute("INSERT INTO `%s`(hash_id, data) VALUES (?,?)" % self._table_name, (hash_id, bdata,)) item = cur.lastrowid self.stopTimer('insert') return item def update( self, hash_id, data): """ :param data: bytes :return: int """ self.startTimer() cur = self.getCursor() bdata = Binary(data) cur.execute("UPDATE `%s` SET data=? WHERE hash_id=?" % self._table_name, (bdata, hash_id,)) count = cur.rowcount self.stopTimer('update') return count def get( self, hash_id): """ :param hash_id: int :return: Row """ self.startTimer() cur = self.getCursor() cur.execute("SELECT * FROM `%s` WHERE hash_id=?" % self._table_name, (hash_id,)) item = cur.fetchone() self.stopTimer('get') return item def remove_by_ids(self, id_str): self.startTimer() count = 0 if id_str: cur = self.getCursor() cur.execute("DELETE FROM `%s` " % self.getName()+ " WHERE `hash_id` IN (%s)" % (id_str,)) count = cur.rowcount self.stopTimer('remove_by_ids') return count pass
mit
urban/scaffold
test/prompt-test.js
2054
import test from 'tape' import prompt from '../src/prompt' import MockStream from './helpers/mock-stream' import flatten from 'flat' import questions from './fixtures/questions' import userInput from './fixtures/userInput' import captureOutput from './helpers/capture-output' process.on('unhandledRejection', (err) => { console.error(err) }) const { nextTick } = process const stdin = new MockStream() const stdout = new MockStream() prompt.__Rewire__('stdin', stdin) prompt.__Rewire__('stdout', stdout) prompt.__Rewire__('log', msg => stdout.write(msg)) const question = captureOutput(stdout) const prompts = Object.keys(questions) .reduce((result, key) => { const { description } = questions[key] const defaultValue = questions[key]['default'] result[key] = defaultValue ? `>: ${description}: (${defaultValue})` : `>: ${description}:` return result }, {}) test('It askes all the questions.', async t => { try { const answer = (str) => stdin.writeNextTick(str + '\n') const results = new Promise(resolve => { nextTick(() => resolve(prompt(questions))) }) const userProps = flatten(userInput) for (let key in userProps) { t.equal(await question(), prompts[key], `Asked for ${key}.`) answer(userProps[key]) } const finalProps = await question() t.deepEqual(finalProps.trim(), JSON.stringify(userInput, undefined, 2), 'Has correct answers') answer(true) const now = new Date() const expectedResults = { ...userInput, date: { day: now.getDate(), month: now.getMonth(), fullYear: now.getFullYear() } } t.deepEqual(await Promise.resolve(results), expectedResults, 'Has correct output') t.end() } catch (err) { console.log(err) } }) test('It should skip questions with overrides.', async t => { try { nextTick(() => prompt(questions, { 'pkg.name': 'test' })) const firstQuestion = await question() t.equal(firstQuestion, prompts['pkg.version'], 'Skipped pkg.name.') t.end() } catch (err) { console.log(err) } })
mit
sql-assurance/sql-assurance
sql_assurance/config.py
613
import sys import os import yaml def find_path_to_config_parameter(): args = sys.argv if 'SQLASSURANCE_CONFIG_PATH' in os.environ: return os.environ['SQLASSURANCE_CONFIG_PATH'] for i, arg in enumerate(args): if arg[i] == 'p': return args[i+1] def load_config(path): if not os.path.exists(path): raise ValueError("Path {} is not valid") with open(path, 'r') as context: config = yaml.load(context.read()) context.close() return config path_to_config_file = find_path_to_config_parameter() settings = load_config(path_to_config_file)
mit
jonathanlurie/canvasSpliner
dist/CanvasSpliner.js
30594
(function (global, factory) { typeof exports === 'object' && typeof module !== 'undefined' ? factory(exports) : typeof define === 'function' && define.amd ? define(['exports'], factory) : (factory((global.CanvasSpliner = global.CanvasSpliner || {}))); }(this, (function (exports) { 'use strict'; /** * by George MacKerron, mackerron.com * * Monotonic Cubic Spline: * * adapted from: * http://sourceforge.net/mailarchive/forum.php?thread_name=EC90C5C6-C982-4F49-8D46-A64F270C5247%40gmail.com&forum_name=matplotlib-users * (easier to read at http://old.nabble.com/%22Piecewise-Cubic-Hermite-Interpolating-Polynomial%22-in-python-td25204843.html) * * with help from: * F N Fritsch & R E Carlson (1980) 'Monotone Piecewise Cubic Interpolation', SIAM Journal of Numerical Analysis 17(2), 238 - 246. * http://en.wikipedia.org/wiki/Monotone_cubic_interpolation * http://en.wikipedia.org/wiki/Cubic_Hermite_spline * * * Natural and Clamped: * * adapted from: * http://www.michonline.com/ryan/csc/m510/splinepresent.html **/ var CubicSpline; var MonotonicCubicSpline; MonotonicCubicSpline = function () { function MonotonicCubicSpline(x, y) { var alpha, beta, delta, dist, i, m, n, tau, to_fix, _i, _j, _len, _len2, _ref, _ref2, _ref3, _ref4; n = x.length; delta = []; m = []; alpha = []; beta = []; dist = []; tau = []; for (i = 0, _ref = n - 1; (0 <= _ref ? i < _ref : i > _ref); (0 <= _ref ? i += 1 : i -= 1)) { delta[i] = (y[i + 1] - y[i]) / (x[i + 1] - x[i]); if (i > 0) { m[i] = (delta[i - 1] + delta[i]) / 2; } } m[0] = delta[0]; m[n - 1] = delta[n - 2]; to_fix = []; for (i = 0, _ref2 = n - 1; (0 <= _ref2 ? i < _ref2 : i > _ref2); (0 <= _ref2 ? i += 1 : i -= 1)) { if (delta[i] === 0) { to_fix.push(i); } } for (_i = 0, _len = to_fix.length; _i < _len; _i++) { i = to_fix[_i]; m[i] = m[i + 1] = 0; } for (i = 0, _ref3 = n - 1; (0 <= _ref3 ? i < _ref3 : i > _ref3); (0 <= _ref3 ? i += 1 : i -= 1)) { alpha[i] = m[i] / delta[i]; beta[i] = m[i + 1] / delta[i]; dist[i] = Math.pow(alpha[i], 2) + Math.pow(beta[i], 2); tau[i] = 3 / Math.sqrt(dist[i]); } to_fix = []; for (i = 0, _ref4 = n - 1; (0 <= _ref4 ? i < _ref4 : i > _ref4); (0 <= _ref4 ? i += 1 : i -= 1)) { if (dist[i] > 9) { to_fix.push(i); } } for (_j = 0, _len2 = to_fix.length; _j < _len2; _j++) { i = to_fix[_j]; m[i] = tau[i] * alpha[i] * delta[i]; m[i + 1] = tau[i] * beta[i] * delta[i]; } this.x = x.slice(0, n); this.y = y.slice(0, n); this.m = m; } MonotonicCubicSpline.prototype.interpolate = function (x) { var h, h00, h01, h10, h11, i, t, t2, t3, y, _ref; for (i = _ref = this.x.length - 2; (_ref <= 0 ? i <= 0 : i >= 0); (_ref <= 0 ? i += 1 : i -= 1)) { if (this.x[i] <= x) { break; } } h = this.x[i + 1] - this.x[i]; t = (x - this.x[i]) / h; t2 = Math.pow(t, 2); t3 = Math.pow(t, 3); h00 = 2 * t3 - 3 * t2 + 1; h10 = t3 - 2 * t2 + t; h01 = -2 * t3 + 3 * t2; h11 = t3 - t2; y = h00 * this.y[i] + h10 * h * this.m[i] + h01 * this.y[i + 1] + h11 * h * this.m[i + 1]; return y; }; return MonotonicCubicSpline; }(); CubicSpline = function () { function CubicSpline(x, a, d0, dn) { var b, c, clamped, d, h, i, k, l, n, s, u, y, z, _ref; if (!((x != null) && (a != null))) { return; } clamped = (d0 != null) && (dn != null); n = x.length - 1; h = []; y = []; l = []; u = []; z = []; c = []; b = []; d = []; k = []; s = []; for (i = 0; (0 <= n ? i < n : i > n); (0 <= n ? i += 1 : i -= 1)) { h[i] = x[i + 1] - x[i]; k[i] = a[i + 1] - a[i]; s[i] = k[i] / h[i]; } if (clamped) { y[0] = 3 * (a[1] - a[0]) / h[0] - 3 * d0; y[n] = 3 * dn - 3 * (a[n] - a[n - 1]) / h[n - 1]; } for (i = 1; (1 <= n ? i < n : i > n); (1 <= n ? i += 1 : i -= 1)) { y[i] = 3 / h[i] * (a[i + 1] - a[i]) - 3 / h[i - 1] * (a[i] - a[i - 1]); } if (clamped) { l[0] = 2 * h[0]; u[0] = 0.5; z[0] = y[0] / l[0]; } else { l[0] = 1; u[0] = 0; z[0] = 0; } for (i = 1; (1 <= n ? i < n : i > n); (1 <= n ? i += 1 : i -= 1)) { l[i] = 2 * (x[i + 1] - x[i - 1]) - h[i - 1] * u[i - 1]; u[i] = h[i] / l[i]; z[i] = (y[i] - h[i - 1] * z[i - 1]) / l[i]; } if (clamped) { l[n] = h[n - 1] * (2 - u[n - 1]); z[n] = (y[n] - h[n - 1] * z[n - 1]) / l[n]; c[n] = z[n]; } else { l[n] = 1; z[n] = 0; c[n] = 0; } for (i = _ref = n - 1; (_ref <= 0 ? i <= 0 : i >= 0); (_ref <= 0 ? i += 1 : i -= 1)) { c[i] = z[i] - u[i] * c[i + 1]; b[i] = (a[i + 1] - a[i]) / h[i] - h[i] * (c[i + 1] + 2 * c[i]) / 3; d[i] = (c[i + 1] - c[i]) / (3 * h[i]); } this.x = x.slice(0, n + 1); this.a = a.slice(0, n); this.b = b; this.c = c.slice(0, n); this.d = d; } CubicSpline.prototype.derivative = function () { var c, d, s, x, _i, _j, _len, _len2, _ref, _ref2, _ref3; s = new this.constructor(); s.x = this.x.slice(0, this.x.length); s.a = this.b.slice(0, this.b.length); _ref = this.c; for (_i = 0, _len = _ref.length; _i < _len; _i++) { c = _ref[_i]; s.b = 2 * c; } _ref2 = this.d; for (_j = 0, _len2 = _ref2.length; _j < _len2; _j++) { d = _ref2[_j]; s.c = 3 * d; } for (x = 0, _ref3 = this.d.length; (0 <= _ref3 ? x < _ref3 : x > _ref3); (0 <= _ref3 ? x += 1 : x -= 1)) { s.d = 0; } return s; }; CubicSpline.prototype.interpolate = function (x) { var deltaX, i, y, _ref; for (i = _ref = this.x.length - 1; (_ref <= 0 ? i <= 0 : i >= 0); (_ref <= 0 ? i += 1 : i -= 1)) { if (this.x[i] <= x) { break; } } deltaX = x - this.x[i]; y = this.a[i] + this.b[i] * deltaX + this.c[i] * Math.pow(deltaX, 2) + this.d[i] * Math.pow(deltaX, 3); return y; }; return CubicSpline; }(); var index = { CubicSpline: CubicSpline, MonotonicCubicSpline: MonotonicCubicSpline }; /** * */ class PointCollection { constructor(){ this._points = []; this._min = { x: 0, y: 0, }; this._max = { x: Infinity, y: Infinity }; } /** * Define the acceptable min and max bot both axis. * @param {String} bound - can be "min" or "max" * @param {String} axis - can be "x" or "y" * @param {Number} value - a number * Note that minimum boudaries are inclusive while max are exclusive */ setBoundary( bound, axis, value ){ this["_" + bound][axis] = value; } /** * */ add( p ){ var newIndex = null; if(p.x >= this._min.x && p.x <= this._max.x && p.y >= this._min.y && p.y <= this._max.y) { if( !("xLocked" in p) ) p.xLocked = false; if( !("yLocked" in p) ) p.yLocked = false; if( !("safe" in p) ) p.safe = false; // adding the point this._points.push( p ); this._sortPoints(); newIndex = this._points.indexOf( p ); } return newIndex; } _sortPoints(){ // sorting the array upon x this._points.sort(function(p1, p2) { return p1.x - p2.x; }); } /** * Remove the points at the given index. * @param {Number} index - index of the point to remove * @return {Object} the point that was just removed or null if out of bound */ remove( index ){ var removedPoint = null; if(index >= 0 && index < this._points.length && !this._points[index].safe){ removedPoint = this._points.splice(index, 1); } return removedPoint; } /** * Get the index within the collection of the point that is the closest from * the one given in argument. Returns also the euclidiant distance to this point. * @return {Object} like {index: Number, distance: Number}, or null if there is * no point in this collection. */ getClosestFrom( p ){ if(!this._points.length) return null; var closestDistance = Infinity; var closestPointIndex = null; for(var i=0; i<this._points.length; i++){ var d = Math.sqrt( Math.pow(p.x - this._points[i].x, 2) + Math.pow(p.y - this._points[i].y, 2) ); if( d < closestDistance ){ closestDistance = d; closestPointIndex = i; } } return { index: closestPointIndex, distance: closestDistance } } /** * Gets the point at such index * @param {Number} index - the index of the point we want * @return {Object} point that contains at least "x" and "y" properties. */ getPoint( index ){ if(index >= 0 && index < this._points.length){ return this._points[index]; }else{ return null; } } /** * Get the number of points in the collection * @return {Number} the number of points */ getNumberOfPoints(){ return this._points.length; } /** * Update the posiiton of an existing point * @param {Number} index - index of the existing point to update * @param {Object} p - point that has coord we want to use as new coord. x and y values will be copied, no pointer association * @return {Number} new index, the changed point may have changed its index among the x-ordered list */ updatePoint( index, p ){ var newIndex = index; if(index >= 0 && index < this._points.length){ if(p.x >= this._min.x && p.x < this._max.x && p.y >= this._min.y && p.y < this._max.y){ if(!this._points[index].xLocked) this._points[index].x = p.x; if(!this._points[index].yLocked) this._points[index].y = p.y; var thePointInArray = this._points[index]; this._sortPoints(); // the point may have changed its index newIndex = this._points.indexOf( thePointInArray ); } } return newIndex; } /** * Get all "x" coordinates of the collection as an array of Number * @return {Array} of Number */ getXseries(){ var xSeries = []; for(var i=0; i<this._points.length; i++){ xSeries.push( this._points[i].x ); } return xSeries; } /** * Get all "y" coordinates of the collection as an array of Number * @return {Array} of Number */ getYseries(){ var ySeries = []; for(var i=0; i<this._points.length; i++){ ySeries.push( this._points[i].y ); } return ySeries; } } /* END of class PointCollection */ /* * Author Jonathan Lurie - http://me.jonahanlurie.fr * License MIT * Link https://github.com/jonathanlurie/es6module * Lab MCIN - http://mcin.ca/ - Montreal Neurological Institute */ /** * events: * - "movePoint" called everytime the pointer moves a point, with argument x and y normalized arrays * - "releasePoint" called everytime the pointers is released after moving a point, with argument x and y normalized arrays * - "pointAdded" */ class CanvasSpliner { /** * @param {Object} parentContainer - can be a String: the ID of the parent DIV, or can be directly the DOM element that will host the CanvasSpliner * @param {Number} width - width of the canvas where CanvasSpliner draws * @param {Number} height - height of the canvas where CanvasSpliner draws * @param {String} splineType - "natural" or "monotonic" */ constructor(parentContainer, width, height, splineType = 'natural'){ // some styling // borders of the canvas element this._borderStyle = { in: "1px solid #d3d3ff", out: "1px solid #e3e3e3" }; // radius of the control points this._controlPointRadius = 8; // color of the control points this._controlPointColor = { idle: "rgba(244, 66, 167, 0.5)", hovered: "rgba(0, 0, 255, 0.5)", grabbed: "rgba(0, 200, 0, 0.5)" }; // style of the curve this._curveColor = { idle: 'rgba(0, 128, 255, 1)', moving: 'rgba(255, 128, 0, 1)' }; // color of the grid this._gridColor = "rgba(0, 0, 0, 0.3)"; // color of the text this._textColor = "rgba(0, 0, 0, 0.1)"; // thickness of the curve this._curveThickness = 1; // color of the background this._backgroundColor = false; this._mouse = null; this._pointHoveredIndex = -1; // index of the grabbed point. -1 if none this._pointGrabbedIndex = -1; this._mouseDown = false; // says if the mouse is maintained clicked this._canvas = null; this._ctx = null; this._screenRatio = window.devicePixelRatio; var parentElem = null; if (typeof parentContainer === 'string' || parentContainer instanceof String){ parentElem = document.getElementById( parentContainer ); }else{ parentElem = parentContainer; } // abort if parent div does not exist if(!parentElem) return; // creating the canvas this._canvas = document.createElement('canvas'); this._canvas.width = width; this._canvas.height = height; this._canvas.setAttribute("tabIndex", 1); this._canvas.style.outline = "none"; this._canvas.style.cursor = "default"; this._canvas.style.border = this._borderStyle.out; this._canvas.onselectstart = function () { return false; }; this._width = width; this._height = height; // adding the canvas to the parent div parentElem.appendChild(this._canvas); this._ctx = this._canvas.getContext("2d"); //this._ctx.scale( 1.1, 1.1) this._ctx.scale( this._screenRatio , this._screenRatio ); // init the mouse and keyboard events this._canvas.addEventListener('mousemove', this._onCanvasMouseMove.bind(this), false); this._canvas.addEventListener('mousedown', this._onCanvasMouseDown.bind(this), false); //this._canvas.addEventListener('mouseup', this._onCanvasMouseUp.bind(this), false); window.addEventListener('mouseup', this._onCanvasMouseUp.bind(this), false); this._canvas.addEventListener('dblclick', this._onCanvasMouseDbclick.bind(this), false); this._canvas.addEventListener('mouseleave', this._onCanvasMouseLeave.bind(this), false); this._canvas.addEventListener('mouseenter', this._onCanvasMouseEnter.bind(this), false); this._canvas.addEventListener( 'keyup', this._onKeyUp.bind(this), false ); //this._canvas.addEventListener( 'keydown', this._onKeyDown.bind(this), false ); // dealing with cubic spline type this._splineConstructor = index.CubicSpline; if(splineType === "monotonic"){ this._splineConstructor = index.MonotonicCubicSpline; } // the point collection this._pointCollection = new PointCollection(); this._pointCollection.setBoundary("max", "x", width); this._pointCollection.setBoundary("max", "y", height); // interpolated values in a buffer this._xSeriesInterpolated = new Float32Array(this._width).fill(0); this._ySeriesInterpolated = new Float32Array(this._width).fill(0); this._gridStep = 1/3; // events this._onEvents = { movePoint: null, releasePoint: null, pointAdded: null }; this.draw(); } /** * Get an array of all the x coordinates that CanvasSpliner computed an interpolation of. * See getYSeriesInterpolated to get the corresponding interpolated values. * @return {Array} of x values with regular interval in [0, 1] */ getXSeriesInterpolated(){ return this._xSeriesInterpolated; } /** * Get all the interpolated values for each x given by getXSeriesInterpolated. * @return {Array} of interpolated y */ getYSeriesInterpolated(){ return this._ySeriesInterpolated; } /** * Change the radius of the control points * @param {Number} r - the radius in pixel */ setControlPointRadius( r ){ this._controlPointRadius = r; } /** * Set the color of the control point in a specific state * @param {String} state - must be one of: "idle", "hovered" or "grabbed" * @param {String} color - must be css style best is of form "rgba(244, 66, 167, 0.5)" */ setControlPointColor( state, color ){ this._controlPointColor[ state ] = color; } /** * Set the color of the curve in a specific state * @param {String} state - must be one of: "idle" or "moving" * @param {String} color - must be css style best is of form "rgba(244, 66, 167, 0.5)" */ setCurveColor( state, color ){ this._curveColor[ state ] = color; } /** * Set the color of the grid * @param {String} color - must be css style best is of form "rgba(244, 66, 167, 0.5)" */ setGridColor( color ){ this._gridColor = color; } /** * Define the grid step in unit coodinate. Default: 0.33 * @param {Number} */ setGridStep( gs ){ if( gs<=0 || gs >=1){ this._gridStep = 0; }else{ this._gridStep = gs; } this.draw(); } /** * Set the color of the text * @param {String} color - must be css style best is of form "rgba(244, 66, 167, 0.5)" */ setTextColor( color ){ this._textColor = color; } /** * Define the thickness of the curve * @param {Number} t - thickness in pixel */ setCurveThickness( t ){ this._curveThickness = t; } /** * Define the canvas background color * @param {String} color - must be css style best is of form "rgba(244, 66, 167, 0.5)" * Can allso be null/0/false to leave a blank background */ setBackgroundColor( color ){ this._backgroundColor = color; } /** * @param {String} splineType - "natural" or "monotonic" */ setSplineType( splineType ){ if(splineType === "monotonic"){ this._splineConstructor = index.MonotonicCubicSpline; }else{ this._splineConstructor = index.CubicSpline; } } /** * [PRIVATE] * Refresh the position of the pointer we store internally (relative to the canvas) */ _updateMousePosition(evt) { var rect = this._canvas.getBoundingClientRect(); this._mouse = { x: evt.clientX - rect.left, y: this._height - (evt.clientY - rect.top) }; } /** * [EVENT] [PRIVATE] * for when the mouse is moving over the canvas */ _onCanvasMouseMove(evt){ this._updateMousePosition(evt); //console.log( 'moving: ' + this._mouse.x + ',' + this._mouse.y ); // check what control point is the closest from the pointer position var closestPointInfo = this._pointCollection.getClosestFrom( this._mouse ); if(!closestPointInfo) return; // no point is currently grabbed if(this._pointGrabbedIndex == -1){ // the pointer hovers a point if( closestPointInfo.distance <= this._controlPointRadius){ this._pointHoveredIndex = closestPointInfo.index; } // the pointer does not hover a point else{ // ... but maybe it used to hove a point, in this case we want to redraw // to change back the color to idle mode var mustRedraw = false; if( this._pointHoveredIndex != -1) mustRedraw = true; this._pointHoveredIndex = -1; if(mustRedraw) this.draw(); } } // a point is grabbed else{ this._pointGrabbedIndex = this._pointCollection.updatePoint( this._pointGrabbedIndex, this._mouse ); this._pointHoveredIndex = this._pointGrabbedIndex; } // reduce usless drawing if( this._pointHoveredIndex != -1 || this._pointGrabbedIndex != -1){ this.draw(); } // now the buffer is filled (after draw) if( this._pointGrabbedIndex != -1 ){ var grabbedPoint = this._pointCollection.getPoint( this._pointGrabbedIndex ); this._drawCoordinates( Math.round((grabbedPoint.x / this._width)*1000 ) / 1000, Math.round((grabbedPoint.y/this._height)*1000 ) / 1000 ); if(this._onEvents.movePoint) this._onEvents.movePoint( this ); } } /** * [EVENT] [PRIVATE] * for when the mouse is clicked over the canvas */ _onCanvasMouseDown(evt){ //console.log( 'down '); this._mouseDown = true; if( this._pointHoveredIndex != -1 ){ //console.log("grabing a point"); this._pointGrabbedIndex = this._pointHoveredIndex; } } /** * [EVENT] [PRIVATE] * for when the mouse is released over the canvas */ _onCanvasMouseUp(evt){ //console.log( 'up ' ); var aPointWasGrabbed = (this._pointGrabbedIndex != -1); this._mouseDown = false; this._pointGrabbedIndex = -1; this.draw(); if(this._onEvents.releasePoint && aPointWasGrabbed) this._onEvents.releasePoint( this ); } /** * [EVENT] [PRIVATE] * for when we double click on the canvas */ _onCanvasMouseDbclick(evt){ //console.log("dbclick"); this._canvas.focus(); if(this._pointHoveredIndex == -1 ){ var index$$1 = this.add( {x: this._mouse.x / this._width, y: this._mouse.y / this._height} ); this._pointHoveredIndex = index$$1; }else{ this.remove( this._pointHoveredIndex ); this._pointHoveredIndex = -1; this._pointGrabbedIndex = -1; } } /** * [EVENT] [PRIVATE] * for when the mouse is leaving the canvas */ _onCanvasMouseLeave(evt){ /* this._mouse = null; //console.log( "leave" ); this._canvas.blur(); this._canvas.style.border = this._borderStyle.out; this._mouseDown = false; this._pointGrabbedIndex = -1; this._pointHoveredIndex = -1; this.draw(); */ this.draw(); } /** * [EVENT] [PRIVATE] * The mouse enters the canvas */ _onCanvasMouseEnter(evt){ //console.log("enter"); this._canvas.focus(); this._canvas.style.border = this._borderStyle.in; } /** * [EVENT] [PRIVATE] * A keyboard key is released */ _onKeyUp(evt){ // mouse must be inside if(! this._mouse) return; //console.log("pressed: " + evt.key); switch (evt.key) { case "d": this.remove( this._pointHoveredIndex ); break; default: } } /** * Add a point to the collection * @param {Object} pt - of type {x: Number, y: Number} and optionnally the boolean properties "xLocked" and "yLocked". x and y must be in [0, 1] */ add( pt, draw = true ){ var index$$1 = null; if("x" in pt && "y" in pt){ pt.x *= this._width; pt.y *= this._height; index$$1 = this._pointCollection.add( pt ); //console.log("a point is added"); } if( draw ){ this.draw(); } if(this._onEvents.pointAdded) this._onEvents.pointAdded( this ); return index$$1; } /** * Remove a point using its index * @param {Number} index - index of the point to remove (from left to right, starting at 0) */ remove( index$$1 ){ var removedPoint = this._pointCollection.remove( index$$1 ); this.draw(); if(this._onEvents.pointRemoved) this._onEvents.pointRemoved( this ); } /** * Draw the whole canvas */ draw(){ this._ctx.clearRect(0, 0, this._width, this._height); this._fillBackground(); this._drawGrid(); this._drawData(); } /** * [PRIVATE] * Paint the background with a given color */ _fillBackground(){ if(! this._backgroundColor) return; this._ctx.beginPath(); this._ctx.rect(0, 0, this._width, this._height); this._ctx.fillStyle = this._backgroundColor; this._ctx.fill(); } /** * [PRIVATE] * Display xy coordinates on the upper left corner */ _drawCoordinates(x, y){ var textSize = 14 / this._screenRatio; this._ctx.fillStyle = this._textColor; this._ctx.font = textSize + "px courier"; this._ctx.fillText("x: " + x, 10/this._screenRatio, 20/this._screenRatio); this._ctx.fillText("y: " + y, 10/this._screenRatio, 35/this._screenRatio); } /** * [PRIVATE] * Draw the background grid */ _drawGrid(){ var step = this._gridStep; if( step == 0) return; // horitontal grid this._ctx.beginPath(); this._ctx.moveTo(0, 0); for(var i=step*this._height/this._screenRatio; i<this._height/this._screenRatio; i += step*this._height/this._screenRatio){ this._ctx.moveTo(0, Math.round(i) + 0.5/this._screenRatio); this._ctx.lineTo(this._width ,Math.round(i) + 0.5/this._screenRatio ); } this._ctx.moveTo(0, 0); for(var i=step*this._width/this._screenRatio; i<this._width/this._screenRatio; i += step*this._width/this._screenRatio){ this._ctx.moveTo(Math.round(i) + 0.5/this._screenRatio, 0); this._ctx.lineTo(Math.round(i) + 0.5/this._screenRatio , this._height ); } this._ctx.strokeStyle = this._gridColor; this._ctx.lineWidth = 0.5; this._ctx.stroke(); this._ctx.closePath(); } /** * [PRIVATE] * Draw the data on the canvas * @param {Boolean} curve - whether or not we draw the curve * @param {Boolean} control - whether or not we draw the control points */ _drawData( curve = true, control = true){ var xSeries = this._pointCollection.getXseries(); var ySeries = this._pointCollection.getYseries(); var w = this._width; var h = this._height; if(!xSeries.length) return; // drawing the curve if( curve ){ //console.log("draw curve"); this._ctx.beginPath(); this._ctx.moveTo(xSeries[0] / this._screenRatio, (h - ySeries[0]) / this._screenRatio); var splineInterpolator = new this._splineConstructor(xSeries, ySeries); this._xSeriesInterpolated.fill(0); this._ySeriesInterpolated.fill(0); // before the first point (if not at the left of the canvas) for(var x=0; x<Math.ceil(xSeries[0]); x++){ var y = ySeries[0]; // copying the inteprolated values in a buffer this._xSeriesInterpolated[x] = x / w; this._ySeriesInterpolated[x] = y / h; // adjusting y for visual purpose y = y < 0 ? 0.5 : y > h ? h - 0.5 : y; this._ctx.lineTo(x/this._screenRatio, (h - y)/this._screenRatio); } // between the first and the last point for(var x=Math.ceil(xSeries[0]); x<Math.ceil(xSeries[ xSeries.length - 1]); x++){ var y = splineInterpolator.interpolate(x); // copying the inteprolated values in a buffer this._xSeriesInterpolated[x] = x / w; this._ySeriesInterpolated[x] = y / h; // adjusting y for visual purpose y = y < 0 ? 0.5 : y > h ? h - 0.5 : y; this._ctx.lineTo(x/this._screenRatio, (h - y)/this._screenRatio); } // after the last point (if not at the right of the canvas) for(var x=Math.ceil(xSeries[xSeries.length - 1]); x<w; x++){ var y = ySeries[ySeries.length - 1]; // copying the inteprolated values in a buffer this._xSeriesInterpolated[x] = x / w; this._ySeriesInterpolated[x] = y / h; // adjusting y for visual purpose y = y < 0 ? 0.5 : y > h ? h - 0.5 : y; this._ctx.lineTo(x/this._screenRatio, (h - y)/this._screenRatio); } this._ctx.strokeStyle = this._pointGrabbedIndex == -1 ? this._curveColor.idle : this._curveColor.moving; this._ctx.lineWidth = this._curveThickness / this._screenRatio; this._ctx.stroke(); this._ctx.closePath(); } // drawing the control points if( control ){ // control points for(var i=0; i<xSeries.length; i++){ this._ctx.beginPath(); this._ctx.arc( xSeries[i]/this._screenRatio, (h - ySeries[i]) / this._screenRatio, this._controlPointRadius/this._screenRatio, 0, 2*Math.PI ); // drawing a point that is neither hovered nor grabbed if( this._pointHoveredIndex == -1 ){ this._ctx.fillStyle = this._controlPointColor.idle; }else{ // drawing a point that is hovered or grabbed if( i == this._pointHoveredIndex){ // the point is grabbed if( this._mouseDown ){ this._ctx.fillStyle = this._controlPointColor.grabbed; } // the point is hovered else{ this._ctx.fillStyle = this._controlPointColor.hovered; } }else{ this._ctx.fillStyle = this._controlPointColor.idle; } } this._ctx.fill(); this._ctx.closePath(); } } } /** * Get a single interpolated value * @param {Number} x - normalized x (in [0, 1]) * @return {number} the normalized interpolated value */ getValue( x ){ var xSeries = this._pointCollection.getXseries(); var ySeries = this._pointCollection.getYseries(); // before the first x, we return the fist y if( x<= (xSeries[0]/this._width) ){ return ySeries[0] / this._height; }else // after the last x, we return the last y if(x>= (xSeries[xSeries.length-1]/this._width)){ return ySeries[ySeries.length-1] / this._height; } // somwhere in the the series, we interpolate else{ var splineInterpolator = new this._splineConstructor(xSeries, ySeries); return splineInterpolator.interpolate( x * this._width ) / this._height; } } /** * Define an event * @param {String} eventName - name of the event. "movePoint", "releasePoint", "pointAdded" or "pointRemoved". They are both called with this in argument */ on( eventName, callback ){ this._onEvents[ eventName ] = callback; } } /* END of class CanvasSpliner */ // Note: we chose not to export PointCollection exports.CanvasSpliner = CanvasSpliner; Object.defineProperty(exports, '__esModule', { value: true }); }))); //# sourceMappingURL=CanvasSpliner.js.map
mit
jean1187/plantilla_sf2
app/AppKernel.php
1723
<?php use Symfony\Component\HttpKernel\Kernel; use Symfony\Component\Config\Loader\LoaderInterface; class AppKernel extends Kernel { public function registerBundles() { $bundles = array( new Symfony\Bundle\FrameworkBundle\FrameworkBundle(), new Symfony\Bundle\SecurityBundle\SecurityBundle(), new Symfony\Bundle\TwigBundle\TwigBundle(), new Symfony\Bundle\MonologBundle\MonologBundle(), new Symfony\Bundle\SwiftmailerBundle\SwiftmailerBundle(), new Symfony\Bundle\DoctrineBundle\DoctrineBundle(), new Symfony\Bundle\AsseticBundle\AsseticBundle(), new Sensio\Bundle\FrameworkExtraBundle\SensioFrameworkExtraBundle(), new JMS\SecurityExtraBundle\JMSSecurityExtraBundle(), new Symfony\Bundle\DoctrineFixturesBundle\DoctrineFixturesBundle(), new FOS\UserBundle\FOSUserBundle(), new Knp\Bundle\MenuBundle\KnpMenuBundle(), new Empresa\PlantillaBundle\PlantillaBundle(), new Configuration\GralBundle\ConfigurationGralBundle(), ); if (in_array($this->getEnvironment(), array('dev', 'test'))) { $bundles[] = new Acme\DemoBundle\AcmeDemoBundle(); $bundles[] = new Symfony\Bundle\WebProfilerBundle\WebProfilerBundle(); $bundles[] = new Sensio\Bundle\DistributionBundle\SensioDistributionBundle(); $bundles[] = new Sensio\Bundle\GeneratorBundle\SensioGeneratorBundle(); } return $bundles; } public function registerContainerConfiguration(LoaderInterface $loader) { $loader->load(__DIR__.'/config/config_'.$this->getEnvironment().'.yml'); } }
mit
ROFISH/smn-tumblr-admin
config/environments/production.rb
3350
Rails.application.configure do # Settings specified here will take precedence over those in config/application.rb. # Code is not reloaded between requests. config.cache_classes = true # Eager load code on boot. This eager loads most of Rails and # your application in memory, allowing both threaded web servers # and those relying on copy on write to perform better. # Rake tasks automatically ignore this option for performance. config.eager_load = true # Full error reports are disabled and caching is turned on. config.consider_all_requests_local = false config.action_controller.perform_caching = true # Enable Rack::Cache to put a simple HTTP cache in front of your application # Add `rack-cache` to your Gemfile before enabling this. # For large-scale production use, consider using a caching reverse proxy like nginx, varnish or squid. # config.action_dispatch.rack_cache = true # Disable Rails's static asset server (Apache or nginx will already do this). config.serve_static_assets = false # Compress JavaScripts and CSS. config.assets.js_compressor = :uglifier # config.assets.css_compressor = :sass # Do not fallback to assets pipeline if a precompiled asset is missed. config.assets.compile = false # Generate digests for assets URLs. config.assets.digest = true # Version of your assets, change this if you want to expire all your assets. config.assets.version = '1.2' # Specifies the header that your server uses for sending files. # config.action_dispatch.x_sendfile_header = "X-Sendfile" # for apache # config.action_dispatch.x_sendfile_header = 'X-Accel-Redirect' # for nginx # Force all access to the app over SSL, use Strict-Transport-Security, and use secure cookies. # config.force_ssl = true # Set to :debug to see everything in the log. config.log_level = :info # Prepend all log lines with the following tags. # config.log_tags = [ :subdomain, :uuid ] # Use a different logger for distributed setups. # config.logger = ActiveSupport::TaggedLogging.new(SyslogLogger.new) # Use a different cache store in production. # config.cache_store = :mem_cache_store # Enable serving of images, stylesheets, and JavaScripts from an asset server. # config.action_controller.asset_host = "http://assets.example.com" # Precompile additional assets. # application.js, application.css, and all non-JS/CSS in app/assets folder are already added. # config.assets.precompile += %w( search.js ) # Ignore bad email addresses and do not raise email delivery errors. # Set this to true and configure the email server for immediate delivery to raise delivery errors. # config.action_mailer.raise_delivery_errors = false # Enable locale fallbacks for I18n (makes lookups for any locale fall back to # the I18n.default_locale when a translation cannot be found). config.i18n.fallbacks = true # Send deprecation notices to registered listeners. config.active_support.deprecation = :notify # Disable automatic flushing of the log to improve performance. # config.autoflush_log = false # Use default logging formatter so that PID and timestamp are not suppressed. config.log_formatter = ::Logger::Formatter.new # Do not dump schema after migrations. config.active_record.dump_schema_after_migration = false end
mit
coojee2012/pm3
SurveyDesign/JSDW/ApplyAQJDBA/PrjFileList.aspx.cs
2789
using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.UI; using System.Web.UI.WebControls; using Approve.RuleCenter; using EgovaDAO; using Tools; public partial class JSDW_ApplyAQJDBA_PrjFileList : System.Web.UI.Page { EgovaDB dbContext = new EgovaDB(); RCenter rc = new RCenter(); protected void Page_Load(object sender, EventArgs e) { if (!Page.IsPostBack) { if (!string.IsNullOrEmpty(EConvert.ToString(Session["FAppId"]))) { ViewState["FAppId"] = EConvert.ToString(Session["FAppId"]); } ShowTitle(); pageTool tool1 = new pageTool(this.Page); if (EConvert.ToInt(Session["FIsApprove"]) != 0) { tool1.ExecuteScript("btnEnable();"); } } } private void ShowTitle() { var v = from t in dbContext.TC_AJBA_PrjFile orderby t.FId select new { t.FFileName, t.FFileType, t.FSize, t.FCreateTime, t.FId }; Pager1.RecordCount = v.Count(); this.Ent_List.DataSource = v.Skip((Pager1.CurrentPageIndex - 1) * Pager1.PageSize).Take(Pager1.PageSize); Ent_List.DataBind(); } protected void btnReload_Click(object sender, EventArgs e) { ShowTitle(); } protected void App_List_ItemDataBound(object sender, DataGridItemEventArgs e) { if (e.Item.ItemIndex > -1) { e.Item.Cells[1].Text = (e.Item.ItemIndex + 1 + this.Pager1.PageSize * (this.Pager1.CurrentPageIndex - 1)).ToString(); string fid = EConvert.ToString(DataBinder.Eval(e.Item.DataItem, "FID")); e.Item.Cells[2].Text = "<a href='javascript:void(0)' onclick=\"showAddWindow('PrjFile.aspx?fid=" + fid + "',900,700);\">" + e.Item.Cells[2].Text + "</a>"; } } protected void btnDel_Click(object sender, EventArgs e) { pageTool tool = new pageTool(this.Page); tool.DelInfoFromGrid(Ent_List, dbContext.TC_AJBA_PrjFile, tool_Deleting); ShowTitle(); } private void tool_Deleting(System.Collections.Generic.IList<string> FIdList, System.Data.Linq.DataContext context) { dbContext = new EgovaDB(); if (dbContext != null) { var para = dbContext.TC_AJBA_PrjFile.Where(t => FIdList.ToArray().Contains(t.FId)); dbContext.TC_AJBA_PrjFile.DeleteAllOnSubmit(para); } } protected void Pager1_PageChanging(object src, Wuqi.Webdiyer.PageChangingEventArgs e) { Pager1.CurrentPageIndex = e.NewPageIndex; ShowTitle(); } }
mit
teohm/natives
spec/natives/catalog_spec.rb
4375
require 'spec_helper' require 'natives/catalog' describe Natives::Catalog do describe "#new" do it "loads catalogs" do Natives::Catalog.any_instance.should_receive(:reload) Natives::Catalog.new('rubygems', 'mac_os_x', '10.7.5', 'homebrew') end it "requires caller to provide platform and package provider details" do catalog = Natives::Catalog.new('rubygems', 'mac_os_x', '10.7.5', 'homebrew') expect(catalog.name).to eq('rubygems') expect(catalog.platform).to eq('mac_os_x') expect(catalog.platform_version).to eq('10.7.5') expect(catalog.package_provider).to eq('homebrew') end end describe "#reload" do it "reloads catalogs from default catalog paths" do loader = double() loader. should_receive(:load_from_paths). with([ Natives::Catalog::CATALOG_PATH_IN_GEM, File.absolute_path(File.join(Dir.pwd, 'natives-catalogs')) ]). and_return({ 'rubygems' => {'foo' => {'key' => 'value'}}, 'npm' => {'bar' => {'key' => 'value'}} }) catalog = Natives::Catalog.new('rubygems', 'mac_os_x', '10.7.5', 'homebrew', loader: loader) expect(catalog.to_hash).to eq({'foo' => {'key' => 'value'}}) end it "reloads catalogs from given working directory" do loader = double() loader. should_receive(:load_from_paths). with([ Natives::Catalog::CATALOG_PATH_IN_GEM, '/path/to/working_dir/natives-catalogs' ]). and_return({ 'rubygems' => {'foo' => {'key' => 'value'}}, 'npm' => {'bar' => {'key' => 'value'}} }) catalog = Natives::Catalog.new('rubygems', 'mac_os_x', '10.7.5', 'homebrew', loader: loader, working_dir: '/path/to/working_dir') expect(catalog.to_hash).to eq({'foo' => {'key' => 'value'}}) end end describe "#to_hash" do before do Natives::Catalog::Loader.any_instance. stub(:load_from_paths). and_return({ 'rubygems' => {'foo' => {'key' => 'value'}}, 'npm' => {'bar' => {'key' => 'value'}} }) end it "returns catalog hash of the specified catalog name" do catalog = Natives::Catalog.new("npm", nil, nil, nil) expect(catalog.to_hash).to eq({'bar' => {'key' => 'value'}}) end it "returns empty hash if the sepcified catalog not found" do catalog = Natives::Catalog.new("notfound", nil, nil, nil) expect(catalog.to_hash).to eq({}) end end describe "#native_packages_for" do before do Natives::Catalog::Loader.any_instance. stub(:load_from_paths). and_return({ 'rubygems' => { 'nokogiri' => { 'apt' => { 'ubuntu' => { '13.10' => 'value1', 'default' => 'value2' } } }, 'curb' => { 'apt' => { 'ubuntu' => { 'default' => 'value3' } } } }, }) end it "returns native packages for the given catalog entry name" do catalog = Natives::Catalog.new(:rubygems, 'ubuntu', '13.10', 'apt') expect(catalog.native_packages_for('nokogiri')).to eq(['value1']) end it "returns empty list if the given catalog entry name does not exist" do catalog = Natives::Catalog.new(:rubygems, 'ubuntu', '13.10', 'apt') expect(catalog.native_packages_for('notfound')).to eq([]) end it "return native packages for the given catalog entry name list" do catalog = Natives::Catalog.new(:rubygems, 'ubuntu', '13.10', 'apt') expect(catalog.native_packages_for( 'nokogiri', 'notfound', 'curb')).to eq(['value1', 'value3']) end it "return native packages for the given catalog entry name array" do catalog = Natives::Catalog.new(:rubygems, 'ubuntu', '13.10', 'apt') expect(catalog.native_packages_for( ['nokogiri', 'notfound', 'curb'])).to eq(['value1', 'value3']) end end end
mit
Stillat/Collection
src/Collection/Traits/Macroable.php
2121
<?php namespace Collection\Traits; use Closure; use BadMethodCallException; trait Macroable { /** * The registered string macros. * * @var array */ protected static $macros = []; /** * Register a custom macro. * * @param string $name * @param callable $macro * * @return void */ public static function macro($name, callable $macro) { static::$macros[$name] = $macro; } /** * Checks if macro is registered. * * @param string $name * * @return bool */ public static function hasMacro($name) { return isset(static::$macros[$name]); } /** * Dynamically handle calls to the class. * * @param string $method * @param array $parameters * * @return mixed * * @throws \BadMethodCallException */ public static function __callStatic($method, $parameters) { if (static::hasMacro($method)) { if (static::$macros[$method] instanceof Closure) { return call_user_func_array(Closure::bind(static::$macros[$method], null, get_called_class()), $parameters); } else { return call_user_func_array(static::$macros[$method], $parameters); } } throw new BadMethodCallException("Method {$method} does not exist."); } /** * Dynamically handle calls to the class. * * @param string $method * @param array $parameters * * @return mixed * * @throws \BadMethodCallException */ public function __call($method, $parameters) { if (static::hasMacro($method)) { if (static::$macros[$method] instanceof Closure) { return call_user_func_array(static::$macros[$method]->bindTo($this, get_class($this)), $parameters); } else { return call_user_func_array(static::$macros[$method], $parameters); } } throw new BadMethodCallException("Method {$method} does not exist."); } }
mit
diasdavid/nitd
modules/fetchIssues.js
3350
require('colors'); var request = require('request'); var Issue = require('model').getModelByName('Issue'); var secret = require('./../secret.json').secret; var repo = 'joyent/node'; var options = { url: 'https://api.github.com/repos/' + repo + '/issues', headers: { 'User-Agent': secret.useragent }, qs: { state: 'open', page: 1, access_token: secret.accesstoken } }; module.exports = function(state) { if(!secret.useragent || !secret.accesstoken){ return console.log('No access credentials defined'); } if (state) { options.qs.state = state; } request.get(options, receiveIssues); }; function receiveIssues(err, response, body) { if (err) { return console.log(err); } parseIssues(body); if (response.headers.link && response.headers.link.indexOf('next') !== -1){ // there is more to fetch options.qs.page = options.qs.page + 1; request.get(options, receiveIssues); } else { options.qs.page = 1; } } function parseIssues(body) { if(body.indexOf('API rate limit exceeded') !== -1) { console.log('API rate limit exceeded'); process.exit(1); } JSON.parse(body).forEach(storeIssue); } function storeIssue(issue) { // 1. Verify if exists Issue.all({number: issue.number}, gotIssues(issue)); function gotIssues(_issue) { var issue = _issue; return function (err, result) { if (err) { return console.log(err); } if (result.length > 0) { // 1.a if yes - update result[0].url = issue.url; result[0].htmlUrl = issue.html_url; result[0].state = issue.state; result[0].title = issue.title; result[0].body = issue.body; result[0].user = issue.user; result[0].labels = issue.labels; result[0].assignee = issue.assignee; result[0].milestone = issue.milestone; result[0].comments = issue.comments; result[0].pullRequest = issue.pull_request; result[0].closedAt = issue.closed_at; result[0].createdAt = issue.created_at; result[0].updatedAt = issue.updated_at; result[0].save(function (err, data) { if (err) { return console.log(err); } console.log('Updated Issue: '.green+issue.number + ' ' + new Date()); }); } else { // 1.b if not - store var cleanIssue = {}; cleanIssue.url = issue.url; cleanIssue.htmlUrl = issue.html_url; cleanIssue.number = issue.number; cleanIssue.state = issue.state; cleanIssue.title = issue.title; cleanIssue.body = issue.body; cleanIssue.user = issue.user; cleanIssue.labels = issue.labels; cleanIssue.assignee = issue.assignee; cleanIssue.milestone = issue.milestone; cleanIssue.comments = issue.comments; cleanIssue.pullRequest = issue.pull_request; cleanIssue.closedAt = issue.closed_at; cleanIssue.createdAt = issue.created_at; cleanIssue.updatedAt = issue.updated_at; var newIssue = Issue.create(cleanIssue); newIssue.save( function (err, data) { if (err) { return console.log(err); } console.log('New Issue Saved: '.green+data.number + ' ' + new Date()); }); } }; } }
mit
JMdeKlerk/SMSIM
Windows/Conversation.Designer.cs
4332
namespace SMSIM { partial class Conversation { /// <summary> /// Required designer variable. /// </summary> private System.ComponentModel.IContainer components = null; /// <summary> /// Clean up any resources being used. /// </summary> /// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param> protected override void Dispose(bool disposing) { if (disposing && (components != null)) { components.Dispose(); } base.Dispose(disposing); } #region Windows Form Designer generated code /// <summary> /// Required method for Designer support - do not modify /// the contents of this method with the code editor. /// </summary> private void InitializeComponent() { System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(Conversation)); this.send = new System.Windows.Forms.Button(); this.entry = new System.Windows.Forms.TextBox(); this.messageBox = new System.Windows.Forms.RichTextBox(); this.SuspendLayout(); // // send // this.send.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Right))); this.send.Location = new System.Drawing.Point(247, 206); this.send.Name = "send"; this.send.Size = new System.Drawing.Size(75, 23); this.send.TabIndex = 0; this.send.Text = "Send"; this.send.UseVisualStyleBackColor = true; this.send.Click += new System.EventHandler(this.send_Click); // // entry // this.entry.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Left) | System.Windows.Forms.AnchorStyles.Right))); this.entry.Location = new System.Drawing.Point(12, 208); this.entry.Name = "entry"; this.entry.Size = new System.Drawing.Size(229, 20); this.entry.TabIndex = 1; // // messageBox // this.messageBox.Anchor = ((System.Windows.Forms.AnchorStyles)((((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Bottom) | System.Windows.Forms.AnchorStyles.Left) | System.Windows.Forms.AnchorStyles.Right))); this.messageBox.BackColor = System.Drawing.SystemColors.ButtonHighlight; this.messageBox.Font = new System.Drawing.Font("Microsoft Sans Serif", 8F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.messageBox.Location = new System.Drawing.Point(13, 13); this.messageBox.Name = "messageBox"; this.messageBox.ReadOnly = true; this.messageBox.Size = new System.Drawing.Size(309, 187); this.messageBox.TabIndex = 2; this.messageBox.Text = ""; // // Conversation // this.AcceptButton = this.send; this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F); this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font; this.ClientSize = new System.Drawing.Size(334, 241); this.Controls.Add(this.messageBox); this.Controls.Add(this.entry); this.Controls.Add(this.send); this.Icon = ((System.Drawing.Icon)(resources.GetObject("$this.Icon"))); this.Name = "Conversation"; this.StartPosition = System.Windows.Forms.FormStartPosition.CenterParent; this.Text = "Conversation"; this.FormClosing += new System.Windows.Forms.FormClosingEventHandler(this.Conversation_FormClosing); this.ResumeLayout(false); this.PerformLayout(); } #endregion private System.Windows.Forms.Button send; private System.Windows.Forms.TextBox entry; private System.Windows.Forms.RichTextBox messageBox; } }
mit
ragingwind/hyphenize
index.js
549
'use strict'; module.exports = function (h) { return h.replace(/^(\W|-|\.)*/g, '') .replace(/(|\W|\s)*$/g, '') .replace(/([A-Z])([A-Z])([a-z0-9]){1,2}./g, function (match) { return match.substr(0, 1) + '-' + match.substr(1).toLowerCase(); }) .replace(/([a-z\d])([A-Z])/g, function (match, a, b) { return a + (match.indexOf('-') >= 0 ? '' : '-') + b.toLowerCase(); }) .replace(/([a-z0-9])([A-Z\d])([a-z0-9]){1,2}./g, function (match, a, b) { return a.toLowerCase() + '-' + b; }) .replace(/ |\./g, '-') .toLowerCase(); };
mit
manland/angular2-bien-ou-pas-bien
app/client/8.1-testDi/Talks/Talks.spec.ts
955
import {beforeEachProviders, inject, async, it, describe} from "@angular/core/testing"; import {Server} from "../Server"; import {Observable} from "rxjs/Observable"; import {TalkModel} from "../Talk/Talk"; import {Talks} from "../Talks/Talks"; import "rxjs/add/observable/of"; const fakeTalks = [{id: 0, speaker: {avatar: 'avatar'}, title: 'title', description: 'description'}]; export class FakeServer implements Server { getTalks(): Observable<TalkModel> { return Observable.of(...fakeTalks); } saveTalk(): Promise<TalkModel> { throw new Error('Server.saveTalk() called'); } } describe('Talks/Talks.spec', () => { beforeEachProviders(() => [ [{ provide: Server, useClass: FakeServer }], Talks ]); it('Load talks', async(inject([Talks], (talks: Talks) => { expect(talks.talks.length).toEqual(fakeTalks.length); expect(talks.talks[0]).toEqual(fakeTalks[0]); }))); });
mit
lukeapage/rollup
test/form/unmodified-default-exports-function-argument/_expected/umd.js
374
(function (global, factory) { typeof exports === 'object' && typeof module !== 'undefined' ? factory() : typeof define === 'function' && define.amd ? define(factory) : factory(); }(this, function () { 'use strict'; var foo = function () { return 42; }; function bar () { return contrivedExample( foo ); } var answer = foo(); var somethingElse = bar(); }));
mit
tscolari/docode
docode/runner.go
782
package docode import ( "github.com/tscolari/docode/config" "github.com/tscolari/docode/runtime" ) type Runner struct { config config.Configuration docker runtime.Wrapper } func NewWithWrapper(config config.Configuration, docker runtime.Wrapper) *Runner { return &Runner{ config: config, docker: docker, } } func New(configuration config.Configuration) *Runner { return &Runner{ config: configuration, docker: runtime.New(), } } func (r *Runner) Run() error { if !r.config.DontPull { err := r.docker.PullImage(r.config.ImageName, r.config.ImageTag) if err != nil { return err } } return r.docker.Run( r.config.RunList, r.config.Ports, r.config.ImageName, r.config.ImageTag, r.config.SSHKey, r.config.EnvSets, r.config.MountSets, ) }
mit
jrechandi/sundahipP
src/Sunahip/LicenciaBundle/Entity/AdmClasfLicencias.php
8838
<?php namespace Sunahip\LicenciaBundle\Entity; use Doctrine\ORM\Mapping as ORM; /** * AdmClasfLicencias * * @ORM\Table(name="adm_clasf_licencias", indexes={@ORM\Index(name="fk_adm_clasf_licencias_adm_tipos_licencias1_idx", columns={"adm_tipos_licencias_id"})}) * @ORM\Entity */ class AdmClasfLicencias { /** * @var integer * * @ORM\Column(name="id", type="integer", nullable=false) * @ORM\Id * @ORM\GeneratedValue(strategy="IDENTITY") */ private $id; /** * @var string * * @ORM\Column(name="clasf_licencia", type="string", length=45, nullable=false) */ private $clasfLicencia; /** * @var integer * * @ORM\Column(name="solicitud_ut", type="integer", nullable=false) */ private $solicitudUt; /** * @var integer * * @ORM\Column(name="otorgamiento_ut", type="integer", nullable=false) */ private $otorgamientoUt; /** * @var string * * @ORM\Column(name="status", type="string", length=45, nullable=false) */ private $status; /** * @var string * * @ORM\Column(name="cod_licencia", type="string", length=45, nullable=false) */ private $codLicencia; /** * @var integer * * @ORM\Column(name="cod_actual", type="integer", nullable=true) */ private $codActual=0; /** * @var \AdmTiposLicencias * * @ORM\ManyToOne(targetEntity="AdmTiposLicencias") * @ORM\JoinColumns({ * @ORM\JoinColumn(name="adm_tipos_licencias_id", referencedColumnName="id") * }) */ private $admTiposLicencias; /** * @var \Doctrine\Common\Collections\Collection * * @ORM\ManyToMany(targetEntity="AdmJuegosExplotados", inversedBy="admClasfLicencias") * @ORM\JoinTable(name="adm_clasf_licencias_has_adm_juegos_explotados", * joinColumns={ * @ORM\JoinColumn(name="adm_clasf_licencias_id", referencedColumnName="id") * }, * inverseJoinColumns={ * @ORM\JoinColumn(name="adm_juegos_explotados_id", referencedColumnName="id") * } * ) */ private $admJuegosExplotados; /** * @var \Doctrine\Common\Collections\Collection * * @ORM\ManyToMany(targetEntity="AdmRecaudosLicencias", inversedBy="admClasfLicencias") * @ORM\JoinTable(name="adm_clasf_licencias_has_adm_recaudos_licencias", * joinColumns={ * @ORM\JoinColumn(name="adm_clasf_licencias_id", referencedColumnName="id") * }, * inverseJoinColumns={ * @ORM\JoinColumn(name="adm_recaudos_licencias_id", referencedColumnName="id") * } * ) */ private $admRecaudosLicencias; /** * @var boolean * * @ORM\Column(name="has_operadora", type="boolean", nullable=true) */ private $hasOperadora; /** * @var boolean * * @ORM\Column(name="has_hipodromo", type="boolean", nullable=true) */ private $hasHipodromo; /** * Constructor */ public function __construct() { $this->admJuegosExplotados = new \Doctrine\Common\Collections\ArrayCollection(); $this->admRecaudosLicencias = new \Doctrine\Common\Collections\ArrayCollection(); } /** * @return string */ public function __toString() { return $this->getClasfLicencia(); } /** * Get id * * @return integer */ public function getId() { return $this->id; } /** * Set clasfLicencia * * @param string $clasfLicencia * @return AdmClasfLicencias */ public function setClasfLicencia($clasfLicencia) { $this->clasfLicencia = $clasfLicencia; return $this; } /** * Get clasfLicencia * * @return string */ public function getClasfLicencia() { return $this->clasfLicencia; } /** * Set solicitudUt * * @param string $solicitudUt * @return AdmClasfLicencias */ public function setSolicitudUt($solicitudUt) { $this->solicitudUt = $solicitudUt; return $this; } /** * Get solicitudUt * * @return string */ public function getSolicitudUt() { return $this->solicitudUt; } /** * Set otorgamientoUt * * @param string $otorgamientoUt * @return AdmClasfLicencias */ public function setOtorgamientoUt($otorgamientoUt) { $this->otorgamientoUt = $otorgamientoUt; return $this; } /** * Get otorgamientoUt * * @return string */ public function getOtorgamientoUt() { return $this->otorgamientoUt; } /** * Set status * * @param string $status * @return AdmClasfLicencias */ public function setStatus($status) { $this->status = $status; return $this; } /** * Get status * * @return string */ public function getStatus() { return $this->status; } /** * Set codLicencia * * @param string $status * @return AdmClasfLicencias */ public function setCodLicencia($codLicencia) { $this->codLicencia = $codLicencia; return $this; } /** * Get codLicencia * * @return string */ public function getCodLicencia() { return $this->codLicencia; } /** * Set codActual * * @param integer $codActual * @return AdmClasfLicencias */ public function setCodActual($codActual) { $this->codActual = $codActual; return $this; } /** * Get codActual * * @return integer */ public function getCodActual() { return $this->codActual; } /** * Set admTiposLicencias * * @param \Sunahip\LicenciaBundle\Entity\AdmTiposLicencias $admTiposLicencias * @return AdmClasfLicencias */ public function setAdmTiposLicencias(\Sunahip\LicenciaBundle\Entity\AdmTiposLicencias $admTiposLicencias = null) { $this->admTiposLicencias = $admTiposLicencias; return $this; } /** * Get admTiposLicencias * * @return \Sunahip\LicenciaBundle\Entity\AdmTiposLicencias */ public function getAdmTiposLicencias() { return $this->admTiposLicencias; } /** * Add admJuegosExplotados * * @param \Sunahip\LicenciaBundle\Entity\AdmJuegosExplotados $admJuegosExplotados * @return AdmClasfLicencias */ public function addAdmJuegosExplotado(\Sunahip\LicenciaBundle\Entity\AdmJuegosExplotados $admJuegosExplotados) { $this->admJuegosExplotados[] = $admJuegosExplotados; return $this; } /** * Remove admJuegosExplotados * * @param \Sunahip\LicenciaBundle\Entity\AdmJuegosExplotados $admJuegosExplotados */ public function removeAdmJuegosExplotado(\Sunahip\LicenciaBundle\Entity\AdmJuegosExplotados $admJuegosExplotados) { $this->admJuegosExplotados->removeElement($admJuegosExplotados); } /** * Get admJuegosExplotados * * @return \Doctrine\Common\Collections\Collection */ public function getAdmJuegosExplotados() { return $this->admJuegosExplotados; } /** * Add admRecaudosLicencias * * @param \Sunahip\LicenciaBundle\Entity\AdmRecaudosLicencias $admRecaudosLicencias * @return AdmClasfLicencias */ public function addAdmRecaudosLicencia(\Sunahip\LicenciaBundle\Entity\AdmRecaudosLicencias $admRecaudosLicencias) { $this->admRecaudosLicencias[] = $admRecaudosLicencias; return $this; } /** * Remove admRecaudosLicencias * * @param \Sunahip\LicenciaBundle\Entity\AdmRecaudosLicencias $admRecaudosLicencias */ public function removeAdmRecaudosLicencia(\Sunahip\LicenciaBundle\Entity\AdmRecaudosLicencias $admRecaudosLicencias) { $this->admRecaudosLicencias->removeElement($admRecaudosLicencias); } /** * Get admRecaudosLicencias * * @return \Doctrine\Common\Collections\Collection */ public function getAdmRecaudosLicencias() { return $this->admRecaudosLicencias; } public function setHasOperadora($hasOperadora) { $this->hasOperadora = $hasOperadora; return $this; } public function getHasOperadora() { return $this->hasOperadora; } public function setHasHipodromo($hasHipodromo) { $this->hasHipodromo = $hasHipodromo; return $this; } public function getHasHipodromo() { return $this->hasHipodromo; } }
mit
cbetta/primo
spec/primo/template_spec.rb
2538
require "spec_helper" describe Primo::Template do describe ".for" do it "should initialize a template with the right name and remote" do template = Primo::Template.for "foo-bar" expect(template.filename).to be == "bar.rb" expect(template.remote.name).to be == "foo" end end describe ".list" do it "should return a list of templates for every configured remote" do FileUtils.mkdir_p("#{Primo::Remote::DIRECTORY}/default") FileUtils.touch "#{Primo::Remote::DIRECTORY}/default/foobar.rb" FileUtils.mkdir_p("#{Primo::Remote::DIRECTORY}/foo") FileUtils.touch "#{Primo::Remote::DIRECTORY}/foo/bar.rb" Primo::Config.instance.config[:remotes]["foo"] = "some_url" expect(Primo::Template.list).to have(2).item end end context "with an instance" do before :each do @template = Primo::Template.new "bar.rb", Primo::Remote.new("foo") end describe "#initialize" do it "should set the filename and the remote" do expect(@template.filename).to be == "bar.rb" expect(@template.remote.name).to be == "foo" end end describe "#display_name" do it "should return the display name" do expect(@template.display_name).to be == "foo-bar" end end describe "#name" do it "should return the template name" do expect(@template.name).to be == "bar" end end describe "#expanded_filename" do it "should return the template's full filename" do expect(@template.expanded_filename).to be == File.expand_path("~/.primo_remotes/foo/bar.rb") end end describe "#default" do before do Primo::Template.should_receive(:list).and_return([Primo::Template.for("default-rails")]) end it "should set the default" do expect(Primo::Template.default).not_to be == "default-rails" Primo::Template.default = "default-rails" expect(Primo::Template.default).to be == "default-rails" end it "should error if the default template doesn't exist" do expect(-> {Primo::Template.default = "default-foo"}).to raise_error(ArgumentError) end end describe "#read" do before do FileUtils.mkdir_p("#{Primo::Remote::DIRECTORY}/#{@template.remote.name}") File.open(@template.expanded_filename, 'w') { |file| file.write("FOOBAR") } end it "should return the template content" do expect(@template.read).to be == "FOOBAR" end end end end
mit
letid/framework
src/form/database.php
5470
<?php namespace letId\form; trait database { // NOTE: DONE -> SIGNING UP public function signup($Id=null) { if ($this->responseTerminal()) { $db = avail::$database->insert($this->formPost)->to($this->table)->execute()->rowsId(); $this->responseTask($db->rowsId,$Id,$db,array('Inserted!','Unchanged!')); } return $this; } // NOTE: DONE -> SIGNING IN public function signin($Id=null) { if ($this->responseTerminal()) { $db = avail::$database->select()->from($this->table)->where($this->formPost)->execute()->fetchAll()->rowsCount(); if ($db->rowsCount) { $row = $db->rows[0]; if (isset($row['status'])) { if ($row['status'] > 0) { if(isset($row['logs'])) { avail::$database->update(array_filter($row, function(&$v, $k) { if ($k == 'logs') { return $v=$v+1; } if ($k == 'modified') { return $v=date('Y-m-d G:i:s'); } }, ARRAY_FILTER_USE_BOTH))->to($this->table)->where($this->formPost)->execute()->rowsAffected(); } } else { // NOTE: user account has been deactivated, and needed to activate! } $userCookie = array_intersect_key($row, array_flip(array('userid','password'))); avail::session()->delete(); avail::$authentication->usersCookie()->set($userCookie); // $this->responseTaskerror($Id,$db,'Ok....'); // setcookie("testme",serialize($userCookie),time()+199); // print_r($userCookie); } } else { $this->message = avail::language('invalid VALUE')->get(array( 'value'=>avail::arrays(array_keys($this->formPost))->to_sentence(null, ' / ') )); $this->responseTaskerror($Id,$db,$this->message); } } return $this; } // NOTE: UNDONE public function signout() { return $this; } public function forgotpassword() { if ($this->responseTerminal()) { $db = avail::$database->select('*')->from($this->table)->where($this->formPost)->execute()->rowsId()->fetchObject(); if ($db->rowsCount) { $taskId = avail::assist('password')->sha1($db->rows->userid); $taskCode = avail::assist()->uniqid(); $taskQuery = array( 'taskid' => 'password-user-'.$db->rows->userid, 'code'=> $taskCode, 'status' => 1, 'userid' => $db->rows->userid, 'subject' => 'reset password' ); $status = avail::mail(array('email/reset.password'=>$taskQuery))->send(); if($status) { avail::$database->insert( $taskQuery )->to( 'tasks' )->duplicateUpdate( $taskQuery )->execute(); } $msg = array(avail::language('Verification code has been sent')->get(),avail::language('Mail could not send')->get()); $this->responseTask($status,$Id,$db,$msg); } else { $this->message = avail::language('no VALUE exists')->get(array( 'value'=>avail::arrays($this->formPost)->to_sentence() )); $this->responseTaskerror($Id,$db,$this->message); } } return $this; } public function changepassword($Id=null) { if ($this->responseTerminal()) { $db = avail::$database->update($this->formPost)->to($this->table)->where($this->formId)->execute()->rowsAffected(); if ($db->rowsAffected) { avail::$authentication->usersCookie()->set(array_merge($this->formId,$this->formPost)); } $this->responseTask($db->rowsAffected,$Id,$db,array('Changed!','Unchanged!')); } return $this; } public function resetpassword($Id=null) { if ($this->responseTerminal()) { $db = avail::$database->select()->from('tasks')->where('code',$this->formPost['code'])->execute()->rowsCount()->fetchObject(); if ($db->rowsCount) { $update = avail::$database->update( array('password'=>$this->formPost['password'], 'status'=>1) )->to($this->table)->where('userid',$db->rows->userid)->execute()->rowsAffected(); if ($update->rowsAffected) { avail::$database->delete()->from('tasks')->where('taskid',$db->rows->taskid)->execute(); } $this->responseTask($update->rowsAffected,$Id,$db,array('Reseted!','Unchanged!')); } else { $this->responseTaskerror($Id,$db,'Invalid verification code!'); } } return $this; } // NOTE: DONE -> INSERTING public function insert($Id=null) { if ($this->responseTerminal()) { $db = avail::$database->insert($this->formPost)->to($this->table)->execute()->rowsId(); $this->responseTask($db->rowsId,$Id,$db,array('Inserted!','Unchanged!')); } return $this; } // NOTE: DONE -> UPDATING public function update($Id=null) { if ($this->responseTerminal()) { $db = avail::$database->update($this->formPost)->to($this->table)->where($this->formId)->execute()->rowsAffected(); $this->responseTask($db->rowsAffected,$Id,$db,array('Updated!','Unchanged!')); } return $this; } // NOTE: DONE -> INSERTING OR UPDATING public function insertOrupdate($Id=null) { if ($this->responseTerminal()) { $db = avail::$database->insert( array_merge($this->formId,$this->formPost) )->to( $this->table )->duplicateUpdate( $this->formPost )->execute()->rowsAffected(); $this->responseTask($db->result,$Id,$db,array('Updated!','Unchanged!')); } return $this; } // NOTE: DONE -> DELETING public function delete($Id=null) { if ($this->responseTerminal()) { $db = avail::$database->delete()->from($this->table)->where($this->formId)->execute()->rowsAffected(); $this->responseTask($db->rowsAffected,$Id,$db,array('Deleted!','Unchanged!')); } return $this; } }
mit
RISCfuture/hierarchy
spec/spec_helper.rb
735
require 'bundler' Bundler.require :default, :development require 'active_support' require 'active_record' $LOAD_PATH.unshift(File.dirname(__FILE__)) $LOAD_PATH.unshift(File.join(File.dirname(__FILE__), '..', 'lib')) require 'hierarchy' ActiveRecord::Base.establish_connection( adapter: 'postgresql', database: 'hierarchy_test', username: 'hierarchy_tester' ) system "echo \"CREATE EXTENSION IF NOT EXISTS ltree\" | psql hierarchy_test" class Model < ActiveRecord::Base include Hierarchy end RSpec.configure do |config| config.before(:each) do Model.connection.execute "DROP TABLE IF EXISTS models" Model.connection.execute "CREATE TABLE models (id SERIAL PRIMARY KEY, path LTREE NOT NULL DEFAULT '')" end end
mit
Data2Semantics/nodes
nodes/src/test/java/org/nodes/LightUGraphTest.java
13098
package org.nodes; import static org.junit.Assert.*; import java.io.File; import java.io.IOException; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.Collections; import java.util.HashSet; import java.util.List; import java.util.Set; import org.junit.Test; import org.nodes.data.Data; import org.nodes.data.Examples; import nl.peterbloem.kit.FrequencyModel; import nl.peterbloem.kit.Functions; import nl.peterbloem.kit.Global; import nl.peterbloem.kit.Pair; import nl.peterbloem.kit.Series; public class LightUGraphTest { @Test public void testMapDTGraph() { UGraph<String> graph = new LightUGraph<String>(); assertEquals(0, graph.size()); assertEquals(0, graph.numLinks()); } @Test public void testToString() { UGraph<String> graph = new LightUGraph<String>(); UNode<String> a = graph.add("a"), b = graph.add("b"); graph.add("c"); a.connect(b); System.out.println(graph); } @Test public void starTest() { UGraph<String> graph = new LightUGraph<String>(); UNode<String> a = graph.add("a"), b = graph.add("b"), c = graph.add("c"), d = graph.add("d"), e = graph.add("e"); b.connect(a); c.connect(a); d.connect(a); e.connect(a); System.out.println(graph); e.disconnect(a); System.out.println(graph); System.out.println(a.index()); a.remove(); System.out.println(graph); } @Test public void testRemove() { UGraph<String> graph = new LightUGraph<String>(); UNode<String> a = graph.add("a"), b = graph.add("b"), c = graph.add("c"), d = graph.add("d"), e = graph.add("e"); b.connect(a); c.connect(a); d.connect(a); e.connect(a); System.out.println(graph.numLinks() + " " + graph.size()); assertEquals(4, graph.numLinks()); assertEquals(5, graph.size()); a.remove(); assertEquals(0, graph.numLinks()); assertEquals(4, graph.size()); } @Test public void testConnected() { UGraph<String> graph = new LightUGraph<String>(); UNode<String> a = graph.add("a"), b = graph.add("b"), c = graph.add("c"); a.connect(b); a.connect(c); assertTrue(a.connected(b)); assertFalse(a.connected(a)); assertTrue(b.connected(a)); assertTrue(a.connected(c)); assertTrue(c.connected(a)); assertFalse(b.connected(c)); assertFalse(c.connected(b)); } @Test public void testLinks() { UGraph<String> graph = new LightUGraph<String>(); UNode<String> a = graph.add(null), b = graph.add(null), c = graph.add(null); a.connect(b); a.connect(c); a.connect(c); assertEquals(0, a.links(a).size()); assertEquals(1, a.links(b).size()); assertEquals(1, b.links(a).size()); assertEquals(2, a.links(c).size()); assertEquals(2, c.links(a).size()); } @Test public void testLinkRemove() { UGraph<String> graph = new LightUGraph<String>(); UNode<String> a = graph.add(null), b = graph.add(null), c = graph.add(null); a.connect(b); a.connect(c); a.connect(c); ULink<String> link = a.links(c).iterator().next(); link.remove(); assertEquals(2, graph.numLinks()); assertEquals(1, a.links(c).size()); assertTrue(link.dead()); int n = 0; for(ULink<String> l : graph.links()) n++; assertEquals(2, n); } @Test public void testEquals() { UGraph<String> g1 = new LightUGraph<String>(); g1.add("a"); g1.add("b"); g1.add("c"); g1.node("a").connect(g1.node("b")); g1.node("b").connect(g1.node("c")); UGraph<String> g2 = new LightUGraph<String>(); g2.add("a"); g2.add("b"); g2.add("c"); g2.node("b").connect(g2.node("c")); g2.node("a").connect(g2.node("b")); assertTrue(g1.equals(g2)); g2.node("a").connect(g2.node("c")); assertFalse(g1.equals(g2)); } @Test public void testNotEquals() { UGraph<String> g1 = new LightUGraph<String>(); UTGraph<String, String> g2 = new MapUTGraph<String, String>(); assertFalse(g1.equals(g2)); assertFalse(g2.equals(g1)); } // @Test public void copy() throws IOException { UGraph<String> data = Data.edgeList(new File("/Users/Peter/Documents/datasets/graphs/neural/celegans.txt"), false); data = Graphs.blank(data, ""); data = Graphs.toSimpleUGraph(data); Data.writeEdgeList(data, new File("/Users/Peter/Documents/datasets/graphs/neural/simple.txt")); } @Test public void testCopy() { UGraph<String> graph = new MapUTGraph<String, String>(); UNode<String> a = graph.add("a"); UNode<String> b = graph.add("b"); UNode<String> c = graph.add("c"); a.connect(a); b.connect(c); c.connect(a); a.connect(c); a.connect(c); { int numLinks = 0; for(Link<String> link : graph.links()) numLinks++; assertEquals(5, numLinks); assertEquals(graph.numLinks(), numLinks); } graph = LightUGraph.copy(graph); { int numLinks = 0; for(Link<String> link : graph.links()) numLinks++; assertEquals(5, numLinks); assertEquals(graph.numLinks(), numLinks); } graph = LightUGraph.copy(graph); { int numLinks = 0; for(Link<String> link : graph.links()) numLinks++; assertEquals(5, numLinks); assertEquals(graph.numLinks(), numLinks); } } @Test public void testCopy2() { UGraph<String> graph = Examples.yeast(); { int numLinks = 0; for(Link<String> link : graph.links()) numLinks++; assertEquals(2277, numLinks); assertEquals(graph.numLinks(), numLinks); } graph = LightUGraph.copy(graph); { int numLinks = 0; for(Link<String> link : graph.links()) numLinks++; assertEquals(2277, numLinks); assertEquals(graph.numLinks(), numLinks); } graph = LightUGraph.copy(graph); { int numLinks = 0; for(Link<String> link : graph.links()) numLinks++; assertEquals(2277, numLinks); assertEquals(graph.numLinks(), numLinks); } } @Test public void testNumLinks() { UGraph<String> graph = Examples.yeast(); graph = LightUGraph.copy(graph); int numLinks = 0; for(Link<String> link : graph.links()) numLinks++; assertEquals(2277, graph.numLinks()); assertEquals(graph.numLinks(), numLinks); } @Test public void testnumLinks2() { UGraph<String> graph = new LightUGraph<String>(); UNode<String> a = graph.add("a"); UNode<String> b = graph.add("b"); UNode<String> c = graph.add("c"); a.connect(a); b.connect(c); c.connect(a); a.connect(c); a.connect(c); int numLinks = 0; for(Link<String> link : graph.links()) numLinks++; assertEquals(5, graph.numLinks()); assertEquals(graph.numLinks(), numLinks); } @Test public void testRemove2() { LightUGraph<String> graph = new LightUGraph<String>(); UNode<String> a = graph.add(null), b = graph.add(null), c = graph.add(null), d = graph.add(null); a.connect(b); b.connect(c); c.connect(d); d.connect(a); b.remove(); assertFalse(graph.get(0).connected(graph.get(0))); assertFalse(graph.get(0).connected(graph.get(1))); assertTrue (graph.get(0).connected(graph.get(2))); assertFalse(graph.get(1).connected(graph.get(0))); assertFalse(graph.get(1).connected(graph.get(1))); assertTrue (graph.get(1).connected(graph.get(2))); assertTrue (graph.get(2).connected(graph.get(0))); assertTrue (graph.get(2).connected(graph.get(1))); assertFalse(graph.get(2).connected(graph.get(2))); } @Test public void testIndices2() { // Note that light graphs have non-persistent nodes, so the indices // don't update after removal UGraph<String> in = Examples.yeast(); for(int reps : Series.series(100)) { LightUGraph<String> graph = LightUGraph.copy(in); Node<String> node = graph.get(145); assertEquals(145, node.index()); graph.get(150).remove(); // edit causes an exception boolean exThrown = false; try { System.out.println(node.index()); } catch(Exception e) { exThrown = true; } assertTrue(exThrown); // * Do some random removals for(int i : Series.series(10)) { // - random node graph.get(Global.random().nextInt(graph.size())).remove(); // - random link Node<String> a = graph.get(Global.random().nextInt(graph.size())); if(! a.neighbors().isEmpty()) { Node<String> b = Functions.choose(a.neighbors()); Link<String> link = Functions.choose(a.links(b)); link.remove(); } } int i = 0; for(Node<String> n : graph.nodes()) assertEquals(i++, n.index()); } } @Test public void testNodeLinks() { UGraph<String> graph = Examples.yeast(); graph = LightUGraph.copy(graph); for(Node<String> node : graph.nodes()) { Collection<? extends Node<String>> nbs = node.neighbors(); for(Node<String> neighbor : nbs) assertTrue(node.links(neighbor).size() > 0); } } @Test public void testNodeLinks2() { UGraph<String> graph = new LightUGraph<String>(); UNode<String> a = graph.add(""); UNode<String> b = graph.add(""); UNode<String> c = graph.add(""); a.connect(a); b.connect(c); c.connect(a); a.connect(c); a.connect(c); { Node<String> node = graph.get(0); Collection<? extends Node<String>> nbs = node.neighbors(); assertEquals(2, nbs.size()); assertEquals(1, node.links(graph.get(0)).size()); assertEquals(0, node.links(graph.get(1)).size()); assertEquals(3, node.links(graph.get(2)).size()); } { Node<String> node = graph.get(1); Collection<? extends Node<String>> nbs = node.neighbors(); assertEquals(1, nbs.size()); assertEquals(0, node.links(graph.get(0)).size()); assertEquals(0, node.links(graph.get(1)).size()); assertEquals(1, node.links(graph.get(2)).size()); } { Node<String> node = graph.get(2); Collection<? extends Node<String>> nbs = node.neighbors(); assertEquals(2, nbs.size()); assertEquals(3, node.links(graph.get(0)).size()); assertEquals(1, node.links(graph.get(1)).size()); assertEquals(0, node.links(graph.get(2)).size()); } } @Test public void testNeighbors() { UGraph<String> graph = new LightUGraph<String>(); UNode<String> a = graph.add("a"); UNode<String> b = graph.add("b"); UNode<String> c = graph.add("c"); a.connect(a); b.connect(c); c.connect(a); a.connect(c); a.connect(c); Set<Node<String>> aNbsExpected = new HashSet<Node<String>>(Arrays.asList(a, c)); Set<Node<String>> bNbsExpected = new HashSet<Node<String>>(Arrays.asList(c)); Set<Node<String>> cNbsExpected = new HashSet<Node<String>>(Arrays.asList(b, a)); Set<Node<String>> aNbsActual = new HashSet<Node<String>>(a.neighbors()); Set<Node<String>> bNbsActual = new HashSet<Node<String>>(b.neighbors()); Set<Node<String>> cNbsActual = new HashSet<Node<String>>(c.neighbors()); assertEquals(aNbsExpected, aNbsActual); assertEquals(bNbsExpected, bNbsActual); assertEquals(cNbsExpected, cNbsActual); } @Test public void testNeighborsFast() { UGraph<String> graph = Examples.yeast(); graph = LightUGraph.copy(graph); assertTrue(graph instanceof FastWalkable); for(Node<String> node : graph.nodes()) { Collection<? extends Node<String>> nbs = node.neighbors(); Collection<? extends Node<String>> col = ((FastWalkable<String,? extends Node<String>>)graph).neighborsFast(node); assertTrue(col instanceof List<?>); Set<Node<String>> nbsFast = new HashSet<Node<String>>(col); List<Integer> nbsList = new ArrayList<Integer>(); for(Node<String> nod : nbs) nbsList.add(nod.index()); List<Integer> nbsFastList = new ArrayList<Integer>(); for(Node<String> nod : nbsFast) nbsFastList.add(nod.index()); Collections.sort(nbsList); Collections.sort(nbsFastList); assertEquals(nbsList, nbsFastList); } } // @Test public void temp() throws IOException { UGraph<String> yeast = Data.edgeList(new File("/Users/Peter/Documents/datasets/graphs/yeast-lit/yeast-lit.txt"), false, false); int numSelfLoops = 0; for(Link<String> link : yeast.links()) if(link.first().index() == link.second().index()) numSelfLoops ++; System.out.println("num self loops " + numSelfLoops); FrequencyModel<Pair<Integer, Integer>> fm = new FrequencyModel<Pair<Integer,Integer>>(); yeast = Graphs.toSimpleUGraph(yeast, fm); System.out.println("num multi edges " + fm.total()); Data.writeEdgeList(yeast, new File("/Users/Peter/Documents/datasets/graphs/yeast-lit/yeast-lit-simple.txt")); yeast = Data.edgeList(new File("/Users/Peter/Documents/datasets/graphs/yeast-lit/yeast-lit-simple.txt"), false, false); assertTrue(Graphs.isSimple(yeast)); System.out.println("size " + yeast.size()); System.out.println("num links " + yeast.numLinks()); } }
mit
ideaworld/FHIR_Tester
FHIR_Tester_statics/js/build/.module-cache/3c85e614fa517a7dc1eab324d38caf65ae4a6c72.js
13382
var app = app || {}; (function(){ app.TestButton = React.createClass({displayName: "TestButton", handleClick: function() { this.props.submitTestTask(this.props.btnType); }, render: function() { return ( React.createElement("button", {onClick: this.handleClick, className: "btn btn-test"}, " ", React.createElement("span", {className: "btn-test-text"}, " ", this.props.btn_name, " ")) ); } }); app.CodeEditor = React.createClass({displayName: "CodeEditor", handleType:function(){ this.props.updateCode(this.editor.session.getValue()); }, componentDidMount:function(){ this.editor = ace.edit("codeeditor"); this.editor.setTheme("ace/theme/clouds"); this.editor.setOptions({ fontSize: "1.2em" }); this.editor.session.setMode("ace/mode/"+this.props.language); }, render:function(){ return ( React.createElement("div", {id: "codeeditor", onKeyUp: this.handleType}) ); } }); app.TokenEditor = React.createClass({displayName: "TokenEditor", handleChange:function(){ var new_token = this.refs.tokenInput.value; this.props.updateToken(new_token); }, render: function(){ return ( React.createElement("input", {className: "input-url", onChange: this.handleChange, ref: "tokenInput", placeholder: "Input Server Access Token"}) ); } }); app.UrlEditor = React.createClass({displayName: "UrlEditor", getInitialState: function(){ return { url_vaild:true } }, handleChange:function(){ //if url valid, update state, if not, warn var url_str = this.refs.urlInput.value; if (app.isUrl(url_str)){ this.setState({url_vaild:true}); //this.probs.updateUrl(url_str) }else{ this.setState({url_vaild:false}); } this.props.updateUrl(url_str); }, classNames:function(){ return 'input-url ' + ((this.state.url_vaild) ? 'input-right':'input-error'); }, render: function(){ return ( React.createElement("input", {className: this.classNames(), onChange: this.handleChange, ref: "urlInput", placeholder: "Type Server or App URL"}) ); } }); var ServerList = app.ServerList = React.createClass({displayName: "ServerList", getInitialState:function(){ return {chosedServer:-1, currentDisplay:"Servers",servers:[]}; }, componentDidMount:function(){ //get server list this.serverRequest = $.get('http://localhost:8000/home/servers', function (result) { if( result.isSuccessful ){ this.setState({servers:result.servers}); } }.bind(this)); }, componentWillUnmount: function() { this.serverRequest.abort(); }, onServerClick:function(event){ this.setState({currentDisplay:event.currentTarget.dataset.servername}); }, render:function(){ return ( React.createElement("div", {className: "dropdown"}, React.createElement("button", {ref: "menu_display", className: "btn btn-default dropdown-toggle", type: "button", id: "dropdownMenu1", "data-toggle": "dropdown"}, this.state.currentDisplay, React.createElement("span", {className: "caret"}) ), React.createElement("ul", {className: "dropdown-menu", role: "menu", "aria-labelledby": "dropdownMenu1"}, this.state.servers.map(function(server){ return React.createElement("li", {role: "presentation"}, React.createElement("a", {"data-serverName": server.name, "data-serverid": server.id, onClick: this.onServerClick, role: "menuitem", tabindex: "-1", href: "#"}, server.name)) }), React.createElement("li", {role: "presentation"}, React.createElement("a", {"data-serverName": "HAPI FHIR", "data-serverid": "2", onClick: this.onServerClick, role: "menuitem", tabindex: "-1", href: "#"}, "HAPI FHIR")), React.createElement("li", {role: "presentation"}, React.createElement("a", {"data-serverName": "FHIR Genomics", "data-serverid": "3", onClick: this.onServerClick, role: "menuitem", tabindex: "-1", href: "#"}, "FHIR Genomics")) ) ) ); } }) var ResultDisplay = app.ResultDisplay = React.createClass({displayName: "ResultDisplay", getInitialState:function(){ return {'level':-1, test_type:0, 'steps':[]} }, displayResult:function(res_dict){ console.log(res_dict); var test_type = res_dict.test_type this.setState({'test_type':test_type}) if (test_type == 0){ this.setState({'level':res_dict.level}); } this.setState({'steps':res_dict['steps']}); }, render: function(){ return ( React.createElement("div", {className: "result-container"}, React.createElement("div", {className: "result-head"}, React.createElement("span", {className: "area-title area-title-black"}, "Test Type: "), " ", React.createElement("span", null, this.props.testType)), React.createElement("div", {className: "detail-result"}, React.createElement("div", {className: "result-sum"}, this.state.test_type == 0 ? React.createElement("h3", null, "Level: ", this.state.level) : null ), this.state.steps.map(function(step){ return React.createElement(StepDisplay, {stepInfo: step}) }) ) ) ) } }); var StepDisplay = app.StepDisplay = React.createClass({displayName: "StepDisplay", getInitialState: function(){ return { is_img_hide:true, is_modal_show:false, is_has_image:false } }, componentDidMount:function(){ if(this.props.stepInfo.addi){ this.setState({is_has_image:true}); } }, handleTextClick:function(){ if (this.state.is_has_image){ this.setState({is_img_hide:!this.state.is_img_hide}); } }, handleShowFullImage:function(event){ event.stopPropagation(); this.setState({is_modal_show:true}); }, handleHideModal(){ this.setState({is_modal_show:false}); }, handleShowModal(){ this.setState({is_modal_show: true}); }, render:function(){ return ( React.createElement("div", {className: "step-brief step-brief-success", onClick: this.handleTextClick}, React.createElement("div", null, React.createElement("span", {className: "step-brief-text"}, this.props.stepInfo.desc)), React.createElement("div", {hidden: this.state.is_img_hide && !this.state.is_has_image, className: "step-img-block"}, React.createElement("button", {onClick: this.handleShowFullImage, className: "btn btn-primary"}, "Full Image"), React.createElement("img", {className: "img-responsive img-rounded step-img", src: this.props.stepInfo.addi}) ), this.state.is_modal_show && this.state.is_has_image ? React.createElement(Modal, {handleHideModal: this.handleHideModal, title: "Step Image", content: React.createElement(FullImageArea, {img_src: this.props.stepInfo.addi})}) : null ) ); } }); app.UserBtnArea = React.createClass({displayName: "UserBtnArea", handleLogout:function(){ app.showMsg("Logout"); }, render:function(){ return ( React.createElement("div", {className: "user-op"}, React.createElement("button", {className: "btn btn-user", onClick: this.props.history_action}, "History"), React.createElement("button", {className: "btn btn-user"}, "Search Task"), React.createElement("button", {className: "btn btn-user"}, "Change Password"), React.createElement("button", {className: "btn btn-user", onClick: this.handleLogout}, React.createElement("span", {className: "glyphicon glyphicon-off"})) ) ); } }); var FullImageArea = app.FullImageArea = React.createClass({displayName: "FullImageArea", render:function(){ return( React.createElement("img", {src: this.props.img_src, className: "img-responsive"}) ); } }); var TaskItem = app.TaskItem = React.createClass({displayName: "TaskItem", handleClick:function(){ this.props.itemClicked(this.props.task_id); }, render:function(){ return ( React.createElement("div", {className: "list-item", onClick: this.handleClick}, React.createElement("span", null, "Task ID:"), this.props.task_id ) ); } }); var TaskList = app.TaskList = React.createClass({displayName: "TaskList", render:function(){ return ( React.createElement("div", {className: "task-list"}, React.createElement("h2", null, "History Tasks"), React.createElement("div", {className: "list-content"}, this.props.tasks.map(function(task_id){ return React.createElement(TaskItem, {itemClicked: this.props.fetchTaskDetail, task_id: task_id}) },this) ) ) ); } }); var HistoryViewer = app.HistoryViewer = React.createClass({displayName: "HistoryViewer", getInitialState:function(){ return {tasks:[]}; }, updateTestResult:function(res){ this.refs.res_area.displayResult(res); }, componentDidMount:function(){ window.hist = this; var postData = { token:$.cookie('fhir_token') }; var self = this; console.log(postData); $.ajax({ url:'http://localhost:8000/home/history', type:'POST', data:JSON.stringify(postData), dataType:'json', cache:false, success:function(data){ if( data.isSuccessful ){ self.setState({tasks:data.tasks}); } } }); }, getTaskDetail:function(task_id){ console.log(task_id); app.setup_websocket(task_id,2) }, render:function(){ return ( React.createElement("div", {className: "history-area"}, React.createElement(TaskList, {fetchTaskDetail: this.getTaskDetail, tasks: this.state.tasks}), React.createElement(ResultDisplay, {ref: "res_area"}) ) ); } }); var Modal = app.Modal = React.createClass({displayName: "Modal", componentDidMount(){ $(ReactDOM.findDOMNode(this)).modal('show'); $(ReactDOM.findDOMNode(this)).on('hidden.bs.modal', this.props.handleHideModal); }, render:function(){ return ( React.createElement("div", {className: "modal modal-wide fade"}, React.createElement("div", {className: "modal-dialog"}, React.createElement("div", {className: "modal-content"}, React.createElement("div", {className: "modal-header"}, React.createElement("button", {type: "button", className: "close", "data-dismiss": "modal", "aria-label": "Close"}, React.createElement("span", {"aria-hidden": "true"}, "×")), React.createElement("h4", {className: "modal-title"}, this.props.title) ), React.createElement("div", {className: "modal-body"}, this.props.content ), React.createElement("div", {className: "modal-footer text-center"}, React.createElement("button", {className: "btn btn-primary center-block", "data-dismiss": "modal"}, "Close") ) ) ) ) ); } }); })();
mit
MacHu-GWU/dataIO-project
create_doctree.py
473
#!/usr/bin/env python # -*- coding: utf-8 -*- import docfly # Uncomment this if you follow Sanhe's Sphinx Doc Style Guide #--- Manually Made Doc --- doc = docfly.DocTree("source") doc.fly(table_of_content_header="Table of Content") #--- Api Reference Doc --- package_name = "dataIO" doc = docfly.ApiReferenceDoc( package_name, dst="source", ignore=[ "%s.packages" % package_name, "%s.zzz_manual_install.py" % package_name, ] ) doc.fly()
mit
jordifierro/abidria-api
scenes/interactors.py
4108
from .entities import Scene class GetScenesFromExperienceInteractor: def __init__(self, scene_repo, permissions_validator): self.scene_repo = scene_repo self.permissions_validator = permissions_validator def set_params(self, experience_id, logged_person_id): self.experience_id = experience_id self.logged_person_id = logged_person_id return self def execute(self): self.permissions_validator.validate_permissions(logged_person_id=self.logged_person_id) return self.scene_repo.get_scenes(experience_id=self.experience_id) class CreateNewSceneInteractor: def __init__(self, scene_repo, scene_validator, permissions_validator): self.scene_repo = scene_repo self.scene_validator = scene_validator self.permissions_validator = permissions_validator def set_params(self, title, description, latitude, longitude, experience_id, logged_person_id): self.title = title self.description = description self.latitude = latitude self.longitude = longitude self.experience_id = experience_id self.logged_person_id = logged_person_id return self def execute(self): self.permissions_validator.validate_permissions(logged_person_id=self.logged_person_id, has_permissions_to_modify_experience=self.experience_id) scene = Scene(title=self.title, description=self.description, latitude=self.latitude, longitude=self.longitude, experience_id=self.experience_id) self.scene_validator.validate_scene(scene) return self.scene_repo.create_scene(scene) class ModifySceneInteractor: def __init__(self, scene_repo, scene_validator, permissions_validator): self.scene_repo = scene_repo self.scene_validator = scene_validator self.permissions_validator = permissions_validator def set_params(self, id, title, description, latitude, longitude, experience_id, logged_person_id): self.id = id self.title = title self.description = description self.latitude = latitude self.longitude = longitude self.experience_id = experience_id self.logged_person_id = logged_person_id return self def execute(self): self.permissions_validator.validate_permissions(logged_person_id=self.logged_person_id, has_permissions_to_modify_experience=self.experience_id) scene = self.scene_repo.get_scene(id=self.id) new_title = self.title if self.title is not None else scene.title new_description = self.description if self.description is not None else scene.description new_latitude = self.latitude if self.latitude is not None else scene.latitude new_longitude = self.longitude if self.longitude is not None else scene.longitude new_experience_id = self.experience_id if self.experience_id is not None else scene.experience_id updated_scene = Scene(id=scene.id, title=new_title, description=new_description, latitude=new_latitude, longitude=new_longitude, experience_id=new_experience_id) self.scene_validator.validate_scene(updated_scene) return self.scene_repo.update_scene(updated_scene) class UploadScenePictureInteractor: def __init__(self, scene_repo, permissions_validator): self.scene_repo = scene_repo self.permissions_validator = permissions_validator def set_params(self, scene_id, picture, logged_person_id): self.scene_id = scene_id self.picture = picture self.logged_person_id = logged_person_id return self def execute(self): self.permissions_validator.validate_permissions(logged_person_id=self.logged_person_id, has_permissions_to_modify_scene=self.scene_id) return self.scene_repo.attach_picture_to_scene(scene_id=self.scene_id, picture=self.picture)
mit
talentegra/TesNow
application/views/roles/roles_read.php
326
<h2 style="margin-top:0px">Roles Read</h2> <table class="table"> <tr><td>Name</td><td><?php echo $name; ?></td></tr> <tr><td>Definition</td><td><?php echo $definition; ?></td></tr> <tr><td></td><td><a href="<?php echo site_url('roles') ?>" class="btn btn-default">Cancel</a></td></tr> </table>
mit
hgaard/intro-to-docker
src/aspnet-core-sql-server/Data/Migrations/ApplicationDbContextModelSnapshot.cs
7328
using System; using Microsoft.EntityFrameworkCore; using Microsoft.EntityFrameworkCore.Infrastructure; using Microsoft.EntityFrameworkCore.Metadata; using Microsoft.EntityFrameworkCore.Migrations; namespace app.Data.Migrations { [DbContext(typeof(ApplicationDbContext))] partial class ApplicationDbContextModelSnapshot : ModelSnapshot { protected override void BuildModel(ModelBuilder modelBuilder) { modelBuilder .HasAnnotation("ProductVersion", "1.0.2"); modelBuilder.Entity("Microsoft.AspNetCore.Identity.EntityFrameworkCore.IdentityRole", b => { b.Property<string>("Id"); b.Property<string>("ConcurrencyStamp") .IsConcurrencyToken(); b.Property<string>("Name") .HasMaxLength(256); b.Property<string>("NormalizedName") .HasMaxLength(256); b.HasKey("Id"); b.HasIndex("NormalizedName") .HasName("RoleNameIndex"); b.ToTable("AspNetRoles"); }); modelBuilder.Entity("Microsoft.AspNetCore.Identity.EntityFrameworkCore.IdentityRoleClaim<string>", b => { b.Property<int>("Id") .ValueGeneratedOnAdd(); b.Property<string>("ClaimType"); b.Property<string>("ClaimValue"); b.Property<string>("RoleId") .IsRequired(); b.HasKey("Id"); b.HasIndex("RoleId"); b.ToTable("AspNetRoleClaims"); }); modelBuilder.Entity("Microsoft.AspNetCore.Identity.EntityFrameworkCore.IdentityUserClaim<string>", b => { b.Property<int>("Id") .ValueGeneratedOnAdd(); b.Property<string>("ClaimType"); b.Property<string>("ClaimValue"); b.Property<string>("UserId") .IsRequired(); b.HasKey("Id"); b.HasIndex("UserId"); b.ToTable("AspNetUserClaims"); }); modelBuilder.Entity("Microsoft.AspNetCore.Identity.EntityFrameworkCore.IdentityUserLogin<string>", b => { b.Property<string>("LoginProvider"); b.Property<string>("ProviderKey"); b.Property<string>("ProviderDisplayName"); b.Property<string>("UserId") .IsRequired(); b.HasKey("LoginProvider", "ProviderKey"); b.HasIndex("UserId"); b.ToTable("AspNetUserLogins"); }); modelBuilder.Entity("Microsoft.AspNetCore.Identity.EntityFrameworkCore.IdentityUserRole<string>", b => { b.Property<string>("UserId"); b.Property<string>("RoleId"); b.HasKey("UserId", "RoleId"); b.HasIndex("RoleId"); b.HasIndex("UserId"); b.ToTable("AspNetUserRoles"); }); modelBuilder.Entity("Microsoft.AspNetCore.Identity.EntityFrameworkCore.IdentityUserToken<string>", b => { b.Property<string>("UserId"); b.Property<string>("LoginProvider"); b.Property<string>("Name"); b.Property<string>("Value"); b.HasKey("UserId", "LoginProvider", "Name"); b.ToTable("AspNetUserTokens"); }); modelBuilder.Entity("app.Models.ApplicationUser", b => { b.Property<string>("Id"); b.Property<int>("AccessFailedCount"); b.Property<string>("ConcurrencyStamp") .IsConcurrencyToken(); b.Property<string>("Email") .HasMaxLength(256); b.Property<bool>("EmailConfirmed"); b.Property<bool>("LockoutEnabled"); b.Property<DateTimeOffset?>("LockoutEnd"); b.Property<string>("NormalizedEmail") .HasMaxLength(256); b.Property<string>("NormalizedUserName") .HasMaxLength(256); b.Property<string>("PasswordHash"); b.Property<string>("PhoneNumber"); b.Property<bool>("PhoneNumberConfirmed"); b.Property<string>("SecurityStamp"); b.Property<bool>("TwoFactorEnabled"); b.Property<string>("UserName") .HasMaxLength(256); b.HasKey("Id"); b.HasIndex("NormalizedEmail") .HasName("EmailIndex"); b.HasIndex("NormalizedUserName") .IsUnique() .HasName("UserNameIndex"); b.ToTable("AspNetUsers"); }); modelBuilder.Entity("Microsoft.AspNetCore.Identity.EntityFrameworkCore.IdentityRoleClaim<string>", b => { b.HasOne("Microsoft.AspNetCore.Identity.EntityFrameworkCore.IdentityRole") .WithMany("Claims") .HasForeignKey("RoleId") .OnDelete(DeleteBehavior.Cascade); }); modelBuilder.Entity("Microsoft.AspNetCore.Identity.EntityFrameworkCore.IdentityUserClaim<string>", b => { b.HasOne("app.Models.ApplicationUser") .WithMany("Claims") .HasForeignKey("UserId") .OnDelete(DeleteBehavior.Cascade); }); modelBuilder.Entity("Microsoft.AspNetCore.Identity.EntityFrameworkCore.IdentityUserLogin<string>", b => { b.HasOne("app.Models.ApplicationUser") .WithMany("Logins") .HasForeignKey("UserId") .OnDelete(DeleteBehavior.Cascade); }); modelBuilder.Entity("Microsoft.AspNetCore.Identity.EntityFrameworkCore.IdentityUserRole<string>", b => { b.HasOne("Microsoft.AspNetCore.Identity.EntityFrameworkCore.IdentityRole") .WithMany("Users") .HasForeignKey("RoleId") .OnDelete(DeleteBehavior.Cascade); b.HasOne("app.Models.ApplicationUser") .WithMany("Roles") .HasForeignKey("UserId") .OnDelete(DeleteBehavior.Cascade); }); } } }
mit
visa-innovation-sf/ldn-retail-demo
src/components/ui/Button.js
3240
/** * Buttons * <Button text={'Server is down'} /> * * React Native Starter App * https://github.com/mcnamee/react-native-starter-app */ import React, { Component } from 'react'; import PropTypes from 'prop-types'; import { Button } from 'react-native-elements'; // Consts and Libs import { AppColors, AppFonts, AppSizes } from '@theme/'; /* Component ==================================================================== */ class CustomButton extends Component { static propTypes = { small: PropTypes.bool, large: PropTypes.bool, outlined: PropTypes.bool, backgroundColor: PropTypes.string, onPress: PropTypes.func, icon: PropTypes.shape({ name: PropTypes.string, }), } static defaultProps = { small: false, large: false, outlined: false, icon: {}, backgroundColor: null, onPress: null, } buttonProps = () => { // Defaults const props = { title: 'Coming Soon...', color: '#fff', fontWeight: 'bold', onPress: this.props.onPress, fontFamily: AppFonts.base.family, fontSize: AppFonts.base.size, raised: false, buttonStyle: { padding: 12, }, containerViewStyle: { marginLeft: 0, marginRight: 0, }, ...this.props, backgroundColor: this.props.backgroundColor || AppColors.brand.primary, small: false, large: false, icon: (this.props.icon && this.props.icon.name) ? { size: 24, ...this.props.icon, } : null, }; // Overrides // Size if (this.props.small) { props.fontSize = 12; props.buttonStyle.padding = 8; if (props.icon && props.icon.name) { props.icon = { size: 14, ...props.icon, }; } } if (this.props.large) { props.fontSize = 20; props.buttonStyle.padding = 20; props.color = this.props.color || AppColors.base.black; if (props.icon && props.icon.name) { props.icon = { size: 20, ...props.icon, }; } } // Outlined if (this.props.outlined) { props.raised = false; props.backgroundColor = this.props.backgroundColor || 'transparent'; props.color = AppColors.brand.secondary; props.buttonStyle.borderWidth = 1; props.buttonStyle.borderColor = AppColors.brand.secondary; if (props.icon && props.icon.name) { props.icon = { color: AppColors.brand.secondary, ...props.icon, }; } } return props; } render = () => <Button {...this.buttonProps()} />; } /* Export Component ==================================================================== */ export default CustomButton;
mit
IndustrialDragonfly/DEdC
Interface/ClassLoader.php
939
<?php /** * Attempts to load Interface classes (Request and Response). * @param String $classname */ function InterfaceClassLoader($classname) { // Handle setting the path if there is one set - such as for PHPUnit if (isset($GLOBALS['path'])) { $prefix = $GLOBALS['path'] . "/"; } else { $prefix = ""; } // Request if (file_exists($prefix . "Interface/Request/" . $classname . ".php")) { require_once $prefix . "Interface/Request/" . $classname . ".php"; } elseif (file_exists($prefix . "Interface/Request/AuthenticationHandlers/" . $classname . ".php")) { require_once $prefix . "Interface/Request/AuthenticationHandlers/" . $classname . ".php"; } // Response elseif (file_exists($prefix . "Interface/Response/" . $classname . ".php")) { require_once $prefix . "Interface/Response/" . $classname . ".php"; } }
mit
mmnaseri/spring-data-mock
spring-data-mock/src/main/java/com/mmnaseri/utils/spring/data/domain/impl/ImmutableInvocation.java
785
package com.mmnaseri.utils.spring.data.domain.impl; import com.mmnaseri.utils.spring.data.domain.Invocation; import java.lang.reflect.Method; import java.util.Arrays; /** * This is an immutable invocation. * * @author Milad Naseri ([email protected]) * @since 1.0 (9/23/15) */ public class ImmutableInvocation implements Invocation { private final Method method; private final Object[] arguments; public ImmutableInvocation(Method method, Object[] arguments) { this.method = method; this.arguments = arguments; } @Override public Method getMethod() { return method; } @Override public Object[] getArguments() { return arguments; } @Override public String toString() { return method + ", " + Arrays.toString(arguments); } }
mit
PrismLibrary/Prism-Samples-Windows
AdventureWorks.Shopper/AdventureWorks.UILogic/Models/Category.cs
875
using System; using System.Collections.Generic; using System.Runtime.Serialization; namespace AdventureWorks.UILogic.Models { [DataContract] public class Category { // Needed only for Serialization public Category() { } [DataMember] public int Id { get; set; } [DataMember] public int ParentId { get; set; } [DataMember] public string Title { get; set; } [DataMember] public Uri ImageUri { get; set; } [DataMember] public IEnumerable<Category> Subcategories { get; set; } [DataMember] public IEnumerable<Product> Products { get; set; } [DataMember] public int TotalNumberOfItems { get; set; } [DataMember] public bool HasSubcategories { get; set; } } }
mit
karlthepagan/Glowstone
src/main/java/net/glowstone/net/codec/MapDataCodec.java
1152
package net.glowstone.net.codec; import java.io.IOException; import org.jboss.netty.buffer.ChannelBuffer; import org.jboss.netty.buffer.ChannelBuffers; import net.glowstone.msg.MapDataMessage; public final class MapDataCodec extends MessageCodec<MapDataMessage> { public MapDataCodec() { super(MapDataMessage.class, 0x83); } @Override public MapDataMessage decode(ChannelBuffer buffer) throws IOException { short type = buffer.readShort(); short id = buffer.readShort(); short size = buffer.readUnsignedByte(); byte[] data = new byte[size]; for (int i = 0; i < data.length; ++i) { data[i] = buffer.readByte(); } return new MapDataMessage(type, id, data); } @Override public ChannelBuffer encode(MapDataMessage message) throws IOException { ChannelBuffer buffer = ChannelBuffers.dynamicBuffer(); buffer.writeShort(message.getType()); buffer.writeShort(message.getId()); buffer.writeByte(message.getData().length); buffer.writeBytes(message.getData()); return buffer; } }
mit
Sensis/pyaem
pyaem/packagemanagerservicejsp.py
5185
from . import bagofrequests as bag from . import handlers from . import result as res import xmltodict class PackageManagerServiceJsp(object): def __init__(self, url, **kwargs): self.url = url self.kwargs = kwargs self.handlers = { 401: handlers.auth_fail } def is_package_uploaded(self, group_name, package_name, package_version, **kwargs): def _handler_ok(response, **kwargs): data = xmltodict.parse(response['body']) status_code = data['crx']['response']['status']['@code'] status_value = data['crx']['response']['status']['#text'] result = res.PyAemResult(response) if status_code != '200' or status_value != 'ok': message = 'Unable to retrieve package list. Command status code {0} and status value {1}'.format( status_code, status_value) result.failure(message) else: def match(package): # when version value is not specified, the version xml element will be empty <version></version> if package['version'] == None: package['version'] = '' return (package['group'] == group_name and package['name'] == package_name and package['version'] == package_version) is_uploaded = False packages = data['crx']['response']['data']['packages'] if packages != None: if isinstance(packages['package'], list): for package in packages['package']: if match(package): is_uploaded = True elif match(packages['package']): is_uploaded = True if is_uploaded == True: message = 'Package {0}/{1}-{2} is uploaded'.format(group_name, package_name, package_version) result.success(message) else: message = 'Package {0}/{1}-{2} is not uploaded'.format(group_name, package_name, package_version) result.failure(message) return result _handlers = { 200: _handler_ok } params = { 'cmd': 'ls' } method = 'get' url = '{0}/crx/packmgr/service.jsp'.format(self.url, package_name) params = dict(params.items() + kwargs.items()) _handlers = dict(self.handlers.items() + _handlers.items()) opts = self.kwargs return bag.request(method, url, params, _handlers, **opts) def is_package_installed(self, group_name, package_name, package_version, **kwargs): def _handler_ok(response, **kwargs): data = xmltodict.parse(response['body']) status_code = data['crx']['response']['status']['@code'] status_value = data['crx']['response']['status']['#text'] result = res.PyAemResult(response) if status_code != '200' or status_value != 'ok': message = 'Unable to retrieve package list. Command status code {0} and status value {1}'.format( status_code, status_value) result.failure(message) else: def match(package): # when version value is not specified, the version xml element will be empty <version></version> if package['version'] == None: package['version'] = '' return (package['group'] == group_name and package['name'] == package_name and package['version'] == package_version and package['lastUnpackedBy'] != 'null') is_installed = False packages = data['crx']['response']['data']['packages'] if packages != None: if isinstance(packages['package'], list): for package in packages['package']: if match(package): is_installed = True elif match(packages['package']): is_installed = True if is_installed == True: message = 'Package {0}/{1}-{2} is installed'.format(group_name, package_name, package_version) result.success(message) else: message = 'Package {0}/{1}-{2} is not installed'.format(group_name, package_name, package_version) result.failure(message) return result _handlers = { 200: _handler_ok } params = { 'cmd': 'ls' } method = 'get' url = '{0}/crx/packmgr/service.jsp'.format(self.url, package_name) params = dict(params.items() + kwargs.items()) _handlers = dict(self.handlers.items() + _handlers.items()) opts = self.kwargs return bag.request(method, url, params, _handlers, **opts)
mit
hoopsomuah/orleans
src/Orleans/Serialization/BinaryTokenStreamReader.cs
36804
//#define TRACE_SERIALIZATION using System; using System.Collections.Generic; using System.Diagnostics; using System.IO; using System.Linq; using System.Net; using System.Runtime.Serialization; using System.Text; using Orleans.CodeGeneration; using Orleans.GrainDirectory; using Orleans.Runtime; namespace Orleans.Serialization { /// <summary> /// Reader for Orleans binary token streams /// </summary> public class BinaryTokenStreamReader { private readonly IList<ArraySegment<byte>> buffers; private int currentSegmentIndex; private ArraySegment<byte> currentSegment; private byte[] currentBuffer; private int currentOffset; private int totalProcessedBytes; private readonly int totalLength; private static readonly ArraySegment<byte> emptySegment = new ArraySegment<byte>(new byte[0]); /// <summary> /// Create a new BinaryTokenStreamReader to read from the specified input byte array. /// </summary> /// <param name="input">Input binary data to be tokenized.</param> public BinaryTokenStreamReader(byte[] input) : this(new List<ArraySegment<byte>> { new ArraySegment<byte>(input) }) { } /// <summary> /// Create a new BinaryTokenStreamReader to read from the specified input buffers. /// </summary> /// <param name="buffs">The list of ArraySegments to use for the data.</param> public BinaryTokenStreamReader(IList<ArraySegment<byte>> buffs) { buffers = buffs; totalProcessedBytes = 0; currentSegmentIndex = 0; currentSegment = buffs[0]; currentBuffer = currentSegment.Array; currentOffset = currentSegment.Offset; totalLength = buffs.Sum(b => b.Count); Trace("Starting new stream reader"); } /// <summary> /// Create a new BinaryTokenStreamReader to read from the specified input buffer. /// </summary> /// <param name="buff">ArraySegment to use for the data.</param> public BinaryTokenStreamReader(ArraySegment<byte> buff) : this(new[] { buff }) { } /// <summary> Current read position in the stream. </summary> public int CurrentPosition { get { return currentOffset + totalProcessedBytes - currentSegment.Offset; } } /// <summary> /// Creates a copy of the current stream reader. /// </summary> /// <returns>The new copy</returns> public BinaryTokenStreamReader Copy() { return new BinaryTokenStreamReader(this.buffers); } private void StartNextSegment() { totalProcessedBytes += currentSegment.Count; currentSegmentIndex++; if (currentSegmentIndex < buffers.Count) { currentSegment = buffers[currentSegmentIndex]; currentBuffer = currentSegment.Array; currentOffset = currentSegment.Offset; } else { currentSegment = emptySegment; currentBuffer = null; currentOffset = 0; } } private ArraySegment<byte> CheckLength(int n) { bool ignore; return CheckLength(n, out ignore); } private ArraySegment<byte> CheckLength(int n, out bool safeToUse) { safeToUse = false; if (n == 0) { safeToUse = true; return emptySegment; } if ((CurrentPosition + n > totalLength)) { throw new SerializationException( String.Format("Attempt to read past the end of the input stream: CurrentPosition={0}, n={1}, totalLength={2}", CurrentPosition, n, totalLength)); } if (currentSegmentIndex >= buffers.Count) { throw new SerializationException( String.Format("Attempt to read past buffers.Count: currentSegmentIndex={0}, buffers.Count={1}.", currentSegmentIndex, buffers.Count)); } if (currentOffset == currentSegment.Offset + currentSegment.Count) { StartNextSegment(); } if (currentOffset + n <= currentSegment.Offset + currentSegment.Count) { var result = new ArraySegment<byte>(currentBuffer, currentOffset, n); currentOffset += n; if (currentOffset >= currentSegment.Offset + currentSegment.Count) { StartNextSegment(); } return result; } var temp = new byte[n]; var i = 0; while (i < n) { var bytesFromThisBuffer = Math.Min(currentSegment.Offset + currentSegment.Count - currentOffset, n - i); Buffer.BlockCopy(currentBuffer, currentOffset, temp, i, bytesFromThisBuffer); i += bytesFromThisBuffer; currentOffset += bytesFromThisBuffer; if (currentOffset >= currentSegment.Offset + currentSegment.Count) { StartNextSegment(); } } safeToUse = true; return new ArraySegment<byte>(temp); } /// <summary> Read an <c>Int32</c> value from the stream. </summary> /// <returns>Data from current position in stream, converted to the appropriate output type.</returns> public int ReadInt() { var buff = CheckLength(sizeof(int)); var val = BitConverter.ToInt32(buff.Array, buff.Offset); Trace("--Read int {0}", val); return val; } /// <summary> Read an <c>UInt32</c> value from the stream. </summary> /// <returns>Data from current position in stream, converted to the appropriate output type.</returns> public uint ReadUInt() { var buff = CheckLength(sizeof(uint)); var val = BitConverter.ToUInt32(buff.Array, buff.Offset); Trace("--Read uint {0}", val); return val; } /// <summary> Read an <c>Int16</c> value from the stream. </summary> /// <returns>Data from current position in stream, converted to the appropriate output type.</returns> public short ReadShort() { var buff = CheckLength(sizeof(short)); var val = BitConverter.ToInt16(buff.Array, buff.Offset); Trace("--Read short {0}", val); return val; } /// <summary> Read an <c>UInt16</c> value from the stream. </summary> /// <returns>Data from current position in stream, converted to the appropriate output type.</returns> public ushort ReadUShort() { var buff = CheckLength(sizeof(ushort)); var val = BitConverter.ToUInt16(buff.Array, buff.Offset); Trace("--Read ushort {0}", val); return val; } /// <summary> Read an <c>Int64</c> value from the stream. </summary> /// <returns>Data from current position in stream, converted to the appropriate output type.</returns> public long ReadLong() { var buff = CheckLength(sizeof(long)); var val = BitConverter.ToInt64(buff.Array, buff.Offset); Trace("--Read long {0}", val); return val; } /// <summary> Read an <c>UInt64</c> value from the stream. </summary> /// <returns>Data from current position in stream, converted to the appropriate output type.</returns> public ulong ReadULong() { var buff = CheckLength(sizeof(ulong)); var val = BitConverter.ToUInt64(buff.Array, buff.Offset); Trace("--Read ulong {0}", val); return val; } /// <summary> Read an <c>float</c> value from the stream. </summary> /// <returns>Data from current position in stream, converted to the appropriate output type.</returns> public float ReadFloat() { var buff = CheckLength(sizeof(float)); var val = BitConverter.ToSingle(buff.Array, buff.Offset); Trace("--Read float {0}", val); return val; } /// <summary> Read an <c>double</c> value from the stream. </summary> /// <returns>Data from current position in stream, converted to the appropriate output type.</returns> public double ReadDouble() { var buff = CheckLength(sizeof(double)); var val = BitConverter.ToDouble(buff.Array, buff.Offset); Trace("--Read double {0}", val); return val; } /// <summary> Read an <c>decimal</c> value from the stream. </summary> /// <returns>Data from current position in stream, converted to the appropriate output type.</returns> public decimal ReadDecimal() { var buff = CheckLength(4 * sizeof(int)); var raw = new int[4]; Trace("--Read decimal"); var n = buff.Offset; for (var i = 0; i < 4; i++) { raw[i] = BitConverter.ToInt32(buff.Array, n); n += sizeof(int); } return new decimal(raw); } /// <summary> Read an <c>string</c> value from the stream. </summary> /// <returns>Data from current position in stream, converted to the appropriate output type.</returns> public string ReadString() { var n = ReadInt(); if (n == 0) { Trace("--Read empty string"); return String.Empty; } string s = null; // a length of -1 indicates that the string is null. if (-1 != n) { var buff = CheckLength(n); s = Encoding.UTF8.GetString(buff.Array, buff.Offset, n); } Trace("--Read string '{0}'", s); return s; } /// <summary> Read the next bytes from the stream. </summary> /// <param name="count">Number of bytes to read.</param> /// <returns>Data from current position in stream, converted to the appropriate output type.</returns> public byte[] ReadBytes(int count) { if (count == 0) { return new byte[0]; } bool safeToUse; var buff = CheckLength(count, out safeToUse); Trace("--Read byte array of length {0}", count); if (!safeToUse) { var result = new byte[count]; Array.Copy(buff.Array, buff.Offset, result, 0, count); return result; } else { return buff.Array; } } /// <summary> Read the next bytes from the stream. </summary> /// <param name="destination">Output array to store the returned data in.</param> /// <param name="offset">Offset into the destination array to write to.</param> /// <param name="count">Number of bytes to read.</param> public void ReadByteArray(byte[] destination, int offset, int count) { if (offset + count > destination.Length) { throw new ArgumentOutOfRangeException("count", "Reading into an array that is too small"); } var buff = CheckLength(count); Buffer.BlockCopy(buff.Array, buff.Offset, destination, offset, count); } /// <summary> Read an <c>char</c> value from the stream. </summary> /// <returns>Data from current position in stream, converted to the appropriate output type.</returns> public char ReadChar() { Trace("--Read char"); return Convert.ToChar(ReadShort()); } /// <summary> Read an <c>byte</c> value from the stream. </summary> /// <returns>Data from current position in stream, converted to the appropriate output type.</returns> public byte ReadByte() { var buff = CheckLength(1); Trace("--Read byte"); return buff.Array[buff.Offset]; } /// <summary> Read an <c>sbyte</c> value from the stream. </summary> /// <returns>Data from current position in stream, converted to the appropriate output type.</returns> public sbyte ReadSByte() { var buff = CheckLength(1); Trace("--Read sbyte"); return unchecked((sbyte)(buff.Array[buff.Offset])); } /// <summary> Read an <c>IPAddress</c> value from the stream. </summary> /// <returns>Data from current position in stream, converted to the appropriate output type.</returns> public IPAddress ReadIPAddress() { var buff = CheckLength(16); bool v4 = true; for (var i = 0; i < 12; i++) { if (buff.Array[buff.Offset + i] != 0) { v4 = false; break; } } if (v4) { var v4Bytes = new byte[4]; for (var i = 0; i < 4; i++) { v4Bytes[i] = buff.Array[buff.Offset + 12 + i]; } return new IPAddress(v4Bytes); } else { var v6Bytes = new byte[16]; for (var i = 0; i < 16; i++) { v6Bytes[i] = buff.Array[buff.Offset + i]; } return new IPAddress(v6Bytes); } } /// <summary> Read an <c>IPEndPoint</c> value from the stream. </summary> /// <returns>Data from current position in stream, converted to the appropriate output type.</returns> public IPEndPoint ReadIPEndPoint() { var addr = ReadIPAddress(); var port = ReadInt(); return new IPEndPoint(addr, port); } /// <summary> Read an <c>SiloAddress</c> value from the stream. </summary> /// <returns>Data from current position in stream, converted to the appropriate output type.</returns> public SiloAddress ReadSiloAddress() { var ep = ReadIPEndPoint(); var gen = ReadInt(); return SiloAddress.New(ep, gen); } /// <summary> Read an <c>GrainId</c> value from the stream. </summary> /// <returns>Data from current position in stream, converted to the appropriate output type.</returns> internal GrainId ReadGrainId() { UniqueKey key = ReadUniqueKey(); return GrainId.GetGrainId(key); } /// <summary> Read an <c>ActivationId</c> value from the stream. </summary> /// <returns>Data from current position in stream, converted to the appropriate output type.</returns> internal ActivationId ReadActivationId() { UniqueKey key = ReadUniqueKey(); return ActivationId.GetActivationId(key); } internal UniqueKey ReadUniqueKey() { ulong n0 = ReadULong(); ulong n1 = ReadULong(); ulong typeCodeData = ReadULong(); string keyExt = ReadString(); return UniqueKey.NewKey(n0, n1, typeCodeData, keyExt); } internal Guid ReadGuid() { byte[] bytes = ReadBytes(16); return new Guid(bytes); } internal MultiClusterStatus ReadMultiClusterStatus() { byte val = ReadByte(); return (MultiClusterStatus) val; } /// <summary> Read an <c>ActivationAddress</c> value from the stream. </summary> /// <returns>Data from current position in stream, converted to the appropriate output type.</returns> internal ActivationAddress ReadActivationAddress() { var silo = ReadSiloAddress(); var grain = ReadGrainId(); var act = ReadActivationId(); var mcstatus = ReadMultiClusterStatus(); if (silo.Equals(SiloAddress.Zero)) silo = null; if (act.Equals(ActivationId.Zero)) act = null; return ActivationAddress.GetAddress(silo, grain, act, mcstatus); } /// <summary> /// Read a block of data into the specified output <c>Array</c>. /// </summary> /// <param name="array">Array to output the data to.</param> /// <param name="n">Number of bytes to read.</param> public void ReadBlockInto(Array array, int n) { var buff = CheckLength(n); Buffer.BlockCopy(buff.Array, buff.Offset, array, 0, n); Trace("--Read block of {0} bytes", n); } /// <summary> /// Peek at the next token in this input stream. /// </summary> /// <returns>Next token thatr will be read from the stream.</returns> internal SerializationTokenType PeekToken() { if (currentOffset == currentSegment.Count + currentSegment.Offset) StartNextSegment(); return (SerializationTokenType)currentBuffer[currentOffset]; } /// <summary> Read a <c>SerializationTokenType</c> value from the stream. </summary> /// <returns>Data from current position in stream, converted to the appropriate output type.</returns> internal SerializationTokenType ReadToken() { var buff = CheckLength(1); Trace("--Read token {0}", (SerializationTokenType)buff.Array[buff.Offset]); return (SerializationTokenType)buff.Array[buff.Offset]; } internal bool TryReadSimpleType(out object result, out SerializationTokenType token) { token = ReadToken(); byte[] bytes; switch (token) { case SerializationTokenType.True: result = true; break; case SerializationTokenType.False: result = false; break; case SerializationTokenType.Null: result = null; break; case SerializationTokenType.Object: result = new object(); break; case SerializationTokenType.Int: result = ReadInt(); break; case SerializationTokenType.Uint: result = ReadUInt(); break; case SerializationTokenType.Short: result = ReadShort(); break; case SerializationTokenType.Ushort: result = ReadUShort(); break; case SerializationTokenType.Long: result = ReadLong(); break; case SerializationTokenType.Ulong: result = ReadULong(); break; case SerializationTokenType.Byte: result = ReadByte(); break; case SerializationTokenType.Sbyte: result = ReadSByte(); break; case SerializationTokenType.Float: result = ReadFloat(); break; case SerializationTokenType.Double: result = ReadDouble(); break; case SerializationTokenType.Decimal: result = ReadDecimal(); break; case SerializationTokenType.String: result = ReadString(); break; case SerializationTokenType.Character: result = ReadChar(); break; case SerializationTokenType.Guid: bytes = ReadBytes(16); result = new Guid(bytes); break; case SerializationTokenType.Date: result = DateTime.FromBinary(ReadLong()); break; case SerializationTokenType.TimeSpan: result = new TimeSpan(ReadLong()); break; case SerializationTokenType.GrainId: result = ReadGrainId(); break; case SerializationTokenType.ActivationId: result = ReadActivationId(); break; case SerializationTokenType.SiloAddress: result = ReadSiloAddress(); break; case SerializationTokenType.ActivationAddress: result = ReadActivationAddress(); break; case SerializationTokenType.IpAddress: result = ReadIPAddress(); break; case SerializationTokenType.IpEndPoint: result = ReadIPEndPoint(); break; case SerializationTokenType.CorrelationId: result = new CorrelationId(ReadBytes(CorrelationId.SIZE_BYTES)); break; default: result = null; return false; } return true; } /// <summary> Read a <c>Type</c> value from the stream. </summary> /// <param name="expected">Expected Type, if known.</param> /// <returns>Data from current position in stream, converted to the appropriate output type.</returns> public Type ReadFullTypeHeader(Type expected = null) { var token = ReadToken(); if (token == SerializationTokenType.ExpectedType) { return expected; } var t = CheckSpecialTypeCode(token); if (t != null) { return t; } if (token == SerializationTokenType.SpecifiedType) { #if TRACE_SERIALIZATION var tt = ReadSpecifiedTypeHeader(); Trace("--Read specified type header for type {0}", tt); return tt; #else return ReadSpecifiedTypeHeader(); #endif } throw new SerializationException("Invalid '" + token + "'token in input stream where full type header is expected"); } internal static Type CheckSpecialTypeCode(SerializationTokenType token) { switch (token) { case SerializationTokenType.Boolean: return typeof(bool); case SerializationTokenType.Int: return typeof(int); case SerializationTokenType.Short: return typeof(short); case SerializationTokenType.Long: return typeof(long); case SerializationTokenType.Sbyte: return typeof(sbyte); case SerializationTokenType.Uint: return typeof(uint); case SerializationTokenType.Ushort: return typeof(ushort); case SerializationTokenType.Ulong: return typeof(ulong); case SerializationTokenType.Byte: return typeof(byte); case SerializationTokenType.Float: return typeof(float); case SerializationTokenType.Double: return typeof(double); case SerializationTokenType.Decimal: return typeof(decimal); case SerializationTokenType.String: return typeof(string); case SerializationTokenType.Character: return typeof(char); case SerializationTokenType.Guid: return typeof(Guid); case SerializationTokenType.Date: return typeof(DateTime); case SerializationTokenType.TimeSpan: return typeof(TimeSpan); case SerializationTokenType.IpAddress: return typeof(IPAddress); case SerializationTokenType.IpEndPoint: return typeof(IPEndPoint); case SerializationTokenType.GrainId: return typeof(GrainId); case SerializationTokenType.ActivationId: return typeof(ActivationId); case SerializationTokenType.SiloAddress: return typeof(SiloAddress); case SerializationTokenType.ActivationAddress: return typeof(ActivationAddress); case SerializationTokenType.CorrelationId: return typeof(CorrelationId); #if false // Note: not yet implemented as simple types on the Writer side case SerializationTokenType.Object: return typeof(Object); case SerializationTokenType.ByteArray: return typeof(byte[]); case SerializationTokenType.ShortArray: return typeof(short[]); case SerializationTokenType.IntArray: return typeof(int[]); case SerializationTokenType.LongArray: return typeof(long[]); case SerializationTokenType.UShortArray: return typeof(ushort[]); case SerializationTokenType.UIntArray: return typeof(uint[]); case SerializationTokenType.ULongArray: return typeof(ulong[]); case SerializationTokenType.FloatArray: return typeof(float[]); case SerializationTokenType.DoubleArray: return typeof(double[]); case SerializationTokenType.CharArray: return typeof(char[]); case SerializationTokenType.BoolArray: return typeof(bool[]); #endif default: break; } return null; } /// <summary> Read a <c>Type</c> value from the stream. </summary> internal Type ReadSpecifiedTypeHeader() { // Assumes that the SpecifiedType token has already been read var token = ReadToken(); switch (token) { case SerializationTokenType.Boolean: return typeof(bool); case SerializationTokenType.Int: return typeof(int); case SerializationTokenType.Short: return typeof(short); case SerializationTokenType.Long: return typeof(long); case SerializationTokenType.Sbyte: return typeof(sbyte); case SerializationTokenType.Uint: return typeof(uint); case SerializationTokenType.Ushort: return typeof(ushort); case SerializationTokenType.Ulong: return typeof(ulong); case SerializationTokenType.Byte: return typeof(byte); case SerializationTokenType.Float: return typeof(float); case SerializationTokenType.Double: return typeof(double); case SerializationTokenType.Decimal: return typeof(decimal); case SerializationTokenType.String: return typeof(string); case SerializationTokenType.Character: return typeof(char); case SerializationTokenType.Guid: return typeof(Guid); case SerializationTokenType.Date: return typeof(DateTime); case SerializationTokenType.TimeSpan: return typeof(TimeSpan); case SerializationTokenType.IpAddress: return typeof(IPAddress); case SerializationTokenType.IpEndPoint: return typeof(IPEndPoint); case SerializationTokenType.GrainId: return typeof(GrainId); case SerializationTokenType.ActivationId: return typeof(ActivationId); case SerializationTokenType.SiloAddress: return typeof(SiloAddress); case SerializationTokenType.ActivationAddress: return typeof(ActivationAddress); case SerializationTokenType.CorrelationId: return typeof(CorrelationId); case SerializationTokenType.Request: return typeof(InvokeMethodRequest); case SerializationTokenType.Response: return typeof(Response); case SerializationTokenType.StringObjDict: return typeof(Dictionary<string, object>); case SerializationTokenType.Object: return typeof(Object); case SerializationTokenType.Tuple + 1: Trace("----Reading type info for a Tuple'1"); return typeof(Tuple<>).MakeGenericType(ReadGenericArguments(1)); case SerializationTokenType.Tuple + 2: Trace("----Reading type info for a Tuple'2"); return typeof(Tuple<,>).MakeGenericType(ReadGenericArguments(2)); case SerializationTokenType.Tuple + 3: Trace("----Reading type info for a Tuple'3"); return typeof(Tuple<,,>).MakeGenericType(ReadGenericArguments(3)); case SerializationTokenType.Tuple + 4: Trace("----Reading type info for a Tuple'4"); return typeof(Tuple<,,,>).MakeGenericType(ReadGenericArguments(4)); case SerializationTokenType.Tuple + 5: Trace("----Reading type info for a Tuple'5"); return typeof(Tuple<,,,,>).MakeGenericType(ReadGenericArguments(5)); case SerializationTokenType.Tuple + 6: Trace("----Reading type info for a Tuple'6"); return typeof(Tuple<,,,,,>).MakeGenericType(ReadGenericArguments(6)); case SerializationTokenType.Tuple + 7: Trace("----Reading type info for a Tuple'7"); return typeof(Tuple<,,,,,,>).MakeGenericType(ReadGenericArguments(7)); case SerializationTokenType.Array + 1: var et1 = ReadFullTypeHeader(); return et1.MakeArrayType(); case SerializationTokenType.Array + 2: var et2 = ReadFullTypeHeader(); return et2.MakeArrayType(2); case SerializationTokenType.Array + 3: var et3 = ReadFullTypeHeader(); return et3.MakeArrayType(3); case SerializationTokenType.Array + 4: var et4 = ReadFullTypeHeader(); return et4.MakeArrayType(4); case SerializationTokenType.Array + 5: var et5 = ReadFullTypeHeader(); return et5.MakeArrayType(5); case SerializationTokenType.Array + 6: var et6 = ReadFullTypeHeader(); return et6.MakeArrayType(6); case SerializationTokenType.Array + 7: var et7 = ReadFullTypeHeader(); return et7.MakeArrayType(7); case SerializationTokenType.Array + 8: var et8 = ReadFullTypeHeader(); return et8.MakeArrayType(8); case SerializationTokenType.List: return typeof(List<>).MakeGenericType(ReadGenericArguments(1)); case SerializationTokenType.Dictionary: return typeof(Dictionary<,>).MakeGenericType(ReadGenericArguments(2)); case SerializationTokenType.KeyValuePair: return typeof(KeyValuePair<,>).MakeGenericType(ReadGenericArguments(2)); case SerializationTokenType.Set: return typeof(HashSet<>).MakeGenericType(ReadGenericArguments(1)); case SerializationTokenType.SortedList: return typeof(SortedList<,>).MakeGenericType(ReadGenericArguments(2)); case SerializationTokenType.SortedSet: return typeof(SortedSet<>).MakeGenericType(ReadGenericArguments(1)); case SerializationTokenType.Stack: return typeof(Stack<>).MakeGenericType(ReadGenericArguments(1)); case SerializationTokenType.Queue: return typeof(Queue<>).MakeGenericType(ReadGenericArguments(1)); case SerializationTokenType.LinkedList: return typeof(LinkedList<>).MakeGenericType(ReadGenericArguments(1)); case SerializationTokenType.Nullable: return typeof(Nullable<>).MakeGenericType(ReadGenericArguments(1)); case SerializationTokenType.ByteArray: return typeof(byte[]); case SerializationTokenType.ShortArray: return typeof(short[]); case SerializationTokenType.IntArray: return typeof(int[]); case SerializationTokenType.LongArray: return typeof(long[]); case SerializationTokenType.UShortArray: return typeof(ushort[]); case SerializationTokenType.UIntArray: return typeof(uint[]); case SerializationTokenType.ULongArray: return typeof(ulong[]); case SerializationTokenType.FloatArray: return typeof(float[]); case SerializationTokenType.DoubleArray: return typeof(double[]); case SerializationTokenType.CharArray: return typeof(char[]); case SerializationTokenType.BoolArray: return typeof(bool[]); case SerializationTokenType.NamedType: var typeName = ReadString(); try { return SerializationManager.ResolveTypeName(typeName); } catch (TypeAccessException ex) { throw new TypeAccessException("Named type \"" + typeName + "\" is invalid: " + ex.Message); } default: break; } throw new SerializationException("Unexpected '" + token + "' found when expecting a type reference"); } private Type[] ReadGenericArguments(int n) { Trace("About to read {0} generic arguments", n); var args = new Type[n]; for (var i = 0; i < n; i++) { args[i] = ReadFullTypeHeader(); } Trace("Finished reading {0} generic arguments", n); return args; } private StreamWriter trace; [Conditional("TRACE_SERIALIZATION")] private void Trace(string format, params object[] args) { if (trace == null) { var path = String.Format("d:\\Trace-{0}.{1}.{2}.txt", DateTime.UtcNow.Hour, DateTime.UtcNow.Minute, DateTime.UtcNow.Ticks); Console.WriteLine("Opening trace file at '{0}'", path); trace = File.CreateText(path); } trace.Write(format, args); trace.WriteLine(" at offset {0}", CurrentPosition); trace.Flush(); } } }
mit
reasonml-editor/reasonml-idea-plugin
src/com/reason/lang/core/stub/type/PsiModuleStubElementType.java
2966
package com.reason.lang.core.stub.type; import com.intellij.lang.Language; import com.intellij.psi.stubs.IndexSink; import com.intellij.psi.stubs.StubElement; import com.intellij.psi.stubs.StubInputStream; import com.intellij.psi.stubs.StubOutputStream; import com.intellij.util.io.StringRef; import com.reason.ide.search.index.IndexKeys; import com.reason.lang.core.psi.PsiModule; import com.reason.lang.core.stub.PsiModuleStub; import java.io.IOException; import org.jetbrains.annotations.NotNull; public abstract class PsiModuleStubElementType extends ORStubElementType<PsiModuleStub, PsiModule> { public PsiModuleStubElementType(@NotNull String name, Language language) { super(name, language); } @NotNull public PsiModuleStub createStub(@NotNull final PsiModule psi, final StubElement parentStub) { return new PsiModuleStub( parentStub, this, psi.getName(), psi.getPath(), psi.getAlias(), psi.isComponent(), psi.isInterface()); } public void serialize( @NotNull final PsiModuleStub stub, @NotNull final StubOutputStream dataStream) throws IOException { dataStream.writeName(stub.getName()); dataStream.writeUTFFast(stub.getPath()); dataStream.writeBoolean(stub.isComponent()); dataStream.writeBoolean(stub.isInterface()); String alias = stub.getAlias(); dataStream.writeBoolean(alias != null); if (alias != null) { dataStream.writeUTFFast(stub.getAlias()); } } @NotNull public PsiModuleStub deserialize( @NotNull final StubInputStream dataStream, final StubElement parentStub) throws IOException { StringRef moduleName = dataStream.readName(); String path = dataStream.readUTFFast(); boolean isComponent = dataStream.readBoolean(); boolean isInterface = dataStream.readBoolean(); String alias = null; boolean isAlias = dataStream.readBoolean(); if (isAlias) { alias = dataStream.readUTFFast(); } return new PsiModuleStub(parentStub, this, moduleName, path, alias, isComponent, isInterface); } public void indexStub(@NotNull final PsiModuleStub stub, @NotNull final IndexSink sink) { String name = stub.getName(); if (name != null) { sink.occurrence(IndexKeys.MODULES, name); if (stub.isComponent()) { sink.occurrence(IndexKeys.MODULES_COMP, name); } } int fqnHash = stub.getQualifiedName().hashCode(); sink.occurrence(IndexKeys.MODULES_FQN, fqnHash); if (stub.isComponent()) { sink.occurrence(IndexKeys.MODULES_COMP_FQN, fqnHash); } } @NotNull public String getExternalId() { return getLanguage().getID() + "." + super.toString(); } }
mit
akhan-weltkind/newtek
app/Modules/Admin/Resources/Views/common/topmenu/all.blade.php
226
@if (isset($routePrefix)) <div class="header-module-controls"> @include('admin::common.topmenu.list', ['routePrefix'=>$routePrefix]) @include('admin::common.topmenu.create', ['routePrefix'=>$routePrefix]) </div> @endif
mit
JonMercer/Join-Daily-Wave-Files-to-Weekly-Wave-Files
WavWeeklyJoin.java
6502
import java.io.*; import java.util.*; import java.nio.file.Files; import javax.sound.sampled.AudioFileFormat; import javax.sound.sampled.AudioInputStream; import javax.sound.sampled.AudioSystem; import java.text.SimpleDateFormat; import java.text.DateFormat; // The MIT License (MIT) // Copyright (c) [2014] [Jonathan J Mercer] // 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. /** * @author: Jonathan J Mercer * * What it does (TLDR): Concatinates multiple WAV files into one large one based on week created * * This code works on my 2013 MBP Retina runing OSX 10.9.2 * * Thanks to the following for their code in StackOverflow * -James Van Huis: merging audio files * -Ralph: week number of the year * * @Requirements: * -Bit-rate and sample rate of WAV files must be exactly the same * -There must be an "intro.wav" inside the "INPUT" folder * -Path of input and output folders * -Name of wav files must be "yyyy-mm-dd....wav" */ class WavWeeklyJoin { //You can change these based on your system private static final String INPUT_PATH = "/Users/Odin/Desktop/testfolder"; private static final String OUTOUT_PATH = "/Users/Odin/Desktop"; private static final String INTRO = "intro.wav"; /** * Contains the main logic of the code. Calls a bunch of helper functions */ public static void main(String[] args) { try { //Simple counters int weekNum = -1; int previousWeekNum = -1; int yearNum = -1; int previousYearNum = -1; //Initialize the currentWav AudioInputStream currentWav = AudioSystem.getAudioInputStream(new File(INPUT_PATH+"/"+INTRO)); //Make a list of all items in the folder and itterate through them File folder = new File(INPUT_PATH); File[] listOfFiles = folder.listFiles(); for (File file : listOfFiles) { if (file.isFile() && file.getName().contains(".wav") && file.getName().contains("-")) { weekNum = findWeekNum(file.getName()); yearNum = findYearNum(file.getName()); //Checks if weeknum has changed if(weekNum != previousWeekNum) { if(previousWeekNum > 0) { System.out.println("<-- Writing WAV with year "+previousYearNum+" and week " + previousWeekNum); writeWav(currentWav,previousWeekNum,previousYearNum); } System.out.println("<-- Creating new WAV"); currentWav = AudioSystem.getAudioInputStream(new File(INPUT_PATH+"/"+INTRO)); currentWav = appendWav(currentWav,file.getName()); previousWeekNum = weekNum; previousYearNum = yearNum; } else { System.out.println("<-- Appending WAV"); currentWav = appendWav(currentWav,file.getName()); } } } System.out.println("<-- Writing final WAV"); writeWav(currentWav,previousWeekNum,yearNum); } catch (Exception e) { e.printStackTrace(); } } /** * Find the week number based on date * @param String date * @return int week number */ public static int findWeekNum(String date) { try{ //Strips out just the date from the file name String shortDate = date.substring(0,10); DateFormat sdf = new SimpleDateFormat("yyyy-MM-dd"); Date parsedShortDate = sdf.parse(shortDate); Calendar calUs = Calendar.getInstance(Locale.US); calUs.setTime(parsedShortDate); return calUs.get( Calendar.WEEK_OF_YEAR ); } catch (Exception e) { System.out.println("Error"); } return -1;//note: this return value is not handled properly on the other end } /** * Find the year number based on date * @param String date * @return int year number */ public static int findYearNum(String date) { return Integer.parseInt(date.substring(0,4)); } /** * Appends two WAV files * @param AudioInputStream currentWav: the main file * @param String appendName: a name of a WAV file that exists in the INPUT_PATH * @return AudioInputStream appended WAV files */ public static AudioInputStream appendWav(AudioInputStream currentWav, String appendName) { try{ AudioInputStream toAppend = AudioSystem.getAudioInputStream(new File(INPUT_PATH+"/"+appendName)); AudioInputStream appendedFiles = new AudioInputStream( new SequenceInputStream(currentWav, toAppend), currentWav.getFormat(), currentWav.getFrameLength() + toAppend.getFrameLength()); return appendedFiles; } catch (Exception e) { e.printStackTrace(); } //Note, I'm not catching this null on the return. return null; } /** * Writes the appended WAV files into the output folder * @param AudioInputStream wav: the file we want to write * @param int week: * @param int year: */ public static void writeWav(AudioInputStream wav, int week, int year) { try { if(week < 10) { //Prepend a 0 infront of the number AudioSystem.write(wav, AudioFileFormat.Type.WAVE, new File(OUTOUT_PATH+"/"+year+"-0"+week+".wav")); } else { AudioSystem.write(wav, AudioFileFormat.Type.WAVE, new File(OUTOUT_PATH+"/"+year+"-"+week+".wav")); } } catch (Exception e) { System.out.println("Error in writeWav"); e.printStackTrace(); } } }
mit
executablebooks/markdown-it-py
markdown_it/__init__.py
113
"""A Python port of Markdown-It""" __all__ = ("MarkdownIt",) __version__ = "2.0.1" from .main import MarkdownIt
mit
realitix/cvulkan
cvulkan/example/example.py
23749
# flake8: noqa import ctypes import os import sdl2 import sdl2.ext from vulkan import * WIDTH = 400 HEIGHT = 400 # ---------- # Create instance appInfo = VkApplicationInfo( sType=VK_STRUCTURE_TYPE_APPLICATION_INFO, pApplicationName="Hello Triangle", applicationVersion=VK_MAKE_VERSION(1, 0, 0), pEngineName="No Engine", engineVersion=VK_MAKE_VERSION(1, 0, 0), apiVersion=VK_API_VERSION_1_0) extensions = vkEnumerateInstanceExtensionProperties(None) extensions = [e.extensionName for e in extensions] print("availables extensions: %s\n" % extensions) layers = vkEnumerateInstanceLayerProperties(None) layers = [l.layerName for l in layers] print("availables layers: %s\n" % layers) layers = ['VK_LAYER_LUNARG_standard_validation'] extensions = ['VK_KHR_surface', 'VK_KHR_xlib_surface', 'VK_EXT_debug_report'] createInfo = VkInstanceCreateInfo( sType=VK_STRUCTURE_TYPE_INSTANCE_CREATE_INFO, flags=0, pApplicationInfo=appInfo, enabledExtensionCount=len(extensions), ppEnabledExtensionNames=extensions, enabledLayerCount=len(layers), ppEnabledLayerNames=layers) instance = vkCreateInstance(pCreateInfo=createInfo) # ---------- # Debug instance vkCreateDebugReportCallbackEXT = vkGetInstanceProcAddr( instance, "vkCreateDebugReportCallbackEXT") vkDestroyDebugReportCallbackEXT = vkGetInstanceProcAddr( instance, "vkDestroyDebugReportCallbackEXT") def debugCallback(*args): print(args) debug_create = VkDebugReportCallbackCreateInfoEXT( sType=VK_STRUCTURE_TYPE_DEBUG_REPORT_CALLBACK_CREATE_INFO_EXT, flags=VK_DEBUG_REPORT_ERROR_BIT_EXT | VK_DEBUG_REPORT_WARNING_BIT_EXT, pfnCallback=debugCallback) callback = vkCreateDebugReportCallbackEXT(instance=instance, pCreateInfo=debug_create) # ---------- # Init sdl2 if sdl2.SDL_Init(sdl2.SDL_INIT_VIDEO) != 0: raise Exception(sdl2.SDL_GetError()) window = sdl2.SDL_CreateWindow( 'test'.encode('ascii'), sdl2.SDL_WINDOWPOS_UNDEFINED, sdl2.SDL_WINDOWPOS_UNDEFINED, WIDTH, HEIGHT, 0) if not window: raise Exception(sdl2.SDL_GetError()) wm_info = sdl2.SDL_SysWMinfo() sdl2.SDL_VERSION(wm_info.version) sdl2.SDL_GetWindowWMInfo(window, ctypes.byref(wm_info)) # ---------- # Create surface vkDestroySurfaceKHR = vkGetInstanceProcAddr(instance, "vkDestroySurfaceKHR") def surface_xlib(): print("Create Xlib surface") vkCreateXlibSurfaceKHR = vkGetInstanceProcAddr(instance, "vkCreateXlibSurfaceKHR") surface_create = VkXlibSurfaceCreateInfoKHR( sType=VK_STRUCTURE_TYPE_XLIB_SURFACE_CREATE_INFO_KHR, dpy=wm_info.info.x11.display, window=wm_info.info.x11.window, flags=0) return vkCreateXlibSurfaceKHR(instance=instance, pCreateInfo=surface_create) def surface_mir(): print("Create mir surface") vkCreateMirSurfaceKHR = vkGetInstanceProcAddr(instance, "vkCreateMirSurfaceKHR") surface_create = VkMirSurfaceCreateInfoKHR( sType=VK_STRUCTURE_TYPE_MIR_SURFACE_CREATE_INFO_KHR, connection=wm_info.info.mir.connection, mirSurface=wm_info.info.mir.surface, flags=0) return vkCreateMirSurfaceKHR(instance=instance, pCreateInfo=surface_create) def surface_wayland(): print("Create wayland surface") vkCreateWaylandSurfaceKHR = vkGetInstanceProcAddr(instance, "vkCreateWaylandSurfaceKHR") surface_create = VkWaylandSurfaceCreateInfoKHR( sType=VK_STRUCTURE_TYPE_WAYLAND_SURFACE_CREATE_INFO_KHR, display=wm_info.info.wl.display, surface=wm_info.info.surface, flags=0) return vkCreateWaylandSurfaceKHR(instance=instance, pCreateInfo=surface_create) def surface_win32(): print("Create windows surface") vkCreateWin32SurfaceKHR = vkGetInstanceProcAddr(instance, "vkCreateWin32SurfaceKHR") surface_create = VkWin32SurfaceCreateInfoKHR( sType=VK_STRUCTURE_TYPE_WAYLAND_SURFACE_CREATE_INFO_KHR, hinstance='TODO', hwdn=wm_info.info.win.window, flags=0) return vkCreateWin32SurfaceKHR(instance=instance, pCreateInfo=surface_create) surface_mapping = { sdl2.SDL_SYSWM_X11: surface_xlib} surface = surface_mapping[wm_info.subsystem]() # ---------- # Select physical device physical_devices = vkEnumeratePhysicalDevices(instance) physical_devices_features = {physical_device: vkGetPhysicalDeviceFeatures(physical_device) for physical_device in physical_devices} physical_devices_properties = {physical_device: vkGetPhysicalDeviceProperties(physical_device) for physical_device in physical_devices} physical_device = physical_devices[0] print("availables devices: %s" % [p.deviceName for p in physical_devices_properties.values()]) print("selected device: %s\n" % physical_devices_properties[physical_device].deviceName) # ---------- # Select queue family vkGetPhysicalDeviceSurfaceSupportKHR = vkGetInstanceProcAddr( instance, 'vkGetPhysicalDeviceSurfaceSupportKHR') queue_families = vkGetPhysicalDeviceQueueFamilyProperties(physicalDevice=physical_device) print("%s available queue family" % len(queue_families)) queue_family_graphic_index = -1 queue_family_present_index = -1 for i, queue_family in enumerate(queue_families): support_present = vkGetPhysicalDeviceSurfaceSupportKHR( physicalDevice=physical_device, queueFamilyIndex=i, surface=surface) if (queue_family.queueCount > 0 and queue_family.queueFlags & VK_QUEUE_GRAPHICS_BIT): queue_family_graphic_index = i if queue_family.queueCount > 0 and support_present: queue_family_present_index = i print("indice of selected queue families, graphic: %s, presentation: %s\n" % ( queue_family_graphic_index, queue_family_present_index)) # ---------- # Create logical device and queues extensions = vkEnumerateDeviceExtensionProperties(physicalDevice=physical_device, pLayerName=None) extensions = [e.extensionName for e in extensions] print("availables device extensions: %s\n" % extensions) queues_create = [VkDeviceQueueCreateInfo(sType=VK_STRUCTURE_TYPE_DEVICE_QUEUE_CREATE_INFO, queueFamilyIndex=i, queueCount=1, pQueuePriorities=[1], flags=0) for i in {queue_family_graphic_index, queue_family_present_index}] device_create = VkDeviceCreateInfo( sType=VK_STRUCTURE_TYPE_DEVICE_CREATE_INFO, pQueueCreateInfos=queues_create, queueCreateInfoCount=len(queues_create), pEnabledFeatures=physical_devices_features[physical_device], flags=0, enabledLayerCount=len(layers), ppEnabledLayerNames=layers, enabledExtensionCount=len(extensions), ppEnabledExtensionNames=extensions ) logical_device = vkCreateDevice(physicalDevice=physical_device, pCreateInfo=device_create) graphic_queue = vkGetDeviceQueue( device=logical_device, queueFamilyIndex=queue_family_graphic_index, queueIndex=0) presentation_queue = vkGetDeviceQueue( device=logical_device, queueFamilyIndex=queue_family_present_index, queueIndex=0) print("Logical device and graphic queue successfully created\n") # ---------- # Create swapchain vkGetPhysicalDeviceSurfaceCapabilitiesKHR = vkGetInstanceProcAddr(instance, "vkGetPhysicalDeviceSurfaceCapabilitiesKHR") vkGetPhysicalDeviceSurfaceFormatsKHR = vkGetInstanceProcAddr(instance, "vkGetPhysicalDeviceSurfaceFormatsKHR") vkGetPhysicalDeviceSurfacePresentModesKHR = vkGetInstanceProcAddr(instance, "vkGetPhysicalDeviceSurfacePresentModesKHR") surface_capabilities = vkGetPhysicalDeviceSurfaceCapabilitiesKHR(physicalDevice=physical_device, surface=surface) surface_formats = vkGetPhysicalDeviceSurfaceFormatsKHR(physicalDevice=physical_device, surface=surface) surface_present_modes = vkGetPhysicalDeviceSurfacePresentModesKHR(physicalDevice=physical_device, surface=surface) if not surface_formats or not surface_present_modes: raise Exception('No available swapchain') def get_surface_format(formats): for f in formats: if f.format == VK_FORMAT_UNDEFINED: return f if (f.format == VK_FORMAT_B8G8R8A8_UNORM and f.colorSpace == VK_COLOR_SPACE_SRGB_NONLINEAR_KHR): return f return formats[0] def get_surface_present_mode(present_modes): for p in present_modes: if p == VK_PRESENT_MODE_MAILBOX_KHR: return p return VK_PRESENT_MODE_FIFO_KHR; def get_swap_extent(capabilities): uint32_max = 4294967295 if capabilities.currentExtent.width != uint32_max: return capabilities.currentExtent width = max( capabilities.minImageExtent.width, min(capabilities.maxImageExtent.width, WIDTH)) height = max( capabilities.minImageExtent.height, min(capabilities.maxImageExtent.height, HEIGHT)) actualExtent = VkExtent2D(width=width, height=height); return actualExtent surface_format = get_surface_format(surface_formats) present_mode = get_surface_present_mode(surface_present_modes) extent = get_swap_extent(surface_capabilities) imageCount = surface_capabilities.minImageCount + 1; if surface_capabilities.maxImageCount > 0 and imageCount > surface_capabilities.maxImageCount: imageCount = surface_capabilities.maxImageCount print('selected format: %s' % surface_format.format) print('%s available swapchain present modes' % len(surface_present_modes)) imageSharingMode = VK_SHARING_MODE_EXCLUSIVE queueFamilyIndexCount = 0 pQueueFamilyIndices = None if queue_family_graphic_index != queue_family_present_index: imageSharingMode = VK_SHARING_MODE_CONCURREN queueFamilyIndexCount = 2 pQueueFamilyIndices = queueFamilyIndices vkCreateSwapchainKHR = vkGetInstanceProcAddr(instance, 'vkCreateSwapchainKHR') vkDestroySwapchainKHR = vkGetInstanceProcAddr(instance, 'vkDestroySwapchainKHR') vkGetSwapchainImagesKHR = vkGetInstanceProcAddr(instance, 'vkGetSwapchainImagesKHR') swapchain_create = VkSwapchainCreateInfoKHR( sType=VK_STRUCTURE_TYPE_SWAPCHAIN_CREATE_INFO_KHR, flags=0, surface=surface, minImageCount=imageCount, imageFormat=surface_format.format, imageColorSpace=surface_format.colorSpace, imageExtent=extent, imageArrayLayers=1, imageUsage=VK_IMAGE_USAGE_COLOR_ATTACHMENT_BIT, imageSharingMode=imageSharingMode, queueFamilyIndexCount=queueFamilyIndexCount, pQueueFamilyIndices=pQueueFamilyIndices, compositeAlpha=VK_COMPOSITE_ALPHA_OPAQUE_BIT_KHR, presentMode=present_mode, clipped=VK_TRUE, oldSwapchain=None, preTransform=surface_capabilities.currentTransform) swapchain = vkCreateSwapchainKHR(logical_device, swapchain_create) swapchain_images = vkGetSwapchainImagesKHR(logical_device, swapchain) # Create image view for each image in swapchain image_views = [] for image in swapchain_images: subresourceRange = VkImageSubresourceRange( aspectMask=VK_IMAGE_ASPECT_COLOR_BIT, baseMipLevel=0, levelCount=1, baseArrayLayer=0, layerCount=1) components = VkComponentMapping( r=VK_COMPONENT_SWIZZLE_IDENTITY, g=VK_COMPONENT_SWIZZLE_IDENTITY, b=VK_COMPONENT_SWIZZLE_IDENTITY, a=VK_COMPONENT_SWIZZLE_IDENTITY) imageview_create = VkImageViewCreateInfo( sType=VK_STRUCTURE_TYPE_IMAGE_VIEW_CREATE_INFO, image=image, flags=0, viewType=VK_IMAGE_VIEW_TYPE_2D, format=surface_format.format, components=components, subresourceRange=subresourceRange) image_views.append(vkCreateImageView(logical_device, imageview_create)) print("%s images view created" % len(image_views)) # Load spirv shader path = os.path.dirname(os.path.abspath(__file__)) with open(os.path.join(path, "vert.spv"), 'rb') as f: vert_shader_spirv = f.read() with open(os.path.join(path, "frag.spv"), 'rb') as f: frag_shader_spirv = f.read() # Create shader vert_shader_create = VkShaderModuleCreateInfo( sType=VK_STRUCTURE_TYPE_SHADER_MODULE_CREATE_INFO, flags=0, codeSize=len(vert_shader_spirv), pCode=vert_shader_spirv) vert_shader_module = vkCreateShaderModule(logical_device, vert_shader_create) frag_shader_create = VkShaderModuleCreateInfo( sType=VK_STRUCTURE_TYPE_SHADER_MODULE_CREATE_INFO, flags=0, codeSize=len(frag_shader_spirv), pCode=frag_shader_spirv) frag_shader_module = vkCreateShaderModule(logical_device, frag_shader_create) # Create shader stage vert_stage_create = VkPipelineShaderStageCreateInfo( sType=VK_STRUCTURE_TYPE_PIPELINE_SHADER_STAGE_CREATE_INFO, stage=VK_SHADER_STAGE_VERTEX_BIT, module=vert_shader_module, flags=0, pSpecializationInfo=None, pName='main') frag_stage_create = VkPipelineShaderStageCreateInfo( sType=VK_STRUCTURE_TYPE_PIPELINE_SHADER_STAGE_CREATE_INFO, stage=VK_SHADER_STAGE_FRAGMENT_BIT, module=frag_shader_module, flags=0, pSpecializationInfo=None, pName='main') # Create render pass color_attachement = VkAttachmentDescription( flags=0, format=surface_format.format, samples=VK_SAMPLE_COUNT_1_BIT, loadOp=VK_ATTACHMENT_LOAD_OP_CLEAR, storeOp=VK_ATTACHMENT_STORE_OP_STORE, stencilLoadOp=VK_ATTACHMENT_LOAD_OP_DONT_CARE, stencilStoreOp=VK_ATTACHMENT_STORE_OP_DONT_CARE, initialLayout=VK_IMAGE_LAYOUT_UNDEFINED, finalLayout=VK_IMAGE_LAYOUT_PRESENT_SRC_KHR) color_attachement_reference = VkAttachmentReference( attachment=0, layout=VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL) sub_pass = VkSubpassDescription( flags=0, pipelineBindPoint=VK_PIPELINE_BIND_POINT_GRAPHICS, inputAttachmentCount=0, pInputAttachments=None, pResolveAttachments=None, pDepthStencilAttachment=None, preserveAttachmentCount=0, pPreserveAttachments=None, colorAttachmentCount=1, pColorAttachments=[color_attachement_reference]) dependency = VkSubpassDependency( dependencyFlags=0, srcSubpass=VK_SUBPASS_EXTERNAL, dstSubpass=0, srcStageMask=VK_PIPELINE_STAGE_COLOR_ATTACHMENT_OUTPUT_BIT, srcAccessMask=0, dstStageMask=VK_PIPELINE_STAGE_COLOR_ATTACHMENT_OUTPUT_BIT, dstAccessMask=VK_ACCESS_COLOR_ATTACHMENT_READ_BIT | VK_ACCESS_COLOR_ATTACHMENT_WRITE_BIT) render_pass_create = VkRenderPassCreateInfo( flags=0, sType=VK_STRUCTURE_TYPE_RENDER_PASS_CREATE_INFO, attachmentCount=1, pAttachments=[color_attachement], subpassCount=1, pSubpasses=[sub_pass], dependencyCount=1, pDependencies=[dependency]) render_pass = vkCreateRenderPass(logical_device, render_pass_create) # Create graphic pipeline vertex_input_create = VkPipelineVertexInputStateCreateInfo( sType=VK_STRUCTURE_TYPE_PIPELINE_VERTEX_INPUT_STATE_CREATE_INFO, flags=0, vertexBindingDescriptionCount=0, pVertexBindingDescriptions=None, vertexAttributeDescriptionCount=0, pVertexAttributeDescriptions=None) input_assembly_create = VkPipelineInputAssemblyStateCreateInfo( sType=VK_STRUCTURE_TYPE_PIPELINE_INPUT_ASSEMBLY_STATE_CREATE_INFO, flags=0, topology=VK_PRIMITIVE_TOPOLOGY_TRIANGLE_LIST, primitiveRestartEnable=VK_FALSE) viewport = VkViewport( x=0., y=0., width=float(extent.width), height=float(extent.height), minDepth=0., maxDepth=1.) scissor_offset = VkOffset2D(x=0, y=0) scissor = VkRect2D(offset=scissor_offset, extent=extent) viewport_state_create = VkPipelineViewportStateCreateInfo( sType=VK_STRUCTURE_TYPE_PIPELINE_VIEWPORT_STATE_CREATE_INFO, flags=0, viewportCount=1, pViewports=[viewport], scissorCount=1, pScissors=[scissor]) rasterizer_create = VkPipelineRasterizationStateCreateInfo( sType=VK_STRUCTURE_TYPE_PIPELINE_RASTERIZATION_STATE_CREATE_INFO, flags=0, depthClampEnable=VK_FALSE, rasterizerDiscardEnable=VK_FALSE, polygonMode=VK_POLYGON_MODE_FILL, lineWidth=1, cullMode=VK_CULL_MODE_BACK_BIT, frontFace=VK_FRONT_FACE_CLOCKWISE, depthBiasEnable=VK_FALSE, depthBiasConstantFactor=0., depthBiasClamp=0., depthBiasSlopeFactor=0.) multisample_create = VkPipelineMultisampleStateCreateInfo( sType=VK_STRUCTURE_TYPE_PIPELINE_MULTISAMPLE_STATE_CREATE_INFO, flags=0, sampleShadingEnable=VK_FALSE, rasterizationSamples=VK_SAMPLE_COUNT_1_BIT, minSampleShading=1, pSampleMask=None, alphaToCoverageEnable=VK_FALSE, alphaToOneEnable=VK_FALSE) color_blend_attachement = VkPipelineColorBlendAttachmentState( colorWriteMask=VK_COLOR_COMPONENT_R_BIT | VK_COLOR_COMPONENT_G_BIT | VK_COLOR_COMPONENT_B_BIT | VK_COLOR_COMPONENT_A_BIT, blendEnable=VK_FALSE, srcColorBlendFactor=VK_BLEND_FACTOR_ONE, dstColorBlendFactor=VK_BLEND_FACTOR_ZERO, colorBlendOp=VK_BLEND_OP_ADD, srcAlphaBlendFactor=VK_BLEND_FACTOR_ONE, dstAlphaBlendFactor=VK_BLEND_FACTOR_ZERO, alphaBlendOp=VK_BLEND_OP_ADD) color_blend_create = VkPipelineColorBlendStateCreateInfo( sType=VK_STRUCTURE_TYPE_PIPELINE_COLOR_BLEND_STATE_CREATE_INFO, flags=0, logicOpEnable=VK_FALSE, logicOp=VK_LOGIC_OP_COPY, attachmentCount=1, pAttachments=[color_blend_attachement], blendConstants=[0, 0, 0, 0]) push_constant_ranges = VkPushConstantRange( stageFlags=0, offset=0, size=0) pipeline_layout_create = VkPipelineLayoutCreateInfo( sType=VK_STRUCTURE_TYPE_PIPELINE_LAYOUT_CREATE_INFO, flags=0, setLayoutCount=0, pSetLayouts=None, pushConstantRangeCount=0, pPushConstantRanges=[push_constant_ranges]) pipeline_layout = vkCreatePipelineLayout(logical_device, pipeline_layout_create) # Finally create graphic pipeline pipeline_create = VkGraphicsPipelineCreateInfo( sType=VK_STRUCTURE_TYPE_GRAPHICS_PIPELINE_CREATE_INFO, flags=0, stageCount=2, pStages=[vert_stage_create, frag_stage_create], pVertexInputState=vertex_input_create, pInputAssemblyState=input_assembly_create, pTessellationState=None, pViewportState=viewport_state_create, pRasterizationState=rasterizer_create, pMultisampleState=multisample_create, pDepthStencilState=None, pColorBlendState=color_blend_create, pDynamicState=None, layout=pipeline_layout, renderPass=render_pass, subpass=0, basePipelineHandle=None, basePipelineIndex=-1) pipeline = vkCreateGraphicsPipelines(logical_device, None, 1, [pipeline_create]) # Framebuffers creation framebuffers = [] for image in image_views: attachments = [image] framebuffer_create = VkFramebufferCreateInfo( sType=VK_STRUCTURE_TYPE_FRAMEBUFFER_CREATE_INFO, flags=0, renderPass=render_pass, attachmentCount=len(attachments), pAttachments=attachments, width=extent.width, height=extent.height, layers=1) framebuffers.append( vkCreateFramebuffer(logical_device, framebuffer_create)) # Create command pools command_pool_create = VkCommandPoolCreateInfo( sType=VK_STRUCTURE_TYPE_COMMAND_POOL_CREATE_INFO, queueFamilyIndex=queue_family_graphic_index, flags=0) command_pool = vkCreateCommandPool(logical_device, command_pool_create) # Create command buffers command_buffers_create = VkCommandBufferAllocateInfo( sType=VK_STRUCTURE_TYPE_COMMAND_BUFFER_ALLOCATE_INFO, commandPool=command_pool, level=VK_COMMAND_BUFFER_LEVEL_PRIMARY, commandBufferCount=len(framebuffers)) command_buffers = vkAllocateCommandBuffers(logical_device, command_buffers_create) # Record command buffer for i, command_buffer in enumerate(command_buffers): command_buffer_begin_create = VkCommandBufferBeginInfo( sType=VK_STRUCTURE_TYPE_COMMAND_BUFFER_BEGIN_INFO, flags=VK_COMMAND_BUFFER_USAGE_SIMULTANEOUS_USE_BIT, pInheritanceInfo=None) vkBeginCommandBuffer(command_buffer, command_buffer_begin_create) # Create render pass render_area = VkRect2D(offset=VkOffset2D(x=0, y=0), extent=extent) color = VkClearColorValue(float32=[0, 1, 0, 1]) clear_value = VkClearValue(color=color) render_pass_begin_create = VkRenderPassBeginInfo( sType=VK_STRUCTURE_TYPE_RENDER_PASS_BEGIN_INFO, renderPass=render_pass, framebuffer=framebuffers[i], renderArea=render_area, clearValueCount=1, pClearValues=[clear_value]) vkCmdBeginRenderPass(command_buffer, render_pass_begin_create, VK_SUBPASS_CONTENTS_INLINE) # Bing pipeline vkCmdBindPipeline(command_buffer, VK_PIPELINE_BIND_POINT_GRAPHICS, pipeline) # Draw vkCmdDraw(command_buffer, 3, 1, 0, 0) # End vkCmdEndRenderPass(command_buffer) vkEndCommandBuffer(command_buffer) # Create semaphore semaphore_create = VkSemaphoreCreateInfo( sType=VK_STRUCTURE_TYPE_SEMAPHORE_CREATE_INFO, flags=0) semaphore_image_available = vkCreateSemaphore(logical_device, semaphore_create) semaphore_render_finished = vkCreateSemaphore(logical_device, semaphore_create) vkAcquireNextImageKHR = vkGetInstanceProcAddr(instance, "vkAcquireNextImageKHR") vkQueuePresentKHR = vkGetInstanceProcAddr(instance, "vkQueuePresentKHR") def draw_frame(): try: image_index = vkAcquireNextImageKHR(logical_device, swapchain, UINT64_MAX, semaphore_image_available, None) except VkNotReady: print('not ready') return wait_semaphores = [semaphore_image_available] wait_stages = [VK_PIPELINE_STAGE_COLOR_ATTACHMENT_OUTPUT_BIT] signal_semaphores = [semaphore_render_finished] cbs = [command_buffers[image_index]] submit_create = VkSubmitInfo( sType=VK_STRUCTURE_TYPE_SUBMIT_INFO, waitSemaphoreCount=len(wait_semaphores), pWaitSemaphores=wait_semaphores, pWaitDstStageMask=wait_stages, commandBufferCount=len(cbs), pCommandBuffers=cbs, signalSemaphoreCount=len(signal_semaphores), pSignalSemaphores=signal_semaphores) vkQueueSubmit(graphic_queue, 1, [submit_create], None) present_create = VkPresentInfoKHR( sType=VK_STRUCTURE_TYPE_PRESENT_INFO_KHR, waitSemaphoreCount=1, pWaitSemaphores=signal_semaphores, swapchainCount=1, pSwapchains=[swapchain], pImageIndices=[image_index], pResults=None) vkQueuePresentKHR(presentation_queue, present_create) # Main loop running = True #running = False i = 0 import time last_time = time.perf_counter() * 1000 fps = 0 while running: fps += 1 if time.perf_counter() * 1000 - last_time >= 1000: last_time = time.perf_counter() * 1000 print("FPS: %s" % fps) fps = 0 events = sdl2.ext.get_events() draw_frame() for event in events: if event.type == sdl2.SDL_QUIT: running = False vkDeviceWaitIdle(logical_device) break # ---------- # Clean everything vkDestroySemaphore(logical_device, semaphore_image_available) vkDestroySemaphore(logical_device, semaphore_render_finished) vkDestroyCommandPool(logical_device, command_pool) for f in framebuffers: vkDestroyFramebuffer(logical_device, f) vkDestroyPipeline(logical_device, pipeline) vkDestroyPipelineLayout(logical_device, pipeline_layout) vkDestroyRenderPass(logical_device, render_pass) vkDestroyShaderModule(logical_device, frag_shader_module) vkDestroyShaderModule(logical_device, vert_shader_module) for i in image_views: vkDestroyImageView(logical_device, i) vkDestroySwapchainKHR(logical_device, swapchain) vkDestroyDevice(logical_device) vkDestroySurfaceKHR(instance, surface) vkDestroyDebugReportCallbackEXT(instance, callback) vkDestroyInstance(instance)
mit
fathomminds/php-rest-models
tests/DynamoDb/QueryBuilderTest.php
1203
<?php namespace Fathomminds\Rest\Tests\DynamoDb; use Mockery; use Aws\DynamoDb\DynamoDbClient as Client; use Fathomminds\Rest\Exceptions\RestException; use Fathomminds\Rest\Database\DynamoDb\Finder; use Fathomminds\Rest\Examples\DynamoDb\Models\FinderModel; class QueryBuilderTest extends TestCase { public function testModelFind() { $mockClient = Mockery::mock(Client::class); $model = new FinderModel; $res = $model->find($mockClient)->first(); $this->assertNull($res); } public function testModelFindCreateClient() { $model = new FinderModel; $res = $model->find(); $this->assertEquals(Finder::class, get_class($res)); } public function testFinderCreateClient() { $finder = new Finder; $property = new \ReflectionProperty($finder, 'client'); $property->setAccessible(true); $this->assertEquals(Client::class, get_class($property->getValue($finder))); } public function testFinderGet() { $mockClient = Mockery::mock(Client::class); $finder = new Finder($mockClient); $res = $finder->get()->first(); $this->assertNull($res); } }
mit
josemesona/ManagedDism
src/Microsoft.Dism/DismDriverPackageCollection.cs
909
// Copyright (c). All rights reserved. // // Licensed under the MIT license. using System; using System.Collections.ObjectModel; namespace Microsoft.Dism { /// <summary> /// Represents a collection of <see cref="DismDriverPackage" /> objects. /// </summary> public sealed class DismDriverPackageCollection : ReadOnlyCollection<DismDriverPackage> { /// <summary> /// Initializes a new instance of the <see cref="DismDriverPackageCollection" /> class. /// </summary> /// <param name="pointer">A pointer to the array of <see cref="DismApi.DismAppxPackage_" /> objects.</param> /// <param name="count">The number of objects in the array.</param> internal DismDriverPackageCollection(IntPtr pointer, uint count) : base(pointer.ToList(count, (DismApi.DismDriverPackage_ i) => new DismDriverPackage(i))) { } } }
mit
VictorJL/Redirector
server_modules/test.js
282
var DBManager = require("./export.js")(); var db_manager = new DBManager("../database/users.db"); db_manager.verify("password", "mypwd", "users", "username", "guest", function(err, result){ if(result){ console.log("great"); } else { console.log("not great"); } });
mit
bluedogtraining/avetmiss
src/Config/Config.php
1543
<?php namespace Bdt\Avetmiss\Config; /** * Class for managing configuration options via static values on the object. * * To extend this class, define your own properties on the extending class, e.g.: * * class ExampleConfig extends Config * { * protected $myOptions = [ * 'key' => 'value', * 'foo' => 'bar', * ]; * } */ abstract class Config { /** * Get the array for a given configuration option. * * @param string $name * * @return array */ public static function get($name) { self::check($name); return static::$$name; } /** * Get the keys for a given configuration option. * * @param string $name * * @return array */ public static function keys($name) { self::check($name); return array_keys(static::$$name); } /** * Get the values for a given configuration option. * * @param string $name * * @return array */ public static function values($name) { self::check($name); return array_values(static::$$name); } /** * Check that a given configuration option exists. * * @throws \DomainException * * @param string $name * * @return boolean */ private static function check($name) { if (!isset(static::$$name)) { throw new \DomainException('could not find ' . $name . ' in the config'); } } }
mit
NikitaKozlov/Switchman
app/src/main/java/org/zalando/switchman/ui/RecommendationStateChecker.java
524
package org.zalando.switchman.ui; import org.zalando.switchman.ItemId; import org.zalando.switchman.data.RecommendationDataSource; public class RecommendationStateChecker { private final RecommendationDataSource recommendationDataSource; public RecommendationStateChecker(RecommendationDataSource recommendationDataSource) { this.recommendationDataSource = recommendationDataSource; } public boolean isRecommended(ItemId itemId) { return recommendationDataSource.hasItem(itemId); } }
mit
Boriow/Telerik-Academy
Databases/Nice Solutions Exam 2016/InterestingImporter_Exam/01. Code First/SuperHeroesUniverse/StartUp/StartUp.cs
947
using System.IO; using System; using SuperHeroes.Data; using StartUp.ExportToXml; using System.Data.Entity; using SuperHeroes.Data.Migrations; namespace StartUp { public class StartUp { static void Main() { Database.SetInitializer(new MigrateDatabaseToLatestVersion<SuperHeroesDbContext, Configuration>()); var db = new SuperHeroesDbContext(); db.Database.CreateIfNotExists(); using (db) { var importData = new Importer(); importData.Import(db); var export = new SuperheroesUniverseExporter(); File.Create("..\\..\\..\\..\\..\\02. Xml Files\\01. AllSuperHeroes.xml"); File.WriteAllText("..\\..\\..\\..\\..\\02. Xml Files\\01. AllSuperHeroes.xml", export.ExportAllSuperheroes()); Console.WriteLine(export.ExportAllSuperheroes()); } } } }
mit
cmdconfig/CodeIgniter_EvrosetParser
application/config/database.php
3787
<?php defined('BASEPATH') OR exit('No direct script access allowed'); /* | ------------------------------------------------------------------- | DATABASE CONNECTIVITY SETTINGS | ------------------------------------------------------------------- | This file will contain the settings needed to access your database. | | For complete instructions please consult the 'Database Connection' | page of the User Guide. | | ------------------------------------------------------------------- | EXPLANATION OF VARIABLES | ------------------------------------------------------------------- | | ['dsn'] The full DSN string describe a connection to the database. | ['hostname'] The hostname of your database server. | ['username'] The username used to connect to the database | ['password'] The password used to connect to the database | ['database'] The name of the database you want to connect to | ['dbdriver'] The database driver. e.g.: mysqli. | Currently supported: | cubrid, ibase, mssql, mysql, mysqli, oci8, | odbc, pdo, postgre, sqlite, sqlite3, sqlsrv | ['dbprefix'] You can add an optional prefix, which will be added | to the table name when using the Query Builder class | ['pconnect'] TRUE/FALSE - Whether to use a persistent connection | ['db_debug'] TRUE/FALSE - Whether database errors should be displayed. | ['cache_on'] TRUE/FALSE - Enables/disables query caching | ['cachedir'] The path to the folder where cache files should be stored | ['char_set'] The character set used in communicating with the database | ['dbcollat'] The character collation used in communicating with the database | NOTE: For MySQL and MySQLi databases, this setting is only used | as a backup if your server is running PHP < 5.2.3 or MySQL < 5.0.7 | (and in table creation queries made with DB Forge). | There is an incompatibility in PHP with mysql_real_escape_string() which | can make your site vulnerable to SQL injection if you are using a | multi-byte character set and are running versions lower than these. | Sites using Latin-1 or UTF-8 database character set and collation are unaffected. | ['swap_pre'] A default table prefix that should be swapped with the dbprefix | ['encrypt'] Whether or not to use an encrypted connection. | ['compress'] Whether or not to use client compression (MySQL only) | ['stricton'] TRUE/FALSE - forces 'Strict Mode' connections | - good for ensuring strict SQL while developing | ['failover'] array - A array with 0 or more data for connections if the main should fail. | ['save_queries'] TRUE/FALSE - Whether to "save" all executed queries. | NOTE: Disabling this will also effectively disable both | $this->db->last_query() and profiling of DB queries. | When you run a query, with this setting set to TRUE (default), | CodeIgniter will store the SQL statement for debugging purposes. | However, this may cause high memory usage, especially if you run | a lot of SQL queries ... disable this to avoid that problem. | | The $active_group variable lets you choose which connection group to | make active. By default there is only one group (the 'default' group). | | The $query_builder variables lets you determine whether or not to load | the query builder class. */ $active_group = 'default'; $query_builder = TRUE; $db['default'] = array( 'dsn' => '', 'hostname' => 'ps-st.ru', 'username' => '', 'password' => '', 'database' => 'test_parsers', 'dbdriver' => 'mysqli', 'dbprefix' => '', 'pconnect' => FALSE, 'db_debug' => TRUE, 'cache_on' => FALSE, 'cachedir' => '', 'char_set' => 'utf8', 'dbcollat' => 'utf8_general_ci', 'swap_pre' => '', 'encrypt' => FALSE, 'compress' => FALSE, 'stricton' => FALSE, 'failover' => array(), 'save_queries' => TRUE );
mit
hiphapis/backup
spec/storage/dropbox_spec.rb
8758
require "spec_helper" module Backup describe Storage::Dropbox do let(:model) { Model.new(:test_trigger, 'test label') } let(:storage) { Storage::Dropbox.new(model) } let(:s) { sequence '' } it_behaves_like 'a class that includes Config::Helpers' it_behaves_like 'a subclass of Storage::Base' it_behaves_like 'a storage that cycles' describe '#initialize' do it 'provides default values' do expect( storage.storage_id ).to be_nil expect( storage.api_token ).to be_nil expect( storage.chunk_size ).to be 4 expect( storage.max_retries ).to be 10 expect( storage.retry_waitsec ).to be 30 expect( storage.path ).to eq 'backups' end it 'configures the storage' do storage = Storage::Dropbox.new(model, :my_id) do |db| db.api_token = 'my_api_token' db.chunk_size = 10 db.max_retries = 15 db.retry_waitsec = 45 db.path = 'my/path' end expect( storage.storage_id ).to eq 'my_id' expect( storage.api_token ).to eq 'my_api_token' expect( storage.chunk_size ).to eq 10 expect( storage.max_retries ).to eq 15 expect( storage.retry_waitsec ).to eq 45 expect( storage.path ).to eq 'my/path' end it 'strips leading path separator' do storage = Storage::Dropbox.new(model) do |s3| s3.path = '/this/path' end expect( storage.path ).to eq 'this/path' end end # describe '#initialize' describe '#client' do let(:client) { mock } context 'when client exists' do before do DropboxApi::Client.expects(:new).once.with(nil).returns(client) end it 'returns an already existing client' do storage.send(:client).should be(client) storage.send(:client).should be(client) end end context 'when an error is raised creating a client for the session' do it 'raises an error' do DropboxApi::Client.expects(:new).raises('error') expect do storage.send(:client) end.to raise_error(Storage::Dropbox::Error) {|err| expect( err.message ).to eq( "Storage::Dropbox::Error: Authorization Failed\n" + "--- Wrapped Exception ---\n" + "RuntimeError: error" ) } end end end # describe '#client' describe '#transfer!' do let(:client) { mock } let(:timestamp) { Time.now.strftime("%Y.%m.%d.%H.%M.%S") } let(:remote_path) { File.join('my/path/test_trigger', timestamp) } let(:file) { mock } let(:uploader) { mock } before do Timecop.freeze storage.package.time = timestamp storage.stubs(:client).returns(client) file.stubs(:stat).returns(stub(size: 6_291_456)) storage.path = 'my/path' storage.chunk_size = 2 end after { Timecop.return } it 'transfers the package files' do storage.package.stubs(:filenames).returns( ['test_trigger.tar-aa', 'test_trigger.tar-ab'] ) # first file src = File.join(Config.tmp_path, 'test_trigger.tar-aa') dest = File.join('/', remote_path, 'test_trigger.tar-aa') Storage::Dropbox::ChunkedUploader.expects(:new).with(client, file).returns(uploader) Logger.expects(:info).in_sequence(s).with("Storing '#{ dest }'...") File.expects(:open).in_sequence(s).with(src, 'r').yields(file) uploader.expects(:upload).in_sequence(s).with(2_097_152) uploader.expects(:finish).in_sequence(s).with(dest) # # second file src = File.join(Config.tmp_path, 'test_trigger.tar-ab') dest = File.join('/', remote_path, 'test_trigger.tar-ab') Storage::Dropbox::ChunkedUploader.expects(:new).with(client, file).returns(uploader) Logger.expects(:info).in_sequence(s).with("Storing '#{ dest }'...") File.expects(:open).in_sequence(s).with(src, 'r').yields(file) uploader.expects(:upload).in_sequence(s) uploader.expects(:finish).in_sequence(s).with(dest) storage.send(:transfer!) end it 'retries on errors' do storage.max_retries = 1 storage.package.stubs(:filenames).returns(['test_trigger.tar']) src = File.join(Config.tmp_path, 'test_trigger.tar') dest = File.join('/', remote_path, 'test_trigger.tar') @logger_calls = 0 Logger.expects(:info).times(3).with do |arg| @logger_calls += 1 case @logger_calls when 1 expect( arg ).to eq "Storing '#{ dest }'..." when 2 expect( arg ).to be_an_instance_of Storage::Dropbox::Error expect( arg.message ).to match( "Storage::Dropbox::Error: Retry #1 of 1." ) expect( arg.message ).to match('RuntimeError: chunk failed') when 3 expect( arg ).to be_an_instance_of Storage::Dropbox::Error expect( arg.message ).to match( "Storage::Dropbox::Error: Retry #1 of 1." ) expect( arg.message ).to match('RuntimeError: finish failed') end end File.expects(:open).in_sequence(s).with(src, 'r').yields(file) Storage::Dropbox::ChunkedUploader.expects(:new).in_sequence(s). with(client, file).returns(uploader) uploader.expects(:upload).in_sequence(s).raises('chunk failed') storage.expects(:sleep).in_sequence(s).with(30) uploader.expects(:upload).in_sequence(s).with(2_097_152) uploader.expects(:finish).in_sequence(s).with(dest).raises('finish failed') storage.expects(:sleep).in_sequence(s).with(30) uploader.expects(:finish).in_sequence(s).with(dest) storage.send(:transfer!) end it 'fails when retries are exceeded' do storage.max_retries = 2 storage.package.stubs(:filenames).returns(['test_trigger.tar']) src = File.join(Config.tmp_path, 'test_trigger.tar') dest = File.join('/', remote_path, 'test_trigger.tar') @logger_calls = 0 Logger.expects(:info).times(3).with do |arg| @logger_calls += 1 case @logger_calls when 1 expect( arg ).to eq "Storing '#{ dest }'..." when 2 expect( arg ).to be_an_instance_of Storage::Dropbox::Error expect( arg.message ).to match( "Storage::Dropbox::Error: Retry #1 of 2." ) expect( arg.message ).to match('RuntimeError: chunk failed') when 3 expect( arg ).to be_an_instance_of Storage::Dropbox::Error expect( arg.message ).to match( "Storage::Dropbox::Error: Retry #2 of 2." ) expect( arg.message ).to match('RuntimeError: chunk failed again') end end File.expects(:open).in_sequence(s).with(src, 'r').yields(file) Storage::Dropbox::ChunkedUploader.expects(:new).in_sequence(s). with(client, file).returns(uploader) uploader.expects(:upload).in_sequence(s).raises('chunk failed') storage.expects(:sleep).in_sequence(s).with(30) uploader.expects(:upload).in_sequence(s).raises('chunk failed again') storage.expects(:sleep).in_sequence(s).with(30) uploader.expects(:upload).in_sequence(s).raises('strike three') uploader.expects(:finish).never expect do storage.send(:transfer!) end.to raise_error(Storage::Dropbox::Error) {|err| expect( err.message ).to match('Upload Failed!') expect( err.message ).to match('RuntimeError: strike three') } end end # describe '#transfer!' describe '#remove!' do let(:client) { mock } let(:timestamp) { Time.now.strftime("%Y.%m.%d.%H.%M.%S") } let(:remote_path) { File.join('/my/path/test_trigger', timestamp) } let(:package) { stub( # loaded from YAML storage file :trigger => 'test_trigger', :time => timestamp ) } before do Timecop.freeze storage.stubs(:client).returns(client) storage.path = 'my/path' end after { Timecop.return } it 'removes the given package from the remote' do Logger.expects(:info).in_sequence(s). with("Removing backup package dated #{ timestamp }...") client.expects(:delete).with(remote_path) storage.send(:remove!, package) end end # describe '#remove!' end end
mit
yogeshsaroya/new-cdnjs
ajax/libs/webshim/1.12.1/minified/shims/form-validators.js
129
version https://git-lfs.github.com/spec/v1 oid sha256:df3617a4d5e30a2fe3c353dd08d8ef572578d0fa8cd4033b7339ef0baa398d70 size 6313
mit
Nexmo/nexmo-java-sdk
src/main/java/com/vonage/client/account/SettingsResponse.java
2857
/* * Copyright 2020 Vonage * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.vonage.client.account; import com.fasterxml.jackson.annotation.JsonIgnoreProperties; import com.fasterxml.jackson.annotation.JsonInclude; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.databind.ObjectMapper; import com.vonage.client.VonageUnexpectedException; import java.io.IOException; @JsonInclude(JsonInclude.Include.NON_NULL) @JsonIgnoreProperties(ignoreUnknown = true) public class SettingsResponse { @JsonProperty("mo-callback-url") private String incomingSmsUrl; @JsonProperty("dr-callback-url") private String deliveryReceiptUrl; @JsonProperty("max-outbound-request") private Integer maxOutboundMessagesPerSecond; @JsonProperty("max-inbound-request") private Integer maxInboundMessagesPerSecond; @JsonProperty("max-calls-per-second") private Integer maxApiCallsPerSecond; /** * @return The URL where Vonage will send a webhook when an incoming SMS is received when a number-specific URL is * not configured. */ public String getIncomingSmsUrl() { return incomingSmsUrl; } /** * @return The URL where Vonage will send a webhook when a delivery receipt is received when a number-specific URL is * not configured. */ public String getDeliveryReceiptUrl() { return deliveryReceiptUrl; } /** * @return The maximum number of outbound messages per second. */ public Integer getMaxOutboundMessagesPerSecond() { return maxOutboundMessagesPerSecond; } /** * @return The maximum number of inbound messages per second. */ public Integer getMaxInboundMessagesPerSecond() { return maxInboundMessagesPerSecond; } /** * @return The maximum number of API calls per second. */ public Integer getMaxApiCallsPerSecond() { return maxApiCallsPerSecond; } public static SettingsResponse fromJson(String json) { try { ObjectMapper mapper = new ObjectMapper(); return mapper.readValue(json, SettingsResponse.class); } catch (IOException e) { throw new VonageUnexpectedException("Failed to produce SettingsResponse from json.", e); } } }
mit
Tarvald/goodAndEvil
app/Interface/components/registerForm/registerForm.component.ts
1330
import { Component } from '@angular/core'; import { CreatureService } from '../../../Game/components/creature/creature.service'; import { RegisterFormService } from './registerForm.service'; @Component({ moduleId: module.id, selector: 'registration-form', templateUrl: './registerForm.component.html', providers: [ CreatureService, RegisterFormService ] }) export class registerFormComponent { public godName: String; public creatureName: String; public creatureType; public creaturesType; public message: String; constructor(private CreatureService: CreatureService, private RegisterFormService: RegisterFormService) { this.CreatureService.getCreaturesTypes().subscribe( creaturesTypes => this.creaturesType = creaturesTypes, error => this.message = <any>error ) } public async submit() { const newPlayer = this.RegisterFormService.parseNewPlayer(this.godName, this.creatureName, this.creatureType); const registered = await this.RegisterFormService.registerNewPlayer(newPlayer); this.setAfterRegistrationMessage(registered); } private setAfterRegistrationMessage(hasBeenRegistered) { return hasBeenRegistered ? this.message = 'new.player.registered' : this.message = 'registration.error'; } }
mit
kbunkrams97/SQL-Log
src/com/gmail/kbunkrams97/DatabaseHandler/SQLSelection.java
2842
package com.gmail.kbunkrams97.DatabaseHandler; import java.sql.Connection; import java.sql.DriverManager; import java.sql.SQLException; import java.sql.Statement; import com.gmail.kbunkrams97.SQLMain; public class SQLSelection { private static Connection con; private static SQLMain plugin = SQLMain.getInstance(); private static String address = (String) plugin.getConfig().get("MySQL.Address"); private static String database = (String) plugin.getConfig().get("MySQL.Database"); private static String username = (String) plugin.getConfig().get("MySQL.Username"); private static String password = (String) plugin.getConfig().get("MySQL.Password"); private static int port = plugin.getConfig().getInt("MySQL.Port"); public static Connection getConnection() throws SQLException, ClassNotFoundException { String prefix = "[SQL-Log] "; if (plugin.getConfig().getBoolean("MySQL.Enabled")) { try { Class.forName("com.mysql.jdbc.Driver"); if (con != null && con.isClosed() == false) {} else { con = DriverManager.getConnection("jdbc:mysql://" + address + ":" + port + "/" + database, username, password); } } catch (SQLException | ClassNotFoundException e) { plugin.log.info(prefix + "MySQL connection failed. Switching to SQLite."); plugin.getConfig().set("MySQL.Enabled", false); plugin.saveConfig(); plugin.firstLoad = true; con = getConnection(); } if(plugin.firstLoad == true) { plugin.log.info(prefix + "Connection to MySQL database was successful."); plugin.firstLoad = false; } } else { try { Class.forName("org.sqlite.JDBC"); if (con != null && con.isClosed() == false) {} else { con = DriverManager.getConnection("jdbc:sqlite:plugins/SQL-Log/Data.sql"); } } catch (SQLException | ClassNotFoundException e) { e.printStackTrace(); } if(plugin.firstLoad == true) { plugin.log.info(prefix + "Connection SQLite database was successful."); plugin.firstLoad = false; } } return con; } public static Statement getStatement() throws SQLException, ClassNotFoundException { if (plugin.getConfig().getBoolean("MySQL.Enabled")) { return getConnection().createStatement(); } else { return getConnection().createStatement(); } } }
mit
thesevenlayers/sevenlayers-crm
src/Seven/FEBundle/Entity/Client.php
8892
<?php namespace Seven\FEBundle\Entity; use Doctrine\ORM\Mapping as ORM; use Seven\FEBundle\Entity\Partial\BasicInfo; use Seven\FEBundle\Entity\Utilities\ImageContainer; /** * @ORM\Entity(repositoryClass="Seven\FEBundle\Repository\ClientRepository") * @ORM\Table(name="clients") * @ORM\HasLifecycleCallbacks */ class Client { use BasicInfo; /** * @ORM\OneToMany(targetEntity="ClientContact", mappedBy="client", cascade={"persist", "remove"}) */ protected $contacts; /** * @ORM\OneToMany(targetEntity="ProviderAccount", mappedBy="client", cascade={"remove"}) */ protected $provider_accounts; /** * @ORM\OneToMany(targetEntity="Domain", mappedBy="client", cascade={"persist", "remove"}) */ protected $domains; /** * @ORM\OneToMany(targetEntity="EmailHost", mappedBy="client", cascade={"persist", "remove"}) */ protected $email_hosts; /** * @ORM\OneToMany(targetEntity="Host", mappedBy="client", cascade={"persist", "remove"}) */ protected $hosts; /** * @ORM\OneToMany(targetEntity="Maintenance", mappedBy="client", cascade={"persist", "remove"}) */ protected $maintenance; /** * @ORM\OneToMany(targetEntity="Miscellaneous", mappedBy="client", cascade={"persist", "remove"}) */ protected $miscellaneous; /** * @ORM\OneToOne(targetEntity="Seven\FEBundle\Entity\Utilities\ImageContainer", cascade={"persist", "remove"}) */ protected $image_container; /** * @ORM\Column(type="text", nullable=true) */ protected $name; /** * @ORM\Column(type="text", nullable=true) */ protected $address; /** * Constructor */ public function __construct() { $this->contacts = new \Doctrine\Common\Collections\ArrayCollection(); $this->provider_accounts = new \Doctrine\Common\Collections\ArrayCollection(); $this->domains = new \Doctrine\Common\Collections\ArrayCollection(); $this->email_hosts = new \Doctrine\Common\Collections\ArrayCollection(); $this->hosts = new \Doctrine\Common\Collections\ArrayCollection(); $this->maintenance = new \Doctrine\Common\Collections\ArrayCollection(); $this->miscellaneous = new \Doctrine\Common\Collections\ArrayCollection(); } /** * Set name * * @param string $name * @return Client */ public function setName($name) { $this->name = $name; return $this; } /** * Get name * * @return string */ public function getName() { return $this->name; } /** * Set address * * @param string $address * @return Client */ public function setAddress($address) { $this->address = $address; return $this; } /** * Get address * * @return string */ public function getAddress() { return $this->address; } /** * Add contacts * * @param \Seven\FEBundle\Entity\ClientContact $contacts * @return Client */ public function addContact(\Seven\FEBundle\Entity\ClientContact $contacts) { $this->contacts[] = $contacts; $contacts->setClient($this); return $this; } /** * Remove contacts * * @param \Seven\FEBundle\Entity\ClientContact $contacts */ public function removeContact(\Seven\FEBundle\Entity\ClientContact $contacts) { $this->contacts->removeElement($contacts); } /** * Get contacts * * @return \Doctrine\Common\Collections\Collection */ public function getContacts() { return $this->contacts; } /** * Add provider_accounts * * @param \Seven\FEBundle\Entity\ProviderAccount $providerAccounts * @return Client */ public function addProviderAccount(\Seven\FEBundle\Entity\ProviderAccount $providerAccounts) { $this->provider_accounts[] = $providerAccounts; return $this; } /** * Remove provider_accounts * * @param \Seven\FEBundle\Entity\ProviderAccount $providerAccounts */ public function removeProviderAccount(\Seven\FEBundle\Entity\ProviderAccount $providerAccounts) { $this->provider_accounts->removeElement($providerAccounts); } /** * Get provider_accounts * * @return \Doctrine\Common\Collections\Collection */ public function getProviderAccounts() { return $this->provider_accounts; } /** * Add domains * * @param \Seven\FEBundle\Entity\Domain $domains * @return Client */ public function addDomain(\Seven\FEBundle\Entity\Domain $domains) { $this->domains[] = $domains; $domains->setClient($this); return $this; } /** * Remove domains * * @param \Seven\FEBundle\Entity\Domain $domains */ public function removeDomain(\Seven\FEBundle\Entity\Domain $domains) { $this->domains->removeElement($domains); } /** * Get domains * * @return \Doctrine\Common\Collections\Collection */ public function getDomains() { return $this->domains; } /** * Add email_hosts * * @param \Seven\FEBundle\Entity\EmailHost $emailHosts * @return Client */ public function addEmailHost(\Seven\FEBundle\Entity\EmailHost $emailHosts) { $this->email_hosts[] = $emailHosts; $emailHosts->setClient($this); return $this; } /** * Remove email_hosts * * @param \Seven\FEBundle\Entity\EmailHost $emailHosts */ public function removeEmailHost(\Seven\FEBundle\Entity\EmailHost $emailHosts) { $this->email_hosts->removeElement($emailHosts); } /** * Get email_hosts * * @return \Doctrine\Common\Collections\Collection */ public function getEmailHosts() { return $this->email_hosts; } /** * Add hosts * * @param \Seven\FEBundle\Entity\Host $hosts * @return Client */ public function addHost(\Seven\FEBundle\Entity\Host $hosts) { $this->hosts[] = $hosts; $hosts->setClient($this); return $this; } /** * Remove hosts * * @param \Seven\FEBundle\Entity\Host $hosts */ public function removeHost(\Seven\FEBundle\Entity\Host $hosts) { $this->hosts->removeElement($hosts); } /** * Get hosts * * @return \Doctrine\Common\Collections\Collection */ public function getHosts() { return $this->hosts; } /** * Add maintenance * * @param \Seven\FEBundle\Entity\Maintenance $maintenance * @return Client */ public function addMaintenance(\Seven\FEBundle\Entity\Maintenance $maintenance) { $this->maintenance[] = $maintenance; $maintenance->setClient($this); return $this; } /** * Remove maintenance * * @param \Seven\FEBundle\Entity\Maintenance $maintenance */ public function removeMaintenance(\Seven\FEBundle\Entity\Maintenance $maintenance) { $this->maintenance->removeElement($maintenance); } /** * Get maintenance * * @return \Doctrine\Common\Collections\Collection */ public function getMaintenance() { return $this->maintenance; } /** * Add miscellaneous * * @param \Seven\FEBundle\Entity\Miscellaneous $miscellaneous * @return Client */ public function addMiscellaneous(\Seven\FEBundle\Entity\Miscellaneous $miscellaneous) { $this->miscellaneous[] = $miscellaneous; $miscellaneous->setClient($this); return $this; } /** * Remove miscellaneous * * @param \Seven\FEBundle\Entity\Miscellaneous $miscellaneous */ public function removeMiscellaneous(\Seven\FEBundle\Entity\Miscellaneous $miscellaneous) { $this->miscellaneous->removeElement($miscellaneous); } /** * Get miscellaneous * * @return \Doctrine\Common\Collections\Collection */ public function getMiscellaneous() { return $this->miscellaneous; } /** * Set image_container * * @param \Seven\FEBundle\Entity\Utilities\ImageContainer $imageContainer * @return Client */ public function setImageContainer(\Seven\FEBundle\Entity\Utilities\ImageContainer $imageContainer = null) { $this->image_container = $imageContainer; return $this; } /** * Get image_container * * @return \Seven\FEBundle\Entity\Utilities\ImageContainer */ public function getImageContainer() { return $this->image_container; } }
mit
simon-downes/eams
src/classes/users/UserRepository.php
4700
<?php namespace eams\users; use \spf\model\Fieldset; class UserRepository extends \spf\model\GenericRepository { protected $_keys; public function __construct( $db, $map, $mapper, $key_mapper ) { parent::__construct($db, $map, $mapper); $this->keys = $key_mapper; \spf\assert_instance($this->keys, '\\eams\\users\\KeyMapper'); } public function findByEmail( $email ) { $filter = new \spf\model\Filter(); return $this->findFirst( $filter->equals('email', $email) ); } public function findByName( $name ) { $filter = new \spf\model\Filter(); return $this->findFirst( $filter->equals('name', $name) ); } public function exists( $user ) { if( !($user instanceof User) ) throw new \InvalidArgumentException(sprintf("\\%s expects \\eams\\users\\User, '%s' given", __METHOD__, \spf\var_info($user))); $exists = false; $filter = new \spf\model\Filter; if( !$user->getError('name') ) { $filter ->clear() ->equals('name', $user->name) ->notEquals('id', $user->id); if( $this->count($filter) ) { $user->setError('name', Fieldset::ERROR_EXISTS); $exists = true; } } if( !$user->getError('email') ) { $filter ->clear() ->equals('email', $user->email) ->notEquals('id', $user->id); if( $this->count($filter) ) { $user->setError('email', Fieldset::ERROR_EXISTS); $exists = true; } } return $exists; } public function keyExists( $key ) { if( !($key instanceof Key) ) throw new \InvalidArgumentException(sprintf("\\%s expects \\eams\\users\\Key, '%s' given", __METHOD__, \spf\var_info($key))); if( $exists = (bool) $this->db->getOne("SELECT COUNT(*) FROM user_api_keys WHERE id = ?", $key->id) ) { $key->setError('id', Fieldset::ERROR_EXISTS); } return $exists; } public function save( $user ) { $success = parent::save($user); foreach( $user->tokens as $hash => $token ) { if( $token === false ) $this->mapper->deleteToken($hash); elseif( !$token->isPersisted() ) $success = $success && $this->mapper->saveToken($token); } foreach( $user->keys as $id => $key ) { if( $key === false ) $success = $success && $this->keys->delete($id); elseif( $key->original('id') ) $success = $success && $this->keys->update($key); else $success = $success && $this->keys->insert($key); } return $success; } public function seen( $user ) { if( !($user instanceof User) ) throw new \InvalidArgumentException(sprintf("\\%s expects \\eams\\users\\User, '%s' given", __METHOD__, \spf\var_info($user))); if( $user->id ) { $user->last_seen = time(); $this->save($user); } return $this; } public function createToken( $user_id, $access, $expires, $extra = '' ) { $ts = filter_var($expires, FILTER_VALIDATE_INT); if( $ts === false ) $ts = strtotime($expires); if( !$ts || ($ts < 86400) ) $ts = time() + 86400; return $this->mapper->createToken( array( 'hash' => \spf\randomHex(40), 'user_id' => $user_id, 'access' => $access, 'expires' => $expires, 'extra' => $extra, ) ); } public function loadTokens( $users ) { if( $users instanceof User ) { $users = array($users->id => $users); } elseif( !is_array($users) ) { throw new \InvalidArgumentException("Not a valid set of users: ". \spf\var_info($users)); } // make sure we're only dealing with instances of User whose tokens haven't been loaded yet $users = array_filter( $users, function( $user ) { return ($user instanceof User) && !$user->tokens; } ); if( $users ) { // find all the tokens for the users in question and assign them to the correct user $tokens = $this->mapper->fetchTokens(array_keys($users)); foreach( $tokens as $token ) { $users[$token->user_id]->addToken($token); } } return $this; } public function createKey( $data = array() ) { return $this->keys->create($data); } public function loadKeys( $users ) { if( $users instanceof User ) { $users = array($users->id => $users); } elseif( !is_array($users) ) { throw new \InvalidArgumentException("Not a valid set of users: ". \spf\var_info($users)); } // make sure we're only dealing with instances of User whose tokens haven't been loaded yet $users = array_filter( $users, function( $user ) { return ($user instanceof User) && !$user->keys; } ); if( $users ) { $ids = $this->db->getCol(sprintf("SELECT id FROM user_api_keys WHERE user_id IN (%s)", implode(', ', array_keys($users)))); foreach( $this->keys->fetch($ids) as $key ) { $users[$key->user_id]->addKey($key); } } return $this; } } // EOF
mit
gleicon/RedisLive
src/redis-live.py
1091
#! /usr/bin/env python from twisted.internet import reactor import cyclone.options import cyclone.web from api.controller.BaseStaticFileHandler import BaseStaticFileHandler from api.controller.ServerListController import ServerListController from api.controller.InfoController import InfoController from api.controller.MemoryController import MemoryController from api.controller.CommandsController import CommandsController from api.controller.TopCommandsController import TopCommandsController from api.controller.TopKeysController import TopKeysController # Bootup application = cyclone.web.Application([ (r"/api/servers", ServerListController), (r"/api/info", InfoController), (r"/api/memory", MemoryController), (r"/api/commands", CommandsController), (r"/api/topcommands", TopCommandsController), (r"/api/topkeys", TopKeysController), (r"/(.*)", BaseStaticFileHandler, {"path": "www"}) ], debug="True") if __name__ == "__main__": cyclone.options.parse_command_line() reactor.listenTCP(8888, application, interface="127.0.0.1") reactor.run()
mit
mateusmaso/hipbone
lib/storage/index.js
1866
(function() { var Module, Storage, _, extend = function(child, parent) { for (var key in parent) { if (hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; }, hasProp = {}.hasOwnProperty; _ = require("underscore"); Module = require("./../module"); module.exports = Storage = (function(superClass) { extend(Storage, superClass); function Storage(prefix) { if (prefix == null) { prefix = "hipbone_"; } this.prefix = prefix; } Storage.prototype.match = function(regex) { var key, matches, value; matches = {}; for (key in localStorage) { value = localStorage[key]; if (regex.test(key) && key.indexOf(this.prefix) >= 0) { matches[key.replace(this.prefix, "")] = _.parse(value).data; } } return matches; }; Storage.prototype.get = function(key) { var value; if (value = localStorage["" + this.prefix + key]) { return _.parse(value).data; } }; Storage.prototype.set = function(key, value) { return localStorage.setItem("" + this.prefix + key, JSON.stringify({ data: value, timestamp: _.now() })); }; Storage.prototype.unset = function(key) { return localStorage.removeItem("" + this.prefix + key); }; Storage.prototype.clear = function() { var key, ref, regex, results, value; regex = new RegExp(this.prefix); ref = this.match(regex); results = []; for (key in ref) { value = ref[key]; results.push(this.unset(key)); } return results; }; Storage.register("Storage"); return Storage; })(Module); }).call(this);
mit
junaidappimagine/smartedu
application/views/fees/feesDefaulters.php
12744
<style> .panel-body h1{ font-size: 15px; } </style> <link href="<?php echo base_url(); ?>assets/datatable/jquery.dataTables.min.css" rel="stylesheet" /> <div id="content" class="content"> <ol class="breadcrumb pull-right"> <li><a href="javascript:;">Fees</a></li> <li><a href="javascript:;">Fees Defaulters</a></li> </ol> <h1 class="page-header">Fees Defaulters | Students with fees due </h1> <div class="row"> <div class="col-md-12"> <div class="panel panel-inverse" data-sortable-id="form-stuff-1"> <div class="panel-heading"> <div class="panel-heading-btn"> <a href="javascript:;" class="btn btn-xs btn-icon btn-circle btn-default" data-click="panel-expand"><i class="fa fa-expand"></i></a> <a href="javascript:;" class="btn btn-xs btn-icon btn-circle btn-success" data-click="panel-reload"><i class="fa fa-repeat"></i></a> <a href="javascript:;" class="btn btn-xs btn-icon btn-circle btn-warning" data-click="panel-collapse"><i class="fa fa-minus"></i></a> <!-- <a href="javascript:;" class="btn btn-xs btn-icon btn-circle btn-danger" data-click="panel-remove"><i class="fa fa-times"></i></a>--> </div> <h4 class="panel-title">Fees refund</h4> </div> <div class="panel-body"> <div class="well"> <div class="row"> <div class="form-group"> <label class="col-md-2 col-md-offset-2 control-label"> <h1 class="page-header"><b>Select Class :</b></h1></label> <div class="col-md-3"> <select id="selectClass" class="form-control selectpicker" data-style="btn-white btn-sm"> <option value="">Select Class</option> <option value="Grade1">Grade1</option> <option value="">Class1</option> <option value="">Standard1</option> </select> </div> </div> </div> <div class="row"> <div class="form-group"> <label class="col-md-2 col-md-offset-2 control-label"> <h1 class="page-header"><b>Select Batch :</b></h1></label> <div class="col-md-3"> <select id="emptyBatch" class="form-control selectpicker " data-style="btn-white btn-sm"> <option value="">Select Batch</option> <option value="G01" class="hidden show">G01-A</option> </select> </div> </div> </div> <div class="row"> <div class="form-group"> <label class="col-md-4 control-label" style="float:left;"> <h1 class="page-header"><b style="margin-left:74px;">Select Fee Collection Date :</b></h1></label> <div class="col-md-3"> <select id="dropdown1" class="form-control selectpicker" data-style="btn-white btn-sm"> <option value="">Select Fee collection</option> <option value="Term1">Term1 for class1:24/02/2016To</option> <option value="feeStd1">Fee for std_c1-g4:23/03/2016To</option> <option value="Term2">Term2 fee collection:25/03/2016To</option> <option value="str">Fee str:06/04/2016To</option> </select> </div> </div> </div> </div> <br> <div class="panel-body " id="panel"> <div class="table-responsive"> <table id="example" class="table datatable table-bordered nowrap responsive " cellspacing="0" width="100%"> <thead> <tr> <th data-class="hidden">id</th> <th>S.No</th> <th>Name</th> <th>Email</th> <th>Emp_Id</th> <th>Payslip NO</th> <th>Designation</th> <th>For The Month Of</th> <th>Total Working Days</th> <th>Worked Days</th> <th>Basic Salary</th> <th>HRA</th> <th>DA</th> <th>TA</th> <th>Incentive</th> <th>Increment</th> <th>Gross Earnings</th> <th>LOP</th> <th>Advance salary paid</th> <th>Other deduction</th> <th>Gross deductions</th> <th>Net-Salary</th> <th>Remarks</th> <th>Insert Timestamp</th> <th>Update Timestamp</th> </tr> </thead> <tbody id="sbody"> </tbody> </table> <div class="col-md-offset-3"> <br> <div class="col-sm-2"> <a class="form-control btn btn-primary btn-sm" href="<?php echo base_url('FeesCntrl/defaulter_pdf_generate');?>">PDF report</a> </div> <div class="col-md-3"> <input type="button" class="form-control btn btn-success" name="send" onclick="multiple_mail_send()" value="Send Email"> </div> <!-- <button type="button" id="updatebutton" class="btn btn-primary" disabled> Edit </button> <button type="button" id="deletebutton" name="" class="btn btn-danger">Delete</button>--> </div> </div> <!-- <div class="col-sm-2 col-sm-offset-3"> <a class="form-control btn btn-primary btn-sm" href="<?php echo base_url('FeesCntrl/defaulter_pdf_generate');?>">PDF report</a> </div> <div class="col-sm-2"> <a class="form-control btn btn-primary btn-sm" data-toggle="modal" data-target="#getToEmail" id="sendEmail" name="sendEmail"><i class="fa fa-envelope"></i> Email</a> </div> --> </div> </div> </div> </div> <div> </div> <!-- <div class="modal fade" id="EmailUserFancy" data_value="EmailUserFancy" data-backdrop="static" tabindex="-1" role="dialog" aria-labelledby="EmailUserFancy"> <div class="modal-dialog"> <div class="modal-content"> <form id="EmailUserFancy" class="smart-form" > <div class="modal-header" style="border-bottom: 1px solid #e5e5e5; min-height: 16.4286px; padding: 15px;"> <b> <img alt="Ruby" data-id="login-cover-image" src="<?php echo base_url();?>/assets/img/logo.jpg" style="width: 55px;"> </b> <button aria-hidden="true" data-dismiss="modal" class="close" type="button onClick="onClickHandler(this)"> <i class="fa fa-times-circle "></i> </button> </div> <div class="model-body"> <fieldset> <p></p> <div class="form-group"> <div class="col-md-12"> <label class="col-md-4">Enter Email Address</label> <div class="col-md-5"> <input type="text" class="form-control EmailIdClass" name="EmailId" /> </div> </div> </div> </fieldset> <fieldset><p></p></fieldset> </div> <div class="modal-footer"> <button type="button" class="btn btn-default" data-dismiss="modal">Close</button> <button type="button" id="Savechanges" onclick="EmailIdPerson();" class="btn btn-primary">Send Email</button> </div> </form> </div> </div> </div> --> <script> $(document).ready(function(){ $('#selectClass').change(function(){ if($(this).val()=='Grade1'){ $('.show').removeClass('hidden'); $('#emptyBatch').addClass('hidden'); }else{ $('.hidden').addClass('hidden'); } }); // $('#dropdown1').change(function(){ // console.log($(this).val()); // if($(this).val()=='Term1' ) // { // $('#panel').removeClass('hidden'); // $('#view').removeClass('hidden'); // $('#termData1').removeClass('hidden'); // $('#termData2').removeClass('hidden'); // $('#str').addClass('hidden'); // $('#feeStd').addClass('hidden'); // } // else if ($(this).val()=='feeStd1' ) { // $('#panel').removeClass('hidden'); // $('#view').removeClass('hidden'); // $('#feeStd').removeClass('hidden'); // $('#termData1').addClass('hidden'); // $('#termData2').addClass('hidden'); // $('#term2').addClass('hidden'); // // // } else if ($(this).val()=='Term2' ) { // $('#panel').removeClass('hidden'); // $('#view').removeClass('hidden'); // $('#term2').removeClass('hidden'); // $('#str').addClass('hidden'); // $('#feeStd').addClass('hidden'); // $('#termData1').addClass('hidden'); // $('#termData2').addClass('hidden'); // } // else if ($(this).val()=='str') { // $('#panel').removeClass('hidden'); // $('#view').removeClass('hidden'); // $('#str').removeClass('hidden'); // $('#term2').addClass('hidden'); // $('#feeStd').addClass('hidden'); // $('#termData1').addClass('hidden'); // $('#termData2').addClass('hidden'); // } // else // { // $('#panel').addClass('hidden'); // } // }); var t= $('#example').DataTable({ "bServerSide": true, "bProcessing": true, "sAjaxSource": '<?php echo site_url('FeesCntrl/payslip_Multiple_Data');?>', 'responsive': true, 'scrollX':true, "lengthMenu": [ [5,10, 20, 50, -1], [5,10, 20, 50, "All"] // change per page values here ], columns: [ { data: 'ID',"orderable": true}, { data: 'ID'}, { data: 'EMP_NAME'}, { data: 'EMP_EMAIL'}, { data: 'EMP_ID'}, { data: 'PAYSLIP_NO'}, { data: 'EMP_DEPARTMENT'}, { data: 'MONTH_YEAR'}, { data: 'TOTAL_WORKING_DAYS'}, { data: 'WORKED_DAYS'}, { data: 'BASIC_SALARY'}, { data: 'HRA'}, { data: 'DA'}, { data: 'TRAVELLING_ALLOWANCE'}, { data: 'INCENTIVE'}, { data: 'INCREMENT'}, { data: 'GROSS_EARNINGS'}, { data: 'LOP'}, { data: 'ADVANCE_SALARY'}, { data: 'OTHER_DEDUCTIONS'}, { data: 'GROSS_DEDUCTIONS'}, { data: 'NET_AMOUNT'}, { data: 'REMARKS'}, { data: 'CR_DATE'}, { data: 'UPDATED_DATE'}, ], 'columnDefs': [ { 'targets': 0, 'checkboxes': { 'selectRow': true } } ], 'select': { 'style': 'multi' }, 'order': [[0, 'desc']], //"order": [[ 0, 'desc' ]], 'fnServerData': function(sSource, aoData, fnCallback){ $.ajax({ 'dataType': 'json', 'type' : 'POST', 'url' : sSource, 'data' : aoData, 'success' : fnCallback }); }, }); t.on( 'order.dt search.dt processing.dt page.dt', function () { t.column(1, {search:'applied', order:'applied'}).nodes().each( function (cell, i) { cell.innerHTML = i+1; var info = t.page.info(); var page = info.page+1; if (page >'1') { hal = (page-1) *5; // u can change this value of ur page cell.innerHTML = hal+i+1; } } ); } ).draw(); function loadLoader() { $('body').addClass('loading').loader('show', { overlay: true }); } function unLoader() { $('body').removeClass('loading').loader('hide'); //alert('Mail Send Sucessfully'); } $('#sendEmail').on('click',function(){ $('#EmailUserFancy').modal('show'); }); }); function multiple_mail_send() { var names=[]; var email=[]; $('tr.selected').each(function(){ var datas=$(this).find('td:eq(2)').text(); var data1=$(this).find('td:eq(3)').text(); names.push(datas); email.push(data1); }); console.log(names); console.log(email); //loadLoader(); $.ajax({ type:"post", url:"http://localhost/smartedu/FeesCntrl/Multiple_send_email", data:{names:names,email:email}, success:function(){ //unLoader(); bootbox.alert('<h4><center>Email Send Successfully<center></h4>'); $('#emailfa').removeAttr('class',true).attr('class','fa fa-envelope'); }, }); } // function EmailIdPerson(){ // $('#EmailUserFancy').modal('hide'); // $('#emailfa').removeAttr('class',true).attr('class','fa fa-circle-o-notch fa-spin fa-fw margin-bottom'); // //var emailSystemId = $('#emailSystemId').val(); // var EmailIdClass = $('.EmailIdClass').val(); // console.log(EmailIdClass); // $.ajax({ // type: "POST", // data: {EmailId:EmailIdClass}, // url:"<?php echo site_url('FeesCntrl/feesDefaulterEmail')?>", // success: function (response) { // $('.EmailIdClass').val(''); // bootbox.alert('<b><img alt="" data-id="login-cover-image" src="<?php echo base_url();?>/assets/img/logo.jpg" style="width: 55px;"></b><h4><center>Email Send Successfully<center></h4>'); // $('#emailfa').removeAttr('class',true).attr('class','fa fa-envelope'); // } // }); // // } </script>
mit
Fatal1ty/amqpipe
amqpipe/utils.py
1021
import twisted.internet.error from twisted.internet import defer, reactor from pika.adapters import twisted_connection def asleep(seconds): d = defer.Deferred() reactor.callLater(seconds, d.callback, None) return d class AMQPConnection(twisted_connection.TwistedProtocolConnection): def __init__(self, parameters, connection_errback=None): super(AMQPConnection, self).__init__(parameters) self.connection_errback = connection_errback def connectionLost(self, reason): super(AMQPConnection, self).connectionLost(reason) if self.connection_errback: self.connection_errback(reason) def connectionFailed(self, connection_unused, error_message=None): super(AMQPConnection, self).connectionFailed(connection_unused, error_message) if self.connection_errback: self.connection_errback(twisted.internet.error.ConnectionLost(error_message)) def add_connection_errback(self, method): self.connection_errback = method
mit
stivalet/PHP-Vulnerability-test-suite
Injection/CWE_90/unsafe/CWE_90__system__no_sanitizing__userByMail-interpretation_simple_quote.php
1354
<?php /* Unsafe sample input : execute a ls command using the function system, and put the last result in $tainted sanitize : none construction : interpretation with simple quote */ /*Copyright 2015 Bertrand STIVALET Permission is hereby granted, without written agreement or royalty fee, to use, copy, modify, and distribute this software and its documentation for any purpose, provided that the above copyright notice and the following three paragraphs appear in all copies of this software. IN NO EVENT SHALL AUTHORS BE LIABLE TO ANY PARTY FOR DIRECT, INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OF THIS SOFTWARE AND ITS DOCUMENTATION, EVEN IF AUTHORS HAVE BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. AUTHORS SPECIFICALLY DISCLAIM ANY WARRANTIES INCLUDING, BUT NOT LIMITED TO THE IMPLIED WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE, AND NON-INFRINGEMENT. THE SOFTWARE IS PROVIDED ON AN "AS-IS" BASIS AND AUTHORS HAVE NO OBLIGATION TO PROVIDE MAINTENANCE, SUPPORT, UPDATES, ENHANCEMENTS, OR MODIFICATIONS.*/ $tainted = system('ls', $retval); //no_sanitizing $query = "(&(objectCategory=person)(objectClass=user)(mail=' $tainted '))"; //flaw $ds=ldap_connect("localhost"); $r=ldap_bind($ds); $sr=ldap_search($ds,"o=My Company, c=US", $query); ldap_close($ds); ?>
mit
octavioamu/facebook-app-frame
js/functions.js
384
function inputKeyUp(e) { function urlSet(urlSrc) { var iframeElement = document.getElementById('iframeid'); iframeElement.src = "http://" + urlSrc; } e.which = e.which || e.keyCode; if(e.which == 13) { var urlInput = document.getElementById('urlInput'); urlSet(document.getElementById("urlInput").value); } }
mit
hackforwesternmass/seednetwork
seednetwork/models.py
886
from django.db import models from django.contrib.auth.models import User, AnonymousUser # Create your models here. class MemberInfo(models.Model): user = models.ForeignKey(User) email_is_public = models.BooleanField(default=True) town = models.CharField(max_length=150, blank=True) phone = models.CharField(max_length=150, blank=True) phone_is_public = models.BooleanField(default=True) street_address = models.TextField(blank=True) street_address_is_public = models.BooleanField(default=True) mailing_address = models.TextField(blank=True) mailing_address_is_public = models.BooleanField(default=True) about_me = models.TextField(blank=True) include_in_member_profiles = models.BooleanField(default=True) def __unicode__(self): return self.user.first_name + ' ' + self.user.last_name def __str__(self): return self.user.first_name + ' ' + self.user.last_name
mit
mattmueller/montabe
test/helper.rb
428
require 'rubygems' require 'bundler' begin Bundler.setup(:default, :development) rescue Bundler::BundlerError => e $stderr.puts e.message $stderr.puts "Run `bundle install` to install missing gems" exit e.status_code end require 'test/unit' require 'shoulda' $LOAD_PATH.unshift(File.join(File.dirname(__FILE__), '..', 'lib')) $LOAD_PATH.unshift(File.dirname(__FILE__)) require 'montabe' class Test::Unit::TestCase end
mit
Quanteek/bluetoe
tests/test_services.hpp
2377
#ifndef BLUETOE_TESTS_TEST_SERVICES_HPP #define BLUETOE_TESTS_TEST_SERVICES_HPP #include <bluetoe/service.hpp> #include <bluetoe/characteristic.hpp> namespace { std::uint32_t global_temperature; typedef bluetoe::service< bluetoe::service_uuid< 0xF0426E52, 0x4450, 0x4F3B, 0xB058, 0x5BAB1191D92A >, bluetoe::characteristic< bluetoe::characteristic_uuid< 0x8C8B4094, 0x0DE2, 0x499F, 0xA28A, 0x4EED5BC73CAA >, bluetoe::bind_characteristic_value< std::uint32_t, &global_temperature > > > global_temperature_service; typedef bluetoe::service< bluetoe::service_uuid< 0xF0426E52, 0x4450, 0x4F3B, 0xB058, 0x5BAB1191D92A > > empty_service; bool characteristic_value_1 = 1; const std::uint64_t characteristic_value_2 = 2; const std::int16_t characteristic_value_3 = 3; typedef bluetoe::service< bluetoe::service_uuid< 0x8C8B4094, 0x0DE2, 0x499F, 0xA28A, 0x4EED5BC73CA9 >, bluetoe::characteristic< bluetoe::characteristic_uuid< 0x8C8B4094, 0x0DE2, 0x499F, 0xA28A, 0x4EED5BC73CAA >, bluetoe::bind_characteristic_value< decltype( characteristic_value_1 ), &characteristic_value_1 >, bluetoe::no_read_access >, bluetoe::characteristic< bluetoe::characteristic_uuid< 0x8C8B4094, 0x0DE2, 0x499F, 0xA28A, 0x4EED5BC73CAB >, bluetoe::bind_characteristic_value< decltype( characteristic_value_2 ), &characteristic_value_2 > >, bluetoe::characteristic< bluetoe::characteristic_uuid16< 0x0815 >, bluetoe::bind_characteristic_value< decltype( characteristic_value_3 ), &characteristic_value_3 > > > service_with_3_characteristics; std::uint32_t csc_measurement = 0; static const std::uint16_t csc_feature = 0; typedef bluetoe::service< bluetoe::service_uuid16< 0x1816 >, bluetoe::characteristic< bluetoe::characteristic_uuid16< 0x2A5B >, bluetoe::bind_characteristic_value< decltype( csc_measurement ), &csc_measurement > >, bluetoe::characteristic< bluetoe::characteristic_uuid16< 0x2A5C >, bluetoe::bind_characteristic_value< decltype( csc_feature ), &csc_feature > > > cycling_speed_and_cadence_service; } #endif
mit
aldeed/PhysicsJS
src/behaviors/interactive.js
7515
/** * class InteractiveBehavior < Behavior * * `Physics.behavior('interactive')`. * * User interaction helper. * * Used to get mouse/touch events and add a mouse grab interaction. * * Additional options include: * - el: The element of the renderer. What you input as the `el` for the renderer. * - moveThrottle: The min time between move events (default: `10`). * - minVel: The minimum velocity clamp [[Vectorish]] (default: { x: -5, y: -5 }) to restrict velocity a user can give to a body * - maxVel: The maximum velocity clamp [[Vectorish]] (default: { x: 5, y: 5 }) to restrict velocity a user can give to a body * * The behavior also triggers the following events on the world: * ```javascript * // a body has been grabbed * world.on('interact:grab', function( data ){ * data.x; // the x coord * data.y; // the y coord * data.body; // the body that was grabbed * }); * // no body was grabbed, but the renderer area was clicked, or touched * world.on('interact:poke', function( data ){ * data.x; // the x coord * data.y; // the y coord * }); * world.on('interact:move', function( data ){ * data.x; // the x coord * data.y; // the y coord * data.body; // the body that was grabbed (if applicable) * }); * // when the viewport is released (mouseup, touchend) * world.on('interact:release', function( data ){ * data.x; // the x coord * data.y; // the y coord * }); * ``` **/ Physics.behavior('interactive', function( parent ){ if ( !document ){ // must be in node environment return {}; } var defaults = { // the element to monitor el: null, // time between move events moveThrottle: 1000 / 100 | 0, // minimum velocity clamp minVel: { x: -5, y: -5 }, // maximum velocity clamp maxVel: { x: 5, y: 5 } } ,getElementOffset = function( el ){ var curleft = 0 ,curtop = 0 ; if (el.offsetParent) { do { curleft += el.offsetLeft; curtop += el.offsetTop; } while (el = el.offsetParent); } return { left: curleft, top: curtop }; } ,getCoords = function( e ){ var offset = getElementOffset( e.target ) ,obj = ( e.changedTouches && e.changedTouches[0] ) || e ,x = obj.pageX - offset.left ,y = obj.pageY - offset.top ; return { x: x ,y: y }; } ; return { // extended init: function( options ){ var self = this ,prevTreatment ,time ; // call parent init method parent.init.call( this ); this.options.defaults( defaults ); this.options( options ); // vars this.mousePos = new Physics.vector(); this.mousePosOld = new Physics.vector(); this.offset = new Physics.vector(); this.el = typeof this.options.el === 'string' ? document.getElementById(this.options.el) : this.options.el; if ( !this.el ){ throw "No DOM element specified"; } // init events var grab = function grab( e ){ var pos = getCoords( e ) ,body ; time = Physics.util.ticker.now(); if ( self._world ){ body = self._world.findOne({ $at: new Physics.vector( pos.x, pos.y ) }); if ( body ){ // we're trying to grab a body // fix the body in place prevTreatment = body.treatment; body.treatment = 'kinematic'; body.state.vel.zero(); body.state.angular.vel = 0; // remember the currently grabbed body self.body = body; // remember the mouse offset self.mousePos.clone( pos ); self.mousePosOld.clone( pos ); self.offset.clone( pos ).vsub( body.state.pos ); pos.body = body; self._world.emit('interact:grab', pos); } else { self._world.emit('interact:poke', pos); } } }; var move = Physics.util.throttle(function move( e ){ var pos = getCoords( e ) ,state ; if ( self.body ){ time = Physics.util.ticker.now(); self.mousePosOld.clone( self.mousePos ); // get new mouse position self.mousePos.set(pos.x, pos.y); pos.body = self.body; } self._world.emit('interact:move', pos); }, self.options.moveThrottle); var release = function release( e ){ var pos = getCoords( e ) ,body ,dt = Math.max(Physics.util.ticker.now() - time, self.options.moveThrottle) ; // get new mouse position self.mousePos.set(pos.x, pos.y); // release the body if (self.body){ self.body.treatment = prevTreatment; // calculate the release velocity self.body.state.vel.clone( self.mousePos ).vsub( self.mousePosOld ).mult( 1 / dt ); // make sure it's not too big self.body.state.vel.clamp( self.options.minVel, self.options.maxVel ); self.body = false; } if ( self._world ){ self._world.emit('interact:release', pos); } }; this.el.addEventListener('mousedown', grab); this.el.addEventListener('touchstart', grab); this.el.addEventListener('mousemove', move); this.el.addEventListener('touchmove', move); this.el.addEventListener('mouseup', release); this.el.addEventListener('touchend', release); }, // extended connect: function( world ){ // subscribe the .behave() method to the position integration step world.on('integrate:positions', this.behave, this); }, // extended disconnect: function( world ){ // unsubscribe when disconnected world.off('integrate:positions', this.behave); }, // extended behave: function( data ){ var self = this ,state ,dt = Math.max(data.dt, self.options.moveThrottle) ; if ( self.body ){ // if we have a body, we need to move it the the new mouse position. // we'll do this by adjusting the velocity so it gets there at the next step state = self.body.state; state.vel.clone( self.mousePos ).vsub( self.offset ).vsub( state.pos ).mult( 1 / dt ); } } }; });
mit
e-travel/evelpidon_core_ext
test/hash_test.rb
1130
require 'test_helper' require 'evelpidon_core_ext/hash' class HashTest < ActiveSupport::TestCase test "underscore with string camel case keys" do original = {"StringCamelCase" => "string value", "IntegerCamelCase" => 1, "ArrayCamelCase" => ["Foo", "Bar", {"ArrayNestedStringCamelCase" => "string value"}], "HashCamelCase" => {"NestedStringCamelCase" => "string value", "NestedHashCamelCase" => {"SubNestedIntegerCamelCase" => 2}}} expected = {"string_camel_case" => "string value", "integer_camel_case" => 1, "array_camel_case" => ["Foo", "Bar", {"array_nested_string_camel_case" => "string value"}], "hash_camel_case" => {"nested_string_camel_case" => "string value", "nested_hash_camel_case" => {"sub_nested_integer_camel_case" => 2}}} assert_equal expected, original.underscore_keys end end
mit