code
stringlengths
3
1.05M
repo_name
stringlengths
4
116
path
stringlengths
4
991
language
stringclasses
9 values
license
stringclasses
15 values
size
int32
3
1.05M
import { Component } from '@angular/core'; @Component({ template: 'play' }) export class GamePlayComponent {}
s-robertson/things-angular
src/app/components/game/game-play.component.ts
TypeScript
mit
113
/** * @file NWayBlender.cpp * @brief N-Way shape blend deformer plugin for Maya * @section LICENSE The MIT License * @section requirements: Eigen 3: http://eigen.tuxfamily.org/ * @section Autodesk Maya: http://www.autodesk.com/products/autodesk-maya/overview * @section (included) AffineLib: https://github.com/shizuo-kaji/AffineLib * @version 0.20 * @date 18/Jul/2015 * @author Shizuo KAJI */ #include "StdAfx.h" #include "nwayBlender.h" #include <set> #include <queue> #include <ctime> using namespace Eigen; using namespace AffineLib; using namespace Tetrise; MTypeId nwayDeformerNode::id( 0x00000300 ); MString nwayDeformerNode::nodeName( "nwayBlender" ); MObject nwayDeformerNode::aBlendMode; MObject nwayDeformerNode::aTetMode; MObject nwayDeformerNode::aBlendMesh; MObject nwayDeformerNode::aWeight; MObject nwayDeformerNode::aIteration; MObject nwayDeformerNode::aRotationConsistency; MObject nwayDeformerNode::aVisualiseEnergy; MObject nwayDeformerNode::aVisualisationMultiplier; MObject nwayDeformerNode::aEnergy; MObject nwayDeformerNode::aInitRotation; MObject nwayDeformerNode::aAreaWeighted; MObject nwayDeformerNode::aARAP; // blend matrices template<typename T> void blendMatList(const std::vector< std::vector<T> >& A, const std::vector<double>& weight, std::vector<T>& X){ int numMesh= (int)A.size(); if(numMesh == 0) return; int numTet= (int)A[0].size(); for(int i=0;i<numTet;i++){ X[i].setZero(); for(int j=0;j<numMesh;j++){ X[i] += weight[j]*A[j][i]; } } } template<typename T> void blendMatLinList(const std::vector< std::vector<T> >& A, const std::vector<double>& weight, std::vector<T>& X){ int numMesh= (int)A.size(); if(numMesh == 0) return; int numTet= (int)A[0].size(); for(int i=0;i<numTet;i++){ double sum = 0.0; X[i].setZero(); for(int j=0;j<numMesh;j++){ X[i] += weight[j] * A[j][i]; sum += weight[j]; } X[i] += (1.0-sum) * T::Identity(); } } // blend quaternion linearly void blendQuatList(const std::vector< std::vector<Vector4d> >& A, const std::vector<double>& weight, std::vector<Vector4d>& X){ int numMesh= (int)A.size(); if(numMesh == 0) return; int numTet= (int)A[0].size(); Vector4d I(0,0,0,1); for(int i=0;i<numTet;i++){ double sum = 0.0; X[i].setZero(); for(int j=0;j<numMesh;j++){ X[i] += weight[j] * A[j][i]; sum += weight[j]; } X[i] += (1.0-sum) * I; X[i].normalized(); } } // void* nwayDeformerNode::creator() { return new nwayDeformerNode; } MStatus nwayDeformerNode::deform( MDataBlock& data, MItGeometry& itGeo, const MMatrix &localToWorldMatrix, unsigned int mIndex ) { // clock_t clock_start=clock(); MObject thisNode = thisMObject(); MStatus status; MThreadUtils::syncNumOpenMPThreads(); // for OpenMP MArrayDataHandle hBlendMesh = data.inputArrayValue(aBlendMesh); short numIter = data.inputValue( aIteration ).asShort(); short nblendMode = data.inputValue( aBlendMode ).asShort(); short tetMode = data.inputValue( aTetMode ).asShort(); double visualisationMultiplier = data.inputValue(aVisualisationMultiplier).asDouble(); bool visualiseEnergy = data.inputValue( aVisualiseEnergy ).asBool(); bool nrotationCosistency = data.inputValue( aRotationConsistency ).asBool(); MPointArray Mpts; itGeo.allPositions(Mpts); int nnumMesh = hBlendMesh.elementCount(); int numPts = Mpts.length(); // initialisation if(!data.isClean(aARAP)){ // clock_t clock_start=clock(); numMesh = 0; // point list pts.resize(numPts); for(int i=0;i<numPts;i++){ pts[i] << Mpts[i].x, Mpts[i].y, Mpts[i].z; } // make tetrahedral structure getMeshData(data, input, inputGeom, mIndex, tetMode, pts, mesh.tetList, faceList, edgeList, vertexList, mesh.tetMatrix, mesh.tetWeight); mesh.dim = removeDegenerate(tetMode, numPts, mesh.tetList, faceList, edgeList, vertexList, mesh.tetMatrix); makeTetMatrix(tetMode, pts, mesh.tetList, faceList, edgeList, vertexList, mesh.tetMatrix, mesh.tetWeight); makeAdjacencyList(tetMode, mesh.tetList, edgeList, vertexList, adjacencyList); mesh.numTet = (int)mesh.tetList.size()/4; mesh.computeTetMatrixInverse(); // prepare ARAP solver if(!data.inputValue( aAreaWeighted ).asBool()){ mesh.tetWeight.clear(); mesh.tetWeight.resize(mesh.numTet,1.0); } mesh.constraintWeight.resize(1); mesh.constraintWeight[0] = std::make_pair(0,1.0); mesh.constraintVal.resize(1,3); mesh.constraintVal(0,0) = pts[0][0]; mesh.constraintVal(0,1) = pts[0][1]; mesh.constraintVal(0,2) = pts[0][2]; isError = mesh.ARAPprecompute(); status = data.setClean(aARAP); // MString es="Init timing: "; // double timing=(double)(clock()- clock_start)/CLOCKS_PER_SEC; // es += timing; // MGlobal::displayInfo(es); } if(isError>0) return MS::kFailure; // if blend mesh is added, compute log for each tet logR.resize(nnumMesh); logS.resize(nnumMesh); R.resize(nnumMesh); S.resize(nnumMesh); GL.resize(nnumMesh); logGL.resize(nnumMesh); quat.resize(nnumMesh); L.resize(nnumMesh); // for recomputation of parametrisation if(numMesh>nnumMesh || nblendMode != blendMode || nrotationCosistency != rotationCosistency){ numMesh =0; blendMode = nblendMode; rotationCosistency = nrotationCosistency; } for(int j=numMesh; j<nnumMesh; j++){ hBlendMesh.jumpToElement(j); MFnMesh blendMesh(hBlendMesh.inputValue().asMesh()); MPointArray Mbpts; blendMesh.getPoints( Mbpts ); if(numPts != Mbpts.length()){ MGlobal::displayInfo("incompatible mesh"); return MS::kFailure; } std::vector<Vector3d> bpts(numPts); for(int i=0;i<numPts;i++){ bpts[i] << Mbpts[i].x, Mbpts[i].y, Mbpts[i].z; } makeTetMatrix(tetMode, bpts, mesh.tetList, faceList, edgeList, vertexList, Q, dummy_weight); logR[j].resize(mesh.numTet); logS[j].resize(mesh.numTet); R[j].resize(mesh.numTet); S[j].resize(mesh.numTet); GL[j].resize(mesh.numTet); L[j].resize(mesh.numTet); for(int i=0;i<mesh.numTet;i++) { Matrix4d aff=mesh.tetMatrixInverse[i]*Q[i]; GL[j][i]=aff.block(0,0,3,3); L[j][i]=transPart(aff); parametriseGL(GL[j][i], logS[j][i] ,R[j][i]); } if( blendMode == BM_LOG3){ logGL[j].resize(mesh.numTet); for(int i=0;i<mesh.numTet;i++) logGL[j][i]=GL[j][i].log(); }else if( blendMode == BM_SQL){ quat[j].resize(mesh.numTet); for(int i=0;i<mesh.numTet;i++){ S[j][i]=expSym(logS[j][i]); Quaternion<double> q(R[j][i].transpose()); quat[j][i] << q.x(), q.y(), q.z(), q.w(); } }else if( blendMode == BM_SlRL){ for(int i=0;i<mesh.numTet;i++){ S[j][i]=expSym(logS[j][i]); } } // traverse tetrahedra to compute continuous log of rotation if(rotationCosistency){ std::set<int> remain; std::queue<int> later; // load initial rotation from the attr Matrix3d initR; double angle = data.inputValue(aInitRotation).asDouble(); initR << 0,M_PI * angle/180.0,0, -M_PI * angle/180.0,0,0, 0,0,0; std::vector<Matrix3d> prevSO(mesh.numTet, initR); // create the adjacency graph to traverse for(int i=0;i<mesh.numTet;i++){ remain.insert(remain.end(),i); } while(!remain.empty()){ int next; if( !later.empty()){ next = later.front(); later.pop(); remain.erase(next); }else{ next = *remain.begin(); remain.erase(remain.begin()); } logR[j][next]=logSOc(R[j][next],prevSO[next]); for(int k=0;k<adjacencyList[next].size();k++){ int f=adjacencyList[next][k]; if(remain.erase(f)>0){ prevSO[f]=logR[j][next]; later.push(f); } } } }else{ for(int i=0;i<mesh.numTet;i++) logR[j][i] = logSO(R[j][i]); } } numMesh=nnumMesh; if(numMesh == 0) return MS::kSuccess; // load weights std::vector<double> weight(numMesh); MArrayDataHandle hWeight = data.inputArrayValue(aWeight); if(hWeight.elementCount() != numMesh) { return MS::kSuccess; } for(int i=0;i<numMesh;i++){ hWeight.jumpToArrayElement(i); weight[i]=hWeight.inputValue().asDouble(); } // compute ideal affine std::vector<Vector3d> new_pts(numPts); std::vector<Matrix4d> A(mesh.numTet); std::vector<Matrix3d> AR(mesh.numTet),AS(mesh.numTet); std::vector<Vector3d> AL(mesh.numTet); blendMatList(L, weight, AL); if(blendMode==BM_SRL){ blendMatList(logR, weight, AR); blendMatList(logS, weight, AS); #pragma omp parallel for for(int i=0;i<mesh.numTet;i++){ AR[i] = expSO(AR[i]); AS[i] = expSym(AS[i]); } }else if(blendMode == BM_LOG3){ // log blendMatList(logGL, weight, AR); #pragma omp parallel for for(int i=0;i<mesh.numTet;i++){ AR[i] = AR[i].exp(); AS[i] = Matrix3d::Identity(); } }else if(blendMode == BM_SQL){ // quaternion std::vector<Vector4d> Aq(mesh.numTet); blendMatLinList(S, weight, AS); blendQuatList(quat, weight, Aq); #pragma omp parallel for for(int i=0;i<mesh.numTet;i++){ Quaternion<double> Q(Aq[i]); AR[i] = Q.matrix().transpose(); } }else if(blendMode == BM_SlRL){ // expSO+linear Sym blendMatList(logR, weight, AR); blendMatLinList(S, weight, AS); #pragma omp parallel for for(int i=0;i<mesh.numTet;i++){ AR[i] = expSO(AR[i]); } }else if(blendMode == BM_AFF){ // linear blendMatLinList(GL, weight, AR); for(int i=0;i<mesh.numTet;i++){ AS[i] = Matrix3d::Identity(); } }else{ return MS::kFailure; } std::vector<double> tetEnergy(mesh.numTet); // iterate to determine vertices position for(int k=0;k<numIter;k++){ for(int i=0;i<mesh.numTet;i++){ A[i]=pad(AS[i]*AR[i],AL[i]); } // solve ARAP mesh.ARAPSolve(A); // set new vertices position for(int i=0;i<numPts;i++){ new_pts[i][0]=mesh.Sol(i,0); new_pts[i][1]=mesh.Sol(i,1); new_pts[i][2]=mesh.Sol(i,2); } // if iteration continues if(k+1<numIter || visualiseEnergy){ makeTetMatrix(tetMode, new_pts, mesh.tetList, faceList, edgeList, vertexList, Q, dummy_weight); Matrix3d S,R; #pragma omp parallel for for(int i=0;i<mesh.numTet;i++) { polarHigham((mesh.tetMatrixInverse[i]*Q[i]).block(0,0,3,3), S, AR[i]); tetEnergy[i] = (S-AS[i]).squaredNorm(); } } } // set new vertex position for(int i=0;i<numPts;i++){ Mpts[i].x=mesh.Sol(i,0); Mpts[i].y=mesh.Sol(i,1); Mpts[i].z=mesh.Sol(i,2); } itGeo.setAllPositions(Mpts); // set vertex color according to ARAP energy if(visualiseEnergy){ std::vector<double> ptsEnergy; makePtsWeightList(tetMode, numPts, mesh.tetList, faceList, edgeList, vertexList, tetEnergy, ptsEnergy); //double max_energy = *std::max_element(ptsEnergy.begin(), ptsEnergy.end()); outputAttr(data, aEnergy, ptsEnergy); for(int i=0;i<numPts;i++){ ptsEnergy[i] *= visualisationMultiplier; // or /= max_energy } visualise(data, outputGeom, ptsEnergy); } // MString es="Runtime timing: "; // double timing=(double)(clock()- clock_start)/CLOCKS_PER_SEC; // es += timing; // MGlobal::displayInfo(es); return MS::kSuccess; } // plugin (un)initialiser MStatus nwayDeformerNode::initialize() { MFnTypedAttribute tAttr; MFnNumericAttribute nAttr; MFnEnumAttribute eAttr; MFnMatrixAttribute mAttr; // this attr will be dirtied when ARAP recomputation is needed aARAP = nAttr.create( "arap", "arap", MFnNumericData::kBoolean, true ); nAttr.setStorable(false); nAttr.setKeyable(false); nAttr.setHidden(true); addAttribute( aARAP ); aBlendMesh = tAttr.create("blendMesh", "mesh", MFnData::kMesh); tAttr.setArray(true); tAttr.setUsesArrayDataBuilder(true); addAttribute(aBlendMesh); attributeAffects( aBlendMesh, outputGeom ); aWeight = nAttr.create("blendWeight", "bw", MFnNumericData::kDouble, 0.0); nAttr.setArray(true); nAttr.setKeyable(true); nAttr.setStorable(true); nAttr.setUsesArrayDataBuilder(true); addAttribute(aWeight); attributeAffects( aWeight, outputGeom ); aRotationConsistency = nAttr.create( "rotationConsistency", "rc", MFnNumericData::kBoolean, false ); nAttr.setStorable(true); addAttribute( aRotationConsistency ); attributeAffects( aRotationConsistency, outputGeom ); aInitRotation = nAttr.create("initRotation", "ir", MFnNumericData::kDouble); addAttribute(aInitRotation); attributeAffects( aInitRotation, outputGeom ); aVisualiseEnergy = nAttr.create( "visualiseEnergy", "ve", MFnNumericData::kBoolean, false ); nAttr.setStorable(true); addAttribute( aVisualiseEnergy ); attributeAffects( aVisualiseEnergy, outputGeom ); aAreaWeighted = nAttr.create( "areaWeighted", "aw", MFnNumericData::kBoolean, false ); nAttr.setStorable(true); addAttribute( aAreaWeighted ); attributeAffects( aAreaWeighted, outputGeom ); attributeAffects( aAreaWeighted, aARAP ); aVisualisationMultiplier = nAttr.create("visualisationMultiplier", "vmp", MFnNumericData::kDouble, 1.0); nAttr.setStorable(true); addAttribute( aVisualisationMultiplier ); attributeAffects( aVisualisationMultiplier, outputGeom ); aBlendMode = eAttr.create( "blendMode", "bm", BM_SRL ); eAttr.addField( "expSO+expSym", BM_SRL ); eAttr.addField( "logmatrix3", BM_LOG3 ); eAttr.addField( "quat+linear", BM_SQL ); eAttr.addField( "expSO+linear", BM_SlRL ); eAttr.addField( "linear", BM_AFF ); eAttr.addField( "off", BM_OFF ); addAttribute( aBlendMode ); attributeAffects( aBlendMode, outputGeom ); aTetMode = eAttr.create( "tetMode", "tm", TM_FACE ); eAttr.addField( "face", TM_FACE ); eAttr.addField( "edge", TM_EDGE ); eAttr.addField( "vertex", TM_VERTEX ); eAttr.addField( "vface", TM_VFACE ); addAttribute( aTetMode ); attributeAffects( aTetMode, outputGeom ); attributeAffects( aTetMode, aARAP ); aIteration = nAttr.create("iteration", "it", MFnNumericData::kShort, 1); addAttribute(aIteration); attributeAffects(aIteration, outputGeom); // this shouldn't affect outputGeom aEnergy = nAttr.create("energy", "energy", MFnNumericData::kDouble, 0.0); nAttr.setArray(true); nAttr.setKeyable(true); nAttr.setStorable(true); nAttr.setUsesArrayDataBuilder(true); addAttribute(aEnergy); // Make the deformer weights paintable MGlobal::executeCommand( "makePaintable -attrType multiFloat -sm deformer nwayBlender weights;" ); return MS::kSuccess; } // this deformer also changes colours void nwayDeformerNode::postConstructor(){ setDeformationDetails(kDeformsColors); } MStatus initializePlugin( MObject obj ) { MStatus status; MFnPlugin plugin( obj, "Shizuo KAJI", "0.1", "Any"); status = plugin.registerNode( nwayDeformerNode::nodeName, nwayDeformerNode::id, nwayDeformerNode::creator, nwayDeformerNode::initialize, MPxNode::kDeformerNode ); CHECK_MSTATUS_AND_RETURN_IT( status ); return status; } MStatus uninitializePlugin( MObject obj ) { MStatus status; MFnPlugin plugin( obj ); status = plugin.deregisterNode( nwayDeformerNode::id ); CHECK_MSTATUS_AND_RETURN_IT( status ); return status; }
shizuo-kaji/NWayBlenderMaya
nwayBlender/nwayBlender.cpp
C++
mit
17,135
var extend = require('extend'); var plivo = require('plivo'); var crypto = require('crypto') var phone = require('phone'); var TelcomPlivoClient = module.exports = function(opts){ if (!(this instanceof TelcomPlivoClient)) return new TelcomPlivoClient(options); this.options = {}; extend(this.options,opts); this._client = plivo.RestAPI({ authId: this.options.sid, authToken: this.options.token }); }; TelcomPlivoClient.prototype.validateRequest = function(req,callback){ if(req.header('X-Plivo-Signature') === undefined) return callback('missing requrired header.') var params = req.body; if(req.method === 'GET'){ params = req.query; } var toSign = req._telcomRequestUrlNoQuery; var expectedSignature = create_signature(toSign, params,this.options.token); if(req.header('X-Plivo-Signature') === expectedSignature) callback(); else callback('signature does not match'); } TelcomPlivoClient.prototype.sms = function(obj,callback){ var plivoMesg = { src : phone(obj.from), dst : phone(obj.to), text : obj.body }; /* { api_id: 'xxxxxxxxx-1f9d-11e3-b44b-22000ac53995', message: 'message(s) queued', message_uuid: [ 'xxxxxxxx-1f9d-11e3-b1d3-123141013a24' ] } */ this._client.send_message(plivoMesg, function(err, ret) { if(err === 202){ err = undefined; } if(!ret) ret = {}; callback(err,ret.message_uuid[0],ret.message,ret); }); }; /* { To: '15559633214', Type: 'sms', MessageUUID: 'xxxxxxx-2465-11e3-985d-0025907b94de', From: '15557894561', Text: 'Vg\n' } { to : '', from : '', body : '', messageId : '', } */ TelcomPlivoClient.prototype._convertSmsRequest = function(params){ return { to : phone(params['To']), from : phone(params['From']), body : params['Text'], messageId : params['MessageUUID'], _clientRequest : params }; } // For verifying the plivo server signature // By Jon Keating - https://github.com/mathrawka/plivo-node function create_signature(url, params,token) { var toSign = url; Object.keys(params).sort().forEach(function(key) { toSign += key + params[key]; }); var signature = crypto .createHmac('sha1',token) .update(toSign) .digest('base64'); return signature; };
AdamMagaluk/telcom
lib/providers/plivo.js
JavaScript
mit
2,286
/* * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for * license information. * * Code generated by Microsoft (R) AutoRest Code Generator. * Changes may cause incorrect behavior and will be lost if the code is * regenerated. */ import { ServiceClientOptions, RequestOptions, ServiceCallback } from 'ms-rest'; import * as models from '../models'; /** * @class * Deployments * __NOTE__: An instance of this class is automatically created for an * instance of the ResourceManagementClient. */ export interface Deployments { /** * Delete deployment. * * @param {string} resourceGroupName The name of the resource group. The name * is case insensitive. * * @param {string} deploymentName The name of the deployment to be deleted. * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @param {ServiceCallback} [callback] callback function; see ServiceCallback * doc in ms-rest index.d.ts for details */ deleteMethod(resourceGroupName: string, deploymentName: string, options: { customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<void>): void; deleteMethod(resourceGroupName: string, deploymentName: string, callback: ServiceCallback<void>): void; /** * Delete deployment. * * @param {string} resourceGroupName The name of the resource group. The name * is case insensitive. * * @param {string} deploymentName The name of the deployment to be deleted. * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @param {ServiceCallback} [callback] callback function; see ServiceCallback * doc in ms-rest index.d.ts for details */ beginDeleteMethod(resourceGroupName: string, deploymentName: string, options: { customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<void>): void; beginDeleteMethod(resourceGroupName: string, deploymentName: string, callback: ServiceCallback<void>): void; /** * Checks whether deployment exists. * * @param {string} resourceGroupName The name of the resource group to check. * The name is case insensitive. * * @param {string} deploymentName The name of the deployment. * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @param {ServiceCallback} [callback] callback function; see ServiceCallback * doc in ms-rest index.d.ts for details */ checkExistence(resourceGroupName: string, deploymentName: string, options: { customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<boolean>): void; checkExistence(resourceGroupName: string, deploymentName: string, callback: ServiceCallback<boolean>): void; /** * Create a named template deployment using a template. * * @param {string} resourceGroupName The name of the resource group. The name * is case insensitive. * * @param {string} deploymentName The name of the deployment. * * @param {object} [options] Optional Parameters. * * @param {object} [options.properties] Gets or sets the deployment properties. * * @param {object} [options.properties.template] Gets or sets the template * content. Use only one of Template or TemplateLink. * * @param {object} [options.properties.templateLink] Gets or sets the URI * referencing the template. Use only one of Template or TemplateLink. * * @param {string} [options.properties.templateLink.uri] URI referencing the * template. * * @param {string} [options.properties.templateLink.contentVersion] If * included it must match the ContentVersion in the template. * * @param {object} [options.properties.parameters] Deployment parameters. Use * only one of Parameters or ParametersLink. * * @param {object} [options.properties.parametersLink] Gets or sets the URI * referencing the parameters. Use only one of Parameters or ParametersLink. * * @param {string} [options.properties.parametersLink.uri] URI referencing the * template. * * @param {string} [options.properties.parametersLink.contentVersion] If * included it must match the ContentVersion in the template. * * @param {string} [options.properties.mode] Gets or sets the deployment mode. * Possible values include: 'Incremental', 'Complete' * * @param {object} [options.properties.debugSetting] Gets or sets the debug * setting of the deployment. * * @param {string} [options.properties.debugSetting.detailLevel] Gets or sets * the debug detail level. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @param {ServiceCallback} [callback] callback function; see ServiceCallback * doc in ms-rest index.d.ts for details */ createOrUpdate(resourceGroupName: string, deploymentName: string, options: { properties? : models.DeploymentProperties, customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<models.DeploymentExtended>): void; createOrUpdate(resourceGroupName: string, deploymentName: string, callback: ServiceCallback<models.DeploymentExtended>): void; /** * Create a named template deployment using a template. * * @param {string} resourceGroupName The name of the resource group. The name * is case insensitive. * * @param {string} deploymentName The name of the deployment. * * @param {object} [options] Optional Parameters. * * @param {object} [options.properties] Gets or sets the deployment properties. * * @param {object} [options.properties.template] Gets or sets the template * content. Use only one of Template or TemplateLink. * * @param {object} [options.properties.templateLink] Gets or sets the URI * referencing the template. Use only one of Template or TemplateLink. * * @param {string} [options.properties.templateLink.uri] URI referencing the * template. * * @param {string} [options.properties.templateLink.contentVersion] If * included it must match the ContentVersion in the template. * * @param {object} [options.properties.parameters] Deployment parameters. Use * only one of Parameters or ParametersLink. * * @param {object} [options.properties.parametersLink] Gets or sets the URI * referencing the parameters. Use only one of Parameters or ParametersLink. * * @param {string} [options.properties.parametersLink.uri] URI referencing the * template. * * @param {string} [options.properties.parametersLink.contentVersion] If * included it must match the ContentVersion in the template. * * @param {string} [options.properties.mode] Gets or sets the deployment mode. * Possible values include: 'Incremental', 'Complete' * * @param {object} [options.properties.debugSetting] Gets or sets the debug * setting of the deployment. * * @param {string} [options.properties.debugSetting.detailLevel] Gets or sets * the debug detail level. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @param {ServiceCallback} [callback] callback function; see ServiceCallback * doc in ms-rest index.d.ts for details */ beginCreateOrUpdate(resourceGroupName: string, deploymentName: string, options: { properties? : models.DeploymentProperties, customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<models.DeploymentExtended>): void; beginCreateOrUpdate(resourceGroupName: string, deploymentName: string, callback: ServiceCallback<models.DeploymentExtended>): void; /** * Get a deployment. * * @param {string} resourceGroupName The name of the resource group to get. * The name is case insensitive. * * @param {string} deploymentName The name of the deployment. * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @param {ServiceCallback} [callback] callback function; see ServiceCallback * doc in ms-rest index.d.ts for details */ get(resourceGroupName: string, deploymentName: string, options: { customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<models.DeploymentExtended>): void; get(resourceGroupName: string, deploymentName: string, callback: ServiceCallback<models.DeploymentExtended>): void; /** * Cancel a currently running template deployment. * * @param {string} resourceGroupName The name of the resource group. The name * is case insensitive. * * @param {string} deploymentName The name of the deployment. * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @param {ServiceCallback} [callback] callback function; see ServiceCallback * doc in ms-rest index.d.ts for details */ cancel(resourceGroupName: string, deploymentName: string, options: { customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<void>): void; cancel(resourceGroupName: string, deploymentName: string, callback: ServiceCallback<void>): void; /** * Validate a deployment template. * * @param {string} resourceGroupName The name of the resource group. The name * is case insensitive. * * @param {string} deploymentName The name of the deployment. * * @param {object} [options] Optional Parameters. * * @param {object} [options.properties] Gets or sets the deployment properties. * * @param {object} [options.properties.template] Gets or sets the template * content. Use only one of Template or TemplateLink. * * @param {object} [options.properties.templateLink] Gets or sets the URI * referencing the template. Use only one of Template or TemplateLink. * * @param {string} [options.properties.templateLink.uri] URI referencing the * template. * * @param {string} [options.properties.templateLink.contentVersion] If * included it must match the ContentVersion in the template. * * @param {object} [options.properties.parameters] Deployment parameters. Use * only one of Parameters or ParametersLink. * * @param {object} [options.properties.parametersLink] Gets or sets the URI * referencing the parameters. Use only one of Parameters or ParametersLink. * * @param {string} [options.properties.parametersLink.uri] URI referencing the * template. * * @param {string} [options.properties.parametersLink.contentVersion] If * included it must match the ContentVersion in the template. * * @param {string} [options.properties.mode] Gets or sets the deployment mode. * Possible values include: 'Incremental', 'Complete' * * @param {object} [options.properties.debugSetting] Gets or sets the debug * setting of the deployment. * * @param {string} [options.properties.debugSetting.detailLevel] Gets or sets * the debug detail level. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @param {ServiceCallback} [callback] callback function; see ServiceCallback * doc in ms-rest index.d.ts for details */ validate(resourceGroupName: string, deploymentName: string, options: { properties? : models.DeploymentProperties, customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<models.DeploymentValidateResult>): void; validate(resourceGroupName: string, deploymentName: string, callback: ServiceCallback<models.DeploymentValidateResult>): void; /** * Exports a deployment template. * * @param {string} resourceGroupName The name of the resource group. The name * is case insensitive. * * @param {string} deploymentName The name of the deployment. * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @param {ServiceCallback} [callback] callback function; see ServiceCallback * doc in ms-rest index.d.ts for details */ exportTemplate(resourceGroupName: string, deploymentName: string, options: { customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<models.DeploymentExportResult>): void; exportTemplate(resourceGroupName: string, deploymentName: string, callback: ServiceCallback<models.DeploymentExportResult>): void; /** * Get a list of deployments. * * @param {string} resourceGroupName The name of the resource group to filter * by. The name is case insensitive. * * @param {object} [options] Optional Parameters. * * @param {string} [options.filter] The filter to apply on the operation. * * @param {number} [options.top] Query parameters. If null is passed returns * all deployments. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @param {ServiceCallback} [callback] callback function; see ServiceCallback * doc in ms-rest index.d.ts for details */ list(resourceGroupName: string, options: { filter? : string, top? : number, customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<models.DeploymentListResult>): void; list(resourceGroupName: string, callback: ServiceCallback<models.DeploymentListResult>): void; /** * Get a list of deployments. * * @param {string} nextPageLink The NextLink from the previous successful call * to List operation. * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @param {ServiceCallback} [callback] callback function; see ServiceCallback * doc in ms-rest index.d.ts for details */ listNext(nextPageLink: string, options: { customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<models.DeploymentListResult>): void; listNext(nextPageLink: string, callback: ServiceCallback<models.DeploymentListResult>): void; } /** * @class * Providers * __NOTE__: An instance of this class is automatically created for an * instance of the ResourceManagementClient. */ export interface Providers { /** * Unregisters provider from a subscription. * * @param {string} resourceProviderNamespace Namespace of the resource * provider. * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @param {ServiceCallback} [callback] callback function; see ServiceCallback * doc in ms-rest index.d.ts for details */ unregister(resourceProviderNamespace: string, options: { customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<models.Provider>): void; unregister(resourceProviderNamespace: string, callback: ServiceCallback<models.Provider>): void; /** * Registers provider to be used with a subscription. * * @param {string} resourceProviderNamespace Namespace of the resource * provider. * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @param {ServiceCallback} [callback] callback function; see ServiceCallback * doc in ms-rest index.d.ts for details */ register(resourceProviderNamespace: string, options: { customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<models.Provider>): void; register(resourceProviderNamespace: string, callback: ServiceCallback<models.Provider>): void; /** * Gets a list of resource providers. * * @param {object} [options] Optional Parameters. * * @param {number} [options.top] Query parameters. If null is passed returns * all deployments. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @param {ServiceCallback} [callback] callback function; see ServiceCallback * doc in ms-rest index.d.ts for details */ list(options: { top? : number, customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<models.ProviderListResult>): void; list(callback: ServiceCallback<models.ProviderListResult>): void; /** * Gets a resource provider. * * @param {string} resourceProviderNamespace Namespace of the resource * provider. * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @param {ServiceCallback} [callback] callback function; see ServiceCallback * doc in ms-rest index.d.ts for details */ get(resourceProviderNamespace: string, options: { customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<models.Provider>): void; get(resourceProviderNamespace: string, callback: ServiceCallback<models.Provider>): void; /** * Gets a list of resource providers. * * @param {string} nextPageLink The NextLink from the previous successful call * to List operation. * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @param {ServiceCallback} [callback] callback function; see ServiceCallback * doc in ms-rest index.d.ts for details */ listNext(nextPageLink: string, options: { customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<models.ProviderListResult>): void; listNext(nextPageLink: string, callback: ServiceCallback<models.ProviderListResult>): void; } /** * @class * ResourceGroups * __NOTE__: An instance of this class is automatically created for an * instance of the ResourceManagementClient. */ export interface ResourceGroups { /** * Get all of the resources under a subscription. * * @param {string} resourceGroupName Query parameters. If null is passed * returns all resource groups. * * @param {object} [options] Optional Parameters. * * @param {string} [options.filter] The filter to apply on the operation. * * @param {number} [options.top] Query parameters. If null is passed returns * all resource groups. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @param {ServiceCallback} [callback] callback function; see ServiceCallback * doc in ms-rest index.d.ts for details */ listResources(resourceGroupName: string, options: { filter? : string, top? : number, customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<models.ResourceListResult>): void; listResources(resourceGroupName: string, callback: ServiceCallback<models.ResourceListResult>): void; /** * Checks whether resource group exists. * * @param {string} resourceGroupName The name of the resource group to check. * The name is case insensitive. * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @param {ServiceCallback} [callback] callback function; see ServiceCallback * doc in ms-rest index.d.ts for details */ checkExistence(resourceGroupName: string, options: { customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<boolean>): void; checkExistence(resourceGroupName: string, callback: ServiceCallback<boolean>): void; /** * Create a resource group. * * @param {string} resourceGroupName The name of the resource group to be * created or updated. * * @param {object} parameters Parameters supplied to the create or update * resource group service operation. * * @param {string} [parameters.name] Gets or sets the Name of the resource * group. * * @param {object} [parameters.properties] * * @param {string} [parameters.location] Gets or sets the location of the * resource group. It cannot be changed after the resource group has been * created. Has to be one of the supported Azure Locations, such as West US, * East US, West Europe, East Asia, etc. * * @param {object} [parameters.tags] Gets or sets the tags attached to the * resource group. * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @param {ServiceCallback} [callback] callback function; see ServiceCallback * doc in ms-rest index.d.ts for details */ createOrUpdate(resourceGroupName: string, parameters: models.ResourceGroup, options: { customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<models.ResourceGroup>): void; createOrUpdate(resourceGroupName: string, parameters: models.ResourceGroup, callback: ServiceCallback<models.ResourceGroup>): void; /** * Delete resource group. * * @param {string} resourceGroupName The name of the resource group to be * deleted. The name is case insensitive. * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @param {ServiceCallback} [callback] callback function; see ServiceCallback * doc in ms-rest index.d.ts for details */ deleteMethod(resourceGroupName: string, options: { customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<void>): void; deleteMethod(resourceGroupName: string, callback: ServiceCallback<void>): void; /** * Delete resource group. * * @param {string} resourceGroupName The name of the resource group to be * deleted. The name is case insensitive. * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @param {ServiceCallback} [callback] callback function; see ServiceCallback * doc in ms-rest index.d.ts for details */ beginDeleteMethod(resourceGroupName: string, options: { customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<void>): void; beginDeleteMethod(resourceGroupName: string, callback: ServiceCallback<void>): void; /** * Get a resource group. * * @param {string} resourceGroupName The name of the resource group to get. * The name is case insensitive. * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @param {ServiceCallback} [callback] callback function; see ServiceCallback * doc in ms-rest index.d.ts for details */ get(resourceGroupName: string, options: { customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<models.ResourceGroup>): void; get(resourceGroupName: string, callback: ServiceCallback<models.ResourceGroup>): void; /** * Resource groups can be updated through a simple PATCH operation to a group * address. The format of the request is the same as that for creating a * resource groups, though if a field is unspecified current value will be * carried over. * * @param {string} resourceGroupName The name of the resource group to be * created or updated. The name is case insensitive. * * @param {object} parameters Parameters supplied to the update state resource * group service operation. * * @param {string} [parameters.name] Gets or sets the Name of the resource * group. * * @param {object} [parameters.properties] * * @param {string} [parameters.location] Gets or sets the location of the * resource group. It cannot be changed after the resource group has been * created. Has to be one of the supported Azure Locations, such as West US, * East US, West Europe, East Asia, etc. * * @param {object} [parameters.tags] Gets or sets the tags attached to the * resource group. * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @param {ServiceCallback} [callback] callback function; see ServiceCallback * doc in ms-rest index.d.ts for details */ patch(resourceGroupName: string, parameters: models.ResourceGroup, options: { customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<models.ResourceGroup>): void; patch(resourceGroupName: string, parameters: models.ResourceGroup, callback: ServiceCallback<models.ResourceGroup>): void; /** * Captures the specified resource group as a template. * * @param {string} resourceGroupName The name of the resource group to be * created or updated. * * @param {object} parameters Parameters supplied to the export template * resource group operation. * * @param {array} [parameters.resources] Gets or sets the ids of the * resources. The only supported string currently is '*' (all resources). * Future api updates will support exporting specific resources. * * @param {string} [parameters.options] The export template options. Supported * values include 'IncludeParameterDefaultValue', 'IncludeComments' or * 'IncludeParameterDefaultValue, IncludeComments * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @param {ServiceCallback} [callback] callback function; see ServiceCallback * doc in ms-rest index.d.ts for details */ exportTemplate(resourceGroupName: string, parameters: models.ExportTemplateRequest, options: { customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<models.ResourceGroupExportResult>): void; exportTemplate(resourceGroupName: string, parameters: models.ExportTemplateRequest, callback: ServiceCallback<models.ResourceGroupExportResult>): void; /** * Gets a collection of resource groups. * * @param {object} [options] Optional Parameters. * * @param {string} [options.filter] The filter to apply on the operation. * * @param {number} [options.top] Query parameters. If null is passed returns * all resource groups. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @param {ServiceCallback} [callback] callback function; see ServiceCallback * doc in ms-rest index.d.ts for details */ list(options: { filter? : string, top? : number, customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<models.ResourceGroupListResult>): void; list(callback: ServiceCallback<models.ResourceGroupListResult>): void; /** * Get all of the resources under a subscription. * * @param {string} nextPageLink The NextLink from the previous successful call * to List operation. * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @param {ServiceCallback} [callback] callback function; see ServiceCallback * doc in ms-rest index.d.ts for details */ listResourcesNext(nextPageLink: string, options: { customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<models.ResourceListResult>): void; listResourcesNext(nextPageLink: string, callback: ServiceCallback<models.ResourceListResult>): void; /** * Gets a collection of resource groups. * * @param {string} nextPageLink The NextLink from the previous successful call * to List operation. * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @param {ServiceCallback} [callback] callback function; see ServiceCallback * doc in ms-rest index.d.ts for details */ listNext(nextPageLink: string, options: { customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<models.ResourceGroupListResult>): void; listNext(nextPageLink: string, callback: ServiceCallback<models.ResourceGroupListResult>): void; } /** * @class * Resources * __NOTE__: An instance of this class is automatically created for an * instance of the ResourceManagementClient. */ export interface Resources { /** * Move resources from one resource group to another. The resources being * moved should all be in the same resource group. * * @param {string} sourceResourceGroupName Source resource group name. * * @param {object} parameters move resources' parameters. * * @param {array} [parameters.resources] Gets or sets the ids of the resources. * * @param {string} [parameters.targetResourceGroup] The target resource group. * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @param {ServiceCallback} [callback] callback function; see ServiceCallback * doc in ms-rest index.d.ts for details */ moveResources(sourceResourceGroupName: string, parameters: models.ResourcesMoveInfo, options: { customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<void>): void; moveResources(sourceResourceGroupName: string, parameters: models.ResourcesMoveInfo, callback: ServiceCallback<void>): void; /** * Move resources from one resource group to another. The resources being * moved should all be in the same resource group. * * @param {string} sourceResourceGroupName Source resource group name. * * @param {object} parameters move resources' parameters. * * @param {array} [parameters.resources] Gets or sets the ids of the resources. * * @param {string} [parameters.targetResourceGroup] The target resource group. * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @param {ServiceCallback} [callback] callback function; see ServiceCallback * doc in ms-rest index.d.ts for details */ beginMoveResources(sourceResourceGroupName: string, parameters: models.ResourcesMoveInfo, options: { customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<void>): void; beginMoveResources(sourceResourceGroupName: string, parameters: models.ResourcesMoveInfo, callback: ServiceCallback<void>): void; /** * Get all of the resources under a subscription. * * @param {object} [options] Optional Parameters. * * @param {string} [options.filter] The filter to apply on the operation. * * @param {number} [options.top] Query parameters. If null is passed returns * all resource groups. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @param {ServiceCallback} [callback] callback function; see ServiceCallback * doc in ms-rest index.d.ts for details */ list(options: { filter? : string, top? : number, customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<models.ResourceListResult>): void; list(callback: ServiceCallback<models.ResourceListResult>): void; /** * Checks whether resource exists. * * @param {string} resourceGroupName The name of the resource group. The name * is case insensitive. * * @param {string} resourceProviderNamespace Resource identity. * * @param {string} parentResourcePath Resource identity. * * @param {string} resourceType Resource identity. * * @param {string} resourceName Resource identity. * * @param {string} apiVersion * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @param {ServiceCallback} [callback] callback function; see ServiceCallback * doc in ms-rest index.d.ts for details */ checkExistence(resourceGroupName: string, resourceProviderNamespace: string, parentResourcePath: string, resourceType: string, resourceName: string, apiVersion: string, options: { customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<boolean>): void; checkExistence(resourceGroupName: string, resourceProviderNamespace: string, parentResourcePath: string, resourceType: string, resourceName: string, apiVersion: string, callback: ServiceCallback<boolean>): void; /** * Delete resource and all of its resources. * * @param {string} resourceGroupName The name of the resource group. The name * is case insensitive. * * @param {string} resourceProviderNamespace Resource identity. * * @param {string} parentResourcePath Resource identity. * * @param {string} resourceType Resource identity. * * @param {string} resourceName Resource identity. * * @param {string} apiVersion * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @param {ServiceCallback} [callback] callback function; see ServiceCallback * doc in ms-rest index.d.ts for details */ deleteMethod(resourceGroupName: string, resourceProviderNamespace: string, parentResourcePath: string, resourceType: string, resourceName: string, apiVersion: string, options: { customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<void>): void; deleteMethod(resourceGroupName: string, resourceProviderNamespace: string, parentResourcePath: string, resourceType: string, resourceName: string, apiVersion: string, callback: ServiceCallback<void>): void; /** * Create a resource. * * @param {string} resourceGroupName The name of the resource group. The name * is case insensitive. * * @param {string} resourceProviderNamespace Resource identity. * * @param {string} parentResourcePath Resource identity. * * @param {string} resourceType Resource identity. * * @param {string} resourceName Resource identity. * * @param {string} apiVersion * * @param {object} parameters Create or update resource parameters. * * @param {object} [parameters.plan] Gets or sets the plan of the resource. * * @param {string} [parameters.plan.name] Gets or sets the plan ID. * * @param {string} [parameters.plan.publisher] Gets or sets the publisher ID. * * @param {string} [parameters.plan.product] Gets or sets the offer ID. * * @param {string} [parameters.plan.promotionCode] Gets or sets the promotion * code. * * @param {object} [parameters.properties] Gets or sets the resource * properties. * * @param {string} [parameters.kind] Gets or sets the kind of the resource. * * @param {string} [parameters.managedBy] Gets or sets the managedBy property * of the resource. * * @param {object} [parameters.sku] Gets or sets the sku of the resource. * * @param {string} [parameters.sku.name] Gets or sets the sku name. * * @param {string} [parameters.sku.tier] Gets or sets the sku tier. * * @param {string} [parameters.sku.size] Gets or sets the sku size. * * @param {string} [parameters.sku.family] Gets or sets the sku family. * * @param {string} [parameters.sku.model] Gets or sets the sku model. * * @param {number} [parameters.sku.capacity] Gets or sets the sku capacity. * * @param {object} [parameters.identity] Gets or sets the identity of the * resource. * * @param {string} [parameters.identity.type] Gets or sets the identity type. * Possible values include: 'SystemAssigned' * * @param {string} [parameters.location] Resource location * * @param {object} [parameters.tags] Resource tags * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @param {ServiceCallback} [callback] callback function; see ServiceCallback * doc in ms-rest index.d.ts for details */ createOrUpdate(resourceGroupName: string, resourceProviderNamespace: string, parentResourcePath: string, resourceType: string, resourceName: string, apiVersion: string, parameters: models.GenericResource, options: { customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<models.GenericResource>): void; createOrUpdate(resourceGroupName: string, resourceProviderNamespace: string, parentResourcePath: string, resourceType: string, resourceName: string, apiVersion: string, parameters: models.GenericResource, callback: ServiceCallback<models.GenericResource>): void; /** * Returns a resource belonging to a resource group. * * @param {string} resourceGroupName The name of the resource group. The name * is case insensitive. * * @param {string} resourceProviderNamespace Resource identity. * * @param {string} parentResourcePath Resource identity. * * @param {string} resourceType Resource identity. * * @param {string} resourceName Resource identity. * * @param {string} apiVersion * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @param {ServiceCallback} [callback] callback function; see ServiceCallback * doc in ms-rest index.d.ts for details */ get(resourceGroupName: string, resourceProviderNamespace: string, parentResourcePath: string, resourceType: string, resourceName: string, apiVersion: string, options: { customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<models.GenericResource>): void; get(resourceGroupName: string, resourceProviderNamespace: string, parentResourcePath: string, resourceType: string, resourceName: string, apiVersion: string, callback: ServiceCallback<models.GenericResource>): void; /** * Get all of the resources under a subscription. * * @param {string} nextPageLink The NextLink from the previous successful call * to List operation. * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @param {ServiceCallback} [callback] callback function; see ServiceCallback * doc in ms-rest index.d.ts for details */ listNext(nextPageLink: string, options: { customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<models.ResourceListResult>): void; listNext(nextPageLink: string, callback: ServiceCallback<models.ResourceListResult>): void; } /** * @class * Tags * __NOTE__: An instance of this class is automatically created for an * instance of the ResourceManagementClient. */ export interface Tags { /** * Delete a subscription resource tag value. * * @param {string} tagName The name of the tag. * * @param {string} tagValue The value of the tag. * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @param {ServiceCallback} [callback] callback function; see ServiceCallback * doc in ms-rest index.d.ts for details */ deleteValue(tagName: string, tagValue: string, options: { customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<void>): void; deleteValue(tagName: string, tagValue: string, callback: ServiceCallback<void>): void; /** * Create a subscription resource tag value. * * @param {string} tagName The name of the tag. * * @param {string} tagValue The value of the tag. * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @param {ServiceCallback} [callback] callback function; see ServiceCallback * doc in ms-rest index.d.ts for details */ createOrUpdateValue(tagName: string, tagValue: string, options: { customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<models.TagValue>): void; createOrUpdateValue(tagName: string, tagValue: string, callback: ServiceCallback<models.TagValue>): void; /** * Create a subscription resource tag. * * @param {string} tagName The name of the tag. * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @param {ServiceCallback} [callback] callback function; see ServiceCallback * doc in ms-rest index.d.ts for details */ createOrUpdate(tagName: string, options: { customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<models.TagDetails>): void; createOrUpdate(tagName: string, callback: ServiceCallback<models.TagDetails>): void; /** * Delete a subscription resource tag. * * @param {string} tagName The name of the tag. * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @param {ServiceCallback} [callback] callback function; see ServiceCallback * doc in ms-rest index.d.ts for details */ deleteMethod(tagName: string, options: { customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<void>): void; deleteMethod(tagName: string, callback: ServiceCallback<void>): void; /** * Get a list of subscription resource tags. * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @param {ServiceCallback} [callback] callback function; see ServiceCallback * doc in ms-rest index.d.ts for details */ list(options: { customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<models.TagsListResult>): void; list(callback: ServiceCallback<models.TagsListResult>): void; /** * Get a list of subscription resource tags. * * @param {string} nextPageLink The NextLink from the previous successful call * to List operation. * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @param {ServiceCallback} [callback] callback function; see ServiceCallback * doc in ms-rest index.d.ts for details */ listNext(nextPageLink: string, options: { customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<models.TagsListResult>): void; listNext(nextPageLink: string, callback: ServiceCallback<models.TagsListResult>): void; } /** * @class * DeploymentOperations * __NOTE__: An instance of this class is automatically created for an * instance of the ResourceManagementClient. */ export interface DeploymentOperations { /** * Get a list of deployments operations. * * @param {string} resourceGroupName The name of the resource group. The name * is case insensitive. * * @param {string} deploymentName The name of the deployment. * * @param {string} operationId Operation Id. * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @param {ServiceCallback} [callback] callback function; see ServiceCallback * doc in ms-rest index.d.ts for details */ get(resourceGroupName: string, deploymentName: string, operationId: string, options: { customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<models.DeploymentOperation>): void; get(resourceGroupName: string, deploymentName: string, operationId: string, callback: ServiceCallback<models.DeploymentOperation>): void; /** * Gets a list of deployments operations. * * @param {string} resourceGroupName The name of the resource group. The name * is case insensitive. * * @param {string} deploymentName The name of the deployment. * * @param {object} [options] Optional Parameters. * * @param {number} [options.top] Query parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @param {ServiceCallback} [callback] callback function; see ServiceCallback * doc in ms-rest index.d.ts for details */ list(resourceGroupName: string, deploymentName: string, options: { top? : number, customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<models.DeploymentOperationsListResult>): void; list(resourceGroupName: string, deploymentName: string, callback: ServiceCallback<models.DeploymentOperationsListResult>): void; /** * Gets a list of deployments operations. * * @param {string} nextPageLink The NextLink from the previous successful call * to List operation. * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @param {ServiceCallback} [callback] callback function; see ServiceCallback * doc in ms-rest index.d.ts for details */ listNext(nextPageLink: string, options: { customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<models.DeploymentOperationsListResult>): void; listNext(nextPageLink: string, callback: ServiceCallback<models.DeploymentOperationsListResult>): void; }
DeepakRajendranMsft/azure-sdk-for-node
lib/services/resourceManagement/lib/resource/operations/index.d.ts
TypeScript
mit
48,012
// T4 code generation is enabled for model 'C:\WS\TFS2015\DeadManSwitch\Dev\WebAPIv2\Source\DeadManSwitch.Data.SqlRepository\DeadManSwitchDataModel.edmx'. // To enable legacy code generation, change the value of the 'Code Generation Strategy' designer // property to 'Legacy ObjectContext'. This property is available in the Properties Window when the model // is open in the designer. // If no context and entity classes have been generated, it may be because you created an empty model but // have not yet chosen which version of Entity Framework to use. To generate a context class and entity // classes for your model, open the model in the designer, right-click on the designer surface, and // select 'Update Model from Database...', 'Generate Database from Model...', or 'Add Code Generation // Item...'.
tategriffin/DeadManSwitch
Source/DeadManSwitch.Data.SqlRepository/DeadManSwitchDataModel.Designer.cs
C#
mit
815
using UnityEngine; using System.Collections; using UnityEngine.UI; namespace RPG { public class ForestBossFightIntro : MonoBehaviour { private GameObject Player; private Player_Manager PM; public GameObject Boss; private ForestBoss_Manager FBM; public ChangeBackgroundMusic BossMusicTrigger; private CameraFollow MainCamera; private GameObject BossText; private Text BossTextText; //new stuff public bool triggered = false; // Use this for initialization void Start() { Boss = GameObject.Find("ForestBoss"); FBM = Boss.GetComponent<ForestBoss_Manager>(); BossMusicTrigger = GameObject.Find("BossMusicTrigger").GetComponent<ChangeBackgroundMusic>(); MainCamera = GameObject.Find("Main Camera").GetComponent<CameraFollow>(); Player = GameObject.Find("Player"); PM = Player.GetComponent<Player_Manager>(); BossText = GameObject.Find("BossText"); BossTextText = BossText.GetComponent<Text>(); } // Update is called once per frame void Update() { if (FBM.defeated) { BossMusicTrigger.RevertBackToOldMusic(); } } IEnumerator StartFight() { yield return new WaitForSeconds(1); BossTextText.text = "The Forsaken One"; yield return new WaitForSeconds(3); //Destroy(BossText); BossTextText.text = null; MainCamera.Target = Player.transform; PM.canAttack = true; PM.canMove = true; yield return new WaitForSeconds(2); FBM.IntroComplete = true; } private void OnTriggerEnter2D(Collider2D PlayerCollider) { if (PlayerCollider.gameObject.CompareTag("Player") && !triggered) { // camera goes up to boss PM.canAttack = false; PM.canMove = false; MainCamera.Target = Boss.transform; StartCoroutine(StartFight()); triggered = true; } } } }
mhueter/legend-of-z
Assets/Scripts/Scene/ForestBossFightIntro.cs
C#
mit
1,969
require 'net/http' require 'net/https' require 'json' class ISPManager::Base def initialize params @params = params end protected def request method, params = {} result = ISPManager::Request.create method, params, @params result = JSON.parse(result) if result.is_a? Hash result.recursive_symbolize_keys! return result[:elem] ? result[:elem] : result end end class ::Hash def recursive_symbolize_keys! recursive_modify_keys! { |key| key.to_sym } end protected def modify_keys! keys.each do |key| self[(yield(key) rescue key) || key] = delete(key) end self end def recursive_modify_keys! &block modify_keys!(&block) values.each { |h| h.recursive_modify_keys!(&block) if h.is_a?(Hash) } values.select { |v| v.is_a?(Array) }.flatten.each { |h| h.recursive_modify_keys!(&block) if h.is_a?(Hash) } self end end end
alexkv/ispmanager
lib/ispmanager/base.rb
Ruby
mit
880
using Microsoft.AspNetCore.Mvc.Razor.Internal; using Abp.AspNetCore.Mvc.Views; using Abp.Runtime.Session; namespace AbpKendoDemo.Web.Views { public abstract class AbpKendoDemoRazorPage<TModel> : AbpRazorPage<TModel> { [RazorInject] public IAbpSession AbpSession { get; set; } protected AbpKendoDemoRazorPage() { LocalizationSourceName = AbpKendoDemoConsts.LocalizationSourceName; } } }
aspnetboilerplate/aspnetboilerplate-samples
KendoUiDemo/src/AbpKendoDemo.Web.Mvc/Views/AbpKendoDemoRazorPage.cs
C#
mit
455
using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; // General Information about an assembly is controlled through the following // set of attributes. Change these attribute values to modify the information // associated with an assembly. [assembly: AssemblyTitle("ServiceFabricModel")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("Microsoft Corporation")] [assembly: AssemblyProduct("ServiceFabricModel")] [assembly: AssemblyCopyright("Copyright © 2016")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. [assembly: ComVisible(false)] // The following GUID is for the ID of the typelib if this project is exposed to COM [assembly: Guid("70882438-7657-444c-84e6-e2faed2ad307")] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Build and Revision Numbers // by using the '*' as shown below: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("1.0.0.0")] [assembly: AssemblyFileVersion("1.0.0.0")]
p-org/PSharpModels
ServiceFabric/ServiceFabricModel/ServiceFabricModel/Properties/AssemblyInfo.cs
C#
mit
1,433
using UnityEngine; using System.Collections; using System; using static User; using static CRUD; using static GameStates; public class PopulateIndestructableDebris : Level { public override int levelNumber { get { return 0; } } public override string levelName { get { return "Test"; } } private void Start() { gameState = GameState.Playing; create(1, 1, (int)System.DateTime.Now.Ticks, false); } protected override void createLevel() { createObject("SpaceDustPF", gameBounds.center, 0); for (int i = 0; i < 1; i++) { IndestructableDebris current = (IndestructableDebris)createObject("IndestructableDebrisPF", new Vector2(30,35), getRandomAngle(), 0, random.Next(100)); } } protected override void updateLevel() { } protected override void endLevel() { } }
maerman/CSCI466Project
Assets/Unit Test/PopulateIndestructableDebris.cs
C#
mit
990
<?php /** * Created by JetBrains PhpStorm. * User: spiderman * Date: 31/12/2556 * Time: 12:15 น. * To change this template use File | Settings | File Templates. */ ?> <ul class="breadcrumb"> <li><a href="<?php echo site_url()?>">หน้าหลัก </a></li> <li ><a href="<?php echo site_url()."/audit/"?>">Audit </a></li> <li class="active"><a href="<?php echo site_url()."/audit/audit_hosp/"?>">Audit57 </a></li> </ul> รายชื่อสถานบริการที่ได้รับ การ Audit 2557 <div class="navbar navbar-default"> <form action="#" class="navbar-form"> <select id="sl_office" style="width: 180px;" class="form-control"> <option value=""> หน่วยบริการ </option> <?php foreach($audit as $r) { echo '<option value="' . $r->off_id . '">'.''.$r->off_id. ' : '. $r->off_name .'</option>'; } ?> </select> <label> ตั้งแต่วันที่</label> <input type="text" id="date_start" data-type="date" class="form-control" placeholder="วว/ดด/ปปปป" title="เช่น 01/01/2556" data-rel="tooltip" style="width: 110px;"> <label>ถึงวันที่</label> <input type="text" id="date_end" data-type="date" class="form-control" placeholder="วว/ดด/ปปปป" style="width: 110px;" title="เช่น 31/01/2556" data-rel="tooltip"> <span> เลขบัตรประชาชน <input class='form-control' type='text' id='cid' value="<?php echo @$cid?>" style="width:200px"> </span> <div class="checkbox"> <label> <input type="checkbox" id="op" checked="checked" value="1"> เฉพาะผู้ป่วยOP </label> </div> <button class='btn btn-info ' id='btn_search'><span class="glyphicon glyphicon-search"></span> ค้นหา </button> </form> </div> <div class='well'> <table class='table' id='tbl_person_list'> <thead> <tr> <td>#</td> <td> หน่วยบริการ</td> <td> ชื่อ นามสกุล</td> <td> เลขบัตรประชาชน</td> <td> ที่อยู่ </td> <td> วันเดือนปีเกิด</td> <td> อายุ </td> <td> Type Area</td> </tr> </thead> <tbody> <tr> <td colspan="10">....</td> </tr> </tbody> </table> </div> <div class='row'> <div class='col col-lg-3'> <div class='panel panel-default'> <div class='panel-heading'> วันที่รับบริการ </div> <ul class="list-group list-group-flush" id='service_list' style="height: 350px; overflow-y: scroll; scrollbar-arrow-color:blue;"> </ul> </div> </div> <div class='col col-lg-9 col-offset-1'> <div class='panel panel-default'> <div class='panel-heading'> ราบละเอียดการรับบริการ </div> <div class='panel-body'> <ul class="list-group list-group-flush" id='visit_list'> </ul> </div> </div> </div> </div> <script src="<?php echo base_url()?>assets/apps/js/audit.audit4.js" charset="utf-8"></script> <script src="<?php echo base_url()?>assets/apps/js/basic.js" charset="utf-8"></script>
kataynoi/data_audit
application/views/audit/audit4_view.php
PHP
mit
3,650
require 'delayed_job' Delayed::Worker.backend = :active_record BackgroundTaskJob.reset_all_queues rescue nil
javiyu/redis_monitor
lib/engine/config/initializers/delayed_job.rb
Ruby
mit
109
import GameEvent from './GameEvent'; import Creature from '../entities/creatures/Creature'; import Ability from '../abilities/Ability'; import Tile from '../tiles/Tile'; export default class AbilityEvent extends GameEvent { /** * @class AbilityEvent * @description Fired whenever a creature attacks */ constructor(dungeon, creature, ability, tile) { super(dungeon); if(!(creature instanceof Creature)) { throw new Error('Second parameter must be a Creature'); } else if(!(ability instanceof Ability)) { throw new Error('Third parameter must be an Ability'); } else if((tile instanceof Tile) !== ability.isTargetted()) { throw new Error('Fourth parameter must be a Tile iff ability is targetted'); } this._creature = creature; this._ability = ability; this._tile = tile; } getCreature() { return this._creature; } getAbility() { return this._ability; } getTile() { return this._tile; } getText(dungeon) { var creature = this.getCreature(); var ability = this.getAbility(); var tile = dungeon.getTile(creature); return `${creature} used ${ability}` + (tile ? ` on ${tile}` : ''); } }
acbabis/roguelike
src/client/js/app/events/AbilityEvent.js
JavaScript
mit
1,309
//------------------------------- // ADMINISTER CODES FUNCTIONALITY //------------------------------- MFILE.administerCodes = function () { MFILE.administerCodes.handleDisplay(); MFILE.administerCodes.handleKeyboard(); } MFILE.administerCodes.handleDisplay = function () { $('#result').empty(); $('#codebox').html(MFILE.html.code_box); if (MFILE.activeCode.cstr.length === 0) { //$('#code').val('<EMPTY>'); $('#code').val(''); } else { $('#code').val(MFILE.activeCode.cstr); } $("#code").focus(function(event) { $("#topmesg").html("ESC=Back, Ins=Insert, F3=Lookup, F5=Delete, ENTER=Accept"); $("#mainarea").html(MFILE.html.change_code); }); $("#code").blur(function(event) { $('#topmesg').empty(); }); } MFILE.administerCodes.handleKeyboard = function () { // Handle function keys in Code field $("#code").keydown(function (event) { MFILE.administerCodes.processKey(event); }); $('#code').focus(); } MFILE.administerCodes.processKey = function (event) { console.log("KEYDOWN. WHICH "+event.which+", KEYCODE "+event.keyCode); // Function key handler if (event.which === 9) { // tab, shift-tab event.preventDefault(); console.log("IGNORING TAB"); return true; } else if (event.which === 27) { // ESC event.preventDefault(); MFILE.activeCode.cstr = ""; $('#code').val(''); $('#code').blur(); $('#codebox').empty(); $('#result').empty(); MFILE.state = 'MAIN_MENU'; MFILE.actOnState(); } else if (event.which === 13) { // ENTER event.preventDefault(); $('#result').empty(); MFILE.fetchCode("ACCEPT"); } else if (event.which === 45) { // Ins event.preventDefault(); MFILE.activeCode.cstr = $('#code').val(); console.log("Asking server to insert code '"+MFILE.activeCode.cstr+"'"); MFILE.insertCode(); $('#result').html(MFILE.activeCode.result); } else if (event.which === 114) { // F3 event.preventDefault(); MFILE.activeCode.cstr = $('#code').val(); console.log("Consulting server concerning the code '"+MFILE.activeCode.cstr+"'"); MFILE.searchCode(); } else if (event.which == 116) { // F5 event.preventDefault(); MFILE.activeCode.cstr = $('#code').val(); console.log("Asking server to delete code '"+MFILE.activeCode.cstr+"'"); MFILE.fetchCode('DELETE'); $('#result').html(MFILE.activeCode.result); } } //--------------- // AJAX FUNCTIONS //--------------- MFILE.insertCode = function() { console.log("About to insert code string "+MFILE.activeCode["cstr"]); $.ajax({ url: "insertcode", type: "POST", dataType: "json", data: MFILE.activeCode, success: function(result) { console.log("Query result is: '"+result.queryResult+"'"); $("#id").empty(); if (result.queryResult === "success") { console.log("SUCCESS") console.log(result); $("#code").val(result.mfilecodeCode); $("#result").empty(); $("#result").append("New code "+result.mfilecodeCode+" (ID "+result.mfilecodeId+") added to database.") } else { console.log("FAILURE") console.log(result); $("#code").empty(); $("#result").empty(); $("#result").append("FAILED: '"+result.queryResult+"'") } }, error: function(xhr, status, error) { $("#result").html("AJAX ERROR: "+xhr.status); } }); } MFILE.fetchCode = function (action) { // we fetch it in order to delete it console.log("Attempting to fetch code "+MFILE.activeCode["cstr"]); $.ajax({ url: "fetchcode", type: "POST", dataType: "json", data: MFILE.activeCode, success: function(result) { console.log("AJAX POST success, result is: '"+result.queryResult+"'"); if (result.queryResult === "success") { MFILE.activeCode.cstr = result.mfilecodeCode; $("#code").val(MFILE.activeCode.cstr); if (action === "DELETE") { MFILE.deleteCodeConf(); } else { MFILE.state = 'MAIN_MENU'; MFILE.actOnState(); } } else { $('#result').html("FAILED: '"+result.queryResult+"'"); return false; } }, error: function(xhr, status, error) { $("#result").html("AJAX ERROR: "+xhr.status); } }); } MFILE.deleteCodeConf = function () { // for now, called only from fetchCode console.log("Asking for confirmation to delete "+MFILE.activeCode["cstr"]); $("#mainarea").html(MFILE.html.code_delete_conf1); $("#mainarea").append(MFILE.activeCode.cstr+"<BR>"); $("#mainarea").append(MFILE.html.code_delete_conf2); $("#yesno").focus(); console.log("Attempting to fetch code "+MFILE.activeCode["cstr"]); $("#yesno").keydown(function(event) { event.preventDefault(); logKeyPress(event); if (event.which === 89) { MFILE.deleteCode(); } MFILE.actOnState(); }); } MFILE.searchCode = function () { console.log("Attempting to search code "+MFILE.activeCode["cstr"]); $.ajax({ url: "searchcode", type: "POST", dataType: "json", data: MFILE.activeCode, success: function(result) { console.log("AJAX POST success, result is: '"+result.result+"'"); if (result.result === "success") { if (result.values.length === 0) { $("#result").html("FAILED: 'Nothing matches'"); } else if (result.values.length === 1) { $("#result").html("SUCCESS: Code found"); MFILE.activeCode.cstr = result.values[0]; $("#code").val(MFILE.activeCode.cstr); } else { $("#mainarea").html(MFILE.html.code_search_results1); $.each(result.values, function (key, value) { $("#mainarea").append(value+" "); }); $("#mainarea").append(MFILE.html.press_any_key); $("#continue").focus(); $("#continue").keydown(function(event) { event.preventDefault(); MFILE.actOnState(); }); $("#result").html("Search found multiple matching codes. Please narrow it down."); } } else { console.log("FAILURE: "+result); $("#code").empty(); $("#result").html("FAILED: '"+result.result+"'"); } }, error: function(xhr, status, error) { $("#result").html("AJAX ERROR: "+xhr.status); } }); } MFILE.deleteCode = function() { console.log("Attempting to delete code "+MFILE.activeCode["cstr"]); $.ajax({ url: "deletecode", type: "POST", dataType: "json", data: MFILE.activeCode, success: function(result) { console.log("Query result is: '"+result.queryResult+"'"); $("#id").empty(); if (result.queryResult === "success") { console.log("SUCCESS"); console.log(result); $("#code").empty(); $("#result").empty(); $("#result").append("Code deleted"); } else { console.log("FAILURE") console.log(result); $("#result").empty(); $("#result").append("FAILED: '"+result.queryResult+"'") } }, error: function(xhr, status, error) { $("#result").html("AJAX ERROR: "+xhr.status); } }); }
smithfarm/mfile-erlang
priv/static/06code.js
JavaScript
mit
7,539
using System; using System.Windows.Input; namespace Asteroids.ViewModel { /// <summary> /// Általános parancs típusa. /// </summary> public class DelegateCommand : ICommand { private readonly Action<Object> _execute; // a tevékenységet végrehajtó lambda-kifejezés private readonly Func<Object, Boolean> _canExecute; // a tevékenység feltételét ellenőző lambda-kifejezés /// <summary> /// Végrehajthatóság változásának eseménye. /// </summary> public event EventHandler CanExecuteChanged { add { CommandManager.RequerySuggested += value; } remove { CommandManager.RequerySuggested -= value; } } /// <summary> /// Parancs létrehozása. /// </summary> /// <param name="execute">Végrehajtandó tevékenység.</param> public DelegateCommand(Action<Object> execute) : this(null, execute) { } /// <summary> /// Parancs létrehozása. /// </summary> /// <param name="canExecute">Végrehajthatóság feltétele.</param> /// <param name="execute">Végrehajtandó tevékenység.</param> public DelegateCommand(Func<Object, Boolean> canExecute, Action<Object> execute) { if (execute == null) { throw new ArgumentNullException("execute"); } _execute = execute; _canExecute = canExecute; } /// <summary> /// Végrehajthatóság ellenőrzése /// </summary> /// <param name="parameter">A tevékenység paramétere.</param> /// <returns>Igaz, ha a tevékenység végrehajtható.</returns> public Boolean CanExecute(Object parameter) { return _canExecute == null ? true : _canExecute(parameter); } /// <summary> /// Tevékenység végrehajtása. /// </summary> /// <param name="parameter">A tevékenység paramétere.</param> public void Execute(Object parameter) { _execute(parameter); } } }
balintsoos/EVA2-bead2
Asteroids/Asteroids.ViewModel/DelegateCommand.cs
C#
mit
2,146
# encoding: utf-8 require "bprum_shop_api/version" require 'bcrypt' require 'json' module BprumShopApi class Api def initialize(my_key,remote_key,remote_path,remote_host,remote_port=80,charset='utf-8') @my_key = my_key @remote_port = remote_port @remote_key = remote_key @remote_path = remote_path @remote_host = remote_host @charset = charset @number_of_message = 0 @out_file = File.open('log/api.log','a') log_write("API class initializied") end def log_write(message) @number_of_message += 1 puts @number_of_message.to_s + ": \t" + message + " - in: "+Time.now.to_s+" \n" @out_file.write( @number_of_message.to_s + ": \t" + message + "\n") end def checkRequest(request) begin log_write("cheking request: \n\t|type::"+request.class.to_s+" \n\t|content::"+request.to_s) parsed=JSON.parse(request.force_encoding('UTF-8')) log_write("respond JSON is:\n"+parsed.inspect) arr=parsed["request_body"].sort log_write("sorted content:\n"+arr.inspect) #order_hash=arr.to_h order_hash=arr.inject({}) do |r, s| r.merge!({s[0] => s[1]}) end mysign=Digest::SHA2.hexdigest(order_hash.to_json+@my_key).to_s log_write("signature of this request must be:\n"+mysign) log_write("signature of this request:\n"+parsed["sign"]) if mysign==parsed["sign"] log_write("this request is valid") return parsed["request_body"] else log_write("this request is invalid") false end rescue Exception => e log_write("fatal "+e.message+"::\n"+e.backtrace.join("\n")) end end def signRequest(params) log_write("now generating signature for new request") arr=params[:request_body].sort params[:request_body]=arr.to_h Digest::SHA2.hexdigest(params[:request_body].to_json+@remote_key).to_s end def requestProcessor(params) hash=params hash[:sign]=signRequest(params) hash=hash.to_json result={} Net::HTTP.start(@remote_host) do |http| req = Net::HTTP::Post.new(@remote_path,initheader = {'Content-Type' =>'application/json','Encoding'=>'utf-8'}) req.body = hash begin response = http.request(req) if response.class.to_s == 'Net::HTTPOK' puts response.inspect puts response.value puts "returned BODY is:",response.body result = JSON.parse(response.body) else puts response.inspect end rescue result["access"]="unknow" result["reason"]="connection lost" end end if result["access"]=="granted" or result["access"]=="unknow" result elsif result["access"]=="denied" result else false end end end end
nottewae/bprum_shop_api
lib/bprum_shop_api.rb
Ruby
mit
2,939
/** * @fileOverview * @name aqicn.js * @author ctgnauh <huangtc@outlook.com> * @license MIT */ var request = require('request'); var cheerio = require('cheerio'); var info = require('./info.json'); /** * 从 aqicn.org 上获取空气信息 * @module aqicn */ module.exports = { // 一些多余的信息 info: info, /** * fetchWebPage 的 callback * @callback module:aqicn~fetchWebPageCallback * @param {object} error - 请求错误 * @param {object} result - 页面文本 */ /** * 抓取移动版 aqicn.org 页面。 * aqicn.org 桌面版在300kb以上,而移动版则不足70kb。所以使用移动版,链接后面加 /m/ 。 * @param {string} city - 城市或地区代码,详见[全部地区](http://aqicn.org/city/all/) * @param {module:aqicn~fetchWebPageCallback} callback */ fetchWebPage: function (city, callback) { 'use strict'; var options = { url: 'http://aqicn.org/city/' + city + '/m/', headers: { 'User-Agent': 'wget' } }; request.get(options, function (err, res, body) { if (err) { callback(err, ''); } else { callback(null, body); } }); }, /** * 分析 html 文件并返回指定的 AQI 值 * @param {string} body - 页面文本 * @param {string} name - 污染物代码:pm25、pm10、o3、no2、so2、co * @returns {number} AQI 值 */ selectAQIText: function (body, name) { 'use strict'; var self = this; var $ = cheerio.load(body); var json; var value; try { json = JSON.parse($('#table script').text().slice(12, -2)); // "genAqiTable({...})" value = self.info.species.indexOf(name); } catch (err) { return NaN; } return json.d[value].iaqi; }, /** * 分析 html 文件并返回更新时间 * @param {string} body - 页面文本 * @returns {string} ISO格式的时间 */ selectUpdateTime: function (body) { 'use strict'; var $ = cheerio.load(body); var json; try { json = JSON.parse($('#table script').text().slice(12, -2)); // "genAqiTable({...})" } catch (err) { return new Date(0).toISOString(); } return json.t; }, /** * 污染等级及相关信息 * @param {number} level - AQI 级别 * @param {string} lang - 语言:cn、en、jp、es、kr、ru、hk、fr、pl(但当前只有 cn 和 en) * @returns {object} 由AQI级别、污染等级、对健康影响情况、建议采取的措施组成的对象 */ selectInfoText: function (level, lang) { 'use strict'; var self = this; if (level > 6 || level < 0) { level = 0; } return { value: level, name: self.info.level[level].name[lang], implication: self.info.level[level].implication[lang], statement: self.info.level[level].statement[lang] }; }, /** * 计算 AQI,这里选取 aqicn.org 采用的算法,选取 AQI 中数值最大的一个 * @param {array} aqis - 包含全部 AQI 数值的数组 * @returns {number} 最大 AQI */ calculateAQI: function (aqis) { 'use strict'; return Math.max.apply(null, aqis); }, /** * 计算空气污染等级,分级标准详见[关于空气质量与空气污染指数](http://aqicn.org/?city=&size=xlarge&aboutaqi) * @param {number} aqi - 最大 AQI * @returns {number} AQI 级别 */ calculateLevel: function (aqi) { 'use strict'; var level = 0; if (aqi >= 0 && aqi <= 50) { level = 1; } else if (aqi >= 51 && aqi <= 100) { level = 2; } else if (aqi >= 101 && aqi <= 150) { level = 3; } else if (aqi >= 151 && aqi <= 200) { level = 4; } else if (aqi >= 201 && aqi <= 300) { level = 5; } else if (aqi > 300) { level = 6; } return level; }, /** * getAQIs 的 callback * @callback module:aqicn~getAQIsCallback * @param {object} error - 请求错误 * @param {object} result - 包含全部污染物信息的对象 */ /** * 获取指定城市的全部 AQI 数值 * @param {string} city - 城市或地区代码,详见[全部地区](http://aqicn.org/city/all/) * @param {string} lang - 语言:cn、en、jp、es、kr、ru、hk、fr、pl(但当前只有 cn 和 en) * @param {module:aqicn~getAQIsCallback} callback */ getAQIs: function (city, lang, callback) { 'use strict'; var self = this; self.fetchWebPage(city, function (err, body) { if (err) { callback(err); } var result = {}; var aqis = []; // 城市代码 result.city = city; // 数据提供时间 result.time = self.selectUpdateTime(body); // 全部 AQI 值 self.info.species.forEach(function (name) { var aqi = self.selectAQIText(body, name); aqis.push(aqi); result[name] = aqi; }); // 主要 AQI 值 result.aqi = self.calculateAQI(aqis); // AQI 等级及其它 var level = self.calculateLevel(result.aqi); var levelInfo = self.selectInfoText(level, lang); result.level = levelInfo; callback(null, result); }); }, /** * getAQIByName 的 callback * @callback module:aqicn~getAQIByNameCallback * @param {object} error - 请求错误 * @param {object} result - 城市或地区代码与指定的 AQI */ /** * 获取指定城市的指定污染物数值 * @param {string} city - 城市或地区代码 * @param {string} name - 污染物代码:pm25、pm10、o3、no2、so2、co * @param {module:aqicn~getAQIByNameCallback} callback */ getAQIByName: function (city, name, callback) { 'use strict'; var self = this; self.getAQIs(city, 'cn', function (err, res) { if (err) { callback(err); } callback(null, { city: city, value: res[name], time: res.time }); }); } };
ctgnauh/aqicn
src/aqicn.js
JavaScript
mit
5,915
package com.ev34j.mindstorms.sensor; import com.ev34j.core.sensor.SensorPort; import com.ev34j.core.sensor.SensorSetting; import com.ev34j.core.sensor.UltrasonicSensor; public class NxtUltrasonicSensor extends AbstractUltrasonicSensor { public NxtUltrasonicSensor(final int portNum) { this("" + portNum); } public NxtUltrasonicSensor(final String portName) { super((new UltrasonicSensor(NxtUltrasonicSensor.class, SensorPort.findByPort(portName), SensorSetting.NXT_US))); } }
ev34j/ev34j
ev34j-mindstorms/src/main/java/com/ev34j/mindstorms/sensor/NxtUltrasonicSensor.java
Java
mit
500
<?php namespace Cacic\CommonBundle\Controller; use Doctrine\Common\Util\Debug; use Symfony\Component\HttpFoundation\Request; use Symfony\Component\HttpFoundation\Response; use Symfony\Bundle\FrameworkBundle\Controller\Controller; use Cacic\CommonBundle\Entity\SoftwareEstacao; use Cacic\CommonBundle\Form\Type\SoftwareEstacaoType; class SoftwareEstacaoController extends Controller { /** * * Tela de listagem dos softwares por estação * @param int $page */ public function indexAction( $page ) { return $this->render( 'CacicCommonBundle:SoftwareEstacao:index.html.twig', array( 'SoftwareEstacao' => $this->getDoctrine()->getRepository( 'CacicCommonBundle:SoftwareEstacao' )->paginar( $this->get( 'knp_paginator' ), $page ) )); } /** * * Tela de cadastro de software por estação * @param Request $request */ public function cadastrarAction(Request $request) { $SoftwareEstacao = new SoftwareEstacao(); $form = $this->createForm( new SoftwareEstacaoType(), $SoftwareEstacao ); if ( $request->isMethod('POST') ) { $form->bind( $request ); if ( $form->isValid() ) { $this->getDoctrine()->getManager()->persist( $SoftwareEstacao ); $this->getDoctrine()->getManager()->flush();// Efetuar a edição do Software Estacao $this->get('session')->getFlashBag()->add('success', 'Dados salvos com sucesso!'); return $this->redirect( $this->generateUrl( 'cacic_software_estacao_index', array( 'idComputador' => $SoftwareEstacao->getIdComputador()->getIdComputador() ) ) ); } } return $this->render( 'CacicCommonBundle:SoftwareEstacao:cadastrar.html.twig', array( 'form' => $form->createView() ) ); } /** * Página de editar dados do Software Estacao * @param int $idComputador * @param int $idSoftware */ public function editarAction( $idComputador, Request $request ) { $SoftwareEstacao = $this->getDoctrine()->getRepository('CacicCommonBundle:SoftwareEstacao') ->find( array( 'idComputador'=>$idComputador ) ); if ( ! $SoftwareEstacao ) throw $this->createNotFoundException( 'Software de Estacao não encontrado' ); $form = $this->createForm( new SoftwareEstacaoType(), $SoftwareEstacao ); if ( $request->isMethod('POST') ) { $form->bind( $request ); if ( $form->isValid() ) { $this->getDoctrine()->getManager()->persist( $SoftwareEstacao ); $this->getDoctrine()->getManager()->flush();// Efetuar a edição do Software Estacao $this->get('session')->getFlashBag()->add('success', 'Dados salvos com sucesso!'); return $this->redirect( $this->generateUrl( 'cacic_software_estacao_editar', array( 'idComputador' => $SoftwareEstacao->getIdComputador()->getIdComputador() ) ) ); } } return $this->render( 'CacicCommonBundle:SoftwareEstacao:cadastrar.html.twig', array( 'form' => $form->createView() ) ); } /** * * [AJAX] Exclusão de Software Estacao já cadastrado * @param integer $idSoftwareEstacao */ public function excluirAction( Request $request ) { if ( ! $request->isXmlHttpRequest() ) // Verifica se se trata de uma requisição AJAX throw $this->createNotFoundException( 'Página não encontrada' ); $SoftwareEstacao = $this->getDoctrine()->getRepository('CacicCommonBundle:SoftwareEstacao')->find( $request->get('compositeKeys') ); if ( ! $SoftwareEstacao ) throw $this->createNotFoundException( 'Software Estação não encontrado' ); $em = $this->getDoctrine()->getManager(); $em->remove( $SoftwareEstacao ); $em->flush(); $response = new Response( json_encode( array('status' => 'ok') ) ); $response->headers->set('Content-Type', 'application/json'); return $response; } /** * * Relatorio de Autorizacoes Cadastradas */ public function autorizacoesAction() { return $this->render( 'CacicCommonBundle:SoftwareEstacao:autorizacoes.html.twig', array( 'registros' => $this->getDoctrine()->getRepository('CacicCommonBundle:SoftwareEstacao')->gerarRelatorioAutorizacoes() ) ); } }
lightbase/cacic
src/Cacic/CommonBundle/Controller/SoftwareEstacaoController.php
PHP
mit
4,723
module Tremor module Seismi class Response prepend Tremor::Response::Base def initialize(data) @data = JSON.load(data) end def count @data['count'.freeze] end def earthquakes @data['earthquakes'.freeze].map do |earthquake| Tremor::Seismi::Earthquake.new(earthquake) end end end end end
stuhalliburton/tremor
lib/tremor/adapters/seismi/response.rb
Ruby
mit
387
# -*- coding: utf-8 -*- # Generated by Django 1.10.4 on 2017-01-18 18:01 from __future__ import unicode_literals from django.db import migrations, models import django.forms.widgets class Migration(migrations.Migration): dependencies = [ ('sshcomm', '0002_auto_20170118_1702'), ] operations = [ migrations.AlterField( model_name='userdata', name='user_name', field=models.CharField(max_length=128), ), migrations.AlterField( model_name='userdata', name='user_password', field=models.CharField(max_length=128, verbose_name=django.forms.widgets.PasswordInput), ), ]
t-mertz/slurmCompanion
django-web/sshcomm/migrations/0003_auto_20170118_1901.py
Python
mit
697
'use strict'; import { IPCMessageReader, IPCMessageWriter, createConnection, IConnection, TextDocumentSyncKind, TextDocuments, Diagnostic, DiagnosticSeverity, TextDocumentPositionParams, InitializeParams, InitializeResult, CompletionItem, CompletionItemKind, Files, Definition, CodeActionParams, Command, DidChangeTextDocumentParams } from 'vscode-languageserver'; import { CompletionItemFactory } from "./Factory/CompletionItemFactory"; import { TypescriptImporter } from "./Settings/TypeScriptImporterSettings"; import ImportCache = require('./Cache/ImportCache'); import ICacheFile = require('./Cache/ICacheFile'); import CommunicationMethods = require('./Methods/CommunicationMethods'); import IFramework = require('./Cache/IFramework'); import { CompletionGlobals } from "./Factory/Helper/CompletionGlobals"; import { PrototypeAdditions } from "./d"; import OS = require('os'); import fs = require('fs'); /// Can't seem to get this to self instantiate in a node context and actually apply PrototypeAdditions(); // Create a connection for the server. The connection uses // stdin / stdout for message passing let connection: IConnection = createConnection(new IPCMessageReader(process), new IPCMessageWriter(process)); // After the server has started the client sends an initilize request. The server receives // in the passed params the rootPath of the workspace plus the client capabilites. connection.onInitialize((params): InitializeResult => { CompletionGlobals.Root = params.rootPath.replace(/\\/g, '/'); return { capabilities: { // Tell the client that the server support code complete completionProvider: { resolveProvider: true }, /// Need full sync textDocumentSync: TextDocumentSyncKind.Full } } }); // /// ================================= // /// Configuration // /// ================================= /// Maximum amount of imports let maxNumberOfImports: number; /// Show namespace on imports let showNamespaceOnImports: boolean; // The settings have changed. Is send on server activation // as well. connection.onDidChangeConfiguration((change) => { const settings = change.settings.TypeScriptImporter as TypescriptImporter; showNamespaceOnImports = settings.showNamespaceOnImports || true; CompletionItemFactory.ShowNamespace = showNamespaceOnImports; }); /// ================================= /// Importer code /// ================================= let _importCache = new ImportCache(); let _targetString: string; let _targetLine: number; let _fileArray: string[] = []; let documents = new TextDocuments(); documents.listen(connection); /// Listen for when we get a notification for a namespace update connection.onNotification(CommunicationMethods.NAMESPACE_UPDATE, (params: ICacheFile) => { if(params){ _importCache.register(params); } }); 3 /// Listen for when we get a notification for a tsconfig update connection.onNotification(CommunicationMethods.TSCONFIG_UPDATE, (params: IFramework) => { if(params){ _importCache.registerFramework(params); } }) /// Listen for when we get a notification for a tsconfig update connection.onNotification(CommunicationMethods.RESYNC, () => { _importCache.reset(); }) /** * When a completion is requested, see if it's an import */ connection.onCompletion((textDocumentPosition: TextDocumentPositionParams): CompletionItem[] => { try { // There's no quick way of getting this information without keeping the files permanently in memory... // TODO: Can we add some validation here so that we bomb out quicker? let text; /// documents doesn't automatically update if(_fileArray[textDocumentPosition.textDocument.uri]){ text = _fileArray[textDocumentPosition.textDocument.uri]; } else { /// Get this if we don't have anything in cache text = documents.get(textDocumentPosition.textDocument.uri).getText(); } const input = text.split(OS.EOL); _targetLine = textDocumentPosition.position.line; _targetString = input[_targetLine]; CompletionGlobals.Uri = decodeURIComponent(textDocumentPosition.textDocument.uri).replace("file:///", ""); /// If we are not on an import, we don't care if(_targetString.indexOf("import") !== -1){ return _importCache.getOnImport(CompletionItemFactory.getItemCommonJS, CompletionItemFactory.getItem); /// Make sure it's not a comment (i think?) } else if(!_targetString.match(/(\/\/|\*|\w\.$)/)) { return _importCache.getOnImport(CompletionItemFactory.getInlineItemCommonJS, CompletionItemFactory.getInlineItem); } } catch(e) { console.warn("Typescript Import: Unable to creation completion items"); return []; } }); /** * This is now mandatory */ connection.onCompletionResolve((item: CompletionItem): CompletionItem => { if(item.data && item.data === 365) { item.detail = item.label; } return item; }); /** * */ connection.onDidChangeTextDocument((params: DidChangeTextDocumentParams) => { /// We have to manually remember this on the server /// NOTE: don't query doucments if this isn't available _fileArray[params.textDocument.uri] = params.contentChanges[0].text; /// If we have no target, make sure the user hasn't tried to undo and left behind our hidden characters, otherwise the plugin appears to stop working if(!_targetString) { if(_fileArray[params.textDocument.uri].indexOf("\u200B\u200B") > -1) { /// Inform the client to do the change (faster than node FS) connection.sendNotification( CommunicationMethods.UNDO_SAVE_REQUEST, /// CompletionGlobals.Uri? [decodeURIComponent(params.textDocument.uri.replace("file:///", ""))] ); } } else { const content = params.contentChanges[0].text; const contentString = content.split(OS.EOL)[_targetLine]; /// If there has been a change, aka the user has selected the option if(contentString && contentString !== _targetString && !contentString.match(/(\/\/|\*|\w\.$)/)) { /// Get the type if we're typing inline let result: RegExpExecArray; let subString = contentString; /// May be multiple results, loop over to see if any match while(result = /([:|=]\s*?)?(\w+)[\u200B\u200B]/.exec(subString)) { if(result.length >= 3) { let target = _importCache.getFromMethodName(result[2]); if(target){ /// Inform the client to do the change (faster than node FS) connection.sendNotification( CommunicationMethods.SAVE_REQUEST, /// CompletionGlobals.Uri? [decodeURIComponent(params.textDocument.uri.replace("file:///", "")), target, _targetLine] ); _targetString = null; _targetLine = 0; break; } } /// shorten subString = subString.slice(result.index + result.length) } if(!contentString.match(/(\w+)[\)|\s]?/)) { _targetString = null; _targetLine = 0; } } } }); // Listen on the connection connection.listen();
starkevin/VSCode-TypeScript-Importer
server/src/server.ts
TypeScript
mit
7,738
package hextostring.debug; import java.util.List; import hexcapture.HexSelectionsContentSnapshot; import hextostring.format.DecorableList; /** * Wraps the content of hex selections into an object containing the necessary * information for debugging * * @author Maxime PIA */ public class DebuggableHexSelectionsContent implements DebuggableStrings, DecorableList { private HexSelectionsContentSnapshot snapshot; private List<DebuggableStrings> orderedResults; private String decorationBefore = ""; private String decorationBetween = ""; private String decorationAfter = ""; public DebuggableHexSelectionsContent( HexSelectionsContentSnapshot snapshot, List<DebuggableStrings> orderedResults) { this.snapshot = snapshot; this.orderedResults = orderedResults; if (snapshot.getSize() != orderedResults.size()) { throw new IllegalArgumentException("Incompatible sizes"); } } @Override public void setDecorationBefore(String decorationBefore) { this.decorationBefore = decorationBefore; } @Override public void setDecorationBetween(String decorationBetween) { this.decorationBetween = decorationBetween; } @Override public void setDecorationAfter(String decorationAfter) { this.decorationAfter = decorationAfter; } @Override public void setLinesDecorations(String before, String after) {} @Override public DecorableList getDecorableList() { return this; } @Override public String toString(long debuggingFlags, int converterStrictness) { StringBuilder sb = new StringBuilder(); int index = 0; boolean selectionsBoundsFlagOn = (debuggingFlags & DebuggingFlags.HEX_SELECTIONS_BOUNDS) > 0; boolean selectionsContentFlagOn = (debuggingFlags & DebuggingFlags.HEX_SELECTIONS_CONTENT) > 0; boolean selectionDebuggingOn = selectionsBoundsFlagOn || selectionsContentFlagOn; sb.append(decorationBefore); for (DebuggableStrings ds : orderedResults) { if (selectionDebuggingOn) { sb.append("["); } if (selectionsBoundsFlagOn) { sb.append( "#" + snapshot.getSelectionIdAt(index) + (snapshot.getActiveSelectionIndex() == index ? " (active)" : "") + ", from " + formatToHexString(snapshot.getSelectionStartAt(index)) + " to " + formatToHexString(snapshot.getSelectionEndAt(index)) ); } if (selectionsContentFlagOn) { sb.append( " (selected as: \"" + snapshot.getValueAt(index) + "\")" ); } if (selectionDebuggingOn) { sb.append(":\n"); } if (ds != null) { sb.append(ds.toString(debuggingFlags, converterStrictness)); } else if (selectionDebuggingOn) { sb.append("<null>"); } if (selectionDebuggingOn) { sb.append("]"); } if (index != orderedResults.size() - 1) { sb.append(decorationBetween); } ++index; } sb.append(decorationAfter); if (selectionDebuggingOn) { sb.append("\n"); } return sb.toString(); } private String formatToHexString(Number n) { return "0x" + String.format("%02X", n); } }
MX-Futhark/hook-any-text
src/main/java/hextostring/debug/DebuggableHexSelectionsContent.java
Java
mit
3,023
require 'virtus' module Billing class BillItem include Virtus::ValueObject attribute :title, String attribute :amount, Float attribute :price, Float def sub_total self.amount.to_f * self.price.to_f end end end
jgroeneveld/uber_pong
lib/billing/entities/bill_item.rb
Ruby
mit
245
from bson.objectid import ObjectId import json class Room(): def __init__(self, players_num, objectid, table, current_color='purple'): if players_num: self.players_num = players_num else: self.players_num = 0 for el in ['p', 'b', 'g', 'r']: if el in table: self.players_num += 1 self.objectid = objectid self.current_color = current_color self.players_dict = {} self.alredy_ex = [] self.colors = [] self.winner = None for col in ['p', 'b', 'g', 'r']: if col in table: self.colors.append( {'p': 'purple', 'b': 'blue', 'g': 'green', 'r': 'red'}[col]) if current_color in self.colors: self.current_color = current_color else: self.current_color = self.colors[0] self.users_nicks = {} self.color_player_dict = {'purple': None, 'blue': None, 'green': None, 'red': None} self.player_color_dict = {} self.status = 'waiting' def get_player_by_color(self, color): if color in self.color_player_dict: return self.players_dict[self.color_player_dict[color]] return None def get_color_by_player(self, player_id): if player_id in self.player_color_dict: return self.player_color_dict[player_id] return None def add_player(self, player_id, name): self.players_dict[player_id] = False self.users_nicks[player_id] = name for color in self.colors: if not self.color_player_dict[color]: self.color_player_dict[color] = player_id self.player_color_dict[player_id] = color break def dell_player(self, player_id): self.players_dict[player_id] = False return self def change_row(self, row, i, to): return row[:i] + to + row[i + 1:] def update_table(self, move, table): print('Table updating') pymove = json.loads(move) pytable = json.loads(table) print('Old table:') for row in pytable: print(' ', row) x0, y0 = int(pymove['X0']), int(pymove['Y0']) x1, y1 = int(pymove['X1']), int(pymove['Y1']) print('Move from ({}, {}) to ({}, {})'.format(x0, y0, x1, y1)) if ((abs(x1 - x0) > 1) or (abs(y1 - y0) > 1)): pytable[x0] = self.change_row(pytable[x0], y0, 'e') for i in range(-1, 2): for j in range(-1, 2): if (x1 + i < len(pytable)) and (x1 + i > -1): if (y1 + j < len(pytable[x1])) and (y1 + j > -1): if pytable[x1 + i][y1 + j] != 'e': pytable[x1 + i] = self.change_row(pytable[x1 + i], y1 + j, self.current_color[0].lower()) pytable[x1] = self.change_row(pytable[x1], y1, self.current_color[0].lower()) res = json.dumps(pytable) if 'e' not in res: r_count = (res.count('r'), 'red') b_count = (res.count('b'), 'blue') g_count = (res.count('g'), 'green') p_count = (res.count('p'), 'purple') sort_list = [r_count, b_count, p_count, g_count] sort_list.sort() self.winner = sort_list[-1][1] print('New table:') for row in pytable: print(' ', row) return res def can_move(self, table): pytable = json.loads(table) for row_id, row in enumerate(pytable): for char_id in range(len(row)): char = row[char_id] if char == self.current_color[0].lower(): for i in range(-2, 3): for j in range(-2, 3): if (row_id + i < len(pytable)) and (row_id + i > -1): if (char_id + j < len(row)) and (char_id + j > -1): if pytable[row_id + i][char_id + j] == 'e': return True return False def change_color(self, table): print('Сolor changing') colors = self.colors self.current_color = colors[ (colors.index(self.current_color) + 1) % self.players_num] i = 1 while ((not self.players_dict[self.color_player_dict[self.current_color]]) or (not self.can_move(table))) and (i <= 5): self.current_color = colors[ (colors.index(self.current_color) + 1) % self.players_num] i += 1 if not self.can_move(table): return None return self.current_color class RoomsManager(): def __init__(self, db): # dict of rooms by their obj_id self.db = db self.rooms_dict = {} def get_room(self, objectid): if objectid not in self.rooms_dict: rid = objectid room_in_db = self.db.rooms.find_one({'_id': ObjectId(rid)}) if room_in_db: print('Room', objectid, 'extrapolated from db') new_room = Room( int(room_in_db['players_num']), rid, room_in_db['table']) new_room.current_color = room_in_db['current_color'] for user_id in room_in_db['players']: player = room_in_db['players'][user_id] new_room.color_player_dict[player['color']] = user_id new_room.player_color_dict[user_id] = player['color'] new_room.users_nicks[user_id] = player['nick'] new_room.players_dict[user_id] = None self.rooms_dict[rid] = new_room else: return None return self.rooms_dict[objectid] def add_room(self, room): self.rooms_dict[room.objectid] = room def rooms(self): for objectid in self.rooms_dict: yield self.rooms_dict[objectid]
Andrey-Tkachev/infection
models/room.py
Python
mit
6,066
class Solution: def countSegments(self, s: 'str') -> 'int': return len(s.split())
jiadaizhao/LeetCode
0401-0500/0434-Number of Segments in a String/0434-Number of Segments in a String.py
Python
mit
94
package com.rallydev.jarvis; import clojure.lang.RT; import clojure.lang.Symbol; import clojure.lang.Var; import groovy.lang.Closure; import java.util.HashMap; import java.util.Map; public abstract class Bot { public static void addPlugin(Object plugin, Map metadata) { ADD_PLUGIN.invoke(plugin, metadata); } public static void addCommand(String commandName, String description, String author, final Closure callback) { HashMap<String, String> map = new HashMap<String,String>(); map.put("command", commandName); map.put("description", description); map.put("author", author); addPlugin(new GroovyCommand(callback, commandName), map); } private static final Var REQUIRE = RT.var("clojure.core", "require"); static { REQUIRE.invoke(Symbol.intern("jarvis.plugins")); } private static final Var ADD_PLUGIN = RT.var("jarvis.plugins", "add-plugin"); private static class GroovyCommand implements Plugin { private final Closure callback; private final String command; private GroovyCommand(Closure callback, String command) { this.callback = callback; this.command = command; } public Object invoke(Map message) { return callback.call(message); } } }
RallySoftware/jarvis-core
src/main/java/com/rallydev/jarvis/Bot.java
Java
mit
1,334
// Copyright (c) 2010 Satoshi Nakamoto // Copyright (c) 2009-2012 The Bitcoin developers // Distributed under the MIT/X11 software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include <boost/assign/list_of.hpp> #include "base58.h" #include "bitcoinrpc.h" #include "txdb.h" #include "init.h" #include "main.h" #include "net.h" #include "wallet.h" using namespace std; using namespace boost; using namespace boost::assign; using namespace json_spirit; void ScriptPubKeyToJSON(const CScript& scriptPubKey, Object& out, bool fIncludeHex) { txnouttype type; vector<CTxDestination> addresses; int nRequired; out.push_back(Pair("asm", scriptPubKey.ToString())); if (fIncludeHex) out.push_back(Pair("hex", HexStr(scriptPubKey.begin(), scriptPubKey.end()))); if (!ExtractDestinations(scriptPubKey, type, addresses, nRequired)) { out.push_back(Pair("type", GetTxnOutputType(TX_NONSTANDARD))); return; } out.push_back(Pair("reqSigs", nRequired)); out.push_back(Pair("type", GetTxnOutputType(type))); Array a; BOOST_FOREACH(const CTxDestination& addr, addresses) a.push_back(CBitcoinAddress(addr).ToString()); out.push_back(Pair("addresses", a)); } void TxToJSON(const CTransaction& tx, const uint256 hashBlock, Object& entry) { entry.push_back(Pair("txid", tx.GetHash().GetHex())); entry.push_back(Pair("version", tx.nVersion)); entry.push_back(Pair("time", (boost::int64_t)tx.nTime)); entry.push_back(Pair("locktime", (boost::int64_t)tx.nLockTime)); Array vin; BOOST_FOREACH(const CTxIn& txin, tx.vin) { Object in; if (tx.IsCoinBase()) in.push_back(Pair("coinbase", HexStr(txin.scriptSig.begin(), txin.scriptSig.end()))); else { in.push_back(Pair("txid", txin.prevout.hash.GetHex())); in.push_back(Pair("vout", (boost::int64_t)txin.prevout.n)); Object o; o.push_back(Pair("asm", txin.scriptSig.ToString())); o.push_back(Pair("hex", HexStr(txin.scriptSig.begin(), txin.scriptSig.end()))); in.push_back(Pair("scriptSig", o)); } in.push_back(Pair("sequence", (boost::int64_t)txin.nSequence)); vin.push_back(in); } entry.push_back(Pair("vin", vin)); Array vout; for (unsigned int i = 0; i < tx.vout.size(); i++) { const CTxOut& txout = tx.vout[i]; Object out; out.push_back(Pair("value", ValueFromAmount(txout.nValue))); out.push_back(Pair("n", (boost::int64_t)i)); Object o; ScriptPubKeyToJSON(txout.scriptPubKey, o, false); out.push_back(Pair("scriptPubKey", o)); vout.push_back(out); } entry.push_back(Pair("vout", vout)); if (hashBlock != 0) { entry.push_back(Pair("blockhash", hashBlock.GetHex())); map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(hashBlock); if (mi != mapBlockIndex.end() && (*mi).second) { CBlockIndex* pindex = (*mi).second; if (pindex->IsInMainChain()) { entry.push_back(Pair("confirmations", 1 + nBestHeight - pindex->nHeight)); entry.push_back(Pair("time", (boost::int64_t)pindex->nTime)); entry.push_back(Pair("blocktime", (boost::int64_t)pindex->nTime)); } else entry.push_back(Pair("confirmations", 0)); } } } Value getrawtransaction(const Array& params, bool fHelp) { if (fHelp || params.size() < 1 || params.size() > 2) throw runtime_error( "getrawtransaction <txid> [verbose=0]\n" "If verbose=0, returns a string that is\n" "serialized, hex-encoded data for <txid>.\n" "If verbose is non-zero, returns an Object\n" "with information about <txid>."); uint256 hash; hash.SetHex(params[0].get_str()); bool fVerbose = false; if (params.size() > 1) fVerbose = (params[1].get_int() != 0); CTransaction tx; uint256 hashBlock = 0; if (!GetTransaction(hash, tx, hashBlock)) throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "No information available about transaction"); CDataStream ssTx(SER_NETWORK, PROTOCOL_VERSION); ssTx << tx; string strHex = HexStr(ssTx.begin(), ssTx.end()); if (!fVerbose) return strHex; Object result; result.push_back(Pair("hex", strHex)); TxToJSON(tx, hashBlock, result); return result; } Value listunspent(const Array& params, bool fHelp) { if (fHelp || params.size() > 3) throw runtime_error( "listunspent [minconf=1] [maxconf=9999999] [\"address\",...]\n" "Returns array of unspent transaction outputs\n" "with between minconf and maxconf (inclusive) confirmations.\n" "Optionally filtered to only include txouts paid to specified addresses.\n" "Results are an array of Objects, each of which has:\n" "{txid, vout, scriptPubKey, amount, confirmations}"); RPCTypeCheck(params, list_of(int_type)(int_type)(array_type)); int nMinDepth = 1; if (params.size() > 0) nMinDepth = params[0].get_int(); int nMaxDepth = 9999999; if (params.size() > 1) nMaxDepth = params[1].get_int(); set<CBitcoinAddress> setAddress; if (params.size() > 2) { Array inputs = params[2].get_array(); BOOST_FOREACH(Value& input, inputs) { CBitcoinAddress address(input.get_str()); if (!address.IsValid()) throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, string("Invalid Abundance address: ")+input.get_str()); if (setAddress.count(address)) throw JSONRPCError(RPC_INVALID_PARAMETER, string("Invalid parameter, duplicated address: ")+input.get_str()); setAddress.insert(address); } } Array results; vector<COutput> vecOutputs; pwalletMain->AvailableCoins(vecOutputs, false); BOOST_FOREACH(const COutput& out, vecOutputs) { if (out.nDepth < nMinDepth || out.nDepth > nMaxDepth) continue; if(setAddress.size()) { CTxDestination address; if(!ExtractDestination(out.tx->vout[out.i].scriptPubKey, address)) continue; if (!setAddress.count(address)) continue; } int64_t nValue = out.tx->vout[out.i].nValue; const CScript& pk = out.tx->vout[out.i].scriptPubKey; Object entry; entry.push_back(Pair("txid", out.tx->GetHash().GetHex())); entry.push_back(Pair("vout", out.i)); CTxDestination address; if (ExtractDestination(out.tx->vout[out.i].scriptPubKey, address)) { entry.push_back(Pair("address", CBitcoinAddress(address).ToString())); if (pwalletMain->mapAddressBook.count(address)) entry.push_back(Pair("account", pwalletMain->mapAddressBook[address])); } entry.push_back(Pair("scriptPubKey", HexStr(pk.begin(), pk.end()))); entry.push_back(Pair("amount",ValueFromAmount(nValue))); entry.push_back(Pair("confirmations",out.nDepth)); results.push_back(entry); } return results; } Value createrawtransaction(const Array& params, bool fHelp) { if (fHelp || params.size() != 2) throw runtime_error( "createrawtransaction [{\"txid\":txid,\"vout\":n},...] {address:amount,...}\n" "Create a transaction spending given inputs\n" "(array of objects containing transaction id and output number),\n" "sending to given address(es).\n" "Returns hex-encoded raw transaction.\n" "Note that the transaction's inputs are not signed, and\n" "it is not stored in the wallet or transmitted to the network."); RPCTypeCheck(params, list_of(array_type)(obj_type)); Array inputs = params[0].get_array(); Object sendTo = params[1].get_obj(); CTransaction rawTx; BOOST_FOREACH(Value& input, inputs) { const Object& o = input.get_obj(); const Value& txid_v = find_value(o, "txid"); if (txid_v.type() != str_type) throw JSONRPCError(RPC_INVALID_PARAMETER, "Invalid parameter, missing txid key"); string txid = txid_v.get_str(); if (!IsHex(txid)) throw JSONRPCError(RPC_INVALID_PARAMETER, "Invalid parameter, expected hex txid"); const Value& vout_v = find_value(o, "vout"); if (vout_v.type() != int_type) throw JSONRPCError(RPC_INVALID_PARAMETER, "Invalid parameter, missing vout key"); int nOutput = vout_v.get_int(); if (nOutput < 0) throw JSONRPCError(RPC_INVALID_PARAMETER, "Invalid parameter, vout must be positive"); CTxIn in(COutPoint(uint256(txid), nOutput)); rawTx.vin.push_back(in); } set<CBitcoinAddress> setAddress; BOOST_FOREACH(const Pair& s, sendTo) { CBitcoinAddress address(s.name_); if (!address.IsValid()) throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, string("Invalid Abundance address: ")+s.name_); if (setAddress.count(address)) throw JSONRPCError(RPC_INVALID_PARAMETER, string("Invalid parameter, duplicated address: ")+s.name_); setAddress.insert(address); CScript scriptPubKey; scriptPubKey.SetDestination(address.Get()); int64_t nAmount = AmountFromValue(s.value_); CTxOut out(nAmount, scriptPubKey); rawTx.vout.push_back(out); } CDataStream ss(SER_NETWORK, PROTOCOL_VERSION); ss << rawTx; return HexStr(ss.begin(), ss.end()); } Value decoderawtransaction(const Array& params, bool fHelp) { if (fHelp || params.size() != 1) throw runtime_error( "decoderawtransaction <hex string>\n" "Return a JSON object representing the serialized, hex-encoded transaction."); RPCTypeCheck(params, list_of(str_type)); vector<unsigned char> txData(ParseHex(params[0].get_str())); CDataStream ssData(txData, SER_NETWORK, PROTOCOL_VERSION); CTransaction tx; try { ssData >> tx; } catch (std::exception &e) { throw JSONRPCError(RPC_DESERIALIZATION_ERROR, "TX decode failed"); } Object result; TxToJSON(tx, 0, result); return result; } Value decodescript(const Array& params, bool fHelp) { if (fHelp || params.size() != 1) throw runtime_error( "decodescript <hex string>\n" "Decode a hex-encoded script."); RPCTypeCheck(params, list_of(str_type)); Object r; CScript script; if (params[0].get_str().size() > 0){ vector<unsigned char> scriptData(ParseHexV(params[0], "argument")); script = CScript(scriptData.begin(), scriptData.end()); } else { // Empty scripts are valid } ScriptPubKeyToJSON(script, r, false); r.push_back(Pair("p2sh", CBitcoinAddress(script.GetID()).ToString())); return r; } Value signrawtransaction(const Array& params, bool fHelp) { if (fHelp || params.size() < 1 || params.size() > 4) throw runtime_error( "signrawtransaction <hex string> [{\"txid\":txid,\"vout\":n,\"scriptPubKey\":hex},...] [<privatekey1>,...] [sighashtype=\"ALL\"]\n" "Sign inputs for raw transaction (serialized, hex-encoded).\n" "Second optional argument (may be null) is an array of previous transaction outputs that\n" "this transaction depends on but may not yet be in the blockchain.\n" "Third optional argument (may be null) is an array of base58-encoded private\n" "keys that, if given, will be the only keys used to sign the transaction.\n" "Fourth optional argument is a string that is one of six values; ALL, NONE, SINGLE or\n" "ALL|ANYONECANPAY, NONE|ANYONECANPAY, SINGLE|ANYONECANPAY.\n" "Returns json object with keys:\n" " hex : raw transaction with signature(s) (hex-encoded string)\n" " complete : 1 if transaction has a complete set of signature (0 if not)" + HelpRequiringPassphrase()); RPCTypeCheck(params, list_of(str_type)(array_type)(array_type)(str_type), true); vector<unsigned char> txData(ParseHex(params[0].get_str())); CDataStream ssData(txData, SER_NETWORK, PROTOCOL_VERSION); vector<CTransaction> txVariants; while (!ssData.empty()) { try { CTransaction tx; ssData >> tx; txVariants.push_back(tx); } catch (std::exception &e) { throw JSONRPCError(RPC_DESERIALIZATION_ERROR, "TX decode failed"); } } if (txVariants.empty()) throw JSONRPCError(RPC_DESERIALIZATION_ERROR, "Missing transaction"); // mergedTx will end up with all the signatures; it // starts as a clone of the rawtx: CTransaction mergedTx(txVariants[0]); bool fComplete = true; // Fetch previous transactions (inputs): map<COutPoint, CScript> mapPrevOut; for (unsigned int i = 0; i < mergedTx.vin.size(); i++) { CTransaction tempTx; MapPrevTx mapPrevTx; CTxDB txdb("r"); map<uint256, CTxIndex> unused; bool fInvalid; // FetchInputs aborts on failure, so we go one at a time. tempTx.vin.push_back(mergedTx.vin[i]); tempTx.FetchInputs(txdb, unused, false, false, mapPrevTx, fInvalid); // Copy results into mapPrevOut: BOOST_FOREACH(const CTxIn& txin, tempTx.vin) { const uint256& prevHash = txin.prevout.hash; if (mapPrevTx.count(prevHash) && mapPrevTx[prevHash].second.vout.size()>txin.prevout.n) mapPrevOut[txin.prevout] = mapPrevTx[prevHash].second.vout[txin.prevout.n].scriptPubKey; } } // Add previous txouts given in the RPC call: if (params.size() > 1 && params[1].type() != null_type) { Array prevTxs = params[1].get_array(); BOOST_FOREACH(Value& p, prevTxs) { if (p.type() != obj_type) throw JSONRPCError(RPC_DESERIALIZATION_ERROR, "expected object with {\"txid'\",\"vout\",\"scriptPubKey\"}"); Object prevOut = p.get_obj(); RPCTypeCheck(prevOut, map_list_of("txid", str_type)("vout", int_type)("scriptPubKey", str_type)); string txidHex = find_value(prevOut, "txid").get_str(); if (!IsHex(txidHex)) throw JSONRPCError(RPC_DESERIALIZATION_ERROR, "txid must be hexadecimal"); uint256 txid; txid.SetHex(txidHex); int nOut = find_value(prevOut, "vout").get_int(); if (nOut < 0) throw JSONRPCError(RPC_DESERIALIZATION_ERROR, "vout must be positive"); string pkHex = find_value(prevOut, "scriptPubKey").get_str(); if (!IsHex(pkHex)) throw JSONRPCError(RPC_DESERIALIZATION_ERROR, "scriptPubKey must be hexadecimal"); vector<unsigned char> pkData(ParseHex(pkHex)); CScript scriptPubKey(pkData.begin(), pkData.end()); COutPoint outpoint(txid, nOut); if (mapPrevOut.count(outpoint)) { // Complain if scriptPubKey doesn't match if (mapPrevOut[outpoint] != scriptPubKey) { string err("Previous output scriptPubKey mismatch:\n"); err = err + mapPrevOut[outpoint].ToString() + "\nvs:\n"+ scriptPubKey.ToString(); throw JSONRPCError(RPC_DESERIALIZATION_ERROR, err); } } else mapPrevOut[outpoint] = scriptPubKey; } } bool fGivenKeys = false; CBasicKeyStore tempKeystore; if (params.size() > 2 && params[2].type() != null_type) { fGivenKeys = true; Array keys = params[2].get_array(); BOOST_FOREACH(Value k, keys) { CBitcoinSecret vchSecret; bool fGood = vchSecret.SetString(k.get_str()); if (!fGood) throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY,"Invalid private key"); CKey key; bool fCompressed; CSecret secret = vchSecret.GetSecret(fCompressed); key.SetSecret(secret, fCompressed); tempKeystore.AddKey(key); } } else EnsureWalletIsUnlocked(); const CKeyStore& keystore = (fGivenKeys ? tempKeystore : *pwalletMain); int nHashType = SIGHASH_ALL; if (params.size() > 3 && params[3].type() != null_type) { static map<string, int> mapSigHashValues = boost::assign::map_list_of (string("ALL"), int(SIGHASH_ALL)) (string("ALL|ANYONECANPAY"), int(SIGHASH_ALL|SIGHASH_ANYONECANPAY)) (string("NONE"), int(SIGHASH_NONE)) (string("NONE|ANYONECANPAY"), int(SIGHASH_NONE|SIGHASH_ANYONECANPAY)) (string("SINGLE"), int(SIGHASH_SINGLE)) (string("SINGLE|ANYONECANPAY"), int(SIGHASH_SINGLE|SIGHASH_ANYONECANPAY)) ; string strHashType = params[3].get_str(); if (mapSigHashValues.count(strHashType)) nHashType = mapSigHashValues[strHashType]; else throw JSONRPCError(RPC_INVALID_PARAMETER, "Invalid sighash param"); } bool fHashSingle = ((nHashType & ~SIGHASH_ANYONECANPAY) == SIGHASH_SINGLE); // Sign what we can: for (unsigned int i = 0; i < mergedTx.vin.size(); i++) { CTxIn& txin = mergedTx.vin[i]; if (mapPrevOut.count(txin.prevout) == 0) { fComplete = false; continue; } const CScript& prevPubKey = mapPrevOut[txin.prevout]; txin.scriptSig.clear(); // Only sign SIGHASH_SINGLE if there's a corresponding output: if (!fHashSingle || (i < mergedTx.vout.size())) SignSignature(keystore, prevPubKey, mergedTx, i, nHashType); // ... and merge in other signatures: BOOST_FOREACH(const CTransaction& txv, txVariants) { txin.scriptSig = CombineSignatures(prevPubKey, mergedTx, i, txin.scriptSig, txv.vin[i].scriptSig); } if (!VerifyScript(txin.scriptSig, prevPubKey, mergedTx, i, 0)) fComplete = false; } Object result; CDataStream ssTx(SER_NETWORK, PROTOCOL_VERSION); ssTx << mergedTx; result.push_back(Pair("hex", HexStr(ssTx.begin(), ssTx.end()))); result.push_back(Pair("complete", fComplete)); return result; } Value sendrawtransaction(const Array& params, bool fHelp) { if (fHelp || params.size() < 1 || params.size() > 1) throw runtime_error( "sendrawtransaction <hex string>\n" "Submits raw transaction (serialized, hex-encoded) to local node and network."); RPCTypeCheck(params, list_of(str_type)); // parse hex string from parameter vector<unsigned char> txData(ParseHex(params[0].get_str())); CDataStream ssData(txData, SER_NETWORK, PROTOCOL_VERSION); CTransaction tx; // deserialize binary data stream try { ssData >> tx; } catch (std::exception &e) { throw JSONRPCError(RPC_DESERIALIZATION_ERROR, "TX decode failed"); } uint256 hashTx = tx.GetHash(); // See if the transaction is already in a block // or in the memory pool: CTransaction existingTx; uint256 hashBlock = 0; if (GetTransaction(hashTx, existingTx, hashBlock)) { if (hashBlock != 0) throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, string("transaction already in block ")+hashBlock.GetHex()); // Not in block, but already in the memory pool; will drop // through to re-relay it. } else { // push to local node CTxDB txdb("r"); if (!tx.AcceptToMemoryPool(txdb)) throw JSONRPCError(RPC_DESERIALIZATION_ERROR, "TX rejected"); SyncWithWallets(tx, NULL, true); } RelayTransaction(tx, hashTx); return hashTx.GetHex(); }
AbundanceSource/ABC2
src/rpcrawtransaction.cpp
C++
mit
20,288
var loadState = { preload: function() { /* Load all game assets Place your load bar, some messages. In this case of loading, only text is placed... */ var loadingLabel = game.add.text(80, 150, 'loading...', {font: '30px Courier', fill: '#fff'}); //Load your images, spritesheets, bitmaps... game.load.image('kayle', 'assets/img/kayle.png'); game.load.image('tree', 'assets/img/tree.png'); game.load.image('rock', 'assets/img/rock.png'); game.load.image('undefined', 'assets/img/undefined.png'); game.load.image('grass', 'assets/img/grass.png'); game.load.image('player', 'assets/img/player.png'); game.load.image('btn-play','assets/img/btn-play.png'); game.load.image('btn-load','assets/img/btn-play.png'); //Load your sounds, efx, music... //Example: game.load.audio('rockas', 'assets/snd/rockas.wav'); //Load your data, JSON, Querys... //Example: game.load.json('version', 'http://phaser.io/version.json'); }, create: function() { game.stage.setBackgroundColor('#DEDEDE'); game.scale.fullScreenScaleMode = Phaser.ScaleManager.EXACT_FIT; game.state.start('menu'); } };
Edznux/kayle
js/load.js
JavaScript
mit
1,271
<?php class sfGuardFormSignin extends sfForm { public function configure() { $this->setWidgets(array( 'username' => new sfWidgetFormInput(), 'password' => new sfWidgetFormInput(array('type' => 'password')),/* 'remember' => new sfWidgetFormInputCheckbox(),*/ )); $this->setValidators(array( 'username' => new sfValidatorString(), 'password' => new sfValidatorString(),/* 'remember' => new sfValidatorBoolean(),*/ )); $this->validatorSchema->setPostValidator(new sfGuardValidatorUser()); $this->widgetSchema->setNameFormat('signin[%s]'); } }
aleste/proyectodev
plugins/sfGuardPlugin/lib/form/sfGuardFormSignin.class.php
PHP
mit
610
import edu.princeton.cs.algs4.QuickUnionUF; public class PercolationQF { private int[][] directions = new int[][] { { 1, 0 }, // BOTTOM { -1, 0 }, // TOP { 0, -1 }, // LEFT { 0, 1 } // RIGHT }; private int size; private int[] grid; // Main union find data structure used to determine if the system percolates private QuickUnionUF ufMain; // Support union find data structure used to discover if a site is full or not // and avoid backwash. private QuickUnionUF ufSupport; public PercolationQF(int n) { if (n <= 0) { throw new java.lang.IllegalArgumentException(); } this.size = n; // add two virtual sites, one connected to all the elements of the top row, // and one connected to all the ones at the bottom row. ufMain = new QuickUnionUF((n * n) + 2); // add one virtual site connected to all the elements of the top row. ufSupport = new QuickUnionUF((n * n) + 1); // connect top row sites to virtual top site for (int i = 1; i < n + 1; i++) { ufMain.union(i, 0); ufSupport.union(i, 0); } // connect bottom row sites to virtual bottom site for (int i = n * n; i > n * n - n; i--) { ufMain.union(i, (n * n) + 1); } // create n-by-n grid, with all sites blocked // No need to keep a multidimensional array grid = new int[n * n]; // Initialize all to full for (int i = 0; i < n * n; i++) { grid[i] = 0; } } // open site (row i, column j) if it is not open already public void open(int i, int j) { if (!isValidCoordinate(i, j)) { throw new java.lang.IndexOutOfBoundsException(); } int tmpi = i; int tmpj = j; if (isBlocked(i, j)) { // it is indeed blocked, let's open it grid[getIndex(i, j)] = 1; for (int d = 0; d < directions.length; d++) { i = tmpi + directions[d][0]; j = tmpj + directions[d][1]; // if a site in one of the allowed directions is open we can perform a // connection if (isValidCoordinate(i, j) && isOpen(i, j)) { // shift by one because of the virtual top site int siteA = getIndex(i, j) + 1; int siteB = getIndex(tmpi, tmpj) + 1; ufMain.union(siteA, siteB); ufSupport.union(siteA, siteB); } } } } // is site (row i, column j) open? public boolean isOpen(int i, int j) { if (isValidCoordinate(i, j)) { return grid[getIndex(i, j)] == 1; } throw new java.lang.IndexOutOfBoundsException(); } // is site (row i, column j) full? public boolean isFull(int i, int j) { if (isValidCoordinate(i, j)) { if (isOpen(i, j)) { // index is shifted by one due to the virtual top site int index = getIndex(i, j) + 1; if (index < size) { // by definition an open site at the first row is full return true; } return ufSupport.connected(index, 0); } } else { throw new java.lang.IndexOutOfBoundsException(); } return false; } // is site (row i, column j) blocked? private boolean isBlocked(int i, int j) { if (isValidCoordinate(i, j)) { return grid[getIndex(i, j)] == 0; } return false; } // does the system percolate? public boolean percolates() { // we don't use the isFull definition int virtualTop = 0; int virtualBottom = size * size + 1; // corner case: 1 site if (virtualBottom == 2) { return isOpen(1, 1); } // corner case: no sites if (virtualBottom == 0) { return false; } return ufMain.connected(virtualTop, virtualBottom); } // get single index from row and column private int getIndex(int i, int j) { return (i - 1) * size + (j - 1); } private boolean isValidCoordinate(int i, int j) { if (i > 0 && i <= size && j > 0 && j <= size) { return true; } return false; } }
SirGandal/Percolation
Percolation/src/PercolationQF.java
Java
mit
3,956
/* * Copyright (c) 2013 Jadler contributors * This program is made available under the terms of the MIT License. */ package net.jadler.matchers; import java.util.List; import net.jadler.Request; import org.apache.commons.lang.Validate; import org.hamcrest.Factory; import org.hamcrest.Matcher; /** * A {@link RequestMatcher} used for matching a request parameter. */ public class ParameterRequestMatcher extends RequestMatcher<List<String>> { private final String paramName; private final String desc; /** * Protected constructor useful only when subtyping. For creating instances of this class use * {@link #requestParameter(java.lang.String, org.hamcrest.Matcher)} instead. * @param pred a predicate to be applied on the given request parameter * @param paramName name of a request parameter (case sensitive) */ public ParameterRequestMatcher(final Matcher<? super List<String>> pred, final String paramName) { super(pred); Validate.notEmpty(paramName, "paramName cannot be empty"); this.paramName = paramName; this.desc = "parameter \"" + paramName + "\" is"; } /** * Retrieves a parameter (defined in {@link #ParameterRequestMatcher(org.hamcrest.Matcher, java.lang.String)}) * of the given request. The values are percent-encoded. * @param req request to retrieve the parameter from * @return the request parameter as a list of values or {@code null} if there is no such a parameter in the request */ @Override protected List<String> retrieveValue(final Request req) { return req.getParameters().getValues(this.paramName); } /** * {@inheritDoc} */ @Override protected String provideDescription() { return this.desc; } /** * Factory method to create new instance of this matcher. * @param paramName name of a request parameter * @param pred a predicate to be applied on the request parameter * @return new instance of this matcher */ @Factory public static ParameterRequestMatcher requestParameter(final String paramName, final Matcher<? super List<String>> pred) { return new ParameterRequestMatcher(pred, paramName); } }
mohitbnsl/BANSAL
jadler-core/src/main/java/net/jadler/matchers/ParameterRequestMatcher.java
Java
mit
2,285
/* */ var htmlparser = require('htmlparser2'); var _ = require('lodash'); var quoteRegexp = require('regexp-quote'); module.exports = sanitizeHtml; // Ignore the _recursing flag; it's there for recursive // invocation as a guard against this exploit: // https://github.com/fb55/htmlparser2/issues/105 function sanitizeHtml(html, options, _recursing) { var result = ''; function Frame(tag, attribs) { var that = this; this.tag = tag; this.attribs = attribs || {}; this.tagPosition = result.length; this.text = ''; // Node inner text this.updateParentNodeText = function() { if (stack.length) { var parentFrame = stack[stack.length - 1]; parentFrame.text += that.text; } }; } if (!options) { options = sanitizeHtml.defaults; } else { _.defaults(options, sanitizeHtml.defaults); } // Tags that contain something other than HTML. If we are not allowing // these tags, we should drop their content too. For other tags you would // drop the tag but keep its content. var nonTextTagsMap = { script: true, style: true }; var allowedTagsMap; if(options.allowedTags) { allowedTagsMap = {}; _.each(options.allowedTags, function(tag) { allowedTagsMap[tag] = true; }); } var selfClosingMap = {}; _.each(options.selfClosing, function(tag) { selfClosingMap[tag] = true; }); var allowedAttributesMap; var allowedAttributesGlobMap; if(options.allowedAttributes) { allowedAttributesMap = {}; allowedAttributesGlobMap = {}; _.each(options.allowedAttributes, function(attributes, tag) { allowedAttributesMap[tag] = {}; var globRegex = []; _.each(attributes, function(name) { if(name.indexOf('*') >= 0) { globRegex.push(quoteRegexp(name).replace(/\\\*/g, '.*')); } else { allowedAttributesMap[tag][name] = true; } }); allowedAttributesGlobMap[tag] = new RegExp('^(' + globRegex.join('|') + ')$'); }); } var allowedClassesMap = {}; _.each(options.allowedClasses, function(classes, tag) { // Implicitly allows the class attribute if(allowedAttributesMap) { if (!allowedAttributesMap[tag]) { allowedAttributesMap[tag] = {}; } allowedAttributesMap[tag]['class'] = true; } allowedClassesMap[tag] = {}; _.each(classes, function(name) { allowedClassesMap[tag][name] = true; }); }); var transformTagsMap = {}; _.each(options.transformTags, function(transform, tag){ if (typeof transform === 'function') { transformTagsMap[tag] = transform; } else if (typeof transform === "string") { transformTagsMap[tag] = sanitizeHtml.simpleTransform(transform); } }); var depth = 0; var stack = []; var skipMap = {}; var transformMap = {}; var skipText = false; var parser = new htmlparser.Parser({ onopentag: function(name, attribs) { var frame = new Frame(name, attribs); stack.push(frame); var skip = false; if (_.has(transformTagsMap, name)) { var transformedTag = transformTagsMap[name](name, attribs); frame.attribs = attribs = transformedTag.attribs; if (name !== transformedTag.tagName) { frame.name = name = transformedTag.tagName; transformMap[depth] = transformedTag.tagName; } } if (allowedTagsMap && !_.has(allowedTagsMap, name)) { skip = true; if (_.has(nonTextTagsMap, name)) { skipText = true; } skipMap[depth] = true; } depth++; if (skip) { // We want the contents but not this tag return; } result += '<' + name; if (!allowedAttributesMap || _.has(allowedAttributesMap, name)) { _.each(attribs, function(value, a) { if (!allowedAttributesMap || _.has(allowedAttributesMap[name], a) || (_.has(allowedAttributesGlobMap, name) && allowedAttributesGlobMap[name].test(a))) { if ((a === 'href') || (a === 'src')) { if (naughtyHref(value)) { delete frame.attribs[a]; return; } } if (a === 'class') { value = filterClasses(value, allowedClassesMap[name]); if (!value.length) { delete frame.attribs[a]; return; } } result += ' ' + a; if (value.length) { result += '="' + escapeHtml(value) + '"'; } } else { delete frame.attribs[a]; } }); } if (_.has(selfClosingMap, name)) { result += " />"; } else { result += ">"; } }, ontext: function(text) { if (skipText) { return; } var tag = stack[stack.length-1] && stack[stack.length-1].tag; if (_.has(nonTextTagsMap, tag)) { result += text; } else { var escaped = escapeHtml(text); if (options.textFilter) { result += options.textFilter(escaped); } else { result += escaped; } } if (stack.length) { var frame = stack[stack.length - 1]; frame.text += text; } }, onclosetag: function(name) { var frame = stack.pop(); if (!frame) { // Do not crash on bad markup return; } skipText = false; depth--; if (skipMap[depth]) { delete skipMap[depth]; frame.updateParentNodeText(); return; } if (transformMap[depth]) { name = transformMap[depth]; delete transformMap[depth]; } if (options.exclusiveFilter && options.exclusiveFilter(frame)) { result = result.substr(0, frame.tagPosition); return; } frame.updateParentNodeText(); if (_.has(selfClosingMap, name)) { // Already output /> return; } result += "</" + name + ">"; } }, { decodeEntities: true }); parser.write(html); parser.end(); return result; function escapeHtml(s) { if (typeof(s) !== 'string') { s = s + ''; } return s.replace(/\&/g, '&amp;').replace(/</g, '&lt;').replace(/\>/g, '&gt;').replace(/\"/g, '&quot;'); } function naughtyHref(href) { // Browsers ignore character codes of 32 (space) and below in a surprising // number of situations. Start reading here: // https://www.owasp.org/index.php/XSS_Filter_Evasion_Cheat_Sheet#Embedded_tab href = href.replace(/[\x00-\x20]+/g, ''); // Clobber any comments in URLs, which the browser might // interpret inside an XML data island, allowing // a javascript: URL to be snuck through href = href.replace(/<\!\-\-.*?\-\-\>/g, ''); // Case insensitive so we don't get faked out by JAVASCRIPT #1 var matches = href.match(/^([a-zA-Z]+)\:/); if (!matches) { // No scheme = no way to inject js (right?) return false; } var scheme = matches[1].toLowerCase(); return (!_.contains(options.allowedSchemes, scheme)); } function filterClasses(classes, allowed) { if (!allowed) { // The class attribute is allowed without filtering on this tag return classes; } classes = classes.split(/\s+/); return _.filter(classes, function(c) { return _.has(allowed, c); }).join(' '); } } // Defaults are accessible to you so that you can use them as a starting point // programmatically if you wish sanitizeHtml.defaults = { allowedTags: [ 'h3', 'h4', 'h5', 'h6', 'blockquote', 'p', 'a', 'ul', 'ol', 'nl', 'li', 'b', 'i', 'strong', 'em', 'strike', 'code', 'hr', 'br', 'div', 'table', 'thead', 'caption', 'tbody', 'tr', 'th', 'td', 'pre' ], allowedAttributes: { a: [ 'href', 'name', 'target' ], // We don't currently allow img itself by default, but this // would make sense if we did img: [ 'src' ] }, // Lots of these won't come up by default because we don't allow them selfClosing: [ 'img', 'br', 'hr', 'area', 'base', 'basefont', 'input', 'link', 'meta' ], // URL schemes we permit allowedSchemes: [ 'http', 'https', 'ftp', 'mailto' ] }; sanitizeHtml.simpleTransform = function(newTagName, newAttribs, merge) { merge = (merge === undefined) ? true : merge; newAttribs = newAttribs || {}; return function(tagName, attribs) { var attrib; if (merge) { for (attrib in newAttribs) { attribs[attrib] = newAttribs[attrib]; } } else { attribs = newAttribs; } return { tagName: newTagName, attribs: attribs }; }; };
npelletm/np-jdanyow-skeleton-navigation
jspm_packages/npm/sanitize-html@1.6.1/index.js
JavaScript
mit
8,674
<?php /** * @filesource modules/product/controllers/sitemap.php * * @copyright 2016 Goragod.com * @license http://www.kotchasan.com/license/ * * @see http://www.kotchasan.com/ */ namespace Product\Sitemap; /** * sitemap.xml * * @author Goragod Wiriya <admin@goragod.com> * * @since 1.0 */ class Controller extends \Kotchasan\Controller { /** * แสดงผล sitemap.xml * * @param array $ids แอเรย์ของ module_id * @param array $modules แอเรย์ของ module ที่ติดตั้งแล้ว * @param string $date วันที่วันนี้ * * @return array */ public function init($ids, $modules, $date) { $result = array(); foreach (\Product\Sitemap\Model::getStories($ids, $date) as $item) { $module = $modules[$item->module_id]; $result[] = (object) array( 'url' => \Product\Index\Controller::url($module, $item->alias, $item->id, false), 'date' => date('Y-m-d', $item->last_update), ); $result[] = (object) array( 'url' => WEB_URL.'amp.php?module='.$module.'&amp;id='.$item->id, 'date' => date('Y-m-d', $item->last_update), ); } return $result; } }
goragod/GCMS
modules/product/controllers/sitemap.php
PHP
mit
1,346
var path = require('path'); var winston = require('winston'); var config = require('./config.js'); var util = require('./util.js'); module.exports = initLogger(); function initLogger() { var targetDir = path.join(config('workingdir'), 'log'); util.createDirectoryIfNeeded(targetDir); var winstonConfig = { transports: [ new (winston.transports.Console)({ level: 'debug' }), new (winston.transports.File)({ filename: path.join(targetDir, 'tsync.log') }) ] }; return new (winston.Logger)(winstonConfig); }
brbrt/tsync
log.js
JavaScript
mit
629
using System; using System.Linq; using System.Threading.Tasks; using System.Web; using System.Web.Mvc; using Microsoft.AspNet.Identity; using Microsoft.AspNet.Identity.Owin; using Microsoft.Owin.Security; using cristventcode_static.Models; namespace cristventcode_static.Controllers { [Authorize] public class ManageController : Controller { private ApplicationSignInManager _signInManager; private ApplicationUserManager _userManager; public ManageController() { } public ManageController(ApplicationUserManager userManager, ApplicationSignInManager signInManager) { UserManager = userManager; SignInManager = signInManager; } public ApplicationSignInManager SignInManager { get { return _signInManager ?? HttpContext.GetOwinContext().Get<ApplicationSignInManager>(); } private set { _signInManager = value; } } public ApplicationUserManager UserManager { get { return _userManager ?? HttpContext.GetOwinContext().GetUserManager<ApplicationUserManager>(); } private set { _userManager = value; } } // // GET: /Manage/Index public async Task<ActionResult> Index(ManageMessageId? message) { ViewBag.StatusMessage = message == ManageMessageId.ChangePasswordSuccess ? "Your password has been changed." : message == ManageMessageId.SetPasswordSuccess ? "Your password has been set." : message == ManageMessageId.SetTwoFactorSuccess ? "Your two-factor authentication provider has been set." : message == ManageMessageId.Error ? "An error has occurred." : message == ManageMessageId.AddPhoneSuccess ? "Your phone number was added." : message == ManageMessageId.RemovePhoneSuccess ? "Your phone number was removed." : ""; var userId = User.Identity.GetUserId(); var model = new IndexViewModel { HasPassword = HasPassword(), PhoneNumber = await UserManager.GetPhoneNumberAsync(userId), TwoFactor = await UserManager.GetTwoFactorEnabledAsync(userId), Logins = await UserManager.GetLoginsAsync(userId), BrowserRemembered = await AuthenticationManager.TwoFactorBrowserRememberedAsync(userId) }; return View(model); } // // POST: /Manage/RemoveLogin [HttpPost] [ValidateAntiForgeryToken] public async Task<ActionResult> RemoveLogin(string loginProvider, string providerKey) { ManageMessageId? message; var result = await UserManager.RemoveLoginAsync(User.Identity.GetUserId(), new UserLoginInfo(loginProvider, providerKey)); if (result.Succeeded) { var user = await UserManager.FindByIdAsync(User.Identity.GetUserId()); if (user != null) { await SignInManager.SignInAsync(user, isPersistent: false, rememberBrowser: false); } message = ManageMessageId.RemoveLoginSuccess; } else { message = ManageMessageId.Error; } return RedirectToAction("ManageLogins", new { Message = message }); } // // GET: /Manage/AddPhoneNumber public ActionResult AddPhoneNumber() { return View(); } // // POST: /Manage/AddPhoneNumber [HttpPost] [ValidateAntiForgeryToken] public async Task<ActionResult> AddPhoneNumber(AddPhoneNumberViewModel model) { if (!ModelState.IsValid) { return View(model); } // Generate the token and send it var code = await UserManager.GenerateChangePhoneNumberTokenAsync(User.Identity.GetUserId(), model.Number); if (UserManager.SmsService != null) { var message = new IdentityMessage { Destination = model.Number, Body = "Your security code is: " + code }; await UserManager.SmsService.SendAsync(message); } return RedirectToAction("VerifyPhoneNumber", new { PhoneNumber = model.Number }); } // // POST: /Manage/EnableTwoFactorAuthentication [HttpPost] [ValidateAntiForgeryToken] public async Task<ActionResult> EnableTwoFactorAuthentication() { await UserManager.SetTwoFactorEnabledAsync(User.Identity.GetUserId(), true); var user = await UserManager.FindByIdAsync(User.Identity.GetUserId()); if (user != null) { await SignInManager.SignInAsync(user, isPersistent: false, rememberBrowser: false); } return RedirectToAction("Index", "Manage"); } // // POST: /Manage/DisableTwoFactorAuthentication [HttpPost] [ValidateAntiForgeryToken] public async Task<ActionResult> DisableTwoFactorAuthentication() { await UserManager.SetTwoFactorEnabledAsync(User.Identity.GetUserId(), false); var user = await UserManager.FindByIdAsync(User.Identity.GetUserId()); if (user != null) { await SignInManager.SignInAsync(user, isPersistent: false, rememberBrowser: false); } return RedirectToAction("Index", "Manage"); } // // GET: /Manage/VerifyPhoneNumber public async Task<ActionResult> VerifyPhoneNumber(string phoneNumber) { var code = await UserManager.GenerateChangePhoneNumberTokenAsync(User.Identity.GetUserId(), phoneNumber); // Send an SMS through the SMS provider to verify the phone number return phoneNumber == null ? View("Error") : View(new VerifyPhoneNumberViewModel { PhoneNumber = phoneNumber }); } // // POST: /Manage/VerifyPhoneNumber [HttpPost] [ValidateAntiForgeryToken] public async Task<ActionResult> VerifyPhoneNumber(VerifyPhoneNumberViewModel model) { if (!ModelState.IsValid) { return View(model); } var result = await UserManager.ChangePhoneNumberAsync(User.Identity.GetUserId(), model.PhoneNumber, model.Code); if (result.Succeeded) { var user = await UserManager.FindByIdAsync(User.Identity.GetUserId()); if (user != null) { await SignInManager.SignInAsync(user, isPersistent: false, rememberBrowser: false); } return RedirectToAction("Index", new { Message = ManageMessageId.AddPhoneSuccess }); } // If we got this far, something failed, redisplay form ModelState.AddModelError("", "Failed to verify phone"); return View(model); } // // POST: /Manage/RemovePhoneNumber [HttpPost] [ValidateAntiForgeryToken] public async Task<ActionResult> RemovePhoneNumber() { var result = await UserManager.SetPhoneNumberAsync(User.Identity.GetUserId(), null); if (!result.Succeeded) { return RedirectToAction("Index", new { Message = ManageMessageId.Error }); } var user = await UserManager.FindByIdAsync(User.Identity.GetUserId()); if (user != null) { await SignInManager.SignInAsync(user, isPersistent: false, rememberBrowser: false); } return RedirectToAction("Index", new { Message = ManageMessageId.RemovePhoneSuccess }); } // // GET: /Manage/ChangePassword public ActionResult ChangePassword() { return View(); } // // POST: /Manage/ChangePassword [HttpPost] [ValidateAntiForgeryToken] public async Task<ActionResult> ChangePassword(ChangePasswordViewModel model) { if (!ModelState.IsValid) { return View(model); } var result = await UserManager.ChangePasswordAsync(User.Identity.GetUserId(), model.OldPassword, model.NewPassword); if (result.Succeeded) { var user = await UserManager.FindByIdAsync(User.Identity.GetUserId()); if (user != null) { await SignInManager.SignInAsync(user, isPersistent: false, rememberBrowser: false); } return RedirectToAction("Index", new { Message = ManageMessageId.ChangePasswordSuccess }); } AddErrors(result); return View(model); } // // GET: /Manage/SetPassword public ActionResult SetPassword() { return View(); } // // POST: /Manage/SetPassword [HttpPost] [ValidateAntiForgeryToken] public async Task<ActionResult> SetPassword(SetPasswordViewModel model) { if (ModelState.IsValid) { var result = await UserManager.AddPasswordAsync(User.Identity.GetUserId(), model.NewPassword); if (result.Succeeded) { var user = await UserManager.FindByIdAsync(User.Identity.GetUserId()); if (user != null) { await SignInManager.SignInAsync(user, isPersistent: false, rememberBrowser: false); } return RedirectToAction("Index", new { Message = ManageMessageId.SetPasswordSuccess }); } AddErrors(result); } // If we got this far, something failed, redisplay form return View(model); } // // GET: /Manage/ManageLogins public async Task<ActionResult> ManageLogins(ManageMessageId? message) { ViewBag.StatusMessage = message == ManageMessageId.RemoveLoginSuccess ? "The external login was removed." : message == ManageMessageId.Error ? "An error has occurred." : ""; var user = await UserManager.FindByIdAsync(User.Identity.GetUserId()); if (user == null) { return View("Error"); } var userLogins = await UserManager.GetLoginsAsync(User.Identity.GetUserId()); var otherLogins = AuthenticationManager.GetExternalAuthenticationTypes().Where(auth => userLogins.All(ul => auth.AuthenticationType != ul.LoginProvider)).ToList(); ViewBag.ShowRemoveButton = user.PasswordHash != null || userLogins.Count > 1; return View(new ManageLoginsViewModel { CurrentLogins = userLogins, OtherLogins = otherLogins }); } // // POST: /Manage/LinkLogin [HttpPost] [ValidateAntiForgeryToken] public ActionResult LinkLogin(string provider) { // Request a redirect to the external login provider to link a login for the current user return new AccountController.ChallengeResult(provider, Url.Action("LinkLoginCallback", "Manage"), User.Identity.GetUserId()); } // // GET: /Manage/LinkLoginCallback public async Task<ActionResult> LinkLoginCallback() { var loginInfo = await AuthenticationManager.GetExternalLoginInfoAsync(XsrfKey, User.Identity.GetUserId()); if (loginInfo == null) { return RedirectToAction("ManageLogins", new { Message = ManageMessageId.Error }); } var result = await UserManager.AddLoginAsync(User.Identity.GetUserId(), loginInfo.Login); return result.Succeeded ? RedirectToAction("ManageLogins") : RedirectToAction("ManageLogins", new { Message = ManageMessageId.Error }); } protected override void Dispose(bool disposing) { if (disposing && _userManager != null) { _userManager.Dispose(); _userManager = null; } base.Dispose(disposing); } #region Helpers // Used for XSRF protection when adding external logins private const string XsrfKey = "XsrfId"; private IAuthenticationManager AuthenticationManager { get { return HttpContext.GetOwinContext().Authentication; } } private void AddErrors(IdentityResult result) { foreach (var error in result.Errors) { ModelState.AddModelError("", error); } } private bool HasPassword() { var user = UserManager.FindById(User.Identity.GetUserId()); if (user != null) { return user.PasswordHash != null; } return false; } private bool HasPhoneNumber() { var user = UserManager.FindById(User.Identity.GetUserId()); if (user != null) { return user.PhoneNumber != null; } return false; } public enum ManageMessageId { AddPhoneSuccess, ChangePasswordSuccess, SetTwoFactorSuccess, SetPasswordSuccess, RemoveLoginSuccess, RemovePhoneSuccess, Error } #endregion } }
cristventcode/cristventcode-static
cristventcode-static/Controllers/ManageController.cs
C#
mit
14,142
<?php /* * Copyright 2017 Jack Sleight <http://jacksleight.com/> * This source file is subject to the MIT license that is bundled with this package in the file LICENCE.md. */ use Chalk\Chalk; if (php_sapi_name() != 'cli') { exit("Must be run from the command line\n"); } $init = getcwd() . '/chalk-cli.php'; if (!is_file($init)) { exit("No 'chalk-cli.php' initialization file found in '" . getcwd() . "'\n"); } $app = require_once $init; Chalk::isFrontend(false); if (!isset($_SERVER['argv'][1])) { cli\err("You must specify the module and tool name (module:tool)"); exit; } $parts = explode(':', $_SERVER['argv'][1]); if (count($parts) != 2) { cli\err("You must specify the module and tool name (module:tool)"); exit; } $module = $app->module($parts[0]); if (!isset($module)) { cli\err("Invalid module"); exit; } $params = []; $flags = []; $args = []; foreach (array_slice($_SERVER['argv'], 2) as $arg) { if (preg_match('/^--([\w-]+)=([\w-]+)$/', $arg, $match)) { $params[$match[1]] = $match[2]; } else if (preg_match('/^--([\w-]+)$/', $arg, $match)) { $flags[] = $match[1]; } else { $args[] = $arg; } } $result = $module->execScript('tools', $parts[1], [$args, $flags, $params]); if (!$result) { cli\err("Tool '{$module->name()}:{$parts[1]}' does not exist"); }
jacksleight/chalk
cli/chalk.php
PHP
mit
1,355
package base64 import ( "testing" "github.com/stretchr/testify/assert" ) func must(r interface{}, err error) interface{} { if err != nil { return err } return r } func TestEncode(t *testing.T) { assert.Equal(t, "", must(Encode([]byte("")))) assert.Equal(t, "Zg==", must(Encode([]byte("f")))) assert.Equal(t, "Zm8=", must(Encode([]byte("fo")))) assert.Equal(t, "Zm9v", must(Encode([]byte("foo")))) assert.Equal(t, "Zm9vYg==", must(Encode([]byte("foob")))) assert.Equal(t, "Zm9vYmE=", must(Encode([]byte("fooba")))) assert.Equal(t, "Zm9vYmFy", must(Encode([]byte("foobar")))) assert.Equal(t, "A+B/", must(Encode([]byte{0x03, 0xe0, 0x7f}))) } func TestDecode(t *testing.T) { assert.Equal(t, []byte(""), must(Decode(""))) assert.Equal(t, []byte("f"), must(Decode("Zg=="))) assert.Equal(t, []byte("fo"), must(Decode("Zm8="))) assert.Equal(t, []byte("foo"), must(Decode("Zm9v"))) assert.Equal(t, []byte("foob"), must(Decode("Zm9vYg=="))) assert.Equal(t, []byte("fooba"), must(Decode("Zm9vYmE="))) assert.Equal(t, []byte("foobar"), must(Decode("Zm9vYmFy"))) assert.Equal(t, []byte{0x03, 0xe0, 0x7f}, must(Decode("A+B/"))) assert.Equal(t, []byte{0x03, 0xe0, 0x7f}, must(Decode("A-B_"))) _, err := Decode("b.o.g.u.s") assert.Error(t, err) }
hairyhenderson/gomplate
base64/base64_test.go
GO
mit
1,264
import datetime from sqlalchemy import create_engine, ForeignKey, Column, Integer, String, Text, Date, Table, Boolean from sqlalchemy.orm import sessionmaker, relationship from sqlalchemy.ext.declarative import declarative_base from . import app from flask_login import UserMixin engine = create_engine(app.config["SQLALCHEMY_DATABASE_URI"]) Base = declarative_base() Session = sessionmaker(bind=engine) session = Session() class Fighter(Base): __tablename__ = "fighters" id = Column(Integer, primary_key=True) first_name = Column(String(1024), nullable=False) last_name = Column(String(1024), nullable=False) nickname = Column(String(1024)) gender = Column(String(128), nullable=False) dob = Column(Date) age = Column(Integer) promotion = Column(String(1024), nullable=False) profile_image = Column(String(1024)) right_full = Column(String(1024)) left_full = Column(String(1024)) height = Column(Integer) weight = Column(String(128), nullable=False) win = Column(Integer, nullable=False) loss = Column(Integer, nullable=False) draw = Column(Integer) no_contest = Column(Integer) def as_dictionary(self): fighter = { "id": self.id, "first_name": self.first_name, "last_name": self.last_name, "nickname": self.nickname, "gender": self.gender, "age": self.age, "promotion": self.promotion, "profile_image": self.profile_image, "right_full": self.right_full, "left_full": self.left_full, "height": self.height, "weight": self.weight, "win": self.win, "loss": self.loss, "draw": self.draw, "no_contest": self.no_contest, } return fighter class User(Base, UserMixin): __tablename__ = "users" id = Column(Integer, primary_key=True) email = Column(String(1024), unique=True, nullable=False) password = Column(String(128), nullable=False) user_history = relationship("History", backref="user") class History(Base): __tablename__ = "history" id = Column(Integer, primary_key=True) fight_date = Column(String, nullable=False) has_occured = Column(Boolean, nullable=False) red_corner = Column(String(1024), nullable=False) blue_corner = Column(String(1024), nullable=False) winner = Column(String(1024)) end_round = Column(String, nullable=False) end_time = Column(String, nullable=False) method = Column(String, nullable=False) visible = Column(Boolean, nullable=False) user_id = Column(Integer, ForeignKey('users.id'), nullable=False) def as_dictionary(self): results = { "id": self.id, "fight_date": self.fight_date, "has_occured": self.has_occured, "red_corner": self.red_corner, "blue_corner": self.blue_corner, "winner": self.winner, "end_round": self.end_round, "end_time": self.end_time, "method": self.method, "user_id": self.user_id, } return results class Event(Base): __tablename__ = "events" id = Column(Integer, primary_key=True) event_date = Column(String(256)) base_title = Column(String(1024), nullable=False) title_tag_line = Column(String(1024)) #feature_image = Column(String(1024)) arena = Column(String(1024)) location = Column(String(1024)) event_id = Column(Integer) def as_dictionary(self): event = { "id": self.id, "event_date": self.event_date, "base_title": self.base_title, "title_tag_line": self.title_tag_line, #"feature_image": self.feature_image, "arena": self.arena, "location": self.location, "event_id": self.event_id } return event Base.metadata.create_all(engine)
tydonk/fight_simulator
fight_simulator/database.py
Python
mit
3,978
# encoding: utf-8 require 'devise' require 'devise_ldap_authenticatable/exception' require 'devise_ldap_authenticatable/logger' require 'devise_ldap_authenticatable/ldap/adapter' require 'devise_ldap_authenticatable/ldap/attribute_mapper' require 'devise_ldap_authenticatable/ldap/connection' # Get ldap information from config/ldap.yml now module Devise # Allow logging mattr_accessor :ldap_logger @@ldap_logger = true # Add valid users to database mattr_accessor :ldap_create_user @@ldap_create_user = false # A path to YAML config file or a Proc that returns a # configuration hash mattr_accessor :ldap_config # @@ldap_config = "#{Rails.root}/config/ldap.yml" mattr_accessor :ldap_update_password @@ldap_update_password = true mattr_accessor :ldap_check_group_membership @@ldap_check_group_membership = false mattr_accessor :ldap_check_attributes @@ldap_check_role_attribute = false mattr_accessor :ldap_use_admin_to_bind @@ldap_use_admin_to_bind = false mattr_accessor :ldap_auth_username_builder @@ldap_auth_username_builder = Proc.new() {|attribute, login, ldap| "#{attribute}=#{login},#{ldap.base}" } mattr_accessor :ldap_ad_group_check @@ldap_ad_group_check = false end # Add ldap_authenticatable strategy to defaults. # Devise.add_module(:ldap_authenticatable, :route => :session, ## This will add the routes, rather than in the routes.rb :strategy => true, :controller => :sessions, :model => 'devise_ldap_authenticatable/model')
cgservices/devise_ldap_authenticatable
lib/devise_ldap_authenticatable.rb
Ruby
mit
1,584
<?php namespace App\Providers; use Illuminate\Support\ServiceProvider; use Illuminate\Support\Facades\Schema; class AppServiceProvider extends ServiceProvider { /** * Bootstrap any application services. * * @return void */ public function boot() { \URL::forceScheme('http'); Schema::defaultStringLength(191); } /** * Register any application services. * * @return void */ public function register() { // } }
RamiroAldana/ProyectoTresFronteras
app/Providers/AppServiceProvider.php
PHP
mit
506
#include "page.h" using namespace AhoViewer::Booru; #include "curler.h" #include "image.h" #include "settings.h" #include "site.h" #include "threadpool.h" #include <glibmm/i18n.h> #include <iostream> #define RETRY_COUNT 5 void Page::CellRendererThumbnail::get_preferred_width_vfunc(Gtk::Widget& widget, int& minimum_width, int& natural_width) const { // Item padding is applied to right and left auto width{ widget.get_width() / (widget.get_width() / (Image::BooruThumbnailSize + IconViewItemPadding * 2)) }; minimum_width = width - IconViewItemPadding * 2; natural_width = width - IconViewItemPadding * 2; } Page::Page() : Gtk::ScrolledWindow{}, m_PopupMenu{ nullptr }, m_IconView{ Gtk::make_managed<IconView>() }, m_Tab{ Gtk::make_managed<Gtk::EventBox>() }, m_TabIcon{ Gtk::make_managed<Gtk::Image>(Gtk::Stock::NEW, Gtk::ICON_SIZE_MENU) }, m_TabLabel{ Gtk::make_managed<Gtk::Label>(_("New Tab")) }, m_MenuLabel{ Gtk::make_managed<Gtk::Label>(_("New Tab")) }, m_TabButton{ Gtk::make_managed<Gtk::Button>() }, m_ImageList{ std::make_shared<ImageList>(this) }, m_SaveCancel{ Gio::Cancellable::create() } { set_policy(Gtk::POLICY_NEVER, Gtk::POLICY_AUTOMATIC); set_shadow_type(Gtk::SHADOW_ETCHED_IN); // Create page tab {{{ m_TabButton->add(*(Gtk::make_managed<Gtk::Image>(Gtk::Stock::CLOSE, Gtk::ICON_SIZE_MENU))); m_TabButton->property_relief() = Gtk::RELIEF_NONE; m_TabButton->set_focus_on_click(false); m_TabButton->set_tooltip_text(_("Close Tab")); m_TabButton->signal_clicked().connect([&]() { m_SignalClosed(this); }); m_TabLabel->set_alignment(0.0, 0.5); m_TabLabel->set_ellipsize(Pango::ELLIPSIZE_END); m_MenuLabel->set_alignment(0.0, 0.5); m_MenuLabel->set_ellipsize(Pango::ELLIPSIZE_END); auto* hbox{ Gtk::make_managed<Gtk::HBox>() }; hbox->pack_start(*m_TabIcon, false, false); hbox->pack_start(*m_TabLabel, true, true, 2); hbox->pack_start(*m_TabButton, false, false); hbox->show_all(); m_Tab->set_visible_window(false); m_Tab->add(*hbox); m_Tab->signal_button_release_event().connect( sigc::mem_fun(*this, &Page::on_tab_button_release_event)); // }}} m_ScrollConn = get_vadjustment()->signal_value_changed().connect( sigc::mem_fun(*this, &Page::on_value_changed)); m_IconView->set_column_spacing(0); m_IconView->set_row_spacing(0); m_IconView->set_margin(0); m_IconView->set_item_padding(IconViewItemPadding); m_IconView->set_model(m_ListStore); m_IconView->set_selection_mode(Gtk::SELECTION_BROWSE); m_IconView->signal_selection_changed().connect( sigc::mem_fun(*this, &Page::on_selection_changed)); m_IconView->signal_button_press_event().connect( sigc::mem_fun(*this, &Page::on_button_press_event)); // Workaround to have fully centered pixbufs auto* cell{ Gtk::make_managed<CellRendererThumbnail>() }; m_IconView->pack_start(*cell); m_IconView->add_attribute(cell->property_pixbuf(), m_Columns.pixbuf); m_SignalPostsDownloaded.connect(sigc::mem_fun(*this, &Page::on_posts_downloaded)); m_SignalSaveProgressDisp.connect([&]() { m_SignalSaveProgress(this); }); // Check if next page should be loaded after current finishes m_ImageList->signal_thumbnails_loaded().connect([&]() { on_selection_changed(); if (!m_KeepAligned) on_value_changed(); }); add(*m_IconView); show_all(); } Page::~Page() { m_Curler.cancel(); if (m_GetPostsThread.joinable()) m_GetPostsThread.join(); cancel_save(); m_ListStore->clear(); } void Page::set_pixbuf(const size_t index, const Glib::RefPtr<Gdk::Pixbuf>& pixbuf) { m_ScrollConn.block(); ImageList::Widget::set_pixbuf(index, pixbuf); while (Glib::MainContext::get_default()->pending()) Glib::MainContext::get_default()->iteration(true); m_ScrollConn.unblock(); // Only keep the thumbnail aligned if the user has not scrolled // and the thumbnail is most likely still being loaded if (m_KeepAligned && m_ImageList->get_index() >= index) scroll_to_selected(); } void Page::set_selected(const size_t index) { Gtk::TreePath path{ std::to_string(index) }; m_IconView->select_path(path); scroll_to_selected(); } void Page::scroll_to_selected() { std::vector<Gtk::TreePath> paths{ m_IconView->get_selected_items() }; if (!paths.empty()) { Gtk::TreePath path{ paths[0] }; if (path) { m_ScrollConn.block(); m_IconView->scroll_to_path(path, false, 0, 0); m_ScrollConn.unblock(); } } } void Page::search(const std::shared_ptr<Site>& site) { if (!ask_cancel_save()) return; m_Curler.cancel(); cancel_save(); m_ImageList->clear(); if (m_GetPostsThread.joinable()) m_GetPostsThread.join(); m_Site = site; m_Page = 1; m_LastPage = false; m_SearchTags = m_Tags; // Trim leading and trailing whitespace for tab label // and m_SearchTags which is used to display tags in other places if (!m_SearchTags.empty()) { size_t f{ m_SearchTags.find_first_not_of(' ') }, l{ m_SearchTags.find_last_not_of(' ') }; m_SearchTags = f == std::string::npos ? "" : m_SearchTags.substr(f, l - f + 1); } std::string label{ m_Site->get_name() + (m_SearchTags.empty() ? "" : " - " + m_SearchTags) }; m_TabLabel->set_text(label); m_MenuLabel->set_text(label); m_TabIcon->set(m_Site->get_icon_pixbuf()); m_Curler.set_share_handle(m_Site->get_share_handle()); m_Curler.set_referer(m_Site->get_url()); get_posts(); } void Page::save_image(const std::string& path, const std::shared_ptr<Image>& img) { m_SaveCancel->reset(); if (m_SaveImagesThread.joinable()) m_SaveImagesThread.join(); m_Saving = true; m_SaveImagesThread = std::thread([&, path, img]() { img->save(path); m_Saving = false; }); } void Page::save_images(const std::string& path) { m_SaveCancel->reset(); if (m_SaveImagesThread.joinable()) m_SaveImagesThread.join(); m_Saving = true; m_SaveImagesCurrent = 0; m_SaveImagesTotal = m_ImageList->get_vector_size(); m_SaveImagesThread = std::thread([&, path]() { ThreadPool pool; for (const std::shared_ptr<AhoViewer::Image>& img : *m_ImageList) { pool.push([&, path, img]() { if (m_SaveCancel->is_cancelled()) return; std::shared_ptr<Image> bimage = std::static_pointer_cast<Image>(img); bimage->save( Glib::build_filename(path, Glib::path_get_basename(bimage->get_filename()))); ++m_SaveImagesCurrent; if (!m_SaveCancel->is_cancelled()) m_SignalSaveProgressDisp(); }); } m_SignalSaveProgressDisp(); pool.wait(); m_Saving = false; }); } // Returns true if we want to cancel or we're not saving bool Page::ask_cancel_save() { if (!m_Saving) return true; auto* window = static_cast<Gtk::Window*>(get_toplevel()); Gtk::MessageDialog dialog(*window, _("Are you sure that you want to stop saving images?"), false, Gtk::MESSAGE_QUESTION, Gtk::BUTTONS_YES_NO, true); dialog.set_secondary_text(_("Closing this tab will stop the save operation.")); return dialog.run() == Gtk::RESPONSE_YES; } void Page::cancel_save() { m_SaveCancel->cancel(); for (const std::shared_ptr<AhoViewer::Image>& img : *m_ImageList) { std::shared_ptr<Image> bimage{ std::static_pointer_cast<Image>(img) }; bimage->cancel_download(); } if (m_SaveImagesThread.joinable()) m_SaveImagesThread.join(); m_Saving = false; } void Page::get_posts() { std::string tags{ m_SearchTags }; m_KeepAligned = true; if (m_Tags.find("rating:") == std::string::npos) { if (Settings.get_booru_max_rating() == Rating::SAFE) { tags += " rating:safe"; } else if (Settings.get_booru_max_rating() == Rating::QUESTIONABLE) { tags += " -rating:explicit"; } } tags = m_Curler.escape(tags); m_GetPostsThread = std::thread([&, tags]() { // DanbooruV2 doesn't give the post count with the posts // Get it from thier counts api if (m_Page == 1 && m_Site->get_type() == Type::DANBOORU_V2) { m_Curler.set_url(m_Site->get_url() + "/counts/posts.xml?tags=" + tags); if (m_Curler.perform()) { try { xml::Document doc{ reinterpret_cast<char*>(m_Curler.get_data()), m_Curler.get_data_size() }; if (doc.get_n_nodes()) { std::string posts_count{ doc.get_children()[0].get_value() }; // Usually when you use a wildcard operator danbooru's count api will return // a blank value here (blank but contains some whitespace and newlines) if (posts_count.find_first_not_of(" \n\r") != std::string::npos) m_PostsCount = std::stoul(posts_count); } } catch (const std::runtime_error& e) { std::cerr << e.what() << std::endl << m_Curler.get_data() << std::endl; } catch (const std::invalid_argument& e) { std::cerr << e.what() << std::endl << "Failed to parse posts_count" << std::endl; } } else if (m_Curler.is_cancelled()) { return; } } m_Curler.set_url(m_Site->get_posts_url(tags, m_Page)); if (m_Site->get_type() == Type::GELBOORU) m_Curler.set_cookie_file(m_Site->get_cookie()); else m_Curler.set_http_auth(m_Site->get_username(), m_Site->get_password()); bool success{ false }; size_t retry_count{ 0 }; do { success = m_Curler.perform(); if (success) { auto [posts, posts_count, error]{ m_Site->parse_post_data( m_Curler.get_data(), m_Curler.get_data_size()) }; m_Posts = std::move(posts); if (posts_count > 0) m_PostsCount = posts_count; m_PostsError = error; } } while (!m_Curler.is_cancelled() && !success && ++retry_count < RETRY_COUNT); if (!success && !m_Curler.is_cancelled()) { std::cerr << "Error while downloading posts on " << m_Curler.get_url() << std::endl << " " << m_Curler.get_error() << std::endl; m_PostsError = Glib::ustring::compose(_("Failed to download posts on %1"), m_Site->get_name()); } if (!m_Curler.is_cancelled()) m_SignalPostsDownloaded(); }); m_SignalPostsDownloadStarted(); } bool Page::get_next_page() { // Do not fetch the next page if this is the last // or the current page is still loading if (m_LastPage || m_GetPostsThread.joinable() || m_ImageList->is_loading()) return false; if (!m_Saving) { ++m_Page; get_posts(); return false; } else if (!m_GetNextPageConn) { m_GetNextPageConn = Glib::signal_timeout().connect(sigc::mem_fun(*this, &Page::get_next_page), 1000); } return true; } // Adds the downloaded posts to the image list. void Page::on_posts_downloaded() { if (!m_PostsError.empty()) { m_SignalDownloadError(m_PostsError); } // 401 = Unauthorized else if (m_Curler.get_response_code() == 401) { auto e{ Glib::ustring::compose( _("Failed to login as %1 on %2"), m_Site->get_username(), m_Site->get_name()) }; m_SignalDownloadError(e); } else { auto n_posts{ m_Posts.size() }; if (!m_Posts.empty()) { auto size_before{ m_ImageList->get_vector_size() }; m_ImageList->load(m_Posts, m_PostsCount); // Number of posts that actually got added to the image list // ie supported file types n_posts = m_ImageList->get_vector_size() - size_before; } // No posts added to the imagelist if (n_posts == 0) { if (m_Page == 1) m_SignalDownloadError(_("No results found")); else m_SignalOnLastPage(); m_LastPage = true; } } m_Curler.clear(); m_Posts.clear(); m_GetPostsThread.join(); } void Page::on_selection_changed() { std::vector<Gtk::TreePath> paths{ m_IconView->get_selected_items() }; if (!paths.empty()) { Gtk::TreePath path{ paths[0] }; if (path) { size_t index = path[0]; if (index + Settings.get_int("CacheSize") >= m_ImageList->get_vector_size() - 1) get_next_page(); m_SignalSelectedChanged(index); } } } // Vertical scrollbar value changed void Page::on_value_changed() { double value = get_vadjustment()->get_value(), limit = get_vadjustment()->get_upper() - get_vadjustment()->get_page_size() - get_vadjustment()->get_step_increment() * 3; m_KeepAligned = false; if (value >= limit) get_next_page(); } bool Page::on_button_press_event(GdkEventButton* e) { if (e->type == GDK_BUTTON_PRESS && e->button == 3) { Gtk::TreePath path = m_IconView->get_path_at_pos(e->x, e->y); if (path) { m_IconView->select_path(path); m_IconView->scroll_to_path(path, false, 0, 0); m_PopupMenu->popup_at_pointer((GdkEvent*)e); return true; } } return false; } bool Page::on_tab_button_release_event(GdkEventButton* e) { if (e->type == GDK_BUTTON_RELEASE && e->button == 2) m_SignalClosed(this); return false; }
ahodesuka/ahoviewer
src/booru/page.cc
C++
mit
14,716
/* * Copyright (c) 2012, 2013, Oracle and/or its affiliates. All rights reserved. * ORACLE PROPRIETARY/CONFIDENTIAL. Use is subject to license terms. * * * * * * * * * * * * * * * * * * * * */ package javan.util.function; /** * Represents an operation upon two {@code int}-valued operands and producing an * {@code int}-valued result. This is the primitive type specialization of * {@link BinaryOperator} for {@code int}. * * <p>This is a <a href="package-summary.html">functional interface</a> * whose functional method is {@link #applyAsInt(int, int)}. * * @see BinaryOperator * @see IntUnaryOperator * @since 1.8 */ @FunctionalInterface public interface IntBinaryOperator { /** * Applies this operator to the given operands. * * @param left the first operand * @param right the second operand * @return the operator result */ int applyAsInt(int left, int right); }
emacslisp/Java
JavaN/src/javan/util/function/IntBinaryOperator.java
Java
mit
944
#! /usr/bin/env python # -*- coding: utf-8 -*- """Pyramidal bidirectional LSTM encoder.""" from __future__ import absolute_import from __future__ import division from __future__ import print_function import tensorflow as tf class PyramidBLSTMEncoder(object): """Pyramidal bidirectional LSTM Encoder. Args: num_units (int): the number of units in each layer num_layers (int): the number of layers lstm_impl (string, optional): BasicLSTMCell or LSTMCell or LSTMBlockCell or LSTMBlockFusedCell or CudnnLSTM. Choose the background implementation of tensorflow. Default is LSTMBlockCell. use_peephole (bool, optional): if True, use peephole parameter_init (float, optional): the range of uniform distribution to initialize weight parameters (>= 0) clip_activation (float, optional): the range of activation clipping (> 0) # num_proj (int, optional): the number of nodes in the projection layer concat (bool, optional): name (string, optional): the name of encoder """ def __init__(self, num_units, num_layers, lstm_impl, use_peephole, parameter_init, clip_activation, num_proj, concat=False, name='pblstm_encoder'): assert num_proj != 0 assert num_units % 2 == 0, 'num_unit should be even number.' self.num_units = num_units self.num_proj = None self.num_layers = num_layers self.lstm_impl = lstm_impl self.use_peephole = use_peephole self.parameter_init = parameter_init self.clip_activation = clip_activation self.name = name def _build(self, inputs, inputs_seq_len, keep_prob, is_training): """Construct Pyramidal Bidirectional LSTM encoder. Args: inputs (placeholder): A tensor of size`[B, T, input_size]` inputs_seq_len (placeholder): A tensor of size` [B]` keep_prob (placeholder, float): A probability to keep nodes in the hidden-hidden connection is_training (bool): Returns: outputs: Encoder states, a tensor of size `[T, B, num_units (num_proj)]` final_state: A final hidden state of the encoder """ initializer = tf.random_uniform_initializer( minval=-self.parameter_init, maxval=self.parameter_init) # Hidden layers outputs = inputs for i_layer in range(1, self.num_layers + 1, 1): with tf.variable_scope('pblstm_hidden' + str(i_layer), initializer=initializer) as scope: lstm_fw = tf.contrib.rnn.LSTMCell( self.num_units, use_peepholes=self.use_peephole, cell_clip=self.clip_activation, initializer=initializer, num_proj=None, forget_bias=1.0, state_is_tuple=True) lstm_bw = tf.contrib.rnn.LSTMCell( self.num_units, use_peepholes=self.use_peephole, cell_clip=self.clip_activation, initializer=initializer, num_proj=self.num_proj, forget_bias=1.0, state_is_tuple=True) # Dropout for the hidden-hidden connections lstm_fw = tf.contrib.rnn.DropoutWrapper( lstm_fw, output_keep_prob=keep_prob) lstm_bw = tf.contrib.rnn.DropoutWrapper( lstm_bw, output_keep_prob=keep_prob) if i_layer > 0: # Convert to time-major: `[T, B, input_size]` outputs = tf.transpose(outputs, (1, 0, 2)) max_time = tf.shape(outputs)[0] max_time_half = tf.floor(max_time / 2) + 1 # Apply concat_fn to each tensor in outputs along # dimension 0 (times-axis) i_time = tf.constant(0) final_time, outputs, tensor_list = tf.while_loop( cond=lambda t, hidden, tensor_list: t < max_time, body=lambda t, hidden, tensor_list: self._concat_fn( t, hidden, tensor_list), loop_vars=[i_time, outputs, tf.Variable([])], shape_invariants=[i_time.get_shape(), outputs.get_shape(), tf.TensorShape([None])]) outputs = tf.stack(tensor_list, axis=0) inputs_seq_len = tf.cast(tf.floor( tf.cast(inputs_seq_len, tf.float32) / 2), tf.int32) # Transpose to `[batch_size, time, input_size]` outputs = tf.transpose(outputs, (1, 0, 2)) (outputs_fw, outputs_bw), final_state = tf.nn.bidirectional_dynamic_rnn( cell_fw=lstm_fw, cell_bw=lstm_bw, inputs=outputs, sequence_length=inputs_seq_len, dtype=tf.float32, time_major=False, scope=scope) # NOTE: initial states are zero states by default # Concatenate each direction outputs = tf.concat(axis=2, values=[outputs_fw, outputs_bw]) return outputs, final_state def _concat_fn(self, current_time, x, tensor_list): """Concatenate each 2 time steps to reduce time resolution. Args: current_time: The current timestep x: A tensor of size `[max_time, batch_size, feature_dim]` result: A tensor of size `[t, batch_size, feature_dim * 2]` Returns: current_time: current_time + 2 x: A tensor of size `[max_time, batch_size, feature_dim]` result: A tensor of size `[t + 1, batch_size, feature_dim * 2]` """ print(tensor_list) print(current_time) print('-----') batch_size = tf.shape(x)[1] feature_dim = x.get_shape().as_list()[2] # Concat features in 2 timesteps concat_x = tf.concat( axis=0, values=[tf.reshape(x[current_time], shape=[1, batch_size, feature_dim]), tf.reshape(x[current_time + 1], shape=[1, batch_size, feature_dim])]) # Reshape to `[1, batch_size, feature_dim * 2]` concat_x = tf.reshape(concat_x, shape=[1, batch_size, feature_dim * 2]) tensor_list = tf.concat(axis=0, values=[tensor_list, [concat_x]]) # Skip 2 timesteps current_time += 2 return current_time, x, tensor_list
hirofumi0810/tensorflow_end2end_speech_recognition
models/encoders/core/pyramidal_blstm.py
Python
mit
7,080
<?php namespace Osiset\ShopifyApp\Objects\Enums; use Funeralzone\ValueObjects\Enums\EnumTrait; use Funeralzone\ValueObjects\ValueObject; /** * API types for charges. * * @method static ChargeType RECURRING() * @method static ChargeType CHARGE() * @method static ChargeType ONETIME() * @method static ChargeType USAGE() * @method static ChargeType CREDIT() */ final class ChargeType implements ValueObject { use EnumTrait; /** * Charge: Recurring. * * @var int */ public const RECURRING = 1; /** * Charge: One-time. * * @var int */ public const CHARGE = 2; /** * Charge: Alias for onetime. * * @var int */ public const ONETIME = 2; /** * Charge: Usage. * * @var int */ public const USAGE = 3; /** * Charge: Credit. * * @var int */ public const CREDIT = 4; }
ohmybrew/laravel-shopify
src/ShopifyApp/Objects/Enums/ChargeType.php
PHP
mit
917
#pragma once #include <memory> #include <utility> #include <vector> #include "Runtime/CSaveWorld.hpp" #include "Runtime/CToken.hpp" #include "Runtime/rstl.hpp" #include "Runtime/MP1/CPauseScreenBase.hpp" namespace metaforce { class CPlayerState; class CScannableObjectInfo; class CStringTable; } // namespace metaforce namespace metaforce::MP1 { class CArtifactDoll; class CLogBookScreen : public CPauseScreenBase { rstl::reserved_vector<std::vector<std::pair<CAssetId, bool>>, 5> x19c_scanCompletes; std::vector<std::pair<TCachedToken<CScannableObjectInfo>, TCachedToken<CStringTable>>> x1f0_curViewScans; rstl::reserved_vector<std::vector<std::pair<TLockedToken<CScannableObjectInfo>, TLockedToken<CStringTable>>>, 5> x200_viewScans; float x254_viewInterp = 0.f; std::unique_ptr<CArtifactDoll> x258_artifactDoll; enum class ELeavePauseState { InPause = 0, LeavingPause = 1, LeftPause = 2 } x25c_leavePauseState = ELeavePauseState::InPause; bool x260_24_loaded : 1 = false; bool x260_25_inTextScroll : 1 = false; bool x260_26_exitTextScroll : 1 = false; void InitializeLogBook(); void UpdateRightTitles(); void PumpArticleLoad(); bool IsScanCategoryReady(CSaveWorld::EScanCategory category) const; void UpdateBodyText(); void UpdateBodyImagesAndText(); int NextSurroundingArticleIndex(int cur) const; bool IsArtifactCategorySelected() const; int GetSelectedArtifactHeadScanIndex() const; static bool IsScanComplete(CSaveWorld::EScanCategory category, CAssetId scan, const CPlayerState& playerState); public: CLogBookScreen(const CStateManager& mgr, CGuiFrame& frame, const CStringTable& pauseStrg); ~CLogBookScreen() override; bool InputDisabled() const override; void TransitioningAway() override; void Update(float dt, CRandom16& rand, CArchitectureQueue& archQueue) override; void Touch() override; void ProcessControllerInput(const CFinalInput& input) override; void Draw(float transInterp, float totalAlpha, float yOff) override; bool VReady() const override; void VActivate() override; void RightTableSelectionChanged(int oldSel, int newSel) override; void ChangedMode(EMode oldMode) override; void UpdateRightTable() override; bool ShouldLeftTableAdvance() const override; bool ShouldRightTableAdvance() const override; u32 GetRightTableCount() const override; }; } // namespace metaforce::MP1
AxioDL/PathShagged
Runtime/MP1/CLogBookScreen.hpp
C++
mit
2,401
const router = require('express').Router(); const db1 = require('../db'); // GET - Get All Students Info (Admin) // response: // [] students: // account_id: uuid // user_id: uuid // first_name: string // last_name: string // hometown: string // college: string // major: string // gender: string // birthdate: date // email: string // date_created: timestamp // image_path: string // bio: string router.get('/student/all', (req, res) => { db1.any(` SELECT account_id, user_id, first_name, last_name, hometown, college, major, gender, bio, birthdate, email, date_created, image_path FROM students natural join account natural join images`) .then(function(data) { // Send All Students Information console.log('Success: Admin Get All Students Information'); res.json({students: data}) }) .catch(function(error) { console.log(error); return res.status(400).send('Error: Problem executing Query'); }); }); // GET - Get All Associations Info (Admin) // response: // [] associations: // account_id: uuid // association_id: uuid // association_name: string // initials: string // email: string // page_link: string // image_path: string // bio: string // date_created: timestamp // room: string // building: string // city: string router.get('/association/all', (req, res) => { db1.any(` SELECT account_id, association_id, association_name, initials, page_link, image_path, email, bio, room, building, city, date_created FROM associations natural join account natural join location natural join images`) .then(function(data) { // Send All Associations Information console.log('Success: Admin Get All Associations Information'); res.json({associations: data}); }) .catch(function(error) { console.log(error); return res.status(400).send('Error: Problem executing Query'); }); }); // GET - Get All Events Info (Admin) // response: // [] events // event_id: id // event_name: string // is_live: bool (yes/no) // registration_link: string // start_date: date // end_date: date // start_time: time // end_time: time // room: string // building: string // city: string // image_path: string // time_stamp: timestamp router.get('/event/all', (req, res) => { db1.any(` SELECT event_id, event_name, is_live, registration_link, start_date, end_date, start_time, end_time, room, building, city, image_path, time_stamp FROM events natural join images natural join location`) .then(function(data) { // Send All Events Information console.log('Success: Admin Get All Events Information'); res.json({events: data}); }) .catch(function(error) { console.log(error); return res.status(400).send('Error: Problem executing Query'); }); }); module.exports = router;
mario2904/ICOM5016-Project
api/admin.js
JavaScript
mit
3,056
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace TestRunner.Asserts { public class SuperIntTestLibrary { private int expectedValue; private bool denyEverything; internal SuperIntTestLibrary(int startValue) : this(startValue, false) { } internal SuperIntTestLibrary(int startValue, bool denyEverything) { this.expectedValue = startValue; this.denyEverything = denyEverything; } public void Eq(int compareTo) { MakeCondition(expectedValue != compareTo); } public void IsGreater(int compareTo) { MakeCondition(expectedValue <= compareTo); } public SuperIntTestLibrary Not() { return new SuperIntTestLibrary(expectedValue, true); } private void MakeCondition(bool condition) { if (denyEverything) condition = !condition; if (condition) { throw new ExpectationFailedExceptin(); } } } }
mironiasty/Stuff
TestRunner/TestRunner/Asserts/SuperIntTestLibrary.cs
C#
mit
1,231
<html> <head> <title> When the lights went out on Enron </title> <meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1"> <?php include "../../legacy-includes/Script.htmlf" ?> </head> <body bgcolor="#FFFFCC" text="000000" link="990000" vlink="660000" alink="003366" leftmargin="0" topmargin="0"> <table width="744" cellspacing="0" cellpadding="0" border="0"> <tr><td width="474"><a name="Top"></a><?php include "../../legacy-includes/TopLogo.htmlf" ?></td> <td width="270"><?php include "../../legacy-includes/TopAd.htmlf" ?> </td></tr></table> <table width="744" cellspacing="0" cellpadding="0" border="0"> <tr><td width="18" bgcolor="FFCC66"></td> <td width="108" bgcolor="FFCC66" valign=top><?php include "../../legacy-includes/LeftButtons.htmlf" ?></td> <td width="18"></td> <td width="480" valign="top"> <?php include "../../legacy-includes/BodyInsert.htmlf" ?> <P><font face="Arial, Helvetica, sans-serif" size="2"><b>WHAT WE THINK</b></font><BR> <font face="Times New Roman, Times, serif" size="5"><b>When the lights went out on Enron</b></font></P> <p><font face="Arial, Helvetica, sans-serif" size="2">December 7, 2001 | Page 3</font></p> <font face="Times New Roman, Times, serif" size="3"><P>THE SPECTACULAR collapse of the giant energy company Enron last month was a fitting conclusion to the hype and lies about the 1990s "miracle" economy.</P> <P>With federal investigators looking into a multibillion-dollar accounting scandal, Enron, the seventh-largest corporation in the U.S. last year, declared bankruptcy at the beginning of December. No one knows what the full impact will be on the economy.</P> <P>So much for one of the great "success stories" of the 1990s--an unknown, medium-scale natural gas producer transformed into the toast of Wall Street.</P> <P>Enron became a corporate giant by exploiting deregulation--the dismantling of government restrictions, supposedly to allow the free market to work its magic. What deregulation really did was line the bosses' pockets.</P> <P>As consumer rights advocate Doug Heller explained, Enron specialized in taking over a system run by the government--like electricity transmission--and raking in profits "out of nothing, simply by adding cost to the product en route."</P> <P>California's disastrous 1996 deregulation law was a classic example. The state's utility companies were required to sell power plants and buy electricity on the open market--from middlemen like Enron that jacked up prices to staggering highs.</P> <P>The scam depended on political connections. In particular, Enron CEO Ken Lay was a big booster of fellow Texan George W. Bush. When his boy took over the White House, Lay got veto power over administration energy policy.</P> <P>But the company's success also depended on sophisticated accounting practices--otherwise known as fraud. To keep its profit statements looking good, Enron hid billions upon billions in debt. Wall Street investors and even financial auditors tolerated the company's incomprehensible records as long as the profits kept rolling in.</P> <P>But when the scale of the swindle began to emerge recently, Enron's stock price plummeted. Lay and his boardroom buddies got their money out in time and remain multimillionaires. But Enron workers got the shaft--their retirement plans are locked up in now worthless company stock.</P> <P>Government investigators may indict a few executives for wrongdoing. But as <I>Salon</I> magazine columnist Andrew Leonard said, the free-marketeers will keep claiming that Enron was a bad apple and its meltdown was "exceptional."</P> <P>"Come on," Leonard wrote. "What could possibly be more business as usual than high-ranking executives cashing out at the top of the market, as Lay did, while employees are left holding the bag?"</P> <P>Enron's collapse shows that the only thing "miraculous" about the "miracle" economy was the obscene wealth of the bosses.</P> <?php include "../../legacy-includes/BottomNavLinks.htmlf" ?> <td width="12"></td> <td width="108" valign="top"> <?php include "../../legacy-includes/RightAdFolder.htmlf" ?> </td> </tr> </table> </body> </html>
ISO-tech/sw-d8
web/2001/386/386_03_Enron.php
PHP
mit
4,151
module Nantoka VERSION = "0.0.1" end
dtan4/nantoka
lib/nantoka/version.rb
Ruby
mit
39
using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; // General Information about an assembly is controlled through the following // set of attributes. Change these attribute values to modify the information // associated with an assembly. [assembly: AssemblyTitle("DbUp.Postgresql")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("DbUp.Postgresql")] [assembly: AssemblyCopyright("Copyright © 2014")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. [assembly: ComVisible(false)] // The following GUID is for the ID of the typelib if this project is exposed to COM [assembly: Guid("5ddc04cc-0bd3-421e-9ae4-9fd0e4f4ef04")] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Build and Revision Numbers // by using the '*' as shown below: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("1.0.0.0")] [assembly: AssemblyFileVersion("1.0.0.0")]
JakeGinnivan/DbUp
src/DbUp.Postgresql/Properties/AssemblyInfo.cs
C#
mit
1,406
module Prefixfree module Rails VERSION = "0.0.1" end end
sijokg/prefixfree-rails
lib/prefixfree/rails/version.rb
Ruby
mit
65
import numpy as np import pandas as pd arts = pd.DataFrame() # 1. Clean the dates so you only see numbers by using string manipulations arts["execution_date"] = arts["execution_date"].str.findall(r"([0-9]+)").str[0] arts["execution_date"] = arts["execution_date"].astype(float) arts.head() # 1. If a year is lower than 100, then is referred to 1900. For example, 78 is actually 1978, and that needs to be fixed too. arts["execution_date"] = arts["execution_date"].apply(lambda x: 1900 + x if x < 100 else x) arts.head() # 2. Get the average execution year per artist. arts.groupby("artist_name").mean().head() # 3. Get the average execution year per category. arts.groupby("category").mean().head() # 4. Get the number of artworks per artist. Which artist is the most prolific? artworks_by_artist = arts.groupby("artist_name")[["title"]].aggregate(np.count_nonzero) artworks_by_artist.sort("title", ascending=False).head() # 5. Get the number of artworks per category. Which category has the highest number? artworks_by_category = arts.groupby("category")[["title"]].aggregate(np.count_nonzero) artworks_by_category.sort("title", ascending=False).head() # 6. Get the average length of artworks titles per category and artist. arts['title_length'] = arts['title'].str.len() length_by_category = arts.groupby("category")[["title_length"]].aggregate(np.mean) length_by_category.sort("title_length", ascending=False).head() # 6. Get the year with the highest production. artworks_by_year = arts.groupby("execution_date")[["title"]].aggregate(np.count_nonzero) artworks_by_year.sort("title", ascending=False).head() # 8. Get the approximate period of production for each artist. If an artist painted from 1970 to 1990, the period is 20. period_min = arts.groupby("artist_name")[['execution_date']].aggregate(np.min) period_max = arts.groupby("artist_name")[['execution_date']].aggregate(np.max) (period_max - period_min).sort("execution_date", ascending=False).head()
versae/DH2304
data/arts2.py
Python
mit
1,974
<?php return array ( 'id' => 'tianyu_ktouchv908_ver1_subua', 'fallback' => 'tianyu_ktouchv908_ver1', 'capabilities' => array ( ), );
cuckata23/wurfl-data
data/tianyu_ktouchv908_ver1_subua.php
PHP
mit
144
// This is an open source non-commercial project. Dear PVS-Studio, please check it. // PVS-Studio Static Code Analyzer for C, C++ and C#: http://www.viva64.com /* PrefixInfo.cs -- * Ars Magna project, http://arsmagna.ru * ------------------------------------------------------- * Status: poor */ #region Using directives using System; using System.Collections.Concurrent; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Diagnostics; using System.Drawing; using System.IO; using System.Linq; using System.Reflection; using System.Text; using System.Threading.Tasks; using System.Xml.Serialization; using AM; using AM.Collections; using AM.IO; using AM.Runtime; using CodeJam; using JetBrains.Annotations; using ManagedIrbis; using ManagedIrbis.Batch; using ManagedIrbis.Infrastructure.Commands; using ManagedIrbis.Mapping; using ManagedIrbis.Readers; using Newtonsoft.Json; using CM = System.Configuration.ConfigurationManager; #endregion namespace WriteOffER { /// <summary> /// /// </summary> public class PrefixInfo { /// <summary> /// /// </summary> public string Prefix { get; set; } /// <summary> /// /// </summary> public string Description { get; set; } /// <inheritdoc cref="object.ToString"/> public override string ToString() { return Description; } } }
amironov73/ManagedIrbis
Source/Classic/Apps/WriteOffER/Source/PrefixInfo.cs
C#
mit
1,463
using System; using System.Collections.Generic; using System.Linq; using System.Security.Claims; using System.Threading.Tasks; using Microsoft.AspNet.Identity; using Microsoft.AspNet.Identity.EntityFramework; using Microsoft.AspNet.Identity.Owin; using Microsoft.Owin.Security; using Microsoft.Owin.Security.Cookies; using Microsoft.Owin.Security.OAuth; using TsAngular2.Models; namespace TsAngular2.Providers { public class ApplicationOAuthProvider : OAuthAuthorizationServerProvider { private readonly string _publicClientId; public ApplicationOAuthProvider(string publicClientId) { if (publicClientId == null) { throw new ArgumentNullException("publicClientId"); } _publicClientId = publicClientId; } public override async Task GrantResourceOwnerCredentials(OAuthGrantResourceOwnerCredentialsContext context) { var userManager = context.OwinContext.GetUserManager<ApplicationUserManager>(); ApplicationUser user = await userManager.FindAsync(context.UserName, context.Password); if (user == null) { context.SetError("invalid_grant", "The user name or password is incorrect."); return; } ClaimsIdentity oAuthIdentity = await user.GenerateUserIdentityAsync(userManager, OAuthDefaults.AuthenticationType); ClaimsIdentity cookiesIdentity = await user.GenerateUserIdentityAsync(userManager, CookieAuthenticationDefaults.AuthenticationType); AuthenticationProperties properties = CreateProperties(user.UserName); AuthenticationTicket ticket = new AuthenticationTicket(oAuthIdentity, properties); context.Validated(ticket); context.Request.Context.Authentication.SignIn(cookiesIdentity); } public override Task TokenEndpoint(OAuthTokenEndpointContext context) { foreach (KeyValuePair<string, string> property in context.Properties.Dictionary) { context.AdditionalResponseParameters.Add(property.Key, property.Value); } return Task.FromResult<object>(null); } public override Task ValidateClientAuthentication(OAuthValidateClientAuthenticationContext context) { // Resource owner password credentials does not provide a client ID. if (context.ClientId == null) { context.Validated(); } return Task.FromResult<object>(null); } public override Task ValidateClientRedirectUri(OAuthValidateClientRedirectUriContext context) { if (context.ClientId == _publicClientId) { Uri expectedRootUri = new Uri(context.Request.Uri, "/"); if (expectedRootUri.AbsoluteUri == context.RedirectUri) { context.Validated(); } } return Task.FromResult<object>(null); } public static AuthenticationProperties CreateProperties(string userName) { IDictionary<string, string> data = new Dictionary<string, string> { { "userName", userName } }; return new AuthenticationProperties(data); } } }
wilk666/Angular2SandBox
TsAngular2/Providers/ApplicationOAuthProvider.cs
C#
mit
3,437
<?php namespace Rainlab\Translate\Console; use Illuminate\Console\Command; use Symfony\Component\Console\Input\InputOption; use RainLab\Translate\Classes\ThemeScanner; use RainLab\Translate\Models\Message; /** * ScanCommand */ class ScanCommand extends Command { protected $name = 'translate:scan'; protected $description = 'Scan theme localization files for new messages.'; public function handle() { if ($this->option('purge')) { $this->output->writeln('Purging messages...'); Message::truncate(); } ThemeScanner::scan(); $this->output->success('Messages scanned successfully.'); $this->output->note('You may need to run cache:clear for updated messages to take effect.'); } protected function getArguments() { return []; } protected function getOptions() { return [ ['purge', 'null', InputOption::VALUE_NONE, 'First purge existing messages.', null], ]; } }
rainlab/translate-plugin
console/ScanCommand.php
PHP
mit
1,013
using System; namespace MagicalLifeAPI.World.Data.Disk.DataStorage { /// <summary> /// Implementers of this handle what happens to the sections of serialized world data. /// </summary> public abstract class AbstractWorldSink { ///<summary></summary> /// <param name="data">The data to be handled. This must be Protobuf-net serializable, otherwise this will fail quite rapidly.</param> /// <param name="filePath">The filepath to where the data should be stored if saving to disk is the intent.</param> public abstract void Receive<T>(T data, string filePath, Guid dimensionID); } }
SneakyTactician/EarthWithMagic
MagicalLifeAPIStandard/World/Data/Disk/DataStorage/AbstractWorldSink.cs
C#
mit
640
import one from './index-loader-syntax.css'; import two from 'button.modules.css!=!./index-loader-syntax-sass.css'; // Hash should be different import three from './button.module.scss!=!./base64-loader?LmZvbyB7IGNvbG9yOiByZWQ7IH0=!./simple.js?foo=bar'; import four from './other.module.scss!=!./base64-loader?LmZvbyB7IGNvbG9yOiByZWQ7IH0=!./simple.js?foo=baz'; __export__ = [...one, ...two, ...three, ...four]; export default [...one, ...two, ...three, ...four];
webpack-contrib/css-loader
test/fixtures/index-loader-syntax.js
JavaScript
mit
463
import os from .base import Output class AppleSay(Output): """Speech output supporting the Apple Say subsystem.""" name = 'Apple Say' def __init__(self, voice = 'Alex', rate = '300'): self.voice = voice self.rate = rate super(AppleSay, self).__init__() def is_active(self): return not os.system('which say') def speak(self, text, interrupt = 0): if interrupt: self.silence() os.system('say -v %s -r %s "%s" &' % (self.voice, self.rate, text)) def silence(self): os.system('killall say') output_class = AppleSay
frastlin/PyAudioGame
pyaudiogame/accessible_output2/outputs/say.py
Python
mit
535
package com.taobao.messenger.service.common; /** * Æ£ÀͶÈÖÜÆÚ * @author huohu * @since 1.0, 2009-5-7 ÏÂÎç05:30:35 */ public enum Period { /** * Ìì */ ONEDAY(1), /** * ÖÜ£¨ÆßÌ죩 */ ONEWEEK(7), /** * Ô£¨31Ì죩 */ ONEMONTH(31); private int value; private Period(int value){ this.value = value; } public int getValue(){ return value; } }
ianli-sc/website
study/node/hsfTest/messenger-common-1.3.3-sources/com/taobao/messenger/service/common/Period.java
Java
mit
402
RSpec.describe PokerInputParser, '#parse' do shared_examples_for PokerInputParser do |players_expected_cards| before(:each) do parser = PokerInputParser.new subject @players = parser.players end it "has #{players_expected_cards.count} players" do expect(@players.count).to eq(players_expected_cards.count) end it 'each player has 5 cards' do @players.each do |player| expect(player.cards.count).to eq(5) end end players_expected_cards.each.with_index do |expected_cards, i| it "player #{i+1}\'s cards are #{expected_cards}" do actual_cards = @players[i].cards expected_cards.each.with_index do |c, card_index| expect(actual_cards[card_index]).to match(CardParser.parse c) end end end end context 'given input with two players' do subject { 'Black: 2H 3D 5S 9C KD White: 2C 3H 4S 8C AH' } it_should_behave_like PokerInputParser, [ ['2H', '3D', '5S', '9C', 'KD'], ['2C', '3H', '4S', '8C', 'AH'], ] end context 'given input with three players' do subject { 'Black: 3H AD 6C 8C QD White: 8D 3S 5S 9C AH Orange: 3D 4C 8H AS JD' } it_should_behave_like PokerInputParser, [ ['3H', 'AD', '6C', '8C', 'QD'], ['8D', '3S', '5S', '9C', 'AH'], ['3D', '4C', '8H', 'AS', 'JD'], ] end end
NxSoftware/Kata-Ruby-PokerHands
spec/input_parser_spec.rb
Ruby
mit
1,430
namespace Shapes { using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; public class Square : Shape { public Square(double sides) :base (sides,sides) { } public override double CalculateSurface() { return this.Width * this.Height; } } }
Konstantin-Todorov/CSharpOOP
C#OOP-Homeworks/05.OOP Principles-Part2/Shapes/Square.cs
C#
mit
410
class TokyoMetro::Factory::Decorate::Api::TrainOperation::Info::NetworkError < TokyoMetro::Factory::Decorate::Api::TrainOperation::Info::BasicError private def h_locals_for_status_additional_infos { text_ja_abstruct: "ネットワークエラー" , text_ja_precise: "接続を確認し、ページを更新してください" , text_en_abstruct: "Error on network" , text_en_precise: "Check your network and reload this page." } end end
osorubeki-fujita/odpt_tokyo_metro
lib/tokyo_metro/factory/decorate/api/train_operation/info/network_error.rb
Ruby
mit
478
var mysql = require('mysql'); function discountMember(router,connection){ var self=this; self.handleRoutes(router,connection); } //KALO...UDH SEKALI DIDISKON>>>BERARTI GABOLEH LAGI LAGI DISKON YAA TODO: discountMember.prototype.handleRoutes = function(router,connection){ router.post('/discountMember',function(req,res){ var sessionCode = req.body.sessionCode; var no_bon = req.body.no_bon; var membershipCode = req.body.membershipCode; if(sessionCode == null || sessionCode == undefined || sessionCode == ''){ res.json({"message":"err.. no params s_c rec"}); }else{ if(no_bon == null || no_bon == undefined || no_bon == ''){ res.json({"message":"err.. no params n_b rec"}); }else{ if(membershipCode == null || membershipCode == undefined || membershipCode == ''){ res.json({"message":"err.. no params m_c rec"}); }else{ var query = "select role.id_role as id_role from `session` join `user` on session.id_user=user.id_user join role on role.id_role=user.id_role where session.session_code='"+sessionCode+"'"; connection.query(query,function(err,rows){ if(err){ res.json({"message":"err.. error on session","query":query}); }else{ if(rows.length == 1){ if(rows[0].id_role == 2 || rows[0].id_role == 1){ var q012 = "select discount,no_bon from `order` where no_bon='"+no_bon+"'"; connection.query(q012,function(err,rows){ if(err){ res.json({"message":"err.. on selecting disc st1"}); }else{ if(rows.length>0){ if(rows[0].discount == null || rows[0].discount == undefined || rows[0].discount == ''){ //ambil jumlah discount dulu di membership code var q2 = "select discount from `membership` where membership_code='"+membershipCode+"'"; connection.query(q2,function(err,rows){ if(err){ res.json({"message":"err.. error selecting discount"}); }else{ if(rows.length>0){ var discount = rows[0].discount; //pending var q3 = "select jumlah_bayar from `order` where no_bon = '"+no_bon+"'"; connection.query(q3,function(err,rows){ if(err){ res.json({"message":"err.. error on selecting jumlah Bayar"}); }else{ if(rows.length>0){ var jumlahBayar = rows[0].jumlah_bayar; var afterDisc = jumlahBayar-(jumlahBayar*discount/100); var q4 = "update `order` set discount="+discount+",harga_bayar_fix="+afterDisc+",jumlah_bayar="+afterDisc+" where no_bon='"+no_bon+"'"; connection.query(q4,function(err,rows){ if(err){ res.json({"message":"err.. error on updating"}); }else{ res.json({"message":"err.. success adding discount","priceAfterDiscount":afterDisc,"discount":discount}); } }); }else{ res.json({"message":"Err.. no rows absbas","q3":q3}); } } }); }else{ res.json({"message":"err.. no rows","q2":q2}); } } }); }else{ res.json({"message":"err.. have already discounted"}); } }else{ res.json({"message":"err.. no rows on order with given n_b"}); } } }); }else{ res.json({"message":"err.. you have no authorize to do this action"}); } }else{ res.json({"message":"err... rows length not equal to 1"}); } } }); } } } }); } module.exports = discountMember;
mczal/widji-server
model/cashier/discountMember.js
JavaScript
mit
4,751
package com.slack.api.methods.response.admin.conversations.restrict_access; import com.slack.api.methods.SlackApiResponse; import com.slack.api.model.ErrorResponseMetadata; import lombok.Data; import java.util.List; @Data public class AdminConversationsRestrictAccessListGroupsResponse implements SlackApiResponse { private boolean ok; private String warning; private String error; private String needed; private String provided; private List<String> groupIds; private ErrorResponseMetadata responseMetadata; }
seratch/jslack
slack-api-client/src/main/java/com/slack/api/methods/response/admin/conversations/restrict_access/AdminConversationsRestrictAccessListGroupsResponse.java
Java
mit
543
import React from 'react'; import Home from './Home.js'; import Login from './Login.js'; import PointInTime from './PointInTime.js'; import Vispdat from './VISPDAT.js'; import Refuse from './Refuse.js'; import { Actions, Scene } from 'react-native-router-flux'; /** * Order of rendering is based on index of Child scene. * We set hideNavBar to true to prevent that ugly default * header. We can enable and style when we need to. */ export default Actions.create( <Scene key="root"> <Scene key="login" component={Login} hideNavBar={true} /> <Scene key="home" component={Home} hideNavBar={true} /> <Scene key="pointInTime" component={PointInTime} hideNavBar={true} /> <Scene key="vispdat" component={Vispdat} hideNavBar={true} /> <Scene key="refuse" component={Refuse} hideNavBar={true} /> </Scene> );
kawikadkekahuna/react-native-form
src/routes/index.js
JavaScript
mit
834
//------------------------------------------------------------------------------ // Piece Manipulation Device (c) 2010 Robert MacGregor // Version: 3.0b // Comment: This file has went through much organization and it still isn't // very neat! // // ----------------------------- Description ----------------------------------- // The Piece Manipulation Device is a special pack that enables // you to create special effects on your creations by directly modifying // any pieces found upon its list. When the device gains power, it scans // a list of its pieces and takes the appropiate action for each one. // // Supported Actions: // // 1. Cloaking // 2. Fading // 3. Hiding (Just like fade, except the object cannot by collided with) // 4. Scaling // 5. Naming // 6. Rotation (A special tool will be added to handle this) // // All of the above performance options are performed when the device gains // power. The action taken will be undone when the device loses power. // // ------------------------------- Agreement ----------------------------------- // // You may use this pack as a part of any other mod as long as // you agree to the following terms: // // 1. You MAY NOT strip my name Robert MacGregor // from any part of the script. This includes the header you are reading now. // // 2. You must directly state that I, Robert MacGregor created this pack in a // clearly seen place in Tribes 2. This may include the debriefGui, // loadingGui or bottom & center print texts. // // 3. You MAY NOT modify any of the functioning code without my explicit // permission. You can however, modify the settings that are GLOBAL VARIABLES. // // If you cannot abide by those terms, then don't edit this file at all. //------------------------------------------------------------------------------ // Settings $Editor::MaxScale["X"] = 20; $Editor::MaxScale["Y"] = 20; $Editor::MaxScale["Z"] = 20; $Editor::MinScale["X"] = -20; $Editor::MinScale["Y"] = -20; $Editor::MinScale["Z"] = -20; // Hidden Debris Option $Editor::Debris::Enabled = false; $Editor::Debris::MinMS = 100; $Editor::Debris::Max = 5; $Editor::Debris::Count = 0; // Datablocks (From here on out, you cannot modify) datablock StaticShapeData(DeployedEditorPack) : StaticShapeDamageProfile { className = "EditorPack"; shapeFile = "stackable2s.dts"; maxDamage = 2.0; destroyedLevel = 2.0; disabledLevel = 2.0; mass = 1.2; elasticity = 0.1; friction = 0.9; collideable = 1; pickupRadius = 1; sticky = false; explosion = HandGrenadeExplosion; expDmgRadius = 1.0; expDamage = 0.1; expImpulse = 200.0; dynamicType = $TypeMasks::StaticShapeObjectType; deployedObject = true; cmdCategory = "DSupport"; cmdIcon = CMDSensorIcon; cmdMiniIconName = "commander/MiniIcons/com_deploymotionsensor"; targetNameTag = 'Piece Manipulation'; targetTypeTag = 'Device'; deployAmbientThread = true; debrisShapeName = "debris_generic_small.dts"; debris = DeployableDebris; heatSignature = 0; needsPower = true; }; datablock ShapeBaseImageData(EditorPackDeployableImage) { mass = 10; emap = true; shapeFile = "stackable1s.dts"; item = EditorPackDeployable; mountPoint = 1; offset = "0 0 0"; deployed = DeployedEditorPack; heatSignature = 0; collideable = 1; stateName[0] = "Idle"; stateTransitionOnTriggerDown[0] = "Activate"; stateName[1] = "Activate"; stateScript[1] = "onActivate"; stateTransitionOnTriggerUp[1] = "Idle"; isLarge = true; maxDepSlope = 360; deploySound = ItemPickupSound; minDeployDis = 0.5; maxDeployDis = 5.0; }; datablock ItemData(EditorPackDeployable) { className = Pack; catagory = "Deployables"; shapeFile = "stackable1s.dts"; mass = 5.0; elasticity = 0.2; friction = 0.6; pickupRadius = 1; rotate = true; image = "EditorPackDeployableImage"; pickUpName = "a Piece Manipulation Device"; heatSignature = 0; emap = true; }; // Code function EditorPackDeployableImage::onDeploy(%item, %plyr, %slot) { %className = "StaticShape"; %playerVector = vectorNormalize(getWord(%plyr.getEyeVector(),1) SPC -1 * getWord(%plyr.getEyeVector(),0) SPC "0"); %item.surfaceNrm2 = %playerVector; if (vAbs(floorVec(%item.surfaceNrm,100)) $= "0 0 1") %item.surfaceNrm2 = %playerVector; else %item.surfaceNrm2 = vectorNormalize(vectorCross(%item.surfaceNrm,"0 0 -1")); %rot = fullRot(%item.surfaceNrm,%item.surfaceNrm2); %deplObj = new (%className)() { dataBlock = %item.deployed; scale = "1 1 1"; }; // set orientation %deplObj.setTransform(%item.surfacePt SPC %rot); %deplObj.deploy(); // set team, owner, and handle %deplObj.team = %plyr.client.Team; %deplObj.setOwner(%plyr); %deplObj.paded=1; //Msg Client messageclient(%plyr.client, 'MsgClient', "\c2Type /editor CMDs for a list of device CMD's."); // set the sensor group if it needs one if (%deplObj.getTarget() != -1) setTargetSensorGroup(%deplObj.getTarget(), %plyr.client.team); // place the deployable in the MissionCleanup/Deployables group (AI reasons) addToDeployGroup(%deplObj); //Set the power frequency %deplObj.powerFreq = %plyr.powerFreq; checkPowerObject(%deplObj); //let the AI know as well... AIDeployObject(%plyr.client, %deplObj); // play the deploy sound serverPlay3D(%item.deploySound, %deplObj.getTransform()); // increment the team count for this deployed object $TeamDeployedCount[%plyr.team, %item.item]++; addDSurface(%item.surface,%deplObj); %deplObj.playThread($PowerThread,"Power"); %deplObj.playThread($AmbientThread,"ambient"); // take the deployable off the player's back and out of inventory %plyr.unmountImage(%slot); %plyr.decInventory(%item.item, 1); //Set the slot count %deplobj.slotcount = 1; //For /editor addobj //Set the type %type = addTaggedString("Device ("@%plyr.powerFreq@")"); setTargetType(%deplObj.target,%type); return %deplObj; } function EditorPack::onCollision(%data,%obj,%col) { // created to prevent console errors } function EditorPackDeployable::onPickup(%this, %obj, %shape, %amount) { // created to prevent console errors } function EditorPackDeployableImage::onMount(%data, %obj, %node) { displayPowerFreq(%obj); } function EditorPackDeployableImage::onUnmount(%data, %obj, %node) { // created to prevent console errors } function DeployedEditorPack::gainPower(%data, %obj) { if (%obj.IsPowered) //A source was turned off when multiple ones exist return; EditorPerform(%obj); } function DeployedEditorPack::losePower(%data, %obj) { if (!%obj.IsPowered) //Already off. return; %obj.RevertPieces(false); } function DeployedEditorPack::onDestroyed(%this, %obj, %prevState) { %obj.RevertPieces(true); if (%obj.isRemoved) return; %obj.isRemoved = true; Parent::onDestroyed(%this, %obj, %prevState); $TeamDeployedCount[%obj.team, bogypackDeployable]--; remDSurface(%obj); %obj.schedule(500, "delete"); fireBallExplode(%obj,1); } function DeployedEditorPack::Disassemble(%data,%plyr,%obj) { %obj.RevertPieces(true); Parent::Disassemble(%data,%plyr,%obj); } //*********************************************\\ // Command Code *\\ //*********************************************\\ function ccEditor(%sender,%args) { %f = getWord(%args,0); %f = strLwr(%f); //Convert To LowerCase %f = stripChars(%f," "); //Strip spaces. %pos = %sender.player.getMuzzlePoint($WeaponSlot); %vec = %sender.player.getMuzzleVector($WeaponSlot); %targetpos = vectoradd(%pos,vectorscale(%vec,100)); %obj = containerraycast(%pos,%targetpos,$typemasks::staticshapeobjecttype,%sender.player); %obj = getword(%obj,0); if (%f $="") { messageclient(%sender,'msgclient',"\c2No command specified, please type '/Editor Help' for a list of commands."); return 1; } else if (!EvaluateFunction(%f)) { messageclient(%sender,'msgclient','\c2Unknown command: %1.', %f); return 1; } else if (%f $="help" || %f $="cmds") { messageclient(%sender,'msgclient',"\c2/Editor Select - Selects the device you're looking at."); messageclient(%sender,'msgclient',"\c2/Editor DelObj - Removes the object you're looking at from your currently selected device."); messageclient(%sender,'msgclient',"\c2/Editor List - If you own the device you're looking at, this command will list all pieces assigned to it."); messageclient(%sender,'msgclient',"\c2/Editor Cloak - Adds the object you're looking at to your device's currently selected cloak list."); messageclient(%sender,'msgclient',"\c2/Editor Fade - Adds the object you're looking at to your device's currently selected fade list."); messageclient(%sender,'msgclient',"\c2/Editor Name <New Name> - Adds the object you're looking at to your currently selected device's fade list."); messageclient(%sender,'msgclient',"\c2/Editor Scale <New Scale> - Adds the object you're looking at to your currently selected device's scale list."); messageclient(%sender,'msgclient',"\c2/Editor Hide - Adds the object you're looking at to your currently selected device's fade list."); messageclient(%sender,'msgclient',"\c2/Editor Rotate <Rotation> - Adds the object you're looking at to your currently selected device's rotation list."); if ($Editor::Debris::Enabled) messageclient(%sender,'msgclient',"\c2/Editor Debris <Human-Bioderm> <TimeMS> - Adds the object you're looking at to your currently selected device's debris list."); return 1; } else if (!%obj) { messageclient(%sender,'msgclient',"\c2Unable to find an object."); return 1; } else if (IsObject(%obj) && IsValidClass(%obj.getclassname())) { messageclient(%sender,'msgclient','\c2Invalid object. Error: Invalid Class - %1.', %obj.getclassname()); return 1; } else if (%f $="delobj") { ProcessDelObj(%sender,%obj,%args); return 1; } else if (%f $="list") { ProcessList(%sender,%obj); return 1; } else if (%f $="size") { ProcessSize(%sender,%obj); return 1; } else if (%f $="addobj") { ProcessAddObj(%sender,%obj); return 1; } else if (%f $="debris") { ProcessDebris(%sender,%obj,%args); return 1; } else if (%f $="fade") { ProcessFade(%sender,%obj,%args); return 1; } else if (%f $="cloak") { ProcessCloak(%sender,%obj,%args); return 1; } else if (%f $="scale") { ProcessScale(%sender,%obj,%args); return 1; } else if (%f $="rotate") { ProcessRotate(%sender,%obj,%args); return 1; } else if (%f $="name") { ProcessName(%sender,%obj,%args); return 1; } else if (%f $="hide") { ProcessHide(%sender,%obj,%args); return 1; } else { ProcessEditorRequest(%sender,%obj,%f); return 1; } messageclient(%sender,'msgclient',"\c2Piece Editor: An unknown error has occurred. Code: 1"); //Shouldn't see this return 1; } function ProcessList(%sender,%obj) { if (IsObject(%obj)) { %count = %obj.slotcount; %count = %count - 1; if (%count > 1) { for (%i = 0; %i < %count; %i++) { %slotobj = %obj.slot[%i]; if (IsObject(%slotobj)) { messageclient(%sender,'msgclient','\c2%1: %2 - %3', %i, %slotobj, %slotobj.getclassname()); } else { messageclient(%sender,'msgclient','\c2%1: %2 - Does not exist. You should not see this error. Code: 2.', %i, %slotobj); } } } else { messageclient(%sender,'msgclient','\c2This device has an invalid slot count: %1. You should not see this error. Code: 3.', %count); return; } } else { messageclient(%sender,'msgclient','\c2Object %1 does not exist. You should not see this error. Code: 4', %obj); return; } } function ProcessEditorRequest(%sender,%obj,%f) { if (%obj.owner!=%sender && %obj.owner !$=""){ messageclient(%sender,'msgclient',"\c2This editor pack is not yours!"); return; } if (%obj.getdatablock().getname() !$="DeployedEditorPack") { messageclient(%sender,'msgclient',"\c2Unable to edit devices!"); return; } if (%f $="select" || %f $="selecteditor" || %f = "seledit") { %sender.currentedit = %obj; %obj.cloakAnim(500); messageclient(%sender,'msgclient',"\c2Current device set."); return; } } function ProcessAddObj(%sender,%obj) { if (%obj.owner!=%sender && %obj.owner !$=""){ messageclient(%sender,'msgclient',"\c2This object is not yours!"); return; } if (!IsObject(%Sender.CurrentEdit)) { messageclient(%sender,'msgclient',"\c2No device selected! You can use '/Editor Select' while pointing at a device to select it."); return; } if (%obj.getdatablock().getname() $= "DeployedEditorPack") { messageclient(%sender,'msgclient',"\c2Unable to edit Piece Manipulating Devices!"); return; } %Slots = %sender.currentedit.slotcount; %edit = %sender.currentedit; for (%i=0;%i<%slots;%i++) { if (%edit.slot[%i] $="") { %edit.slot[%i] = %obj; %edit.slotcount++; messageclient(%sender,'msgclient','\c2Object has been added to your current device. (%1)', %i); %obj.slot = %i; %obj.editor = true; %obj.cloakAnim(500); return; } } } function ProcessDelObj(%sender,%obj,%args) { %edit = %sender.currentedit; if (!IsObject(%edit)) { messageclient(%sender,'msgclient',"\c2No device selected!"); return; } if (%obj.owner!=%sender && %obj.owner !$=""){ messageclient(%sender,'msgclient',"\c2Not your object!"); return; } if (!%obj.editor) { messageclient(%sender,'msgclient',"\c2This object is not bound to a device!"); return; } messageclient(%sender,'msgclient','\c2Object deleted from your currently selected device. (%1)', %edit.slot[%obj.slot]); %edit.slot[%obj.slot] = ""; %obj.slot = ""; %obj.editor = false; Revert(%obj,"all"); %obj.cloakAnim(500); if (%edit.slotcount > 1) %edit.slotcount--; } function ProcessRotate(%sender,%obj,%args) { %edit = %sender.currentedit; %args = GetWords(%args, 1); if (!IsObject(%edit)) { messageclient(%sender,'msgclient',"\c2No device selected!"); return; } if (%obj.owner!=%sender && %obj.owner !$=""){ messageclient(%sender,'msgclient',"\c2Not your object!"); return; } if (%obj.istrotate) { Revert(%obj,"rotation"); messageclient(%sender,'msgclient','\c2Object has been removed from your current device\'s rotation list.'); %obj.cloakAnim(500); } else { if (%args $= "") { messageclient(%sender,'msgclient','\c2No rotation angle set.'); return 1; } else if (%args $= "L") { return 1; } else { if (!%obj.editor) ProcessAddObj(%Sender,%obj); %obj.istrotate = true; %obj.erotation = %args; %obj.oldrotation = %obj.getRotation(); %obj.iserotated = false; %obj.cloakAnim(500); messageclient(%sender,'msgclient','\c2Object will be rotated with the following angles: %1.', %args); } } } function ProcessScale(%sender,%obj,%args) { %scale = getwords(%args,1); %edit = %sender.currentedit; if (!IsObject(%edit)) { messageclient(%sender,'msgclient',"\c2No device selected!"); return; } else if (%obj.owner!=%sender && %obj.owner !$=""){ messageclient(%sender,'msgclient',"\c2Not your object!"); return; } else if (%obj.getdatablock().getname() $= "DeployedEditorPack") { messageclient(%sender,'msgclient',"\c2Unable to scale devices!"); return; } else if (%scale $="" && %obj.istscale == false) { messageclient(%sender,'msgclient',"\c2No scale specified."); return; } else if (getword(%scale,0) > $Editor::MaxScale["X"] && %obj.istscale == false) { messageclient(%sender,'msgclient','\c2The scale %1 is invalid. The X axis is too big. Max: %2', %scale, $Editor::MaxScale["X"]); return; } else if (getword(%scale,1) > $Editor::MaxScale["Y"] && %obj.istscale == false) { messageclient(%sender,'msgclient','\c2The scale %1 is invalid. The Y axis is too big. Max: %2', %scale, $Editor::MaxScale["Y"]); return; } else if (getword(%scale,2) > $Editor::MaxScale["Z"] && %obj.istscale == false) { messageclient(%sender,'msgclient','\c2The scale %1 is invalid. The Z axis is too big. Max: %2', %scale,$Editor::MaxScale["Z"]); return; } else if (getword(%scale,0) < $Editor::MinScale["X"] && %obj.istscale == false) { messageclient(%sender,'msgclient','\c2The scale %1 is invalid. The X axis is too small. Min: %2', %scale, $Editor::MinScale["X"]); return; } else if (getword(%scale,1) < $Editor::MinScale["Y"] && %obj.istscale == false) { messageclient(%sender,'msgclient','\c2The scale %1 is invalid. The Y axis is too small. Min:', %scale, $Editor::MinScale["Y"]); return; } else if (getword(%scale,2) < $Editor::MinScale["Z"] && %obj.istscale == false) { messageclient(%sender,'msgclient','\c2The scale %1is invalid. The Z axis is too small. Min:', %scale, $Editor::MinScale["Z"]); return; } else { %scale = CheckScale(%scale); if (!%obj.istscale) { if (!%obj.editor) ProcessAddObj(%Sender,%obj); %obj.istscale = true; %obj.isescaled = false; messageclient(%sender,'msgclient','\c2Object has been added to your currently selected device\'s scale list. This object will be scaled to %1.', %scale); %obj.escale = %scale; %obj.oldscale = %obj.getscale(); %obj.cloakAnim(500); return; } else { Revert(%obj,"scale"); messageclient(%sender,'msgclient',"\c2Object has been removed from your currently selected device's scale list. Original scale restored."); %obj.setscale(%obj.oldscale); %obj.cloakAnim(500); } } } function ProcessSize(%sender,%obj,%args) { %scale = getwords(%args,1); %edit = %sender.currentedit; if (!IsObject(%edit)) { messageclient(%sender,'msgclient',"\c2No device selected!"); return; } else if (%obj.owner!=%sender && %obj.owner !$=""){ messageclient(%sender,'msgclient',"\c2Not your object!"); return; } else if (%obj.getdatablock().getname() $= "DeployedEditorPack") { messageclient(%sender,'msgclient',"\c2Unable to size devices!"); return; } else if (%scale $="" && %obj.istscale == false) { messageclient(%sender,'msgclient',"\c2No size specified."); return; } else if (getword(%scale,0) > $Editor::MaxScale["X"] && %obj.istscale == false) { messageclient(%sender,'msgclient','\c2The size %1 is invalid. The X axis is too big. Max: %2', %scale, $Editor::MaxScale["X"]); return; } else if (getword(%scale,1) > $Editor::MaxScale["Y"] && %obj.istscale == false) { messageclient(%sender,'msgclient','\c2The size %1 is invalid. The Y axis is too big. Max: %2', %scale, $Editor::MaxScale["Y"]); return; } else if (getword(%scale,2) > $Editor::MaxScale["Z"] && %obj.istscale == false) { messageclient(%sender,'msgclient','\c2The size %1 is invalid. The Z axis is too big. Max: %2', %scale,$Editor::MaxScale["Z"]); return; } else if (getword(%scale,0) < $Editor::MinScale["X"] && %obj.istscale == false) { messageclient(%sender,'msgclient','\c2The size %1 is invalid. The X axis is too small. Min: %2', %scale, $Editor::MinScale["X"]); return; } else if (getword(%scale,1) < $Editor::MinScale["Y"] && %obj.istscale == false) { messageclient(%sender,'msgclient','\c2The size %1 is invalid. The Y axis is too small. Min:', %scale, $Editor::MinScale["Y"]); return; } else if (getword(%scale,2) < $Editor::MinScale["Z"] && %obj.istscale == false) { messageclient(%sender,'msgclient','\c2The size %1is invalid. The Z axis is too small. Min:', %scale, $Editor::MinScale["Z"]); return; } else { %scale = CheckScale(%scale); if (!%obj.istsize) { if (!%obj.editor) ProcessAddObj(%Sender,%obj); %obj.istsize = true; %obj.isesized = false; messageclient(%sender,'msgclient','\c2Object has been added to your currently selected device\'s size list. This object will be scaled to %1.', %scale); %obj.esize = %scale; %obj.oldsize = %obj.getrealsize(); %obj.cloakAnim(500); return; } else { Revert(%obj,"scale"); messageclient(%sender,'msgclient',"\c2Object has been removed from your currently selected device's size list. Original scale restored."); %obj.setscale(%obj.oldsize); %obj.cloakAnim(500); } } } function ProcessFade(%sender,%obj,%args) { %edit = %sender.currentedit; if (!isObject(%edit)) { messageclient(%sender,'msgclient',"\c2No device selected!"); return; } if (%obj.owner!=%sender && %obj.owner !$=""){ messageclient(%sender,'msgclient',"\c2This object is not yours!"); return; } if (%obj.getdatablock().getname() $= "DeployedEditorPack") { messageclient(%sender,'msgclient',"\c2Unable to fade Piece Manipulating Devices!"); return; } if (!%obj.istfade) { if (!%obj.editor) ProcessAddObj(%Sender,%obj); %obj.istfade = true; %obj.isefaded = false; %obj.setcloaked(true); %obj.cloakAnim(500); return; } else { Revert(%obj,"fade"); %obj.cloakAnim(500); messageclient(%sender,'msgclient',"\c2Object has been removed from your currently selected device's fade list."); } } function ProcessDebris(%sender,%obj,%args) { %edit = %sender.currentedit; %deb = GetWord(%args, 0); %debris = GetWord(%args, 1); %timems = GetWord(%args, 2); if (!$Editor::Debris::Enabled) { messageclient(%sender,'msgclient','\c2Unknown command: %1.', %deb); return 1; } if (!isObject(%edit)) { messageclient(%sender,'msgclient',"\c2No device selected!"); return; } if (%obj.owner!=%sender && %obj.owner !$=""){ messageclient(%sender,'msgclient',"\c2This object is not yours!"); return; } if (%obj.getdatablock().getname() $= "DeployedEditorPack") { messageclient(%sender,'msgclient',"\c2Unable to edit Piece Manipulating Devices!"); return; } if (%obj.istdebris) { Revert(%obj,"debris"); $Editor::Debris::Count--; %obj.cloakAnim(500); messageclient(%sender,'msgclient',"\c2Object has been removed from your currently selected device's debris list."); return 1; } if (%debris $= "Human" || %debris $= "Bioderm") { if (!%obj.istdebris) { if ($Editor::Debris::Count > $Editor::Debris::Max) { messageclient(%sender,'msgclient','\c2Unable to create debtis emitter, reached max. Max: %1', $Editor::Debris::Max); return 1; } if (%timeMS $= "") { messageclient(%sender,'msgclient',"\c2No time in milliseconds specified."); return 1; } if (%timeMS < $Editor::Debris::MinMS) { messageclient(%sender,'msgclient',"\c2Invalid time in milliseconds, too low: "@%timeMS@". Minimum is 100."); return 1; } if (!%obj.editor) ProcessAddObj(%Sender,%obj); %obj.istdebris = true; %obj.isedebris = false; %obj.debristime = %timems; %obj.isedebris = false; %obj.debris = %debris; %obj.cloakAnim(500); $Editor::Debris::Count++; messageclient(%sender,'msgclient',"\c2Object has been added to your currently selected device's debris list. Type: "@%debris@"."); return; } } else { messageclient(%sender,'msgclient',"\c2Invalid debris type: "@%debris@". Available are: Human and Bioderm."); } } function ProcessHide(%sender,%obj,%args) { %edit = %sender.currentedit; if (!isObject(%edit)) { messageclient(%sender,'msgclient',"\c2No device selected!"); return; } if (%obj.owner!=%sender && %obj.owner !$=""){ messageclient(%sender,'msgclient',"\c2This object is not yours!"); return; } if (%obj.getdatablock().getname() $= "DeployedEditorPack") { messageclient(%sender,'msgclient',"\c2Unable to fade devices!"); return; } if (!%obj.isthide) { if (!%obj.editor) ProcessAddObj(%Sender,%obj); %obj.isthide = true; %obj.isehidden = false; messageclient(%sender,'msgclient',"\c2Object has been added to your currently selected device's hide list."); %obj.cloakAnim(500); return; } else { Revert(%obj,"hide"); messageclient(%sender,'msgclient',"\c2Object has been removed from your currently selected device's hide list."); %obj.cloakAnim(500); } } function ProcessCloak(%sender,%obj,%args) { %edit = %sender.currentedit; if (!isObject(%edit)) { messageclient(%sender,'msgclient',"\c2No device selected!"); return; } if (%obj.owner!=%sender && %obj.owner !$=""){ messageclient(%sender,'msgclient',"\c2This object is not yours!"); return; } if (%obj.getdatablock().getname() $= "DeployedEditorPack") { messageclient(%sender,'msgclient',"\c2Unable to cloak devices!"); return; } if (!%obj.istcloak) { if (!%obj.editor) ProcessAddObj(%Sender,%obj); %obj.istcloak = true; %obj.isecloaked = false; messageclient(%sender,'msgclient',"\c2Object has been added to your currently selected device's cloak list."); %obj.cloakAnim(500); return; } else { Revert(%obj,"cloak"); messageclient(%sender,'msgclient',"\c2Object has been removed from your currently selected device's cloak list."); %obj.cloakAnim(500); } } function ProcessName(%sender,%obj,%args) { %edit = %sender.currentedit; %name = getwords(%args,1); if (!isObject(%edit)) { messageclient(%sender,'msgclient',"\c2No device selected!"); return 1; } else if (%obj.owner!=%sender && %obj.owner !$="") { messageclient(%sender,'msgclient',"\c2This object is not yours!"); return 1; } else if (%obj.getdatablock().getname() $= "DeployedEditorPack") { messageclient(%sender,'msgclient',"\c2Unable to name devices!"); return 1; } else if (!%obj.istname) { if (!%obj.editor) { ProcessAddObj(%Sender,%obj); } %obj.istname = true; %obj.isenamed = false; //<--Must Be defined-->\\ %db = %obj.GetDataBlock(); if (%obj.nametag !$= "") %obj.oldname = %obj.nametag; else if (%db.targetNameTag !$= "" && %db.targetTypeTag !$= "") %obj.oldname = GetTaggedString(%obj.getdatablock().targetNameTag SPC %obj.getdatablock().targetTypeTag); else //Gotta fall back on the target name %obj.oldname = GetTaggedString(GetTargetName(%obj.target)); %obj.ename = %name; messageclient(%sender,'msgclient',"\c2Object has been added to your currently selected device's name list. This object will be named to: "@%name@""); %obj.cloakAnim(500); return 1; } else if (%obj.istname) { Revert(%obj,"name"); messageclient(%sender,'msgclient',"\c2Object has been removed from your currently selected device's cloak list. Old name restored."); %obj.cloakAnim(500); return 1; } else { messageclient(%sender,'msgclient',"\c2An unknown error has occured. Code 5:"); return 1; } } //*********************************************\\ // PERFORMANCE CODE *\\ //*********************************************\\ function EditorPerform(%obj) { PerformCloak(%obj); PerformFade(%obj); PerformScale(%obj); PerformHide(%obj); PerformName(%obj); PerformRotate(%obj); PerformSize(%obj); PerformDebris(%obj); } function PerformCloak(%obj) { if (!IsObject(%obj)) return; %c = %obj.slotcount; %c++; for (%i=0;%i<%c;%i++) { %object = %obj.slot[%i]; if (!IsObject(%Object)) return; if (!%object.istcloak) //IsTFade = Is To Fade %object.isecloaked = true; //To Make The System Think It's Already Cloaked if (%object.isecloaked) { %object.setcloaked(false); %object.isecloaked = false; } else { schedule(510,0,"SetCloaked",%object,true); //Somehow Fixed The Cloaking Problem %object.isecloaked = true; } } } function PerformFade(%obj) { if (!IsObject(%obj)) return; %c = %obj.slotcount; %c = %c++; for (%i=0;%i<%c;%i++) { %object = %obj.slot[%i]; if (!IsObject(%Object)) return; if (!%object.istfade) //IsTFade = Is To Fade %object.isefaded = true; //To Make The System Think It's Already Faded if (%object.isefaded) { %object.startfade(1,0,0); %object.isefaded= false; } else { %object.cloakAnim(500); schedule(510,0,"fade",%object); %object.isefaded = true; } } } function PerformHide(%obj) { if (!IsObject(%obj)) return; for (%i=0;%i<%obj.slotcount;%i++) { %object = %obj.slot[%i]; if (!IsObject(%Object)) return; if (!%object.isthide) //IsTFade = Is To Fade %object.isehidden = true; //To Make The System Think It's Already Hidden if (%object.isehidden) { %object.hide(0); %object.isehidden= false; } else { %object.cloakAnim(500); schedule(510,0,"Hide",%object); %object.isehidden = true; } } } function PerformDebris(%obj) { if (!$Editor::Debris::Enabled) return; if (!IsObject(%obj)) return; for (%i=0;%i<%obj.slotcount;%i++) { %object = %obj.slot[%i]; if (!IsObject(%Object)) return; if (%object.istdebris) { if (%object.isedebris) { %object.isedebris= false; %object.debrisemitter.delete(); } else { %object.isedebris = true; PerformDebrisLoop(%object); } } } } function PerformDebrisLoop(%obj) { cancel(%obj.debrisloop); if (!%obj.isedebris || !$Editor::Debris::Enabled) { if (IsObject(%obj.debrisemitter)) %obj.debrisemitter.delete(); %obj.debrisemitter = ""; if (!$Editor::Debris::Enabled) { $Editor::Debris::Count--; %obj.istdebris = false; %obj.isedebris = false; %obj.debristime = ""; %obj.isedebris = false; %obj.debris = ""; } return; } if (!IsObject(%obj.debrisemitter)) { if (%obj.debris $= "Human") %obj.debrisemitter = new player(){ position = %obj.gettransform(); Datablock = "LightMaleHumanArmor"; Scale = "0 0 0"; Obj = %obj; }; else %obj.debrisemitter = new player(){ position = %obj.gettransform(); Datablock = "LightMaleBiodermArmor"; Scale = "0 0 0"; Obj = %obj; }; %obj.debrisemitter.startfade(1,0,1); %obj.debrisemitter.setmovestate(true); } %obj.debrisemitter.blowup(); %obj.debrisloop = schedule(%obj.debristime,0,"PerformDebrisLoop",%obj); } function PerformScale(%obj) { if (!IsObject(%obj)) return; %c = %obj.slotcount; %c = %c++; for (%i=0;%i<%c;%i++) { %object = %obj.slot[%i]; if (!IsObject(%Object)) return; if (!%object.istscale){ //IsTFade = Is To Fade %object.isescaled = true; //To Make The System Think It's Already Scaled %object.oldscale = %object.getscale(); } if (%object.isescaled) { %object.setscale(%object.oldscale); %object.cloakAnim(500); %object.isescaled= false; } else { %object.setscale(%object.escale); %object.cloakAnim(500); %object.isescaled = true; } } } function PerformSize(%obj) { if (!IsObject(%obj)) return; %c = %obj.slotcount; %c = %c++; for (%i=0;%i<%c;%i++) { %object = %obj.slot[%i]; if (!IsObject(%Object)) return; if (!%object.istsize){ //IsTFade = Is To Fade %object.isesized = true; //To Make The System Think It's Already Scaled %object.oldsize = %object.getrealsize(); } if (%object.isesized) { %object.setrealsize(%object.oldsize); %object.cloakAnim(500); %object.isescaled= false; } else { %object.setrealsize(%object.escale); %object.cloakAnim(500); %object.isesized = true; } } } function PerformRotate(%obj) { if (!IsObject(%obj)) return; %c = %obj.slotcount; %c = %c++; for (%i=0;%i<%c;%i++) { %object = %obj.slot[%i]; if (!IsObject(%Object)) return; if (%object.istrotate) { %object.cloakAnim(500); if (%object.iserotated) { %object.iserotated = false; %object.setrotation(%object.oldrotation); } else { %object.iserotated = true; %object.setrotation(%object.erotation); } } } } function PerformName(%obj) { if (!IsObject(%obj)) return; if (!%obj.isTName) //Idiotic Console Error Fix return; %c = %obj.slotcount; %c = %c++; for (%i=0;%i<%c;%i++) { %object = %obj.slot[%i]; if (!IsObject(%Object)) return; if (!%object.istname){ //IsTFade = Is To Fade %object.isenamed = true; //To Make The System Think It's Already Scaled if (%object.nametag !$="") %object.oldname = %object.nametag; else %object.oldname = %object.getdatablock().targetNameTag; } if (%object.isenamed) { %object.nametag = %obj.oldname; setTargetName(%object.target,addTaggedString("\c6"@%object.oldname@"")); %object.isenamed = false; } else { %object.nametag = %object.ename; setTargetName(%object.target,addTaggedString("\c6"@%object.ename@"")); %object.isenamed = true; } } } //*********************************************\\ // MISC. CODE *\\ //*********************************************\\ function Hide(%obj) { %obj.hide(1); } function fade(%obj) { %obj.startfade(1,0,1); } function EvaluateFunction(%f) //To Eval The Command { if (%f $="addobj" || %f $= "selecteditor" || %f $="select" || %f $="delobj" || %f $="help" || %f $="cmds" || %f $="fade" || %f $="cloak" || %f $="scale" || %f $="hide" || %f $="name" || %f $="list" || %f $="rotate" || %f $="debris" || %f $="size") return true; else return false; } function IsMatch(%string1,%string2) { %string1 = StrLwr(%string1); %string2 = StrLwr(%string2); if (%string1 $=%string2) return true; else return false; } function CheckScale(%scale) //Evals The Scale For Any Missing Args, If So, Puts A 1 In The Blank Slot { if (getword(%scale,0) $="") %scale = "1" SPC getWord(%scale,1) SPC getWord(%scale,2); if (getword(%scale,1) $="") %scale = getWord(%scale,0) SPC "1" SPC getWord(%scale,2); if (getword(%scale,2) $="") %scale = getWord(%scale,0) SPC getWord(%scale,1) SPC "1"; return %scale; } function IsValidClass(%class) { if (%class $="Spine" || %class $="Generator" || %class $="Switch" || %class $="WWall" || %class $="Wall" || %class $="MSpine" || %class $="Station" || %class $="Sensor" || %class $="DeployedTurret" || %class $="LogoProjector" || %class $="DeployedLightBase" || %class $="Tripwire" || %class $="Teleport" || %class $="Jumpad" || %class $="Tree" || %class $="Crate" || %class $="GravityField") return true; else return false; } function StaticShape::RevertPieces(%obj,%reset){ return RevertPieces(%obj,%reset); } function RevertPieces(%obj) { if (!%obj.getDataBlock().getName() $="DeployedEditorPack") return; %count = %obj.slotcount; %count = %count - 1; for (%i = 0; %i < %count; %i++) { %slotobj = %obj.slot[%i]; if (%reset) { %slotObj.slot = ""; %slotObj.editor = false; %obj.slot[%i] = ""; //Nada.. } if (%slotobj.istrotate) { %slotobj.erotation = ""; %slotobj.setrotation(%slotobj.oldrotation); if (%reset) %slotObj.isTRotate = false; } else if (%slotobj.istscale) { %slotobj.isescaled = false; %slotobj.escale = ""; %slotobj.setscale(%slotobj.oldscale); if (%reset) %slotObj.isTScale = false; } else if (%slotobj.istsize) { %slotobj.isesized = false; %slotobj.setscale(%slotobj.oldsize); if (%reset) %slotObj.isTSize = false; } else if (%slotobj.istfade) { %slotobj.isefaded = false; %slotobj.startfade(0,0,0); if (%reset) %slotObj.isTFade = false; } else if (%slotobj.istdebris) { %slotobj.isedebris = false; $Editor::Debris::Count--; if (%reset) %slotObj.isDebris = false; } else if (%slotobj.isthide) { %slotobj.isehidden = false; %slotobj.hide(0); if (%reset) %slotObj.isTHide = false; } else if (%slotobj.istcloak) { %slotobj.isecloaked = false; %slotobj.setcloaked(0); if (%reset) %slotObj.isTCloak = false; } %slotObj.cloakAnim(500); } return %obj; }
Ragora/T2-ScriptDump
scripts/ancient/packs/Piece Manipulator_3-0b.cs
C#
mit
37,696
/*global Showdown*/ describe('$showdown', function () { 'use strict'; beforeEach(module('pl.itcrowd.services')); it('should be possible to inject initialized $showdown converter', inject(function ($showdown) { expect($showdown).not.toBeUndefined(); })); it('should be instance of $showdown.converter', inject(function ($showdown) { expect($showdown instanceof Showdown.converter).toBeTruthy(); })); });
it-crowd/angular-js-itc-utils
test/unit/services/showdown.test.js
JavaScript
mit
454
import type { Prng } from '@dicebear/core'; import type { Options } from '../options'; import type { ComponentPickCollection } from '../static-types'; import { pickComponent } from './pickComponent'; type Props = { prng: Prng; options: Options; }; export function getComponents({ prng, options, }: Props): ComponentPickCollection { const eyesComponent = pickComponent({ prng, group: 'eyes', values: options.eyes, }); const eyebrowsComponent = pickComponent({ prng, group: 'eyebrows', values: options.eyebrows, }); const mouthComponent = pickComponent({ prng, group: 'mouth', values: options.mouth, }); const accessoiresComponent = pickComponent({ prng, group: 'accessoires', values: options.accessoires, }); return { eyes: eyesComponent, eyebrows: eyebrowsComponent, mouth: mouthComponent, accessoires: prng.bool(options.accessoiresProbability) ? accessoiresComponent : undefined, }; }
DiceBear/avatars
packages/@dicebear/adventurer-neutral/src/utils/getComponents.ts
TypeScript
mit
993
// Copyright (c) Charlie Poole, Rob Prouse and Contributors. MIT License - see LICENSE.txt #nullable enable using System; using System.Linq; using System.Reflection; using NUnit.Compatibility; using NUnit.Framework.Interfaces; namespace NUnit.Framework.Internal { /// <summary> /// The TypeWrapper class wraps a Type so it may be used in /// a platform-independent manner. /// </summary> public class TypeWrapper : ITypeInfo { /// <summary> /// Construct a TypeWrapper for a specified Type. /// </summary> public TypeWrapper(Type type) { Guard.ArgumentNotNull(type, nameof(Type)); Type = type; } /// <summary> /// Gets the underlying Type on which this TypeWrapper is based. /// </summary> public Type Type { get; private set; } /// <summary> /// Gets the base type of this type as an ITypeInfo /// </summary> public ITypeInfo? BaseType { get { var baseType = Type.GetTypeInfo().BaseType; return baseType != null ? new TypeWrapper(baseType) : null; } } /// <summary> /// Gets the Name of the Type /// </summary> public string Name { get { return Type.Name; } } /// <summary> /// Gets the FullName of the Type /// </summary> public string FullName { get { return Type.FullName; } } /// <summary> /// Gets the assembly in which the type is declared /// </summary> public Assembly Assembly { get { return Type.GetTypeInfo().Assembly; } } /// <summary> /// Gets the namespace of the Type /// </summary> public string Namespace { get { return Type.Namespace; } } /// <summary> /// Gets a value indicating whether the type is abstract. /// </summary> public bool IsAbstract { get { return Type.GetTypeInfo().IsAbstract; } } /// <summary> /// Gets a value indicating whether the Type is a generic Type /// </summary> public bool IsGenericType { get { return Type.GetTypeInfo().IsGenericType; } } /// <summary> /// Returns true if the Type wrapped is T /// </summary> public bool IsType(Type type) { return Type == type; } /// <summary> /// Gets a value indicating whether the Type has generic parameters that have not been replaced by specific Types. /// </summary> public bool ContainsGenericParameters { get { return Type.GetTypeInfo().ContainsGenericParameters; } } /// <summary> /// Gets a value indicating whether the Type is a generic Type definition /// </summary> public bool IsGenericTypeDefinition { get { return Type.GetTypeInfo().IsGenericTypeDefinition; } } /// <summary> /// Gets a value indicating whether the type is sealed. /// </summary> public bool IsSealed { get { return Type.GetTypeInfo().IsSealed; } } /// <summary> /// Gets a value indicating whether this type represents a static class. /// </summary> public bool IsStaticClass => Type.IsStatic(); /// <summary> /// Get the display name for this type /// </summary> public string GetDisplayName() { return TypeHelper.GetDisplayName(Type); } /// <summary> /// Get the display name for an object of this type, constructed with the specified args. /// </summary> public string GetDisplayName(object?[]? args) { return TypeHelper.GetDisplayName(Type, args); } /// <summary> /// Returns a new ITypeInfo representing an instance of this generic Type using the supplied Type arguments /// </summary> public ITypeInfo MakeGenericType(Type[] typeArgs) { return new TypeWrapper(Type.MakeGenericType(typeArgs)); } /// <summary> /// Returns a Type representing a generic type definition from which this Type can be constructed. /// </summary> public Type GetGenericTypeDefinition() { return Type.GetGenericTypeDefinition(); } /// <summary> /// Returns an array of custom attributes of the specified type applied to this type /// </summary> public T[] GetCustomAttributes<T>(bool inherit) where T : class { return Type.GetAttributes<T>(inherit); } /// <summary> /// Returns a value indicating whether the type has an attribute of the specified type. /// </summary> /// <typeparam name="T"></typeparam> /// <param name="inherit"></param> /// <returns></returns> public bool IsDefined<T>(bool inherit) where T : class { return Type.HasAttribute<T>(inherit); } /// <summary> /// Returns a flag indicating whether this type has a method with an attribute of the specified type. /// </summary> /// <param name="attributeType"></param> /// <returns></returns> public bool HasMethodWithAttribute(Type attributeType) { return Reflect.HasMethodWithAttribute(Type, attributeType); } /// <summary> /// Returns an array of IMethodInfos for methods of this Type /// that match the specified flags. /// </summary> public IMethodInfo[] GetMethods(BindingFlags flags) { var methods = Type.GetMethods(flags); var result = new MethodWrapper[methods.Length]; for (int i = 0; i < methods.Length; i++) result[i] = new MethodWrapper(Type, methods[i]); return result; } /// <summary> /// Gets the public constructor taking the specified argument Types /// </summary> public ConstructorInfo? GetConstructor(Type[] argTypes) { return Type.GetConstructor(argTypes); } /// <summary> /// Returns a value indicating whether this Type has a public constructor taking the specified argument Types. /// </summary> public bool HasConstructor(Type[] argTypes) { return GetConstructor(argTypes) != null; } /// <summary> /// Construct an object of this Type, using the specified arguments. /// </summary> public object Construct(object?[]? args) { return Reflect.Construct(Type, args); } /// <summary> /// Override ToString() so that error messages in NUnit's own tests make sense /// </summary> public override string ToString() { return Type.ToString(); } /// <summary> /// Returns all methods declared by this type that have the specified attribute, optionally /// including base classes. Methods from a base class are always returned before methods from a class that /// inherits from it. /// </summary> /// <param name="inherit">Specifies whether to search the fixture type inheritance chain.</param> public IMethodInfo[] GetMethodsWithAttribute<T>(bool inherit) where T : class { if (!inherit) { return Type .GetMethods(Reflect.AllMembers | BindingFlags.DeclaredOnly) .Where(method => method.IsDefined(typeof(T), inherit: false)) .Select(method => new MethodWrapper(Type, method)) .ToArray(); } var methodsByDeclaringType = Type .GetMethods(Reflect.AllMembers | BindingFlags.FlattenHierarchy) // FlattenHierarchy is complex to replicate by looping over base types with DeclaredOnly. .Where(method => method.IsDefined(typeof(T), inherit: true)) .ToLookup(method => method.DeclaringType); return Type.TypeAndBaseTypes() .Reverse() .SelectMany(declaringType => methodsByDeclaringType[declaringType].Select(method => new MethodWrapper(declaringType, method))) .ToArray(); } } }
nunit/nunit
src/NUnitFramework/framework/Internal/TypeWrapper.cs
C#
mit
8,699
define(function () { var exports = {}; /** * Hashes string with a guarantee that if you need to hash a new string * that contains already hashed string at it's start, you can pass only * added part of that string along with the hash of already computed part * and will get correctly hash as if you passed full string. * * @param {string} str * @param {number=} hash * @return {number} */ exports.hash = function (str, hash) { hash = hash || 5381; // alghorithm by Dan Bernstein var i = -1, length = str.length; while(++i < length) { hash = ((hash << 5) + hash) ^ str.charCodeAt(i); } return hash; }; var entityDecoder = document.createElement('div'); /** * Correctly decodes all hex, decimal and named entities * @param {string} text * @return {string} */ exports.decodeHtmlEntities = function(text){ return text.replace(/&(?:#(x)?(\d+)|(\w+));/g, function(match, hexFlag, decOrHex, name) { if(decOrHex) { return String.fromCharCode(parseInt(decOrHex, hexFlag ? 16 : 10)); } switch(name) { case 'lt': return '<'; case 'gt': return '>'; case 'amp': return '&'; case 'quote': return '"'; default: entityDecoder.innerHTML = '&' + name + ';'; return entityDecoder.textContent; } }); }; /** * Calculates shallow difference between two object * @param {Object} one * @param {Object} other * @return {Object} */ exports.shallowObjectDiff = function(one, other) { // since we will be calling setAttribute there is no need to // differentiate between changes and additions var set = {}, removed = [], haveChanges = false, keys = Object.keys(one), length, key, i; // first go through all keys of `one` for(i = 0, length = keys.length; i < length; ++i) { key = keys[i]; if(other[key] != null) { if(one[key] !== other[key]) { set[key] = other[key]; haveChanges = true; } } else { removed.push(key); haveChanges = true; } } // then add all missing from the `other` into `one` keys = Object.keys(other); for(i = 0, length = keys.length; i < length; ++i) { key = keys[i]; if(one[key] == null) { set[key] = other[key]; haveChanges = true; } } return haveChanges ? { set: set, removed: removed } : false; }; return exports; });
grassator/live-html
js/src/utils.js
JavaScript
mit
2,563
/* * Copyright © 2016 David Sargent * Permission is hereby granted, free of charge, to any person obtaining a copy of this software * and associated documentation files (the "Software"), to deal in the Software without restriction, * including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, * and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to * the following conditions: * * The above copyright notice and this permission notice shall be included in all copies or * substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING * BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, * DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING * FROM,OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ package org.ftccommunity.i2clibrary.interfaces; import com.qualcomm.robotcore.eventloop.opmode.OpMode; import com.qualcomm.robotcore.hardware.I2cDevice; import org.ftccommunity.i2clibrary.ClassFactory; import org.ftccommunity.i2clibrary.navigation.Acceleration; import org.ftccommunity.i2clibrary.navigation.AngularVelocity; import org.ftccommunity.i2clibrary.navigation.EulerAngles; import org.ftccommunity.i2clibrary.navigation.MagneticFlux; import org.ftccommunity.i2clibrary.navigation.Position; import org.ftccommunity.i2clibrary.navigation.Quaternion; import org.ftccommunity.i2clibrary.navigation.Velocity; /** * Interface API to the Adafruit 9-DOF Absolute Orientation IMU Fusion Breakout - BNO055 sensor. You * can create an implementation of this interface for a given sensor using {@link * ClassFactory#createAdaFruitBNO055IMU(OpMode, I2cDevice) ClassFactory.createAdaFruitBNO055IMU()}. * * @see IAccelerationIntegrator * @see ClassFactory#createAdaFruitBNO055IMU(OpMode, I2cDevice) * @see <a href="http://www.adafruit.com/products/2472">http://www.adafruit.com/products/2472</a> * @see <a href="http://www.bosch-sensortec.com/en/homepage/products_3/9_axis_sensors_5/ecompass_2/bno055_3/bno055_4">http://www.bosch-sensortec.com/en/homepage/products_3/9_axis_sensors_5/ecompass_2/bno055_3/bno055_4</a> */ public interface IBNO055IMU { //---------------------------------------------------------------------------------------------- // Construction //---------------------------------------------------------------------------------------------- /** * The size of the calibration data, starting at ACCEL_OFFSET_X_LSB, is 22 bytes. */ int cbCalibrationData = 22; /** * Initialize the sensor using the indicated set of parameters. Note that the execution of this * method can take a fairly long while, possibly several tens of milliseconds. * * @param parameters the parameters with which to initialize the IMU */ void initialize(Parameters parameters); /** * Shut down the sensor. This doesn't do anything in the hardware device itself, but rather * shuts down any resources (threads, etc) that we use to communicate with it. */ void close(); //---------------------------------------------------------------------------------------------- // Reading sensor output //---------------------------------------------------------------------------------------------- /** * Returns the current temperature. Units are as configured during initialization. * * @return the current temperature */ double getTemperature(); /** * Returns the magnetic field strength experienced by the sensor. See Section 3.6.5.2 of the * BNO055 specification. * * @return the magnetic field strength experienced by the sensor, in units of tesla * @see <a href="https://en.wikipedia.org/wiki/Tesla_(unit)">https://en.wikipedia.org/wiki/Tesla_(unit)</a> */ MagneticFlux getMagneticFieldStrength(); /** * Returns the overall acceleration experienced by the sensor. This is composed of a component * due to the movement of the sensor and a component due to the force of gravity. * * @return the overall acceleration vector experienced by the sensor */ Acceleration getOverallAcceleration(); /** * Returns the acceleration experienced by the sensor due to the movement of the sensor. * * @return the acceleration vector of the sensor due to its movement */ Acceleration getLinearAcceleration(); /** * Returns the direction of the force of gravity relative to the sensor. * * @return the acceleration vector of gravity relative to the sensor */ Acceleration getGravity(); /** * Returns the rate of change of the absolute orientation of the sensor. * * @return the rate at which the orientation of the sensor is changing. * @see #getAngularOrientation() */ AngularVelocity getAngularVelocity(); /** * Returns the absolute orientation of the sensor as a set of Euler angles. * * @return the absolute orientation of the sensor * @see #getQuaternionOrientation() */ EulerAngles getAngularOrientation(); /** * Returns the absolute orientation of the sensor as a quaternion. * * @return the absolute orientation of the sensor * @see #getAngularOrientation() */ Quaternion getQuaternionOrientation(); //---------------------------------------------------------------------------------------------- // Position and velocity management //---------------------------------------------------------------------------------------------- /** * Returns the current position of the sensor as calculated by doubly integrating the observed * sensor accelerations. * * @return the current position of the sensor. */ Position getPosition(); /** * Returns the current velocity of the sensor as calculated by integrating the observed sensor * accelerations. * * @return the current velocity of the sensor */ Velocity getVelocity(); /** * Returns the last observed acceleration of the sensor. Note that this does not communicate * with the sensor, but rather returns the most recent value reported to the acceleration * integration algorithm. * * @return the last observed acceleration of the sensor */ Acceleration getAcceleration(); /** * Start (or re-start) a thread that continuously at intervals polls the current linear * acceleration of the sensor and integrates it to provide velocity and position information. A * default polling interval of 100ms is used. * * @param initalPosition If non-null, the current sensor position is set to this value. If * null, the current sensor position is unchanged. * @param initialVelocity If non-null, the current sensor velocity is set to this value. If * null, the current sensor velocity is unchanged. * @see #startAccelerationIntegration(Position, Velocity) * @see #getLinearAcceleration() */ void startAccelerationIntegration(Position initalPosition, Velocity initialVelocity); /** * As in {@link #startAccelerationIntegration(Position, Velocity)}, but provides control over * the frequency which which the acceleration is polled. * * @param initalPosition If non-null, the current sensor position is set to this value. If * null, the current sensor position is unchanged. * @param initialVelocity If non-null, the current sensor velocity is set to this value. If * null, the current sensor velocity is unchanged. * @param msPollInterval the interval to use, in milliseconds, between successive calls to * {@link #getLinearAcceleration()} * @see #startAccelerationIntegration(Position, Velocity, int) */ void startAccelerationIntegration(Position initalPosition, Velocity initialVelocity, int msPollInterval); /** * Stop the integration thread if it is currently running. */ void stopAccelerationIntegration(); //---------------------------------------------------------------------------------------------- // Status inquiry //---------------------------------------------------------------------------------------------- /** * Returns the current status of the system. * * @return the current status of the system <p> See section 4.3.58 of the BNO055 specification. * @see #getSystemError() <p> <table summary="System Status Codes"> * <tr><td>Result</td><td>Meaning</td></tr> <tr><td>0</td><td>idle</td></tr> * <tr><td>1</td><td>system error</td></tr> <tr><td>2</td><td>initializing peripherals</td></tr> * <tr><td>3</td><td>system initialization</td></tr> <tr><td>4</td><td>executing * self-test</td></tr> <tr><td>5</td><td>sensor fusion algorithm running</td></tr> * <tr><td>6</td><td>system running without fusion algorithms</td></tr> </table> */ byte getSystemStatus(); /** * If {@link #getSystemStatus()} is 'system error' (1), returns particulars regarding that * error. <p> See section 4.3.58 of the BNO055 specification. * * @return the current error status * @see #getSystemStatus() <p> <table summary="System Error Codes"> * <tr><td>Result</td><td>Meaning</td></tr> <tr><td>0</td><td>no error</td></tr> * <tr><td>1</td><td>peripheral initialization error</td></tr> <tr><td>2</td><td>system * initialization error</td></tr> <tr><td>3</td><td>self test result failed</td></tr> * <tr><td>4</td><td>register map value out of range</td></tr> <tr><td>5</td><td>register map * address out of range</td></tr> <tr><td>6</td><td>register map write error</td></tr> * <tr><td>7</td><td>BNO low power mode not available for selected operation mode</td></tr> * <tr><td>8</td><td>acceleromoeter power mode not available</td></tr> <tr><td>9</td><td>fusion * algorithm configuration error</td></tr> <tr><td>A</td><td>sensor configuraton error</td></tr> * </table> */ byte getSystemError(); boolean isSystemCalibrated(); boolean isGyroCalibrated(); boolean isAccelerometerCalibrated(); boolean isMagnetometerCalibrated(); /** * Read calibration data from the IMU which later can be restored with writeCalibrationData(). * This might be persistently stored, and reapplied at a later power-on. <p> For greatest * utility, full calibration should be achieved before reading the calibration data * * @return the calibration data * @see #writeCalibrationData(byte[]) */ byte[] readCalibrationData(); /** * Write calibration data previously retrieved. * * @param data the calibration data to write * @see #readCalibrationData() */ void writeCalibrationData(byte[] data); /** * Low level: read the byte starting at the indicated register * * @param register the location from which to read the data * @return the data that was read */ byte read8(REGISTER register); //---------------------------------------------------------------------------------------------- // Low level reading and writing //---------------------------------------------------------------------------------------------- /** * Low level: read data starting at the indicated register * * @param register the location from which to read the data * @param cb the number of bytes to read * @return the data that was read */ byte[] read(REGISTER register, int cb); /** * Low level: write a byte to the indicated register * * @param register the location at which to write the data * @param bVal the data to write */ void write8(REGISTER register, int bVal); /** * Low level: write data starting at the indicated register * * @param register the location at which to write the data * @param data the data to write */ void write(REGISTER register, byte[] data); enum I2CADDR { UNSPECIFIED(-1), DEFAULT(0x28 * 2), ALTERNATE(0x29 * 2); public final byte bVal; I2CADDR(int i) { bVal = (byte) i; } } //---------------------------------------------------------------------------------------------- // Enumerations to make all of the above work //---------------------------------------------------------------------------------------------- enum TEMPUNIT { CELSIUS(0), FARENHEIT(1); public final byte bVal; TEMPUNIT(int i) { bVal = (byte) i; } } enum ANGLEUNIT { DEGREES(0), RADIANS(1); public final byte bVal; ANGLEUNIT(int i) { bVal = (byte) i; } } enum ACCELUNIT { METERS_PERSEC_PERSEC(0), MILLIGALS(1); public final byte bVal; ACCELUNIT(int i) { bVal = (byte) i; } } enum PITCHMODE { WINDOWS(0), ANDROID(1); public final byte bVal; PITCHMODE(int i) { bVal = (byte) i; } } /** * Sensor modes are described in Table 3-5 (p21) of the BNO055 specification, where they are * termed "operation modes". */ enum SENSOR_MODE { CONFIG(0X00), ACCONLY(0X01), MAGONLY(0X02), GYRONLY(0X03), ACCMAG(0X04), ACCGYRO(0X05), MAGGYRO(0X06), AMG(0X07), IMU(0X08), COMPASS(0X09), M4G(0X0A), NDOF_FMC_OFF(0X0B), NDOF(0X0C); //------------------------------------------------------------------------------------------ public final byte bVal; SENSOR_MODE(int i) { this.bVal = (byte) i; } } /** * REGISTER provides symbolic names for each of the BNO055 device registers */ enum REGISTER { /** * Controls which of the two register pages are visible */ PAGE_ID(0X07), CHIP_ID(0x00), ACCEL_REV_ID(0x01), MAG_REV_ID(0x02), GYRO_REV_ID(0x03), SW_REV_ID_LSB(0x04), SW_REV_ID_MSB(0x05), BL_REV_ID(0X06), /** * Acceleration data register */ ACCEL_DATA_X_LSB(0X08), ACCEL_DATA_X_MSB(0X09), ACCEL_DATA_Y_LSB(0X0A), ACCEL_DATA_Y_MSB(0X0B), ACCEL_DATA_Z_LSB(0X0C), ACCEL_DATA_Z_MSB(0X0D), /** * Magnetometer data register */ MAG_DATA_X_LSB(0X0E), MAG_DATA_X_MSB(0X0F), MAG_DATA_Y_LSB(0X10), MAG_DATA_Y_MSB(0X11), MAG_DATA_Z_LSB(0X12), MAG_DATA_Z_MSB(0X13), /** * Gyro data registers */ GYRO_DATA_X_LSB(0X14), GYRO_DATA_X_MSB(0X15), GYRO_DATA_Y_LSB(0X16), GYRO_DATA_Y_MSB(0X17), GYRO_DATA_Z_LSB(0X18), GYRO_DATA_Z_MSB(0X19), /** * Euler data registers */ EULER_H_LSB(0X1A), EULER_H_MSB(0X1B), EULER_R_LSB(0X1C), EULER_R_MSB(0X1D), EULER_P_LSB(0X1E), EULER_P_MSB(0X1F), /** * Quaternion data registers */ QUATERNION_DATA_W_LSB(0X20), QUATERNION_DATA_W_MSB(0X21), QUATERNION_DATA_X_LSB(0X22), QUATERNION_DATA_X_MSB(0X23), QUATERNION_DATA_Y_LSB(0X24), QUATERNION_DATA_Y_MSB(0X25), QUATERNION_DATA_Z_LSB(0X26), QUATERNION_DATA_Z_MSB(0X27), /** * Linear acceleration data registers */ LINEAR_ACCEL_DATA_X_LSB(0X28), LINEAR_ACCEL_DATA_X_MSB(0X29), LINEAR_ACCEL_DATA_Y_LSB(0X2A), LINEAR_ACCEL_DATA_Y_MSB(0X2B), LINEAR_ACCEL_DATA_Z_LSB(0X2C), LINEAR_ACCEL_DATA_Z_MSB(0X2D), /** * Gravity data registers */ GRAVITY_DATA_X_LSB(0X2E), GRAVITY_DATA_X_MSB(0X2F), GRAVITY_DATA_Y_LSB(0X30), GRAVITY_DATA_Y_MSB(0X31), GRAVITY_DATA_Z_LSB(0X32), GRAVITY_DATA_Z_MSB(0X33), /** * Temperature data register */ TEMP(0X34), /** * Status registers */ CALIB_STAT(0X35), SELFTEST_RESULT(0X36), INTR_STAT(0X37), SYS_CLK_STAT(0X38), SYS_STAT(0X39), SYS_ERR(0X3A), /** * Unit selection register */ UNIT_SEL(0X3B), DATA_SELECT(0X3C), /** * Mode registers */ OPR_MODE(0X3D), PWR_MODE(0X3E), SYS_TRIGGER(0X3F), TEMP_SOURCE(0X40), /** * Axis remap registers */ AXIS_MAP_CONFIG(0X41), AXIS_MAP_SIGN(0X42), /** * SIC registers */ SIC_MATRIX_0_LSB(0X43), SIC_MATRIX_0_MSB(0X44), SIC_MATRIX_1_LSB(0X45), SIC_MATRIX_1_MSB(0X46), SIC_MATRIX_2_LSB(0X47), SIC_MATRIX_2_MSB(0X48), SIC_MATRIX_3_LSB(0X49), SIC_MATRIX_3_MSB(0X4A), SIC_MATRIX_4_LSB(0X4B), SIC_MATRIX_4_MSB(0X4C), SIC_MATRIX_5_LSB(0X4D), SIC_MATRIX_5_MSB(0X4E), SIC_MATRIX_6_LSB(0X4F), SIC_MATRIX_6_MSB(0X50), SIC_MATRIX_7_LSB(0X51), SIC_MATRIX_7_MSB(0X52), SIC_MATRIX_8_LSB(0X53), SIC_MATRIX_8_MSB(0X54), /** * Accelerometer Offset registers */ ACCEL_OFFSET_X_LSB(0X55), ACCEL_OFFSET_X_MSB(0X56), ACCEL_OFFSET_Y_LSB(0X57), ACCEL_OFFSET_Y_MSB(0X58), ACCEL_OFFSET_Z_LSB(0X59), ACCEL_OFFSET_Z_MSB(0X5A), /** * Magnetometer Offset registers */ MAG_OFFSET_X_LSB(0X5B), MAG_OFFSET_X_MSB(0X5C), MAG_OFFSET_Y_LSB(0X5D), MAG_OFFSET_Y_MSB(0X5E), MAG_OFFSET_Z_LSB(0X5F), MAG_OFFSET_Z_MSB(0X60), /** * Gyroscope Offset register s */ GYRO_OFFSET_X_LSB(0X61), GYRO_OFFSET_X_MSB(0X62), GYRO_OFFSET_Y_LSB(0X63), GYRO_OFFSET_Y_MSB(0X64), GYRO_OFFSET_Z_LSB(0X65), GYRO_OFFSET_Z_MSB(0X66), /** * Radius registers */ ACCEL_RADIUS_LSB(0X67), ACCEL_RADIUS_MSB(0X68), MAG_RADIUS_LSB(0X69), MAG_RADIUS_MSB(0X6A); //------------------------------------------------------------------------------------------ public final byte bVal; REGISTER(int i) { this.bVal = (byte) i; } } /** * Instances of Parameters contain data indicating how a BNO055 absolute orientation sensor is * to be initialized. * * @see #initialize(Parameters) */ class Parameters { /** * the address at which the sensor resides on the I2C bus. */ public I2CADDR i2cAddr8Bit = I2CADDR.DEFAULT; /** * the mode we wish to use the sensor in */ public SENSOR_MODE mode = SENSOR_MODE.IMU; /** * whether to use the external or internal 32.768khz crystal. External crystal use is * recommended by the BNO055 specification. */ public boolean useExternalCrystal = true; /** * units in which temperature are measured. See Section 3.6.1 (p31) of the BNO055 * specification */ public TEMPUNIT temperatureUnit = TEMPUNIT.CELSIUS; /** * units in which angles and angular rates are measured. See Section 3.6.1 (p31) of the * BNO055 specification */ public ANGLEUNIT angleunit = ANGLEUNIT.RADIANS; /** * units in which accelerations are measured. See Section 3.6.1 (p31) of the BNO055 * specification */ public ACCELUNIT accelunit = ACCELUNIT.METERS_PERSEC_PERSEC; /** * directional convention for measureing pitch angles. See Section 3.6.1 (p31) of the BNO055 * specification */ public PITCHMODE pitchmode = PITCHMODE.ANDROID; // Section 3.6.2 /** * calibration data with which the BNO055 should be initialized */ public byte[] calibrationData = null; /** * the algorithm to use for integrating acceleration to produce velocity and position. If * not specified, a simple but not especially effective internal algorithm will be used. */ public IAccelerationIntegrator accelerationIntegrationAlgorithm = null; /** * the boost in thread priority to use for data acquisition. A small increase in the thread * priority can help reduce timestamping jitter and improve acceleration integration at only * a small detriment to other parts of the system. */ public int threadPriorityBoost = 0; /** * debugging aid: enable logging for this device? */ public boolean loggingEnabled = false; /** * debugging aid: the logging tag to use when logging */ public String loggingTag = "AdaFruitIMU"; } }
MHS-FIRSTrobotics/TeamClutch-FTC2016
I2cLibrary/src/main/java/org/ftccommunity/i2clibrary/interfaces/IBNO055IMU.java
Java
mit
21,574
<?php use Symfony\Component\Routing\Exception\MethodNotAllowedException; use Symfony\Component\Routing\Exception\ResourceNotFoundException; use Symfony\Component\Routing\RequestContext; /** * appprodUrlMatcher * * This class has been auto-generated * by the Symfony Routing Component. */ class appprodUrlMatcher extends Symfony\Bundle\FrameworkBundle\Routing\RedirectableUrlMatcher { /** * Constructor. */ public function __construct(RequestContext $context) { $this->context = $context; } public function match($pathinfo) { $allow = array(); $pathinfo = rawurldecode($pathinfo); // hello if (0 === strpos($pathinfo, '/hello') && preg_match('#^/hello/(?P<name>[^/]+)$#s', $pathinfo, $matches)) { return array_merge($this->mergeDefaults($matches, array ( '_controller' => 'ZMB\\HelloBundle\\Controller\\HelloController::indexAction',)), array('_route' => 'hello')); } throw 0 < count($allow) ? new MethodNotAllowedException(array_unique($allow)) : new ResourceNotFoundException(); } }
polo90344/sym_home
app/cache/prod/appprodUrlMatcher.php
PHP
mit
1,101
from models import Event from django.views.generic import DetailView, ListView class EventListView(ListView): template_name = 'agenda/event_list.html' queryset = Event.objects.upcoming() paginate_by = 20 class EventArchiveview(EventListView): queryset = Event.objects.past() class EventDetailView(DetailView): model = Event template_name = 'agenda/event_detail.html'
feinheit/feincms-elephantagenda
elephantagenda/views.py
Python
mit
403
package com.example.MacGo; import com.parse.Parse; import com.parse.ParseObject; import java.text.Format; import java.text.SimpleDateFormat; import java.util.Calendar; import java.util.Date; import java.util.Locale; /** * Created by KD on 1/12/2015. */ public class Item { String itemId; String itemName; Number itemPrice; int calories; Number itemQuantity; private static ParseObject category; public final String getItemId() { return itemId; } public Number getPurchaseItemQuantity() { return itemQuantity; } public final String getItemName() { return itemName; } public final Number getItemPrice() { return itemPrice; } public final int getItemCalories() { return calories; } public final ParseObject getItemCategory() { return category; } public static String covertDataFormat(Date date, String format) { String formatDate = "00 MMMMM YYYY"; Format sdf = new SimpleDateFormat(format, Locale.US); Calendar calendar = Calendar.getInstance(); calendar.setTime(date); int hours = calendar.get(Calendar.HOUR); if (calendar.get(Calendar.AM_PM) == Calendar.PM) { formatDate = sdf.format(date).toString() + " @"+hours+"pm"; } else { formatDate = sdf.format(date).toString() + " @"+hours+"am"; } return formatDate; } public Item(String itemId, String itemName, Number itemPrice, int calories, Number itemQuantity,ParseObject category) { this.itemId = itemId; this.itemName = itemName; this.itemPrice = itemPrice; this.itemQuantity = itemQuantity; this.calories = calories; this.category = category; } }
McMasterGo/MacGo_Android
app/src/main/java/com/example/MacGo/Item.java
Java
mit
1,892
using System; using System.Linq.Expressions; using Remotion.Linq.Clauses; using Remotion.Linq.Clauses.ResultOperators; using Remotion.Linq.Clauses.StreamedData; namespace Marten.Linq.Operators { public class ToJsonArrayResultOperator : SequenceTypePreservingResultOperatorBase { public ToJsonArrayResultOperator(Expression parameter) { Parameter = parameter; } public Expression Parameter { get; private set; } public override ResultOperatorBase Clone(CloneContext cloneContext) { return new ToJsonArrayResultOperator(Parameter); } public override void TransformExpressions( Func<Expression, Expression> transformation) { Parameter = transformation(Parameter); } public override StreamedSequence ExecuteInMemory<T>(StreamedSequence input) { return input; } } }
JasperFx/Marten
src/Marten/Linq/Operators/ToJsonArrayResultOperator.cs
C#
mit
952
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import models, migrations class Migration(migrations.Migration): dependencies = [ ] operations = [ migrations.CreateModel( name='Prueba', fields=[ ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)), ('nombre', models.CharField(max_length=100)), ], options={ }, bases=(models.Model,), ), ]
HenryGBC/landing_company
landing/migrations/0001_initial.py
Python
mit
556
version https://git-lfs.github.com/spec/v1 oid sha256:558005fd55405d3069b06849812a921274543d712676f42ad4a8c122034c02e4 size 819
yogeshsaroya/new-cdnjs
ajax/libs/mathjax/2.4.0/localization/eo/TeX.js
JavaScript
mit
128
let allExpenses exports.up = (knex, Promise) => { return knex('expenses').select('*') .then(expenses => { allExpenses = expenses return knex.schema.createTable('expense_items', (table) => { table.increments('id').primary().notNullable() table.integer('expense_id').notNullable().references('id').inTable('expenses') table.integer('position').notNullable() table.decimal('preTaxAmount').notNullable() table.decimal('taxrate').notNullable() table.text('description') table.index('expense_id') }) }) .then(() => { // this is necessary BEFORE creating the expense items because knex // drops the expenses table and then recreates it (foreign key problem). console.log('Dropping "preTaxAmount" and "taxrate" columns in expenses') return knex.schema.table('expenses', table => { table.dropColumn('preTaxAmount') table.dropColumn('taxrate') }) }) .then(() => { console.log('Migrating ' + allExpenses.length + ' expenses to items') return Promise.all( allExpenses.map(expense => createExpenseItem(knex, expense)) ) }) } exports.down = (knex, Promise) => { return knex.schema.dropTableIfExists('expense_items') } function createExpenseItem(knex, expense) { return knex('expense_items') .insert({ expense_id: expense.id, position: 0, preTaxAmount: expense.preTaxAmount, taxrate: expense.taxrate, description: '' }) }
haimich/billy
sql/migrations/20170323200721_expense_items.js
JavaScript
mit
1,527
// A method override middleware for [rkgo/web](https://github.com/rkgo/web) // // app := web.New() // app.Use(methodoverride.Middleware()) // package methodoverride import ( "strings" "github.com/rkgo/web" ) const ( overrideFormField = "_method" overrideHeader = "X-HTTP-Method-Override" ) // The method override middleware allows overriding a POST request to a PUT, // PATCH or DELETE request using either the form field `_method` or the // header X-HTTP-Method-Override. func Middleware() web.Middleware { return func(ctx web.Context, next web.Next) { if ctx.Req().Method == "POST" { method := ctx.Req().FormValue(overrideFormField) if len(ctx.Req().Header.Get(overrideHeader)) > 0 { method = ctx.Req().Header.Get(overrideHeader) } if len(method) > 0 { method = strings.ToUpper(method) switch method { case "PUT", "PATCH", "DELETE": ctx.Req().Method = method } } } next(ctx) } }
rkgo/methodoverride
methodoverride.go
GO
mit
946
var express = require('express'); var app = express(); var path = require('path'); var session = require('express-session'); var bodyParser = require('body-parser') var fs = require('fs'); app.use(express.static(path.join(__dirname, 'public'))); app.use(bodyParser.urlencoded({extended: true})); app.use(bodyParser.json()); app.use(session({ secret: 'angular_tutorial', resave: true, saveUninitialized: true, })); var Db = require('mongodb').Db; var Connection = require('mongodb').Connection; var Server = require('mongodb').Server; var ObjectID = require('mongodb').ObjectID; var db = new Db('tutor', new Server("localhost", 27017, {safe: true}, {auto_reconnect: true}, {})); db.open(function(){ console.log("mongo db is opened!"); db.collection('notes', function(error, notes) { db.notes = notes; }); db.collection('sections', function(error, sections) { db.sections = sections; }); }); app.get("/notes", function(req,res) { db.notes.find(req.query).toArray(function(err, items) { res.send(items); }); }); app.post("/notes", function(req,res) { db.notes.insert(req.body); res.end(); }); app.get("/sections", function(req,res) { db.sections.find(req.query).toArray(function(err, items) { res.send(items); }); }); app.get("/checkUser", function(req,res) { if (req.query.user.length>2) { res.send(true); } else { res.send(false); } }); app.post("/sections/replace", function(req,resp) { // do not clear the list if (req.body.length==0) { resp.end(); } // this should be used only for reordering db.sections.remove({}, function(err, res) { if (err) console.log(err); db.sections.insert(req.body, function(err, res) { if (err) console.log("err after insert",err); resp.end(); }); }); }); app.listen(3000);
RomanLysak/angularJsLabsLuxoft
courceLabsReady/task10/server.js
JavaScript
mit
1,778
#!/usr/bin/env python """ Download NLTK data """ __author__ = "Manan Kalra" __email__ = "manankalr29@gmail.com" import nltk nltk.download()
manankalra/Twitter-Sentiment-Analysis
demo/download.py
Python
mit
145
import numpy as np import ctypes import struct import time # relative imports in Python3 must be explicit from .ioctl_numbers import _IOR, _IOW from fcntl import ioctl SPI_IOC_MAGIC = ord("k") SPI_IOC_RD_MODE = _IOR(SPI_IOC_MAGIC, 1, "=B") SPI_IOC_WR_MODE = _IOW(SPI_IOC_MAGIC, 1, "=B") SPI_IOC_RD_LSB_FIRST = _IOR(SPI_IOC_MAGIC, 2, "=B") SPI_IOC_WR_LSB_FIRST = _IOW(SPI_IOC_MAGIC, 2, "=B") SPI_IOC_RD_BITS_PER_WORD = _IOR(SPI_IOC_MAGIC, 3, "=B") SPI_IOC_WR_BITS_PER_WORD = _IOW(SPI_IOC_MAGIC, 3, "=B") SPI_IOC_RD_MAX_SPEED_HZ = _IOR(SPI_IOC_MAGIC, 4, "=I") SPI_IOC_WR_MAX_SPEED_HZ = _IOW(SPI_IOC_MAGIC, 4, "=I") SPI_CPHA = 0x01 # /* clock phase */ SPI_CPOL = 0x02 # /* clock polarity */ SPI_MODE_0 = (0|0) # /* (original MicroWire) */ SPI_MODE_1 = (0|SPI_CPHA) SPI_MODE_2 = (SPI_CPOL|0) SPI_MODE_3 = (SPI_CPOL|SPI_CPHA) class Lepton(object): """Communication class for FLIR Lepton module on SPI Args: spi_dev (str): Location of SPI device node. Default '/dev/spidev0.0'. """ ROWS = 60 COLS = 80 VOSPI_FRAME_SIZE = COLS + 2 VOSPI_FRAME_SIZE_BYTES = VOSPI_FRAME_SIZE * 2 MODE = SPI_MODE_3 BITS = 8 SPEED = 18000000 SPIDEV_MESSAGE_LIMIT = 24 def __init__(self, spi_dev = "/dev/spidev0.0"): self.__spi_dev = spi_dev self.__txbuf = np.zeros(Lepton.VOSPI_FRAME_SIZE, dtype=np.uint16) # struct spi_ioc_transfer { # __u64 tx_buf; # __u64 rx_buf; # __u32 len; # __u32 speed_hz; # __u16 delay_usecs; # __u8 bits_per_word; # __u8 cs_change; # __u32 pad; # }; self.__xmit_struct = struct.Struct("=QQIIHBBI") self.__msg_size = self.__xmit_struct.size self.__xmit_buf = np.zeros((self.__msg_size * Lepton.ROWS), dtype=np.uint8) self.__msg = _IOW(SPI_IOC_MAGIC, 0, self.__xmit_struct.format) self.__capture_buf = np.zeros((Lepton.ROWS, Lepton.VOSPI_FRAME_SIZE, 1), dtype=np.uint16) for i in range(Lepton.ROWS): self.__xmit_struct.pack_into(self.__xmit_buf, i * self.__msg_size, self.__txbuf.ctypes.data, # __u64 tx_buf; self.__capture_buf.ctypes.data + Lepton.VOSPI_FRAME_SIZE_BYTES * i, # __u64 rx_buf; Lepton.VOSPI_FRAME_SIZE_BYTES, # __u32 len; Lepton.SPEED, # __u32 speed_hz; 0, # __u16 delay_usecs; Lepton.BITS, # __u8 bits_per_word; 1, # __u8 cs_change; 0) # __u32 pad; def __enter__(self): # "In Python 3 the only way to open /dev/tty under Linux appears to be 1) in binary mode and 2) with buffering disabled." self.__handle = open(self.__spi_dev, "wb+", buffering=0) ioctl(self.__handle, SPI_IOC_RD_MODE, struct.pack("=B", Lepton.MODE)) ioctl(self.__handle, SPI_IOC_WR_MODE, struct.pack("=B", Lepton.MODE)) ioctl(self.__handle, SPI_IOC_RD_BITS_PER_WORD, struct.pack("=B", Lepton.BITS)) ioctl(self.__handle, SPI_IOC_WR_BITS_PER_WORD, struct.pack("=B", Lepton.BITS)) ioctl(self.__handle, SPI_IOC_RD_MAX_SPEED_HZ, struct.pack("=I", Lepton.SPEED)) ioctl(self.__handle, SPI_IOC_WR_MAX_SPEED_HZ, struct.pack("=I", Lepton.SPEED)) return self def __exit__(self, type, value, tb): self.__handle.close() @staticmethod def capture_segment(handle, xs_buf, xs_size, capture_buf): messages = Lepton.ROWS iow = _IOW(SPI_IOC_MAGIC, 0, xs_size) ioctl(handle, iow, xs_buf, True) while (capture_buf[0] & 0x000f) == 0x000f: # byteswapped 0x0f00 ioctl(handle, iow, xs_buf, True) messages -= 1 # NB: the default spidev bufsiz is 4096 bytes so that's where the 24 message limit comes from: 4096 / Lepton.VOSPI_FRAME_SIZE_BYTES = 24.97... # This 24 message limit works OK, but if you really need to optimize the read speed here, this hack is for you: # The limit can be changed when spidev is loaded, but since it is compiled statically into newer raspbian kernels, that means # modifying the kernel boot args to pass this option. This works too: # $ sudo chmod 666 /sys/module/spidev/parameters/bufsiz # $ echo 65536 > /sys/module/spidev/parameters/bufsiz # Then Lepton.SPIDEV_MESSAGE_LIMIT of 24 can be raised to 59 while messages > 0: if messages > Lepton.SPIDEV_MESSAGE_LIMIT: count = Lepton.SPIDEV_MESSAGE_LIMIT else: count = messages iow = _IOW(SPI_IOC_MAGIC, 0, xs_size * count) ret = ioctl(handle, iow, xs_buf[xs_size * (60 - messages):], True) if ret < 1: raise IOError("can't send {0} spi messages ({1})".format(60, ret)) messages -= count def capture(self, data_buffer = None, log_time = False, debug_print = False, retry_reset = True): """Capture a frame of data. Captures 80x60 uint16 array of non-normalized (raw 12-bit) data. Returns that frame and a frame_id (which is currently just the sum of all pixels). The Lepton will return multiple, identical frames at a rate of up to ~27 Hz, with unique frames at only ~9 Hz, so the frame_id can help you from doing additional work processing duplicate frames. Args: data_buffer (numpy.ndarray): Optional. If specified, should be ``(60,80,1)`` with `dtype`=``numpy.uint16``. Returns: tuple consisting of (data_buffer, frame_id) """ start = time.time() if data_buffer is None: data_buffer = np.ndarray((Lepton.ROWS, Lepton.COLS, 1), dtype=np.uint16) elif data_buffer.ndim < 2 or data_buffer.shape[0] < Lepton.ROWS or data_buffer.shape[1] < Lepton.COLS or data_buffer.itemsize < 2: raise Exception("Provided input array not large enough") while True: Lepton.capture_segment(self.__handle, self.__xmit_buf, self.__msg_size, self.__capture_buf[0]) if retry_reset and (self.__capture_buf[20, 0] & 0xFF0F) != 0x1400: # make sure that this is a well-formed frame, should find line 20 here # Leave chip select deasserted for at least 185 ms to reset if debug_print: print("Garbage frame number reset waiting...") time.sleep(0.185) else: break self.__capture_buf.byteswap(True) data_buffer[:,:] = self.__capture_buf[:,2:] end = time.time() if debug_print: print("---") for i in range(Lepton.ROWS): fid = self.__capture_buf[i, 0, 0] crc = self.__capture_buf[i, 1, 0] fnum = fid & 0xFFF print("0x{0:04x} 0x{1:04x} : Row {2:2} : crc={1}".format(fid, crc, fnum)) print("---") if log_time: print("frame processed int {0}s, {1}hz".format(end-start, 1.0/(end-start))) # TODO: turn on telemetry to get real frame id, sum on this array is fast enough though (< 500us) return data_buffer, data_buffer.sum()
varunsuresh2912/SafeRanger
Python PiCode/Lepton.py
Python
mit
7,177
import numpy as np import matplotlib.pyplot as plt from astropy.io import fits from scipy.interpolate import interp1d,splev,splrep def extractSpectrum(filename): """ NAME: extractSpectrum PURPOSE: To open an input fits file from SDSS and extract the relevant components, namely the flux and corresponding wavelength. INPUTS: filename The path and filename (including the extension) to the file to be read in. OUTPUTS: lam The wavelengths, in angstrom, of the flux values flux The actual flux, in arbitrary units EXAMPLE: flux, lam = extractSpectra('path/to/file/filename.fits') """ hdu = fits.open(filename) #Open the file using astropy data = hdu[1].data #Data is in 2nd component of HDU flux = data['flux'] #Get flux from read in dict lam = 10**(data['loglam']) #Get wavelength, make it not log10 hdu.close() #Close the file, we're done with it return lam, flux #Return the values as numpy arrays def interpolate(points, lam, flux, method): """ NAME: interpolate PURPOSE: General purpose function that can call and use various scipy.interpolate methods. Defined for convienience. INPUTS: points Set of new points to get interpolated values for. lam The wavelengths of the data points flux The fluxes of the data points method The method of interpolation to use. Valide values include 'interp1d:linear', 'interp1d:quadratic', and 'splrep'. OUTPUTS: Interpolated set of values for each corresponding input point. EXAMPLE: interpFlux = interpolate(interpLam, lam, flux) """ if method == 'interp1d:linear': f = interp1d(lam, flux, assume_sorted = True) return f(points) if method == 'interp1d:quadratic': f = interp1d(lam, flux, kind = 'quadratic', assume_sorted = True) return f(points) if method == 'splrep': return splev(points, splrep(lam, flux)) raise Exception("You didn't choose a proper interpolating method") #First extract the flux and corresponding wavelength fileName = 'spec-4053-55591-0938.fits' lam, flux = extractSpectrum(fileName) #Now let's plot it, without any processing plt.figure(1) plt.plot(lam, flux, '-o', lw = 1.5, c = (0.694,0.906,0.561), mec = 'none', ms = 4, label = 'Original data') plt.xlabel('Wavelength', fontsize = 16) plt.ylabel('Flux', fontsize = 16) plt.ylim(0,1.1*max(flux)) #Now let's interpolate and plot that up interpLam = np.arange(4000,10000,1) interpFlux = interpolate(interpLam, lam, flux, 'splrep') #This is my own method plt.plot(interpLam, interpFlux, '-k', label = 'Interpolated') plt.legend(loc = 0) plt.show(block = False) print('Done...')
BU-PyCon/Meeting-3
Programs/interpolate.py
Python
mit
3,010
import { NgModule } from '@angular/core'; import { Routes, RouterModule } from '@angular/router'; import { UserListComponent } from "../user-list/user-list.component"; import { UserDetailComponent } from "../user-detail/user-detail.component"; const routes: Routes = [ { path: '', children: [ { path: '', component: UserListComponent, data: { title: 'Users' } }, { path: 'add', component: UserDetailComponent, data: { title: 'Add User' } } ] } ]; @NgModule({ imports: [RouterModule.forChild(routes)], exports: [RouterModule] }) export class UsersRoutingModule { }
gcasanova90/tp-support
client/app/users/_shared/users-routing.module.ts
TypeScript
mit
599
var Screen = require('./basescreen'); var Game = require('../game'); var helpScreen = new Screen('Help'); // Define our winning screen helpScreen.render = function (display) { var text = 'jsrogue help'; var border = '-------------'; var y = 0; display.drawText(Game.getScreenWidth() / 2 - text.length / 2, y++, text); display.drawText(Game.getScreenWidth() / 2 - text.length / 2, y++, border); display.drawText(0, y++, 'The villagers have been complaining of a terrible stench coming from the cave.'); display.drawText(0, y++, 'Find the source of this smell and get rid of it!'); y += 3; display.drawText(0, y++, '[h or Left Arrow] to move left'); display.drawText(0, y++, '[l or Right Arrow] to move right'); display.drawText(0, y++, '[j or Down Arrow] to move down'); display.drawText(0, y++, '[k or Up Arrow] to move up'); display.drawText(0, y++, '[,] to pick up items'); //display.drawText(0, y++, '[d] to drop items'); //display.drawText(0, y++, '[e] to eat items'); //display.drawText(0, y++, '[w] to wield items'); //display.drawText(0, y++, '[W] to wield items'); //display.drawText(0, y++, '[x] to examine items'); display.drawText(0, y++, '[i] to view and manipulate your inventory'); display.drawText(0, y++, '[;] to look around you'); display.drawText(0, y++, '[?] to show this help screen'); y += 3; text = '--- press any key to continue ---'; display.drawText(Game.getScreenWidth() / 2 - text.length / 2, y++, text); }; helpScreen.handleInput = function (inputType, inputData) { // Switch back to the play screen. this.getParentScreen().setSubScreen(undefined); }; module.exports = helpScreen;
shaddockh/js_roguelike_tutorial
client/assets/screens/helpscreen.js
JavaScript
mit
1,665
requirejs(['helper/util'], function(util){ });
mcramos/financaspessoais
scripts/helper/util.js
JavaScript
mit
47
package au.id.villar.email.webClient.users; public interface UserDao { User find(String username); User find(int id); User create(String username, String password); void remove(int userId); }
morgano5/mail_web_client
src/main/java/au/id/villar/email/webClient/users/UserDao.java
Java
mit
214
import unittest import random from pygraph.classes.graph import graph class SWIM(object): def __init__(self, graph): self.graph = graph def edge_alive(self, nodeA, nodeB, alive): ''' edge_alive(A, B, True|False) ''' edge = (nodeA, nodeB) if alive: self.graph.add_edge(edge) else: self.graph.del_edge(edge) def node_alive(self, node, alive): ''' node_alive(A, True|False) ''' if alive: self.graph.node_attributes(node).clear() else: self.graph.node_attributes(node).append("dead") def ping(self, nodeStart, nodeEnd, k): ''' NodeStart to ping NodeEnd directly or indirectly through K random neighbors. Return True if nodeEnd receives ping, or False otherwise ''' g = self.graph # Check if direct ping works if g.has_edge((nodeStart, nodeEnd)) and \ "dead" not in g.node_attributes(nodeEnd): return True # Pick k random neighbors and let them ping end node for neighbor in self._random_neighbors(nodeStart, k): if self.ping(neighbor, nodeEnd, 0): return True # All pings have failed return False def _random_neighbors(self, node, b): neighbors = self.graph.neighbors(node) if len(neighbors) <= b: return neighbors else: return random.sample(neighbors, b) class SWIMTest(unittest.TestCase): def setUp(self): g = graph() g.add_nodes(xrange(10)) g.complete() self.graph = g self.swim = SWIM(g) def test_good_ping(self): swim = self.swim self.assertTrue(swim.ping(0, 1, 0)) self.assertTrue(swim.ping(1, 3, 0)) def test_dead_edge_ping(self): swim = self.swim swim.edge_alive(0, 1, False) self.assertFalse(swim.ping(0, 1, 0)) self.assertTrue(swim.ping(0, 1, 1)) def test_dead_node_ping(self): swim = self.swim swim.node_alive(2, False) self.assertFalse(swim.ping(0, 2, 0)) self.assertFalse(swim.ping(0, 2, 3)) if __name__ == '__main__': unittest.main()
achoi007/CloudComputing
Concepts/SWIM.py
Python
mit
2,292
namespace ArgentPonyWarcraftClient; public partial class WarcraftClient { /// <inheritdoc /> public async Task<RequestResult<CharacterEncountersSummary>> GetCharacterEncountersSummaryAsync(string realmSlug, string characterName, string @namespace) { return await GetCharacterEncountersSummaryAsync(realmSlug, characterName, @namespace, Region, Locale); } /// <inheritdoc /> public async Task<RequestResult<CharacterEncountersSummary>> GetCharacterEncountersSummaryAsync(string realmSlug, string characterName, string @namespace, Region region, Locale locale) { string host = GetHost(region); return await GetAsync<CharacterEncountersSummary>($"{host}/profile/wow/character/{realmSlug}/{characterName?.ToLowerInvariant()}/encounters?namespace={@namespace}&locale={locale}"); } /// <inheritdoc /> public async Task<RequestResult<CharacterDungeons>> GetCharacterDungeonsAsync(string realmSlug, string characterName, string @namespace) { return await GetCharacterDungeonsAsync(realmSlug, characterName, @namespace, Region, Locale); } /// <inheritdoc /> public async Task<RequestResult<CharacterDungeons>> GetCharacterDungeonsAsync(string realmSlug, string characterName, string @namespace, Region region, Locale locale) { string host = GetHost(region); return await GetAsync<CharacterDungeons>($"{host}/profile/wow/character/{realmSlug}/{characterName?.ToLowerInvariant()}/encounters/dungeons?namespace={@namespace}&locale={locale}"); } /// <inheritdoc /> public async Task<RequestResult<CharacterRaids>> GetCharacterRaidsAsync(string realmSlug, string characterName, string @namespace) { return await GetCharacterRaidsAsync(realmSlug, characterName, @namespace, Region, Locale); } /// <inheritdoc /> public async Task<RequestResult<CharacterRaids>> GetCharacterRaidsAsync(string realmSlug, string characterName, string @namespace, Region region, Locale locale) { string host = GetHost(region); return await GetAsync<CharacterRaids>($"{host}/profile/wow/character/{realmSlug}/{characterName?.ToLowerInvariant()}/encounters/raids?namespace={@namespace}&locale={locale}"); } }
danjagnow/ArgentPonyWarcraftClient
src/ArgentPonyWarcraftClient/Client/ProfileApi/CharacterEncountersApi.cs
C#
mit
2,248
<center> <img src="http://www.mporzio.astro.it/~mkast/globular_1.gif"><br> <img src="http://www.mporzio.astro.it/~mkast/globular_2.gif"> </center> <p> <br> <br> <center> <p> <hr WIDTH="100%"></center> <p><br> <h3><i> Based upon the<br> <font face="Arial,Helvetica"> <a href="http://physun.physics.mcmaster.ca/Globular.html"> Catalog of parameters for Milky Way globular clusters</a><br> </font> compiled by <a href="http://physun.physics.mcmaster.ca/~harris/WEHarris.html"> William E. Harris. </a> </i></h3> <p> <h3> Ref.: <a href="http://cdsads.u-strasbg.fr/cgi-bin/nph-bib_query?bibcode=1996AJ....112.1487H"> Harris, W.E. 1996, Astronomical Journal, 112, 1487</a></h3> <p> <hr> <p> <table> <tr> <td> <img src="lavori.gif"> </td> <td> <i> <b> Note:</b> the present version (which makes use of a <a href="http://www.mysql.com">MySQL</a> database) is <strong>under developement</strong> and at the moment it's still very preliminary.<br> To switch to the "old" version <a href="http://www.mporzio.astro.it/~mkast/gc.html"> clich here</a>. </i> </td> </tr> </table> <p> <hr> <p>
gclusters/gclusters
inte.php
PHP
mit
1,097
package com.ekey.service.impl; import com.ekey.repository.BooksRepository; import com.ekey.repository.UserRepository; import com.ekey.models.Book; import com.ekey.models.Transaction; import com.ekey.models.User; import com.ekey.models.out.UserOut; import com.ekey.service.TransactionService; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import java.util.ArrayList; import java.util.Collection; /** * Created by faos7 on 12.11.16. */ @Service public class TransactionServiceImpl implements TransactionService { private static final Logger LOGGER = LoggerFactory.getLogger(TransactionServiceImpl.class); private UserRepository userRepository; private BooksRepository booksRepository; @Autowired public TransactionServiceImpl(UserRepository userRepository, BooksRepository booksRepository) { this.userRepository = userRepository; this.booksRepository = booksRepository; } @Override public Collection<Book> getAllBooksStudentEverHad(Long studentCardId) { User user = userRepository.findOneByStudentCardId(studentCardId); Collection<Transaction> transactions = user.getStTransactions(); Collection<Book> res = new ArrayList<>(); for (Transaction tx:transactions) { res.add(tx.getBook()); } return res; } @Override public Collection<Book> getAllBooksLibrarianEverGiven(Long studentCardId) { User user = userRepository.findOneByStudentCardId(studentCardId); Collection<Transaction> transactions = user.getLbTransactions(); Collection<Book> res = new ArrayList<>(); for (Transaction tx:transactions) { res.add(tx.getBook()); } return res; } @Override public Collection<UserOut> getAllBookOwners(String number) { Book book = booksRepository.findOneByNumber(number).get(); Collection<Transaction> transactions = book.getTransactions(); Collection<UserOut> res = new ArrayList<>(); for (Transaction tx:transactions) { res.add(new UserOut(tx.getStudent())); } return res; } @Override public Transaction getTransactionByBookAndStudent(User student, Book book) { Collection<Transaction> transactions = student.getStTransactions(); Transaction tx = new Transaction(); for (Transaction transaction:transactions) { if (tx.isFinished() == false){ if (transaction.getBook() == book){ tx = transaction; } } } return tx; } }
Faos7/ekey_backend_java
src/main/java/com/ekey/service/impl/TransactionServiceImpl.java
Java
mit
2,722
<?php /** * Description of FoursquareUser * * @author ner0tic */ namespace Ddnet\FoursquareBundle\Foursquare; class FoursquareUser { //extends FoursquareBase { protected $id = null, $createdAt = null, $oAuthToken = null, $fname = null, $lname = null, $homeCity = null, $photo = null, $gender = null, $relationship = null; protected $type = null, $contact = array( 'twitter' => null, 'phone' => null, 'formattedPhone' => null ), $pings = null, $mayorships = array(), $tips = array(), $todos = array(), $photos = array(), $friends = array(), $followers = null, $requests = null, $pageInfo = null; public static function createFromArray($a = array()) { if(sizeof($a)===0) throw new FoursquareException('not an array'); return new FoursquareUser($a); } public function __construct() { $args = func_get_args(); } //getters public function getId() { return $this->id; } public function getFirstname() { return $this->fname; } public function getLastname() { return $this->lname; } public function getHomeCity() { return $this->homeCity; } public function getPhoto() { return $this->photo; } public function getGender() { return $this->gender; } public function getRelationship() { return $this->relationship; } public function getType() { return $this->type; } public function getTwitter() { return $this->contact['twitter']; } public function getPhone($formatted=true) { return $formatted ? $this->contact['formattedPhone'] : $this->contact['phone']; } public function getPings() { return $this->ping; } public function getMayorships() { return $this->mayorships; } public function getTips() { return $this->tips; } public function getTodos() { return $this->todos; } public function getPhotos() { return $this->photos; } public function getFriends() { return $this->friends; } public function getFollowers() { return $this->followers; } public function getRequests() { return $this->requests; } public function getPageInfo() { return $this->pageInfo; } //setters public function setFirstname($n) { $this->fname = $n; return $this; } public function setLastname($n) { $this->lname = $n; return $this; } public function setHomeCity($c) { $this->homeCity = $c; return $this; } public function setPhoto(FoursquarePhoto $p) { $this->photo = $p; return $this; } public function setGender($g) { switch($g) { case 'm': case 'male': $this->gender = 'm'; break; case 'f': case 'female': $this->gender = 'f'; break; default: $this->gender = null; break; } return $this; } public function setRelationship($r) { $this->relationship = $r; return $this; } public function setType($t) { $this->type = $t; return $this; } public function setTwitter($t) { $this->contact['twitter'] = $t; return $this; } public function setPhone($p) { $this->contact['phone'] = $p; return $this; } public function setPhotos($p) { $this->photos = array_merge($this->photos,$p); } public function setTips($t = array()) { $this->tips = array_merge($this->tips,$t); return $this; } //public function } ?>
ner0tic/daviddurost.net
src/Ddnet/FoursquareBundle/Foursquare/FoursquareUser.php
PHP
mit
3,752
using System; using System.Security.Cryptography; using System.Text; namespace Songhay.Extensions { using Songhay.Models; /// <summary> /// Extensions of <see cref="OpenAuthorizationData"/>. /// </summary> public static class OpenAuthorizationDataExtensions { /// <summary> /// Gets the name of the twitter base URI with screen. /// </summary> /// <param name="twitterBaseUri">The twitter base URI.</param> /// <param name="screenName">Name of the screen.</param> public static Uri GetTwitterBaseUriWithScreenName(this Uri twitterBaseUri, string screenName) { if (twitterBaseUri == null) return null; return new Uri(twitterBaseUri.OriginalString + "?screen_name=" + Uri.EscapeDataString(screenName)); } /// <summary> /// Gets the name of the twitter base URI with screen. /// </summary> /// <param name="twitterBaseUri">The twitter base URI.</param> /// <param name="screenName">Name of the screen.</param> /// <param name="count">The count.</param> public static Uri GetTwitterBaseUriWithScreenName(this Uri twitterBaseUri, string screenName, int count) { if (twitterBaseUri == null) return null; return new Uri(twitterBaseUri.OriginalString + string.Format("?count={0}&screen_name={1}", count, Uri.EscapeDataString(screenName))); } /// <summary> /// Gets the twitter request header. /// </summary> /// <param name="data">The data.</param> /// <param name="twitterBaseUri">The twitter base URI.</param> /// <param name="screenName">Name of the screen.</param> /// <param name="httpMethod">The HTTP method.</param> public static string GetTwitterRequestHeader(this OpenAuthorizationData data, Uri twitterBaseUri, string screenName, string httpMethod) { if (data == null) return null; if (twitterBaseUri == null) return null; var baseFormat = "oauth_consumer_key={0}&oauth_nonce={1}&oauth_signature_method={2}" + "&oauth_timestamp={3}&oauth_token={4}&oauth_version={5}&screen_name={6}"; var baseString = string.Format( baseFormat, data.ConsumerKey, data.Nonce, data.SignatureMethod, data.TimeStamp, data.Token, data.Version, Uri.EscapeDataString(screenName)); baseString = string.Concat(httpMethod.ToUpper(),"&", Uri.EscapeDataString(twitterBaseUri.OriginalString), "&", Uri.EscapeDataString(baseString)); var compositeKey = string.Concat(Uri.EscapeDataString(data.ConsumerSecret), "&", Uri.EscapeDataString(data.TokenSecret)); string signature; using (HMACSHA1 hasher = new HMACSHA1(ASCIIEncoding.ASCII.GetBytes(compositeKey))) { signature = Convert.ToBase64String(hasher.ComputeHash(ASCIIEncoding.ASCII.GetBytes(baseString))); } var headerFormat = "OAuth oauth_nonce=\"{0}\", oauth_signature_method=\"{1}\", " + "oauth_timestamp=\"{2}\", oauth_consumer_key=\"{3}\", " + "oauth_token=\"{4}\", oauth_signature=\"{5}\", " + "oauth_version=\"{6}\""; var authHeader = string.Format(headerFormat, Uri.EscapeDataString(data.Nonce), Uri.EscapeDataString(data.SignatureMethod), Uri.EscapeDataString(data.TimeStamp), Uri.EscapeDataString(data.ConsumerKey), Uri.EscapeDataString(data.Token), Uri.EscapeDataString(signature), Uri.EscapeDataString(data.Version)); return authHeader; } } }
BryanWilhite/SonghayCore
SonghayCore/Extensions/OpenAuthorizationDataExtensions.cs
C#
mit
3,892
var View = require('ampersand-view'); var templates = require('../templates'); module.exports = View.extend({ template: templates.includes.scholarship, bindings: { 'model.field': '[role=field]', 'model.slots': '[role=slots]', 'model.holder': '[role=holder]', 'model.type': '[role=type]', 'model.link': { type: 'attribute', role: 'link', name: 'href' }, 'model.scholarshipIdUpperCase': '[role=link]', 'model.releaseDateFormated': '[role=release-date]', 'model.closeDateFormated': '[role=close-date]' } });
diasdavid/bolsas.istecni.co
clientApp/views/scholarship.js
JavaScript
mit
626
import global from 'global'; import dedent from 'ts-dedent'; import { RenderContext, ElementArgs, OptionsArgs } from './types'; const { window: globalWindow, document } = global; declare let Ember: any; const rootEl = document.getElementById('root'); const config = globalWindow.require(`${globalWindow.STORYBOOK_NAME}/config/environment`); const app = globalWindow.require(`${globalWindow.STORYBOOK_NAME}/app`).default.create({ autoboot: false, rootElement: rootEl, ...config.APP, }); let lastPromise = app.boot(); let hasRendered = false; let isRendering = false; function render(options: OptionsArgs, el: ElementArgs) { if (isRendering) return; isRendering = true; const { template, context = {}, element } = options; if (hasRendered) { lastPromise = lastPromise.then((instance: any) => instance.destroy()); } lastPromise = lastPromise .then(() => { const appInstancePrivate = app.buildInstance(); return appInstancePrivate.boot().then(() => appInstancePrivate); }) .then((instance: any) => { instance.register( 'component:story-mode', Ember.Component.extend({ layout: template || options, ...context, }) ); const component = instance.lookup('component:story-mode'); if (element) { component.appendTo(element); element.appendTo(el); } else { component.appendTo(el); } hasRendered = true; isRendering = false; return instance; }); } export default function renderMain({ storyFn, kind, name, showMain, showError }: RenderContext) { const element = storyFn(); if (!element) { showError({ title: `Expecting a Ember element from the story: "${name}" of "${kind}".`, description: dedent` Did you forget to return the Ember element from the story? Use "() => hbs('{{component}}')" or "() => { return { template: hbs\`{{component}}\` } }" when defining the story. `, }); return; } showMain(); render(element, rootEl); }
storybooks/storybook
app/ember/src/client/preview/render.ts
TypeScript
mit
2,077
#include "stdafx.h" #include "Exception.h" #include "ThreadLocal.h" #include "Log.h" #include "IocpManager.h" #include "EduServer_IOCP.h" #include "ClientSession.h" #include "IOThread.h" #include "ClientSessionManager.h" #include "DBContext.h" IocpManager* GIocpManager = nullptr; LPFN_DISCONNECTEX IocpManager::mFnDisconnectEx = nullptr; LPFN_ACCEPTEX IocpManager::mFnAcceptEx = nullptr; LPFN_CONNECTEX IocpManager::mFnConnectEx = nullptr; char IocpManager::mAcceptBuf[64] = { 0, }; BOOL DisconnectEx(SOCKET hSocket, LPOVERLAPPED lpOverlapped, DWORD dwFlags, DWORD reserved) { return IocpManager::mFnDisconnectEx(hSocket, lpOverlapped, dwFlags, reserved); } BOOL MyAcceptEx(SOCKET sListenSocket, SOCKET sAcceptSocket, PVOID lpOutputBuffer, DWORD dwReceiveDataLength, DWORD dwLocalAddressLength, DWORD dwRemoteAddressLength, LPDWORD lpdwBytesReceived, LPOVERLAPPED lpOverlapped) { return IocpManager::mFnAcceptEx(sListenSocket, sAcceptSocket, lpOutputBuffer, dwReceiveDataLength, dwLocalAddressLength, dwRemoteAddressLength, lpdwBytesReceived, lpOverlapped); } BOOL ConnectEx(SOCKET hSocket, const struct sockaddr* name, int namelen, PVOID lpSendBuffer, DWORD dwSendDataLength, LPDWORD lpdwBytesSent, LPOVERLAPPED lpOverlapped) { return IocpManager::mFnConnectEx(hSocket, name, namelen, lpSendBuffer, dwSendDataLength, lpdwBytesSent, lpOverlapped); } IocpManager::IocpManager() : mCompletionPort(NULL), mListenSocket(NULL) { memset(mIoWorkerThread, 0, sizeof(mIoWorkerThread)); } IocpManager::~IocpManager() { } bool IocpManager::Initialize() { /// winsock initializing WSADATA wsa; if (WSAStartup(MAKEWORD(2, 2), &wsa) != 0) return false; /// Create I/O Completion Port mCompletionPort = CreateIoCompletionPort(INVALID_HANDLE_VALUE, NULL, 0, 0); if (mCompletionPort == NULL) return false; /// create TCP socket mListenSocket = WSASocket(AF_INET, SOCK_STREAM, IPPROTO_TCP, NULL, 0, WSA_FLAG_OVERLAPPED); if (mListenSocket == INVALID_SOCKET) return false; HANDLE handle = CreateIoCompletionPort((HANDLE)mListenSocket, mCompletionPort, 0, 0); if (handle != mCompletionPort) { printf_s("[DEBUG] listen socket IOCP register error: %d\n", GetLastError()); return false; } int opt = 1; setsockopt(mListenSocket, SOL_SOCKET, SO_REUSEADDR, (const char*)&opt, sizeof(int)); /// bind SOCKADDR_IN serveraddr; ZeroMemory(&serveraddr, sizeof(serveraddr)); serveraddr.sin_family = AF_INET; serveraddr.sin_port = htons(LISTEN_PORT); serveraddr.sin_addr.s_addr = htonl(INADDR_ANY); if (SOCKET_ERROR == bind(mListenSocket, (SOCKADDR*)&serveraddr, sizeof(serveraddr))) return false; GUID guidDisconnectEx = WSAID_DISCONNECTEX ; DWORD bytes = 0 ; if (SOCKET_ERROR == WSAIoctl(mListenSocket, SIO_GET_EXTENSION_FUNCTION_POINTER, &guidDisconnectEx, sizeof(GUID), &mFnDisconnectEx, sizeof(LPFN_DISCONNECTEX), &bytes, NULL, NULL) ) return false; GUID guidAcceptEx = WSAID_ACCEPTEX ; if (SOCKET_ERROR == WSAIoctl(mListenSocket, SIO_GET_EXTENSION_FUNCTION_POINTER, &guidAcceptEx, sizeof(GUID), &mFnAcceptEx, sizeof(LPFN_ACCEPTEX), &bytes, NULL, NULL)) return false; GUID guidConnectEx = WSAID_CONNECTEX; if (SOCKET_ERROR == WSAIoctl(mListenSocket, SIO_GET_EXTENSION_FUNCTION_POINTER, &guidConnectEx, sizeof(GUID), &mFnConnectEx, sizeof(LPFN_CONNECTEX), &bytes, NULL, NULL)) return false; /// make session pool GClientSessionManager->PrepareClientSessions(); return true; } bool IocpManager::StartIoThreads() { /// create I/O Thread for (int i = 0; i < MAX_IO_THREAD; ++i) { DWORD dwThreadId; /// ½º·¹µåID´Â DB ½º·¹µå ÀÌÈÄ¿¡ IO ½º·¹µå·Î.. HANDLE hThread = (HANDLE)_beginthreadex(NULL, 0, IoWorkerThread, (LPVOID)(i+MAX_DB_THREAD), CREATE_SUSPENDED, (unsigned int*)&dwThreadId); if (hThread == NULL) return false; mIoWorkerThread[i] = new IOThread(hThread, mCompletionPort); } /// start! for (int i = 0; i < MAX_IO_THREAD; ++i) { ResumeThread(mIoWorkerThread[i]->GetHandle()); } return true; } void IocpManager::StartAccept() { /// listen if (SOCKET_ERROR == listen(mListenSocket, SOMAXCONN)) { printf_s("[DEBUG] listen error\n"); return; } while (GClientSessionManager->AcceptClientSessions()) { Sleep(100); } } void IocpManager::Finalize() { for (int i = 0; i < MAX_IO_THREAD; ++i) { CloseHandle(mIoWorkerThread[i]->GetHandle()); } CloseHandle(mCompletionPort); /// winsock finalizing WSACleanup(); } unsigned int WINAPI IocpManager::IoWorkerThread(LPVOID lpParam) { LThreadType = THREAD_IO_WORKER; LWorkerThreadId = reinterpret_cast<int>(lpParam); LSendRequestSessionList = new std::deque<Session*>; GThreadCallHistory[LWorkerThreadId] = LThreadCallHistory = new ThreadCallHistory(LWorkerThreadId); GThreadCallElapsedRecord[LWorkerThreadId] = LThreadCallElapsedRecord = new ThreadCallElapsedRecord(LWorkerThreadId); /// ¹Ýµå½Ã DB ¾²·¹µå¸¦ ¸ÕÀú ¶ç¿î ÈÄ¿¡ ÁøÀÔÇØ¾ß ÇÑ´Ù. CRASH_ASSERT(LWorkerThreadId >= MAX_DB_THREAD); return GIocpManager->mIoWorkerThread[LWorkerThreadId-MAX_DB_THREAD]->Run(); } void IocpManager::PostDatabaseResult(DatabaseJobContext* dbContext) { if (FALSE == PostQueuedCompletionStatus(mCompletionPort, 0, (ULONG_PTR)CK_DB_RESULT, (LPOVERLAPPED)dbContext)) { printf_s("IocpManager::PostDatabaseResult PostQueuedCompletionStatus Error: %d\n", GetLastError()); CRASH_ASSERT(false); } }
abiles/gameServer2015
Homework6/EduServer_IOCP/IocpManager.cpp
C++
mit
5,347
var toInteger = require('./toInteger'); /** Used as the `TypeError` message for "Functions" methods. */ var FUNC_ERROR_TEXT = 'Expected a function'; /** * The opposite of `_.before`; this method creates a function that invokes * `func` once it's called `n` or more times. * * @static * @memberOf _ * @category Function * @param {number} n The number of calls before `func` is invoked. * @param {Function} func The function to restrict. * @returns {Function} Returns the new restricted function. * @specs * * var saves = ['profile', 'settings']; * * var done = _.after(saves.length, function() { * console.log('done saving!'); * }); * * _.forEach(saves, function(type) { * asyncSave({ 'type': type, 'complete': done }); * }); * // => logs 'done saving!' after the two async saves have completed */ function after(n, func) { if (typeof func != 'function') { throw new TypeError(FUNC_ERROR_TEXT); } n = toInteger(n); return function() { if (--n < 1) { return func.apply(this, arguments); } }; } module.exports = after;
mdchristopher/Protractor
node_modules/lodash/after.js
JavaScript
mit
1,073
<h2>Inicio</h2> <div class="container"> <div class="starter-template"> <p class="lead">Bienvenid@ <?php echo $username; ?>, ya puedes disfrutar creando y conociendo nuevas canciones.</p> </div> </div><!-- /.container -->
joseluir/Codeigniter-3.0.6-con-la-libretia-Tank-Auth-1.0.9-
application/views/welcome.php
PHP
mit
251