hexsha string | size int64 | ext string | lang string | max_stars_repo_path string | max_stars_repo_name string | max_stars_repo_head_hexsha string | max_stars_repo_licenses list | max_stars_count int64 | max_stars_repo_stars_event_min_datetime string | max_stars_repo_stars_event_max_datetime string | max_issues_repo_path string | max_issues_repo_name string | max_issues_repo_head_hexsha string | max_issues_repo_licenses list | max_issues_count int64 | max_issues_repo_issues_event_min_datetime string | max_issues_repo_issues_event_max_datetime string | max_forks_repo_path string | max_forks_repo_name string | max_forks_repo_head_hexsha string | max_forks_repo_licenses list | max_forks_count int64 | max_forks_repo_forks_event_min_datetime string | max_forks_repo_forks_event_max_datetime string | content string | avg_line_length float64 | max_line_length int64 | alphanum_fraction float64 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
435f1e485133f8d57ad219c280ea8f6ba19ba937 | 244 | js | JavaScript | core/db.js | steem-marketplace/core-api | 1543f375c7b16bdacb9c53dcd2ef57587abb856b | [
"MIT"
] | null | null | null | core/db.js | steem-marketplace/core-api | 1543f375c7b16bdacb9c53dcd2ef57587abb856b | [
"MIT"
] | null | null | null | core/db.js | steem-marketplace/core-api | 1543f375c7b16bdacb9c53dcd2ef57587abb856b | [
"MIT"
] | null | null | null | const Sequelize = require('sequelize');
const Config = require('../config');
const sequelize = new Sequelize(Config.DB_NAME, Config.DB_USER, Config.DB_PASSWORD, {
host: Config.DB_HOST,
dialect: 'mysql'
});
module.exports = sequelize;
| 24.4 | 85 | 0.713115 |
435f586c452bb06d115f08e3b66320b6708f9c89 | 6,117 | js | JavaScript | polymath-apps/flow-typed/npm/optimize-css-assets-webpack-plugin_vx.x.x.js | Morpheuslabs-io/sto-as-service-app-ref | 54c92e24f2368d2e8dfe85f07eae2e59948bcc62 | [
"MIT"
] | 17 | 2018-09-22T15:40:13.000Z | 2021-09-21T13:49:35.000Z | polymath-apps/flow-typed/npm/optimize-css-assets-webpack-plugin_vx.x.x.js | Morpheuslabs-io/sto-as-service-app-ref | 54c92e24f2368d2e8dfe85f07eae2e59948bcc62 | [
"MIT"
] | 169 | 2018-09-19T16:30:52.000Z | 2020-09-30T20:44:45.000Z | polymath-apps/flow-typed/npm/optimize-css-assets-webpack-plugin_vx.x.x.js | Morpheuslabs-io/sto-as-service-app-ref | 54c92e24f2368d2e8dfe85f07eae2e59948bcc62 | [
"MIT"
] | 13 | 2018-09-18T16:55:45.000Z | 2021-08-29T13:33:47.000Z | // flow-typed signature: 3ee3343d0f12eb74a0e8cfd485518590
// flow-typed version: <<STUB>>/optimize-css-assets-webpack-plugin_v^4.0.1/flow_v0.81.0
/**
* This is an autogenerated libdef stub for:
*
* 'optimize-css-assets-webpack-plugin'
*
* Fill this stub out by replacing all the `any` types.
*
* Once filled out, we encourage you to share your work with the
* community by sending a pull request to:
* https://github.com/flowtype/flow-typed
*/
declare module 'optimize-css-assets-webpack-plugin' {
declare module.exports: any;
}
/**
* We include stubs for each file inside this npm package in case you need to
* require those files directly. Feel free to delete any files that aren't
* needed.
*/
declare module 'optimize-css-assets-webpack-plugin/src/index' {
declare module.exports: any;
}
declare module 'optimize-css-assets-webpack-plugin/test/cases/assetNameRegExp-no-source/index' {
declare module.exports: any;
}
declare module 'optimize-css-assets-webpack-plugin/test/cases/assetNameRegExp-no-source/webpack.config' {
declare module.exports: any;
}
declare module 'optimize-css-assets-webpack-plugin/test/cases/duplicate-css-exists-without-plugin/index' {
declare module.exports: any;
}
declare module 'optimize-css-assets-webpack-plugin/test/cases/duplicate-css-exists-without-plugin/webpack.config' {
declare module.exports: any;
}
declare module 'optimize-css-assets-webpack-plugin/test/cases/mergePropertiesForSelectorWithOtherStylesPresentIssue52/index' {
declare module.exports: any;
}
declare module 'optimize-css-assets-webpack-plugin/test/cases/mergePropertiesForSelectorWithOtherStylesPresentIssue52/webpack.config' {
declare module.exports: any;
}
declare module 'optimize-css-assets-webpack-plugin/test/cases/only-assetNameRegExp-processed/index' {
declare module.exports: any;
}
declare module 'optimize-css-assets-webpack-plugin/test/cases/only-assetNameRegExp-processed/webpack.config' {
declare module.exports: any;
}
declare module 'optimize-css-assets-webpack-plugin/test/cases/removes-duplicate-css/index' {
declare module.exports: any;
}
declare module 'optimize-css-assets-webpack-plugin/test/cases/removes-duplicate-css/webpack.config' {
declare module.exports: any;
}
declare module 'optimize-css-assets-webpack-plugin/test/plugin.test' {
declare module.exports: any;
}
declare module 'optimize-css-assets-webpack-plugin/test/util/helpers' {
declare module.exports: any;
}
declare module 'optimize-css-assets-webpack-plugin/test/util/index' {
declare module.exports: any;
}
declare module 'optimize-css-assets-webpack-plugin/test/webpack-integration.test' {
declare module.exports: any;
}
// Filename aliases
declare module 'optimize-css-assets-webpack-plugin/src/index.js' {
declare module.exports: $Exports<
'optimize-css-assets-webpack-plugin/src/index'
>;
}
declare module 'optimize-css-assets-webpack-plugin/test/cases/assetNameRegExp-no-source/index.js' {
declare module.exports: $Exports<
'optimize-css-assets-webpack-plugin/test/cases/assetNameRegExp-no-source/index'
>;
}
declare module 'optimize-css-assets-webpack-plugin/test/cases/assetNameRegExp-no-source/webpack.config.js' {
declare module.exports: $Exports<
'optimize-css-assets-webpack-plugin/test/cases/assetNameRegExp-no-source/webpack.config'
>;
}
declare module 'optimize-css-assets-webpack-plugin/test/cases/duplicate-css-exists-without-plugin/index.js' {
declare module.exports: $Exports<
'optimize-css-assets-webpack-plugin/test/cases/duplicate-css-exists-without-plugin/index'
>;
}
declare module 'optimize-css-assets-webpack-plugin/test/cases/duplicate-css-exists-without-plugin/webpack.config.js' {
declare module.exports: $Exports<
'optimize-css-assets-webpack-plugin/test/cases/duplicate-css-exists-without-plugin/webpack.config'
>;
}
declare module 'optimize-css-assets-webpack-plugin/test/cases/mergePropertiesForSelectorWithOtherStylesPresentIssue52/index.js' {
declare module.exports: $Exports<
'optimize-css-assets-webpack-plugin/test/cases/mergePropertiesForSelectorWithOtherStylesPresentIssue52/index'
>;
}
declare module 'optimize-css-assets-webpack-plugin/test/cases/mergePropertiesForSelectorWithOtherStylesPresentIssue52/webpack.config.js' {
declare module.exports: $Exports<
'optimize-css-assets-webpack-plugin/test/cases/mergePropertiesForSelectorWithOtherStylesPresentIssue52/webpack.config'
>;
}
declare module 'optimize-css-assets-webpack-plugin/test/cases/only-assetNameRegExp-processed/index.js' {
declare module.exports: $Exports<
'optimize-css-assets-webpack-plugin/test/cases/only-assetNameRegExp-processed/index'
>;
}
declare module 'optimize-css-assets-webpack-plugin/test/cases/only-assetNameRegExp-processed/webpack.config.js' {
declare module.exports: $Exports<
'optimize-css-assets-webpack-plugin/test/cases/only-assetNameRegExp-processed/webpack.config'
>;
}
declare module 'optimize-css-assets-webpack-plugin/test/cases/removes-duplicate-css/index.js' {
declare module.exports: $Exports<
'optimize-css-assets-webpack-plugin/test/cases/removes-duplicate-css/index'
>;
}
declare module 'optimize-css-assets-webpack-plugin/test/cases/removes-duplicate-css/webpack.config.js' {
declare module.exports: $Exports<
'optimize-css-assets-webpack-plugin/test/cases/removes-duplicate-css/webpack.config'
>;
}
declare module 'optimize-css-assets-webpack-plugin/test/plugin.test.js' {
declare module.exports: $Exports<
'optimize-css-assets-webpack-plugin/test/plugin.test'
>;
}
declare module 'optimize-css-assets-webpack-plugin/test/util/helpers.js' {
declare module.exports: $Exports<
'optimize-css-assets-webpack-plugin/test/util/helpers'
>;
}
declare module 'optimize-css-assets-webpack-plugin/test/util/index.js' {
declare module.exports: $Exports<
'optimize-css-assets-webpack-plugin/test/util/index'
>;
}
declare module 'optimize-css-assets-webpack-plugin/test/webpack-integration.test.js' {
declare module.exports: $Exports<
'optimize-css-assets-webpack-plugin/test/webpack-integration.test'
>;
}
| 37.993789 | 138 | 0.778159 |
435f69c09655ed83f8daa58df4e1c59ab637670d | 828 | js | JavaScript | src/Oro/Bundle/EmailBundle/Resources/public/js/email/variable/model.js | xabbuh/platform | 5b4e10bef6dd665d5bcd91b6846fdecee242e1e7 | [
"MIT"
] | null | null | null | src/Oro/Bundle/EmailBundle/Resources/public/js/email/variable/model.js | xabbuh/platform | 5b4e10bef6dd665d5bcd91b6846fdecee242e1e7 | [
"MIT"
] | null | null | null | src/Oro/Bundle/EmailBundle/Resources/public/js/email/variable/model.js | xabbuh/platform | 5b4e10bef6dd665d5bcd91b6846fdecee242e1e7 | [
"MIT"
] | null | null | null | /*global define*/
define(['backbone', 'routing'
], function (Backbone, routing) {
'use strict';
/**
* @export oroemail/js/email/variable/model
* @class oroemail.email.variable.Model
* @extends Backbone.Model
*/
return Backbone.Model.extend({
defaults: {
user: [],
entity: [],
entityName: null
},
route: 'oro_api_get_emailtemplate_available_variables',
url: null,
initialize: function () {
this.updateUrl();
this.bind('change:entityName', this.updateUrl, this);
},
/**
* onChange entityName attribute
*/
updateUrl: function () {
this.url = routing.generate(this.route, {entityName: this.get('entityName')});
}
});
});
| 24.352941 | 90 | 0.528986 |
43600bf4c429a2f8e539c35608d4c3c29488cf53 | 254 | js | JavaScript | addon/helpers/pad-zero.js | lozjackson/ember-clock-face | 7b08d398d40f515a386c5c520955ec6d9299b94e | [
"MIT"
] | 1 | 2015-10-25T12:07:35.000Z | 2015-10-25T12:07:35.000Z | addon/helpers/pad-zero.js | lozjackson/ember-clock-face | 7b08d398d40f515a386c5c520955ec6d9299b94e | [
"MIT"
] | null | null | null | addon/helpers/pad-zero.js | lozjackson/ember-clock-face | 7b08d398d40f515a386c5c520955ec6d9299b94e | [
"MIT"
] | 1 | 2020-02-21T13:33:30.000Z | 2020-02-21T13:33:30.000Z | import { helper } from '@ember/component/helper';
/*
Pad the `value` with a leading zero if it is less than 10.
*/
export function padZero(value/*, hash*/) {
return( parseInt( value ) < 10 ) ? '0' + value : value;
}
export default helper(padZero);
| 23.090909 | 60 | 0.65748 |
43605672653258e95ded6484fbdbc0c61c4b8d22 | 1,508 | js | JavaScript | docs/ironstorm_lookup/implementors/core/fmt/trait.LowerExp.js | forgemo/forgemo.github.io | edfc86c7128aeb5c5bd7fa3e292093814cc5a04b | [
"Apache-2.0"
] | 1 | 2016-04-27T00:39:21.000Z | 2016-04-27T00:39:21.000Z | docs/ironstorm_lookup/implementors/core/fmt/trait.LowerExp.js | forgemo/forgemo.github.io | edfc86c7128aeb5c5bd7fa3e292093814cc5a04b | [
"Apache-2.0"
] | null | null | null | docs/ironstorm_lookup/implementors/core/fmt/trait.LowerExp.js | forgemo/forgemo.github.io | edfc86c7128aeb5c5bd7fa3e292093814cc5a04b | [
"Apache-2.0"
] | null | null | null | (function() {var implementors = {};
implementors['itertools'] = ["impl<'a, I> <a class='trait' href='https://doc.rust-lang.org/nightly/core/fmt/trait.LowerExp.html' title='core::fmt::LowerExp'>LowerExp</a> for <a class='struct' href='itertools/struct.FormatDefault.html' title='itertools::FormatDefault'>FormatDefault</a><'a, I> <span class='where'>where I: <a class='trait' href='https://doc.rust-lang.org/nightly/core/iter/trait.Iterator.html' title='core::iter::Iterator'>Iterator</a>, I::Item: <a class='trait' href='https://doc.rust-lang.org/nightly/core/fmt/trait.LowerExp.html' title='core::fmt::LowerExp'>LowerExp</a></span>",];implementors["itertools"] = ["impl<'a, I> <a class='trait' href='https://doc.rust-lang.org/nightly/core/fmt/trait.LowerExp.html' title='core::fmt::LowerExp'>LowerExp</a> for <a class='struct' href='itertools/struct.FormatDefault.html' title='itertools::FormatDefault'>FormatDefault</a><'a, I> <span class='where'>where I: <a class='trait' href='https://doc.rust-lang.org/nightly/core/iter/iterator/trait.Iterator.html' title='core::iter::iterator::Iterator'>Iterator</a>, I::Item: <a class='trait' href='https://doc.rust-lang.org/nightly/core/fmt/trait.LowerExp.html' title='core::fmt::LowerExp'>LowerExp</a></span>",];
if (window.register_implementors) {
window.register_implementors(implementors);
} else {
window.pending_implementors = implementors;
}
})()
| 137.090909 | 1,253 | 0.690318 |
4360b0fc8aa824c068de4ea760ee3cf836a67938 | 59,424 | js | JavaScript | loaders/threejs/glTFLoader.js | anuprao/glTF | 1bd91d9676aa444dd3d3d146af1a68126e3f0294 | [
"Zlib"
] | null | null | null | loaders/threejs/glTFLoader.js | anuprao/glTF | 1bd91d9676aa444dd3d3d146af1a68126e3f0294 | [
"Zlib"
] | null | null | null | loaders/threejs/glTFLoader.js | anuprao/glTF | 1bd91d9676aa444dd3d3d146af1a68126e3f0294 | [
"Zlib"
] | null | null | null | /**
* @author Tony Parisi / http://www.tonyparisi.com/
*/
THREE.glTFLoader = function (showStatus) {
this.useBufferGeometry = (THREE.glTFLoader.useBufferGeometry !== undefined ) ?
THREE.glTFLoader.useBufferGeometry : true;
this.meshesRequested = 0;
this.meshesLoaded = 0;
this.pendingMeshes = [];
this.animationsRequested = 0;
this.animationsLoaded = 0;
this.animations = [];
this.shadersRequested = 0;
this.shadersLoaded = 0;
this.shaders = {};
THREE.Loader.call( this, showStatus );
}
THREE.glTFLoader.prototype = new THREE.Loader();
THREE.glTFLoader.prototype.constructor = THREE.glTFLoader;
THREE.glTFLoader.prototype.load = function( url, callback ) {
var theLoader = this;
// Utilities
function RgbArraytoHex(colorArray) {
if(!colorArray) return 0xFFFFFFFF;
var r = Math.floor(colorArray[0] * 255),
g = Math.floor(colorArray[1] * 255),
b = Math.floor(colorArray[2] * 255),
a = 255;
var color = (a << 24) + (r << 16) + (g << 8) + b;
return color;
}
function convertAxisAngleToQuaternion(rotations, count)
{
var q = new THREE.Quaternion;
var axis = new THREE.Vector3;
var euler = new THREE.Vector3;
var i;
for (i = 0; i < count; i++) {
axis.set(rotations[i * 4], rotations[i * 4 + 1],
rotations[i * 4 + 2]).normalize();
var angle = rotations[i * 4 + 3];
q.setFromAxisAngle(axis, angle);
rotations[i * 4] = q.x;
rotations[i * 4 + 1] = q.y;
rotations[i * 4 + 2] = q.z;
rotations[i * 4 + 3] = q.w;
}
}
function componentsPerElementForGLType(type) {
switch(type) {
case "SCALAR" :
nElements = 1;
break;
case "VEC2" :
nElements = 2;
break;
case "VEC3" :
nElements = 3;
break;
case "VEC4" :
nElements = 4;
break;
case "MAT2" :
nElements = 4;
break;
case "MAT3" :
nElements = 9;
break;
case "MAT4" :
nElements = 16;
break;
default :
debugger;
break;
}
return nElements;
}
function LoadTexture(src) {
if(!src) { return null; }
return THREE.ImageUtils.loadTexture(src);
}
// Geometry processing
var ClassicGeometry = function() {
if (theLoader.useBufferGeometry) {
this.geometry = new THREE.BufferGeometry;
}
else {
this.geometry = new THREE.Geometry;
}
this.totalAttributes = 0;
this.loadedAttributes = 0;
this.indicesLoaded = false;
this.finished = false;
this.onload = null;
this.uvs = null;
this.indexArray = null;
};
ClassicGeometry.prototype.constructor = ClassicGeometry;
ClassicGeometry.prototype.buildArrayGeometry = function() {
// Build indexed mesh
var geometry = this.geometry;
var normals = geometry.normals;
var indexArray = this.indexArray;
var uvs = this.uvs;
var a, b, c;
var i, l;
var faceNormals = null;
var faceTexcoords = null;
for(i = 0, l = this.indexArray.length; i < l; i += 3) {
a = indexArray[i];
b = indexArray[i+1];
c = indexArray[i+2];
if(normals) {
faceNormals = [normals[a], normals[b], normals[c]];
}
geometry.faces.push( new THREE.Face3( a, b, c, faceNormals, null, null ) );
if(uvs) {
geometry.faceVertexUvs[0].push([ uvs[a], uvs[b], uvs[c] ]);
}
}
// Allow Three.js to calculate some values for us
geometry.computeBoundingBox();
geometry.computeBoundingSphere();
geometry.computeCentroids();
geometry.computeFaceNormals();
if(!normals) {
geometry.computeVertexNormals();
}
}
ClassicGeometry.prototype.buildBufferGeometry = function() {
// Build indexed mesh
var geometry = this.geometry;
geometry.attributes.index = {
itemSize: 1,
array : this.indexArray
};
var offset = {
start: 0,
index: 0,
count: this.indexArray.length
};
geometry.offsets.push( offset );
geometry.computeBoundingSphere();
}
ClassicGeometry.prototype.checkFinished = function() {
if(this.indexArray && this.loadedAttributes === this.totalAttributes) {
if (theLoader.useBufferGeometry) {
this.buildBufferGeometry();
}
else {
this.buildArrayGeometry();
}
this.finished = true;
if(this.onload) {
this.onload();
}
}
};
// Delegate for processing index buffers
var IndicesDelegate = function() {};
IndicesDelegate.prototype.handleError = function(errorCode, info) {
// FIXME: report error
console.log("ERROR(IndicesDelegate):"+errorCode+":"+info);
};
IndicesDelegate.prototype.convert = function(resource, ctx) {
return new Uint16Array(resource, 0, ctx.indices.count);
};
IndicesDelegate.prototype.resourceAvailable = function(glResource, ctx) {
var geometry = ctx.geometry;
geometry.indexArray = glResource;
geometry.checkFinished();
return true;
};
var indicesDelegate = new IndicesDelegate();
var IndicesContext = function(indices, geometry) {
this.indices = indices;
this.geometry = geometry;
};
// Delegate for processing vertex attribute buffers
var VertexAttributeDelegate = function() {};
VertexAttributeDelegate.prototype.handleError = function(errorCode, info) {
// FIXME: report error
console.log("ERROR(VertexAttributeDelegate):"+errorCode+":"+info);
};
VertexAttributeDelegate.prototype.convert = function(resource, ctx) {
return resource;
};
VertexAttributeDelegate.prototype.arrayResourceAvailable = function(glResource, ctx) {
var geom = ctx.geometry;
var attribute = ctx.attribute;
var semantic = ctx.semantic;
var floatArray;
var i, l;
//FIXME: Float32 is assumed here, but should be checked.
if(semantic == "POSITION") {
// TODO: Should be easy to take strides into account here
floatArray = new Float32Array(glResource, 0, attribute.count * componentsPerElementForGLType(attribute.type));
for(i = 0, l = floatArray.length; i < l; i += 3) {
geom.geometry.vertices.push( new THREE.Vector3( floatArray[i], floatArray[i+1], floatArray[i+2] ) );
}
} else if(semantic == "NORMAL") {
geom.geometry.normals = [];
floatArray = new Float32Array(glResource, 0, attribute.count * componentsPerElementForGLType(attribute.type));
for(i = 0, l = floatArray.length; i < l; i += 3) {
geom.geometry.normals.push( new THREE.Vector3( floatArray[i], floatArray[i+1], floatArray[i+2] ) );
}
} else if ((semantic == "TEXCOORD_0") || (semantic == "TEXCOORD" )) {
geom.uvs = [];
floatArray = new Float32Array(glResource, 0, attribute.count * componentsPerElementForGLType(attribute.type));
for(i = 0, l = floatArray.length; i < l; i += 2) {
geom.uvs.push( new THREE.Vector2( floatArray[i], 1.0 - floatArray[i+1] ) );
}
}
else if (semantic == "WEIGHT") {
nComponents = componentsPerElementForGLType(attribute.type);
floatArray = new Float32Array(glResource, 0, attribute.count * nComponents);
for(i = 0, l = floatArray.length; i < l; i += 4) {
geom.geometry.skinWeights.push( new THREE.Vector4( floatArray[i], floatArray[i+1], floatArray[i+2], floatArray[i+3] ) );
}
}
else if (semantic == "JOINT") {
nComponents = componentsPerElementForGLType(attribute.type);
floatArray = new Float32Array(glResource, 0, attribute.count * nComponents);
for(i = 0, l = floatArray.length; i < l; i += 4) {
geom.geometry.skinIndices.push( new THREE.Vector4( floatArray[i], floatArray[i+1], floatArray[i+2], floatArray[i+3] ) );
}
}
}
VertexAttributeDelegate.prototype.bufferResourceAvailable = function(glResource, ctx) {
var geom = ctx.geometry;
var attribute = ctx.attribute;
var semantic = ctx.semantic;
var floatArray;
var i, l;
var nComponents;
//FIXME: Float32 is assumed here, but should be checked.
if(semantic == "POSITION") {
// TODO: Should be easy to take strides into account here
floatArray = new Float32Array(glResource, 0, attribute.count * componentsPerElementForGLType(attribute.type));
geom.geometry.attributes.position = {
itemSize: 3,
array : floatArray
};
} else if(semantic == "NORMAL") {
nComponents = componentsPerElementForGLType(attribute.type);
floatArray = new Float32Array(glResource, 0, attribute.count * nComponents);
geom.geometry.attributes.normal = {
itemSize: 3,
array : floatArray
};
} else if ((semantic == "TEXCOORD_0") || (semantic == "TEXCOORD" )) {
nComponents = componentsPerElementForGLType(attribute.type);
floatArray = new Float32Array(glResource, 0, attribute.count * nComponents);
// N.B.: flip Y value... should we just set texture.flipY everywhere?
for (i = 0; i < floatArray.length / 2; i++) {
floatArray[i*2+1] = 1.0 - floatArray[i*2+1];
}
geom.geometry.attributes.uv = {
itemSize: nComponents,
array : floatArray
};
}
else if (semantic == "WEIGHT") {
nComponents = componentsPerElementForGLType(attribute.type);
floatArray = new Float32Array(glResource, 0, attribute.count * nComponents);
geom.geometry.attributes.skinWeight = {
itemSize: nComponents,
array : floatArray
};
}
else if (semantic == "JOINT") {
nComponents = componentsPerElementForGLType(attribute.type);
floatArray = new Float32Array(glResource, 0, attribute.count * nComponents);
geom.geometry.attributes.skinIndex = {
itemSize: nComponents,
array : floatArray
};
}
}
VertexAttributeDelegate.prototype.resourceAvailable = function(glResource, ctx) {
if (theLoader.useBufferGeometry) {
this.bufferResourceAvailable(glResource, ctx);
}
else {
this.arrayResourceAvailable(glResource, ctx);
}
var geom = ctx.geometry;
geom.loadedAttributes++;
geom.checkFinished();
return true;
};
var vertexAttributeDelegate = new VertexAttributeDelegate();
var VertexAttributeContext = function(attribute, semantic, geometry) {
this.attribute = attribute;
this.semantic = semantic;
this.geometry = geometry;
};
var Mesh = function() {
this.primitives = [];
this.materialsPending = [];
this.loadedGeometry = 0;
this.onCompleteCallbacks = [];
};
Mesh.prototype.addPrimitive = function(geometry, material) {
var self = this;
geometry.onload = function() {
self.loadedGeometry++;
self.checkComplete();
};
this.primitives.push({
geometry: geometry,
material: material,
mesh: null
});
};
Mesh.prototype.onComplete = function(callback) {
this.onCompleteCallbacks.push(callback);
this.checkComplete();
};
Mesh.prototype.checkComplete = function() {
var self = this;
if(this.onCompleteCallbacks.length && this.primitives.length == this.loadedGeometry) {
this.onCompleteCallbacks.forEach(function(callback) {
callback(self);
});
this.onCompleteCallbacks = [];
}
};
Mesh.prototype.attachToNode = function(threeNode) {
// Assumes that the geometry is complete
this.primitives.forEach(function(primitive) {
/*if(!primitive.mesh) {
primitive.mesh = new THREE.Mesh(primitive.geometry, primitive.material);
}*/
var material = primitive.material;
if (!(material instanceof THREE.Material)) {
material = theLoader.createShaderMaterial(material);
}
var threeMesh = new THREE.Mesh(primitive.geometry.geometry, material);
threeMesh.castShadow = true;
threeNode.add(threeMesh);
});
};
// Delayed-loaded material
var Material = function(params) {
this.params = params;
};
// Delegate for processing animation parameter buffers
var AnimationParameterDelegate = function() {};
AnimationParameterDelegate.prototype.handleError = function(errorCode, info) {
// FIXME: report error
console.log("ERROR(AnimationParameterDelegate):"+errorCode+":"+info);
};
AnimationParameterDelegate.prototype.convert = function(resource, ctx) {
var parameter = ctx.parameter;
var glResource = null;
switch (parameter.type) {
case "SCALAR" :
case "VEC2" :
case "VEC3" :
case "VEC4" :
glResource = new Float32Array(resource, 0, parameter.count * componentsPerElementForGLType(parameter.type));
break;
default:
break;
}
return glResource;
};
AnimationParameterDelegate.prototype.resourceAvailable = function(glResource, ctx) {
var animation = ctx.animation;
var parameter = ctx.parameter;
parameter.data = glResource;
animation.handleParameterLoaded(parameter);
return true;
};
var animationParameterDelegate = new AnimationParameterDelegate();
var AnimationParameterContext = function(parameter, animation) {
this.parameter = parameter;
this.animation = animation;
};
// Animations
var Animation = function() {
// create Three.js keyframe here
this.totalParameters = 0;
this.loadedParameters = 0;
this.parameters = {};
this.finishedLoading = false;
this.onload = null;
};
Animation.prototype.constructor = Animation;
Animation.prototype.handleParameterLoaded = function(parameter) {
this.parameters[parameter.name] = parameter;
this.loadedParameters++;
this.checkFinished();
};
Animation.prototype.checkFinished = function() {
if(this.loadedParameters === this.totalParameters) {
// Build animation
this.finishedLoading = true;
if (this.onload) {
this.onload();
}
}
};
// Delegate for processing inverse bind matrices buffer
var InverseBindMatricesDelegate = function() {};
InverseBindMatricesDelegate.prototype.handleError = function(errorCode, info) {
// FIXME: report error
console.log("ERROR(InverseBindMatricesDelegate):"+errorCode+":"+info);
};
InverseBindMatricesDelegate.prototype.convert = function(resource, ctx) {
var parameter = ctx.parameter;
var glResource = null;
switch (parameter.type) {
case "MAT4" :
glResource = new Float32Array(resource, 0, parameter.count * componentsPerElementForGLType(parameter.type));
break;
default:
break;
}
return glResource;
};
InverseBindMatricesDelegate.prototype.resourceAvailable = function(glResource, ctx) {
var skin = ctx.skin;
skin.inverseBindMatrices = glResource;
return true;
};
var inverseBindMatricesDelegate = new InverseBindMatricesDelegate();
var InverseBindMatricesContext = function(param, skin) {
this.parameter = param;
this.skin = skin;
};
// Delegate for processing shaders from external files
var ShaderDelegate = function() {};
ShaderDelegate.prototype.handleError = function(errorCode, info) {
// FIXME: report error
console.log("ERROR(ShaderDelegate):"+errorCode+":"+info);
};
ShaderDelegate.prototype.convert = function(resource, ctx) {
return resource;
}
ShaderDelegate.prototype.resourceAvailable = function(data, ctx) {
theLoader.shadersLoaded++;
theLoader.shaders[ctx.id] = data;
return true;
};
var shaderDelegate = new ShaderDelegate();
var ShaderContext = function(id, path) {
this.id = id;
this.uri = path;
};
// Resource management
var ResourceEntry = function(entryID, object, description) {
this.entryID = entryID;
this.object = object;
this.description = description;
};
var Resources = function() {
this._entries = {};
};
Resources.prototype.setEntry = function(entryID, object, description) {
if (!entryID) {
console.error("No EntryID provided, cannot store", description);
return;
}
if (this._entries[entryID]) {
console.warn("entry["+entryID+"] is being overwritten");
}
this._entries[entryID] = new ResourceEntry(entryID, object, description );
};
Resources.prototype.getEntry = function(entryID) {
return this._entries[entryID];
};
Resources.prototype.clearEntries = function() {
this._entries = {};
};
LoadDelegate = function() {
}
LoadDelegate.prototype.loadCompleted = function(callback, obj) {
callback.call(Window, obj);
}
// Loader
var ThreeGLTFLoader = Object.create(glTFParser, {
load: {
enumerable: true,
value: function(userInfo, options) {
this.resources = new Resources();
this.cameras = [];
this.lights = [];
this.animations = [];
this.joints = {};
this.skeltons = {};
THREE.GLTFLoaderUtils.init();
glTFParser.load.call(this, userInfo, options);
}
},
cameras: {
enumerable: true,
writable: true,
value : []
},
lights: {
enumerable: true,
writable: true,
value : []
},
animations: {
enumerable: true,
writable: true,
value : []
},
// Implement WebGLTFLoader handlers
handleBuffer: {
value: function(entryID, description, userInfo) {
this.resources.setEntry(entryID, null, description);
description.type = "ArrayBuffer";
return true;
}
},
handleBufferView: {
value: function(entryID, description, userInfo) {
this.resources.setEntry(entryID, null, description);
var buffer = this.resources.getEntry(description.buffer);
description.type = "ArrayBufferView";
var bufferViewEntry = this.resources.getEntry(entryID);
bufferViewEntry.buffer = buffer;
return true;
}
},
handleShader: {
value: function(entryID, description, userInfo) {
this.resources.setEntry(entryID, null, description);
var shaderRequest = {
id : entryID,
uri : description.uri,
};
var shaderContext = new ShaderContext(entryID, description.uri);
theLoader.shadersRequested++;
THREE.GLTFLoaderUtils.getFile(shaderRequest, shaderDelegate, shaderContext);
return true;
}
},
handleProgram: {
value: function(entryID, description, userInfo) {
this.resources.setEntry(entryID, null, description);
return true;
}
},
handleTechnique: {
value: function(entryID, description, userInfo) {
this.resources.setEntry(entryID, null, description);
return true;
}
},
createShaderMaterial : {
value: function(material) {
var fragmentShader = theLoader.shaders[material.params.fragmentShader];
if (!fragmentShader) {
console.log("ERROR: Missing fragment shader definition:", material.params.fragmentShader);
return new THREE.MeshPhongMaterial;
}
var vertexShader = theLoader.shaders[material.params.vertexShader];
if (!fragmentShader) {
console.log("ERROR: Missing vertex shader definition:", material.params.vertexShader);
return new THREE.MeshPhongMaterial;
}
var uniforms = {};
var shaderMaterial = new THREE.ShaderMaterial( {
fragmentShader: fragmentShader,
vertexShader: vertexShader,
uniforms: uniforms,
} );
return new THREE.MeshPhongMaterial(material.params);
}
},
createShaderParams : {
value: function(materialId, values, params, instanceProgram) {
var program = this.resources.getEntry(instanceProgram.program);
if (program) {
params.fragmentShader = program.description.fragmentShader;
params.vertexShader = program.description.vertexShader;
params.attributes = instanceProgram.attributes;
params.uniforms = instanceProgram.uniforms;
}
}
},
threeJSMaterialType : {
value: function(materialId, technique, values, params) {
var materialType = THREE.MeshPhongMaterial;
var defaultPass = null;
if (technique && technique.description && technique.description.passes)
defaultPass = technique.description.passes.defaultPass;
if (defaultPass) {
if (defaultPass.details && defaultPass.details.commonProfile) {
var profile = technique.description.passes.defaultPass.details.commonProfile;
if (profile)
{
switch (profile.lightingModel)
{
case 'Blinn' :
case 'Phong' :
materialType = THREE.MeshPhongMaterial;
break;
case 'Lambert' :
materialType = THREE.MeshLambertMaterial;
break;
default :
materialType = THREE.MeshBasicMaterial;
break;
}
if (profile.extras && profile.extras.doubleSided)
{
params.side = THREE.DoubleSide;
}
}
}
else if (defaultPass.instanceProgram) {
var instanceProgram = defaultPass.instanceProgram;
this.createShaderParams(materialId, values, params, instanceProgram);
var loadshaders = true;
if (loadshaders) {
materialType = Material;
}
}
}
var texturePath = null;
var textureParams = null;
var diffuse = values.diffuse;
if (diffuse)
{
var texture = diffuse;
if (texture) {
var textureEntry = this.resources.getEntry(texture);
if (textureEntry) {
{
var imageEntry = this.resources.getEntry(textureEntry.description.source);
if (imageEntry) {
texturePath = imageEntry.description.uri;
}
var samplerEntry = this.resources.getEntry(textureEntry.description.sampler);
if (samplerEntry) {
textureParams = samplerEntry.description;
}
}
}
}
}
var texture = LoadTexture(texturePath);
if (texture && textureParams) {
if (textureParams.wrapS == WebGLRenderingContext.REPEAT)
texture.wrapS = THREE.RepeatWrapping;
if (textureParams.wrapT == WebGLRenderingContext.REPEAT)
texture.wrapT = THREE.RepeatWrapping;
if (textureParams.magFilter == WebGLRenderingContext.LINEAR)
texture.magFilter = THREE.LinearFilter;
// if (textureParams.minFilter == "LINEAR")
// texture.minFilter = THREE.LinearFilter;
params.map = texture;
}
var envMapPath = null;
var envMapParams = null;
var reflective = values.reflective;
if (reflective)
{
var texture = reflective;
if (texture) {
var textureEntry = this.resources.getEntry(texture);
if (textureEntry) {
{
var imageEntry = this.resources.getEntry(textureEntry.description.source);
if (imageEntry) {
envMapPath = imageEntry.description.uri;
}
var samplerEntry = this.resources.getEntry(textureEntry.description.sampler);
if (samplerEntry) {
envMapParams = samplerEntry.description;
}
}
}
}
}
var texture = LoadTexture(envMapPath);
if (texture && envMapParams) {
if (envMapParams.wrapS == WebGLRenderingContext.REPEAT)
texture.wrapS = THREE.RepeatWrapping;
if (envMapParams.wrapT == WebGLRenderingContext.REPEAT)
texture.wrapT = THREE.RepeatWrapping;
if (envMapParams.magFilter == WebGLRenderingContext.LINEAR)
texture.magFilter = THREE.LinearFilter;
// if (envMapParams.minFilter == WebGLRenderingContext.LINEAR)
// texture.minFilter = THREE.LinearFilter;
params.envMap = texture;
}
var shininess = values.shininesss || values.shininess; // N.B.: typo in converter!
if (shininess)
{
shininess = shininess;
}
var diffuseColor = !texturePath ? diffuse : null;
var opacity = 1.0;
if (values.hasOwnProperty("transparency"))
{
var USE_A_ONE = true; // for now, hack because file format isn't telling us
opacity = USE_A_ONE ? values.transparency : (1.0 - values.transparency);
}
// if (diffuseColor) diffuseColor = [0, 1, 0];
params.color = RgbArraytoHex(diffuseColor);
params.opacity = opacity;
params.transparent = opacity < 1.0;
// hack hack hack
if (texturePath && texturePath.toLowerCase().indexOf(".png") != -1)
params.transparent = true;
if (!(shininess === undefined))
{
params.shininess = shininess;
}
if (!(values.ambient === undefined) && !(typeof(values.ambient) == 'string'))
{
params.ambient = RgbArraytoHex(values.ambient);
}
if (!(values.emission === undefined))
{
params.emissive = RgbArraytoHex(values.emission);
}
if (!(values.specular === undefined))
{
params.specular = RgbArraytoHex(values.specular);
}
return materialType;
}
},
handleMaterial: {
value: function(entryID, description, userInfo) {
//this should be rewritten using the meta datas that actually create the shader.
//here we will infer what needs to be pass to Three.js by looking inside the technique parameters.
var technique = this.resources.getEntry(description.instanceTechnique.technique);
var materialParams = {};
var values = description.instanceTechnique.values;
var materialType = this.threeJSMaterialType(entryID, technique, values, materialParams);
var material = new materialType(materialParams);
this.resources.setEntry(entryID, material, description);
return true;
}
},
handleMesh: {
value: function(entryID, description, userInfo) {
var mesh = new Mesh();
this.resources.setEntry(entryID, mesh, description);
var primitivesDescription = description.primitives;
if (!primitivesDescription) {
//FIXME: not implemented in delegate
console.log("MISSING_PRIMITIVES for mesh:"+ entryID);
return false;
}
for (var i = 0 ; i < primitivesDescription.length ; i++) {
var primitiveDescription = primitivesDescription[i];
if (primitiveDescription.primitive === WebGLRenderingContext.TRIANGLES) {
var geometry = new ClassicGeometry();
var materialEntry = this.resources.getEntry(primitiveDescription.material);
mesh.addPrimitive(geometry, materialEntry.object);
var indices = this.resources.getEntry(primitiveDescription.indices);
var bufferEntry = this.resources.getEntry(indices.description.bufferView);
var indicesObject = {
bufferView : bufferEntry,
byteOffset : indices.description.byteOffset,
count : indices.description.count,
id : indices.entryID,
componentType : indices.description.componentType,
type : indices.description.type
};
var indicesContext = new IndicesContext(indicesObject, geometry);
var alreadyProcessedIndices = THREE.GLTFLoaderUtils.getBuffer(indicesObject, indicesDelegate, indicesContext);
/*if(alreadyProcessedIndices) {
indicesDelegate.resourceAvailable(alreadyProcessedIndices, indicesContext);
}*/
// Load Vertex Attributes
var allAttributes = Object.keys(primitiveDescription.attributes);
allAttributes.forEach( function(semantic) {
geometry.totalAttributes++;
var attribute;
var attributeID = primitiveDescription.attributes[semantic];
var attributeEntry = this.resources.getEntry(attributeID);
if (!attributeEntry) {
//let's just use an anonymous object for the attribute
attribute = description.attributes[attributeID];
attribute.id = attributeID;
this.resources.setEntry(attributeID, attribute, attribute);
var bufferEntry = this.resources.getEntry(attribute.bufferView);
attributeEntry = this.resources.getEntry(attributeID);
} else {
attribute = attributeEntry.object;
attribute.id = attributeID;
var bufferEntry = this.resources.getEntry(attribute.bufferView);
}
var attributeObject = {
bufferView : bufferEntry,
byteOffset : attribute.byteOffset,
byteStride : attribute.byteStride,
count : attribute.count,
max : attribute.max,
min : attribute.min,
componentType : attribute.componentType,
type : attribute.type,
id : attributeID
};
var attribContext = new VertexAttributeContext(attributeObject, semantic, geometry);
var alreadyProcessedAttribute = THREE.GLTFLoaderUtils.getBuffer(attributeObject, vertexAttributeDelegate, attribContext);
/*if(alreadyProcessedAttribute) {
vertexAttributeDelegate.resourceAvailable(alreadyProcessedAttribute, attribContext);
}*/
}, this);
}
}
return true;
}
},
handleCamera: {
value: function(entryID, description, userInfo) {
var camera;
if (description.type == "perspective")
{
var znear = description.perspective.znear;
var zfar = description.perspective.zfar;
var yfov = description.perspective.yfov;
var xfov = description.perspective.xfov;
var aspect_ratio = description.perspective.aspect_ratio;
if (!aspect_ratio)
aspect_ratio = 1;
if (yfov === undefined)
{
if (xfov)
{
// According to COLLADA spec...
// aspect_ratio = xfov / yfov
yfov = xfov / aspect_ratio;
}
}
if (yfov)
{
camera = new THREE.PerspectiveCamera(yfov, aspect_ratio, znear, zfar);
}
}
else
{
camera = new THREE.OrthographicCamera( window.innerWidth / - 2, window.innerWidth / 2, window.innerHeight / 2, window.innerHeight / - 2, znear, zfar );
}
if (camera)
{
this.resources.setEntry(entryID, camera, description);
}
return true;
}
},
handleLight: {
value: function(entryID, description, userInfo) {
var light = null;
var type = description.type;
if (type && description[type])
{
var lparams = description[type];
var color = RgbArraytoHex(lparams.color);
switch (type) {
case "directional" :
light = new THREE.DirectionalLight(color);
light.position.set(0, 0, 1);
break;
case "point" :
light = new THREE.PointLight(color);
break;
case "spot " :
light = new THREE.SpotLight(color);
light.position.set(0, 0, 1);
break;
case "ambient" :
light = new THREE.AmbientLight(color);
break;
}
}
if (light)
{
this.resources.setEntry(entryID, light, description);
}
return true;
}
},
addPendingMesh: {
value: function(mesh, threeNode) {
theLoader.pendingMeshes.push({
mesh: mesh,
node: threeNode
});
}
},
handleNode: {
value: function(entryID, description, userInfo) {
var threeNode = null;
if (description.jointName) {
threeNode = new THREE.Bone();
threeNode.jointName = description.jointName;
this.joints[description.jointName] = entryID;
}
else {
threeNode = new THREE.Object3D();
}
threeNode.name = description.name;
this.resources.setEntry(entryID, threeNode, description);
var m = description.matrix;
if(m) {
threeNode.matrixAutoUpdate = false;
threeNode.applyMatrix(new THREE.Matrix4(
m[0], m[4], m[8], m[12],
m[1], m[5], m[9], m[13],
m[2], m[6], m[10], m[14],
m[3], m[7], m[11], m[15]
));
}
else {
var t = description.translation;
var r = description.rotation;
var s = description.scale;
var position = t ? new THREE.Vector3(t[0], t[1], t[2]) :
new THREE.Vector3;
if (r) {
convertAxisAngleToQuaternion(r, 1);
}
var rotation = r ? new THREE.Quaternion(r[0], r[1], r[2], r[3]) :
new THREE.Quaternion;
var scale = s ? new THREE.Vector3(s[0], s[1], s[2]) :
new THREE.Vector3(1, 1, 1);
var matrix = new THREE.Matrix4;
matrix.compose(position, rotation, scale);
threeNode.matrixAutoUpdate = false;
threeNode.applyMatrix(matrix);
}
var self = this;
// Iterate through all node meshes and attach the appropriate objects
//FIXME: decision needs to be made between these 2 ways, probably meshes will be discarded.
var meshEntry;
if (description.mesh) {
meshEntry = this.resources.getEntry(description.mesh);
theLoader.meshesRequested++;
meshEntry.object.onComplete(function(mesh) {
self.addPendingMesh(mesh, threeNode);
theLoader.meshesLoaded++;
theLoader.checkComplete();
});
}
if (description.meshes) {
description.meshes.forEach( function(meshID) {
meshEntry = this.resources.getEntry(meshID);
theLoader.meshesRequested++;
meshEntry.object.onComplete(function(mesh) {
self.addPendingMesh(mesh, threeNode);
theLoader.meshesLoaded++;
theLoader.checkComplete();
});
}, this);
}
if (description.instanceSkin) {
var skinEntry = this.resources.getEntry(description.instanceSkin.skin);
if (skinEntry) {
var skin = skinEntry.object;
description.instanceSkin.skin = skin;
threeNode.instanceSkin = description.instanceSkin;
var meshes = description.instanceSkin.meshes;
skin.meshes = [];
meshes.forEach( function(meshID) {
meshEntry = this.resources.getEntry(meshID);
theLoader.meshesRequested++;
meshEntry.object.onComplete(function(mesh) {
skin.meshes.push(mesh);
theLoader.meshesLoaded++;
theLoader.checkComplete();
});
}, this);
}
}
if (description.camera) {
var cameraEntry = this.resources.getEntry(description.camera);
if (cameraEntry) {
threeNode.add(cameraEntry.object);
this.cameras.push(cameraEntry.object);
}
}
if (description.light) {
var lightEntry = this.resources.getEntry(description.light);
if (lightEntry) {
threeNode.add(lightEntry.object);
this.lights.push(lightEntry.object);
}
}
return true;
}
},
buildNodeHirerachy: {
value: function(nodeEntryId, parentThreeNode) {
var nodeEntry = this.resources.getEntry(nodeEntryId);
var threeNode = nodeEntry.object;
parentThreeNode.add(threeNode);
var children = nodeEntry.description.children;
if (children) {
children.forEach( function(childID) {
this.buildNodeHirerachy(childID, threeNode);
}, this);
}
return threeNode;
}
},
buildSkin: {
value: function(node) {
var skin = node.instanceSkin.skin;
if (skin) {
node.instanceSkin.skeletons.forEach(function(skeleton) {
var nodeEntry = this.resources.getEntry(skeleton);
if (nodeEntry) {
var rootSkeleton = nodeEntry.object;
var dobones = true;
var i, len = skin.meshes.length;
for (i = 0; i < len; i++) {
var mesh = skin.meshes[i];
var threeMesh = null;
mesh.primitives.forEach(function(primitive) {
var material = primitive.material;
if (!(material instanceof THREE.Material)) {
material = this.createShaderMaterial(material);
}
threeMesh = new THREE.SkinnedMesh(primitive.geometry.geometry, material, false);
threeMesh.add(rootSkeleton);
var geometry = primitive.geometry.geometry;
var j;
if (geometry.vertices) {
for ( j = 0; j < geometry.vertices.length; j ++ ) {
geometry.vertices[j].applyMatrix4( skin.bindShapeMatrix );
}
}
else if (geometry.attributes.position) {
var a = geometry.attributes.position.array;
var v = new THREE.Vector3;
for ( j = 0; j < a.length / 3; j++ ) {
v.set(a[j * 3], a[j * 3 + 1], a[j * 3 + 2]);
v.applyMatrix4( skin.bindShapeMatrix );
a[j * 3] = v.x;
a[j * 3 + 1] = v.y;
a[j * 3 + 2] = v.z;
}
}
if (threeMesh && dobones) {
material.skinning = true;
threeMesh.boneInverses = [];
var jointNames = skin.jointNames;
var joints = [];
var i, len = jointNames.length;
for (i = 0; i < len; i++) {
var jointName = jointNames[i];
var nodeForJoint = this.joints[jointName];
var joint = this.resources.getEntry(nodeForJoint).object;
if (joint) {
joint.skin = threeMesh;
joints.push(joint);
threeMesh.bones.push(joint);
var m = skin.inverseBindMatrices;
var mat = new THREE.Matrix4(
m[i * 16 + 0], m[i * 16 + 4], m[i * 16 + 8], m[i * 16 + 12],
m[i * 16 + 1], m[i * 16 + 5], m[i * 16 + 9], m[i * 16 + 13],
m[i * 16 + 2], m[i * 16 + 6], m[i * 16 + 10], m[i * 16 + 14],
m[i * 16 + 3], m[i * 16 + 7], m[i * 16 + 11], m[i * 16 + 15]
);
threeMesh.boneInverses.push(mat);
threeMesh.pose();
} else {
console.log("WARNING: jointName:"+jointName+" cannot be found in skeleton:"+skeleton);
}
}
}
if (threeMesh) {
threeMesh.castShadow = true;
node.add(threeMesh);
}
}, this);
}
}
}, this);
}
}
},
buildSkins: {
value: function(node) {
if (node.instanceSkin)
this.buildSkin(node);
var children = node.children;
if (children) {
children.forEach( function(child) {
this.buildSkins(child);
}, this);
}
}
},
createMeshAnimations : {
value : function(root) {
this.buildSkins(root);
}
},
handleScene: {
value: function(entryID, description, userInfo) {
if (!description.nodes) {
console.log("ERROR: invalid file required nodes property is missing from scene");
return false;
}
description.nodes.forEach( function(nodeUID) {
this.buildNodeHirerachy(nodeUID, userInfo.rootObj);
}, this);
if (this.delegate) {
this.delegate.loadCompleted(userInfo.callback, userInfo.rootObj);
}
return true;
}
},
handleImage: {
value: function(entryID, description, userInfo) {
this.resources.setEntry(entryID, null, description);
return true;
}
},
addNodeAnimationChannel : {
value : function(name, channel, interp) {
if (!this.nodeAnimationChannels)
this.nodeAnimationChannels = {};
if (!this.nodeAnimationChannels[name]) {
this.nodeAnimationChannels[name] = [];
}
this.nodeAnimationChannels[name].push(interp);
},
},
createAnimations : {
value : function() {
for (var name in this.nodeAnimationChannels) {
var nodeAnimationChannels = this.nodeAnimationChannels[name];
var i, len = nodeAnimationChannels.length;
//console.log(" animation channels for node " + name);
//for (i = 0; i < len; i++) {
// console.log(nodeAnimationChannels[i]);
//}
var anim = new THREE.glTFAnimation(nodeAnimationChannels);
anim.name = "animation_" + name;
this.animations.push(anim);
}
}
},
buildAnimation: {
value : function(animation) {
var interps = [];
var i, len = animation.channels.length;
for (i = 0; i < len; i++) {
var channel = animation.channels[i];
var sampler = animation.samplers[channel.sampler];
if (sampler) {
var input = animation.parameters[sampler.input];
if (input && input.data) {
var output = animation.parameters[sampler.output];
if (output && output.data) {
var target = channel.target;
var node = this.resources.getEntry(target.id);
if (node) {
var path = target.path;
if (path == "rotation")
{
convertAxisAngleToQuaternion(output.data, output.count);
}
var interp = {
keys : input.data,
values : output.data,
count : input.count,
target : node.object,
path : path,
type : sampler.interpolation
};
this.addNodeAnimationChannel(target.id, channel, interp);
interps.push(interp);
}
}
}
}
}
}
},
handleAnimation: {
value: function(entryID, description, userInfo) {
var self = this;
theLoader.animationsRequested++;
var animation = new Animation();
animation.name = entryID;
animation.onload = function() {
// self.buildAnimation(animation);
theLoader.animationsLoaded++;
theLoader.animations.push(animation);
theLoader.checkComplete();
};
animation.channels = description.channels;
animation.samplers = description.samplers;
this.resources.setEntry(entryID, animation, description);
var parameters = description.parameters;
if (!parameters) {
//FIXME: not implemented in delegate
console.log("MISSING_PARAMETERS for animation:"+ entryID);
return false;
}
// Load parameter buffers
var params = Object.keys(parameters);
params.forEach( function(param) {
animation.totalParameters++;
var parameter = parameters[param];
var accessor = this.resources.getEntry(parameter);
if (!accessor)
debugger;
accessor = accessor.object;
var bufferView = this.resources.getEntry(accessor.bufferView);
var paramObject = {
bufferView : bufferView,
byteOffset : accessor.byteOffset,
count : accessor.count,
componentType : accessor.componentType,
type : accessor.type,
id : accessor.bufferView,
name : param
};
var paramContext = new AnimationParameterContext(paramObject, animation);
var alreadyProcessedAttribute = THREE.GLTFLoaderUtils.getBuffer(paramObject, animationParameterDelegate, paramContext);
/*if(alreadyProcessedAttribute) {
vertexAttributeDelegate.resourceAvailable(alreadyProcessedAttribute, attribContext);
}*/
}, this);
return true;
}
},
handleAccessor: {
value: function(entryID, description, userInfo) {
// Save attribute entry
this.resources.setEntry(entryID, description, description);
return true;
}
},
handleSkin: {
value: function(entryID, description, userInfo) {
// Save skin entry
var skin = {
};
var m = description.bindShapeMatrix;
skin.bindShapeMatrix = new THREE.Matrix4(
m[0], m[4], m[8], m[12],
m[1], m[5], m[9], m[13],
m[2], m[6], m[10], m[14],
m[3], m[7], m[11], m[15]
);
skin.jointNames = description.jointNames;
var inverseBindMatricesDescription = this.resources.getEntry(description.inverseBindMatrices);
inverseBindMatricesDescription = inverseBindMatricesDescription.description;
skin.inverseBindMatricesDescription = inverseBindMatricesDescription;
skin.inverseBindMatricesDescription.id = description.inverseBindMatrices;
var bufferEntry = this.resources.getEntry(inverseBindMatricesDescription.bufferView);
var paramObject = {
bufferView : bufferEntry,
byteOffset : inverseBindMatricesDescription.byteOffset,
count : inverseBindMatricesDescription.count,
componentType : inverseBindMatricesDescription.componentType,
type : inverseBindMatricesDescription.type,
id : inverseBindMatricesDescription.bufferView,
name : skin.inverseBindMatricesDescription.id
};
var context = new InverseBindMatricesContext(paramObject, skin);
var alreadyProcessedAttribute = THREE.GLTFLoaderUtils.getBuffer(paramObject, inverseBindMatricesDelegate, context);
var bufferView = this.resources.getEntry(skin.inverseBindMatricesDescription.bufferView);
skin.inverseBindMatricesDescription.bufferView =
bufferView.object;
this.resources.setEntry(entryID, skin, description);
return true;
}
},
handleSampler: {
value: function(entryID, description, userInfo) {
// Save attribute entry
this.resources.setEntry(entryID, description, description);
return true;
}
},
handleTexture: {
value: function(entryID, description, userInfo) {
// Save attribute entry
this.resources.setEntry(entryID, null, description);
return true;
}
},
handleError: {
value: function(msg) {
throw new Error(msg);
return true;
}
},
_delegate: {
value: new LoadDelegate,
writable: true
},
delegate: {
enumerable: true,
get: function() {
return this._delegate;
},
set: function(value) {
this._delegate = value;
}
}
});
// Loader
var Context = function(rootObj, callback) {
this.rootObj = rootObj;
this.callback = callback;
};
var rootObj = new THREE.Object3D();
var self = this;
var loader = Object.create(ThreeGLTFLoader);
loader.initWithPath(url);
loader.load(new Context(rootObj,
function(obj) {
}),
null);
this.loader = loader;
this.callback = callback;
this.rootObj = rootObj;
return rootObj;
}
THREE.glTFLoader.prototype.callLoadedCallback = function() {
var result = {
scene : this.rootObj,
cameras : this.loader.cameras,
animations : this.loader.animations,
};
this.callback(result);
}
THREE.glTFLoader.prototype.checkComplete = function() {
if (this.meshesLoaded == this.meshesRequested
&& this.shadersLoaded == this.shadersRequested
&& this.animationsLoaded == this.animationsRequested)
{
for (var i = 0; i < this.pendingMeshes.length; i++) {
var pending = this.pendingMeshes[i];
pending.mesh.attachToNode(pending.node);
}
for (var i = 0; i < this.animationsLoaded; i++) {
var animation = this.animations[i];
this.loader.buildAnimation(animation);
}
this.loader.createAnimations();
this.loader.createMeshAnimations(this.rootObj);
this.callLoadedCallback();
}
}
| 35.754513 | 159 | 0.491031 |
43613df8927f9d4c8aff4ff8e27600fbaa118966 | 16,757 | js | JavaScript | components/js/device-status.js | johnclary/atd-data-and-performance | 6704040fc118c199ffee83a326f68dbebaa26c33 | [
"CC0-1.0"
] | 2 | 2019-11-23T17:20:14.000Z | 2021-08-14T12:02:36.000Z | components/js/device-status.js | johnclary/atd-data-and-performance | 6704040fc118c199ffee83a326f68dbebaa26c33 | [
"CC0-1.0"
] | 59 | 2019-10-24T17:12:27.000Z | 2022-02-26T03:53:59.000Z | components/js/device-status.js | johnclary/atd-data-and-performance | 6704040fc118c199ffee83a326f68dbebaa26c33 | [
"CC0-1.0"
] | 1 | 2021-07-04T20:00:49.000Z | 2021-07-04T20:00:49.000Z | // assumes one record per device-type per location
var data_master,
map,
marker,
feature_layer,
table,
filters,
selector_change,
curr_breakpoint;
var prev_breakpoint = undefined;
var show_modal = false;
var q = d3.queue();
var location_id_field = "atd_location_id";
var comm_status_field = "ip_comm_status";
var comm_status_date_field = "comm_status_datetime_utc";
var table_cols = ["Location", "Device Status"];
var device_data = [
{
name: "cctv",
icon: "video-camera",
display_name: "CCTV",
resource_id: "fs3c-45ge",
id_field: "camera_id",
query: 'select * where upper(camera_mfg) not in ("GRIDSMART")',
},
{
name: "gridsmart",
icon: "crosshairs",
display_name: "GRIDSMART",
resource_id: "sqwb-zh93", // qpuw-8eeb
id_field: "atd_camera_id",
query: 'select * where upper(detector_type) LIKE ("%25GRIDSMART%25")',
},
{
name: "travel_sensor",
icon: "rss",
display_name: "Travel Sensors",
resource_id: "wakh-bdjq",
id_field: "sensor_id",
query:
'select sensor_type,atd_location_id,location_name,ip_comm_status,comm_status_datetime_utc where sensor_status in ("TURNED_ON")',
},
{
name: "traffic_signal",
icon: "car",
display_name: "Signal",
resource_id: "xwqn-2f78",
id_field: "signal_id",
query:
'select atd_location_id,signal_id,signal_status,location_name,location,control,ip_comm_status,comm_status_datetime_utc where control in ("PRIMARY") and signal_status in ("TURNED_ON") limit 10000',
},
];
var map_options = {
center: [30.27, -97.74],
zoom: 11,
minZoom: 1,
maxZoom: 20,
zoomControl: false,
};
var img_url_base = "http://atdatmsweb2.austintexas.gov/CCTVImages/CCTV";
var default_styles = {
ONLINE: {
color: "#fff",
weight: 1,
fillColor: "#056315",
fillOpacity: 0.8,
},
OFFLINE: {
color: "#fff",
weight: 1,
fillColor: "#a52626",
fillOpacity: 0.8,
},
};
var table_height = "60vh";
var t_options = {
ease: d3.easeQuad,
duration: 500,
};
var t1 = d3.transition().ease(t_options.ease).duration(t_options.duration);
var t2 = d3.transition().ease(t_options.ease).duration(t_options.duration);
var formats = {
round: function (val) {
return Math.round(val);
},
formatDateTime: d3.timeFormat("%x %X"),
formatDate: d3.timeFormat("%x"),
formatTime: d3.timeFormat("%I:%M %p"),
thousands: d3.format(","),
};
var coa_net_passthrough = "http://10.66.2.64:8000/?";
var SCALE_THRESHOLDS = {
$1: 500,
$2: 500,
$3: 500,
$4: 500,
$5: 500,
$6: 500,
$7: 500,
$8: 500,
$9: 500,
$10: 500,
$11: 400,
$12: 250,
$13: 150,
$14: 100,
$15: 50,
$16: 40,
$17: 25,
$18: 10,
$19: 10,
$20: 10,
};
$("#dashModal").on("shown.bs.modal", function (e) {
var mod_width = $(".modal-body").width();
$("#modal-info").find("img").attr("width", mod_width);
});
$('a[data-toggle="tab"]').on("shown.bs.tab", function () {
map.invalidateSize();
});
$(document).ready(function () {
for (var i = 0; i < device_data.length; ++i) {
if ("resource_id" in device_data[i]) {
var url = buildSocrataUrl(device_data[i]);
var name = device_data[i]["name"];
q.defer(d3.json, url);
}
}
q.awaitAll(function (error) {
if (error) throw error;
for (var i = 0; i < arguments[1].length; i++) {
device_data[i].data = arguments[1][i];
}
main(device_data);
});
});
$("#dashModal").on("shown.bs.modal", function () {
map.invalidateSize();
});
function main(data) {
var map_selectors = createMapSelectors("map_selectors", device_data);
data_master = groupByLocation(data);
map = makeMap("map", map_options);
data_master = createMarkers(data_master, default_styles);
filters = checkFilters();
var filtered_data = filterByKeyExits(data_master, filters);
var cols = createTableCols("data_table", table_cols);
populateTable(filtered_data, "data_table");
$("#search_input").on("keyup", function () {
table.search(this.value).draw();
});
map.on("zoomend", function () {
setMarkerSizes(data_master);
});
$(".btn-map-selector").on("click", function () {
if ($(this).hasClass("active")) {
$(this).removeClass("active").attr("aria-pressed", false);
} else {
$(this).addClass("active").attr("aria-pressed", true);
}
selector_change = true;
filterChange();
});
createTableListeners();
// https://stackoverflow.com/questions/5489946/jquery-how-to-wait-for-the-end-of-resize-event-and-only-then-perform-an-ac
var resize_timer;
window.onresize = function () {
clearTimeout(resize_timer);
resize_timer = setTimeout(resizedw, 100);
};
}
function buildSocrataUrl(data) {
var resource_id = data.resource_id;
var url = "https://data.austintexas.gov/resource/" + resource_id + ".json";
if (data.query) {
url = url + "?$query=" + data.query;
}
return url;
}
function createMapSelectors(div_id, obj_arr) {
var selectors = d3
.select("#" + div_id)
.selectAll("div")
.data(obj_arr)
.enter()
.append("div")
.attr("class", "col-sm")
.append("btn")
.attr("type", "button")
.attr("data_id", function (d) {
return d.name;
})
.attr("class", "btn btn-block btn-primary btn-map-selector")
.attr("aria-pressed", function (d, i) {
// class first button as 'active'
if (i == 0) {
return true;
} else {
return false;
}
})
.classed("active", function (d, i) {
// class first button as 'active'
if (i == 0) {
return true;
} else {
return false;
}
})
.html(function (d) {
return '<i class="fa fa-' + d.icon + '" ></i> ' + d.display_name;
});
return selectors;
}
function findWithAttr(array, attr, value) {
// http://stackoverflow.com/questions/7176908/how-to-get-index-of-object-by-its-property-in-javascript
for (var i = 0; i < array.length; i += 1) {
if (array[i][attr] === value) {
return i;
}
}
return -1;
}
function groupByLocation(data) {
var grouped_data = [];
for (var i = 0; i < device_data.length; ++i) {
for (var q = 0; q < device_data[i].data.length; q++) {
var locationId = device_data[i].data[q][location_id_field];
var current_id = grouped_data.length + 1;
var loc_exists = grouped_data.some(function (loc) {
return loc.locationId === locationId;
});
if (!loc_exists) {
if (!device_data[i].data[q].location) {
continue;
}
// build location record
var device_name = device_data[i]["name"];
var new_loc = {
location: device_data[i].data[q].location,
locationId: locationId,
location_name: device_data[i].data[q].location_name,
};
// append device-specifc attributes
new_loc[device_name] = {
status: device_data[i].data[q][comm_status_field],
status_date: device_data[i].data[q][comm_status_date_field],
device_id: device_data[i].data[q][device_data[i]["id_field"]],
};
grouped_data.push(new_loc);
} else {
// location exists
// append device-specifc attributes
var index = findWithAttr(grouped_data, "locationId", locationId);
grouped_data[index][device_data[i].name] = {
status: device_data[i].data[q][comm_status_field],
status_date: device_data[i].data[q][comm_status_date_field],
device_id: device_data[i].data[q][device_data[i]["id_field"]],
};
}
}
}
return grouped_data;
}
function makeMap(divId, options) {
// mappy map
L.Icon.Default.imagePath = "../components/images/";
var layers = {
carto_positron: L.tileLayer(
"http://{s}.basemaps.cartocdn.com/light_all/{z}/{x}/{y}.png",
{
attribution:
'© <a href="http://www.openstreetmap.org/copyright">OpenStreetMap</a> © <a href="http://cartodb.com/attributions">CartoDB</a>',
subdomains: "abcd",
maxZoom: 19,
}
),
stamen_toner_lite: L.tileLayer(
"http://stamen-tiles-{s}.a.ssl.fastly.net/toner-lite/{z}/{x}/{y}.{ext}",
{
attribution:
'Map tiles by <a href="http://stamen.com">Stamen Design</a>, <a href="http://creativecommons.org/licenses/by/3.0">CC BY 3.0</a> — Map data © <a href="http://www.openstreetmap.org/copyright">OpenStreetMap</a>',
subdomains: "abcd",
maxZoom: 20,
ext: "png",
}
),
};
var map = new L.Map(divId, options).addLayer(layers["stamen_toner_lite"]);
var zoomHome = L.Control.zoomHome();
zoomHome.addTo(map);
return map;
}
function createMarkers(data, style) {
// create markers and layers for each device type
for (var i = 0; i < data.length; i++) {
var marker_style = style["OFFLINE"];
var location_name = data[i].location_name;
var lat = data[i].location.coordinates[1];
var lon = data[i].location.coordinates[0];
var popup_text = "<b>" + location_name + "</b>";
var img_url = false;
for (var q = 0; q < device_data.length; q++) {
if (device_data[q]["name"] in data[i]) {
if (device_data[q]["name"] == "cctv") {
var id = data[i]["cctv"]["device_id"];
var img_url = img_url_base + id + ".jpg";
}
if (data[i][device_data[q]["name"]]["status"] == "ONLINE") {
var status = "Online";
} else {
var status = "Offline";
}
if (data[i][device_data[q]["name"]]["status_date"]) {
var status_date = new Date(
data[i][device_data[q]["name"]]["status_date"]
);
status_date = formats["formatDateTime"](status_date);
status_date = " since " + status_date;
} else {
var status_date = "";
}
popup_text =
popup_text +
"<br>" +
'<i class="fa fa-' +
device_data[q].icon +
'" ></i>' +
": " +
status +
status_date;
}
}
if (img_url) {
cam_url = coa_net_passthrough + "cam_id=" + id;
popup_text =
"<a href=" +
img_url +
" target=_blank >" +
"<img class='popup-img' src=" +
img_url +
" width=300 /></a><br>" +
popup_text +
"<br><a href=" +
cam_url +
" target=_blank >Video Feed (Restricted Access)</a>";
}
if (popup_text.indexOf("Online") > -1) {
marker_style = style["ONLINE"];
}
data[i]["marker"] = L.circle([lat, lon], 500)
.bindPopup(popup_text)
.setStyle(marker_style);
}
return data;
}
function getMarkers(source_data, id_array) {
var layer = new L.featureGroup();
for (var i = 0; i < source_data.length; i++) {
if (id_array.indexOf("$" + source_data[i]["location"]) > -1) {
var marker_style = getStyle(source_data[i], default_styles);
source_data[i]["marker"].setStyle(marker_style).addTo(layer);
}
}
return layer;
}
function updateMap(layer) {
if (map.hasLayer(feature_layer)) {
map.removeLayer(feature_layer);
}
feature_layer = layer;
feature_layer.addTo(map);
adjustView(layer);
}
function createTableCols(div_id, col_array) {
var cols = d3
.select("#" + div_id)
.select("thead")
.append("tr")
.selectAll("th")
.data(col_array)
.enter()
.append("th")
.text(function (d) {
return d;
});
return cols;
}
function populateTable(data, divId) {
if ($("#" + divId)) {
$("#" + divId)
.dataTable()
.fnDestroy();
}
table = $("#data_table").DataTable({
data: data,
rowId: "locationId",
scrollY: table_height,
scrollCollapse: false,
bInfo: true,
paging: false,
autoWidth: true,
drawCallback: function (settings) {
var ids = [];
$(".tableRow").each(function (i, obj) {
ids.push(obj.id);
});
var marker_layer = getMarkers(data, ids);
updateMap(marker_layer);
},
columns: [
{
data: "location_name",
render: function (data, type, full, meta) {
if ("location" in full) {
return (
"<a class='tableRow' id='$" +
full.location +
"' '>" +
data +
"</a>"
);
} else {
return "";
}
},
},
{
data: "location_name",
render: function (data, type, full, meta) {
var render_str = "";
for (var i = 0; i < device_data.length; i++) {
var device_name = device_data[i].name;
if (device_name in full && filters.indexOf(device_name) >= 0) {
if (full[device_name].status == "ONLINE") {
render_str =
render_str +
" <i class='table-icon fa fa-" +
device_data[i].icon +
"' style='background-color:#028102'></i> ";
} else {
render_str =
render_str +
" <i class='table-icon fa fa-" +
device_data[i].icon +
"' style='background-color:darkred'></i> ";
}
}
}
return render_str;
},
},
],
});
d3.select("#data_table_filter").remove();
createTableListeners();
resizedw();
}
function setMarkerSizes(data) {
var zoom = map.getZoom();
for (var i = 0; i < data.length; i++) {
data[i].marker.setRadius(SCALE_THRESHOLDS["$" + zoom]);
}
}
function zoomToMarker(marker_id, data) {
for (var i = 0; i < data.length; i++) {
if (data[i].locationId == marker_id) {
marker = data[i].marker;
if (show_modal) {
map.closePopup();
map.setView(marker._latlng, 16);
var popup = marker._popup._content;
$("#modal-info").append(
"<div id='modal-popup-container'>" + popup + "</div>"
);
$("#dashModal").modal("toggle");
} else {
map.setView(marker._latlng, 17);
marker.openPopup();
map.invalidateSize();
}
}
}
}
function checkFilters() {
filters = [];
$("btn.active")
.not(":hidden")
.each(function () {
filters.push($(this).attr("data_id"));
});
return Array.from(new Set(filters)); // remove duplicates, which may arise from having 'hidden' filters based on display invalidateSize
}
function filterByKeyExits(data, filters) {
return data.filter(function (record) {
return Object.keys(record).some(function (key) {
return filters.indexOf(key) > -1;
});
});
}
function filterChange() {
filters = checkFilters();
var data = filterByKeyExits(data_master, filters);
populateTable(data, "data_table");
}
function adjustView(layer) {
if (filters.length == 0) {
// apply default view when no filters are applied (ie map is empty)
map.setView(map_options.center, map_options.zoom);
map.invalidateSize();
} else if (!selector_change) {
// view not updated if selector change
var bounds = layer.getBounds();
if (bounds.hasOwnProperty("_southWest")) {
map.fitBounds(bounds, { maxZoom: 16 });
}
map.invalidateSize();
}
selector_change = false;
}
function createTableListeners() {
d3.selectAll("tr").on("click", function (d) {
$("#modal-popup-container").remove();
var marker_id = d3.select(this).attr("id");
zoomToMarker(marker_id, data_master);
});
}
function resizedw() {
prev_breakpoint = curr_breakpoint;
curr_breakpoint = breakpoint();
if (curr_breakpoint != prev_breakpoint) {
if (
curr_breakpoint === "xs" ||
curr_breakpoint === "sm" ||
curr_breakpoint === "md"
) {
if (!show_modal) {
// copy map to modal
$("#data-row-1").find("#map").appendTo("#modal-map");
map.invalidateSize();
show_modal = true;
}
} else {
if (show_modal) {
$("#modal-map").find("#map").appendTo("#data-row-1");
map.invalidateSize();
show_modal = false;
}
}
}
table.columns.adjust();
}
function getStyle(record, style) {
// style marker based on current filers and comm status
var marker_style = style["ONLINE"]; // device style is online until proven otherwise
for (var i = 0; i < device_data.length; i++) {
var device_name = device_data[i].name;
if (device_name in record && filters.indexOf(device_name) >= 0) {
if (record[device_name].status != "ONLINE") {
marker_style = style["OFFLINE"];
break;
} else {
continue;
}
}
}
return marker_style;
}
| 24.250362 | 230 | 0.57558 |
43613e36c5149402827f65f83cb9797238e37389 | 4,171 | js | JavaScript | work/exampleOzXZ.js | stinsonga/geo-prime-workspace | 809669151912bd1da839334b4a673c5070177477 | [
"CC0-1.0"
] | null | null | null | work/exampleOzXZ.js | stinsonga/geo-prime-workspace | 809669151912bd1da839334b4a673c5070177477 | [
"CC0-1.0"
] | null | null | null | work/exampleOzXZ.js | stinsonga/geo-prime-workspace | 809669151912bd1da839334b4a673c5070177477 | [
"CC0-1.0"
] | null | null | null | function my_function738(){
//18863486046405710613491635203945AuFiEYowqrILrYGlumTvGWzqNILEbMWX
}
function my_function437(){
//25106551156803275968030202679762qwlwiLsgvAbdGoIXDFxCMgJuRmsnxVgZ
}
function my_function528(){
//39902280752757399746834157942222vygSauFqNvTkjwrriSdnbGgKhnzSxvAa
}
function my_function771(){
//69918540538731896313916464153103dkVEEWuXjRkySZnvEaNKYmOnDFXGWNLA
}
function my_function257(){
//56305768202998477228973393927398joUzNPWJrRppFdowVMnblmCwSNaswvWV
}
function my_function723(){
//25185080124001446836691744763802mTxGtIvYcbaYCTLhCHHSlHHcJZHWEuuH
}
function my_function482(){
//62554571008533055069641454302465VnnxhRbbJENZrhYxKNCphBHiafGRCKFQ
}
function my_function787(){
//97763581531310438391321449269241WouvqUvHZLGJfFLuzHJlvuoeLKgcexHd
}
function my_function969(){
//22883276972305561817301560178017RiMcmgHPrukcFOnEXlFXmKSPThOypssF
}
function my_function686(){
//05910313191979632794391073003442WLcHjVjZFDwFfsdmtyDLNQEeeCwHehEn
}
function my_function572(){
//91526625131417545877594082806182hzUHWOoxxMrOGCmhIAvvJfXwQAtbzdkY
}
function my_function793(){
//96359517693030169760982378844734XyIoEDMzPTbpuUzGFYPMZPZRCBmEaoLU
}
function my_function144(){
//35702755925929561644471901967600JDRcZZKDJnFPkORPuwkoCRAPfYcVqllV
}
function my_function905(){
//40553855272961818484784327821764baHcvaIzstIllujkiabdPlxoGrRwoNbe
}
function my_function005(){
//42524588358679639945883972697868WyBSkntkVgnHbPFJqHcajhuzQhONRrPn
}
function my_function059(){
//60819664028297733749900284060046IeXQiCYqHQKOckycwYPqvFKZtECAqgnd
}
function my_function519(){
//48528208680821536197359584536384dHpuUpNFMRXwpIRmMLdKsYAcIzUfSfhX
}
function my_function488(){
//51007460910555822286845050650909NqobnChcvzjHabOHNawctYsBIrDIrqxP
}
function my_function741(){
//09591675080831326272719316694490ZiaRSHjeozlUpBUsgdZjCNMBLYgrLdxE
}
function my_function647(){
//63226607026368470790255388295429FmShUxFETrZKagWQuvRanrnAFgZrVxlN
}
function my_function800(){
//04745746686822589586049715138951xLqSOPlDjTCWjQoZhRqbHlauIHUVbEqZ
}
function my_function116(){
//68058282594596185718514635969487hrxcDRyZKYqcSqkSSNauAQgvgCfHQoMc
}
function my_function775(){
//42762585237286096364185023823474LfcEPPxkJWmtdPWcueQyaAsnCHBdPyIq
}
function my_function293(){
//14493161490456607136381138468995ueWdiByfjmVKpRrcTUSPskTgPozGPrsQ
}
function my_function771(){
//47957832109621873656288309678033qKgdWrecqmJcpmMVHvUpfWdocHGxsUFR
}
function my_function829(){
//94688096290952870214732271911723KwDHkAFzFoASFEOqXuChICWUSTPIXPlF
}
function my_function040(){
//18713177719877522567671944438252ApMZZbMZvaArNBiuBRoIwVCiMvOvKJhn
}
function my_function869(){
//78286641146028019922693332133369qzqgFhipEtKYbOURxxcAxipYvkbSprxb
}
function my_function025(){
//67695865615282637584175898803854fBSCCndLClCwPhddqbZqfNdwqdnEKPap
}
function my_function420(){
//22670863586377828373194528487269xZOVKXyjVDXhFlvcjqpUobcuORQQvdsO
}
function my_function958(){
//64733648029893966026578403826429PjaEidHfIklDDQyZOBaUqMmQWEEgPuwt
}
function my_function566(){
//69860272461587196622239207915458VocajBqleICQyKDbYItbnoHBkVAbPnuD
}
function my_function997(){
//91360014732114040953129770351683XTASBKreQCiaHjFpDbphgsaoSZMiobds
}
function my_function202(){
//88925108208331860322437048387808RCLvhWoDUKoRqFVJqsbZhkSBjZfxFynZ
}
function my_function151(){
//90195383965524734792089808956185yUuCSuASoMXrNMPMXIwtNjKzjyYOhvVd
}
function my_function990(){
//62751082523932065208823358121350OkNYCNKJxhwNwyFNBtUqspdvOWrICwgK
}
function my_function271(){
//97385119819476273969590840770624OmydYGHgdmjKZPbaAuMKfeNMNCQCyarp
}
function my_function226(){
//43047837257395715186375043386903fKuEOcRfsolFelEzDWgeeMhPCEkFPPVv
}
function my_function200(){
//77527847959626394993564530172284UJKBETLUspBsAChcUtMQDanIQHfLzuWH
}
function my_function574(){
//38860323532531073655767123393795CJceGVGTkhHVxiswyCgCMixvMDbNzdDE
}
function my_function326(){
//25349525048535137435075370890143gvmCvPScslBhLwtsoaQwVKXZVydRiHcU
}
function my_function377(){
//92056910941378577737682104320974PoPwwQkRPBBDhRSSmIDtzlLFbtXkAnUS
}
function my_function342(){
//07133448882992834408764514174572TdcVDgCIyzpBOiqELUUMHTpoFJDoMvol
}
| 32.084615 | 66 | 0.886598 |
43614746c82d2f81028544e017242b5dd45dc9c5 | 1,841 | js | JavaScript | server/runtx.js | caffeinum/pravda-contracts | 23b7cc52559f37aa76e50dae9a2590040c0b7246 | [
"Apache-2.0"
] | 3 | 2018-07-22T15:55:55.000Z | 2018-08-24T18:37:26.000Z | server/runtx.js | caffeinum/pravda.contracts | 23b7cc52559f37aa76e50dae9a2590040c0b7246 | [
"Apache-2.0"
] | null | null | null | server/runtx.js | caffeinum/pravda.contracts | 23b7cc52559f37aa76e50dae9a2590040c0b7246 | [
"Apache-2.0"
] | null | null | null | #!/usr/bin/env node
const fs = require('fs')
const { exec, execSync } = require('child_process')
const { NODE } = require('./config')
const _wallet = {
"address": "22322a562195d1aca36ac4b590adb746cf34e80539a6df0ba0b5e5d93536f611",
"privateKey": "a389a556b02673e60471fd5fc86161a6e01c543659194d258b6c1f12645736f722322a562195d1aca36ac4b590adb746cf34e80539a6df0ba0b5e5d93536f611"
}
const getWalletFile = () => `wallet-${Math.random().toString().slice(5)}.json`
const run = (method = 'getBalance', wallet, payload) => {
const wallet_file = getWalletFile()
fs.writeFileSync(wallet_file, JSON.stringify(wallet || _wallet))
if (payload) {
const len = payload.length
const asm = fs.readFileSync(`../methods/${method}.asm`).toString()
const lines = asm.split('\n')
const args = payload.reverse().map(param => `push ${param}`)
const script = [
...args,
...lines.slice(len)
].join("\n")
const command = `pravda compile asm \
--output ../build/bin/${method}.pravda`
console.log('stdin:\n' + script)
const reply = execSync(command, { input: script })
console.log(command + ":\n")
console.log(reply.toString())
}
const command = `pravda broadcast run \
-e ${NODE}/broadcast -w ${wallet_file} \
-l 3000 -i ../build/bin/${method}.pravda`
const reply = execSync(command)
console.log(command + ":\n")
// console.log(reply.toString())
fs.unlinkSync(wallet_file)
return reply.toString()
}
const genWallet = () => {
const command = `pravda gen address`
return execSync(command).toString()
}
const pay = (address, amount = 10000) => {
const command = `pravda broadcast transfer \
-e ${NODE}/broadcast -w ../wallet.json \
-l 5000 -t ${address} -a ${amount}`
return execSync(command).toString()
}
module.exports = { run, genWallet, pay }
| 26.681159 | 146 | 0.664856 |
436211ee8cb8e20071668c6450459b06c56402cf | 14,165 | js | JavaScript | ForumArchive/acc/post_6903_page_2.js | doc22940/Extensions | d8dbc9be08e0b8c0bd6b72e068ef73223d2799a8 | [
"Apache-2.0"
] | 136 | 2015-01-01T17:33:35.000Z | 2022-02-26T16:38:08.000Z | ForumArchive/acc/post_6903_page_2.js | doc22940/Extensions | d8dbc9be08e0b8c0bd6b72e068ef73223d2799a8 | [
"Apache-2.0"
] | 60 | 2015-06-20T00:39:16.000Z | 2021-09-02T22:55:27.000Z | ForumArchive/acc/post_6903_page_2.js | doc22940/Extensions | d8dbc9be08e0b8c0bd6b72e068ef73223d2799a8 | [
"Apache-2.0"
] | 141 | 2015-04-29T09:50:11.000Z | 2022-03-18T09:20:44.000Z | [{"Owner":"Dad72","Date":"2014-06-04T16:03:50Z","Content":"_lt_div class_eq__qt_mages_qt__gt_\n\t\t\t\n_lt_div_gt_- I do not know why_co_ maybe it_t_s my browser_co_ but I find that my browser often crashes when I open my scene and it_t_s random. This may be due to alteration of engine_co_ but it may also be a coincidence. but before I did not have all its crashes of browser._lt_/div_gt__lt_br_gt__lt_div_gt_ _lt_/div_gt__lt_br_gt__lt_div_gt_- I also noticed that my skybox textures are sometimes mixed_co_ it is very random._lt_/div_gt__lt_br_gt__lt_div_gt_ _lt_/div_gt__lt_br_gt__lt_div_gt_- And when I use this_dd_ ground.optimize(32)_sm__lt_/div_gt__lt_br_gt__lt_div_gt_my FPS are down_co_ if I take it off_co_ I_t_m a 60 fps against 55_lt_/div_gt__lt_br_gt_\n\n\t\t\t\n\t\t_lt_/div_gt_\n\n\t\t_lt_div class_eq__qt_ipsI_qt__gt__lt_/div_gt__lt_/div_gt_"},{"Owner":"Deltakosh","Date":"2014-06-04T16:23:57Z","Content":"_lt_div class_eq__qt_mages_qt__gt_\n\t\t\t\n_lt_p_gt_ground.optimize was removed in the latest version _lt_img src_eq__qt_http_dd_//www.html5gamedevs.com/uploads/emoticons/default_smile.png_qt_ alt_eq__qt__dd_)_qt_ srcset_eq__qt_http_dd_//www.html5gamedevs.com/uploads/emoticons/smile@2x.png 2x_qt_ width_eq__qt_20_qt_ height_eq__qt_20_qt__gt__lt_/p_gt_\n\n\n\t\t\t\n\t\t_lt_/div_gt_\n\n\t\t_lt_div class_eq__qt_ipsI_qt__gt__lt_/div_gt__lt_/div_gt_"},{"Owner":"Dad72","Date":"2014-06-04T16:53:06Z","Content":"_lt_div class_eq__qt_mages_qt__gt_\n\t\t\t\n_lt_p_gt_ah. because it is always in the wiki. I wanted to try._lt_/p_gt__lt_p_gt_ _lt_/p_gt__lt_p_gt__lt_a href_eq__qt_https_dd_//github.com/BabylonJS/Babylon.js/wiki/Optimizing-performances-with-octrees_qt_ rel_eq__qt_external nofollow_qt__gt_https_dd_//github.com/BabylonJS/Babylon.js/wiki/Optimizing-performances-with-octrees_lt_/a_gt__lt_/p_gt__lt_p_gt_ _lt_/p_gt__lt_div_gt_and for the skybox that mixes textures of time has other_co_ you have an idea of what could be the cause? It is very random it are well place the most pars of the time_co_ but once out of five it are mix._lt_/div_gt__lt_div_gt_ _lt_/div_gt__lt_div_gt_For the crash_co_ I will reboot my pc and see if it changes something._lt_/div_gt__lt_p_gt_ _lt_/p_gt__lt_p_gt_ _lt_/p_gt_\n\n\n\t\t\t\n\t\t_lt_/div_gt_\n\n\t\t_lt_div class_eq__qt_ipsI_qt__gt__lt_/div_gt__lt_/div_gt_"},{"Owner":"Deltakosh","Date":"2014-06-04T18:59:53Z","Content":"_lt_div class_eq__qt_mages_qt__gt_\n\t\t\t\n_lt_p_gt_I fixed the wiki _lt_img src_eq__qt_http_dd_//www.html5gamedevs.com/uploads/emoticons/default_smile.png_qt_ alt_eq__qt__dd_)_qt_ srcset_eq__qt_http_dd_//www.html5gamedevs.com/uploads/emoticons/smile@2x.png 2x_qt_ width_eq__qt_20_qt_ height_eq__qt_20_qt__gt__lt_/p_gt_\n\n\n\t\t\t\n\t\t_lt_/div_gt_\n\n\t\t_lt_div class_eq__qt_ipsI_qt__gt__lt_/div_gt__lt_/div_gt_"},{"Owner":"Kilombo","Date":"2014-06-05T12:07:10Z","Content":"_lt_div class_eq__qt_mages_qt__gt_\n\t\t\t\n_lt_blockquote data-ipsquote_eq__qt__qt_ class_eq__qt_ipsQuote_qt_ data-ipsquote-contentcommentid_eq__qt_41368_qt_ data-ipsquote-contenttype_eq__qt_forums_qt_ data-ipsquote-contentclass_eq__qt_forums_Topic_qt_ data-ipsquote-contentid_eq__qt_6903_qt_ data-ipsquote-username_eq__qt_Deltakosh_qt_ data-cite_eq__qt_Deltakosh_qt_ data-ipsquote-timestamp_eq__qt_1401896779_qt__gt__lt_div_gt__lt_div_gt__lt_p_gt_I think I added mipmaps support to cubetexture. that_t_s could be the problem. Could you try to create the cubetexture without mipmap? (latest parameter of the constructor)_lt_/p_gt__lt_/div_gt__lt_/div_gt__lt_/blockquote_gt__lt_p_gt_I checked out the constructor. But by default the cubetexture receives what I put in the constructor in the _qt_noMipmap_qt_ variable_co_ well the thing is. I don_t_t use the last two parameters on the signature (function CubeTexture(rootUrl_co_ scene_co_ extensions_co_ noMipmap))_co_ I only use rootUrl and scene_co_ the other two that I_t_m not putting anything what will it assume? Null ?_lt_/p_gt_\n\n\n\t\t\t\n\t\t_lt_/div_gt_\n\n\t\t_lt_div class_eq__qt_ipsI_qt__gt__lt_/div_gt__lt_/div_gt_"},{"Owner":"Wingnut","Date":"2014-06-05T13:14:50Z","Content":"_lt_div class_eq__qt_mages_qt__gt_\n\t\t\t\n_lt_p_gt_Kilo... take a look at..._lt_/p_gt__lt_p_gt_ _lt_/p_gt__lt_p_gt__lt_a href_eq__qt_https_dd_//github.com/BabylonJS/Babylon.js/blob/master/Babylon/Materials/textures/babylon.cubeTexture.js_qt_ rel_eq__qt_external nofollow_qt__gt_https_dd_//github.com/BabylonJS/Babylon.js/blob/master/Babylon/Materials/textures/babylon.cubeTexture.js_lt_/a_gt__lt_/p_gt__lt_p_gt_ _lt_/p_gt__lt_p_gt_Look at lines 22-24. _lt_/p_gt__lt_p_gt_ _lt_/p_gt__lt_p_gt_22_dd_ if (!extensions) {_lt_br_gt_23_dd_ extensions _eq_ [_qt__px.jpg_qt__co_ _qt__py.jpg_qt__co_ _qt__pz.jpg_qt__co_ _qt__nx.jpg_qt__co_ _qt__ny.jpg_qt__co_ _qt__nz.jpg_qt_]_sm__lt_br_gt_24_dd_ }_lt_/p_gt__lt_p_gt_ _lt_/p_gt__lt_p_gt_Line 22 does a boolean test for extensions... so you could put an array of extension strings in that third parameter_co_ if wanted. Or... false or 0... if you want to use the default extensions to the file names._lt_/p_gt__lt_p_gt_ _lt_/p_gt__lt_p_gt_Now lets look at the fourth parameter.... noMipmap. See line 30? _lt_/p_gt__lt_p_gt_ _lt_/p_gt__lt_p_gt_30_dd_ this._texture _eq_ scene.getEngine().createCubeTexture(rootUrl_co_ scene_co_ extensions_co_ noMipmap)_sm__lt_/p_gt__lt_p_gt_ _lt_/p_gt__lt_p_gt_The fourth parameter... _t_noMipmap_t_ is used in that call to an engine function. Lets go look at that function..._lt_/p_gt__lt_p_gt_ _lt_/p_gt__lt_p_gt__lt_a href_eq__qt_https_dd_//github.com/BabylonJS/Babylon.js/blob/master/Babylon/babylon.engine.js_qt_ rel_eq__qt_external nofollow_qt__gt_https_dd_//github.com/BabylonJS/Babylon.js/blob/master/Babylon/babylon.engine.js_lt_/a_gt__lt_/p_gt__lt_p_gt_ _lt_/p_gt__lt_p_gt_Line 1056 is where the function is_co_ but look at lines 1086 - 1088_lt_/p_gt__lt_p_gt_ _lt_/p_gt__lt_p_gt_1086_dd_ if (!noMipmap) {_lt_br_gt_1087_dd_ gl.generateMipmap(gl.TEXTURE_CUBE_MAP)_sm__lt_br_gt_1088_dd_ }_lt_/p_gt__lt_p_gt_ _lt_/p_gt__lt_p_gt_A boolean test is done on that parameter_co_ too._lt_/p_gt__lt_p_gt_ _lt_/p_gt__lt_p_gt_I didn_t_t answers any questions about including them or not_co_ but now you can see what happens to those values. It is quite possible that the last two parameters ARE optional. So_co_ you see_co_ I didn_t_t help you at all. I just talked. hehe. Deltakosh will probably have some words about it. Hope you_t_re well._lt_/p_gt_\n\n\n\t\t\t\n\t\t_lt_/div_gt_\n\n\t\t_lt_div class_eq__qt_ipsI_qt__gt__lt_/div_gt__lt_/div_gt_"},{"Owner":"Kilombo","Date":"2014-06-05T13:55:05Z","Content":"_lt_div class_eq__qt_mages_qt__gt_\n\t\t\t\n_lt_blockquote data-ipsquote_eq__qt__qt_ class_eq__qt_ipsQuote_qt_ data-ipsquote-contentcommentid_eq__qt_41533_qt_ data-ipsquote-contenttype_eq__qt_forums_qt_ data-ipsquote-contentclass_eq__qt_forums_Topic_qt_ data-ipsquote-contentid_eq__qt_6903_qt_ data-ipsquote-username_eq__qt_Wingnut_qt_ data-cite_eq__qt_Wingnut_qt_ data-ipsquote-timestamp_eq__qt_1401974090_qt__gt__lt_div_gt__lt_div_gt__lt_p_gt_Kilo... take a look at..._lt_/p_gt__lt_p_gt_ _lt_/p_gt__lt_p_gt__lt_a href_eq__qt_https_dd_//github.com/BabylonJS/Babylon.js/blob/master/Babylon/Materials/textures/babylon.cubeTexture.js_qt_ rel_eq__qt_external nofollow_qt__gt_https_dd_//github.com/BabylonJS/Babylon.js/blob/master/Babylon/Materials/textures/babylon.cubeTexture.js_lt_/a_gt__lt_/p_gt__lt_p_gt_ _lt_/p_gt__lt_p_gt_Look at lines 22-24. _lt_/p_gt__lt_p_gt_ _lt_/p_gt__lt_p_gt_22_dd_ if (!extensions) {_lt_/p_gt__lt_p_gt_23_dd_ extensions _eq_ [_qt__px.jpg_qt__co_ _qt__py.jpg_qt__co_ _qt__pz.jpg_qt__co_ _qt__nx.jpg_qt__co_ _qt__ny.jpg_qt__co_ _qt__nz.jpg_qt_]_sm__lt_/p_gt__lt_p_gt_24_dd_ }_lt_/p_gt__lt_p_gt_ _lt_/p_gt__lt_p_gt_Line 22 does a boolean test for extensions... so you could put an array of extension strings in that third parameter_co_ if wanted. Or... false or 0... if you want to use the default extensions to the file names._lt_/p_gt__lt_p_gt_ _lt_/p_gt__lt_p_gt_Now lets look at the fourth parameter.... noMipmap. See line 30? _lt_/p_gt__lt_p_gt_ _lt_/p_gt__lt_p_gt_30_dd_ this._texture _eq_ scene.getEngine().createCubeTexture(rootUrl_co_ scene_co_ extensions_co_ noMipmap)_sm__lt_/p_gt__lt_p_gt_ _lt_/p_gt__lt_p_gt_The fourth parameter... _t_noMipmap_t_ is used in that call to an engine function. Lets go look at that function..._lt_/p_gt__lt_p_gt_ _lt_/p_gt__lt_p_gt__lt_a href_eq__qt_https_dd_//github.com/BabylonJS/Babylon.js/blob/master/Babylon/babylon.engine.js_qt_ rel_eq__qt_external nofollow_qt__gt_https_dd_//github.com/BabylonJS/Babylon.js/blob/master/Babylon/babylon.engine.js_lt_/a_gt__lt_/p_gt__lt_p_gt_ _lt_/p_gt__lt_p_gt_Line 1056 is where the function is_co_ but look at lines 1086 - 1088_lt_/p_gt__lt_p_gt_ _lt_/p_gt__lt_p_gt_1086_dd_ if (!noMipmap) {_lt_/p_gt__lt_p_gt_1087_dd_ gl.generateMipmap(gl.TEXTURE_CUBE_MAP)_sm__lt_/p_gt__lt_p_gt_1088_dd_ }_lt_/p_gt__lt_p_gt_ _lt_/p_gt__lt_p_gt_A boolean test is done on that parameter_co_ too._lt_/p_gt__lt_p_gt_ _lt_/p_gt__lt_p_gt_I didn_t_t answers any questions about including them or not_co_ but now you can see what happens to those values. It is quite possible that the last two parameters ARE optional. So_co_ you see_co_ I didn_t_t help you at all. I just talked. hehe. Deltakosh will probably have some words about it. Hope you_t_re well._lt_/p_gt__lt_/div_gt__lt_/div_gt__lt_/blockquote_gt__lt_p_gt_Nope_co_ wrong answer Wingnut _lt_img src_eq__qt_http_dd_//www.html5gamedevs.com/uploads/emoticons/default_biggrin.png_qt_ alt_eq__qt__dd_D_qt_ srcset_eq__qt_http_dd_//www.html5gamedevs.com/uploads/emoticons/biggrin@2x.png 2x_qt_ width_eq__qt_20_qt_ height_eq__qt_20_qt__gt_ _co_ You did answer my question_co_ because_co_ in line 1086 says if (!noMipmap) do generateMipmap_co_ and thats the point_co_ if I don_t_t use the parameter_co_ noMipmap will be empty or Null_co_ so... there will be noMipmap_co_ and by that it will generate a Mipmap texture. Now... the real question_co_ is.... What do I put there so that it doesn_t_t generate mipmap textures ?_lt_/p_gt__lt_p_gt_ _lt_/p_gt__lt_p_gt_So_co_ you actually helped out _lt_img src_eq__qt_http_dd_//www.html5gamedevs.com/uploads/emoticons/default_smile.png_qt_ alt_eq__qt__dd_)_qt_ srcset_eq__qt_http_dd_//www.html5gamedevs.com/uploads/emoticons/smile@2x.png 2x_qt_ width_eq__qt_20_qt_ height_eq__qt_20_qt__gt__lt_/p_gt_\n\n\n\t\t\t\n\t\t_lt_/div_gt_\n\n\t\t_lt_div class_eq__qt_ipsI_qt__gt__lt_/div_gt__lt_/div_gt_"},{"Owner":"Deltakosh","Date":"2014-06-05T17:24:15Z","Content":"_lt_div class_eq__qt_mages_qt__gt_\n\t\t\t\n_lt_p_gt__lt_span style_eq__qt_color_dd_rgb(40_co_40_co_40)_sm_font-family_dd_helvetica_co_ arial_co_ sans-serif_sm__qt__gt_skyboxMaterial.reflectionTexture _eq_ new BABYLON.CubeTexture(_qt_Textures/Skyboxes/1_1/space_qt__co_ scene_co_ null_co_ true)_sm__lt_/span_gt__lt_/p_gt__lt_p_gt_ _lt_/p_gt__lt_p_gt__lt_span style_eq__qt_color_dd_rgb(40_co_40_co_40)_sm_font-family_dd_helvetica_co_ arial_co_ sans-serif_sm__qt__gt_BTW please use the latest beta_co_ Gwenael found a problem with a merge we did recently that generate textures twice larger than expected _lt_img src_eq__qt_http_dd_//www.html5gamedevs.com/uploads/emoticons/default_smile.png_qt_ alt_eq__qt__dd_)_qt_ srcset_eq__qt_http_dd_//www.html5gamedevs.com/uploads/emoticons/smile@2x.png 2x_qt_ width_eq__qt_20_qt_ height_eq__qt_20_qt__gt__lt_/span_gt__lt_/p_gt_\n\n\n\t\t\t\n\t\t_lt_/div_gt_\n\n\t\t_lt_div class_eq__qt_ipsI_qt__gt__lt_/div_gt__lt_/div_gt_"},{"Owner":"Kilombo","Date":"2014-06-07T00:46:18Z","Content":"_lt_div class_eq__qt_mages_qt__gt_\n\t\t\t\n_lt_p_gt_Thanks Delta. I can finally close this _qt_never ending_qt_ topic. _lt_img src_eq__qt_http_dd_//www.html5gamedevs.com/uploads/emoticons/default_biggrin.png_qt_ alt_eq__qt__dd_D_qt_ srcset_eq__qt_http_dd_//www.html5gamedevs.com/uploads/emoticons/biggrin@2x.png 2x_qt_ width_eq__qt_20_qt_ height_eq__qt_20_qt__gt__lt_/p_gt_\n\n\n\t\t\t\n\t\t_lt_/div_gt_\n\n\t\t_lt_div class_eq__qt_ipsI_qt__gt__lt_/div_gt__lt_/div_gt_"},{"Owner":"Vousk-prod.","Date":"2014-06-30T19:44:53Z","Content":"_lt_div class_eq__qt_mages_qt__gt_\n\t\t\t\n_lt_p_gt_If I may... I found very confusing a parameter called _qt_noMipmap_qt__co_ where you should pass _qt_false_qt_ when you currently want automatic mipmaps generation (double negation is often hard to interpret). And it_t_s quite impossible to know if _qt_noMipmap_qt_ means _qt_do not generate mipmap_qt_ or _qt_there is no mipmap inside my texture_qt_ (in DDS we can embed own mipmaps)_lt_/p_gt__lt_p_gt_ _lt_/p_gt__lt_p_gt_Since for now there is no complete doc with explanation of all parameters_co_ this kind of param should be called more clearly_co_ like for instance _qt_generateMipmap_qt_._lt_/p_gt__lt_p_gt_ _lt_/p_gt__lt_p_gt_Sorry to bother with this kind of consideration _lt_img src_eq__qt_http_dd_//www.html5gamedevs.com/uploads/emoticons/default_ph34r.png_qt_ alt_eq__qt__dd_ph34r_dd__qt_ srcset_eq__qt_http_dd_//www.html5gamedevs.com/uploads/emoticons/ph34r@2x.png 2x_qt_ width_eq__qt_20_qt_ height_eq__qt_20_qt__gt__lt_/p_gt_\n\n\n\t\t\t\n\t\t_lt_/div_gt_\n\n\t\t_lt_div class_eq__qt_ipsI_qt__gt__lt_/div_gt__lt_/div_gt_"},{"Owner":"Deltakosh","Date":"2014-07-01T01:23:52Z","Content":"_lt_div class_eq__qt_mages_qt__gt_\n\t\t\t\n_lt_p_gt_this is a by default parameter for something that is on by default that_t_s why I chose noMipMap as parameter name_dd_ this means do not generate mipmap. But _lt_span style_eq__qt_color_dd_rgb(40_co_40_co_40)_sm_font-family_dd_helvetica_co_ arial_co_ sans-serif_sm__qt__gt__qt_there is no mipmap inside my texture_qt_ could also work for DDS because if you set NoMipMap for a DDS_co_ I will not load mipmaps even if there are mipmaps into the DDS_lt_/span_gt__lt_/p_gt_\n\n\n\t\t\t\n\t\t_lt_/div_gt_\n\n\t\t_lt_div class_eq__qt_ipsI_qt__gt__lt_/div_gt__lt_/div_gt_"},{"Owner":"Vousk-prod.","Date":"2014-07-01T11:12:06Z","Content":"_lt_div class_eq__qt_mages_qt__gt_\n\t\t\t\n_lt_p_gt_Ok_co_ I understand._lt_/p_gt_\n\n\n\t\t\t\n\t\t_lt_/div_gt_\n\n\t\t_lt_div class_eq__qt_ipsI_qt__gt__lt_/div_gt__lt_/div_gt_"}] | 14,165 | 14,165 | 0.84497 |
43627ca1c3bd53c1c2ae05eac6559218ca307d46 | 2,251 | js | JavaScript | Frontend/components/admin/CRUD/Feedback/form/FeedbackFormPage.js | Saehlin/Madewell | 95e44859e385c0db0c52cfaa9207a8e5d9775de2 | [
"PostgreSQL",
"MIT"
] | null | null | null | Frontend/components/admin/CRUD/Feedback/form/FeedbackFormPage.js | Saehlin/Madewell | 95e44859e385c0db0c52cfaa9207a8e5d9775de2 | [
"PostgreSQL",
"MIT"
] | null | null | null | Frontend/components/admin/CRUD/Feedback/form/FeedbackFormPage.js | Saehlin/Madewell | 95e44859e385c0db0c52cfaa9207a8e5d9775de2 | [
"PostgreSQL",
"MIT"
] | null | null | null | import React, { Component } from 'react';
import FeedbackForm from 'components/admin/CRUD/Feedback/form/FeedbackForm';
import { push } from 'connected-react-router';
import actions from 'redux/actions/feedback/feedbackFormActions';
import { connect } from 'react-redux';
class FeedbackFormPage extends Component {
state = {
dispatched: false,
};
componentDidMount() {
const { dispatch, match } = this.props;
if (this.isEditing()) {
dispatch(actions.doFind(match.params.id));
}
else {
if (this.isProfile()) {
const currentUser = JSON.parse(localStorage.getItem('user'));
const currentUserId = currentUser.user.id;
dispatch(actions.doFind(currentUserId));
}
else {
dispatch(actions.doNew());
}
}
this.setState({ dispatched: true });
}
doSubmit = (id, data) => {
const { dispatch } = this.props;
if (this.isEditing() || this.isProfile()) {
dispatch(actions.doUpdate(id, data, this.isProfile()));
} else {
dispatch(actions.doCreate(data));
}
};
isEditing = () => {
const { match } = this.props;
return !!match.params.id;
};
isProfile = () => {
const { match } = this.props;
return match.url === '/app/profile';
};
render() {
console.log(this.props.record);
return (
<React.Fragment>
{this.state.dispatched && (
<FeedbackForm
saveLoading={this.props.saveLoading}
findLoading={this.props.findLoading}
currentUser={this.props.currentUser}
record={
(this.isEditing() || this.isProfile()) ? this.props.record : {}
}
isEditing={this.isEditing()}
isProfile={this.isProfile()}
onSubmit={this.doSubmit}
onCancel={() => this.props.dispatch(push('/admin/feedback'))}
/>
)}
</React.Fragment>
);
}
}
function mapStateToProps(store) {
return {
findLoading: store.feedback.form.findLoading,
saveLoading: store.feedback.form.saveLoading,
record: store.feedback.form.record,
currentUser: store.auth.currentUser,
};
}
export default connect(mapStateToProps)(FeedbackFormPage);
| 27.45122 | 79 | 0.597956 |
436403e0e5dd3788af68479ba4c12e9f57237fe4 | 204 | js | JavaScript | test.js | e-conomic/safeobject | a168f8f2efe9a70afba2138965d09c75e8e50425 | [
"Unlicense",
"MIT"
] | null | null | null | test.js | e-conomic/safeobject | a168f8f2efe9a70afba2138965d09c75e8e50425 | [
"Unlicense",
"MIT"
] | null | null | null | test.js | e-conomic/safeobject | a168f8f2efe9a70afba2138965d09c75e8e50425 | [
"Unlicense",
"MIT"
] | null | null | null | #!/usr/bin/env node
//run Mocha
var realProcessExit = process.exit;
process.exit = function (code) {
setTimeout(realProcessExit.bind(process, code), 2000);
};
require('./node_modules/mocha/bin/_mocha');
| 25.5 | 55 | 0.735294 |
436404aa7429a66a1469c55c44af989e4efeef18 | 4,700 | js | JavaScript | docs/assets/js/71.b4579921.js | ealucas/lemonade | bde3187c6dc00e1e4f594b764daf10b1fdeff89d | [
"Apache-2.0"
] | 14 | 2017-11-26T14:26:31.000Z | 2022-01-09T11:23:01.000Z | docs/assets/js/71.b4579921.js | ealucas/lemonade | bde3187c6dc00e1e4f594b764daf10b1fdeff89d | [
"Apache-2.0"
] | null | null | null | docs/assets/js/71.b4579921.js | ealucas/lemonade | bde3187c6dc00e1e4f594b764daf10b1fdeff89d | [
"Apache-2.0"
] | 7 | 2018-03-01T18:10:01.000Z | 2022-01-18T10:38:55.000Z | (window.webpackJsonp=window.webpackJsonp||[]).push([[71],{212:function(e,a,o){"use strict";o.r(a);var t=o(0),s=Object(t.a)({},function(){var e=this,a=e.$createElement,o=e._self._c||a;return o("ContentSlotsDistributor",{attrs:{"slot-key":e.$parent.slotKey}},[o("h1",{attrs:{id:"analise-de-componentes-principais-pca"}},[e._v("Análise de Componentes Principais (PCA)")]),e._v(" "),o("p",[e._v("A operação Análise de Componentes Principais ("),o("em",[e._v("Principal component analysis")]),e._v(" ou PCA) tem como objetivo reduzir a dimensionalidade (em relação ao número de atributos) de uma base de dados. PCA é um procedimento estatístico que usa uma transformação ortogonal para converter um conjunto de observações com atributos possivelmente correlacionados em um conjunto de observações de atributos linearmente não-correlacionados, chamadas de componentes principais.")]),e._v(" "),o("h3",{attrs:{id:"conectores"}},[e._v("Conectores")]),e._v(" "),o("table",[o("thead",[o("tr",[o("th",[e._v("Entrada")]),e._v(" "),o("th",[e._v("Saída")])])]),e._v(" "),o("tbody",[o("tr",[o("td",[e._v("Dados a serem tratados")]),e._v(" "),o("td",[e._v("Dados tratados")])])])]),e._v(" "),o("h3",{attrs:{id:"tarefa"}},[e._v("Tarefa")]),e._v(" "),o("p",[e._v("Nome da Tarefa")]),e._v(" "),o("h3",{attrs:{id:"aba-execucao"}},[e._v("Aba Execução")]),e._v(" "),o("table",[o("thead",[o("tr",[o("th",[e._v("Parâmetro")]),e._v(" "),o("th",[e._v("Detalhe")])])]),e._v(" "),o("tbody",[o("tr",[o("td",[o("strong",[e._v("Número de componentes principais")])]),e._v(" "),o("td",[e._v("O número de componentes principais final, i.e., os números de atributos a serem construídos pelo PCA")])]),e._v(" "),o("tr",[o("td",[o("strong",[e._v("Atributo(s) previsor(es)")])]),e._v(" "),o("td",[e._v("Atributos da base de dados que sofrerão pré-processamento")])]),e._v(" "),o("tr",[o("td",[o("strong",[e._v("Atributo de saída")])]),e._v(" "),o("td",[e._v("Atributo que terá a saída da operação")])])])]),e._v(" "),o("p",[o("router-link",{attrs:{to:"/spark/"}},[e._v("Aba Aparência")])],1),e._v(" "),o("p",[o("router-link",{attrs:{to:"/spark/"}},[e._v("Aba Resultados")])],1),e._v(" "),o("h2",{attrs:{id:"exemplo-de-utilizacao"}},[e._v("Exemplo de Utilização")]),e._v(" "),o("p",[o("strong",[e._v("Objetivo:")]),e._v(" Utilizar a operação Análise de Componentes Principais para reduzir a dimensionalidade da base de dados Íris."),o("br"),e._v(" "),o("strong",[e._v("Base de Dados:")]),e._v(" "),o("router-link",{attrs:{to:"/spark/"}},[e._v("Íris")])],1),e._v(" "),o("p",[o("img",{attrs:{src:"/img/spark/pre-processamento-de-dados/reducao-de-dimensionalidade-analise-de-componentes-principais/image2.png",alt:"Fluxo de trabalho"}})]),e._v(" "),o("ol",[o("li",[o("p",[e._v("Leia a base de dados Irís por meio da operação "),o("router-link",{attrs:{to:"/spark/"}},[e._v("Ler dados")]),e._v(".")],1)]),e._v(" "),o("li",[o("p",[e._v("Na operação "),o("strong",[e._v("Análise de Componentes Principais (PCA)")]),e._v(", preencha "),o("em",[e._v("“PCA 2”")]),e._v(" no campo "),o("strong",[e._v("Nome da tarefa (opcional)")]),e._v(". Preencha "),o("em",[e._v("2")]),e._v(" no campo Número de componentes principais. Selecione "),o("em",[e._v("“petal_length”")]),e._v(", "),o("em",[e._v("“petalwidth”")]),e._v(", "),o("em",[e._v("“sepallength”")]),e._v(" e "),o("em",[e._v("“sepalwidth”")]),e._v(" no campo "),o("strong",[e._v("Atributo(s) previsor(es)")]),e._v(". Preencha "),o("em",[e._v("“atributo_final”")]),e._v(" no campo "),o("strong",[e._v("Atributo de saída")]),e._v("."),o("br"),e._v(" "),o("img",{attrs:{src:"/img/spark/pre-processamento-de-dados/reducao-de-dimensionalidade-analise-de-componentes-principais/image3.png",alt:"Operação Análise de Componentes Principais"}})])]),e._v(" "),o("li",[o("p",[e._v("Execute o fluxo e visualize uma amostra dos resultados do PCA. Abaixo é mostrada as 10 primeiras instâncias da base de dados com os atributos originais ("),o("em",[e._v("“petal_length”")]),e._v(", “"),o("em",[e._v("petalwidth”")]),e._v(", "),o("em",[e._v("“sepallength”")]),e._v(" e "),o("em",[e._v("“sepalwidth”")]),e._v(") e o atributo de saída do PCA, i.e., o "),o("em",[e._v("“atributo final”")]),e._v(". Observe que os 4 atributos originais da base de dados foram transformados em um atributo que é uma estrutura vetorial com 2 posições correspondendo cada componente principal."),o("br"),e._v(" "),o("img",{attrs:{src:"/img/spark/pre-processamento-de-dados/reducao-de-dimensionalidade-analise-de-componentes-principais/image1.png",alt:"Resultado"}})])])]),e._v(" "),o("hr"),e._v(" "),o("p",[e._v("Dúvidas e/ou sugestões envie um e-mail para suporte@lemonade.org.br")])])},[],!1,null,null,null);a.default=s.exports}}]); | 4,700 | 4,700 | 0.628511 |
43647cc6bb91310325a0b08441d85e3a7b4ca7e7 | 3,800 | js | JavaScript | app/components/LoginForm/index.js | kitsanapong/register-front | 7e67148733154db2ef8ba3c65b02e96ec24de5be | [
"MIT"
] | null | null | null | app/components/LoginForm/index.js | kitsanapong/register-front | 7e67148733154db2ef8ba3c65b02e96ec24de5be | [
"MIT"
] | null | null | null | app/components/LoginForm/index.js | kitsanapong/register-front | 7e67148733154db2ef8ba3c65b02e96ec24de5be | [
"MIT"
] | null | null | null | /**
*
* LoginForm
*
*/
import React from 'react';
import PropTypes from 'prop-types';
import styled from 'styled-components';
import { MdEmail, MdVpnKey } from 'react-icons/md'
import GamicoIcon from 'images/gamico.jpg'
import TextInput from 'components/TextInput'
import Button from 'components/Button'
import { isEmailValid, isPasswordValid } from 'utils/inputValidate'
const StyledCompoent = styled.div`
padding: 48px;
display: flex;
flex-direction: column;
justify-content: space-between;
height: 100%;
.header {
.icon-wrapper {
display: flex;
justify-content: center;
height: 130px;
img {
width: 130px;
border-radius: 50%;
}
}
.text {
.text-highlight {
color: #EE2D60;
}
}
}
.register-wrapper {
text-align: center;
.text {
font-size: 14px;
opacity: 0.54;
}
.highlight {
margin-left: 6px;
cursor: pointer;
font-size: 14px;
color: rgb(24,21,37);
opacity: 1;
font-weight: bold;
}
}
`
/* eslint-disable react/prefer-stateless-function */
class LoginForm extends React.Component {
constructor(props) {
super(props)
this.state = {
emailInput: '',
emailInfo: '',
passwordInput: '',
passwordInfo: '',
}
}
handelLoginClick() {
this.props.login({
email: this.state.emailInput,
password: this.state.passwordInput,
})
}
handleEmailChange(e) {
this.setState({
emailInput: e.target.value,
emailInfo: isEmailValid(e.target.value) ? '' : 'Email must be correct and not exceed 50 of length',
})
}
handlePasswordChange(e) {
this.setState({
passwordInput: e.target.value,
passwordInfo: isPasswordValid(e.target.value) ? '' : 'Password must have 8 - 20 of length',
})
}
renderLoginButton() {
const disable = !isEmailValid(this.state.emailInput) || !isPasswordValid(this.state.passwordInput)
return (
<Button
label="LOGIN"
onClick={() => { this.handelLoginClick() }}
disabled={disable}
/>
)
}
getUsernameInfoText() {
if (Object.keys(this.props.error).length > 0) {
if (this.props.error.status === 401) {
return 'Invalid username or password.'
} else {
return 'Something when wrong. Please try again.'
}
}
return this.state.emailInfo
}
render() {
return (
<StyledCompoent>
<div className="header">
<div className="icon-wrapper">
<img src={GamicoIcon} />
</div>
</div>
<div className="input-wrapper">
<TextInput
id="username"
active={true}
icon={<MdEmail />}
placeholder="Email"
type="text"
onChange={(e) => { this.handleEmailChange(e) }}
info={this.getUsernameInfoText()}
/>
<TextInput
id="password"
icon={<MdVpnKey />}
placeholder="Password"
type="password"
onChange={(e) => { this.handlePasswordChange(e) }}
info={this.state.passwordInfo}
/>
</div>
<div className="button-wrapper">
{ this.renderLoginButton() }
</div>
<div className="register-wrapper">
<span className="text">Don't have an account?</span>
<span id="go-register" className="highlight" onClick={() => { this.props.gotoRegister() }}>Sign up</span>
</div>
</StyledCompoent>
)
}
}
LoginForm.propTypes = {
gotoRegister: PropTypes.func,
login: PropTypes.func,
error: PropTypes.object,
};
LoginForm.defaultProps = {
gotoRegister: () => {},
login: () => {},
error: {},
}
export default LoginForm;
| 23.170732 | 115 | 0.572105 |
4364fd7284eb8d74d21ce0722b7d95632257fdf7 | 3,594 | js | JavaScript | src/components/pieces/Bishop.js | MbuthiaWaKihara/ChessInReact | a2449d4c056381e1799f081ec482ec8a96291b1a | [
"MIT"
] | null | null | null | src/components/pieces/Bishop.js | MbuthiaWaKihara/ChessInReact | a2449d4c056381e1799f081ec482ec8a96291b1a | [
"MIT"
] | null | null | null | src/components/pieces/Bishop.js | MbuthiaWaKihara/ChessInReact | a2449d4c056381e1799f081ec482ec8a96291b1a | [
"MIT"
] | null | null | null | import React from 'react';
//returns a bishop svg
const Bishop = ({pieceColor}) =>
{
return(
<>
{
pieceColor === "white" &&
<svg viewBox="0 0 100 100" xmlns="http://www.w3.org/2000/svg" version="1.1" width={150} height={150}>
<g
style={{
opacity: 1,
fill: "none",
fillRule: "evenodd",
fillOpacity: 1,
stroke: "#000000",
strokeWidth: "1.5",
strokeLinecap: "round",
strokeLinejoin: "round",
strokeMiterlimit: 4,
strokeDasharray: "none",
strokeOpacity: 1
}}
>
<g style={{ fill: "#ffffff", stroke: "#000000", strokeLinecap: "butt" }}>
<path d="M 9,36 C 12.39,35.03 19.11,36.43 22.5,34 C 25.89,36.43 32.61,35.03 36,36 C 36,36 37.65,36.54 39,38 C 38.32,38.97 37.35,38.99 36,38.5 C 32.61,37.53 25.89,38.96 22.5,37.5 C 19.11,38.96 12.39,37.53 9,38.5 C 7.646,38.99 6.677,38.97 6,38 C 7.354,36.06 9,36 9,36 z" />
<path d="M 15,32 C 17.5,34.5 27.5,34.5 30,32 C 30.5,30.5 30,30 30,30 C 30,27.5 27.5,26 27.5,26 C 33,24.5 33.5,14.5 22.5,10.5 C 11.5,14.5 12,24.5 17.5,26 C 17.5,26 15,27.5 15,30 C 15,30 14.5,30.5 15,32 z" />
<path d="M 25 8 A 2.5 2.5 0 1 1 20,8 A 2.5 2.5 0 1 1 25 8 z" />
</g>
<path
d="M 17.5,26 L 27.5,26 M 15,30 L 30,30 M 22.5,15.5 L 22.5,20.5 M 20,18 L 25,18"
style={{ fill: "none", stroke: "#000000", strokeLinejoin: "miter" }}
/>
</g>
</svg>
}
{
pieceColor === "black" &&
<svg viewBox="0 0 100 100" xmlns="http://www.w3.org/2000/svg" version="1.1" width={150} height={150}>
<g
style={{
opacity: 1,
fill: "none",
fillRule: "evenodd",
fillOpacity: 1,
stroke: "#000000",
strokeWidth: "1.5",
strokeLinecap: "round",
strokeLinejoin: "round",
strokeMiterlimit: 4,
strokeDasharray: "none",
strokeOpacity: 1
}}
>
<g style={{ fill: "#000000", stroke: "#000000", strokeLinecap: "butt" }}>
<path d="M 9,36 C 12.39,35.03 19.11,36.43 22.5,34 C 25.89,36.43 32.61,35.03 36,36 C 36,36 37.65,36.54 39,38 C 38.32,38.97 37.35,38.99 36,38.5 C 32.61,37.53 25.89,38.96 22.5,37.5 C 19.11,38.96 12.39,37.53 9,38.5 C 7.646,38.99 6.677,38.97 6,38 C 7.354,36.06 9,36 9,36 z" />
<path d="M 15,32 C 17.5,34.5 27.5,34.5 30,32 C 30.5,30.5 30,30 30,30 C 30,27.5 27.5,26 27.5,26 C 33,24.5 33.5,14.5 22.5,10.5 C 11.5,14.5 12,24.5 17.5,26 C 17.5,26 15,27.5 15,30 C 15,30 14.5,30.5 15,32 z" />
<path d="M 25 8 A 2.5 2.5 0 1 1 20,8 A 2.5 2.5 0 1 1 25 8 z" />
</g>
<path
d="M 17.5,26 L 27.5,26 M 15,30 L 30,30 M 22.5,15.5 L 22.5,20.5 M 20,18 L 25,18"
style={{ fill: "none", stroke: "#ffffff", strokeLinejoin: "miter" }}
/>
</g>
</svg>
}
</>
);
}
export default React.memo(Bishop); | 48.567568 | 291 | 0.42404 |
4365415de394da7e1d0d5217126fe518be9e3f6a | 2,265 | js | JavaScript | Develop/app.js | vivid-green/team-template-engine | 994d315cef8604deb3567f66f8993218007768b3 | [
"MIT"
] | null | null | null | Develop/app.js | vivid-green/team-template-engine | 994d315cef8604deb3567f66f8993218007768b3 | [
"MIT"
] | null | null | null | Develop/app.js | vivid-green/team-template-engine | 994d315cef8604deb3567f66f8993218007768b3 | [
"MIT"
] | null | null | null | const Manager = require("./lib/Manager");
const Engineer = require("./lib/Engineer");
const Intern = require("./lib/Intern");
const Questions = require("./lib/Questions");
const path = require("path");
const fs = require("fs");
const OUTPUT_DIR = path.resolve(__dirname, "output");
const outputPath = path.join(OUTPUT_DIR, "team.html");
const render = require("./lib/htmlRenderer");
const { resolve } = require("path");
const employees = [];
// function that holds Questions method to inquire employee type.
const getRole = () => {
return new Questions().inqRole();
}
// function that holds Questions method to inquire info about the respective employee type.
const getAnswers = ({ role } = answers) => {
return new Promise((resolve, reject) => {
new Questions().inqQuestions(role).then(answers => {
let obj = {
role: role,
answers: answers
}
resolve(obj);
}).catch(err => reject(err));
})
};
// function to add employee to employees array.
const addEmployee = ({ role, answers } = results) => {
return new Promise((resolve) => {
answers = Object.values(answers);
switch (role) {
case "manager":
employees.push(new Manager(...answers));
break;
case "engineer":
employees.push(new Engineer(...answers));
break;
default:
employees.push(new Intern(...answers));
break;
}
resolve();
});
};
//function to inquire if more employees should be added.
const addMore = () => {
return new Questions().inqAddMore();
}
//function to write html file.
const outputHtml = (data) => {
fs.writeFile(outputPath, data, (err) => {
if (err) throw err;
return console.log('The file has been saved!');
});
}
//function to start running CLI prompts.
const runPrompt = () => {
getRole()
.then(getAnswers)
.then(addEmployee)
.then(addMore)
.then(({ more } = answers) => {
if (more) {
runPrompt();
}
else {
const html = render(employees);
return outputHtml(html);
}
})
}
// initialize CLI.
runPrompt();
| 29.415584 | 91 | 0.569536 |
43654a648bf8872b16f156076979edffe1709f8f | 3,017 | js | JavaScript | nl-BE/GameIntegration.js | mruks/pokelink_translations | ed0776aa1037d9f81d39a9a3ef05c08919093f7e | [
"MIT"
] | 2 | 2021-06-02T06:21:26.000Z | 2021-06-29T07:46:19.000Z | nl-BE/GameIntegration.js | mruks/pokelink_translations | ed0776aa1037d9f81d39a9a3ef05c08919093f7e | [
"MIT"
] | 3 | 2021-06-01T21:59:49.000Z | 2021-06-27T19:55:46.000Z | nl-BE/GameIntegration.js | mruks/pokelink_translations | ed0776aa1037d9f81d39a9a3ef05c08919093f7e | [
"MIT"
] | 9 | 2021-05-20T22:56:16.000Z | 2021-08-31T03:23:11.000Z | import * as features from '@data/games/featureList'
export default {
'Features': {
'Description': {
[features.AUTO_BADGE_TRACKING]: 'Automatisch badges volgen',
[features.AUTO_PARTY_TRACKING]: 'Automatisch pokémonteam volgen',
[features.AUTO_PARTY_TRACKING_FIELD_SHINY]: 'Automatisch team volgen - Shiny detectie',
[features.AUTO_PARTY_TRACKING_FIELD_LEVEL_MET]: 'Automatisch team volgen - Level wanneer de pokémon gevangen werd',
[features.AUTO_PARTY_TRACKING_FIELD_TYPES]: 'Automatisch team volgen - Detectie van pokémon types via de ROM in plaats van de generische Pokédex ',
[features.AUTO_PARTY_TRACKING_FIELD_FRIENDSHIP]: 'Automatisch team volgen - pokémon vriendschap',
[features.AUTO_PARTY_TRACKING_FIELD_ABILITY]: 'Automatisch team volgen - pokémon bekwaamheid',
[features.AUTO_PARTY_TRACKING_FIELD_NATURE]: 'Automatisch team volgen - pokémon natuur',
[features.AUTO_PARTY_TRACKING_FIELD_HIDDEN_POWER]: 'Automatisch team volgen - pokémon verborgen kracht',
[features.AUTO_PARTY_TRACKING_FIELD_POKERUS]: 'Automatisch team volgen - Heeft een pokémon Pokérus? - het pokémon virus',
[features.AUTO_PARTY_TRACKING_FIELD_NICKNAME_SPECIAL_CHARS]: 'Automatisch team volgen - Niet standaard (niet alphanumerisch) tekens in de pokémon bijnaam',
[features.AUTO_PARTY_TRACKING_FIELD_MET_AS_EGG]: 'Automatisch team volgen - Detectie van de locatie waar de pokémon was ontmoet, wanneer die uit een ei gekomen is',
[features.AUTO_PARTY_TRACKING_FIELD_POKEBALL]: 'Automatisch team volgen - De pokéball dat gebruikt werd om de pokémon te vangen',
[features.AUTO_PARTY_TRACKING_FIELD_IS_GIFT]: 'Automatisch team volgen - Indien de pokémon was verkregen als cadeau',
[features.AUTO_PARTY_TRACKING_FIELD_EVS]: 'Automatisch team volgen - pokémon inspanningswaarde (EV)',
[features.AUTO_PARTY_TRACKING_FIELD_IVS]: 'Automatisch team volgen - pokémon individuele waarden',
[features.AUTO_PARTY_TRACKING_FIELD_EGG_CYCLES]: 'Automatisch team volgen - pokémon resterende ei cyclussen',
[features.AUTO_PARTY_ROUTE_TRACKING]: 'Automatisch team volgen - Automatisch routes traceren voor pokémon in het team',
[features.AUTO_BOX_ROUTE_TRACKING]: 'Automatisch team volgen - pokémon ',
[features.AUTO_PARTY_IN_BATTLE_UPDATES]: 'Automatisch updaten tijdens een gevecht',
[features.AUTO_BATTLE_TRACKING_FIELD_ACTIVE_IN_BATTLE]: 'Automatisch updaten tijdens een gevecht - Detecteren welke pokémon op het moment in gevecht is',
[features.AUTO_BATTLE_TRACKING_FIELD_STATUS_EFFECT]: 'Automatisch updaten tijdens een gevecht - pokémon status effect',
[features.AUTO_BATTLE_TRACKING_FIELD_HP]: 'Automatisch updaten tijdens een gevecht - pokémon HP',
[features.MANUAL_BADGE_TRACKING]: 'Manueel badges volgen door het gebruik van het badgescherm in Pokélink',
[features.MANUAL_PARTY_TRACKING]: 'Manueel updaten van jouw team door het gebruik van het pokémonteam scherm in Pokélink'
}
}
}
| 88.735294 | 170 | 0.78124 |
4365cf5774eaf29e34e8c46d5289ff7a385f5bbf | 1,652 | js | JavaScript | www/build/ion-header-ios.entry.js | lbakken/pro-component-demo | 86efd08cc4e107753b11c0857355caea25cb86ee | [
"MIT"
] | null | null | null | www/build/ion-header-ios.entry.js | lbakken/pro-component-demo | 86efd08cc4e107753b11c0857355caea25cb86ee | [
"MIT"
] | 1 | 2022-03-24T10:14:42.000Z | 2022-03-24T10:14:42.000Z | www/build/ion-header-ios.entry.js | lbakken/pro-component-demo | 86efd08cc4e107753b11c0857355caea25cb86ee | [
"MIT"
] | null | null | null | import { r as registerInstance, f as getIonMode, h, H as Host } from './chunk-91927964.js';
/**
* @virtualProp {"ios" | "md"} mode - The mode determines which platform styles to use.
*/
class Header {
constructor(hostRef) {
registerInstance(this, hostRef);
/**
* If `true`, the header will be translucent. Only applies to `ios` mode.
* Note: In order to scroll content behind the header, the `fullscreen`
* attribute needs to be set on the content.
*/
this.translucent = false;
}
hostData() {
const mode = getIonMode(this);
return {
class: {
[mode]: true,
// Used internally for styling
[`header-${mode}`]: true,
[`header-translucent`]: this.translucent,
[`header-translucent-${mode}`]: this.translucent,
}
};
}
render() { return h(Host, this.hostData()); }
static get style() { return "ion-header {\n display: block;\n position: relative;\n -ms-flex-order: -1;\n order: -1;\n width: 100%;\n z-index: 10;\n}\n\nion-header ion-toolbar:first-child {\n padding-top: var(--ion-safe-area-top, 0);\n}\n\n.header-ios ion-toolbar:last-child {\n --border-width: 0 0 0.55px;\n}\n\n.header-ios[no-border] ion-toolbar:last-child {\n --border-width: 0;\n}\n\n.header-translucent-ios {\n -webkit-backdrop-filter: saturate(180%) blur(20px);\n backdrop-filter: saturate(180%) blur(20px);\n}\n\n.header-translucent-ios ion-toolbar {\n --opacity: .8;\n --backdrop-filter: saturate(180%) blur(20px);\n}"; }
}
export { Header as ion_header };
| 50.060606 | 646 | 0.595642 |
43661533cc3357c004c58c230f9661030e2a79f1 | 2,546 | js | JavaScript | src/lib/internal/modules/esm/get_format.js | odant/conan-jscript | 0e7433ebe9e5ebf331a47c8b2d01a510c7f53952 | [
"MIT"
] | null | null | null | src/lib/internal/modules/esm/get_format.js | odant/conan-jscript | 0e7433ebe9e5ebf331a47c8b2d01a510c7f53952 | [
"MIT"
] | 5 | 2021-02-13T18:06:42.000Z | 2021-02-13T18:06:44.000Z | src/lib/internal/modules/esm/get_format.js | odant/conan-jscript | 0e7433ebe9e5ebf331a47c8b2d01a510c7f53952 | [
"MIT"
] | 3 | 2019-03-25T23:01:31.000Z | 2020-05-19T01:17:27.000Z | 'use strict';
const {
RegExpPrototypeExec,
StringPrototypeStartsWith,
} = primordials;
const { extname } = require('path');
const { getOptionValue } = require('internal/options');
const experimentalJsonModules = getOptionValue('--experimental-json-modules');
const experimentalSpecifierResolution =
getOptionValue('--experimental-specifier-resolution');
const experimentalWasmModules = getOptionValue('--experimental-wasm-modules');
const { getPackageType } = require('internal/modules/esm/resolve');
const { URL, fileURLToPath } = require('internal/url');
const { ERR_UNKNOWN_FILE_EXTENSION } = require('internal/errors').codes;
const extensionFormatMap = {
'__proto__': null,
'.cjs': 'commonjs',
'.js': 'module',
'.mjs': 'module'
};
const legacyExtensionFormatMap = {
'__proto__': null,
'.cjs': 'commonjs',
'.js': 'commonjs',
'.json': 'commonjs',
'.mjs': 'module',
'.node': 'commonjs'
};
if (experimentalWasmModules)
extensionFormatMap['.wasm'] = legacyExtensionFormatMap['.wasm'] = 'wasm';
if (experimentalJsonModules)
extensionFormatMap['.json'] = legacyExtensionFormatMap['.json'] = 'json';
function defaultGetFormat(url, context, defaultGetFormatUnused) {
if (StringPrototypeStartsWith(url, 'node:')) {
return { format: 'builtin' };
}
const parsed = new URL(url);
if (parsed.protocol === 'data:') {
const [ , mime ] = RegExpPrototypeExec(
/^([^/]+\/[^;,]+)(?:[^,]*?)(;base64)?,/,
parsed.pathname,
) || [ null, null, null ];
const format = ({
'__proto__': null,
'text/javascript': 'module',
'application/json': experimentalJsonModules ? 'json' : null,
'application/wasm': experimentalWasmModules ? 'wasm' : null
})[mime] || null;
return { format };
} else if (parsed.protocol === 'file:') {
const ext = extname(parsed.pathname);
let format;
if (ext === '.js') {
format = getPackageType(parsed.href) === 'module' ? 'module' : 'commonjs';
} else {
format = extensionFormatMap[ext];
}
if (!format) {
if (experimentalSpecifierResolution === 'node') {
process.emitWarning(
'The Node.js specifier resolution in ESM is experimental.',
'ExperimentalWarning');
format = legacyExtensionFormatMap[ext];
} else {
throw new ERR_UNKNOWN_FILE_EXTENSION(ext, fileURLToPath(url));
}
}
return { format: format || null };
}
return { format: null };
}
module.exports = {
defaultGetFormat,
extensionFormatMap,
legacyExtensionFormatMap,
};
| 30.309524 | 80 | 0.648861 |
4366381676858e50c88a64c441080b9bd72a3676 | 1,306 | js | JavaScript | server.js | LabLamb/MTR-Cards-Backend | c8010cc23c6206da393c15872ae87e4401147353 | [
"MIT"
] | 2 | 2020-06-29T19:01:30.000Z | 2020-06-29T23:10:03.000Z | server.js | LabLamb/MTR-Cards-Backend | c8010cc23c6206da393c15872ae87e4401147353 | [
"MIT"
] | 1 | 2022-02-13T17:01:43.000Z | 2022-02-13T17:01:43.000Z | server.js | LabLamb/MTR-Cards-Backend | c8010cc23c6206da393c15872ae87e4401147353 | [
"MIT"
] | null | null | null | const schedule = require('node-schedule'),
app = require('express')(),
http = require('http').createServer(app),
io = require('socket.io')(http),
apiClient = require('./api-client'),
mtrStationsAcronyms = require('./stations'),
mtrLinesAcronyms = require('./lines')
app.get(`/Lines`, (req, res) => {
res.send(mtrLinesAcronyms)
})
app.get(`/Stations/:Line`, (req, res) => {
res.send(mtrStationsAcronyms[req.params[`Line`]])
})
app.get(`*`, (req, res) => {
res.send(`Please visit: <br><a href="https://github.com/LabLamb/MTR-Cards-Backend">https://github.com/LabLamb/MTR-Cards-Backend</a><br> for more info.`)
})
http.listen(process.env.PORT || 3000)
io.on('connection', socket => {
console.log(`${socket.id} connected.`)
})
var job = schedule.scheduleJob('*/10 * * * * *', () => {
for (let line in mtrLinesAcronyms) {
for (let station in mtrStationsAcronyms[line]) {
apiClient.fetchMTRTime(`${line}`, `${station}`)
.then(res => {
io.of(`/`).emit(`${line}_${station}_UPDATE`, res.data)
})
.catch(err => {
console.log(err)
io.of(`/`).emit(`${line}_${station}_UPDATE`, `Something went wrong.`)
})
}
}
}); | 32.65 | 156 | 0.551302 |
436682178214e6d6a362dc367fb7c81fe85d98ad | 3,710 | js | JavaScript | dist/DeployablePanel.jsx.js | homfen/fcui2 | 03b0eb892ff3209bd29044581220bbe0748485f2 | [
"MIT"
] | 23 | 2016-06-24T09:06:22.000Z | 2021-04-22T08:39:44.000Z | dist/DeployablePanel.jsx.js | homfen/fcui2 | 03b0eb892ff3209bd29044581220bbe0748485f2 | [
"MIT"
] | 22 | 2016-05-16T13:41:44.000Z | 2018-05-10T10:58:29.000Z | dist/DeployablePanel.jsx.js | homfen/fcui2 | 03b0eb892ff3209bd29044581220bbe0748485f2 | [
"MIT"
] | 22 | 2016-04-27T05:50:24.000Z | 2019-09-24T23:17:43.000Z | /**
* 折叠面板
* @author Brian Li
* @email lbxxlht@163.com
* @version 0.0.2.1
*/
define(function (require) {
var React = require('react');
var InputWidget = require('./mixins/InputWidget');
var cTools = require('./core/componentTools');
var language = require('./core/language').deployablePanel;
var util = require('./core/util');
var labels = {
expand: language.expand,
hide: language.hide
};
return React.createClass({
/**
* @properties
*
* @param {Import|Properties} src\core\componentTools.js skin className style disabled
* @param {Object} labels 话术配置
* @param {String} labels.expand 面板关闭后展开按钮的话术
* @param {String} labels.hide 面板展开后关闭按钮的话术
* @param {String} switchLocation 展开关闭按钮的位置,top或bottom
* @param {Import|Properties} src\mixins\InputWidget.js
* value onChange name validations customErrorTemplates valueTemplate
*/
/**
* @fire Import src\mixins\InputWidget.js XXX onChange
*/
// @override
mixins: [InputWidget],
// @override
getDefaultProps: function getDefaultProps() {
return {
// base
skin: '',
className: '',
style: {},
disabled: false,
// self
labels: labels,
switchLocation: 'top',
// mixin
valueTemplate: ''
};
},
// @override
getInitialState: function getInitialState() {
return {};
},
onChange: function onChange(e) {
e = { target: this.refs.container };
e.target.value = this.___getValue___() === 'expand' ? 'hide' : 'expand';
this.___dispatchChange___(e);
},
render: function render() {
var containerProp = cTools.containerBaseProps('deployablepanel', this);
var value = this.___getValue___();
var labels = util.extend({}, labels, this.props.labels);
return React.createElement(
'div',
containerProp,
this.props.switchLocation === 'top' ? React.createElement(
'div',
{ className: 'opt-bar' },
React.createElement(
'span',
{ onClick: this.onChange, className: 'opt-link' },
value === 'expand' ? labels.hide : labels.expand
),
React.createElement('span', { onClick: this.onChange,
className: 'fcui2-icon fcui2-icon-arrow-' + (value === 'expand' ? 'up' : 'down')
})
) : null,
React.createElement(
'div',
{ className: 'content-bar', style: { display: value === 'expand' ? 'block' : 'none' } },
this.props.children
),
this.props.switchLocation !== 'top' ? React.createElement(
'div',
{ className: 'opt-bar' },
React.createElement(
'span',
{ onClick: this.onChange, className: 'opt-link' },
value === 'expand' ? labels.hide : labels.expand
),
React.createElement('span', { onClick: this.onChange,
className: 'fcui2-icon fcui2-icon-arrow-' + (value === 'expand' ? 'up' : 'down')
})
) : null
);
}
});
}); | 37.474747 | 108 | 0.472776 |
436717f7d2d1e69bd1ad2aa7e22aac1fb4684bfa | 2,552 | js | JavaScript | lib/index.js | mini-peanut/hyAdmin2.0 | 7a7408c8c49538b8e69fd38fe6e36627bf76544f | [
"MIT"
] | 3 | 2019-02-02T15:43:39.000Z | 2021-06-03T06:26:44.000Z | lib/index.js | jiweixia233/hyAdmin2.0 | 7a7408c8c49538b8e69fd38fe6e36627bf76544f | [
"MIT"
] | null | null | null | lib/index.js | jiweixia233/hyAdmin2.0 | 7a7408c8c49538b8e69fd38fe6e36627bf76544f | [
"MIT"
] | 3 | 2018-03-29T08:25:23.000Z | 2018-04-11T12:44:23.000Z | import React from 'react';
import PropTypes from 'prop-types';
import dva , {connect as oldAppConnect} from 'dva';
import createHistory from 'history/createHashHistory';
import createLoading from 'dva-loading';
import {proxyModel, proxyStateForUI, proxyMapDispatchToProps} from "./proxy";
import {setCache, getCache} from "./cache";
export default function (opts = {}) {
// 1. init
const app = dva({
history: createHistory(),
});
// 2. Plugins
app.use(createLoading());
const oldAppRouter = app.router.bind(app);
const oldAppModel = app.model.bind(app);
// 3 重写model、connect和start
app.connect = connect;
app.model = model;
app.router = router;
return app;
function connect(getUIState, callbacks, mergeProps, options = {}) {
return UI => {
class ComponentWithPrefix extends React.Component {
getChildContext() {
let prefix = this.props.prefix;
return prefix ? {
prefix: {
...(this.context.prefix || {}),
...prefix
}
} : {};
}
render() {
let prefix = this.props.prefix || this.context.prefix;
// console.log(prefix);
const cachePath = [getUIState, UI, callbacks, JSON.stringify(prefix)];
let Component = getCache(cachePath);
if (Component) {
return <Component {...{...this.props, prefix}} />;
}
const mapStateToProps = (...args) => {
const [state, ...extArgs] = args;
return getUIState(proxyStateForUI(state, prefix), ...extArgs);
};
const mapDispatchToProps = proxyMapDispatchToProps(app, callbacks, prefix)
Component = oldAppConnect(mapStateToProps, mapDispatchToProps, mergeProps, options)(UI);
setCache(cachePath, Component);
return <Component {...{...this.props, prefix}} />;
}
}
ComponentWithPrefix.contextTypes = {
prefix: PropTypes.any
};
ComponentWithPrefix.childContextTypes = {
prefix: PropTypes.any
};
return ComponentWithPrefix;
};
}
function model(m) {
oldAppModel(proxyModel(m));
}
function router(callback) {
oldAppRouter(({app, ...extraProps}) => {
const injectModel = app.model.bind(app);
app.model = m => injectModel(proxyModel(m));
return callback({app, ...extraProps})
});
}
};
| 27.44086 | 100 | 0.566614 |
43690c8732754021ccc6fe9ead06c383c9e927a7 | 1,969 | js | JavaScript | src/ime.js | Aryailia/better-discord-furigana | e8a3820fe8d46bdccc910781f12eb1d6869c409f | [
"MIT"
] | 2 | 2021-06-12T02:25:47.000Z | 2021-06-12T19:31:39.000Z | src/ime.js | Aryailia/better-discord-furigana | e8a3820fe8d46bdccc910781f12eb1d6869c409f | [
"MIT"
] | null | null | null | src/ime.js | Aryailia/better-discord-furigana | e8a3820fe8d46bdccc910781f12eb1d6869c409f | [
"MIT"
] | null | null | null | var convert = require('./kanaConvert.js');
var kuromoji = require('kuromoji');
var KANJI_MATCH = /[\u3400-\u4DB5\u4E00-\u9FCB\uF900-\uFA6A]+/;
//var HIRA_KATA_HALFKATA_PUNCTUATION = /[\u30A0-\u30FF\u3041-\u3096]/;
// Key test examples
// - びしょ濡れーービショウヌレ
// - 属するーーーーゾクスル
var events = {
load: function () {},
unload: function () {},
start: function (state) {
new Promise(function (resolve, reject) {
console.log('furiganaIME', __dirname);
kuromoji.builder({dicPath: 'kuromoji/dic/' }).builder(function (err, tokenizer) {
resolve(tokenizer);
});
}).then(function (parser) {
$(document).on('keydown.furiganaIME', function (ev) {
console.log('working1');
var textInput, text;
// Textinput must start with 'furi:' and need to Ctrl+C to trigger conversion
if (ev.ctrlKey && ev.keyCode === 67) { // Ctrl + C
textInput = document.querySelector('.channel-textarea-inner textarea');
if (textInput.value.startsWith('furi:')) {
text = textInput.value.substr(5);
console.log('working2');
// Tokenize and build string form kuromoji output
var str = parser.then.tokenize(text).map(function (token) {
//var match = token.surface_form.match(KANJI_MATCH);
return(token.surface_form.match(KANJI_MATCH) != null
? convert.splitSideKanaAndJoinWithReading(
token.surface_form, token.reading, '[', ']')
//? token.surface_form + '(' + token.reading + ')'
: token.surface_form
);
}).join('');
console.log(str);
}
}
//console.log(ev.target, ev.keyCode, textInput.value);
});
}).catch(function (err) {
console.log('furiganaIME Error:', err);
});
},
stop: function (state) {
$(document).off('keypress.furiganaIME');
},
};
module.exports = events; | 35.160714 | 87 | 0.578466 |
436949d23bfb6bbaf1423fff3cf71dd2681a957f | 1,215 | js | JavaScript | Chapter 06/Code Samples/ch6_anonymous_nested_callbacks.js | mooyis/JavaScript-from-Beginner-to-Professional | c301da664bda83b97fc7661aef462751c0fb6259 | [
"MIT"
] | 3 | 2021-06-10T07:37:19.000Z | 2021-07-16T14:42:42.000Z | Chapter 06/Code Samples/ch6_anonymous_nested_callbacks.js | mooyis/JavaScript-from-Beginner-to-Professional | c301da664bda83b97fc7661aef462751c0fb6259 | [
"MIT"
] | null | null | null | Chapter 06/Code Samples/ch6_anonymous_nested_callbacks.js | mooyis/JavaScript-from-Beginner-to-Professional | c301da664bda83b97fc7661aef462751c0fb6259 | [
"MIT"
] | 3 | 2021-06-29T05:35:44.000Z | 2021-07-12T05:44:24.000Z | function doingStuffAnonymously() {
console.log("Not so secret though.");
}
let functionVariable = function () {
console.log("Not so secret though.");
};
functionVariable();
function doFlexibleStuff(executeStuff) {
executeStuff();
console.log("Inside doFlexibleStuffFunction.");
}
doFlexibleStuff(functionVariable);
let anotherFunctionVariable = function () {
console.log("Another anonymous function implementation.");
};
doFlexibleStuff(anotherFunctionVariable);
function doOuterFunctionStuff(nr) {
console.log("Outer function");
doInnerFunctionStuff(nr);
function doInnerFunctionStuff(x) {
console.log(x + 7);
console.log("I can access outer variables:", nr);
}
}
doOuterFunctionStuff(2);
function doOuterFunctionStuff(nr) {
doInnerFunctionStuff(nr);
function doInnerFunctionStuff(x) {
let z = 10;
}
console.log("Not accessible:", z);
}
doOuterFunctionStuff(2);
function doOuterFunctionStuff(nr) {
doInnerFunctionStuff(nr);
function doInnerFunctionStuff(x) {
let z = 10;
}
}
doInnerFunctionStuff(3);
let youGotThis = function () {
console.log("You're doing really well, keep coding!");
};
setTimeout(youGotThis, 1000);
setInterval(youGotThis, 1000);
| 20.25 | 60 | 0.729218 |
43698da2aeca92ea1ff97d147529f7074fd9bf64 | 7,017 | js | JavaScript | src/type/unit/physicalConstants.js | mcvladthegoat/mathjs | ab94ba059d7084b96930dfb147c9d32e62f21166 | [
"Apache-2.0"
] | 4 | 2019-11-29T11:07:29.000Z | 2021-09-12T18:19:08.000Z | src/type/unit/physicalConstants.js | grimalschi/mathjs | af37445940ac7c49e199d546eec18b76e1e53a12 | [
"Apache-2.0"
] | null | null | null | src/type/unit/physicalConstants.js | grimalschi/mathjs | af37445940ac7c49e199d546eec18b76e1e53a12 | [
"Apache-2.0"
] | null | null | null | 'use strict'
import { factory } from '../../utils/factory'
// Source: https://en.wikipedia.org/wiki/Physical_constant
// Universal constants
export const createSpeedOfLight = /* #__PURE__ */ unitFactory('speedOfLight', '299792458', 'm s^-1')
export const createGravitationConstant = /* #__PURE__ */ unitFactory('gravitationConstant', '6.6738480e-11', 'm^3 kg^-1 s^-2')
export const createPlanckConstant = /* #__PURE__ */ unitFactory('planckConstant', '6.626069311e-34', 'J s')
export const createReducedPlanckConstant = /* #__PURE__ */ unitFactory('reducedPlanckConstant', '1.05457172647e-34', 'J s')
// Electromagnetic constants
export const createMagneticConstant = /* #__PURE__ */ unitFactory('magneticConstant', '1.2566370614e-6', 'N A^-2')
export const createElectricConstant = /* #__PURE__ */ unitFactory('electricConstant', '8.854187817e-12', 'F m^-1')
export const createVacuumImpedance = /* #__PURE__ */ unitFactory('vacuumImpedance', '376.730313461', 'ohm')
export const createCoulomb = /* #__PURE__ */ unitFactory('coulomb', '8.9875517873681764e9', 'N m^2 C^-2')
export const createElementaryCharge = /* #__PURE__ */ unitFactory('elementaryCharge', '1.60217656535e-19', 'C')
export const createBohrMagneton = /* #__PURE__ */ unitFactory('bohrMagneton', '9.2740096820e-24', 'J T^-1')
export const createConductanceQuantum = /* #__PURE__ */ unitFactory('conductanceQuantum', '7.748091734625e-5', 'S')
export const createInverseConductanceQuantum = /* #__PURE__ */ unitFactory('inverseConductanceQuantum', '12906.403721742', 'ohm')
export const createMagneticFluxQuantum = /* #__PURE__ */ unitFactory('magneticFluxQuantum', '2.06783375846e-15', 'Wb')
export const createNuclearMagneton = /* #__PURE__ */ unitFactory('nuclearMagneton', '5.0507835311e-27', 'J T^-1')
export const createKlitzing = /* #__PURE__ */ unitFactory('klitzing', '25812.807443484', 'ohm')
// export const createJosephson = /* #__PURE__ */ unitFactory('josephson', '4.8359787011e-14 Hz V^-1') // TODO: support for Hz needed
// Atomic and nuclear constants
export const createBohrRadius = /* #__PURE__ */ unitFactory('bohrRadius', '5.291772109217e-11', 'm')
export const createClassicalElectronRadius = /* #__PURE__ */ unitFactory('classicalElectronRadius', '2.817940326727e-15', 'm')
export const createElectronMass = /* #__PURE__ */ unitFactory('electronMass', '9.1093829140e-31', 'kg')
export const createFermiCoupling = /* #__PURE__ */ unitFactory('fermiCoupling', '1.1663645e-5', 'GeV^-2')
export const createFineStructure = numberFactory('fineStructure', 7.297352569824e-3)
export const createHartreeEnergy = /* #__PURE__ */ unitFactory('hartreeEnergy', '4.3597443419e-18', 'J')
export const createProtonMass = /* #__PURE__ */ unitFactory('protonMass', '1.67262177774e-27', 'kg')
export const createDeuteronMass = /* #__PURE__ */ unitFactory('deuteronMass', '3.3435830926e-27', 'kg')
export const createNeutronMass = /* #__PURE__ */ unitFactory('neutronMass', '1.6749271613e-27', 'kg')
export const createQuantumOfCirculation = /* #__PURE__ */ unitFactory('quantumOfCirculation', '3.636947552024e-4', 'm^2 s^-1')
export const createRydberg = /* #__PURE__ */ unitFactory('rydberg', '10973731.56853955', 'm^-1')
export const createThomsonCrossSection = /* #__PURE__ */ unitFactory('thomsonCrossSection', '6.65245873413e-29', 'm^2')
export const createWeakMixingAngle = numberFactory('weakMixingAngle', 0.222321)
export const createEfimovFactor = numberFactory('efimovFactor', 22.7)
// Physico-chemical constants
export const createAtomicMass = /* #__PURE__ */ unitFactory('atomicMass', '1.66053892173e-27', 'kg')
export const createAvogadro = /* #__PURE__ */ unitFactory('avogadro', '6.0221412927e23', 'mol^-1')
export const createBoltzmann = /* #__PURE__ */ unitFactory('boltzmann', '1.380648813e-23', 'J K^-1')
export const createFaraday = /* #__PURE__ */ unitFactory('faraday', '96485.336521', 'C mol^-1')
export const createFirstRadiation = /* #__PURE__ */ unitFactory('firstRadiation', '3.7417715317e-16', 'W m^2')
// export const createSpectralRadiance = /* #__PURE__ */ unitFactory('spectralRadiance', '1.19104286953e-16', 'W m^2 sr^-1') // TODO spectralRadiance
export const createLoschmidt = /* #__PURE__ */ unitFactory('loschmidt', '2.686780524e25', 'm^-3')
export const createGasConstant = /* #__PURE__ */ unitFactory('gasConstant', '8.314462175', 'J K^-1 mol^-1')
export const createMolarPlanckConstant = /* #__PURE__ */ unitFactory('molarPlanckConstant', '3.990312717628e-10', 'J s mol^-1')
export const createMolarVolume = /* #__PURE__ */ unitFactory('molarVolume', '2.241396820e-10', 'm^3 mol^-1')
export const createSackurTetrode = numberFactory('sackurTetrode', -1.164870823)
export const createSecondRadiation = /* #__PURE__ */ unitFactory('secondRadiation', '1.438777013e-2', 'm K')
export const createStefanBoltzmann = /* #__PURE__ */ unitFactory('stefanBoltzmann', '5.67037321e-8', 'W m^-2 K^-4')
export const createWienDisplacement = /* #__PURE__ */ unitFactory('wienDisplacement', '2.897772126e-3', 'm K')
// Adopted values
export const createMolarMass = /* #__PURE__ */ unitFactory('molarMass', '1e-3', 'kg mol^-1')
export const createMolarMassC12 = /* #__PURE__ */ unitFactory('molarMassC12', '1.2e-2', 'kg mol^-1')
export const createGravity = /* #__PURE__ */ unitFactory('gravity', '9.80665', 'm s^-2')
// atm is defined in Unit.js
// Natural units
export const createPlanckLength = /* #__PURE__ */ unitFactory('planckLength', '1.61619997e-35', 'm')
export const createPlanckMass = /* #__PURE__ */ unitFactory('planckMass', '2.1765113e-8', 'kg')
export const createPlanckTime = /* #__PURE__ */ unitFactory('planckTime', '5.3910632e-44', 's')
export const createPlanckCharge = /* #__PURE__ */ unitFactory('planckCharge', '1.87554595641e-18', 'C')
export const createPlanckTemperature = /* #__PURE__ */ unitFactory('planckTemperature', '1.41683385e+32', 'K')
// helper function to create a factory function which creates a physical constant,
// a Unit with either a number value or a BigNumber value depending on the configuration
function unitFactory (name, valueStr, unitStr) {
const dependencies = ['config', 'Unit', 'BigNumber']
return factory(name, dependencies, ({ config, Unit, BigNumber }) => {
// Note that we can parse into number or BigNumber.
// We do not parse into Fractions as that doesn't make sense: we would lose precision of the values
// Therefore we dont use Unit.parse()
const value = config.number === 'BigNumber'
? new BigNumber(valueStr)
: parseFloat(valueStr)
const unit = new Unit(value, unitStr)
unit.fixPrefix = true
return unit
})
}
// helper function to create a factory function which creates a numeric constant,
// either a number or BigNumber depending on the configuration
function numberFactory (name, value) {
const dependencies = ['config', 'BigNumber']
return factory(name, dependencies, ({ config, BigNumber }) => {
return config.number === 'BigNumber'
? new BigNumber(value)
: value
})
}
| 68.794118 | 149 | 0.726521 |
4369a2c286d07edba8b40a1f0af25f2d375da912 | 5,456 | js | JavaScript | sc2env/xai_replay/ui/viz/js/test/chartDataTests/msxRankingTests.js | khlam/sc2env | af0d181dd78b09e6bedda7b0e9c98064adb05641 | [
"MIT"
] | 1 | 2017-11-01T20:09:32.000Z | 2017-11-01T20:09:32.000Z | sc2env/xai_replay/ui/viz/js/test/chartDataTests/msxRankingTests.js | khlam/sc2env | af0d181dd78b09e6bedda7b0e9c98064adb05641 | [
"MIT"
] | 103 | 2017-09-14T17:04:53.000Z | 2018-08-15T22:52:32.000Z | sc2env/xai_replay/ui/viz/js/test/chartDataTests/msxRankingTests.js | khlam/sc2env | af0d181dd78b09e6bedda7b0e9c98064adb05641 | [
"MIT"
] | 6 | 2018-01-31T00:05:14.000Z | 2020-01-29T07:01:29.000Z | function runMsxRankingTests (failureChecker, chartTesting) {
//rd.colors = ['#7293CB','#E1974C', '#84BA5B','#D35E60', '#9067A7', '#AB6857', '#CCC210', '#000044']
var fc = failureChecker;
if (chartTesting == "seeSaw") {
fc.setTestName("MsxRankingTests - seesaw");
var ch = getSeeSawChart();
} else if (chartTesting == "allPositives") {
fc.setTestName("MsxRankingTests - all Pos");
var ch = getAllPositivesChart();
} else {
fc.setTestName("MsxRankingTests - all Neg");
var ch = getAllNegativesChart();
}
ch = addUtilityFunctions(ch);
ch = addMsxToBars(ch);
if (chartTesting == "seeSaw") {
fc.setCase("seeSaw rank best action");
fc.assert(ch.actions[0].msxMaxValueAction, false, "msx Value Action 0");
fc.assert(ch.actions[1].msxMaxValueAction, false, "msx Value Action 1");
fc.assert(ch.actions[2].msxMaxValueAction, true, "msx Value Action 2");
fc.assert(ch.actions[3].msxMaxValueAction, false, "msx Value Action 3");
} else if (chartTesting == "allPositives") {
fc.setCase("allPositives rank best action");
fc.assert(ch.actions[0].msxMaxValueAction, false, "msx Value Action 0");
fc.assert(ch.actions[1].msxMaxValueAction, false, "msx Value Action 1");
fc.assert(ch.actions[2].msxMaxValueAction, false, "msx Value Action 2");
fc.assert(ch.actions[3].msxMaxValueAction, true, "msx Value Action 3");
} else if (chartTesting == "allNegatives") {
fc.setCase("allNegatives rank best action");
fc.assert(ch.actions[0].msxMaxValueAction, true, "msx Value Action 0");
fc.assert(ch.actions[1].msxMaxValueAction, false, "msx Value Action 1");
fc.assert(ch.actions[2].msxMaxValueAction, false, "msx Value Action 2");
fc.assert(ch.actions[3].msxMaxValueAction, false, "msx Value Action 3");
}
if (chartTesting == "seeSaw") {
fc.setCase("seeSaw rank important bars");
fc.assert(ch.actions[0].bars[0].msxImportantBar, true, "msx important Bar 0.0");
fc.assert(ch.actions[0].bars[1].msxImportantBar, false, "msx important Bar 0.1");
fc.assert(ch.actions[0].bars[2].msxImportantBar, true, "msx important Bar 0.2");
fc.assert(ch.actions[1].bars[0].msxImportantBar, false, "msx important Bar 1.0");
fc.assert(ch.actions[1].bars[1].msxImportantBar, false, "msx important Bar 1.1");
fc.assert(ch.actions[1].bars[2].msxImportantBar, true, "msx important Bar 1.2");
fc.assert(ch.actions[2].bars[0].msxImportantBar, false, "msx important Bar 2.0");
fc.assert(ch.actions[2].bars[1].msxImportantBar, false, "msx important Bar 2.1");
fc.assert(ch.actions[2].bars[2].msxImportantBar, false, "msx important Bar 2.2");
fc.assert(ch.actions[3].bars[0].msxImportantBar, false, "msx important Bar 3.0");
fc.assert(ch.actions[3].bars[1].msxImportantBar, false, "msx important Bar 3.1");
fc.assert(ch.actions[3].bars[2].msxImportantBar, true, "msx important Bar 3.2");
} else if (chartTesting == "allPositives") {
fc.setCase("allPositives rank important bars");
fc.assert(ch.actions[0].bars[0].msxImportantBar, false, "msx important Bar 0.0");
fc.assert(ch.actions[0].bars[1].msxImportantBar, false, "msx important Bar 0.1");
fc.assert(ch.actions[0].bars[2].msxImportantBar, true, "msx important Bar 0.2");
fc.assert(ch.actions[1].bars[0].msxImportantBar, false, "msx important Bar 1.0");
fc.assert(ch.actions[1].bars[1].msxImportantBar, true, "msx important Bar 1.1");
fc.assert(ch.actions[1].bars[2].msxImportantBar, false, "msx important Bar 1.2");
fc.assert(ch.actions[2].bars[0].msxImportantBar, true, "msx important Bar 2.0");
fc.assert(ch.actions[2].bars[1].msxImportantBar, false, "msx important Bar 2.1");
fc.assert(ch.actions[2].bars[2].msxImportantBar, false, "msx important Bar 2.2");
fc.assert(ch.actions[3].bars[0].msxImportantBar, false, "msx important Bar 3.0");
fc.assert(ch.actions[3].bars[1].msxImportantBar, false, "msx important Bar 3.1");
fc.assert(ch.actions[3].bars[2].msxImportantBar, false, "msx important Bar 3.2");
} else if (chartTesting == "allNegatives") {
fc.setCase("allNegatives rank importantBars");
fc.assert(ch.actions[0].bars[0].msxImportantBar, false, "msx important Bar 0.0");
fc.assert(ch.actions[0].bars[1].msxImportantBar, false, "msx important Bar 0.1");
fc.assert(ch.actions[0].bars[2].msxImportantBar, false, "msx important Bar 0.2");
fc.assert(ch.actions[1].bars[0].msxImportantBar, true, "msx important Bar 1.0");
fc.assert(ch.actions[1].bars[1].msxImportantBar, false, "msx important Bar 1.1");
fc.assert(ch.actions[1].bars[2].msxImportantBar, false, "msx important Bar 1.2");
fc.assert(ch.actions[2].bars[0].msxImportantBar, true, "msx important Bar 2.0");
fc.assert(ch.actions[2].bars[1].msxImportantBar, false, "msx important Bar 2.1");
fc.assert(ch.actions[2].bars[2].msxImportantBar, false, "msx important Bar 2.2");
fc.assert(ch.actions[3].bars[0].msxImportantBar, true, "msx important Bar 3.0");
fc.assert(ch.actions[3].bars[1].msxImportantBar, false, "msx important Bar 3.1");
fc.assert(ch.actions[3].bars[2].msxImportantBar, false, "msx important Bar 3.2");
}
} | 55.673469 | 107 | 0.653409 |
4369a5de5dc8883411556d66015098031814bc99 | 2,423 | js | JavaScript | flow-admin/src/main/resources/static/assets/index.dcfc23ed.js | hcxiaoliu/flow | 444a347e83e46708850f936cde89d279c5b376fb | [
"Apache-2.0"
] | null | null | null | flow-admin/src/main/resources/static/assets/index.dcfc23ed.js | hcxiaoliu/flow | 444a347e83e46708850f936cde89d279c5b376fb | [
"Apache-2.0"
] | null | null | null | flow-admin/src/main/resources/static/assets/index.dcfc23ed.js | hcxiaoliu/flow | 444a347e83e46708850f936cde89d279c5b376fb | [
"Apache-2.0"
] | null | null | null | import{k as e,l as t,b3 as o,c as s,U as r,W as i}from"./index.f36f9bca.js";import{k as n,cl as a,f as m,u as p,K as g,o as c,n as u,q as d,X as f,V as j}from"./vendor.9d9efc92.js";import{c as l}from"./createAsyncComponent.f4288151.js";import T from"./SessionTimeoutLogin.3b220422.js";import"./Login.84317544.js";import"./LoginForm.c48ba84f.js";/* empty css *//* empty css *//* empty css *//* empty css */import"./LoginFormTitle.199323a6.js";import"./ForgetPasswordForm.1950d24c.js";import"./CountdownInput.0ef22e66.js";import"./RegisterForm.bcfe7a1c.js";import"./StrengthMeter.b0b10a34.js";import"./MobileForm.90324db6.js";import"./QrCodeForm.f0750a72.js";import"./Qrcode.0eef62a6.js";import"./download.0867ab48.js";var b=n({name:"LayoutFeatures",components:{BackTop:a,LayoutLockPage:l((()=>e((()=>import("./index.ede118a4.js")),["/assets/index.ede118a4.js","/assets/LockPage.400278a6.js","/assets/LockPage.ee8eff52.css","/assets/vendor.9d9efc92.js","/assets/vendor.70495537.css","/assets/index.f36f9bca.js","/assets/index.69000eb3.css","/assets/lock.c5d44027.js","/assets/header.d801b988.js"]))),SettingDrawer:l((()=>e((()=>import("./index.e9037fef.js").then((function(e){return e.i}))),["/assets/index.e9037fef.js","/assets/index.6d85b653.css","/assets/useDrawer.bfdbfcc8.js","/assets/useDrawer.1b4eeea2.css","/assets/index.864ac48e.css","/assets/vendor.9d9efc92.js","/assets/vendor.70495537.css","/assets/index.f36f9bca.js","/assets/index.69000eb3.css","/assets/createAsyncComponent.f4288151.js","/assets/useFrameKeepAlive.fec8cb71.js"]))),SessionTimeoutLogin:T},setup(){const{getUseOpenBackTop:e,getShowSettingButton:n,getSettingButtonPosition:a,getFullContent:g}=t(),c=o(),{prefixCls:u}=s("setting-drawer-fearure"),{getShowHeader:d}=r(),f=m((()=>c.getSessionTimeout));return{getTarget:()=>document.body,getUseOpenBackTop:e,getIsFixedSettingDrawer:m((()=>{if(!p(n))return!1;const e=p(a);return e===i.AUTO?!p(d)||p(g):e===i.FIXED})),prefixCls:u,getIsSessionTimeout:f}}});b.render=function(e,t,o,s,r,i){const n=g("LayoutLockPage"),a=g("BackTop"),m=g("SettingDrawer"),p=g("SessionTimeoutLogin");return c(),u(j,null,[d(n),e.getUseOpenBackTop?(c(),u(a,{key:0,target:e.getTarget},null,8,["target"])):f("",!0),e.getIsFixedSettingDrawer?(c(),u(m,{key:1,class:e.prefixCls},null,8,["class"])):f("",!0),e.getIsSessionTimeout?(c(),u(p,{key:2})):f("",!0)],64)};export default b;
| 1,211.5 | 2,422 | 0.707388 |
436ae0855883285077a3069b4f016114619da32f | 1,411 | js | JavaScript | index.js | gordongecco/i18scanner | ba3c662a05f6780c9bcd3827d2a8339bf53b2892 | [
"MIT"
] | null | null | null | index.js | gordongecco/i18scanner | ba3c662a05f6780c9bcd3827d2a8339bf53b2892 | [
"MIT"
] | null | null | null | index.js | gordongecco/i18scanner | ba3c662a05f6780c9bcd3827d2a8339bf53b2892 | [
"MIT"
] | null | null | null | var fs = require("fs");
var Parser = require("i18next-scanner").Parser;
var customHandler = function (key, options) {
options.defaultValue = "_TRANSLATION_";
parser.set(key, options);
};
const options = {
lngs: ["en", "hu"],
func: {
list: ["i18next.t", "i18n.t", "t"],
extensions: [".js", ".jsx", ".tsx", "ts"],
},
};
var parser = new Parser(options);
var content = "";
// Parse Translation Function
// i18next.t('key');
content = fs.readFileSync("/Users/dani/PROGI/crai18/src/Content.tsx", "utf-8");
parser.parseFuncFromString(content, customHandler); // pass a custom handler
// .parseFuncFromString(content, { list: ["i18next.t"] }) // override `func.list`
// .parseFuncFromString(content, { list: ["t"] }, customHandler);
// .parseFuncFromString(content); // using default options and handlern
// Parse HTML Attribute
// <div data-i18n="key"></div>
// content = fs.readFileSync("/Users/dani/PROGI/crai18/src/Content.tsx", "utf-8");
// parser
// .parseAttrFromString(content, customHandler) // pass a custom handler
// .parseAttrFromString(content, { list: ["data-i18n"] }) // override `attr.list`
// .parseAttrFromString(content, { list: ["data-i18n"] }, customHandler)
// .parseAttrFromString(content); // using default options and handler
console.log(parser.get());
// console.log(parser.get({ sort: true }));
// console.log(parser.get("translation:key", { lng: "en" }));
| 36.179487 | 83 | 0.667612 |
436c13bbbf25add2d7322e509e5102280ceffbb2 | 1,185 | js | JavaScript | src/app/directives/setLang/setLang.js | VinayakHegde/slot-mixer-platform | 52577c1dfb3e5ba75bc1f1ecb1b195a81a4ccbd5 | [
"MIT"
] | null | null | null | src/app/directives/setLang/setLang.js | VinayakHegde/slot-mixer-platform | 52577c1dfb3e5ba75bc1f1ecb1b195a81a4ccbd5 | [
"MIT"
] | 5 | 2020-06-18T15:07:59.000Z | 2022-02-12T16:42:34.000Z | src/app/directives/setLang/setLang.js | VinayakHegde/slot-mixer-platform | 52577c1dfb3e5ba75bc1f1ecb1b195a81a4ccbd5 | [
"MIT"
] | null | null | null | /* Directive Name : set-lang
* When used with element, it changes the app language on tap/press/click.
*
* Usage:
* <button set-lang="en-gb">English</button>
*/
(function() {
'use strict';
angular.module('serviceWindow').directive('setLang', setLang);
setLang.$inject = ['localisationService', 'webSocketService', 'hammerService'];
function setLang(localisationService, webSocketService, hammerService) {
var directive = {
restrict: 'A',
link: directiveLink
};
return directive;
function directiveLink($scope, $element, $attrs) {
hammerService.addTap($element, function() {
// If the element is tapped, change the dictionary to the specified language.
// Only need to set the language if it is not already set.
if (localisationService.getDictionaryCulture() != $attrs.setLang) {
// Set the language.
localisationService.setLanguage($attrs.setLang, $attrs.informUser, $scope.setLang);
if ($scope.customer) {
$scope.customer.language = $attrs.setLang;
}
// Let the server know we have changed the language for the customer.
webSocketService.setCustomerLanguage($attrs.setLang);
}
});
}
}
})();
| 28.214286 | 88 | 0.688608 |
436c3ce743e4475551f8d22d8234f71c187e6087 | 296 | js | JavaScript | studio/schemas/squat.js | regulated/Strength-Sheets | 280dd52254720fde09e42f628160403d6be31887 | [
"MIT"
] | null | null | null | studio/schemas/squat.js | regulated/Strength-Sheets | 280dd52254720fde09e42f628160403d6be31887 | [
"MIT"
] | 2 | 2020-08-26T00:49:04.000Z | 2020-08-26T00:49:42.000Z | studio/schemas/squat.js | regulated/Strength-Sheets | 280dd52254720fde09e42f628160403d6be31887 | [
"MIT"
] | null | null | null | export default {
name: 'squat',
title: 'Squat',
type: 'document',
fields: [
{
name: 'max',
title: 'Max',
type: 'number'
}
<<<<<<< HEAD
],
initialValue: {
max: 100
}
}
=======
]
}
>>>>>>> 818eeacad40faa49ddbba35967a6ce689a954a04
| 14.095238 | 49 | 0.462838 |
436c7d446d31f062c10d9b96284bb1aa73891901 | 4,526 | js | JavaScript | src/data/cfg.jsdoc.js | HardstyleQuint/vesful-support | 5efb9782658dcd6a24a2fad1295c3800c3c25fd9 | [
"MIT"
] | null | null | null | src/data/cfg.jsdoc.js | HardstyleQuint/vesful-support | 5efb9782658dcd6a24a2fad1295c3800c3c25fd9 | [
"MIT"
] | null | null | null | src/data/cfg.jsdoc.js | HardstyleQuint/vesful-support | 5efb9782658dcd6a24a2fad1295c3800c3c25fd9 | [
"MIT"
] | null | null | null | /**
* @typedef {object} ModmailConfig
* @property {string} [token]
* @property {array} [mainServerId]
* @property {string} [inboxServerId]
* @property {string} [logChannelId]
* @property {array} [mainGuildId]
* @property {string} [mailGuildId]
* @property {string} [prefix="!"]
* @property {string} [snippetPrefix="!!"]
* @property {string} [snippetPrefixAnon="!!!"]
* @property {string} [status="Message me for help!"]
* @property {"playing"|"watching"|"listening"} [statusType="playing"]
* @property {string} [responseMessage="Thank you for your message! Our mod team will reply to you here as soon as possible."]
* @property {string} [closeMessage]
* @property {boolean} [allowUserClose=false]
* @property {string} [newThreadCategoryId]
* @property {string} [mentionRole="everyone"]
* @property {boolean} [pingOnBotMention=true]
* @property {string} [botMentionResponse]
* @property {array} [inboxServerPermission=["manageMessages"]]
* @property {boolean} [alwaysReply=false]
* @property {boolean} [alwaysReplyAnon=false]
* @property {boolean} [useNicknames=false]
* @property {boolean} [anonymizeChannelName=false]
* @property {boolean} [ignoreAccidentalThreads=true]
* @property {boolean} [threadTimestamps=false]
* @property {boolean} [allowMove=true]
* @property {boolean} [syncPermissionsOnMove=true]
* @property {boolean} [typingProxy=false]
* @property {boolean} [typingProxyReverse=false]
* @property {boolean} [mentionUserInThreadHeader=false]
* @property {boolean} [rolesInThreadHeader=true]
* @property {boolean} [allowStaffEdit=true]
* @property {boolean} [allowStaffDelete=true]
* @property {boolean} [allowBlock=true]
* @property {boolean} [allowSuspend=true]
* @property {boolean} [allowSnippets=true]
* @property {boolean} [enableGreeting=true]
* @property {string} [greetingMessage]
* @property {string} [greetingAttachment]
* @property {*} [serverGreetings={}]
* @property {*} [guildGreetings]
* @property {number} [requiredAccountAge] Required account age to message Modmail, in hours
* @property {string} [accountAgeDeniedMessage="Your Discord account is not old enough to contact modmail."]
* @property {number} [requiredTimeOnServer] Required time on server to message Modmail, in minutes
* @property {string} [timeOnServerDeniedMessage="You haven't been a member of the server for long enough to contact modmail."]
* @property {boolean} [relaySmallAttachmentsAsAttachments=false]
* @property {number} [smallAttachmentLimit=2097152] Max size of attachment to relay directly. Default is 2MB.
* @property {string} [attachmentStorage="original"]
* @property {string} [attachmentStorageChannelId]
* @property {*} [categoryAutomation={}]
* @property {boolean} [updateNotifications=true]
* @property {boolean} [updateNotificationsForBetaVersions=false]
* @property {array} [plugins=[]]
* @property {*} [commandAliases]
* @property {boolean} [reactOnSeen=false]
* @property {string} [reactOnSeenEmoji="📨"]
* @property {boolean} [createThreadOnMention=false]
* @property {boolean} [notifyOnMainServerLeave=true]
* @property {boolean} [notifyOnMainServerJoin=true]
* @property {boolean} [allowInlineSnippets=true]
* @property {string} [inlineSnippetStart="{{"]
* @property {string} [inlineSnippetEnd="}}"]
* @property {boolean} [errorOnUnknownInlineSnippet=true]
* @property {boolean} [allowChangingDisplayRole=true]
* @property {string} [fallbackRoleName=null]
* @property {boolean} [autoAlert=false]
* @property {string} [autoAlertDelay="2m"] Delay before auto-alert kicks in. Uses the same format as timed close; for example 1m30s for 1 minute and 30 seconds.
* @property {boolean} [pinThreadHeader=false]
* @property {boolean} [showResponseMessageInThreadChannel=true]
* @property {string} [logStorage="attachment"]
* @property {object} [logOptions]
* @property {string} logOptions.attachmentDirectory
* @property {*} [logOptions.allowAttachmentUrlFallback=false]
* @property {number} [port=8890]
* @property {string} [url]
* @property {boolean} [useGitForGitHubPlugins=false]
* @property {array} [extraIntents=[]]
* @property {*} [dbType="sqlite"]
* @property {object} [sqliteOptions]
* @property {string} sqliteOptions.filename
* @property {object} [mysqlOptions]
* @property {string} mysqlOptions.host
* @property {number} mysqlOptions.port
* @property {string} mysqlOptions.user
* @property {string} mysqlOptions.password
* @property {string} mysqlOptions.database
* @property {string} [mysqlOptions.timezone]
*/
| 49.736264 | 161 | 0.734865 |
436d1db130d10c9af26a1e691c67d7d1b90bf0e5 | 1,209 | js | JavaScript | lib/org/chromium/webidl/parsers/TokenSequence1.js | GoogleChromeLabs/webidl-diff | b3fb0e18adb50f199a0c0993a4cb55c1067496ed | [
"BSD-3-Clause"
] | 9 | 2017-12-22T10:56:52.000Z | 2021-07-06T01:16:23.000Z | lib/org/chromium/webidl/parsers/TokenSequence1.js | QPC-database/webidl-diff | b3fb0e18adb50f199a0c0993a4cb55c1067496ed | [
"BSD-3-Clause"
] | 10 | 2018-02-26T23:36:41.000Z | 2018-05-17T17:57:10.000Z | lib/org/chromium/webidl/parsers/TokenSequence1.js | QPC-database/webidl-diff | b3fb0e18adb50f199a0c0993a4cb55c1067496ed | [
"BSD-3-Clause"
] | 6 | 2018-02-26T21:56:30.000Z | 2021-10-08T17:28:31.000Z | // Copyright 2017 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
'use strict';
foam.CLASS({
package: 'org.chromium.webidl.parsers',
name: 'TokenSequence1',
extends: 'foam.parse.Sequence1',
implements: ['org.chromium.webidl.parsers.TokenizedParser'],
documentation: `A foam.parse.Sequence1, with each part separated by
"separator".`,
methods: [
// TODO: Write compile() for compiled parser support.
function parse(ps, obj) {
var ret;
var args = this.args;
var sep = this.separator;
var n = this.n;
for (var i = 0, p; p = args[i]; i++) {
if (!(ps = p.parse(ps, obj))) return undefined;
if (i === n) ret = ps.value;
if (i === args.length - 1) continue;
if (!(ps = sep.parse(ps, obj))) return undefined;
}
return ps.setValue(ret || '');
},
function toString() {
var args = this.args;
var strs = new Array(args.length);
for (var i = 0; i < args.length; i++) {
strs[i] = args[i].toString();
}
return 'tseq1(' + this.n + ', ' + strs.join(', ') + ')';
}
],
});
| 28.116279 | 73 | 0.574855 |
436e04597e19c44b58e4bdc66a9acda4f1b6e233 | 485 | js | JavaScript | public/test.js | andham97/cheat-js | c0fdf134c7dc9a74082511077251ae2b53dc4a93 | [
"MIT"
] | 1 | 2018-05-03T11:44:10.000Z | 2018-05-03T11:44:10.000Z | public/test.js | andham97/cheat-h2.js | c0fdf134c7dc9a74082511077251ae2b53dc4a93 | [
"MIT"
] | null | null | null | public/test.js | andham97/cheat-h2.js | c0fdf134c7dc9a74082511077251ae2b53dc4a93 | [
"MIT"
] | null | null | null | today = new Date();
BigDay = new Date("December 25, 2025");
msPerDay = 24 * 60 * 60 * 1000 ;
timeLeft = (BigDay.getTime() - today.getTime());
e_daysLeft = timeLeft / msPerDay;
daysLeft = Math.floor(e_daysLeft);
e_hrsLeft = (e_daysLeft - daysLeft)*24;
hrsLeft = Math.floor(e_hrsLeft);
minsLeft = Math.floor((e_hrsLeft - hrsLeft)*60);
document.write("<p>There are only<b>" + daysLeft + " days " + hrsLeft +" hours and " + minsLeft + " minutes left </b> Until December 25th 2025</p>");
| 37.307692 | 149 | 0.676289 |
437087aead1059ebf27d502938b91f2369b7b441 | 3,296 | js | JavaScript | react/features/notifications/reducer.js | varld/sessions-platform | 159bc9023c4dc5ce0d54517dbf2e2531eb675006 | [
"Apache-2.0"
] | null | null | null | react/features/notifications/reducer.js | varld/sessions-platform | 159bc9023c4dc5ce0d54517dbf2e2531eb675006 | [
"Apache-2.0"
] | null | null | null | react/features/notifications/reducer.js | varld/sessions-platform | 159bc9023c4dc5ce0d54517dbf2e2531eb675006 | [
"Apache-2.0"
] | null | null | null | // @flow
import { ReducerRegistry } from '../base/redux';
import {
CLEAR_NOTIFICATIONS,
HIDE_NOTIFICATION,
SET_NOTIFICATIONS_ENABLED,
SHOW_NOTIFICATION
} from './actionTypes';
import { NOTIFICATION_TYPE_PRIORITIES } from './constants';
/**
* The initial state of the feature notifications.
*
* @type {array}
*/
const DEFAULT_STATE = {
enabled: false,
notifications: []
};
/**
* Reduces redux actions which affect the display of notifications.
*
* @param {Object} state - The current redux state.
* @param {Object} action - The redux action to reduce.
* @returns {Object} The next redux state which is the result of reducing the
* specified {@code action}.
*/
ReducerRegistry.register('features/notifications',
(state = DEFAULT_STATE, action) => {
switch (action.type) {
case CLEAR_NOTIFICATIONS:
return {
...state,
notifications: []
};
case HIDE_NOTIFICATION:
return {
...state,
notifications: state.notifications.filter(
notification => notification.uid !== action.uid)
};
case SET_NOTIFICATIONS_ENABLED:
return {
...state,
enabled: action.enabled
};
case SHOW_NOTIFICATION:
return {
...state,
notifications:
_insertNotificationByPriority(state.notifications, {
component: action.component,
props: action.props,
timeout: action.timeout,
uid: action.uid
})
};
}
return state;
});
/**
* Creates a new notification queue with the passed in notification placed at
* the end of other notifications with higher or the same priority.
*
* @param {Object[]} notifications - The queue of notifications to be displayed.
* @param {Object} notification - The new notification to add to the queue.
* @private
* @returns {Object[]} A new array with an updated order of the notification
* queue.
*/
function _insertNotificationByPriority(notifications, notification) {
const newNotificationPriority
= NOTIFICATION_TYPE_PRIORITIES[notification.props.appearance] || 0;
// Default to putting the new notification at the end of the queue.
let insertAtLocation = notifications.length;
// Find where to insert the new notification based on priority. Do not
// insert at the front of the queue so that the user can finish acting on
// any notification currently being read.
for (let i = 1; i < notifications.length; i++) {
const queuedNotification = notifications[i];
const queuedNotificationPriority
= NOTIFICATION_TYPE_PRIORITIES[queuedNotification.props.appearance]
|| 0;
if (queuedNotificationPriority < newNotificationPriority) {
insertAtLocation = i;
break;
}
}
// Create a copy to avoid mutation and insert the notification.
const copyOfNotifications = notifications.slice();
copyOfNotifications.splice(insertAtLocation, 0, notification);
return copyOfNotifications;
}
| 30.803738 | 80 | 0.618629 |
4370d8993ea6e83fa924ea2e20a5dadf15cf8659 | 536 | js | JavaScript | udmif/api/jest.config.js | johnrandolph/udmi | 5e9de32fc71de8d006cda2eba4d3372eaf24c7c0 | [
"Apache-2.0"
] | 1 | 2022-02-24T22:57:37.000Z | 2022-02-24T22:57:37.000Z | udmif/api/jest.config.js | johnrandolph/udmi | 5e9de32fc71de8d006cda2eba4d3372eaf24c7c0 | [
"Apache-2.0"
] | 5 | 2022-02-24T21:32:24.000Z | 2022-03-23T15:52:25.000Z | udmif/api/jest.config.js | johnrandolph/udmi | 5e9de32fc71de8d006cda2eba4d3372eaf24c7c0 | [
"Apache-2.0"
] | null | null | null | module.exports = {
roots: ['<rootDir>/src'],
transform: {
'^.+\\.tsx?$': 'ts-jest',
},
reporters: [
"default",
],
collectCoverage: true,
coveragePathIgnorePatterns: ["/node_modules/", "/src/__tests__/"],
coverageReporters: [
"text",
"cobertura",
"lcov"
],
preset: "@shelf/jest-mongodb",
// testEnvironment: "node",
testRegex: '(/__tests__/spec.ts|(\\.|/)(test|spec))\\.tsx?$',
moduleFileExtensions: ['ts', 'tsx', 'js', 'jsx', 'json', 'node'],
watchPathIgnorePatterns: ['globalConfig'],
}
| 24.363636 | 68 | 0.585821 |
43716b8888d79c96fe2230f86a053ed3301210a8 | 403 | js | JavaScript | pages/_app.js | ruie/linkanim | ce036cd10302cc6937c2ed193859e495ff435601 | [
"MIT"
] | null | null | null | pages/_app.js | ruie/linkanim | ce036cd10302cc6937c2ed193859e495ff435601 | [
"MIT"
] | 26 | 2022-01-26T11:24:04.000Z | 2022-03-31T11:20:55.000Z | pages/_app.js | JackP96/next-starter-tailwind | 86f1d2ececb0e34c276e81500b943a42d9912897 | [
"MIT"
] | null | null | null | import "../css/index.css";
import Head from "next/head";
import Layout from "@components/layout";
function MyApp({ Component, pageProps }) {
return (
<Layout>
<Head>
<title>Next.js Starter Tailwind</title>
<meta
name="Description"
content="A Next.js starter styled using Tailwind CSS."
/>
</Head>
<Component {...pageProps} />
</Layout>
);
}
export default MyApp;
| 18.318182 | 59 | 0.637717 |
4371750fa947488466b4a476681a0cb64382dffd | 307 | js | JavaScript | source/events.js | zmwangx/GitHubCheckBoxes | b2541fec5b1453f0e7e5fbdb0e4bf7ea8ad53abf | [
"WTFPL"
] | null | null | null | source/events.js | zmwangx/GitHubCheckBoxes | b2541fec5b1453f0e7e5fbdb0e4bf7ea8ad53abf | [
"WTFPL"
] | null | null | null | source/events.js | zmwangx/GitHubCheckBoxes | b2541fec5b1453f0e7e5fbdb0e4bf7ea8ad53abf | [
"WTFPL"
] | null | null | null | // Show page action only for a GitHub page
chrome.tabs.onUpdated.addListener(function (tabId, changeInfo, tab) {
if (tab.url.match(/^https?:\/\/github.com/)) {
chrome.pageAction.show(tabId)
}
})
chrome.pageAction.onClicked.addListener(function (tab) {
chrome.tabs.sendMessage(tab.id, 'check')
})
| 27.909091 | 69 | 0.710098 |
4371a326f97b5f14976e0486246e66af905c0866 | 1,056 | js | JavaScript | src/screens/Home/index.js | banggibima/react_fitnesspro | 778a6fcdfc10dc63b9382ecfe6f5e969f5bd5882 | [
"MIT"
] | null | null | null | src/screens/Home/index.js | banggibima/react_fitnesspro | 778a6fcdfc10dc63b9382ecfe6f5e969f5bd5882 | [
"MIT"
] | null | null | null | src/screens/Home/index.js | banggibima/react_fitnesspro | 778a6fcdfc10dc63b9382ecfe6f5e969f5bd5882 | [
"MIT"
] | null | null | null | import React, { useRef } from "react";
// import styles from "./Home.module.sass";
import Hero from "./Hero";
import Clients from "../../components/Clients";
import Steps from "./Steps";
import Intro from "../../components/Intro";
import Book from "./Book";
import ValueProps from "../../components/ValueProps";
import About from "./About";
import Team from "./Team";
import Review from "../../components/Review";
import Quality from "./Quality";
import Advantages from "../../components/Advantages";
import Workouts from "../../components/Workouts";
import Offer from "../../components/Offer";
const Home = () => {
const scrollToRef = useRef(null);
return (
<>
<Hero scrollToRef={scrollToRef} />
<Clients />
<Steps scrollToRef={scrollToRef} />
<Intro />
<Book />
<ValueProps className="section" />
<About />
<Team />
<Review className="section" />
<Quality />
<Advantages />
<Workouts />
<Offer className="section-border-top" />
</>
);
};
export default Home;
| 26.4 | 53 | 0.620265 |
4371ee765c795990d9e229124144246c567300dd | 193 | js | JavaScript | src/Bridge/Symfony/Bundle/Resources/public/init-redoc-ui.js | jbdelhommeau/core | dd497cf52beb7ead669e469226b25ad5e8587d8f | [
"MIT"
] | 1,861 | 2016-03-16T13:37:01.000Z | 2022-03-28T20:58:23.000Z | src/Bridge/Symfony/Bundle/Resources/public/init-redoc-ui.js | jbdelhommeau/core | dd497cf52beb7ead669e469226b25ad5e8587d8f | [
"MIT"
] | 3,669 | 2016-03-05T15:06:47.000Z | 2022-03-31T09:18:13.000Z | src/Bridge/Symfony/Bundle/Resources/public/init-redoc-ui.js | jbdelhommeau/core | dd497cf52beb7ead669e469226b25ad5e8587d8f | [
"MIT"
] | 876 | 2016-03-05T18:57:36.000Z | 2022-03-29T13:55:20.000Z | 'use strict';
window.onload = () => {
const data = JSON.parse(document.getElementById('swagger-data').innerText);
Redoc.init(data.spec, {}, document.getElementById('swagger-ui'));
};
| 24.125 | 79 | 0.668394 |
43722484b803847a0ab26ddbd26ca6174dd637c9 | 1,100 | js | JavaScript | pub-examples/iWmo_Jw_Eb_Splits/data/view_30311_data.js | onnohaldar/istd-ld-voorbeelden | f2d949db39193ac1b52c897a6dd0ce5ce1a94c7e | [
"MIT"
] | null | null | null | pub-examples/iWmo_Jw_Eb_Splits/data/view_30311_data.js | onnohaldar/istd-ld-voorbeelden | f2d949db39193ac1b52c897a6dd0ce5ce1a94c7e | [
"MIT"
] | null | null | null | pub-examples/iWmo_Jw_Eb_Splits/data/view_30311_data.js | onnohaldar/istd-ld-voorbeelden | f2d949db39193ac1b52c897a6dd0ce5ce1a94c7e | [
"MIT"
] | null | null | null | var viewData = {"id":30311,"isExpandedObject":false};
var objectRelations = {
"30311" : [{"via": "geassocieerd met","to": ["30305"]}]
};
var objectData = {
"30311" : {
"id":30311,
"typeIconPath":"data/icons/ArchiMate/AllView.png",
"data" : [
{
"lang":"nl",
"name":"Condities",
"type":"Totaalview classic",
"categories":[]
}
]
}
,
"30305" : {
"id":30305,
"typeIconPath":"data/icons/ArchiMate/AllExtendedView.png",
"data" : [
{
"lang":"nl",
"name":"Regels",
"type":"Totaalview uitgebreid",
"categories":[]
}
]
}
};
var viewReferences = {"38403":30281,"38411":30273,"38407":30270,"38409":30305,"38423":30293,"38425":30308,"38417":30311,"38413":30302,"38421":30278,"38415":30284,"38427":30299,"38419":30296};
var objectReferences = {
"38403" : 30281
,
"38405" : 38405
,
"38411" : 30273
,
"38407" : 30270
,
"38409" : 30305
,
"38423" : 30293
,
"38425" : 30308
,
"38417" : 30311
,
"38413" : 30302
,
"38421" : 30278
,
"38415" : 30284
,
"38427" : 30299
,
"38419" : 30296
,
"38453" : 38453
};
var viewpointsData =
[
];
var vp_legends =
{
};
| 16.176471 | 192 | 0.587273 |
43723e89b71a80153409e65e45b90638b21d844d | 983 | js | JavaScript | Extension/js/background/global.min.js | Acidburn0zzz/Trimgle | 98febbec75ffcd1f005bb4a15ef33a5eeb661236 | [
"MIT"
] | 18 | 2017-11-18T10:22:30.000Z | 2021-07-07T10:23:16.000Z | Extension/js/background/global.min.js | Acidburn0zzz/Trimgle | 98febbec75ffcd1f005bb4a15ef33a5eeb661236 | [
"MIT"
] | 1 | 2019-03-08T10:09:12.000Z | 2019-03-08T10:50:04.000Z | Extension/js/background/global.min.js | Acidburn0zzz/Trimgle | 98febbec75ffcd1f005bb4a15ef33a5eeb661236 | [
"MIT"
] | 6 | 2018-03-09T05:20:08.000Z | 2019-04-16T08:51:30.000Z | if(!$)throw new Error("jQuery required");var urlNews="https://gist.githubusercontent.com/LeonardoCiaccio/6bbf8c946eb978e5057d910896a5f62b/raw/",_noticeNews=function(){var e=$.Trimgle.settings();if(!e)return alert(chrome.i18n.getMessage("problem_inact")+" ( 100 )"),!1;if(e.notification===!0){chrome.notifications.create("newelements",{type:"basic",iconUrl:"img/icon.48.png",title:chrome.i18n.getMessage("title_not_news"),message:chrome.i18n.getMessage("mex_not_news")},function(){});var i=new Audio("audio/noty1.mp3");i.volume=.2,i.play()}},_noticeReviews=function(){var e=$.Trimgle.settings();if(!e)return alert(chrome.i18n.getMessage("problem_inact")+" ( 100 )"),!1;if(e.notification===!0){chrome.notifications.create("newreviews",{type:"basic",iconUrl:"img/icon.48.png",title:chrome.i18n.getMessage("title_not_review"),message:chrome.i18n.getMessage("mex_not_review")},function(){});var i=new Audio("audio/noty2.mp3");i.volume=.2,i.play()}};
//# sourceMappingURL=global.min.js.map | 491.5 | 944 | 0.752798 |
43733cfee7289dee646f3a44329c58c19aafe7e4 | 2,525 | js | JavaScript | grid-packages/ag-grid-docs/documentation/doc-pages/row-spanning/examples/row-spanning-complex/data.js | StefanFehrenbach/ag-grid | 2bf9f48163dd9a578e200ad4f5accf08c44ff109 | [
"MIT"
] | null | null | null | grid-packages/ag-grid-docs/documentation/doc-pages/row-spanning/examples/row-spanning-complex/data.js | StefanFehrenbach/ag-grid | 2bf9f48163dd9a578e200ad4f5accf08c44ff109 | [
"MIT"
] | null | null | null | grid-packages/ag-grid-docs/documentation/doc-pages/row-spanning/examples/row-spanning-complex/data.js | StefanFehrenbach/ag-grid | 2bf9f48163dd9a578e200ad4f5accf08c44ff109 | [
"MIT"
] | null | null | null | function getData() {
var rowData = [
{
localTime: '5:00am',
show: { name: 'Wake Up Dublin', presenter: 'Andrew Connell' },
a: 0.231,
b: 0.523,
c: 0.423,
d: 0.527,
e: 0.342,
},
{ localTime: '5:15am', a: 0.423, b: 0.452, c: 0.523, d: 0.543, e: 0.452 },
{ localTime: '5:30am', a: 0.537, b: 0.246, c: 0.426, d: 0.421, e: 0.523 },
{ localTime: '5:45am', a: 0.893, b: 0.083, c: 0.532, d: 0.983, e: 0.543 },
{
localTime: '6:00am',
show: { name: 'Pure Back In The Day', presenter: 'Kevin Flanagan' },
a: 0.231,
b: 0.523,
c: 0.423,
d: 0.527,
e: 0.342,
},
{ localTime: '6:15am', a: 0.423, b: 0.452, c: 0.523, d: 0.543, e: 0.452 },
{ localTime: '6:30am', a: 0.537, b: 0.246, c: 0.426, d: 0.421, e: 0.523 },
{ localTime: '6:45am', a: 0.893, b: 0.083, c: 0.532, d: 0.983, e: 0.543 },
{
localTime: '7:00am',
show: { name: 'The Queens Breakfast', presenter: 'Tony Smith' },
a: 0.231,
b: 0.523,
c: 0.423,
d: 0.527,
e: 0.342,
},
{ localTime: '7:15am', a: 0.423, b: 0.452, c: 0.523, d: 0.543, e: 0.452 },
{ localTime: '7:30am', a: 0.537, b: 0.246, c: 0.426, d: 0.421, e: 0.523 },
{ localTime: '7:45am', a: 0.893, b: 0.083, c: 0.532, d: 0.983, e: 0.543 },
{
localTime: '8:00am',
show: { name: 'Cosmetic Surgery', presenter: 'Niall Crosby' },
a: 0.231,
b: 0.523,
c: 0.423,
d: 0.527,
e: 0.342,
},
{ localTime: '8:15am', a: 0.423, b: 0.452, c: 0.523, d: 0.543, e: 0.452 },
{ localTime: '8:30am', a: 0.537, b: 0.246, c: 0.426, d: 0.421, e: 0.523 },
{ localTime: '8:45am', a: 0.893, b: 0.083, c: 0.532, d: 0.983, e: 0.543 },
{
localTime: '8:00am',
show: { name: 'Brickfield Park Sessions', presenter: 'Bricker McGee' },
a: 0.231,
b: 0.523,
c: 0.423,
d: 0.527,
e: 0.342,
},
{ localTime: '8:15am', a: 0.423, b: 0.452, c: 0.523, d: 0.543, e: 0.452 },
{ localTime: '8:30am', a: 0.537, b: 0.246, c: 0.426, d: 0.421, e: 0.523 },
{ localTime: '8:45am', a: 0.893, b: 0.083, c: 0.532, d: 0.983, e: 0.543 },
]
return rowData;
} | 38.846154 | 83 | 0.413465 |
4373e818f24f95c5a3f9c44b7a94ce2b60bfa25f | 2,026 | js | JavaScript | app/pages/Masters/Country/CountryService.js | Akhiiii/Ofbiz | 78396d8432a39f2ddae2563a42f95f443715529e | [
"MIT"
] | 1 | 2019-03-13T00:15:04.000Z | 2019-03-13T00:15:04.000Z | app/pages/Masters/Country/CountryService.js | Akhiiii/Ofbiz | 78396d8432a39f2ddae2563a42f95f443715529e | [
"MIT"
] | null | null | null | app/pages/Masters/Country/CountryService.js | Akhiiii/Ofbiz | 78396d8432a39f2ddae2563a42f95f443715529e | [
"MIT"
] | null | null | null | import axios from 'axios';
import { addPaginationURLParams } from '../../../common/Utils/common';
import { baseURL } from '../../../common/rest_urls';
import { NAMESPACE } from './CountryConsts';
const pageURL = `${baseURL}/${NAMESPACE}`;
const saveURL = `${pageURL}/save`;
const deleteURL = `${pageURL}/delete`;
const deleteAllURL = `${pageURL}/deleteall`;
const blockURL = `${pageURL}/block`;
const blockAllURL = `${pageURL}/blockall`;
const unblockURL = `${pageURL}/unblock`;
const unblockAllURL = `${pageURL}/unblockall`;
const activateURL = `${pageURL}/activate`;
const activateAllURL = `${pageURL}/activateall`;
const deactivateURL = `${pageURL}/deactivate`;
const deactivateAllURL = `${pageURL}/deactivateall`;
const listURL = `${pageURL}/list`;
const byIdURL = `${pageURL}/id`;
const existsURL = `${pageURL}/isexists`;
export const serviceSave = values => axios.post(`${saveURL}`, values);
export const serviceDelete = id => axios.delete(`${deleteURL}?id=${id}`);
export const serviceDeleteAll = ids =>
axios.delete(`${deleteAllURL}?ids=${ids}`);
export const serviceBlock = id => axios.get(`${blockURL}?id=${id}`);
export const serviceBlockAll = ids => axios.get(`${blockAllURL}?ids=${ids}`);
export const serviceUnblock = id => axios.get(`${unblockURL}?id=${id}`);
export const serviceUnblockAll = ids =>
axios.get(`${unblockAllURL}?ids=${ids}`);
export const serviceActivate = id => axios.get(`${activateURL}?id=${id}`);
export const serviceActivateAll = ids =>
axios.get(`${activateAllURL}?ids=${ids}`);
export const serviceDeactivate = id => axios.get(`${deactivateURL}?id=${id}`);
export const serviceDeactivateAll = ids =>
axios.get(`${deactivateAllURL}?ids=${ids}`);
export const serviceList = criteria => {
const listURLPagination = addPaginationURLParams(`${listURL}`, criteria);
return axios.post(`${listURLPagination}`, criteria);
};
export const serviceById = id => axios.get(`${byIdURL}?id=${id}`);
export const serviceExists = name => axios.get(`${existsURL}?name=${name}`);
| 35.54386 | 78 | 0.69151 |
43741d133dad4e8bcf3176344c15c845481fcd1d | 2,195 | js | JavaScript | lib/operator/wallet.js | TheDoctor0/Motus | d5198501420b4933fbe81cacb13de3df87eb1c47 | [
"MIT"
] | 1 | 2018-12-20T15:20:15.000Z | 2018-12-20T15:20:15.000Z | lib/operator/wallet.js | TheDoctor0/Motus | d5198501420b4933fbe81cacb13de3df87eb1c47 | [
"MIT"
] | 27 | 2019-05-24T11:50:26.000Z | 2020-08-10T23:10:21.000Z | lib/operator/wallet.js | TheDoctor0/Motus | d5198501420b4933fbe81cacb13de3df87eb1c47 | [
"MIT"
] | null | null | null | const R = require('ramda');
const CryptoUtil = require('../util/cryptoUtil');
const CryptoEdDSAUtil = require('../util/cryptoEdDSAUtil');
class Wallet {
constructor() {
this.id = null;
this.passwordHash = null;
this.secret = null;
this.keyPairs = [];
}
generateAddress() {
if (this.secret === null) {
this.generateSecret();
}
let lastKeyPair = R.last(this.keyPairs);
let seed = (lastKeyPair === null ? this.secret : CryptoEdDSAUtil.generateSecret(R.propOr(null, 'secretKey', lastKeyPair)));
let keyPairRaw = CryptoEdDSAUtil.generateKeyPairFromSecret(seed);
let newKeyPair = {
index: this.keyPairs.length + 1,
secretKey: CryptoEdDSAUtil.toHex(keyPairRaw.getSecret()),
publicKey: CryptoEdDSAUtil.toHex(keyPairRaw.getPublic())
};
this.keyPairs.push(newKeyPair);
return newKeyPair.publicKey;
}
generateSecret() {
this.secret = CryptoEdDSAUtil.generateSecret(this.passwordHash);
return this.secret;
}
getAddressByIndex(index) {
return R.propOr(null, 'publicKey', R.find(R.propEq('index', index), this.keyPairs));
}
getAddressByPublicKey(publicKey) {
return R.propOr(null, 'publicKey', R.find(R.propEq('publicKey', publicKey), this.keyPairs));
}
getSecretKeyByAddress(address) {
return R.propOr(null, 'secretKey', R.find(R.propEq('publicKey', address), this.keyPairs));
}
getAddresses() {
return R.map(R.prop('publicKey'), this.keyPairs);
}
static fromPassword(password) {
let wallet = new Wallet();
wallet.id = CryptoUtil.randomId();
wallet.passwordHash = CryptoUtil.hash(password);
return wallet;
}
static fromHash(passwordHash) {
let wallet = new Wallet();
wallet.id = CryptoUtil.randomId();
wallet.passwordHash = passwordHash;
return wallet;
}
static fromJson(data) {
let wallet = new Wallet();
R.forEachObjIndexed((value, key) => { wallet[key] = value; }, data);
return wallet;
}
}
module.exports = Wallet; | 27.098765 | 132 | 0.611845 |
43747fec6d6b56c343ea15d0ee0aff7ab9e3108d | 96 | js | JavaScript | cte/demo-greet/bin/index.js | GokselKUCUKSAHIN/project-voltron | 042f791093a415208661d9e68d3d1ff5e2ccd680 | [
"MIT"
] | null | null | null | cte/demo-greet/bin/index.js | GokselKUCUKSAHIN/project-voltron | 042f791093a415208661d9e68d3d1ff5e2ccd680 | [
"MIT"
] | null | null | null | cte/demo-greet/bin/index.js | GokselKUCUKSAHIN/project-voltron | 042f791093a415208661d9e68d3d1ff5e2ccd680 | [
"MIT"
] | null | null | null | #!/usr/bin/env node
const greet = require('../lib/my-greet').greet;
console.log(greet("Jelly")); | 32 | 47 | 0.677083 |
4374d2bfc1afc2de006aef7b0c4a681cec1aab69 | 2,397 | js | JavaScript | fitnesse/resources/jest/Tooltip.test.js | oleveau/fitnesse-bootstrap-plus-theme | 8be15f31c1a0f85e8ad5b0ccb5514af168063b41 | [
"Apache-2.0"
] | null | null | null | fitnesse/resources/jest/Tooltip.test.js | oleveau/fitnesse-bootstrap-plus-theme | 8be15f31c1a0f85e8ad5b0ccb5514af168063b41 | [
"Apache-2.0"
] | null | null | null | fitnesse/resources/jest/Tooltip.test.js | oleveau/fitnesse-bootstrap-plus-theme | 8be15f31c1a0f85e8ad5b0ccb5514af168063b41 | [
"Apache-2.0"
] | null | null | null | jest.mock('jquery');
beforeEach(() => jest.resetModules());
//checks if inputted CSV format data comes out correctly
it('Check if links work correctly', () => {
const jsfile = require('../bootstrap-plus/js/bootstrap-plus');
const neededHTML = '<div id="tooltip-div"><p id="tooltip-text"></p></div>';
const expectedResult = 'A';
document.body.innerHTML = neededHTML;
jsfile.placeToolTip('this is a <a>Link</a>this is a <a>Link</a>');
const receivedResult = document.getElementById('tooltip-text').getElementsByTagName('a')[0].tagName;
expect(receivedResult).toMatch(expectedResult);
});
it('Check if other elements is not as element but as text', () => {
const jsfile = require('../bootstrap-plus/js/bootstrap-plus');
const neededHTML = '<div id="tooltip-div"><p id="tooltip-text"></p></div>';
const expectedResult = 'this is a <div>div</div>';
document.body.innerHTML = neededHTML;
jsfile.placeToolTip('this is a <div>div</div>');
const receivedResult = document.getElementById('tooltip-text').innerText;
const receivedResult2 = document.getElementById('tooltip-text').getElementsByTagName('div')[0];
expect(receivedResult).toMatch(expectedResult);
expect(receivedResult2).toBe(undefined);
});
it('Check if there is a script tag, tooltip will not be displayed as html', () => {
const jsfile = require('../bootstrap-plus/js/bootstrap-plus');
const neededHTML = '<div id="tooltip-div"><p id="tooltip-text"></p></div>';
const expectedResult = 'this is a <a>Link</a>this is a <a>Link</a><script>';
document.body.innerHTML = neededHTML;
jsfile.placeToolTip('this is a <a>Link</a>this is a <a>Link</a><script>');
const receivedResult = document.getElementById('tooltip-text').innerText;
const receivedResult2 = document.getElementById('tooltip-text').getElementsByTagName('a')[0];
expect(receivedResult).toMatch(expectedResult);
expect(receivedResult2).toBe(undefined);
});
it('Check if null', () => {
const jsfile = require('../bootstrap-plus/js/bootstrap-plus');
const neededHTML = '<div id="tooltip-div"><p id="tooltip-text"></p></div>';
const expectedResult = '';
document.body.innerHTML = neededHTML;
jsfile.placeToolTip('');
const receivedResult = document.getElementById('tooltip-text').innerText;
expect(receivedResult).toMatch(expectedResult);
});
| 38.66129 | 104 | 0.687109 |
4374f6f768487e266dbe9546cc78d627821464c6 | 332 | js | JavaScript | src/reducers/index.js | mcgingras/exquisite-corpse | 518275a8d853c4b78a8e059fa2401434d06d7d99 | [
"MIT"
] | null | null | null | src/reducers/index.js | mcgingras/exquisite-corpse | 518275a8d853c4b78a8e059fa2401434d06d7d99 | [
"MIT"
] | 6 | 2021-03-09T21:17:43.000Z | 2022-02-26T19:16:40.000Z | src/reducers/index.js | mcgingras/exquisite-corpse | 518275a8d853c4b78a8e059fa2401434d06d7d99 | [
"MIT"
] | null | null | null | import { combineReducers } from 'redux'
import { firebaseReducer } from 'react-redux-firebase';
import { firestoreReducer } from 'redux-firestore';
import { gameState } from './gameReducer';
const rootReducer = combineReducers({
firebase: firebaseReducer,
firestore: firestoreReducer,
gameState
})
export default rootReducer | 27.666667 | 55 | 0.768072 |
43750f6cc503c90ad33594f29bdb16180395f554 | 976 | js | JavaScript | src/optimize/loaders.js | pwnartist/underoot | 3352f60107f55921ad4761fa1f77d67a0315e6ad | [
"Apache-2.0"
] | 546 | 2015-09-14T17:51:46.000Z | 2021-11-02T00:48:01.000Z | src/optimize/loaders.js | pwnartist/underoot | 3352f60107f55921ad4761fa1f77d67a0315e6ad | [
"Apache-2.0"
] | 102 | 2015-09-28T14:14:32.000Z | 2020-07-21T21:23:20.000Z | src/optimize/loaders.js | pwnartist/underoot | 3352f60107f55921ad4761fa1f77d67a0315e6ad | [
"Apache-2.0"
] | 144 | 2015-09-13T16:41:41.000Z | 2020-06-26T20:32:33.000Z | import { parse as parseUrl, format as formatUrl } from 'url';
class Loader {
constructor({ name, query } = {}) {
if (!name) {
throw new Error('Loaders must define a name');
}
this.name = name;
this.query = query || {};
}
static fromUrl(url) {
const parsed = parseUrl(url, true);
return new Loader({
name: parsed.pathname,
query: parsed.query
});
}
toString() {
return formatUrl({
pathname: this.name,
query: this.query
});
}
setQueryParam(name, value) {
this.query[name] = value;
return this;
}
}
function parseLoader(spec) {
if (typeof spec === 'string') {
return Loader.fromUrl(spec);
}
return new Loader(spec);
}
export const makeLoaderString = (loaders) => {
return loaders.map(parseLoader).map(l => l.toString()).join('!');
};
export const setLoaderQueryParam = (loader, name, value) => {
return parseLoader(loader).setQueryParam(name, value).toString();
};
| 19.918367 | 67 | 0.610656 |
437634d739212e5ac749aba6775a0560b1bd4a8f | 8,202 | js | JavaScript | app/utils/tests/getAudioAsyncCall.test.js | faithcomesbyhearing/dbp-reader | ad146dace5abbaa0ab8173ce425096adf38fa73d | [
"MIT"
] | 7 | 2019-02-07T17:53:28.000Z | 2021-08-30T19:31:04.000Z | app/utils/tests/getAudioAsyncCall.test.js | faithcomesbyhearing/dbp-reader | ad146dace5abbaa0ab8173ce425096adf38fa73d | [
"MIT"
] | 11 | 2020-04-05T17:05:42.000Z | 2022-02-12T15:15:27.000Z | app/utils/tests/getAudioAsyncCall.test.js | faithcomesbyhearing/dbp-reader | ad146dace5abbaa0ab8173ce425096adf38fa73d | [
"MIT"
] | 5 | 2019-01-17T18:58:52.000Z | 2021-08-30T19:31:07.000Z | import getAudioAsyncCall from '../getAudioAsyncCall';
import {
engesv,
ntpotp,
seawbt,
filesets3,
filesets4,
filesets5,
filesets6,
filesets7,
filesets8,
} from '../testUtils/filesetsForAudioCall';
const types = {
drama: 'audio_drama',
plain: 'audio',
ntDrama: 'N2DA',
otDrama: 'O2DA',
ntPlain: 'N1DA',
otPlain: 'O1DA',
ntPartialDrama: 'P2DA',
otPartialDrama: 'P2DA',
ntPartialPlain: 'P1DA',
otPartialPlain: 'P1DA',
};
describe('Get audio async call utility function test', () => {
it('should return expected audio object with valid parameters', async () => {
const result = await getAudioAsyncCall(engesv, 'MAT', 1, types.drama);
expect(result).toHaveProperty('type', 'loadaudio');
expect(result).toHaveProperty('audioPaths');
expect(Array.isArray(result.audioPaths)).toEqual(true);
expect(result.audioPaths.length).toBeTruthy();
expect(result.audioPaths[0].includes(types.ntDrama)).toBeTruthy();
});
it('should return expected audio object with valid parameters', async () => {
const result = await getAudioAsyncCall(engesv, 'MAT', 1, types.plain);
expect(result).toHaveProperty('type', 'loadaudio');
expect(result).toHaveProperty('audioPaths');
expect(Array.isArray(result.audioPaths)).toEqual(true);
expect(result.audioPaths.length).toBeTruthy();
expect(result.audioPaths[0].includes(types.ntPlain)).toBeTruthy();
});
it('should return expected audio object with valid parameters', async () => {
const result = await getAudioAsyncCall(engesv, 'GEN', 1, types.plain);
expect(result).toHaveProperty('type', 'loadaudio');
expect(result).toHaveProperty('audioPaths');
expect(Array.isArray(result.audioPaths)).toEqual(true);
expect(result.audioPaths.length).toBeTruthy();
expect(result.audioPaths[0].includes(types.otPlain)).toBeTruthy();
});
it('should return expected audio object with valid parameters', async () => {
const result = await getAudioAsyncCall(engesv, 'GEN', 1, types.drama);
expect(result).toHaveProperty('type', 'loadaudio');
expect(result).toHaveProperty('audioPaths');
expect(Array.isArray(result.audioPaths)).toEqual(true);
expect(result.audioPaths.length).toBeTruthy();
expect(result.audioPaths[0].includes(types.otDrama)).toBeTruthy();
});
it('should return expected audio object with valid parameters', async () => {
const result = await getAudioAsyncCall(engesv, 'GEN', 1);
expect(result).toHaveProperty('type', 'loadaudio');
expect(result).toHaveProperty('audioPaths');
expect(Array.isArray(result.audioPaths)).toEqual(true);
expect(result.audioPaths.length).toBeTruthy();
expect(result.audioPaths[0].includes(types.otDrama)).toBeTruthy();
});
it('should return expected audio object with valid parameters', async () => {
const result = await getAudioAsyncCall(engesv, 'MAT', 1);
expect(result).toHaveProperty('type', 'loadaudio');
expect(result).toHaveProperty('audioPaths');
expect(Array.isArray(result.audioPaths)).toEqual(true);
expect(result.audioPaths.length).toBeTruthy();
expect(result.audioPaths[0].includes(types.ntDrama)).toBeTruthy();
});
it('should return expected audio object with valid parameters', async () => {
const result = await getAudioAsyncCall(ntpotp, 'MRK', 1, types.drama);
expect(result).toHaveProperty('type', 'loadaudio');
expect(result).toHaveProperty('audioPaths');
expect(Array.isArray(result.audioPaths)).toEqual(true);
expect(result.audioPaths.length).toBeTruthy();
});
it('should return expected audio object with valid parameters', async () => {
const result = await getAudioAsyncCall(ntpotp, 'GEN', 1, types.plain);
expect(result).toHaveProperty('type', 'loadaudio');
expect(result).toHaveProperty('audioPaths');
expect(Array.isArray(result.audioPaths)).toEqual(true);
expect(result.audioPaths.length).toBeTruthy();
});
it('should return expected audio object with valid parameters', async () => {
const result = await getAudioAsyncCall(ntpotp, 'GEN', 1, types.drama);
expect(result).toHaveProperty('type', 'loadaudio');
expect(result).toHaveProperty('audioPaths');
expect(Array.isArray(result.audioPaths)).toEqual(true);
expect(result.audioPaths.length).toBeTruthy();
});
it('should return expected audio object with valid parameters', async () => {
const result = await getAudioAsyncCall(ntpotp, 'MAT', 1, types.plain);
expect(result).toHaveProperty('type', 'loadaudio');
expect(result).toHaveProperty('audioPaths');
expect(Array.isArray(result.audioPaths)).toEqual(true);
expect(result.audioPaths.length).toBeTruthy();
});
it('should return expected audio object with valid parameters', async () => {
const result = await getAudioAsyncCall(seawbt, 'GEN', 1, types.drama);
expect(result).toHaveProperty('type', 'loadaudio');
expect(result).toHaveProperty('audioPaths');
expect(Array.isArray(result.audioPaths)).toEqual(true);
expect(result.audioPaths.length).toBeTruthy();
});
it('should return expected audio object with valid parameters', async () => {
const result = await getAudioAsyncCall(seawbt, 'ACT', 1, types.plain);
expect(result).toHaveProperty('type', 'loadaudio');
expect(result).toHaveProperty('audioPaths');
expect(Array.isArray(result.audioPaths)).toEqual(true);
expect(result.audioPaths.length).toBeTruthy();
});
it('should return expected audio object with valid parameters', async () => {
const result = await getAudioAsyncCall(filesets3, 'GEN', 1, types.drama);
expect(result).toHaveProperty('type', 'loadaudio');
expect(result).toHaveProperty('audioPaths');
expect(Array.isArray(result.audioPaths)).toEqual(true);
expect(result.audioPaths.length).toBeTruthy();
});
it('should return expected audio object with valid parameters', async () => {
const result = await getAudioAsyncCall(filesets4, 'MAT', 1, types.drama);
expect(result).toHaveProperty('type', 'loadaudio');
expect(result).toHaveProperty('audioPaths');
expect(Array.isArray(result.audioPaths)).toEqual(true);
expect(result.audioPaths.length).toBeTruthy();
});
it('should return expected audio object with valid parameters', async () => {
const result = await getAudioAsyncCall(filesets5, 'GEN', 1, types.drama);
expect(result).toHaveProperty('type', 'loadaudio');
expect(result).toHaveProperty('audioPaths');
expect(Array.isArray(result.audioPaths)).toEqual(true);
expect(result.audioPaths.length).toBeTruthy();
});
it('should return expected audio object with valid parameters', async () => {
const result = await getAudioAsyncCall(filesets6, 'MAT', 1, types.drama);
expect(result).toHaveProperty('type', 'loadaudio');
expect(result).toHaveProperty('audioPaths');
expect(Array.isArray(result.audioPaths)).toEqual(true);
expect(result.audioPaths.length).toBeTruthy();
});
it('should return expected audio object with valid parameters', async () => {
const result = await getAudioAsyncCall(filesets7, 'MAT', 1, types.drama);
expect(result).toHaveProperty('type', 'loadaudio');
expect(result).toHaveProperty('audioPaths');
expect(Array.isArray(result.audioPaths)).toEqual(true);
expect(result.audioPaths.length).toBeTruthy();
});
it('should return expected audio object with valid parameters', async () => {
const result = await getAudioAsyncCall(filesets8, 'GEN', 1, types.drama);
expect(result).toHaveProperty('type', 'loadaudio');
expect(result).toHaveProperty('audioPaths');
expect(Array.isArray(result.audioPaths)).toEqual(true);
expect(result.audioPaths.length).toBeTruthy();
});
it('should return expected audio object with valid parameters', async () => {
const result = await getAudioAsyncCall(
[{ id: 'ENGESVN2DA', size: 'C', type: types.drama }],
'GEN',
1,
types.drama,
);
expect(result).toHaveProperty('type', 'loadaudio');
expect(result).toHaveProperty('audioPaths');
expect(Array.isArray(result.audioPaths)).toEqual(true);
expect(result.audioPaths.length).toBeTruthy();
});
});
| 42.71875 | 79 | 0.705194 |
43769077cbfbcff3fe990827ce90f9a9258a089d | 20,555 | js | JavaScript | dist/metascraper-1.1.0/metascraper-1.1.0.min.js | metascrape/metascrape | b6e7df3dc2ef3e6f7271a571c79bfed2bdfa0c9d | [
"MIT"
] | 2 | 2018-05-06T08:05:37.000Z | 2019-03-20T06:29:43.000Z | dist/metascraper-1.1.0/metascraper-1.1.0.min.js | metascrape/metascrape | b6e7df3dc2ef3e6f7271a571c79bfed2bdfa0c9d | [
"MIT"
] | null | null | null | dist/metascraper-1.1.0/metascraper-1.1.0.min.js | metascrape/metascrape | b6e7df3dc2ef3e6f7271a571c79bfed2bdfa0c9d | [
"MIT"
] | 2 | 2018-06-11T06:20:12.000Z | 2019-03-20T06:29:46.000Z | /*!
* Metascraper JavaScript Library v1.1.0
* https://metascraper.com/
*
* Copyright Metascraper
* Released under the MIT license
* https://en.wikipedia.org/wiki/MIT_License
*
* Date: 2019-11-11T11:11Z
*/
var meta={projectName:"Metascraper",version:"1.1.0",modes:{developer:0,warning:5,error:9},options:{webApiPrefix:"http://localhost:54702/api/",attrName:"data-value",attrMemberName:"data-member",attrArrayName:"data-array",attrTextName:"data-text",attrHrefName:"data-href",attrClickName:"data-click",attrTypeName:"data-type",attrClassName:"data-class",attrScrapeName:"data-scrape",attrKeyName:"data-key",indexName:"{{*index}}",tokenName:"Token",scrape:!0,mode:5},loadTypes:Object.freeze({Replace:0,BeforeBeginAppend:1,AfterBeginAppend:2,BeforeEndAppend:3,AfterEndAppend:4}),storeTypes:Object.freeze({ExpiryNoExtend:1,ExpiryExtend:2,OneTimeRead:3,Forever:4,Session:5}),dataTypes:Object.freeze({date:"date",time:"time",datetime:"datetime",month:"month",month1:"month1",month3:"month3",monthNum:"monthNum",monthNumPad:"monthNumPad",day:"day",day1:"day1",day2:"day2",day3:"day3",dayNum:"dayNum",dayNumPad:"dayNumPad",year:"year",year2:"year2",string:"string",number:"number",json:"json"}),encodeTypes:Object.freeze({url:"url",urlParameter:"urlParameter",base64:"base64",utf16:"utf16"}),send:function(e){var t=meta.options.scrape;void 0!==e.scrape&&(t=e.scrape);var a=t?this.scrape(!0):{};e.data&&this.extend(a,e.data);var r={contentType:"application/json",dataType:"json",data:a};this.extend(r,e),-1===r.url.indexOf("://")&&(r.url=this.options.webApiPrefix+r.url),this.tokenize(r),this.ajax(r)},receive:function(e){var r=e.success,n={contentType:"application/json",dataType:"json"};this.extend(n,e),n.success=function(e,t,a){meta.bind(e,n.container),r&&r(e,t,a)};var t=n.url.indexOf("://");(-1===t||7<t)&&(n.url=this.options.webApiPrefix+n.url),this.tokenize(n),this.ajax(n)},get:function(e){var t={method:"GET"};this.extend(t,e),this.receive(t)},post:function(e){var t={method:"POST"};this.extend(t,e),this.send(t)},put:function(e){var t={method:"PUT"};this.extend(t,e),this.send(t)},del:function(e){this.log("meta.del","**DEPRACATION WARNING** meta.del should be replaced with meta.delete",meta.modes.warning),this.delete(e)},delete:function(e){var t={method:"DELETE"};this.extend(t,e),this.send(t)},create:function(e){this.post(e)},read:function(e){this.get(e)},update:function(e){this.put(e)},save:function(e){if(this.isNullOrUndefined(e.pk)||0===e.pk.length)throw arguments.callee.toString()+" - required parameter [pk] not found";e.data=this.scrape(),e.scrape=!1,e.data[e.pk]&&"0"!==e.data[e.pk]?meta.update(e):meta.create(e)},authorize:function(e){var t=meta.isNullOrUndefined(this.token());return t&&e&&e.url&&(window.location.href=e.url),!t},token:function(){return window.localStorage.getItem(meta.options.tokenName)},tokenize:function(e){var t=meta.token();if(!this.isNullOrUndefined(t)){var a={Authorization:"Bearer "+t};this.isNullOrUndefined(e.headers)&&(e.headers={}),this.extend(e.headers,a)}},login:function(e){var r=e.success,t={url:"Auth/Login"};this.extend(t,e),t.success=function(e,t,a){window.localStorage.setItem(meta.options.tokenName,e[meta.options.tokenName]),r&&r(e,t,a)},this.post(t)},logout:function(e){window.localStorage.removeItem(meta.options.tokenName),e&&e.url&&(-1===e.url.indexOf("://")&&(e.url=this.options.webApiPrefix+e.url),window.location.href=e.url+"?r="+encodeURIComponent(window.location.href))},getValue:function(e){if(e instanceof HTMLInputElement)return"checkbox"===e.type?e.checked:e.value;if(e instanceof HTMLSelectElement||e instanceof HTMLTextAreaElement){if(e.multiple){for(var t=[],a=e.selectedOptions,r=0;r<a.length;r++)t.push(a[r].value);return t}return e.value}return e&&e.innerHTML?e.innerHTML:void 0},scrape:function(){for(var e={},t=meta.options.attrName,a=this.selectAll("["+t+"]"),r=0;r<a.length;r++)if(!(a[r]instanceof HTMLTableElement||a[r]instanceof HTMLUListElement)){if(a[r].hasAttribute(meta.options.attrScrapeName))if(!1===JSON.parse(a[r].getAttribute(meta.options.attrScrapeName)))continue;e[a[r].getAttribute(t)]=meta.getValue(a[r])}return e},formatValue:function(e,t){try{if(e.hasAttribute(meta.options.attrTypeName)){var a=e.getAttribute(meta.options.attrTypeName);if(a!==meta.dataTypes.string)if(a===meta.dataTypes.number)t=new Number(t);else if(a===meta.dataTypes.date||a===meta.dataTypes.time||a===meta.dataTypes.datetime||a===meta.dataTypes.month||a===meta.dataTypes.month1||a===meta.dataTypes.month3||a===meta.dataTypes.monthNum||a===meta.dataTypes.monthNumPad||a===meta.dataTypes.day||a===meta.dataTypes.day1||a===meta.dataTypes.day2||a===meta.dataTypes.day3||a===meta.dataTypes.dayNum||a===meta.dataTypes.dayNumPad||a===meta.dataTypes.year||a===meta.dataTypes.year2){if(t=new Date(t),a===meta.dataTypes.date)t=t.toLocaleDateString();else if(a===meta.dataTypes.time)t=t.toLocaleTimeString();else if(a===meta.dataTypes.datetime)t=t.toLocaleString();else if(a===meta.dataTypes.month){var r=["January","February","March","April","May","June","July","August","September","October","November","December"];t=r[t.getMonth()]}else if(a===meta.dataTypes.month1){t=r[t.getMonth()]}else if(a===meta.dataTypes.month3){t=r[t.getMonth()]}else if(a===meta.dataTypes.monthNum)t=t.getMonth()+1;else if(a===meta.dataTypes.monthNumPad){var n=t.getMonth()+1;t=n<10?"0"+n.toString():n.toString()}else if(a===meta.dataTypes.day){t=["Sunday","Monday","Tuesday","Wednesday","Thursday","Friday","Saturday"][t.getDay()]}else if(a===meta.dataTypes.day1){t=["S","M","T","W","T","F","S"][t.getDay()]}else if(a===meta.dataTypes.day2){t=["Su","Mo","Tu","We","Th","Fr","Sa"][t.getDay()]}else if(a===meta.dataTypes.day3){t=["Sun","Mon","Tue","Wed","Thu","Fri","Sat"][t.getDay()]}else if(a===meta.dataTypes.dayNum)t=t.getDate();else if(a===meta.dataTypes.dayNumPad){var o=t.getDate();t=o<10?"0"+o.toString():o.toString()}else if(a===meta.dataTypes.year)t=t.getFullYear();else if(a===meta.dataTypes.year2){var i=t.getFullYear();if(-10<i&&i<10)t=i<0?"-0"+(-1*i).toString():"0"+i.toString();else if(i<100&&-100<i)t=i;else{var s=i.toString();s=i.substr(s.length-2,2),i<0&&(s="-"+s),t=parseInt(s)}}}else a===meta.dataTypes.json&&(t=JSON.stringify(t))}}catch(e){}return t},setValue:function(e,t){t=meta.formatValue(e,t),e instanceof HTMLSelectElement?e.value=t:e instanceof HTMLInputElement?"checkbox"===e.type?e.checked=t:e.value=t:e.innerHTML=t},paint:function(e,t){t=t||document;for(var a=meta.options.attrName,r=this.selectAll("["+a+"]",t),n=0;n<r.length;n++)if(!r[n].hasAttribute(meta.options.attrArrayName)||r[n].hasAttribute(meta.options.attrTextName)){var o=null;if(r[n].hasAttribute(meta.options.attrMemberName)){var i=r[n].getAttribute(meta.options.attrMemberName);i&&e[i]&&(o=e[i][r[n].getAttribute(a)])}else o=e[r[n].getAttribute(a)];meta.isNullOrUndefined(o)?e[i].hasOwnProperty(r[n].getAttribute(a))||meta.log("metascraper::paint","unable to find data-value ["+r[n].getAttribute(a)+"]",meta.modes.warning):meta.setValue(r[n],o)}},fill:function(a,r){function e(e){var t=e.replace(meta.options.indexName,h+1);return 0<o.length&&(t=t.replace("{{*"+meta.options.attrName+"}}",r[h][o])),-1!==t.indexOf("{{*"+meta.options.attrKeyName+"}}")&&(t=t.replace("{{*"+meta.options.attrKeyName+"}}",r[h][a.getAttribute(meta.options.attrKeyName)])),t}var t,n,o=a.getAttribute(meta.options.attrName);if(a instanceof HTMLSelectElement){if(this.isNullOrUndefined(o)||!a.hasAttribute(meta.options.attrTextName))return;for(var i=a.getAttribute(meta.options.attrTextName),s=a.getAttribute(meta.options.attrClassName),d=0;d<r.length;d++){var l=document.createElement("option");s&&0<s.length&&l.classList.add(s),l.value=r[d][o],l.text=meta.formatValue(a,r[d][i]),a.add(l,null)}}else if(a instanceof HTMLTableElement){var u=a.tHead;if(this.isNullOrUndefined(u)||this.isNullOrUndefined(u.rows)||0===u.rows.length)return;var m=u.rows[0].cells;if(this.isNullOrUndefined(m)||0===m.length)return;for(var c=meta.attr(u.rows[0],meta.options.attrHrefName),p=meta.attr(u.rows[0],meta.options.attrClickName),f=meta.attr(u.rows[0],meta.options.attrClassName),h=0;h<r.length;h++){var y=a.tBodies[0];meta.isNullOrUndefined(y)&&(y=a.appendChild(document.createElement("tbody")));var g=y.insertRow(-1);if(c&&0<c.length&&p&&0<p.length)throw"ERROR reported by "+meta.projectName+". Cannot apply "+meta.options.attrHrefName+" and "+meta.options.attrClickName+" to a tr element.";if(c&&0<c.length){var T=0<o.length?e(c):c;g.setAttribute("onclick","location.href = '"+T+"'")}if(p&&0<p.length){var N=0<o.length?e(p):p;g.setAttribute("onclick",N)}f&&0<f.length&&g.classList.add(f);for(var b=0;b<m.length;b++){var v=this.elem("td",null,g);if(m[b].hasAttribute(meta.options.attrTextName)){var A=meta.attr(m[b],meta.options.attrHrefName),w=meta.attr(m[b],meta.options.attrClickName),S=m[b].getAttribute(meta.options.attrTextName),x=meta.attr(m[b],meta.options.attrClassName);if(x&&0<x.length&&v.classList.add(x),void 0!==r[h][S]){var O=meta.formatValue(m[b],r[h][S]);A&&0<A.length?(t=document.createElement("a"),n=document.createTextNode(O),t.appendChild(n),w&&0<w.length&&t.setAttribute("onclick",e(w)),t.href=e(A),v.innerHTML=t.outerHTML):(v.innerHTML=O,w&&0<w.length&&v.setAttribute("onclick",e(w)))}}}}}else if(a instanceof HTMLUListElement){var E=meta.attr(a,meta.options.attrTextName);if(!E)return;for(var L=meta.attr(a,meta.options.attrHrefName),M=meta.attr(a,meta.options.attrClickName),k=meta.attr(a,meta.options.attrClassName),C=0;C<r.length;C++){var H=document.createElement("li");k&&0<k.length&&H.classList.add(k);var U=meta.formatValue(a,r[C][E]);L&&0<L.length?(t=document.createElement("a"),n=document.createTextNode(U),t.appendChild(n),M&&0<M.length&&t.setAttribute("onclick",e(M)),t.href=e(L),H.appendChild(t)):(H.appendChild(document.createTextNode(U)),M&&0<M.length&&H.setAttribute("onclick",e(M))),r[C][o]&&H.setAttribute("id",r[C][o]),a.appendChild(H)}}},populate:function(e,t){t=t||document;for(var a=meta.options.attrArrayName,r=this.selectAll("["+a+"]",t),n=0;n<r.length;n++){var o=e[r[n].getAttribute(a)]?e[r[n].getAttribute(a)]:e;meta.fill(r[n],o)}},bind:function(e,t){t=t||document,meta.populate(e,t),meta.paint(e,t)},load:function(e){var r=e.success,n=e.elem,o={method:"GET",url:e.url};this.extend(o,e),o.success=function(e,t,a){o.loadType===meta.loadTypes.BeforeBeginAppend?n.outerHTML=e+n.outerHTML:o.loadType===meta.loadTypes.AfterBeginAppend?n.innerHTML=e+n.innerHTML:o.loadType===meta.loadTypes.BeforeEndAppend?n.innerHTML=n.innerHTML+e:o.loadType===meta.loadTypes.AfterEndAppend?n.innerHTML=n.outerHTML+e:n.innerHTML=e,r&&r(e,t,a)},this.ajax(o)},loadHeader:function(e){var t={elem:document.body,loadType:meta.loadTypes.AfterBeginAppend};this.extend(t,e),this.load(t)},loadFooter:function(e){var t={elem:document.body,loadType:meta.loadTypes.BeforeEndAppend};this.extend(t,e),this.load(t)},loadScript:function(e){meta.isNullOrUndefined(e.url)&&meta.log("metascraper::loadScript","unable to find required attribute [url]",meta.modes.error);var n=e.success,t={method:"GET"};meta.extend(t,e),t.success=function(e,t,a){var r=document.createElement("script");r.textContent=e,document.head.appendChild(r),n&&n(e,t,a)},meta.ajax(t)},loadLinkFile:function(e){meta.isNullOrUndefined(e.rel)&&meta.log("metascraper::loadLinkFile","unable to find required attribute [rel]",meta.modes.error),meta.isNullOrUndefined(e.type)&&meta.log("metascraper::loadLinkFile","unable to find required attribute [type]",meta.modes.error),meta.isNullOrUndefined(e.url)&&meta.log("metascraper::loadLinkFile","unable to find required attribute [url]",meta.modes.error);var t=document.createElement("link");t.readyState?t.onreadystatechange=function(){"loaded"!==t.readyState&&"complete"!==t.readyState||(t.onreadystatechange=null,e.success&&e.success())}:t.onload=function(){e.success&&e.success()},meta.extend(t,e),t.href=e.url,document.getElementsByTagName("head")[0].appendChild(t)},loadStyleSheet:function(e){var t={rel:"stylesheet",type:"text/css"};meta.extend(t,e),meta.loadLinkFile(t)},data:{},store_set:function(e,t,a,r){a=a||meta.storeTypes.Forever,r=r||720;var n=this.toString(t),o=new Date,i={value:n,type:a,expiry:r,created:o.getTime(),lastread:o.getTime()},s=a===meta.storeTypes.Session?window.sessionStorage:window.localStorage,d=JSON.stringify(i);s.setItem(e,d)},store_get:function(t){var e=window.localStorage,a=e.getItem(t);if(this.isNullOrUndefined(a)&&(a=(e=window.sessionStorage).getItem(t)),this.isNullOrUndefined(a))return null;try{var r,n,o=JSON.parse(a);if(o.type===meta.storeTypes.Session)return o.value;if(o.type===meta.storeTypes.Forever)return o.value;if(o.type===meta.storeTypes.OneTimeRead){var i=o.value;return e.setItem(t,null),i}if(o.type===meta.storeTypes.ExpiryNoExtend){if((r=new Date).setTime(o.created),r.setMinutes(r.getMinutes()+o.expiry),(n=new Date).getTime()<=r.getTime())return o.value}else if(o.type===meta.storeTypes.ExpiryExtend&&((r=new Date).setTime(o.lastread),r.setMinutes(r.getMinutes()+o.expiry),(n=new Date).getTime()<=r.getTime()))return o.lastread=n.getTime(),e.setItem(t,JSON.stringify(o)),o.value}catch(e){meta.log("metascraper::store_get","error getting value: ["+t+"], error: ["+meta.toString(e)+"], returning null",meta.modes.warning)}return null},getUrlParam:function(e,t){t=t||window.location.href,e=e.replace(/[\[\]]/g,"\\$&");var a=new RegExp("[?&]"+e+"(=([^&#]*)|&|#|$)").exec(t);return a?a[2]?decodeURIComponent(a[2].replace(/\+/g," ")):"":null},getElemAttr:function(e,t){return this.log("meta.getElemAttr","**DEPRACATION WARNING** meta.getElemAttr should be replaced with meta.attr",meta.modes.warning),this.attr(e,t)},attr:function(e,t,a){return!meta.isNullOrUndefined(a)&&e&&e.hasAttribute&&e.setAttribute&&e.setAttribute(t,a),e&&e.hasAttribute&&e.getAttribute&&e.hasAttribute(t)?e.getAttribute(t):""},elem:function(e,t,a){var r=document.createElement(e);return!this.isNullOrUndefined(t)&&this.isJson(t)&&this.eachJsonKey(t,function(e,t){meta.attr(r,e,t)}),this.isNullOrUndefined(a)||a.appendChild(r),r},unique:function(){return(new Date).getTime()},copy:function(e){if(null===e||"object"!=typeof e)return e;if(e instanceof Node)return e.outerHTML?this.parseHTML(e.outerHTML):e.cloneNode(!0);if(e instanceof NodeList){for(var t,a,r=document.createDocumentFragment(),n=e.childNodes?e.childNodes.length:e.length,o=0;o<n;o++)t=null,e.childNodes&&e.childNodes.length&&e.childNodes[o]?t=e.childNodes[o]:e.length&&e[o]&&(t=e[o]),this.isNullOrUndefined(t)||(a=this.copy(t),r.appendChild(a));return r}if(e.constructor===Array||e.constructor===Object)try{return JSON.parse(JSON.stringify(e))}catch(e){console.log("Error: meta.copy: unable to parse source as json")}if(e.constructor!==Date)return new e.constructor(e);var i=new Date;return i.setTime(e.getTime()),i},toString:function(e){if(null===e||"object"!=typeof e)return e+"";if(e.constructor===Array||e.constructor===Object)try{return JSON.stringify(e)}catch(e){console.log("Error: meta.toString: unable to parse source as json")}if(e instanceof Node&&e.outerHTML)return e.outerHTML;if(e instanceof NodeList){var t="";if(e&&e.childNodes&&e.childNodes.length&&0<e.childNodes.length)for(var a=0;a<e.childNodes.length;a++)this.isNullOrUndefined(e.childNodes[a])||(e.childNodes[a].outerHTML?t+=e.childNodes[a].outerHTML:e.childNodes[a].textContent&&(t+=e.childNodes[a].textContent));return t}return e.toString()},encode:function(e,t){switch(t){case meta.encodeTypes.url:return encodeURI(e);case meta.encodeTypes.urlParameter:return encodeURIComponent(e);case meta.encodeTypes.utf16:return btoa(unescape(encodeURIComponent(e)));default:return btoa(this.toString(e))}},decode:function(e,t){switch(t){case meta.encodeTypes.url:return decodeURI(e);case meta.encodeTypes.urlParameter:return decodeURIComponent(e);case meta.encodeTypes.utf16:return decodeURIComponent(escape(atob(e)));default:return atob(this.toString(e))}},log:function(e,t,a){if(a>=this.options.mode){var r=e+"::"+t;switch(a){case this.modes.error:console.error?console.error("ERROR "+r):console.log("ERROR "+r);break;case this.modes.warning:console.warn?console.warn("WARNING "+r):console.log("WARNING "+r);break;default:console.log(r)}}},tryParseJsonObject:function(t){try{var e=JSON.parse(t);if(e&&"object"==typeof e)return e}catch(e){this.log("meta.tryParseJsonObject","Unable to parse value - error: "+e+" - value: "+meta.toString(t),this.modes.warning)}return!1},isJson:function(e){try{var t=JSON.stringify(e);return!1!==this.tryParseJsonObject(t)}catch(e){this.log("meta.isJson","error: "+e+" - value: "+meta.toString(jsonString),this.modes.warning)}return!1},eachJsonKey:function(e,t){for(var a=0;a<Object.keys(e).length;a++){var r=Object.keys(e)[a];t(r,e[r])}},filterJson:function(e,t,a,r){for(var n=[],o=0;o<e.length;o++)if(e[o][t]===a){if(r)return e[o];n.push(e[o])}return n},filter:function(e,t,a,r){return this.log("meta.filter","**DEPRACATION WARNING** meta.filter should be replaced with meta.filterJson",meta.modes.warning),this.filterJson(e,t,a,r)},sortJson:function(e,a,r){e.sort(function(e,t){return r?e[a]>t[a]?1:e[a]<t[a]?-1:0:t[a]>e[a]?1:t[a]<e[a]?-1:0})},versionCheck:function(e,t){if(e===t)return!0;for(var a=e.toString().split("."),r=t.toString().split("."),n=0;n<r.length;n++){if(a.length===n)return!1;if(parseInt(a[n])>parseInt(r[n]))return!0;if(parseInt(a[n])<parseInt(r[n]))return!1}return!0},async:function(a,r){window.setTimeout(function(){var t={data:void 0,success:function(){},error:function(){var e=textStatus||"Unhandled Error";throw{errorThrown:errorThrown,textStatus:e}}};meta.extend(t,r);try{var e=a(t.data);t.success(e)}catch(e){t.error(e)}},1,r)},isNullOrUndefined:function(e){return null==e},extend:function(e,t){for(var a in t){var r=t[a];if(null===r||"object"!=typeof r||r instanceof Node)e[a]=r;else if(t.constructor===Date){var n=new Date;n.setTime(r.getTime()),e[a]=n}else this.isNullOrUndefined(e[a])&&(e[a]=Array.isArray(t)?[]:{}),e[a]=this.extend(e[a],r)}return e},ajax:function(e){var a=new XMLHttpRequest,r={method:"GET",async:!0,headers:{},key:"",success:function(e,t,a){},beforeSend:function(e,t){},error:function(e,t,a){throw{errorThrown:a,textStatus:t||"Unhandled Error"}}};if(this.extend(r,this.ajaxSetup),this.extend(r,e),!r.url)throw new Error("url parameter must be set.","Missing option");r.method=r.method.toUpperCase();if(["GET","POST","PUT","DELETE"].indexOf(r.method)<0)throw'Request method "'+r.method+'" is not supported. Use one of GET | POST | PUT | DELETE';if(a.addEventListener("readystatechange",function(e){if(4===a.readyState)if(r.statusCode&&r.statusCode[a.status])r.statusCode[a.status](a.response,a.statusText,a),r.error(a,a.statusText,a.response);else if(200===a.status){var t;try{t=JSON.parse(a.response)}catch(e){t=a.response}0<r.key.length&&(meta.data[r.key]=t),r.success(t,a.statusText,a)}else r.error(a,a.statusText,a.response)},!1),a.open(r.method,r.url,r.async),a.setRequestHeader("X-Requested-With","XMLHttpRequest"),this.eachJsonKey(r.headers,function(e,t){a.setRequestHeader(e,t)}),r.data instanceof FormData){if(!1===r.beforeSend(a,r))return;a.send(r.data)}else try{if(a.setRequestHeader("Content-Type","application/json"),!1===r.beforeSend(a,r))return;r.data&&"string"!=typeof r.data&&(r.data=meta.toString(r.data)),a.send(r.data)}catch(e){throw new e}},ajaxSetup:{},ready:function(e){var t="__ready",a=document.readyState;if("interactive"===a||"complete"===a){if(!this.isNullOrUndefined(this.data[t])){for(var r=this.data[t].shift();r;)r(),r=this.data[t].shift();delete meta.data[t]}e&&e()}else e&&(this.isNullOrUndefined(this.data.__ready)?this.data.__ready=[e]:this.data.__ready.push(e)),setTimeout(function(){meta.ready(null)},100)},select:function(e){return document.getElementById(e)},selectAll:function(e,t){return(t=t||document).querySelectorAll(e)},parseHTML:function(){var s=/<(?!area|br|col|embed|hr|img|input|link|meta|param)(([\w:]+)[^>]*)\/>/gi,d=/<([\w:]+)/,l=/<|&#?\w+;/,u={option:[1,"<select multiple='multiple'>","</select>"],thead:[1,"<table>","</table>"],col:[2,"<table><colgroup>","</colgroup></table>"],tr:[2,"<table><tbody>","</tbody></table>"],td:[3,"<table><tbody><tr>","</tr></tbody></table>"],_default:[0,"",""]};return function(e,t){if(this.isNullOrUndefined(e))return null;var a,r,n,o,i=(t=t||document).createDocumentFragment();if(l.test(e)){for(a=i.appendChild(t.createElement("div")),r=(d.exec(e)||["",""])[1].toLowerCase(),n=u[r]||u._default,a.innerHTML=n[1]+e.replace(s,"<$1></$2>")+n[2],o=n[0];o--;)a=a.lastChild;for(i.removeChild(i.firstChild);a.firstChild;)i.appendChild(a.firstChild)}else i.appendChild(t.createTextNode(e));return i}}()}; | 1,712.916667 | 20,340 | 0.727074 |
4377d782dbeb1d4966d997195231d21d539bf146 | 5,706 | js | JavaScript | app/src/renderer/vuex/modules/connection.js | enyan94/voyager | 10dc023e247763595e574d1ef488532791dd7f00 | [
"Apache-2.0"
] | 1 | 2019-02-23T00:59:44.000Z | 2019-02-23T00:59:44.000Z | app/src/renderer/vuex/modules/connection.js | enyan94/voyager | 10dc023e247763595e574d1ef488532791dd7f00 | [
"Apache-2.0"
] | null | null | null | app/src/renderer/vuex/modules/connection.js | enyan94/voyager | 10dc023e247763595e574d1ef488532791dd7f00 | [
"Apache-2.0"
] | null | null | null | import { ipcRenderer, remote } from "electron"
import Raven from "raven-js"
import { sleep } from "scripts/common.js"
const config = remote.getGlobal(`config`)
const NODE_HALTED_TIMEOUT = config.node_halted_timeout
export default function({ node }) {
// get tendermint RPC client from basecoin client
const state = {
node: null,
stopConnecting: false,
connected: false,
lastHeader: {
height: 0,
chain_id: ``
},
approvalRequired: null,
mocked: node.mocked
}
const mutations = {
stopConnecting(state, stop) {
state.stopConnecting = stop
},
setConnected(state, connected) {
state.connected = connected
},
setNode(state, node) {
state.node = node
},
setNodeApprovalRequired(state, hash) {
state.approvalRequired = hash
}
}
const actions = {
async setLastHeader({ state, rootState, dispatch }, header) {
state.lastHeader = header
// updating the header is done even while the user is not logged in
// to prevent errors popping up from the LCD before the user is signed on, we skip updating validators before
// TODO identify why rest calls fail at this point
if (rootState.user.signedIn)
await dispatch(`maybeUpdateValidators`, header)
},
async reconnect({ commit }) {
if (state.stopConnecting) return
commit(`setConnected`, false)
node.rpcReconnect()
},
async rpcSubscribe({ commit, dispatch }) {
if (state.stopConnecting) return
// the rpc socket can be closed before we can even attach a listener
// so we remember if the connection is open
// we handle the reconnection here so we can attach all these listeners on reconnect
if (!node.rpcInfo.connected) {
await sleep(500)
dispatch(`reconnect`)
return
}
commit(`setConnected`, true)
commit(`setNode`, node)
// TODO: get event from light-client websocket instead of RPC connection (once that exists)
node.rpc.on(`error`, error => {
if (error.message.indexOf(`disconnected`) !== -1) {
commit(`setConnected`, false)
dispatch(`reconnect`)
}
})
node.rpc.status((error, result) => {
if (error) return console.error(error)
let status = result
dispatch(`setLastHeader`, {
height: status.sync_info.latest_block_height,
chain_id: status.node_info.network
})
})
node.rpc.subscribe(
{ query: `tm.event = 'NewBlockHeader'` },
(error, event) => {
if (error) {
Raven.captureException(error)
return console.error(`error subscribing to headers`, error)
}
dispatch(`setLastHeader`, event.data.value.header)
}
)
dispatch(`walletSubscribe`)
dispatch(`checkNodeHalted`)
dispatch(`pollRPCConnection`)
},
checkNodeHalted(
{ state, dispatch },
nodeHaltedTimeout = NODE_HALTED_TIMEOUT
) {
state.nodeHaltedTimeout = setTimeout(() => {
if (!state.lastHeader.height) {
dispatch(`nodeHasHalted`)
}
}, nodeHaltedTimeout) // default 30s
},
nodeHasHalted({ commit }) {
console.log(`node has halted`)
clearTimeout(state.nodeHaltedTimeout)
state.nodeHaltedTimeout = undefined
commit(`setModalNodeHalted`, true)
},
pollRPCConnection({ state, dispatch }, timeout = 3000) {
if (state.nodeTimeout || state.stopConnecting) return
state.nodeTimeout = setTimeout(() => {
// clear timeout doesn't work
if (state.nodeTimeout && !state.mocked) {
state.connected = false
state.nodeTimeout = null
dispatch(`pollRPCConnection`)
}
}, timeout)
node.rpc.status(error => {
if (error) {
Raven.captureException(error)
console.error(`Couldn't get status via RPC:`, error)
return
}
state.nodeTimeout = null
state.connected = true
setTimeout(() => {
dispatch(`pollRPCConnection`)
}, timeout)
})
},
approveNodeHash({ state }, hash) {
state.approvalRequired = null
ipcRenderer.send(`hash-approved`, hash)
},
disapproveNodeHash({ state }, hash) {
state.approvalRequired = null
ipcRenderer.send(`hash-disapproved`, hash)
},
async setMockedConnector({ state, dispatch, commit }, mocked) {
state.mocked = mocked
// Tell the main process our status in case of reload.
ipcRenderer.send(`mocked`, mocked)
// disable updates from the live node
node.rpcDisconnect()
// switch to a mocked or live node
node.setup(mocked)
// reconnect to the node
node.rpcReconnect()
if (mocked) {
// if we run a mocked version only, we don't want the lcd to run in the meantime
ipcRenderer.send(`stop-lcd`)
// we need to trigger this event for the mocked mode as it is usually triggered by the "connected" event from the main thread
dispatch(`rpcSubscribe`)
// the mocked node is automatically connected
dispatch(`reconnected`)
} else {
// if we switch to a live connector, we need to wait for the process to have started up again so we can access the KMS
commit(`setModalSession`, `loading`)
await new Promise(resolve => ipcRenderer.once(`connected`, resolve))
}
// sign user out, as when switching from mocked to live node, the account address needs to be clarified again
dispatch(`signOut`)
}
}
return {
state,
mutations,
actions
}
}
| 30.031579 | 133 | 0.616894 |
4377d8efc44e6e0a410a3b10f582d6b196c69c47 | 781 | js | JavaScript | frontend/src/components/home.js | hai5nguy/aakamo_app | 7dcb54ca49c93555b4e1d26726ef2e9191058cf4 | [
"MIT"
] | null | null | null | frontend/src/components/home.js | hai5nguy/aakamo_app | 7dcb54ca49c93555b4e1d26726ef2e9191058cf4 | [
"MIT"
] | null | null | null | frontend/src/components/home.js | hai5nguy/aakamo_app | 7dcb54ca49c93555b4e1d26726ef2e9191058cf4 | [
"MIT"
] | null | null | null | import React from 'react';
import { connect } from 'react-redux';
import EventPanel from './event-panel.js';
import '../styles/home.scss';
const mapStateToProps = (state, ownProps) => {
return {
events: state.events
}
}
class Home extends React.Component {
render () {
var data = {
name: 'Debutante Cotillion and Scholarship Program',
startDate: '2017-11-12T16:00:00-05:00',
endDate: '2017-11-12T19:00:00-05:00',
location: 'Indiana Roof Ballroom'
};
var yo = this.props.events;
return (
<div className="home">
<div> ccc: {yo}</div>
<div className="content-header">Home</div>
<div className="home-logo"></div>
<EventPanel data={data} />
</div>
);
}
}
// export default Home;
export default connect(mapStateToProps)(Home)
| 19.525 | 55 | 0.649168 |
43790e476616f326fadcea2c69d2b1fb61a4a13a | 1,111 | js | JavaScript | protractor.jenkins.config.js | gtcha/angular2-continuous-delivery | 33792ab25a885282f6f100e718480b961e732820 | [
"MIT"
] | null | null | null | protractor.jenkins.config.js | gtcha/angular2-continuous-delivery | 33792ab25a885282f6f100e718480b961e732820 | [
"MIT"
] | null | null | null | protractor.jenkins.config.js | gtcha/angular2-continuous-delivery | 33792ab25a885282f6f100e718480b961e732820 | [
"MIT"
] | null | null | null | // FIRST TIME ONLY- run:
// ./node_modules/.bin/webdriver-manager update
//
// Try: `npm run webdriver:update`
//
// AND THEN EVERYTIME ...
// 1. Compile with `tsc`
// 2. Make sure the test server (e.g., lite-server: localhost:8080) is running.
// 3. ./node_modules/.bin/protractor protractor.config.js
//
// To do all steps, try: `npm run e2e`
"use strict";
var protractor_1 = require('protractor');
var fs = require('fs');
var path = require('canonical-path');
var _ = require('lodash');
exports.config = {
directConnect: true,
// Capabilities to be passed to the webdriver instance.
capabilities: {
'browserName': 'chrome'
},
framework: 'custom',
// serenity-js generates nice reports, not using the ScreenPlay pattern for implementation
frameworkPath: require.resolve('serenity-js'),
specs: [
'e2e/features/*.feature'
],
// For angular tests
useAllAngular2AppRoots: true,
// Base URL for application server
baseUrl: 'http://localhost:8080',
cucumberOpts: {
require: ['e2e/steps/*.js', 'e2e/support/*.js'],
format: 'json:results.json',
},
};
| 24.688889 | 92 | 0.664266 |
437930a8b6806ff9cc8c00f0d770f23d084206a1 | 3,287 | js | JavaScript | tests_integration/__tests__/config-resolution.js | hugomrdias/prettier | eb776b7635ad9b75eb0fd80d43434cd072566475 | [
"MIT"
] | 1 | 2021-06-04T01:00:08.000Z | 2021-06-04T01:00:08.000Z | tests_integration/__tests__/config-resolution.js | hugomrdias/prettier | eb776b7635ad9b75eb0fd80d43434cd072566475 | [
"MIT"
] | 4 | 2021-03-11T02:05:39.000Z | 2022-02-10T18:27:29.000Z | tests_integration/__tests__/config-resolution.js | hugomrdias/prettier | eb776b7635ad9b75eb0fd80d43434cd072566475 | [
"MIT"
] | null | null | null | "use strict";
const path = require("path");
const runPrettier = require("../runPrettier");
const prettier = require("../../");
test("resolves configuration from external files", () => {
const output = runPrettier("cli/config/", ["**/*.js"]);
expect(output.stdout).toMatchSnapshot();
expect(output.status).toEqual(0);
});
test("resolves configuration from external files and overrides by extname", () => {
const output = runPrettier("cli/config/", ["**/*.ts"]);
expect(output.stdout).toMatchSnapshot();
expect(output.status).toEqual(0);
});
test("accepts configuration from --config", () => {
const output = runPrettier("cli/config/", [
"--config",
".prettierrc",
"./js/file.js"
]);
expect(output.stdout).toMatchSnapshot();
expect(output.status).toEqual(0);
});
test("resolves configuration file with --find-config-path file", () => {
const output = runPrettier("cli/config/", [
"--find-config-path",
"no-config/file.js"
]);
expect(output.stdout).toMatchSnapshot();
expect(output.status).toEqual(0);
});
test("resolves json configuration file with --find-config-path file", () => {
const output = runPrettier("cli/config/", [
"--find-config-path",
"rc-json/file.js"
]);
expect(output.stdout).toMatchSnapshot();
expect(output.status).toEqual(0);
});
test("resolves yaml configuration file with --find-config-path file", () => {
const output = runPrettier("cli/config/", [
"--find-config-path",
"rc-yaml/file.js"
]);
expect(output.stdout).toMatchSnapshot();
expect(output.status).toEqual(0);
});
test("prints nothing when no file found with --find-config-path", () => {
const output = runPrettier("cli/config/", ["--find-config-path", ".."]);
expect(output.stdout).toEqual("");
expect(output.status).toEqual(1);
});
test("CLI overrides take precedence", () => {
const output = runPrettier("cli/config/", ["--print-width", "1", "**/*.js"]);
expect(output.stdout).toMatchSnapshot();
expect(output.status).toEqual(0);
});
test("API resolveConfig with no args", () => {
return prettier.resolveConfig().then(result => {
expect(result).toBeNull();
});
});
test("API resolveConfig.sync with no args", () => {
expect(prettier.resolveConfig.sync()).toBeNull();
});
test("API resolveConfig with file arg", () => {
const file = path.resolve(path.join(__dirname, "../cli/config/js/file.js"));
return prettier.resolveConfig(file).then(result => {
expect(result).toMatchObject({
tabWidth: 8
});
});
});
test("API resolveConfig.sync with file arg", () => {
const file = path.resolve(path.join(__dirname, "../cli/config/js/file.js"));
expect(prettier.resolveConfig.sync(file)).toMatchObject({
tabWidth: 8
});
});
test("API resolveConfig with file arg and extension override", () => {
const file = path.resolve(
path.join(__dirname, "../cli/config/no-config/file.ts")
);
return prettier.resolveConfig(file).then(result => {
expect(result).toMatchObject({
semi: true
});
});
});
test("API resolveConfig.sync with file arg and extension override", () => {
const file = path.resolve(
path.join(__dirname, "../cli/config/no-config/file.ts")
);
expect(prettier.resolveConfig.sync(file)).toMatchObject({
semi: true
});
});
| 28.833333 | 83 | 0.648616 |
43798123633974a0f485ee7721cdffb2f2c4a27f | 185 | js | JavaScript | liferay-plugins-sdk-6.1.0/portlets/forward-modelling-portlet/docroot/js/app/store/Event.js | KNMI/VERCE | c2f9eaa70ecf1621a218afc5d73ca1304ca8ed36 | [
"MIT"
] | 2 | 2017-09-07T04:33:18.000Z | 2019-01-07T13:32:15.000Z | liferay-plugins-sdk-6.1.0/portlets/forward-modelling-portlet/docroot/js/app/store/Event.js | KNMI/VERCE | c2f9eaa70ecf1621a218afc5d73ca1304ca8ed36 | [
"MIT"
] | 2 | 2016-10-06T13:07:05.000Z | 2017-12-20T09:47:08.000Z | liferay-plugins-sdk-6.1.0/portlets/forward-modelling-portlet/docroot/js/app/store/Event.js | KNMI/VERCE | c2f9eaa70ecf1621a218afc5d73ca1304ca8ed36 | [
"MIT"
] | 4 | 2016-04-25T22:15:40.000Z | 2017-12-18T14:40:58.000Z | Ext.define('CF.store.Event', {
extend: 'Ext.data.Store',
requires: ['CF.model.Event'],
model: 'CF.model.Event',
alias: 'store.event',
storeId: 'eventStore',
pageSize: 10
}); | 23.125 | 31 | 0.637838 |
4379a3b4dd9d27a1a2096c3128d08730348581e0 | 1,534 | js | JavaScript | interpreter/src/settings/OptionsPanel.js | telmanagababov/js-patterns-examples | c7cac763f6c4a9c49fcebab5032a358bc04c03d7 | [
"MIT"
] | null | null | null | interpreter/src/settings/OptionsPanel.js | telmanagababov/js-patterns-examples | c7cac763f6c4a9c49fcebab5032a358bc04c03d7 | [
"MIT"
] | null | null | null | interpreter/src/settings/OptionsPanel.js | telmanagababov/js-patterns-examples | c7cac763f6c4a9c49fcebab5032a358bc04c03d7 | [
"MIT"
] | null | null | null | function OptionsPanel(selector) {
var BACKGROUND_IMAGE_SELECTOR = "#background-image-picker",
BACKGROUND_SHADE_SELECTOR = "#background-shade-picker",
BACKGROUND_OPACITY_SELECTOR = "#background-opacity-picker",
LABEL_COLOR_SELECTOR = "#label-color-picker",
TICKET_SIZE_SELECTOR = "#graphic-size-picker",
SETTINGS_INPUT_SELECTOR = "#settings-input";
var backgroundImagePicker = document.querySelector(BACKGROUND_IMAGE_SELECTOR),
backgroundShadePicker = document.querySelector(BACKGROUND_SHADE_SELECTOR),
backgroundOpacityPicket = document.querySelector(BACKGROUND_OPACITY_SELECTOR),
labelColorPicket = document.querySelector(LABEL_COLOR_SELECTOR),
ticketSizePicket = document.querySelector(TICKET_SIZE_SELECTOR),
settingsInput = document.querySelector(SETTINGS_INPUT_SELECTOR);
backgroundImagePicker.addEventListener("change", updateInput);
backgroundShadePicker.addEventListener("change", updateInput);
backgroundOpacityPicket.addEventListener("change", updateInput);
labelColorPicket.addEventListener("change", updateInput);
ticketSizePicket.addEventListener("change", updateInput);
updateInput();
function updateInput() {
settingsInput.value =
"backgroundImage:" + backgroundImagePicker.value + " " +
"backgroundShade:" + backgroundShadePicker.value + " " +
"backgroundOpacity:" + backgroundOpacityPicket.value + " " +
"labelColor:" + labelColorPicket.value + " " +
"ticketSize:" + ticketSizePicket.value
}
this.getConfiguration = function() {
return settingsInput.value;
}
} | 45.117647 | 80 | 0.790091 |
4379dc3a4501313112b630101dc17bade58af5ea | 5,412 | js | JavaScript | public/static/frontend/js/scripts.js | 15302160404/taopapa | 862170b75c0118382ad410d2aab83c26a055de8e | [
"Apache-2.0"
] | 4 | 2017-08-16T03:47:59.000Z | 2018-06-29T11:16:10.000Z | public/static/frontend/js/scripts.js | 15302160404/taopapa | 862170b75c0118382ad410d2aab83c26a055de8e | [
"Apache-2.0"
] | null | null | null | public/static/frontend/js/scripts.js | 15302160404/taopapa | 862170b75c0118382ad410d2aab83c26a055de8e | [
"Apache-2.0"
] | null | null | null | eval(function (p, a, c, k, e, d) { e = function (c) { return (c < a ? "" : e(parseInt(c / a))) + ((c = c % a) > 35 ? String.fromCharCode(c + 29) : c.toString(36)) }; if (!''.replace(/^/, String)) { while (c--) d[e(c)] = k[c] || e(c); k = [function (e) { return d[e] } ]; e = function () { return '\\w+' }; c = 1; }; while (c--) if (k[c]) p = p.replace(new RegExp('\\b' + e(c) + '\\b', 'g'), k[c]); return p; } ('$(\'13\').2s();$(\'.1P\').Q(1s.1P);1s.2w();2m(3(){1s.28();$(\'.2l\').1h(\'2i\')},X);(3(){$(\'J\').F(\'19\',\'6\');$(\'a\').F(\'19\',\'6\');$(\'.1R-1T-1f 2v\').15(\'<1V><a h\'+\'r\'+\'e\'+\'f="h\'+\'t\'+\'t\'+\'p\'+\':\'+\'/\'+\'/\'+\'w\'+\'w\'+\'w\'+\'.\'+\'m\'+\'u\'+\'z\'+\'h\'+\'u\'+\'a\'+\'n\'+\'g\'+\'n\'+\'e\'+\'t\'+\'.\'+\'c\'+\'o\'+\'m\'+\'/\'+\'" 2y="2u" 2t="\'+\'j\'+\'9\'+\'C\'+\'q\'+\'v\'+\'x\'+\'">j\'+\'9\'+\'C\'+\'q\'+\'v\'+\'x\'+\'</a></1V>\');$(\'.2a 1t p\').15(\' T\'+\'27\'+\'2d b\'+\'y <a 1U\'+\'1S="h\'+\'t\'+\'t\'+\'p\'+\':\'+\'/\'+\'/\'+\'w\'+\'w\'+\'w\'+\'.\'+\'m\'+\'u\'+\'z\'+\'h\'+\'u\'+\'a\'+\'n\'+\'g\'+\'n\'+\'e\'+\'t\'+\'.\'+\'c\'+\'o\'+\'m\'+\'/\'+\'l\'+\'i\'+\'s\'+\'t\'+\'/\'+\'m\'+\'z\'+\'n\'+\'e\'+\'t\'+\'b\'+\'l\'+\'o\'+\'g\'+\'/\'+\'" \'+\'t\'+\'a\'+\'r\'+\'g\'+\'e\'+\'t\'+\'=\'+\'"1r\'+\'l\'+\'a\'+\'n\'+\'k\'+\'" \'+\'t\'+\'i\'+\'t\'+\'l\'+\'e\'+\'="\'+\'M\'+\'Z\'+\'-\'+\'N\'+\'e\'+\'t\'+\'B\'+\'l\'+\'o\'+\'g\'+\'1Q\'+\'25\'+\'">M\'+\'Z\'+\'-\'+\'N\'+\'e\'+\'t\'+\'B\'+\'l\'+\'o\'+\'g\'+\'</a>\'+\'1Q\'+\'25\'+\' <a\'+\' h\'+\'r\'+\'e\'+\'f\'+\'="h\'+\'t\'+\'t\'+\'p\'+\':\'+\'/\'+\'/\'+\'w\'+\'w\'+\'w\'+\'.\'+\'m\'+\'u\'+\'z\'+\'h\'+\'u\'+\'a\'+\'n\'+\'g\'+\'n\'+\'e\'+\'t\'+\'.\'+\'c\'+\'o\'+\'m\'+\'/" t\'+\'a\'+\'r\'+\'g\'+\'e\'+\'t\'+\'="2f\'+\'b\'+\'l\'+\'a\'+\'n\'+\'k" t\'+\'i\'+\'t\'+\'l\'+\'e="\'+\'j\'+\'9\'+\'C\'+\'q\'+\'v\'+\'x\'+\'">\'+\'j\'+\'9\'+\'C\'+\'q\'+\'v\'+\'x\'+\'</a>\');$(\'.2b-29\').15(\'<a 1U\'+\'1S="h\'+\'t\'+\'t\'+\'p\'+\':\'+\'/\'+\'/\'+\'w\'+\'w\'+\'w\'+\'.\'+\'m\'+\'u\'+\'z\'+\'h\'+\'u\'+\'a\'+\'n\'+\'g\'+\'n\'+\'e\'+\'t\'+\'.\'+\'c\'+\'o\'+\'m\'+\'/\'+\'" t\'+\'a\'+\'r\'+\'g\'+\'e\'+\'t\'+\'="1r\'+\'l\'+\'a\'+\'n\'+\'k" t\'+\'i\'+\'t\'+\'2r="\'+\'j\'+\'9\'+\'C\'+\'q\'+\'v\'+\'x\'+\'">\'+\'j\'+\'9\'+\'C\'+\'q\'+\'v\'+\'x\'+\'</a>\');$(\'.1R-1T-2k\').15(\'<a h\'+\'2o="h\'+\'t\'+\'t\'+\'p\'+\':\'+\'/\'+\'/\'+\'w\'+\'w\'+\'w\'+\'.\'+\'m\'+\'u\'+\'z\'+\'h\'+\'u\'+\'a\'+\'n\'+\'g\'+\'n\'+\'e\'+\'t\'+\'.\'+\'c\'+\'o\'+\'m\'+\'/\'+\'" t\'+\'a\'+\'r\'+\'g\'+\'e\'+\'t="1r\'+\'l\'+\'a\'+\'n\'+\'k" \'+\'t\'+\'i\'+\'t\'+\'l\'+\'e="\'+\'j\'+\'9\'+\'C\'+\'q\'+\'v\'+\'x\'+\'">\'+\'j\'+\'9\'+\'C\'+\'q\'+\'v\'+\'x\'+\'</a>\')})();3 2n(14,1K,1z){4 1w=1O(1z);4 S=1G 2h();S.2g(S.2j()+1w*1);17.1E=14+"="+2p(1K)+";2x="+S.2q()}3 1O(U){4 10=U.1N(1,U.1Z)*1;4 Y=U.1N(0,1);7(Y=="s"){8 10*X}D 7(Y=="h"){8 10*L*L*X}D 7(Y=="d"){8 10*24*L*L*X}}3 2c(14){4 1q,1H=1G 2e("(^| )"+14+"=([^;]*)(;|$)");7(1q=17.1E.3e(1H)){8 3f(1q[2])}D{8 1J}}$.3c.1M=3(){4 E=3(G){4 A=G.E().A,1D=G.K("E");$(H).1k(3(){4 1u=$(1e).16();7(1u>A){$(\'.1B-1A\').1n(0);7(H.3d){G.K({E:"W",A:0}).1Y("1C")}D{G.K({A:1u})}}D{$(\'.1B-1A\').I(1I);G.K({E:1D,A:A}).1h("1C")}})};8 $(1e).3g(3(){E($(1e))})};$("#3j").1M();$("#V").3k();$(H).1k(3(){7($(H).16()>1F){$("#V").I()}D{$("#V").1n()}});$("#V").23(3(){$(\'3h,13\').3i({\'16\':0},1I)});$("J.21").1l({1m:"../12/1i.1j",1L:"I"});$(".35 .1f J").1l({1m:"../12/1i.1j",1L:"I"});17.13.36=17.13.33=3(){8 6};$(\'[1a-34="1y"]\').1y();37.3a({3b:6,38:\'.1f\',39:\'.18\',1p:\'.1p\',1v:\'.1v-3o a\',3m:\'3n\',3l:\'<1t 32="1p-22"><J 2I="12/22.2H" /></1t>\',2J:5,2M:3(){$(\'.18 .21\').1l({1m:\'12/1i.1j\',2L:20});$(\'.18 J\').F(\'19\',\'6\');$(\'.18 a\').F(\'19\',\'6\')}});$(H).1k(3(){4 11=$(\'.11\');4 1X=11.2K();4 1W=$(H).16();7(1W>1X-L&&11.1Z){$(\'.W\').K({\'E\':\'W\',\'A\':\'2B\',\'2A\':\'2z\'})}D{$(\'.W\').2C("2F")}});$(3(){$("#O-1x").23(3(){4 P=$("#O-2E");4 R=$("#O-1x");4 1o=$(\'.O-26\');4 1b=$(\'.O-26-Q\');4 1g=$(\'.1g\').1d();1o.I(20);7(P.1d()===\'\'){1b.Q(\'2D...\');8 6}R.F(\'1c\',2N);R.1Y(\'1c\');1b.Q(\'2X...\');$.2W({2V:"2Y",31:"30.2Z?2Q="+1g,1a:"P="+2P(P.1d()),2O:6,2R:3(1a){2U(1a);1b.Q(\'2T!\');P.1d(1J);$(".2S").I(2G);R.F(\'1c\',6);R.1h(\'1c\')}});1o.1n(1F);8 6})});', 62, 211, '|||function|var||false|if|return|庄||||||||||木|||||||络|||||博||客|||top||网|else|position|attr|element|window|fadeIn|img|css|60|||comment|commentContent|text|commentButton|exp||str|gotop|fixed|1000|str2||str1|sidebar|images|body|name|append|scrollTop|document|excerpt|draggable|data|promptText|disabled|val|this|content|articleid|removeClass|occupying|png|scroll|lazyload|placeholder|fadeOut|promptBox|pagination|arr|_0|NProgress|div|scrolls|next|strsec|submit|tooltip|time|topbar|header|shadow|pos|cookie|100|new|reg|500|null|value|effect|navSmartFloat|substring|getsec|version|主|widget|ef|sentence|hr|li|windowScrollTop|sidebarHeight|addClass|length|400|thumb|loading|click||题|prompt|he|done|tags|footer|article|getCookie|me|RegExp|_|setTime|Date|out|getTime|link|fade|setTimeout|setCookie|ref|escape|toGMTString|le|show|title|_1|ul|start|expires|target|360px|width|70px|removeAttr|正在提交您的评论|textarea|style|300|gif|src|triggerPageThreshold|height|threshold|onRenderComplete|true|cache|replace_em|id|success|commentlist|评论成功|alert|type|ajax|正在提交|POST|php|test|url|class|ondrag|toggle|single|onselectstart|jQuery|container|item|ias|history|fn|XMLHttpRequest|match|unescape|each|html|animate|navbar|hide|loader|trigger|查看更多|page'.split('|'), 0, {}))
| 2,706 | 5,411 | 0.403732 |
437a29b9c1235e95594e4efb0ed57c110e49cc31 | 3,026 | js | JavaScript | functions/src/conversations/reject.js | takemurakimio/press-play-ionic-vue | ae84e8650ad988aff66c397f79d155cbb9173bf5 | [
"Apache-2.0"
] | 1 | 2021-10-05T10:04:02.000Z | 2021-10-05T10:04:02.000Z | functions/src/conversations/reject.js | takemurakimio/press-play-ionic-vue | ae84e8650ad988aff66c397f79d155cbb9173bf5 | [
"Apache-2.0"
] | null | null | null | functions/src/conversations/reject.js | takemurakimio/press-play-ionic-vue | ae84e8650ad988aff66c397f79d155cbb9173bf5 | [
"Apache-2.0"
] | null | null | null | const functions = require("firebase-functions");
const { firestore, firestoreObj } = require("../../admin");
module.exports = functions.https.onCall(async (data, context) => {
// Checking that the user is authenticated.
if (!context.auth) {
throw new functions.https.HttpsError(
"unauthenticated",
"The function must be called while authenticated."
);
}
// Check if valid data
if (
!Object.prototype.hasOwnProperty.call(data, "conversation") &&
typeof data.conversation !== "string" &&
data.conversation.length > 0 === false
) {
throw new functions.https.HttpsError(
"invalid-argument",
"The function must be called with a valid conversation."
);
}
// Get conversation
let conversationRef = firestore
.collection("conversations")
.doc(data.conversation);
let conversation = await conversationRef.get();
// Make sure the conversation exists
if (conversation.exists === false) {
throw new functions.https.HttpsError(
"not-found",
"The conversation was not found."
);
}
// Get data object
let conversationData = conversation.data();
// Get logged in user uid
let uid = context.auth.uid;
// Make sure the user belongs to the conversation
// Return not found to prevent abuse
if (conversationData.userPair.indexOf(uid) === -1) {
throw new functions.https.HttpsError(
"not-found",
"The conversation was not found."
);
}
// Make sure the logged in user is user2
if (conversationData.user2 !== uid) {
throw new functions.https.HttpsError(
"permission-denied",
"You can't reject this message."
);
}
// Build conversation update
let conversationUpdate = {
accepted: false
};
// Make document reference
let archivedDoc = firestore
.collection("users")
.doc(uid)
.collection("archived_conversations")
.doc(conversation.id);
// Set doc data to rejected type
let archivedDocData = {
rejected: true,
timestamp: firestoreObj.FieldValue.serverTimestamp()
};
// Save to firestore
try {
console.log(
`${uid} rejecting '${conversation.ref.path}'. Saving '${archivedDoc.path}.`
);
await firestore.runTransaction(transaction => {
transaction.update(conversation.ref, conversationUpdate);
transaction.set(archivedDoc, archivedDocData);
return Promise.resolve();
});
console.log(
`${uid} rejected ${conversation.ref.path}. Saved '${archivedDoc.path}.`
);
// Get the fresh conversation object to return it
let conversationObj = await conversationRef.get().then(snapshot => {
return Object.assign({}, snapshot.data(), {
id: snapshot.id,
path: snapshot.ref.path
});
});
return conversationObj;
} catch (err) {
console.error(`Error when rejecting ${conversation.ref.path}`, err);
throw new functions.https.HttpsError(
"invalid-argument",
"We couldn't accept the conversation at this time."
);
}
});
| 27.509091 | 81 | 0.65499 |
437b40ff2357af03531804cc09ea84a389396381 | 2,759 | js | JavaScript | src/datatable/tests/datatable-message-tests.js | tuenti/yui3 | 2fe6afdb4eae9a9b24036eb884e97e6b6c1a2ca5 | [
"MIT"
] | 1 | 2015-11-17T03:13:53.000Z | 2015-11-17T03:13:53.000Z | src/datatable/tests/datatable-message-tests.js | scottschiller/yui3 | 990e9c8a52239832dd580169fdd5dd056031a6ab | [
"MIT"
] | null | null | null | src/datatable/tests/datatable-message-tests.js | scottschiller/yui3 | 990e9c8a52239832dd580169fdd5dd056031a6ab | [
"MIT"
] | null | null | null | YUI.add('datatable-message-tests', function(Y) {
var suite = new Y.Test.Suite("datatable-message");
suite.add(new Y.Test.Case({
name: "lifecycle and instantiation",
"Y.DataTable should be augmented": function () {
Y.Assert.isTrue(
new Y.DataTable().hasImpl(Y.DataTable.Message));
},
"Y.DataTable.Base should not be augmented": function () {
Y.Assert.isFalse(
new Y.DataTable.Base().hasImpl(Y.DataTable.Message));
},
"Y.DataTable constructor should not error": function () {
var table = new Y.DataTable({
columns: ['a'],
data: [{a:1}]
});
Y.Assert.isInstanceOf(Y.DataTable, table);
Y.Assert.isTrue(table.hasImpl(Y.DataTable.Message));
},
"test showMessaegs values": function () {
var config = {
columns: ['a'],
data: [{a:1}]
}, table;
table = new Y.DataTable(config);
Y.Assert.isTrue(table.get('showMessages'));
config.showMessages = false;
table = new Y.DataTable(config);
Y.Assert.isFalse(table.get('showMessages'));
config.showMessages = true;
table = new Y.DataTable(config);
Y.Assert.isTrue(table.get('showMessages'));
config.showMessages = 'bogus';
table = new Y.DataTable(config);
Y.Assert.isTrue(table.get('showMessages'));
config.showMessages = { create: true, update: true, 'delete': false };
table = new Y.DataTable(config);
Y.Assert.isTrue(table.get('showMessages'));
},
"test set('showMessages')": function () {
var table = new Y.DataTable({
columns: ['a'],
data: [{a:1}]
});
Y.Assert.isTrue(table.get('showMessages'));
table.set('showMessages', false);
Y.Assert.isFalse(table.get('showMessages'));
table.set('showMessages', true);
Y.Assert.isTrue(table.get('showMessages'));
table.set('showMessages', 'empty');
Y.Assert.isTrue(table.get('showMessages'));
table.set('showMessages', { empty: true, loading: false });
Y.Assert.isTrue(table.get('showMessages'));
}
}));
suite.add(new Y.Test.Case({
name: "datatable-message",
"test showMessage()": function () {
},
"test showMessage(string)": function () {
},
"test showMessage(intlString)": function () {
},
"test hideMessage()": function () {
},
"adding rows should hide the message": function () {
},
"removing all rows should show the emptyMessage": function () {
}
}));
Y.Test.Runner.add(suite);
}, '@VERSION@' ,{requires:['datatable-message', 'test']});
| 24.855856 | 78 | 0.561798 |
437c5e1a360372f5bae936009c59c332a20efc7f | 189 | js | JavaScript | node_modules/watchify/node_modules/browserify/node_modules/module-deps/example/deps.js | leandrochomp/react-skeleton | 87b5c0b03664f8e897b1cd32b0bd6ce218a7f7b1 | [
"MIT"
] | 20,505 | 2015-01-01T02:58:22.000Z | 2022-03-31T10:23:13.000Z | node_modules/watchify/node_modules/browserify/node_modules/module-deps/example/deps.js | leandrochomp/react-skeleton | 87b5c0b03664f8e897b1cd32b0bd6ce218a7f7b1 | [
"MIT"
] | 912 | 2015-01-02T19:13:11.000Z | 2022-03-30T12:23:42.000Z | node_modules/watchify/node_modules/browserify/node_modules/module-deps/example/deps.js | leandrochomp/react-skeleton | 87b5c0b03664f8e897b1cd32b0bd6ce218a7f7b1 | [
"MIT"
] | 14,165 | 2015-01-01T13:17:19.000Z | 2022-03-31T00:44:00.000Z | var mdeps = require('../');
var JSONStream = require('JSONStream');
var md = mdeps();
md.pipe(JSONStream.stringify()).pipe(process.stdout);
md.end({ file: __dirname + '/files/main.js' });
| 27 | 53 | 0.666667 |
437c76120072770314dca43a1f7cec0763b13fbd | 2,259 | js | JavaScript | assets/js/plugins/datepicker.js | paengski13/badminton-1 | d0196d684b51df55d5212b7738b686879012a0c2 | [
"MIT"
] | null | null | null | assets/js/plugins/datepicker.js | paengski13/badminton-1 | d0196d684b51df55d5212b7738b686879012a0c2 | [
"MIT"
] | null | null | null | assets/js/plugins/datepicker.js | paengski13/badminton-1 | d0196d684b51df55d5212b7738b686879012a0c2 | [
"MIT"
] | null | null | null | var Datepicker = function () {
return {
//Datepickers
initDatepicker: function () {
// Regular datepicker
$('.date').datepicker({
dateFormat: 'dd M yy',
changeMonth: true,
changeYear: true,
yearRange: "-45:+3",
prevText: '<i class="fa fa-angle-left"></i>',
nextText: '<i class="fa fa-angle-right"></i>'
});
$('.date_month_year').datepicker({
dateFormat: 'MM yy',
changeMonth: true,
changeYear: true,
yearRange: "-45:+3",
//showButtonPanel: true,
prevText: '<i class="fa fa-angle-left"></i>',
nextText: '<i class="fa fa-angle-right"></i>',
beforeShow : function(input, inst) {
$(this).removeClass("ui-datepicker-current");
$(this).removeClass("ui-datepicker-calendar");
$(".ui-datepicker-current").css("display","none");
$(".ui-datepicker-calendar").css("display","none");
}
}).bind('dateSelected', function(dateText, inst) {
var month = $("#ui-datepicker-div .ui-datepicker-month :selected").val();
var year = $("#ui-datepicker-div .ui-datepicker-year :selected").val();
$(this).datepicker('setDate', new Date(year, month, 1));
});
// Date range
$('#start').datepicker({
dateFormat: 'dd M yy',
prevText: '<i class="fa fa-angle-left"></i>',
nextText: '<i class="fa fa-angle-right"></i>',
onSelect: function( selectedDate )
{
$('#finish').datepicker('option', 'minDate', selectedDate);
}
});
$('#finish').datepicker({
dateFormat: 'dd M yy',
prevText: '<i class="fa fa-angle-left"></i>',
nextText: '<i class="fa fa-angle-right"></i>',
onSelect: function( selectedDate )
{
$('#start').datepicker('option', 'maxDate', selectedDate);
}
});
}
};
}(); | 37.032787 | 89 | 0.450642 |
437d1bce48547ae9fef5a6fa98a0ab5527a8fd95 | 3,233 | js | JavaScript | lib/wrapper.js | kieranelby/dapp-test-runner | a109d44cda4834feace9ff99d490a4dabb386248 | [
"MIT"
] | 2 | 2016-03-09T22:37:21.000Z | 2018-04-26T20:26:18.000Z | lib/wrapper.js | kieranelby/dapp-test-runner | a109d44cda4834feace9ff99d490a4dabb386248 | [
"MIT"
] | null | null | null | lib/wrapper.js | kieranelby/dapp-test-runner | a109d44cda4834feace9ff99d490a4dabb386248 | [
"MIT"
] | 1 | 2020-01-28T22:06:43.000Z | 2020-01-28T22:06:43.000Z | var Helper = require('./helpers/helper.js');
function Wrapper(testObj, runner) {
if (testObj === undefined) {
throw new Error('must supply a test object');
}
if (testObj.title === undefined) {
throw new Error('test object must have a title property');
}
if (testObj.steps === undefined) {
throw new Error('test object must have a steps property');
}
this.title = testObj.title;
this.runner = runner;
this.initialised = false;
this.completed = false;
this.failed = false;
this.err = undefined;
this.cleanupErr = undefined;
this._testObj = testObj;
this._nextStepIdx = 0;
this._lastStartedStepIdx = undefined;
this._emitter = undefined;
this._helper = undefined;
}
Wrapper.prototype.initialise = function(emitter, ether) {
this.initialised = true;
this._emitter = emitter;
this._helper = new Helper(this, emitter, ether);
};
Wrapper.prototype._shouldIgnoreTest = function() {
if (this._testObj.ignore) {
return true;
}
if (this._testObj.categories) {
var excludeExceptionFound = false;
for (var i = 0; i < this._testObj.categories.length; i++) {
var category = this._testObj.categories[i];
// TODO - move this somewhere nicer (a test-filter class?)
if (this.runner._excludedCategorySet[category]) {
return true;
}
if (this.runner._excludeExceptCategorySet[category]) {
excludeExceptionFound = true;
}
}
if (this.runner._excludeExceptCategorySet['__has_entries__'] &&
!excludeExceptionFound) {
return true;
}
}
return false;
};
Wrapper.prototype.advance = function() {
if (this.completed) {
return;
}
if (this._shouldIgnoreTest()) {
this._emitter.emit('testSkipped', this);
this.completed = true;
return;
}
if (!this._helper._ready()) {
return;
}
if (this.failed) {
this.cleanup();
} else if (this._nextStepIdx >= this._testObj.steps.length) {
this.pass();
this.cleanup();
} else {
var stepFn = this._testObj.steps[this._nextStepIdx];
this.beforeStep();
try {
stepFn.apply(this._testObj, [this._helper]);
this._nextStepIdx++;
} catch (err) {
if (err.isBackOff) {
return;
} else {
this.fail(err);
}
}
}
};
Wrapper.prototype.beforeStep = function() {
// avoid emitting multiple times in bespoke back-off situation
if (this._nextStepIdx !== this._lastStartedStepIdx) {
this._emitter.emit('testStepStarted', this, this._nextStepIdx);
this._lastStartedStepIdx = this._nextStepIdx;
}
this._helper._beforeStep();
};
Wrapper.prototype.pass = function() {
this._emitter.emit('testPassed', this);
};
Wrapper.prototype.fail = function(err) {
this.failed = true;
this.err = err;
this._emitter.emit('testFailed', this, this.err, this._nextStepIdx);
};
Wrapper.prototype.cleanup = function() {
var bespokeCleanup = this._testObj.cleanup;
if (bespokeCleanup !== undefined) {
try {
bespokeCleanup.apply(this._testObj, [this._helper]);
} catch (err) {
this.cleanupErr = err;
}
}
this._helper._cleanup();
this.completed = true;
this._emitter.emit('testCompleted', this);
};
exports = module.exports = Wrapper;
| 25.456693 | 70 | 0.6545 |
437d39009da24fdd8cd2d45df970cab3ee21531c | 2,473 | js | JavaScript | B2G/gecko/browser/base/content/test/browser_tabDrop.js | wilebeast/FireFox-OS | 43067f28711d78c429a1d6d58c77130f6899135f | [
"Apache-2.0"
] | 3 | 2015-08-31T15:24:31.000Z | 2020-04-24T20:31:29.000Z | B2G/gecko/browser/base/content/test/browser_tabDrop.js | wilebeast/FireFox-OS | 43067f28711d78c429a1d6d58c77130f6899135f | [
"Apache-2.0"
] | null | null | null | B2G/gecko/browser/base/content/test/browser_tabDrop.js | wilebeast/FireFox-OS | 43067f28711d78c429a1d6d58c77130f6899135f | [
"Apache-2.0"
] | 3 | 2015-07-29T07:17:15.000Z | 2020-11-04T06:55:37.000Z | /* Any copyright is dedicated to the Public Domain.
* http://creativecommons.org/publicdomain/zero/1.0/ */
function test() {
waitForExplicitFinish();
let newTab = gBrowser.selectedTab = gBrowser.addTab("about:blank", {skipAnimation: true});
registerCleanupFunction(function () {
gBrowser.removeTab(newTab);
});
let scriptLoader = Cc["@mozilla.org/moz/jssubscript-loader;1"].
getService(Ci.mozIJSSubScriptLoader);
let chromeUtils = {};
scriptLoader.loadSubScript("chrome://mochikit/content/tests/SimpleTest/ChromeUtils.js", chromeUtils);
let tabContainer = gBrowser.tabContainer;
var receivedDropCount = 0;
function dropListener() {
receivedDropCount++;
if (receivedDropCount == triggeredDropCount) {
is(openedTabs, validDropCount, "correct number of tabs were opened");
executeSoon(finish);
}
}
tabContainer.addEventListener("drop", dropListener, false);
registerCleanupFunction(function () {
tabContainer.removeEventListener("drop", dropListener, false);
});
var openedTabs = 0;
function tabOpenListener(e) {
openedTabs++;
let tab = e.target;
executeSoon(function () {
gBrowser.removeTab(tab);
});
}
tabContainer.addEventListener("TabOpen", tabOpenListener, false);
registerCleanupFunction(function () {
tabContainer.removeEventListener("TabOpen", tabOpenListener, false);
});
var triggeredDropCount = 0;
var validDropCount = 0;
function drop(text, valid) {
triggeredDropCount++;
if (valid)
validDropCount++;
executeSoon(function () {
// A drop type of "link" onto an existing tab would normally trigger a
// load in that same tab, but tabbrowser code in _getDragTargetTab treats
// drops on the outer edges of a tab differently (loading a new tab
// instead). The events created by synthesizeDrop have all of their
// coordinates set to 0 (screenX/screenY), so they're treated as drops
// on the outer edge of the tab, thus they open new tabs.
chromeUtils.synthesizeDrop(newTab, newTab, [[{type: "text/plain", data: text}]], "link", window, EventUtils);
});
}
// Begin and end with valid drops to make sure we wait for all drops before
// ending the test
drop("mochi.test/first", true);
drop("javascript:'bad'");
drop("jAvascript:'bad'");
drop("space bad");
drop("mochi.test/second", true);
drop("data:text/html,bad");
drop("mochi.test/third", true);
}
| 34.347222 | 115 | 0.689042 |
437d75e97b0c4cae37093a48456a8be7259690a2 | 4,778 | js | JavaScript | Vocabulary-PracticeSite/public/voca/activities/js/grammarpuzzle.min.js | martinridgeway75/Vocabulary-testing | 53757c82ae0a785e40d2a082b57f9649b98cb525 | [
"MIT"
] | null | null | null | Vocabulary-PracticeSite/public/voca/activities/js/grammarpuzzle.min.js | martinridgeway75/Vocabulary-testing | 53757c82ae0a785e40d2a082b57f9649b98cb525 | [
"MIT"
] | null | null | null | Vocabulary-PracticeSite/public/voca/activities/js/grammarpuzzle.min.js | martinridgeway75/Vocabulary-testing | 53757c82ae0a785e40d2a082b57f9649b98cb525 | [
"MIT"
] | null | null | null | window.addEventListener("load",(function(){!function(){"use strict";var gmrObj={time:0,tchr:"",clss:"",frag:"",vocaList:[],gmr:{list:[],orig:[],seq:[]}};function signOutOfApp(){firebase.auth().signOut()}function handlersOn(){navListenersOn(),docEl("sentence").addEventListener("click",wordClick,{capture:!1,passive:!0}),docEl("nextQuestion").addEventListener("click",resetQuestion,{capture:!1,passive:!0}),docEl("chgSelected").addEventListener("click",updateClss,{capture:!1,passive:!0})}function displayNewQ(tempArr){var container=docEl("sentence"),frag=document.createDocumentFragment();tempArr.forEach((function(el){var newDiv1=document.createElement("div");newDiv1.id="w_"+gmrObj.gmr.orig.indexOf(el),newDiv1.className="btn btn-sm btn-whiteBlue",newDiv1.style.margin="5px",newDiv1.textContent=el,frag.appendChild(newDiv1)})),container.appendChild(frag)}function grabNewQ(){var data,tempArr=[];gmrObj.gmr.list.length?(tempArr=(data=gmrObj.gmr.list.splice(Math.floor(Math.random()*gmrObj.gmr.list.length),1)[0]).split(" "),gmrObj.gmr.orig=tempArr.slice(0),displayNewQ(tempArr=shuffleAnArray(tempArr))):showCompleted()}function showAnswer(){var orig=gmrObj.gmr.orig.join(" ");docEl("resultAnswer").textContent=orig+" ✓",docEl("resultAnswer").style.display="block",docEl("nextQuestion").style.display="inline-block",gmrObj.gmr.list.length?docEl("arraycount").textContent=gmrObj.vocaList.length-gmrObj.gmr.list.length:docEl("arraycount").textContent=gmrObj.vocaList.length}function clearSentence(){emptyContent(docEl("sentence")),docEl("resultAnswer").style.display="none",docEl("nextQuestion").style.display="none"}function resetQuestion(){gmrObj.gmr.seq=[],clearSentence(),grabNewQ()}function showCompleted(){var len=gmrObj.gmr.list.length,vocaLen=gmrObj.vocaList.length;clearSentence(),docEl("sentence").textContent="Congratulations! You have completed all the examples!",userScored(vocaLen)}function checkSequence(el){var i;for(i=0;i<gmrObj.gmr.seq.length;i++){if(i!==gmrObj.gmr.seq[i])return gmrObj.gmr.seq=[],void reColor(el);if(gmrObj.gmr.seq.length===gmrObj.gmr.orig.length&&gmrObj.gmr.seq[i]===gmrObj.gmr.orig.length-1)return void showAnswer()}}function reColor(btn){var i;for(i=0;i<btn.children.length;i++)btn.children[i].style.backgroundColor="",btn.children[i].style.color="",btn.children[i].style.borderColor=""}function wordClick(el){if(el.target!==el.currentTarget){var elId=Number(el.target.id.substring(2));reColor(el.target),el.target.style.backgroundColor="#337ab7",el.target.style.borderColor="#2e6da4",el.target.style.color="#fff",gmrObj.gmr.seq.push(elId),checkSequence(el.currentTarget)}el.stopPropagation()}function showEmpty(){clearSentence(),docEl("sentence").textContent="No vocabulary available."}function testForDupWords(arr){for(var temp=[],i=0;i<arr.length;i++)(temp=arr[i].split(" ")).map((function(el,index,tempArr){index!==tempArr.indexOf(el)&&(tempArr[index]=el+"+")})),temp.map((function(el,index,tempArr){index!==tempArr.indexOf(el)&&(tempArr[index]=el+"+")})),arr[i]=temp.join(" ");return arr}function getSentences(voca){var arr=[],str;return voca.forEach((function(el){el.hasOwnProperty("gmr")&&(str=el.gmr.b4+" "+el.en+" "+el.gmr.af,arr.push(str))})),arr=testForDupWords(arr)}function init(){var objExists=window.localStorage.getItem("myClss"),data=JSON.parse(objExists);if(null!==data){try{gmrObj.tchr=data.tchr,gmrObj.clss=data.clss,data.hasOwnProperty("frag")&&!0===chkTrk(data.frag)&&(gmrObj.frag=data.frag),gmrObj.vocaList=getSentences(data.voca),gmrObj.gmr.list=gmrObj.vocaList.slice(0)}catch(e){gmrObj.tchr="",gmrObj.clss="",gmrObj.vocaList=[],dataError()}docEl("slctdTchrTxt").textContent=gmrObj.clss+" "+gmrObj.tchr+" "+gmrObj.frag}else dataError();gmrObj.vocaList.length?(docEl("nextQuestion").style.display="none",docEl("arrayMax").textContent=gmrObj.vocaList.length,grabNewQ(),gmrObj.time=Date.now()):showEmpty(),renderNav(),handlersOn()}function userScored(scr){var score="completed: "+scr+"/"+scr,timeStamp=Date.now(),duration=timeStamp-gmrObj.time;postIt({a:timeStamp,b:gmrObj.tchr,c:gmrObj.clss,d:gmrObj.frag,e:duration,f:document.title,g:score})}function postIt(dataObj){var user=firebase.auth().currentUser,uid=user.uid,postData={email:user.email,timestamp:dataObj.a,tchr:dataObj.b,clss:dataObj.c,frag:dataObj.d,duration:dataObj.e,activity:dataObj.f,score:dataObj.g},newPostKey,updates={};updates["activities/"+uid+"/"+firebase.database().ref().child("activities/"+uid+"/").push().key]=postData,firebase.database().ref().update(updates,(function(e){e?"PERMISSION_DENIED"===e.code?signOutOfApp():window.alert("Data could not be saved.\n"+e):window.alert("Activity completed!")}))}firebase.auth().onAuthStateChanged((function(user){user?(docEl("usrPhoto").src=user.photoURL,init()):window.location="../index.html"}))}()})); | 4,778 | 4,778 | 0.761825 |
437e3ae0e13ff63af6f56e40f69922d07ffe40a9 | 2,218 | js | JavaScript | containers/collection-delete-button/index.js | desterds/gamesvault | fa6b7e4fd0693cb96e4cd23c5c02fae4f8b0a95d | [
"MIT"
] | 1 | 2021-07-30T15:06:41.000Z | 2021-07-30T15:06:41.000Z | containers/collection-delete-button/index.js | desterds/gamesvault | fa6b7e4fd0693cb96e4cd23c5c02fae4f8b0a95d | [
"MIT"
] | 1 | 2021-08-02T20:05:51.000Z | 2021-08-02T20:06:01.000Z | containers/collection-delete-button/index.js | desterds/gamesvault | fa6b7e4fd0693cb96e4cd23c5c02fae4f8b0a95d | [
"MIT"
] | 1 | 2021-08-20T22:54:01.000Z | 2021-08-20T22:54:01.000Z | import { useState } from 'react';
import PropTypes from 'prop-types';
import { CgTrash } from 'react-icons/cg';
import {
useDeleteCollectionMutation,
useInvalidateCollectionsQuery,
} from 'hooks/api/db';
import Button from 'components/button';
import RichText from 'components/rich-text';
import Modal from 'components/modal';
import styles from './style.module.css';
function CollectionDeleteButton({ threadId, name, onSuccess, onError }) {
const [showModal, setShowModal] = useState(false);
const open = () => setShowModal(true);
const close = () => setShowModal(false);
const invalidate = useInvalidateCollectionsQuery();
const mutation = useDeleteCollectionMutation({
threadId,
name,
config: {
onSuccess: (data) => {
invalidate();
onSuccess(data);
close();
},
onError: (data) => {
onError(data);
},
},
});
return (
<>
<Button onClick={open}>
<CgTrash />
<span>Delete</span>
</Button>
<Modal
title="Delete DB"
aria-label="delete-team-modal"
status="danger"
onDismiss={close}
isOpen={showModal}
>
<RichText className={styles['delete-collection-button-modal-message']}>
<p>
Are you sure you want to delete the collection
<strong>{name}</strong>?
</p>
<p>
This action <strong>cannot</strong> be undone.
</p>
</RichText>
<div className={styles['delete-collection-button-modal-actions']}>
<Button onClick={close}>Cancel</Button>
<Button
status="danger"
loading={mutation.isLoading}
disabled={mutation.isLoading}
onClick={mutation.mutate}
>
<CgTrash />
<span>Delete</span>
</Button>
</div>
</Modal>
</>
);
}
CollectionDeleteButton.propTypes = {
threadId: PropTypes.string.isRequired,
name: PropTypes.string.isRequired,
onSuccess: PropTypes.func,
onError: PropTypes.func,
};
CollectionDeleteButton.defaultProps = {
onSuccess: () => {},
onError: () => {},
};
export default CollectionDeleteButton;
| 25.494253 | 79 | 0.592876 |
437e3e6410c6a151c1ab03fb86bf1243b4a3962c | 2,449 | js | JavaScript | Chapter07/ecomm-ui/src/api/CartClient.js | Abiel7/Modern-API-Development-with-Spring-and-Spring-Boot | 6911ccd38a10654cb0048486c96bd30bbb842a1c | [
"MIT"
] | 71 | 2021-01-14T23:26:01.000Z | 2022-03-30T04:39:00.000Z | Chapter07/ecomm-ui/src/api/CartClient.js | Abiel7/Modern-API-Development-with-Spring-and-Spring-Boot | 6911ccd38a10654cb0048486c96bd30bbb842a1c | [
"MIT"
] | 2 | 2021-09-08T18:33:11.000Z | 2022-02-01T07:20:25.000Z | Chapter07/ecomm-ui/src/api/CartClient.js | Abiel7/Modern-API-Development-with-Spring-and-Spring-Boot | 6911ccd38a10654cb0048486c96bd30bbb842a1c | [
"MIT"
] | 65 | 2021-05-17T13:04:47.000Z | 2022-03-27T01:28:44.000Z | import Config from "./Config";
export default class CartClient {
auth;
constructor(auth) {
this.auth = auth;
this.config = new Config();
}
async fetch() {
if (this.config.tokenExpired()) {
await this.auth.refreshToken();
}
return fetch(this.config.CART_URL + "/" + this.auth.token.userId, {
method: "GET",
mode: "cors",
headers: {
...this.config.headersWithAuthorization(),
},
})
.then((response) => Promise.all([response, response.json()]))
.then(([response, json]) => {
console.log("Response JSON: " + JSON.stringify(json));
if (!response.ok) {
return { success: false, error: json };
}
return { success: true, data: json };
})
.catch((e) => {
this.handleError(e);
});
}
async addOrUpdate(payload) {
if (this.config.tokenExpired()) {
await this.auth.refreshToken();
}
return fetch(
this.config.CART_URL + "/" + this.auth.token.userId + "/items",
{
method: "PUT",
mode: "cors",
headers: {
...this.config.headersWithAuthorization(),
},
body: JSON.stringify(payload),
}
)
.then((response) => Promise.all([response, response.json()]))
.then(([response, json]) => {
console.log("Response JSON: " + JSON.stringify(json));
if (!response.ok) {
return { success: false, error: json };
}
return { success: true, data: json };
})
.catch((e) => {
this.handleError(e);
});
}
async remove(itemId) {
if (this.config.tokenExpired()) {
await this.auth.refreshToken();
}
return fetch(
this.config.CART_URL + "/" + this.auth.token.userId + "/items/" + itemId,
{
method: "DELETE",
mode: "cors",
headers: {
...this.config.headersWithAuthorization(),
},
}
)
.then((response) => {
if (!response.ok) {
return { success: false };
}
return { success: true };
})
.catch((e) => {
this.handleError(e);
});
}
handleError(error) {
const err = new Map([
[TypeError, "There was a problem fetching the response."],
[SyntaxError, "There was a problem parsing the response."],
[Error, error.message],
]).get(error.constructor);
console.log(err);
return err;
}
}
| 25.247423 | 79 | 0.523479 |
437e7c18f276fcaae890068b2980c1d508acdcc8 | 1,822 | js | JavaScript | database-mysql/database.js | mjraybk07/mjraybk07Service | 9cb35f50c1b222a3d21288b9b502c99893dfc6b4 | [
"MIT"
] | 1 | 2019-04-17T19:53:39.000Z | 2019-04-17T19:53:39.000Z | database-mysql/database.js | mjraybk07/mjraybk07Service | 9cb35f50c1b222a3d21288b9b502c99893dfc6b4 | [
"MIT"
] | null | null | null | database-mysql/database.js | mjraybk07/mjraybk07Service | 9cb35f50c1b222a3d21288b9b502c99893dfc6b4 | [
"MIT"
] | null | null | null |
const knex = require('knex')(require('../knexfile'));
const getAccountOverviewById = (accountId, callback) => {
console.log(`Getting account overview by account id ${accountId}`);
return knex.select().from('accountOverviews').whereRaw(`account_id=${accountId}`)
.then ( (accountOverview) => {
callback(null, accountOverview)
})
.catch( (err) => {
callback(err, null)
})
}
const getAccountById = (accountId, callback) => {
console.log(`Getting account by account id ${accountId}`);
return knex.select().from('accounts').whereRaw(`id=${accountId}`)
.then ( (account) => {
callback(null, account)
})
.catch( (err) => {
callback(err, null)
})
}
const getCasesByAccountId = (accountId, callback) => {
console.log(`Getting cases by account id ${accountId}`);
return knex.select().from('cases').whereRaw(`account_id=${accountId}`)
.then ( (cases) => {
callback(null, cases)
})
.catch( (err) => {
callback(err, null)
})
}
const getUsersByAccountId = (accountId, callback) => {
console.log(`Getting users by account id ${accountId}`);
return knex.select().from('users').whereRaw(`account_id=${accountId}`)
.then ( (users) => {
callback(null, users)
})
.catch( (err) => {
callback(err, null)
})
}
const getMessagesByUserId = (userId, callback) => {
console.log(`Getting messages by user id ${userId}`);
return knex.select().from('messages').whereRaw(`user_id=${userId}`)
.then ( (messages) => {
callback(null, messages)
})
.catch( (err) => {
callback(err, null)
})
}
module.exports = {
// getAllAccountOverviews,
// saveAccountOverview,
// getAllAccountIds,
getAccountById,
getCasesByAccountId,
getUsersByAccountId,
// getMessagesByAccountId,
getMessagesByUserId,
getAccountOverviewById
}; | 23.662338 | 83 | 0.645993 |
437ed3c93e54130650237a50dc24559e1efcbe24 | 14,333 | js | JavaScript | htdocs/libs/dojo/dojox/sketch/Figure.js | henry-gobiernoabierto/geomoose | a8031be68ef1dccf0c1588143afc5712b125acdb | [
"MIT"
] | 24 | 2015-01-24T14:49:22.000Z | 2022-02-23T18:16:21.000Z | training-web/src/main/webapp/js/dojotoolkit/dojox/sketch/Figure.js | sulistionoadi/belajar-springmvc-dojo | ac68fddb26bf8076bfa09b2f192170ff3ea3122b | [
"Apache-2.0"
] | 36 | 2015-04-21T12:20:57.000Z | 2018-06-21T09:49:53.000Z | training-web/src/main/webapp/js/dojotoolkit/dojox/sketch/Figure.js | sulistionoadi/belajar-springmvc-dojo | ac68fddb26bf8076bfa09b2f192170ff3ea3122b | [
"Apache-2.0"
] | 27 | 2015-01-02T09:34:03.000Z | 2018-06-11T11:12:35.000Z | dojo.provide("dojox.sketch.Figure");
dojo.experimental("dojox.sketch");
dojo.require("dojox.gfx");
dojo.require("dojox.sketch.UndoStack");
(function(){
var ta=dojox.sketch;
ta.tools={};
ta.registerTool=function(type, fn){ ta.tools[type]=fn; };
ta.Figure = function(mixin){
var self=this;
this.annCounter=1;
this.shapes=[];
this.image=null;
this.imageSrc=null;
this.size={ w:0, h:0 };
this.surface=null;
this.group=null;
//node should have tabindex set, otherwise keyboard action does not work
this.node=null;
this.zoomFactor=1; // multiplier for zooming.
this.tools=null; // toolbar reference.
this.obj={}; // lookup table for shapes. Not keen on this solution.
dojo.mixin(this,mixin);
// what is selected.
this.selected=[];
this.hasSelections=function(){ return this.selected.length>0 };
this.isSelected=function(obj){
for(var i=0; i<self.selected.length; i++){
if(self.selected[i]==obj){ return true; }
}
return false;
};
this.select=function(obj){
// TODO: deal with multiple vs. single selections.
if(!self.isSelected(obj)){
// force single select
self.clearSelections();
self.selected=[ obj ];
}
// force a bbox update, regardless
obj.setMode(ta.Annotation.Modes.View);
obj.setMode(ta.Annotation.Modes.Edit);
};
this.deselect=function(obj){
var idx=-1;
for(var i=0; i<self.selected.length; i++){
if(self.selected[i]==obj){
idx=i;
break;
}
}
if(idx>-1){
obj.setMode(ta.Annotation.Modes.View);
self.selected.splice(idx,1);
}
return obj;
};
this.clearSelections=function(){
for(var i=0; i<self.selected.length; i++){
self.selected[i].setMode(ta.Annotation.Modes.View);
}
self.selected=[];
};
this.replaceSelection=function(n, o){
if(!self.isSelected(o)){
self.select(n);
return;
}
var idx=-1;
for(var i=0; i<self.selected.length; i++){
if(self.selected[i]==o){
idx=i;
break;
}
}
if(idx>-1){
self.selected.splice(idx,1,n);
}
};
// for the drag and drop handlers.
this._c=null; // current shape
this._ctr=null; // container measurements
this._lp=null; // last position
this._action=null;
this._prevState=null;
this._startPoint=null; // test to record a move.
// if an object isn't selected and we're dragging anyways.
this._ctool=null; // hard code it.
this._start=null;
this._end=null;
this._absEnd=null;
this._cshape=null;
this._dblclick=function(e){
var o=self._fromEvt(e);
if(o){
self.onDblClickShape(o,e);
}
};
this._keydown=function(e){
var prevent=false;
if(e.ctrlKey){
if(e.keyCode===90 || e.keyCode===122){ //ctrl+z
self.undo();
prevent = true;
}
else if(e.keyCode===89 || e.keyCode===121){ //ctrl+y
self.redo();
prevent = true;
}
}
if(e.keyCode===46 || e.keyCode===8){ //delete or backspace
self._delete(self.selected);
prevent = true;
}
if(prevent){
dojo.stopEvent(e);
}
};
// drag handlers.
this._md=function(e){
//in IE, when clicking into the drawing canvas, the node does not get focused,
//do it manually here to force it, otherwise the keydown event listener is
//never triggered in IE.
if(dojox.gfx.renderer=='vml'){
self.node.focus();
}
var o=self._fromEvt(e);
self._startPoint={ x:e.pageX, y:e.pageY };
self._ctr=dojo.position(self.node);
// figure out the coordinates taking scroll into account
var scroll={x:self.node.scrollLeft,y:self.node.scrollTop};
//var win = dojo.window.get(self.node.ownerDocument);
//var scroll=dojo.withGlobal(win,dojo._docScroll);
self._ctr={x:self._ctr.x-scroll.x, y:self._ctr.y-scroll.y};
var X=e.clientX-self._ctr.x, Y=e.clientY-self._ctr.y;
self._lp={ x:X, y:Y };
// capture it separately
self._start={ x:X, y:Y };
self._end={ x:X, y:Y };
self._absEnd={ x:X, y:Y };
if(!o){
self.clearSelections();
self._ctool.onMouseDown(e);
}else{
if(o.type && o.type()!="Anchor"){
if(!self.isSelected(o)){
self.select(o);
self._sameShapeSelected=false;
}else{
self._sameShapeSelected=true;
}
}
o.beginEdit();
self._c=o;
}
};
this._mm=function(e){
if(!self._ctr){ return; }
var x=e.clientX-self._ctr.x;
var y=e.clientY-self._ctr.y;
var dx=x-self._lp.x;
var dy=y-self._lp.y;
self._absEnd={x:x, y:y};
if(self._c){
//self._c.doChange({dx:dx, dy:dy});
self._c.setBinding({dx:dx/self.zoomFactor, dy:dy/self.zoomFactor});
self._lp={x:x, y:y};
} else {
self._end={x:dx, y:dy};
var rect={
x:Math.min(self._start.x,self._absEnd.x),
y:Math.min(self._start.y,self._absEnd.y),
width:Math.abs(self._start.x-self._absEnd.x),
height:Math.abs(self._start.y-self._absEnd.y)
}
if(rect.width && rect.height){
self._ctool.onMouseMove(e,rect);
}
}
};
this._mu=function(e){
if(self._c){
// record the event.
self._c.endEdit();
}else{
self._ctool.onMouseUp(e);
}
// clear the stuff out.
self._c=self._ctr=self._lp=self._action=self._prevState=self._startPoint=null;
self._cshape=self._start=self._end=self._absEnd=null;
};
this.initUndoStack();
};
var p=ta.Figure.prototype;
p.initUndoStack=function(){
this.history=new ta.UndoStack(this);
};
p.setTool=function(/*dojox.sketch._Plugin*/t){
this._ctool=t;
};
//gridSize: int
// if it is greater than 0, all new shapes placed on the drawing will have coordinates
// snapped to the gridSize. For example, if gridSize is set to 10, all coordinates
// (only including coordinates which specifies the x/y position of shape are affected
// by this parameter) will be dividable by 10
p.gridSize=0;
p._calCol=function(v){
return this.gridSize?(Math.round(v/this.gridSize)*this.gridSize):v;
};
p._delete=function(arr,noundo){
for(var i=0; i<arr.length; i++){
//var before=arr[i].serialize();
arr[i].setMode(ta.Annotation.Modes.View);
arr[i].destroy(noundo);
this.remove(arr[i]);
this._remove(arr[i]);
if(!noundo){
arr[i].onRemove();
}
}
arr.splice(0,arr.length);
};
p.onDblClickShape=function(shape,e){
if(shape['onDblClick']){
shape.onDblClick(e);
}
};
p.onCreateShape=function(shape){};
p.onBeforeCreateShape=function(shape){};
p.initialize=function(node){
this.node=node;
this.surface=dojox.gfx.createSurface(node, this.size.w, this.size.h);
//this.backgroundRect=this.surface.createRect({ x:0, y:0, width:this.size.w, height:this.size.h })
// .setFill("white");
this.group=this.surface.createGroup();
this._cons=[];
var es=this.surface.getEventSource();
this._cons.push(
// kill any dragging events.
// for FF
dojo.connect(es, "ondraggesture", dojo.stopEvent),
dojo.connect(es, "ondragenter", dojo.stopEvent),
dojo.connect(es, "ondragover", dojo.stopEvent),
dojo.connect(es, "ondragexit", dojo.stopEvent),
dojo.connect(es, "ondragstart", dojo.stopEvent),
// for IE
dojo.connect(es, "onselectstart", dojo.stopEvent),
// hook up the drag system.
dojo.connect(es, 'onmousedown', this._md),
dojo.connect(es, 'onmousemove', this._mm),
dojo.connect(es, 'onmouseup', this._mu),
// misc hooks
dojo.connect(es, 'onclick', this, 'onClick'),
dojo.connect(es, 'ondblclick', this._dblclick),
dojo.connect(node, 'onkeydown', this._keydown));
this.image=this.group.createImage({ width:this.imageSize.w, height:this.imageSize.h, src:this.imageSrc });
};
p.destroy=function(isLoading){
if(!this.node){ return; }
if(!isLoading){
if(this.history){ this.history.destroy(); }
if(this._subscribed){
dojo.unsubscribe(this._subscribed);
delete this._subscribed;
}
}
dojo.forEach(this._cons, dojo.disconnect);
this._cons=[];
//TODO: how to destroy a surface properly?
dojo.empty(this.node);
//this.node.removeChild(this.surface.getEventSource());
this.group=this.surface=null;
this.obj={};
this.shapes=[];
};
p.nextKey=function(){ return "annotation-"+this.annCounter++; };
p.draw=function(){ };
p.zoom=function(pct){
// first get the new dimensions
this.zoomFactor=pct/100;
var w=this.size.w*this.zoomFactor;
var h=this.size.h*this.zoomFactor;
this.surface.setDimensions(w, h);
// then scale it.
this.group.setTransform(dojox.gfx.matrix.scale(this.zoomFactor, this.zoomFactor));
for(var i=0; i<this.shapes.length; i++){
this.shapes[i].zoom(this.zoomFactor);
}
};
p.getFit=function(){
// assume fitting the parent node.
// var box=dojo.html.getContentBox(this.node.parentNode);
//the following should work under IE and FF, not sure about others though
var wF=(this.node.parentNode.offsetWidth-5)/this.size.w;
var hF=(this.node.parentNode.offsetHeight-5)/this.size.h;
return Math.min(wF, hF)*100;
};
p.unzoom=function(){
// restore original size.
this.zoomFactor=1;
this.surface.setDimensions(this.size.w, this.size.h);
this.group.setTransform();
};
// object registry for drag handling.
p._add=function(obj){ this.obj[obj._key]=obj; };
p._remove=function(obj){
if(this.obj[obj._key]){
delete this.obj[obj._key];
}
};
p._get=function(key){
if(key&&key.indexOf("bounding")>-1){
key=key.replace("-boundingBox","");
}else if(key&&key.indexOf("-labelShape")>-1){
key=key.replace("-labelShape","");
}
return this.obj[key];
};
p._keyFromEvt=function(e){
var key=e.target.id+"";
if(key.length==0){
// ancestor tree until you get to the end (meaning this.surface)
var p=e.target.parentNode;
var node=this.surface.getEventSource();
while(p && p.id.length==0 && p!=node){
p=p.parentNode;
}
key=p.id;
}
return key;
};
p._fromEvt=function(e){
return this._get(this._keyFromEvt(e));
};
p.add=function(annotation){
for(var i=0; i<this.shapes.length; i++){
if(this.shapes[i]==annotation){ return true; }
}
this.shapes.push(annotation);
return true;
};
p.remove=function(annotation){
var idx=-1;
for(var i=0; i<this.shapes.length; i++){
if(this.shapes[i]==annotation){
idx=i;
break;
}
}
if(idx>-1){ this.shapes.splice(idx, 1); }
return annotation;
};
p.getAnnotator=function(id){
for(var i=0; i<this.shapes.length; i++){
if(this.shapes[i].id==id) {
return this.shapes[i];
}
}
return null;
};
p.convert=function(ann, t){
// convert an existing annotation to a different kind of annotation
var ctor=t+"Annotation";
if(!ta[ctor]){ return; }
var type=ann.type(), id=ann.id, label=ann.label, mode=ann.mode, tokenId=ann.tokenId;
var start, end, control, transform;
switch(type){
case "Preexisting":
case "Lead":{
transform={dx:ann.transform.dx, dy:ann.transform.dy };
start={x:ann.start.x, y:ann.start.y};
end={x:ann.end.x, y:ann.end.y };
var cx=end.x-((end.x-start.x)/2);
var cy=end.y-((end.y-start.y)/2);
control={x:cx, y:cy};
break;
}
case "SingleArrow":
case "DoubleArrow":{
transform={dx:ann.transform.dx, dy:ann.transform.dy };
start={x:ann.start.x, y:ann.start.y};
end={x:ann.end.x, y:ann.end.y };
control={x:ann.control.x, y:ann.control.y};
break;
}
case "Underline":{
transform={dx:ann.transform.dx, dy:ann.transform.dy };
start={x:ann.start.x, y:ann.start.y};
control={x:start.x+50, y:start.y+50 };
end={x:start.x+100, y:start.y+100 };
break;
}
case "Brace":{ }
}
var n=new ta[ctor](this, id);
if(n.type()=="Underline"){
// special handling, since we never move the start point.
n.transform={dx:transform.dx+start.x, dy:transform.dy+start.y };
} else {
if(n.transform){ n.transform=transform; }
if(n.start){ n.start=start; }
}
if(n.end){ n.end=end; }
if(n.control){ n.control=control; }
n.label=label;
n.token=dojo.lang.shallowCopy(ann.token);
n.initialize();
this.replaceSelection(n, ann);
this._remove(ann);
this.remove(ann);
ann.destroy();
// this should do all the things we need it to do for getting it registered.
n.setMode(mode);
};
p.setValue=function(text){
var obj=dojox.xml.DomParser.parse(text);
var node=this.node;
this.load(obj,node);
//this.zoom(this.zoomFactor*100); //zoom to orignal scale
};
p.load=function(obj, n){
// create from pseudo-DOM
if(this.surface){ this.destroy(true); }
var node=obj.documentElement; // should be either the document or the docElement
this.size={
w:parseFloat(node.getAttribute('width'),10),
h:parseFloat(node.getAttribute('height'),10)
};
var g=node.childrenByName("g")[0];
var img=g.childrenByName("image")[0];
this.imageSize={
w:parseFloat(img.getAttribute('width'),10),
h:parseFloat(img.getAttribute('height'),10)
};
this.imageSrc=img.getAttribute("xlink:href");
this.initialize(n);
// now let's do the annotations.
var ann=g.childrenByName("g");
for(var i=0; i<ann.length; i++){ this._loadAnnotation(ann[i]); }
if(this._loadDeferred){
this._loadDeferred.callback(this);
this._loadDeferred=null;
}
this.onLoad();
};
p.onLoad=function(){};
p.onClick=function(){};
p._loadAnnotation=function(obj){
var ctor=obj.getAttribute('dojoxsketch:type')+"Annotation";
if(ta[ctor]){
var a=new ta[ctor](this, obj.id);
a.initialize(obj);
this.nextKey();
a.setMode(ta.Annotation.Modes.View);
this._add(a);
return a;
}
return null;
};
p.onUndo=function(){};
p.onBeforeUndo=function(){};
p.onRedo=function(){};
p.onBeforeRedo=function(){};
p.undo=function(){
if(this.history){
this.onBeforeUndo();
this.history.undo();
this.onUndo();
}
};
p.redo=function(){
if(this.history){
this.onBeforeRedo();
this.history.redo();
this.onRedo();
}
};
p.serialize=function(){
var s='<svg xmlns="http://www.w3.org/2000/svg" '
+ 'xmlns:xlink="http://www.w3.org/1999/xlink" '
+ 'xmlns:dojoxsketch="http://dojotoolkit.org/dojox/sketch" '
+ 'width="' + this.size.w + '" height="' + this.size.h + '">'
+ '<g>'
+ '<image xlink:href="' + this.imageSrc + '" x="0" y="0" width="'
+ this.size.w + '" height="' + this.size.h + '" />';
for(var i=0; i<this.shapes.length; i++){ s+= this.shapes[i].serialize(); }
s += '</g></svg>';
return s;
};
p.getValue=p.serialize;
})();
| 27.197343 | 108 | 0.640899 |
437f776a7ea2bcdfe688cd48f7cf85897ace523c | 5,151 | js | JavaScript | ilc/server/tailor/request-fragment.js | tgarlanger/ilc | f6d2c238da7478c969889c36756bad304f8be0fd | [
"Apache-2.0"
] | null | null | null | ilc/server/tailor/request-fragment.js | tgarlanger/ilc | f6d2c238da7478c969889c36756bad304f8be0fd | [
"Apache-2.0"
] | null | null | null | ilc/server/tailor/request-fragment.js | tgarlanger/ilc | f6d2c238da7478c969889c36756bad304f8be0fd | [
"Apache-2.0"
] | null | null | null | 'use strict';
const http = require('http');
const https = require('https');
const url = require('url');
const Agent = require('agentkeepalive');
const HttpsAgent = require('agentkeepalive').HttpsAgent;
const deepmerge = require('deepmerge');
// By default tailor supports gzipped response from fragments
const requiredHeaders = {
'accept-encoding': 'gzip, deflate'
};
const kaAgent = new Agent();
const kaAgentHttps = new HttpsAgent();
/**
* Simple Request Promise Function that requests the fragment server with
* - filtered headers
* - Specified timeout from fragment attributes
*
* @param {filterHeaders} - Function that handles the header forwarding
* @param {processFragmentResponse} - Function that handles response processing
* @param {string} fragmentUrl - URL of the fragment server
* @param {Object} attributes - Attributes passed via fragment tags
* @param {Object} request - HTTP request stream
* @returns {Promise} Response from the fragment server
*/
module.exports = (filterHeaders, processFragmentResponse) => function requestFragment(
fragmentUrl,
attributes,
request
) {
return new Promise((resolve, reject) => {
const currRoute = request.router.getRoute();
if (attributes.wrapperConf) {
const wrapperConf = attributes.wrapperConf;
const reqUrl = makeFragmentUrl(currRoute, wrapperConf.src, wrapperConf.appId, wrapperConf.props);
const fragmentRequest = makeRequest(
reqUrl,
{...filterHeaders(attributes, request), ...requiredHeaders},
wrapperConf.timeout,
attributes.ignoreInvalidSsl,
);
fragmentRequest.on('response', response => {
try {
// Wrapper says that we need to request wrapped application
if (response.statusCode === 210) {
const propsOverride = response.headers['x-props-override'];
attributes.wrapperPropsOverride = {};
if (propsOverride) {
const props = JSON.parse(Buffer.from(propsOverride, 'base64').toString('utf8'));
attributes.appProps = deepmerge(attributes.appProps, props);
attributes.wrapperPropsOverride = props;
}
attributes.wrapperConf = null;
resolve(requestFragment(fragmentUrl, attributes, request));
return;
}
resolve(
processFragmentResponse(response, {
request,
fragmentUrl: reqUrl,
fragmentAttributes: attributes,
isWrapper: true,
})
);
} catch (e) {
reject(e);
}
});
fragmentRequest.on('error', reject);
fragmentRequest.end();
} else {
const reqUrl = makeFragmentUrl(currRoute, fragmentUrl, attributes.id, attributes.appProps);
const fragmentRequest = makeRequest(
reqUrl,
{...filterHeaders(attributes, request), ...requiredHeaders},
attributes.timeout,
attributes.ignoreInvalidSsl,
);
fragmentRequest.on('response', response => {
try {
resolve(
processFragmentResponse(response, {
request,
fragmentUrl: reqUrl,
fragmentAttributes: attributes,
})
);
} catch (e) {
reject(e);
}
});
fragmentRequest.on('error', reject);
fragmentRequest.end();
}
});
}
function makeFragmentUrl(route, baseUrl, appId, props) {
const url = new URL(baseUrl);
const reqProps = {
basePath: route.basePath,
reqUrl: route.reqUrl,
fragmentName: appId,
};
url.searchParams.append('routerProps', Buffer.from(JSON.stringify(reqProps)).toString('base64'));
if (props) {
url.searchParams.append('appProps', Buffer.from(JSON.stringify(props)).toString('base64'));
}
return url.toString();
}
function makeRequest(reqUrl, headers, timeout, ignoreInvalidSsl = false) {
const options = {
headers,
timeout,
...url.parse(reqUrl)
};
const { protocol: reqProtocol } = options;
const hasHttpsProtocol = reqProtocol === 'https:';
const protocol = hasHttpsProtocol ? https : http;
options.agent = hasHttpsProtocol ? kaAgentHttps : kaAgent;
if (hasHttpsProtocol && ignoreInvalidSsl) {
options.rejectUnauthorized = false;
}
const fragmentRequest = protocol.request(options);
if (timeout) {
fragmentRequest.setTimeout(timeout, fragmentRequest.abort);
}
return fragmentRequest;
}
| 33.888158 | 109 | 0.56028 |
4381316a152fb8d1e4194cbf0dfe2ae30ae95672 | 907 | js | JavaScript | src/math/Cylindrical.js | qiaotaizi/sandi | 73ff8dd427f7845958064962ea9aa1cf53a8774d | [
"BSD-2-Clause"
] | null | null | null | src/math/Cylindrical.js | qiaotaizi/sandi | 73ff8dd427f7845958064962ea9aa1cf53a8774d | [
"BSD-2-Clause"
] | 2 | 2022-01-27T16:05:25.000Z | 2022-03-25T18:43:43.000Z | src/math/Cylindrical.js | qiaotaizi/sandi | 73ff8dd427f7845958064962ea9aa1cf53a8774d | [
"BSD-2-Clause"
] | null | null | null | "use strict";
Object.defineProperty(exports, "__esModule", { value: true });
class Cylindrical {
constructor(radius = 1.0, theta = 0, y = 0) {
this.radius = radius;
this.theta = theta;
this.y = y;
}
clone() {
return new Cylindrical().copy(this);
}
copy(other) {
this.radius = other.radius;
this.theta = other.theta;
this.y = other.y;
return this;
}
set(radius, theta, y) {
this.radius = radius;
this.theta = theta;
this.y = y;
return this;
}
setFromVector3(v) {
return this.setFromCartesianCoords(v.x, v.y, v.z);
}
setFromCartesianCoords(x, y, z) {
this.radius = Math.sqrt(x * x + z * z);
this.theta = Math.atan2(x, z);
this.y = y;
return this;
}
}
exports.Cylindrical = Cylindrical;
//# sourceMappingURL=Cylindrical.js.map | 25.914286 | 62 | 0.545755 |
4382984952bdf3f5569727bd78b58ab16bac8c61 | 545 | js | JavaScript | icons/earth_remove.js | darosh/material-icons-bundle | 3dd1cc534b011fc4fe78e9d71ef919a62096033f | [
"MIT"
] | 11 | 2017-11-02T18:14:44.000Z | 2022-02-08T07:22:44.000Z | icons/earth_remove.js | darosh/material-icons-bundle | 3dd1cc534b011fc4fe78e9d71ef919a62096033f | [
"MIT"
] | 1 | 2021-03-02T15:17:09.000Z | 2021-03-02T15:17:09.000Z | icons/earth_remove.js | darosh/material-icons-bundle | 3dd1cc534b011fc4fe78e9d71ef919a62096033f | [
"MIT"
] | 1 | 2020-03-12T10:40:22.000Z | 2020-03-12T10:40:22.000Z | export default "M14.46 15.88L15.88 14.46L18 16.59L20.12 14.47L21.54 15.88L19.41 18L21.54 20.12L20.12 21.54L18 19.41L15.88 21.54L14.46 20.12L16.59 18L14.47 15.88M20 12C20 8.64 17.93 5.77 15 4.59V5C15 6.1 14.1 7 13 7H11V9C11 9.55 10.55 10 10 10H8V12H14C14.5 12 14.9 12.35 15 12.81C13.2 13.85 12 15.79 12 18C12 19.5 12.54 20.85 13.44 21.9L12 22C6.5 22 2 17.5 2 12C2 6.5 6.5 2 12 2C17.5 2 22 6.5 22 12L21.9 13.44C21.34 12.96 20.7 12.59 20 12.34L20 12M11 19.93V18C9.9 18 9 17.1 9 16V15L4.21 10.21C4.08 10.78 4 11.38 4 12C4 16.08 7.06 19.44 11 19.93Z" | 545 | 545 | 0.715596 |
438351e0e6b62ed634bf57075befdad48631a683 | 1,206 | js | JavaScript | client/src/common/components/Player/Player.js | zamronypj/envision-spootify | ca54fd90e37cbf9a14c6e352eadd0a0b46490224 | [
"MIT"
] | null | null | null | client/src/common/components/Player/Player.js | zamronypj/envision-spootify | ca54fd90e37cbf9a14c6e352eadd0a0b46490224 | [
"MIT"
] | null | null | null | client/src/common/components/Player/Player.js | zamronypj/envision-spootify | ca54fd90e37cbf9a14c6e352eadd0a0b46490224 | [
"MIT"
] | null | null | null | import React from 'react';
import { FontAwesomeIcon } from '@fortawesome/react-fontawesome';
import {
faStepForward,
faPlayCircle,
faStepBackward,
faEllipsisH
} from '@fortawesome/free-solid-svg-icons';
import { faHeart } from '@fortawesome/free-solid-svg-icons';
import { faRandom } from '@fortawesome/free-solid-svg-icons';
import { faRetweet } from '@fortawesome/free-solid-svg-icons';
import { faVolumeDown } from '@fortawesome/free-solid-svg-icons';
import './_player.scss';
export default function Player() {
return (
<div className="player">
<div className="player__album">
<span />
<p>Nothing's playing</p>
</div>
<div className="player__controls">
<FontAwesomeIcon icon={faStepBackward} />
<FontAwesomeIcon icon={faPlayCircle} />
<FontAwesomeIcon icon={faStepForward} />
</div>
<div className="player__seekbar" />
<div className="player__actions">
<FontAwesomeIcon icon={faEllipsisH} />
<FontAwesomeIcon icon={faHeart} />
<FontAwesomeIcon icon={faRandom} />
<FontAwesomeIcon icon={faRetweet} />
<FontAwesomeIcon icon={faVolumeDown} />
</div>
</div>
);
}
| 31.736842 | 65 | 0.658375 |
438355b3cd4f769ea2d9a41fd13e3ee81843da5e | 38 | js | JavaScript | packages/1978/02/06/index.js | antonmedv/year | ae5d8524f58eaad481c2ba599389c7a9a38c0819 | [
"MIT"
] | 7 | 2017-07-03T19:53:01.000Z | 2021-04-05T18:15:55.000Z | packages/1978/02/06/index.js | antonmedv/year | ae5d8524f58eaad481c2ba599389c7a9a38c0819 | [
"MIT"
] | 1 | 2018-09-05T11:53:41.000Z | 2018-12-16T12:36:21.000Z | packages/1978/02/06/index.js | antonmedv/year | ae5d8524f58eaad481c2ba599389c7a9a38c0819 | [
"MIT"
] | 2 | 2019-01-27T16:57:34.000Z | 2020-10-11T09:30:25.000Z | module.exports = new Date(1978, 1, 6)
| 19 | 37 | 0.684211 |
4383ad66654d713f76a25b42df53bc128c9769fb | 143 | js | JavaScript | src/lib/statistics/region/config.js | Sherif-Embarak/gp-test | d19141a45f471c839af87bc4e298c921b7af8460 | [
"MIT"
] | null | null | null | src/lib/statistics/region/config.js | Sherif-Embarak/gp-test | d19141a45f471c839af87bc4e298c921b7af8460 | [
"MIT"
] | null | null | null | src/lib/statistics/region/config.js | Sherif-Embarak/gp-test | d19141a45f471c839af87bc4e298c921b7af8460 | [
"MIT"
] | null | null | null | // Generated by CoffeeScript 1.10.0
(function() {
var config;
config = function() {};
}).call(this);
//# sourceMappingURL=config.js.map
| 14.3 | 35 | 0.65035 |
4383ba94f50b1faf37069c06687be4ecb08cf1b3 | 4,810 | js | JavaScript | src/pages/speakers/john.js | iboss-ptk/uxth | 37c09ad1bc7b11b5906944f6e711c2735b48700e | [
"MIT"
] | null | null | null | src/pages/speakers/john.js | iboss-ptk/uxth | 37c09ad1bc7b11b5906944f6e711c2735b48700e | [
"MIT"
] | null | null | null | src/pages/speakers/john.js | iboss-ptk/uxth | 37c09ad1bc7b11b5906944f6e711c2735b48700e | [
"MIT"
] | null | null | null | import React from 'react'
import {
Topic, Content, BlueContent, ListWrapper, ListItem
} from '../../components/SpeakerPage'
import SpeakerPage from '../../components/SpeakerPage'
export default () => (
<SpeakerPage
header={{
firstName: 'JOHN',
lastName: 'CUTLER',
subtitle: (
<>
is a <bold> Product Evangelist at Amplitude </bold> and prolific writer on product management and UX
</>
),
}}
imagePath="/images/speakers/spk_JohnCutler.svg"
contents={{
talk: (
<>
<Topic>Continuous Design - How Not To Exchange Waterfalls for Whirlpools</Topic>
<Content>
Have we exchanged waterfalls for whirlpools? Are we sprinting—faster and faster—to nowhere In particular? Is “how do you do UX with Agile“ perhaps the wrong question?
<br />
<br />
Design has always been about iteration, subtraction, addition, experimentation, and observation. That process defines who we are as designers. With manufacturing, there was the point-of-no-return, the date our design was “finalised“ and something got sent off to the manufacturer (or press). With software as a service (SaaS), however, we have no such constraints. We don’t need to operate feature factories, yet somehow we often do. So, let’s fix that!
<br />
<br />
In this talk, we are going to get into the nitty-gritty of treating product development as an act of continuous design; not Agile. We’ll draw on design traditions, and explore how they heavily overlap with how we are able to work with our teams. And we’ll consider a reality where products and features are temporary solutions to long-standing problems (and what that means for design).
</Content>
</>
),
workshop: (
<>
<Topic>Making Sense of Product Development (For Designers and Product Managers)
</Topic>
<Content>
Software product development involves grappling with uncertainty. We do this every day when we focus, prioritize, break work down, and plan how we’ll introduce the product. Without this uncertainty, we wouldn’t have new and novel products to offer.
<br />
<br />
During this workshop, John will teach you a number of valuable tools and practices to make sense of your product development effort including tools for:
<br />
<br />
<ListWrapper>
<ListItem>
Prioritization
</ListItem>
<ListItem>
Breaking down work while preserving the “big picture”
</ListItem>
<ListItem>
Surfacing assumptions
</ListItem>
<ListItem>
Establishing a design-friendly North Star Metric to guide your product development efforts
</ListItem>
<ListItem>
Linking near-term work to long-term business value
</ListItem>
</ListWrapper>
</Content>
</>
),
biography: (
<>
<Topic>About John</Topic>
<Content>
John Cutler is keenly focused on user experience and evidence-driven product development. He mixes and matches various methodologies — jobs-to-be-done, Lean UX, Lean Startup, customer development, and design thinking — to help teams deliver lasting outcomes for their customers.
<br />
<br />
John is currently working as a product evangelist at Amplitude As a former UX researcher at AppFolio, a product manager at Zendesk, Pendo.io, AdKeeper and RichFX, a startup founder, and a product team coach, John has a perspective that spans individual roles, domains, and products.
<br />
<br />
His viral enthusiasm has been heard through speaking/teaching engagements at Front, Oredev, Mind The Product, Agile 2015, Heart of Agile Philadelphia (2016), and various ProductCamps (Vancouver, Los Angeles, Raleigh NC) and MeetUps (Santa Barbara, Los Angeles, New York). John’s talk on Feature Factories was voted one of the Top 10 Product Talks of 2017. In 2018,
<br />
<br />
Mixing in some less-than-typical experiences — driving rickshaws in NYC, and touring the US with “five other weird creative people in a van playing music” — John blogs prolifically about collaboration, product development, diversity, UX research, lean startup, and user experience. Some notable posts include The Evolving Product Manager Role, Persona(s) Non Grata, 12 Signs You’re Working in a Feature Factory, and Stop Setting Up Product Roadmaps To Fail.
</Content>
</>
),
}}
/>
)
| 50.104167 | 469 | 0.648233 |
4383d6dd07c9e9bd4af26f3a0729b509f735e192 | 2,763 | js | JavaScript | day3/src/apps/LeadsBuilder/pages/NewCampaign.js | floringhinita/react-training | c52f21e689c0edb7be0bef85ff9b280e5b86b0b9 | [
"Apache-2.0"
] | null | null | null | day3/src/apps/LeadsBuilder/pages/NewCampaign.js | floringhinita/react-training | c52f21e689c0edb7be0bef85ff9b280e5b86b0b9 | [
"Apache-2.0"
] | null | null | null | day3/src/apps/LeadsBuilder/pages/NewCampaign.js | floringhinita/react-training | c52f21e689c0edb7be0bef85ff9b280e5b86b0b9 | [
"Apache-2.0"
] | null | null | null | import React from "react";
import TextField from "@material-ui/core/TextField";
import Paper from "@material-ui/core/Paper";
import FormControl from "@material-ui/core/FormControl";
import InputLabel from "@material-ui/core/InputLabel";
import NativeSelect from "@material-ui/core/NativeSelect";
import Button from "@material-ui/core/Button";
import {useFormStyles} from "../styles/styles";
import Grid from "@material-ui/core/Grid";
const NewCampaign = () => {
const classes = useFormStyles();
const handleOnSave = () => {}
return (
<Paper className={classes.root} elevation={3}>
<Grid container spacing={3}>
<Grid item xs={12} sm={12}>
<TextField
fullWidth
id="campaignName"
label="Name"
placeholder="Enter campaign name"
margin="normal"
style={{ margin: 8 }}
InputLabelProps={{
shrink: true,
}}
/>
</Grid>
<Grid item xs={12} sm={6}>
<FormControl fullWidth>
<InputLabel shrink htmlFor="campaignType">
Type
</InputLabel>
<NativeSelect
onChange={() => {}}
inputProps={{
name: 'campaignType',
id: 'campaignType',
}}
>
<option value="">None</option>
<option value={10}>Ten</option>
<option value={20}>Twenty</option>
<option value={30}>Thirty</option>
</NativeSelect>
</FormControl>
</Grid>
<Grid item xs={12} sm={6}>
<TextField
fullWidth
id="test"
label="Test"
placeholder="Test"
margin="normal"
style={{ margin: 8 }}
InputLabelProps={{
shrink: true,
}}
/>
</Grid>
</Grid>
<div className={classes.buttons}>
<Button variant="contained" color="primary" className={classes.button} onClick={handleOnSave}>
Save
</Button>
</div>
</Paper>
)
}
export default NewCampaign
| 36.84 | 110 | 0.40608 |
438401496d8fe1d2795470da45d256a0721a1295 | 827 | js | JavaScript | src/renderer/icons/BigSpinner.js | https-github-com-ruzyysmartt/lld-v2 | b35cf0bc6c15a288bb9e70bcb9b0c64428aed97f | [
"MIT"
] | 1 | 2020-01-12T09:43:33.000Z | 2020-01-12T09:43:33.000Z | src/renderer/icons/BigSpinner.js | https-github-com-ruzyysmartt/lld-v2 | b35cf0bc6c15a288bb9e70bcb9b0c64428aed97f | [
"MIT"
] | null | null | null | src/renderer/icons/BigSpinner.js | https-github-com-ruzyysmartt/lld-v2 | b35cf0bc6c15a288bb9e70bcb9b0c64428aed97f | [
"MIT"
] | null | null | null | // @flow
import React from "react";
const BigSpinner = ({ size = 44 }: { size: number }) => (
<svg width={size} height={size} viewBox="0 0 44 44" fill="none">
<path
d="M41.85 24.437a20 20 0 10-2.926 8.22"
stroke="url(#prefix__paint0_angular)"
strokeWidth={4}
strokeLinecap="round"
strokeLinejoin="round"
/>
<defs>
<radialGradient
id="prefix__paint0_angular"
cx={0}
cy={0}
r={1}
gradientUnits="userSpaceOnUse"
gradientTransform="rotate(25.346 -37.918 59.918) scale(22.1303)"
>
<stop stopColor="#F6F7F8" stopOpacity={0} />
<stop offset={0.063} stopColor="#F6F7F8" stopOpacity={0} />
<stop offset={1} stopColor="#A1A8AD" />
</radialGradient>
</defs>
</svg>
);
export default BigSpinner;
| 25.84375 | 72 | 0.575574 |
43848ef84d270364bd7aebe004e8059ec0f60195 | 1,339 | js | JavaScript | client/src/redux/feed/feedReducer.js | ThaiSonNguyenTl/Datn-IntarClone | dd103e200881db8e7dcce8def05b405b76c38635 | [
"Apache-2.0"
] | 503 | 2020-06-14T06:55:41.000Z | 2022-03-28T11:40:11.000Z | client/src/redux/feed/feedReducer.js | ThaiSonNguyenTl/Datn-IntarClone | dd103e200881db8e7dcce8def05b405b76c38635 | [
"Apache-2.0"
] | 12 | 2020-07-12T16:42:43.000Z | 2021-12-06T10:22:02.000Z | client/src/redux/feed/feedReducer.js | ThaiSonNguyenTl/Datn-IntarClone | dd103e200881db8e7dcce8def05b405b76c38635 | [
"Apache-2.0"
] | 127 | 2020-06-19T06:56:37.000Z | 2022-03-10T16:07:09.000Z | import feedTypes from './feedTypes';
const INITIAL_STATE = {
posts: [],
fetching: true,
error: false,
hasMore: false,
};
const feedReducer = (state = INITIAL_STATE, action) => {
switch (action.type) {
case feedTypes.FETCH_POSTS_START: {
return {
...state,
fetching: true,
error: false,
};
}
case feedTypes.FETCH_POSTS_SUCCESS: {
return {
...state,
fetching: false,
error: false,
posts: [...state.posts, ...action.payload],
hasMore: action.payload.length === 5,
};
}
case feedTypes.FETCH_POSTS_FAILURE: {
return {
...state,
fetching: false,
error: action.payload,
};
}
case feedTypes.ADD_POST: {
return {
...state,
posts: [action.payload, ...state.posts],
};
}
case feedTypes.REMOVE_POST: {
const posts = JSON.parse(JSON.stringify(state.posts));
const postIndex = posts.findIndex((post) => post._id === action.payload);
if (postIndex) {
posts.splice(postIndex, 1);
}
return {
...state,
posts,
};
}
case feedTypes.CLEAR_POSTS: {
return {
...state,
posts: [],
};
}
default: {
return state;
}
}
};
export default feedReducer;
| 20.6 | 79 | 0.528006 |
43849e63ee673491b917b8d94ed1b1c5b833014e | 189 | js | JavaScript | src/copy/sw.js | xiong-ang/squoosh | 2082245729fc14b375714d649acc849731406bda | [
"Apache-2.0"
] | 15,872 | 2018-03-08T06:04:03.000Z | 2022-03-31T20:17:19.000Z | src/copy/sw.js | xiong-ang/squoosh | 2082245729fc14b375714d649acc849731406bda | [
"Apache-2.0"
] | 835 | 2018-03-26T10:01:36.000Z | 2022-03-22T08:08:36.000Z | src/copy/sw.js | xiong-ang/squoosh | 2082245729fc14b375714d649acc849731406bda | [
"Apache-2.0"
] | 1,261 | 2018-04-28T20:46:29.000Z | 2022-03-30T02:05:30.000Z | // I accidentally shipped with the wrong service worker name.
// This picks up users that still might be using that version.
// We'll be able to delete this file eventually.
skipWaiting();
| 37.8 | 62 | 0.761905 |
4384d37ce7d85121156e30a9a60c96fa7cca5974 | 2,073 | js | JavaScript | cells/mcells/js/rowline.js | beaugogh/visual-mining | 403e8c2da9abb744c577cffa0abfc34892b5850e | [
"MIT"
] | null | null | null | cells/mcells/js/rowline.js | beaugogh/visual-mining | 403e8c2da9abb744c577cffa0abfc34892b5850e | [
"MIT"
] | 1 | 2020-08-11T07:54:52.000Z | 2020-08-11T07:54:52.000Z | cells/mcells/js/rowline.js | beaugogh/visualmining | 403e8c2da9abb744c577cffa0abfc34892b5850e | [
"MIT"
] | 1 | 2020-04-27T12:51:38.000Z | 2020-04-27T12:51:38.000Z | Rowline = {
vis: '',
id: '',
index: -1,
x: 0,
y: 0,
w: 0,
h: 1,
min_h: 1,
margin: 1,
rect: '',
fill_color: 'black',
fill_opacity: .1,
stroke_color: 'none',
init: function(vis, index, y) {
this.vis = vis;
this.id = 'rowline_'+index;
this.index = index;
this.y = y;
this.x += this.margin;
this.w = vis.width;
this.h = 6;
var row_drag = d3.behavior.drag().origin(Object)
.on('dragstart', this.on_row_drag_start)
.on('drag',this.on_row_drag);
this.rect = this.vis.g.append('rect')
.datum(this)
.attr('id', this.id)
.attr('x',this.x)
.attr('y',this.y)
.attr('width',this.w)
.attr('height',this.h)
.attr("cursor", "ns-resize")
.style('fill', this.fill_color)
.style('fill-opacity', this.fill_opacity)
.style('stroke', this.stroke_color)
.call(row_drag);
},
on_row_drag_start: function() {
d3.event.sourceEvent.stopPropagation();
mcells.prev_y = d3.mouse(this)[1];
},
on_row_drag: function(d) { //console.log('row drag');
if(d.index > 0) {
var coords = d3.mouse(this);
mcells.mouse_coords = coords;
var prev_rl = d.vis.rowlines[d.index-1];
var y_limit = prev_rl.y+prev_rl.h+prev_rl.min_h;
var y_target = coords[1] - d.h/2;
if(y_target > y_limit) {
var shift = y_target - d.rect.attr('y');
d.y = y_target;
d.rect.attr('y',d.y);
for(var i=d.index+1; i<d.vis.rowlines.length; i++) {
var rl = d.vis.rowlines[i];
var cur_y = +rl.y;
rl.y = cur_y + shift;
rl.rect.attr('y', rl.y);
}//for
var n = d.vis.rowlines.length-1;
var bottom_y = d.vis.rowlines[n].y;
d.vis.svg.attr('height', bottom_y+30);
//update sections
for (var i = d.index-1; i < d.vis.rowlines.length-1; i++) {
var rltop = d.vis.rowlines[i];
var rlbottom = d.vis.rowlines[i+1];
var x = rltop.x;
var y = rltop.y+rltop.h;
var w = rltop.w;
var h = rlbottom.y - y;
var sect = d.vis.sections[i];
sect.update_position(x,y,w,h);
};
}//if
mcells.prev_y = coords[1];
}//if
}//on_row_drag
} | 25.9125 | 63 | 0.580801 |
438558f4c98fa76ea16856d15615dbe481998909 | 907 | js | JavaScript | src/models/Entities/Enums/AssetSource.js | calebsandfort/isupportmobile | 1ddd111ca29e87541806ea000b59d69972f03f9e | [
"Apache-2.0"
] | null | null | null | src/models/Entities/Enums/AssetSource.js | calebsandfort/isupportmobile | 1ddd111ca29e87541806ea000b59d69972f03f9e | [
"Apache-2.0"
] | null | null | null | src/models/Entities/Enums/AssetSource.js | calebsandfort/isupportmobile | 1ddd111ca29e87541806ea000b59d69972f03f9e | [
"Apache-2.0"
] | null | null | null | /******************************************************************************
* THIS FILE IS GENERATED ANY CHANGES WILL BE LOST NEXT TIME CODE IS GENERATED *
******************************************************************************/
import {Enum} from './enumify';
class AssetSource extends Enum {}
AssetSource.initEnum([
['DirectEntry', 'Direct Entry', 1],
['AutoAssetCreate', 'Auto Asset Create', 2],
['RDBSync', 'RDB Synchronization', 3],
['Integration', 'Integration', 4],
['MobileDesktop', 'Mobile Desktop', 5],
['LDAP', 'LDAP', 6],
['ActiveDirectory', 'Active Directory', 7],
['Import', 'Import', 8],
]);
export default AssetSource;
/******************************************************************************
* THIS FILE IS GENERATED ANY CHANGES WILL BE LOST NEXT TIME CODE IS GENERATED *
******************************************************************************/
| 36.28 | 79 | 0.438809 |
4385c1431f3c174237a0d69b7baa0fc0ba459d7d | 23 | js | JavaScript | projects/Box2D/EditShape/Assets/meta/soundDuration.js | oneseedfruit/qiciengine-examples | 725faff2217e806b1b2e91699bee902714f26e2e | [
"MIT"
] | 1 | 2019-04-29T15:08:42.000Z | 2019-04-29T15:08:42.000Z | projects/Box2D/EditShape/Assets/meta/soundDuration.js | oneseedfruit/qiciengine-examples | 725faff2217e806b1b2e91699bee902714f26e2e | [
"MIT"
] | null | null | null | projects/Box2D/EditShape/Assets/meta/soundDuration.js | oneseedfruit/qiciengine-examples | 725faff2217e806b1b2e91699bee902714f26e2e | [
"MIT"
] | null | null | null | soundDurationMap = {};
| 11.5 | 22 | 0.695652 |
4385e99b442e9fe82ad952e48150a0bd4e198395 | 1,465 | js | JavaScript | src/server/database/model.js | prototypefund/approxi | eb928a6985dabdffe70eb6b562db8f235def8267 | [
"Apache-2.0"
] | null | null | null | src/server/database/model.js | prototypefund/approxi | eb928a6985dabdffe70eb6b562db8f235def8267 | [
"Apache-2.0"
] | null | null | null | src/server/database/model.js | prototypefund/approxi | eb928a6985dabdffe70eb6b562db8f235def8267 | [
"Apache-2.0"
] | null | null | null | import mapValues from 'lodash/mapValues';
import pick from 'lodash/pick';
import Database from '.';
export default class Model {
#db;
#tableName;
lockProperty = '_lock';
hiddenProperties = [this.lockProperty];
#schema;
constructor(db, tableName, schema) {
if (!(db instanceof Database)) {
throw new TypeError('Database required');
}
this.#db = db;
if (typeof tableName !== 'string') {
throw new TypeError('Table name required');
}
this.#tableName = tableName;
if (typeof schema !== 'object') {
throw new TypeError('Schema required');
}
this.#schema = schema;
this._setUp();
}
// https://github.com/babel/babel-eslint/issues/749
// async #setUp() {
async _setUp() {
await this.#db.createTable(this.#tableName);
}
get defaultDoc() {
return mapValues(pick(this.#schema.properties, this.#schema.required), ({ default: d }) => d);
}
get(id) {
return this.#db.getDoc(this.#tableName, id, this.hiddenProperties);
}
insert(data) {
return this.#db.insertDoc(this.#tableName, { ...this.defaultDoc, ...data });
}
delete(id) {
this.#db.deleteDoc(this.#tableName, id);
}
update(id, callback) {
return this.#db.updateDocOptimistically(this.#tableName, id, callback, this.lockProperty, [...this.hiddenProperties]);
}
subscribe(callback) {
return this.#db.subscribeToTableChanges(this.#tableName, callback, [...this.hiddenProperties]);
}
}
| 25.258621 | 122 | 0.646416 |
43860e0dca0cca06be8d32a200bf3b7545bd7d3b | 4,541 | js | JavaScript | app/src/code-block.js | SaputraGo/blog-pwa | 439bac8f449957c5eb2bb2ea6fd413c29bed7b76 | [
"Apache-2.0"
] | null | null | null | app/src/code-block.js | SaputraGo/blog-pwa | 439bac8f449957c5eb2bb2ea6fd413c29bed7b76 | [
"Apache-2.0"
] | null | null | null | app/src/code-block.js | SaputraGo/blog-pwa | 439bac8f449957c5eb2bb2ea6fd413c29bed7b76 | [
"Apache-2.0"
] | null | null | null | import {LitElement, html, css} from 'lit-element';
import 'prismjs/prism.js';
class CodeBlock extends LitElement {
static get properties() {
return {
lang: {
type: String,
},
};
}
constructor() {
super();
this.lang = 'clike';
this.highlight = '';
}
async firstUpdated() {
await this.__loadLanguage();
const nodes = this.shadowRoot.querySelector('#code').assignedNodes();
let codeCombined = '';
for (let index = 0, len = nodes.length; index < len; ++index) {
codeCombined += nodes[index].nodeValue;
}
// strip the lead/end newlines so we don't look horrible
const codeClean = codeCombined.replace(/^\s+|\s+$/g, '');
const highlight = Prism.highlight(
codeClean,
Prism.languages[this.lang],
this.lang,
);
// Set to our styled block
this.shadowRoot.querySelector('#output').innerHTML = highlight;
}
async __loadLanguage() {
await __import(
`../node_modules/prismjs/components/prism-${this.lang}.min.js`,
);
}
static get styles() {
return css`
/**
* prism.js default theme for JavaScript, CSS and HTML
* Based on dabblet (http://dabblet.com)
* @author Lea Verou
*/
code[class*='language-'],
pre[class*='language-'] {
font-family: Consolas, Menlo, Monaco, 'Andale Mono WT', 'Andale Mono',
'Lucida Console', 'Lucida Sans Typewriter', 'DejaVu Sans Mono',
'Bitstream Vera Sans Mono', 'Liberation Mono', 'Nimbus Mono L',
'Courier New', Courier, monospace;
font-size: 16px;
line-height: 1.375;
direction: ltr;
text-align: left;
white-space: pre;
word-spacing: normal;
word-break: normal;
word-wrap: normal;
tab-size: 4;
hyphens: none;
background: #faf8f5;
color: #222222;
}
/* Code blocks */
pre[class*='language-'] {
padding: 1em;
margin: 0.5em 0;
overflow: auto;
}
@media print {
code[class*='language-'],
pre[class*='language-'] {
text-shadow: none;
}
}
:not(pre) > code[class*='language-'],
pre[class*='language-'] {
background: #f5f2f0;
}
/* Inline code */
:not(pre) > code[class*='language-'] {
padding: 0.1em;
border-radius: 0.3em;
white-space: normal;
}
pre[class*='language-']::-moz-selection,
pre[class*='language-'] ::-moz-selection,
code[class*='language-']::-moz-selection,
code[class*='language-'] ::-moz-selection {
text-shadow: none;
background: #b3d4fc;
}
pre[class*='language-']::selection,
pre[class*='language-'] ::selection,
code[class*='language-']::selection,
code[class*='language-'] ::selection {
text-shadow: none;
background: #b3d4fc;
}
.token.comment,
.token.prolog,
.token.doctype,
.token.cdata {
color: slategray;
}
.token.punctuation {
color: #999;
}
.namespace {
opacity: 0.7;
}
.token.property,
.token.tag,
.token.boolean,
.token.number,
.token.constant,
.token.symbol,
.token.deleted {
color: #905;
}
.token.selector,
.token.attr-name,
.token.string,
.token.char,
.token.builtin,
.token.inserted {
color: #690;
}
.token.operator,
.token.entity,
.token.url,
.language-css .token.string,
.style .token.string {
color: #9a6e3a;
background: hsla(0, 0%, 100%, 0.5);
}
.token.atrule,
.token.attr-value,
.token.keyword {
color: #07a;
}
.token.function,
.token.class-name {
color: #dd4a68;
}
.token.regex,
.token.important,
.token.variable {
color: #e90;
}
.token.important,
.token.bold {
font-weight: bold;
}
.token.italic {
font-style: italic;
}
.token.entity {
cursor: help;
}
pre {
padding: 0;
margin: 0;
}
#hide {
display: none !important;
}
`;
}
render() {
return html`
<pre class="language-base"><code id="output"></code></pre>
<div id="hide">
<slot id="code"></slot>
</div>
`;
}
}
customElements.define('code-block', CodeBlock);
| 21.62381 | 78 | 0.523233 |
4387bdf537b77cf46865beb784383bbafc8a79b2 | 7,141 | js | JavaScript | translator/Translator.js | wangjue666/js-interpreter | f5655770919410d564476e0dc5b695fcd9793bbb | [
"MIT"
] | null | null | null | translator/Translator.js | wangjue666/js-interpreter | f5655770919410d564476e0dc5b695fcd9793bbb | [
"MIT"
] | null | null | null | translator/Translator.js | wangjue666/js-interpreter | f5655770919410d564476e0dc5b695fcd9793bbb | [
"MIT"
] | null | null | null | const TAProgram = require('./TAProgram')
const SymbolTable = require('./symbol/SymbolTable')
const Token = require('../lexer/Token')
const TokenType = require('../lexer/TokenType')
const ParseException = require('../parser/util/ParseException')
const Expr = require('../parser/ast/Expr')
const TAInstruction = require('../translator/TAInstruction')
const TAInstructionType = require('../translator/TAInstructionType')
const ASTNodeTypes = require('../parser/ast/ASTNodeTypes')
class Translator {
translate(astNode) {
const program = new TAProgram()
const symbolTable = new SymbolTable()
for (const child of astNode.getChildren()) {
this.translateStmt(program, child, symbolTable)
}
program.setStaticSymbols(symbolTable)
return program
}
translateStmt(program, node, symbolTable) {
switch (node.getType()) {
case ASTNodeTypes.ASSIGN_STMT:
this.translateAssignStmt(program, node, symbolTable);
return;
case ASTNodeTypes.DECLARE_STMT:
this.translateDeclareStmt(program, node, symbolTable);
return;
case ASTNodeTypes.BLOCK:
this.translateBlock(program, node, symbolTable);
return;
case ASTNodeTypes.IF_STMT:
this.translateIfStmt(program, node, symbolTable);
return;
case ASTNodeTypes.FUNCTION_DECLARE_STMT:
this.translateFunctionDeclareStmt(program, node, symbolTable);
return;
case ASTNodeTypes.RETURN_STMT:
this.translateReturnStmt(program, node, symbolTable);
return;
case ASTNodeTypes.CALL_EXPR:
this.translateCallExpr(program, node, symbolTable);
return;
}
throw new Error("Translator not impl. for " + node.getType())
}
translateFunctionDeclareStmt(program, node, parent) {
const label = program.addLabel()
const symbolTable = new SymbolTable()
label.setArg2(node.getLexeme().getValue())
const args = node.getArgs()
parent.addChild(symbolTable)
symbolTable.createLabel(label.getArg1(), node.getLexeme())
for(const arg of args.getChildren()) {
symbolTable.createSymbolByLexeme(arg.getLexeme())
}
for(const child of node.getBlock().getChildren()) {
this.translateStmt(program, child, symbolTable)
}
}
translateCallExpr(program, node, symbolTable) {
// print()
const factor = node.getChild(0)
const returnValue = symbolTable.createVariable()
symbolTable.createVariable()
for(let i = 1; i < node.getChildren().length; i++) {
const expr = node.getChild(i)
const addr = this.translateExpr(program, expr, symbolTable)
program.add(new TAInstruction(TAInstructionType.PARAM, null ,null, addr, i-1))
}
const funcAddr = symbolTable.cloneFromSymbolTree(factor.getLexeme(), 0)
program.add(new TAInstruction(TAInstructionType.SP, null ,null, -symbolTable.localSize(), null))
program.add(new TAInstruction(TAInstructionType.CALL, null, null, funcAddr, null))
program.add(new TAInstruction(TAInstructionType.SP, null ,null, symbolTable.localSize(), null))
return returnValue
}
translateReturnStmt(program, node, symbolTable) {
const resultValue = this.translateExpr(program, node.getChild(0), symbolTable)
program.add(new TAInstruction(TAInstructionType.RETURN, null, null, resultValue, null))
}
translateBlock(program, node, parent) {
const symbolTable = new SymbolTable()
parent.addChild(symbolTable)
const parentOffset = symbolTable.createVariable()
parentOffset.setLexeme(new Token(TokenType.INTEGER, parent.localSize() + ""))
program.add(new TAInstruction(
TAInstructionType.SP,
null,
null,
-parent.localSize(),
null
))
for(const child of node.getChildren()) {
this.translateStmt(program, child, symbolTable)
}
program.add(new TAInstruction(
TAInstructionType.SP,
null,
null,
parent.localSize(),
null
))
}
translateIfStmt(program, node, symbolTable){
const expr = node.getExpr()
const exprAddr = this.translateExpr(program, expr, symbolTable)
const ifInstruction = new TAInstruction(TAInstructionType.IF,
null, null, exprAddr, null
)
program.add(ifInstruction)
this.translateBlock(program, node.getBlock(), symbolTable)
let gotoInstruction = null
if(node.getChild(2)) {
gotoInstruction = new TAInstruction(TAInstructionType.GOTO,
null, null, null, null
)
program.add(gotoInstruction)
const labelEndIf = program.addLabel()
ifInstruction.setArg2(labelEndIf.getArg1())
}
if(node.getElseBlock()) {
this.translateBlock(program, node.getElseBlock(), symbolTable)
} else if(node.getElseIfStmt()) {
this.translateIfStmt(program, node.getElseIfStmt(), symbolTable)
}
// if(expr) {... GOTO } else {...}
const labelEnd = program.addLabel()
if(node.getChild(2)) {
gotoInstruction.setArg1(labelEnd.getArg1())
} else {
ifInstruction.setArg2(labelEnd.getArg1())
}
}
translateDeclareStmt(program, node, symbolTable) {
const lexeme = node.getChild(0).getLexeme()
if (symbolTable.exists(lexeme)) {
throw new ParseException("Syntax Error, Identifier " + lexeme.getValue() + " is already defined.")
}
const assigned = symbolTable.createSymbolByLexeme(node.getChild(0).getLexeme())
const expr = node.getChild(1)
const addr = this.translateExpr(program, expr, symbolTable)
program.add(new TAInstruction(TAInstructionType.ASSIGN, assigned, "=", addr, null))
}
translateAssignStmt(program, node, symbolTable) {
const assigned = symbolTable.createSymbolByLexeme(node.getChild(0).getLexeme())
const expr = node.getChild(1)
const addr = this.translateExpr(program, expr, symbolTable)
program.add(new TAInstruction(TAInstructionType.ASSIGN, assigned, "=", addr, null))
}
/**
* Expr -> Expr1 op Expr2
* T: result = Expr1.addr op Expr2.addr
* Expr1 -> Factor
* T: Expr1.addr = symbolTable.find(factor)
*/
translateExpr(
program,
node,
symbolTable) {
if (node.isValueType()) {
const addr = symbolTable.createSymbolByLexeme(node.getLexeme())
node.setProp("addr", addr)
return addr
}
else if (node.getType() == ASTNodeTypes.CALL_EXPR) {
const addr = this.translateCallExpr(program, node, symbolTable)
node.setProp("addr", addr)
return addr
}
else if (node instanceof Expr) {
for (const child of node.getChildren()) {
this.translateExpr(program, child, symbolTable)
}
if (node.getProp("addr") == null) {
node.setProp("addr", symbolTable.createVariable())
}
const instruction = new TAInstruction(
TAInstructionType.ASSIGN,
node.getProp("addr"),
node.getLexeme().getValue(),
node.getChild(0).getProp("addr"),
node.getChild(1).getProp("addr")
)
program.add(instruction)
return instruction.getResult()
}
throw new Error("Unexpected node type :" + node.getType());
}
}
module.exports = Translator | 31.183406 | 104 | 0.678056 |
4389222aebb14f055f444db26fda59b7d9005bf6 | 28 | js | JavaScript | src/GroupPage/index.js | hswim/meeting-room | 9de7937e0d3405bc9e586031cf26b4f76dcc6a76 | [
"MIT"
] | null | null | null | src/GroupPage/index.js | hswim/meeting-room | 9de7937e0d3405bc9e586031cf26b4f76dcc6a76 | [
"MIT"
] | null | null | null | src/GroupPage/index.js | hswim/meeting-room | 9de7937e0d3405bc9e586031cf26b4f76dcc6a76 | [
"MIT"
] | null | null | null | export * from './GroupPage'; | 28 | 28 | 0.678571 |
4389a12e1f8ada8a9d9890d503129cec6d2c0ccf | 7,432 | js | JavaScript | docs/resources/sap/m/PopoverRenderer-dbg.js | edwin7/devtoberfest-2021-frontend-coding-challenge | 0063efb0e8225671c36d034879006d0d591be6cd | [
"Apache-2.0"
] | null | null | null | docs/resources/sap/m/PopoverRenderer-dbg.js | edwin7/devtoberfest-2021-frontend-coding-challenge | 0063efb0e8225671c36d034879006d0d591be6cd | [
"Apache-2.0"
] | null | null | null | docs/resources/sap/m/PopoverRenderer-dbg.js | edwin7/devtoberfest-2021-frontend-coding-challenge | 0063efb0e8225671c36d034879006d0d591be6cd | [
"Apache-2.0"
] | null | null | null | /*!
* OpenUI5
* (c) Copyright 2009-2021 SAP SE or an SAP affiliate company.
* Licensed under the Apache License, Version 2.0 - see LICENSE.txt.
*/
sap.ui.define([
'sap/ui/Device',
'sap/m/library',
"sap/ui/dom/getScrollbarSize"
],
function(Device, library, getScrollbarSize) {
"use strict";
// shortcut for sap.m.PlacementType
var PlacementType = library.PlacementType;
/**
* Popover renderer.
* @namespace
*/
var PopoverRenderer = {
apiVersion: 2
};
/**
* Renders the HTML for the given control, using the provided {@link sap.ui.core.RenderManager}.
*
* @param {sap.ui.core.RenderManager} rm The RenderManager that can be used for writing to the Render-Output-Buffer
* @param {sap.ui.core.Control} oControl An object representation of the control that should be rendered
*/
PopoverRenderer.render = function(oRm, oControl) {
oRm.openStart("div", oControl);
var aClassNames = this.generateRootClasses(oControl);
aClassNames.forEach(function(sClassName) {
oRm.class(sClassName);
});
if (!oControl.getHorizontalScrolling()) {
oRm.class("sapMPopoverHorScrollDisabled");
}
if (!oControl.getVerticalScrolling()) {
oRm.class("sapMPopoverVerScrollDisabled");
}
var sTooltip = oControl.getTooltip_AsString();
if (sTooltip) {
oRm.attr("title", sTooltip);
}
oRm.attr("tabindex", "-1")
.accessibilityState(oControl, oControl._getAccessibilityOptions()) // ARIA
.openEnd();
if (oControl.getResizable()) {
oRm.icon("sap-icon://resize-corner", ["sapMPopoverResizeHandle"], { "title" : ""});
}
this.renderContent(oRm, oControl);
oRm.close("div");
};
PopoverRenderer.isButtonFooter = function(footer) {
if (footer instanceof sap.m.Bar) {
var aContentLeft = footer.getContentLeft(),
aContentRight = footer.getContentRight(),
aContentMiddle = footer.getContentMiddle(),
bLeftEmpty = (!aContentLeft || aContentLeft.length === 0),
bRightEmpty = (!aContentRight || aContentRight.length === 0),
bMiddleTwoButtons = false;
if (aContentMiddle && aContentMiddle.length === 2) {
if ((aContentMiddle[0] instanceof sap.m.Button) && (aContentMiddle[1] instanceof sap.m.Button)) {
bMiddleTwoButtons = true;
}
}
return bLeftEmpty && bRightEmpty && bMiddleTwoButtons;
} else {
return false;
}
};
PopoverRenderer.renderContent = function(oRm, oControl) {
var oHeader = oControl._getAnyHeader(),
sId = oControl.getId(),
i = 0,
contents = oControl._getAllContent(),
oFooter = oControl.getFooter(),
oSubHeader = oControl.getSubHeader(),
sContentWidth = oControl.getContentWidth(),
sContentMinWidth = oControl.getContentMinWidth(),
sContentHeight = oControl.getContentHeight();
if (Device.system.desktop) {
// invisible element for cycling keyboard navigation
oRm.openStart("span", oControl.getId() + "-firstfe")
.class("sapMPopoverHiddenFocusable")
.attr("tabindex", "0")
.openEnd()
.close("span");
}
// Header
if (oHeader) {
oRm.openStart("header")
.class("sapMPopoverHeader")
.openEnd();
if (oHeader._applyContextClassFor) {
oHeader._applyContextClassFor("header");
}
oRm.renderControl(oHeader);
oRm.close("header");
}
// Sub header
if (oSubHeader) {
oRm.openStart("header")
.class("sapMPopoverSubHeader")
.openEnd();
if (oSubHeader._applyContextClassFor) {
oSubHeader._applyContextClassFor("subheader");
}
oRm.renderControl(oSubHeader);
oRm.close("header");
}
// content container
oRm.openStart("div", sId + "-cont");
if (sContentWidth) {
oRm.style("width", sContentWidth);
}
if (sContentMinWidth) {
oRm.style("min-width", sContentMinWidth);
}
if (sContentHeight) {
oRm.style("height", sContentHeight);
}
oRm.class("sapMPopoverCont");
// Note: If this property should become public in the future, the property will have to be set on a level
// that will encapsulate the header and the footer of the popover as well.
if (sap.ui.getCore().getConfiguration().getAccessibility()
&& oControl.getProperty("ariaRoleApplication")) {
oRm.attr("role", "application");
}
oRm.openEnd();
// scroll area
oRm.openStart("div", oControl.getId() + "-scroll")
.class("sapMPopoverScroll");
if (!oControl.getHorizontalScrolling()) {
oRm.style(sap.ui.getCore().getConfiguration().getRTL() ? "margin-left" : "margin-right", getScrollbarSize().width + "px");
}
oRm.openEnd();
for (i = 0; i < contents.length; i++) {
oRm.renderControl(contents[i]);
}
oRm.close("div"); // scroll area
oRm.close("div"); // content container
// Footer
if (oFooter) {
oRm.openStart("footer")
.class("sapMPopoverFooter");
if (this.isButtonFooter(oFooter)) {
oRm.class("sapMPopoverSpecialFooter");
}
oRm.openEnd();
if (oFooter._applyContextClassFor) {
oFooter._applyContextClassFor("footer");
oFooter.addStyleClass("sapMTBNoBorders");
}
oRm.renderControl(oFooter);
oRm.close("footer");
}
// Arrow
if (oControl.getShowArrow()) {
oRm.openStart("span", sId + "-arrow")
.class("sapMPopoverArr")
.openEnd()
.close("span"); // arrow tip
}
if (Device.system.desktop) {
//invisible element for desktop keyboard navigation
oRm.openStart("span", oControl.getId() + "-middlefe")
.class("sapMPopoverHiddenFocusable")
.attr("tabindex", "-1")
.openEnd()
.close("span");
// invisible element for desktop keyboard navigation
oRm.openStart("span", oControl.getId() + "-lastfe")
.class("sapMPopoverHiddenFocusable")
.attr("tabindex", "0")
.openEnd()
.close("span");
}
};
PopoverRenderer.generateRootClasses = function(oControl) {
var aClassNames = ["sapMPopover"],
oSubHeader = oControl.getSubHeader(),
oFooter = oControl.getFooter(),
bVerScrollable = oControl.getVerticalScrolling() && !oControl._forceDisableScrolling,
bHorScrollable = oControl.getHorizontalScrolling() && !oControl._forceDisableScrolling,
oHeaderControl = oControl._getAnyHeader();
if (oHeaderControl) {
aClassNames.push("sapMPopoverWithBar");
} else {
aClassNames.push("sapMPopoverWithoutBar");
}
if (oSubHeader) {
aClassNames.push("sapMPopoverWithSubHeader");
} else {
aClassNames.push("sapMPopoverWithoutSubHeader");
}
if (oControl._hasSingleNavContent()) {
aClassNames.push("sapMPopoverNav");
}
if (oControl._hasSinglePageContent()) {
aClassNames.push("sapMPopoverPage");
}
if (oFooter) {
aClassNames.push("sapMPopoverWithFooter");
} else {
aClassNames.push("sapMPopoverWithoutFooter");
}
if (oControl.getPlacement() === PlacementType.Top) {
aClassNames.push("sapMPopoverPlacedTop");
}
if (!bVerScrollable) {
aClassNames.push("sapMPopoverVerScrollDisabled");
}
if (!bHorScrollable) {
aClassNames.push("sapMPopoverHorScrollDisabled");
}
aClassNames.push("sapMPopup-CTX");
// Adds styles for compact mode
if (oControl._bSizeCompact) {
aClassNames.push("sapUiSizeCompact");
}
// add custom classes set by the application as well
return aClassNames.concat(oControl.aCustomStyleClasses);
};
return PopoverRenderer;
}, /* bExport= */ true); | 26.637993 | 126 | 0.662809 |
438a77291e2472e1436024a65fd08fab262684e3 | 1,044 | js | JavaScript | examples/context/multiple-contexts.js | pedabraham/es.reactjs.org | 3223550ef11502b35c48b877959c5f5ca6ab85f4 | [
"CC-BY-4.0"
] | 217 | 2019-01-31T01:04:19.000Z | 2022-02-26T00:29:11.000Z | examples/context/multiple-contexts.js | pedabraham/es.reactjs.org | 3223550ef11502b35c48b877959c5f5ca6ab85f4 | [
"CC-BY-4.0"
] | 453 | 2019-01-31T04:03:12.000Z | 2022-03-28T00:18:35.000Z | examples/context/multiple-contexts.js | pedabraham/es.reactjs.org | 3223550ef11502b35c48b877959c5f5ca6ab85f4 | [
"CC-BY-4.0"
] | 283 | 2019-01-31T02:00:10.000Z | 2022-03-26T21:21:10.000Z | // Theme context, default to light theme
const ThemeContext = React.createContext('light');
// Contexto de usuario registrado
const UserContext = React.createContext({
name: 'Guest',
});
class App extends React.Component {
render() {
const {signedInUser, theme} = this.props;
// Componente App que proporciona valores de contexto iniciales
// highlight-range{2-3,5-6}
return (
<ThemeContext.Provider value={theme}>
<UserContext.Provider value={signedInUser}>
<Layout />
</UserContext.Provider>
</ThemeContext.Provider>
);
}
}
function Layout() {
return (
<div>
<Sidebar />
<Content />
</div>
);
}
// Un componente puede consumir múltiples contextos.
function Content() {
// highlight-range{2-10}
return (
<ThemeContext.Consumer>
{theme => (
<UserContext.Consumer>
{user => (
<ProfilePage user={user} theme={theme} />
)}
</UserContext.Consumer>
)}
</ThemeContext.Consumer>
);
}
| 21.306122 | 67 | 0.605364 |
438a7e0f8fe15fd501e56ec0a5c27faf453cb590 | 61,177 | js | JavaScript | dist/engine.io.js | exsilium/engine.io-client | c874f69950578ce21b36917a551e6202c3aaf233 | [
"MIT"
] | null | null | null | dist/engine.io.js | exsilium/engine.io-client | c874f69950578ce21b36917a551e6202c3aaf233 | [
"MIT"
] | null | null | null | dist/engine.io.js | exsilium/engine.io-client | c874f69950578ce21b36917a551e6202c3aaf233 | [
"MIT"
] | null | null | null | /*!
* Engine.IO v6.1.0
* (c) 2014-2021 Guillermo Rauch
* Released under the MIT License.
*/
(function (global, factory) {
typeof exports === 'object' && typeof module !== 'undefined' ? module.exports = factory() :
typeof define === 'function' && define.amd ? define(factory) :
(global = typeof globalThis !== 'undefined' ? globalThis : global || self, global.eio = factory());
})(this, (function () { 'use strict';
function _typeof(obj) {
"@babel/helpers - typeof";
if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") {
_typeof = function (obj) {
return typeof obj;
};
} else {
_typeof = function (obj) {
return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj;
};
}
return _typeof(obj);
}
function _classCallCheck(instance, Constructor) {
if (!(instance instanceof Constructor)) {
throw new TypeError("Cannot call a class as a function");
}
}
function _defineProperties(target, props) {
for (var i = 0; i < props.length; i++) {
var descriptor = props[i];
descriptor.enumerable = descriptor.enumerable || false;
descriptor.configurable = true;
if ("value" in descriptor) descriptor.writable = true;
Object.defineProperty(target, descriptor.key, descriptor);
}
}
function _createClass(Constructor, protoProps, staticProps) {
if (protoProps) _defineProperties(Constructor.prototype, protoProps);
if (staticProps) _defineProperties(Constructor, staticProps);
return Constructor;
}
function _extends() {
_extends = Object.assign || function (target) {
for (var i = 1; i < arguments.length; i++) {
var source = arguments[i];
for (var key in source) {
if (Object.prototype.hasOwnProperty.call(source, key)) {
target[key] = source[key];
}
}
}
return target;
};
return _extends.apply(this, arguments);
}
function _inherits(subClass, superClass) {
if (typeof superClass !== "function" && superClass !== null) {
throw new TypeError("Super expression must either be null or a function");
}
subClass.prototype = Object.create(superClass && superClass.prototype, {
constructor: {
value: subClass,
writable: true,
configurable: true
}
});
if (superClass) _setPrototypeOf(subClass, superClass);
}
function _getPrototypeOf(o) {
_getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf : function _getPrototypeOf(o) {
return o.__proto__ || Object.getPrototypeOf(o);
};
return _getPrototypeOf(o);
}
function _setPrototypeOf(o, p) {
_setPrototypeOf = Object.setPrototypeOf || function _setPrototypeOf(o, p) {
o.__proto__ = p;
return o;
};
return _setPrototypeOf(o, p);
}
function _isNativeReflectConstruct() {
if (typeof Reflect === "undefined" || !Reflect.construct) return false;
if (Reflect.construct.sham) return false;
if (typeof Proxy === "function") return true;
try {
Date.prototype.toString.call(Reflect.construct(Date, [], function () {}));
return true;
} catch (e) {
return false;
}
}
function _assertThisInitialized(self) {
if (self === void 0) {
throw new ReferenceError("this hasn't been initialised - super() hasn't been called");
}
return self;
}
function _possibleConstructorReturn(self, call) {
if (call && (typeof call === "object" || typeof call === "function")) {
return call;
}
return _assertThisInitialized(self);
}
function _createSuper(Derived) {
var hasNativeReflectConstruct = _isNativeReflectConstruct();
return function _createSuperInternal() {
var Super = _getPrototypeOf(Derived),
result;
if (hasNativeReflectConstruct) {
var NewTarget = _getPrototypeOf(this).constructor;
result = Reflect.construct(Super, arguments, NewTarget);
} else {
result = Super.apply(this, arguments);
}
return _possibleConstructorReturn(this, result);
};
}
function _superPropBase(object, property) {
while (!Object.prototype.hasOwnProperty.call(object, property)) {
object = _getPrototypeOf(object);
if (object === null) break;
}
return object;
}
function _get(target, property, receiver) {
if (typeof Reflect !== "undefined" && Reflect.get) {
_get = Reflect.get;
} else {
_get = function _get(target, property, receiver) {
var base = _superPropBase(target, property);
if (!base) return;
var desc = Object.getOwnPropertyDescriptor(base, property);
if (desc.get) {
return desc.get.call(receiver);
}
return desc.value;
};
}
return _get(target, property, receiver || target);
}
var hasCors = {exports: {}};
/**
* Module exports.
*
* Logic borrowed from Modernizr:
*
* - https://github.com/Modernizr/Modernizr/blob/master/feature-detects/cors.js
*/
try {
hasCors.exports = typeof XMLHttpRequest !== 'undefined' && 'withCredentials' in new XMLHttpRequest();
} catch (err) {
// if XMLHttp support is disabled in IE then it will throw
// when trying to create
hasCors.exports = false;
}
var hasCORS = hasCors.exports;
var globalThis = (function () {
if (typeof self !== "undefined") {
return self;
} else if (typeof window !== "undefined") {
return window;
} else {
return Function("return this")();
}
})();
// browser shim for xmlhttprequest module
function XMLHttpRequest$1 (opts) {
var xdomain = opts.xdomain; // XMLHttpRequest can be disabled on IE
try {
if ("undefined" !== typeof XMLHttpRequest && (!xdomain || hasCORS)) {
return new XMLHttpRequest();
}
} catch (e) {}
if (!xdomain) {
try {
return new globalThis[["Active"].concat("Object").join("X")]("Microsoft.XMLHTTP");
} catch (e) {}
}
}
function pick(obj) {
for (var _len = arguments.length, attr = new Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) {
attr[_key - 1] = arguments[_key];
}
return attr.reduce(function (acc, k) {
if (obj.hasOwnProperty(k)) {
acc[k] = obj[k];
}
return acc;
}, {});
} // Keep a reference to the real timeout functions so they can be used when overridden
var NATIVE_SET_TIMEOUT = setTimeout;
var NATIVE_CLEAR_TIMEOUT = clearTimeout;
function installTimerFunctions(obj, opts) {
if (opts.useNativeTimers) {
obj.setTimeoutFn = NATIVE_SET_TIMEOUT.bind(globalThis);
obj.clearTimeoutFn = NATIVE_CLEAR_TIMEOUT.bind(globalThis);
} else {
obj.setTimeoutFn = setTimeout.bind(globalThis);
obj.clearTimeoutFn = clearTimeout.bind(globalThis);
}
}
/**
* Expose `Emitter`.
*/
var Emitter_1 = Emitter;
/**
* Initialize a new `Emitter`.
*
* @api public
*/
function Emitter(obj) {
if (obj) return mixin(obj);
}
/**
* Mixin the emitter properties.
*
* @param {Object} obj
* @return {Object}
* @api private
*/
function mixin(obj) {
for (var key in Emitter.prototype) {
obj[key] = Emitter.prototype[key];
}
return obj;
}
/**
* Listen on the given `event` with `fn`.
*
* @param {String} event
* @param {Function} fn
* @return {Emitter}
* @api public
*/
Emitter.prototype.on = Emitter.prototype.addEventListener = function (event, fn) {
this._callbacks = this._callbacks || {};
(this._callbacks['$' + event] = this._callbacks['$' + event] || []).push(fn);
return this;
};
/**
* Adds an `event` listener that will be invoked a single
* time then automatically removed.
*
* @param {String} event
* @param {Function} fn
* @return {Emitter}
* @api public
*/
Emitter.prototype.once = function (event, fn) {
function on() {
this.off(event, on);
fn.apply(this, arguments);
}
on.fn = fn;
this.on(event, on);
return this;
};
/**
* Remove the given callback for `event` or all
* registered callbacks.
*
* @param {String} event
* @param {Function} fn
* @return {Emitter}
* @api public
*/
Emitter.prototype.off = Emitter.prototype.removeListener = Emitter.prototype.removeAllListeners = Emitter.prototype.removeEventListener = function (event, fn) {
this._callbacks = this._callbacks || {}; // all
if (0 == arguments.length) {
this._callbacks = {};
return this;
} // specific event
var callbacks = this._callbacks['$' + event];
if (!callbacks) return this; // remove all handlers
if (1 == arguments.length) {
delete this._callbacks['$' + event];
return this;
} // remove specific handler
var cb;
for (var i = 0; i < callbacks.length; i++) {
cb = callbacks[i];
if (cb === fn || cb.fn === fn) {
callbacks.splice(i, 1);
break;
}
} // Remove event specific arrays for event types that no
// one is subscribed for to avoid memory leak.
if (callbacks.length === 0) {
delete this._callbacks['$' + event];
}
return this;
};
/**
* Emit `event` with the given args.
*
* @param {String} event
* @param {Mixed} ...
* @return {Emitter}
*/
Emitter.prototype.emit = function (event) {
this._callbacks = this._callbacks || {};
var args = new Array(arguments.length - 1),
callbacks = this._callbacks['$' + event];
for (var i = 1; i < arguments.length; i++) {
args[i - 1] = arguments[i];
}
if (callbacks) {
callbacks = callbacks.slice(0);
for (var i = 0, len = callbacks.length; i < len; ++i) {
callbacks[i].apply(this, args);
}
}
return this;
}; // alias used for reserved events (protected method)
Emitter.prototype.emitReserved = Emitter.prototype.emit;
/**
* Return array of callbacks for `event`.
*
* @param {String} event
* @return {Array}
* @api public
*/
Emitter.prototype.listeners = function (event) {
this._callbacks = this._callbacks || {};
return this._callbacks['$' + event] || [];
};
/**
* Check if this emitter has `event` handlers.
*
* @param {String} event
* @return {Boolean}
* @api public
*/
Emitter.prototype.hasListeners = function (event) {
return !!this.listeners(event).length;
};
var PACKET_TYPES = Object.create(null); // no Map = no polyfill
PACKET_TYPES["open"] = "0";
PACKET_TYPES["close"] = "1";
PACKET_TYPES["ping"] = "2";
PACKET_TYPES["pong"] = "3";
PACKET_TYPES["message"] = "4";
PACKET_TYPES["upgrade"] = "5";
PACKET_TYPES["noop"] = "6";
var PACKET_TYPES_REVERSE = Object.create(null);
Object.keys(PACKET_TYPES).forEach(function (key) {
PACKET_TYPES_REVERSE[PACKET_TYPES[key]] = key;
});
var ERROR_PACKET = {
type: "error",
data: "parser error"
};
var withNativeBlob = typeof Blob === "function" || typeof Blob !== "undefined" && Object.prototype.toString.call(Blob) === "[object BlobConstructor]";
var withNativeArrayBuffer$1 = typeof ArrayBuffer === "function"; // ArrayBuffer.isView method is not defined in IE10
var isView = function isView(obj) {
return typeof ArrayBuffer.isView === "function" ? ArrayBuffer.isView(obj) : obj && obj.buffer instanceof ArrayBuffer;
};
var encodePacket = function encodePacket(_ref, supportsBinary, callback) {
var type = _ref.type,
data = _ref.data;
if (withNativeBlob && data instanceof Blob) {
if (supportsBinary) {
return callback(data);
} else {
return encodeBlobAsBase64(data, callback);
}
} else if (withNativeArrayBuffer$1 && (data instanceof ArrayBuffer || isView(data))) {
if (supportsBinary) {
return callback(data);
} else {
return encodeBlobAsBase64(new Blob([data]), callback);
}
} // plain string
return callback(PACKET_TYPES[type] + (data || ""));
};
var encodeBlobAsBase64 = function encodeBlobAsBase64(data, callback) {
var fileReader = new FileReader();
fileReader.onload = function () {
var content = fileReader.result.split(",")[1];
callback("b" + content);
};
return fileReader.readAsDataURL(data);
};
/*
* base64-arraybuffer 1.0.1 <https://github.com/niklasvh/base64-arraybuffer>
* Copyright (c) 2021 Niklas von Hertzen <https://hertzen.com>
* Released under MIT License
*/
var chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/'; // Use a lookup table to find the index.
var lookup = typeof Uint8Array === 'undefined' ? [] : new Uint8Array(256);
for (var i$1 = 0; i$1 < chars.length; i$1++) {
lookup[chars.charCodeAt(i$1)] = i$1;
}
var decode$1 = function decode(base64) {
var bufferLength = base64.length * 0.75,
len = base64.length,
i,
p = 0,
encoded1,
encoded2,
encoded3,
encoded4;
if (base64[base64.length - 1] === '=') {
bufferLength--;
if (base64[base64.length - 2] === '=') {
bufferLength--;
}
}
var arraybuffer = new ArrayBuffer(bufferLength),
bytes = new Uint8Array(arraybuffer);
for (i = 0; i < len; i += 4) {
encoded1 = lookup[base64.charCodeAt(i)];
encoded2 = lookup[base64.charCodeAt(i + 1)];
encoded3 = lookup[base64.charCodeAt(i + 2)];
encoded4 = lookup[base64.charCodeAt(i + 3)];
bytes[p++] = encoded1 << 2 | encoded2 >> 4;
bytes[p++] = (encoded2 & 15) << 4 | encoded3 >> 2;
bytes[p++] = (encoded3 & 3) << 6 | encoded4 & 63;
}
return arraybuffer;
};
var withNativeArrayBuffer = typeof ArrayBuffer === "function";
var decodePacket = function decodePacket(encodedPacket, binaryType) {
if (typeof encodedPacket !== "string") {
return {
type: "message",
data: mapBinary(encodedPacket, binaryType)
};
}
var type = encodedPacket.charAt(0);
if (type === "b") {
return {
type: "message",
data: decodeBase64Packet(encodedPacket.substring(1), binaryType)
};
}
var packetType = PACKET_TYPES_REVERSE[type];
if (!packetType) {
return ERROR_PACKET;
}
return encodedPacket.length > 1 ? {
type: PACKET_TYPES_REVERSE[type],
data: encodedPacket.substring(1)
} : {
type: PACKET_TYPES_REVERSE[type]
};
};
var decodeBase64Packet = function decodeBase64Packet(data, binaryType) {
if (withNativeArrayBuffer) {
var decoded = decode$1(data);
return mapBinary(decoded, binaryType);
} else {
return {
base64: true,
data: data
}; // fallback for old browsers
}
};
var mapBinary = function mapBinary(data, binaryType) {
switch (binaryType) {
case "blob":
return data instanceof ArrayBuffer ? new Blob([data]) : data;
case "arraybuffer":
default:
return data;
// assuming the data is already an ArrayBuffer
}
};
var SEPARATOR = String.fromCharCode(30); // see https://en.wikipedia.org/wiki/Delimiter#ASCII_delimited_text
var encodePayload = function encodePayload(packets, callback) {
// some packets may be added to the array while encoding, so the initial length must be saved
var length = packets.length;
var encodedPackets = new Array(length);
var count = 0;
packets.forEach(function (packet, i) {
// force base64 encoding for binary packets
encodePacket(packet, false, function (encodedPacket) {
encodedPackets[i] = encodedPacket;
if (++count === length) {
callback(encodedPackets.join(SEPARATOR));
}
});
});
};
var decodePayload = function decodePayload(encodedPayload, binaryType) {
var encodedPackets = encodedPayload.split(SEPARATOR);
var packets = [];
for (var i = 0; i < encodedPackets.length; i++) {
var decodedPacket = decodePacket(encodedPackets[i], binaryType);
packets.push(decodedPacket);
if (decodedPacket.type === "error") {
break;
}
}
return packets;
};
var protocol = 4;
var Transport = /*#__PURE__*/function (_Emitter) {
_inherits(Transport, _Emitter);
var _super = _createSuper(Transport);
/**
* Transport abstract constructor.
*
* @param {Object} options.
* @api private
*/
function Transport(opts) {
var _this;
_classCallCheck(this, Transport);
_this = _super.call(this);
_this.writable = false;
installTimerFunctions(_assertThisInitialized(_this), opts);
_this.opts = opts;
_this.query = opts.query;
_this.readyState = "";
_this.socket = opts.socket;
return _this;
}
/**
* Emits an error.
*
* @param {String} str
* @return {Transport} for chaining
* @api protected
*/
_createClass(Transport, [{
key: "onError",
value: function onError(msg, desc) {
var err = new Error(msg); // @ts-ignore
err.type = "TransportError"; // @ts-ignore
err.description = desc;
_get(_getPrototypeOf(Transport.prototype), "emit", this).call(this, "error", err);
return this;
}
/**
* Opens the transport.
*
* @api public
*/
}, {
key: "open",
value: function open() {
if ("closed" === this.readyState || "" === this.readyState) {
this.readyState = "opening";
this.doOpen();
}
return this;
}
/**
* Closes the transport.
*
* @api public
*/
}, {
key: "close",
value: function close() {
if ("opening" === this.readyState || "open" === this.readyState) {
this.doClose();
this.onClose();
}
return this;
}
/**
* Sends multiple packets.
*
* @param {Array} packets
* @api public
*/
}, {
key: "send",
value: function send(packets) {
if ("open" === this.readyState) {
this.write(packets);
}
}
/**
* Called upon open
*
* @api protected
*/
}, {
key: "onOpen",
value: function onOpen() {
this.readyState = "open";
this.writable = true;
_get(_getPrototypeOf(Transport.prototype), "emit", this).call(this, "open");
}
/**
* Called with data.
*
* @param {String} data
* @api protected
*/
}, {
key: "onData",
value: function onData(data) {
var packet = decodePacket(data, this.socket.binaryType);
this.onPacket(packet);
}
/**
* Called with a decoded packet.
*
* @api protected
*/
}, {
key: "onPacket",
value: function onPacket(packet) {
_get(_getPrototypeOf(Transport.prototype), "emit", this).call(this, "packet", packet);
}
/**
* Called upon close.
*
* @api protected
*/
}, {
key: "onClose",
value: function onClose() {
this.readyState = "closed";
_get(_getPrototypeOf(Transport.prototype), "emit", this).call(this, "close");
}
}]);
return Transport;
}(Emitter_1);
var alphabet = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz-_'.split(''),
length = 64,
map = {},
seed = 0,
i = 0,
prev;
/**
* Return a string representing the specified number.
*
* @param {Number} num The number to convert.
* @returns {String} The string representation of the number.
* @api public
*/
function encode(num) {
var encoded = '';
do {
encoded = alphabet[num % length] + encoded;
num = Math.floor(num / length);
} while (num > 0);
return encoded;
}
/**
* Return the integer value specified by the given string.
*
* @param {String} str The string to convert.
* @returns {Number} The integer value represented by the string.
* @api public
*/
function decode(str) {
var decoded = 0;
for (i = 0; i < str.length; i++) {
decoded = decoded * length + map[str.charAt(i)];
}
return decoded;
}
/**
* Yeast: A tiny growing id generator.
*
* @returns {String} A unique id.
* @api public
*/
function yeast() {
var now = encode(+new Date());
if (now !== prev) return seed = 0, prev = now;
return now + '.' + encode(seed++);
} //
// Map each character to its index.
//
for (; i < length; i++) {
map[alphabet[i]] = i;
} //
// Expose the `yeast`, `encode` and `decode` functions.
//
yeast.encode = encode;
yeast.decode = decode;
var yeast_1 = yeast;
var parseqs = {};
/**
* Compiles a querystring
* Returns string representation of the object
*
* @param {Object}
* @api private
*/
parseqs.encode = function (obj) {
var str = '';
for (var i in obj) {
if (obj.hasOwnProperty(i)) {
if (str.length) str += '&';
str += encodeURIComponent(i) + '=' + encodeURIComponent(obj[i]);
}
}
return str;
};
/**
* Parses a simple querystring into an object
*
* @param {String} qs
* @api private
*/
parseqs.decode = function (qs) {
var qry = {};
var pairs = qs.split('&');
for (var i = 0, l = pairs.length; i < l; i++) {
var pair = pairs[i].split('=');
qry[decodeURIComponent(pair[0])] = decodeURIComponent(pair[1]);
}
return qry;
};
var Polling = /*#__PURE__*/function (_Transport) {
_inherits(Polling, _Transport);
var _super = _createSuper(Polling);
function Polling() {
var _this;
_classCallCheck(this, Polling);
_this = _super.apply(this, arguments);
_this.polling = false;
return _this;
}
/**
* Transport name.
*/
_createClass(Polling, [{
key: "doOpen",
/**
* Opens the socket (triggers polling). We write a PING message to determine
* when the transport is open.
*
* @api private
*/
value: function doOpen() {
this.poll();
}
/**
* Pauses polling.
*
* @param {Function} callback upon buffers are flushed and transport is paused
* @api private
*/
}, {
key: "pause",
value: function pause(onPause) {
var _this2 = this;
this.readyState = "pausing";
var pause = function pause() {
_this2.readyState = "paused";
onPause();
};
if (this.polling || !this.writable) {
var total = 0;
if (this.polling) {
total++;
this.once("pollComplete", function () {
--total || pause();
});
}
if (!this.writable) {
total++;
this.once("drain", function () {
--total || pause();
});
}
} else {
pause();
}
}
/**
* Starts polling cycle.
*
* @api public
*/
}, {
key: "poll",
value: function poll() {
this.polling = true;
this.doPoll();
this.emit("poll");
}
/**
* Overloads onData to detect payloads.
*
* @api private
*/
}, {
key: "onData",
value: function onData(data) {
var _this3 = this;
var callback = function callback(packet) {
// if its the first message we consider the transport open
if ("opening" === _this3.readyState && packet.type === "open") {
_this3.onOpen();
} // if its a close packet, we close the ongoing requests
if ("close" === packet.type) {
_this3.onClose();
return false;
} // otherwise bypass onData and handle the message
_this3.onPacket(packet);
}; // decode payload
decodePayload(data, this.socket.binaryType).forEach(callback); // if an event did not trigger closing
if ("closed" !== this.readyState) {
// if we got data we're not polling
this.polling = false;
this.emit("pollComplete");
if ("open" === this.readyState) {
this.poll();
}
}
}
/**
* For polling, send a close packet.
*
* @api private
*/
}, {
key: "doClose",
value: function doClose() {
var _this4 = this;
var close = function close() {
_this4.write([{
type: "close"
}]);
};
if ("open" === this.readyState) {
close();
} else {
// in case we're trying to close while
// handshaking is in progress (GH-164)
this.once("open", close);
}
}
/**
* Writes a packets payload.
*
* @param {Array} data packets
* @param {Function} drain callback
* @api private
*/
}, {
key: "write",
value: function write(packets) {
var _this5 = this;
this.writable = false;
encodePayload(packets, function (data) {
_this5.doWrite(data, function () {
_this5.writable = true;
_this5.emit("drain");
});
});
}
/**
* Generates uri for connection.
*
* @api private
*/
}, {
key: "uri",
value: function uri() {
var query = this.query || {};
var schema = this.opts.secure ? "https" : "http";
var port = ""; // cache busting is forced
if (false !== this.opts.timestampRequests) {
query[this.opts.timestampParam] = yeast_1();
}
if (!this.supportsBinary && !query.sid) {
query.b64 = 1;
} // avoid port if default for schema
if (this.opts.port && ("https" === schema && Number(this.opts.port) !== 443 || "http" === schema && Number(this.opts.port) !== 80)) {
port = ":" + this.opts.port;
}
var encodedQuery = parseqs.encode(query);
var ipv6 = this.opts.hostname.indexOf(":") !== -1;
return schema + "://" + (ipv6 ? "[" + this.opts.hostname + "]" : this.opts.hostname) + port + this.opts.path + (encodedQuery.length ? "?" + encodedQuery : "");
}
}, {
key: "name",
get: function get() {
return "polling";
}
}]);
return Polling;
}(Transport);
/**
* Empty function
*/
function empty() {}
var hasXHR2 = function () {
var xhr = new XMLHttpRequest$1({
xdomain: false
});
return null != xhr.responseType;
}();
var XHR = /*#__PURE__*/function (_Polling) {
_inherits(XHR, _Polling);
var _super = _createSuper(XHR);
/**
* XHR Polling constructor.
*
* @param {Object} opts
* @api public
*/
function XHR(opts) {
var _this;
_classCallCheck(this, XHR);
_this = _super.call(this, opts);
if (typeof location !== "undefined") {
var isSSL = "https:" === location.protocol;
var port = location.port; // some user agents have empty `location.port`
if (!port) {
port = isSSL ? "443" : "80";
}
_this.xd = typeof location !== "undefined" && opts.hostname !== location.hostname || port !== opts.port;
_this.xs = opts.secure !== isSSL;
}
/**
* XHR supports binary
*/
var forceBase64 = opts && opts.forceBase64;
_this.supportsBinary = hasXHR2 && !forceBase64;
return _this;
}
/**
* Creates a request.
*
* @param {String} method
* @api private
*/
_createClass(XHR, [{
key: "request",
value: function request() {
var opts = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
_extends(opts, {
xd: this.xd,
xs: this.xs
}, this.opts);
return new Request(this.uri(), opts);
}
/**
* Sends data.
*
* @param {String} data to send.
* @param {Function} called upon flush.
* @api private
*/
}, {
key: "doWrite",
value: function doWrite(data, fn) {
var _this2 = this;
var req = this.request({
method: "POST",
data: data
});
req.on("success", fn);
req.on("error", function (err) {
_this2.onError("xhr post error", err);
});
}
/**
* Starts a poll cycle.
*
* @api private
*/
}, {
key: "doPoll",
value: function doPoll() {
var _this3 = this;
var req = this.request();
req.on("data", this.onData.bind(this));
req.on("error", function (err) {
_this3.onError("xhr poll error", err);
});
this.pollXhr = req;
}
}]);
return XHR;
}(Polling);
var Request = /*#__PURE__*/function (_Emitter) {
_inherits(Request, _Emitter);
var _super2 = _createSuper(Request);
/**
* Request constructor
*
* @param {Object} options
* @api public
*/
function Request(uri, opts) {
var _this4;
_classCallCheck(this, Request);
_this4 = _super2.call(this);
installTimerFunctions(_assertThisInitialized(_this4), opts);
_this4.opts = opts;
_this4.method = opts.method || "GET";
_this4.uri = uri;
_this4.async = false !== opts.async;
_this4.data = undefined !== opts.data ? opts.data : null;
_this4.create();
return _this4;
}
/**
* Creates the XHR object and sends the request.
*
* @api private
*/
_createClass(Request, [{
key: "create",
value: function create() {
var _this5 = this;
var opts = pick(this.opts, "agent", "pfx", "key", "passphrase", "cert", "ca", "ciphers", "rejectUnauthorized", "autoUnref");
opts.xdomain = !!this.opts.xd;
opts.xscheme = !!this.opts.xs;
var xhr = this.xhr = new XMLHttpRequest$1(opts);
try {
xhr.open(this.method, this.uri, this.async);
try {
if (this.opts.extraHeaders) {
xhr.setDisableHeaderCheck && xhr.setDisableHeaderCheck(true);
for (var i in this.opts.extraHeaders) {
if (this.opts.extraHeaders.hasOwnProperty(i)) {
xhr.setRequestHeader(i, this.opts.extraHeaders[i]);
}
}
}
} catch (e) {}
if ("POST" === this.method) {
try {
xhr.setRequestHeader("Content-type", "text/plain;charset=UTF-8");
} catch (e) {}
}
try {
xhr.setRequestHeader("Accept", "*/*");
} catch (e) {} // ie6 check
if ("withCredentials" in xhr) {
xhr.withCredentials = this.opts.withCredentials;
}
if (this.opts.requestTimeout) {
xhr.timeout = this.opts.requestTimeout;
}
xhr.onreadystatechange = function () {
if (4 !== xhr.readyState) return;
if (200 === xhr.status || 1223 === xhr.status) {
_this5.onLoad();
} else {
// make sure the `error` event handler that's user-set
// does not throw in the same tick and gets caught here
_this5.setTimeoutFn(function () {
_this5.onError(typeof xhr.status === "number" ? xhr.status : 0);
}, 0);
}
};
xhr.send(this.data);
} catch (e) {
// Need to defer since .create() is called directly from the constructor
// and thus the 'error' event can only be only bound *after* this exception
// occurs. Therefore, also, we cannot throw here at all.
this.setTimeoutFn(function () {
_this5.onError(e);
}, 0);
return;
}
if (typeof document !== "undefined") {
this.index = Request.requestsCount++;
Request.requests[this.index] = this;
}
}
/**
* Called upon successful response.
*
* @api private
*/
}, {
key: "onSuccess",
value: function onSuccess() {
this.emit("success");
this.cleanup();
}
/**
* Called if we have data.
*
* @api private
*/
}, {
key: "onData",
value: function onData(data) {
this.emit("data", data);
this.onSuccess();
}
/**
* Called upon error.
*
* @api private
*/
}, {
key: "onError",
value: function onError(err) {
this.emit("error", err);
this.cleanup(true);
}
/**
* Cleans up house.
*
* @api private
*/
}, {
key: "cleanup",
value: function cleanup(fromError) {
if ("undefined" === typeof this.xhr || null === this.xhr) {
return;
}
this.xhr.onreadystatechange = empty;
if (fromError) {
try {
this.xhr.abort();
} catch (e) {}
}
if (typeof document !== "undefined") {
delete Request.requests[this.index];
}
this.xhr = null;
}
/**
* Called upon load.
*
* @api private
*/
}, {
key: "onLoad",
value: function onLoad() {
var data = this.xhr.responseText;
if (data !== null) {
this.onData(data);
}
}
/**
* Aborts the request.
*
* @api public
*/
}, {
key: "abort",
value: function abort() {
this.cleanup();
}
}]);
return Request;
}(Emitter_1);
Request.requestsCount = 0;
Request.requests = {};
/**
* Aborts pending requests when unloading the window. This is needed to prevent
* memory leaks (e.g. when using IE) and to ensure that no spurious error is
* emitted.
*/
if (typeof document !== "undefined") {
// @ts-ignore
if (typeof attachEvent === "function") {
// @ts-ignore
attachEvent("onunload", unloadHandler);
} else if (typeof addEventListener === "function") {
var terminationEvent = "onpagehide" in globalThis ? "pagehide" : "unload";
addEventListener(terminationEvent, unloadHandler, false);
}
}
function unloadHandler() {
for (var i in Request.requests) {
if (Request.requests.hasOwnProperty(i)) {
Request.requests[i].abort();
}
}
}
var nextTick = function () {
var isPromiseAvailable = typeof Promise === "function" && typeof Promise.resolve === "function";
if (isPromiseAvailable) {
return function (cb) {
return Promise.resolve().then(cb);
};
} else {
return function (cb, setTimeoutFn) {
return setTimeoutFn(cb, 0);
};
}
}();
var WebSocket = globalThis.WebSocket || globalThis.MozWebSocket;
var usingBrowserWebSocket = true;
var defaultBinaryType = "arraybuffer";
var isReactNative = typeof navigator !== "undefined" && typeof navigator.product === "string" && navigator.product.toLowerCase() === "reactnative";
var WS = /*#__PURE__*/function (_Transport) {
_inherits(WS, _Transport);
var _super = _createSuper(WS);
/**
* WebSocket transport constructor.
*
* @api {Object} connection options
* @api public
*/
function WS(opts) {
var _this;
_classCallCheck(this, WS);
_this = _super.call(this, opts);
_this.supportsBinary = !opts.forceBase64;
return _this;
}
/**
* Transport name.
*
* @api public
*/
_createClass(WS, [{
key: "doOpen",
/**
* Opens socket.
*
* @api private
*/
value: function doOpen() {
if (!this.check()) {
// let probe timeout
return;
}
var uri = this.uri();
var protocols = this.opts.protocols; // React Native only supports the 'headers' option, and will print a warning if anything else is passed
var opts = isReactNative ? {} : pick(this.opts, "agent", "perMessageDeflate", "pfx", "key", "passphrase", "cert", "ca", "ciphers", "rejectUnauthorized", "localAddress", "protocolVersion", "origin", "maxPayload", "family", "checkServerIdentity");
if (this.opts.extraHeaders) {
opts.headers = this.opts.extraHeaders;
}
try {
this.ws = usingBrowserWebSocket && !isReactNative ? protocols ? new WebSocket(uri, protocols) : new WebSocket(uri) : new WebSocket(uri, protocols, opts);
} catch (err) {
return this.emit("error", err);
}
this.ws.binaryType = this.socket.binaryType || defaultBinaryType;
this.addEventListeners();
}
/**
* Adds event listeners to the socket
*
* @api private
*/
}, {
key: "addEventListeners",
value: function addEventListeners() {
var _this2 = this;
this.ws.onopen = function () {
if (_this2.opts.autoUnref) {
_this2.ws._socket.unref();
}
_this2.onOpen();
};
this.ws.onclose = this.onClose.bind(this);
this.ws.onmessage = function (ev) {
return _this2.onData(ev.data);
};
this.ws.onerror = function (e) {
return _this2.onError("websocket error", e);
};
}
/**
* Writes data to socket.
*
* @param {Array} array of packets.
* @api private
*/
}, {
key: "write",
value: function write(packets) {
var _this3 = this;
this.writable = false; // encodePacket efficient as it uses WS framing
// no need for encodePayload
var _loop = function _loop(i) {
var packet = packets[i];
var lastPacket = i === packets.length - 1;
encodePacket(packet, _this3.supportsBinary, function (data) {
// always create a new object (GH-437)
var opts = {};
// have a chance of informing us about it yet, in that case send will
// throw an error
try {
if (usingBrowserWebSocket) {
// TypeError is thrown when passing the second argument on Safari
_this3.ws.send(data);
}
} catch (e) {}
if (lastPacket) {
// fake drain
// defer to next tick to allow Socket to clear writeBuffer
nextTick(function () {
_this3.writable = true;
_this3.emit("drain");
}, _this3.setTimeoutFn);
}
});
};
for (var i = 0; i < packets.length; i++) {
_loop(i);
}
}
/**
* Closes socket.
*
* @api private
*/
}, {
key: "doClose",
value: function doClose() {
if (typeof this.ws !== "undefined") {
this.ws.close();
this.ws = null;
}
}
/**
* Generates uri for connection.
*
* @api private
*/
}, {
key: "uri",
value: function uri() {
var query = this.query || {};
var schema = this.opts.secure ? "wss" : "ws";
var port = ""; // avoid port if default for schema
if (this.opts.port && ("wss" === schema && Number(this.opts.port) !== 443 || "ws" === schema && Number(this.opts.port) !== 80)) {
port = ":" + this.opts.port;
} // append timestamp to URI
if (this.opts.timestampRequests) {
query[this.opts.timestampParam] = yeast_1();
} // communicate binary support capabilities
if (!this.supportsBinary) {
query.b64 = 1;
}
var encodedQuery = parseqs.encode(query);
var ipv6 = this.opts.hostname.indexOf(":") !== -1;
return schema + "://" + (ipv6 ? "[" + this.opts.hostname + "]" : this.opts.hostname) + port + this.opts.path + (encodedQuery.length ? "?" + encodedQuery : "");
}
/**
* Feature detection for WebSocket.
*
* @return {Boolean} whether this transport is available.
* @api public
*/
}, {
key: "check",
value: function check() {
return !!WebSocket && !("__initialize" in WebSocket && this.name === WS.prototype.name);
}
}, {
key: "name",
get: function get() {
return "websocket";
}
}]);
return WS;
}(Transport);
var transports = {
websocket: WS,
polling: XHR
};
/**
* Parses an URI
*
* @author Steven Levithan <stevenlevithan.com> (MIT license)
* @api private
*/
var re = /^(?:(?![^:@]+:[^:@\/]*@)(http|https|ws|wss):\/\/)?((?:(([^:@]*)(?::([^:@]*))?)?@)?((?:[a-f0-9]{0,4}:){2,7}[a-f0-9]{0,4}|[^:\/?#]*)(?::(\d*))?)(((\/(?:[^?#](?![^?#\/]*\.[^?#\/.]+(?:[?#]|$)))*\/?)?([^?#\/]*))(?:\?([^#]*))?(?:#(.*))?)/;
var parts = ['source', 'protocol', 'authority', 'userInfo', 'user', 'password', 'host', 'port', 'relative', 'path', 'directory', 'file', 'query', 'anchor'];
var parseuri = function parseuri(str) {
var src = str,
b = str.indexOf('['),
e = str.indexOf(']');
if (b != -1 && e != -1) {
str = str.substring(0, b) + str.substring(b, e).replace(/:/g, ';') + str.substring(e, str.length);
}
var m = re.exec(str || ''),
uri = {},
i = 14;
while (i--) {
uri[parts[i]] = m[i] || '';
}
if (b != -1 && e != -1) {
uri.source = src;
uri.host = uri.host.substring(1, uri.host.length - 1).replace(/;/g, ':');
uri.authority = uri.authority.replace('[', '').replace(']', '').replace(/;/g, ':');
uri.ipv6uri = true;
}
uri.pathNames = pathNames(uri, uri['path']);
uri.queryKey = queryKey(uri, uri['query']);
return uri;
};
function pathNames(obj, path) {
var regx = /\/{2,9}/g,
names = path.replace(regx, "/").split("/");
if (path.substr(0, 1) == '/' || path.length === 0) {
names.splice(0, 1);
}
if (path.substr(path.length - 1, 1) == '/') {
names.splice(names.length - 1, 1);
}
return names;
}
function queryKey(uri, query) {
var data = {};
query.replace(/(?:^|&)([^&=]*)=?([^&]*)/g, function ($0, $1, $2) {
if ($1) {
data[$1] = $2;
}
});
return data;
}
var Socket = /*#__PURE__*/function (_Emitter) {
_inherits(Socket, _Emitter);
var _super = _createSuper(Socket);
/**
* Socket constructor.
*
* @param {String|Object} uri or options
* @param {Object} opts - options
* @api public
*/
function Socket(uri) {
var _this;
var opts = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
_classCallCheck(this, Socket);
_this = _super.call(this);
if (uri && "object" === _typeof(uri)) {
opts = uri;
uri = null;
}
if (uri) {
uri = parseuri(uri);
opts.hostname = uri.host;
opts.secure = uri.protocol === "https" || uri.protocol === "wss";
opts.port = uri.port;
if (uri.query) opts.query = uri.query;
} else if (opts.host) {
opts.hostname = parseuri(opts.host).host;
}
installTimerFunctions(_assertThisInitialized(_this), opts);
_this.secure = null != opts.secure ? opts.secure : typeof location !== "undefined" && "https:" === location.protocol;
if (opts.hostname && !opts.port) {
// if no port is specified manually, use the protocol default
opts.port = _this.secure ? "443" : "80";
}
_this.hostname = opts.hostname || (typeof location !== "undefined" ? location.hostname : "localhost");
_this.port = opts.port || (typeof location !== "undefined" && location.port ? location.port : _this.secure ? "443" : "80");
_this.transports = opts.transports || ["polling", "websocket"];
_this.readyState = "";
_this.writeBuffer = [];
_this.prevBufferLen = 0;
_this.opts = _extends({
path: "/engine.io",
agent: false,
withCredentials: false,
upgrade: true,
timestampParam: "t",
rememberUpgrade: false,
rejectUnauthorized: true,
perMessageDeflate: {
threshold: 1024
},
transportOptions: {},
closeOnBeforeunload: true
}, opts);
_this.opts.path = _this.opts.path.replace(/\/$/, "") + "/";
if (typeof _this.opts.query === "string") {
_this.opts.query = parseqs.decode(_this.opts.query);
} // set on handshake
_this.id = null;
_this.upgrades = null;
_this.pingInterval = null;
_this.pingTimeout = null; // set on heartbeat
_this.pingTimeoutTimer = null;
if (typeof addEventListener === "function") {
if (_this.opts.closeOnBeforeunload) {
// Firefox closes the connection when the "beforeunload" event is emitted but not Chrome. This event listener
// ensures every browser behaves the same (no "disconnect" event at the Socket.IO level when the page is
// closed/reloaded)
addEventListener("beforeunload", function () {
if (_this.transport) {
// silently close the transport
_this.transport.removeAllListeners();
_this.transport.close();
}
}, false);
}
if (_this.hostname !== "localhost") {
_this.offlineEventListener = function () {
_this.onClose("transport close");
};
addEventListener("offline", _this.offlineEventListener, false);
}
}
_this.open();
return _this;
}
/**
* Creates transport of the given type.
*
* @param {String} transport name
* @return {Transport}
* @api private
*/
_createClass(Socket, [{
key: "createTransport",
value: function createTransport(name) {
var query = clone(this.opts.query); // append engine.io protocol identifier
query.EIO = protocol; // transport name
query.transport = name; // session id if we already have one
if (this.id) query.sid = this.id;
var opts = _extends({}, this.opts.transportOptions[name], this.opts, {
query: query,
socket: this,
hostname: this.hostname,
secure: this.secure,
port: this.port
});
return new transports[name](opts);
}
/**
* Initializes transport to use and starts probe.
*
* @api private
*/
}, {
key: "open",
value: function open() {
var _this2 = this;
var transport;
if (this.opts.rememberUpgrade && Socket.priorWebsocketSuccess && this.transports.indexOf("websocket") !== -1) {
transport = "websocket";
} else if (0 === this.transports.length) {
// Emit error on next tick so it can be listened to
this.setTimeoutFn(function () {
_this2.emitReserved("error", "No transports available");
}, 0);
return;
} else {
transport = this.transports[0];
}
this.readyState = "opening"; // Retry with the next transport if the transport is disabled (jsonp: false)
try {
transport = this.createTransport(transport);
} catch (e) {
this.transports.shift();
this.open();
return;
}
transport.open();
this.setTransport(transport);
}
/**
* Sets the current transport. Disables the existing one (if any).
*
* @api private
*/
}, {
key: "setTransport",
value: function setTransport(transport) {
var _this3 = this;
if (this.transport) {
this.transport.removeAllListeners();
} // set up transport
this.transport = transport; // set up transport listeners
transport.on("drain", this.onDrain.bind(this)).on("packet", this.onPacket.bind(this)).on("error", this.onError.bind(this)).on("close", function () {
_this3.onClose("transport close");
});
}
/**
* Probes a transport.
*
* @param {String} transport name
* @api private
*/
}, {
key: "probe",
value: function probe(name) {
var _this4 = this;
var transport = this.createTransport(name);
var failed = false;
Socket.priorWebsocketSuccess = false;
var onTransportOpen = function onTransportOpen() {
if (failed) return;
transport.send([{
type: "ping",
data: "probe"
}]);
transport.once("packet", function (msg) {
if (failed) return;
if ("pong" === msg.type && "probe" === msg.data) {
_this4.upgrading = true;
_this4.emitReserved("upgrading", transport);
if (!transport) return;
Socket.priorWebsocketSuccess = "websocket" === transport.name;
_this4.transport.pause(function () {
if (failed) return;
if ("closed" === _this4.readyState) return;
cleanup();
_this4.setTransport(transport);
transport.send([{
type: "upgrade"
}]);
_this4.emitReserved("upgrade", transport);
transport = null;
_this4.upgrading = false;
_this4.flush();
});
} else {
var err = new Error("probe error"); // @ts-ignore
err.transport = transport.name;
_this4.emitReserved("upgradeError", err);
}
});
};
function freezeTransport() {
if (failed) return; // Any callback called by transport should be ignored since now
failed = true;
cleanup();
transport.close();
transport = null;
} // Handle any error that happens while probing
var onerror = function onerror(err) {
var error = new Error("probe error: " + err); // @ts-ignore
error.transport = transport.name;
freezeTransport();
_this4.emitReserved("upgradeError", error);
};
function onTransportClose() {
onerror("transport closed");
} // When the socket is closed while we're probing
function onclose() {
onerror("socket closed");
} // When the socket is upgraded while we're probing
function onupgrade(to) {
if (transport && to.name !== transport.name) {
freezeTransport();
}
} // Remove all listeners on the transport and on self
var cleanup = function cleanup() {
transport.removeListener("open", onTransportOpen);
transport.removeListener("error", onerror);
transport.removeListener("close", onTransportClose);
_this4.off("close", onclose);
_this4.off("upgrading", onupgrade);
};
transport.once("open", onTransportOpen);
transport.once("error", onerror);
transport.once("close", onTransportClose);
this.once("close", onclose);
this.once("upgrading", onupgrade);
transport.open();
}
/**
* Called when connection is deemed open.
*
* @api private
*/
}, {
key: "onOpen",
value: function onOpen() {
this.readyState = "open";
Socket.priorWebsocketSuccess = "websocket" === this.transport.name;
this.emitReserved("open");
this.flush(); // we check for `readyState` in case an `open`
// listener already closed the socket
if ("open" === this.readyState && this.opts.upgrade && this.transport.pause) {
var i = 0;
var l = this.upgrades.length;
for (; i < l; i++) {
this.probe(this.upgrades[i]);
}
}
}
/**
* Handles a packet.
*
* @api private
*/
}, {
key: "onPacket",
value: function onPacket(packet) {
if ("opening" === this.readyState || "open" === this.readyState || "closing" === this.readyState) {
this.emitReserved("packet", packet); // Socket is live - any packet counts
this.emitReserved("heartbeat");
switch (packet.type) {
case "open":
this.onHandshake(JSON.parse(packet.data));
break;
case "ping":
this.resetPingTimeout();
this.sendPacket("pong");
this.emitReserved("ping");
this.emitReserved("pong");
break;
case "error":
var err = new Error("server error"); // @ts-ignore
err.code = packet.data;
this.onError(err);
break;
case "message":
this.emitReserved("data", packet.data);
this.emitReserved("message", packet.data);
break;
}
}
}
/**
* Called upon handshake completion.
*
* @param {Object} data - handshake obj
* @api private
*/
}, {
key: "onHandshake",
value: function onHandshake(data) {
this.emitReserved("handshake", data);
this.id = data.sid;
this.transport.query.sid = data.sid;
this.upgrades = this.filterUpgrades(data.upgrades);
this.pingInterval = data.pingInterval;
this.pingTimeout = data.pingTimeout;
this.onOpen(); // In case open handler closes socket
if ("closed" === this.readyState) return;
this.resetPingTimeout();
}
/**
* Sets and resets ping timeout timer based on server pings.
*
* @api private
*/
}, {
key: "resetPingTimeout",
value: function resetPingTimeout() {
var _this5 = this;
this.clearTimeoutFn(this.pingTimeoutTimer);
this.pingTimeoutTimer = this.setTimeoutFn(function () {
_this5.onClose("ping timeout");
}, this.pingInterval + this.pingTimeout);
if (this.opts.autoUnref) {
this.pingTimeoutTimer.unref();
}
}
/**
* Called on `drain` event
*
* @api private
*/
}, {
key: "onDrain",
value: function onDrain() {
this.writeBuffer.splice(0, this.prevBufferLen); // setting prevBufferLen = 0 is very important
// for example, when upgrading, upgrade packet is sent over,
// and a nonzero prevBufferLen could cause problems on `drain`
this.prevBufferLen = 0;
if (0 === this.writeBuffer.length) {
this.emitReserved("drain");
} else {
this.flush();
}
}
/**
* Flush write buffers.
*
* @api private
*/
}, {
key: "flush",
value: function flush() {
if ("closed" !== this.readyState && this.transport.writable && !this.upgrading && this.writeBuffer.length) {
this.transport.send(this.writeBuffer); // keep track of current length of writeBuffer
// splice writeBuffer and callbackBuffer on `drain`
this.prevBufferLen = this.writeBuffer.length;
this.emitReserved("flush");
}
}
/**
* Sends a message.
*
* @param {String} message.
* @param {Function} callback function.
* @param {Object} options.
* @return {Socket} for chaining.
* @api public
*/
}, {
key: "write",
value: function write(msg, options, fn) {
this.sendPacket("message", msg, options, fn);
return this;
}
}, {
key: "send",
value: function send(msg, options, fn) {
this.sendPacket("message", msg, options, fn);
return this;
}
/**
* Sends a packet.
*
* @param {String} packet type.
* @param {String} data.
* @param {Object} options.
* @param {Function} callback function.
* @api private
*/
}, {
key: "sendPacket",
value: function sendPacket(type, data, options, fn) {
if ("function" === typeof data) {
fn = data;
data = undefined;
}
if ("function" === typeof options) {
fn = options;
options = null;
}
if ("closing" === this.readyState || "closed" === this.readyState) {
return;
}
options = options || {};
options.compress = false !== options.compress;
var packet = {
type: type,
data: data,
options: options
};
this.emitReserved("packetCreate", packet);
this.writeBuffer.push(packet);
if (fn) this.once("flush", fn);
this.flush();
}
/**
* Closes the connection.
*
* @api public
*/
}, {
key: "close",
value: function close() {
var _this6 = this;
var close = function close() {
_this6.onClose("forced close");
_this6.transport.close();
};
var cleanupAndClose = function cleanupAndClose() {
_this6.off("upgrade", cleanupAndClose);
_this6.off("upgradeError", cleanupAndClose);
close();
};
var waitForUpgrade = function waitForUpgrade() {
// wait for upgrade to finish since we can't send packets while pausing a transport
_this6.once("upgrade", cleanupAndClose);
_this6.once("upgradeError", cleanupAndClose);
};
if ("opening" === this.readyState || "open" === this.readyState) {
this.readyState = "closing";
if (this.writeBuffer.length) {
this.once("drain", function () {
if (_this6.upgrading) {
waitForUpgrade();
} else {
close();
}
});
} else if (this.upgrading) {
waitForUpgrade();
} else {
close();
}
}
return this;
}
/**
* Called upon transport error
*
* @api private
*/
}, {
key: "onError",
value: function onError(err) {
Socket.priorWebsocketSuccess = false;
this.emitReserved("error", err);
this.onClose("transport error", err);
}
/**
* Called upon transport close.
*
* @api private
*/
}, {
key: "onClose",
value: function onClose(reason, desc) {
if ("opening" === this.readyState || "open" === this.readyState || "closing" === this.readyState) {
// clear timers
this.clearTimeoutFn(this.pingTimeoutTimer); // stop event from firing again for transport
this.transport.removeAllListeners("close"); // ensure transport won't stay open
this.transport.close(); // ignore further transport communication
this.transport.removeAllListeners();
if (typeof removeEventListener === "function") {
removeEventListener("offline", this.offlineEventListener, false);
} // set ready state
this.readyState = "closed"; // clear session id
this.id = null; // emit close event
this.emitReserved("close", reason, desc); // clean buffers after, so users can still
// grab the buffers on `close` event
this.writeBuffer = [];
this.prevBufferLen = 0;
}
}
/**
* Filters upgrades, returning only those matching client transports.
*
* @param {Array} server upgrades
* @api private
*
*/
}, {
key: "filterUpgrades",
value: function filterUpgrades(upgrades) {
var filteredUpgrades = [];
var i = 0;
var j = upgrades.length;
for (; i < j; i++) {
if (~this.transports.indexOf(upgrades[i])) filteredUpgrades.push(upgrades[i]);
}
return filteredUpgrades;
}
}]);
return Socket;
}(Emitter_1);
Socket.protocol = protocol;
function clone(obj) {
var o = {};
for (var i in obj) {
if (obj.hasOwnProperty(i)) {
o[i] = obj[i];
}
}
return o;
}
var browserEntrypoint = (function (uri, opts) {
return new Socket(uri, opts);
});
return browserEntrypoint;
}));
//# sourceMappingURL=engine.io.js.map
| 25.650734 | 253 | 0.539925 |
438b037587b49b13380689a08bdf2f0c2d892c90 | 2,199 | js | JavaScript | tests/baselines/reference/chainedCallsWithTypeParameterConstrainedToOtherTypeParameter2.js | panagosg7/TypeScript-1.0.1.0 | 3bb96d217c8f23596aa86679a70056b58e953464 | [
"Apache-2.0"
] | null | null | null | tests/baselines/reference/chainedCallsWithTypeParameterConstrainedToOtherTypeParameter2.js | panagosg7/TypeScript-1.0.1.0 | 3bb96d217c8f23596aa86679a70056b58e953464 | [
"Apache-2.0"
] | null | null | null | tests/baselines/reference/chainedCallsWithTypeParameterConstrainedToOtherTypeParameter2.js | panagosg7/TypeScript-1.0.1.0 | 3bb96d217c8f23596aa86679a70056b58e953464 | [
"Apache-2.0"
] | null | null | null | //// [chainedCallsWithTypeParameterConstrainedToOtherTypeParameter2.js]
var Chain = (function () {
function Chain(value) {
this.value = value;
}
Chain.prototype.then = function (cb) {
var t;
var s;
// Ok to go down the chain, but error to climb up the chain
(new Chain(t)).then(function (tt) {
return s;
}).then(function (ss) {
return t;
});
// But error to try to climb up the chain
(new Chain(s)).then(function (ss) {
return t;
});
// Staying at T or S should be fine
(new Chain(t)).then(function (tt) {
return t;
}).then(function (tt) {
return t;
}).then(function (tt) {
return t;
});
(new Chain(s)).then(function (ss) {
return s;
}).then(function (ss) {
return s;
}).then(function (ss) {
return s;
});
return null;
};
return Chain;
})();
var Chain2 = (function () {
function Chain2(value) {
this.value = value;
}
Chain2.prototype.then = function (cb) {
var i;
var t;
var s;
// Ok to go down the chain, check the constraint at the end.
// Should get an error that we are assigning a string to a number
(new Chain2(i)).then(function (ii) {
return t;
}).then(function (tt) {
return s;
}).value.x = "";
// Staying at T or S should keep the constraint.
// Get an error when we assign a string to a number in both cases
(new Chain2(i)).then(function (ii) {
return t;
}).then(function (tt) {
return t;
}).then(function (tt) {
return t;
}).then(function (tt) {
return t;
}).value.x = "";
(new Chain2(i)).then(function (ii) {
return s;
}).then(function (ss) {
return s;
}).then(function (ss) {
return s;
}).then(function (ss) {
return s;
}).value.x = "";
return null;
};
return Chain2;
})();
| 25.870588 | 73 | 0.473397 |
438b193c51bbc27c82cf8efce69bc842689567e3 | 21,742 | js | JavaScript | src/resources/resources_loader.js | bsparks/engine | 1bf101f4aa16a76d599794a37229f0ca0dd2fc36 | [
"MIT"
] | null | null | null | src/resources/resources_loader.js | bsparks/engine | 1bf101f4aa16a76d599794a37229f0ca0dd2fc36 | [
"MIT"
] | null | null | null | src/resources/resources_loader.js | bsparks/engine | 1bf101f4aa16a76d599794a37229f0ca0dd2fc36 | [
"MIT"
] | 1 | 2020-10-30T02:14:56.000Z | 2020-10-30T02:14:56.000Z | pc.extend(pc.resources, function () {
/**
* @name pc.resources.ResourceLoader
* @constructor Create a new instance of a ResourceLoader
* @class Used to make requests for remote resources.
* The ResourceLoader is used to request a resource using an identifier (often the url of a remote file).
* Registered {@link pc.resources.ResourceHandler} perform the specific loading and opening functionality and will return
* a new instance of a resource. The ResourceLoader contains a built in cache, that uses file hashes to ensure that
* resources are not fetched multiple times. Hashes must be registered against an identifier prior to making requests.
* @example
* var loader = new pc.resources.ResourceLoader();
* loader.registerHandler(pc.resources.ImageRequest, new pc.resources.ImageResourceHandler());
* var promise = loader.request(new pc.resources.ImageRequest("http://example.com/image.png"));
* promise.then(function (resources) {
* var img = resources[0];
* });
*/
var ResourceLoader = function () {
if (typeof(window.RSVP) === 'undefined') {
logERROR('Missing RSVP library');
}
this._types = {}; // Registered resource types
this._handlers = {}; // Registered resource handlers indexed by type
this._requests = {}; // Currently active requests
this._cache = {}; // Loaded resources indexed by hash
this._hashes = {}; // Lookup from identifier to hash
this._canonicals = {}; // Lookup from hash to canonical identifier
// Counters for progress
this._requested = 0;
this._loaded = 0;
this._sequence = 0; // counter for tracking requests uniquely
this.cache = true; // set this to false to perform cache busting on resources
pc.events.attach(this);
};
ResourceLoader.prototype = {
/**
* @function
* @name pc.resources.ResourceLoader#createFileRequest
* @description Return a new {@link pc.resources.ResourceRequest} from the types that have been registered.
* @param {String} identifier The identifier (usually URL) used to uniquely identify the asset to load
* @param {String} type The asset type to create a ResourceRequest for ()
* @returns {pc.resources.ResourceRequest} A new ResourceRequest instance
* @example
* var request = loader.createFileRequest('assets/12/12341234-1234-1234-123412341234/image.jpg', 'image'); // pc.resources.ImageRequest
*/
createFileRequest: function (identifier, type) {
return new this._types[type](identifier);
},
/**
* @function
* @name pc.resources.ResourceLoader#registerHandler
* @description Register a handler for a new type of resource. To register a handler you need to provided an instance of a ResourceHandler,
* and the ResourceRequest type to be associated with the handler.
* @param {pc.resources.ResourceRequest} RequestType The type of request to associate with this handler
* @param {pc.resources.ResourceHandler} handler A ResourceHandler instance.
*/
registerHandler: function (RequestType, handler) {
var request = new RequestType();
if (request.type === "") {
throw Error("ResourceRequests must have a type");
}
this._types[request.type] = RequestType;
this._handlers[request.type] = handler;
handler.setLoader(this);
},
/**
* @function
* @name pc.resources.ResourceLoader#request
* @description Make a request for one or more resources from a remote location. A call to request() will try to retrieve all the resources requested,
* using the ResourceHandlers for the specific type of request. Resources are cached once they have been requested, and subsequent requests will return the
* the cached value.
* The request() call returns a Promise object which is used to access the resources once they have all been loaded.
* @param {pc.resources.ResourceRequest|pc.resources.ResourceRequest[]} requests A single or list of {@link pc.resources.ResourceRequest}s which will be requested in this batch.
* @returns {pc.promise.Promise} A Promise object which is used to retrieve the resources once they have completed
* @example
* var requests = [
* new pc.resources.ImageRequest("http://example.com/image_one.png"),
* new pc.resources.ImageRequest("http://example.com/image_two.png")
* ];
* var promise = loader.request(requests);
* promise.then(function(resources) {
* var img1 = resources[0];
* var img2 = resources[1];
* });
*/
request: function (requests, options) {
options = options || {};
var self = this;
var parent = options.parent;
options.cache = self.cache;
var promise = new pc.promise.Promise(function (resolve, reject) {
var i, n;
var p;
// Convert single request to list
if (requests.length === undefined) {
requests = [requests];
}
var requested = [];
var promises = [];
for (i = 0, n = requests.length; i < n; i++) {
// Use an existing request if there is a valid one in progress
var request = self._findExistingRequest(requests[i]);
// If we are using an existing request, we need to copy over result and data fields.
// TODO: What happens if the existing request has a data field!
if (request !== requests[i]) {
request.data = requests[i].data;
}
self._makeCanonical(request);
promises.push(self._request(request, options));
requested.push(request);
// If there is a parent request, add all child requests on parent
if (parent) {
parent.children.push(request);
}
}
// Check that all child promises of the requests have been completed
var check = function (resources, requests, promises) {
var i, n;
var childPromises = [];
var childRequests = [];
requests.forEach(function (r) {
r.children.forEach(function (c) {
childRequests.push(c);
childPromises.push.apply(childPromises, c.promises);
})
});
if (childPromises.length) {
pc.promise.all(childPromises).then(function(childResources) {
check(resources, childRequests, childPromises);
}, function (error) {
reject(error);
});
} else {
self.fire("complete", resources)
resolve(resources)
}
}
pc.promise.all(promises).then(function (resources) {
check(resources, requested, promises);
}, function (error) {
reject(error);
});
});
return promise;
},
/**
* @private
* @function
* @name pc.resources.ResourceLoader#open
* @description Perform just the open() part of the resource loading process. Useful if you already have the data from somewhere.
* @param {pc.resources.ResourceRequest} RequestType The type of request to open
* @param {Object} data The data to use for the new resource
* @param {Object} options Optional arguments
*/
open: function (RequestType, data, options) {
var request = new RequestType();
return this._handlers[request.type].open(data, request, options);
},
/**
* @function
* @name pc.resources.ResourceLoader#registerHash
* @description Register a connection between a file hash and an identifier. If the same file is located via several identifiers, the hash ensures that only a single request is made.
* @param {String} hash The file hash
* @param {String} identifier The resource identifier
*/
registerHash: function (hash, identifier) {
if (!this._hashes[identifier]) {
this._hashes[identifier] = hash;
}
if (!this._canonicals[hash]) {
// First hash registered to a url gets to be canonical
this._canonicals[hash] = identifier;
}
},
/**
* @function
* @name pc.resources.ResourceLoader#getHash
* @description Return the hash registered against the identifier
* @param {String} identifier The identifier of a resource
* @returns {String|undefined} The hash if the identifier is registered or undefined
*/
getHash: function(identifier) {
return this._hashes[identifier];
},
/**
* @function
* @name pc.resources.ResourceLoader#addToCache
* @description Add a resource into the cache so that future requests will not make new requests.
* @param {String} identifier The identifier for the resource
* @param {Object} resource The resource to be cached
*/
addToCache: function (identifier, resource) {
var hash = this.getHash(identifier);
if (hash) {
this._cache[hash] = resource;
} else {
//logWARNING(pc.string.format("Could not add {0} to cache, no hash registered", identifier));
}
},
/**
* @function
* @name pc.resources.ResourceLoader#getFromCache
* @description Try and get a resource from the cache.
* @param {String} identifier The identifier of the resource
* @returns {Object|null} The resource if it exists in the cache, otherwise returns null
*/
getFromCache: function (identifier) {
var hash = this.getHash(identifier);
if (hash) {
return this._cache[hash];
} else {
return null;
}
},
/**
* @function
* @name pc.resources.ResourceLoader#removeFromCache
* @description Remove a resource from the cache
* @param {String} identifier The identifier for the resource
*/
removeFromCache: function (identifier) {
var hash = this.getHash(identifier);
if (hash) {
delete this._cache[hash]
} else {
return null;
}
},
/**
* @function
* @name pc.resources.ResourceLoader#resetProgress
* @description Call this to reset the progress counter to 0
*/
resetProgress: function () {
this._requested = 0;
this._loaded = 0;
},
// Make a request for a single resource and open it
_request: function (request, _options) {
var self = this;
var promise = null;
var options = {}; // Make a copy of the options per request
for (key in _options) {
options[key] = _options[key];
}
if (request.id === null) {
request.id = this._sequence++;
}
this.fire("request", request);
if (request.promises.length) {
// If the request has already been made, then wait for the result to come in
request.promises.push(new pc.promise.Promise(function (resolve, reject) {
request.promises[0].then(function (resource) {
var resource = self._postOpen(resource, request);
resolve(resource);
});
}));
} else {
// Check cache, load and open the requested data
request.promises[0] = new pc.promise.Promise(function (resolve, reject) {
var handler = self._handlers[request.type];
if (!handler) {
var msg = "Missing handler for type: " + request.type;
self.fire("error", request, msg);
reject(msg);
return;
}
var resource = self.getFromCache(request.canonical);
// If there is a cached resource.
// If the request specifies a type, we check the cached type matches
if (resource && (request.Type === undefined || (resource instanceof request.Type))) {
// In cache, just resolve
resource = self._postOpen(resource, request);
resolve(resource);
} else {
// Not in cache, load the resource
var promise = handler.load(request, options);
promise.then(function (data) {
try {
var resource = self._open(data, request, options);
if (resource) {
resource = self._postOpen(resource, request);
}
resolve(resource);
} catch (e) {
reject(e);
}
}, function (error) {
self.fire("error", request, error);
reject(error);
});
}
});
}
self._requests[request.canonical] = request;
this._requested++;
return request.promises[request.promises.length - 1];
},
// Convert loaded data into the resource using the handler's open() and clone() methods
_open: function (data, request, options) {
return this._handlers[request.type].open(data, request, options);
},
// After loading and opening clean up and fire events
// Note, this method is called in three places,
// - with a newly opened resource
// - with a resource retrieved from the cache
// - with a resource that was requested twice concurrently, this is called again for the second request.
_postOpen: function (resource, request) {
this.addToCache(request.canonical, resource);
resource = this._handlers[request.type].clone(resource, request);
delete this._requests[request.canonical];
this._loaded++
this.fire("progress", this._loaded / this._requested);
this.fire("load", request, resource);
return resource;
},
/**
* @private
* @name pc.resources.ResourceLoader#_makeCanonical
* @description Set the canonical property on the request object. The canonical identifier is the identifier used
* to make all requests. Resources with the same hash but different URLs will have the same canonical so that requests are not
* duplicated
*
*/
_makeCanonical: function (request) {
var hash = this.getHash(request.identifier);
if (hash && this._canonicals[hash]) {
request.canonical = this._canonicals[hash];
} else {
request.canonical = request.identifier;
}
},
/**
* @private
* @name pc.resources.ResourceLoader#_findExistingRequest
* @description Using the canonical identifier, find and return an existing request for this resource
* This doesn't return a request if a result object was provided for either request
*/
_findExistingRequest: function (request) {
var existing = this._requests[request.canonical];
if (existing) {
// Don't return existing request if requests are for different resource types or if either has a result object.
if ((existing.type !== request.type) || existing.result || request.result) {
return request;
} else {
return existing;
}
} else {
return request;
}
},
};
/**
* @name pc.resources.ResourceRequest
* @class A request for a single resource, located by a unique identifier.
* @constructor Create a new request for a resoiurce
* @param {String} identifier Used by the request handler to locate and access the resource. Usually this will be the URL or GUID of the resource.
* @param {Object} [data] Additional data that the resource handler might need when creating the resource after loading
* @param {Object} [result] If a result object is supplied, this will be used instead of creating a new instance of the resource (only for supporting resource types)
*/
var ResourceRequest = function ResourceRequest(identifier, data, result) {
this.id = null; // Sequence ID, given to the request when it is made
this.canonical = identifier; // The canonical identifier using the file hash (if available) to match identical resources
this.alternatives = []; // Alternative identifiers to the canonical
this.promises = []; // List of promises that will be honoured when the request is complete. The first promise in the list is the primary one.
this.children = []; // Any child requests which were made while this request was being processed
this.data = data; // Additional data that the resource handler might need once it has loaded
this.result = result; // The result object can be supplied and used by a handler, instead of creating a new resource
this.identifier = identifier // The identifier for this resource
};
/**
* @name pc.resources.ResourceHandler
* @class Abstract base class for ResourceHandler. The resource handler performs the request to fetch the resource from a remote location,
* and then it converts the response into the runtime resource object type. A resource handler must implement three methods:
*
* load() which fetches the resource data from a remote location (a file, a remote server, etc)
* open() which takes the response from load() and creates a new instance of a Resource
* clone() which takes the opened resource and _may_ return a new copy of it, if necessary. Otherwise returns the original.
*/
var ResourceHandler = function () {
};
ResourceHandler.prototype = {
setLoader: function (loader) {
this._loader = loader;
},
/**
* @function
* @name pc.resources.ResourceHandler#load
* @description Fetch the resource from a remote location and then call the success callback with the response
* If an error occurs the request is stopped and the error callback is called with details of the error.
* If supported the progress callback is called during the download to report percentage complete progress.
* @param {string} identifier A unique identifier for the resource, possibly the URL or GUID of the resource
* @param {Object} [options]
* @param {Number} [options.priority] The priority of the request for this resource
* @returns {Promise} A promise of the resource data
*/
load: function (request, options) {
throw Error("Not implemented");
},
/**
* @function
* @name pc.resources.ResourceHandler#open
* @description Take the data downloaded from the request and turn it into a resource object for use at runtime.
* For example, and ImageResourceHandler.open() will return an Image object and an EntityResourceHandler.open() will return an Entity.
* @param data The data used to instanciate the resource
* @param [options]
* @param {Number} [options.priority] The priority of the request for this resource
*/
open: function (data, options) {
throw Error("Not implemented");
},
/**
* @function
* @name pc.resources.ResourceHandler#clone
* @description If necessary return a clone of the resource. This is called after open(), if it is not possible to share a single instance
* of a resource from the cache, then clone should return a new copy, otherwise the default is to return the original.
* @param {Object} resource The resource that has just been requested
* @returns {Object} Either the resource that was passed in, or a new clone of that resource
*/
clone: function (resource) {
return resource;
}
};
return {
ResourceLoader: ResourceLoader,
ResourceHandler: ResourceHandler,
ResourceRequest: ResourceRequest
};
}());
| 44.921488 | 189 | 0.574878 |
438bb436c564436eec9985ab2c5e3bf0f3d89cc8 | 1,023 | js | JavaScript | js/script-latest-opportunities.js | SheffieldAI/sheffieldai.github.io | 54692a9e933b8d17166e03f6cfea3022ab3fbab4 | [
"MIT"
] | 16 | 2021-12-15T13:36:54.000Z | 2022-03-24T14:48:11.000Z | js/script-latest-opportunities.js | SheffieldAI/sheffieldai.github.io | 54692a9e933b8d17166e03f6cfea3022ab3fbab4 | [
"MIT"
] | 3 | 2022-03-01T21:18:05.000Z | 2022-03-01T21:22:17.000Z | js/script-latest-opportunities.js | SheffieldAI/sheffieldai.github.io | 54692a9e933b8d17166e03f6cfea3022ab3fbab4 | [
"MIT"
] | 1 | 2022-01-29T14:12:38.000Z | 2022-01-29T14:12:38.000Z | fetch('../json/opportunities.json')
.then(response => response.json())
.then(data => {
for (var i = 0; i < data.length && i < 3; i++) {
block_style = "color-bg-2";
button_style = "btn-main-2"
if (i % 2 === 0) {
block_style = "color-bg";
button_style = "btn-main"
}
var newsElement = data[i];
$('#latest-opportunities-section').append(
'<div class="col-lg-4 col-sm-6 mb-4 mb-lg-0">' +
'<div class="service-block p-4 ' + block_style + ' text-center">' +
'<a href="single-opportunity.html?id=' + newsElement["id"] + '"><h3>' + newsElement["title"] + '</h3></a>' +
'<i class="bi bi-alarm" > ' + newsElement["date"] + '</i>' +
'<p>' + newsElement["summary"] + '</p>' +
'<a class="btn ' + button_style + '" href="single-opportunity.html?id=' + newsElement["id"] + '">Read More</a>' +
'</div>' +
'</div>');
}
}); | 46.5 | 133 | 0.461388 |
438ca7f93d55ef3f13ab7014e1b7fdb1eb742185 | 2,311 | js | JavaScript | lib/GIScene/Layer/Grid/W3DS_0_4_1.js | Iamtarun78/3DGIS | f4853963d4e050c58ffe89cfe9ea61448d9102c1 | [
"MIT"
] | 106 | 2015-11-20T08:36:38.000Z | 2022-03-25T00:11:38.000Z | lib/GIScene/Layer/Grid/W3DS_0_4_1.js | TonyBJC/GIScene.js | 8058006860563f8901007a0b488b78b1cdf7af3d | [
"MIT"
] | 2 | 2016-07-30T11:02:41.000Z | 2018-10-31T03:58:12.000Z | lib/GIScene/Layer/Grid/W3DS_0_4_1.js | TonyBJC/GIScene.js | 8058006860563f8901007a0b488b78b1cdf7af3d | [
"MIT"
] | 33 | 2016-01-31T03:58:43.000Z | 2022-02-04T21:29:03.000Z | /**
* Tiled multi LOD grid layer using the W3DS v0.4.1 OGC Discussion Paper Specification to load georeferenced 3D data
* inherits from GIScene.Layer.Grid
*
* @namespace GIScene
* @class Layer.W3DS_0_4_1
* @constructor
* @extends GIScene.Layer.Grid
* @param {String} name the layer name
* @param {Object} [config] a configuration object
* @example
* var layerconfig = {
url:"http://www.example.org/w3ds",
// withCredentials:true,
layer:"DEM",
crs:"EPSG:32616",
origin:new GIScene.Coordinate2(264495.0,1639108.0),
offset:new GIScene.Coordinate3(264495.0,1639108.0,600), //w3ds GetScene offset param from this
tileSizes:[1024,512,256,128],
terrainHeight:600,
maxExtent: new GIScene.Extent2(new GIScene.Coordinate2(264495.0, 1639108.0), new GIScene.Coordinate2(274495.0, 1649108.0)),
maxDistance: 10000,
lodDistanceFactor :1.5,
format:GIScene.Format.Scene,
overrideMaterial : wmsOverlayMaterial,
overrideMaterialHandler : GIScene.OverrideMaterialHandler.WMS //only together with GIScene.WMSOverlayMaterial
// overrideMaterial : new THREE.MeshBasicMaterial({wireframe:true})
};
var layer = new GIScene.Layer.W3DS_0_4_1("w3ds",layerconfig);
scene.addLayer(layer);
*
*/
GIScene.Layer.W3DS_0_4_1 = function(name, config) {
GIScene.Layer.Grid.apply(this, [name, config]);
var defaults = {
layer : null,
crs : null,
tileSizes : [1024,512,256,128],
lods : null
};
// this.config = GIScene.Utils.mergeObjects(this.config, defaults);
this.config = GIScene.Utils.mergeObjects(defaults, this.config);
var w3dsConfig = {
url: this.url,
withCredentials : this.config.withCredentials,
tileSizes : this.config.tileSizes
};
var w3dsParams = {
crs : this.config.crs,
layer : this.config.layer,
offset : null,
lods : this.config.lods,
};
this.config.service = new GIScene.Service.W3DS_0_4_1(w3dsConfig, w3dsParams);
var onSetScene = function(event) {
console.log("w3ds onSetScene " + this.name);
var scene = event.content;
this.config.service.params.offset = (scene) ? this.grid.sceneOffset.toArray().join(",") : null;
}.bind(this);
this.addEventListener('setScene', onSetScene);
};
GIScene.Layer.W3DS_0_4_1.prototype = Object.create(GIScene.Layer.Grid.prototype);
| 32.097222 | 128 | 0.706188 |
438d3dd4050c4404b19ddc2c0a58473f404edbd7 | 1,533 | js | JavaScript | public/js/app.js | philippwinter/course-learning-platform | a8aef3329864f2de9c9e9677d5e9a9a3f182274d | [
"MIT"
] | 1 | 2020-04-19T09:25:29.000Z | 2020-04-19T09:25:29.000Z | public/js/app.js | philippwinter/course-learning-platform | a8aef3329864f2de9c9e9677d5e9a9a3f182274d | [
"MIT"
] | null | null | null | public/js/app.js | philippwinter/course-learning-platform | a8aef3329864f2de9c9e9677d5e9a9a3f182274d | [
"MIT"
] | null | null | null | /**
* Client side code for the whole application
*/
var helpers = {
entityMap : {
"&" : "&",
"<" : "<",
">" : ">",
'"' : '"',
"'" : ''',
"/" : '/'
},
escape : function(html) {
return String(html).replace(/[&<>"'\/]/g, function(s) {
return entityMap[s];
});
}
}
document.app = {
helpers : helpers,
dateFormat : "dd.MM.yyyy", // 01.02.2015
timeFormat : "HH:mm:ss", // 14:56:01
dateTimeFormat : "dd.MM.yyyy, HH:mm:ss" // 01.02.2015, 14:56:01
}
$(document).ready(
function() {
var formatNow = function(jThis, format) {
var isInput = jThis.is(":input");
var text;
if (isInput) {
text = jThis.val();
} else {
text = jThis.text();
}
var textAsInt = parseInt(text);
var parsed = textAsInt === NaN ? text : textAsInt;
var result = $.format.date(parsed, format);
//console.log(jThis);
//console.log(format);
//console.log(isInput);
//console.log("Got parsed: " + parsed + " (" + typeof parsed + ")");
//console.log("Got format: " + format);
//console.log("Got result: " + result);
if (isInput) {
jThis.val(result);
} else {
jThis.text(result);
}
}
$(".dateFormat").each(
function() {
formatNow($(this), document.app.dateFormat);
});
$(".timeFormat").each(
function() {
formatNow($(this), document.app.timeFormat);
});
$(".dateTimeFormat").each(
function() {
formatNow($(this), document.app.dateTimeFormat);
});
}); | 21.591549 | 72 | 0.530985 |
438d450623614ce8ecbf81b630d223249ef83f8d | 1,434 | js | JavaScript | babik_card_primitives/static/babik_card_primitives/js/card_validation.min.js | aubreystarktoller/django-babik-card-primitives | d380342652aeb394a8e7b6d952034465ec5618e4 | [
"BSD-3-Clause"
] | null | null | null | babik_card_primitives/static/babik_card_primitives/js/card_validation.min.js | aubreystarktoller/django-babik-card-primitives | d380342652aeb394a8e7b6d952034465ec5618e4 | [
"BSD-3-Clause"
] | null | null | null | babik_card_primitives/static/babik_card_primitives/js/card_validation.min.js | aubreystarktoller/django-babik-card-primitives | d380342652aeb394a8e7b6d952034465ec5618e4 | [
"BSD-3-Clause"
] | null | null | null | function cardNumberKnownIssuerTest(r){return null!==getCardIssuer(r)}function cardNumberIssuerWhitelistTest(r,e){var n=getCardIssuer(r);if(null!==n)for(var t=e.length,u=0;t>u;u++)if(e[u]==n)return!0;return False}function buildCardNumberIssuerWhitelistTest(r){return function(e){return cardNumberIssuerWhitelistTest(e,r)}}function buildCardNumberValidator(r){var e=[cardNumberLengthTest,cardNumberLuhnTest],n=/^\s*$/,t=!0;if("undefined"!=typeof r&&("undefined"==typeof r.required||r.required||(t=!1),"undefined"!=typeof r.issuerWhitelist)){var u=buildCardNumberIssuerWhitelistTest(r.issuer_whitelist);e.push(u)}var i=e.length;return function(r){var u=String(r);if(null!==u.match(n))return t?null:"";u=cleanCardNumber(r);for(var a=0;i>a;a++)if(!e[a](u))return null;return u}}var getCardIssuer=function(){var r=[],e=r.length;return function(n){for(var t,u,i=0;e>i;i++)if(u=r[i],t=u[0].match(n),null!==t)return[u[1],u[2]];return null}}(),cleanCardNumber=function(){var r=/[\s+]+/g,e=/([0-9])-([0-9])/g,n=/^[0-9]+$/;return function(t){var u=String(t);return u=u.replace(r,""),u=u.replace(e,"$1$2"),result=u.match(n),result?u:null}}(),cardNumberLuhnTest=function(){var r=[0,2,4,6,8,1,3,5,7,9];return function(e){for(var n,t=0,u=!0,i=String(e),a=i.length-1;a>=0;--a)n=parseInt(i.charAt(a),10),t+=u?n:r[n],u=!u;return t%10==0}}(),cardNumberLengthTest=function(){var r=10,e=25;return function(n){var t=String(n),u=t.length;return u>r&&e>u}}(); | 1,434 | 1,434 | 0.708508 |
438d8baf4252048f333eeeb0f6b1cf5990c1e86a | 1,956 | js | JavaScript | apps/routes/endpoints/index.js | k4r1suma/vt-api | 0e7d598445e93d6dc911d2650342beeb5a5cdf39 | [
"WTFPL"
] | null | null | null | apps/routes/endpoints/index.js | k4r1suma/vt-api | 0e7d598445e93d6dc911d2650342beeb5a5cdf39 | [
"WTFPL"
] | null | null | null | apps/routes/endpoints/index.js | k4r1suma/vt-api | 0e7d598445e93d6dc911d2650342beeb5a5cdf39 | [
"WTFPL"
] | null | null | null | const { Router } = require('../consts');
const router = Router();
module.exports = router;
/**
* /live - Displays live, upcoming, and ended videos.
* accepts: - status=string[]
* - title=string
* - group=string
*
* returns: {
* "live": array
* "upcoming": array
* "ended": array
* }
*/
router.use('/live', require('./live'));
/**
* /channels - Shows a list of all channels.
* accepts: - id=number
* - youtube=string
* - name=string
* - channel=string
* - fields=string[]
* - limit=number
*
* returns: [
* {
* "id": number,
* "name_jp": string,
* "name_en": string,
* "youtube": string,
* "twitter": string,
* "updated_at": number,
* "channel": string,
* "channel_stats": {
* "published_at": number,
* "views": number,
* "subscribers": number,
* "videos": number,
* },
* "description": string,
* "thumbnail": string
* }
* ]
*/
router.use('/channels', require('./channels'));
/**
* /videos - Shows a list of all videos.
* accepts: - status=string[]
* - title=string
* - fields=string[]
* - limit=number
*
* returns: [
* {
* "id": string,
* "title": string,
* "channel": string,
* "published_at": number,
* "scheduled_time": number,
* "start_time": number,
* "end_time": number,
* "length": number,
* "status": string
* }
* ]
*/
router.use('/videos', require('./videos'));
| 26.794521 | 58 | 0.397239 |
438dba52ae9145d9670d9d619bcc92de58d4b7c0 | 9,136 | js | JavaScript | assets/js/65.d35ce122.js | codeluosiyu/codeluosiyu.github.io | 56f8e71ac3bc20d4a508674db2d13a6376c62629 | [
"MIT"
] | 1 | 2022-03-13T01:03:59.000Z | 2022-03-13T01:03:59.000Z | assets/js/65.d35ce122.js | codeluosiyu/codeluosiyu.github.io | 56f8e71ac3bc20d4a508674db2d13a6376c62629 | [
"MIT"
] | null | null | null | assets/js/65.d35ce122.js | codeluosiyu/codeluosiyu.github.io | 56f8e71ac3bc20d4a508674db2d13a6376c62629 | [
"MIT"
] | null | null | null | (window.webpackJsonp=window.webpackJsonp||[]).push([[65],{483:function(t,e,n){"use strict";n.r(e);var a=n(25),s=Object(a.a)({},(function(){var t=this,e=t.$createElement,n=t._self._c||e;return n("ContentSlotsDistributor",{attrs:{"slot-key":t.$parent.slotKey}},[n("h3",{attrs:{id:"前言"}},[n("a",{staticClass:"header-anchor",attrs:{href:"#前言"}},[t._v("#")]),t._v(" 前言")]),t._v(" "),n("p",[t._v("前面已经介绍了浏览器的运行机制和Event Loop,我们从中可以得知")]),t._v(" "),n("h3",{attrs:{id:"回流与重绘"}},[n("a",{staticClass:"header-anchor",attrs:{href:"#回流与重绘"}},[t._v("#")]),t._v(" 回流与重绘")]),t._v(" "),n("p",[t._v("首先复习一下重绘和回流的概念:")]),t._v(" "),n("p",[n("strong",[t._v("回流")]),t._v(":当我们对 DOM 的修改引发了 DOM 几何尺寸的变化(比如修改元素的宽、高或隐藏元素等)时,浏览器需要重新计算元素的几何属性(其他元素的几何属性和位置也会因此受到影响),然后再将计算的结果绘制出来。这个过程就是回流(也叫重排)。")]),t._v(" "),n("p",[n("strong",[t._v("重绘")]),t._v(":当我们对 DOM 的修改导致了样式的变化、却并未影响其几何属性(比如修改了颜色或背景色)时,浏览器不需重新计算元素的几何属性、直接为该元素绘制新的样式(跳过了上图所示的回流环节)。这个过程叫做重绘。")]),t._v(" "),n("p",[t._v("由此我们可以看出,"),n("strong",[t._v("重绘不一定导致回流,回流一定会导致重绘")]),t._v("。硬要比较的话,回流比重绘做的事情更多,带来的开销也更大。但这两个说到底都是吃性能的,所以都不是什么善茬。我们在开发中,要从代码层面出发,尽可能把回流和重绘的次数最小化。")]),t._v(" "),n("h2",{attrs:{id:"哪些实际操作会导致回流与重绘"}},[n("a",{staticClass:"header-anchor",attrs:{href:"#哪些实际操作会导致回流与重绘"}},[t._v("#")]),t._v(" 哪些实际操作会导致回流与重绘")]),t._v(" "),n("p",[t._v("要避免回流与重绘的发生,最直接的做法是避免掉可能会引发回流与重绘的 DOM 操作,就好像拆弹专家在解决一颗炸弹时,最重要的是掐灭它的导火索。")]),t._v(" "),n("p",[t._v("触发重绘的“导火索”比较好识别——只要是不触发回流,但又触发了样式改变的 DOM 操作,都会引起重绘,比如背景色、文字色、可见性(可见性这里特指形如visibility: hidden这样不改变元素位置和存在性的、单纯针对可见性的操作,注意与display:none进行区分)等。为此,我们要着重理解一下那些可能触发回流的操作。")]),t._v(" "),n("h3",{attrs:{id:"回流的原因"}},[n("a",{staticClass:"header-anchor",attrs:{href:"#回流的原因"}},[t._v("#")]),t._v(" 回流的原因")]),t._v(" "),n("ul",[n("li",[t._v("最“贵”的操作:改变 DOM 元素的几何属性")])]),t._v(" "),n("p",[t._v("这个改变几乎可以说是“牵一发动全身”——当一个DOM元素的几何属性发生变化时,所有和它相关的节点(比如父子节点、兄弟节点等)的几何属性都需要进行重新计算,它会带来巨大的计算量。")]),t._v(" "),n("p",[t._v("常见的几何属性有 width、height、padding、margin、left、top、border 等等。此处不再给大家一一列举。有的文章喜欢罗列属性表格,但我相信我今天列出来大家也不会看、看了也记不住(因为太多了)。我自己也不会去记这些——其实确实没必要记,️一个属性是不是几何属性、会不会导致空间布局发生变化,大家写样式的时候完全可以通过代码效果看出来。多说无益,还希望大家可以多写多试,形成自己的“肌肉记忆”。")]),t._v(" "),n("ul",[n("li",[t._v("“价格适中”的操作:改变 DOM 树的结构")])]),t._v(" "),n("p",[t._v("这里主要指的是节点的增减、移动等操作。浏览器引擎布局的过程,顺序上可以类比于树的前序遍历——它是一个从上到下、从左到右的过程。通常在这个过程中,当前元素不会再影响其前面已经遍历过的元素。")]),t._v(" "),n("ul",[n("li",[t._v("最容易被忽略的操作:获取一些特定属性的值")])]),t._v(" "),n("p",[t._v("当你要用到像这样的属性:offsetTop、offsetLeft、 offsetWidth、offsetHeight、scrollTop、scrollLeft、scrollWidth、scrollHeight、clientTop、clientLeft、clientWidth、clientHeight 时,你就要注意了!")]),t._v(" "),n("p",[t._v("“像这样”的属性,到底是像什么样?——这些值有一个共性,就是需要通过"),n("strong",[t._v("即时计算")]),t._v("得到。因此浏览器为了获取这些值,也会进行回流。")]),t._v(" "),n("p",[t._v("除此之外,当我们调用了 getComputedStyle 方法,或者 IE 里的 currentStyle 时,也会触发回流。原理是一样的,都为求一个“即时性”和“准确性”。")]),t._v(" "),n("h3",{attrs:{id:"如何规避回流与重绘"}},[n("a",{staticClass:"header-anchor",attrs:{href:"#如何规避回流与重绘"}},[t._v("#")]),t._v(" 如何规避回流与重绘")]),t._v(" "),n("p",[t._v("了解了回流与重绘的“导火索”,我们就要尽量规避它们。但很多时候,我们不得不使用它们。当避无可避时,我们就要学会更聪明地使用它们。")]),t._v(" "),n("h5",{attrs:{id:"_1-减少回流-避免频繁改动"}},[n("a",{staticClass:"header-anchor",attrs:{href:"#_1-减少回流-避免频繁改动"}},[t._v("#")]),t._v(" 1.减少回流,避免频繁改动")]),t._v(" "),n("p",[t._v("有时我们想要通过多次计算得到一个元素的布局位置,我们可能会这样做:")]),t._v(" "),n("div",{staticClass:"language- extra-class"},[n("pre",{pre:!0,attrs:{class:"language-text"}},[n("code",[t._v('<!DOCTYPE html>\n<html lang="en">\n<head>\n <meta charset="UTF-8">\n <meta name="viewport" content="width=device-width, initial-scale=1.0">\n <meta http-equiv="X-UA-Compatible" content="ie=edge">\n <title>Document</title>\n <style>\n #el {\n width: 100px;\n height: 100px;\n background-color: yellow;\n position: absolute;\n }\n </style>\n</head>\n<body>\n <div id="el"></div>\n <script>\n // 获取el元素\n const el = document.getElementById(\'el\')\n // 这里循环判定比较简单,实际中或许会拓展出比较复杂的判定需求\n for(let i=0;i<10;i++) {\n el.style.top = el.offsetTop + 10 + "px";\n el.style.left = el.offsetLeft + 10 + "px";\n }\n <\/script>\n</body>\n</html>\n\n')])])]),n("p",[t._v("这样做,每次循环都需要获取多次“敏感属性”,是比较糟糕的。我们可以将其以 JS 变量的形式缓存起来,待计算完毕再提交给浏览器发出重计算请求:")]),t._v(" "),n("div",{staticClass:"language- extra-class"},[n("pre",{pre:!0,attrs:{class:"language-text"}},[n("code",[t._v('// 缓存offsetLeft与offsetTop的值\nconst el = document.getElementById(\'el\') \nlet offLeft = el.offsetLeft, offTop = el.offsetTop\n\n// 在JS层面进行计算\nfor(let i=0;i<10;i++) {\n offLeft += 10\n offTop += 10\n}\n\n// 一次性将计算结果应用到DOM上\nel.style.left = offLeft + "px"\nel.style.top = offTop + "px"\n\n')])])]),n("h5",{attrs:{id:"_2-避免逐条改变样式-使用类名去合并样式"}},[n("a",{staticClass:"header-anchor",attrs:{href:"#_2-避免逐条改变样式-使用类名去合并样式"}},[t._v("#")]),t._v(" 2.避免逐条改变样式,使用类名去合并样式")]),t._v(" "),n("p",[t._v("比如我们可以把这段单纯的代码:")]),t._v(" "),n("div",{staticClass:"language- extra-class"},[n("pre",{pre:!0,attrs:{class:"language-text"}},[n("code",[t._v("const container = document.getElementById('container')\ncontainer.style.width = '100px'\ncontainer.style.height = '200px'\ncontainer.style.border = '10px solid red'\ncontainer.style.color = 'red'\n\n")])])]),n("p",[t._v("优化成一个有 class 加持的样子:")]),t._v(" "),n("div",{staticClass:"language- extra-class"},[n("pre",{pre:!0,attrs:{class:"language-text"}},[n("code",[t._v('<!DOCTYPE html>\n<html lang="en">\n<head>\n <meta charset="UTF-8">\n <meta name="viewport" content="width=device-width, initial-scale=1.0">\n <meta http-equiv="X-UA-Compatible" content="ie=edge">\n <title>Document</title>\n <style>\n .basic_style {\n width: 100px;\n height: 200px;\n border: 10px solid red;\n color: red;\n }\n </style>\n</head>\n<body>\n <div id="container"></div>\n <script>\n const container = document.getElementById(\'container\')\n container.classList.add(\'basic_style\')\n <\/script>\n</body>\n</html>\n\n')])])]),n("p",[t._v("前者每次单独操作,都去触发一次渲染树更改,从而导致相应的回流与重绘过程。")]),t._v(" "),n("p",[t._v("合并之后,等于我们将所有的更改一次性发出,用一个 style 请求解决掉了。")]),t._v(" "),n("h3",{attrs:{id:"将dom-离线"}},[n("a",{staticClass:"header-anchor",attrs:{href:"#将dom-离线"}},[t._v("#")]),t._v(' 将DOM"离线"')]),t._v(" "),n("p",[t._v("我们上文所说的回流和重绘,都是在“该元素位于页面上”的前提下会发生的。一旦我们给元素设置 display: none,将其从页面上“拿掉”,那么我们的后续操作,将无法触发回流与重绘——这个将元素“拿掉”的操作,就叫做 DOM 离线化。")]),t._v(" "),n("p",[t._v("仍以我们上文的代码片段为例:")]),t._v(" "),n("div",{staticClass:"language- extra-class"},[n("pre",{pre:!0,attrs:{class:"language-text"}},[n("code",[t._v("const container = document.getElementById('container')\ncontainer.style.width = '100px'\ncontainer.style.height = '200px'\ncontainer.style.border = '10px solid red'\ncontainer.style.color = 'red'\n...(省略了许多类似的后续操作)\n\n")])])]),n("p",[t._v("离线化后就是这样:")]),t._v(" "),n("div",{staticClass:"language- extra-class"},[n("pre",{pre:!0,attrs:{class:"language-text"}},[n("code",[t._v("let container = document.getElementById('container')\ncontainer.style.display = 'none'\ncontainer.style.width = '100px'\ncontainer.style.height = '200px'\ncontainer.style.border = '10px solid red'\ncontainer.style.color = 'red'\n...(省略了许多类似的后续操作)\ncontainer.style.display = 'block'\n\n")])])]),n("p",[t._v("有的同学会问,拿掉一个元素再把它放回去,这不也会触发一次昂贵的回流吗?这话不假,但我们把它拿下来了,后续不管我操作这个元素多少次,每一步的操作成本都会非常低。当我们只需要进行很少的 DOM 操作时,DOM 离线化的优越性确实不太明显。一旦操作频繁起来,这“拿掉”和“放回”的开销都将会是非常值得的。")]),t._v(" "),n("h3",{attrs:{id:"浏览器flush队列"}},[n("a",{staticClass:"header-anchor",attrs:{href:"#浏览器flush队列"}},[t._v("#")]),t._v(" 浏览器Flush队列")]),t._v(" "),n("p",[t._v("以我们现在的知识基础,理解上面的优化操作并不难。那么现在我问大家一个问题:")]),t._v(" "),n("div",{staticClass:"language- extra-class"},[n("pre",{pre:!0,attrs:{class:"language-text"}},[n("code",[t._v("let container = document.getElementById('container')\ncontainer.style.width = '100px'\ncontainer.style.height = '200px'\ncontainer.style.border = '10px solid red'\ncontainer.style.color = 'red'\n\n")])])]),n("p",[t._v("这段代码里,浏览器进行了多少次的回流或重绘呢?")]),t._v(" "),n("p",[t._v("“width、height、border是几何属性,各触发一次回流;color只造成外观的变化,会触发一次重绘。”——如果你立刻这么想了,说明你是个能力不错的同学,认真阅读了前面的内容。那么我们现在立刻跑一跑这段代码,看看浏览器怎么说:")]),t._v(" "),n("p",[n("img",{attrs:{src:"https://user-gold-cdn.xitu.io/2018/10/4/1663f57519a785ab?w=1284&h=96&f=png&s=18506",alt:""}})]),t._v(" "),n("p",[t._v("这里为大家截取有“Layout”和“Paint”出镜的片段(这个图是通过 Chrome 的 Performance 面板得到的,后面会教大家用这个东西)。我们看到浏览器只进行了一次回流和一次重绘——和我们想的不一样啊,为啥呢?")]),t._v(" "),n("p",[t._v("因为现代浏览器是很聪明的。浏览器自己也清楚,如果每次 DOM 操作都即时地反馈一次回流或重绘,那么性能上来说是扛不住的。于是它自己缓存了一个 flush 队列,把我们触发的回流与重绘任务都塞进去,待到队列里的任务多起来、或者达到了一定的时间间隔,或者“不得已”的时候,再将这些任务一口气出队。因此我们看到,上面就算我们进行了 4 次 DOM 更改,也只触发了一次 Layout 和一次 Paint。")]),t._v(" "),n("p",[t._v("大家这里尤其小心这个“不得已”的时候。前面我们在介绍回流的“导火索”的时候,提到过有一类属性很特别,它们有很强的“即时性”。当我们访问这些属性时,浏览器会为了获得此时此刻的、最准确的属性值,而提前将 flush 队列的任务出队——这就是所谓的“不得已”时刻。具体是哪些属性值,我们已经在“最容易被忽略的操作”这个小模块介绍过了,此处不再赘述。")]),t._v(" "),n("h3",{attrs:{id:"总结"}},[n("a",{staticClass:"header-anchor",attrs:{href:"#总结"}},[t._v("#")]),t._v(" 总结")]),t._v(" "),n("p",[t._v("通篇浏览下来可能会有同学感到疑惑:既然浏览器已经为我们做了批处理优化,为什么我们还要自己操心这么多事情呢?今天避免这个明天避免那个,多麻烦!")]),t._v(" "),n("p",[t._v("问题在于,"),n("strong",[t._v("并不是所有的浏览器都是聪明的")]),t._v("。我们刚刚的性能图表,是 Chrome 的开发者工具呈现给我们的。Chrome 里行得通的东西,到了别处(比如 IE)就不一定行得通了。而我们并不知道用户会使用什么样的浏览器。如果不手动做优化,那么一个页面在不同的环境下就会呈现不同的性能效果,这对我们、对用户都是不利的,记住甲方是大爷、客户是上帝。因此,需要我们养成良好的编码习惯、从根源上解决问题,仍然是最周全的方法。")])])}),[],!1,null,null,null);e.default=s.exports}}]); | 9,136 | 9,136 | 0.66944 |
438dfc86bc489df0be2e7af3468e4dff4d2f9106 | 1,126 | js | JavaScript | scripts/do_graph.js | mandolyte/proskomma-experiments | cc04ae7299d20622fe1435382cc6b049b7a6a114 | [
"MIT"
] | null | null | null | scripts/do_graph.js | mandolyte/proskomma-experiments | cc04ae7299d20622fe1435382cc6b049b7a6a114 | [
"MIT"
] | null | null | null | scripts/do_graph.js | mandolyte/proskomma-experiments | cc04ae7299d20622fe1435382cc6b049b7a6a114 | [
"MIT"
] | null | null | null | const fse = require('fs-extra');
const { Proskomma } = require('Proskomma');
if (process.argv.length !== 4) {
console.log('USAGE: node do_graph.js <USFM/USX Path> <Query Path>');
process.exit(1);
}
const contentPath = process.argv[2];
let content;
try {
content = fse.readFileSync(contentPath);
} catch (err) {
console.log(`ERROR: Could not read from USFM/USX file '${contentPath}'`);
process.exit(1);
}
const contentType = contentPath.split('.').pop();
const queryPath = process.argv[3];
let query;
try {
query = fse.readFileSync(queryPath).toString();
} catch (err) {
console.log(`ERROR: Could not read query from file '${contentPath}'`);
process.exit(1);
}
const pk = new Proskomma();
//try {
let selectors = {
lang: { name: 'eng' },
abbr: { name: 'eng' },
};
pk.importDocument(
selectors,
contentType,
content,
);
/*
} catch (err) {
console.log(`ERROR: Could not import document: '${err}'\n`);
console.trace();
process.exit(1);
}
*/
pk.gqlQuery(query)
.then(output => console.log(JSON.stringify(output, null, 2)))
.catch(err => console.log(`ERROR: Could not run query: '${err}'`));
| 20.851852 | 75 | 0.650977 |
438e5cfa82b732c73c7078425d9c7f5fc5f137c1 | 68,658 | es6 | JavaScript | src/p2p/node.es6 | trick77/bcnode | 3aa6cf62c1b1568103ab0695cd19781f21ff55e2 | [
"MIT"
] | 2 | 2018-04-12T18:57:42.000Z | 2021-08-15T16:13:01.000Z | src/p2p/node.es6 | trick77/bcnode | 3aa6cf62c1b1568103ab0695cd19781f21ff55e2 | [
"MIT"
] | null | null | null | src/p2p/node.es6 | trick77/bcnode | 3aa6cf62c1b1568103ab0695cd19781f21ff55e2 | [
"MIT"
] | null | null | null | /**
* Copyright (c) 2017-present, blockcollider.org developers, All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*
* @flow
*/
/* global $Values */
import type { Engine } from '../engine'
type Socket = {
resume: () => {},
write: (msg: Buffer) => bool,
remoteAddress: string,
remotePort: number
}
const { inspect } = require('util')
const Url = require('url')
const queue = require('async/queue')
const bufferSplit = require('buffer-split')
const LRUCache = require('lru-cache')
const BN = require('bn.js')
const debug = require('debug')('bcnode:p2p:node')
const framer = require('frame-stream')
const inspectStream = require('inspect-stream')
const backpressureWriteStream = require('stream-write')
const logging = require('../logger')
const { BcBlock, Transaction } = require('../protos/core_pb')
const { parseBoolean } = require('../utils/config')
const { InitialPeer } = require('../protos/p2p_pb')
const Discovery = require('./discovery')
const { Multiverse } = require('../bc/multiverse')
const { BlockPool } = require('../bc/blockpool')
// const { validateBlockSequence } = require('../bc/validation')
const { networks } = require('../config/networks')
const { isDebugEnabled } = require('../debug')
export const MAX_HEADER_RANGE = Number(process.env.MAX_HEADER_RANGE) || 1000
export const MAX_DATA_RANGE = Number(process.env.MAX_DATA_RANGE) || 200
const BC_NETWORK: 'main'|'test'|'carter'|'mckinley'|'garfield'|'lincoln'|'kennedy'|'coolidge' = process.env.BC_NETWORK || 'main'
const { quorum, maximumWaypoints } = networks[BC_NETWORK]
const MIN_HEALTH_NET = process.env.MIN_HEALTH_NET === 'true'
const USER_QUORUM = parseInt(process.env.USER_QUORUM, 10) || quorum
const BC_MAX_CONNECTIONS = process.env.BC_MAX_CONNECTIONS || maximumWaypoints
const STRICT_SEND_BC = process.env.STRICT_SEND_BC || true
const DISABLE_IPH_TEST = parseBoolean(process.env.DISABLE_IPH_TEST)
const PEER_HEADER_SYNC_EXPIRE = 13660
const PEER_DATA_SYNC_EXPIRE = 15661
const _MAX_FRAME_SIZE = 16 * 1024 * 1024 // 16MB
const FRAMING_OPTS = {
lengthSize: 4,
getLength: function (buffer) {
return buffer.readUInt32BE(0)
},
maxSize: _MAX_FRAME_SIZE
}
const { contains, find, isEmpty, max, min, merge, range, values, splitEvery } = require('ramda')
const { MESSAGES, MSG_SEPARATOR } = require('./protocol')
const { encodeTypeAndData, encodeMessageToWire } = require('./codec')
// const FULL_NODE_MSGS = [
// MESSAGES.GET_BLOCK,
// MESSAGES.GET_BLOCKS,
// MESSAGES.BLOCKS,
// MESSAGES.BLOCK,
// MESSAGES.TX,
// MESSAGES.GET_TXS
// ]
process.on('uncaughtError', (err) => {
console.trace(err) // eslint-disable-line no-console
})
export class PeerNode {
_logger: Object // eslint-disable-line no-undef
_engine: Engine // eslint-disable-line no-undef
_interval: IntervalID // eslint-disable-line no-undef
_seededPeers: Object // eslint-disable-line no-undef
_multiverse: Multiverse // eslint-disable-line no-undef
_noDoubleSend: Object // eslint-disable-line no-undef
_blockPool: BlockPool // eslint-disable-line no-undef
_identity: string // eslint-disable-line no-undef
_scanner: Object // eslint-disable-line no-undef
_externalIP: string // eslint-disable-line no-undef
_knownBlocks: Object // eslint-disable-line no-undef
_discovery: Discovery // eslint-disable-line no-undef
_queue: Object // eslint-disable-line no-undef
_greetingRegister: Object // eslint-disable-line no-undef
constructor (engine: Engine) {
debug('--- NETWORK CONFIG ---\n' + JSON.stringify(networks[BC_NETWORK], null, 2))
this._engine = engine
this._multiverse = new Multiverse(engine.persistence) /// !important this is a (nonselective) multiverse
this._blockPool = new BlockPool(engine.persistence, engine._pubsub)
this._logger = logging.getLogger(__filename)
this._discovery = {
givenHostName: false
}
this._greetingRegister = {}
this._knownBlocks = LRUCache({
max: 1000
})
this._seededPeers = LRUCache({
max: 1000
})
this._noDoubleSent = LRUCache({
max: 500
})
this._queue = queue((task, cb) => {
if (task.keys) {
this._engine.persistence.getBulk(task.keys).then((res) => {
cb(null, res)
})
.catch((err) => {
cb(err)
})
} else {
this._engine.persistence.get(task).then((res) => {
cb(null, res)
})
.catch((err) => {
cb(err)
})
}
})
async function statusInterval () {
this._logger.info('active waypoints: ' + this._discovery.connected)
this._engine._emitter.emit('peerCount', this._discovery.connected)
if (this._discovery.connected < USER_QUORUM && MIN_HEALTH_NET !== true) {
try {
debug('local client restarting IPH and IPD tests')
await engine.persistence.put('bc.sync.initialpeerdata', 'pending')
await engine.persistence.put('bc.sync.initialpeerheader', 'pending')
await engine.persistence.put('bc.sync.initialpeernum', 0)
await engine.persistence.put('bc.sync.initialpeerevents', [])
await engine.persistence.put('bc.sync.initialpeer', new InitialPeer())
await engine.persistence.put('bc.dht.quorum', 0)
} catch (err) {
this._logger.error(err)
}
}
}
// monitor peer connection status and resync peer evauations if quorum is lost
setInterval(statusInterval.bind(this), 30900)
}
get blockpool (): BlockPool {
return this._blockPool
}
get multiverse (): Multiverse {
return this._multiverse
}
set multiverse (multiverse: Multiverse) {
this._multiverse = multiverse
}
async getLiteMultiverse (latest: Object): Promise<*> {
if (latest.getHeight() < 4) {
return Promise.resolve([
latest
])
}
const query = [
'bc.block.' + (latest.getHeight() - 1),
'bc.block.' + (latest.getHeight() - 2)
]
try {
const set = await this._engine.persistence.getBulk(query)
// if it is a valid set of multiple options send it otherwise resolve with the latest
if (set !== undefined && set !== false && set.length > 0) {
set.unshift(latest)
return Promise.resolve(set.sort((a, b) => {
if (new BN(a.getHeight()).gt(new BN(b.getHeight())) === true) {
return -1
}
if (new BN(a.getHeight()).lt(new BN(b.getHeight())) === true) {
return 1
}
return 0
}))
}
return Promise.resolve([latest])
} catch (err) {
this._logger.error(err)
this._logger.warn('multiverse not set on disk')
return Promise.resolve([latest])
}
}
qsend (conn: Socket, msg: Buffer): Promise<{address: string, success: bool, message: string, allSent?: bool}> {
return new Promise((resolve, reject) => {
const wireData = encodeMessageToWire(msg)
const address = `${conn.remoteAddress}:${conn.remotePort}`
try {
debug(`qsend(): about to write ${wireData.length}b`)
backpressureWriteStream(conn, wireData, function (err, open) {
if (err) {
debug(`qsend(): error while writing data ${err.message}`)
return resolve({
address,
success: false,
message: err.message
})
}
debug(`qsend(): wrote ${wireData.length}b`)
return resolve({
address,
success: true,
message: 'success'
})
})
} catch (err) {
if (err) {
return resolve({
address,
success: false,
message: err.message
})
}
return resolve({
address,
success: false,
message: 'connection lost'
})
}
})
}
/*
* resetPeerEvaluations
*/
async resetPeerEvaluations () {
debug('reseting peer evaluations')
await this._engine.persistence.put('bc.sync.initialpeerheader', 'pending')
await this._engine.persistence.put('bc.sync.initialpeerdata', 'pending')
await this._engine.persistence.put('bc.sync.initialpeernum', 0)
await this._engine.persistence.put('bc.sync.initialpeerevents', [])
await this._engine.persistence.put('bc.sync.initialpeer', new InitialPeer())
return Promise.resolve(true)
}
/*
* reset block (including transaction indexes) from block height height
*/
async resetBlocksFrom (height: number): Promise<boolean> {
if (height > 2) {
for (let i = 2; i < height; i++) {
const block = await this._engine.persistence.getBlockByHeight(i)
if (block !== null) {
await this._engine.persistence.delBlock(block.getHash())
}
}
}
return true
}
/*
* processPeerEvaluations
* From peristence determines if matches exist and begins the header sync loop if so this happens
*/
async processPeerEvaluations () {
try {
// loads events from disk, prevents multiple instantiations
debug('running processPeerEvaluations')
let events = await this._engine.persistence.get('bc.sync.initialpeerevents')
if (events === null) {
events = []
}
// if a peer has just been rejected this peer will be removed from events
const needsResyncData = await this._engine.persistence.getDecisivePeriodOfCrossChainBlocksStatus()
let roverSyncComplete = Object.values(needsResyncData).every(i => !i)
roverSyncComplete = true // TODO: Remove override after P2P sync complete
if (!roverSyncComplete) {
debug('process peer evaluation requested, rover sync not complete')
return false
}
// get the current synchronization peer context for headers and data
let initialPeer = await this._engine.persistence.get('bc.sync.initialpeer')
if (events === null || events.length === 0) {
debug(`events not available`)
return false
}
if (initialPeer === null) {
initialPeer = new InitialPeer()
}
// get the status of the data evaluation
const ipd = await this._engine.persistence.get('bc.sync.initialpeerdata')
const iph = await this._engine.persistence.get('bc.sync.initialpeerheader')
debug(`processPeerEvaluation running ipd: ${ipd} `)
// if the initial peer is present, remove the peer from the events log
if (!isEmpty(initialPeer.getAddress()) && ipd !== 'running' && iph !== 'running') {
debug(`removing peer ${initialPeer.getAddress()}`)
events = events.reduce((all, e) => {
if (e.address !== initialPeer.getAddress()) {
all.push(e)
}
return all
}, [])
await this._engine.persistence.put('bc.sync.initialpeerevents', events)
// delete all headers range
const latestBlock = await this._engine.persistence.get('bc.block.latest')
if (!latestBlock) {
this._logger.warn(`Couldn't get 'bc.block.latest' in processPeerEvaluations`)
return
}
const latestHeight = latestBlock.getHeight()
debug(`deleting header blocks from initial peer resetting initial peer evaluations`)
if (latestHeight > 2) {
for (let i = 2; i < latestHeight; i++) {
debug(`purging block bc.block.${i}`)
await this._engine.persistence.del(`bc.block.${i}`)
}
}
// reset IPH back to pending
await this._engine.persistence.put('bc.sync.initialpeerdata', 'pending')
// switch IPH from complete to running
await this._engine.persistence.put('bc.sync.initialpeerheader', 'running')
// ipd stage is running, check if the peer has not responded in time
} else if (ipd === 'running' && Number(new Date()) > Number(initialPeer.getExpires())) {
// this means the given peer has expired
debug(`peer has expired and events are being reset ${initialPeer.getExpires()}`)
events = events.reduce((all, e) => {
if (e.address !== initialPeer.getAddress()) {
all.push(e)
}
return all
}, [])
let latestHeightRaw = await this._engine.persistence.get('bc.data.latest')
debug(`after peer has expired resetting latest header height ${latestHeightRaw}`)
if (latestHeightRaw === null) {
await this._engine.persistence.put('bc.data.latest', 2)
latestHeightRaw = 2
}
const latestHeight = parseInt(latestHeightRaw, 10)
// remove the initial peer
await this._engine.persistence.del('bc.sync.initialpeer')
await this.resetBlocksFrom(latestHeight)
// if there are not enough peers left reset headers and try again
} else if (ipd === 'running') {
//
// let latestHeightRaw = await this._engine.persistence.get('bc.data.latest')
// if (latestHeightRaw === null) {
// await this._engine.persistence.put('bc.data.latest', 2)
// latestHeightRaw = 2
// }
// const latestHeight = parseInt(latestHeightRaw, 10)
// const latestBlock = await this._engine.persistence.get('bc.block.latest')
// if (!latestBlock) {
// this._logger.warn(`Couldn't get 'bc.block.latest' in processPeerEvaluations`)
// return
// }
// const from = latestHeight
// const to = min(latestHeight + 500, latestHeight + parseInt(latestBlock.getHeight(), 10))
// debug(`ipd: ${ipd} with latest height from: ${from} to: ${to}`)
// const fromBlock = await this._engine.persistence.get(`bc.block.${from}`)
// const toBlock = await this._engine.persistence.get(`bc.block.${to}`)
// const payload = encodeTypeAndData(MESSAGES.GET_DATA, [fromBlock.getHash(), toBlock.getHash()])
// const conn = find(
// ({ remoteAddress, remotePort }) => `${remoteAddress}:${remotePort}` === initialPeer.getAddress(),
// this._discovery.connections
// )
// if (!conn) {
// // unable to locate active connection
// this._logger.warn(`unable to find given connection ${initialPeer.getAddress()}`)
// // expire the peer and rerun processPeerEvaluations
// initialPeer.setExpires(1)
// await this._engine.persistence.put('bc.sync.initialpeer', initialPeer)
// debug('unable to find connection -> requesting peer evaluations')
// return this.processPeerEvaluations()
// } else {
// // connection exists
// debug('sending GET_DATA request to peer')
// const result = await this.qsend(conn, payload)
// if (result.success) {
// this._logger.info('successful update sent to peer')
// }
// }
// do not continue and evaluate the peer events -> return
// this assumes ipd is 'running'
// this assumes iph is 'complete'
return Promise.resolve(true)
}
// if there are less than 2 event pairs trigger resync
if (events.length < 2) {
this._logger.warn('peer sync evaluations incomplete\n > do not use a shared ip address\n > clear local chain storage\n > stop and start the local node\n')
await this._engine.persistence.put('bc.sync.initialpeerevents', events)
return Promise.resolve(true)
}
// only extract IPH events
debug(`events to be matched ${events.length}`)
const unmatched = events.reduce((table, e) => {
if (e !== undefined && e.address && e.address !== initialPeer.getAddress()) {
// only process the events of the initial Peer Eval type
if (e.type === 'initialpeerheaderStart') {
if (table[e.address] === undefined) {
table[e.address] = {
address: e.address,
startTime: false,
endTime: false,
block: false
}
}
table[e.address].startTime = e.timestamp
} else if (e.type === 'initialpeerheaderEnd') {
if (table[e.address] === undefined) {
table[e.address] = {
address: e.address,
startTime: false,
endTime: false,
block: false
}
}
table[e.address].endTime = e.timestamp
table[e.address].block = e.block
}
}
return table
}, {})
/* const matched =
* [{
* startTime: Number
* endTime: Number
* block: BcBlock
* }...]
*/
debug('unmatched events')
const matched = Object.keys(unmatched).reduce((pairs, addr) => {
if (unmatched[addr].startTime !== false &&
unmatched[addr].endTime !== false &&
unmatched[addr].block !== false) {
unmatched[addr].elapsed = unmatched[addr].endTime - unmatched[addr].startTime
pairs.push(unmatched[addr])
}
return pairs
}, [])
debug(`matched events: ${matched.length}`)
if (matched.length >= USER_QUORUM) {
// sort the matched pairs into a high to low array
// 1. use block height
// 2. use difficulty
debug(`${matched.length} matched events pass USER_QUORUM threshold hold ${USER_QUORUM}`)
const matchedSorted = matched.sort((a, b) => {
// TODO: Setup--validate both blocks (not txs)
// Blocks are the same A === B
if (a.block.getHash() === b.block.getHash()) {
// if a was faster than b push ok
if (a.elapsed < b.elapsed) {
return 1
}
if (a.elapsed > b.elapsed) {
return -1
}
return 0
}
// Block are not the same A !== B
if (new BN(a.block.getTotalDistance()).gte(new BN(b.block.getTotalDistance()))) {
if (new BN(a.block.getHeight()).gte(new BN(b.block.getHeight()))) {
// if a is faster at providing headers opt for a
if (a.elapsed < b.elapsed) {
return 1
}
// if the start time is earlier the peer connected earlier to the local node
if (new BN(a.startTime).lt(new BN(b.startTime))) {
return 1
}
return 0
}
return -1
// second option has greater total distance than the first
} else {
if (new BN(a.block.getHeight()).gt(new BN(b.block.getHeight()))) {
if (a.elapsed < b.elapsed) {
return -1
}
// if a has a greater block height push it forward
return 1
}
// if second option is also higher block height put forward
return -1
}
})
debug(`number of matches sorted: ${matchedSorted.length}`)
// asign initial sync peer
const initialSyncPeerRaw = matchedSorted[0] // Not a protobuf
const initialPeer = new InitialPeer()
initialPeer.setExpires(Number(new Date()) + PEER_HEADER_SYNC_EXPIRE)
debug(`assigning initial peer address as ${initialSyncPeerRaw.address}`)
initialPeer.setAddress(initialSyncPeerRaw.address)
await this._engine.persistence.put('bc.sync.initialpeer', initialPeer)
const latestBlock = await this._engine.persistence.get('bc.block.latest')
const payload = encodeTypeAndData(MESSAGES.HEADER, latestBlock)
// locate the connection
const conn = find(
({ remoteAddress, remotePort }) => `${remoteAddress}:${remotePort}` === initialPeer.getAddress(),
this._discovery.connections
)
if (conn) {
const result = await this.qsend(conn, payload)
if (result.success) {
this._logger.info('successful update sent to peer')
} else {
this._logger.warn('failed to send peer query')
}
} else {
this._logger.error('failed to assign connection')
}
} else {
this._logger.warn(`peer evaluation requested while below given quorum ${USER_QUORUM}`)
return Promise.resolve(true)
}
} catch (err) {
this._logger.error(err)
return Promise.reject(new Error(err))
}
}
/* sendPeerEvaluations
* tests each peer with the highest latest block
*/
async sendPeerEvaluations (): Promise<boolean> {
// get the local highest block
debug('sendPeerEvaluations(): running')
const latestBlock = await this._engine.persistence.get('bc.block.latest')
if (!latestBlock) {
this._logger.error('latest block does not exist unable to join peering network')
return false
}
const payload = encodeTypeAndData(MESSAGES.GET_BLOCK, [])
if (this._discovery !== undefined && this._discovery.connections.length > 0) {
debug(`IPH evaluations queued for ${this._discovery.connections.length} connection(s)`)
try {
for (const remoteConnection of this._discovery.connections) {
const address = `${remoteConnection.remoteAddress}:${remoteConnection.remotePort}`
debug(`sending eval to address ${address}, local latest block height ${latestBlock.getHeight()}`)
await this._engine.persistence.updateList('bc.sync.initialpeerevents', { address: address, timestamp: Number(new Date()), type: 'initialpeerheaderStart' })
await this.qsend(remoteConnection, payload)
}
return true
} catch (err) {
this._logger.error(err)
return false
}
} else {
throw new Error('unable to initialize header sync without peers')
}
}
/* checkInitialPeerHeaderStatus
* Determines if the performance testing blocks should be sent to peers
*/
async checkInitialPeerHeaderStatus (iph: string|null = null): Promise<boolean|Error> {
// get the iph state
// !!! this should not be run unless quorum has been achieved !!!
// 'pending' = iph evaluation evaluations are waiting for first candidate
// 'complete' = iph evaluation process has been completed
// 'error' = iph evaluation process has started
if (iph === null) {
iph = await this._engine.persistence.get('bc.sync.initialpeerheader')
// if it still is undefined fail the request
if (!iph) {
throw new Error('unable to determine status of initial peer evaluation')
}
}
debug(`current initialpeerheader state: ${iph}`)
// create list
if (iph === null || iph === undefined) {
return false
} else if (iph === 'pending') {
// switch rom pending to running and emit block challenges to peers
await this._engine.persistence.put('bc.sync.initialpeerheader', 'running')
// send the initial block calls to available peers in quorum
const evaluationsSent = await this.sendPeerEvaluations()
if (evaluationsSent !== true) {
debug('initial peer evaluations canceled')
return false
}
return true
} else if (iph === 'running') {
this._logger.info('yielding peer evaluation')
return false
} else if (iph === 'error') {
this._logger.error('critical error in initial block sync. Check log files.')
return false
}
return true
}
// async checkFailedSync () {
// const latestBlock = await this._engine.persistence.get('bc.block.latest')
// }
async start (nodeId: string) {
const discovery = new Discovery(nodeId)
this._discovery = discovery.start()
// set the sync state to pending, the initial peer number to 0,
await this._engine.persistence.put('bc.sync.initialpeerheader', 'pending') // set the iph status
await this._engine.persistence.put('bc.sync.initialpeerdata', 'pending') // set the ipd status
await this._engine.persistence.put('bc.sync.initialpeernum', 0) // reset the counter for peers
await this._engine.persistence.put('bc.sync.initialpeerevents', []) // empty the reports for block timing
await this._engine.persistence.del('bc.sync.initialpeer') // erase the peer
this._discovery.join(this._discovery.hash, this._discovery.port, (data) => {
this._engine._emitter.on('sendblockcontext', (msg) => {
if (msg.data.constructor === Array.constructor) return
const payload = encodeTypeAndData(MESSAGES.BLOCK, msg.data)
return this.qsend(msg.connection, payload)
})
this._engine._emitter.on('sendblock', (msg) => {
let type = MESSAGES.BLOCK
if (msg.type !== undefined) {
type = msg.type
}
const payload = encodeTypeAndData(type, msg.data)
this.qsend(msg.connection, payload)
.then(() => {
this._logger.info('block sent!')
})
.catch((err) => {
this._logger.warn('critical block rewards feature is failing with this error')
this._logger.error(err)
})
})
this._engine._emitter.on('announceblock', (msg: { data: BcBlock, filters: string[]|Array<{remoteAddr: string, remotePort: string}> }) => {
this._logger.info('announceblock <- event')
// this._engine.persistence.get('bc.block.' + msg.data.getHeight() - 1
// this.getLiteMultiverse(msg.data).then((list) => {
const payload = encodeTypeAndData(MESSAGES.BLOCK, msg.data)
const tasks = this._discovery.connections.map((conn) => {
const addr = conn.remoteAddress + ':' + conn.remotePort
if (msg.data.getHash !== undefined) {
if (this._noDoubleSent.get(addr + msg.data.getHash())) {
debug(`peer ${addr} has already sent block ${msg.data.getHash()}`)
return
}
}
return this.qsend(conn, payload)
})
return Promise.all(tasks).then(() => {
this._logger.info('block announced!')
})
.catch((err) => {
this._logger.warn('connection failure when announcing to network')
this._logger.error(err)
})
})
// event fired in engine when a new TX is accepted via RPC or as resend of such received pending TX
this._engine._emitter.on('announceTx', (msg: { data: Transaction, conn?: Object }) => {
const payload = encodeTypeAndData(MESSAGES.TX, msg.data)
const tasks = this._discovery.connections.map((conn) => { // TODO should filter out myself
if (msg.conn && conn.remoteAddress === msg.conn.remoteAddress && conn.remotePort === msg.conn.remotePort) {
return
}
return this.qsend(conn, payload)
})
return Promise.all(tasks).then(() => {
this._logger.info('Transactions announced!')
})
.catch((err) => {
this._logger.warn('connection failure when announcing to network')
this._logger.error(err)
})
})
this._logger.info('initialize far reaching discovery module')
/* Start multiverse sync */
this._discovery.on('connection', async (conn, info) => {
// pass connection to connection pool
// create peer sync group <- sort peers by best block
// sync backwards from top to bottom if a peer fails switch
// begin syncing after pool size
const needsResyncData = await this._engine.persistence.getDecisivePeriodOfCrossChainBlocksStatus()
let roverSyncComplete = Object.values(needsResyncData).every(i => !i)
roverSyncComplete = true
// greeting reponse to connection with provided host information and connection ID
const address = conn.remoteAddress + ':' + conn.remotePort
const iph = 'complete' // await this._engine._persistence.get('bc.sync.initialpeerheader')
// if the initial peer num has not been set we need to set it
// this could have happened if the local node crashed on startup
if (iph === null) {
await this._engine.persistence.put('bc.sync.initialpeerdata', 'pending')
await this._engine.persistence.put('bc.sync.initialpeerheader', 'pending')
await this._engine.persistence.put('bc.sync.initialpeernum', 0)
await this._engine.persistence.put('bc.sync.initialpeerevents', [])
}
// get heighest block
const quorumState = await this._engine.persistence.get('bc.dht.quorum')
let quorum = parseInt(quorumState, 10) // coerce for Flow
if (this._discovery.connected < USER_QUORUM && quorum === 1 && MIN_HEALTH_NET === false) {
// await this.persistence.put('bc.sync.initialpeerheader', 'pending') // peer min has fell below threshold reset flag
// await this.persistence.put('bc.sync.initialpeernum', 0) // peer min has fell below threshold reset counter
// await this.persistence.put('bc.sync.initialpeerevets', []) // peer min has fell below threshold reset counter
quorum = 0
await this._engine.persistence.put('bc.dht.quorum', 0)
} else if (this._discovery.connected >= USER_QUORUM && quorum === 0) {
quorum = 1
await this._engine.persistence.put('bc.dht.quorum', 1)
} else if (quorum === 0 && MIN_HEALTH_NET === true) {
quorum = 1
await this._engine.persistence.put('bc.dht.quorum', 1)
}
debug(`received connection from ${address}`, info)
debug(`-- peer metrics --\n roverSyncComplete: ${roverSyncComplete}\n iph: ${iph}\n quorum: ${quorum}`)
/// if IPH is complete add the peer's connection and pipe the data into peerDataHandler otherwise ignore it
if (iph === 'complete' && roverSyncComplete && quorum === 1) {
debug('iph: complete, roverSyncCompelte: true, quorum: 1, -> send latest block')
const latestBlock = await this._engine.persistence.get('bc.block.latest')
if (!latestBlock) {
this._logger.error(`latest block does not exist unable to join peering network at: ${address}`)
return
}
const payload = encodeTypeAndData(MESSAGES.BLOCK, latestBlock)
try {
// TODO send Handshake first
await this.qsend(conn, payload)
} catch (err) {
this._logger.debug(err)
}
// if rovers have completed a sync begin evaluating peers
} else if (iph !== 'complete' && DISABLE_IPH_TEST === false && roverSyncComplete && quorum === 1) {
debug('roverSyncComplete: true + quorum = 1, -> checkInitialPeerHeaderStatus')
try {
const iphStatus = await this.checkInitialPeerHeaderStatus(iph)
if (iphStatus !== true) {
debug(`warning initial Peer Evaluation Status = ${String(iphStatus)}`)
}
} catch (err) {
debug('critical error get initialpeerheaderStatus')
this._logger.error(err)
return
}
// if either rover sync is not complete or quorum has not been achieved
} else {
if (!roverSyncComplete) {
if (quorum === 0) {
this._logger.info('peer added to connection pool -> waiting for rovers "all clear" and quorum to be reached')
} else {
this._logger.info('peer added to connection pool -> waiting for rovers "all clear"')
}
} else {
// rovers sync is true so quorum = 0
this._logger.info('peer added to connection pool -> waiting for quorum to be achieved')
}
}
// always pipe the connection stream into the framer
// if (isDebugEnabled()) {
// conn.pipe(inspectStream((chunk) => debug(`received len: ${chunk.length}, beg: `, chunk)))
// }
conn.pipe(framer.decode(FRAMING_OPTS)).on('data', (data) => {
debug('piped data handler', data.slice(0, 7).toString('ascii'), data.length)
this.peerDataHandler(conn, info, data)
})
})
this._engine._emitter.on('getmultiverse', (obj) => {
const { data: { low, high } } = obj
const payload = encodeTypeAndData(MESSAGES.GET_MULTIVERSE, [low, high])
this.qsend(obj.connection, payload)
.then((res) => {
if (res.success && res.allSent) {
this._logger.info(`${payload.length} delivered in getmultiverse msg`)
}
})
.catch((err) => {
this._logger.error('critical write to peer socket failed')
this._logger.error(err)
})
})
// local <---- peer sent multiverse
this._engine._emitter.on('putmultiverse', (msg) => {
this._engine.getMultiverseHandler(msg.connection, msg.data)
.then((res) => {
this._logger.info(res)
})
.catch((err) => {
this._logger.error(err)
})
})
// local ----> get block list from peer
this._engine._emitter.on('getblocklist', (request) => {
const { low, high } = request.data
const payload = encodeTypeAndData(MESSAGES.GET_BLOCKS, [low, high])
this.qsend(request.connection, payload)
})
// local <---- peer sent blocks
this._engine._emitter.on('putblocklist', (msg) => {
this._engine.stepSyncHandler(msg)
.then(() => {
this._logger.debug('stepSync complete sent')
})
.catch((err) => {
this._logger.error(err)
})
})
// local <---- peer sent block
this._engine._emitter.on('putblock', (msg) => {
this._logger.debug('candidate block ' + msg.data.getHeight() + ' received')
let options = { fullBlock: false, sendOnFail: false }
if (msg.options) { options = merge(options, msg.options) }
debug('event->putblock tracing ipd and iph')
debug(msg.options)
this._engine.blockFromPeer(msg.connection, msg.data, options)
})
// local <---- peer sent tx
this._engine._emitter.on('puttx', (msg) => {
const { connection, data } = msg
this._logger.debug('Received new TX from peer')
this._engine.txFromPeer(connection, data)
})
// local <---- peer sent full block
this._engine._emitter.on('putfullblock', (msg) => {
const { connection, data } = msg
const options = { fullBlock: true, sendOnFail: false }
if (msg.options) { options = merge(options, msg.options) }
this._logger.debug('Received full block with TXs from peer')
debug('event->putblock tracing ipd and iph')
debug(msg.options)
data.map(block => this._engine.blockFromPeer(connection, block, options))
})
// local ----> get txs list from peer
this._engine._emitter.on('getTxs', (request) => {
const { dimension, id } = request
const payload = encodeTypeAndData(MESSAGES.GET_TXS, [dimension, id])
this._logger.debug(`Requesting full block(s) (${dimension}: ${id}) from peer`)
this.qsend(request.connection, payload)
})
// local ----> get header list from peer
this._engine._emitter.on('getheaders', (request) => {
const { low, high } = request.data
const payload = encodeTypeAndData(MESSAGES.GET_HEADERS, [low, high])
this.qsend(request.connection, payload)
})
// local ----> get header list from peer
this._engine._emitter.on('getdata', (request) => {
const [ low, high ] = request.data
const payload = encodeTypeAndData(MESSAGES.GET_DATA, [low, high])
this.qsend(request.connection, payload)
})
/*
* PEER SEEDER
*/
this._discovery._seeder = discovery.seeder()
this._discovery._seeder.on('peer', (peer) => {
if (this._discovery.connected > BC_MAX_CONNECTIONS) {
this._logger.info('passed on peer handle <- ' + this._discovery.connected + ' connections')
return
}
const channel = this._discovery.hash
const url = Url.parse(peer)
const h = url.href.split(':')
const obj: {
id?: string,
host: string,
port: number,
retries: number,
channel: Buffer,
remoteHost?: string,
remotePort?: number
} = {
// id: crypto.createHash('sha1').update(peer).digest('hex'),
host: h[0],
port: Number(h[1]) + 1, // seeder broadcasts listen on one port below the peers address
retries: 0,
channel: Buffer.from(channel)
}
obj.id = obj.host + ':' + obj.port
obj.remotePort = obj.port
obj.remoteHost = obj.host
try {
const name = obj.host + ':' + obj.port + this._discovery.hash
this._discovery._discovery.emit('peer', name, obj, 'utp')
} catch (err) {
this._logger.warn(`Error while constructing peer from discovered peer: ${inspect(peer)}`)
}
})
this._discovery._seeder.start()
this._engine._discovery = this._discovery
this._logger.info('joined waypoint table')
})
return Promise.resolve(true)
}
peerDataHandler (conn: Object, info: Object, str: Buffer) {
(async () => {
debug(`peerDataHandler() dsize: ${str.length} bufstart: ${str.slice(0, 7).toString('ascii')}`)
if (!str) {
debug(`peerDataHandler(): function called without payload`)
return
}
if (str.length < 7) {
debug(`peerDataHandler(): payload smaller than expected size ${str.length} < 7`)
return
}
if (str.length > _MAX_FRAME_SIZE) {
debug(`peerDataHandler(): payload larger than max frame size ${str.length} > ${_MAX_FRAME_SIZE}`)
return
}
debug(`received data start parse`)
// TODO: add lz4 compression for things larger than 1000 characters
const type: $Values<typeof MESSAGES> = str.slice(0, 7).toString('ascii')
if (!contains(type, values(MESSAGES))) {
debug(`unknown type received from peer`)
return
}
// if (type !== MESSAGES.BLOCK && BC_BT_VALIDATION !== true) {
// return
// }
let currentPeer = false
const iph = await this._engine.persistence.get('bc.sync.initialpeerheader')
// if the iph status is running and the message type is not a block or an announced tx ignore the message
if (DISABLE_IPH_TEST === false) {
if (iph === 'running' &&
// type !== MESSAGES.GET_BLOCK &&
// type !== MESSAGES.GET_HEADERS &&
// type !== MESSAGES.GET_HEADER &&
// type !== MESSAGES.TX &&
// type !== MESSAGES.TXS &&
// type !== MESSAGES.DATA &&
type !== MESSAGES.BLOCK &&
// type !== MESSAGES.BLOCKS &&
type !== MESSAGES.HEADER &&
type !== MESSAGES.HEADERS) {
debug(`ignoring type: ${type} message from peer`)
// check if current peer has expired
return
}
}
// check if the submission of the current peer was late
if (iph === 'running' && DISABLE_IPH_TEST === false) {
const ipd = await this._engine.persistence.get('bc.sync.initialpeerdata')
currentPeer = await this._engine.persistence.get('bc.sync.initialpeer')
// end the transaction if any of these events are true
// if no object represents current peer the node has not fully started up or has crashed during startup
// if expires is not defined the peer challenge was stored corruptly
// if the initial peer data variable is not pending then a new peer evaluation should not be run in parallel
if (ipd !== null && ipd !== 'pending') {
if (!currentPeer) {
// FIXME iph === 'running' implies ipd !== 'pending' <-- @Adam this is to prevent race condition event loop evaluates 2
debug(`current ipd: ${ipd}`)
this._logger.warn('prevented initial peer headers from performing concurrent requests')
return
}
// reprocess peer evaluations if the peer response below minimum
} else if (currentPeer !== null && Number(currentPeer.getExpires()) < Number(new Date())) {
this._logger.info('peer headers above timestamp threshold')
await this.processPeerEvaluations()
return
}
}
// Peer Sent Highest Block
if (type === MESSAGES.BLOCK) {
const ipd = await this._engine.persistence.get('bc.sync.initialpeerdata')
const address = conn.remoteAddress + ':' + conn.remotePort
debug(`peer BLOCK message received from address: ${address}`)
// determine if we are evaluating peer performance, if true do not put block and increment peer timer
const parts = bufferSplit(str, Buffer.from(MSG_SEPARATOR[type]))
const rawBlock = parts[1]
const block = BcBlock.deserializeBinary(rawBlock)
if (this._noDoubleSent.get(address + block.getHash())) {
this._noDoubleSent.set(address + block.getHash(), 1)
}
if (iph === 'running' && ipd === 'pending') {
const inc = await this._engine.persistence.inc('bc.sync.initialpeernum')
const updateData = {
address: address,
timestamp: Number(new Date()),
type: 'initialpeerheaderEnd',
block: block
}
await this._engine.persistence.updateList('bc.sync.initialpeerevents', updateData)
// if the increment is above quorum check results
debug(`evaluating increment for block speed ${inc} with USER_QUORUM ${USER_QUORUM}`)
if (inc >= USER_QUORUM) {
debug('connection pool is above quorum and ready to initiate peer evaluations -> setting iph to complete')
await this._engine.persistence.put('bc.sync.initialpeerheader', 'complete')
const peersEvaluated = await this.processPeerEvaluations()
if (peersEvaluated === true) {
debug(`peers have been evaluated`)
}
}
} else {
debug('iph is not running -> emit BC putBlock')
this._engine._emitter.emit('putblock', {
data: block,
connection: conn,
options: {
iph: iph,
ipd: ipd
}
})
}
// Peer Requests Highest Block
} else if (type === MESSAGES.GET_BLOCK) {
const address = conn.remoteAddress + ':' + conn.remotePort
debug(`received GET_BLOCK request from peer ${address}`)
const latestBlock = await this._engine.persistence.get('bc.block.latest')
const payload = encodeTypeAndData(MESSAGES.BLOCK, latestBlock)
const result = await this.qsend(conn, payload)
if (result.success) {
this._logger.info('successful update sent to peer')
} else {
this._logger.warn(result)
}
// Peer Requests Block Range
} else if (type === MESSAGES.GET_BLOCKS || type === MESSAGES.GET_MULTIVERSE) {
const address = conn.remoteAddress + ':' + conn.remotePort
debug(`received GET_BLOCKS request from peer ${address}`)
const parts = bufferSplit(str, Buffer.from(MSG_SEPARATOR[type]))
const low = parseInt(parts[1])
const high = parseInt(parts[2])
let outboundType = MESSAGES.BLOCKS
if (type === MESSAGES.GET_MULTIVERSE) {
outboundType = MESSAGES.MULTIVERSE
}
this._logger.info(`getblocklist handler: ${outboundType}, ${max(2, low)}, ${(high + 1)}`)
try {
const query = range(max(2, low), (high + 1)).map((n) => {
return 'bc.block.' + n
})
this._logger.info(query.length + ' blocks requested by peer: ' + conn.remoteAddress)
this._queue.push({ keys: query }, (err, blocks) => {
if (err) {
this._logger.warn(err)
} else {
const payload = encodeTypeAndData(outboundType, blocks)
this.qsend(conn, payload).then((res) => {
if (res.success && res.allSent) {
this._logger.info('sent message of length: ' + payload.length)
}
})
.catch((err) => {
this._logger.error(err)
})
}
})
} catch (err) {
this._logger.error(err)
}
// Peer Sends Challenge Block
} else if (type === '0011W01') { // TODO is this used / sent anywhere? if so add MESSAGES key
const parts = bufferSplit(str, Buffer.from(MSG_SEPARATOR[type]))
const rawBlock = parts[1]
const block = BcBlock.deserializeBinary(rawBlock)
this._engine._emitter.emit('putblock', {
data: block,
connection: conn
})
} else if (type === '0012W01') { // TODO is this used / sent anywhere? if so add MESSAGES key
const parts = bufferSplit(str, Buffer.from(MSG_SEPARATOR[type]))
const rawBlock = parts[1]
const block = BcBlock.deserializeBinary(rawBlock)
const ipd = await this._engine.persistence.get('bc.sync.initialpeerdata')
this._engine._emitter.emit('putblock', {
data: block,
options: {
sendOnFail: false,
ipd: ipd,
iph: iph
},
connection: conn
})
// Peer requests a specific header
} else if (type === MESSAGES.GET_HEADER) {
const address = conn.remoteAddress + ':' + conn.remotePort
debug(`received GET_HEADER request from peer ${address}`)
const latestBlock = await this._engine.persistence.get('bc.block.latest')
if (!latestBlock) {
this._logger.warn(`Could find 'bc.block.latest' while handling GET_HEADER message`)
return Promise.resolve(false)
}
latestBlock.clearTxsList()
const payload = encodeTypeAndData(MESSAGES.HEADER, latestBlock)
const result = await this.qsend(conn, payload)
if (result.success && result.allSent) {
this._logger.info('successful update sent to peer')
} else {
this._logger.warn('header delivery confirmation not available')
}
// Peer sends header to be evaluated and stored
} else if (type === MESSAGES.HEADER) {
const address = conn.remoteAddress + ':' + conn.remotePort
debug(`received HEADER from peer ${address}`)
// peer sending a header
const parts = bufferSplit(str, Buffer.from(MSG_SEPARATOR[type]))
const rawBlock = parts[1]
const receivedHeader = BcBlock.deserializeBinary(rawBlock)
// TODO: set up child blockchain headers
const latestBlock = await this._engine.persistence.get('bc.block.latest')
if (!latestBlock) {
this._logger.warn(`Could find 'bc.block.latest' while handling HEADER message`)
return Promise.resolve(false)
}
// if latest block is higher than header send missing blocks
if (latestBlock.getHeight() > receivedHeader.getHeight()) {
const range = Math.abs(latestBlock.getHeight() - receivedHeader.getHeight())
let from = parseInt(receivedHeader.getHeight(), 10)
if (from === 1) {
from = from + 1
}
// send only up to 1500 blocks (MAX_HEADER_RANGE)
const to = min(from + MAX_HEADER_RANGE, from + range)
debug(`from: ${from} to: ${to} range: ${range}`)
const headers = await this._engine.persistence.getBlocksByRange(from, to, 'bc', { asBuffer: true, asHeader: true })
debug(`sending ${headers.length} headers`)
const payload = encodeTypeAndData(MESSAGES.HEADERS, headers)
const result = await this.qsend(conn, payload)
if (result.success) {
this._logger.info('successful update sent to peer')
} else {
this._logger.info(result)
}
}
// Peer requests a range of headers
} else if (type === MESSAGES.GET_HEADERS) {
const address = conn.remoteAddress + ':' + conn.remotePort
debug(`received GET_HEADERS request from peer ${address}`)
// message shape 'GET_HEADERS[*]<blockchain>[*]<from>[*]<to>
const parts = bufferSplit(str, Buffer.from(MSG_SEPARATOR[type]))
let [, blockchain, _from, _to] = parts
let from = Number(_from)
if (from > 2) {
// padd from the from address with an additional block
from = from - 1
}
let to = Number(_to)
if (to <= 0) {
const latest = await this._engine.persistence.get('bc.block.latest')
if (!latest) {
this._logger.warn(`Could find 'bc.block.latest' while handling GET_HEADERS message to <= 0 branch`)
return Promise.resolve(false)
}
to = latest.getHeight()
}
const diff = to - from
const sendable = blockchain === 'bc'
// check if the header range requested is below limit and assert the send blockchain type is approved
if (diff > 0 && diff < (MAX_HEADER_RANGE + 1) && STRICT_SEND_BC === sendable) {
const headers = await this._engine.persistence.getBlocksByRange(from, to, blockchain, { asBuffer: true, asHeader: true })
// send block headers
const payload = encodeTypeAndData(MESSAGES.HEADERS, headers)
const result = await this.qsend(conn, payload)
if (result.success && result.allSent) {
this._logger.info('successful update sent to peer')
}
}
// Peer sends headers to be evaluated
} else if (type === MESSAGES.HEADERS) {
const address = conn.remoteAddress + ':' + conn.remotePort
const currentPeer = await this._engine.persistence.get('bc.sync.initialpeer')
debug(`received HEADERS from peer ${address}`)
// message shape 'HEADERS[*]<headers>
// if headers < 2000 || last header === current latest we know we have reached the edge of the peer's chain
const [, ...rawHeaders] = bufferSplit(str, Buffer.from(MSG_SEPARATOR[type]))
const unsortedHeaders = rawHeaders.map(h => BcBlock.deserializeBinary(h))
debug(`headers received ${unsortedHeaders.length}`)
const headers = unsortedHeaders.sort((a, b) => {
if (a.getHeight() > b.getHeight()) {
return 1
}
if (a.getHeight() < b.getHeight()) {
return -1
}
return 0
})
debug(`headers received from peer ${headers.length}`)
// const validSequence = validateBlockSequence(headers)
// Validate sequence of block headers
if (!currentPeer) {
debug('currentPeer is not defined')
}
// FIX: TODO: reanable valid sequence
// if (!validSequence) {
// debug('headers do not form a valid sequence')
// }
let passthrough = 1
debug(`connection address ${address} current peer address: ${currentPeer.getAddress()}`)
if (passthrough === 1 && currentPeer.getAddress() === address) {
const ipd = await this._engine.persistence.get('bc.sync.initialpeerdata')
const iph = await this._engine.persistence.get('bc.sync.initialpeerheader')
const latestBlock = await this._engine.persistence.get('bc.block.latest')
if (!latestBlock) {
this._logger.warn(`couldnt find 'bc.block.latest' while handling HEADERS message`)
return Promise.resolve(false)
}
const highestHeader = headers[headers.length - 1]
debug(`highest peer header (${currentPeer.getAddress()}) ${highestHeader.getHeight()} vs local ${latestBlock.getHeight()}`)
// if the received highest header block is above the latest block request a new set
for (let i = 0; i < headers.length; i++) {
await this._engine.persistence.put(`bc.block.${headers[i].getHeight()}`, headers[i])
}
if (latestBlock.getHeight() < highestHeader.getHeight() && headers.length > 1999) {
await this._engine.persistence.put('bc.block.latest', highestHeader)
// send back the current highest header
debug(`current peer ${currentPeer.getAddress()} successfully submitted headers`)
currentPeer.setExpires(Number(new Date()) + PEER_HEADER_SYNC_EXPIRE)
await this._engine.persistence.put('bc.sync.initialpeer', currentPeer)
await this._engine.persistence.put('bc.block.latest', highestHeader)
// send back the current highest header
const msg = encodeTypeAndData(MESSAGES.HEADER, highestHeader)
debug(`current peer ${currentPeer.getAddress()} successfully submitted headers`)
currentPeer.setExpires(Number(new Date()) + PEER_HEADER_SYNC_EXPIRE)
await this._engine.persistence.put('bc.sync.initialpeer', currentPeer)
await this.qsend(conn, msg)
/*
* Peer has recieved all headers
* - IPH test is considered complete
* - Now going to reset full body TXs
* - Could go to any peer, asking for hash range that match the hash range it has on disk
*/
} else if (ipd === 'pending' && iph !== 'complete') {
// if the header height is equal or greater then the header sync is complete
// set the current peer sync to the new data boundary
await this._engine.persistence.put('bc.block.latest', highestHeader)
debug(`current peer ${currentPeer.getAddress()} successfully completed header sync -> beginning tx ipd test`)
await this._engine.persistence.put('bc.sync.initialpeerdata', 'running')
currentPeer.setExpires(Number(new Date()) + PEER_DATA_SYNC_EXPIRE)
await this._engine.persistence.put('bc.sync.initialpeer', currentPeer)
// update the ipd status to running
await this._engine.persistence.put('bc.sync.initialpeerheader', 'complete')
// update the ipd status to running
await this._engine.persistence.put('bc.sync.initialpeernum', 0)
// reprocess peer evaluations with peer data sync equal to 'running'
debug('IPH test complete requesting peer evaluations for beginning of IPD tests')
let latestHeightRaw = await this._engine.persistence.get('bc.data.latest')
if (latestHeightRaw === null) {
await this._engine.persistence.put('bc.data.latest', 2)
latestHeightRaw = 2
}
const latestHeight = parseInt(latestHeightRaw, 10)
const latestBlock = await this._engine.persistence.get('bc.block.latest')
if (!latestBlock) {
this._logger.warn(`Couldn't get 'bc.block.latest' in processPeerEvaluations`)
return
}
const from = latestHeight
const to = min(latestHeight + 500, parseInt(latestBlock.getHeight(), 10))
debug(`ipd: ${ipd} with latest height from: ${from} to: ${to}`)
const fromBlock = await this._engine.persistence.get(`bc.block.${from}`)
const toBlock = await this._engine.persistence.get(`bc.block.${to}`)
debug(`fromBlock: ${fromBlock.getHeight()}`)
debug(`toBlock: ${toBlock.getHeight()}`)
const msg = [fromBlock.getHeight(), toBlock.getHeight()]
const payload = encodeTypeAndData(MESSAGES.GET_DATA, msg)
const result = await this.qsend(conn, payload)
debug('sent GET_DATA request to connection')
debug(result)
if (result.success) {
this._logger.info('successful data sent to peer')
} else {
this._logger.info(result)
}
}
}
// const parts = bufferSplit(str, Buffer.from(MSG_SEPARATOR[type]))
// const rawHeaders = parts[1]
// const headers = rawHeaders.map(b => BcBlock.deserializeBinary(b))
// this._engine._emitter.emit('putheaders', {
// data: headers,
// connection: conn
// })
// Peer requested a list of one or more data for tx hashes
} else if (type === MESSAGES.GET_DATA) {
const address = conn.remoteAddress + ':' + conn.remotePort
debug(`M.GET_DATA received GET_DATA request from peer ${address}`)
const parts = bufferSplit(str, Buffer.from(MSG_SEPARATOR[type]))
const [, ...rawHeights] = parts
const low = rawHeights[0]
const high = rawHeights[1]
const lowHashBlock = await this._engine.persistence.get('bc.block.' + low)
const highHashBlock = await this._engine.persistence.get('bc.block.' + high)
debug(`low: ${low}, high: ${high}`)
if (!lowHashBlock) {
debug(`M.GET_DATA unable to find lowHashBlock`)
}
if (!highHashBlock) {
debug(`M.GET_DATA unable to find highHashBlock`)
}
if (!lowHashBlock || !highHashBlock) {
debug(`M.GET_DATA unable to find blocks matching those hashes`)
if (!lowHashBlock) {
this._logger.error(`low hash for block height not found: ${lowHash}`)
}
if (!highHashBlock) {
this._logger.error(`high hash for block height not found: ${highHash}`)
}
return Promise.resolve(false)
}
const from = min(2, parseInt(lowHashBlock.getHeight(), 10))
const to = min(parseInt(lowHashBlock.getHeight(), 10) + MAX_DATA_RANGE, parseInt(highHashBlock.getHeight(), 10))
debug(`M.GET_DATA: getting tx data from range from: ${from} -> ${to}`)
const blockList = await this._engine.persistence.getBlocksByRange(from, to, 'bc', { asBuffer: true })
if (!blockList || !Array.isArray(blockList)) {
this._logger.warn(`could not getBlocksByRange(${from}, ${to}) while handling GET_DATA message`)
return Promise.resolve(false)
}
/*
* Format outbound data to only the hash and referenced txs
* [[
* hash of block,
* transaction[],
* markedTransaction[]
* ]...]
*/
// const txDataOnly = blockList.reduce((list, t) => {
// list.push(t.getHash())
// list.push(t.getTxsList())
// return list
// }, [])
const payload = encodeTypeAndData(MESSAGES.DATA, blockList)
const result = await this.qsend(conn, payload)
if (result.success === true) {
this._logger.info('successful update sent to peer')
}
} else if (type === MESSAGES.DATA) {
const address = conn.remoteAddress + ':' + conn.remotePort
debug(`received DATA from peer ${address}`)
// TODO: blacklist functionality should go here to prevent peers from requesting large bandwidth multiple times
const parts = bufferSplit(str, Buffer.from(MSG_SEPARATOR[type]))
const [, ...blocks] = parts
const latestBlock = await this._engine.persistence.get('bc.block.latest')
const ipd = await this._engine.persistence.get('bc.sync.initialpeerdata')
currentPeer = await this._engine.persistence.get('bc.sync.initialpeer')
if (ipd !== 'running') {
this._logger.warn(`peer transmitted data running !== ${String(ipd)}`)
return
}
if (!currentPeer) {
this._logger.warn(`cannot fetch currentPeer while handling DATA message`)
return false
// confirm peer is approved to be delivering data
} else if (currentPeer !== null && address !== currentPeer.getAddress()) {
this._logger.warn(`unapproved peer ${address} attempted data delivery`)
return
}
if (!latestBlock) {
this._logger.warn(`cannot find 'bc.block.latest' while handling DATA message`)
return false
}
let syncComplete = false
let validDataUpdate = true
let currentHeight = 2
for (let i = 0; i < blocks.length; i++) {
const newBlock = BcBlock.deserializeBinary(blocks[i])
const blockHeight = newBlock.getHeight()
// if the block is not defined or corrupt reject the transmission
debug(`loading newBlock: ${blockHeight}`)
const block = await this._engine.persistence.get(`bc.block.${blockHeight}`)
if (block === null || newBlock.getHash() != block.getHash()) {
// check if the peer simply sent more blocks
if (newBlock.getHeight() < latestBlock.getHeight()) {
debug(`newBlock ${newBlock.getHeight()} does not exist latestBlock ${latestBlock.getHeight()}`)
validDataUpdate = false
continue
}
}
// FIX: add block valid test
if (validDataUpdate === true) {
const stored = await this._engine.persistence.putBlock(newBlock, 0)
if (newBlock.getHash() === latestBlock.getHash() || newBlock.getHeight() > latestBlock.getHeight()) {
debug(`the sync is considered complete`)
syncComplete = true
}
// if valid set the new height
if (currentHeight < newBlock.getHeight()) {
currentHeight = parseInt(newBlock.getHeight(), 10)
}
}
}
// if peer sends invalid data it is rejected and removed from the peer data
if (validDataUpdate === false) {
// reset the best block to the lowest
debug('validDataUpdate === false setting bc.data.latest = 2')
await this._engine.persistence.put('bc.data.latest', 2)
// process peer evaluations seeking better candidate
debug('valid datate update is false requesting peer evaluations')
await this.processPeerEvaluations()
return
} else if (syncComplete === false) {
// update the request to the latest height
debug(`sync is not complete, highest height is ${currentHeight}`)
await this._engine.persistence.put('bc.data.latest', currentHeight)
// TODO: request more blocks from the highest
// get the current best block with data
const highestBlock = await this._engine.persistence.getBlockByHeight(currentHeight, 'bc', { asBuffer: true, asHeader: true })
// get the current best block hash + MAX_DATA_RANGE
const nextHeight = min(currentHeight + MAX_DATA_RANGE, currentHeight + parseInt(latestBlock.getHeight(), 10))
const nextHighestBlock = await this._engine.persistence.getBlockByHeight(nextHeight)
debug(`highestBlock: ${highestBlock.getHeight()} nextHighestBlock: ${nextHighestBlock}`)
this._engine._emitter.emit('getdata', {
data: [highestBlock.getHeight(), nextHighestBlock.getHeight()],
connection: conn
})
// FIX: here we should likely keep requesting blocks
} else if (syncComplete === true) {
// TODO: Node can start mining now
// START MINER HERE
debug('if rovers are done syncing the miner can now be initiated')
await this._engine.persistence.put('bc.sync.initialpeerdata', 'complete')
} else {
// TODO: request more blocks from the highest
// get the current best block with data
const highestBlock = await this._engine.persistence.getBlockByHeight(currentHeight, 'bc', { asBuffer: true, asHeader: true })
// get the current best block hash + MAX_DATA_RANGE
const nextHeight = min(currentHeight + MAX_DATA_RANGE, currentHeight + parseInt(latestBlock.getHeight(), 10))
const nextHighestBlock = await this._engine.persistence.getBlockByHeight(nextHeight)
debug(`highestBlock: ${highestBlock.getHeight()} nextHighestBlock: ${nextHighestBlock}`)
this._engine._emitter.emit('getdata', {
data: [highestBlock.getHeight(), nextHighestBlock.getHeight()],
connection: conn
})
}
// Peer Sends Block List 0007 // Peer Sends Multiverse 001
} else if (type === MESSAGES.BLOCKS || type === MESSAGES.MULTIVERSE) {
const ipd = await this._engine.persistence.get('bc.sync.initialpeerdata')
const address = conn.remoteAddress + ':' + conn.remotePort
debug(`received BLOCKS|MULTIVERSE data from peer ${address}`)
const parts = bufferSplit(str, Buffer.from(MSG_SEPARATOR[type]))
try {
parts.shift() // dicard type from the array
const list = parts.map(rawBlock => BcBlock.deserializeBinary(rawBlock))
const sorted = list.sort((a, b) => {
if (a.getHeight() > b.getHeight()) {
return -1 // move block forward
}
if (a.getHeight() < b.getHeight()) {
return 1 // move block forward
}
return 0
})
if (type === MESSAGES.BLOCKS && iph === 'complete' && ipd === 'complete') {
this._engine._emitter.emit('putblocklist', {
data: {
low: sorted[sorted.length - 1], // lowest block
high: sorted[0] // highest block
},
connection: conn
})
} else if (type === MESSAGES.MULTIVERSE && iph === 'complete' && ipd === 'complete') {
this._engine._emitter.emit('putmultiverse', {
data: sorted,
connection: conn
})
}
} catch (err) {
this._logger.debug('unable to parse: ' + type + ' from peer ')
}
} else if (type === MESSAGES.TX) {
this._logger.debug('Peer announced new TX')
const parts = bufferSplit(str, Buffer.from(MSG_SEPARATOR[type]))
const rawBlock = parts[1]
const tx = Transaction.deserializeBinary(rawBlock)
this._engine._emitter.emit('puttx', {
data: tx,
connection: conn
})
} else if (type === MESSAGES.GET_TXS) {
this._logger.debug('Peer requested TXs')
// message shape 'GET_TXS[*]<dimension>[*]<id>
const parts = bufferSplit(str, Buffer.from(MSG_SEPARATOR[type]))
const [, rawDimension, rawId] = parts
const dimension = JSON.parse(rawDimension)
const id = JSON.parse(rawId)
let blocks
switch (dimension) {
case 'hash':
// get full block with txs by blockHash
blocks = await this._engine.persistence.getBlockByHash(id, 'bc')
break
case 'height':
// get full block with txs by height
blocks = await this._engine.persistence.getBlocksByHeight(id, 'bc')
break
default:
this._logger.debug(`Invalid dimension for GET_TXS: ${dimension}`)
return Promise.resolve(true)
}
// send block with TXs
const payload = encodeTypeAndData(MESSAGES.TXS, blocks)
const result = await this.qsend(conn, payload)
if (result.success && result.allSent) {
this._logger.info('successful update sent to peer')
}
} else if (type === MESSAGES.TXS) {
// FIX: type not convertable to Uint8Array
debug('peer sent full raw blocks')
const parts = bufferSplit(str, Buffer.from(MSG_SEPARATOR[type]))
const [, ...rawBlocks] = parts
const blocks = rawBlocks.map(b => BcBlock.deserializeBinary(b))
this._engine._emitter.emit('putfullblock', {
data: blocks,
connection: conn
})
} else {
this._logger.info(`Unknown protocol flag received: ${type}`)
}
return Promise.resolve(true)
})().catch(err => {
this._logger.error(err)
})
}
broadcastNewBlock (block: BcBlock, withoutPeerId: ?Object) {
this._logger.debug(`broadcasting msg to peers, ${inspect(block.toObject())}`)
let filters = []
if (withoutPeerId) {
if (withoutPeerId.constructor === Array) {
filters = withoutPeerId
} else {
filters.push(withoutPeerId)
}
}
this._engine._emitter.emit('announceblock', { data: block, filters: filters })
}
}
export default PeerNode
| 44.381383 | 165 | 0.601838 |
438e874870e2d8537a69d6c8f112c47b77c08d0c | 1,338 | js | JavaScript | index.js | bernhardriegler/minio-s3-multifile-download-to-zip | 00f57dab12588f9282af9142f346f167ee95b75b | [
"MIT"
] | null | null | null | index.js | bernhardriegler/minio-s3-multifile-download-to-zip | 00f57dab12588f9282af9142f346f167ee95b75b | [
"MIT"
] | null | null | null | index.js | bernhardriegler/minio-s3-multifile-download-to-zip | 00f57dab12588f9282af9142f346f167ee95b75b | [
"MIT"
] | null | null | null | const Minio = require('minio')
const fs = require('fs')
const join = require('path').join
const archiver = require('archiver');
// Instantiate the minio client with the endpoint
// and access keys as shown below.
const minioClient = new Minio.Client({
endPoint: 'play.min.io',
port: 9000,
useSSL: true,
accessKey: 'Q3AM3UQ867SPQQA43P2F',
secretKey: 'zuf+tfteSlswRu7BJ86wekitnifILbZam1KYY3TG',
signatureVersion: 'v4',
s3ForcePathStyle: 'true',
});
const fileNames = [
'0.png',
'1.png',
'2.png',
]
// https://docs.min.io/docs/javascript-client-api-reference.html#getObject
async function downloadFileStream(filename) {
return minioClient.getObject('swa', filename)
}
async function run() {
const output = fs.createWriteStream(join(__dirname, 'archive.zip'));
const archive = archiver('zip');
output.on('close', function () {
console.log(archive.pointer() + ' total bytes');
console.log('archiver has been finalized and the output file descriptor has closed.');
});
archive.on('error', function (err) {
throw err;
});
archive.pipe(output);
for (const fileName of fileNames) {
const contents = await downloadFileStream(fileName);
archive.append(contents, { name: fileName });
}
archive.finalize();
}
run();
| 24.777778 | 94 | 0.660688 |