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 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
c616037fddcf1b5b18f4e7a037ad7d61bc1c7d5a | 356 | js | JavaScript | middleware/sigevent/web-app/js/dojox/grid/enhanced/nls/fr/EnhancedGrid.js | dataplumber/dmas | 34f3da0e71df5b2dd6b47b30687dd5438ca05435 | [
"Apache-2.0"
] | 2 | 2016-03-10T21:29:29.000Z | 2016-03-12T03:30:09.000Z | middleware/sigevent/web-app/js/dojox/grid/enhanced/nls/fr/EnhancedGrid.js | dataplumber/dmas | 34f3da0e71df5b2dd6b47b30687dd5438ca05435 | [
"Apache-2.0"
] | 29 | 2021-03-13T06:58:13.000Z | 2021-03-13T06:58:29.000Z | rollout/web/src/main/html/js/dojox/grid/enhanced/nls/fr/EnhancedGrid.js | dataplumber/dmas | 34f3da0e71df5b2dd6b47b30687dd5438ca05435 | [
"Apache-2.0"
] | null | null | null | ({"singleSort":"Tri simple","indirectSelectionRadio":"Ligne ${0}, sélection unique, bouton radio","ascending":"Croissant","indirectSelectionCheckBox":"Ligne ${0}, sélection multiple, case à cocher","selectAll":"Tout sélectionner","descending":"Décroissant","nestedSort":"Tri imbriqué","unsorted":"Ne pas trier cette colonne","sortingState":"${0} - ${1}"})
| 178 | 355 | 0.733146 |
c61613a740f02cf1a8bd14d09468113951dab460 | 276 | js | JavaScript | src/components/slidesFolder/EachSlide.js | lezzles11/small_pleasures | 06821d4c11ffe9fe131c70257a1e20f9fe983488 | [
"MIT"
] | null | null | null | src/components/slidesFolder/EachSlide.js | lezzles11/small_pleasures | 06821d4c11ffe9fe131c70257a1e20f9fe983488 | [
"MIT"
] | 1 | 2020-05-08T17:10:55.000Z | 2020-05-08T17:10:55.000Z | src/components/slidesFolder/EachSlide.js | lezzles11/Gatsby-First-Draft | 06821d4c11ffe9fe131c70257a1e20f9fe983488 | [
"MIT"
] | null | null | null | import React from "react"
function EachSlide({ text }) {
const style = {
color: "#37474f ",
fontSize: "4rem",
}
return (
<div>
<h1 style={style} className="font6">
{text}
</h1>{" "}
<br />
</div>
)
}
export default EachSlide
| 15.333333 | 42 | 0.514493 |
c616adb6f1be900795d0ce2ee08dc6e31d1a2439 | 12,364 | js | JavaScript | examples/jsm/renderers/webgl/nodes/WebGLNodeBuilder.js | Hyeong-jin/three.js | 1ba40183ecca92098af52ff580446c0252031a62 | [
"MIT"
] | 3 | 2015-04-20T13:54:52.000Z | 2021-11-28T04:41:44.000Z | examples/jsm/renderers/webgl/nodes/WebGLNodeBuilder.js | Hyeong-jin/three.js | 1ba40183ecca92098af52ff580446c0252031a62 | [
"MIT"
] | 1 | 2019-09-04T22:03:51.000Z | 2019-09-17T14:23:48.000Z | examples/jsm/renderers/webgl/nodes/WebGLNodeBuilder.js | Hyeong-jin/three.js | 1ba40183ecca92098af52ff580446c0252031a62 | [
"MIT"
] | 1 | 2020-09-28T11:39:03.000Z | 2020-09-28T11:39:03.000Z | import NodeBuilder, { defaultShaderStages } from 'three-nodes/core/NodeBuilder.js';
import NodeFrame from 'three-nodes/core/NodeFrame.js';
import SlotNode from './SlotNode.js';
import GLSLNodeParser from 'three-nodes/parsers/GLSLNodeParser.js';
import WebGLPhysicalContextNode from './WebGLPhysicalContextNode.js';
import { PerspectiveCamera, ShaderChunk, ShaderLib, UniformsUtils, UniformsLib,
LinearEncoding, RGBAFormat, UnsignedByteType, sRGBEncoding } from 'three';
const nodeFrame = new NodeFrame();
nodeFrame.camera = new PerspectiveCamera();
const nodeShaderLib = {
LineBasicNodeMaterial: ShaderLib.basic,
MeshBasicNodeMaterial: ShaderLib.basic,
PointsNodeMaterial: ShaderLib.points,
MeshStandardNodeMaterial: ShaderLib.standard
};
function getIncludeSnippet( name ) {
return `#include <${name}>`;
}
function getShaderStageProperty( shaderStage ) {
return `${shaderStage}Shader`;
}
class WebGLNodeBuilder extends NodeBuilder {
constructor( object, renderer, shader ) {
super( object, renderer, new GLSLNodeParser() );
this.shader = shader;
this.slots = { vertex: [], fragment: [] };
this._parseObject();
}
addSlot( shaderStage, slotNode ) {
this.slots[ shaderStage ].push( slotNode );
return this.addFlow( shaderStage, slotNode );
}
addFlowCode( code ) {
if ( ! /;\s*$/.test( code ) ) {
code += ';';
}
super.addFlowCode( code + '\n\t' );
}
_parseObject() {
const material = this.material;
let type = material.type;
// shader lib
if ( material.isMeshStandardNodeMaterial ) type = 'MeshStandardNodeMaterial';
else if ( material.isMeshBasicNodeMaterial ) type = 'MeshBasicNodeMaterial';
else if ( material.isPointsNodeMaterial ) type = 'PointsNodeMaterial';
else if ( material.isLineBasicNodeMaterial ) type = 'LineBasicNodeMaterial';
if ( nodeShaderLib[ type ] !== undefined ) {
const shaderLib = nodeShaderLib[ type ];
const shader = this.shader;
shader.vertexShader = shaderLib.vertexShader;
shader.fragmentShader = shaderLib.fragmentShader;
shader.uniforms = UniformsUtils.merge( [ shaderLib.uniforms, UniformsLib.lights ] );
}
if ( material.isMeshStandardNodeMaterial !== true ) {
this.replaceCode( 'fragment', getIncludeSnippet( 'tonemapping_fragment' ), '' );
}
// parse inputs
if ( material.colorNode && material.colorNode.isNode ) {
this.addSlot( 'fragment', new SlotNode( material.colorNode, 'COLOR', 'vec4' ) );
}
if ( material.opacityNode && material.opacityNode.isNode ) {
this.addSlot( 'fragment', new SlotNode( material.opacityNode, 'OPACITY', 'float' ) );
}
if ( material.normalNode && material.normalNode.isNode ) {
this.addSlot( 'fragment', new SlotNode( material.normalNode, 'NORMAL', 'vec3' ) );
}
if ( material.emissiveNode && material.emissiveNode.isNode ) {
this.addSlot( 'fragment', new SlotNode( material.emissiveNode, 'EMISSIVE', 'vec3' ) );
}
if ( material.metalnessNode && material.metalnessNode.isNode ) {
this.addSlot( 'fragment', new SlotNode( material.metalnessNode, 'METALNESS', 'float' ) );
}
if ( material.roughnessNode && material.roughnessNode.isNode ) {
this.addSlot( 'fragment', new SlotNode( material.roughnessNode, 'ROUGHNESS', 'float' ) );
}
if ( material.clearcoatNode && material.clearcoatNode.isNode ) {
this.addSlot( 'fragment', new SlotNode( material.clearcoatNode, 'CLEARCOAT', 'float' ) );
}
if ( material.clearcoatRoughnessNode && material.clearcoatRoughnessNode.isNode ) {
this.addSlot( 'fragment', new SlotNode( material.clearcoatRoughnessNode, 'CLEARCOAT_ROUGHNESS', 'float' ) );
}
if ( material.envNode && material.envNode.isNode ) {
const envRadianceNode = new WebGLPhysicalContextNode( WebGLPhysicalContextNode.RADIANCE, material.envNode );
const envIrradianceNode = new WebGLPhysicalContextNode( WebGLPhysicalContextNode.IRRADIANCE, material.envNode );
this.addSlot( 'fragment', new SlotNode( envRadianceNode, 'RADIANCE', 'vec3' ) );
this.addSlot( 'fragment', new SlotNode( envIrradianceNode, 'IRRADIANCE', 'vec3' ) );
}
if ( material.positionNode && material.positionNode.isNode ) {
this.addSlot( 'vertex', new SlotNode( material.positionNode, 'POSITION', 'vec3' ) );
}
if ( material.sizeNode && material.sizeNode.isNode ) {
this.addSlot( 'vertex', new SlotNode( material.sizeNode, 'SIZE', 'float' ) );
}
}
getTexture( textureProperty, uvSnippet ) {
return `texture2D( ${textureProperty}, ${uvSnippet} )`;
}
getTextureBias( textureProperty, uvSnippet, biasSnippet ) {
if ( this.material.extensions !== undefined ) this.material.extensions.shaderTextureLOD = true;
return `textureLod( ${textureProperty}, ${uvSnippet}, ${biasSnippet} )`;
}
getCubeTexture( textureProperty, uvSnippet ) {
return `textureCube( ${textureProperty}, ${uvSnippet} )`;
}
getCubeTextureBias( textureProperty, uvSnippet, biasSnippet ) {
if ( this.material.extensions !== undefined ) this.material.extensions.shaderTextureLOD = true;
return `textureLod( ${textureProperty}, ${uvSnippet}, ${biasSnippet} )`;
}
getUniforms( shaderStage ) {
const uniforms = this.uniforms[ shaderStage ];
let snippet = '';
for ( const uniform of uniforms ) {
if ( uniform.type === 'texture' ) {
snippet += `uniform sampler2D ${uniform.name}; `;
} else if ( uniform.type === 'cubeTexture' ) {
snippet += `uniform samplerCube ${uniform.name}; `;
} else {
const vectorType = this.getVectorType( uniform.type );
snippet += `uniform ${vectorType} ${uniform.name}; `;
}
}
return snippet;
}
getAttributes( shaderStage ) {
let snippet = '';
if ( shaderStage === 'vertex' ) {
const attributes = this.attributes;
for ( let index = 0; index < attributes.length; index ++ ) {
const attribute = attributes[ index ];
// ignore common attributes to prevent redefinitions
if ( attribute.name === 'uv' || attribute.name === 'position' || attribute.name === 'normal' )
continue;
snippet += `attribute ${attribute.type} ${attribute.name}; `;
}
}
return snippet;
}
getVarys( /* shaderStage */ ) {
let snippet = '';
const varys = this.varys;
for ( let index = 0; index < varys.length; index ++ ) {
const vary = varys[ index ];
snippet += `varying ${vary.type} ${vary.name}; `;
}
return snippet;
}
addCodeAfterSnippet( shaderStage, snippet, code ) {
const shaderProperty = getShaderStageProperty( shaderStage );
let source = this[ shaderProperty ];
const index = source.indexOf( snippet );
if ( index !== - 1 ) {
const start = source.substring( 0, index + snippet.length );
const end = source.substring( index + snippet.length );
source = `${start}\n${code}\n${end}`;
}
this[ shaderProperty ] = source;
}
addCodeAfterInclude( shaderStage, includeName, code ) {
const includeSnippet = getIncludeSnippet( includeName );
this.addCodeAfterSnippet( shaderStage, includeSnippet, code );
}
replaceCode( shaderStage, source, target ) {
const shaderProperty = getShaderStageProperty( shaderStage );
this.shader[ shaderProperty ] = this.shader[ shaderProperty ].replaceAll( source, target );
}
parseInclude( shaderStage, ...includes ) {
for ( const name of includes ) {
const includeSnippet = getIncludeSnippet( name );
const code = ShaderChunk[ name ];
this.replaceCode( shaderStage, includeSnippet, code );
}
}
getTextureEncodingFromMap( map ) {
const isWebGL2 = this.renderer.capabilities.isWebGL2;
if ( isWebGL2 && map && map.isTexture && map.format === RGBAFormat && map.type === UnsignedByteType && map.encoding === sRGBEncoding ) {
return LinearEncoding; // disable inline decode for sRGB textures in WebGL 2
}
return super.getTextureEncodingFromMap( map );
}
getFrontFacing() {
return 'gl_FrontFacing';
}
buildCode() {
const shaderData = {};
for ( const shaderStage of defaultShaderStages ) {
const uniforms = this.getUniforms( shaderStage );
const attributes = this.getAttributes( shaderStage );
const varys = this.getVarys( shaderStage );
const vars = this.getVars( shaderStage );
const codes = this.getCodes( shaderStage );
shaderData[ shaderStage ] = `${this.getSignature()}
// <node_builder>
// uniforms
${uniforms}
// attributes
${attributes}
// varys
${varys}
// vars
${vars}
// codes
${codes}
// </node_builder>
${this.shader[ getShaderStageProperty( shaderStage ) ]}
`;
}
this.vertexShader = shaderData.vertex;
this.fragmentShader = shaderData.fragment;
}
build() {
super.build();
this._addSnippets();
this._addUniforms();
this._updateUniforms();
this.shader.vertexShader = this.vertexShader;
this.shader.fragmentShader = this.fragmentShader;
return this;
}
getSlot( shaderStage, name ) {
const slots = this.slots[ shaderStage ];
for ( const node of slots ) {
if ( node.name === name ) {
return this.getFlowData( shaderStage, node );
}
}
}
_addSnippets() {
this.parseInclude( 'fragment', 'lights_physical_fragment' );
const colorSlot = this.getSlot( 'fragment', 'COLOR' );
const opacityNode = this.getSlot( 'fragment', 'OPACITY' );
const normalSlot = this.getSlot( 'fragment', 'NORMAL' );
const emissiveNode = this.getSlot( 'fragment', 'EMISSIVE' );
const roughnessNode = this.getSlot( 'fragment', 'ROUGHNESS' );
const metalnessNode = this.getSlot( 'fragment', 'METALNESS' );
const clearcoatNode = this.getSlot( 'fragment', 'CLEARCOAT' );
const clearcoatRoughnessNode = this.getSlot( 'fragment', 'CLEARCOAT_ROUGHNESS' );
const positionNode = this.getSlot( 'vertex', 'POSITION' );
const sizeNode = this.getSlot( 'vertex', 'SIZE' );
if ( colorSlot !== undefined ) {
this.addCodeAfterInclude(
'fragment',
'color_fragment',
`${colorSlot.code}\n\tdiffuseColor = ${colorSlot.result};`
);
}
if ( opacityNode !== undefined ) {
this.addCodeAfterInclude(
'fragment',
'alphatest_fragment',
`${opacityNode.code}\n\tdiffuseColor.a = ${opacityNode.result};`
);
}
if ( normalSlot !== undefined ) {
this.addCodeAfterInclude(
'fragment',
'normal_fragment_begin',
`${normalSlot.code}\n\tnormal = ${normalSlot.result};`
);
}
if ( emissiveNode !== undefined ) {
this.addCodeAfterInclude(
'fragment',
'emissivemap_fragment',
`${emissiveNode.code}\n\ttotalEmissiveRadiance = ${emissiveNode.result};`
);
}
if ( roughnessNode !== undefined ) {
this.addCodeAfterInclude(
'fragment',
'roughnessmap_fragment',
`${roughnessNode.code}\n\troughnessFactor = ${roughnessNode.result};`
);
}
if ( metalnessNode !== undefined ) {
this.addCodeAfterInclude(
'fragment',
'metalnessmap_fragment',
`${metalnessNode.code}\n\tmetalnessFactor = ${metalnessNode.result};`
);
}
if ( clearcoatNode !== undefined ) {
this.addCodeAfterSnippet(
'fragment',
'material.clearcoatRoughness = clearcoatRoughness;',
`${clearcoatNode.code}\n\tmaterial.clearcoat = ${clearcoatNode.result};`
);
}
if ( clearcoatRoughnessNode !== undefined ) {
this.addCodeAfterSnippet(
'fragment',
'material.clearcoatRoughness = clearcoatRoughness;',
`${clearcoatRoughnessNode.code}\n\tmaterial.clearcoatRoughness = ${clearcoatRoughnessNode.result};`
);
}
if ( positionNode !== undefined ) {
this.addCodeAfterInclude(
'vertex',
'begin_vertex',
`${positionNode.code}\n\ttransformed = ${positionNode.result};`
);
}
if ( sizeNode !== undefined ) {
this.addCodeAfterSnippet(
'vertex',
'gl_PointSize = size;',
`${sizeNode.code}\n\tgl_PointSize = ${sizeNode.result};`
);
}
for ( const shaderStage of defaultShaderStages ) {
this.addCodeAfterSnippet(
shaderStage,
'main() {',
this.flowCode[ shaderStage ]
);
}
}
_addUniforms() {
for ( const shaderStage of defaultShaderStages ) {
// uniforms
for ( const uniform of this.uniforms[ shaderStage ] ) {
this.shader.uniforms[ uniform.name ] = uniform;
}
}
}
_updateUniforms() {
nodeFrame.object = this.object;
nodeFrame.renderer = this.renderer;
for ( const node of this.updateNodes ) {
nodeFrame.updateNode( node );
}
}
}
export { WebGLNodeBuilder };
| 21.54007 | 138 | 0.677127 |
c617314c45205d4f27e08ec940780b26d57feac2 | 773 | js | JavaScript | src/robot-services/cleaning/houseCleaning/houseCleaningMinimal2.js | jbtibor/neato-sdk-js | d39379e5a65a55e46415e90db19b2aace6735efc | [
"MIT"
] | 36 | 2016-11-05T20:40:53.000Z | 2022-03-21T17:33:34.000Z | src/robot-services/cleaning/houseCleaning/houseCleaningMinimal2.js | jbtibor/neato-sdk-js | d39379e5a65a55e46415e90db19b2aace6735efc | [
"MIT"
] | 15 | 2016-11-16T11:11:19.000Z | 2022-02-21T15:32:58.000Z | src/robot-services/cleaning/houseCleaning/houseCleaningMinimal2.js | jbtibor/neato-sdk-js | d39379e5a65a55e46415e90db19b2aace6735efc | [
"MIT"
] | 16 | 2016-11-22T12:56:48.000Z | 2020-10-10T13:48:30.000Z | Neato.Services.houseCleaning_minimal2 = {
startHouseCleaning: function(options) {
options = options || {};
var message = {
reqId: "1",
cmd: "startCleaning",
params: {
category: Neato.Constants.CLEAN_HOUSE_MODE,
navigationMode: options.navigationMode || Neato.Constants.EXTRA_CARE_OFF
}
};
return this.__call(message);
},
supportEcoTurboMode: function() {
return false;
},
supportFrequency: function() {
return false;
},
supportExtraCare: function() {
return true;
},
stopCleaning: Neato.Services.cleaning.stopCleaning,
pauseCleaning: Neato.Services.cleaning.pauseCleaning,
resumeCleaning: Neato.Services.cleaning.resumeCleaning,
sendToBase: Neato.Services.cleaning.sendToBase
};
| 25.766667 | 80 | 0.689521 |
c617662f735a1a1ffc589734c392a49d7b6dd28d | 1,467 | js | JavaScript | tests/empty.spec.js | shimisnow/utm-manager | b618aeb7ca2e9da6028f25757571d4242519bff2 | [
"MIT"
] | null | null | null | tests/empty.spec.js | shimisnow/utm-manager | b618aeb7ca2e9da6028f25757571d4242519bff2 | [
"MIT"
] | 1 | 2021-05-11T00:01:02.000Z | 2021-05-11T00:01:02.000Z | tests/empty.spec.js | shimisnow/utm-manager | b618aeb7ca2e9da6028f25757571d4242519bff2 | [
"MIT"
] | null | null | null | const UTMManager = require('../dist/utm-manager.min')
describe('UTMManager Test - empty()', () => {
it('empty().result() - false', () => {
const utm = new UTMManager('utm_source=source&utm_medium=medium&utm_campaign=campaign')
expect(
utm.is('utm_source')
.empty()
.result()
).toBeFalsy()
})
it('empty().result() - true', () => {
const utm = new UTMManager('utm_source=source&utm_medium=medium&utm_campaign=campaign')
expect(
utm.is('utm_term')
.empty()
.result()
).toBeTruthy()
})
it('defined().and().empty().result() - true', () => {
const utm = new UTMManager('utm_source=source&utm_medium=medium&utm_campaign=campaign&utm_term=')
expect(
utm.is('utm_term')
.defined()
.and()
.empty()
.result()
).toBeTruthy()
})
it('defined().and().empty().result() - false (undefined)', () => {
const utm = new UTMManager('utm_source=source&utm_medium=medium&utm_campaign=campaign')
expect(
utm.is('utm_term')
.defined()
.and()
.empty()
.result()
).toBeFalsy()
})
it('defined().and().empty().result() - false (defined but not empty)', () => {
const utm = new UTMManager('utm_source=source&utm_medium=medium&utm_campaign=campaign&utm_term=term')
expect(
utm.is('utm_term')
.defined()
.and()
.empty()
.result()
).toBeFalsy()
})
})
| 23.66129 | 105 | 0.562372 |
c618646fdcc17e02c0aa821e23546ff7a18b3f5f | 925 | js | JavaScript | src/pages/404.js | theAdhocracy/theadhocracy-web | d0cd8ee68bd8d980e35a58dbeff4aa685a2d1a05 | [
"MIT"
] | null | null | null | src/pages/404.js | theAdhocracy/theadhocracy-web | d0cd8ee68bd8d980e35a58dbeff4aa685a2d1a05 | [
"MIT"
] | 3 | 2021-09-02T06:18:13.000Z | 2022-02-19T00:44:32.000Z | src/pages/404.js | theAdhocracy/theadhocracy-web | d0cd8ee68bd8d980e35a58dbeff4aa685a2d1a05 | [
"MIT"
] | null | null | null | import React from "react"
import { Link } from "gatsby"
import Layout from "../components/layout"
const FourOhFour = () => {
return (
<Layout title="oh no!" sidebar={false}>
<section id="content">
<header>
<h1>
404: Someone screwed up{" "}
<span role="img" aria-label="Nervous and sad">
😥
</span>
</h1>
</header>
<p>
Looks like you tried to find a page which doesn't exist. If you think the page <em>used to</em> exist then please let me know and I'll check it out.
</p>
<p>
Otherwise, why not take a look around? Try <Link to="/search/">searching</Link> if you think you were close, or head back <Link to="/">home</Link> to see the latest things going on around here.
</p>
<p>
Thanks for dropping by{" "}
<span role="img" aria-label="Thumbs up">
👍
</span>
</p>
</section>
</Layout>
)
}
export default FourOhFour
| 26.428571 | 198 | 0.597838 |
c618bcc0ffcf6bb723fadd7dc795eec5c1739797 | 20,850 | js | JavaScript | sites/all/libraries/plupload/src/javascript/jquery.ui.plupload.js | eolchina/CASBRAHMS-node | f15893126141869c69b89aaca600975db962c8a5 | [
"MIT"
] | null | null | null | sites/all/libraries/plupload/src/javascript/jquery.ui.plupload.js | eolchina/CASBRAHMS-node | f15893126141869c69b89aaca600975db962c8a5 | [
"MIT"
] | null | null | null | sites/all/libraries/plupload/src/javascript/jquery.ui.plupload.js | eolchina/CASBRAHMS-node | f15893126141869c69b89aaca600975db962c8a5 | [
"MIT"
] | null | null | null | /**
* jquery.ui.plupload.js
*
* Copyright 2009, Moxiecode Systems AB
* Released under GPL License.
*
* License: http://www.plupload.com/license
* Contributing: http://www.plupload.com/contributing
*
* Depends:
* jquery.ui.core.js
* jquery.ui.widget.js
*
* Optionally:
* jquery.ui.button.js
* jquery.ui.progressbar.js
* jquery.ui.sortable.js
*/
// JSLint defined globals
/*global window:false, document:false, plupload:false, jQuery:false */
(function(window, document, plupload, $, undef) {
var uploaders = {};
function _(str) {
return plupload.translate(str) || str;
}
function renderUI(obj) {
obj.html(
'<div class="plupload_wrapper">' +
'<div class="ui-widget-content plupload_container">' +
'<div class="plupload">' +
'<div class="ui-state-default ui-widget-header plupload_header">' +
'<div class="plupload_header_content">' +
'<div class="plupload_header_title">' + _('Select files') + '</div>' +
'<div class="plupload_header_text">' + _('Add files to the upload queue and click the start button.') + '</div>' +
'</div>' +
'</div>' +
'<div class="plupload_content">' +
'<table class="plupload_filelist">' +
'<tr class="ui-widget-header plupload_filelist_header">' +
'<td class="plupload_cell plupload_file_name">' + _('Filename') + '</td>' +
'<td class="plupload_cell plupload_file_status">' + _('Status') + '</td>' +
'<td class="plupload_cell plupload_file_size">' + _('Size') + '</td>' +
'<td class="plupload_cell plupload_file_action"> </td>' +
'</tr>' +
'</table>' +
'<div class="plupload_scroll">' +
'<table class="plupload_filelist_content"></table>' +
'</div>' +
'<table class="plupload_filelist">' +
'<tr class="ui-widget-header ui-widget-content plupload_filelist_footer">' +
'<td class="plupload_cell plupload_file_name">' +
'<div class="plupload_buttons"><!-- Visible -->' +
'<a class="plupload_button plupload_add">' + _('Add Files') + '</a> ' +
'<a class="plupload_button plupload_start">' + _('Start Upload') + '</a> ' +
'<a class="plupload_button plupload_stop plupload_hidden">'+_('Stop Upload') + '</a> ' +
'</div>' +
'<div class="plupload_started plupload_hidden"><!-- Hidden -->' +
'<div class="plupload_progress plupload_right">' +
'<div class="plupload_progress_container"></div>' +
'</div>' +
'<div class="plupload_cell plupload_upload_status"></div>' +
'<div class="plupload_clearer"> </div>' +
'</div>' +
'</td>' +
'<td class="plupload_file_status"><span class="plupload_total_status">0%</span></td>' +
'<td class="plupload_file_size"><span class="plupload_total_file_size">0 kb</span></td>' +
'<td class="plupload_file_action"></td>' +
'</tr>' +
'</table>' +
'</div>' +
'</div>' +
'</div>' +
'<input class="plupload_count" value="0" type="hidden">' +
'</div>'
);
}
$.widget("ui.plupload", {
contents_bak: '',
runtime: null,
options: {
browse_button_hover: 'ui-state-hover',
browse_button_active: 'ui-state-active',
// widget specific
dragdrop : true,
multiple_queues: true, // re-use widget by default
buttons: {
browse: true,
start: true,
stop: true
},
autostart: false,
sortable: false,
rename: false,
max_file_count: 0 // unlimited
},
FILE_COUNT_ERROR: -9001,
_create: function() {
var self = this, id, uploader;
id = this.element.attr('id');
if (!id) {
id = plupload.guid();
this.element.attr('id', id);
}
this.id = id;
// backup the elements initial state
this.contents_bak = this.element.html();
renderUI(this.element);
// container, just in case
this.container = $('.plupload_container', this.element).attr('id', id + '_container');
// list of files, may become sortable
this.filelist = $('.plupload_filelist_content', this.container).attr('id', id + '_filelist');
// buttons
this.browse_button = $('.plupload_add', this.container).attr('id', id + '_browse');
this.start_button = $('.plupload_start', this.container).attr('id', id + '_start');
this.stop_button = $('.plupload_stop', this.container).attr('id', id + '_stop');
if ($.ui.button) {
this.browse_button.button({
icons: { primary: 'ui-icon-circle-plus' }
});
this.start_button.button({
icons: { primary: 'ui-icon-circle-arrow-e' },
disabled: true
});
this.stop_button.button({
icons: { primary: 'ui-icon-circle-close' }
});
}
// all buttons are optional, so they can be disabled and hidden
if (!this.options.buttons.browse) {
this.browse_button.button('disable').hide();
$('#' + id + self.runtime + '_container').hide();
}
if (!this.options.buttons.start) {
this.start_button.button('disable').hide();
}
if (!this.options.buttons.stop) {
this.stop_button.button('disable').hide();
}
// progressbar
this.progressbar = $('.plupload_progress_container', this.container);
if ($.ui.progressbar) {
this.progressbar.progressbar();
}
// counter
this.counter = $('.plupload_count', this.element)
.attr({
id: id + '_count',
name: id + '_count'
});
// initialize uploader instance
uploader = this.uploader = uploaders[id] = new plupload.Uploader($.extend({
container: id ,
browse_button: id + '_browse'
}, this.options));
uploader.bind('Init', function(up, res) {
if (!self.options.unique_names && self.options.rename) {
self._enableRenaming();
}
if (uploader.features.dragdrop && self.options.dragdrop) {
self._enableDragAndDrop();
}
self.container.attr('title', _('Using runtime: ') + (self.runtime = res.runtime));
self.start_button.click(function(e) {
if (!$(this).button('option', 'disabled')) {
self.start();
}
e.preventDefault();
});
self.stop_button.click(function(e) {
uploader.stop();
e.preventDefault();
});
});
// check if file count doesn't exceed the limit
if (self.options.max_file_count) {
uploader.bind('FilesAdded', function(up, files) {
var length = files.length, removed = [];
if (length > self.options.max_file_count) {
removed = files.splice(self.options.max_file_count);
up.trigger('Error', {
code : self.FILE_COUNT_ERROR,
message : _('File count error.'),
file : removed
});
}
});
}
// uploader internal events must run first
uploader.init();
uploader.bind('FilesAdded', function(up, files) {
self._trigger('selected', null, { up: up, files: files } );
if (self.options.autostart) {
self.start();
}
});
uploader.bind('FilesRemoved', function(up, files) {
self._trigger('removed', null, { up: up, files: files } );
});
uploader.bind('QueueChanged', function() {
self._updateFileList();
});
uploader.bind('StateChanged', function() {
self._handleState();
});
uploader.bind('UploadFile', function(up, file) {
self._handleFileStatus(file);
});
uploader.bind('FileUploaded', function(up, file) {
self._handleFileStatus(file);
self._trigger('uploaded', null, { up: up, file: file } );
});
uploader.bind('UploadProgress', function(up, file) {
// Set file specific progress
$('#' + file.id + ' .plupload_file_status', self.element).html(file.percent + '%');
self._handleFileStatus(file);
self._updateTotalProgress();
self._trigger('progress', null, { up: up, file: file } );
});
uploader.bind('UploadComplete', function(up, files) {
self._trigger('complete', null, { up: up, files: files } );
});
uploader.bind('Error', function(up, err) {
var file = err.file, message, details;
if (file) {
message = '<strong>' + err.message + '</strong>';
details = err.details;
if (details) {
message += " <br /><i>" + err.details + "</i>";
} else {
switch (err.code) {
case plupload.FILE_EXTENSION_ERROR:
details = _("File: %s").replace('%s', file.name);
break;
case plupload.FILE_SIZE_ERROR:
details = _("File: %f, size: %s, max file size: %m").replace(/%([fsm])/g, function($0, $1) {
switch ($1) {
case 'f': return file.name;
case 's': return file.size;
case 'm': return plupload.parseSize(self.options.max_file_size);
}
});
break;
case self.FILE_COUNT_ERROR:
details = _("Upload element accepts only %d file(s) at a time. Extra files were stripped.")
.replace('%d', self.options.max_file_count);
break;
case plupload.IMAGE_FORMAT_ERROR :
details = plupload.translate('Image format either wrong or not supported.');
break;
case plupload.IMAGE_MEMORY_ERROR :
details = plupload.translate('Runtime ran out of available memory.');
break;
case plupload.IMAGE_DIMENSIONS_ERROR :
details = plupload.translate('Resoultion out of boundaries! <b>%s</b> runtime supports images only up to %wx%hpx.').replace(/%([swh])/g, function($0, $1) {
switch ($1) {
case 's': return up.runtime;
case 'w': return up.features.maxWidth;
case 'h': return up.features.maxHeight;
}
});
break;
case plupload.HTTP_ERROR:
details = _("Upload URL might be wrong or doesn't exist");
break;
}
message += " <br /><i>" + details + "</i>";
}
self._notify('error', message);
}
});
},
_setOption: function(key, value) {
if (key == 'buttons' && typeof(value) == 'object') {
value = $.extend(this.options.buttons, value);
if (!value.browse) {
this.browse_button.button('disable').hide();
$('#' + this.id + self.runtime + '_container').hide();
} else {
this.browse_button.button('enable').show();
$('#' + this.id + self.runtime + '_container').show();
}
if (!value.start) {
this.start_button.button('disable').hide();
} else {
this.start_button.button('enable').show();
}
if (!value.stop) {
this.stop_button.button('disable').hide();
} else {
this.start_button.button('enable').show();
}
}
this.uploader.settings[key] = value;
},
start: function() {
this.uploader.start();
this._trigger('start', null);
},
stop: function() {
this.uploader.stop();
this._trigger('stop', null);
},
getFile: function(id) {
var file;
if (typeof id === 'number') {
file = this.uploader.files[id];
} else {
file = this.uploader.getFile(id);
}
return file;
},
removeFile: function(id) {
var file = this.getFile(id);
if (file) {
this.uploader.removeFile(file);
}
},
clearQueue: function() {
this.uploader.splice();
},
getUploader: function() {
return this.uploader;
},
refresh: function() {
this.uploader.refresh();
},
_handleState: function() {
var self = this, uploader = this.uploader;
if (uploader.state === plupload.STARTED) {
$(self.start_button).button('disable');
$([])
.add(self.stop_button)
.add('.plupload_started')
.removeClass('plupload_hidden');
$('.plupload_upload_status', self.element).text(
_('Uploaded %d/%d files').replace('%d/%d', uploader.total.uploaded+'/'+uploader.files.length)
);
$('.plupload_header_content', self.element).addClass('plupload_header_content_bw');
} else {
$([])
.add(self.stop_button)
.add('.plupload_started')
.addClass('plupload_hidden');
if (self.options.multiple_queues) {
$(self.start_button).button('enable');
$('.plupload_header_content', self.element).removeClass('plupload_header_content_bw');
}
self._updateFileList();
}
},
_handleFileStatus: function(file) {
var actionClass, iconClass;
switch (file.status) {
case plupload.DONE:
actionClass = 'plupload_done';
iconClass = 'ui-icon ui-icon-circle-check';
break;
case plupload.FAILED:
actionClass = 'ui-state-error plupload_failed';
iconClass = 'ui-icon ui-icon-alert';
break;
case plupload.QUEUED:
actionClass = 'plupload_delete';
iconClass = 'ui-icon ui-icon-circle-minus';
break;
case plupload.UPLOADING:
actionClass = 'ui-state-highlight plupload_uploading';
iconClass = 'ui-icon ui-icon-circle-arrow-w';
// scroll uploading file into the view if its bottom boundary is out of it
var scroller = $('.plupload_scroll', this.container),
scrollTop = scroller.scrollTop(),
scrollerHeight = scroller.height(),
rowOffset = $('#' + file.id).position().top + $('#' + file.id).height();
if (scrollerHeight < rowOffset) {
scroller.scrollTop(scrollTop + rowOffset - scrollerHeight);
}
break;
}
actionClass += ' ui-state-default plupload_file';
$('#' + file.id)
.attr('class', actionClass)
.find('.ui-icon')
.attr('class', iconClass);
},
_updateTotalProgress: function() {
var uploader = this.uploader;
this.progressbar.progressbar('value', uploader.total.percent);
$('.plupload_total_status', this.element).html(uploader.total.percent + '%');
$('.plupload_upload_status', this.element).text(
_('Uploaded %d/%d files').replace('%d/%d', uploader.total.uploaded+'/'+uploader.files.length)
);
// All files are uploaded
if (uploader.total.uploaded === uploader.files.length) {
uploader.stop();
}
},
_updateFileList: function() {
var self = this, uploader = this.uploader, filelist = this.filelist,
count = 0,
id, prefix = this.id + '_',
fields;
// destroy sortable if enabled
if ($.ui.sortable && this.options.sortable) {
$('tbody', filelist).sortable('destroy');
}
filelist.empty();
$.each(uploader.files, function(i, file) {
fields = '';
id = prefix + count;
if (file.status === plupload.DONE) {
if (file.target_name) {
fields += '<input type="hidden" name="' + id + '_tmpname" value="'+plupload.xmlEncode(file.target_name)+'" />';
}
fields += '<input type="hidden" name="' + id + '_name" value="'+plupload.xmlEncode(file.name)+'" />';
fields += '<input type="hidden" name="' + id + '_status" value="' + (file.status === plupload.DONE ? 'done' : 'failed') + '" />';
count++;
self.counter.val(count);
}
filelist.append(
'<tr class="ui-state-default plupload_file" id="' + file.id + '">' +
'<td class="plupload_cell plupload_file_name"><span>' + file.name + '</span></td>' +
'<td class="plupload_cell plupload_file_status">' + file.percent + '%</td>' +
'<td class="plupload_cell plupload_file_size">' + plupload.formatSize(file.size) + '</td>' +
'<td class="plupload_cell plupload_file_action"><div class="ui-icon"></div>' + fields + '</td>' +
'</tr>'
);
self._handleFileStatus(file);
$('#' + file.id + '.plupload_delete .ui-icon, #' + file.id + '.plupload_done .ui-icon')
.click(function(e) {
$('#' + file.id).remove();
uploader.removeFile(file);
e.preventDefault();
});
self._trigger('updatelist', null, filelist);
});
$('.plupload_total_file_size', self.element).html(plupload.formatSize(uploader.total.size));
if (uploader.total.queued === 0) {
$('.ui-button-text', self.browse_button).text(_('Add Files'));
} else {
$('.ui-button-text', self.browse_button).text(_('%d files queued').replace('%d', uploader.total.queued));
}
if (uploader.files.length === (uploader.total.uploaded + uploader.total.failed)) {
self.start_button.button('disable');
} else {
self.start_button.button('enable');
}
// Scroll to end of file list
filelist[0].scrollTop = filelist[0].scrollHeight;
self._updateTotalProgress();
if (!uploader.files.length && uploader.features.dragdrop && uploader.settings.dragdrop) {
// Re-add drag message if there are no files
$('#' + id + '_filelist').append('<tr><td class="plupload_droptext">' + _("Drag files here.") + '</td></tr>');
} else {
// Otherwise re-initialize sortable
if (self.options.sortable && $.ui.sortable) {
self._enableSortingList();
}
}
},
_enableRenaming: function() {
var self = this;
$('.plupload_file_name span', this.filelist).live('click', function(e) {
var targetSpan = $(e.target), file, parts, name, ext = "";
// Get file name and split out name and extension
file = self.uploader.getFile(targetSpan.parents('tr')[0].id);
name = file.name;
parts = /^(.+)(\.[^.]+)$/.exec(name);
if (parts) {
name = parts[1];
ext = parts[2];
}
// Display input element
targetSpan.hide().after('<input class="plupload_file_rename" type="text" />');
targetSpan.next().val(name).focus().blur(function() {
targetSpan.show().next().remove();
}).keydown(function(e) {
var targetInput = $(this);
if ($.inArray(e.keyCode, [13, 27]) !== -1) {
e.preventDefault();
// Rename file and glue extension back on
if (e.keyCode === 13) {
file.name = targetInput.val() + ext;
targetSpan.text(file.name);
}
targetInput.blur();
}
});
});
},
_enableDragAndDrop: function() {
this.filelist.append('<tr><td class="plupload_droptext">' + _("Drag files here.") + '</td></tr>');
this.filelist.parent().attr('id', this.id + '_dropbox');
this.uploader.settings.drop_element = this.options.drop_element = this.id + '_dropbox';
},
_enableSortingList: function() {
var idxStart, self = this;
if ($('tbody tr', this.filelist).length < 2) {
return;
}
$('tbody', this.filelist).sortable({
containment: 'parent',
items: '.plupload_delete',
helper: function(e, el) {
return el.clone(true).find('td:not(.plupload_file_name)').remove().end().css('width', '100%');
},
start: function(e, ui) {
idxStart = $('tr', this).index(ui.item);
},
stop: function(e, ui) {
var i, length, idx, files = [], idxStop = $('tr', this).index(ui.item);
for (i = 0, length = self.uploader.files.length; i < length; i++) {
if (i === idxStop) {
idx = idxStart;
} else if (i === idxStart) {
idx = idxStop;
} else {
idx = i;
}
files[files.length] = self.uploader.files[idx];
}
files.unshift(files.length);
files.unshift(0);
// re-populate files array
Array.prototype.splice.apply(self.uploader.files, files);
}
});
},
_notify: function(type, message) {
var popup = $(
'<div class="plupload_message">' +
'<span class="plupload_message_close ui-icon ui-icon-circle-close" title="'+_('Close')+'"></span>' +
'<p><span class="ui-icon"></span>' + message + '</p>' +
'</div>'
);
popup
.addClass('ui-state-' + (type === 'error' ? 'error' : 'highlight'))
.find('p .ui-icon')
.addClass('ui-icon-' + (type === 'error' ? 'alert' : 'info'))
.end()
.find('.plupload_message_close')
.click(function() {
popup.remove();
})
.end()
.appendTo('.plupload_header_content', this.container);
},
destroy: function() {
// unbind all button events
$('.plupload_button', this.element).unbind();
// destroy buttons
if ($.ui.button) {
$('.plupload_add, .plupload_start, .plupload_stop', this.container)
.button('destroy');
}
// destroy progressbar
if ($.ui.progressbar) {
this.progressbar.progressbar('destroy');
}
// destroy sortable behavior
if ($.ui.sortable && this.options.sortable) {
$('tbody', this.filelist).sortable('destroy');
}
// destroy uploader instance
this.uploader.destroy();
// restore the elements initial state
this.element
.empty()
.html(this.contents_bak);
this.contents_bak = '';
$.Widget.prototype.destroy.apply(this);
}
});
} (window, document, plupload, jQuery));
| 28.024194 | 163 | 0.58048 |
c618c3ad22fe579ef6db16c569feec481208ea1e | 48 | js | JavaScript | js/bgapp.js | robnoorda/asana-betterizer | 200765933893290208e1d231194beb1ae8dde17e | [
"MIT"
] | 20 | 2016-09-01T12:55:54.000Z | 2020-10-14T17:09:36.000Z | js/bgapp.js | robnoorda/asana-betterizer | 200765933893290208e1d231194beb1ae8dde17e | [
"MIT"
] | 39 | 2016-08-16T09:47:10.000Z | 2019-11-14T12:01:43.000Z | js/bgapp.js | robnoorda/asana-betterizer | 200765933893290208e1d231194beb1ae8dde17e | [
"MIT"
] | 5 | 2016-12-05T21:34:06.000Z | 2020-10-14T17:09:41.000Z | var asanaModule = angular.module("asanabg", []); | 48 | 48 | 0.708333 |
c618ed6f5f73717ceb02d29aba63b163b2b4c28a | 195 | js | JavaScript | grouper-misc/grouper-ui-dojo/dojo/dojox/editor/plugins/nls/pt/InsertAnchor.js | manasys/grouper | f6fc9e9d93768a971187289afd9df6d650a128e8 | [
"Apache-2.0"
] | 337 | 2015-01-14T14:59:33.000Z | 2022-03-26T21:01:59.000Z | grouper-misc/grouper-ui-dojo/dojo/dojox/editor/plugins/nls/pt/InsertAnchor.js | manasys/grouper | f6fc9e9d93768a971187289afd9df6d650a128e8 | [
"Apache-2.0"
] | 485 | 2015-01-08T12:17:53.000Z | 2022-03-07T11:53:48.000Z | grouper-misc/grouper-ui-dojo/dojo/dojox/editor/plugins/nls/pt/InsertAnchor.js | manasys/grouper | f6fc9e9d93768a971187289afd9df6d650a128e8 | [
"Apache-2.0"
] | 94 | 2015-08-29T19:05:43.000Z | 2022-01-10T15:36:40.000Z | //>>built
define("dojox/editor/plugins/nls/pt/InsertAnchor",({insertAnchor:"Inserir Âncora",title:"Propriedades de Âncora",anchor:"Nome:",text:"Descrição:",set:"Configurar",cancel:"Cancelar"}));
| 65 | 184 | 0.748718 |
c619ba8dbb686a90772a4d14e18be92c26f2e728 | 346 | js | JavaScript | packages/react-native-dom/ReactDom/bridge/RCTModuleConfig.js | nutstick/react-native-dom | b2660426e7a2783e2750eed52924a1d8e0f5ef6b | [
"MIT"
] | 3,107 | 2018-05-17T13:48:55.000Z | 2022-02-04T08:37:21.000Z | packages/react-native-dom/ReactDom/bridge/RCTModuleConfig.js | 38438-38438-org/react-native-dom | 235cae7e628fe1e4d89f662153e90da5ac5d0a9b | [
"MIT"
] | 82 | 2018-05-17T17:25:21.000Z | 2022-01-22T04:39:56.000Z | packages/react-native-dom/ReactDom/bridge/RCTModuleConfig.js | 38438-38438-org/react-native-dom | 235cae7e628fe1e4d89f662153e90da5ac5d0a9b | [
"MIT"
] | 91 | 2018-05-17T23:40:46.000Z | 2021-02-15T13:06:02.000Z | /** @flow */
import type { ModuleDescription, Constants } from "RCTModule";
export function moduleConfigFactory(
name: string,
constants: Constants,
functions: Array<string>,
promiseMethodIDs: Array<number>,
syncMethodIDs: Array<number>
): ModuleDescription {
return [name, constants, functions, promiseMethodIDs, syncMethodIDs];
}
| 24.714286 | 71 | 0.748555 |
c61a63e3fefb205aba75457c4fafa8c2fd9802ac | 2,539 | js | JavaScript | node_modules/pouchdb-all-dbs/node_modules/infusion/instrumented/src/framework/preferences/js/SelfVoicingSchemas.js | waharnum/dictionary-prototype-kettle | 163806dffa21a1c56c0ace145ba6cce1f1941006 | [
"BSD-3-Clause"
] | null | null | null | node_modules/pouchdb-all-dbs/node_modules/infusion/instrumented/src/framework/preferences/js/SelfVoicingSchemas.js | waharnum/dictionary-prototype-kettle | 163806dffa21a1c56c0ace145ba6cce1f1941006 | [
"BSD-3-Clause"
] | null | null | null | node_modules/pouchdb-all-dbs/node_modules/infusion/instrumented/src/framework/preferences/js/SelfVoicingSchemas.js | waharnum/dictionary-prototype-kettle | 163806dffa21a1c56c0ace145ba6cce1f1941006 | [
"BSD-3-Clause"
] | 1 | 2018-03-31T02:27:26.000Z | 2018-03-31T02:27:26.000Z |
var __cov_9zhNSGOtxP8qb_J$rrAqDA = (Function('return this'))();
if (!__cov_9zhNSGOtxP8qb_J$rrAqDA.__coverage__) { __cov_9zhNSGOtxP8qb_J$rrAqDA.__coverage__ = {}; }
__cov_9zhNSGOtxP8qb_J$rrAqDA = __cov_9zhNSGOtxP8qb_J$rrAqDA.__coverage__;
if (!(__cov_9zhNSGOtxP8qb_J$rrAqDA['E:\\source\\gits\\infusion-master\\src\\framework\\preferences\\js\\SelfVoicingSchemas.js'])) {
__cov_9zhNSGOtxP8qb_J$rrAqDA['E:\\source\\gits\\infusion-master\\src\\framework\\preferences\\js\\SelfVoicingSchemas.js'] = {"path":"E:\\source\\gits\\infusion-master\\src\\framework\\preferences\\js\\SelfVoicingSchemas.js","s":{"1":0,"2":0,"3":0,"4":0},"b":{"1":[0,0]},"f":{"1":0},"fnMap":{"1":{"name":"(anonymous_1)","line":14,"loc":{"start":{"line":14,"column":1},"end":{"line":14,"column":18}}}},"statementMap":{"1":{"start":{"line":12,"column":0},"end":{"line":12,"column":36}},"2":{"start":{"line":14,"column":0},"end":{"line":69,"column":16}},"3":{"start":{"line":25,"column":4},"end":{"line":50,"column":7}},"4":{"start":{"line":59,"column":4},"end":{"line":67,"column":7}}},"branchMap":{"1":{"line":12,"type":"binary-expr","locations":[{"start":{"line":12,"column":18},"end":{"line":12,"column":29}},{"start":{"line":12,"column":33},"end":{"line":12,"column":35}}]}}};
}
__cov_9zhNSGOtxP8qb_J$rrAqDA = __cov_9zhNSGOtxP8qb_J$rrAqDA['E:\\source\\gits\\infusion-master\\src\\framework\\preferences\\js\\SelfVoicingSchemas.js'];
__cov_9zhNSGOtxP8qb_J$rrAqDA.s['1']++;var fluid_3_0_0=(__cov_9zhNSGOtxP8qb_J$rrAqDA.b['1'][0]++,fluid_3_0_0)||(__cov_9zhNSGOtxP8qb_J$rrAqDA.b['1'][1]++,{});__cov_9zhNSGOtxP8qb_J$rrAqDA.s['2']++;(function(fluid){'use strict';__cov_9zhNSGOtxP8qb_J$rrAqDA.f['1']++;__cov_9zhNSGOtxP8qb_J$rrAqDA.s['3']++;fluid.defaults('fluid.prefs.auxSchema.speak',{gradeNames:['fluid.prefs.auxSchema'],auxiliarySchema:{'namespace':'fluid.prefs.constructed','terms':{'templatePrefix':'../../framework/preferences/html/','messagePrefix':'../../framework/preferences/messages/'},'template':'%templatePrefix/SeparatedPanelPrefsEditor.html','message':'%messagePrefix/prefsEditor.json',speak:{type:'fluid.prefs.speak',enactor:{type:'fluid.prefs.enactor.selfVoicing',container:'body'},panel:{type:'fluid.prefs.panel.speak',container:'.flc-prefsEditor-speak',template:'%templatePrefix/PrefsEditorTemplate-speak.html',message:'%messagePrefix/speak.json'}}}});__cov_9zhNSGOtxP8qb_J$rrAqDA.s['4']++;fluid.defaults('fluid.prefs.schemas.speak',{gradeNames:['fluid.prefs.schemas'],schema:{'fluid.prefs.speak':{'type':'boolean','default':false}}});}(fluid_3_0_0));
| 253.9 | 1,130 | 0.707365 |
c61ac5e579a9f7ce63d2ea60396fca0d1c85cc7c | 445 | js | JavaScript | src/routes/Todo/components/Footer.js | cedzz/react-redux-learn | 61f6b67b0c500b0c03583662184511af06364ab0 | [
"MIT"
] | null | null | null | src/routes/Todo/components/Footer.js | cedzz/react-redux-learn | 61f6b67b0c500b0c03583662184511af06364ab0 | [
"MIT"
] | null | null | null | src/routes/Todo/components/Footer.js | cedzz/react-redux-learn | 61f6b67b0c500b0c03583662184511af06364ab0 | [
"MIT"
] | null | null | null | import React from 'react';
import FilterLink from './FilterLink';
const Footer = () => {
return (
<p>
<FilterLink
filter="SHOW_ALL"
>
ALL
</FilterLink>
{' '}
<FilterLink
filter="SHOW_ACTIVE"
>
ACTIVE
</FilterLink>
{' '}
<FilterLink
filter="SHOW_COMPLETED"
>
COMPLETED
</FilterLink>
</p>
)
};
export default Footer;
| 14.354839 | 38 | 0.48764 |
c61accb67319f743541e4e3b5619044d32d05d35 | 579 | js | JavaScript | src/configure.js | codetojoy/WarO_JavaScript_Ramda | f518f73f381804dc43a3a639d023827ca8862778 | [
"Apache-2.0"
] | null | null | null | src/configure.js | codetojoy/WarO_JavaScript_Ramda | f518f73f381804dc43a3a639d023827ca8862778 | [
"Apache-2.0"
] | null | null | null | src/configure.js | codetojoy/WarO_JavaScript_Ramda | f518f73f381804dc43a3a639d023827ca8862778 | [
"Apache-2.0"
] | null | null | null |
const R = require('ramda')
function configure(state) {
const newPlayers = R.map(R.compose(
R.assoc('hand', []),
R.assoc('roundsWon', 0),
R.assoc('total', 0)
), state.players)
const numPlayers = newPlayers.length
const newState = R.compose(
R.assoc('kitty', []),
R.assoc('numPlayers', numPlayers),
R.assoc('numCardsPerHand', R.divide(state.numCards, R.inc(numPlayers))),
R.assoc('players', newPlayers)
)(state)
return newState
}
module.exports = configure
| 24.125 | 84 | 0.561313 |
c61acefe7a15ec31f12ea860a9b153cf08eebbcf | 193 | js | JavaScript | gulpfile.js | tibor19/Aurelia-workshop-DevSum15 | 2c55e4b5a2884214e9852dd742d81795ecb90b3f | [
"MIT"
] | 8 | 2016-07-26T19:03:02.000Z | 2017-10-20T19:59:53.000Z | gulpfile.js | tibor19/Aurelia-workshop-DevSum15 | 2c55e4b5a2884214e9852dd742d81795ecb90b3f | [
"MIT"
] | 1 | 2017-04-24T23:05:31.000Z | 2017-04-25T03:06:14.000Z | gulpfile.js | tibor19/Aurelia-workshop-DevSum15 | 2c55e4b5a2884214e9852dd742d81795ecb90b3f | [
"MIT"
] | null | null | null | /// <binding ProjectOpened='watch' />
// all gulp tasks are located in the ./build/tasks directory
// gulp configuration is in files in ./build directory
require('require-dir')('build/tasks');
| 38.6 | 60 | 0.725389 |
c61ad3f2037de055e2300cc3b4b322dfe4eb414e | 7,247 | js | JavaScript | Public/js_old_zhifu/wffh.js | zz11223/tt | 7840e472ca550b46ebfba90e2d5a5398ee90ec63 | [
"BSD-2-Clause"
] | null | null | null | Public/js_old_zhifu/wffh.js | zz11223/tt | 7840e472ca550b46ebfba90e2d5a5398ee90ec63 | [
"BSD-2-Clause"
] | null | null | null | Public/js_old_zhifu/wffh.js | zz11223/tt | 7840e472ca550b46ebfba90e2d5a5398ee90ec63 | [
"BSD-2-Clause"
] | null | null | null | /**
************************************************************************
WFPHP订单系统版权归WENFEI所有,凡是破解此系统者都会死全家,非常灵验。
************************************************************************
WFPHP订单系统官方网站:http://www.wforder.com/ (盗版盗卖者死全家)
WFPHP订单系统官方店铺:http://889889.taobao.com/ (破解系统者死全家)
************************************************************************
郑重警告:凡是破解此系统者出门就被车撞死,盗卖此系统者三日内必死全家。
************************************************************************
*/
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;}('(6(){V={1Z:{3t:\'2z\',1K:\'2T\',1p:19,2X:T},G:{},1I:6(){8 a=1V,l=a.L,i=1,1k=a[0];9(l===1){i=0,1k=7.G};D(i;i<l;i++){D(8 p 1s a[i])9(!(p 1s 1k))1k[p]=a[i][p]}}};8 q={$:6(a){x 2x a===\'2F\'?W.2W(a):a},$$:6(a,b){x(7.$(b)||W).2V(a)},$$1G:6(b,c){8 d=[],a=7.$$(b,c);D(8 i=0;i<a.L;i++){9(a[i].2q===c)d.12(a[i]);i+=7.$$(b,a[i]).L};x d},$c:6(a,b){8 c=7.$$(\'*\',b),a=a.1h(/\\-/g,\'\\\\-\'),1q=1Q 2Q(\'(^|\\\\s)\'+a+\'(\\\\s|$)\'),1M=[];D(8 i=0,l=c.L;i<l;i++){9(1q.2K(c[i].K)){1M.12(c[i]);2k}};x 1M[0]},$C:6(a,b){x 7.$$1G(\'C\',7.$c(a,b))},1p:6(a,b){8 c=W.20(\'2L\');c.K=b;a[0].2q.2d(c,a[0]);D(8 i=0;i<a.L;i++)c.2Y(a[i])},3d:6(a,b){a.1f=\'<N 2o=\'+b+\'>\'+a.1f+\'</N>\'},3l:6(a,b){8 s=[],N=7.$$(\'N\',a)[0],C=7.$$1G(\'C\',N),B,n=C.L,1U=b.L;D(8 j=0;j<1U;j++){s.12(\'<N 2o=\'+b[j]+\'>\');D(8 i=0;i<n;i++){B=7.$$(\'B\',C[i])[0];s.12(\'<C>\'+(b[j]==\'1U\'?(\'<a>\'+(i+1)+\'</a>\'):(b[j]==\'1e\'&&B?C[i].1f.1h(/<B(.|\\n|\\r)*?(\\>\\<\\/a\\>)/i,B.3i+\'</a>\')+\'<p>\'+B.2u("1t")+\'</p>\':(b[j]==\'2i\'&&B?\'<B 1i=\'+(B.2u("2i")||B.1i)+\' />\':\'\')))+\'<1L></1L></C>\')};s.12(\'</N>\')};a.1f+=s.1F(\'\')}},2r={y:6(o,a){8 v=(+[1,]?31(o,2m):o.2Z)[a],1y=34(v);x 2B(1y)?v:1y},2w:6(o,a){o.y.39="37(I="+a+")",o.y.I=a/T},2y:6(o,a){8 b=o.K,1q="/\\\\s*"+a+"\\\\b/g";o.K=b?b.1h(2n(1q),\'\'):\'\'}},2s={1v:6(a,f,g,h,i,j){8 k=f===\'I\'?19:E,I=7.2w,2C=2x g===\'2F\',2c=(1Q 29).28();9(k&&7.y(a,\'1l\')===\'1w\')a.y.1l=\'35\',I(a,0);8 l=7.y(a,f),b=2B(l)?1:l,c=2C?g/1:g-b,d=h||3h,e=7.2b[i||\'1X\'],m=c>0?\'36\':\'2l\';9(a[f+\'1g\'])1d(a[f+\'1g\']);a[f+\'1g\']=1C(6(){8 t=(1Q 29).28()-2c;9(t<d){k?I(a,15[m](e(t,b*T,c*T,d))):a.y[f]=15[m](e(t,b,c,d))+\'A\'}Q{1d(a[f+\'1g\']),k?I(a,(c+b)*T):a.y[f]=c+b+\'A\',k&&g===0&&(a.y.1l=\'1w\'),j&&j.38(a)}},13);x 7},30:6(a,b,c){7.1v(a,\'I\',1,b==1b?1J:b,\'1D\',c);x 7},33:6(a,b,c){7.1v(a,\'I\',0,b==1b?1J:b,\'1D\',c);x 7},2t:6(a,b,c,d,e){D(8 p 1s b)7.1v(a,p,b[p],c,d,e);x 7},32:6(a){D(8 p 1s a)9(p.3a(\'1g\')!==-1)1d(a[p]);x 7},2b:{1D:6(t,b,c,d){x c*t/d+b},3j:6(t,b,c,d){x-c/2*(15.3k(15.3g*t/d)-1)+b},3c:6(t,b,c,d){x c*(t/=d)*t*t*t+b},1X:6(t,b,c,d){x-c*((t=t/d-1)*t*t*t-1)+b},3b:6(t,b,c,d){x((t/=d/2)<1)?(c/2*t*t*t*t+b):(-c/2*((t-=2)*t*t*t-2)+b)}}},2h={2G:6(p,a){8 F=7;p.S=p.G+\'-\'+p.1n,F.1I(p,F.G[p.G].2H,F.1Z);6 1r(){F.$(p.1n).K+=\' \'+p.G+\' \'+p.S,F.23(p)};6 1S(){F.G[p.G](p,F)};9(a){1r(),1S();x};9(25.2p){(6(){3f{1r()}3e(e){2J(1V.2P,0)}})()}Q{7.1P(W,\'2O\',1r)};7.1P(25,\'2U\',1S)},23:6(p){8 a=[],w=p.10,h=p.M||7.$(p.1n).2R,U=W.20(\'y\');U.2N=\'1t/1Y\';9(p.1p)7.1p([7.$(p.1n)],p.G+\'2S\');9(p.1Y!==E)a.12(\'.\'+p.S+\' *{2M:0;22:0;43:0;3Q-y:1w;}.\'+p.S+\'{1O:24;10:\'+w+\'A;M:\'+p.M+\'A;1T:1R;41:3W/1.5 48,4d,4a-4b;1t-26:1z;2a:#27;}.\'+p.S+\' .1A{1O:3S;z-u:3Z;10:T%;M:T%;3Y:#3X;1t-26:1W;22-42:\'+0.3*h+\'A;2a:#27 40(46://3R.3V.3U/3T/49/4c-1A.44) 1W \'+0.4*h+\'A 45-47;}.\'+p.S+\' .3P{1O:24;10:\'+w+\'A;M:\'+h+\'A;1T:1R;}.\'+p.S+\' .1e C,.\'+p.S+\' .1e C 1L,.\'+p.S+\' .1e-3v{10:\'+w+\'A;M:\'+p.1K+\'A!2D;3u-M:\'+p.1K+\'A!2D;1T:1R;}.\'+p.S+\' .1e C p a{1l:3w;}\');9(U.21){U.21.3z=a.1F(\'\')}Q{U.1f=a.1F(\'\')};8 b=7.$$(\'3y\',W)[0];b.2d(U,b.3x)}},2j={3o:6(a,b,c,d,e){x"8 18=V,1N=18.$c(\'1A\',1c),R="+c+",P=19,Z="+d+"||\'1z\',1m=Z==\'1z\'||Z==\'3n\'?17.10:17.M,14="+e+"||14,u=17.u||0,1u=17.3m*3p;9(R){14.y[Z]=-1m*n+\'A\';u+=n;}9(1N)1c.3s(1N);8 H=6(11){("+a+")();8 3r=u;9(R&&u==2*n-1&&P!=1){14.y[Z]=-(n-1)*1m+\'A\';u=n-1}9(R&&u==0&&P!=2){14.y[Z]=-n*1m+\'A\';u=n}9(!R&&u==n-1&&11==1b)u=-1;9(R&&11!==1b&&u>n-1&&!P) 11+=n;8 16=11!==1b?11:u+1;9("+b+")("+b+")();u=16;P=E;};H(u);9(1u&&17.J!==E)8 J=1C(6(){H()},1u);1c.1B=6(){9(J)1d(J)};1c.1E=6(){9(J)J=1C(6(){H()},1u)};D(8 i=0,1x=18.$$(\'a\',1c),2E=1x.L;i<2E;i++) 1x[i].3q=6(){7.3A();}"},3K:6(a,b,c){x"D (8 j=0;j<n;j++){"+a+"[j].u=j;9("+b+"==\'2z\'){"+a+"[j].1B=6(){9(7.u!=u)7.K+=\' 2I\'};"+a+"[j].1E=6(){18.2y(7,\'2I\')};"+a+"[j].1j=6(){9(7.u!=u) {H(7.u);x E}};}Q 9("+b+"==\'3J\'){"+a+"[j].1B=6(){8 1a=7;9("+c+"==0){9(1a.u!=u){H(1a.u);x E}}Q "+a+".d=2J(6(){9(1a.u!=u) {H(1a.u);x E}},"+c+")};"+a+"[j].1E=6(){3I("+a+".d)};}Q{3L(\'3O 3N : \\"\'+"+b+"+\'\\"\');2k;}}"},3M:6(a,b,c){x"8 1o=E;"+a+".1j=6(){7.K=7.K==\'"+b+"\'?\'"+c+"\':\'"+b+"\';9(!1o){1d(J);J=2m;1o=19;}Q{J=19;1o=E;}}"},3D:6(a,b,c,d,e){x"8 Y={},O="+c+",2e=15.2l("+d+"/2),2f=3C("+a+".y["+b+"])||0,X=16>=n?16-n:16,2v="+e+"||1J,2g=O*(n-"+d+"),1H=O*X+2f;9(1H>O*2e&&X!==n-1) Y["+b+"]=\'-\'+O;9(1H<O&&X!==0) Y["+b+"]=\'+\'+O;9(X===n-1) Y["+b+"]=-2g;9(X===0) Y["+b+"]=0;18.2t("+a+",Y,2v);"},3B:6(a,b){x a+".1j=6(){P=1;H(u>0?u-1:n-1);};"+b+".1j=6(){P=2;8 2A=u>=2*n-1?n-1:u;H(u==n-1&&!R?0:2A+1);}"},3E:6(o,a,b){8 c=7.$$(\'B\',o)[0];c.1i=b?c.1i.1h(2n("/"+a+"\\\\.(?=[^\\\\.]+$)/g"),\'.\'):c.1i.1h(/\\.(?=[^\\.]+$)/g,a+\'.\')},1P:6(a,c,d){8 b=!(+[1,]),e=b?\'2p\':\'3H\',t=(b?\'3G\':\'\')+c;a[e](t,d,E)}};V.1I(V,q,2r,2s,2h,2j);V.2G.3F=6(a,p){V.G[a].2H=p}})();',62,262,'||||||function|this|var|if|||||||||||||||||||||index|||return|style||px|img|li|for|false||pattern|run|opacity|auto|className|length|height|ul|scDis|_turn|else|less||100|oStyle|wfFocus|document|scIdx|scPar|_dir|width|idx|push||pics|Math|next|par|_F|true|self|undefined|box|clearInterval|txt|innerHTML|Timer|replace|src|onclick|parent|display|_dis|id|_stop|wrap|reg|ready|in|text|_t|animate|none|_lk|pv|left|loading|onmouseover|setInterval|linear|onmouseout|join|_|scD|extend|400|txtHeight|span|arr|_ld|position|addEvent|new|hidden|show|overflow|num|arguments|center|easeOut|css|defConfig|createElement|styleSheet|padding|initCSS|relative|window|align|fff|getTime|Date|background|easing|st|insertBefore|scN|scDir|scMax|Init|thumb|Method|break|floor|null|eval|class|attachEvent|parentNode|CSS|Anim|slide|getAttribute|scDur|setOpa|typeof|removeClass|click|tIdx|isNaN|am|important|_ln|string|set|cfg|hover|setTimeout|test|div|margin|type|DOMContentLoaded|callee|RegExp|offsetHeight|_wrap|default|load|getElementsByTagName|getElementById|delay|appendChild|currentStyle|fadeIn|getComputedStyle|stop|fadeOut|parseFloat|block|ceil|alpha|call|filter|indexOf|easeInOut|easeIn|wrapIn|catch|try|PI|800|alt|swing|cos|addList|time|right|switchMF|1000|onfocus|prev|removeChild|trigger|line|bg|inline|firstChild|head|cssText|blur|turn|parseInt|scroll|alterSRC|params|on|addEventListener|clearTimeout|mouseover|bind|alert|toggle|Setting|Error|pic|list|nethd|absolute|wtimg|com|zhongsou|12px|666|color|9999|url|font|top|border|gif|no|http|repeat|Verdana|i_41956|sans|serif|28236|Geneva'.split('|'),0,{}))
//////////////////////////// WFORDERJSEND //////////////////////////// | 603.916667 | 6,679 | 0.485442 |
c61ad4c134cda365426ee706775c686c8d9082ff | 2,179 | js | JavaScript | addon/react-component-lib/react-autocomplete.js | ctwoolsey/ember-paper-react | 5be11aebab9e86406e56ea5021e447cba4b16350 | [
"MIT"
] | null | null | null | addon/react-component-lib/react-autocomplete.js | ctwoolsey/ember-paper-react | 5be11aebab9e86406e56ea5021e447cba4b16350 | [
"MIT"
] | null | null | null | addon/react-component-lib/react-autocomplete.js | ctwoolsey/ember-paper-react | 5be11aebab9e86406e56ea5021e447cba4b16350 | [
"MIT"
] | null | null | null | import React from 'react';
import Autocomplete from '@mui/material/Autocomplete';
import TextField from '@mui/material/TextField';
import { ReactConditionalThemeProvider } from './react-conditional-theme-provider';
import { ReactBase } from './base/react-base';
import { AutocompletePropObj } from '../prop-files/autocomplete-props';
import { TextFieldPropObj } from '../prop-files/text-field-props';
import { reactPropSifter } from './utility/react-prop-sifter';
import { reactPropRemover } from './utility/react-prop-remover';
export class ReactAutocomplete extends ReactBase{
constructor(props) {
super(props);
this.renderTextField = this.renderTextField.bind(this);
this.initialize();
}
initialize() {
const siftedTextFieldProps = reactPropSifter(this.props, TextFieldPropObj);
const siftedAutocompleteProps = reactPropSifter(this.props, AutocompletePropObj, false);
siftedAutocompleteProps.staticProps['renderInput'] = this.renderTextField;
reactPropRemover(siftedTextFieldProps, siftedAutocompleteProps);
this.state = Object.assign({},
siftedAutocompleteProps.stateProps,
siftedAutocompleteProps.statefulPropsNotForComponent,
siftedTextFieldProps.stateProps,
siftedTextFieldProps.statefulPropsNotForComponent);
this.staticAutocompleteProps = siftedAutocompleteProps.staticProps;
this.staticTextFieldProps = siftedTextFieldProps.staticProps;
this.stateAutocompleteProps = siftedAutocompleteProps.stateProps;
this.stateTextFieldProps = siftedTextFieldProps.stateProps;
}
render() {
const {
theme
} = this.state;
return (
<ReactConditionalThemeProvider theme={theme}>
<Autocomplete
ref={this.componentRef}
{...(this.placeStaticProps(this.staticAutocompleteProps))}
{...(this.placeStateProps(this.stateAutocompleteProps))}
/>
</ReactConditionalThemeProvider>
);
}
renderTextField(params) {
return (
<TextField
{...params}
{...(this.placeStaticProps(this.staticTextFieldProps, params))}
{...(this.placeStateProps(this.stateTextFieldProps, params))}
/>
)
}
}
| 34.587302 | 92 | 0.725562 |
c61b8f2ebbfd10ca747b6bb1be026ed293851cb1 | 2,791 | js | JavaScript | node_modules/caniuse-lite/data/regions/PM.js | winprn/LHPOJ | 9c621245f5832c99d9f15a14fecc70c8664b9853 | [
"MIT"
] | 6 | 2019-02-19T06:38:34.000Z | 2021-08-06T06:49:30.000Z | node_modules/caniuse-lite/data/regions/PM.js | winprn/LHPOJ | 9c621245f5832c99d9f15a14fecc70c8664b9853 | [
"MIT"
] | 18 | 2020-04-06T02:00:24.000Z | 2022-03-25T18:52:20.000Z | node_modules/caniuse-lite/data/regions/PM.js | winprn/LHPOJ | 9c621245f5832c99d9f15a14fecc70c8664b9853 | [
"MIT"
] | 4 | 2018-11-26T01:43:22.000Z | 2022-02-25T09:03:01.000Z | module.exports={D:{"4":0.007187,"5":0,"6":0.007187,"7":0,"8":0,"9":0,"10":0,"11":0,"12":0,"13":0,"14":0,"15":0,"16":0,"17":0,"18":0,"19":0,"20":0.007187,"21":0,"22":0,"23":0,"24":0,"25":0.014374,"26":0,"27":0,"28":0,"29":0,"30":0,"31":0,"32":0.014374,"33":0,"34":0.007187,"35":0.007187,"36":0.014374,"37":0,"38":0,"39":0,"40":0,"41":0.007187,"42":0.007187,"43":0.007187,"44":0,"45":0,"46":0,"47":0,"48":0.007187,"49":0.459968,"50":0,"51":0.014374,"52":0.007187,"53":0.035935,"54":0.158114,"55":0,"56":0,"57":0.064683,"58":0.043122,"59":0,"60":0,"61":0,"62":0.057496,"63":0.028748,"64":0.028748,"65":0.007187,"66":0.021561,"67":0.603708,"68":0.402472,"69":15.991075,"70":2.867613,"71":0.007187,"72":0,"73":0},C:{"2":0,"3":0,"4":0.086244,"5":0,"6":0,"7":0,"8":0,"9":0,"10":0,"11":0,"12":0,"13":0,"14":0,"15":0,"16":0,"17":0,"18":0,"19":0,"20":0,"21":0,"22":0,"23":0,"24":0,"25":0,"26":0,"27":0,"28":0,"29":0,"30":0,"31":0,"32":0,"33":0,"34":0,"35":0,"36":0,"37":0,"38":0,"39":0,"40":0,"41":0.007187,"42":0,"43":0,"44":0,"45":0.114992,"46":0,"47":0,"48":1.113985,"49":0,"50":0,"51":0,"52":0.043122,"53":0,"54":0,"55":0,"56":0,"57":0.007187,"58":0.021561,"59":0,"60":0.50309,"61":0.21561,"62":8.272237,"63":1.164294,"64":0,"65":0,"3.5":0,"3.6":0},F:{"9":0,"11":0.007187,"12":0,"15":0,"16":0,"17":0,"18":0,"19":0,"20":0,"21":0,"22":0,"23":0,"24":0,"25":0,"26":0,"27":0,"28":0,"29":0,"30":0,"31":0,"32":0,"33":0,"34":0,"35":0,"36":0,"37":0,"38":0.014374,"39":0.021561,"40":0.007187,"41":0,"42":0.007187,"43":0,"44":0,"45":0,"46":0,"47":0,"48":0,"49":0,"50":0,"51":0,"52":0,"53":0,"54":0,"55":0.237171,"56":0.955871,"9.5-9.6":0,"10.0-10.1":0,"10.5":0,"10.6":0,"11.1":0,"11.5":0,"11.6":0,"12.1":0},E:{"4":0.007187,"5":0.107805,"6":0,"7":0,"8":0,"9":0.007187,"10":0,"11":0.043122,"12":1.056489,_:"0","3.1":0,"3.2":0,"5.1":0.014374,"6.1":0,"7.1":0,"9.1":0.050309,"10.1":0.107805,"11.1":0.409659},G:{"8":0.53291838151396,"12":23.082853202601,"3.2":0.0044042841447435,"4.0-4.1":0,"4.2-4.3":0.01321285243423,"5.0-5.1":0.048447125592178,"6.0-6.1":0.017617136578974,"7.0-7.1":0.11010710361859,"8.1-8.4":0.28187418526358,"9.0-9.2":0.1321285243423,"9.3":0.91609110210664,"10.0-10.2":1.5811380079629,"10.3":1.6912451115815,"11.0-11.2":3.5102144633605,"11.3-11.4":11.772651518899},I:{"3":0.00076722576832151,"4":0.10204102718676,_:"67","2.1":0,"2.2":0.00076722576832151,"2.3":0.016878966903073,"4.1":0.029154579196217,"4.2-4.3":0.15421237943262,"4.4":0,"4.4.3-4.4.4":0.34525159574468},K:{_:"0 10 11 12 11.1 11.5 12.1"},A:{"6":0,"7":0,"8":0.007187,"9":0,"10":0.007187,"11":1.056489,"5.5":0},B:{"12":0,"13":0,"14":0.007187,"15":0,"16":0.007187,"17":2.493889,_:"18"},P:{"4":0,"5":0,"6.2":0,_:"7.2"},N:{"10":0,"11":0},J:{"7":0,"10":0},R:{_:"0"},M:{"0":0.042195},O:{"0":0},Q:{_:"1.2"},H:{"0":0},L:{"0":15.217199}};
| 1,395.5 | 2,790 | 0.545324 |
c61bbbec2a8e173eca9077cf3f1fe2eb53d45ee0 | 585 | js | JavaScript | examples/sonar.js | dIIsplAy/Mbot-toto | f4922e61b20edca0f8706d854995069c96ed5936 | [
"MIT"
] | null | null | null | examples/sonar.js | dIIsplAy/Mbot-toto | f4922e61b20edca0f8706d854995069c96ed5936 | [
"MIT"
] | null | null | null | examples/sonar.js | dIIsplAy/Mbot-toto | f4922e61b20edca0f8706d854995069c96ed5936 | [
"MIT"
] | null | null | null | // Uses proximity sensor on the front to tell the distance from the object
// Assumes prox sensor is plugged into port 2 - if not change the pin to use
// the pin for appropriate port and the second pin within it.
var five = require("johnny-five");
var board = new five.Board({ port: '/dev/ttyUSB0' });
board.on("ready", function() {
var proximity = new five.Proximity({
freq: 1000,
controller: "HCSR04",
pin: 10
});
proximity.on("data", function() {
console.log("inches: ", this.inches);
console.log("cm: ", this.cm);
});
}); | 30.789474 | 76 | 0.623932 |
c61c2b6942135fd02f390d9741adee114b4aaf7e | 357 | js | JavaScript | src/actions/example.js | alfredop-lagash/docker-image | b46697822a77bc1d2b14f126d88e74a9842bbe92 | [
"MIT"
] | null | null | null | src/actions/example.js | alfredop-lagash/docker-image | b46697822a77bc1d2b14f126d88e74a9842bbe92 | [
"MIT"
] | null | null | null | src/actions/example.js | alfredop-lagash/docker-image | b46697822a77bc1d2b14f126d88e74a9842bbe92 | [
"MIT"
] | null | null | null | import { createActions } from 'reduxsauce';
const { Types, Creators } = createActions(
{
setText: ['value'],
setStatus: ['key', 'value']
},
{
prefix: 'EXAMPLE/'
}
);
const { setText, setStatus } = Creators;
const { SET_TEXT, SET_STATUS } = Types;
export { Types, setText, setStatus, SET_TEXT, SET_STATUS };
export default Creators;
| 17.85 | 59 | 0.641457 |
c61c979da480a98262f62be3554d9f3277227b17 | 1,357 | js | JavaScript | integration-tests/__tests__/coverage_remapping.test.js | incleaf/jest | 8d3de491eae9d3a8d495fa37bd11a1a0cd1bc849 | [
"MIT"
] | null | null | null | integration-tests/__tests__/coverage_remapping.test.js | incleaf/jest | 8d3de491eae9d3a8d495fa37bd11a1a0cd1bc849 | [
"MIT"
] | 1 | 2022-03-02T11:06:42.000Z | 2022-03-02T11:06:42.000Z | integration-tests/__tests__/coverage_remapping.test.js | incleaf/jest | 8d3de491eae9d3a8d495fa37bd11a1a0cd1bc849 | [
"MIT"
] | null | null | null | /**
* Copyright (c) 2014-present, Facebook, Inc. 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
*/
'use strict';
const {readFileSync} = require('fs');
const path = require('path');
const skipOnWindows = require('../../scripts/skip_on_windows');
const {cleanup, run} = require('../utils');
const runJest = require('../runJest');
const dir = path.resolve(__dirname, '../coverage-remapping');
const coverageDir = path.join(dir, 'coverage');
skipOnWindows.suite();
beforeAll(() => {
cleanup(coverageDir);
});
it('maps code coverage against original source', () => {
run('yarn', dir);
const result = runJest(dir, ['--coverage', '--mapCoverage', '--no-cache']);
expect(result.status).toBe(0);
const coverageMapFile = path.join(coverageDir, 'coverage-final.json');
const coverageMap = JSON.parse(readFileSync(coverageMapFile, 'utf-8'));
// reduce absolute paths embedded in the coverage map to just filenames
Object.keys(coverageMap).forEach(filename => {
coverageMap[filename].path = path.basename(coverageMap[filename].path);
delete coverageMap[filename].hash;
coverageMap[path.basename(filename)] = coverageMap[filename];
delete coverageMap[filename];
});
expect(coverageMap).toMatchSnapshot();
});
| 30.155556 | 77 | 0.699337 |
c61ca2161f96d936466d288b51bb05fcd8d0111f | 9,956 | js | JavaScript | src/icons/Icons.js | erick-martins/react-native-loyal | 70cfe41e24ad715bfea613583324cbca95fa1271 | [
"MIT"
] | null | null | null | src/icons/Icons.js | erick-martins/react-native-loyal | 70cfe41e24ad715bfea613583324cbca95fa1271 | [
"MIT"
] | null | null | null | src/icons/Icons.js | erick-martins/react-native-loyal | 70cfe41e24ad715bfea613583324cbca95fa1271 | [
"MIT"
] | null | null | null | import React from 'react';
import Icon from './Icon';
const Icons = {
Add: props => <Icon name="icon_add_30px" {...props} />,
Airplane: props => <Icon name="icon_airplane_30px" {...props} />,
Alarm: props => <Icon name="icon_alarm_30px" {...props} />,
Analyse: props => <Icon name="icon_analyse_30px" {...props} />,
Armichair: props => <Icon name="icon_armichair_30px" {...props} />,
ArrowDown: props => <Icon name="icon_arrow_down_30px" {...props} />,
ArrowLeft: props => <Icon name="icon_arrow_left_30px" {...props} />,
ArrowRight: props => <Icon name="icon_arrow_right_30px" {...props} />,
Attach: props => <Icon name="icon_attach_30px" {...props} />,
Baby: props => <Icon name="icon_baby_30px" {...props} />,
Bag: props => <Icon name="icon_bag_30px" {...props} />,
Ball: props => <Icon name="icon_ball_30px" {...props} />,
BallSoccer: props => <Icon name="icon_ball_soccer_30px" {...props} />,
Ballon: props => <Icon name="icon_ballon_30px" {...props} />,
Barcodes: props => <Icon name="icon_barcodes_30px" {...props} />,
Basket: props => <Icon name="icon_basket_30px" {...props} />,
Beauty: props => <Icon name="icon_beauty_30px" {...props} />,
Bike: props => <Icon name="icon_bike_30px" {...props} />,
Bluetooth: props => <Icon name="icon_bluetooth_30px" {...props} />,
Book: props => <Icon name="icon_book_30px" {...props} />,
Bookmark: props => <Icon name="icon_bookmark_30px" {...props} />,
Browser: props => <Icon name="icon_browser_30px" {...props} />,
Bus: props => <Icon name="icon_bus_30px" {...props} />,
Calendar: props => <Icon name="icon_calendar_30px" {...props} />,
Call: props => <Icon name="icon_call_30px" {...props} />,
Camera: props => <Icon name="icon_camera_30px" {...props} />,
Car: props => <Icon name="icon_car_30px" {...props} />,
Card: props => <Icon name="icon_card_30px" {...props} />,
Cart: props => <Icon name="icon_cart_30px" {...props} />,
Cash: props => <Icon name="icon_cash_30px" {...props} />,
Chart: props => <Icon name="icon_chart_30px" {...props} />,
Chat: props => <Icon name="icon_chat_30px" {...props} />,
Check: props => <Icon name="icon_check" {...props} />,
CheckAlt: props => <Icon name="icon_check_30px" {...props} />,
Clock: props => <Icon name="icon_clock_30px" {...props} />,
Close: props => <Icon name="icon_close" {...props} />,
CloseAlt: props => <Icon name="icon_close_30px" {...props} />,
Cloud: props => <Icon name="icon_cloud_30px" {...props} />,
CloudComputing: props => <Icon name="icon_cloud_computing_30px" {...props} />,
CloudDown: props => <Icon name="icon_cloud_down_30px" {...props} />,
CloudUp: props => <Icon name="icon_cloud_up_30px" {...props} />,
Colls: props => <Icon name="icon_colls" {...props} />,
Computer: props => <Icon name="icon_computer_30px" {...props} />,
Conversation: props => <Icon name="icon_conversation_30px" {...props} />,
Convert: props => <Icon name="icon_convert_30px" {...props} />,
Copy: props => <Icon name="icon_copy_30px" {...props} />,
Cruise: props => <Icon name="icon_cruise_30px" {...props} />,
Dev: props => <Icon name="icon_dev_30px" {...props} />,
Dislike: props => <Icon name="icon_dislike_30px" {...props} />,
Down: props => <Icon name="icon_down" {...props} />,
Download: props => <Icon name="icon_download_30px" {...props} />,
Drink: props => <Icon name="icon_drink_30px" {...props} />,
Dryer: props => <Icon name="icon_dryer_30px" {...props} />,
Dvd: props => <Icon name="icon_dvd_30px" {...props} />,
Edit: props => <Icon name="icon_edit_30px" {...props} />,
Equal: props => <Icon name="icon_equal_30px" {...props} />,
File: props => <Icon name="icon_file_30px" {...props} />,
Filter: props => <Icon name="icon_filter_30px" {...props} />,
Folder: props => <Icon name="icon_folder_30px" {...props} />,
FolderOpen: props => <Icon name="icon_folder_open_30px" {...props} />,
Fuel: props => <Icon name="icon_fuel_30px" {...props} />,
Funnel: props => <Icon name="icon_funnel_30px" {...props} />,
Game: props => <Icon name="icon_game_30px" {...props} />,
Gift: props => <Icon name="icon_gift_30px" {...props} />,
Headphone: props => <Icon name="icon_headphone_30px" {...props} />,
Helicopter: props => <Icon name="icon_helicopter_30px" {...props} />,
Help: props => <Icon name="icon_help_30px" {...props} />,
Hierarch: props => <Icon name="icon_hierarch_30px" {...props} />,
Home: props => <Icon name="icon_home_30px" {...props} />,
Host: props => <Icon name="icon_host_30px" {...props} />,
Hotel: props => <Icon name="icon_hotel_30px" {...props} />,
Idea: props => <Icon name="icon_idea_30px" {...props} />,
Joke: props => <Icon name="icon_joke_30px" {...props} />,
Label: props => <Icon name="icon_label_30px" {...props} />,
Laptop: props => <Icon name="icon_laptop_30px" {...props} />,
Left: props => <Icon name="icon_left" {...props} />,
Like: props => <Icon name="icon_like_30px" {...props} />,
Link: props => <Icon name="icon_link_30px" {...props} />,
List: props => <Icon name="icon_list" {...props} />,
ListAlt: props => <Icon name="icon_list_30px" {...props} />,
Location: props => <Icon name="icon_location_30px" {...props} />,
Lock: props => <Icon name="icon_lock_30px" {...props} />,
Login: props => <Icon name="icon_login_30px" {...props} />,
Logout: props => <Icon name="icon_logout_30px" {...props} />,
Map: props => <Icon name="icon_map_30px" {...props} />,
Mechanic: props => <Icon name="icon_mechanic_30px" {...props} />,
Medal: props => <Icon name="icon_medal_30px" {...props} />,
Megaphone: props => <Icon name="icon_megaphone_30px" {...props} />,
Menu: props => <Icon name="icon_menu" {...props} />,
Message: props => <Icon name="icon_message_30px" {...props} />,
MessageRead: props => <Icon name="icon_message_read_30px" {...props} />,
Microwave: props => <Icon name="icon_microwave_30px" {...props} />,
More: props => <Icon name="icon_more" {...props} />,
Motorcycle: props => <Icon name="icon_motorcycle_30px" {...props} />,
Movie: props => <Icon name="icon_movie_30px" {...props} />,
Music: props => <Icon name="icon_music_30px" {...props} />,
Newsletter: props => <Icon name="icon_newsletter_30px" {...props} />,
Notification: props => <Icon name="icon_notification_30px" {...props} />,
NotificationActive: props => <Icon name="icon_notification_active_30px" {...props} />,
Options: props => <Icon name="icon_options" {...props} />,
OptionsVertical: props => <Icon name="icon_options_vertical" {...props} />,
Package: props => <Icon name="icon_package_30px" {...props} />,
Pan: props => <Icon name="icon_pan_30px" {...props} />,
Pay: props => <Icon name="icon_pay_30px" {...props} />,
Pen: props => <Icon name="icon_pen_30px" {...props} />,
Phone: props => <Icon name="icon_phone_30px" {...props} />,
Picture: props => <Icon name="icon_picture_30px" {...props} />,
Pin: props => <Icon name="icon_pin_30px" {...props} />,
Placeholder: props => <Icon name="icon_placeholder_30px" {...props} />,
Play: props => <Icon name="icon_play_30px" {...props} />,
Presentation: props => <Icon name="icon_presentation_30px" {...props} />,
Press: props => <Icon name="icon_press_30px" {...props} />,
Profile: props => <Icon name="icon_profile_30px" {...props} />,
Question: props => <Icon name="icon_question_30px" {...props} />,
Rating: props => <Icon name="icon_rating" {...props} />,
Read: props => <Icon name="icon_read_30px" {...props} />,
Reload: props => <Icon name="icon_reload_30px" {...props} />,
Remove: props => <Icon name="icon_remove" {...props} />,
RemoveAlt: props => <Icon name="icon_remove_30px" {...props} />,
Return: props => <Icon name="icon_return_30px" {...props} />,
Right: props => <Icon name="icon_right" {...props} />,
Rocket: props => <Icon name="icon_rocket_30px" {...props} />,
Ruler: props => <Icon name="icon_ruler_30px" {...props} />,
Sad: props => <Icon name="icon_sad_30px" {...props} />,
Save: props => <Icon name="icon_save_30px" {...props} />,
Search: props => <Icon name="icon_search" {...props} />,
Send: props => <Icon name="icon_send_30px" {...props} />,
Settings: props => <Icon name="icon_settings_30px" {...props} />,
Share: props => <Icon name="icon_share_30px" {...props} />,
Smile: props => <Icon name="icon_smile_30px" {...props} />,
Speek: props => <Icon name="icon_speek_30px" {...props} />,
Star: props => <Icon name="icon_star_30px" {...props} />,
Stats: props => <Icon name="icon_stats_30px" {...props} />,
Sun: props => <Icon name="icon_sun_30px" {...props} />,
Tag: props => <Icon name="icon_tag_30px" {...props} />,
Target: props => <Icon name="icon_target_30px" {...props} />,
Train: props => <Icon name="icon_train_30px" {...props} />,
Translate: props => <Icon name="icon_translate_30px" {...props} />,
Trash: props => <Icon name="icon_trash_30px" {...props} />,
Truck: props => <Icon name="icon_truck_30px" {...props} />,
Tshirt: props => <Icon name="icon_tshirt_30px" {...props} />,
Ufo: props => <Icon name="icon_ufo_30px" {...props} />,
Umbrella: props => <Icon name="icon_umbrella_30px" {...props} />,
Unlock: props => <Icon name="icon_unlock_30px" {...props} />,
Up: props => <Icon name="icon_up" {...props} />,
UpAlt: props => <Icon name="icon_up_30px" {...props} />,
Updown: props => <Icon name="icon_updown" {...props} />,
Upload: props => <Icon name="icon_upload_30px" {...props} />,
View: props => <Icon name="icon_view_30px" {...props} />,
Voltage: props => <Icon name="icon_voltage_-1" {...props} />,
VoltageAlt: props => <Icon name="icon_voltage_30px" {...props} />,
Voucher: props => <Icon name="icon_voucher_30px" {...props} />,
VoucherAir: props => <Icon name="icon_voucher_air_30px" {...props} />,
Warning: props => <Icon name="icon_warning_30px" {...props} />,
Wifi: props => <Icon name="icon_wifi_30px" {...props} />
};
export default Icons;
| 61.079755 | 88 | 0.623242 |
c61d5f7a5da958beb121d95fcb60b74efd4691d2 | 1,224 | js | JavaScript | src/assets/redactor/dist/_langs/he.min.js | SilverStripers/redactor | baa05090b17b9b631ed3eb9f0687f48947d7dbc2 | [
"MIT"
] | 94 | 2017-12-29T16:37:07.000Z | 2022-03-18T08:13:31.000Z | src/assets/redactor/dist/_langs/he.min.js | SilverStripers/redactor | baa05090b17b9b631ed3eb9f0687f48947d7dbc2 | [
"MIT"
] | 366 | 2017-10-25T21:05:30.000Z | 2022-03-31T21:59:21.000Z | src/assets/redactor/dist/_langs/he.min.js | SilverStripers/redactor | baa05090b17b9b631ed3eb9f0687f48947d7dbc2 | [
"MIT"
] | 64 | 2017-10-31T08:14:22.000Z | 2022-03-27T10:40:05.000Z | Redactor.lang.he={format:"פורמט",image:"תמונה",file:"קובץ",link:"קישור",bold:"מודגש",italic:"נטוי",deleted:"מחוק",underline:"Underline",superscript:"Superscript",subscript:"Subscript","bold-abbr":"B","italic-abbr":"I","deleted-abbr":"S","underline-abbr":"U","superscript-abbr":"Sup","subscript-abbr":"Sub",lists:"רשימות","link-insert":"הוסף קישור","link-edit":"ערוך קישור","link-in-new-tab":"פתח קישור בחלון חדש",unlink:"הסר קישור",cancel:"בטל",close:"סגור",insert:"הכנס",save:"שמור",delete:"מחק",text:"טקסט",edit:"ערוך",title:"כותרת",paragraph:"טקסט רגיל",quote:"ציטוט",code:"קוד",heading1:"כותרת 1",heading2:"כותרת 2",heading3:"כותרת 3",heading4:"כותרת 4",heading5:"כותרת 5",heading6:"כותרת 6",filename:"שם",optional:"אופציונאלי",unorderedlist:"רשימת נקודות",orderedlist:"רשימה ממוספרת",outdent:"קרב לשוליים",indent:"הרחק מהשוליים",horizontalrule:"קו אופקי",upload:"Upload","upload-label":"Drop files here or click to upload","upload-change-label":"Drop a new image to change","accessibility-help-label":"עורך טקסט עשיר",caption:"כיתוב",bulletslist:"נקודות",numberslist:"ממוספר","image-position":"Position",none:"None",left:"Left",right:"Right",center:"Center",undo:"Undo",redo:"Redo"};
//# sourceMappingURL=he.min.js.map
| 408 | 1,188 | 0.734477 |
c61e856c0cd4d56ad2d5f9ed08123bb8d288d3ce | 6,970 | js | JavaScript | src/cobra/static/cobra/scripts/global/messages.js | lyoniionly/django-cobra | 2427e5cf74b7739115b1224da3306986b3ee345c | [
"Apache-2.0"
] | 1 | 2015-01-27T08:56:46.000Z | 2015-01-27T08:56:46.000Z | src/cobra/static/cobra/scripts/global/messages.js | lyoniionly/django-cobra | 2427e5cf74b7739115b1224da3306986b3ee345c | [
"Apache-2.0"
] | null | null | null | src/cobra/static/cobra/scripts/global/messages.js | lyoniionly/django-cobra | 2427e5cf74b7739115b1224da3306986b3ee345c | [
"Apache-2.0"
] | null | null | null | (function (app, jQuery, _) {
"use strict";
var $ = jQuery;
var pluginName, pluginClassName, pluginOptions, defaults, Message;
pluginName = 'message';
pluginClassName = pluginName + 'js';
pluginOptions = {
clickToHide: true,
autoHide: true,
autoHideDelay: 50000,
className: 'info',
showAnimation: 'slideDown',
showDuration: 400,
hideAnimation: 'slideUp',
hideDuration: 200,
container: '#messages',
safe: false
};
defaults = function(opts) {
return $.extend(pluginOptions, opts);
};
Message = (function() {
function Message(data, options) {
var type_display_map = {
'danger': gettext("Danger: "),
'warning': gettext("Warning: "),
'info': gettext("Notice: "),
'success': gettext("Success: "),
'error': gettext("Error: ")
}, type_display;
if (typeof options === 'string') {
type_display = type_display_map[options];
options = {
className: options === 'error' ? 'danger' : options
};
}
this.options = app.utils.inherit(pluginOptions, $.isPlainObject(options) ? options : {});
type_display = type_display || type_display_map[this.options.className];
this.options.className = this.options.className === 'error' ? 'danger' : this.options.className;
var template = _.template(app.templates.alert_message),
params = {
"type": this.options.className,
"type_display": type_display,
"message": data,
"safe": this.options.safe
};
this.wrapper = $(template(params));
if (this.options.clickToHide) {
this.wrapper.addClass("" + pluginClassName + "-hidable");
}
this.wrapper.data(pluginClassName, this);
this.wrapper.hide();
this.run();
}
Message.prototype.show = function(show, userCallback) {
var args, callback, elems, fn, hidden,
_this = this;
callback = function() {
if (!show) {
_this.destroy();
}
if (userCallback) {
return userCallback();
}
};
hidden = this.wrapper.parents(':hidden').length > 0;
elems = this.wrapper;
args = [];
if (hidden && show) {
fn = 'show';
} else if (hidden && !show) {
fn = 'hide';
} else if (!hidden && show) {
fn = this.options.showAnimation;
args.push(this.options.showDuration);
} else if (!hidden && !show) {
fn = this.options.hideAnimation;
args.push(this.options.hideDuration);
} else {
return callback();
}
args.push(callback);
return elems[fn].apply(elems, args);
};
Message.prototype.setPosition = function() {
var anchor, css;
if(this.options.container && $(this.options.container).length > 0) {
anchor = $(this.options.container);
} else {
anchor = app.utils.createElem("div");
css = {
top: 0,
right: 0
};
anchor.css(css).addClass("" + pluginClassName + "-corner");
if(this.options.container){
anchor.attr('id', this.options.container)
}
$("body").append(anchor);
}
return anchor.prepend(this.wrapper);
};
Message.prototype.run = function(options) {
var d, datas, name, type, value,
_this = this;
if ($.isPlainObject(options)) {
$.extend(this.options, options);
} else if ($.type(options) === 'string') {
this.options.className = options === 'error' ? 'danger' : options;
}
this.setPosition();
this.show(true);
if (this.options.autoHide) {
clearTimeout(this.autohideTimer);
return this.autohideTimer = setTimeout(function() {
return _this.show(false);
}, this.options.autoHideDelay);
}
};
Message.prototype.destroy = function() {
return this.wrapper.remove();
};
return Message;
})();
app.alert = function (type, message, extra_tags) {
var safe = false;
// Check if the message is tagged as safe.
if (typeof(extra_tags) !== "undefined" && $.inArray('safe', extra_tags.split(' ')) !== -1) {
safe = true;
}
/*new Message(message, {
className: type,
safe: safe
});*/
toastr[type](message);
};
app.clearErrorMessages = function() {
$('#messages .alert.alert-danger').remove();
};
app.clearSuccessMessages = function() {
$('#messages .alert.alert-success').remove();
};
app.clearAllMessages = function() {
app.clearErrorMessages();
app.clearSuccessMessages();
};
app.autoDismissAlerts = function() {
var $alerts = $('#messages .alert');
$alerts.each(function() {
var $alert = $(this),
types = $alert.attr('class').split(' '),
intersection = $.grep(types, function (value) {
return $.inArray(value, app.config.auto_fade_alerts.types) !== -1;
});
// Check if alert should auto-fade
if (intersection.length > 0) {
setTimeout(function() {
$alert.slideUp(app.config.auto_fade_alerts.fade_duration).remove();
}, app.config.auto_fade_alerts.delay);
}
});
};
app.addInitFunction(function () {
// Bind AJAX message handling.
$(document).ajaxComplete(function(event, request, settings){
/*var messages = app.ajax.get_messages(request);
if(messages){
var message_array = $.parseJSON(messages);
$.each(message_array.django_messages, function (i, item) {
app.alert(item.level, item.message, item.extra_tags);
});
}*/
var message_array = $.parseJSON(app.ajax.get_messages(request));
$(message_array).each(function (index, item) {
app.alert(item[0], item[1], item[2]);
});
}).ajaxError(function (event, request, settings, exception) {
app.alert("error", gettext("There was an error processing your request, please try again."));
});
// Dismiss alert messages when moving on to a new type of action.
$('a.ajax-modal').click(function() {
app.clearAllMessages();
});
// Bind dismiss(x) handlers for alert messages.
$(".alert").alert();
$(document).on('click', "." + pluginClassName + "-hidable", function(e) {
return $(this).trigger('message-hide');
});
$(document).on('message-hide', ".alert", function(e) {
var _ref;
return (_ref = $(this).data(pluginClassName)) != null ? _ref.show(false) : void 0;
});
// Hide alerts automatically if attribute data-dismiss-auto is set to true.
app.autoDismissAlerts();
toastr.options.closeButton = true;
toastr.options.progressBar = true;
toastr.options.positionClass = "toast-top-center";
toastr.options.timeOut = 5000;
toastr.options.extendedTimeOut = 0;
toastr.options.showMethod = "slideDown";
toastr.options.hideMethod = "slideUp";
});
}(app, jQuery, _)); | 30.043103 | 103 | 0.585509 |
c61eb463baef26c7973d0361e3cc29ac09b92d4e | 15,787 | js | JavaScript | js/ckeditor/lang/da.js | mir-duet/Dunsky | 3a82abfd3d1ace796a87e4957cb7b523e4f7da21 | [
"MIT"
] | 6 | 2015-03-13T08:34:14.000Z | 2022-03-05T17:10:09.000Z | js/ckeditor/lang/da.js | mir-duet/Dunsky | 3a82abfd3d1ace796a87e4957cb7b523e4f7da21 | [
"MIT"
] | 15 | 2015-03-23T08:40:03.000Z | 2022-01-21T23:14:03.000Z | js/ckeditor/lang/da.js | mir-duet/Dunsky | 3a82abfd3d1ace796a87e4957cb7b523e4f7da21 | [
"MIT"
] | 2 | 2015-04-21T15:06:26.000Z | 2017-02-17T14:44:57.000Z | /*
Copyright (c) 2003-2011, CKSource - Frederico Knabben. All rights reserved.
For licensing, see LICENSE.html or http://ckeditor.com/license
*/
CKEDITOR.lang.da={dir:'ltr',editorTitle:'Rich text editor, %1, press ALT 0 for help.',toolbar:'Toolbar',editor:'Rich Text Editor',source:'Kilde',newPage:'Ny side',save:'Gem',preview:'Vis eksempel',cut:'Klip',copy:'Kopiér',paste:'Indsæt',print:'Udskriv',underline:'Understreget',bold:'Fed',italic:'Kursiv',selectAll:'Vælg alt',removeFormat:'Fjern formatering',strike:'Gennemstreget',subscript:'Sænket skrift',superscript:'Hævet skrift',horizontalrule:'Indsæt vandret streg',pagebreak:'Indsæt sideskift',pagebreakAlt:'Page Break',unlink:'Fjern hyperlink',undo:'Fortryd',redo:'Annullér fortryd',common:{browseServer:'Gennemse...',url:'URL',protocol:'Protokol',upload:'Upload',uploadSubmit:'Upload',image:'Indsæt billede',flash:'Indsæt Flash',form:'Indsæt formular',checkbox:'Indsæt afkrydsningsfelt',radio:'Indsæt alternativknap',textField:'Indsæt tekstfelt',textarea:'Indsæt tekstboks',hiddenField:'Indsæt skjult felt',button:'Indsæt knap',select:'Indsæt liste',imageButton:'Indsæt billedknap',notSet:'<intet valgt>',id:'Id',name:'Navn',langDir:'Tekstretning',langDirLtr:'Fra venstre mod højre (LTR)',langDirRtl:'Fra højre mod venstre (RTL)',langCode:'Sprogkode',longDescr:'Udvidet beskrivelse',cssClass:'Typografiark (CSS)',advisoryTitle:'Titel',cssStyle:'Typografi (CSS)',ok:'OK',cancel:'Annullér',close:'Close',preview:'Preview',generalTab:'Generelt',advancedTab:'Avanceret',validateNumberFailed:'Værdien er ikke et tal.',confirmNewPage:'Alt indhold, der ikke er blevet gemt, vil gå tabt. Er du sikker på, at du vil indlæse en ny side?',confirmCancel:'Nogle af indstillingerne er blevet ændret. Er du sikker på, at du vil lukke vinduet?',options:'Options',target:'Target',targetNew:'New Window (_blank)',targetTop:'Topmost Window (_top)',targetSelf:'Same Window (_self)',targetParent:'Parent Window (_parent)',langDirLTR:'Left to Right (LTR)',langDirRTL:'Right to Left (RTL)',styles:'Style',cssClasses:'Stylesheet Classes',width:'Bredde',height:'Højde',align:'Justering',alignLeft:'Venstre',alignRight:'Højre',alignCenter:'Centreret',alignTop:'Øverst',alignMiddle:'Centreret',alignBottom:'Nederst',invalidHeight:'Højde skal være et tal.',invalidWidth:'Bredde skal være et tal.',unavailable:'%1<span class="cke_accessibility">, ikke tilgængelig</span>'},contextmenu:{options:'Context Menu Options'},specialChar:{toolbar:'Indsæt symbol',title:'Vælg symbol',options:'Special Character Options'},link:{toolbar:'Indsæt/redigér hyperlink',other:'<anden>',menu:'Redigér hyperlink',title:'Egenskaber for hyperlink',info:'Generelt',target:'Mål',upload:'Upload',advanced:'Avanceret',type:'Type',toUrl:'URL',toAnchor:'Bogmærke på denne side',toEmail:'E-mail',targetFrame:'<ramme>',targetPopup:'<popup vindue>',targetFrameName:'Destinationsvinduets navn',targetPopupName:'Popup vinduets navn',popupFeatures:'Egenskaber for popup',popupResizable:'Justérbar',popupStatusBar:'Statuslinje',popupLocationBar:'Adresselinje',popupToolbar:'Værktøjslinje',popupMenuBar:'Menulinje',popupFullScreen:'Fuld skærm (IE)',popupScrollBars:'Scrollbar',popupDependent:'Koblet/dependent (Netscape)',popupLeft:'Position fra venstre',popupTop:'Position fra toppen',id:'Id',langDir:'Tekstretning',langDirLTR:'Fra venstre mod højre (LTR)',langDirRTL:'Fra højre mod venstre (RTL)',acccessKey:'Genvejstast',name:'Navn',langCode:'Tekstretning',tabIndex:'Tabulator indeks',advisoryTitle:'Titel',advisoryContentType:'Indholdstype',cssClasses:'Typografiark',charset:'Tegnsæt',styles:'Typografi',selectAnchor:'Vælg et anker',anchorName:'Efter anker navn',anchorId:'Efter element Id',emailAddress:'E-mail adresse',emailSubject:'Emne',emailBody:'Besked',noAnchors:'(Ingen bogmærker i dokumentet)',noUrl:'Indtast hyperlink URL!',noEmail:'Indtast e-mail adresse!'},anchor:{toolbar:'Indsæt/redigér bogmærke',menu:'Egenskaber for bogmærke',title:'Egenskaber for bogmærke',name:'Bogmærke navn',errorName:'Indtast bogmærke navn'},list:{numberedTitle:'Numbered List Properties',bulletedTitle:'Bulleted List Properties',type:'Type',start:'Start',validateStartNumber:'List start number must be a whole number.',circle:'Circle',disc:'Disc',square:'Square',none:'None',notset:'<not set>',armenian:'Armenian numbering',georgian:'Georgian numbering (an, ban, gan, etc.)',lowerRoman:'Lower Roman (i, ii, iii, iv, v, etc.)',upperRoman:'Upper Roman (I, II, III, IV, V, etc.)',lowerAlpha:'Lower Alpha (a, b, c, d, e, etc.)',upperAlpha:'Upper Alpha (A, B, C, D, E, etc.)',lowerGreek:'Lower Greek (alpha, beta, gamma, etc.)',decimal:'Decimal (1, 2, 3, etc.)',decimalLeadingZero:'Decimal leading zero (01, 02, 03, etc.)'},findAndReplace:{title:'Søg og erstat',find:'Søg',replace:'Erstat',findWhat:'Søg efter:',replaceWith:'Erstat med:',notFoundMsg:'Søgeteksten blev ikke fundet',matchCase:'Forskel på store og små bogstaver',matchWord:'Kun hele ord',matchCyclic:'Match cyklisk',replaceAll:'Erstat alle',replaceSuccessMsg:'%1 forekomst(er) erstattet.'},table:{toolbar:'Tabel',title:'Egenskaber for tabel',menu:'Egenskaber for tabel',deleteTable:'Slet tabel',rows:'Rækker',columns:'Kolonner',border:'Rammebredde',widthPx:'pixels',widthPc:'procent',widthUnit:'width unit',cellSpace:'Celleafstand',cellPad:'Cellemargen',caption:'Titel',summary:'Resumé',headers:'Header',headersNone:'Ingen',headersColumn:'Første kolonne',headersRow:'Første række',headersBoth:'Begge',invalidRows:'Antallet af rækker skal være større end 0.',invalidCols:'Antallet af kolonner skal være større end 0.',invalidBorder:'Rammetykkelse skal være et tal.',invalidWidth:'Tabelbredde skal være et tal.',invalidHeight:'Tabelhøjde skal være et tal.',invalidCellSpacing:'Celleafstand skal være et tal.',invalidCellPadding:'Cellemargen skal være et tal.',cell:{menu:'Celle',insertBefore:'Indsæt celle før',insertAfter:'Indsæt celle efter',deleteCell:'Slet celle',merge:'Flet celler',mergeRight:'Flet til højre',mergeDown:'Flet nedad',splitHorizontal:'Del celle vandret',splitVertical:'Del celle lodret',title:'Celleegenskaber',cellType:'Celletype',rowSpan:'Række span (rows span)',colSpan:'Kolonne span (columns span)',wordWrap:'Tekstombrydning',hAlign:'Vandret justering',vAlign:'Lodret justering',alignBaseline:'Grundlinje',bgColor:'Baggrundsfarve',borderColor:'Rammefarve',data:'Data',header:'Header',yes:'Ja',no:'Nej',invalidWidth:'Cellebredde skal være et tal.',invalidHeight:'Cellehøjde skal være et tal.',invalidRowSpan:'Række span skal være et heltal.',invalidColSpan:'Kolonne span skal være et heltal.',chooseColor:'Choose'},row:{menu:'Række',insertBefore:'Indsæt række før',insertAfter:'Indsæt række efter',deleteRow:'Slet række'},column:{menu:'Kolonne',insertBefore:'Indsæt kolonne før',insertAfter:'Indsæt kolonne efter',deleteColumn:'Slet kolonne'}},button:{title:'Egenskaber for knap',text:'Tekst',type:'Type',typeBtn:'Knap',typeSbm:'Send',typeRst:'Nulstil'},checkboxAndRadio:{checkboxTitle:'Egenskaber for afkrydsningsfelt',radioTitle:'Egenskaber for alternativknap',value:'Værdi',selected:'Valgt'},form:{title:'Egenskaber for formular',menu:'Egenskaber for formular',action:'Handling',method:'Metode',encoding:'Kodning (encoding)'},select:{title:'Egenskaber for liste',selectInfo:'Generelt',opAvail:'Valgmuligheder',value:'Værdi',size:'Størrelse',lines:'Linjer',chkMulti:'Tillad flere valg',opText:'Tekst',opValue:'Værdi',btnAdd:'Tilføj',btnModify:'Redigér',btnUp:'Op',btnDown:'Ned',btnSetValue:'Sæt som valgt',btnDelete:'Slet'},textarea:{title:'Egenskaber for tekstboks',cols:'Kolonner',rows:'Rækker'},textfield:{title:'Egenskaber for tekstfelt',name:'Navn',value:'Værdi',charWidth:'Bredde (tegn)',maxChars:'Max. antal tegn',type:'Type',typeText:'Tekst',typePass:'Adgangskode'},hidden:{title:'Egenskaber for skjult felt',name:'Navn',value:'Værdi'},image:{title:'Egenskaber for billede',titleButton:'Egenskaber for billedknap',menu:'Egenskaber for billede',infoTab:'Generelt',btnUpload:'Upload',upload:'Upload',alt:'Alternativ tekst',lockRatio:'Lås størrelsesforhold',unlockRatio:'Unlock Ratio',resetSize:'Nulstil størrelse',border:'Ramme',hSpace:'Vandret margen',vSpace:'Lodret margen',alertUrl:'Indtast stien til billedet',linkTab:'Hyperlink',button2Img:'Vil du lave billedknappen om til et almindeligt billede?',img2Button:'Vil du lave billedet om til en billedknap?',urlMissing:'Image source URL is missing.',validateBorder:'Border must be a whole number.',validateHSpace:'HSpace must be a whole number.',validateVSpace:'VSpace must be a whole number.'},flash:{properties:'Egenskaber for Flash',propertiesTab:'Egenskaber',title:'Egenskaber for Flash',chkPlay:'Automatisk afspilning',chkLoop:'Gentagelse',chkMenu:'Vis Flash menu',chkFull:'Tillad fuldskærm',scale:'Skalér',scaleAll:'Vis alt',scaleNoBorder:'Ingen ramme',scaleFit:'Tilpas størrelse',access:'Script adgang',accessAlways:'Altid',accessSameDomain:'Samme domæne',accessNever:'Aldrig',alignAbsBottom:'Absolut nederst',alignAbsMiddle:'Absolut centreret',alignBaseline:'Grundlinje',alignTextTop:'Toppen af teksten',quality:'Kvalitet',qualityBest:'Bedste',qualityHigh:'Høj',qualityAutoHigh:'Auto høj',qualityMedium:'Medium',qualityAutoLow:'Auto lav',qualityLow:'Lav',windowModeWindow:'Vindue',windowModeOpaque:'Gennemsigtig (opaque)',windowModeTransparent:'Transparent',windowMode:'Vinduestilstand',flashvars:'Variabler for Flash',bgcolor:'Baggrundsfarve',hSpace:'Vandret margen',vSpace:'Lodret margen',validateSrc:'Indtast hyperlink URL!',validateHSpace:'Vandret margen skal være et tal.',validateVSpace:'Lodret margen skal være et tal.'},spellCheck:{toolbar:'Stavekontrol',title:'Stavekontrol',notAvailable:'Stavekontrol er desværre ikke tilgængelig.',errorLoading:'Fejl ved indlæsning af host: %s.',notInDic:'Ikke i ordbogen',changeTo:'Forslag',btnIgnore:'Ignorér',btnIgnoreAll:'Ignorér alle',btnReplace:'Erstat',btnReplaceAll:'Erstat alle',btnUndo:'Tilbage',noSuggestions:'(ingen forslag)',progress:'Stavekontrollen arbejder...',noMispell:'Stavekontrol færdig: Ingen fejl fundet',noChanges:'Stavekontrol færdig: Ingen ord ændret',oneChange:'Stavekontrol færdig: Et ord ændret',manyChanges:'Stavekontrol færdig: %1 ord ændret',ieSpellDownload:'Stavekontrol ikke installeret. Vil du installere den nu?'},smiley:{toolbar:'Smiley',title:'Vælg smiley',options:'Smiley Options'},elementsPath:{eleLabel:'Elements path',eleTitle:'%1 element'},numberedlist:'Talopstilling',bulletedlist:'Punktopstilling',indent:'Forøg indrykning',outdent:'Formindsk indrykning',justify:{left:'Venstrestillet',center:'Centreret',right:'Højrestillet',block:'Lige margener'},blockquote:'Blokcitat',clipboard:{title:'Indsæt',cutError:'Din browsers sikkerhedsindstillinger tillader ikke editoren at få automatisk adgang til udklipsholderen.<br><br>Brug i stedet tastaturet til at klippe teksten (Ctrl/Cmd+X).',copyError:'Din browsers sikkerhedsindstillinger tillader ikke editoren at få automatisk adgang til udklipsholderen.<br><br>Brug i stedet tastaturet til at kopiere teksten (Ctrl/Cmd+C).',pasteMsg:'Indsæt i feltet herunder (<STRONG>Ctrl/Cmd+V</STRONG>) og klik på <STRONG>OK</STRONG>.',securityMsg:'Din browsers sikkerhedsindstillinger tillader ikke editoren at få automatisk adgang til udklipsholderen.<br><br>Du skal indsætte udklipsholderens indhold i dette vindue igen.',pasteArea:'Paste Area'},pastefromword:{confirmCleanup:'Den tekst du forsøger at indsætte ser ud til at komme fra Word. Vil du rense teksten før den indsættes?',toolbar:'Indsæt fra Word',title:'Indsæt fra Word',error:'It was not possible to clean up the pasted data due to an internal error'},pasteText:{button:'Indsæt som ikke-formateret tekst',title:'Indsæt som ikke-formateret tekst'},templates:{button:'Skabeloner',title:'Indholdsskabeloner',options:'Template Options',insertOption:'Erstat det faktiske indhold',selectPromptMsg:'Vælg den skabelon, som skal åbnes i editoren (nuværende indhold vil blive overskrevet):',emptyListMsg:'(Der er ikke defineret nogen skabelon)'},showBlocks:'Vis afsnitsmærker',stylesCombo:{label:'Typografi',panelTitle:'Formatting Styles',panelTitle1:'Block typografi',panelTitle2:'Inline typografi',panelTitle3:'Object typografi'},format:{label:'Formatering',panelTitle:'Formatering',tag_p:'Normal',tag_pre:'Formateret',tag_address:'Adresse',tag_h1:'Overskrift 1',tag_h2:'Overskrift 2',tag_h3:'Overskrift 3',tag_h4:'Overskrift 4',tag_h5:'Overskrift 5',tag_h6:'Overskrift 6',tag_div:'Normal (DIV)'},div:{title:'Create Div Container',toolbar:'Create Div Container',cssClassInputLabel:'Stylesheet Classes',styleSelectLabel:'Style',IdInputLabel:'Id',languageCodeInputLabel:' Language Code',inlineStyleInputLabel:'Inline Style',advisoryTitleInputLabel:'Advisory Title',langDirLabel:'Language Direction',langDirLTRLabel:'Left to Right (LTR)',langDirRTLLabel:'Right to Left (RTL)',edit:'Edit Div',remove:'Remove Div'},iframe:{title:'IFrame Properties',toolbar:'IFrame',noUrl:'Please type the iframe URL',scrolling:'Enable scrollbars',border:'Show frame border'},font:{label:'Skrifttype',voiceLabel:'Skrifttype',panelTitle:'Skrifttype'},fontSize:{label:'Skriftstørrelse',voiceLabel:'Skriftstørrelse',panelTitle:'Skriftstørrelse'},colorButton:{textColorTitle:'Tekstfarve',bgColorTitle:'Baggrundsfarve',panelTitle:'Colors',auto:'Automatisk',more:'Flere farver...'},colors:{'000':'Black',800000:'Maroon','8B4513':'Saddle Brown','2F4F4F':'Dark Slate Gray','008080':'Teal','000080':'Navy','4B0082':'Indigo',696969:'Dark Gray',B22222:'Fire Brick',A52A2A:'Brown',DAA520:'Golden Rod','006400':'Dark Green','40E0D0':'Turquoise','0000CD':'Medium Blue',800080:'Purple',808080:'Gray',F00:'Red',FF8C00:'Dark Orange',FFD700:'Gold','008000':'Green','0FF':'Cyan','00F':'Blue',EE82EE:'Violet',A9A9A9:'Dim Gray',FFA07A:'Light Salmon',FFA500:'Orange',FFFF00:'Yellow','00FF00':'Lime',AFEEEE:'Pale Turquoise',ADD8E6:'Light Blue',DDA0DD:'Plum',D3D3D3:'Light Grey',FFF0F5:'Lavender Blush',FAEBD7:'Antique White',FFFFE0:'Light Yellow',F0FFF0:'Honeydew',F0FFFF:'Azure',F0F8FF:'Alice Blue',E6E6FA:'Lavender',FFF:'White'},scayt:{title:'Stavekontrol mens du skriver',opera_title:'Not supported by Opera',enable:'Aktivér SCAYT',disable:'Deaktivér SCAYT',about:'Om SCAYT',toggle:'Skift/toggle SCAYT',options:'Indstillinger',langs:'Sprog',moreSuggestions:'Flere forslag',ignore:'Ignorér',ignoreAll:'Ignorér alle',addWord:'Tilføj ord',emptyDic:'Ordbogsnavn må ikke være tom.',optionsTab:'Indstillinger',allCaps:'Ignore All-Caps Words',ignoreDomainNames:'Ignore Domain Names',mixedCase:'Ignore Words with Mixed Case',mixedWithDigits:'Ignore Words with Numbers',languagesTab:'Sprog',dictionariesTab:'Ordbøger',dic_field_name:'Dictionary name',dic_create:'Create',dic_restore:'Restore',dic_delete:'Delete',dic_rename:'Rename',dic_info:'Initially the User Dictionary is stored in a Cookie. However, Cookies are limited in size. When the User Dictionary grows to a point where it cannot be stored in a Cookie, then the dictionary may be stored on our server. To store your personal dictionary on our server you should specify a name for your dictionary. If you already have a stored dictionary, please type its name and click the Restore button.',aboutTab:'Om'},about:{title:'Om CKEditor',dlgTitle:'Om CKEditor',moreInfo:'For informationer omkring licens, se venligst vores hjemmeside (på engelsk):',copy:'Copyright © $1. Alle rettigheder forbeholdes.'},maximize:'Maximér',minimize:'Minimize',fakeobjects:{anchor:'Anker',flash:'Flashanimation',iframe:'IFrame',hiddenfield:'Hidden Field',unknown:'Ukendt objekt'},resize:'Træk for at skalere',colordialog:{title:'Select color',options:'Color Options',highlight:'Highlight',selected:'Selected Color',clear:'Clear'},toolbarCollapse:'Collapse Toolbar',toolbarExpand:'Expand Toolbar',bidi:{ltr:'Text direction from left to right',rtl:'Text direction from right to left'}};
| 2,255.285714 | 15,639 | 0.787103 |
c61ee55a1f9f8fbb63b0719c2e2ee562efed73d9 | 10,317 | js | JavaScript | lib/js-cuint/uint32.js | valentinvichnal/bloomfilters.js | ea0bfa70ed41f847680d969f79453f8a8907e1f0 | [
"MIT"
] | 1 | 2017-01-18T18:49:34.000Z | 2017-01-18T18:49:34.000Z | lib/js-cuint/uint32.js | valentinvichnal/bloomfilters.js | ea0bfa70ed41f847680d969f79453f8a8907e1f0 | [
"MIT"
] | null | null | null | lib/js-cuint/uint32.js | valentinvichnal/bloomfilters.js | ea0bfa70ed41f847680d969f79453f8a8907e1f0 | [
"MIT"
] | null | null | null | /**
C-like unsigned 32 bits integers in Javascript
Copyright (C) 2013, Pierre Curto
MIT license
*/
;(function (root) {
// Local cache for typical radices
var radixPowerCache = {
36: UINT32( Math.pow(36, 5) )
, 16: UINT32( Math.pow(16, 7) )
, 10: UINT32( Math.pow(10, 9) )
, 2: UINT32( Math.pow(2, 30) )
}
var radixCache = {
36: UINT32(36)
, 16: UINT32(16)
, 10: UINT32(10)
, 2: UINT32(2)
}
/**
* Represents an unsigned 32 bits integer
* @constructor
* @param {Number|String|Number} low bits | integer as a string | integer as a number
* @param {Number|Number|Undefined} high bits | radix (optional, default=10)
* @return
*/
function UINT32 (l, h) {
if ( !(this instanceof UINT32) )
return new UINT32(l, h)
this._low = 0
this._high = 0
this.remainder = null
if (typeof h == 'undefined')
return fromNumber.call(this, l)
if (typeof l == 'string')
return fromString.call(this, l, h)
fromBits.call(this, l, h)
}
/**
* Set the current _UINT32_ object with its low and high bits
* @method fromBits
* @param {Number} low bits
* @param {Number} high bits
* @return ThisExpression
*/
function fromBits (l, h) {
this._low = l | 0
this._high = h | 0
return this
}
UINT32.prototype.fromBits = fromBits
/**
* Set the current _UINT32_ object from a number
* @method fromNumber
* @param {Number} number
* @return ThisExpression
*/
function fromNumber (value) {
this._low = value & 0xFFFF
this._high = value >>> 16
return this
}
UINT32.prototype.fromNumber = fromNumber
/**
* Set the current _UINT32_ object from a string
* @method fromString
* @param {String} integer as a string
* @param {Number} radix (optional, default=10)
* @return ThisExpression
*/
function fromString (s, radix) {
var value = parseInt(s, radix || 10)
this._low = value & 0xFFFF
this._high = value >>> 16
return this
}
UINT32.prototype.fromString = fromString
/**
* Convert this _UINT32_ to a number
* @method toNumber
* @return {Number} the converted UINT32
*/
UINT32.prototype.toNumber = function () {
return (this._high << 16) | this._low
}
/**
* Convert this _UINT32_ to a string
* @method toString
* @param {Number} radix (optional, default=10)
* @return {String} the converted UINT32
*/
UINT32.prototype.toString = function (radix) {
radix = radix || 10
var radixUint = radixCache[radix] || new UINT32(radix)
if ( !this.gt(radixUint) ) return this.toNumber().toString(radix)
var self = this.clone()
var res = new Array(32)
for (var i = 31; i >= 0; i--) {
self.div(radixUint)
res[i] = self.remainder.toNumber().toString(radix)
if ( !self.gt(radixUint) ) break
}
res[i-1] = self.toNumber().toString(radix)
return res.join('')
}
/**
* Add two _UINT32_. The current _UINT32_ stores the result
* @method add
* @param {Object} other UINT32
* @return ThisExpression
*/
UINT32.prototype.add = function (other) {
var a00 = this._low + other._low
var a16 = a00 >>> 16
a16 += this._high + other._high
this._low = a00 & 0xFFFF
this._high = a16 & 0xFFFF
return this
}
/**
* Subtract two _UINT32_. The current _UINT32_ stores the result
* @method subtract
* @param {Object} other UINT32
* @return ThisExpression
*/
UINT32.prototype.subtract = function (other) {
//TODO inline
return this.add( other.clone().negate() )
}
/**
* Multiply two _UINT32_. The current _UINT32_ stores the result
* @method multiply
* @param {Object} other UINT32
* @return ThisExpression
*/
UINT32.prototype.multiply = function (other) {
/*
a = a00 + a16
b = b00 + b16
a*b = (a00 + a16)(b00 + b16)
= a00b00 + a00b16 + a16b00 + a16b16
a16b16 overflows the 32bits
*/
var a16 = this._high
var a00 = this._low
var b16 = other._high
var b00 = other._low
/* Removed to increase speed under normal circumstances (i.e. not multiplying by 0 or 1)
// this == 0 or other == 1: nothing to do
if ((a00 == 0 && a16 == 0) || (b00 == 1 && b16 == 0)) return this
// other == 0 or this == 1: this = other
if ((b00 == 0 && b16 == 0) || (a00 == 1 && a16 == 0)) {
this._low = other._low
this._high = other._high
return this
}
*/
var c16, c00
c00 = a00 * b00
c16 = c00 >>> 16
c16 += a16 * b00
c16 &= 0xFFFF // Not required but improves performance
c16 += a00 * b16
this._low = c00 & 0xFFFF
this._high = c16 & 0xFFFF
return this
}
/**
* Divide two _UINT32_. The current _UINT32_ stores the result.
* The remainder is made available as the _remainder_ property on
* the _UINT32_ object. It can be null, meaning there are no remainder.
* @method div
* @param {Object} other UINT32
* @return ThisExpression
*/
UINT32.prototype.div = function (other) {
if ( (other._low == 0) && (other._high == 0) ) throw Error('division by zero')
// other == 1
if (other._high == 0 && other._low == 1) {
this.remainder = new UINT32(0)
return this
}
// other > this: 0
if ( other.gt(this) ) {
this.remainder = new UINT32(0)
this._low = 0
this._high = 0
return this
}
// other == this: 1
if ( this.eq(other) ) {
this.remainder = new UINT32(0)
this._low = 1
this._high = 0
return this
}
// Shift the divisor left until it is higher than the dividend
var _other = other.clone()
var i = -1
while ( !this.lt(_other) ) {
// High bit can overflow the default 16bits
// Its ok since we right shift after this loop
// The overflown bit must be kept though
_other.shiftLeft(1, true)
i++
}
// Set the remainder
this.remainder = this.clone()
// Initialize the current result to 0
this._low = 0
this._high = 0
for (; i >= 0; i--) {
_other.shiftRight(1)
// If shifted divisor is smaller than the dividend
// then subtract it from the dividend
if ( !this.remainder.lt(_other) ) {
this.remainder.subtract(_other)
// Update the current result
if (i >= 16) {
this._high |= 1 << (i - 16)
} else {
this._low |= 1 << i
}
}
}
return this
}
/**
* Negate the current _UINT32_
* @method negate
* @return ThisExpression
*/
UINT32.prototype.negate = function () {
var v = ( ~this._low & 0xFFFF ) + 1
this._low = v & 0xFFFF
this._high = (~this._high + (v >>> 16)) & 0xFFFF
return this
}
/**
* Equals
* @method eq
* @param {Object} other UINT32
* @return {Boolean}
*/
UINT32.prototype.equals = UINT32.prototype.eq = function (other) {
return (this._low == other._low) && (this._high == other._high)
}
/**
* Greater than (strict)
* @method gt
* @param {Object} other UINT32
* @return {Boolean}
*/
UINT32.prototype.greaterThan = UINT32.prototype.gt = function (other) {
if (this._high > other._high) return true
if (this._high < other._high) return false
return this._low > other._low
}
/**
* Less than (strict)
* @method lt
* @param {Object} other UINT32
* @return {Boolean}
*/
UINT32.prototype.lessThan = UINT32.prototype.lt = function (other) {
if (this._high < other._high) return true
if (this._high > other._high) return false
return this._low < other._low
}
/**
* Bitwise OR
* @method or
* @param {Object} other UINT32
* @return ThisExpression
*/
UINT32.prototype.or = function (other) {
this._low |= other._low
this._high |= other._high
return this
}
/**
* Bitwise AND
* @method and
* @param {Object} other UINT32
* @return ThisExpression
*/
UINT32.prototype.and = function (other) {
this._low &= other._low
this._high &= other._high
return this
}
/**
* Bitwise NOT
* @method not
* @return ThisExpression
*/
UINT32.prototype.not = function() {
this._low = ~this._low & 0xFFFF
this._high = ~this._high & 0xFFFF
return this
}
/**
* Bitwise XOR
* @method xor
* @param {Object} other UINT32
* @return ThisExpression
*/
UINT32.prototype.xor = function (other) {
this._low ^= other._low
this._high ^= other._high
return this
}
/**
* Bitwise shift right
* @method shiftRight
* @param {Number} number of bits to shift
* @return ThisExpression
*/
UINT32.prototype.shiftRight = UINT32.prototype.shiftr = function (n) {
if (n > 16) {
this._low = this._high >> (n - 16)
this._high = 0
} else if (n == 16) {
this._low = this._high
this._high = 0
} else {
this._low = (this._low >> n) | ( (this._high << (16-n)) & 0xFFFF )
this._high >>= n
}
return this
}
/**
* Bitwise shift left
* @method shiftLeft
* @param {Number} number of bits to shift
* @param {Boolean} allow overflow
* @return ThisExpression
*/
UINT32.prototype.shiftLeft = UINT32.prototype.shiftl = function (n, allowOverflow) {
if (n > 16) {
this._high = this._low << (n - 16)
this._low = 0
if (!allowOverflow) {
this._high &= 0xFFFF
}
} else if (n == 16) {
this._high = this._low
this._low = 0
} else {
this._high = (this._high << n) | (this._low >> (16-n))
this._low = (this._low << n) & 0xFFFF
if (!allowOverflow) {
// Overflow only allowed on the high bits...
this._high &= 0xFFFF
}
}
return this
}
/**
* Bitwise rotate left
* @method rotl
* @param {Number} number of bits to rotate
* @return ThisExpression
*/
UINT32.prototype.rotateLeft = UINT32.prototype.rotl = function (n) {
var v = (this._high << 16) | this._low
v = (v << n) | (v >>> (32 - n))
this._low = v & 0xFFFF
this._high = v >>> 16
return this
}
/**
* Bitwise rotate right
* @method rotr
* @param {Number} number of bits to rotate
* @return ThisExpression
*/
UINT32.prototype.rotateRight = UINT32.prototype.rotr = function (n) {
var v = (this._high << 16) | this._low
v = (v >>> n) | (v << (32 - n))
this._low = v & 0xFFFF
this._high = v >>> 16
return this
}
/**
* Clone the current _UINT32_
* @method clone
* @return {Object} cloned UINT32
*/
UINT32.prototype.clone = function () {
return new UINT32(this._low, this._high)
}
if (typeof define != 'undefined' && define.amd) {
// AMD / RequireJS
define([], function () {
return UINT32
})
} else if (typeof module != 'undefined' && module.exports) {
// Node.js
module.exports = UINT32
} else {
// Browser
root['UINT32'] = UINT32
}
})(this)
| 22.139485 | 93 | 0.621402 |
c61ef6e2b20396e02bc43555c826fee2e09f1c38 | 586 | js | JavaScript | packages/test262-runner/test262/test/built-ins/BigInt/new-target-throws.js | Kashuhackerone/SES-shim | 195f9887119e1a81ca35dd6f445b73241a5e7338 | [
"Apache-2.0"
] | 203 | 2021-03-15T09:28:14.000Z | 2022-03-26T20:42:49.000Z | packages/test262-runner/test262/test/built-ins/BigInt/new-target-throws.js | rekmarks/endo | 7d4b3d8716d5179af4d26762f3110cc2494d7a12 | [
"Apache-2.0"
] | 417 | 2020-02-21T05:08:48.000Z | 2021-03-13T00:18:53.000Z | packages/test262-runner/test262/test/built-ins/BigInt/new-target-throws.js | rekmarks/endo | 7d4b3d8716d5179af4d26762f3110cc2494d7a12 | [
"Apache-2.0"
] | 29 | 2021-03-18T15:34:29.000Z | 2022-03-08T14:36:07.000Z | // Copyright (C) 2017 Robin Templeton. All rights reserved.
// This code is governed by the BSD license found in the LICENSE file.
/*---
description: Throws a TypeError if BigInt is called with a new target
esid: sec-bigint-constructor
info: |
1. If NewTarget is not undefined, throw a TypeError exception.
...
features: [BigInt]
---*/
assert.sameValue(typeof BigInt, 'function');
assert.throws(TypeError, function() {
new BigInt();
});
assert.throws(TypeError, function() {
new BigInt({
valueOf: function() {
throw new Test262Error("unreachable");
}
});
});
| 23.44 | 70 | 0.691126 |
c61efc85610f2c521d730d99848af282ec2b3d25 | 161 | js | JavaScript | example/static/component/readonly.js | thomas-hoer/minee-go | a279248b870a434fa2f6f6b24f2df183abce1981 | [
"Apache-2.0"
] | null | null | null | example/static/component/readonly.js | thomas-hoer/minee-go | a279248b870a434fa2f6f6b24f2df183abce1981 | [
"Apache-2.0"
] | null | null | null | example/static/component/readonly.js | thomas-hoer/minee-go | a279248b870a434fa2f6f6b24f2df183abce1981 | [
"Apache-2.0"
] | null | null | null | 'use strict'
import { h } from '/js/preact.js'
function Readonly(props){
return h('div',{className:'input-readonly'},props.property.get())
}
export {Readonly} | 20.125 | 66 | 0.701863 |
c61f0dc648119dc1064b8bdcfcf2277a01bea89e | 1,127 | js | JavaScript | app/static/js/promotion_dialog.js | profcalculus/paradigmchess30 | d1cb41d5e18b5449979722d0b95664e60cbed203 | [
"MIT"
] | null | null | null | app/static/js/promotion_dialog.js | profcalculus/paradigmchess30 | d1cb41d5e18b5449979722d0b95664e60cbed203 | [
"MIT"
] | null | null | null | app/static/js/promotion_dialog.js | profcalculus/paradigmchess30 | d1cb41d5e18b5449979722d0b95664e60cbed203 | [
"MIT"
] | null | null | null |
class PromotionDialog {
constructor (board, move_cfg, getImgSrc) {
this.board = board;
this.move_cfg = move_cfg;
// get piece images
$ ('.promotion-piece-q').attr ('src', getImgSrc ('q'));
$ ('.promotion-piece-r').attr ('src', getImgSrc ('r'));
$ ('.promotion-piece-n').attr ('src', getImgSrc ('n'));
$ ('.promotion-piece-b').attr ('src', getImgSrc ('b'));
//show the select piece to promote to dialog
promotion_dialog
.dialog ({
modal: true,
height: 46,
width: 184,
resizable: true,
draggable: false,
close: this.onDialogClose,
closeOnEscape: false,
dialogClass: 'noTitleStuff',
})
.dialog ('widget')
.position ({
of: $ (`#{board_id}`),
my: 'middle middle',
at: 'middle middle',
});
//the actual move is made after the piece to promote to
//has been selected, in the onDialogClose event
} // constructor
onDialogClose () {
this.move_cfg.promotion = promote_to;
move = this.board.makeMove (this.game, this.move_cfg);
}
}
export {PromotionDialog};
| 28.897436 | 59 | 0.582964 |
c61f32aceb3639174db65f877aa70fe556b67aa9 | 1,885 | js | JavaScript | app/core/device.js | gitHubLizi/Test1 | c4033d5e8d061c69238d0c3141c1a3fc46a56c6c | [
"MIT",
"Unlicense"
] | null | null | null | app/core/device.js | gitHubLizi/Test1 | c4033d5e8d061c69238d0c3141c1a3fc46a56c6c | [
"MIT",
"Unlicense"
] | null | null | null | app/core/device.js | gitHubLizi/Test1 | c4033d5e8d061c69238d0c3141c1a3fc46a56c6c | [
"MIT",
"Unlicense"
] | null | null | null | import fs from 'fs'
import path from 'path'
const {app} = require('electron').remote
var userData = app.getPath('userData')
export default class Device {
constructor (name, super_block, inode_table, data_bitmap_buffer, data_block_buffer) {
this.name = name
this.size = data_block_buffer.length
this.super_block = super_block
this.inode_table = inode_table
this.data_bitmap_buffer = data_bitmap_buffer
this.data_block_buffer = data_block_buffer
}
write () {
try {
fs.accessSync(path.join(userData, this.name))
} catch (e) {
fs.mkdirSync(path.join(userData, this.name))
}
try {
fs.writeFileSync(path.join(userData, this.name, 'super_block'), JSON.stringify(this.super_block))
fs.writeFileSync(path.join(userData, this.name, 'inode_table'), JSON.stringify(this.inode_table))
fs.writeFileSync(path.join(userData, this.name, 'data_bitmap_buffer'), this.data_bitmap_buffer)
fs.writeFileSync(path.join(userData, this.name, 'data_block_buffer'), this.data_block_buffer)
return true
} catch (e) {
console.error(e)
return false
}
}
static read (name) {
fs.accessSync(path.join(userData, name))
var super_block = JSON.parse(fs.readFileSync(path.join(userData, name, 'super_block')).toString())
var inode_table = JSON.parse(fs.readFileSync(path.join(userData, name, 'inode_table')).toString())
var data_bitmap_buffer = fs.readFileSync(path.join(userData, name, 'data_bitmap_buffer'))
var data_block_buffer = fs.readFileSync(path.join(userData, name, 'data_block_buffer'))
return new Device(name, super_block, inode_table, data_bitmap_buffer, data_block_buffer)
}
static create (name) {
var data_size = 128 * 1024 * 1024 // bytes
var data_block_buffer = Buffer.alloc(data_size)
return new Device(name, null, null, null, data_block_buffer)
}
}
| 40.978261 | 103 | 0.71565 |
c61f441f9e1c6ea532282a6a086370be679e02cd | 909 | js | JavaScript | ee/app/assets/javascripts/security_dashboard/utils/first_class_project_manager_utils.js | mehulagg/gitlab-codesanbox | 31c455496be37cf6b248012627b9633cd4dd7493 | [
"MIT"
] | null | null | null | ee/app/assets/javascripts/security_dashboard/utils/first_class_project_manager_utils.js | mehulagg/gitlab-codesanbox | 31c455496be37cf6b248012627b9633cd4dd7493 | [
"MIT"
] | null | null | null | ee/app/assets/javascripts/security_dashboard/utils/first_class_project_manager_utils.js | mehulagg/gitlab-codesanbox | 31c455496be37cf6b248012627b9633cd4dd7493 | [
"MIT"
] | 1 | 2020-11-04T05:30:08.000Z | 2020-11-04T05:30:08.000Z | import { s__, sprintf } from '~/locale';
/**
* Creates the notification text to show the user regarding projects that failed to get added
* to the dashboard
*
* @param {Array} invalidProjects all the projects that failed to be added
* @returns {String} the invalid projects formated in a user-friendly way
*/
export const createInvalidProjectMessage = invalidProjects => {
const [firstProject, secondProject, ...rest] = invalidProjects.map(project => project.name);
const translationValues = {
firstProject,
secondProject,
rest: rest.join(', '),
};
if (rest.length > 0) {
return sprintf(
s__('SecurityReports|%{firstProject}, %{secondProject}, and %{rest}'),
translationValues,
);
} else if (secondProject) {
return sprintf(s__('SecurityReports|%{firstProject} and %{secondProject}'), translationValues);
}
return firstProject;
};
export default {};
| 30.3 | 99 | 0.69527 |
c61f7df49e24f4ce7744b1e044b0e9d71fd666ad | 6,099 | js | JavaScript | src/elements/content-sharing/__tests__/useInvites.test.js | The-Speck/box-ui-elements | 53dbdde6d6fa1bbd64292845a667d4721c40d1a1 | [
"Apache-2.0"
] | 673 | 2017-10-03T01:53:24.000Z | 2022-03-30T22:42:15.000Z | src/elements/content-sharing/__tests__/useInvites.test.js | The-Speck/box-ui-elements | 53dbdde6d6fa1bbd64292845a667d4721c40d1a1 | [
"Apache-2.0"
] | 2,087 | 2017-10-26T03:18:49.000Z | 2022-03-29T08:09:16.000Z | src/elements/content-sharing/__tests__/useInvites.test.js | The-Speck/box-ui-elements | 53dbdde6d6fa1bbd64292845a667d4721c40d1a1 | [
"Apache-2.0"
] | 282 | 2017-10-02T23:11:29.000Z | 2022-03-24T11:38:46.000Z | // @flow
import * as React from 'react';
import { act } from 'react-dom/test-utils';
import { mount } from 'enzyme';
import API from '../../../api';
import useInvites from '../hooks/useInvites';
import { TYPE_FOLDER } from '../../../constants';
import {
MOCK_COLLABS_API_RESPONSE,
MOCK_COLLABS_CONVERTED_REQUEST,
MOCK_COLLABS_REQUEST_USERS_AND_GROUPS,
MOCK_COLLABS_CONVERTED_GROUPS,
MOCK_COLLABS_CONVERTED_USERS,
MOCK_ITEM_ID,
} from '../../../features/unified-share-modal/utils/__mocks__/USMMocks';
const itemData = { id: MOCK_ITEM_ID, type: TYPE_FOLDER };
const successfulAPIResponse = MOCK_COLLABS_API_RESPONSE.entries[0];
const handleSuccess = jest.fn();
const handleError = jest.fn();
const transformRequestSpy = jest.fn().mockReturnValue(MOCK_COLLABS_CONVERTED_REQUEST);
const transformResponseSpy = jest.fn().mockReturnValue(successfulAPIResponse);
function FakeComponent({
api,
transformRequest,
transformResponse,
}: {
api: API,
transformRequest: Function,
transformResponse: Function,
}) {
const [sendInvites, setSendInvites] = React.useState<null | Function>(null);
const updatedSendInvitesFn = useInvites(api, MOCK_ITEM_ID, TYPE_FOLDER, {
handleSuccess,
handleError,
transformRequest,
transformResponse,
});
if (updatedSendInvitesFn && !sendInvites) {
setSendInvites(() => updatedSendInvitesFn);
}
return (
sendInvites && (
<button onClick={sendInvites} type="submit">
♫ Box UI Elements ♫
</button>
)
);
}
describe('elements/content-sharing/hooks/useInvites', () => {
let addCollaboration;
let mockAPI;
describe('with successful API calls', () => {
beforeAll(() => {
addCollaboration = jest.fn().mockImplementation((item, collab, addCollaborationSuccess) => {
addCollaborationSuccess(successfulAPIResponse);
});
mockAPI = {
getCollaborationsAPI: jest.fn().mockReturnValue({
addCollaboration,
}),
};
});
test('should set the value of sendInvites() and send invites on invocation', () => {
let fakeComponent;
act(() => {
fakeComponent = mount(
<FakeComponent
api={mockAPI}
transformRequest={transformRequestSpy}
transformResponse={transformResponseSpy}
/>,
);
});
fakeComponent.update();
fakeComponent.find('button').invoke('onClick')(MOCK_COLLABS_REQUEST_USERS_AND_GROUPS);
expect(transformRequestSpy).toHaveBeenCalledWith(MOCK_COLLABS_REQUEST_USERS_AND_GROUPS);
MOCK_COLLABS_CONVERTED_USERS.forEach(user => {
expect(addCollaboration).toHaveBeenCalledWith(
itemData,
user,
expect.anything(Function),
expect.anything(Function),
);
});
MOCK_COLLABS_CONVERTED_GROUPS.forEach(group => {
expect(addCollaboration).toHaveBeenCalledWith(
itemData,
group,
expect.anything(Function),
expect.anything(Function),
);
});
expect(handleSuccess).toHaveBeenCalledWith(successfulAPIResponse);
expect(transformResponseSpy).toHaveBeenCalledWith(successfulAPIResponse);
});
test('should return a null Promise if the transformation function is not provided', () => {
let fakeComponent;
act(() => {
fakeComponent = mount(<FakeComponent api={mockAPI} />);
});
fakeComponent.update();
const sendInvites = fakeComponent.find('button').invoke('onClick')(MOCK_COLLABS_REQUEST_USERS_AND_GROUPS);
expect(addCollaboration).not.toHaveBeenCalled();
return expect(sendInvites).resolves.toBeNull();
});
});
describe('with failed API calls', () => {
beforeAll(() => {
addCollaboration = jest
.fn()
.mockImplementation((item, collab, addCollaborationSuccess, addCollaborationError) => {
addCollaborationError();
});
mockAPI = {
getCollaborationsAPI: jest.fn().mockReturnValue({
addCollaboration,
}),
};
});
test('should set the value of getContacts() and call handleError() when invoked', () => {
let fakeComponent;
act(() => {
fakeComponent = mount(
<FakeComponent
api={mockAPI}
transformRequest={transformRequestSpy}
transformResponse={transformResponseSpy}
/>,
);
});
fakeComponent.update();
fakeComponent.find('button').invoke('onClick')(MOCK_COLLABS_REQUEST_USERS_AND_GROUPS);
expect(transformRequestSpy).toHaveBeenCalledWith(MOCK_COLLABS_REQUEST_USERS_AND_GROUPS);
MOCK_COLLABS_CONVERTED_USERS.forEach(user => {
expect(addCollaboration).toHaveBeenCalledWith(
itemData,
user,
expect.anything(Function),
expect.anything(Function),
);
});
MOCK_COLLABS_CONVERTED_GROUPS.forEach(group => {
expect(addCollaboration).toHaveBeenCalledWith(
itemData,
group,
expect.anything(Function),
expect.anything(Function),
);
});
expect(handleError).toHaveBeenCalled();
expect(transformResponseSpy).not.toHaveBeenCalled();
});
});
});
| 34.851429 | 118 | 0.560256 |
c61ff71b26c8af1cdafde427ccd22e3ee985bb40 | 2,678 | js | JavaScript | node_modules/@slack/web-api/dist/errors.js | micahbowie/hey-avi | 7aa6d3328384bec8e92c0d860468114dd7f7f122 | [
"MIT"
] | 3 | 2020-10-10T10:15:31.000Z | 2021-11-12T10:51:42.000Z | node_modules/@slack/web-api/dist/errors.js | micahbowie/hey-avi | 7aa6d3328384bec8e92c0d860468114dd7f7f122 | [
"MIT"
] | 19 | 2020-10-05T08:18:09.000Z | 2021-09-29T03:36:51.000Z | node_modules/@slack/web-api/dist/errors.js | micahbowie/hey-avi | 7aa6d3328384bec8e92c0d860468114dd7f7f122 | [
"MIT"
] | 1 | 2021-11-11T16:43:31.000Z | 2021-11-11T16:43:31.000Z | "use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.rateLimitedErrorWithDelay = exports.platformErrorFromResult = exports.httpErrorFromResponse = exports.requestErrorWithOriginal = exports.ErrorCode = void 0;
/**
* A dictionary of codes for errors produced by this package
*/
var ErrorCode;
(function (ErrorCode) {
ErrorCode["RequestError"] = "slack_webapi_request_error";
ErrorCode["HTTPError"] = "slack_webapi_http_error";
ErrorCode["PlatformError"] = "slack_webapi_platform_error";
ErrorCode["RateLimitedError"] = "slack_webapi_rate_limited_error";
})(ErrorCode = exports.ErrorCode || (exports.ErrorCode = {}));
/**
* Factory for producing a {@link CodedError} from a generic error
*/
function errorWithCode(error, code) {
// NOTE: might be able to return something more specific than a CodedError with conditional typing
const codedError = error;
codedError.code = code;
return codedError;
}
/**
* A factory to create WebAPIRequestError objects
* @param original - original error
*/
function requestErrorWithOriginal(original) {
const error = errorWithCode(new Error(`A request error occurred: ${original.message}`), ErrorCode.RequestError);
error.original = original;
return error;
}
exports.requestErrorWithOriginal = requestErrorWithOriginal;
/**
* A factory to create WebAPIHTTPError objects
* @param response - original error
*/
function httpErrorFromResponse(response) {
const error = errorWithCode(new Error(`An HTTP protocol error occurred: statusCode = ${response.status}`), ErrorCode.HTTPError);
error.statusCode = response.status;
error.statusMessage = response.statusText;
error.headers = response.headers;
error.body = response.data;
return error;
}
exports.httpErrorFromResponse = httpErrorFromResponse;
/**
* A factory to create WebAPIPlatformError objects
* @param result - Web API call result
*/
function platformErrorFromResult(result) {
const error = errorWithCode(new Error(`An API error occurred: ${result.error}`), ErrorCode.PlatformError);
error.data = result;
return error;
}
exports.platformErrorFromResult = platformErrorFromResult;
/**
* A factory to create WebAPIRateLimitedError objects
* @param retrySec - Number of seconds that the request can be retried in
*/
function rateLimitedErrorWithDelay(retrySec) {
const error = errorWithCode(new Error(`A rate-limit has been reached, you may retry this request in ${retrySec} seconds`), ErrorCode.RateLimitedError);
error.retryAfter = retrySec;
return error;
}
exports.rateLimitedErrorWithDelay = rateLimitedErrorWithDelay;
//# sourceMappingURL=errors.js.map | 40.575758 | 164 | 0.756161 |
c62076efd6b10de0a249f44f8b6b6ff5d1578a21 | 878 | js | JavaScript | SuiteCommerce Advanced/SC_21.1_Live/LocalDistributionAdvanced/javascript/compiled/Newsletter.js | Rudracool/MotherCareBackend- | 1e38dd4c839929b026b8565739fcc7879a9b79c3 | [
"MIT"
] | null | null | null | SuiteCommerce Advanced/SC_21.1_Live/LocalDistributionAdvanced/javascript/compiled/Newsletter.js | Rudracool/MotherCareBackend- | 1e38dd4c839929b026b8565739fcc7879a9b79c3 | [
"MIT"
] | null | null | null | SuiteCommerce Advanced/SC_21.1_Live/LocalDistributionAdvanced/javascript/compiled/Newsletter.js | Rudracool/MotherCareBackend- | 1e38dd4c839929b026b8565739fcc7879a9b79c3 | [
"MIT"
] | null | null | null | /*
© 2020 NetSuite Inc.
User may not copy, modify, distribute, or re-bundle or otherwise make available this code;
provided, however, if you are an authorized user with a NetSuite account or log-in, you
may use this code subject to the terms that govern your access and use.
*/
define("Newsletter", ["require", "exports", "Footer.View", "Newsletter.View"], function (require, exports, Footer_View_1, Newsletter_View_1) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
function mountToApp() {
// Set the Newsletter subscription form on the footer
Footer_View_1.FooterView.addChildViews({
FooterContent: function () {
return new Newsletter_View_1.NewsletterView();
}
});
}
exports.mountToApp = mountToApp;
});
//# sourceMappingURL=Newsletter.js.map
| 39.909091 | 142 | 0.671982 |
c6208a02ecf239adf5b984d329bcc732aae5c1e7 | 1,407 | js | JavaScript | start/server.js | tridungle/node-api-es6-boilerplate | 52adacc8292574270e95afc5c42bf3d246677746 | [
"MIT"
] | null | null | null | start/server.js | tridungle/node-api-es6-boilerplate | 52adacc8292574270e95afc5c42bf3d246677746 | [
"MIT"
] | 4 | 2021-03-08T09:12:13.000Z | 2021-03-08T09:47:53.000Z | start/server.js | tridungle/node-api-es6-boilerplate | 52adacc8292574270e95afc5c42bf3d246677746 | [
"MIT"
] | null | null | null | import express from 'express'
import Application from '@app/core/app'
import ErrorHandler from '@app/core/error-handler'
class Server {
constructor() {
this.server = express()
this.application = new Application(this.server)
}
async start() {
try {
await this.wire()
await this.listen()
} catch (error) {
console.error(error)
await new ErrorHandler(this.application).handleError(error)
}
return this
}
async wire() {
await this.application.setup()
await this.application.bootDatabase()
await this.application.bootRootDefaultRoutes()
await this.application.bootRootRoutes()
}
async listen() {
this.server.listen(this.application.config.port, this.monitorHttpServer)
return this
}
monitorHttpServer = (error) => {
if (error) {
this.application.logger.error(error)
return
}
const { environment, port, host, healthEndpoint } = this.application.config
this.application.logger.info('==================================')
this.application.logger.info(`Environment: ${environment}`)
this.application.logger.info(`Server listening on port ${port}`)
this.application.logger.info(`Health checks available at http://${host}:${port}${healthEndpoint}`)
if (process.send) {
process.send({ origin: 'api-server', ready: true, port, host })
}
}
}
export default new Server()
| 27.588235 | 102 | 0.658138 |
c620944333160d3067d0fbc3389ba71043c11367 | 18,382 | js | JavaScript | CONTENT/DS-n-Algos/Dynamic-Programming/dynamic-time-warping/tests/dtw.js | Web-Dev-Collaborative/DS-ALGO-OFFICIAL | 6d7195d33c28a0fe22f12231efffb39f4bf05c97 | [
"Apache-2.0"
] | 13 | 2021-03-11T00:25:22.000Z | 2022-03-19T00:19:23.000Z | CONTENT/DS-n-Algos/Dynamic-Programming/dynamic-time-warping/tests/dtw.js | Web-Dev-Collaborative/DS-ALGO-OFFICIAL | 6d7195d33c28a0fe22f12231efffb39f4bf05c97 | [
"Apache-2.0"
] | 162 | 2021-03-09T01:52:11.000Z | 2022-03-12T01:09:07.000Z | CONTENT/DS-n-Algos/Dynamic-Programming/dynamic-time-warping/tests/dtw.js | Web-Dev-Collaborative/DS-ALGO-OFFICIAL | 6d7195d33c28a0fe22f12231efffb39f4bf05c97 | [
"Apache-2.0"
] | 12 | 2021-04-26T19:43:01.000Z | 2022-01-31T08:36:29.000Z | const should = require("should");
const DTW = require("../lib/dtw.js");
describe("DTW", () => {
describe("#Constructor()", () => {
it("should not throw an error upon no value being passed for initialization", () => {
(() => {
const instanceFunctions = ["compute", "path"];
const dtw = new DTW();
instanceFunctions.forEach((fn) => {
const typeName = typeof dtw[fn];
typeName.should.equal(
"function",
"Expected function to be accessible: '" + fn + "'"
);
});
}).should.not.throw();
});
});
describe("#Constructor(value)", () => {
it("should throw an error upon an invalid value being passed for initialization", () => {
const invalidOptions = [null, "", {}, () => {}];
invalidOptions.forEach((options) => {
(() => {
const dtw = new DTW(options);
}).should.throw();
});
});
it("should throw an error upon an invalid distance metric value being passed for initialization", () => {
const invalidDistanceMetrics = [null, "", {}, "ea", undefined, () => {}];
invalidDistanceMetrics.forEach((distanceMetric) => {
(() => {
const dtw = new DTW({
distanceMetric: distanceMetric,
});
}).should.throw();
});
});
it("should throw an error upon an invalid distance function value being passed for initialization", () => {
const invalidDistanceFunctions = [null, "", {}, "ea", undefined];
invalidDistanceFunctions.forEach((distanceFunction) => {
(() => {
const dtw = new DTW({
distanceFunction: distanceFunction,
});
}).should.throw();
});
});
it("should throw an error upon an providing both distance metric and function value being passed for initialization", () => {
(() => {
const options = {
distanceMetric: "manhattan",
distanceFunction(x, y) {
return x + y;
},
};
const dtw = new DTW(options);
}).should.throw();
});
it("should not throw an error upon an providing a valid distance metric passed for initialization", () => {
const validDistanceMetric = [
"manhattan",
"manhattaN",
"euclidean",
"eucLidean",
"squaredeuclidean",
"squaredEuclidean",
];
validDistanceMetric.forEach((distanceMetric) => {
(() => {
const options = {
distanceMetric: distanceMetric,
};
const dtw = new DTW(options);
}).should.not.throw();
});
});
it("should not throw an error upon an providing a valid distance function passed for initialization", () => {
(() => {
const options = {
distanceFunction(x, y) {
return x + y;
},
};
const dtw = new DTW(options);
}).should.not.throw();
});
});
describe("#compute(value1, value2)", () => {
it("should throw if invalid type for first sequence", () => {
const invalidSequences = [null, {}, () => {}, [], "", 0];
invalidSequences.forEach((s) => {
(() => {
const options = {
distanceMetric: "squaredEuclidean",
};
const dtw = new DTW(options);
const t = [1, 1, 2, 2, 3, 3, 2, 4, 4, 4];
const cost = dtw.compute(s, t);
}).should.throw();
});
});
it("should throw if invalid type for second sequence", () => {
const invalidSequences = [null, {}, () => {}, [], "", 0];
invalidSequences.forEach((t) => {
(() => {
const options = {
distanceMetric: "squaredEuclidean",
};
const dtw = new DTW(options);
const s = [1, 1, 1, 2, 2, 2, 3, 3, 3, 2, 2, 4, 4, 4, 4];
const cost = dtw.compute(s, t);
}).should.throw();
});
});
it("should compute a valid similarity value for the squared euclidean distance metric", () => {
const options = {
distanceMetric: "squaredEuclidean",
};
const dtw = new DTW(options);
const s = [1, 1, 1, 2, 2, 2, 3, 3, 3, 2, 2, 4, 4, 4, 4];
const t = [1, 1, 2, 2, 3, 3, 2, 4, 4, 4];
const cost = dtw.compute(s, t);
cost.should.equal(0);
});
it("should compute a valid similarity value for the euclidean distance metric", () => {
const options = {
distanceMetric: "euclidean",
};
const dtw = new DTW(options);
const s = [1, 1, 1, 2, 2, 2, 3, 3, 3, 2, 2, 4, 4, 4, 4];
const t = [1, 1, 2, 2, 3, 3, 2, 4, 4, 4];
const cost = dtw.compute(s, t);
cost.should.equal(0);
});
it("should compute a valid similarity value for the manhattan distance metric", () => {
const options = {
distanceMetric: "manhattan",
};
const dtw = new DTW(options);
const s = [1, 1, 1, 2, 2, 2, 3, 3, 3, 2, 2, 4, 4, 4, 4];
const t = [1, 1, 2, 2, 3, 3, 2, 4, 4, 4];
const cost = dtw.compute(s, t);
cost.should.equal(0);
});
});
describe("#compute(value1, value2, value3)", () => {
it("should throw if invalid window type", () => {
const invalidWindowTypes = [null, {}, () => {}, [], "", [0]];
invalidWindowTypes.forEach((w) => {
(() => {
const options = {
distanceMetric: "squaredEuclidean",
};
const dtw = new DTW(options);
const s = [1, 1, 1, 2, 2, 2, 3, 3, 3, 2, 2, 4, 4, 4, 4];
const t = [1, 1, 2, 2, 3, 3, 2, 4, 4, 4];
const cost = dtw.compute(s, t, w);
}).should.throw();
});
});
it("should compute a valid similarity value for the squared euclidean distance metric", () => {
const options = {
distanceMetric: "squaredEuclidean",
};
const dtw = new DTW(options);
const s = [1, 1, 1, 2, 2, 2, 3, 3, 3, 2, 2, 4, 4, 4, 4];
const t = [1, 1, 2, 2, 3, 3, 2, 4, 4, 4];
const w = 5;
const cost = dtw.compute(s, t, w);
cost.should.equal(0);
});
it("should compute a valid similarity value for the euclidean distance metric", () => {
const options = {
distanceMetric: "euclidean",
};
const dtw = new DTW(options);
const s = [1, 1, 1, 2, 2, 2, 3, 3, 3, 2, 2, 4, 4, 4, 4];
const t = [1, 1, 2, 2, 3, 3, 2, 4, 4, 4];
const w = 5;
const cost = dtw.compute(s, t, w);
cost.should.equal(0);
});
it("should compute a valid similarity value for the manhattan distance metric", () => {
const options = {
distanceMetric: "manhattan",
};
const dtw = new DTW(options);
const s = [1, 1, 1, 2, 2, 2, 3, 3, 3, 2, 2, 4, 4, 4, 4];
const t = [1, 1, 2, 2, 3, 3, 2, 4, 4, 4];
const w = 5;
const cost = dtw.compute(s, t, w);
cost.should.equal(0);
});
});
describe("#path()", () => {
it("should compute a valid similarity value and path for the squared euclidean distance metric", () => {
const options = {
distanceMetric: "squaredEuclidean",
};
const dtw = new DTW(options);
const s = [1, 1, 1, 2, 2, 2, 3, 3, 3, 2, 2, 4, 4, 4, 4];
const t = [1, 1, 2, 2, 3, 3, 2, 4, 4, 4];
const cost = dtw.compute(s, t);
cost.should.equal(0);
const path = dtw.path();
const expectedPath = [
[0, 0],
[1, 0],
[2, 1],
[3, 2],
[4, 2],
[5, 3],
[6, 4],
[7, 4],
[8, 5],
[9, 6],
[10, 6],
[11, 7],
[12, 7],
[13, 8],
[14, 9],
];
path.should.eql(expectedPath);
});
it("should compute a valid similarity value and path for the euclidean distance metric", () => {
const options = {
distanceMetric: "euclidean",
};
const dtw = new DTW(options);
const s = [1, 1, 1, 2, 2, 2, 3, 3, 3, 2, 2, 4, 4, 4, 4];
const t = [1, 1, 2, 2, 3, 3, 2, 4, 4, 4];
const cost = dtw.compute(s, t);
cost.should.equal(0);
const path = dtw.path();
const expectedPath = [
[0, 0],
[1, 0],
[2, 1],
[3, 2],
[4, 2],
[5, 3],
[6, 4],
[7, 4],
[8, 5],
[9, 6],
[10, 6],
[11, 7],
[12, 7],
[13, 8],
[14, 9],
];
path.should.eql(expectedPath);
});
it("should compute a valid similarity value and path for the manhattan distance metric", () => {
const options = {
distanceMetric: "manhattan",
};
const dtw = new DTW(options);
const s = [1, 1, 1, 2, 2, 2, 3, 3, 3, 2, 2, 4, 4, 4, 4];
const t = [1, 1, 2, 2, 3, 3, 2, 4, 4, 4];
const cost = dtw.compute(s, t);
cost.should.equal(0);
const path = dtw.path();
const expectedPath = [
[0, 0],
[1, 0],
[2, 1],
[3, 2],
[4, 2],
[5, 3],
[6, 4],
[7, 4],
[8, 5],
[9, 6],
[10, 6],
[11, 7],
[12, 7],
[13, 8],
[14, 9],
];
path.should.eql(expectedPath);
});
it("should compute a valid similarity value and path for the squared euclidean distance metric with infinity locality constraint", () => {
const options = {
distanceMetric: "squaredEuclidean",
};
const dtw = new DTW(options);
const s = [1, 1, 1, 2, 2, 2, 3, 3, 3, 2, 2, 4, 4, 4, 4];
const t = [1, 1, 2, 2, 3, 3, 2, 4, 4, 4];
const w = Number.POSITIVE_INFINITY;
const cost = dtw.compute(s, t, w);
cost.should.equal(0);
const path = dtw.path();
const expectedPath = [
[0, 0],
[1, 0],
[2, 1],
[3, 2],
[4, 2],
[5, 3],
[6, 4],
[7, 4],
[8, 5],
[9, 6],
[10, 6],
[11, 7],
[12, 7],
[13, 8],
[14, 9],
];
path.should.eql(expectedPath);
});
it("should compute a valid similarity value and path for the euclidean distance metric with locality infinity constraint", () => {
const options = {
distanceMetric: "euclidean",
};
const dtw = new DTW(options);
const s = [1, 1, 1, 2, 2, 2, 3, 3, 3, 2, 2, 4, 4, 4, 4];
const t = [1, 1, 2, 2, 3, 3, 2, 4, 4, 4];
const w = Number.POSITIVE_INFINITY;
const cost = dtw.compute(s, t, w);
cost.should.equal(0);
const path = dtw.path();
const expectedPath = [
[0, 0],
[1, 0],
[2, 1],
[3, 2],
[4, 2],
[5, 3],
[6, 4],
[7, 4],
[8, 5],
[9, 6],
[10, 6],
[11, 7],
[12, 7],
[13, 8],
[14, 9],
];
path.should.eql(expectedPath);
});
it("should compute a valid similarity value and path for the manhattan distance metric with locality infinity constraint", () => {
const options = {
distanceMetric: "manhattan",
};
const dtw = new DTW(options);
const s = [1, 1, 1, 2, 2, 2, 3, 3, 3, 2, 2, 4, 4, 4, 4];
const t = [1, 1, 2, 2, 3, 3, 2, 4, 4, 4];
const w = Number.POSITIVE_INFINITY;
const cost = dtw.compute(s, t, w);
cost.should.equal(0);
const path = dtw.path();
const expectedPath = [
[0, 0],
[1, 0],
[2, 1],
[3, 2],
[4, 2],
[5, 3],
[6, 4],
[7, 4],
[8, 5],
[9, 6],
[10, 6],
[11, 7],
[12, 7],
[13, 8],
[14, 9],
];
path.should.eql(expectedPath);
});
it("should compute a valid similarity value and path for the squared euclidean distance metric with locality constraint", () => {
const options = {
distanceMetric: "squaredEuclidean",
};
const dtw = new DTW(options);
const s = [1, 1, 1, 2, 2, 2, 3, 3, 3, 2, 2, 4, 4, 4, 4];
const t = [1, 1, 2, 2, 3, 3, 2, 4, 4, 4];
const w = 5;
const cost = dtw.compute(s, t, w);
cost.should.equal(0);
const path = dtw.path();
const expectedPath = [
[0, 0],
[1, 0],
[2, 1],
[3, 2],
[4, 2],
[5, 3],
[6, 4],
[7, 4],
[8, 5],
[9, 6],
[10, 6],
[11, 7],
[12, 7],
[13, 8],
[14, 9],
];
path.should.eql(expectedPath);
});
it("should compute a valid similarity value and path for the euclidean distance metric with locality constraint", () => {
const options = {
distanceMetric: "euclidean",
};
const dtw = new DTW(options);
const s = [1, 1, 1, 2, 2, 2, 3, 3, 3, 2, 2, 4, 4, 4, 4];
const t = [1, 1, 2, 2, 3, 3, 2, 4, 4, 4];
const w = 5;
const cost = dtw.compute(s, t, w);
cost.should.equal(0);
const path = dtw.path();
const expectedPath = [
[0, 0],
[1, 0],
[2, 1],
[3, 2],
[4, 2],
[5, 3],
[6, 4],
[7, 4],
[8, 5],
[9, 6],
[10, 6],
[11, 7],
[12, 7],
[13, 8],
[14, 9],
];
path.should.eql(expectedPath);
});
it("should compute a valid similarity value and path for the manhattan distance metric with locality constraint", () => {
const options = {
distanceMetric: "manhattan",
};
const dtw = new DTW(options);
const s = [1, 1, 1, 2, 2, 2, 3, 3, 3, 2, 2, 4, 4, 4, 4];
const t = [1, 1, 2, 2, 3, 3, 2, 4, 4, 4];
const w = 5;
const cost = dtw.compute(s, t, w);
cost.should.equal(0);
const path = dtw.path();
const expectedPath = [
[0, 0],
[1, 0],
[2, 1],
[3, 2],
[4, 2],
[5, 3],
[6, 4],
[7, 4],
[8, 5],
[9, 6],
[10, 6],
[11, 7],
[12, 7],
[13, 8],
[14, 9],
];
path.should.eql(expectedPath);
});
});
describe("algorithm implementation", () => {
it("should compute valid cost and path 1 with no locality constraint", () => {
const s = [
0.13105, -0.1966, -0.81353, 1.49472, 0.42999, 0.22573, 0.91088, 0.19439,
0.87484, 0.28494, -1.72894, -0.60786, 1.17165, 0.62805, 0.52309,
1.76012,
];
const t = [
0.13105, -0.1966, -0.81353, 1.49472, 0.22573, 0.19439, 0.28494,
-0.60786, 1.17165, 0.62805, 0.52309, 1.76012, 1.76012, 1.76012, 1.76012,
1.76012,
];
const dtw = new DTW();
const cost = dtw.compute(s, t);
cost.should.be.approximately(2.05, 0.01);
const expectdPath = [
[0, 0],
[1, 1],
[2, 2],
[3, 3],
[4, 4],
[5, 5],
[6, 6],
[7, 6],
[8, 6],
[9, 6],
[10, 7],
[11, 7],
[12, 8],
[13, 9],
[14, 10],
[15, 11],
[15, 12],
[15, 13],
[15, 14],
[15, 15],
];
const path = dtw.path();
path.should.be.eql(expectdPath);
});
it("should compute valid cost and path 2 with no locality constraint", () => {
const s = [1, 1, 2, 3, 2, 0];
const t = [0, 1, 1, 2, 3, 2, 1];
const dtw = new DTW();
const cost = dtw.compute(s, t);
cost.should.be.approximately(2.0, 0.01);
const expectedPath = [
[0, 0],
[0, 1],
[1, 2],
[2, 3],
[3, 4],
[4, 5],
[5, 6],
];
const path = dtw.path();
path.should.be.eql(expectedPath);
});
it("should compute valid cost and path 3 with locality constraint", () => {
const s = [
0.4125044, 0.1827033, 0.7174426, 0.5938232, 0.4614635, 0.5900535,
0.8329995, 0.2489138, 0.020492, 0.9778591, 0.5764358, 0.4740868,
0.4325138, 0.3667226, 0.9619953, 0.457629, 0.2961572, 0.1273494,
0.1837332, 0.664666, 0.0533731, 0.7448532, 0.2209947, 0.1150104,
0.0697953, 0.226266, 0.6347957, 0.6412367, 0.0032259, 0.2817307,
0.95748, 0.5865984, 0.4622795, 0.7135204, 0.692983, 0.7052597,
0.9643922, 0.1590985, 0.8196736, 0.0813144, 0.5112076, 0.1490992,
0.6219234, 0.4254558, 0.1539139, 0.6556169, 0.5459852, 0.3675036,
0.6331521, 0.84436,
];
const t = [
0.954327, 0.371023, 0.305392, 0.917947, 0.100184, 0.636795, 0.301041,
0.726715, 0.850064, 0.362574, 0.634449, 0.241995, 0.470016, 0.187247,
0.080302, 0.164183, 0.337284, 0.721616, 0.228075, 0.049611, 0.401937,
0.599079, 0.36599, 0.883565, 0.444008, 0.87918, 0.165539, 0.220239,
0.318087, 0.356081, 0.769599, 0.301509, 0.247175, 0.20182, 0.243712,
0.531967, 0.68249, 0.028431, 0.627859, 0.350267, 0.751287, 0.658828,
0.115952, 0.449262, 0.697056, 0.479946, 0.017637, 0.7272, 0.153417,
0.467764, 0.315294, 0.165611,
];
const options = {
distanceMetric: "euclidean",
};
const dtw = new DTW(options);
const w = 5;
const cost = dtw.compute(s, t, w);
cost.should.be.approximately(10.38, 0.01);
const expectedPath = [
[0, 0],
[0, 1],
[0, 2],
[0, 3],
[0, 4],
[0, 5],
[0, 6],
[1, 7],
[2, 8],
[3, 9],
[4, 10],
[5, 11],
[6, 12],
[7, 13],
[8, 14],
[9, 15],
[10, 16],
[11, 17],
[12, 18],
[13, 19],
[14, 20],
[15, 21],
[16, 22],
[17, 23],
[18, 24],
[19, 25],
[20, 26],
[21, 27],
[22, 28],
[23, 29],
[24, 30],
[25, 31],
[26, 32],
[27, 33],
[28, 34],
[29, 34],
[30, 35],
[31, 35],
[32, 35],
[33, 36],
[34, 36],
[35, 36],
[36, 36],
[37, 37],
[38, 38],
[39, 39],
[40, 40],
[40, 41],
[41, 42],
[42, 43],
[42, 44],
[43, 45],
[44, 46],
[45, 47],
[46, 48],
[47, 49],
[48, 50],
[49, 51],
];
const path = dtw.path();
path.should.be.eql(expectedPath);
});
});
});
| 28.236559 | 142 | 0.453868 |
c620c17af068a091d75a56b7d54e8fe48d2891ac | 24,907 | js | JavaScript | tests/pre-compiled-app/classes/question/question-elem.js | imaginate/algorithmIV-question-manager | 63ec7b5be965d3bd96d0f878c5ef5c78db7ba53c | [
"Apache-2.0"
] | 42 | 2015-04-10T23:13:57.000Z | 2021-08-29T22:21:47.000Z | tests/pre-compiled-app/classes/question/question-elem.js | imaginate/algorithmIV | f06a6cb09f279afe3ef5783b74d7654950a07c6a | [
"Apache-2.0"
] | 2 | 2016-06-27T20:19:44.000Z | 2018-11-19T21:09:24.000Z | tests/pre-compiled-app/classes/question/question-elem.js | imaginate/algorithmIV | f06a6cb09f279afe3ef5783b74d7654950a07c6a | [
"Apache-2.0"
] | 17 | 2015-04-15T22:31:15.000Z | 2020-12-26T20:14:18.000Z | /**
* -----------------------------------------------------
* Public Class (QuestionElem)
* -----------------------------------------------------
* @desc An object containing the question's html element.
* @param {number} id - The id of the question.
* @constructor
*/
var QuestionElem = function(id) {
this.debug = aIV.debug('QuestionElem');
this.debug.start('init', id);
checkArgs(id, 'number');
////////////////////////////////////////////////////////////////////////////
// Define The Public Properties
////////////////////////////////////////////////////////////////////////////
/**
* -----------------------------------------------
* Public Property (QuestionElem.root)
* -----------------------------------------------
* @desc The question's root element.
* @type {!Element}
*/
this.root;
/**
* -----------------------------------------------
* Public Property (QuestionElem.info)
* -----------------------------------------------
* @desc The question's div.info element.
* @type {!Element}
*/
this.info;
/**
* -----------------------------------------------
* Public Property (QuestionElem.solution)
* -----------------------------------------------
* @desc The question's div.solution element.
* @type {!Element}
*/
this.solution;
/**
* -----------------------------------------------
* Public Property (QuestionElem.pre)
* -----------------------------------------------
* @desc The question's div.preContain element.
* @type {!Element}
*/
this.pre;
/**
* -----------------------------------------------
* Public Property (QuestionElem.code)
* -----------------------------------------------
* @desc The question's code element.
* @type {!Element}
*/
this.code;
////////////////////////////////////////////////////////////////////////////
// Setup The Public Properties
////////////////////////////////////////////////////////////////////////////
this.root = makeElem({
tag : 'section',
id : 'aIV-q' + id,
className: 'question'
});
this.info = makeElem({ className: 'info' });
this.root.appendChild(this.info);
////////////////////////////////////////////////////////////////////////////
// End Of The Class Setup
////////////////////////////////////////////////////////////////////////////
this.debug.end('init');
};
////////////////////////////////////////////////////////////////////////////////
// The Prototype Methods
////////////////////////////////////////////////////////////////////////////////
QuestionElem.prototype.constructor = QuestionElem;
/**
* -----------------------------------------------------
* Public Method (QuestionElem.prototype.addContent)
* -----------------------------------------------------
* @desc Adds the question's contents to its element.
* @param {!{
* id : string,
* url : string,
* complete: string,
* source : {
* id : string,
* name: string
* },
* mainCat : {
* ids : !strings,
* h3 : ?string,
* names: strings
* },
* subCat : {
* ids : !strings,
* h3 : ?string,
* names: strings
* },
* links : !links,
* problem : string,
* descr : string,
* solution: {
* prettyCode: string,
* lineCount : number
* },
* output : string
* }} question - The formatted question details.
*/
QuestionElem.prototype.addContent = function(question) {
var thisDebug = this.debug;
this.debug.group('addContent', 'coll', 'questionID= $$', question.id);
this.debug.start('addContent', question);
/** @type {!Element} */
var root;
/** @type {!Element} */
var info;
checkArgs(question, '!object');
root = this.root;
info = this.info;
// Append all the sections of the question
// Note: See the below private helper methods for more details
if (question.id) {
appendId(question.id, question.url);
}
if (question.source.name) {
appendSource(question.source);
}
if (question.complete) {
appendComplete(question.complete);
}
if (question.mainCat.h3 || question.subCat.h3) {
appendCategory(question.mainCat, question.subCat);
}
if (question.problem || question.descr) {
appendProblem(question.problem, question.descr);
}
if ( hasOwnProp(question.solution, 'prettyCode') ) {
appendSolution.call(this, question.solution);
}
if (question.output) {
appendOutput(question.output);
}
if (question.links.length) {
appendLinks(question.links);
}
this.debug.end('addContent');
this.debug.group('addContent', 'end');
/**
* ---------------------------------------------
* Private Method (appendId)
* ---------------------------------------------
* @desc Appends the question id.
* @param {string} id - The question id.
* @param {string} url - The question id url.
* @private
*/
function appendId(id, url) {
thisDebug.start('appendId', id, url);
/** @type {boolean} */
var config;
/** @type {!Element} */
var div;
/** @type {!Element} */
var h3;
/** @type {!Element} */
var p;
/** @type {!Element} */
var a;
checkArgs(id, 'string', url, 'string');
config = app.config.links.get('id');
div = makeElem({ className: 'idContain' });
h3 = makeElem({ tag: 'h3', text: 'Question:' });
p = makeElem('p');
if (!config) {
setElemText(p, id);
}
// Add the anchor link
if (config) {
a = makeIdLink(id, url);
p.appendChild(a);
}
info.appendChild(div);
div.appendChild(h3);
div.appendChild(p);
thisDebug.end('appendId');
}
/**
* ---------------------------------------------
* Private Method (makeIdLink)
* ---------------------------------------------
* @desc Creates an anchor element for the question id.
* @param {string} id - The question id.
* @param {string} url - The question id url.
* @return {!Element} The anchor element.
* @private
*/
function makeIdLink(id, url) {
thisDebug.start('makeIdLink', id, url);
/** @type {!Element} */
var a;
checkArgs(id, 'string', url, 'string');
if (!url) {
url = Number(id);
}
a = makeElem({ tag: 'a', text: id });
a.href = 'id/' + url;
a.onclick = (function(id) {
return function onclick(event) {
Events.linkId(id);
event.preventDefault && event.preventDefault();
return false;
};
})( Number(id) );
thisDebug.end('makeIdLink', a);
return a;
}
/**
* ---------------------------------------------
* Private Method (appendSource)
* ---------------------------------------------
* @desc Appends the question's source.
* @param {!stringMap} source - The id and name of the source.
* @private
*/
function appendSource(source) {
thisDebug.start('appendSource', source);
/** @type {boolean} */
var config;
/** @type {!Element} */
var div;
/** @type {!Element} */
var h3;
/** @type {!Element} */
var p;
/** @type {!Element} */
var a;
checkArgs(source, '!stringMap');
config = app.config.links.get('source');
div = makeElem({ className: 'source' });
h3 = makeElem({ tag: 'h3', text: 'Source:' });
p = makeElem('p');
if (!config) {
setElemText(p, source.name);
}
info.appendChild(div);
div.appendChild(h3);
div.appendChild(p);
// Add the anchor link
if (config) {
a = makeSourceLink(source.id, source.name);
p.appendChild(a);
}
thisDebug.end('appendSource');
}
/**
* ---------------------------------------------
* Private Method (makeSourceLink)
* ---------------------------------------------
* @desc Creates an anchor element for the question's source.
* @param {string} id - The source's id.
* @param {string} name - The source's name.
* @return {!Element} The anchor element.
* @private
*/
function makeSourceLink(id, name) {
thisDebug.start('makeSourceLink', id, name);
/** @type {string} */
var url;
/** @type {!Element} */
var a;
checkArgs(id, 'string', name, 'string');
url = app.sources.get(id, 'url');
a = makeElem({ tag: 'a', text: name, className: 'dark' });
a.href = 'source/' + url;
a.onclick = (function(id) {
return function onclick(event) {
Events.linkSource(id);
event.preventDefault && event.preventDefault();
return false;
};
})(id);
thisDebug.end('makeSourceLink', a);
return a;
}
/**
* ---------------------------------------------
* Private Method (appendComplete)
* ---------------------------------------------
* @desc Appends the question's completion status.
* @param {string} complete - The question's status.
* @private
*/
function appendComplete(complete) {
thisDebug.start('appendComplete', complete);
/** @type {!Element} */
var div;
/** @type {!Element} */
var h3;
/** @type {!Element} */
var p;
checkArgs(complete, 'string');
div = makeElem({ className: 'stage' });
h3 = makeElem({ tag: 'h3', text: 'Completed:' });
p = makeElem({ tag: 'p' , text: complete });
info.appendChild(div);
div.appendChild(h3);
div.appendChild(p);
thisDebug.end('appendComplete');
}
/**
* ---------------------------------------------
* Private Method (appendCategory)
* ---------------------------------------------
* @desc Appends the question's categories.
* @param {!Object} main - The question's main categories.
* @param {!Object} sub - The question's sub categories.
* @private
*/
function appendCategory(main, sub) {
thisDebug.start('appendCategory', main, sub);
/** @type {!Element} */
var contain;
/** @type {!Element} */
var mainDiv;
/** @type {!Element} */
var subDiv;
checkArgs(main, '!object', sub, '!object');
contain = makeElem({ className: 'category' });
// Add the main categories
if (main.h3) {
mainDiv = makeElem({ className: 'mainCategory' });
appendMainCategories(main, mainDiv);
contain.appendChild(mainDiv);
}
// Add the sub categories
if (sub.h3) {
subDiv = makeElem({ className: 'subCategory' });
appendSubCategories(sub, subDiv);
contain.appendChild(subDiv);
}
root.appendChild(contain);
thisDebug.end('appendCategory');
}
/**
* ---------------------------------------------
* Private Method (appendMainCategories)
* ---------------------------------------------
* @desc Appends the question's main categories.
* @param {!Object} main - The question's main categories.
* @param {!Element} div - The DOM container for the main categories.
* @private
*/
function appendMainCategories(main, div) {
thisDebug.start('appendMainCategories', main, div);
/** @type {boolean} */
var config;
/** @type {!Element} */
var h3;
/** @type {!Element} */
var p;
/** @type {number} */
var i;
/** @type {number} */
var len;
/** @type {number} */
var last;
/** @type {!Element} */
var a;
checkArgs(main, '!object', div, '!element');
config = app.config.links.get('category');
h3 = makeElem({ tag: 'h3', text: main.h3 });
p = makeElem('p');
if (!config) {
setElemText(p, main.names.join(', '));
}
div.appendChild(h3);
div.appendChild(p);
// Add each main category's anchor tag
if (config) {
len = main.ids.length;
last = len - 1;
i = -1;
while (++i < len) {
a = makeMainCatLink(main.ids[i], main.names[i]);
p.appendChild(a);
if (i !== last) {
p.appendChild( makeElem({ tag: 'span', html: ', ' }) );
}
}
}
thisDebug.end('appendMainCategories');
}
/**
* ---------------------------------------------
* Private Method (appendSubCategories)
* ---------------------------------------------
* @desc Appends the question's sub categories.
* @param {!Object} sub - The question's sub categories.
* @param {!Element} div - The DOM container for the sub categories.
* @private
*/
function appendSubCategories(sub, div) {
thisDebug.start('appendSubCategories', sub, div);
/** @type {boolean} */
var config;
/** @type {!Element} */
var h3;
/** @type {!Element} */
var p;
/** @type {number} */
var i;
/** @type {number} */
var len;
/** @type {number} */
var last;
/** @type {!Element} */
var a;
checkArgs(sub, '!object', div, '!element');
config = app.config.links.get('category');
h3 = makeElem({ tag: 'h3', text: sub.h3 });
p = makeElem('p');
if (!config) {
setElemText(p, sub.names.join(', '));
}
div.appendChild(h3);
div.appendChild(p);
// Add each sub category's anchor tag
if (config) {
len = sub.ids.length;
last = len - 1;
i = -1;
while (++i < len) {
a = makeSubCatLink(sub.ids[i], sub.names[i]);
p.appendChild(a);
if (i !== last) {
p.appendChild( makeElem({ tag: 'span', html: ', ' }) );
}
}
}
thisDebug.end('appendSubCategories');
}
/**
* ---------------------------------------------
* Private Method (makeMainCatLink)
* ---------------------------------------------
* @desc Creates a main category link.
* @param {string} id - The main category's id.
* @param {string} name - The main category's name.
* @return {!Element} The anchor link.
* @private
*/
function makeMainCatLink(id, name) {
thisDebug.start('makeMainCatLink', id, name);
/** @type {string} */
var url;
/** @type {!Element} */
var a;
checkArgs(id, 'string', name, 'string');
url = app.categories.get(id, 'url');
a = makeElem({ tag: 'a', text: name, className: 'dark' });
a.href = 'category/' + url;
a.onclick = (function(id) {
return function onclick(event) {
Events.linkMainCat(id);
event.preventDefault && event.preventDefault();
return false;
};
})(id);
thisDebug.end('makeMainCatLink', a);
return a;
}
/**
* ---------------------------------------------
* Private Method (makeSubCatLink)
* ---------------------------------------------
* @desc Creates a sub category link.
* @todo Remove the use of indexOf to find the sub category's parent.
* @param {string} subId - The sub category's id.
* @param {string} name - The sub category's name.
* @return {!Element} The anchor link.
* @private
*/
function makeSubCatLink(subId, name) {
thisDebug.start('makeSubCatLink', subId, name);
/** @type {string} */
var parentUrl;
/** @type {string} */
var parentId;
/** @type {!Category} */
var category;
/** @type {!strings} */
var subIds;
/** @type {string} */
var mainId;
/** @type {string} */
var url;
/** @type {!Element} */
var a;
/** @type {number} */
var i;
checkArgs(subId, 'string', name, 'string');
// Set the sub category's parent id and url
i = app.categories.ids.length;
while (i--) {
mainId = app.categories.ids[i];
category = app.categories.get(mainId);
subIds = category.get('subs');
if (subIds.indexOf(subId) !== -1) {
parentId = mainId;
parentUrl = category.get('url');
break;
}
}
url = app.categories.get(subId, 'url');
a = makeElem({ tag: 'a', text: name, className: 'dark' });
a.href = 'category/' + parentUrl + '/' + url;
a.onclick = (function(subId, parentId) {
return function onclick(event) {
Events.linkSubCat(subId, parentId);
event.preventDefault && event.preventDefault();
return false;
};
})(subId, parentId);
thisDebug.end('makeSubCatLink', a);
return a;
}
/**
* ---------------------------------------------
* Private Method (appendProblem)
* ---------------------------------------------
* @desc Appends the question's problem or description.
* @param {string} problem - The question's problem.
* @param {string} descr - The question's description.
* @private
*/
function appendProblem(problem, descr) {
thisDebug.start('appendProblem', problem, descr);
/** @type {string} */
var content;
/** @type {string} */
var title;
/** @type {!Element} */
var div;
/** @type {!Element} */
var h3;
/** @type {!Element} */
var p;
checkArgs(problem, 'string', descr, 'string');
title = (problem) ? 'Problem:' : 'Description:';
content = problem || descr;
div = makeElem({ className: 'problem' });
h3 = makeElem({ tag: 'h3', text: title });
p = makeElem({ tag: 'p' , html: content });
div.appendChild(h3);
div.appendChild(p);
root.appendChild(div);
thisDebug.end('appendProblem');
}
/**
* ---------------------------------------------
* Private Method (appendSolution)
* ---------------------------------------------
* @desc Appends the question's solution.
* @this {!QuestionElem}
* @param {!Object} solution - The question's solution.
* @private
*/
function appendSolution(solution) {
thisDebug.start('appendSolution', solution);
/** @type {!Element} */
var contain;
/** @type {!Element} */
var h3;
/** @type {!Element} */
var preDiv;
/** @type {!Element} */
var pre;
/** @type {!Element} */
var code;
/** @type {!Element} */
var ol;
/** @type {number} */
var height;
checkArgs(solution, '!object');
contain = makeElem({ className: 'solution' });
h3 = makeElem({ tag: 'h3', text: 'Solution:' });
preDiv = makeElem({ className: 'preContain' });
pre = makeElem('pre');
code = makeElem('code');
ol = makeElem({ tag: 'ol', html: solution.prettyCode });
height = solution.lineCount * app.elems.code.li.height;
height += app.elems.code.ol.height;
preDiv.style.height = height + 'px';
contain.appendChild(h3);
contain.appendChild(preDiv);
preDiv.appendChild(pre);
pre.appendChild(code);
code.appendChild(ol);
root.appendChild(contain);
this.solution = contain;
this.pre = preDiv;
this.code = code;
thisDebug.end('appendSolution');
}
/**
* ---------------------------------------------
* Private Method (appendOutput)
* ---------------------------------------------
* @desc Appends the solution's output for this question.
* @param {string} output - The solution's output.
* @private
*/
function appendOutput(output) {
thisDebug.start('appendOutput', output);
/** @type {!Element} */
var div;
/** @type {!Element} */
var h3;
/** @type {!Element} */
var p;
checkArgs(output, 'string');
div = makeElem({ className: 'output' });
h3 = makeElem({ tag: 'h3', text: 'Output:' });
p = makeElem({ tag: 'p' , html: output });
div.appendChild(h3);
div.appendChild(p);
root.appendChild(div);
thisDebug.end('appendOutput');
}
/**
* ---------------------------------------------
* Private Method (appendLinks)
* ---------------------------------------------
* @desc Appends the question's links.
* @param {!links} links - The question's links.
* @private
*/
function appendLinks(links) {
thisDebug.start('appendLinks', links);
/** @type {!Object} */
var linkObj;
/** @type {number} */
var len;
/** @type {!Element} */
var div;
/** @type {!Element} */
var h3;
/** @type {!Element} */
var p;
/** @type {!Element} */
var a;
/** @type {number} */
var i;
checkArgs(links, '!objects');
div = makeElem({ className: 'links' });
h3 = makeElem({ tag: 'h3', text: 'Links:' });
p = makeElem('p');
div.appendChild(h3);
div.appendChild(p);
// Append the links
len = links.length;
i = -1;
while (++i < len) {
linkObj = links[i];
a = makeElem({ tag: 'a', text: linkObj.name });
a.href = linkObj.href;
a.target = '_blank';
p.appendChild(a);
}
root.appendChild(div);
thisDebug.end('appendLinks');
}
};
/**
* -----------------------------------------------------
* Public Method (QuestionElem.prototype.addCodeExt)
* -----------------------------------------------------
* @desc If overflow occurs in a code element it enables the auto
* extend button for the question.
* @type {function}
*/
QuestionElem.prototype.addCodeExt = function() {
this.debug.start('addCodeExt');
/** @type {number} */
var overflow;
/** @type {number} */
var scrollbar;
/** @type {!Element} */
var code;
/** @type {!Element} */
var ext;
/** @type {!Element} */
var extClose;
/** @type {!Element} */
var extOpen;
/** @type {!Element} */
var extBG;
/** @type {!Element} */
var extHov;
/** @type {!Element} */
var extHovC;
/** @type {!Element} */
var extHovO;
code = this.code;
overflow = code.scrollWidth - code.clientWidth;
debugMsg = 'this.code= $$, scrollWidth= $$, clientWidth= $$, overflow= $$';
debugArgs = [ 'addCodeExt', debugMsg, code, code.scrollWidth ];
debugArgs.push(code.clientWidth, overflow);
this.debug.state(debugArgs);
if (overflow < 1) {
this.root.style.display = 'none';
this.root.style.opacity = '1';
this.debug.end('addCodeExt');
return;
}
scrollbar = app.elems.scrl.height;
this.debug.state('addCodeExt', 'scrollbar= $$', scrollbar);
if (scrollbar > 0) {
this.solution.style.paddingBottom = scrollbar + 'px';
}
ext = makeElem({ className: 'extContain' });
extClose = makeElem({ className: 'extCloseArrow' });
extOpen = makeElem({ className: 'extOpenArrow', text: 'open' });
extBG = makeElem({ className: 'extBG' });
extHov = makeElem({ className: 'extHover' });
extHovC = makeElem({
tag : 'span',
className: 'closeExt',
text : 'Close Extended Code View'
});
extHovO = makeElem({
tag : 'span',
className: 'openExt',
text : 'Extend Code View'
});
extOpen.onmouseover = function() {
extHov.style.opacity = '1';
};
extOpen.onmouseout = function() {
extHov.style.opacity = '0';
};
extOpen.onclick = (function(overflow, code, ext, extOpen,
extClose, extHovO, extHovC) {
/** @type {!elementMap} */
var elems;
elems = {
code : code,
ext : ext,
extOpen : extOpen,
extClose: extClose,
extHovO : extHovO,
extHovC : extHovC
};
freezeObj(elems);
return function() {
Events.extCodeView(overflow, elems);
};
})(overflow, code, ext, extOpen, extClose, extHovO, extHovC);
ext.appendChild(extClose);
ext.appendChild(extOpen);
ext.appendChild(extBG);
extHov.appendChild(extHovC);
extHov.appendChild(extHovO);
this.pre.appendChild(ext);
this.pre.appendChild(extHov);
this.root.style.display = 'none';
this.root.style.opacity = '1';
this.debug.end('addCodeExt');
};
| 26.356614 | 80 | 0.470711 |
c620c5ad8cda21656732976ed4d83c8b946912d2 | 2,995 | js | JavaScript | Demo/router/router.js | jumodada/vueXin | 12ad40a006da292725c3ab3690c0427eedbd0e6b | [
"MIT"
] | 132 | 2019-03-14T10:48:15.000Z | 2019-10-23T08:33:12.000Z | Demo/router/router.js | jumodada/vueXin | 12ad40a006da292725c3ab3690c0427eedbd0e6b | [
"MIT"
] | null | null | null | Demo/router/router.js | jumodada/vueXin | 12ad40a006da292725c3ab3690c0427eedbd0e6b | [
"MIT"
] | 13 | 2019-03-22T16:02:15.000Z | 2019-09-10T02:39:54.000Z | import Main from '../components/main/main.vue'
import Content from '../components/content'
export default [
{
path: '/',
name: 'home',
component: Main,
meta: {
notCache: true
},
children: []
},
{
path: '/components',
name: 'components',
component: Content,
redirect:'/components/Button',
children: [
{
path: '/components/Button',
name: 'Button',
meta: {
name: '按钮',
type: 'component'
},
component: (resolve) => require(['../view/components/Button/index.md'], resolve)
},
{
path: '/components/Input',
name: 'Input',
meta: {
name: '输入框',
type: 'component'
},
component: (resolve) => require(['../view/components/Input/index.md'], resolve)
},
{
path: '/components/Tabs',
name: 'Tabs',
meta: {
name: '标签页',
type: 'component'
},
component: (resolve) => require(['../view/components/tabs/index.md'], resolve)
},
{
path: '/components/Popover',
name: 'Popover',
meta: {
name: '气泡',
type: 'component'
},
component: (resolve) => require(['../view/components/Popover/index.md'], resolve)
},
{
path: '/components/Table',
name: 'Table',
meta: {
name: '表格',
type: 'component'
},
component: (resolve) => require(['../view/components/Table/index.md'], resolve)
},
{
path: '/components/Upload',
name: 'Upload',
meta: {
name: '上传组件',
type: 'component'
},
component: (resolve) => require(['../view/components/Upload/index.md'], resolve)
},
{
path: '/components/Progress',
name: 'Progress',
meta: {
name: '进度条',
type: 'component'
},
component: (resolve) => require(['../view/components/Progress/index.md'], resolve)
}
]
},
{
path: '/500',
name: 'error_500',
meta: {
hideInMenu: true
},
component: () => import('../view/error-page/500.vue')
},
{
path: '*',
name: 'error_404',
meta: {
hideInMenu: true
},
component: () => import('../view/error-page/404.vue')
}
]
| 29.07767 | 98 | 0.373957 |
c620fb381457d89b88ade53cb70d13d73c1f1cec | 1,700 | js | JavaScript | client/store/breakfast.spec.js | Fruit-for-Loops/BreakFaster | 3ad889a8f281bb96afaa3c63a8f2c3c10befe08a | [
"MIT"
] | null | null | null | client/store/breakfast.spec.js | Fruit-for-Loops/BreakFaster | 3ad889a8f281bb96afaa3c63a8f2c3c10befe08a | [
"MIT"
] | 22 | 2019-11-04T17:29:55.000Z | 2019-11-11T20:29:28.000Z | client/store/breakfast.spec.js | Fruit-for-Loops/BreakFaster | 3ad889a8f281bb96afaa3c63a8f2c3c10befe08a | [
"MIT"
] | 1 | 2020-01-01T19:54:11.000Z | 2020-01-01T19:54:11.000Z | /* global describe beforeEach afterEach it */
import {expect} from 'chai'
import {getAllBreakfasts, getSingleBreakfast} from './breakfast'
import axios from 'axios'
import MockAdapter from 'axios-mock-adapter'
import configureMockStore from 'redux-mock-store'
import thunkMiddleware from 'redux-thunk'
import history from '../history'
const middlewares = [thunkMiddleware]
const mockStore = configureMockStore(middlewares)
describe('thunk creators', () => {
let store
let mockAxios
const initialState = {
allBreakfasts: [],
singleBreakfast: {}
}
beforeEach(() => {
mockAxios = new MockAdapter(axios)
store = mockStore(initialState)
})
afterEach(() => {
mockAxios.restore()
store.clearActions()
})
describe('getAllBreakfasts', () => {
it('eventually dispatches the GOT ALL BREAKFASTS action', async () => {
const fakeBreakfast = {name: 'Cheerios'}
mockAxios.onGet('/api/breakfasts').replyOnce(200, fakeBreakfast)
await store.dispatch(getAllBreakfasts())
const actions = store.getActions()
expect(actions[0].type).to.be.equal('GOT_ALL_BREAKFASTS_SUCCESSFULLY')
expect(actions[0].breakfasts).to.be.deep.equal(fakeBreakfast)
})
})
describe('getSingleBreakfast', () => {
it('eventually dispatches the GOT SINGLE BREAKFAST action', async () => {
const fakeBreakfast = {name: 'Cheerios'}
mockAxios.onGet('/api/breakfast/1').replyOnce(200, fakeBreakfast)
await store.dispatch(getSingleBreakfast(1))
const actions = store.getActions()
expect(actions[0].type).to.be.equal('GOT_SINGLE_BREAKFAST')
expect(actions[0].breakfast).to.be.deep.equal(fakeBreakfast)
})
})
})
| 30.909091 | 77 | 0.694706 |
c621e805c4b9bc08b268fab8f3aee2d63cc25131 | 353 | js | JavaScript | resources/static/admin/assets/SalesProductPie.41f142f5.js | Vfuryx/fagin | 2a0a5c4f2611a018a574a0e96db0d94498999a92 | [
"MIT"
] | 5 | 2019-07-23T01:24:47.000Z | 2021-06-20T15:49:09.000Z | resources/static/admin/assets/SalesProductPie.41f142f5.js | Vfuryx/fagin | 2a0a5c4f2611a018a574a0e96db0d94498999a92 | [
"MIT"
] | 9 | 2021-09-21T09:46:10.000Z | 2022-02-19T04:07:53.000Z | resources/static/admin/assets/SalesProductPie.41f142f5.js | Vfuryx/fagin | 2a0a5c4f2611a018a574a0e96db0d94498999a92 | [
"MIT"
] | null | null | null | import{_ as e}from"./SalesProductPie.vue_vue&type=script&setup=true&lang.c058e334.js";export{_ as default}from"./SalesProductPie.vue_vue&type=script&setup=true&lang.c058e334.js";import"./vendor.5da97255.js";/* empty css *//* empty css *//* empty css */import"./useECharts.f11c1965.js";import"./index.ab59a04a.js";
| 176.5 | 352 | 0.671388 |
c622127edeba6fe736ed442e5f64a27139c15f0f | 2,933 | js | JavaScript | build/precache-manifest.5d9f6790deccb229b531847ed5bba80d.js | jram97/spazer-web-root | ba637f0a108e2e0b16c2091d3618d073edccc9a6 | [
"MIT"
] | null | null | null | build/precache-manifest.5d9f6790deccb229b531847ed5bba80d.js | jram97/spazer-web-root | ba637f0a108e2e0b16c2091d3618d073edccc9a6 | [
"MIT"
] | null | null | null | build/precache-manifest.5d9f6790deccb229b531847ed5bba80d.js | jram97/spazer-web-root | ba637f0a108e2e0b16c2091d3618d073edccc9a6 | [
"MIT"
] | null | null | null | self.__precacheManifest = (self.__precacheManifest || []).concat([
{
"revision": "9b0777189a5c7471209bd5708c0c6eb0",
"url": "/index.html"
},
{
"revision": "bc098764e9d16e2a264c",
"url": "/static/css/2.e83c4000.chunk.css"
},
{
"revision": "0538d6a25c372de0ee14",
"url": "/static/css/main.67832bb2.chunk.css"
},
{
"revision": "bc098764e9d16e2a264c",
"url": "/static/js/2.a53c1414.chunk.js"
},
{
"revision": "04e29d502fff485d4151be0beb9ac8b2",
"url": "/static/js/2.a53c1414.chunk.js.LICENSE.txt"
},
{
"revision": "0538d6a25c372de0ee14",
"url": "/static/js/main.4497c6c4.chunk.js"
},
{
"revision": "02abd13eaf1d7c33000d",
"url": "/static/js/runtime-main.6a771f16.js"
},
{
"revision": "6baed2bf580964bec9559ad83caee43d",
"url": "/static/media/CircularStd-Bold.6baed2bf.otf"
},
{
"revision": "22cd7ef0e8de8a6780795f8f5f3ea366",
"url": "/static/media/background_image.22cd7ef0.png"
},
{
"revision": "ee48946b0c3ee39e89eb741cbbdca580",
"url": "/static/media/cheering-crowd-event-17598@2x.ee48946b.png"
},
{
"revision": "89d6373df9a7eaa0257f8234e756915e",
"url": "/static/media/group_10.89d6373d.svg"
},
{
"revision": "8910c99f573974fceb10f3ad865036c1",
"url": "/static/media/group_12.8910c99f.svg"
},
{
"revision": "6a54912f2af8a6e72a4a6efeec4051b8",
"url": "/static/media/group_9.6a54912f.svg"
},
{
"revision": "70f5db09bf87bf6f872cf15635545efb",
"url": "/static/media/hand_icon.70f5db09.svg"
},
{
"revision": "659d3acadd628ec582e24fa3ef973e70",
"url": "/static/media/image_1.659d3aca.png"
},
{
"revision": "0306dfae512b7b7584874cf63b31f2a7",
"url": "/static/media/image_2.0306dfae.png"
},
{
"revision": "fba4bba8818ce5c2bd60ea7b663ce148",
"url": "/static/media/image_3.fba4bba8.png"
},
{
"revision": "bbd6ed3dc44067459227b3ea09f3595c",
"url": "/static/media/jogo_recovery_background.bbd6ed3d.png"
},
{
"revision": "0a2190e7df89994f7ead77008ff053bc",
"url": "/static/media/jogo_revovery_text.0a2190e7.png"
},
{
"revision": "c518f60840d096dc6214d9dbfbf1e8f8",
"url": "/static/media/landing_first_bg.c518f608.png"
},
{
"revision": "a9b830b1a5c4abd0a531493dc4e080ba",
"url": "/static/media/phone_image.a9b830b1.png"
},
{
"revision": "15b50823ad6924b5735d28c6d75cae29",
"url": "/static/media/spazer_phone_one.15b50823.png"
},
{
"revision": "e767b30e43e0d65dc0998d7cae6ebc97",
"url": "/static/media/stuck_two.e767b30e.svg"
},
{
"revision": "e52dd5f68cd816b83200db8b5ff41bd8",
"url": "/static/media/time_icon.e52dd5f6.svg"
},
{
"revision": "5942b31ff4cb8a6dd4f282a133ed93b6",
"url": "/static/media/vector_line_left.5942b31f.svg"
},
{
"revision": "a158ecd906df685fb82ad687987938d5",
"url": "/static/media/world_icon.a158ecd9.svg"
}
]); | 27.669811 | 69 | 0.662121 |
c622443b3b5edb5599bd877442c9647e9c526abb | 998 | js | JavaScript | app/controllers/payment/transferController.js | cheeta24/AngularApp | 28612f4042d786fc88e53a3e59eeef88c0e86fe7 | [
"MIT"
] | null | null | null | app/controllers/payment/transferController.js | cheeta24/AngularApp | 28612f4042d786fc88e53a3e59eeef88c0e86fe7 | [
"MIT"
] | null | null | null | app/controllers/payment/transferController.js | cheeta24/AngularApp | 28612f4042d786fc88e53a3e59eeef88c0e86fe7 | [
"MIT"
] | null | null | null | 'use strict';
transferApp.controller('TransferController',
function($scope, $http, jsonService){
$scope.myCollections = {};
jsonService.getJson( function(data){
$scope.fromnames = data;
$scope.tonames = data;
});
$scope.fromnames = $scope.myCollections;
$scope.tonames = $scope.fromnames;
$scope.onTransfer = function () {
$scope.Message = "Amount Transferred SuccessFully."
}
$scope.onCancel = function () {
$scope.selectedFromName ="";
$scope.selectedToName = "";
$scope.amount = "";
$scope.remark="";
$scope.myVar="";
$scope.Message = "Transaction Cancelled."
}
});
| 29.352941 | 71 | 0.405812 |
c62280fbc060dad96753a43e7f84e6286b30a7d9 | 542 | js | JavaScript | algorithms/141.Linked List Cycle/Linked List Cycle.js | MrErHu/leetcode_answer | bbe5396e1cb532190d4d560542b0ae886468bdc8 | [
"RSA-MD"
] | 14 | 2017-06-29T08:25:49.000Z | 2022-02-04T06:19:06.000Z | algorithms/141.Linked List Cycle/Linked List Cycle.js | MrErHu/Leetcode_answer | bbe5396e1cb532190d4d560542b0ae886468bdc8 | [
"RSA-MD"
] | null | null | null | algorithms/141.Linked List Cycle/Linked List Cycle.js | MrErHu/Leetcode_answer | bbe5396e1cb532190d4d560542b0ae886468bdc8 | [
"RSA-MD"
] | 11 | 2017-02-10T06:11:27.000Z | 2021-04-16T18:00:21.000Z | /**
* Definition for singly-linked list.
* function ListNode(val) {
* this.val = val;
* this.next = null;
* }
*/
/**
* @param {ListNode} head
* @return {boolean}
*/
var hasCycle = function(head) {
if(!head || !head.next){
return false;
}
var front = head.next ? head.next.next : head.next;
var end = head.next;
while(front){
front = front.next ? front.next.next : front.next;
end = end.next;
if(front == end){
return true;
}
}
return false;
}; | 20.074074 | 58 | 0.52583 |
c6228882c18e88edbfdb343b843d4b0b55a99a3c | 5,460 | js | JavaScript | skipole/skis/static/js/dropdown.js | bernie-skipole/skipole | b45d3291c593e7c03c053ab4f192f1ecc5c3e9b9 | [
"MIT"
] | null | null | null | skipole/skis/static/js/dropdown.js | bernie-skipole/skipole | b45d3291c593e7c03c053ab4f192f1ecc5c3e9b9 | [
"MIT"
] | null | null | null | skipole/skis/static/js/dropdown.js | bernie-skipole/skipole | b45d3291c593e7c03c053ab4f192f1ecc5c3e9b9 | [
"MIT"
] | null | null | null |
SKIPOLE.dropdown = {};
SKIPOLE.dropdown.DropDown1 = function (widg_id, error_message, fieldmap) {
SKIPOLE.BaseWidget.call(this, widg_id, error_message, fieldmap);
};
SKIPOLE.dropdown.DropDown1.prototype = Object.create(SKIPOLE.BaseWidget.prototype);
SKIPOLE.dropdown.DropDown1.prototype.constructor = SKIPOLE.dropdown.DropDown1;
SKIPOLE.dropdown.SubmitDropDown1 = function (widg_id, error_message, fieldmap) {
SKIPOLE.BaseWidget.call(this, widg_id, error_message, fieldmap);
};
SKIPOLE.dropdown.SubmitDropDown1.prototype = Object.create(SKIPOLE.BaseWidget.prototype);
SKIPOLE.dropdown.SubmitDropDown1.prototype.constructor = SKIPOLE.dropdown.SubmitDropDown1;
SKIPOLE.dropdown.SubmitDropDown1.prototype.eventfunc = function(e) {
SKIPOLE.skiprefresh = true;
// if action_json url set, call a json page
let jsonurl = this.fieldvalues["url"];
if (jsonurl) {
// json url set, send data with a request for json and prevent default
let self = this;
let widgform = this.widg.find('form');
let senddata = widgform.serializeArray();
e.preventDefault();
// respond to json or html
$.ajax({
url: jsonurl,
data: senddata
})
.done(function(result, textStatus, jqXHR) {
if (jqXHR.responseJSON) {
// JSON response
if (self.get_error(result)) {
// if error, set any results received from the json call
SKIPOLE.setfields(result);
}
else {
// If no error received, clear any previous error
self.clear_error();
SKIPOLE.setfields(result);
}
} else {
// html response
document.open();
document.write(result);
document.close();
}
})
.fail(function( jqXHR, textStatus, errorThrown ) {
if (jqXHR.status == 400 || jqXHR.status == 404 || jqXHR.status == 500) {
document.open();
document.write(jqXHR.responseText);
document.close();
}
else {
SKIPOLE.json_failed( jqXHR, textStatus, errorThrown );
}
});
}
};
SKIPOLE.dropdown.SubmitDropDown1.prototype.setvalues = function (fieldlist, result) {
if (!this.widg_id) {
return;
}
let the_widg = this.widg;
// sets hidden fields
this.sethiddenfields(fieldlist, result);
// sets hide
let set_hide = this.fieldarg_in_result('hide', result, fieldlist);
if (set_hide != undefined) {
if (set_hide) {
if (the_widg.is(":visible")) {
the_widg.fadeOut('slow');
}
}
else {
if (!(the_widg.is(":visible"))) {
the_widg.fadeIn('slow');
}
}
}
};
SKIPOLE.dropdown.HiddenContainer = function (widg_id, error_message, fieldmap) {
SKIPOLE.BaseWidget.call(this, widg_id, error_message, fieldmap);
this.display_errors = false;
};
SKIPOLE.dropdown.HiddenContainer.prototype = Object.create(SKIPOLE.BaseWidget.prototype);
SKIPOLE.dropdown.HiddenContainer.prototype.constructor = SKIPOLE.dropdown.HiddenContainer;
SKIPOLE.dropdown.HiddenContainer.prototype.setvalues = function (fieldlist, result) {
if (!this.widg_id) {
return;
}
let the_widg = this.widg;
// check if hide
let hidebox = this.fieldarg_in_result('hide', result, fieldlist);
if (hidebox != undefined) {
if (hidebox) {
if (the_widg.is(":visible")) {
the_widg.fadeOut('slow');
}
}
else {
if (!(the_widg.is(":visible"))) {
the_widg.fadeIn('slow');
}
}
}
let button = the_widg.find("a");
// get_field1
let get_field1 = this.fieldarg_in_result('get_field1', result, fieldlist);
if (get_field1 != undefined) {
let href = button.attr('href');
let url = this.setgetfield(href, "get_field1", get_field1);
button.attr('href', url);
}
// get_field2
let get_field2 = this.fieldarg_in_result('get_field2', result, fieldlist);
if (get_field2 != undefined) {
let href = button.attr('href');
let url = this.setgetfield(href, "get_field2", get_field2);
button.attr('href', url);
}
// get_field3
let get_field3 = this.fieldarg_in_result('get_field3', result, fieldlist);
if (get_field3 != undefined) {
let href = button.attr('href');
let url = this.setgetfield(href, "get_field3", get_field3);
button.attr('href', url);
}
};
SKIPOLE.dropdown.HiddenContainer.prototype.eventfunc = function (e) {
SKIPOLE.skiprefresh = true;
// pressing close fades out the widget and prevents the link send
let the_widg = this.widg;
if (the_widg.is(":visible")) {
the_widg.fadeOut('slow');
}
e.preventDefault();
};
| 35.921053 | 99 | 0.549451 |
c622ec0c8b31daac5e6b3e0ae83e70d8347d11cc | 37,719 | js | JavaScript | src/channel/channel.js | openziti/ziti-browzer-core | 88369bd503edfa781d392922964b24fefcc22b7b | [
"Apache-2.0"
] | null | null | null | src/channel/channel.js | openziti/ziti-browzer-core | 88369bd503edfa781d392922964b24fefcc22b7b | [
"Apache-2.0"
] | 3 | 2022-03-31T14:36:51.000Z | 2022-03-31T14:56:16.000Z | src/channel/channel.js | openziti/ziti-browzer-core | 88369bd503edfa781d392922964b24fefcc22b7b | [
"Apache-2.0"
] | null | null | null | /*
Copyright Netfoundry, Inc.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
https://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
/**
* Module dependencies.
*/
import { flatOptions } from '../utils/flat-options'
import { defaultOptions } from './channel-options'
import { ZitiConnections } from './connections';
import { ZitiWASMTLSConnection } from './wasm-tls-connection';
import { Header } from './header';
import { ZitiWebSocket } from '../websocket/websocket';
import { ZitiSocket } from '../http/ziti-socket';
import { Messages } from './messages';
import { ZitiEdgeProtocol } from '../channel/protocol';
import throwIf from '../utils/throwif';
import {
appendBuffer,
toUTF8Array,
sumBy,
concatTypedArrays
} from '../utils/utils';
import { isUndefined, isNull, isEqual, forEach } from 'lodash-es';
import { Mutex } from 'async-mutex';
import { Buffer } from 'buffer';
//TODO: this breaks the build at the moment... figure out why!
import sodium from 'libsodium-wrappers';
import PromiseController from 'promise-controller';
import formatMessage from 'format-message';
/**
* ZitiChannel
*/
class ZitiChannel {
/**
*
*/
constructor(options) {
let _options = flatOptions(options, defaultOptions);
this._session_token = _options.session_token;
this._network_session_token = _options.network_session_token;
this._zitiContext = _options.zitiContext;
this._id = this._zitiContext.getNextChannelId();
this._data = _options.data;
this._timeout = _options.timeout;
this._helloTimeout = _options.helloTimeout;
this._state = ZitiEdgeProtocol.conn_state.Initial;
this._msgSeq = -1;
this._edgeRouter = _options.edgeRouter;
this._edgeRouterHost = this._edgeRouter.hostname;
this._connections = new ZitiConnections();
this._zws = new ZitiWebSocket( this._edgeRouter.urls.ws + '/ws' , {
zitiContext: this._zitiContext,
});
this._callerId = "ws:";
this._zws.onMessage.addListener(this._recvFromWire, this);
this._zws.onClose.addListener(this._recvClose, this);
this._zws.onSend.addListener(this._recvSend, this);
this._createHelloController();
// Set the maximum timestamp
this._helloCompletedTimestamp = new Date(8640000000000000); // http://www.ecma-international.org/ecma-262/5.1/#sec-15.9.1.1
this._messages = new Messages({ zitiContext: this._zitiContext, channel: this });
this._view_version = new Uint8Array(new ArrayBuffer(4));
this._view_version.set(ZitiEdgeProtocol.VERSION, 0);
this._mutex = new Mutex();
}
get zitiContext() {
return this._zitiContext;
}
get id() {
return this._id;
}
get tlsConn() {
return this._tlsConn;
}
get data() {
return this._data;
}
get state() {
return this._state;
}
set state(state) {
this._state = state;
}
getAndIncrementSequence() {
return this._msgSeq++;
}
get edgeRouterHost() {
return this._edgeRouterHost;
}
get helloCompletedTimestamp() {
return this._helloCompletedTimestamp;
}
get isHelloCompleted() {
return Boolean(this._helloCompleted);
}
/**
*
*/
_createHelloController() {
const helloTimeout = this._helloTimeout || this._timeout;
this._helloing = new PromiseController({
timeout: helloTimeout,
timeoutReason: `Can't complete 'Hello' within allowed timeout: ${helloTimeout} ms.`
});
}
/**
* Remain in lazy-sleepy loop until tlsConn has completed its TLS handshake.
*
*/
async awaitTLSHandshakeComplete() {
let self = this;
return new Promise((resolve) => {
(function waitForTLSHandshakeComplete() {
if (!self._tlsConn.connected) {
self._zitiContext.logger.trace('awaitTLSHandshakeComplete() tlsConn for ch[%d] TLS handshake still not complete', self.id);
setTimeout(waitForTLSHandshakeComplete, 100);
} else {
self._zitiContext.logger.trace('tlsConn for ch[%d] TLS handshake is now complete', self.id);
let result = self._tlsConn.ssl_get_verify_result();
if (result !== 1) {
self._zitiContext.logger.error('tlsConn for ch[%d] fails TLS verification', self.id);
}
return resolve();
}
})();
});
}
/**
* Do Hello handshake between this channel and associated Edge Router.
*
*/
async hello() {
this._zitiContext.logger.trace('ZitiChannel.hello entered for ch[%o]', this);
await this._zws.open();
this._zitiContext.logger.trace('ZitiChannel.hello _zws.open completed for ch[%o]', this);
if (this.isHelloCompleted) {
this._zitiContext.logger.trace('Hello handshake was previously completed');
return new Promise( async (resolve) => {
resolve( {channel: this, data: null});
});
}
if (isEqual(this._callerId, "ws:")) {
// this._zitiContext.ssl_CTX_new();
// // this._zitiContext.bio_new_ssl_connect();
// // this._zitiContext.bio_set_conn_hostname('www.google.com:443');
// // this._zitiContext.bio_do_connect();
// this._zitiContext.ssl_new();
// this._zitiContext.ssl_set_fd( this.id );
// this._zitiContext.ssl_connect();
this._tlsConn = new ZitiWASMTLSConnection({
zitiContext: this._zitiContext,
ws: this._zws,
ch: this,
datacb: this._recvFromWireAfterDecrypt
});
await this._tlsConn.pullKeyPair();
await this._tlsConn.create();
this._zitiContext.logger.debug('initiating TLS handshake');
this._tlsConn.handshake();
await this.awaitTLSHandshakeComplete();
this._zitiContext.logger.debug('TLS handshake completed');
}
this._zitiContext.logger.debug('initiating message: ZitiEdgeProtocol.content_type.HelloType: ', ZitiEdgeProtocol.header_type.StringType);
let headers = [
new Header( ZitiEdgeProtocol.header_id.SessionToken, {
headerType: ZitiEdgeProtocol.header_type.StringType,
headerData: this._session_token
}),
new Header( ZitiEdgeProtocol.header_id.CallerId, {
headerType: ZitiEdgeProtocol.header_type.StringType,
headerData: this._callerId
})
];
let sequence = this.getAndIncrementSequence();
let msg = await this.sendMessage( ZitiEdgeProtocol.content_type.HelloType, headers, null, {
sequence: sequence,
});
this._helloCompletedTimestamp = Date.now();
this._helloCompleted = true;
this.state = (ZitiEdgeProtocol.conn_state.Connected);
this._zitiContext.logger.debug('ch[%d] Hello handshake to Edge Router [%s] completed at timestamp[%o]', this._id, this._edgeRouterHost, this._helloCompletedTimestamp);
return new Promise( async (resolve) => {
resolve( {channel: this, data: null});
});
}
/**
* Connect specified Connection to associated Edge Router.
*
*/
async connect(conn) {
const self = this;
return new Promise( async (resolve, reject) => {
self._zitiContext.logger.debug('initiating Connect to Edge Router [%s] for conn[%d]', this._edgeRouterHost, conn.id);
await sodium.ready;
let keypair = sodium.crypto_kx_keypair();
conn.keypair = (keypair);
let sequence = this.getAndIncrementSequence();
let headers = [
new Header( ZitiEdgeProtocol.header_id.ConnId, {
headerType: ZitiEdgeProtocol.header_type.IntType,
headerData: conn.id
}),
new Header( ZitiEdgeProtocol.header_id.SeqHeader, {
headerType: ZitiEdgeProtocol.header_type.IntType,
headerData: 0
}),
];
if (conn.encrypted) { // if connected to a service that has 'encryptionRequired'
headers.push(
new Header( ZitiEdgeProtocol.header_id.PublicKey, {
headerType: ZitiEdgeProtocol.header_type.Uint8ArrayType,
headerData: keypair.publicKey
})
);
}
conn.state = (ZitiEdgeProtocol.conn_state.Connecting);
self._zitiContext.logger.debug('about to send Connect to Edge Router [%s] for conn[%d]', conn.channel.edgeRouterHost, conn.id);
let msg = await self.sendMessage( ZitiEdgeProtocol.content_type.Connect, headers, self._network_session_token, {
conn: conn,
sequence: sequence,
}
);
self._zitiContext.logger.debug('connect() calling _recvConnectResponse() for conn[%d]', conn.id);
await self._recvConnectResponse(msg.data, conn);
resolve();
});
}
/**
* Close specified Connection to associated Edge Router.
*
*/
async close(conn) {
const self = this;
return new Promise( async (resolve, reject) => {
self._zitiContext.logger.debug('initiating Close to Edge Router [%s] for conn[%d]', this._edgeRouterHost, conn.id);
let sequence = conn.getAndIncrementSequence();
let headers = [
new Header( ZitiEdgeProtocol.header_id.ConnId, {
headerType: ZitiEdgeProtocol.header_type.IntType,
headerData: conn.id
}),
new Header( ZitiEdgeProtocol.header_id.SeqHeader, {
headerType: ZitiEdgeProtocol.header_type.IntType,
headerData: sequence
}),
];
self._zitiContext.logger.debug('about to send Close to Edge Router [%s] for conn[%d]', conn.channel.edgeRouterHost, conn.id);
let msg = await self.sendMessage( ZitiEdgeProtocol.content_type.StateClosed, headers, self._network_session_token, {
conn: conn,
sequence: sequence,
}
);
self._zitiContext.logger.debug('close() completed with response[%o]', msg);
conn.state = (ZitiEdgeProtocol.conn_state.Closed);
resolve();
});
}
/**
* Receives response from Edge 'Connect' message.
*
*/
async _recvConnectResponse(msg, expectedConn) {
// let buffer = await msg.arrayBuffer();
let buffer = await msg.buffer;
let contentTypeView = new Int32Array(buffer, 4, 1);
let contentType = contentTypeView[0];
let sequenceView = new Int32Array(buffer, 8, 1);
let sequence = sequenceView[0];
let connId = await this._messageGetConnId(msg);
let conn = this._connections._getConnection(connId);
throwIf(isUndefined(conn), formatMessage('Conn not found. Seeking connId { actual }', { actual: connId}) );
if (!isEqual(conn.id, expectedConn.id)) {
this._zitiContext.logger.error("_recvConnectResponse() actual conn[%d] expected conn[%d]", conn.id, expectedConn.id);
}
this._zitiContext.logger.debug("ConnectResponse contentType[%d] seq[%d] received for conn[%d]", contentType, sequence, conn.id);
switch (contentType) {
case ZitiEdgeProtocol.content_type.StateClosed:
this._zitiContext.logger.warn("conn[%d] failed to connect on ch[%d]", conn.id, this.id);
conn.state = (ZitiEdgeProtocol.conn_state.Closed);
break;
case ZitiEdgeProtocol.content_type.StateConnected:
if (conn.state == ZitiEdgeProtocol.conn_state.Connecting) {
this._zitiContext.logger.debug("conn[%d] connected", conn.id);
if (conn.encrypted) { // if connected to a service that has 'encryptionRequired'
await this._establish_crypto(conn, msg);
this._zitiContext.logger.debug("establish_crypto completed for conn[%d]", conn.id);
await this._send_crypto_header(conn);
this._zitiContext.logger.debug("send_crypto_header completed for conn[%d]", conn.id);
}
conn.state = (ZitiEdgeProtocol.conn_state.Connected);
}
else if (conn.state == ZitiEdgeProtocol.conn_state.Closed || conn.state == ZitiEdgeProtocol.conn_state.Timedout) {
this._zitiContext.logger.warn("received connect reply for closed/timedout conne[%d]", conn.id);
// ziti_disconnect(conn);
}
break;
default:
this._zitiContext.logger.error("unexpected content_type[%d] conn[%d]", contentType, conn.id);
// ziti_disconnect(conn);
}
}
/**
*
*/
async _establish_crypto(conn, msg) {
this._zitiContext.logger.debug("_establish_crypto(): entered for conn[%d]", conn.id);
let result = await this._messageGetBytesHeader(msg, ZitiEdgeProtocol.header_id.PublicKey);
let peerKey = result.data;
this._zitiContext.logger.debug("_establish_crypto(): peerKey is: ", peerKey);
if (peerKey == undefined) {
this._zitiContext.logger.debug("_establish_crypto(): did not receive peer key. connection[%d] will not be encrypted: ", conn.id);
conn.encrypted = false;
return;
}
if (conn.state == ZitiEdgeProtocol.conn_state.Connecting) {
let keypair = conn.keypair();
let results = sodium.crypto_kx_client_session_keys(keypair.publicKey, keypair.privateKey, peerKey);
conn.setSharedRx(results.sharedRx);
conn.setSharedTx(results.sharedTx);
} else {
this._zitiContext.logger.error("_establish_crypto(): cannot establish crypto while connection is in %d state: ", conn.state);
}
}
/**
* Receives response from Edge 'Data' message where we sent the Crypto header.
*
*/
async _recvCryptoResponse(msg) {
let connId = await this._messageGetConnId(msg);
this._zitiContext.logger.debug("_recvCryptoResponse(): entered for conn[%d]", connId);
let conn = this._connections._getConnection(connId);
throwIf(isUndefined(conn), formatMessage('Conn not found. Seeking connId { actual }', { actual: connId}) );
//
let buffer = await msg.buffer;
let headersLengthView = new Int32Array(buffer, 12, 1);
let headersLength = headersLengthView[0];
var bodyView = new Uint8Array(buffer, 20 + headersLength);
let state_in = sodium.crypto_secretstream_xchacha20poly1305_init_pull(bodyView, conn.sharedRx);
conn.setCrypt_i(state_in);
// Indicate that subsequent sends on this connection should be encrypted
conn.encrypted = true;
// Unblock writes to the connection now that we have sent the crypto header
conn.setCryptoEstablishComplete(true);
this._zitiContext.logger.debug("_recvCryptoResponse(): setCryptoEstablishComplete for conn[%d]", connId);
}
/**
* Remain in lazy-sleepy loop until specified connection's crypto handshake is complete.
*
* @param {*} conn
*/
awaitConnectionCryptoEstablishComplete(conn) {
return new Promise((resolve) => {
(function waitForCryptoEstablishComplete() {
if (conn.cryptoEstablishComplete) {
conn.zitiContext.logger.debug('Connection [%d] now Crypto-enabled with Edge Router', conn.id);
return resolve();
}
conn.zitiContext.logger.debug('awaitConnectionCryptoEstablishComplete() conn[%d] still not yet CryptoEstablishComplete', conn.id);
setTimeout(waitForCryptoEstablishComplete, 100);
})();
});
}
/**
*
*/
async _send_crypto_header(conn) {
const self = this;
return new Promise( async (resolve, reject) => {
let results = sodium.crypto_secretstream_xchacha20poly1305_init_push( conn.sharedTx );
conn.setCrypt_o(results);
let sequence = conn.getAndIncrementSequence();
let headers = [
new Header( ZitiEdgeProtocol.header_id.ConnId, {
headerType: ZitiEdgeProtocol.header_type.IntType,
headerData: conn.id
}),
new Header( ZitiEdgeProtocol.header_id.SeqHeader, {
headerType: ZitiEdgeProtocol.header_type.IntType,
headerData: sequence
})
];
self._zitiContext.logger.debug('_send_crypto_header(): conn[%d] sending Data [%o]', conn.id, conn.crypt_o.header);
let msg = await self.sendMessage( ZitiEdgeProtocol.content_type.Data, headers, conn.crypt_o.header, {
conn: conn,
sequence: sequence,
}
);
self._zitiContext.logger.debug('_send_crypto_header() calling _recvCryptoResponse() for conn[%d]', conn.id);
await self._recvCryptoResponse(msg.data, conn);
resolve();
});
}
/**
* Write data over specified Edge Router connection.
*
* @returns {Promise}
*/
async write(conn, data) {
if (!isEqual(conn.state, ZitiEdgeProtocol.conn_state.Closed)) {
let sequence = conn.getAndIncrementSequence();
let headers = [
new Header( ZitiEdgeProtocol.header_id.ConnId, {
headerType: ZitiEdgeProtocol.header_type.IntType,
headerData: conn.id
}),
new Header( ZitiEdgeProtocol.header_id.SeqHeader, {
headerType: ZitiEdgeProtocol.header_type.IntType,
headerData: sequence
})
];
this.sendMessageNoWait( ZitiEdgeProtocol.content_type.Data, headers, data, { conn: conn, sequence: sequence });
}
}
/**
* Sends message and waits for response.
*
* @param {String|Number} contentType
* @param {[Header]} headers
* @param {*} body
* @param {Object} [options]
* @returns {Promise}
*/
sendMessage(contentType, headers, body, options = {}) {
const timeout = options.timeout !== undefined ? options.timeout : this._timeout;
let messageId;
if (!isUndefined(options.sequence)) {
messageId = options.sequence;
} else if (!isUndefined(this._sequence)) {
messageId = this._sequence;
}
throwIf(isUndefined(messageId), formatMessage('messageId is undefined', { } ) );
let messagesQueue = this._messages;
let conn;
if (!isUndefined(options.conn)) {
conn = options.conn;
messagesQueue = options.conn.messages;
}
this._zitiContext.logger.debug("send -> conn[%o] seq[%o] contentType[%o] body[%s]", (conn ? conn.id : 'n/a'), messageId, contentType, (body ? body.toString() : 'n/a'));
return messagesQueue.create(messageId, () => {
this._sendMarshaled(contentType, headers, body, options, messageId);
}, timeout);
}
/**
* Sends message and does not wait for response.
*
* @param {String|Number} contentType
* @param {[Header]} headers
* @param {*} body
* @param {Object} [options]
* @returns {Promise}
*/
sendMessageNoWait(contentType, headers, body, options = {}) {
const timeout = options.timeout !== undefined ? options.timeout : this._timeout;
const messageId = options.sequence || this._sequence;
// this._zitiContext.logger.debug("send (no wait) -> conn[%o] seq[%o] contentType[%o]",
// (options.conn ? options.conn.id : 'n/a'),
// messageId,
// contentType,
// (body ? body.toString() : 'n/a'));
this._zitiContext.logger.debug("send (no wait) -> conn[%o] seq[%o] contentType[%o] bodyLen[%o] ",
(options.conn ? options.conn.id : 'n/a'),
messageId, contentType,
(body ? body.length : 'n/a'),
(body ? body.toString() : 'n/a')
);
this._sendMarshaled(contentType, headers, body, options, messageId);
}
/**
* Marshals message into binary wire format and sends to the Edge Router.
*
* @param {String|Number} contentType
* @param {[Header]} headers
* @param {*} body
* @param {Object} [options]
* @param {int} messageId
*/
_sendMarshaled(contentType, headers, body, options, messageId) {
let dataToMarshal = body;
if (contentType != ZitiEdgeProtocol.content_type.HelloType) {
let connId;
forEach(headers, function(header) {
if (header.getId() == ZitiEdgeProtocol.header_id.ConnId) {
connId = header.getData();
}
});
throwIf(isUndefined(connId), formatMessage('Cannot find ConnId header', { } ) );
let conn = this._connections._getConnection(connId);
throwIf(isUndefined(conn), formatMessage('Conn not found. Seeking connId { actual }', { actual: connId}) );
if (conn.encrypted && conn.cryptoEstablishComplete) { // if connected to a service that has 'encryptionRequired'
let [state_out, header] = [conn.crypt_o.state, conn.crypt_o.header];
let encryptedData = sodium.crypto_secretstream_xchacha20poly1305_push(
state_out,
body,
null,
sodium.crypto_secretstream_xchacha20poly1305_TAG_MESSAGE);
dataToMarshal = encryptedData;
}
}
const wireData = this._marshalMessage(contentType, headers, dataToMarshal, options, messageId);
this._zitiContext.logger.trace("_sendMarshaled -> wireDataLen[%o] ", wireData.byteLength);
this._dumpHeaders(' -> ', wireData);
// Inject the listener if specified
if (options.listener !== undefined) {
this._zws.onMessage.addOnceListener(options.listener, this);
}
// If connected to a WS edge router
if (isEqual(this._callerId, "ws:")) {
this._tlsConn.tls_write(wireData);
}
else {
this._zws.send(wireData);
}
}
/**
* Marshals message into binary wire format.
*
* @param {String|Number} contentType
* @param {[Header]} headers
* @param {*} body
* @param {Object} [options]
* @returns {byte[]}
*/
_marshalMessage(contentType, headers, body, options, messageId) {
// wire-protocol: message-section
let buffer_message_section = new ArrayBuffer(
4 // Version
+4 // ContentType (offset 4)
+4 // Sequence (offset 8)
+4 // hdrs-len (offset 12)
+4 // body-len (offset 16)
);
// wire-protocol: Version
let view_message_section = new Uint8Array(buffer_message_section);
view_message_section.set(
ZitiEdgeProtocol.VERSION,
0 // Offset 0
);
var bytes = new Buffer(4);
// wire-protocol: ContentType
bytes.writeUInt32LE(contentType, 0);
view_message_section.set(
bytes,
4 // Offset 4
);
bytes = new Buffer(4);
// wire-protocol: Sequence
bytes.writeInt32LE(messageId, 0);
view_message_section.set(
bytes,
8 // Offset 8
);
bytes = new Buffer(4);
let hdrsLen = sumBy(headers, function (header) {
return header.getLength();
});
// wire-protocol: hdrs-len
bytes.writeInt32LE(hdrsLen, 0);
view_message_section.set(
bytes,
12 // Offset 12
);
bytes = new Buffer(4);
// wire-protocol: body-len
let bodyLength = 0;
if (!isNull(body)) {
bodyLength = body.length;
}
bytes.writeUInt32LE(bodyLength, 0);
view_message_section.set(
bytes,
16 // Offset 16
);
// wire-protocol: headers
let buffer_headers_section = new ArrayBuffer(hdrsLen);
let view_headers_section = new Uint8Array(buffer_headers_section);
let view_headers_section_offset = 0;
forEach(headers, function(header) {
view_headers_section.set(header.getBytesForWire(), view_headers_section_offset);
view_headers_section_offset += header.getLength();
});
// wire-protocol: body
let buffer_body_section = new ArrayBuffer(bodyLength);
if (bodyLength > 0) {
let view_body_section = new Uint8Array(buffer_body_section);
let body_bytes;
if (typeof body === 'string') {
body_bytes = toUTF8Array(body);
} else {
body_bytes = body;
}
let bytesBuffer = Buffer.from(body_bytes);
view_body_section.set(bytesBuffer, 0);
}
// Put it all together
this._zitiContext.logger.trace("_marshalMessage -> buffer_message_section Len[%o] ", buffer_message_section.byteLength);
this._zitiContext.logger.trace("_marshalMessage -> buffer_headers_section Len[%o] ", buffer_headers_section.byteLength);
this._zitiContext.logger.trace("_marshalMessage -> buffer_body_section Len[%o] ", buffer_body_section.byteLength);
let buffer_combined = appendBuffer(buffer_message_section, buffer_headers_section);
buffer_combined = appendBuffer(buffer_combined, buffer_body_section);
let view_combined = new Uint8Array(buffer_combined);
return view_combined.buffer;
}
/**
* Receives a send event from the Websocket.
*
* @param {*} data
*/
async _recvSend(data) {
if (!isUndefined(this._zws)) {
if (!isNull(this._zws._ws)) {
this._zitiContext.logger.debug('_recvSend -> data[%o] sentLen[%o] bufferedLen[%o]', data, data.byteLength, this._zws._ws.bufferedAmount);
}
}
}
/**
* Receives a close event from the Websocket.
*
* @param {*} data
*/
async _recvClose(data) {
this._zitiContext.closeChannelByEdgeRouter( this._edgeRouterHost );
}
/**
* Receives a message from the Edge Router.
*
* @param {*} data
*/
async _recvFromWire(data) {
let buffer = await data.arrayBuffer();
this._zitiContext.logger.debug("_recvFromWire <- data len[%o]", buffer.byteLength);
this._tlsConn.process(buffer);
}
/**
* Receives un-encrypted binary data from the Edge Router (which is either an entire edge protocol message, or a fragment thereof)
*
* @param ArrayBuffer data
*/
async _recvFromWireAfterDecrypt(ch, data) {
let buffer = data;
if (!isUndefined(ch._partialMessage)) { // if we are awaiting rest of a partial msg to arrive, append this chunk onto the end, then proceed
let dataView = new Uint8Array(data);
ch._partialMessage = concatTypedArrays(ch._partialMessage, dataView);
buffer = ch._partialMessage.buffer.slice(0);
}
let versionView = new Uint8Array(buffer, 0, 4);
throwIf(!isEqual(versionView[0], ch._view_version[0]), formatMessage('Unexpected message version. Got { actual }, expected { expected }', { actual: versionView[0], expected: ch._view_version[0]}) );
let headersLengthView = new Int32Array(buffer, 12, 1);
let headersLength = headersLengthView[0];
let bodyLengthView = new Int32Array(buffer, 16, 1);
let bodyLength = bodyLengthView[0];
let msgLength = ( 20 + headersLength + bodyLength );
if (isEqual(msgLength, buffer.byteLength)) { // if entire edge message is present, proceed with unmarshaling effort
ch._partialMessage = undefined;
ch._tryUnmarshal(buffer);
} else {
ch._partialMessage = new Uint8Array(buffer);
if (buffer.byteLength > 20) { // if we have a portion of the data section of the edge message
ch._zitiContext.logger.debug("Only [%o] of msgLength [%o] received; will await rest of fragments before unmarshaling", buffer.byteLength, msgLength);
}
}
}
/**
* Unmarshals binary from the wire into a message
*
* @param {*} data
*/
async _tryUnmarshal(data) {
let buffer = data;
let versionView = new Uint8Array(buffer, 0, 4);
throwIf(!isEqual(versionView[0], this._view_version[0]), formatMessage('Unexpected message version. Got { actual }, expected { expected }', { actual: versionView[0], expected: this._view_version[0]}) );
let contentTypeView = new Int32Array(buffer, 4, 1);
let contentType = contentTypeView[0];
let sequenceView = new Int32Array(buffer, 8, 1);
this._zitiContext.logger.trace("recv <- contentType[%o] seq[%o]", contentType, sequenceView[0]);
let responseSequence = sequenceView[0];
let headersLengthView = new Int32Array(buffer, 12, 1);
let headersLength = headersLengthView[0];
this._zitiContext.logger.trace("recv <- headersLength[%o]", headersLength);
let bodyLengthView = new Int32Array(buffer, 16, 1);
let bodyLength = bodyLengthView[0];
this._zitiContext.logger.trace("recv <- bodyLength[%o]", bodyLength);
this._dumpHeaders(' <- ', buffer);
var bodyView = new Uint8Array(buffer, 20 + headersLength);
let connId;
let conn;
let replyForView;
let haveResponseSequence = false;
const release = await this._mutex.acquire();
/**
* First Data msg for a new connection needs special handling
*/
if (contentType == ZitiEdgeProtocol.content_type.Data) {
connId = await this._messageGetConnId(data);
if (!isUndefined(connId)) {
conn = this._connections._getConnection(connId);
if (!isUndefined(conn)) {
if (isEqual(conn.state, ZitiEdgeProtocol.conn_state.Connecting)) {
let result = await this._messageGetBytesHeader(data, ZitiEdgeProtocol.header_id.SeqHeader);
if (!isUndefined(result)) {
replyForView = new Int32Array(result.data, 0, 1);
responseSequence = replyForView[0];
haveResponseSequence = true;
this._zitiContext.logger.debug("recv <- ReplyFor[%o] (should be for the crypto_header response)", responseSequence);
}
}
}
}
}
if (!haveResponseSequence && (contentType >= ZitiEdgeProtocol.content_type.StateConnected)) {
let result = await this._messageGetBytesHeader(data, ZitiEdgeProtocol.header_id.ReplyFor);
if (!isUndefined(result)) {
replyForView = new DataView( result.data.buffer.slice(result.data.byteOffset, result.data.byteLength + result.data.byteOffset) );
responseSequence = replyForView.getInt32(0, true); // second parameter truethy == want little endian;
this._zitiContext.logger.trace("recv <- ReplyFor[%o]", responseSequence);
} else {
if ( isEqual(contentType, ZitiEdgeProtocol.content_type.Data) && isEqual(bodyLength, 0) ) {
let result = await this._messageGetBytesHeader(data, ZitiEdgeProtocol.header_id.SeqHeader);
replyForView = new Int32Array(result.data, 0, 1);
responseSequence = replyForView[0];
this._zitiContext.logger.trace("recv <- Close Response For [%o]", responseSequence);
} else {
this._zitiContext.logger.trace("recv <- ReplyFor[%o]", 'n/a');
responseSequence--;
this._zitiContext.logger.trace("reducing seq by 1 to [%o]", responseSequence);
}
}
}
if ((contentType >= ZitiEdgeProtocol.content_type.Connect) && (isUndefined(conn))) {
let connId = await this._messageGetConnId(data);
throwIf(isUndefined(connId), formatMessage('Cannot find ConnId header', { } ) );
conn = this._connections._getConnection(connId);
throwIf(isUndefined(conn), formatMessage('Conn not found. Seeking connId { actual }', { actual: connId}) );
}
/**
* Data msgs might need to be decrypted before passing along
*/
if (contentType == ZitiEdgeProtocol.content_type.Data) {
if (bodyLength > 0) {
if (conn.encrypted && conn.cryptoEstablishComplete) { // if connected to a service that has 'encryptionRequired'
let unencrypted_data = sodium.crypto_secretstream_xchacha20poly1305_pull(conn.crypt_i, bodyView);
if (!unencrypted_data) {
this._zitiContext.logger.error("crypto_secretstream_xchacha20poly1305_pull failed. bodyLength[%d]", bodyLength);
}
try {
let [m1, tag1] = [sodium.to_string(unencrypted_data.message), unencrypted_data.tag];
let len = m1.length;
if (len > 2000) {
len = 2000;
}
this._zitiContext.logger.trace("recv <- unencrypted_data (first 2000): %s", m1.substring(0, len));
//
let dbgStr = m1.substring(0, len);
this._zitiContext.logger.trace("recv <- data (first 2000): %s", dbgStr);
} catch (e) { }
bodyView = unencrypted_data.message;
} else {
/* debug...
let len = bodyView.length;
if (len > 2000) {
len = 2000;
}
let dbgStr = String.fromCharCode.apply(null, bodyView).substring(0, len);
this._zitiContext.logger.debug("recv <- data (first 2000): %s", dbgStr);
*/
//temp debugging
// if (dbgStr.includes("var openMe = (window.parent")) {
// let str = String.fromCharCode.apply(null, bodyView).substring(0, bodyView.length);
// // str = str.replace('var openMe = (window.parent', 'debugger; var openMe = (window.parent');
// if (str.indexOf( '/api/extplugins/config' ) !== -1) {
// debugger
// }
// this._zitiContext.logger.debug("============== DEBUG INJECT: %s", str);
// bodyView = new TextEncoder("utf-8").encode(str);
// }
}
}
//
let dataCallback = conn.dataCallback;
if (!isUndefined(dataCallback)) {
this._zitiContext.logger.trace("recv <- contentType[%o] seq[%o] passing body to dataCallback", contentType, sequenceView[0]);
dataCallback(conn, bodyView);
}
}
this._zitiContext.logger.trace("recv <- response body: ", bodyView);
this._tryHandleResponse(conn, responseSequence, {channel: this, data: bodyView});
release();
}
/**
*
*/
_tryHandleResponse(conn, responseSequence, data) {
if (!isUndefined(conn)) {
let socket = conn.socket;
if (!isUndefined(socket)) {
if (socket.isWebSocket) {
return;
}
}
}
let messagesQueue = this._messages;
if (!isUndefined(conn)) {
messagesQueue = conn.messages;
}
this._zitiContext.logger.trace("_tryHandleResponse(): conn[%d] seq[%d]", (conn ? conn.id : 'n/a'), responseSequence);
if (!isNull(responseSequence)) {
messagesQueue.resolve(responseSequence, data);
} else {
debugger
}
}
/**
*
*/
async _dumpHeaders(pfx, buffer) {
var headersView = new Int32Array(buffer, 12, 1);
let headersLength = headersView[0];
let headersOffset = 16 + 4;
let ndx = 0;
let view = new DataView(buffer);
this._zitiContext.logger.trace("_dumpHeaders: "+pfx+"vv----------------------------------");
for ( ; ndx < headersLength; ) {
var _headerId = view.getInt32(headersOffset + ndx, true);
ndx += 4;
var _headerDataLength = view.getInt32(headersOffset + ndx, true);
ndx += 4;
var _headerData = new Uint8Array(buffer, headersOffset + ndx, _headerDataLength);
ndx += _headerDataLength;
let connId = 'n/a';
if (isEqual(_headerId, ZitiEdgeProtocol.header_id.ConnId)) {
let buffer = Buffer.from(_headerData);
connId = buffer.readUIntLE(0, _headerDataLength);
}
this._zitiContext.logger.trace("headerId[%d] conn[%d] dataLength[%d] data[%o]", _headerId, connId, _headerDataLength, _headerData);
}
this._zitiContext.logger.trace("_dumpHeaders: "+pfx+"^^----------------------------------");
}
/**
*
*/
async _findHeader(msg, headerToFind) {
let buffer;
if (!isUndefined(msg.arrayBuffer)) {
buffer = await msg.arrayBuffer();
} else if (!isUndefined(msg.buffer)) {
buffer = await msg.buffer;
} else {
buffer = msg;
}
var headersView = new Int32Array(buffer, 12, 1);
let headersLength = headersView[0];
let headersOffset = 16 + 4;
let ndx = 0;
let view = new DataView(buffer);
for ( ; ndx < headersLength; ) {
var _headerId = view.getInt32(headersOffset + ndx, true);
ndx += 4;
var _headerDataLength = view.getInt32(headersOffset + ndx, true);
ndx += 4;
var _headerData = new Uint8Array(buffer, headersOffset + ndx, _headerDataLength);
ndx += _headerDataLength;
if (_headerId == headerToFind) {
let result = {
dataLength: _headerDataLength,
data: _headerData,
};
return result;
}
}
return undefined;
}
/**
*
*/
async _messageGetBytesHeader(msg, headerToFind) {
return await this._findHeader(msg, headerToFind);
}
/**
*
*/
async _messageGetConnId(msg) {
let results = await this._findHeader(msg, ZitiEdgeProtocol.header_id.ConnId);
throwIf(results == undefined, formatMessage('No ConnId header found'));
var length = results.data.length;
let buffer = Buffer.from(results.data);
var connId = buffer.readUIntLE(0, length);
return connId;
}
getConnection(id) {
return this._connections._getConnection(id);
}
getSocket() {
return this._socket;
}
setSocket(socket) {
this._socket = socket;
}
getDataCallback() {
return this._dataCallback;
}
setDataCallback(fn) {
this._dataCallback = fn;
}
// getEncrypted() {
// return this._encrypted;
// }
// setEncrypted(encrypted) {
// this._encrypted = encrypted;
// }
getCryptoEstablishComplete() {
return this._cryptoEstablishComplete;
}
setCryptoEstablishComplete(complete) {
this._cryptoEstablishComplete = complete;
}
getKeypair() {
return this._keypair;
}
setKeypair(keypair) {
this._keypair = keypair;
}
getSharedRx() {
return this._sharedRx;
}
setSharedRx(sharedRx) {
this._sharedRx = sharedRx;
}
getSharedTx() {
return this._sharedTx;
}
setSharedTx(sharedTx) {
this._sharedTx = sharedTx;
}
getCrypt_o() {
return this._crypt_o;
}
setCrypt_o(crypt_o) {
this._crypt_o = crypt_o;
}
getCrypt_i() {
return this._crypt_i;
}
setCrypt_i(crypt_i) {
this._crypt_i = crypt_i;
}
}
// Export class
export {
ZitiChannel
}
| 29.911975 | 207 | 0.644794 |
c623bfbcf779fb8b1a9c7655bc4719f09c3a9fcb | 121 | js | JavaScript | test/hooks.js | vitalets/bro-fs | da232df3e2a2d0d02e5f67a601e5cb2bbf86ca85 | [
"MIT"
] | 41 | 2016-10-24T14:33:34.000Z | 2022-03-24T18:07:35.000Z | test/hooks.js | vitalets/bro-fs | da232df3e2a2d0d02e5f67a601e5cb2bbf86ca85 | [
"MIT"
] | 10 | 2017-09-19T15:49:49.000Z | 2019-09-19T16:20:50.000Z | test/hooks.js | vitalets/bro-fs | da232df3e2a2d0d02e5f67a601e5cb2bbf86ca85 | [
"MIT"
] | 6 | 2017-08-29T18:53:25.000Z | 2019-03-06T04:43:22.000Z |
before(function () {
return fs.init({type: window.TEMPORARY});
});
beforeEach(function () {
return fs.clear();
});
| 13.444444 | 43 | 0.628099 |
c623ef485a67502264437ef65114f04b98e7680c | 1,049 | js | JavaScript | packages/aquarius/src/global/commands/__test__/ping.test.js | bucket3432/aquarius | 61126a7dfb218e6611e724c26b78faac4ed920f2 | [
"MIT"
] | 60 | 2017-08-13T17:27:53.000Z | 2022-03-17T13:51:42.000Z | packages/aquarius/src/global/commands/__test__/ping.test.js | bucket3432/aquarius | 61126a7dfb218e6611e724c26b78faac4ed920f2 | [
"MIT"
] | 777 | 2016-05-03T03:35:28.000Z | 2022-03-31T23:00:30.000Z | packages/aquarius/src/global/commands/__test__/ping.test.js | bucket3432/aquarius | 61126a7dfb218e6611e724c26b78faac4ed920f2 | [
"MIT"
] | 44 | 2016-05-05T01:24:23.000Z | 2022-03-24T05:30:18.000Z | import { getHandlers, getMatchers } from '@aquarius-bot/testing';
import command from '../ping';
describe('Triggers', () => {
let regex = null;
beforeAll(() => {
// eslint-disable-next-line prefer-destructuring
regex = getMatchers(command)[0];
});
test('Matches Standalone Ping', () => {
expect(regex.test('ping')).toBe(true);
});
test('Does not match a `pin` trigger', () => {
expect(regex.test('pin')).toBe(false);
});
test('Does not match if in phrase', () => {
expect(regex.test('Test Ping')).toBe(false);
expect(regex.test('Test Ping Test')).toBe(false);
});
test('Match is case insensitive', () => {
expect(regex.test('PING')).toBe(true);
expect(regex.test('ping')).toBe(true);
});
});
test('Responds with Pong', () => {
const analytics = { trackUsage: jest.fn() };
const handler = getHandlers(command, { analytics })[0];
const message = {
channel: {
send: jest.fn(),
},
};
handler(message);
expect(message.channel.send).toHaveBeenCalledWith('pong');
});
| 24.395349 | 65 | 0.603432 |
c6241be2f02981a3b8c0f4534129e6de8231d45b | 6,231 | js | JavaScript | ucavatar.js | sfi0zy/ucavatar | 0758384c664db138fb7e7729859d278ba1918f57 | [
"MIT"
] | 15 | 2017-03-12T21:41:20.000Z | 2021-03-22T20:29:38.000Z | ucavatar.js | sfi0zy/ucavatar | 0758384c664db138fb7e7729859d278ba1918f57 | [
"MIT"
] | null | null | null | ucavatar.js | sfi0zy/ucavatar | 0758384c664db138fb7e7729859d278ba1918f57 | [
"MIT"
] | null | null | null | // Ucavatar.js
// Unique avatars generator
//
// Version: 1.0.4
// Author: Ivan Bogachev <sfi0zy@gmail.com>, 2017
// License: MIT
var Ucavatar = (function() {
function strangeHash(str) {
var hash = 0;
if (str.length === 0) {
return hash;
}
for (var i = 0, len = str.length; i < len; i++) {
var chr = str.charCodeAt(i);
hash = ((hash << 5) - hash) + chr;
hash |= 0;
}
return (new Array(9).join('1') + Math.abs(hash)).slice(-8);
}
function getDecimal(num) {
var str = '' + num,
zeroPos = str.indexOf(".");
if (zeroPos == -1) {
return 0;
}
str = str.slice(zeroPos);
return +str;
}
function hslToRgb(h, s, l){
var r, g, b;
if (s == 0){
r = g = b = l;
} else {
var hue2rgb = function(p, q, t) {
if(t < 0) t += 1;
if(t > 1) t -= 1;
if(t < 1/6) return p + (q - p) * 6 * t;
if(t < 1/2) return q;
if(t < 2/3) return p + (q - p) * (2/3 - t) * 6;
return p;
}
var q = l < 0.5 ? l * (1 + s) : l + s - l * s;
var p = 2 * l - q;
r = hue2rgb(p, q, h + 1/3);
g = hue2rgb(p, q, h);
b = hue2rgb(p, q, h - 1/3);
}
return [Math.round(r * 255), Math.round(g * 255), Math.round(b * 255)];
}
function getColorScheme(hash, alpha) {
var colorScheme = [];
var lastH = 0,
lastS = 0,
lastL = 0;
for (var i = 0; i < 4; i++) {
var H = (hash[i]*10 + hash[i+1]) / 1000,
S = hash[i+2] * 0.05 + .5,
L = hash[i+3] * 0.09 + .1,
sign;
if (Math.abs(H - lastH) < .3) {
sign = H > lastH ? 1 : -1;
H = getDecimal(H + sign * .2 + 1);
}
if (Math.abs(S - lastS) < .3) {
sign = S > lastS ? 1 : -1;
S = getDecimal(S + sign * .3 + 1);
}
if (Math.abs(L - lastL) < .3) {
sign = L > lastL ? 1 : -1;
L = getDecimal(L + sign * .3 + 1);
}
var rgb = hslToRgb(H, S, L);
colorScheme.push('rgba(' +
rgb[0] + ',' +
rgb[1] + ',' +
rgb[2] + ',' +
alpha + ')'
);
lastH = H;
lastS = S;
lastL = L;
}
return colorScheme;
}
function getRectCoords(hash, size) {
var coords = [];
for (var i = 4; i < 8; i++) {
var h = hash[i];
if (hash[i] < 0.01) {
h = i;
}
var c = h * size * .03,
c1 = c,
c2 = c,
c3 = c,
c4 = c;
if (2 * c < (size / 2)) {
c1 *= -2;
c2 *= -2;
c3 *= 5;
c4 *= 5;
}
coords.push([c1, c2, c3, c4]);
}
return coords;
}
function drawRects(ctx, colors, coords, s) {
for (var i = 0; i < 4; i++) {
ctx.fillStyle = colors[i];
c = coords[i];
for (var j = 0; j < 2 * s; j++) {
ctx.fillRect(c[0], c[1], c[2], c[3]);
ctx.rotate(Math.PI / s);
}
}
}
function drawCircle(ctx, colors, size) {
ctx.beginPath();
ctx.arc(0, 0, size, 0, 2 * Math.PI, false);
ctx.fillStyle = colors[0];
ctx.fill();
}
function Ucavatar(canvas, str, size) {
if (typeof canvas === 'string') {
canvas = document.querySelector(canvas);
}
if (!canvas || !document.body.contains(canvas)) {
throw new Error('Ucavatar: canvas does not exists');
}
if (!size) {
size = 64;
}
canvas.height = size;
canvas.width = size;
var ctx = canvas.getContext('2d'),
h = strangeHash(str),
colors = getColorScheme(h, .5),
rectCoords = getRectCoords(h, size),
s = h[0] % 5 + 3;
ctx.fillStyle = colors[0];
ctx.fillRect(0, 0, size, size);
ctx.translate(size/2, size/2);
ctx.rotate(h[0] * Math.PI / (h[1] + 1));
drawRects(ctx, colors, getRectCoords(h, size), s);
ctx.rotate(Math.PI / 2);
colors = getColorScheme(h, .8);
drawRects(ctx, colors, getRectCoords(h, size/3), s);
colors = getColorScheme(h, .7);
drawCircle(ctx, colors, size/2);
colors = getColorScheme(h, .8);
drawCircle(ctx, colors, 3);
colors = getColorScheme(h, .8);
drawRects(ctx, colors, getRectCoords(h, size/3), s);
ctx.rotate(Math.PI / 2);
drawCircle(ctx, colors, size/5);
colors = getColorScheme(h, 1);
drawRects(ctx, colors, getRectCoords(h, size/6), s);
ctx.rotate(Math.PI / 2);
drawCircle(ctx, colors, size/8);
drawRects(ctx, colors, getRectCoords(h, size/10), s);
var colors2 = getColorScheme(h, .5);
for (var i = 0; i < s; i++) {
ctx.rotate(2 * Math.PI / s);
ctx.translate(size/4, size/4);
drawRects(ctx, colors, getRectCoords(h, size/(1.7*s)), s);
drawCircle(ctx, colors2, size/(2*s));
drawRects(ctx, colors, getRectCoords(h, size/(3*s)), s);
ctx.translate(-size/4, -size/4);
}
ctx.rotate(Math.PI / s);
for (var i = 0; i < s; i++) {
ctx.rotate(2 * Math.PI / s);
ctx.translate(size/(s*h[0]/10), size/(s*h[0]/10));
drawRects(ctx, colors, getRectCoords(h, size/(3*s)), s);
ctx.translate(-size/(s*h[0]/10), -size/(s*h[0]/10));
}
};
return Ucavatar;
})();
if (typeof module !== 'undefined' && typeof module.exports !== 'undefined') {
module.exports.Ucavatar = Ucavatar;
} else {
window.Ucavatar = Ucavatar;
}
| 25.125 | 79 | 0.411812 |
c62420c348b81a496360bd6b23d45aa44478854e | 1,440 | js | JavaScript | packages/web/.eslintrc.js | hengkx/note | 05be8fed53446d8baa6399baed50aea14e145809 | [
"MIT"
] | 1 | 2017-09-29T07:13:57.000Z | 2017-09-29T07:13:57.000Z | packages/web/.eslintrc.js | hengkx/note | 05be8fed53446d8baa6399baed50aea14e145809 | [
"MIT"
] | null | null | null | packages/web/.eslintrc.js | hengkx/note | 05be8fed53446d8baa6399baed50aea14e145809 | [
"MIT"
] | null | null | null | module.exports = {
"parser": "babel-eslint",
"extends": "airbnb",
"env": {
"browser": true,
"node": true
},
"rules": {
"arrow-parens": ["off"],
"no-script-url": ["off"],
"compat/compat": "error",
"consistent-return": "off",
"comma-dangle": "off",
"generator-star-spacing": "off",
"import/no-unresolved": "error",
"import/no-extraneous-dependencies": "off",
"no-console": "off",
"no-use-before-define": "off",
"no-multi-assign": "off",
"no-underscore-dangle": "off",
"promise/param-names": "error",
"promise/always-return": "error",
"promise/catch-or-return": "error",
"promise/no-native": "off",
"react/sort-comp": ["error", {
"order": ["type-annotations", "static-methods", "lifecycle", "everything-else", "render"]
}],
"jsx-a11y/no-noninteractive-element-interactions": "off",
"jsx-a11y/href-no-hash": "off",
"jsx-a11y/no-static-element-interactions": "off",
"jsx-a11y/no-noninteractive-tabindex": "off",
"react/jsx-no-bind": "off",
"react/require-default-props": "off",
"react/forbid-prop-types": "off",
"react/jsx-filename-extension": ["error", { "extensions": [".js", ".jsx"] }],
"react/prefer-stateless-function": "off",
"react/no-array-index-key": "off",
"quotes": ["error", "single"],
"linebreak-style": 0,
},
"plugins": [
"import",
"promise",
"compat",
"react"
]
}
| 30 | 95 | 0.576389 |
c624a64c765f63cee07c5ab6c57f93d67cdf1d45 | 8,035 | js | JavaScript | src/plugins/UnicornLogCore.js | webdevnerdstuff/vue-unicorn-log | 230d254af30e03ba3cbd6c07335c46e931c6d8a8 | [
"MIT"
] | 6 | 2022-03-22T02:25:32.000Z | 2022-03-28T21:25:57.000Z | src/plugins/UnicornLogCore.js | webdevnerdstuff/vue-unicorn-log | 230d254af30e03ba3cbd6c07335c46e931c6d8a8 | [
"MIT"
] | null | null | null | src/plugins/UnicornLogCore.js | webdevnerdstuff/vue-unicorn-log | 230d254af30e03ba3cbd6c07335c46e931c6d8a8 | [
"MIT"
] | null | null | null | /* eslint-disable no-console */
const rainbowLinearGradient = `linear-gradient(to right,
hsl(0, 100%, 50%),
hsl(39, 100%, 50%),
hsl(60, 100%, 50%),
hsl(120, 100%, 50%),
hsl(180, 100%, 50%),
hsl(240, 100%, 50%),
hsl(300, 100%, 50%),
hsl(360, 100%, 50%)
)`;
const UnicornLog = {
// ========================================== Common Variables //
errors: 0,
logOptions: {},
name: 'UnicornLog',
output: null,
pluginOptions: {},
types: [
'clear',
'count',
'countReset',
'debug',
'dir',
'error',
'group',
'groupCollapsed',
'groupEnd',
'info',
'log',
'table',
'time',
'timeEnd',
'timeLog',
'trace',
'warn',
],
// ===================== Default Styles //
defaultStyles: {
log: [
'background-color: black',
`border-image: ${rainbowLinearGradient} 1`,
'border-style: solid',
'border-width: 4px',
'color: #fff',
'font-weight: normal',
'padding: 8px',
],
info: [
'background-color: hsla(225, 100%, 8%, 1)',
'box-shadow: 999px 0 0 hsla(225, 100%, 8%, 1)',
'color: hsla(225, 100%, 85%, 1)',
'display: block',
'padding: 2px',
],
goNuts: [
`background: ${rainbowLinearGradient}`,
'color: #f7f7f7',
'display: block',
'font-family: "Helvetica", "Arial"',
'font-size: 15px',
'font-weight: bold',
'margin: 5px 0',
'padding: 10px',
'text-shadow: 1px 1px 2px #000',
],
},
// So pretty //
magicalStyleNames: [
'magic',
'magical',
'prism',
'psychedelic',
'rainbow',
'trippy',
'unicorn',
],
// ===================== Default Options //
defaultOptions: {
array: [],
defaultStyles: {},
disabled: true,
logPrefix: false,
magical: false,
name: '[UnicornLog]:',
objects: {},
styles: '',
text: '🦄',
type: 'log',
},
// ========================================== Methods //
// ===================== Init //
init(Vue, pluginOptions = {}, logOptions = {}) {
// Do not run if disabled in the Plugin options //
if (pluginOptions.disabled || logOptions.disabled) {
return false;
}
// Set Options //
this.pluginOptions = pluginOptions;
this.logOptions = { ...this.defaultOptions, ...this.pluginOptions, ...logOptions };
this.defaultStyles = { ...this.defaultStyles, ...this.pluginOptions.defaultStyles, ...logOptions.defaultStyles };
// Run validation functions //
Object.values(this.validateOptions).map((value) => {
if (typeof value === 'function') {
return value.call();
}
return false;
});
// Run Build functions //
Object.values(this.build).map((value) => {
if (typeof value === 'function') {
return value.call();
}
return false;
});
// If errors, don't log //
if (this.errors) {
return false;
}
this.consoleOutput(this.logOptions.type);
return false;
},
// ===================== Validate the options //
validateOptions: {
type() {
const type = UnicornLog.logOptions.type;
const types = UnicornLog.types;
if (!types.includes(type)) {
UnicornLog.errors += 1;
if (type === 'dirXml') {
UnicornLog.logger('console.dir() is not supported console method.', 'warn');
return false;
}
UnicornLog.logger(`console.${type}() is not supported at this time or is not a valid console method.`, 'warn');
return false;
}
return false;
},
styles(value = UnicornLog.logOptions.styles) {
if (!(value instanceof Array) && (typeof value === 'object' || Number.isInteger(value))) {
UnicornLog.logger('The "styles" option is not a String or an Array.', 'error');
}
},
logPrefix(value = UnicornLog.logOptions.logPrefix) {
if (typeof value === 'object' || value instanceof Boolean) {
UnicornLog.logger('The "logPrefix" option is not a string or boolean.', 'error');
}
},
text(value = UnicornLog.logOptions.text) {
if (typeof value !== 'string') {
UnicornLog.logger('The "text" option is not a string.', 'error');
}
},
objects(value = UnicornLog.logOptions.objects) {
if (value instanceof Array || typeof value === 'string' || Number.isInteger(value)) {
UnicornLog.logger('The "objects" option is not an object.', 'error');
}
},
array(value = UnicornLog.logOptions.array) {
if (!(value instanceof Array) || typeof value === 'string' || Number.isInteger(value)) {
UnicornLog.logger('The "array" option is not an array.', 'error');
}
},
},
// ===================== Build stuff //
build: {
// Add Prefix if option set //
prefix() {
const options = UnicornLog.logOptions;
if (options.logPrefix) {
if (typeof options.logPrefix === 'string') {
options.text = `${options.logPrefix} ${options.text}`;
}
else {
options.text = `${options.name} ${options.text}`;
}
}
},
// Build log styles //
styles() {
const options = UnicornLog.logOptions;
let styles = options.styles;
if (styles === false) {
styles = '';
}
// If styles should be magical AF //
else if ((options.type === 'log' || options.type === 'info') && (UnicornLog.magicalStyleNames.includes(options.styles) || options.magical)) {
styles = UnicornLog.defaultStyles.goNuts.join(';');
}
// Styles for info method //
else if ((styles === '' || styles === true) && options.type === 'info') {
styles = UnicornLog.defaultStyles.info.join(';');
}
// Default styles //
else {
styles = styles || UnicornLog.defaultStyles.log.join(';');
}
// If styles is an array, join them //
if (Array.isArray(styles)) {
styles = styles.join(';');
}
options.styles = styles;
},
// Build the output //
output(options = UnicornLog.logOptions) {
const results = ['%c%s', options.styles];
// Build the output results //
if (options.text) {
results.push(options.text);
}
if (options.array.length) {
results.push(options.array);
}
if (Object.keys(options.objects).length) {
results.push(options.objects);
}
UnicornLog.output = results;
},
},
// ========================================== Console Output //
consoleDir() {
const value = {};
if (Object.keys(this.logOptions.objects).length) {
if (Object.keys(this.logOptions.array).length) {
value.objects = this.logOptions.objects;
}
else {
Object.assign(value, this.logOptions.objects);
}
}
if (Object.keys(this.logOptions.array).length) {
if (Object.keys(this.logOptions.objects).length) {
value.array = this.logOptions.array;
}
else {
Object.assign(value, this.logOptions.array);
}
}
if (!Object.keys(value).length) {
return UnicornLog.logger('console.dir() expects the "objects" and/or array option value to be set.', 'error');
}
UnicornLog.logger('console.dir() does not support colors.', 'info');
return value;
},
consoleTable() {
UnicornLog.logger('console.table() does not support colors.', 'info');
return this.logOptions.array;
},
consoleMethodNotSupported(logType) {
this.errors += 1;
UnicornLog.logger(`console.${logType}() does not support colors.`, 'info');
},
// ===================== Make the final magic happen now //
consoleOutput(logType) {
if (logType === 'dir') {
this.output = [this.consoleDir()];
}
if (logType === 'table') {
this.output = [this.consoleTable()];
}
// These methods do not support console colors //
if (logType === 'count' || logType === 'countReset' || logType === 'time' || logType === 'timeEnd' || logType === 'timeLog') {
this.output = [this.consoleMethodNotSupported(logType)];
}
if (!this.errors) {
console[logType](...this.output);
}
},
// ========================================== Unicorn Logger //
logger(msg = 'An error has occurred.', logType = 'log') {
const label = logType.charAt(0).toUpperCase() + logType.slice(1);
let style = '';
if (logType === 'error') {
this.errors += 1;
}
if (logType === 'info') {
style = this.defaultStyles.info.join(';');
}
console[logType]('%c%s', style, `[${UnicornLog.name} ${label}]: ${msg}`);
return false;
},
};
export default UnicornLog;
| 24.422492 | 144 | 0.586185 |
c62547c5e98a15d4e19626f81a56b4a5bd1b7954 | 931 | js | JavaScript | test/test.js | matthewp/child-when | 059db7861dde5ab9f0efa151443ac407c7815c3c | [
"BSD-2-Clause"
] | null | null | null | test/test.js | matthewp/child-when | 059db7861dde5ab9f0efa151443ac407c7815c3c | [
"BSD-2-Clause"
] | 1 | 2016-02-09T13:04:24.000Z | 2016-02-09T13:24:41.000Z | test/test.js | matthewp/child-when | 059db7861dde5ab9f0efa151443ac407c7815c3c | [
"BSD-2-Clause"
] | null | null | null | var test = require("tape");
var spawn = require("child_process").spawn;
var streamWhen = require("../stream-when");
test("Works with functions", function(t){
t.plan(1);
var child = spawn("echo", ["hello"]);
child.stdout.setEncoding("utf8");
var promise = streamWhen(child.stdout, function(data){
return data.trim() === "hello";
});
promise.then(function(){
t.pass("Promise did resolve");
});
});
test("Works with RegExps", function(t){
t.plan(1);
var child = spawn("echo", ["hello"]);
child.stdout.setEncoding("utf8");
var promise = streamWhen(child.stdout, /hello/);
promise.then(function(){
t.pass("Promise did resolve");
});
});
test("Works with strings", function(t){
t.plan(1);
var child = spawn("echo", ["hello"]);
child.stdout.setEncoding("utf8");
var promise = streamWhen(child.stdout, "hello");
promise.then(function(){
t.pass("Promise did resolve");
});
});
| 22.166667 | 56 | 0.632653 |
c625c7a214a0f60b2ebb82cba752e0aac4dbffb1 | 780 | js | JavaScript | build/es6/node_modules/@lrnwebcomponents/elmsln-apps/lib/lrnapp-studio-submission/lrnapp-studio-submission-edit-textarea.js | profmikegreene/HAXcms | 50390c19bc91e49f05038fccb1104707153058f5 | [
"Apache-2.0"
] | 1 | 2019-09-04T20:40:47.000Z | 2019-09-04T20:40:47.000Z | build/es6/node_modules/@lrnwebcomponents/elmsln-apps/lib/lrnapp-studio-submission/lrnapp-studio-submission-edit-textarea.js | profmikegreene/HAXcms | 50390c19bc91e49f05038fccb1104707153058f5 | [
"Apache-2.0"
] | null | null | null | build/es6/node_modules/@lrnwebcomponents/elmsln-apps/lib/lrnapp-studio-submission/lrnapp-studio-submission-edit-textarea.js | profmikegreene/HAXcms | 50390c19bc91e49f05038fccb1104707153058f5 | [
"Apache-2.0"
] | null | null | null | import { html, PolymerElement } from "../../../../@polymer/polymer/polymer-element.js";
import "../../../lrn-markdown-editor/lrn-markdown-editor.js";
class LrnappStudioSubmissionEditTextArea extends PolymerElement {
static get template() {
return html`
<style>
:host {
display: block;
}
</style>
<lrn-markdown-editor content="{{content}}"></lrn-markdown-editor>
`;
}
static get tag() {
return "lrnapp-studio-submission-edit-textarea";
}
static get properties() {
return {
content: {
type: String,
notify: true
}
};
}
}
window.customElements.define(LrnappStudioSubmissionEditTextArea.tag, LrnappStudioSubmissionEditTextArea);
export { LrnappStudioSubmissionEditTextArea }; | 24.375 | 105 | 0.64359 |
c6262c57b2358cb7cf0704c5bae6799dc57ed9ef | 1,783 | js | JavaScript | test/idbobjectstore-query-exception-order.wpt.t.js | micmil1977/indexeddb | ae2c11482282d2fac07d1d9f3ab8a0dfbdf7379b | [
"MIT"
] | 21 | 2016-01-14T20:40:07.000Z | 2022-03-13T07:45:30.000Z | test/idbobjectstore-query-exception-order.wpt.t.js | passariello/indexeddb | 07bbb54222da7ba328697353d06fc19271658171 | [
"MIT"
] | 19 | 2015-10-17T21:42:26.000Z | 2021-07-30T04:20:46.000Z | test/idbobjectstore-query-exception-order.wpt.t.js | passariello/indexeddb | 07bbb54222da7ba328697353d06fc19271658171 | [
"MIT"
] | 3 | 2021-02-02T10:43:11.000Z | 2021-11-28T04:54:15.000Z | require('proof')(12, async okay => {
await require('./harness')(okay, 'idbobjectstore-query-exception-order')
await harness(async function () {
['get',
'getAll',
'getAllKeys',
'count',
'openCursor',
'openKeyCursor'
].forEach(method => {
indexeddb_test(
(t, db) => {
const store = db.createObjectStore('s');
const store2 = db.createObjectStore('s2');
db.deleteObjectStore('s2');
setTimeout(t.step_func(() => {
assert_throws_dom(
'InvalidStateError', () => { store2[method]('key'); },
'"has been deleted" check (InvalidStateError) should precede ' +
'"not active" check (TransactionInactiveError)');
t.done();
}), 0);
},
(t, db) => {},
`IDBObjectStore.${method} exception order: ` +
'InvalidStateError vs. TransactionInactiveError'
);
indexeddb_test(
(t, db) => {
const store = db.createObjectStore('s');
},
(t, db) => {
const tx = db.transaction('s');
const store = tx.objectStore('s');
setTimeout(t.step_func(() => {
assert_throws_dom(
'TransactionInactiveError', () => { store[method]({}); },
'"not active" check (TransactionInactiveError) should precede ' +
'query check (DataError)');
t.done();
}), 0);
},
`IDBObjectStore.${method} exception order: ` +
'TransactionInactiveError vs. DataError'
);
});
})
})
| 31.280702 | 83 | 0.458777 |
c62682c0fbdd1e1a2862761861c3fd7be5b652db | 5,790 | js | JavaScript | components/Ventas/seleccionProducto.js | angelmen/CelFactor-mobile | 77f0b626284e68640e72f7ca7b48cd2d805b614b | [
"MIT"
] | null | null | null | components/Ventas/seleccionProducto.js | angelmen/CelFactor-mobile | 77f0b626284e68640e72f7ca7b48cd2d805b614b | [
"MIT"
] | 4 | 2021-05-11T16:25:17.000Z | 2022-02-27T05:58:11.000Z | components/Ventas/seleccionProducto.js | angelmen/CelFactor-mobile | 77f0b626284e68640e72f7ca7b48cd2d805b614b | [
"MIT"
] | null | null | null | import React, { Component, useState } from 'react';
import {
View,
Text,
FlatList,
TouchableOpacity,
StyleSheet,
ActivityIndicator,
Alert,
AsyncStorage,
ScrollView,
TextInput,
} from 'react-native';
import SearchableDropdown from 'react-native-searchable-dropdown';
import { SearchBar, ListItem } from 'react-native-elements';
import { useIsFocused } from '@react-navigation/native';
import { useNavigation } from '@react-navigation/native';
import { DataTable } from 'react-native-paper';
var count = 0;
function AddToOrders({ item }) {
return (
<View style={{ alignSelf: 'center', zIndex: 100, elevation: 100 }}>
<Text>Agregar a la orden</Text>
<TextInput value={item.description} editable={false} />
<TextInput value={item.unit_price} />
<TextInput placeholder={'Detalles '} />
<TextInput placeholder={'Cantidad '} />
</View>
);
}
function AddProducts() {
const navigation = useNavigation();
navigation.navigate('AddProductsToOrder');
}
export default function Screen({ route, navigation }) {
const isFocused = useIsFocused();
if (isFocused) {
return <SeleccionProducto navigation={navigation}/>;
} else {
return <View />;
}
}
export class SeleccionProducto extends Component {
constructor(props) {
super(props);
this.state = {
serverData: [],
arrayholder: [],
search: '',
isLoading: false,
text: '',
editing: false,
refreshing: false,
error: false,
showItems: true,
orden: [],
};
this.orden = [];
this.navigation = this.props.navigation;
}
render() {
return this.state.isLoading ? (
<View style={{ flex: 1, justifyContent: 'center', alignItems: 'center' }}>
<ActivityIndicator size={'large'} />
</View>
) : (
<View style={styles.container}>
<View
style={{
flex: 1,
flexDirection: 'row',
padding: 5,
justifyContent: 'center',
alignItems: 'center',
}}>
<TouchableOpacity
style={{
paddingVertical: 10,
paddingHorizontal: 10,
backgroundColor: 'red',
marginHorizontal: 10,
borderRadius: 10,
}}
onPress={() => {
this.setState({ orden: [] });
}}>
<Text style={{ color: '#fff' }}>Eliminar orden</Text>
</TouchableOpacity>
<TouchableOpacity
style={{
paddingVertical: 10,
paddingHorizontal: 30,
backgroundColor: 'blue',
marginHorizontal: 10,
borderRadius: 10,
}}
onPress={()=>{alert(this.navigation)}}>
<Text style={{ color: '#fff' }}>Agregar productos</Text>
</TouchableOpacity>
</View>
<View style={{ flex: 6 }}>
<Text
style={{
fontSize: 20,
fontWeight: 'bold',
paddingVertical: 20,
paddingHorizontal: 10,
}}>
Esta venta
</Text>
<DataTable>
<DataTable.Header>
<DataTable.Title>Nombre</DataTable.Title>
<DataTable.Title numeric>Cantidad</DataTable.Title>
<DataTable.Title numeric>Precio</DataTable.Title>
</DataTable.Header>
<ScrollView style={{ maxHeight: 250 }}>
{this.state.orden.map(item => {
return <Product item={item} modal={'orden'} />;
})}
</ScrollView>
</DataTable>
</View>
<View
style={{
flex: 1,
flexDirection: 'row',
padding: 5,
justifyContent: 'center',
alignItems: 'center',
}}>
<TouchableOpacity
style={{
padding: 15,
backgroundColor: 'red',
marginHorizontal: 10,
borderRadius: 10,
}}>
<Text style={{ color: '#fff' }}>cancelar</Text>
</TouchableOpacity>
<TouchableOpacity
style={{
padding: 15,
backgroundColor: 'green',
marginHorizontal: 10,
borderRadius: 10,
}}>
<Text style={{ color: '#fff' }}>Cobrar</Text>
</TouchableOpacity>
</View>
</View>
);
}
}
function Product({ item, modal }) {
if (modal == 'orden') {
return (
<DataTable.Row>
<DataTable.Cell>
<Text style={{ fontSize: 10 }}>{item.description}</Text>
</DataTable.Cell>
<DataTable.Cell numeric>{item.stock}</DataTable.Cell>
<DataTable.Cell numeric>{item.unit_price}</DataTable.Cell>
</DataTable.Row>
);
} else {
return (
<TouchableOpacity style={styles.product}>
<Text style={styles.productDesc}>{item.description}</Text>
<Text style={styles.productDetail}>{'Cantidad: ' + item.stock}</Text>
<Text style={styles.productDetail}>{'Costo: ' + item.cost}</Text>
</TouchableOpacity>
);
}
}
var styles = StyleSheet.create({
container: {
flex: 1,
backgroundColor: '#fff',
},
product: {
alignSelf: 'center',
width: '90%',
borderWidth: 0,
marginVertical: 5,
paddingHorizontal: 10,
paddingVertical: 5,
elevation: 5,
backgroundColor: '#FFF',
shadowColor: 'black',
shadowOffset: { width: 0, height: 2 },
shadowOpacity: 0.3,
shadowRadius: 5,
},
productDesc: {
color: '#6435A6',
fontWeight: 'bold',
fontFamily: 'centuri-gothic',
fontSize: 16,
},
productDetail: {
color: '#B885FF',
fontSize: 12,
},
});
| 26.930233 | 80 | 0.533161 |
c6269e97fbfc30526cf412911b040459017b811c | 615 | js | JavaScript | src/Card.js | tnvr-bhatia/Wikipedia-Viewer | d0b136ca69d79222b42e117c5dc25377437f2a5b | [
"MIT"
] | null | null | null | src/Card.js | tnvr-bhatia/Wikipedia-Viewer | d0b136ca69d79222b42e117c5dc25377437f2a5b | [
"MIT"
] | null | null | null | src/Card.js | tnvr-bhatia/Wikipedia-Viewer | d0b136ca69d79222b42e117c5dc25377437f2a5b | [
"MIT"
] | null | null | null | import React, { Component } from "react";
import "./Card.css";
const PAGE_URL = "https://en.wikipedia.org/?curid=";
class Card extends Component {
render() {
return (
<a
className="card"
href={PAGE_URL + this.props.href}
target="_blank"
rel="noopener noreferrer"
>
{/* <div className="thumbnail">
<img src={this.props.imgSrc} alt="" className="img" />
</div> */}
<div>
<h2>{this.props.title}</h2>
<p className="text-muted">{this.props.extract}</p>
</div>
</a>
);
}
}
export default Card;
| 21.964286 | 64 | 0.530081 |
c6271976d79207849b6531ff692426ac757f3716 | 337 | js | JavaScript | public/assets/js/burger_action.js | anaiva27/Burger-Logger | f6786ddd0119f37835cd09257133f7a92c2a6736 | [
"Unlicense"
] | null | null | null | public/assets/js/burger_action.js | anaiva27/Burger-Logger | f6786ddd0119f37835cd09257133f7a92c2a6736 | [
"Unlicense"
] | null | null | null | public/assets/js/burger_action.js | anaiva27/Burger-Logger | f6786ddd0119f37835cd09257133f7a92c2a6736 | [
"Unlicense"
] | null | null | null | // event for the EAT burger button
$(document).ready(function () {
$(".burger-container").on("click", ".eat-burger-btn", function (event) {
event.preventDefault();
var id = $(this).data("id");
$.ajax(`/burgers/updateOne/${id}`, {
type: "PUT",
}).then(function (data) {
location.reload();
});
});
});
| 24.071429 | 74 | 0.554896 |
c627cdb30e6ce303769cf540dbcb8e15c2110052 | 94,613 | js | JavaScript | node_modules/react-tooltip/standalone/react-tooltip.js | hieudt7/react-sample | 80d630fd2860c994219954d44bc24c6c75b34388 | [
"MIT"
] | 1 | 2020-09-18T19:37:42.000Z | 2020-09-18T19:37:42.000Z | node_modules/react-tooltip/standalone/react-tooltip.js | hieudt7/react-sample | 80d630fd2860c994219954d44bc24c6c75b34388 | [
"MIT"
] | null | null | null | node_modules/react-tooltip/standalone/react-tooltip.js | hieudt7/react-sample | 80d630fd2860c994219954d44bc24c6c75b34388 | [
"MIT"
] | null | null | null | (function(f){if(typeof exports==="object"&&typeof module!=="undefined"){module.exports=f()}else if(typeof define==="function"&&define.amd){define([],f)}else{var g;if(typeof window!=="undefined"){g=window}else if(typeof global!=="undefined"){g=global}else if(typeof self!=="undefined"){g=self}else{g=this}g.ReactTooltip = f()}})(function(){var define,module,exports;return (function(){function r(e,n,t){function o(i,f){if(!n[i]){if(!e[i]){var c="function"==typeof require&&require;if(!f&&c)return c(i,!0);if(u)return u(i,!0);var a=new Error("Cannot find module '"+i+"'");throw a.code="MODULE_NOT_FOUND",a}var p=n[i]={exports:{}};e[i][0].call(p.exports,function(r){var n=e[i][1][r];return o(n||r)},p,p.exports,r,e,n,t)}return n[i].exports}for(var u="function"==typeof require&&require,i=0;i<t.length;i++)o(t[i]);return o}return r})()({1:[function(require,module,exports){
/*!
Copyright (c) 2016 Jed Watson.
Licensed under the MIT License (MIT), see
http://jedwatson.github.io/classnames
*/
/* global define */
(function () {
'use strict';
var hasOwn = {}.hasOwnProperty;
function classNames () {
var classes = [];
for (var i = 0; i < arguments.length; i++) {
var arg = arguments[i];
if (!arg) continue;
var argType = typeof arg;
if (argType === 'string' || argType === 'number') {
classes.push(arg);
} else if (Array.isArray(arg)) {
classes.push(classNames.apply(null, arg));
} else if (argType === 'object') {
for (var key in arg) {
if (hasOwn.call(arg, key) && arg[key]) {
classes.push(key);
}
}
}
}
return classes.join(' ');
}
if (typeof module !== 'undefined' && module.exports) {
module.exports = classNames;
} else if (typeof define === 'function' && typeof define.amd === 'object' && define.amd) {
// register as 'classnames', consistent with npm package name
define('classnames', [], function () {
return classNames;
});
} else {
window.classNames = classNames;
}
}());
},{}],2:[function(require,module,exports){
"use strict";
/**
* Copyright (c) 2013-present, Facebook, Inc.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*
*
*/
function makeEmptyFunction(arg) {
return function () {
return arg;
};
}
/**
* This function accepts and discards inputs; it has no side effects. This is
* primarily useful idiomatically for overridable function endpoints which
* always need to be callable, since JS lacks a null-call idiom ala Cocoa.
*/
var emptyFunction = function emptyFunction() {};
emptyFunction.thatReturns = makeEmptyFunction;
emptyFunction.thatReturnsFalse = makeEmptyFunction(false);
emptyFunction.thatReturnsTrue = makeEmptyFunction(true);
emptyFunction.thatReturnsNull = makeEmptyFunction(null);
emptyFunction.thatReturnsThis = function () {
return this;
};
emptyFunction.thatReturnsArgument = function (arg) {
return arg;
};
module.exports = emptyFunction;
},{}],3:[function(require,module,exports){
(function (process){
/**
* Copyright (c) 2013-present, Facebook, Inc.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*
*/
'use strict';
/**
* Use invariant() to assert state which your program assumes to be true.
*
* Provide sprintf-style format (only %s is supported) and arguments
* to provide information about what broke and what you were
* expecting.
*
* The invariant message will be stripped in production, but the invariant
* will remain to ensure logic does not differ in production.
*/
var validateFormat = function validateFormat(format) {};
if (process.env.NODE_ENV !== 'production') {
validateFormat = function validateFormat(format) {
if (format === undefined) {
throw new Error('invariant requires an error message argument');
}
};
}
function invariant(condition, format, a, b, c, d, e, f) {
validateFormat(format);
if (!condition) {
var error;
if (format === undefined) {
error = new Error('Minified exception occurred; use the non-minified dev environment ' + 'for the full error message and additional helpful warnings.');
} else {
var args = [a, b, c, d, e, f];
var argIndex = 0;
error = new Error(format.replace(/%s/g, function () {
return args[argIndex++];
}));
error.name = 'Invariant Violation';
}
error.framesToPop = 1; // we don't care about invariant's own frame
throw error;
}
}
module.exports = invariant;
}).call(this,require('_process'))
},{"_process":6}],4:[function(require,module,exports){
(function (process){
/**
* Copyright (c) 2014-present, Facebook, Inc.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*
*/
'use strict';
var emptyFunction = require('./emptyFunction');
/**
* Similar to invariant but only logs a warning if the condition is not met.
* This can be used to log issues in development environments in critical
* paths. Removing the logging code for production environments will keep the
* same logic and follow the same code paths.
*/
var warning = emptyFunction;
if (process.env.NODE_ENV !== 'production') {
var printWarning = function printWarning(format) {
for (var _len = arguments.length, args = Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) {
args[_key - 1] = arguments[_key];
}
var argIndex = 0;
var message = 'Warning: ' + format.replace(/%s/g, function () {
return args[argIndex++];
});
if (typeof console !== 'undefined') {
console.error(message);
}
try {
// --- Welcome to debugging React ---
// This error was thrown as a convenience so that you can use this stack
// to find the callsite that caused this warning to fire.
throw new Error(message);
} catch (x) {}
};
warning = function warning(condition, format) {
if (format === undefined) {
throw new Error('`warning(condition, format, ...args)` requires a warning ' + 'message argument');
}
if (format.indexOf('Failed Composite propType: ') === 0) {
return; // Ignore CompositeComponent proptype check.
}
if (!condition) {
for (var _len2 = arguments.length, args = Array(_len2 > 2 ? _len2 - 2 : 0), _key2 = 2; _key2 < _len2; _key2++) {
args[_key2 - 2] = arguments[_key2];
}
printWarning.apply(undefined, [format].concat(args));
}
};
}
module.exports = warning;
}).call(this,require('_process'))
},{"./emptyFunction":2,"_process":6}],5:[function(require,module,exports){
/*
object-assign
(c) Sindre Sorhus
@license MIT
*/
'use strict';
/* eslint-disable no-unused-vars */
var getOwnPropertySymbols = Object.getOwnPropertySymbols;
var hasOwnProperty = Object.prototype.hasOwnProperty;
var propIsEnumerable = Object.prototype.propertyIsEnumerable;
function toObject(val) {
if (val === null || val === undefined) {
throw new TypeError('Object.assign cannot be called with null or undefined');
}
return Object(val);
}
function shouldUseNative() {
try {
if (!Object.assign) {
return false;
}
// Detect buggy property enumeration order in older V8 versions.
// https://bugs.chromium.org/p/v8/issues/detail?id=4118
var test1 = new String('abc'); // eslint-disable-line no-new-wrappers
test1[5] = 'de';
if (Object.getOwnPropertyNames(test1)[0] === '5') {
return false;
}
// https://bugs.chromium.org/p/v8/issues/detail?id=3056
var test2 = {};
for (var i = 0; i < 10; i++) {
test2['_' + String.fromCharCode(i)] = i;
}
var order2 = Object.getOwnPropertyNames(test2).map(function (n) {
return test2[n];
});
if (order2.join('') !== '0123456789') {
return false;
}
// https://bugs.chromium.org/p/v8/issues/detail?id=3056
var test3 = {};
'abcdefghijklmnopqrst'.split('').forEach(function (letter) {
test3[letter] = letter;
});
if (Object.keys(Object.assign({}, test3)).join('') !==
'abcdefghijklmnopqrst') {
return false;
}
return true;
} catch (err) {
// We don't expect any of the above to throw, but better to be safe.
return false;
}
}
module.exports = shouldUseNative() ? Object.assign : function (target, source) {
var from;
var to = toObject(target);
var symbols;
for (var s = 1; s < arguments.length; s++) {
from = Object(arguments[s]);
for (var key in from) {
if (hasOwnProperty.call(from, key)) {
to[key] = from[key];
}
}
if (getOwnPropertySymbols) {
symbols = getOwnPropertySymbols(from);
for (var i = 0; i < symbols.length; i++) {
if (propIsEnumerable.call(from, symbols[i])) {
to[symbols[i]] = from[symbols[i]];
}
}
}
}
return to;
};
},{}],6:[function(require,module,exports){
// shim for using process in browser
var process = module.exports = {};
// cached from whatever global is present so that test runners that stub it
// don't break things. But we need to wrap it in a try catch in case it is
// wrapped in strict mode code which doesn't define any globals. It's inside a
// function because try/catches deoptimize in certain engines.
var cachedSetTimeout;
var cachedClearTimeout;
function defaultSetTimout() {
throw new Error('setTimeout has not been defined');
}
function defaultClearTimeout () {
throw new Error('clearTimeout has not been defined');
}
(function () {
try {
if (typeof setTimeout === 'function') {
cachedSetTimeout = setTimeout;
} else {
cachedSetTimeout = defaultSetTimout;
}
} catch (e) {
cachedSetTimeout = defaultSetTimout;
}
try {
if (typeof clearTimeout === 'function') {
cachedClearTimeout = clearTimeout;
} else {
cachedClearTimeout = defaultClearTimeout;
}
} catch (e) {
cachedClearTimeout = defaultClearTimeout;
}
} ())
function runTimeout(fun) {
if (cachedSetTimeout === setTimeout) {
//normal enviroments in sane situations
return setTimeout(fun, 0);
}
// if setTimeout wasn't available but was latter defined
if ((cachedSetTimeout === defaultSetTimout || !cachedSetTimeout) && setTimeout) {
cachedSetTimeout = setTimeout;
return setTimeout(fun, 0);
}
try {
// when when somebody has screwed with setTimeout but no I.E. maddness
return cachedSetTimeout(fun, 0);
} catch(e){
try {
// When we are in I.E. but the script has been evaled so I.E. doesn't trust the global object when called normally
return cachedSetTimeout.call(null, fun, 0);
} catch(e){
// same as above but when it's a version of I.E. that must have the global object for 'this', hopfully our context correct otherwise it will throw a global error
return cachedSetTimeout.call(this, fun, 0);
}
}
}
function runClearTimeout(marker) {
if (cachedClearTimeout === clearTimeout) {
//normal enviroments in sane situations
return clearTimeout(marker);
}
// if clearTimeout wasn't available but was latter defined
if ((cachedClearTimeout === defaultClearTimeout || !cachedClearTimeout) && clearTimeout) {
cachedClearTimeout = clearTimeout;
return clearTimeout(marker);
}
try {
// when when somebody has screwed with setTimeout but no I.E. maddness
return cachedClearTimeout(marker);
} catch (e){
try {
// When we are in I.E. but the script has been evaled so I.E. doesn't trust the global object when called normally
return cachedClearTimeout.call(null, marker);
} catch (e){
// same as above but when it's a version of I.E. that must have the global object for 'this', hopfully our context correct otherwise it will throw a global error.
// Some versions of I.E. have different rules for clearTimeout vs setTimeout
return cachedClearTimeout.call(this, marker);
}
}
}
var queue = [];
var draining = false;
var currentQueue;
var queueIndex = -1;
function cleanUpNextTick() {
if (!draining || !currentQueue) {
return;
}
draining = false;
if (currentQueue.length) {
queue = currentQueue.concat(queue);
} else {
queueIndex = -1;
}
if (queue.length) {
drainQueue();
}
}
function drainQueue() {
if (draining) {
return;
}
var timeout = runTimeout(cleanUpNextTick);
draining = true;
var len = queue.length;
while(len) {
currentQueue = queue;
queue = [];
while (++queueIndex < len) {
if (currentQueue) {
currentQueue[queueIndex].run();
}
}
queueIndex = -1;
len = queue.length;
}
currentQueue = null;
draining = false;
runClearTimeout(timeout);
}
process.nextTick = function (fun) {
var args = new Array(arguments.length - 1);
if (arguments.length > 1) {
for (var i = 1; i < arguments.length; i++) {
args[i - 1] = arguments[i];
}
}
queue.push(new Item(fun, args));
if (queue.length === 1 && !draining) {
runTimeout(drainQueue);
}
};
// v8 likes predictible objects
function Item(fun, array) {
this.fun = fun;
this.array = array;
}
Item.prototype.run = function () {
this.fun.apply(null, this.array);
};
process.title = 'browser';
process.browser = true;
process.env = {};
process.argv = [];
process.version = ''; // empty string to avoid regexp issues
process.versions = {};
function noop() {}
process.on = noop;
process.addListener = noop;
process.once = noop;
process.off = noop;
process.removeListener = noop;
process.removeAllListeners = noop;
process.emit = noop;
process.prependListener = noop;
process.prependOnceListener = noop;
process.listeners = function (name) { return [] }
process.binding = function (name) {
throw new Error('process.binding is not supported');
};
process.cwd = function () { return '/' };
process.chdir = function (dir) {
throw new Error('process.chdir is not supported');
};
process.umask = function() { return 0; };
},{}],7:[function(require,module,exports){
(function (process){
/**
* Copyright (c) 2013-present, Facebook, Inc.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
'use strict';
if (process.env.NODE_ENV !== 'production') {
var invariant = require('fbjs/lib/invariant');
var warning = require('fbjs/lib/warning');
var ReactPropTypesSecret = require('./lib/ReactPropTypesSecret');
var loggedTypeFailures = {};
}
/**
* Assert that the values match with the type specs.
* Error messages are memorized and will only be shown once.
*
* @param {object} typeSpecs Map of name to a ReactPropType
* @param {object} values Runtime values that need to be type-checked
* @param {string} location e.g. "prop", "context", "child context"
* @param {string} componentName Name of the component for error messages.
* @param {?Function} getStack Returns the component stack.
* @private
*/
function checkPropTypes(typeSpecs, values, location, componentName, getStack) {
if (process.env.NODE_ENV !== 'production') {
for (var typeSpecName in typeSpecs) {
if (typeSpecs.hasOwnProperty(typeSpecName)) {
var error;
// Prop type validation may throw. In case they do, we don't want to
// fail the render phase where it didn't fail before. So we log it.
// After these have been cleaned up, we'll let them throw.
try {
// This is intentionally an invariant that gets caught. It's the same
// behavior as without this statement except with a better message.
invariant(typeof typeSpecs[typeSpecName] === 'function', '%s: %s type `%s` is invalid; it must be a function, usually from ' + 'the `prop-types` package, but received `%s`.', componentName || 'React class', location, typeSpecName, typeof typeSpecs[typeSpecName]);
error = typeSpecs[typeSpecName](values, typeSpecName, componentName, location, null, ReactPropTypesSecret);
} catch (ex) {
error = ex;
}
warning(!error || error instanceof Error, '%s: type specification of %s `%s` is invalid; the type checker ' + 'function must return `null` or an `Error` but returned a %s. ' + 'You may have forgotten to pass an argument to the type checker ' + 'creator (arrayOf, instanceOf, objectOf, oneOf, oneOfType, and ' + 'shape all require an argument).', componentName || 'React class', location, typeSpecName, typeof error);
if (error instanceof Error && !(error.message in loggedTypeFailures)) {
// Only monitor this failure once because there tends to be a lot of the
// same error.
loggedTypeFailures[error.message] = true;
var stack = getStack ? getStack() : '';
warning(false, 'Failed %s type: %s%s', location, error.message, stack != null ? stack : '');
}
}
}
}
}
module.exports = checkPropTypes;
}).call(this,require('_process'))
},{"./lib/ReactPropTypesSecret":11,"_process":6,"fbjs/lib/invariant":3,"fbjs/lib/warning":4}],8:[function(require,module,exports){
/**
* Copyright (c) 2013-present, Facebook, Inc.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
'use strict';
var emptyFunction = require('fbjs/lib/emptyFunction');
var invariant = require('fbjs/lib/invariant');
var ReactPropTypesSecret = require('./lib/ReactPropTypesSecret');
module.exports = function() {
function shim(props, propName, componentName, location, propFullName, secret) {
if (secret === ReactPropTypesSecret) {
// It is still safe when called from React.
return;
}
invariant(
false,
'Calling PropTypes validators directly is not supported by the `prop-types` package. ' +
'Use PropTypes.checkPropTypes() to call them. ' +
'Read more at http://fb.me/use-check-prop-types'
);
};
shim.isRequired = shim;
function getShim() {
return shim;
};
// Important!
// Keep this list in sync with production version in `./factoryWithTypeCheckers.js`.
var ReactPropTypes = {
array: shim,
bool: shim,
func: shim,
number: shim,
object: shim,
string: shim,
symbol: shim,
any: shim,
arrayOf: getShim,
element: shim,
instanceOf: getShim,
node: shim,
objectOf: getShim,
oneOf: getShim,
oneOfType: getShim,
shape: getShim,
exact: getShim
};
ReactPropTypes.checkPropTypes = emptyFunction;
ReactPropTypes.PropTypes = ReactPropTypes;
return ReactPropTypes;
};
},{"./lib/ReactPropTypesSecret":11,"fbjs/lib/emptyFunction":2,"fbjs/lib/invariant":3}],9:[function(require,module,exports){
(function (process){
/**
* Copyright (c) 2013-present, Facebook, Inc.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
'use strict';
var emptyFunction = require('fbjs/lib/emptyFunction');
var invariant = require('fbjs/lib/invariant');
var warning = require('fbjs/lib/warning');
var assign = require('object-assign');
var ReactPropTypesSecret = require('./lib/ReactPropTypesSecret');
var checkPropTypes = require('./checkPropTypes');
module.exports = function(isValidElement, throwOnDirectAccess) {
/* global Symbol */
var ITERATOR_SYMBOL = typeof Symbol === 'function' && Symbol.iterator;
var FAUX_ITERATOR_SYMBOL = '@@iterator'; // Before Symbol spec.
/**
* Returns the iterator method function contained on the iterable object.
*
* Be sure to invoke the function with the iterable as context:
*
* var iteratorFn = getIteratorFn(myIterable);
* if (iteratorFn) {
* var iterator = iteratorFn.call(myIterable);
* ...
* }
*
* @param {?object} maybeIterable
* @return {?function}
*/
function getIteratorFn(maybeIterable) {
var iteratorFn = maybeIterable && (ITERATOR_SYMBOL && maybeIterable[ITERATOR_SYMBOL] || maybeIterable[FAUX_ITERATOR_SYMBOL]);
if (typeof iteratorFn === 'function') {
return iteratorFn;
}
}
/**
* Collection of methods that allow declaration and validation of props that are
* supplied to React components. Example usage:
*
* var Props = require('ReactPropTypes');
* var MyArticle = React.createClass({
* propTypes: {
* // An optional string prop named "description".
* description: Props.string,
*
* // A required enum prop named "category".
* category: Props.oneOf(['News','Photos']).isRequired,
*
* // A prop named "dialog" that requires an instance of Dialog.
* dialog: Props.instanceOf(Dialog).isRequired
* },
* render: function() { ... }
* });
*
* A more formal specification of how these methods are used:
*
* type := array|bool|func|object|number|string|oneOf([...])|instanceOf(...)
* decl := ReactPropTypes.{type}(.isRequired)?
*
* Each and every declaration produces a function with the same signature. This
* allows the creation of custom validation functions. For example:
*
* var MyLink = React.createClass({
* propTypes: {
* // An optional string or URI prop named "href".
* href: function(props, propName, componentName) {
* var propValue = props[propName];
* if (propValue != null && typeof propValue !== 'string' &&
* !(propValue instanceof URI)) {
* return new Error(
* 'Expected a string or an URI for ' + propName + ' in ' +
* componentName
* );
* }
* }
* },
* render: function() {...}
* });
*
* @internal
*/
var ANONYMOUS = '<<anonymous>>';
// Important!
// Keep this list in sync with production version in `./factoryWithThrowingShims.js`.
var ReactPropTypes = {
array: createPrimitiveTypeChecker('array'),
bool: createPrimitiveTypeChecker('boolean'),
func: createPrimitiveTypeChecker('function'),
number: createPrimitiveTypeChecker('number'),
object: createPrimitiveTypeChecker('object'),
string: createPrimitiveTypeChecker('string'),
symbol: createPrimitiveTypeChecker('symbol'),
any: createAnyTypeChecker(),
arrayOf: createArrayOfTypeChecker,
element: createElementTypeChecker(),
instanceOf: createInstanceTypeChecker,
node: createNodeChecker(),
objectOf: createObjectOfTypeChecker,
oneOf: createEnumTypeChecker,
oneOfType: createUnionTypeChecker,
shape: createShapeTypeChecker,
exact: createStrictShapeTypeChecker,
};
/**
* inlined Object.is polyfill to avoid requiring consumers ship their own
* https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/is
*/
/*eslint-disable no-self-compare*/
function is(x, y) {
// SameValue algorithm
if (x === y) {
// Steps 1-5, 7-10
// Steps 6.b-6.e: +0 != -0
return x !== 0 || 1 / x === 1 / y;
} else {
// Step 6.a: NaN == NaN
return x !== x && y !== y;
}
}
/*eslint-enable no-self-compare*/
/**
* We use an Error-like object for backward compatibility as people may call
* PropTypes directly and inspect their output. However, we don't use real
* Errors anymore. We don't inspect their stack anyway, and creating them
* is prohibitively expensive if they are created too often, such as what
* happens in oneOfType() for any type before the one that matched.
*/
function PropTypeError(message) {
this.message = message;
this.stack = '';
}
// Make `instanceof Error` still work for returned errors.
PropTypeError.prototype = Error.prototype;
function createChainableTypeChecker(validate) {
if (process.env.NODE_ENV !== 'production') {
var manualPropTypeCallCache = {};
var manualPropTypeWarningCount = 0;
}
function checkType(isRequired, props, propName, componentName, location, propFullName, secret) {
componentName = componentName || ANONYMOUS;
propFullName = propFullName || propName;
if (secret !== ReactPropTypesSecret) {
if (throwOnDirectAccess) {
// New behavior only for users of `prop-types` package
invariant(
false,
'Calling PropTypes validators directly is not supported by the `prop-types` package. ' +
'Use `PropTypes.checkPropTypes()` to call them. ' +
'Read more at http://fb.me/use-check-prop-types'
);
} else if (process.env.NODE_ENV !== 'production' && typeof console !== 'undefined') {
// Old behavior for people using React.PropTypes
var cacheKey = componentName + ':' + propName;
if (
!manualPropTypeCallCache[cacheKey] &&
// Avoid spamming the console because they are often not actionable except for lib authors
manualPropTypeWarningCount < 3
) {
warning(
false,
'You are manually calling a React.PropTypes validation ' +
'function for the `%s` prop on `%s`. This is deprecated ' +
'and will throw in the standalone `prop-types` package. ' +
'You may be seeing this warning due to a third-party PropTypes ' +
'library. See https://fb.me/react-warning-dont-call-proptypes ' + 'for details.',
propFullName,
componentName
);
manualPropTypeCallCache[cacheKey] = true;
manualPropTypeWarningCount++;
}
}
}
if (props[propName] == null) {
if (isRequired) {
if (props[propName] === null) {
return new PropTypeError('The ' + location + ' `' + propFullName + '` is marked as required ' + ('in `' + componentName + '`, but its value is `null`.'));
}
return new PropTypeError('The ' + location + ' `' + propFullName + '` is marked as required in ' + ('`' + componentName + '`, but its value is `undefined`.'));
}
return null;
} else {
return validate(props, propName, componentName, location, propFullName);
}
}
var chainedCheckType = checkType.bind(null, false);
chainedCheckType.isRequired = checkType.bind(null, true);
return chainedCheckType;
}
function createPrimitiveTypeChecker(expectedType) {
function validate(props, propName, componentName, location, propFullName, secret) {
var propValue = props[propName];
var propType = getPropType(propValue);
if (propType !== expectedType) {
// `propValue` being instance of, say, date/regexp, pass the 'object'
// check, but we can offer a more precise error message here rather than
// 'of type `object`'.
var preciseType = getPreciseType(propValue);
return new PropTypeError('Invalid ' + location + ' `' + propFullName + '` of type ' + ('`' + preciseType + '` supplied to `' + componentName + '`, expected ') + ('`' + expectedType + '`.'));
}
return null;
}
return createChainableTypeChecker(validate);
}
function createAnyTypeChecker() {
return createChainableTypeChecker(emptyFunction.thatReturnsNull);
}
function createArrayOfTypeChecker(typeChecker) {
function validate(props, propName, componentName, location, propFullName) {
if (typeof typeChecker !== 'function') {
return new PropTypeError('Property `' + propFullName + '` of component `' + componentName + '` has invalid PropType notation inside arrayOf.');
}
var propValue = props[propName];
if (!Array.isArray(propValue)) {
var propType = getPropType(propValue);
return new PropTypeError('Invalid ' + location + ' `' + propFullName + '` of type ' + ('`' + propType + '` supplied to `' + componentName + '`, expected an array.'));
}
for (var i = 0; i < propValue.length; i++) {
var error = typeChecker(propValue, i, componentName, location, propFullName + '[' + i + ']', ReactPropTypesSecret);
if (error instanceof Error) {
return error;
}
}
return null;
}
return createChainableTypeChecker(validate);
}
function createElementTypeChecker() {
function validate(props, propName, componentName, location, propFullName) {
var propValue = props[propName];
if (!isValidElement(propValue)) {
var propType = getPropType(propValue);
return new PropTypeError('Invalid ' + location + ' `' + propFullName + '` of type ' + ('`' + propType + '` supplied to `' + componentName + '`, expected a single ReactElement.'));
}
return null;
}
return createChainableTypeChecker(validate);
}
function createInstanceTypeChecker(expectedClass) {
function validate(props, propName, componentName, location, propFullName) {
if (!(props[propName] instanceof expectedClass)) {
var expectedClassName = expectedClass.name || ANONYMOUS;
var actualClassName = getClassName(props[propName]);
return new PropTypeError('Invalid ' + location + ' `' + propFullName + '` of type ' + ('`' + actualClassName + '` supplied to `' + componentName + '`, expected ') + ('instance of `' + expectedClassName + '`.'));
}
return null;
}
return createChainableTypeChecker(validate);
}
function createEnumTypeChecker(expectedValues) {
if (!Array.isArray(expectedValues)) {
process.env.NODE_ENV !== 'production' ? warning(false, 'Invalid argument supplied to oneOf, expected an instance of array.') : void 0;
return emptyFunction.thatReturnsNull;
}
function validate(props, propName, componentName, location, propFullName) {
var propValue = props[propName];
for (var i = 0; i < expectedValues.length; i++) {
if (is(propValue, expectedValues[i])) {
return null;
}
}
var valuesString = JSON.stringify(expectedValues);
return new PropTypeError('Invalid ' + location + ' `' + propFullName + '` of value `' + propValue + '` ' + ('supplied to `' + componentName + '`, expected one of ' + valuesString + '.'));
}
return createChainableTypeChecker(validate);
}
function createObjectOfTypeChecker(typeChecker) {
function validate(props, propName, componentName, location, propFullName) {
if (typeof typeChecker !== 'function') {
return new PropTypeError('Property `' + propFullName + '` of component `' + componentName + '` has invalid PropType notation inside objectOf.');
}
var propValue = props[propName];
var propType = getPropType(propValue);
if (propType !== 'object') {
return new PropTypeError('Invalid ' + location + ' `' + propFullName + '` of type ' + ('`' + propType + '` supplied to `' + componentName + '`, expected an object.'));
}
for (var key in propValue) {
if (propValue.hasOwnProperty(key)) {
var error = typeChecker(propValue, key, componentName, location, propFullName + '.' + key, ReactPropTypesSecret);
if (error instanceof Error) {
return error;
}
}
}
return null;
}
return createChainableTypeChecker(validate);
}
function createUnionTypeChecker(arrayOfTypeCheckers) {
if (!Array.isArray(arrayOfTypeCheckers)) {
process.env.NODE_ENV !== 'production' ? warning(false, 'Invalid argument supplied to oneOfType, expected an instance of array.') : void 0;
return emptyFunction.thatReturnsNull;
}
for (var i = 0; i < arrayOfTypeCheckers.length; i++) {
var checker = arrayOfTypeCheckers[i];
if (typeof checker !== 'function') {
warning(
false,
'Invalid argument supplied to oneOfType. Expected an array of check functions, but ' +
'received %s at index %s.',
getPostfixForTypeWarning(checker),
i
);
return emptyFunction.thatReturnsNull;
}
}
function validate(props, propName, componentName, location, propFullName) {
for (var i = 0; i < arrayOfTypeCheckers.length; i++) {
var checker = arrayOfTypeCheckers[i];
if (checker(props, propName, componentName, location, propFullName, ReactPropTypesSecret) == null) {
return null;
}
}
return new PropTypeError('Invalid ' + location + ' `' + propFullName + '` supplied to ' + ('`' + componentName + '`.'));
}
return createChainableTypeChecker(validate);
}
function createNodeChecker() {
function validate(props, propName, componentName, location, propFullName) {
if (!isNode(props[propName])) {
return new PropTypeError('Invalid ' + location + ' `' + propFullName + '` supplied to ' + ('`' + componentName + '`, expected a ReactNode.'));
}
return null;
}
return createChainableTypeChecker(validate);
}
function createShapeTypeChecker(shapeTypes) {
function validate(props, propName, componentName, location, propFullName) {
var propValue = props[propName];
var propType = getPropType(propValue);
if (propType !== 'object') {
return new PropTypeError('Invalid ' + location + ' `' + propFullName + '` of type `' + propType + '` ' + ('supplied to `' + componentName + '`, expected `object`.'));
}
for (var key in shapeTypes) {
var checker = shapeTypes[key];
if (!checker) {
continue;
}
var error = checker(propValue, key, componentName, location, propFullName + '.' + key, ReactPropTypesSecret);
if (error) {
return error;
}
}
return null;
}
return createChainableTypeChecker(validate);
}
function createStrictShapeTypeChecker(shapeTypes) {
function validate(props, propName, componentName, location, propFullName) {
var propValue = props[propName];
var propType = getPropType(propValue);
if (propType !== 'object') {
return new PropTypeError('Invalid ' + location + ' `' + propFullName + '` of type `' + propType + '` ' + ('supplied to `' + componentName + '`, expected `object`.'));
}
// We need to check all keys in case some are required but missing from
// props.
var allKeys = assign({}, props[propName], shapeTypes);
for (var key in allKeys) {
var checker = shapeTypes[key];
if (!checker) {
return new PropTypeError(
'Invalid ' + location + ' `' + propFullName + '` key `' + key + '` supplied to `' + componentName + '`.' +
'\nBad object: ' + JSON.stringify(props[propName], null, ' ') +
'\nValid keys: ' + JSON.stringify(Object.keys(shapeTypes), null, ' ')
);
}
var error = checker(propValue, key, componentName, location, propFullName + '.' + key, ReactPropTypesSecret);
if (error) {
return error;
}
}
return null;
}
return createChainableTypeChecker(validate);
}
function isNode(propValue) {
switch (typeof propValue) {
case 'number':
case 'string':
case 'undefined':
return true;
case 'boolean':
return !propValue;
case 'object':
if (Array.isArray(propValue)) {
return propValue.every(isNode);
}
if (propValue === null || isValidElement(propValue)) {
return true;
}
var iteratorFn = getIteratorFn(propValue);
if (iteratorFn) {
var iterator = iteratorFn.call(propValue);
var step;
if (iteratorFn !== propValue.entries) {
while (!(step = iterator.next()).done) {
if (!isNode(step.value)) {
return false;
}
}
} else {
// Iterator will provide entry [k,v] tuples rather than values.
while (!(step = iterator.next()).done) {
var entry = step.value;
if (entry) {
if (!isNode(entry[1])) {
return false;
}
}
}
}
} else {
return false;
}
return true;
default:
return false;
}
}
function isSymbol(propType, propValue) {
// Native Symbol.
if (propType === 'symbol') {
return true;
}
// 19.4.3.5 Symbol.prototype[@@toStringTag] === 'Symbol'
if (propValue['@@toStringTag'] === 'Symbol') {
return true;
}
// Fallback for non-spec compliant Symbols which are polyfilled.
if (typeof Symbol === 'function' && propValue instanceof Symbol) {
return true;
}
return false;
}
// Equivalent of `typeof` but with special handling for array and regexp.
function getPropType(propValue) {
var propType = typeof propValue;
if (Array.isArray(propValue)) {
return 'array';
}
if (propValue instanceof RegExp) {
// Old webkits (at least until Android 4.0) return 'function' rather than
// 'object' for typeof a RegExp. We'll normalize this here so that /bla/
// passes PropTypes.object.
return 'object';
}
if (isSymbol(propType, propValue)) {
return 'symbol';
}
return propType;
}
// This handles more types than `getPropType`. Only used for error messages.
// See `createPrimitiveTypeChecker`.
function getPreciseType(propValue) {
if (typeof propValue === 'undefined' || propValue === null) {
return '' + propValue;
}
var propType = getPropType(propValue);
if (propType === 'object') {
if (propValue instanceof Date) {
return 'date';
} else if (propValue instanceof RegExp) {
return 'regexp';
}
}
return propType;
}
// Returns a string that is postfixed to a warning about an invalid type.
// For example, "undefined" or "of type array"
function getPostfixForTypeWarning(value) {
var type = getPreciseType(value);
switch (type) {
case 'array':
case 'object':
return 'an ' + type;
case 'boolean':
case 'date':
case 'regexp':
return 'a ' + type;
default:
return type;
}
}
// Returns class name of the object, if any.
function getClassName(propValue) {
if (!propValue.constructor || !propValue.constructor.name) {
return ANONYMOUS;
}
return propValue.constructor.name;
}
ReactPropTypes.checkPropTypes = checkPropTypes;
ReactPropTypes.PropTypes = ReactPropTypes;
return ReactPropTypes;
};
}).call(this,require('_process'))
},{"./checkPropTypes":7,"./lib/ReactPropTypesSecret":11,"_process":6,"fbjs/lib/emptyFunction":2,"fbjs/lib/invariant":3,"fbjs/lib/warning":4,"object-assign":5}],10:[function(require,module,exports){
(function (process){
/**
* Copyright (c) 2013-present, Facebook, Inc.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
if (process.env.NODE_ENV !== 'production') {
var REACT_ELEMENT_TYPE = (typeof Symbol === 'function' &&
Symbol.for &&
Symbol.for('react.element')) ||
0xeac7;
var isValidElement = function(object) {
return typeof object === 'object' &&
object !== null &&
object.$$typeof === REACT_ELEMENT_TYPE;
};
// By explicitly using `prop-types` you are opting into new development behavior.
// http://fb.me/prop-types-in-prod
var throwOnDirectAccess = true;
module.exports = require('./factoryWithTypeCheckers')(isValidElement, throwOnDirectAccess);
} else {
// By explicitly using `prop-types` you are opting into new production behavior.
// http://fb.me/prop-types-in-prod
module.exports = require('./factoryWithThrowingShims')();
}
}).call(this,require('_process'))
},{"./factoryWithThrowingShims":8,"./factoryWithTypeCheckers":9,"_process":6}],11:[function(require,module,exports){
/**
* Copyright (c) 2013-present, Facebook, Inc.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
'use strict';
var ReactPropTypesSecret = 'SECRET_DO_NOT_PASS_THIS_OR_YOU_WILL_BE_FIRED';
module.exports = ReactPropTypesSecret;
},{}],12:[function(require,module,exports){
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.default = {
GLOBAL: {
HIDE: '__react_tooltip_hide_event',
REBUILD: '__react_tooltip_rebuild_event',
SHOW: '__react_tooltip_show_event'
}
};
},{}],13:[function(require,module,exports){
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.default = function (target) {
target.prototype.isCustomEvent = function (ele) {
var event = this.state.event;
return event || !!ele.getAttribute('data-event');
};
/* Bind listener for custom event */
target.prototype.customBindListener = function (ele) {
var _this = this;
var _state = this.state,
event = _state.event,
eventOff = _state.eventOff;
var dataEvent = ele.getAttribute('data-event') || event;
var dataEventOff = ele.getAttribute('data-event-off') || eventOff;
dataEvent.split(' ').forEach(function (event) {
ele.removeEventListener(event, customListeners.get(ele, event));
var customListener = checkStatus.bind(_this, dataEventOff);
customListeners.set(ele, event, customListener);
ele.addEventListener(event, customListener, false);
});
if (dataEventOff) {
dataEventOff.split(' ').forEach(function (event) {
ele.removeEventListener(event, _this.hideTooltip);
ele.addEventListener(event, _this.hideTooltip, false);
});
}
};
/* Unbind listener for custom event */
target.prototype.customUnbindListener = function (ele) {
var _state2 = this.state,
event = _state2.event,
eventOff = _state2.eventOff;
var dataEvent = event || ele.getAttribute('data-event');
var dataEventOff = eventOff || ele.getAttribute('data-event-off');
ele.removeEventListener(dataEvent, customListeners.get(ele, event));
if (dataEventOff) ele.removeEventListener(dataEventOff, this.hideTooltip);
};
};
function _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; }
/**
* Custom events to control showing and hiding of tooltip
*
* @attributes
* - `event` {String}
* - `eventOff` {String}
*/
var checkStatus = function checkStatus(dataEventOff, e) {
var show = this.state.show;
var id = this.props.id;
var dataIsCapture = e.currentTarget.getAttribute('data-iscapture');
var isCapture = dataIsCapture && dataIsCapture === 'true' || this.props.isCapture;
var currentItem = e.currentTarget.getAttribute('currentItem');
if (!isCapture) e.stopPropagation();
if (show && currentItem === 'true') {
if (!dataEventOff) this.hideTooltip(e);
} else {
e.currentTarget.setAttribute('currentItem', 'true');
setUntargetItems(e.currentTarget, this.getTargetArray(id));
this.showTooltip(e);
}
};
var setUntargetItems = function setUntargetItems(currentTarget, targetArray) {
for (var i = 0; i < targetArray.length; i++) {
if (currentTarget !== targetArray[i]) {
targetArray[i].setAttribute('currentItem', 'false');
} else {
targetArray[i].setAttribute('currentItem', 'true');
}
}
};
var customListeners = {
id: '9b69f92e-d3fe-498b-b1b4-c5e63a51b0cf',
set: function set(target, event, listener) {
if (this.id in target) {
var map = target[this.id];
map[event] = listener;
} else {
// this is workaround for WeakMap, which is not supported in older browsers, such as IE
Object.defineProperty(target, this.id, {
configurable: true,
value: _defineProperty({}, event, listener)
});
}
},
get: function get(target, event) {
var map = target[this.id];
if (map !== undefined) {
return map[event];
}
}
};
},{}],14:[function(require,module,exports){
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.default = function (target) {
target.prototype.getEffect = function (currentTarget) {
var dataEffect = currentTarget.getAttribute('data-effect');
return dataEffect || this.props.effect || 'float';
};
};
},{}],15:[function(require,module,exports){
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.default = function (target) {
target.prototype.isCapture = function (currentTarget) {
return currentTarget && currentTarget.getAttribute('data-iscapture') === 'true' || this.props.isCapture || false;
};
};
},{}],16:[function(require,module,exports){
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.default = function (target) {
/**
* Hide all tooltip
* @trigger ReactTooltip.hide()
*/
target.hide = function (target) {
dispatchGlobalEvent(_constant2.default.GLOBAL.HIDE, { target: target });
};
/**
* Rebuild all tooltip
* @trigger ReactTooltip.rebuild()
*/
target.rebuild = function () {
dispatchGlobalEvent(_constant2.default.GLOBAL.REBUILD);
};
/**
* Show specific tooltip
* @trigger ReactTooltip.show()
*/
target.show = function (target) {
dispatchGlobalEvent(_constant2.default.GLOBAL.SHOW, { target: target });
};
target.prototype.globalRebuild = function () {
if (this.mount) {
this.unbindListener();
this.bindListener();
}
};
target.prototype.globalShow = function (event) {
if (this.mount) {
// Create a fake event, specific show will limit the type to `solid`
// only `float` type cares e.clientX e.clientY
var e = { currentTarget: event.detail.target };
this.showTooltip(e, true);
}
};
target.prototype.globalHide = function (event) {
if (this.mount) {
var hasTarget = event && event.detail && event.detail.target && true || false;
this.hideTooltip({ currentTarget: hasTarget && event.detail.target }, hasTarget);
}
};
};
var _constant = require('../constant');
var _constant2 = _interopRequireDefault(_constant);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
var dispatchGlobalEvent = function dispatchGlobalEvent(eventName, opts) {
// Compatibale with IE
// @see http://stackoverflow.com/questions/26596123/internet-explorer-9-10-11-event-constructor-doesnt-work
var event = void 0;
if (typeof window.CustomEvent === 'function') {
event = new window.CustomEvent(eventName, { detail: opts });
} else {
event = document.createEvent('Event');
event.initEvent(eventName, false, true);
event.detail = opts;
}
window.dispatchEvent(event);
}; /**
* Static methods for react-tooltip
*/
},{"../constant":12}],17:[function(require,module,exports){
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.default = function (target) {
target.prototype.bindRemovalTracker = function () {
var _this = this;
var MutationObserver = getMutationObserverClass();
if (MutationObserver == null) return;
var observer = new MutationObserver(function (mutations) {
for (var m1 = 0; m1 < mutations.length; m1++) {
var mutation = mutations[m1];
for (var m2 = 0; m2 < mutation.removedNodes.length; m2++) {
var element = mutation.removedNodes[m2];
if (element === _this.state.currentTarget) {
_this.hideTooltip();
return;
}
}
}
});
observer.observe(window.document, { childList: true, subtree: true });
this.removalTracker = observer;
};
target.prototype.unbindRemovalTracker = function () {
if (this.removalTracker) {
this.removalTracker.disconnect();
this.removalTracker = null;
}
};
};
/**
* Tracking target removing from DOM.
* It's nessesary to hide tooltip when it's target disappears.
* Otherwise, the tooltip would be shown forever until another target
* is triggered.
*
* If MutationObserver is not available, this feature just doesn't work.
*/
// https://hacks.mozilla.org/2012/05/dom-mutationobserver-reacting-to-dom-changes-without-killing-browser-performance/
var getMutationObserverClass = function getMutationObserverClass() {
return window.MutationObserver || window.WebKitMutationObserver || window.MozMutationObserver;
};
},{}],18:[function(require,module,exports){
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.default = function (target) {
target.prototype.bindWindowEvents = function (resizeHide) {
// ReactTooltip.hide
window.removeEventListener(_constant2.default.GLOBAL.HIDE, this.globalHide);
window.addEventListener(_constant2.default.GLOBAL.HIDE, this.globalHide, false);
// ReactTooltip.rebuild
window.removeEventListener(_constant2.default.GLOBAL.REBUILD, this.globalRebuild);
window.addEventListener(_constant2.default.GLOBAL.REBUILD, this.globalRebuild, false);
// ReactTooltip.show
window.removeEventListener(_constant2.default.GLOBAL.SHOW, this.globalShow);
window.addEventListener(_constant2.default.GLOBAL.SHOW, this.globalShow, false);
// Resize
if (resizeHide) {
window.removeEventListener('resize', this.onWindowResize);
window.addEventListener('resize', this.onWindowResize, false);
}
};
target.prototype.unbindWindowEvents = function () {
window.removeEventListener(_constant2.default.GLOBAL.HIDE, this.globalHide);
window.removeEventListener(_constant2.default.GLOBAL.REBUILD, this.globalRebuild);
window.removeEventListener(_constant2.default.GLOBAL.SHOW, this.globalShow);
window.removeEventListener('resize', this.onWindowResize);
};
/**
* invoked by resize event of window
*/
target.prototype.onWindowResize = function () {
if (!this.mount) return;
this.hideTooltip();
};
};
var _constant = require('../constant');
var _constant2 = _interopRequireDefault(_constant);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
},{"../constant":12}],19:[function(require,module,exports){
(function (global){
'use strict';
var _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; };
var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();
var _class, _class2, _temp;
/* Decoraters */
/* Utils */
/* CSS */
var _react = (typeof window !== "undefined" ? window['React'] : typeof global !== "undefined" ? global['React'] : null);
var _react2 = _interopRequireDefault(_react);
var _propTypes = require('prop-types');
var _propTypes2 = _interopRequireDefault(_propTypes);
var _reactDom = (typeof window !== "undefined" ? window['ReactDOM'] : typeof global !== "undefined" ? global['ReactDOM'] : null);
var _reactDom2 = _interopRequireDefault(_reactDom);
var _classnames = require('classnames');
var _classnames2 = _interopRequireDefault(_classnames);
var _staticMethods = require('./decorators/staticMethods');
var _staticMethods2 = _interopRequireDefault(_staticMethods);
var _windowListener = require('./decorators/windowListener');
var _windowListener2 = _interopRequireDefault(_windowListener);
var _customEvent = require('./decorators/customEvent');
var _customEvent2 = _interopRequireDefault(_customEvent);
var _isCapture = require('./decorators/isCapture');
var _isCapture2 = _interopRequireDefault(_isCapture);
var _getEffect = require('./decorators/getEffect');
var _getEffect2 = _interopRequireDefault(_getEffect);
var _trackRemoval = require('./decorators/trackRemoval');
var _trackRemoval2 = _interopRequireDefault(_trackRemoval);
var _getPosition = require('./utils/getPosition');
var _getPosition2 = _interopRequireDefault(_getPosition);
var _getTipContent = require('./utils/getTipContent');
var _getTipContent2 = _interopRequireDefault(_getTipContent);
var _aria = require('./utils/aria');
var _nodeListToArray = require('./utils/nodeListToArray');
var _nodeListToArray2 = _interopRequireDefault(_nodeListToArray);
var _style = require('./style');
var _style2 = _interopRequireDefault(_style);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; }
function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; }
var ReactTooltip = (0, _staticMethods2.default)(_class = (0, _windowListener2.default)(_class = (0, _customEvent2.default)(_class = (0, _isCapture2.default)(_class = (0, _getEffect2.default)(_class = (0, _trackRemoval2.default)(_class = (_temp = _class2 = function (_React$Component) {
_inherits(ReactTooltip, _React$Component);
function ReactTooltip(props) {
_classCallCheck(this, ReactTooltip);
var _this = _possibleConstructorReturn(this, (ReactTooltip.__proto__ || Object.getPrototypeOf(ReactTooltip)).call(this, props));
_this.state = {
place: props.place || 'top', // Direction of tooltip
desiredPlace: props.place || 'top',
type: 'dark', // Color theme of tooltip
effect: 'float', // float or fixed
show: false,
border: false,
offset: {},
extraClass: '',
html: false,
delayHide: 0,
delayShow: 0,
event: props.event || null,
eventOff: props.eventOff || null,
currentEvent: null, // Current mouse event
currentTarget: null, // Current target of mouse event
ariaProps: (0, _aria.parseAria)(props), // aria- and role attributes
isEmptyTip: false,
disable: false,
originTooltip: null,
isMultiline: false
};
_this.bind(['showTooltip', 'updateTooltip', 'hideTooltip', 'getTooltipContent', 'globalRebuild', 'globalShow', 'globalHide', 'onWindowResize', 'mouseOnToolTip']);
_this.mount = true;
_this.delayShowLoop = null;
_this.delayHideLoop = null;
_this.delayReshow = null;
_this.intervalUpdateContent = null;
return _this;
}
/**
* For unify the bind and unbind listener
*/
_createClass(ReactTooltip, [{
key: 'bind',
value: function bind(methodArray) {
var _this2 = this;
methodArray.forEach(function (method) {
_this2[method] = _this2[method].bind(_this2);
});
}
}, {
key: 'componentDidMount',
value: function componentDidMount() {
var _props = this.props,
insecure = _props.insecure,
resizeHide = _props.resizeHide;
if (insecure) {
this.setStyleHeader(); // Set the style to the <link>
}
this.bindListener(); // Bind listener for tooltip
this.bindWindowEvents(resizeHide); // Bind global event for static method
}
}, {
key: 'componentWillReceiveProps',
value: function componentWillReceiveProps(props) {
var ariaProps = this.state.ariaProps;
var newAriaProps = (0, _aria.parseAria)(props);
var isChanged = Object.keys(newAriaProps).some(function (props) {
return newAriaProps[props] !== ariaProps[props];
});
if (isChanged) {
this.setState({ ariaProps: newAriaProps });
}
}
}, {
key: 'componentWillUnmount',
value: function componentWillUnmount() {
this.mount = false;
this.clearTimer();
this.unbindListener();
this.removeScrollListener();
this.unbindWindowEvents();
}
/**
* Return if the mouse is on the tooltip.
* @returns {boolean} true - mouse is on the tooltip
*/
}, {
key: 'mouseOnToolTip',
value: function mouseOnToolTip() {
var show = this.state.show;
if (show && this.tooltipRef) {
/* old IE or Firefox work around */
if (!this.tooltipRef.matches) {
/* old IE work around */
if (this.tooltipRef.msMatchesSelector) {
this.tooltipRef.matches = this.tooltipRef.msMatchesSelector;
} else {
/* old Firefox work around */
this.tooltipRef.matches = this.tooltipRef.mozMatchesSelector;
}
}
return this.tooltipRef.matches(':hover');
}
return false;
}
/**
* Pick out corresponded target elements
*/
}, {
key: 'getTargetArray',
value: function getTargetArray(id) {
var targetArray = void 0;
if (!id) {
targetArray = document.querySelectorAll('[data-tip]:not([data-for])');
} else {
var escaped = id.replace(/\\/g, '\\\\').replace(/"/g, '\\"');
targetArray = document.querySelectorAll('[data-tip][data-for="' + escaped + '"]');
}
// targetArray is a NodeList, convert it to a real array
return (0, _nodeListToArray2.default)(targetArray);
}
/**
* Bind listener to the target elements
* These listeners used to trigger showing or hiding the tooltip
*/
}, {
key: 'bindListener',
value: function bindListener() {
var _this3 = this;
var _props2 = this.props,
id = _props2.id,
globalEventOff = _props2.globalEventOff,
isCapture = _props2.isCapture;
var targetArray = this.getTargetArray(id);
targetArray.forEach(function (target) {
var isCaptureMode = _this3.isCapture(target);
var effect = _this3.getEffect(target);
if (target.getAttribute('currentItem') === null) {
target.setAttribute('currentItem', 'false');
}
_this3.unbindBasicListener(target);
if (_this3.isCustomEvent(target)) {
_this3.customBindListener(target);
return;
}
target.addEventListener('mouseenter', _this3.showTooltip, isCaptureMode);
if (effect === 'float') {
target.addEventListener('mousemove', _this3.updateTooltip, isCaptureMode);
}
target.addEventListener('mouseleave', _this3.hideTooltip, isCaptureMode);
});
// Global event to hide tooltip
if (globalEventOff) {
window.removeEventListener(globalEventOff, this.hideTooltip);
window.addEventListener(globalEventOff, this.hideTooltip, isCapture);
}
// Track removal of targetArray elements from DOM
this.bindRemovalTracker();
}
/**
* Unbind listeners on target elements
*/
}, {
key: 'unbindListener',
value: function unbindListener() {
var _this4 = this;
var _props3 = this.props,
id = _props3.id,
globalEventOff = _props3.globalEventOff;
var targetArray = this.getTargetArray(id);
targetArray.forEach(function (target) {
_this4.unbindBasicListener(target);
if (_this4.isCustomEvent(target)) _this4.customUnbindListener(target);
});
if (globalEventOff) window.removeEventListener(globalEventOff, this.hideTooltip);
this.unbindRemovalTracker();
}
/**
* Invoke this before bind listener and ummount the compont
* it is necessary to invloke this even when binding custom event
* so that the tooltip can switch between custom and default listener
*/
}, {
key: 'unbindBasicListener',
value: function unbindBasicListener(target) {
var isCaptureMode = this.isCapture(target);
target.removeEventListener('mouseenter', this.showTooltip, isCaptureMode);
target.removeEventListener('mousemove', this.updateTooltip, isCaptureMode);
target.removeEventListener('mouseleave', this.hideTooltip, isCaptureMode);
}
}, {
key: 'getTooltipContent',
value: function getTooltipContent() {
var _props4 = this.props,
getContent = _props4.getContent,
children = _props4.children;
// Generate tooltip content
var content = void 0;
if (getContent) {
if (Array.isArray(getContent)) {
content = getContent[0] && getContent[0](this.state.originTooltip);
} else {
content = getContent(this.state.originTooltip);
}
}
return (0, _getTipContent2.default)(this.state.originTooltip, children, content, this.state.isMultiline);
}
}, {
key: 'isEmptyTip',
value: function isEmptyTip(placeholder) {
return typeof placeholder === 'string' && placeholder === '' || placeholder === null;
}
/**
* When mouse enter, show the tooltip
*/
}, {
key: 'showTooltip',
value: function showTooltip(e, isGlobalCall) {
if (isGlobalCall) {
// Don't trigger other elements belongs to other ReactTooltip
var targetArray = this.getTargetArray(this.props.id);
var isMyElement = targetArray.some(function (ele) {
return ele === e.currentTarget;
});
if (!isMyElement) return;
}
// Get the tooltip content
// calculate in this phrase so that tip width height can be detected
var _props5 = this.props,
multiline = _props5.multiline,
getContent = _props5.getContent;
var originTooltip = e.currentTarget.getAttribute('data-tip');
var isMultiline = e.currentTarget.getAttribute('data-multiline') || multiline || false;
// If it is focus event or called by ReactTooltip.show, switch to `solid` effect
var switchToSolid = e instanceof window.FocusEvent || isGlobalCall;
// if it needs to skip adding hide listener to scroll
var scrollHide = true;
if (e.currentTarget.getAttribute('data-scroll-hide')) {
scrollHide = e.currentTarget.getAttribute('data-scroll-hide') === 'true';
} else if (this.props.scrollHide != null) {
scrollHide = this.props.scrollHide;
}
// Make sure the correct place is set
var desiredPlace = e.currentTarget.getAttribute('data-place') || this.props.place || 'top';
var effect = switchToSolid && 'solid' || this.getEffect(e.currentTarget);
var offset = e.currentTarget.getAttribute('data-offset') || this.props.offset || {};
var result = (0, _getPosition2.default)(e, e.currentTarget, _reactDom2.default.findDOMNode(this), desiredPlace, desiredPlace, effect, offset);
var place = result.isNewState ? result.newState.place : desiredPlace;
// To prevent previously created timers from triggering
this.clearTimer();
var target = e.currentTarget;
var reshowDelay = this.state.show ? target.getAttribute('data-delay-update') || this.props.delayUpdate : 0;
var self = this;
var updateState = function updateState() {
self.setState({
originTooltip: originTooltip,
isMultiline: isMultiline,
desiredPlace: desiredPlace,
place: place,
type: target.getAttribute('data-type') || self.props.type || 'dark',
effect: effect,
offset: offset,
html: target.getAttribute('data-html') ? target.getAttribute('data-html') === 'true' : self.props.html || false,
delayShow: target.getAttribute('data-delay-show') || self.props.delayShow || 0,
delayHide: target.getAttribute('data-delay-hide') || self.props.delayHide || 0,
delayUpdate: target.getAttribute('data-delay-update') || self.props.delayUpdate || 0,
border: target.getAttribute('data-border') ? target.getAttribute('data-border') === 'true' : self.props.border || false,
extraClass: target.getAttribute('data-class') || self.props.class || self.props.className || '',
disable: target.getAttribute('data-tip-disable') ? target.getAttribute('data-tip-disable') === 'true' : self.props.disable || false,
currentTarget: target
}, function () {
if (scrollHide) self.addScrollListener(self.state.currentTarget);
self.updateTooltip(e);
if (getContent && Array.isArray(getContent)) {
self.intervalUpdateContent = setInterval(function () {
if (self.mount) {
var _getContent = self.props.getContent;
var placeholder = (0, _getTipContent2.default)(originTooltip, '', _getContent[0](), isMultiline);
var isEmptyTip = self.isEmptyTip(placeholder);
self.setState({
isEmptyTip: isEmptyTip
});
self.updatePosition();
}
}, getContent[1]);
}
});
};
// If there is no delay call immediately, don't allow events to get in first.
if (reshowDelay) {
this.delayReshow = setTimeout(updateState, reshowDelay);
} else {
updateState();
}
}
/**
* When mouse hover, updatetooltip
*/
}, {
key: 'updateTooltip',
value: function updateTooltip(e) {
var _this5 = this;
var _state = this.state,
delayShow = _state.delayShow,
disable = _state.disable;
var afterShow = this.props.afterShow;
var placeholder = this.getTooltipContent();
var delayTime = parseInt(delayShow, 10);
var eventTarget = e.currentTarget || e.target;
// Check if the mouse is actually over the tooltip, if so don't hide the tooltip
if (this.mouseOnToolTip()) {
return;
}
if (this.isEmptyTip(placeholder) || disable) return; // if the tooltip is empty, disable the tooltip
var updateState = function updateState() {
if (Array.isArray(placeholder) && placeholder.length > 0 || placeholder) {
var isInvisible = !_this5.state.show;
_this5.setState({
currentEvent: e,
currentTarget: eventTarget,
show: true
}, function () {
_this5.updatePosition();
if (isInvisible && afterShow) afterShow(e);
});
}
};
clearTimeout(this.delayShowLoop);
if (delayShow) {
this.delayShowLoop = setTimeout(updateState, delayTime);
} else {
updateState();
}
}
/*
* If we're mousing over the tooltip remove it when we leave.
*/
}, {
key: 'listenForTooltipExit',
value: function listenForTooltipExit() {
var show = this.state.show;
if (show && this.tooltipRef) {
this.tooltipRef.addEventListener('mouseleave', this.hideTooltip);
}
}
}, {
key: 'removeListenerForTooltipExit',
value: function removeListenerForTooltipExit() {
var show = this.state.show;
if (show && this.tooltipRef) {
this.tooltipRef.removeEventListener('mouseleave', this.hideTooltip);
}
}
/**
* When mouse leave, hide tooltip
*/
}, {
key: 'hideTooltip',
value: function hideTooltip(e, hasTarget) {
var _this6 = this;
var _state2 = this.state,
delayHide = _state2.delayHide,
disable = _state2.disable;
var afterHide = this.props.afterHide;
var placeholder = this.getTooltipContent();
if (!this.mount) return;
if (this.isEmptyTip(placeholder) || disable) return; // if the tooltip is empty, disable the tooltip
if (hasTarget) {
// Don't trigger other elements belongs to other ReactTooltip
var targetArray = this.getTargetArray(this.props.id);
var isMyElement = targetArray.some(function (ele) {
return ele === e.currentTarget;
});
if (!isMyElement || !this.state.show) return;
}
var resetState = function resetState() {
var isVisible = _this6.state.show;
// Check if the mouse is actually over the tooltip, if so don't hide the tooltip
if (_this6.mouseOnToolTip()) {
_this6.listenForTooltipExit();
return;
}
_this6.removeListenerForTooltipExit();
_this6.setState({
show: false
}, function () {
_this6.removeScrollListener();
if (isVisible && afterHide) afterHide(e);
});
};
this.clearTimer();
if (delayHide) {
this.delayHideLoop = setTimeout(resetState, parseInt(delayHide, 10));
} else {
resetState();
}
}
/**
* Add scroll eventlistener when tooltip show
* automatically hide the tooltip when scrolling
*/
}, {
key: 'addScrollListener',
value: function addScrollListener(currentTarget) {
var isCaptureMode = this.isCapture(currentTarget);
window.addEventListener('scroll', this.hideTooltip, isCaptureMode);
}
}, {
key: 'removeScrollListener',
value: function removeScrollListener() {
window.removeEventListener('scroll', this.hideTooltip);
}
// Calculation the position
}, {
key: 'updatePosition',
value: function updatePosition() {
var _this7 = this;
var _state3 = this.state,
currentEvent = _state3.currentEvent,
currentTarget = _state3.currentTarget,
place = _state3.place,
desiredPlace = _state3.desiredPlace,
effect = _state3.effect,
offset = _state3.offset;
var node = _reactDom2.default.findDOMNode(this);
var result = (0, _getPosition2.default)(currentEvent, currentTarget, node, place, desiredPlace, effect, offset);
if (result.isNewState) {
// Switch to reverse placement
return this.setState(result.newState, function () {
_this7.updatePosition();
});
}
// Set tooltip position
node.style.left = result.position.left + 'px';
node.style.top = result.position.top + 'px';
}
/**
* Set style tag in header
* in this way we can insert default css
*/
}, {
key: 'setStyleHeader',
value: function setStyleHeader() {
var head = document.getElementsByTagName('head')[0];
if (!head.querySelector('style[id="react-tooltip"]')) {
var tag = document.createElement('style');
tag.id = 'react-tooltip';
tag.innerHTML = _style2.default;
/* eslint-disable */
if (typeof __webpack_nonce__ !== 'undefined' && __webpack_nonce__) {
tag.setAttribute('nonce', __webpack_nonce__);
}
/* eslint-enable */
head.insertBefore(tag, head.firstChild);
}
}
/**
* CLear all kinds of timeout of interval
*/
}, {
key: 'clearTimer',
value: function clearTimer() {
clearTimeout(this.delayShowLoop);
clearTimeout(this.delayHideLoop);
clearTimeout(this.delayReshow);
clearInterval(this.intervalUpdateContent);
}
}, {
key: 'render',
value: function render() {
var _this8 = this;
var _state4 = this.state,
extraClass = _state4.extraClass,
html = _state4.html,
ariaProps = _state4.ariaProps,
disable = _state4.disable;
var placeholder = this.getTooltipContent();
var isEmptyTip = this.isEmptyTip(placeholder);
var tooltipClass = (0, _classnames2.default)('__react_component_tooltip', { 'show': this.state.show && !disable && !isEmptyTip }, { 'border': this.state.border }, { 'place-top': this.state.place === 'top' }, { 'place-bottom': this.state.place === 'bottom' }, { 'place-left': this.state.place === 'left' }, { 'place-right': this.state.place === 'right' }, { 'type-dark': this.state.type === 'dark' }, { 'type-success': this.state.type === 'success' }, { 'type-warning': this.state.type === 'warning' }, { 'type-error': this.state.type === 'error' }, { 'type-info': this.state.type === 'info' }, { 'type-light': this.state.type === 'light' }, { 'allow_hover': this.props.delayUpdate });
var Wrapper = this.props.wrapper;
if (ReactTooltip.supportedWrappers.indexOf(Wrapper) < 0) {
Wrapper = ReactTooltip.defaultProps.wrapper;
}
if (html) {
return _react2.default.createElement(Wrapper, _extends({ className: tooltipClass + ' ' + extraClass,
id: this.props.id,
ref: function ref(_ref) {
return _this8.tooltipRef = _ref;
}
}, ariaProps, {
'data-id': 'tooltip',
dangerouslySetInnerHTML: { __html: placeholder } }));
} else {
return _react2.default.createElement(
Wrapper,
_extends({ className: tooltipClass + ' ' + extraClass,
id: this.props.id
}, ariaProps, {
ref: function ref(_ref2) {
return _this8.tooltipRef = _ref2;
},
'data-id': 'tooltip' }),
placeholder
);
}
}
}]);
return ReactTooltip;
}(_react2.default.Component), _class2.propTypes = {
children: _propTypes2.default.any,
place: _propTypes2.default.string,
type: _propTypes2.default.string,
effect: _propTypes2.default.string,
offset: _propTypes2.default.object,
multiline: _propTypes2.default.bool,
border: _propTypes2.default.bool,
insecure: _propTypes2.default.bool,
class: _propTypes2.default.string,
className: _propTypes2.default.string,
id: _propTypes2.default.string,
html: _propTypes2.default.bool,
delayHide: _propTypes2.default.number,
delayUpdate: _propTypes2.default.number,
delayShow: _propTypes2.default.number,
event: _propTypes2.default.string,
eventOff: _propTypes2.default.string,
watchWindow: _propTypes2.default.bool,
isCapture: _propTypes2.default.bool,
globalEventOff: _propTypes2.default.string,
getContent: _propTypes2.default.any,
afterShow: _propTypes2.default.func,
afterHide: _propTypes2.default.func,
disable: _propTypes2.default.bool,
scrollHide: _propTypes2.default.bool,
resizeHide: _propTypes2.default.bool,
wrapper: _propTypes2.default.string
}, _class2.defaultProps = {
insecure: true,
resizeHide: true,
wrapper: 'div'
}, _class2.supportedWrappers = ['div', 'span'], _class2.displayName = 'ReactTooltip', _temp)) || _class) || _class) || _class) || _class) || _class) || _class;
/* export default not fit for standalone, it will exports {default:...} */
module.exports = ReactTooltip;
}).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
},{"./decorators/customEvent":13,"./decorators/getEffect":14,"./decorators/isCapture":15,"./decorators/staticMethods":16,"./decorators/trackRemoval":17,"./decorators/windowListener":18,"./style":20,"./utils/aria":21,"./utils/getPosition":22,"./utils/getTipContent":23,"./utils/nodeListToArray":24,"classnames":1,"prop-types":10}],20:[function(require,module,exports){
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.default = '.__react_component_tooltip{border-radius:3px;display:inline-block;font-size:13px;left:-999em;opacity:0;padding:8px 21px;position:fixed;pointer-events:none;transition:opacity 0.3s ease-out;top:-999em;visibility:hidden;z-index:999}.__react_component_tooltip.allow_hover{pointer-events:auto}.__react_component_tooltip:before,.__react_component_tooltip:after{content:"";width:0;height:0;position:absolute}.__react_component_tooltip.show{opacity:0.9;margin-top:0px;margin-left:0px;visibility:visible}.__react_component_tooltip.type-dark{color:#fff;background-color:#222}.__react_component_tooltip.type-dark.place-top:after{border-top-color:#222;border-top-style:solid;border-top-width:6px}.__react_component_tooltip.type-dark.place-bottom:after{border-bottom-color:#222;border-bottom-style:solid;border-bottom-width:6px}.__react_component_tooltip.type-dark.place-left:after{border-left-color:#222;border-left-style:solid;border-left-width:6px}.__react_component_tooltip.type-dark.place-right:after{border-right-color:#222;border-right-style:solid;border-right-width:6px}.__react_component_tooltip.type-dark.border{border:1px solid #fff}.__react_component_tooltip.type-dark.border.place-top:before{border-top:8px solid #fff}.__react_component_tooltip.type-dark.border.place-bottom:before{border-bottom:8px solid #fff}.__react_component_tooltip.type-dark.border.place-left:before{border-left:8px solid #fff}.__react_component_tooltip.type-dark.border.place-right:before{border-right:8px solid #fff}.__react_component_tooltip.type-success{color:#fff;background-color:#8DC572}.__react_component_tooltip.type-success.place-top:after{border-top-color:#8DC572;border-top-style:solid;border-top-width:6px}.__react_component_tooltip.type-success.place-bottom:after{border-bottom-color:#8DC572;border-bottom-style:solid;border-bottom-width:6px}.__react_component_tooltip.type-success.place-left:after{border-left-color:#8DC572;border-left-style:solid;border-left-width:6px}.__react_component_tooltip.type-success.place-right:after{border-right-color:#8DC572;border-right-style:solid;border-right-width:6px}.__react_component_tooltip.type-success.border{border:1px solid #fff}.__react_component_tooltip.type-success.border.place-top:before{border-top:8px solid #fff}.__react_component_tooltip.type-success.border.place-bottom:before{border-bottom:8px solid #fff}.__react_component_tooltip.type-success.border.place-left:before{border-left:8px solid #fff}.__react_component_tooltip.type-success.border.place-right:before{border-right:8px solid #fff}.__react_component_tooltip.type-warning{color:#fff;background-color:#F0AD4E}.__react_component_tooltip.type-warning.place-top:after{border-top-color:#F0AD4E;border-top-style:solid;border-top-width:6px}.__react_component_tooltip.type-warning.place-bottom:after{border-bottom-color:#F0AD4E;border-bottom-style:solid;border-bottom-width:6px}.__react_component_tooltip.type-warning.place-left:after{border-left-color:#F0AD4E;border-left-style:solid;border-left-width:6px}.__react_component_tooltip.type-warning.place-right:after{border-right-color:#F0AD4E;border-right-style:solid;border-right-width:6px}.__react_component_tooltip.type-warning.border{border:1px solid #fff}.__react_component_tooltip.type-warning.border.place-top:before{border-top:8px solid #fff}.__react_component_tooltip.type-warning.border.place-bottom:before{border-bottom:8px solid #fff}.__react_component_tooltip.type-warning.border.place-left:before{border-left:8px solid #fff}.__react_component_tooltip.type-warning.border.place-right:before{border-right:8px solid #fff}.__react_component_tooltip.type-error{color:#fff;background-color:#BE6464}.__react_component_tooltip.type-error.place-top:after{border-top-color:#BE6464;border-top-style:solid;border-top-width:6px}.__react_component_tooltip.type-error.place-bottom:after{border-bottom-color:#BE6464;border-bottom-style:solid;border-bottom-width:6px}.__react_component_tooltip.type-error.place-left:after{border-left-color:#BE6464;border-left-style:solid;border-left-width:6px}.__react_component_tooltip.type-error.place-right:after{border-right-color:#BE6464;border-right-style:solid;border-right-width:6px}.__react_component_tooltip.type-error.border{border:1px solid #fff}.__react_component_tooltip.type-error.border.place-top:before{border-top:8px solid #fff}.__react_component_tooltip.type-error.border.place-bottom:before{border-bottom:8px solid #fff}.__react_component_tooltip.type-error.border.place-left:before{border-left:8px solid #fff}.__react_component_tooltip.type-error.border.place-right:before{border-right:8px solid #fff}.__react_component_tooltip.type-info{color:#fff;background-color:#337AB7}.__react_component_tooltip.type-info.place-top:after{border-top-color:#337AB7;border-top-style:solid;border-top-width:6px}.__react_component_tooltip.type-info.place-bottom:after{border-bottom-color:#337AB7;border-bottom-style:solid;border-bottom-width:6px}.__react_component_tooltip.type-info.place-left:after{border-left-color:#337AB7;border-left-style:solid;border-left-width:6px}.__react_component_tooltip.type-info.place-right:after{border-right-color:#337AB7;border-right-style:solid;border-right-width:6px}.__react_component_tooltip.type-info.border{border:1px solid #fff}.__react_component_tooltip.type-info.border.place-top:before{border-top:8px solid #fff}.__react_component_tooltip.type-info.border.place-bottom:before{border-bottom:8px solid #fff}.__react_component_tooltip.type-info.border.place-left:before{border-left:8px solid #fff}.__react_component_tooltip.type-info.border.place-right:before{border-right:8px solid #fff}.__react_component_tooltip.type-light{color:#222;background-color:#fff}.__react_component_tooltip.type-light.place-top:after{border-top-color:#fff;border-top-style:solid;border-top-width:6px}.__react_component_tooltip.type-light.place-bottom:after{border-bottom-color:#fff;border-bottom-style:solid;border-bottom-width:6px}.__react_component_tooltip.type-light.place-left:after{border-left-color:#fff;border-left-style:solid;border-left-width:6px}.__react_component_tooltip.type-light.place-right:after{border-right-color:#fff;border-right-style:solid;border-right-width:6px}.__react_component_tooltip.type-light.border{border:1px solid #222}.__react_component_tooltip.type-light.border.place-top:before{border-top:8px solid #222}.__react_component_tooltip.type-light.border.place-bottom:before{border-bottom:8px solid #222}.__react_component_tooltip.type-light.border.place-left:before{border-left:8px solid #222}.__react_component_tooltip.type-light.border.place-right:before{border-right:8px solid #222}.__react_component_tooltip.place-top{margin-top:-10px}.__react_component_tooltip.place-top:before{border-left:10px solid transparent;border-right:10px solid transparent;bottom:-8px;left:50%;margin-left:-10px}.__react_component_tooltip.place-top:after{border-left:8px solid transparent;border-right:8px solid transparent;bottom:-6px;left:50%;margin-left:-8px}.__react_component_tooltip.place-bottom{margin-top:10px}.__react_component_tooltip.place-bottom:before{border-left:10px solid transparent;border-right:10px solid transparent;top:-8px;left:50%;margin-left:-10px}.__react_component_tooltip.place-bottom:after{border-left:8px solid transparent;border-right:8px solid transparent;top:-6px;left:50%;margin-left:-8px}.__react_component_tooltip.place-left{margin-left:-10px}.__react_component_tooltip.place-left:before{border-top:6px solid transparent;border-bottom:6px solid transparent;right:-8px;top:50%;margin-top:-5px}.__react_component_tooltip.place-left:after{border-top:5px solid transparent;border-bottom:5px solid transparent;right:-6px;top:50%;margin-top:-4px}.__react_component_tooltip.place-right{margin-left:10px}.__react_component_tooltip.place-right:before{border-top:6px solid transparent;border-bottom:6px solid transparent;left:-8px;top:50%;margin-top:-5px}.__react_component_tooltip.place-right:after{border-top:5px solid transparent;border-bottom:5px solid transparent;left:-6px;top:50%;margin-top:-4px}.__react_component_tooltip .multi-line{display:block;padding:2px 0px;text-align:center}';
},{}],21:[function(require,module,exports){
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.parseAria = parseAria;
/**
* Support aria- and role in ReactTooltip
*
* @params props {Object}
* @return {Object}
*/
function parseAria(props) {
var ariaObj = {};
Object.keys(props).filter(function (prop) {
// aria-xxx and role is acceptable
return (/(^aria-\w+$|^role$)/.test(prop)
);
}).forEach(function (prop) {
ariaObj[prop] = props[prop];
});
return ariaObj;
}
},{}],22:[function(require,module,exports){
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.default = function (e, target, node, place, desiredPlace, effect, offset) {
var _getDimensions = getDimensions(node),
tipWidth = _getDimensions.width,
tipHeight = _getDimensions.height;
var _getDimensions2 = getDimensions(target),
targetWidth = _getDimensions2.width,
targetHeight = _getDimensions2.height;
var _getCurrentOffset = getCurrentOffset(e, target, effect),
mouseX = _getCurrentOffset.mouseX,
mouseY = _getCurrentOffset.mouseY;
var defaultOffset = getDefaultPosition(effect, targetWidth, targetHeight, tipWidth, tipHeight);
var _calculateOffset = calculateOffset(offset),
extraOffset_X = _calculateOffset.extraOffset_X,
extraOffset_Y = _calculateOffset.extraOffset_Y;
var windowWidth = window.innerWidth;
var windowHeight = window.innerHeight;
var _getParent = getParent(node),
parentTop = _getParent.parentTop,
parentLeft = _getParent.parentLeft;
// Get the edge offset of the tooltip
var getTipOffsetLeft = function getTipOffsetLeft(place) {
var offset_X = defaultOffset[place].l;
return mouseX + offset_X + extraOffset_X;
};
var getTipOffsetRight = function getTipOffsetRight(place) {
var offset_X = defaultOffset[place].r;
return mouseX + offset_X + extraOffset_X;
};
var getTipOffsetTop = function getTipOffsetTop(place) {
var offset_Y = defaultOffset[place].t;
return mouseY + offset_Y + extraOffset_Y;
};
var getTipOffsetBottom = function getTipOffsetBottom(place) {
var offset_Y = defaultOffset[place].b;
return mouseY + offset_Y + extraOffset_Y;
};
//
// Functions to test whether the tooltip's sides are inside
// the client window for a given orientation p
//
// _____________
// | | <-- Right side
// | p = 'left' |\
// | |/ |\
// |_____________| |_\ <-- Mouse
// / \ |
// |
// |
// Bottom side
//
var outsideLeft = function outsideLeft(p) {
return getTipOffsetLeft(p) < 0;
};
var outsideRight = function outsideRight(p) {
return getTipOffsetRight(p) > windowWidth;
};
var outsideTop = function outsideTop(p) {
return getTipOffsetTop(p) < 0;
};
var outsideBottom = function outsideBottom(p) {
return getTipOffsetBottom(p) > windowHeight;
};
// Check whether the tooltip with orientation p is completely inside the client window
var outside = function outside(p) {
return outsideLeft(p) || outsideRight(p) || outsideTop(p) || outsideBottom(p);
};
var inside = function inside(p) {
return !outside(p);
};
var placesList = ['top', 'bottom', 'left', 'right'];
var insideList = [];
for (var i = 0; i < 4; i++) {
var p = placesList[i];
if (inside(p)) {
insideList.push(p);
}
}
var isNewState = false;
var newPlace = void 0;
if (inside(desiredPlace) && desiredPlace !== place) {
isNewState = true;
newPlace = desiredPlace;
} else if (insideList.length > 0 && outside(desiredPlace) && outside(place)) {
isNewState = true;
newPlace = insideList[0];
}
if (isNewState) {
return {
isNewState: true,
newState: { place: newPlace }
};
}
return {
isNewState: false,
position: {
left: parseInt(getTipOffsetLeft(place) - parentLeft, 10),
top: parseInt(getTipOffsetTop(place) - parentTop, 10)
}
};
};
var getDimensions = function getDimensions(node) {
var _node$getBoundingClie = node.getBoundingClientRect(),
height = _node$getBoundingClie.height,
width = _node$getBoundingClie.width;
return {
height: parseInt(height, 10),
width: parseInt(width, 10)
};
};
// Get current mouse offset
/**
* Calculate the position of tooltip
*
* @params
* - `e` {Event} the event of current mouse
* - `target` {Element} the currentTarget of the event
* - `node` {DOM} the react-tooltip object
* - `place` {String} top / right / bottom / left
* - `effect` {String} float / solid
* - `offset` {Object} the offset to default position
*
* @return {Object}
* - `isNewState` {Bool} required
* - `newState` {Object}
* - `position` {Object} {left: {Number}, top: {Number}}
*/
var getCurrentOffset = function getCurrentOffset(e, currentTarget, effect) {
var boundingClientRect = currentTarget.getBoundingClientRect();
var targetTop = boundingClientRect.top;
var targetLeft = boundingClientRect.left;
var _getDimensions3 = getDimensions(currentTarget),
targetWidth = _getDimensions3.width,
targetHeight = _getDimensions3.height;
if (effect === 'float') {
return {
mouseX: e.clientX,
mouseY: e.clientY
};
}
return {
mouseX: targetLeft + targetWidth / 2,
mouseY: targetTop + targetHeight / 2
};
};
// List all possibility of tooltip final offset
// This is useful in judging if it is necessary for tooltip to switch position when out of window
var getDefaultPosition = function getDefaultPosition(effect, targetWidth, targetHeight, tipWidth, tipHeight) {
var top = void 0;
var right = void 0;
var bottom = void 0;
var left = void 0;
var disToMouse = 3;
var triangleHeight = 2;
var cursorHeight = 12; // Optimize for float bottom only, cause the cursor will hide the tooltip
if (effect === 'float') {
top = {
l: -(tipWidth / 2),
r: tipWidth / 2,
t: -(tipHeight + disToMouse + triangleHeight),
b: -disToMouse
};
bottom = {
l: -(tipWidth / 2),
r: tipWidth / 2,
t: disToMouse + cursorHeight,
b: tipHeight + disToMouse + triangleHeight + cursorHeight
};
left = {
l: -(tipWidth + disToMouse + triangleHeight),
r: -disToMouse,
t: -(tipHeight / 2),
b: tipHeight / 2
};
right = {
l: disToMouse,
r: tipWidth + disToMouse + triangleHeight,
t: -(tipHeight / 2),
b: tipHeight / 2
};
} else if (effect === 'solid') {
top = {
l: -(tipWidth / 2),
r: tipWidth / 2,
t: -(targetHeight / 2 + tipHeight + triangleHeight),
b: -(targetHeight / 2)
};
bottom = {
l: -(tipWidth / 2),
r: tipWidth / 2,
t: targetHeight / 2,
b: targetHeight / 2 + tipHeight + triangleHeight
};
left = {
l: -(tipWidth + targetWidth / 2 + triangleHeight),
r: -(targetWidth / 2),
t: -(tipHeight / 2),
b: tipHeight / 2
};
right = {
l: targetWidth / 2,
r: tipWidth + targetWidth / 2 + triangleHeight,
t: -(tipHeight / 2),
b: tipHeight / 2
};
}
return { top: top, bottom: bottom, left: left, right: right };
};
// Consider additional offset into position calculation
var calculateOffset = function calculateOffset(offset) {
var extraOffset_X = 0;
var extraOffset_Y = 0;
if (Object.prototype.toString.apply(offset) === '[object String]') {
offset = JSON.parse(offset.toString().replace(/\'/g, '\"'));
}
for (var key in offset) {
if (key === 'top') {
extraOffset_Y -= parseInt(offset[key], 10);
} else if (key === 'bottom') {
extraOffset_Y += parseInt(offset[key], 10);
} else if (key === 'left') {
extraOffset_X -= parseInt(offset[key], 10);
} else if (key === 'right') {
extraOffset_X += parseInt(offset[key], 10);
}
}
return { extraOffset_X: extraOffset_X, extraOffset_Y: extraOffset_Y };
};
// Get the offset of the parent elements
var getParent = function getParent(currentTarget) {
var currentParent = currentTarget;
while (currentParent) {
if (window.getComputedStyle(currentParent).getPropertyValue('transform') !== 'none') break;
currentParent = currentParent.parentElement;
}
var parentTop = currentParent && currentParent.getBoundingClientRect().top || 0;
var parentLeft = currentParent && currentParent.getBoundingClientRect().left || 0;
return { parentTop: parentTop, parentLeft: parentLeft };
};
},{}],23:[function(require,module,exports){
(function (global){
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.default = function (tip, children, getContent, multiline) {
if (children) return children;
if (getContent !== undefined && getContent !== null) return getContent; // getContent can be 0, '', etc.
if (getContent === null) return null; // Tip not exist and childern is null or undefined
var regexp = /<br\s*\/?>/;
if (!multiline || multiline === 'false' || !regexp.test(tip)) {
// No trim(), so that user can keep their input
return tip;
}
// Multiline tooltip content
return tip.split(regexp).map(function (d, i) {
return _react2.default.createElement(
'span',
{ key: i, className: 'multi-line' },
d
);
});
};
var _react = (typeof window !== "undefined" ? window['React'] : typeof global !== "undefined" ? global['React'] : null);
var _react2 = _interopRequireDefault(_react);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
}).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
},{}],24:[function(require,module,exports){
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.default = function (nodeList) {
var length = nodeList.length;
if (nodeList.hasOwnProperty) {
return Array.prototype.slice.call(nodeList);
}
return new Array(length).fill().map(function (index) {
return nodeList[index];
});
};
},{}]},{},[19])(19)
});
| 36.07053 | 8,143 | 0.660787 |
c6285829bdd2a16eb2ec346a2a1da723afd11121 | 104 | js | JavaScript | index.js | rappopo/dab | 81d4d25c078513c501ff30c627994f3176aecd2c | [
"MIT"
] | 4 | 2017-12-09T03:39:45.000Z | 2021-07-23T05:17:16.000Z | index.js | rappopo/dab | 81d4d25c078513c501ff30c627994f3176aecd2c | [
"MIT"
] | null | null | null | index.js | rappopo/dab | 81d4d25c078513c501ff30c627994f3176aecd2c | [
"MIT"
] | null | null | null | 'use strict'
module.exports.Dab = require('./dab')
module.exports.Collection = require('./collection')
| 20.8 | 51 | 0.721154 |
c628e7cc9ba6dddb84488f4ce0645fef48953408 | 48 | js | JavaScript | lib/parcel-plugin-wasm-pack/src/__fixtures__/packager/without-wasm-assets/src/lib.js | A1Liu/tcc | 441ff516d974faec922a73daa02c074a2f0ec21c | [
"MIT"
] | 15 | 2019-04-28T08:05:41.000Z | 2021-01-13T07:56:56.000Z | lib/parcel-plugin-wasm-pack/src/__fixtures__/packager/without-wasm-assets/src/lib.js | A1Liu/tcc | 441ff516d974faec922a73daa02c074a2f0ec21c | [
"MIT"
] | 278 | 2019-04-14T23:25:49.000Z | 2021-08-02T10:17:57.000Z | lib/parcel-plugin-wasm-pack/src/__fixtures__/packager/without-wasm-assets/src/lib.js | A1Liu/tcc | 441ff516d974faec922a73daa02c074a2f0ec21c | [
"MIT"
] | 3 | 2019-05-30T00:49:42.000Z | 2021-10-14T16:29:55.000Z | export function run() {
console.log('run');
}
| 12 | 23 | 0.625 |
c628f4605a39ef298c5698f154f922185df053b4 | 697 | js | JavaScript | src/components/TodoList/index.js | ArturW1998/ReactToDoApp | b8f0d82699faf492a171009038175f6cdde125f6 | [
"MIT"
] | 1 | 2019-12-04T16:23:11.000Z | 2019-12-04T16:23:11.000Z | src/components/TodoList/index.js | ArturW1998/ToDoApp | b8f0d82699faf492a171009038175f6cdde125f6 | [
"MIT"
] | 10 | 2020-04-05T13:27:03.000Z | 2022-02-26T20:59:28.000Z | src/components/TodoList/index.js | ArturW1998/ReactToDoApp | b8f0d82699faf492a171009038175f6cdde125f6 | [
"MIT"
] | null | null | null | import React, { useContext, Fragment } from 'react';
import Paper from '@material-ui/core/Paper';
import List from '@material-ui/core/List';
import Divider from '@material-ui/core/Divider';
import { TodosContext } from '~/context/todos.context';
import Todo from '../Todo';
const TodoList = () => {
const todos = useContext(TodosContext);
const todosLength = todos.length - 1;
if (!todos.length) return null;
return (
<Paper>
<List>
{todos.map((todo, i) => (
<Fragment key={todo.id}>
<Todo {...todo} />
{i < todosLength && <Divider />}
</Fragment>
))}
</List>
</Paper>
);
};
export default TodoList;
| 21.78125 | 55 | 0.583931 |
c62922d078b7d2c3152a647ffd7f038a809b6a30 | 2,646 | js | JavaScript | app/admin/controller/category.js | doubleleee/iMall-server | 75f6ee0282f2e2ee5811504d3ea50d2f6092f5c4 | [
"MIT"
] | 5 | 2018-08-20T08:36:24.000Z | 2019-08-06T07:45:57.000Z | app/admin/controller/category.js | doubleleee/iMall-server | 75f6ee0282f2e2ee5811504d3ea50d2f6092f5c4 | [
"MIT"
] | 1 | 2021-05-11T09:56:48.000Z | 2021-05-11T09:56:48.000Z | app/admin/controller/category.js | doubleleee/iMall-server | 75f6ee0282f2e2ee5811504d3ea50d2f6092f5c4 | [
"MIT"
] | 1 | 2018-10-17T09:32:40.000Z | 2018-10-17T09:32:40.000Z | function _asyncToGenerator(fn) { return function () { var gen = fn.apply(this, arguments); return new Promise(function (resolve, reject) { function step(key, arg) { try { var info = gen[key](arg); var value = info.value; } catch (error) { reject(error); return; } if (info.done) { resolve(value); } else { return Promise.resolve(value).then(function (value) { step("next", value); }, function (err) { step("throw", err); }); } } return step("next"); }); }; }
const Base = require('./base.js');
module.exports = class extends Base {
/**
* index action
* @return {Promise} []
*/
indexAction() {
var _this = this;
return _asyncToGenerator(function* () {
const model = _this.model('category');
const data = yield model.where({ is_show: 1 }).order(['sort_order ASC']).select();
const topCategory = data.filter(function (item) {
return item.parent_id === 0;
});
const categoryList = [];
topCategory.map(function (item) {
item.level = 1;
categoryList.push(item);
data.map(function (child) {
if (child.parent_id === item.id) {
child.level = 2;
categoryList.push(child);
}
});
});
return _this.success(categoryList);
})();
}
topCategoryAction() {
var _this2 = this;
return _asyncToGenerator(function* () {
const model = _this2.model('category');
const data = yield model.where({ parent_id: 0 }).order(['id ASC']).select();
return _this2.success(data);
})();
}
infoAction() {
var _this3 = this;
return _asyncToGenerator(function* () {
const id = _this3.get('id');
const model = _this3.model('category');
const data = yield model.where({ id: id }).find();
return _this3.success(data);
})();
}
storeAction() {
var _this4 = this;
return _asyncToGenerator(function* () {
if (!_this4.isPost) {
return false;
}
const values = _this4.post();
const id = _this4.post('id');
const model = _this4.model('category');
values.is_show = values.is_show ? 1 : 0;
if (id > 0) {
yield model.where({ id: id }).update(values);
} else {
delete values.id;
yield model.add(values);
}
return _this4.success(values);
})();
}
destoryAction() {
var _this5 = this;
return _asyncToGenerator(function* () {
const id = _this5.post('id');
yield _this5.model('category').where({ id: id }).limit(1).delete();
// TODO 删除图片
return _this5.success();
})();
}
};
//# sourceMappingURL=category.js.map | 28.76087 | 458 | 0.575208 |
c629768c2c1b3ab63a5f82c77f90760a252b425d | 3,680 | js | JavaScript | server/api/home.js | maxweng/MADao | 38b7e31a81f7d0e98116057a9c02cbb9ca4e4320 | [
"Apache-2.0"
] | null | null | null | server/api/home.js | maxweng/MADao | 38b7e31a81f7d0e98116057a9c02cbb9ca4e4320 | [
"Apache-2.0"
] | null | null | null | server/api/home.js | maxweng/MADao | 38b7e31a81f7d0e98116057a9c02cbb9ca4e4320 | [
"Apache-2.0"
] | null | null | null | var utils = require('../../utils');
var web3 = utils.web3;
function getBalance(addr, gethRPC) {
var data = utils.response.getDefaultResponse();
try {
var addr = utils.eth.formatAddress(addr);
var balancehex = web3.eth.getBalance(addr, "pending");
//var balance = utils.eth.bchexdec(balancehex);
data["data"] = {
"address": addr,
"balance": balancehex.toString()
}
} catch (e) {
data["error"] = true;
data["msg"] = e.toString();
}
return data;
}
function sendRawTransaction(rawtx, gethRPC) {
var data = utils.response.getDefaultResponse();
try {
data["data"] = web3.eth.sendRawTransaction(rawtx);
} catch (e) {
console.log(e);
data["error"] = true;
data["msg"] = e.toString();
}
return data;
}
function getTransactionData(addr, gethRPC) {
var data = utils.response.getDefaultResponse();
try {
var addr = utils.eth.formatAddress(addr);
var balance = web3.eth.getBalance(addr, "pending");
var nonce = web3.eth.getTransactionCount(addr, "pending");
var gasprice = web3.eth.gasPrice;
//var balance = utils.eth.bchexdec(balance);
data["data"] = {
"address": addr,
"balance": balance,
"nonce": web3.toHex(nonce),
"gasprice": web3.toHex(gasprice)
}
} catch (e) {
console.log(e);
data["error"] = true;
data["msg"] = e.toString();
}
return data;
}
function getTransaction(transactionId, gethRPC) {
var data = utils.response.getDefaultResponse();
try {
data["data"] = web3.eth.getTransaction(transactionId)
} catch (e) {
console.log(e);
data["error"] = true;
data["msg"] = e.toString();
}
return data;
}
function getEstimatedGas(txobj, gethRPC) {
var data = utils.response.getDefaultResponse();
try {
data["data"] = web3.eth.estimateGas(txobj);
} catch (e) {
data["error"] = true;
data["msg"] = e.toString();
}
return data;
}
function getEthCall(txobj, gethRPC) {
var data = utils.response.getDefaultResponse();
try {
data["data"] = web3.eth.call(txobj, "pending");
} catch (e) {
data["error"] = true;
data["msg"] = e.toString();
}
return data;
}
exports = module.exports = function(req, res) {
var data = req.body;
res.header("Access-Control-Allow-Origin", "*");
res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
res.header('Content-Type', 'application/json');
if ("balance" in data) {
var jsonRes = getBalance(data["balance"]);
res.write(JSON.stringify(jsonRes));
res.end();
} else if ("rawtx" in data) {
var jsonRes = sendRawTransaction(data["rawtx"]);
res.write(JSON.stringify(jsonRes));
res.end();
} else if ("txdata" in data) {
var jsonRes = getTransactionData(data["txdata"]);
res.write(JSON.stringify(jsonRes));
res.end();
} else if ("txId" in data) {
var jsonRes = getTransaction(data["txId"]);
res.write(JSON.stringify(jsonRes));
res.end();
} else if ("estimatedGas" in data) {
var jsonRes = getEstimatedGas(data["estimatedGas"]);
res.write(JSON.stringify(jsonRes));
res.end();
} else if ("ethCall" in data) {
var jsonRes = getEthCall(data["ethCall"]);
res.write(JSON.stringify(jsonRes));
res.end();
} else {
console.error('Invalid Request: ' + data);
res.status(400).send();
}
};
| 29.677419 | 97 | 0.571196 |
c62b4d176817c2d131a09c025b22ac587296fbb2 | 15,753 | js | JavaScript | v1.testing/assets/js/993.7f1454f4.js | Ecuashungo/docs.px4.io | e9bc1c35518f9c5203cd74aefd223ba98092d03a | [
"CC-BY-4.0"
] | null | null | null | v1.testing/assets/js/993.7f1454f4.js | Ecuashungo/docs.px4.io | e9bc1c35518f9c5203cd74aefd223ba98092d03a | [
"CC-BY-4.0"
] | null | null | null | v1.testing/assets/js/993.7f1454f4.js | Ecuashungo/docs.px4.io | e9bc1c35518f9c5203cd74aefd223ba98092d03a | [
"CC-BY-4.0"
] | null | null | null | (window.webpackJsonp=window.webpackJsonp||[]).push([[993],{2111:function(e,t,s){"use strict";s.r(t);var a=s(18),n=Object(a.a)({},(function(){var e=this,t=e.$createElement,s=e._self._c||t;return s("ContentSlotsDistributor",{attrs:{"slot-key":e.$parent.slotKey}},[s("h1",{attrs:{id:"manually-generate-client-and-agent-code"}},[s("a",{staticClass:"header-anchor",attrs:{href:"#manually-generate-client-and-agent-code"}},[e._v("#")]),e._v(" Manually Generate Client and Agent Code")]),e._v(" "),s("p",[e._v("This topic shows how to manually generate the code for the client and the agent (instead of "),s("RouterLink",{attrs:{to:"/ko/middleware/micrortps.html"}},[e._v("automatically generating")]),e._v(" it when the PX4 Firmware is compiled).")],1),e._v(" "),s("p",[e._v("The code is generated using the python script: "),s("strong",[e._v("/Tools/generate_microRTPS_bridge.py")]),e._v(".")]),e._v(" "),s("h2",{attrs:{id:"disable-automatic-bridge-code-generation"}},[s("a",{staticClass:"header-anchor",attrs:{href:"#disable-automatic-bridge-code-generation"}},[e._v("#")]),e._v(" Disable automatic bridge code generation")]),e._v(" "),s("p",[e._v("First disable automatic generation of bridge code. Set the variable "),s("code",[e._v("GENERATE_RTPS_BRIDGE")]),e._v(" to "),s("em",[e._v("off")]),e._v(" in the "),s("strong",[e._v(".cmake")]),e._v(" file for the target platform:")]),e._v(" "),s("div",{staticClass:"language-sh extra-class"},[s("pre",{pre:!0,attrs:{class:"language-sh"}},[s("code",[e._v("set"),s("span",{pre:!0,attrs:{class:"token punctuation"}},[e._v("(")]),e._v("GENERATE_RTPS_BRIDGE off"),s("span",{pre:!0,attrs:{class:"token punctuation"}},[e._v(")")]),e._v("\n")])])]),s("h2",{attrs:{id:"using-generate-micrortps-bridge-py"}},[s("a",{staticClass:"header-anchor",attrs:{href:"#using-generate-micrortps-bridge-py"}},[e._v("#")]),e._v(" Using generate_microRTPS_bridge.py")]),e._v(" "),s("p",[e._v("The "),s("em",[e._v("generate_microRTPS_bridge")]),e._v(" tool's command syntax is shown below:")]),e._v(" "),s("div",{staticClass:"language-sh extra-class"},[s("pre",{pre:!0,attrs:{class:"language-sh"}},[s("code",[e._v("$ "),s("span",{pre:!0,attrs:{class:"token builtin class-name"}},[e._v("cd")]),e._v(" /path/to/PX4/Firmware/msg/tools\n$ python generate_microRTPS_bridge.py -h\nusage: generate_microRTPS_bridge.py "),s("span",{pre:!0,attrs:{class:"token punctuation"}},[e._v("[")]),e._v("-h"),s("span",{pre:!0,attrs:{class:"token punctuation"}},[e._v("]")]),e._v(" "),s("span",{pre:!0,attrs:{class:"token punctuation"}},[e._v("[")]),e._v("-s *.msg "),s("span",{pre:!0,attrs:{class:"token punctuation"}},[e._v("[")]),e._v("*.msg "),s("span",{pre:!0,attrs:{class:"token punctuation"}},[e._v("..")]),e._v("."),s("span",{pre:!0,attrs:{class:"token punctuation"}},[e._v("]")]),s("span",{pre:!0,attrs:{class:"token punctuation"}},[e._v("]")]),e._v("\n "),s("span",{pre:!0,attrs:{class:"token punctuation"}},[e._v("[")]),e._v("-r *.msg "),s("span",{pre:!0,attrs:{class:"token punctuation"}},[e._v("[")]),e._v("*.msg "),s("span",{pre:!0,attrs:{class:"token punctuation"}},[e._v("..")]),e._v("."),s("span",{pre:!0,attrs:{class:"token punctuation"}},[e._v("]")]),s("span",{pre:!0,attrs:{class:"token punctuation"}},[e._v("]")]),e._v(" "),s("span",{pre:!0,attrs:{class:"token punctuation"}},[e._v("[")]),e._v("-a"),s("span",{pre:!0,attrs:{class:"token punctuation"}},[e._v("]")]),e._v(" "),s("span",{pre:!0,attrs:{class:"token punctuation"}},[e._v("[")]),e._v("-c"),s("span",{pre:!0,attrs:{class:"token punctuation"}},[e._v("]")]),e._v("\n "),s("span",{pre:!0,attrs:{class:"token punctuation"}},[e._v("[")]),e._v("-t MSGDIR"),s("span",{pre:!0,attrs:{class:"token punctuation"}},[e._v("]")]),e._v(" "),s("span",{pre:!0,attrs:{class:"token punctuation"}},[e._v("[")]),e._v("-o AGENTDIR"),s("span",{pre:!0,attrs:{class:"token punctuation"}},[e._v("]")]),e._v(" "),s("span",{pre:!0,attrs:{class:"token punctuation"}},[e._v("[")]),e._v("-u CLIENTDIR"),s("span",{pre:!0,attrs:{class:"token punctuation"}},[e._v("]")]),e._v("\n "),s("span",{pre:!0,attrs:{class:"token punctuation"}},[e._v("[")]),e._v("-f FASTRTPSGEN"),s("span",{pre:!0,attrs:{class:"token punctuation"}},[e._v("]")]),e._v("\n\noptional arguments:\n -h, --help show this "),s("span",{pre:!0,attrs:{class:"token builtin class-name"}},[e._v("help")]),e._v(" message and "),s("span",{pre:!0,attrs:{class:"token builtin class-name"}},[e._v("exit")]),e._v("\n -s *.msg "),s("span",{pre:!0,attrs:{class:"token punctuation"}},[e._v("[")]),e._v("*.msg "),s("span",{pre:!0,attrs:{class:"token punctuation"}},[e._v("..")]),e._v("."),s("span",{pre:!0,attrs:{class:"token punctuation"}},[e._v("]")]),e._v(", --send *.msg "),s("span",{pre:!0,attrs:{class:"token punctuation"}},[e._v("[")]),e._v("*.msg "),s("span",{pre:!0,attrs:{class:"token punctuation"}},[e._v("..")]),e._v("."),s("span",{pre:!0,attrs:{class:"token punctuation"}},[e._v("]")]),e._v("\n Topics to be sent\n -r *.msg "),s("span",{pre:!0,attrs:{class:"token punctuation"}},[e._v("[")]),e._v("*.msg "),s("span",{pre:!0,attrs:{class:"token punctuation"}},[e._v("..")]),e._v("."),s("span",{pre:!0,attrs:{class:"token punctuation"}},[e._v("]")]),e._v(", --receive *.msg "),s("span",{pre:!0,attrs:{class:"token punctuation"}},[e._v("[")]),e._v("*.msg "),s("span",{pre:!0,attrs:{class:"token punctuation"}},[e._v("..")]),e._v("."),s("span",{pre:!0,attrs:{class:"token punctuation"}},[e._v("]")]),e._v("\n Topics to be received\n -a, --agent Flag to generate the agent. Default is true.\n -c, --client Flag to generate the client. Default is true.\n -t MSGDIR, --topic-msg-dir MSGDIR\n Topics message dir. Default is: msg/\n -o AGENTDIR, --agent-outdir AGENTDIR\n Agent output dir. Default is:\n src/modules/micrortps_bridge/micrortps_agent\n -u CLIENTDIR, --client-outdir CLIENTDIR\n Client output dir. Default is:\n src/modules/micrortps_bridge/micrortps_client\n -f FASTRTPSGEN, --fastrtpsgen-dir FASTRTPSGEN\n fastrtpsgen installation dir. Default is: /bin\n --delete-tree Delete "),s("span",{pre:!0,attrs:{class:"token function"}},[e._v("dir")]),e._v(" tree output dir"),s("span",{pre:!0,attrs:{class:"token punctuation"}},[e._v("(")]),e._v("s"),s("span",{pre:!0,attrs:{class:"token punctuation"}},[e._v(")")]),e._v("\n")])])]),s("p",[e._v(":::caution\nUsing with "),s("code",[e._v("--delete-tree")]),e._v(" option erases the content of the "),s("code",[e._v("CLIENTDIR")]),e._v(" and the "),s("code",[e._v("AGENTDIR")]),e._v(" before creating new files and folders.\n:::")]),e._v(" "),s("ul",[s("li",[e._v("The arguments "),s("code",[e._v("--send/-s")]),e._v(" and "),s("code",[e._v("--receive/-r")]),e._v(" specify the uORB topics that can be sent/received from PX4. Code will only be generated for specified messages.")]),e._v(" "),s("li",[e._v("The output appears in "),s("code",[e._v("CLIENTDIR")]),e._v(" ("),s("code",[e._v("-o src/modules/micrortps_bridge/micrortps_client")]),e._v(", by default) and in the "),s("code",[e._v("AGENTDIR")]),e._v(" ("),s("code",[e._v("-u src/modules/micrortps_bridge/micrortps_agent")]),e._v(", by default).")]),e._v(" "),s("li",[e._v("If no flag "),s("code",[e._v("-a")]),e._v(" or "),s("code",[e._v("-c")]),e._v(" is specified, both the client and the agent will be generated and installed.")]),e._v(" "),s("li",[e._v("The "),s("code",[e._v("-f")]),e._v(" option may be needed if "),s("em",[e._v("Fast RTPS")]),e._v(" was not installed in the default location ("),s("code",[e._v("-f /path/to/fastrtps/installation/bin")]),e._v(").")])]),e._v(" "),s("p",[e._v("The example below shows how you can generate bridge code to publish/subscribe just the "),s("code",[e._v("sensor_baro")]),e._v(" single uORB topic.")]),e._v(" "),s("div",{staticClass:"language-sh extra-class"},[s("pre",{pre:!0,attrs:{class:"language-sh"}},[s("code",[e._v("$ "),s("span",{pre:!0,attrs:{class:"token builtin class-name"}},[e._v("cd")]),e._v(" /path/to/PX4/Firmware\n$ python Tools/generate_microRTPS_bridge.py -s msg/sensor_baro.msg -r msg/sensor_combined.msg\n")])])]),s("h2",{attrs:{id:"generated-code"}},[s("a",{staticClass:"header-anchor",attrs:{href:"#generated-code"}},[e._v("#")]),e._v(" Generated code")]),e._v(" "),s("p",[e._v("Code is generated for the "),s("em",[e._v("Client")]),e._v(", "),s("em",[e._v("Agent")]),e._v(", "),s("em",[e._v("CDR serialization/deserialization")]),e._v(" of uORB messages, and the definition of the associated RTPS messages (IDL files).")]),e._v(" "),s("p",[e._v("Manually generated code for the bridge can be found here (by default):")]),e._v(" "),s("ul",[s("li",[s("em",[e._v("Client")]),e._v(": "),s("strong",[e._v("src/modules/micrortps_bridge/micrortps_client/")])]),e._v(" "),s("li",[s("em",[e._v("Agent")]),e._v(": "),s("strong",[e._v("src/modules/micrortps_bridge/micrortps_agent/")])])]),e._v(" "),s("h3",{attrs:{id:"uorb-serialization-code"}},[s("a",{staticClass:"header-anchor",attrs:{href:"#uorb-serialization-code"}},[e._v("#")]),e._v(" uORB serialization code")]),e._v(" "),s("p",[e._v("Serialization functions are generated for all the uORB topics as part of the normal PX4 compilation process (and also for manual generation). For example, the following functions would be generated for the "),s("em",[e._v("sensor_combined.msg")]),e._v(":")]),e._v(" "),s("div",{staticClass:"language-sh extra-class"},[s("pre",{pre:!0,attrs:{class:"language-sh"}},[s("code",[e._v("void serialize_sensor_combined"),s("span",{pre:!0,attrs:{class:"token punctuation"}},[e._v("(")]),e._v("const struct sensor_combined_s *input, char *output, uint32_t *length, struct microCDR *microCDRWriter"),s("span",{pre:!0,attrs:{class:"token punctuation"}},[e._v(")")]),s("span",{pre:!0,attrs:{class:"token punctuation"}},[e._v(";")]),e._v("\nvoid deserialize_sensor_combined"),s("span",{pre:!0,attrs:{class:"token punctuation"}},[e._v("(")]),e._v("struct sensor_combined_s *output, char *input, struct microCDR *microCDRReader"),s("span",{pre:!0,attrs:{class:"token punctuation"}},[e._v(")")]),s("span",{pre:!0,attrs:{class:"token punctuation"}},[e._v(";")]),e._v("\n")])])]),s("h3",{attrs:{id:"rtps-message-idl-files"}},[s("a",{staticClass:"header-anchor",attrs:{href:"#rtps-message-idl-files"}},[e._v("#")]),e._v(" RTPS message IDL files")]),e._v(" "),s("p",[e._v("IDL files are generated from the uORB "),s("strong",[e._v(".msg")]),e._v(" files ("),s("RouterLink",{attrs:{to:"/ko/middleware/micrortps.html#supported-uorb-messages"}},[e._v("for selected uORB topics")]),e._v(") in the generation of the bridge. These can be found in: "),s("strong",[e._v("src/modules/micrortps_bridge/micrortps_agent/idl/")])],1),e._v(" "),s("p",[s("em",[e._v("FastRTSP")]),e._v(" uses IDL files to define the structure of RTPS messages (in this case, RTPS messages that map to uORB topics). They are used to generate code for the "),s("em",[e._v("Agent")]),e._v(", and "),s("em",[e._v("FastRTSP")]),e._v(" applications that need to publish/subscribe to uORB topics.")]),e._v(" "),s("div",{staticClass:"custom-block note"},[s("p",{staticClass:"custom-block-title"},[e._v("Note")]),e._v(" "),s("p",[e._v("IDL files are compiled to C++ by the "),s("em",[e._v("fastrtpsgen")]),e._v(" tool.")])]),e._v(" "),s("h2",{attrs:{id:"verify-code-generation"}},[s("a",{staticClass:"header-anchor",attrs:{href:"#verify-code-generation"}},[e._v("#")]),e._v(" Verify code generation")]),e._v(" "),s("p",[e._v("You can verify successful code generation by checking that the output directories match the listing shown below (On Linux, the "),s("code",[e._v("tree")]),e._v(" command can be used for listing the file structure).")]),e._v(" "),s("p",[e._v("The manually generated "),s("em",[e._v("Client")]),e._v(" code is built and used in "),s("em",[e._v("exactly")]),e._v(" the same way as "),s("RouterLink",{attrs:{to:"/ko/middleware/micrortps.html#client-px4-firmware"}},[e._v("automatically generated Client code")]),e._v(".")],1),e._v(" "),s("div",{staticClass:"language-sh extra-class"},[s("pre",{pre:!0,attrs:{class:"language-sh"}},[s("code",[e._v("$ tree src/modules/micrortps_bridge/micrortps_agent\nsrc/modules/micrortps_bridge/micrortps_agent\n├── build\n├── CMakeLists.txt\n├── idl\n│ ├── sensor_baro_.idl\n│ └── sensor_combined_.idl\n├── microRTPS_agent.cpp\n├── microRTPS_transport.cpp\n├── microRTPS_transport.h\n├── RtpsTopics.cpp\n├── RtpsTopics.h\n├── sensor_baro_.cpp\n├── sensor_baro_.h\n├── sensor_baro_Publisher.cpp\n├── sensor_baro_Publisher.h\n├── sensor_baro_PubSubTypes.cpp\n├── sensor_baro_PubSubTypes.h\n├── sensor_combined_.cpp\n├── sensor_combined_.h\n├── sensor_combined_PubSubTypes.cpp\n├── sensor_combined_PubSubTypes.h\n├── sensor_combined_Subscriber.cpp\n└── sensor_combined_Subscriber.h\n "),s("span",{pre:!0,attrs:{class:"token number"}},[e._v("2")]),e._v(" directories, "),s("span",{pre:!0,attrs:{class:"token number"}},[e._v("20")]),e._v(" files\n")])])]),s("p",[e._v("Client directory:")]),e._v(" "),s("div",{staticClass:"language-sh extra-class"},[s("pre",{pre:!0,attrs:{class:"language-sh"}},[s("code",[e._v("$ tree src/modules/micrortps_bridge/micrortps_client\nsrc/modules/micrortps_bridge/micrortps_client\n├── CMakeLists.txt\n├── microRTPS_client.cpp\n├── microRTPS_client_dummy.cpp\n├── microRTPS_client_main.cpp\n├── microRTPS_transport.cpp\n└── microRTPS_transport.h\n "),s("span",{pre:!0,attrs:{class:"token number"}},[e._v("0")]),e._v(" directories, "),s("span",{pre:!0,attrs:{class:"token number"}},[e._v("4")]),e._v(" files\n")])])]),s("h2",{attrs:{id:"build-and-use-the-code"}},[s("a",{staticClass:"header-anchor",attrs:{href:"#build-and-use-the-code"}},[e._v("#")]),e._v(" Build and use the code")]),e._v(" "),s("p",[e._v("The manually generated "),s("em",[e._v("Client")]),e._v(" code is built and used in "),s("em",[e._v("exactly")]),e._v(" the same way as "),s("RouterLink",{attrs:{to:"/ko/middleware/micrortps.html#client_firmware"}},[e._v("automatically generated Client code")]),e._v(".")],1),e._v(" "),s("p",[e._v("Specifically, once manually generated, the "),s("em",[e._v("Client")]),e._v(" source code is compiled and built into the PX4 firmware as part of the normal build process. For example, to compile the code and include it in firmware for NuttX/Pixhawk targets:")]),e._v(" "),s("div",{staticClass:"language-sh extra-class"},[s("pre",{pre:!0,attrs:{class:"language-sh"}},[s("code",[s("span",{pre:!0,attrs:{class:"token function"}},[e._v("make")]),e._v(" px4_fmu-v4_default upload\n")])])]),s("div",{staticClass:"custom-block note"},[s("p",{staticClass:"custom-block-title"},[e._v("Note")]),e._v(" "),s("p",[e._v("You must first "),s("a",{attrs:{href:"#disable-automatic-bridge-code-generation"}},[e._v("disable automatic bridge code generation")]),e._v(" so that the toolchain uses the manually generated source code (and does not attempt to regenerate it).")])]),e._v(" "),s("p",[e._v("The manually generated "),s("em",[e._v("Agent")]),e._v(" code is also compiled and used in the same way as the "),s("RouterLink",{attrs:{to:"/ko/middleware/micrortps.html#agent-in-a-ros-independent-offboard-fast-rtps-interface"}},[e._v("automatically generated code")]),e._v(". The only difference is that the manually source code is created in "),s("strong",[e._v("src/modules/micrortps_bridge/micrortps_agent")]),e._v(" instead of "),s("strong",[s("emphasis",[e._v("build/BUILDPLATFORM")])],1),s("strong",[e._v("/src/modules/micrortps_bridge/micrortps_agent/")]),e._v(".")],1)])}),[],!1,null,null,null);t.default=n.exports}}]); | 15,753 | 15,753 | 0.625532 |
c62bae056a2a95ba8ac87ac2652a00057f0774b7 | 592 | js | JavaScript | linuxprobe.js | zhubinqiang/tampermonkey_js | e2d9060f1707b0b375b2e5e61d9ce05ff0c5f484 | [
"MIT"
] | 1 | 2020-08-08T14:57:01.000Z | 2020-08-08T14:57:01.000Z | linuxprobe.js | zhubinqiang/tampermonkey_js | e2d9060f1707b0b375b2e5e61d9ce05ff0c5f484 | [
"MIT"
] | null | null | null | linuxprobe.js | zhubinqiang/tampermonkey_js | e2d9060f1707b0b375b2e5e61d9ce05ff0c5f484 | [
"MIT"
] | null | null | null | // ==UserScript==
// @name nuxprobe
// @namespace https://github.com/zhubinqiang/tampermonkey_js
// @version 0.1
// @description block some ads
// @author Zhu,binqiang
// @match https://www.linuxprobe.com/*
// @grant none
// @require https://cdn.bootcss.com/jquery/3.2.1/jquery.min.js
// ==/UserScript==
(function() {
'use strict';
// Your code here...
$().ready(function() {
$("#text-36").hide();
$("#text-37").hide();
$("#text-38").hide();
$("#text-41").hide();
$(".ad").hide();
});
})();
| 23.68 | 67 | 0.503378 |
c62bda180d5fa22b7e28c9e10dbe98db5d1dd189 | 489 | js | JavaScript | src/component/message/Message.js | anselmozago/reactjs-chart-plot | 7d86c8bbcabab24dbc3f8a91a8f0a33b4b615de8 | [
"MIT"
] | null | null | null | src/component/message/Message.js | anselmozago/reactjs-chart-plot | 7d86c8bbcabab24dbc3f8a91a8f0a33b4b615de8 | [
"MIT"
] | null | null | null | src/component/message/Message.js | anselmozago/reactjs-chart-plot | 7d86c8bbcabab24dbc3f8a91a8f0a33b4b615de8 | [
"MIT"
] | null | null | null | import React from 'react'
import PropTypes from 'prop-types';
const Message = props => {
return (
<div className="messageBox">
<div className="messageTitle">
<h1>{props.title}</h1>
</div>
<p className="messageText">{props.message}</p>
<p>{props.children}</p>
</div>
)
}
Message.propTypes = {
title: PropTypes.string.isRequired,
message: PropTypes.string.isRequired,
}
export default Message | 23.285714 | 58 | 0.580777 |
c62bdc0275b07b757e52d873f758f7320101a40a | 3,247 | js | JavaScript | client_04/src/auth/Auth.js | chk-code/cdnd-05-3dinpainting | ab5f16c00c828c255013ba2a0cbc1dc0819d057b | [
"MIT"
] | null | null | null | client_04/src/auth/Auth.js | chk-code/cdnd-05-3dinpainting | ab5f16c00c828c255013ba2a0cbc1dc0819d057b | [
"MIT"
] | null | null | null | client_04/src/auth/Auth.js | chk-code/cdnd-05-3dinpainting | ab5f16c00c828c255013ba2a0cbc1dc0819d057b | [
"MIT"
] | null | null | null | import auth0 from 'auth0-js';
import { authConfig } from '../config';
export default class Auth {
accessToken;
idToken;
expiresAt;
auth0 = new auth0.WebAuth({
domain: authConfig.domain,
clientID: authConfig.clientId,
redirectUri: authConfig.callbackUrl,
responseType: 'token id_token',
scope: 'openid'
});
constructor(history) {
this.history = history
this.login = this.login.bind(this);
this.logout = this.logout.bind(this);
this.handleAuthentication = this.handleAuthentication.bind(this);
this.isAuthenticated = this.isAuthenticated.bind(this);
this.getAccessToken = this.getAccessToken.bind(this);
this.getIdToken = this.getIdToken.bind(this);
this.renewSession = this.renewSession.bind(this);
}
login() {
this.auth0.authorize();
//this.auth0.popup.authorize({}, function(err, response) {}); User popup for login
}
handleAuthentication() {
this.auth0.parseHash((err, authResult) => {
if (authResult && authResult.accessToken && authResult.idToken) {
console.log('Access token: ', authResult.accessToken)
console.log('id token: ', authResult.idToken)
this.setSession(authResult);
//this.auth0.popup.callback(); Close popup after auth
} else if (err) {
this.history.replace('/');
console.log(err);
alert(`Error: ${err.error}. Check the console for further details.`);
}
});
}
getAccessToken() {
return this.accessToken;
}
getIdToken() {
return this.idToken;
}
setSession(authResult) {
// Set isLoggedIn flag in localStorage
localStorage.setItem('isLoggedIn', 'true');
// Set the time that the access token will expire at
let expiresAt = (authResult.expiresIn * 1000) + new Date().getTime();
this.accessToken = authResult.accessToken;
this.idToken = authResult.idToken;
this.expiresAt = expiresAt;
// navigate to the home route
this.history.replace('/');
}
renewSession() {
this.auth0.checkSession({}, (err, authResult) => {
if (authResult && authResult.accessToken && authResult.idToken) {
this.setSession(authResult);
} else if (err) {
this.logout();
console.log(err);
alert(`Could not get a new token (${err.error}: ${err.error_description}).`);
}
});
}
logout() {
// Remove tokens and expiry time
this.accessToken = null;
this.idToken = null;
this.expiresAt = 0;
// Remove isLoggedIn flag from localStorage
localStorage.removeItem('isLoggedIn');
this.auth0.logout({
//return_to: window.location.origin
returnTo: 'http://localhost:3000',
clientID: 'ETvMUHWVGQqIneQ0dSDOAzcCp65RuSLF',
});
// navigate to the home route
this.history.replace('/');
}
isAuthenticated() {
// Check whether the current time is past the
// access token's expiry time
let expiresAt = this.expiresAt;
return new Date().getTime() < expiresAt;
}
silentAuth() {
return new Promise((resolve, reject) => {
this.auth0.checkSession({}, (err, authResult) => {
if (err) return reject(err);
this.setSession(authResult);
resolve();
});
});
}
}
| 27.516949 | 86 | 0.63782 |
c62c4c426f889d8d18c3f0455d278df04ab01a8f | 21,107 | js | JavaScript | node_modules/element-plus/lib/components/form/index.js | Miaohu666/vue_main | cca921b0459b1777975d6277859d066a7f8a138e | [
"Apache-2.0"
] | null | null | null | node_modules/element-plus/lib/components/form/index.js | Miaohu666/vue_main | cca921b0459b1777975d6277859d066a7f8a138e | [
"Apache-2.0"
] | null | null | null | node_modules/element-plus/lib/components/form/index.js | Miaohu666/vue_main | cca921b0459b1777975d6277859d066a7f8a138e | [
"Apache-2.0"
] | null | null | null | 'use strict';
Object.defineProperty(exports, '__esModule', { value: true });
var vue = require('vue');
var mitt = require('mitt');
var tokens = require('../../tokens');
var AsyncValidator = require('async-validator');
var shared = require('@vue/shared');
var util = require('../../utils/util');
var validators = require('../../utils/validators');
var resizeEvent = require('../../utils/resize-event');
function _interopDefaultLegacy (e) { return e && typeof e === 'object' && 'default' in e ? e : { 'default': e }; }
var mitt__default = /*#__PURE__*/_interopDefaultLegacy(mitt);
var AsyncValidator__default = /*#__PURE__*/_interopDefaultLegacy(AsyncValidator);
var __defProp = Object.defineProperty;
var __defProps = Object.defineProperties;
var __getOwnPropDescs = Object.getOwnPropertyDescriptors;
var __getOwnPropSymbols = Object.getOwnPropertySymbols;
var __hasOwnProp = Object.prototype.hasOwnProperty;
var __propIsEnum = Object.prototype.propertyIsEnumerable;
var __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
var __spreadValues = (a, b) => {
for (var prop in b || (b = {}))
if (__hasOwnProp.call(b, prop))
__defNormalProp(a, prop, b[prop]);
if (__getOwnPropSymbols)
for (var prop of __getOwnPropSymbols(b)) {
if (__propIsEnum.call(b, prop))
__defNormalProp(a, prop, b[prop]);
}
return a;
};
var __spreadProps = (a, b) => __defProps(a, __getOwnPropDescs(b));
function useFormLabelWidth() {
const potentialLabelWidthArr = vue.ref([]);
const autoLabelWidth = vue.computed(() => {
if (!potentialLabelWidthArr.value.length)
return "0";
const max = Math.max(...potentialLabelWidthArr.value);
return max ? `${max}px` : "";
});
function getLabelWidthIndex(width) {
const index = potentialLabelWidthArr.value.indexOf(width);
if (index === -1) {
console.warn("[Element Warn][ElementForm]unexpected width " + width);
}
return index;
}
function registerLabelWidth(val, oldVal) {
if (val && oldVal) {
const index = getLabelWidthIndex(oldVal);
potentialLabelWidthArr.value.splice(index, 1, val);
} else if (val) {
potentialLabelWidthArr.value.push(val);
}
}
function deregisterLabelWidth(val) {
const index = getLabelWidthIndex(val);
index > -1 && potentialLabelWidthArr.value.splice(index, 1);
}
return {
autoLabelWidth,
registerLabelWidth,
deregisterLabelWidth
};
}
var script = vue.defineComponent({
name: "ElForm",
props: {
model: Object,
rules: Object,
labelPosition: String,
labelWidth: {
type: [String, Number],
default: ""
},
labelSuffix: {
type: String,
default: ""
},
inline: Boolean,
inlineMessage: Boolean,
statusIcon: Boolean,
showMessage: {
type: Boolean,
default: true
},
size: String,
disabled: Boolean,
validateOnRuleChange: {
type: Boolean,
default: true
},
hideRequiredAsterisk: {
type: Boolean,
default: false
},
scrollToError: Boolean
},
emits: ["validate"],
setup(props, { emit }) {
const formMitt = mitt__default['default']();
const fields = [];
vue.watch(() => props.rules, () => {
fields.forEach((field) => {
field.removeValidateEvents();
field.addValidateEvents();
});
if (props.validateOnRuleChange) {
validate(() => ({}));
}
});
formMitt.on(tokens.elFormEvents.addField, (field) => {
if (field) {
fields.push(field);
}
});
formMitt.on(tokens.elFormEvents.removeField, (field) => {
if (field.prop) {
fields.splice(fields.indexOf(field), 1);
}
});
const resetFields = () => {
if (!props.model) {
console.warn("[Element Warn][Form]model is required for resetFields to work.");
return;
}
fields.forEach((field) => {
field.resetField();
});
};
const clearValidate = (props2 = []) => {
const fds = props2.length ? typeof props2 === "string" ? fields.filter((field) => props2 === field.prop) : fields.filter((field) => props2.indexOf(field.prop) > -1) : fields;
fds.forEach((field) => {
field.clearValidate();
});
};
const validate = (callback) => {
if (!props.model) {
console.warn("[Element Warn][Form]model is required for validate to work!");
return;
}
let promise;
if (typeof callback !== "function") {
promise = new Promise((resolve, reject) => {
callback = function(valid2, invalidFields2) {
if (valid2) {
resolve(true);
} else {
reject(invalidFields2);
}
};
});
}
if (fields.length === 0) {
callback(true);
}
let valid = true;
let count = 0;
let invalidFields = {};
let firstInvalidFields;
for (const field of fields) {
field.validate("", (message, field2) => {
if (message) {
valid = false;
firstInvalidFields || (firstInvalidFields = field2);
}
invalidFields = __spreadValues(__spreadValues({}, invalidFields), field2);
if (++count === fields.length) {
callback(valid, invalidFields);
}
});
}
if (!valid && props.scrollToError) {
scrollToField(Object.keys(firstInvalidFields)[0]);
}
return promise;
};
const validateField = (props2, cb) => {
props2 = [].concat(props2);
const fds = fields.filter((field) => props2.indexOf(field.prop) !== -1);
if (!fields.length) {
console.warn("[Element Warn]please pass correct props!");
return;
}
fds.forEach((field) => {
field.validate("", cb);
});
};
const scrollToField = (prop) => {
fields.forEach((item) => {
if (item.prop === prop) {
item.$el.scrollIntoView();
}
});
};
const elForm = vue.reactive(__spreadValues(__spreadProps(__spreadValues({
formMitt
}, vue.toRefs(props)), {
resetFields,
clearValidate,
validateField,
emit
}), useFormLabelWidth()));
vue.provide(tokens.elFormKey, elForm);
return {
validate,
resetFields,
clearValidate,
validateField,
scrollToField
};
}
});
function render(_ctx, _cache, $props, $setup, $data, $options) {
return vue.openBlock(), vue.createElementBlock("form", {
class: vue.normalizeClass(["el-form", [
_ctx.labelPosition ? "el-form--label-" + _ctx.labelPosition : "",
{ "el-form--inline": _ctx.inline }
]])
}, [
vue.renderSlot(_ctx.$slots, "default")
], 2);
}
script.render = render;
script.__file = "packages/components/form/src/form.vue";
var LabelWrap = vue.defineComponent({
name: "ElLabelWrap",
props: {
isAutoWidth: Boolean,
updateAll: Boolean
},
setup(props, { slots }) {
const el = vue.ref(null);
const elForm = vue.inject(tokens.elFormKey);
const elFormItem = vue.inject(tokens.elFormItemKey);
const computedWidth = vue.ref(0);
vue.watch(computedWidth, (val, oldVal) => {
if (props.updateAll) {
elForm.registerLabelWidth(val, oldVal);
elFormItem.updateComputedLabelWidth(val);
}
});
const getLabelWidth = () => {
var _a;
if ((_a = el.value) == null ? void 0 : _a.firstElementChild) {
const width = window.getComputedStyle(el.value.firstElementChild).width;
return Math.ceil(parseFloat(width));
} else {
return 0;
}
};
const updateLabelWidth = (action = "update") => {
vue.nextTick(() => {
if (slots.default && props.isAutoWidth) {
if (action === "update") {
computedWidth.value = getLabelWidth();
} else if (action === "remove") {
elForm.deregisterLabelWidth(computedWidth.value);
}
}
});
};
const updateLabelWidthFn = () => updateLabelWidth("update");
vue.onMounted(() => {
resizeEvent.addResizeListener(el.value.firstElementChild, updateLabelWidthFn);
updateLabelWidthFn();
});
vue.onUpdated(updateLabelWidthFn);
vue.onBeforeUnmount(() => {
updateLabelWidth("remove");
resizeEvent.removeResizeListener(el.value.firstElementChild, updateLabelWidthFn);
});
function render() {
var _a, _b;
if (!slots)
return null;
if (props.isAutoWidth) {
const autoLabelWidth = elForm.autoLabelWidth;
const style = {};
if (autoLabelWidth && autoLabelWidth !== "auto") {
const marginWidth = Math.max(0, parseInt(autoLabelWidth, 10) - computedWidth.value);
const marginPosition = elForm.labelPosition === "left" ? "marginRight" : "marginLeft";
if (marginWidth) {
style[marginPosition] = marginWidth + "px";
}
}
return vue.h("div", {
ref: el,
class: ["el-form-item__label-wrap"],
style
}, (_a = slots.default) == null ? void 0 : _a.call(slots));
} else {
return vue.h(vue.Fragment, { ref: el }, (_b = slots.default) == null ? void 0 : _b.call(slots));
}
}
return render;
}
});
var __defProp$1 = Object.defineProperty;
var __defProps$1 = Object.defineProperties;
var __getOwnPropDescs$1 = Object.getOwnPropertyDescriptors;
var __getOwnPropSymbols$1 = Object.getOwnPropertySymbols;
var __hasOwnProp$1 = Object.prototype.hasOwnProperty;
var __propIsEnum$1 = Object.prototype.propertyIsEnumerable;
var __defNormalProp$1 = (obj, key, value) => key in obj ? __defProp$1(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
var __spreadValues$1 = (a, b) => {
for (var prop in b || (b = {}))
if (__hasOwnProp$1.call(b, prop))
__defNormalProp$1(a, prop, b[prop]);
if (__getOwnPropSymbols$1)
for (var prop of __getOwnPropSymbols$1(b)) {
if (__propIsEnum$1.call(b, prop))
__defNormalProp$1(a, prop, b[prop]);
}
return a;
};
var __spreadProps$1 = (a, b) => __defProps$1(a, __getOwnPropDescs$1(b));
var script$1 = vue.defineComponent({
name: "ElFormItem",
componentName: "ElFormItem",
components: {
LabelWrap
},
props: {
label: String,
labelWidth: {
type: [String, Number],
default: ""
},
prop: String,
required: {
type: Boolean,
default: void 0
},
rules: [Object, Array],
error: String,
validateStatus: String,
for: String,
inlineMessage: {
type: [String, Boolean],
default: ""
},
showMessage: {
type: Boolean,
default: true
},
size: {
type: String,
validator: validators.isValidComponentSize
}
},
setup(props, { slots }) {
const formItemMitt = mitt__default['default']();
const $ELEMENT = util.useGlobalConfig();
const elForm = vue.inject(tokens.elFormKey, {});
const validateState = vue.ref("");
const validateMessage = vue.ref("");
const validateDisabled = vue.ref(false);
const computedLabelWidth = vue.ref("");
const formItemRef = vue.ref();
const vm = vue.getCurrentInstance();
const isNested = vue.computed(() => {
let parent = vm.parent;
while (parent && parent.type.name !== "ElForm") {
if (parent.type.name === "ElFormItem") {
return true;
}
parent = parent.parent;
}
return false;
});
let initialValue = void 0;
vue.watch(() => props.error, (val) => {
validateMessage.value = val;
validateState.value = val ? "error" : "";
}, {
immediate: true
});
vue.watch(() => props.validateStatus, (val) => {
validateState.value = val;
});
const labelFor = vue.computed(() => props.for || props.prop);
const labelStyle = vue.computed(() => {
const ret = {};
if (elForm.labelPosition === "top")
return ret;
const labelWidth = util.addUnit(props.labelWidth) || util.addUnit(elForm.labelWidth);
if (labelWidth) {
ret.width = labelWidth;
}
return ret;
});
const contentStyle = vue.computed(() => {
const ret = {};
if (elForm.labelPosition === "top" || elForm.inline) {
return ret;
}
if (!props.label && !props.labelWidth && isNested.value) {
return ret;
}
const labelWidth = util.addUnit(props.labelWidth) || util.addUnit(elForm.labelWidth);
if (!props.label && !slots.label) {
ret.marginLeft = labelWidth;
}
return ret;
});
const fieldValue = vue.computed(() => {
const model = elForm.model;
if (!model || !props.prop) {
return;
}
let path = props.prop;
if (path.indexOf(":") !== -1) {
path = path.replace(/:/, ".");
}
return util.getPropByPath(model, path, true).v;
});
const isRequired = vue.computed(() => {
let rules = getRules();
let required = false;
if (rules && rules.length) {
rules.every((rule) => {
if (rule.required) {
required = true;
return false;
}
return true;
});
}
return required;
});
const elFormItemSize = vue.computed(() => props.size || elForm.size);
const sizeClass = vue.computed(() => {
return elFormItemSize.value || $ELEMENT.size;
});
const validate = (trigger, callback = shared.NOOP) => {
validateDisabled.value = false;
const rules = getFilteredRule(trigger);
if ((!rules || rules.length === 0) && props.required === void 0) {
callback();
return;
}
validateState.value = "validating";
const descriptor = {};
if (rules && rules.length > 0) {
rules.forEach((rule) => {
delete rule.trigger;
});
}
descriptor[props.prop] = rules;
const validator = new AsyncValidator__default['default'](descriptor);
const model = {};
model[props.prop] = fieldValue.value;
validator.validate(model, { firstFields: true }, (errors, invalidFields) => {
var _a;
validateState.value = !errors ? "success" : "error";
validateMessage.value = errors ? errors[0].message : "";
callback(validateMessage.value, invalidFields);
(_a = elForm.emit) == null ? void 0 : _a.call(elForm, "validate", props.prop, !errors, validateMessage.value || null);
});
};
const clearValidate = () => {
validateState.value = "";
validateMessage.value = "";
validateDisabled.value = false;
};
const resetField = () => {
validateState.value = "";
validateMessage.value = "";
let model = elForm.model;
let value = fieldValue.value;
let path = props.prop;
if (path.indexOf(":") !== -1) {
path = path.replace(/:/, ".");
}
let prop = util.getPropByPath(model, path, true);
validateDisabled.value = true;
if (Array.isArray(value)) {
prop.o[prop.k] = [].concat(initialValue);
} else {
prop.o[prop.k] = initialValue;
}
vue.nextTick(() => {
validateDisabled.value = false;
});
};
const getRules = () => {
const formRules = elForm.rules;
const selfRules = props.rules;
const requiredRule = props.required !== void 0 ? { required: !!props.required } : [];
const prop = util.getPropByPath(formRules, props.prop || "", false);
const normalizedRule = formRules ? prop.o[props.prop || ""] || prop.v : [];
return [].concat(selfRules || normalizedRule || []).concat(requiredRule);
};
const getFilteredRule = (trigger) => {
const rules = getRules();
return rules.filter((rule) => {
if (!rule.trigger || trigger === "")
return true;
if (Array.isArray(rule.trigger)) {
return rule.trigger.indexOf(trigger) > -1;
} else {
return rule.trigger === trigger;
}
}).map((rule) => __spreadValues$1({}, rule));
};
const onFieldBlur = () => {
validate("blur");
};
const onFieldChange = () => {
if (validateDisabled.value) {
validateDisabled.value = false;
return;
}
validate("change");
};
const updateComputedLabelWidth = (width) => {
computedLabelWidth.value = width ? `${width}px` : "";
};
const addValidateEvents = () => {
const rules = getRules();
if (rules.length || props.required !== void 0) {
formItemMitt.on("el.form.blur", onFieldBlur);
formItemMitt.on("el.form.change", onFieldChange);
}
};
const removeValidateEvents = () => {
formItemMitt.off("el.form.blur", onFieldBlur);
formItemMitt.off("el.form.change", onFieldChange);
};
const elFormItem = vue.reactive(__spreadProps$1(__spreadValues$1({}, vue.toRefs(props)), {
size: sizeClass,
validateState,
$el: formItemRef,
formItemMitt,
removeValidateEvents,
addValidateEvents,
resetField,
clearValidate,
validate,
updateComputedLabelWidth
}));
vue.onMounted(() => {
var _a;
if (props.prop) {
(_a = elForm.formMitt) == null ? void 0 : _a.emit(tokens.elFormEvents.addField, elFormItem);
let value = fieldValue.value;
initialValue = Array.isArray(value) ? [...value] : value;
addValidateEvents();
}
});
vue.onBeforeUnmount(() => {
var _a;
(_a = elForm.formMitt) == null ? void 0 : _a.emit(tokens.elFormEvents.removeField, elFormItem);
});
vue.provide(tokens.elFormItemKey, elFormItem);
const formItemClass = vue.computed(() => [
{
"el-form-item--feedback": elForm.statusIcon,
"is-error": validateState.value === "error",
"is-validating": validateState.value === "validating",
"is-success": validateState.value === "success",
"is-required": isRequired.value || props.required,
"is-no-asterisk": elForm.hideRequiredAsterisk
},
sizeClass.value ? "el-form-item--" + sizeClass.value : ""
]);
const shouldShowError = vue.computed(() => {
return validateState.value === "error" && props.showMessage && elForm.showMessage;
});
return {
formItemRef,
formItemClass,
shouldShowError,
elForm,
labelStyle,
contentStyle,
validateMessage,
labelFor,
resetField,
clearValidate
};
}
});
const _hoisted_1 = ["for"];
function render$1(_ctx, _cache, $props, $setup, $data, $options) {
const _component_LabelWrap = vue.resolveComponent("LabelWrap");
return vue.openBlock(), vue.createElementBlock("div", {
ref: "formItemRef",
class: vue.normalizeClass(["el-form-item", _ctx.formItemClass])
}, [
vue.createVNode(_component_LabelWrap, {
"is-auto-width": _ctx.labelStyle.width === "auto",
"update-all": _ctx.elForm.labelWidth === "auto"
}, {
default: vue.withCtx(() => [
_ctx.label || _ctx.$slots.label ? (vue.openBlock(), vue.createElementBlock("label", {
key: 0,
for: _ctx.labelFor,
class: "el-form-item__label",
style: vue.normalizeStyle(_ctx.labelStyle)
}, [
vue.renderSlot(_ctx.$slots, "label", {
label: _ctx.label + _ctx.elForm.labelSuffix
}, () => [
vue.createTextVNode(vue.toDisplayString(_ctx.label + _ctx.elForm.labelSuffix), 1)
])
], 12, _hoisted_1)) : vue.createCommentVNode("v-if", true)
]),
_: 3
}, 8, ["is-auto-width", "update-all"]),
vue.createElementVNode("div", {
class: "el-form-item__content",
style: vue.normalizeStyle(_ctx.contentStyle)
}, [
vue.renderSlot(_ctx.$slots, "default"),
vue.createVNode(vue.Transition, { name: "el-zoom-in-top" }, {
default: vue.withCtx(() => [
_ctx.shouldShowError ? vue.renderSlot(_ctx.$slots, "error", {
key: 0,
error: _ctx.validateMessage
}, () => [
vue.createElementVNode("div", {
class: vue.normalizeClass(["el-form-item__error", {
"el-form-item__error--inline": typeof _ctx.inlineMessage === "boolean" ? _ctx.inlineMessage : _ctx.elForm.inlineMessage || false
}])
}, vue.toDisplayString(_ctx.validateMessage), 3)
]) : vue.createCommentVNode("v-if", true)
]),
_: 3
})
], 4)
], 2);
}
script$1.render = render$1;
script$1.__file = "packages/components/form/src/form-item.vue";
script.install = (app) => {
app.component(script.name, script);
app.component(script$1.name, script$1);
};
script.FormItem = script$1;
const _Form = script;
const ElForm = _Form;
const ElFormItem = script$1;
exports.ElForm = ElForm;
exports.ElFormItem = ElFormItem;
exports.default = _Form;
| 31.931921 | 180 | 0.58483 |
c62cb4f89543bacebaa9597131ee9a7fe09b9dac | 679 | js | JavaScript | web/js/feedback.js | oshanrube/iva | cef1eb5162dff7c9873493db20475802114d62dd | [
"MIT"
] | 1 | 2015-01-21T00:03:36.000Z | 2015-01-21T00:03:36.000Z | web/js/feedback.js | oshanrube/iva | cef1eb5162dff7c9873493db20475802114d62dd | [
"MIT"
] | null | null | null | web/js/feedback.js | oshanrube/iva | cef1eb5162dff7c9873493db20475802114d62dd | [
"MIT"
] | null | null | null | function toggleFeedback(){
//$("#FeedbackForm").slideToggle('slow');
if( $("#feedbackHandle").css('bottom') == "234px" ) {
$("#feedbackHandle").animate({ bottom: '30' }, 'slow' );
$("#FeedbackForm").animate({ bottom: '-234' }, 'slow' );
} else {
$("#feedbackHandle").animate({ bottom: '234' }, 'slow' );
$("#FeedbackForm").animate({ bottom: '0' }, 'slow' );
}
}
function ajaxFeedbackSubmit(that){
$(that).ajaxSubmit(function(r) {
if(r.response == 'success'){
$(that).resetForm();
toggleFeedback();
$("#feedbackHandle .middle").text('Thank you for your feedback');
} else {
alert("An error adding your request");
}
});
return false;
} | 29.521739 | 68 | 0.590574 |
c62d0b7a221e0c4e3116a7bb000a415027ccbc6f | 2,833 | js | JavaScript | server/index.js | weirdindiankid/urban-refuge | 526b61c7332ed2260e741c60b24fc27550db36e2 | [
"MIT"
] | null | null | null | server/index.js | weirdindiankid/urban-refuge | 526b61c7332ed2260e741c60b24fc27550db36e2 | [
"MIT"
] | null | null | null | server/index.js | weirdindiankid/urban-refuge | 526b61c7332ed2260e741c60b24fc27550db36e2 | [
"MIT"
] | null | null | null | var express = require('express');
var app = express();
var passport = require('passport');
var WindowsLiveStrategy = require('passport-windowslive');
var hbs = require('hbs');
var session = require('express-session');
var bodyParser = require('body-parser');
var cookieParser = require('cookie-parser');
var config = require('./config/config');
/* routes */
var index = require('./routes/index');
var resources = require('./routes/resources');
var users = require('./routes/users');
var api = require('./routes/api');
/* initialize express */
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));
app.set('trust proxy', 1) // trust first proxy
app.use(session({
secret: 'shhhhhhhhh',
resave: true,
saveUninitialized: true
}));
app.use(cookieParser());
/* Add headers */
app.use(function (req, res, next) {
// Website you wish to allow to connect
res.setHeader('Access-Control-Allow-Origin', '*');
// Request methods you wish to allow
res.setHeader('Access-Control-Allow-Methods', 'GET, POST, OPTIONS, PUT, PATCH, DELETE');
// Request headers you wish to allow
res.setHeader('Access-Control-Allow-Headers', 'X-Requested-With,content-type');
// Set to true if you need the website to include cookies in the requests sent
// to the API (e.g. in case you use sessions)
res.setHeader('Access-Control-Allow-Credentials', true);
// Pass to next layer of middleware
next();
});
// Configure Passport to use Auth0
var strategy = new WindowsLiveStrategy({
clientID: config.clientID,
clientSecret: config.clientSecret,
callbackURL: config.callbackURL
}, function(accessToken, refreshToken, profile, done) {
// accessToken is the token to call Auth0 API (not needed in the most cases)
// extraParams.id_token has the JSON Web Token
// profile has all the information from the user
return done(null, profile);
});
passport.use(strategy);
// This can be used to keep a smaller payload
passport.serializeUser(function(user, done) {
done(null, user);
});
passport.deserializeUser(function(user, done) {
done(null, user);
});
app.use(passport.initialize());
app.use(passport.session());
/* initialize handlebars */
app.set('view engine', 'hbs');
app.set('views', __dirname+'/views');
hbs.registerPartials(__dirname + '/views/partials');
hbs.registerHelper('neq', function(lvalue, rvalue, options) {
if (arguments.length < 3)
throw new Error("Handlebars Helper equal needs 2 parameters");
if(lvalue==rvalue) {
return options.inverse(this);
} else {
return options.fn(this);
}
});
/* routes */
app.use('/', index);
app.use('/resources', resources);
app.use('/users', users);
app.use('/api', api);
app.listen(config.port, function () {
console.log('Urban Refuge is listening on port',config.port);
});
| 30.462366 | 92 | 0.69114 |
c62d15253f962d310ef7f65f1832df792acea2d0 | 723 | js | JavaScript | src/item.js | tliebert/todo | 801c307475faf57d624b03b2afc2db6470820fb6 | [
"MIT"
] | null | null | null | src/item.js | tliebert/todo | 801c307475faf57d624b03b2afc2db6470820fb6 | [
"MIT"
] | null | null | null | src/item.js | tliebert/todo | 801c307475faf57d624b03b2afc2db6470820fb6 | [
"MIT"
] | null | null | null | // factory that creates the todo object
const todoFactory = function (title, description, duedate, priority, notes) {
let todoItem = {
title: title,
description: description,
duedate: duedate,
priority: priority,
notes: notes,
};
return todoItem;
};
// explore how to refactor this into a single function with different parameters
function setPriority(todo, priority) {
todo["priority"] = priority;
}
function setDescription(todo, description) {
todo["description"] = description;
}
function setDate(todo, date) {
todo["duedate"] = date;
}
function setNotes(todo, note) {
todo["notes"] = note;
}
function setTitle(todo, title) {
todo["title"] = title;
}
export { todoFactory };
| 19.026316 | 80 | 0.69018 |
c62d4e4632e9bfda6af918ae851e81dcd1881645 | 9,174 | js | JavaScript | class/wallets/abstract-wallet.js | wuyih9/BlueWallet | 2cc0b69cc89ee17690e291a7bf95749767530348 | [
"MIT"
] | 1 | 2021-06-17T22:46:07.000Z | 2021-06-17T22:46:07.000Z | class/wallets/abstract-wallet.js | scoinhawk/BlueWallet | f26b6942935b0ed6ff3ce9be2bed610bec7934cb | [
"MIT"
] | null | null | null | class/wallets/abstract-wallet.js | scoinhawk/BlueWallet | f26b6942935b0ed6ff3ce9be2bed610bec7934cb | [
"MIT"
] | 1 | 2021-06-26T15:16:58.000Z | 2021-06-26T15:16:58.000Z | import { BitcoinUnit, Chain } from '../../models/bitcoinUnits';
import b58 from 'bs58check';
const createHash = require('create-hash');
export class AbstractWallet {
static type = 'abstract';
static typeReadable = 'abstract';
static fromJson(obj) {
const obj2 = JSON.parse(obj);
const temp = new this();
for (const key2 of Object.keys(obj2)) {
temp[key2] = obj2[key2];
}
return temp;
}
constructor() {
this.type = this.constructor.type;
this.typeReadable = this.constructor.typeReadable;
this.segwitType = this.constructor.segwitType;
this._derivationPath = this.constructor.derivationPath;
this.label = '';
this.secret = ''; // private key or recovery phrase
this.balance = 0;
this.unconfirmed_balance = 0;
this._address = false; // cache
this.utxo = [];
this._lastTxFetch = 0;
this._lastBalanceFetch = 0;
this.preferredBalanceUnit = BitcoinUnit.BTC;
this.chain = Chain.ONCHAIN;
this.hideBalance = false;
this.userHasSavedExport = false;
this._hideTransactionsInWalletsList = false;
this._utxoMetadata = {};
}
/**
* @returns {number} Timestamp (millisecsec) of when last transactions were fetched from the network
*/
getLastTxFetch() {
return this._lastTxFetch;
}
getID() {
return createHash('sha256').update(this.getSecret()).digest().toString('hex');
}
getTransactions() {
throw new Error('not implemented');
}
getUserHasSavedExport() {
return this.userHasSavedExport;
}
setUserHasSavedExport(value) {
this.userHasSavedExport = value;
}
getHideTransactionsInWalletsList() {
return this._hideTransactionsInWalletsList;
}
setHideTransactionsInWalletsList(value) {
this._hideTransactionsInWalletsList = value;
}
/**
*
* @returns {string}
*/
getLabel() {
if (this.label.trim().length === 0) {
return 'Wallet';
}
return this.label;
}
getXpub() {
return this._address;
}
/**
*
* @returns {number} Available to spend amount, int, in sats
*/
getBalance() {
return this.balance + (this.getUnconfirmedBalance() < 0 ? this.getUnconfirmedBalance() : 0);
}
getPreferredBalanceUnit() {
for (const value of Object.values(BitcoinUnit)) {
if (value === this.preferredBalanceUnit) {
return this.preferredBalanceUnit;
}
}
return BitcoinUnit.BTC;
}
allowReceive() {
return true;
}
allowSend() {
return true;
}
allowRBF() {
return false;
}
allowHodlHodlTrading() {
return false;
}
allowPayJoin() {
return false;
}
allowCosignPsbt() {
return false;
}
allowSignVerifyMessage() {
return false;
}
allowMasterFingerprint() {
return false;
}
allowXpub() {
return false;
}
weOwnAddress(address) {
throw Error('not implemented');
}
weOwnTransaction(txid) {
throw Error('not implemented');
}
/**
* Returns delta of unconfirmed balance. For example, if theres no
* unconfirmed balance its 0
*
* @return {number} Satoshis
*/
getUnconfirmedBalance() {
return this.unconfirmed_balance;
}
setLabel(newLabel) {
this.label = newLabel;
return this;
}
getSecret() {
return this.secret;
}
setSecret(newSecret) {
this.secret = newSecret.trim().replace('bitcoin:', '').replace('BITCOIN:', '');
if (this.secret.startsWith('BC1')) this.secret = this.secret.toLowerCase();
// [fingerprint/derivation]zpub
const re = /\[([^\]]+)\](.*)/;
const m = this.secret.match(re);
if (m && m.length === 3) {
let hexFingerprint = m[1].split('/')[0];
if (hexFingerprint.length === 8) {
hexFingerprint = Buffer.from(hexFingerprint, 'hex').reverse().toString('hex');
this.masterFingerprint = parseInt(hexFingerprint, 16);
}
this.secret = m[2];
}
try {
let parsedSecret;
// regex might've matched invalid data. if so, parse newSecret.
if (this.secret.trim().length > 0) {
try {
parsedSecret = JSON.parse(this.secret);
} catch (e) {
parsedSecret = JSON.parse(newSecret);
}
} else {
parsedSecret = JSON.parse(newSecret);
}
if (parsedSecret && parsedSecret.keystore && parsedSecret.keystore.xpub) {
let masterFingerprint = false;
if (parsedSecret.keystore.ckcc_xfp) {
// It is a ColdCard Hardware Wallet
masterFingerprint = Number(parsedSecret.keystore.ckcc_xfp);
} else if (parsedSecret.keystore.root_fingerprint) {
masterFingerprint = Number(parsedSecret.keystore.root_fingerprint);
}
if (parsedSecret.keystore.label) {
this.setLabel(parsedSecret.keystore.label);
}
this.secret = parsedSecret.keystore.xpub;
this.masterFingerprint = masterFingerprint;
if (parsedSecret.keystore.type === 'hardware') this.use_with_hardware_wallet = true;
}
// It is a Cobo Vault Hardware Wallet
if (parsedSecret && parsedSecret.ExtPubKey && parsedSecret.MasterFingerprint) {
this.secret = parsedSecret.ExtPubKey;
const mfp = Buffer.from(parsedSecret.MasterFingerprint, 'hex').reverse().toString('hex');
this.masterFingerprint = parseInt(mfp, 16);
this.setLabel('Cobo Vault ' + parsedSecret.MasterFingerprint);
if (parsedSecret.CoboVaultFirmwareVersion) this.use_with_hardware_wallet = true;
}
} catch (_) {}
return this;
}
getLatestTransactionTime() {
return 0;
}
getLatestTransactionTimeEpoch() {
if (this.getTransactions().length === 0) {
return 0;
}
let max = 0;
for (const tx of this.getTransactions()) {
max = Math.max(new Date(tx.received) * 1, max);
}
return max;
}
/**
* @deprecated
*/
createTx() {
throw Error('not implemented');
}
/**
*
* @param utxos {Array.<{vout: Number, value: Number, txId: String, address: String}>} List of spendable utxos
* @param targets {Array.<{value: Number, address: String}>} Where coins are going. If theres only 1 target and that target has no value - this will send MAX to that address (respecting fee rate)
* @param feeRate {Number} satoshi per byte
* @param changeAddress {String} Excessive coins will go back to that address
* @param sequence {Number} Used in RBF
* @param skipSigning {boolean} Whether we should skip signing, use returned `psbt` in that case
* @param masterFingerprint {number} Decimal number of wallet's master fingerprint
* @returns {{outputs: Array, tx: Transaction, inputs: Array, fee: Number, psbt: Psbt}}
*/
createTransaction(utxos, targets, feeRate, changeAddress, sequence, skipSigning = false, masterFingerprint) {
throw Error('not implemented');
}
getAddress() {
throw Error('not implemented');
}
getAddressAsync() {
return new Promise(resolve => resolve(this.getAddress()));
}
async getChangeAddressAsync() {
return new Promise(resolve => resolve(this.getAddress()));
}
useWithHardwareWalletEnabled() {
return false;
}
async wasEverUsed() {
throw new Error('Not implemented');
}
/**
* Returns _all_ external addresses in hierarchy (for HD wallets) or just address for single-address wallets
* _Not_ internal ones, as this method is supposed to be used for subscription of external notifications.
*
* @returns string[] Addresses
*/
getAllExternalAddresses() {
return [];
}
/*
* Converts zpub to xpub
*
* @param {String} zpub
* @returns {String} xpub
*/
static _zpubToXpub(zpub) {
let data = b58.decode(zpub);
data = data.slice(4);
data = Buffer.concat([Buffer.from('0488b21e', 'hex'), data]);
return b58.encode(data);
}
/**
* Converts ypub to xpub
* @param {String} ypub - wallet ypub
* @returns {*}
*/
static _ypubToXpub(ypub) {
let data = b58.decode(ypub);
if (data.readUInt32BE() !== 0x049d7cb2) throw new Error('Not a valid ypub extended key!');
data = data.slice(4);
data = Buffer.concat([Buffer.from('0488b21e', 'hex'), data]);
return b58.encode(data);
}
prepareForSerialization() {}
/*
* Get metadata (frozen, memo) for a specific UTXO
*
* @param {String} txid - transaction id
* @param {number} vout - an index number of the output in transaction
*/
getUTXOMetadata(txid, vout) {
return this._utxoMetadata[`${txid}:${vout}`] || {};
}
/*
* Set metadata (frozen, memo) for a specific UTXO
*
* @param {String} txid - transaction id
* @param {number} vout - an index number of the output in transaction
* @param {{memo: String, frozen: Boolean}} opts - options to attach to UTXO
*/
setUTXOMetadata(txid, vout, opts) {
const meta = this._utxoMetadata[`${txid}:${vout}`] || {};
if ('memo' in opts) meta.memo = opts.memo;
if ('frozen' in opts) meta.frozen = opts.frozen;
this._utxoMetadata[`${txid}:${vout}`] = meta;
}
/**
* @returns {string} Root derivation path for wallet if any
*/
getDerivationPath() {
return this._derivationPath ?? '';
}
}
| 26.136752 | 197 | 0.638435 |
c62e02f738bb4dde85b066b402cafb0d7d8f6390 | 2,344 | js | JavaScript | aka-open.js | arulned/aka-open | 59eba7572ce8ce7fb18191a18edb1d562bac7e40 | [
"Apache-2.0"
] | null | null | null | aka-open.js | arulned/aka-open | 59eba7572ce8ce7fb18191a18edb1d562bac7e40 | [
"Apache-2.0"
] | null | null | null | aka-open.js | arulned/aka-open | 59eba7572ce8ce7fb18191a18edb1d562bac7e40 | [
"Apache-2.0"
] | null | null | null | #!/usr/bin/env node
var EdgeGrid = require('edgegrid');
var untildify = require('untildify');
var fs = require('fs');
// Supply the path to your .edgerc file and name
// of the section with authorization to the client
// you are calling (default section is 'default')
require('sywac')
.command("get <url>", {
description: "Issues a GET request for the specified url",
run: options => {
call(options, 'GET');
}
})
.command("put <url>", {
description: "Issues a PUT request to the specified url",
run: options => {
call(options, 'PUT');
}
})
.command("post <url>", {
description: "Issues a POST request to the specified url",
run: options => {
call(options, 'POST');
}
})
.string('--section <section>', { desc: 'Section name in edgerc file', required: false })
.string('--edgerc <edgerc>', { desc: 'edgerc file path', required: false })
.help('-h, --help')
.version('-v, --version')
.showHelpByDefault()
.outputSettings({ maxWidth: 75 })
.parseAndExit()
.then(argv => {
//console.log(JSON.stringify(argv, null, 2))
});
function call(options, method) {
switch(method) {
case 'GET':
run(options, method);
break;
case 'PUT':
case 'POST':
if (options._[0] && options._[0].indexOf('@') == 0) {
options.data = JSON.parse(fs.readFileSync(options._[0].substring(1), 'utf8'));
run(options, method);
} else {
console.error('Did you provide a file name prefixed with "@"? ' + JSON.stringify(options));
}
break;
case 'DELETE':
throw "Not implemented";
}
}
function run(options, method) {
console.log('Options: ' + JSON.stringify(options));
var eg = new EdgeGrid({
path: options.edgerc ? untildify(options.edgerc) : untildify('~/.edgerc'),
section: options.section || 'default'
});
eg.auth({
path: options.url,
method: method,
headers: {
"Content-Type":"application/json"
},
body: options.data
});
eg.send(function (error, response, body) {
console.log(JSON.stringify(JSON.parse(body),null,2));
});
}
| 29.670886 | 107 | 0.544795 |
c62e0399f11796f6d70e469d785275b1270899f8 | 1,218 | js | JavaScript | src/main/generic/consensus/light/LightConsensus.js | terorie/core | f19f70c098c7e663d5a1669606c27f2b56069ee7 | [
"Apache-2.0"
] | 1 | 2018-12-30T03:01:06.000Z | 2018-12-30T03:01:06.000Z | src/main/generic/consensus/light/LightConsensus.js | terorie/core | f19f70c098c7e663d5a1669606c27f2b56069ee7 | [
"Apache-2.0"
] | 92 | 2019-03-14T04:22:12.000Z | 2021-08-02T04:20:31.000Z | src/main/generic/consensus/light/LightConsensus.js | terorie/nimiq-core | f19f70c098c7e663d5a1669606c27f2b56069ee7 | [
"Apache-2.0"
] | 1 | 2021-12-20T14:26:11.000Z | 2021-12-20T14:26:11.000Z | class LightConsensus extends BaseConsensus {
/**
* @param {LightChain} blockchain
* @param {Mempool} mempool
* @param {Network} network
*/
constructor(blockchain, mempool, network) {
super(blockchain, mempool, network);
/** @type {LightChain} */
this._blockchain = blockchain;
/** @type {Mempool} */
this._mempool = mempool;
}
/**
* @param {Peer} peer
* @returns {BaseConsensusAgent}
* @override
*/
_newConsensusAgent(peer) {
return new LightConsensusAgent(this._blockchain, this._mempool, this._network.time, peer, this._invRequestManager, this._subscription);
}
/**
* @param {Peer} peer
* @override
*/
_onPeerJoined(peer) {
const agent = super._onPeerJoined(peer);
// Forward sync events.
this.bubble(agent, 'sync-chain-proof', 'verify-chain-proof', 'sync-accounts-tree', 'verify-accounts-tree', 'sync-finalize');
return agent;
}
/** @type {LightChain} */
get blockchain() {
return this._blockchain;
}
/** @type {Mempool} */
get mempool() {
return this._mempool;
}
}
Class.register(LightConsensus);
| 25.375 | 143 | 0.591133 |
c62e7c77c0fbab681c89a807057b0ddab7777055 | 885 | js | JavaScript | models/comment.js | Ulysses31/react-tasks-mern | 4504c3bdf7aa2820ebd1f38c61b6411692beb659 | [
"MIT"
] | null | null | null | models/comment.js | Ulysses31/react-tasks-mern | 4504c3bdf7aa2820ebd1f38c61b6411692beb659 | [
"MIT"
] | null | null | null | models/comment.js | Ulysses31/react-tasks-mern | 4504c3bdf7aa2820ebd1f38c61b6411692beb659 | [
"MIT"
] | null | null | null | const { v4: uuidv4 } = require('uuid');
const mongoose = require('mongoose');
const Comment = mongoose.model(
'Comment',
new mongoose.Schema({
_id: mongoose.Schema.Types.ObjectId,
description: {
type: String,
required: true,
maxlength: 255
},
isEnabled: {
type: Boolean,
required: true,
default: true
},
task: {
type: mongoose.Schema.Types.ObjectId,
ref: 'Task'
},
user: {
type: mongoose.Schema.Types.ObjectId,
ref: 'User'
},
createdAt: {
type: Date,
required: true,
default: new Date()
},
createdBy: {
type: String,
required: true
},
updatedAt: {
type: Date
},
updatedBy: {
type: String
},
guid: {
type: String,
required: true,
default: uuidv4()
}
})
);
module.exports = Comment;
| 17.7 | 43 | 0.533333 |
c62f4a3604de8d459cb88b8586c735bd0d96f747 | 2,233 | js | JavaScript | node_modules/write-json-file/index.js | Yodart/arara | e94d1b23a38439ce712b725cba3567880ddffce0 | [
"MIT"
] | 5 | 2020-08-28T07:54:47.000Z | 2021-11-12T12:03:19.000Z | node_modules/write-json-file/index.js | Yodart/arara | e94d1b23a38439ce712b725cba3567880ddffce0 | [
"MIT"
] | 70 | 2020-05-22T02:48:33.000Z | 2020-07-29T18:32:12.000Z | node_modules/write-json-file/index.js | Yodart/arara | e94d1b23a38439ce712b725cba3567880ddffce0 | [
"MIT"
] | 1 | 2021-12-16T08:15:15.000Z | 2021-12-16T08:15:15.000Z | 'use strict';
const {promisify} = require('util');
const path = require('path');
const fs = require('graceful-fs');
const writeFileAtomic = require('write-file-atomic');
const sortKeys = require('sort-keys');
const makeDir = require('make-dir');
const detectIndent = require('detect-indent');
const isPlainObj = require('is-plain-obj');
const readFile = promisify(fs.readFile);
const init = (fn, filePath, data, options) => {
if (!filePath) {
throw new TypeError('Expected a filepath');
}
if (data === undefined) {
throw new TypeError('Expected data to stringify');
}
options = {
indent: '\t',
sortKeys: false,
...options
};
if (options.sortKeys && isPlainObj(data)) {
data = sortKeys(data, {
deep: true,
compare: typeof options.sortKeys === 'function' ? options.sortKeys : undefined
});
}
return fn(filePath, data, options);
};
const main = async (filePath, data, options) => {
let {indent} = options;
let trailingNewline = '\n';
try {
const file = await readFile(filePath, 'utf8');
if (!file.endsWith('\n')) {
trailingNewline = '';
}
if (options.detectIndent) {
indent = detectIndent(file).indent;
}
} catch (error) {
if (error.code !== 'ENOENT') {
throw error;
}
}
const json = JSON.stringify(data, options.replacer, indent);
return writeFileAtomic(filePath, `${json}${trailingNewline}`, {mode: options.mode, chown: false});
};
const mainSync = (filePath, data, options) => {
let {indent} = options;
let trailingNewline = '\n';
try {
const file = fs.readFileSync(filePath, 'utf8');
if (!file.endsWith('\n')) {
trailingNewline = '';
}
if (options.detectIndent) {
indent = detectIndent(file).indent;
}
} catch (error) {
if (error.code !== 'ENOENT') {
throw error;
}
}
const json = JSON.stringify(data, options.replacer, indent);
return writeFileAtomic.sync(filePath, `${json}${trailingNewline}`, {mode: options.mode, chown: false});
};
module.exports = async (filePath, data, options) => {
await makeDir(path.dirname(filePath), {fs});
return init(main, filePath, data, options);
};
module.exports.sync = (filePath, data, options) => {
makeDir.sync(path.dirname(filePath), {fs});
init(mainSync, filePath, data, options);
};
| 24.010753 | 104 | 0.656964 |
c630096e49ae26ee1bd3e8b08fa9c0fb788a59a9 | 1,011 | js | JavaScript | src/equation_editor/button_group_view.js | blueysnow2/_tinymce_mobileequationeditor | 712ed81ae092c2c1450e4d099e06a982bb51b843 | [
"MIT"
] | null | null | null | src/equation_editor/button_group_view.js | blueysnow2/_tinymce_mobileequationeditor | 712ed81ae092c2c1450e4d099e06a982bb51b843 | [
"MIT"
] | null | null | null | src/equation_editor/button_group_view.js | blueysnow2/_tinymce_mobileequationeditor | 712ed81ae092c2c1450e4d099e06a982bb51b843 | [
"MIT"
] | null | null | null | EquationEditor.ButtonGroupView = class ButtonGroupView extends EquationEditor.View {
constructor(events, options) {
super(events, options);
this.toggle = this.toggle.bind(this);
}
initialize() {
this.groupName = this.options.groupName;
return this.buttonViews = this.options.buttonViews;
}
render() {
this.createElement();
this.renderButtons();
new EquationEditor.CollapsibleView({$el: this.$el});
this.find('header').click(this.toggle);
return this;
}
toggle() {
return this.find('.collapsible-box-toggle').click();
}
renderButtons() {
return Array.from(this.buttonViews).map((buttonView) =>
this.find('.buttons').append(buttonView.render().$el));
}
template() {
return `\
<div class="button-group collapsible">
<a href='#' class='collapsible-box-toggle ss-dropdown'></a> <header>${this.groupName}</header>
<div class="buttons box-content-collapsible hidden"></div>
</div>\
`;
}
};
| 25.923077 | 97 | 0.63996 |
c6304a388549e86456523ca52a7302f17f58cfb1 | 1,189 | js | JavaScript | public/js/create_task.js | GaryChen513/RESchedule | ae6f5e82091355447bd3a2faa70d653e0c6be027 | [
"ISC"
] | null | null | null | public/js/create_task.js | GaryChen513/RESchedule | ae6f5e82091355447bd3a2faa70d653e0c6be027 | [
"ISC"
] | null | null | null | public/js/create_task.js | GaryChen513/RESchedule | ae6f5e82091355447bd3a2faa70d653e0c6be027 | [
"ISC"
] | 3 | 2021-03-30T09:27:16.000Z | 2021-03-30T11:34:21.000Z | var cal = [];
document.querySelector('#confirm').addEventListener('click', (e) => {
e.preventDefault();
cal = document.querySelector('#schedule').bulmaCalendar;
// console.log(cal.startTime);
// console.log(cal.endTime);
// console.log(cal.startDate);
// console.log(cal.endDate);
// console.log;
});
const createTaskHandler = async () => {
console.log(cal.startTime);
const employee_select = document.querySelector('#manager_employee');
const employee_id = document.querySelectorAll('option')[
employee_select.selectedIndex
].value;
const title = document.querySelector('#task-title').value.trim();
const response = await fetch('/api/task', {
method: 'POST',
body: JSON.stringify({
title: title,
start_time: cal.startTime,
finish_time: cal.endTime,
employee_id: employee_id,
}),
headers: { 'Content-Type': 'application/json' },
});
if (response.ok) {
const success = document.createElement('P');
success.innerText = 'Task Created Successfully';
document.querySelector('#assign-task').appendChild(success);
} else {
alert(response.statusText);
}
};
document
.querySelector('#task-button')
.addEventListener('click', createTaskHandler);
| 27.651163 | 69 | 0.705635 |
c6306a0a7f6c89b7a3c607c9651fa849a4150066 | 1,061 | js | JavaScript | src/gitter/components/tray.js | baeyun/gitter-slim | 538c635f494f7f700cb66622787e665c433a55ac | [
"MIT"
] | 4 | 2019-07-14T12:23:51.000Z | 2020-05-01T18:08:36.000Z | src/gitter/components/tray.js | bukharim96/gitter-slim | 538c635f494f7f700cb66622787e665c433a55ac | [
"MIT"
] | 4 | 2021-10-06T00:46:18.000Z | 2022-03-02T11:12:56.000Z | src/gitter/components/tray.js | baeyun/gitter-slim | 538c635f494f7f700cb66622787e665c433a55ac | [
"MIT"
] | 1 | 2020-05-01T18:08:40.000Z | 2020-05-01T18:08:40.000Z | 'use strict';
var preferences = require('../utils/user-preferences');
var events = require('../utils/custom-events');
var CLIENT_TYPE = require('../utils/client-type');
var icon = require('../icons.json')[CLIENT_TYPE];
function CustomTray() {
this.tray = new nw.Tray({
icon: icon.disconnected,
alticon: icon.selected,
iconsAreTemplates: false
});
events.on('user:signedOut', this.disconnect.bind(this));
events.on('user:signedIn', this.connect.bind(this));
events.on('traymenu:read', this.connect.bind(this));
events.on('traymenu:unread', this.unread.bind(this));
}
CustomTray.prototype.setIcon = function(icon) {
this.tray.icon = icon;
};
CustomTray.prototype.get = function() {
return this.tray;
};
CustomTray.prototype.disconnect = function() {
this.setIcon(icon.disconnected);
};
CustomTray.prototype.connect = function() {
if (!preferences.token) return; // user is signed out
this.setIcon(icon.connected);
};
CustomTray.prototype.unread = function() {
this.setIcon(icon.unread);
};
module.exports = CustomTray;
| 25.261905 | 58 | 0.70311 |
c630bd54da1e119371383afa5864d2d9a4109b4a | 716 | js | JavaScript | src/index.js | cjgammon/pixi-nano.js | 222bb65dfc8d38bed72a3d34536e4199325863ce | [
"MIT"
] | null | null | null | src/index.js | cjgammon/pixi-nano.js | 222bb65dfc8d38bed72a3d34536e4199325863ce | [
"MIT"
] | null | null | null | src/index.js | cjgammon/pixi-nano.js | 222bb65dfc8d38bed72a3d34536e4199325863ce | [
"MIT"
] | null | null | null | // run the polyfills
require('./polyfill');
var core = module.exports = require('./core');
// add core plugins.
//core.extras = require('./extras');
//core.filters = require('./filters');
//core.interaction = require('./interaction');
//core.loaders = require('./loaders');
//core.mesh = require('./mesh');
// export a premade loader instance
/**
* A premade instance of the loader that can be used to loader resources.
*
* @name loader
* @memberof PIXI
* @property {PIXI.loaders.Loader}
*/
//core.loader = new core.loaders.Loader();
// mixin the deprecation features.
//Object.assign(core, require('./deprecation'));
// Always export pixi globally.
global.PIXI = core;
| 25.571429 | 73 | 0.643855 |
c630f66bcc29567eaa72aa25eab045fb4567f6bc | 2,181 | js | JavaScript | famille/static/js/contact_us.js | huguesmayolle/famille | c7b3399e88a6922cadc0c7c9f2ff7447e7c95377 | [
"Apache-2.0"
] | null | null | null | famille/static/js/contact_us.js | huguesmayolle/famille | c7b3399e88a6922cadc0c7c9f2ff7447e7c95377 | [
"Apache-2.0"
] | null | null | null | famille/static/js/contact_us.js | huguesmayolle/famille | c7b3399e88a6922cadc0c7c9f2ff7447e7c95377 | [
"Apache-2.0"
] | null | null | null | var notifier = require("./notifier.js");
(function ($) {
function validateEmail(email) {
var re = /^(([^<>()[\]\\.,;:\s@\"]+(\.[^<>()[\]\\.,;:\s@\"]+)*)|(\".+\"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;
return re.test(email);
}
function validatePhone(phone) {
var re = /^0\d{9}$/;
return re.test(phone);
}
var nameInput = $("#contact-name");
var msgInput = $("#contact-messageContent");
var emailInput = $("#contact-email");
var modal = $("#contactModal");
$(".send-contact-message").click(function () {
var name = nameInput.val();
var msg = msgInput.val();
var email = emailInput.val();
var errors = [];
var err_msg = "";
// errors
if (!name.trim()) errors.push("Nom ou raison sociale");
if (!msg.trim()) errors.push("Message");
if (!email.trim()) errors.push("Email / contact");
if (errors.length) {
if (errors.lengts === 1) err_msg = "Le champs '" + errors[0] + "' est requis.";
else err_msg = "Les champs '" + errors.join("', '") + "' sont requis.";
}
else if (!validateEmail(email.trim()) && !validatePhone(email.trim())) {
err_msg = (
"Le champs 'Email / contact' doit être un mail valide ou un " +
"numéro de téléphone valide (sans espace ni points ou tirets)."
);
}
if (err_msg.length) {
notifier.error(err_msg);
return;
}
modal.modal("hide");
$.ajax({
url: "/contact-us/",
type: "POST",
data: {name: name, message: msg, email: email},
headers: {'X-CSRFToken': $.cookie('csrftoken')}
}).done(function () {
notifier.success({
duration: 10000,
message: "Votre message a bien été envoyé, nous vous répondrons dans les plus brefs délais."
});
}).fail(function () {
notifier.error("Une erreur est survenue, veuillez réessayer ultérieurement.");
});
});
})(jQuery);
| 34.078125 | 173 | 0.486933 |
c6314db6f2f17f5ccc802a0b3b97b6873e62e484 | 3,604 | js | JavaScript | addon/utils/ce/handlers/emphasis-markdown-handler.js | SchrodingersCat00/ember-rdfa-editor | e81bf1f870dd402f424104d9ae0809b6d20f9d8b | [
"MIT"
] | null | null | null | addon/utils/ce/handlers/emphasis-markdown-handler.js | SchrodingersCat00/ember-rdfa-editor | e81bf1f870dd402f424104d9ae0809b6d20f9d8b | [
"MIT"
] | null | null | null | addon/utils/ce/handlers/emphasis-markdown-handler.js | SchrodingersCat00/ember-rdfa-editor | e81bf1f870dd402f424104d9ae0809b6d20f9d8b | [
"MIT"
] | null | null | null | import getRichNodeMatchingDomNode from '../get-rich-node-matching-dom-node';
import { get } from '@ember/object';
import { isBlank } from '@ember/utils';
import HandlerResponse from './handler-response';
import { invisibleSpace } from '../dom-helpers';
let BOLDMARKDOWN = /(\*\*)(.*?)\1/;
let EMPHASISMARKDOWN = /(\*)([^*].+?)\1/;
let UNDERLINEMARKDOWN = /(_)(.*?)\1/;
let MARKDOWNS = [
{pattern: BOLDMARKDOWN, tag: 'strong'},
{pattern: EMPHASISMARKDOWN, tag: 'em'},
{pattern: UNDERLINEMARKDOWN, tag: 'u'}
];
/**
* handles emphasis markdown
*
* It checks for `*some text here*` `_some text here_` and `**some text here**`
* and then triggers if you put a space behind those snippets
*
* @module contenteditable-editor
* @class EmphasisMarkdownHandler
* @constructor
*/
export default class EmphasisMarkdownHandler {
constructor({rawEditor}) {
this.rawEditor = rawEditor;
}
nodeContainsRelevantMarkdown(node){
if(!node.nodeType === Node.TEXT_NODE)
return false;
return this.findMarkdown(node.textContent);
}
findMarkdown(text){
return MARKDOWNS.find(m => { return text.match(m.pattern); });
}
/**
* tests this handler can handle the specified event
* @method isHandlerFor
* @param {DOMEvent} event
* @return boolean
* @public
*/
isHandlerFor(event){
return event.type === "keydown" &&
this.rawEditor.currentSelectionIsACursor &&
event.key == ' ' &&
this.nodeContainsRelevantMarkdown(this.rawEditor.currentNode);
}
/**
* handle emphasis markdown event
* @method handleEvent
* @return {HandlerResponse}
* @public
*/
handleEvent() {
let currentNode = this.rawEditor.currentNode;
let node = getRichNodeMatchingDomNode(currentNode, this.rawEditor.richNode);
let currentPosition = this.rawEditor.currentSelection[0];
let newCurrentNode;
let markdown = this.findMarkdown(currentNode.textContent).pattern;
let insertElement = () => {
let matchGroups = currentNode.textContent.match(markdown);
let contentEnd = currentPosition - matchGroups[1].length - get(node, 'start');
let contentStart = currentPosition - get(node, 'start') - matchGroups[0].length + matchGroups[1].length;
let beforeContentNode = document.createTextNode(currentNode.textContent.slice(0, matchGroups.index));
let elementContent = currentNode.textContent.slice(contentStart, contentEnd);
if (isBlank(elementContent))
elementContent = invisibleSpace;
let contentTextNode = document.createTextNode(elementContent);
let contentNode = document.createElement(this.findMarkdown(currentNode.textContent).tag);
contentNode.append(contentTextNode);
let afterContent = currentNode.textContent.slice(contentEnd + matchGroups[1].length);
if(isBlank(afterContent))
afterContent = invisibleSpace;
let afterContentNode = document.createTextNode(afterContent);
currentNode.parentNode.insertBefore(beforeContentNode, currentNode);
currentNode.parentNode.insertBefore(contentNode, currentNode);
currentNode.parentNode.insertBefore(afterContentNode, currentNode);
currentNode.parentNode.removeChild(currentNode);
newCurrentNode = afterContentNode;
};
this.rawEditor.externalDomUpdate('inserting markdown', insertElement);
this.rawEditor.updateRichNode();
let richNode = getRichNodeMatchingDomNode(newCurrentNode, this.rawEditor.richNode);
this.rawEditor.setCurrentPosition(get(richNode, 'start'));
return HandlerResponse.create({allowPropagation: false});
}
}
| 33.37037 | 110 | 0.710877 |
fce5d2d7cf5daffd0d44769141500aa15c1f68ae | 760 | js | JavaScript | ci/cypress/integration/auth/logout.spec.js | bit-country/bitcountry-dapp | 3ffb18511b7b2bd90070ddfc7899b592a8f2f08d | [
"Apache-2.0"
] | 11 | 2020-09-15T00:45:51.000Z | 2022-02-24T15:09:54.000Z | ci/cypress/integration/auth/logout.spec.js | bit-country/bitcountry-dapp | 3ffb18511b7b2bd90070ddfc7899b592a8f2f08d | [
"Apache-2.0"
] | null | null | null | ci/cypress/integration/auth/logout.spec.js | bit-country/bitcountry-dapp | 3ffb18511b7b2bd90070ddfc7899b592a8f2f08d | [
"Apache-2.0"
] | 2 | 2020-09-22T23:07:22.000Z | 2020-12-16T08:36:13.000Z | /// <reference types="Cypress" />
describe("Logout Test:", () => {
beforeEach("Login", () => {
cy.login();
});
// TODO this will need to be tested for client/employer later
it("Logout", function () {
cy.login();
cy.visit("/");
// perform UI logout
cy.get("a.nav-btn > .anticon-logout").trigger("click");
// // redirected back to login screen
// cy.location("pathname").should("eq", "/login");
// // check that local storage property 'authority' is set back to Guest
// cy.getLocalStorage("authority").should("equal", '["Guest"]');
// // check that local storage property 'token' has been cleared out
// cy.getLocalStorage("token").then((token) => {
// expect(token).to.be.null;
// });
});
});
| 30.4 | 76 | 0.586842 |
fce6a505be3d28a03bb679b358dfdb8f6b9f8a8a | 8,005 | js | JavaScript | public/lib/angular-kendo/doc/lib/prism/prism.js | Nen0/bazaprojekata | bd5c2e8c9734a02c14b07bf80463b0603918a9e9 | [
"MIT"
] | null | null | null | public/lib/angular-kendo/doc/lib/prism/prism.js | Nen0/bazaprojekata | bd5c2e8c9734a02c14b07bf80463b0603918a9e9 | [
"MIT"
] | 3 | 2019-12-01T15:43:11.000Z | 2021-05-10T20:23:06.000Z | public/lib/angular-kendo/doc/lib/prism/prism.js | Nen0/bazaprojekata | bd5c2e8c9734a02c14b07bf80463b0603918a9e9 | [
"MIT"
] | null | null | null | /* http://prismjs.com/download.html?themes=prism&languages=markup+css+css-extras+clike+javascript&plugins=line-numbers */
var self=typeof window!="undefined"?window:{},Prism=function(){var e=/\blang(?:uage)?-(?!\*)(\w+)\b/i,t=self.Prism={util:{type:function(e){return Object.prototype.toString.call(e).match(/\[object (\w+)\]/)[1]},clone:function(e){var n=t.util.type(e);switch(n){case"Object":var r={};for(var i in e)e.hasOwnProperty(i)&&(r[i]=t.util.clone(e[i]));return r;case"Array":return e.slice()}return e}},languages:{extend:function(e,n){var r=t.util.clone(t.languages[e]);for(var i in n)r[i]=n[i];return r},insertBefore:function(e,n,r,i){i=i||t.languages;var s=i[e],o={};for(var u in s)if(s.hasOwnProperty(u)){if(u==n)for(var a in r)r.hasOwnProperty(a)&&(o[a]=r[a]);o[u]=s[u]}return i[e]=o},DFS:function(e,n){for(var r in e){n.call(e,r,e[r]);t.util.type(e)==="Object"&&t.languages.DFS(e[r],n)}}},highlightAll:function(e,n){var r=document.querySelectorAll('code[class*="language-"], [class*="language-"] code, code[class*="lang-"], [class*="lang-"] code');for(var i=0,s;s=r[i++];)t.highlightElement(s,e===!0,n)},highlightElement:function(r,i,s){var o,u,a=r;while(a&&!e.test(a.className))a=a.parentNode;if(a){o=(a.className.match(e)||[,""])[1];u=t.languages[o]}if(!u)return;r.className=r.className.replace(e,"").replace(/\s+/g," ")+" language-"+o;a=r.parentNode;/pre/i.test(a.nodeName)&&(a.className=a.className.replace(e,"").replace(/\s+/g," ")+" language-"+o);var f=r.textContent;if(!f)return;f=f.replace(/&/g,"&").replace(/</g,"<").replace(/\u00a0/g," ");var l={element:r,language:o,grammar:u,code:f};t.hooks.run("before-highlight",l);if(i&&self.Worker){var c=new Worker(t.filename);c.onmessage=function(e){l.highlightedCode=n.stringify(JSON.parse(e.data),o);t.hooks.run("before-insert",l);l.element.innerHTML=l.highlightedCode;s&&s.call(l.element);t.hooks.run("after-highlight",l)};c.postMessage(JSON.stringify({language:l.language,code:l.code}))}else{l.highlightedCode=t.highlight(l.code,l.grammar,l.language);t.hooks.run("before-insert",l);l.element.innerHTML=l.highlightedCode;s&&s.call(r);t.hooks.run("after-highlight",l)}},highlight:function(e,r,i){return n.stringify(t.tokenize(e,r),i)},tokenize:function(e,n,r){var i=t.Token,s=[e],o=n.rest;if(o){for(var u in o)n[u]=o[u];delete n.rest}e:for(var u in n){if(!n.hasOwnProperty(u)||!n[u])continue;var a=n[u],f=a.inside,l=!!a.lookbehind,c=0;a=a.pattern||a;for(var h=0;h<s.length;h++){var p=s[h];if(s.length>e.length)break e;if(p instanceof i)continue;a.lastIndex=0;var d=a.exec(p);if(d){l&&(c=d[1].length);var v=d.index-1+c,d=d[0].slice(c),m=d.length,g=v+m,y=p.slice(0,v+1),b=p.slice(g+1),w=[h,1];y&&w.push(y);var E=new i(u,f?t.tokenize(d,f):d);w.push(E);b&&w.push(b);Array.prototype.splice.apply(s,w)}}}return s},hooks:{all:{},add:function(e,n){var r=t.hooks.all;r[e]=r[e]||[];r[e].push(n)},run:function(e,n){var r=t.hooks.all[e];if(!r||!r.length)return;for(var i=0,s;s=r[i++];)s(n)}}},n=t.Token=function(e,t){this.type=e;this.content=t};n.stringify=function(e,r,i){if(typeof e=="string")return e;if(Object.prototype.toString.call(e)=="[object Array]")return e.map(function(t){return n.stringify(t,r,e)}).join("");var s={type:e.type,content:n.stringify(e.content,r,i),tag:"span",classes:["token",e.type],attributes:{},language:r,parent:i};s.type=="comment"&&(s.attributes.spellcheck="true");t.hooks.run("wrap",s);var o="";for(var u in s.attributes)o+=u+'="'+(s.attributes[u]||"")+'"';return"<"+s.tag+' class="'+s.classes.join(" ")+'" '+o+">"+s.content+"</"+s.tag+">"};if(!self.document){if(!self.addEventListener)return self.Prism;self.addEventListener("message",function(e){var n=JSON.parse(e.data),r=n.language,i=n.code;self.postMessage(JSON.stringify(t.tokenize(i,t.languages[r])));self.close()},!1);return self.Prism}var r=document.getElementsByTagName("script");r=r[r.length-1];if(r){t.filename=r.src;document.addEventListener&&!r.hasAttribute("data-manual")&&document.addEventListener("DOMContentLoaded",t.highlightAll)}return self.Prism}();typeof module!="undefined"&&module.exports&&(module.exports=Prism);;
Prism.languages.markup={comment:/<!--[\w\W]*?-->/g,prolog:/<\?.+?\?>/,doctype:/<!DOCTYPE.+?>/,cdata:/<!\[CDATA\[[\w\W]*?]]>/i,tag:{pattern:/<\/?[\w:-]+\s*(?:\s+[\w:-]+(?:=(?:("|')(\\?[\w\W])*?\1|[^\s'">=]+))?\s*)*\/?>/gi,inside:{tag:{pattern:/^<\/?[\w:-]+/i,inside:{punctuation:/^<\/?/,namespace:/^[\w-]+?:/}},"attr-value":{pattern:/=(?:('|")[\w\W]*?(\1)|[^\s>]+)/gi,inside:{punctuation:/=|>|"/g}},punctuation:/\/?>/g,"attr-name":{pattern:/[\w:-]+/g,inside:{namespace:/^[\w-]+?:/}}}},entity:/&#?[\da-z]{1,8};/gi};Prism.hooks.add("wrap",function(e){e.type==="entity"&&(e.attributes.title=e.content.replace(/&/,"&"))});;
Prism.languages.css={comment:/\/\*[\w\W]*?\*\//g,atrule:{pattern:/@[\w-]+?.*?(;|(?=\s*{))/gi,inside:{punctuation:/[;:]/g}},url:/url\((["']?).*?\1\)/gi,selector:/[^\{\}\s][^\{\};]*(?=\s*\{)/g,property:/(\b|\B)[\w-]+(?=\s*:)/ig,string:/("|')(\\?.)*?\1/g,important:/\B!important\b/gi,ignore:/&(lt|gt|amp);/gi,punctuation:/[\{\};:]/g};Prism.languages.markup&&Prism.languages.insertBefore("markup","tag",{style:{pattern:/(<|<)style[\w\W]*?(>|>)[\w\W]*?(<|<)\/style(>|>)/ig,inside:{tag:{pattern:/(<|<)style[\w\W]*?(>|>)|(<|<)\/style(>|>)/ig,inside:Prism.languages.markup.tag.inside},rest:Prism.languages.css}}});;
Prism.languages.css.selector={pattern:/[^\{\}\s][^\{\}]*(?=\s*\{)/g,inside:{"pseudo-element":/:(?:after|before|first-letter|first-line|selection)|::[-\w]+/g,"pseudo-class":/:[-\w]+(?:\(.*\))?/g,"class":/\.[-:\.\w]+/g,id:/#[-:\.\w]+/g}};Prism.languages.insertBefore("css","ignore",{hexcode:/#[\da-f]{3,6}/gi,entity:/\\[\da-f]{1,8}/gi,number:/[\d%\.]+/g,"function":/(attr|calc|cross-fade|cycle|element|hsla?|image|lang|linear-gradient|matrix3d|matrix|perspective|radial-gradient|repeating-linear-gradient|repeating-radial-gradient|rgba?|rotatex|rotatey|rotatez|rotate3d|rotate|scalex|scaley|scalez|scale3d|scale|skewx|skewy|skew|steps|translatex|translatey|translatez|translate3d|translate|url|var)/ig});;
Prism.languages.clike={comment:{pattern:/(^|[^\\])(\/\*[\w\W]*?\*\/|(^|[^:])\/\/.*?(\r?\n|$))/g,lookbehind:!0},string:/("|')(\\?.)*?\1/g,"class-name":{pattern:/((?:(?:class|interface|extends|implements|trait|instanceof|new)\s+)|(?:catch\s+\())[a-z0-9_\.\\]+/ig,lookbehind:!0,inside:{punctuation:/(\.|\\)/}},keyword:/\b(if|else|while|do|for|return|in|instanceof|function|new|try|throw|catch|finally|null|break|continue)\b/g,"boolean":/\b(true|false)\b/g,"function":{pattern:/[a-z0-9_]+\(/ig,inside:{punctuation:/\(/}},number:/\b-?(0x[\dA-Fa-f]+|\d*\.?\d+([Ee]-?\d+)?)\b/g,operator:/[-+]{1,2}|!|<=?|>=?|={1,3}|(&){1,2}|\|?\||\?|\*|\/|\~|\^|\%/g,ignore:/&(lt|gt|amp);/gi,punctuation:/[{}[\];(),.:]/g};;
Prism.languages.javascript=Prism.languages.extend("clike",{keyword:/\b(var|let|if|else|while|do|for|return|in|instanceof|function|get|set|new|with|typeof|try|throw|catch|finally|null|break|continue|this)\b/g,number:/\b-?(0x[\dA-Fa-f]+|\d*\.?\d+([Ee]-?\d+)?|NaN|-?Infinity)\b/g});Prism.languages.insertBefore("javascript","keyword",{regex:{pattern:/(^|[^/])\/(?!\/)(\[.+?]|\\.|[^/\r\n])+\/[gim]{0,3}(?=\s*($|[\r\n,.;})]))/g,lookbehind:!0}});Prism.languages.markup&&Prism.languages.insertBefore("markup","tag",{script:{pattern:/(<|<)script[\w\W]*?(>|>)[\w\W]*?(<|<)\/script(>|>)/ig,inside:{tag:{pattern:/(<|<)script[\w\W]*?(>|>)|(<|<)\/script(>|>)/ig,inside:Prism.languages.markup.tag.inside},rest:Prism.languages.javascript}}});;
Prism.hooks.add("after-highlight",function(e){var t=e.element.parentNode;if(!t||!/pre/i.test(t.nodeName)||t.className.indexOf("line-numbers")===-1){return}var n=1+e.code.split("\n").length;var r;lines=new Array(n);lines=lines.join("<span></span>");r=document.createElement("span");r.className="line-numbers-rows";r.innerHTML=lines;if(t.hasAttribute("data-start")){t.style.counterReset="linenumber "+(parseInt(t.getAttribute("data-start"),10)-1)}e.element.appendChild(r)})
;
| 800.5 | 3,964 | 0.643598 |
fce6c872fab36fcab5d43e2d0c68db446876cf2b | 1,609 | js | JavaScript | public/app/utils.js | nicksp/socialhub-addonarea | 6ab686fbe31db40a9a3e8f70450a564ce7e348fd | [
"MIT"
] | null | null | null | public/app/utils.js | nicksp/socialhub-addonarea | 6ab686fbe31db40a9a3e8f70450a564ce7e348fd | [
"MIT"
] | null | null | null | public/app/utils.js | nicksp/socialhub-addonarea | 6ab686fbe31db40a9a3e8f70450a564ce7e348fd | [
"MIT"
] | null | null | null | 'use strict';
// App namespaces
var SHApp = SHApp || {};
SHApp.Models = SHApp.Models || {};
SHApp.Views = SHApp.Views || {};
SHApp.Utils = SHApp.Utils || {};
SHApp.Utils = {
// Asynchronously load templates located in separate .html files
loadTemplate: function (views, callback) {
var deferreds = [];
$.each(views, function(index, view) {
if (SHApp.Views[view]) {
deferreds.push($.get('app/templates/' + view + '.html', function(data) {
SHApp.Views[view].prototype.template = _.template(data);
}));
}
});
$.when.apply(null, deferreds).done(callback);
},
displayValidationErrors: function (messages) {
for (var key in messages) {
if (messages.hasOwnProperty(key)) {
this.addValidationError(key, messages[key]);
}
}
this.showAlert('Warning!', 'Fix validation errors and try again', 'alert-warning');
},
addValidationError: function (field, message) {
var controlGroup = $('#' + field).parent().parent();
controlGroup.addClass('error');
$('.help-inline', controlGroup).html(message);
},
removeValidationError: function (field) {
var controlGroup = $('#' + field).parent().parent();
controlGroup.removeClass('error');
$('.help-inline', controlGroup).html('');
},
showAlert: function(title, text, klass) {
$('.alert').removeClass('alert-error alert-warning alert-success alert-info');
$('.alert').addClass(klass);
$('.alert').html('<strong>' + title + '</strong> ' + text);
$('.alert').show();
},
hideAlert: function() {
$('.alert').hide();
}
};
| 27.271186 | 87 | 0.607209 |
fce7ad7ab276200a96f7cbedd1b936d487178c54 | 115 | js | JavaScript | src/config/index.js | voloviv/rekognition-demo | 6aa6f5027c4b75dee642fa24bfb49097220f14b9 | [
"MIT"
] | 1 | 2018-08-07T13:07:16.000Z | 2018-08-07T13:07:16.000Z | src/config/index.js | voloviv/rekognition-demo | 6aa6f5027c4b75dee642fa24bfb49097220f14b9 | [
"MIT"
] | null | null | null | src/config/index.js | voloviv/rekognition-demo | 6aa6f5027c4b75dee642fa24bfb49097220f14b9 | [
"MIT"
] | null | null | null | /* @flow */
if (__DEV__) {
module.exports = require('./.env');
} else {
module.exports = require('./prod');
}
| 14.375 | 37 | 0.556522 |
fce7c3138b644d338ff2a41ebc6aadd51c27ec3b | 5,603 | js | JavaScript | code_documentation/dynamic_graph_manager/documentation/hierarchy.js | machines-in-motion/machines-in-motion.github.io | 6deb8c3ade0b30893843084da6813789c63d9b43 | [
"BSD-3-Clause"
] | 1 | 2021-02-18T21:10:53.000Z | 2021-02-18T21:10:53.000Z | code_documentation/dynamic_graph_manager/documentation/hierarchy.js | machines-in-motion/machines-in-motion.github.io | 6deb8c3ade0b30893843084da6813789c63d9b43 | [
"BSD-3-Clause"
] | 4 | 2020-05-04T08:34:07.000Z | 2021-03-24T11:22:45.000Z | code_documentation/dynamic_graph_manager/documentation/hierarchy.js | machines-in-motion/machines-in-motion.github.io | 6deb8c3ade0b30893843084da6813789c63d9b43 | [
"BSD-3-Clause"
] | 1 | 2021-02-18T21:10:54.000Z | 2021-02-18T21:10:54.000Z | var hierarchy =
[
[ "dynamic_graph::internal::Add< T >", "structdynamic__graph_1_1internal_1_1Add.html", null ],
[ "dynamic_graph::internal::Add< std::pair< T, dg::Vector > >", "structdynamic__graph_1_1internal_1_1Add_3_01std_1_1pair_3_01T_00_01dg_1_1Vector_01_4_01_4.html", null ],
[ "dynamic_graph::internal::BindedSignalBase", "structdynamic__graph_1_1internal_1_1BindedSignalBase.html", [
[ "dynamic_graph::internal::BindedSignal< T, BufferSize >", "structdynamic__graph_1_1internal_1_1BindedSignal.html", null ]
] ],
[ "ros.dgcompleter.DGCompleter", "classros_1_1dgcompleter_1_1DGCompleter.html", null ],
[ "dynamic_graph::DgToRos< SotType >", "classdynamic__graph_1_1DgToRos.html", null ],
[ "dynamic_graph::DgToRos< double >", "structdynamic__graph_1_1DgToRos_3_01double_01_4.html", null ],
[ "dynamic_graph::DgToRos< Matrix >", "structdynamic__graph_1_1DgToRos_3_01Matrix_01_4.html", null ],
[ "dynamic_graph::DgToRos< MatrixHomogeneous >", "structdynamic__graph_1_1DgToRos_3_01MatrixHomogeneous_01_4.html", null ],
[ "dynamic_graph::DgToRos< specific::Twist >", "structdynamic__graph_1_1DgToRos_3_01specific_1_1Twist_01_4.html", null ],
[ "dynamic_graph::DgToRos< specific::Vector3 >", "structdynamic__graph_1_1DgToRos_3_01specific_1_1Vector3_01_4.html", null ],
[ "dynamic_graph::DgToRos< std::pair< MatrixHomogeneous, Vector > >", "structdynamic__graph_1_1DgToRos_3_01std_1_1pair_3_01MatrixHomogeneous_00_01Vector_01_4_01_4.html", null ],
[ "dynamic_graph::DgToRos< std::pair< specific::Twist, Vector > >", "structdynamic__graph_1_1DgToRos_3_01std_1_1pair_3_01specific_1_1Twist_00_01Vector_01_4_01_4.html", null ],
[ "dynamic_graph::DgToRos< std::pair< specific::Vector3, Vector > >", "structdynamic__graph_1_1DgToRos_3_01std_1_1pair_3_01specific_1_1Vector3_00_01Vector_01_4_01_4.html", null ],
[ "dynamic_graph::DgToRos< unsigned int >", "structdynamic__graph_1_1DgToRos_3_01unsigned_01int_01_4.html", null ],
[ "dynamic_graph::DgToRos< Vector >", "structdynamic__graph_1_1DgToRos_3_01Vector_01_4.html", null ],
[ "dynamic_graph::DynamicGraphManager", "classdynamic__graph_1_1DynamicGraphManager.html", [
[ "dynamic_graph_manager::SimpleDGM", "classdynamic__graph__manager_1_1SimpleDGM.html", null ]
] ],
[ "Entity", null, [
[ "dynamic_graph::Device", "classdynamic__graph_1_1Device.html", [
[ "dynamic_graph::DeviceSimulator", "classdynamic__graph_1_1DeviceSimulator.html", null ]
] ],
[ "dynamic_graph::RosPublish", "classdynamic__graph_1_1RosPublish.html", null ],
[ "dynamic_graph::RosQueuedSubscribe", "classdynamic__graph_1_1RosQueuedSubscribe.html", null ],
[ "dynamic_graph::RosRobotStatePublisher", "classdynamic__graph_1_1RosRobotStatePublisher.html", null ],
[ "dynamic_graph::RosRobotStatePublisherMt", "classdynamic__graph_1_1RosRobotStatePublisherMt.html", null ],
[ "dynamic_graph::RosSubscribe", "classdynamic__graph_1_1RosSubscribe.html", null ],
[ "dynamic_graph::RosTfListener", "classdynamic__graph_1_1RosTfListener.html", null ],
[ "dynamic_graph::RosTime", "classdynamic__graph_1_1RosTime.html", null ]
] ],
[ "exception", null, [
[ "dynamic_graph::ExceptionAbstract", "classdynamic__graph_1_1ExceptionAbstract.html", [
[ "dynamic_graph::ExceptionDynamic", "classdynamic__graph_1_1ExceptionDynamic.html", null ],
[ "dynamic_graph::ExceptionFactory", "classdynamic__graph_1_1ExceptionFactory.html", null ],
[ "dynamic_graph::ExceptionFeature", "classdynamic__graph_1_1ExceptionFeature.html", null ],
[ "dynamic_graph::ExceptionSignal", "classdynamic__graph_1_1ExceptionSignal.html", null ],
[ "dynamic_graph::ExceptionTask", "classdynamic__graph_1_1ExceptionTask.html", null ],
[ "dynamic_graph::ExceptionTools", "classdynamic__graph_1_1ExceptionTools.html", null ],
[ "dynamic_graph::ExceptionYamlCpp", "classdynamic__graph_1_1ExceptionYamlCpp.html", null ]
] ]
] ],
[ "dynamic_graph::GlobalRos", "structdynamic__graph_1_1GlobalRos.html", null ],
[ "InteractiveConsole", null, [
[ "ros.shell_client.DynamicGraphInteractiveConsole", "classros_1_1shell__client_1_1DynamicGraphInteractiveConsole.html", null ],
[ "ros_nodes.run_command.DynamicGraphInteractiveConsole", "classros__nodes_1_1run__command_1_1DynamicGraphInteractiveConsole.html", null ]
] ],
[ "object", null, [
[ "robot.Robot", "classrobot_1_1Robot.html", null ],
[ "ros.ros.Ros", "classros_1_1ros_1_1Ros.html", null ],
[ "ros.ros_client.RosPythonInterpreter", "classros_1_1ros__client_1_1RosPythonInterpreter.html", null ]
] ],
[ "dynamic_graph::PeriodicCall", "classdynamic__graph_1_1PeriodicCall.html", null ],
[ "dynamic_graph::RosPythonInterpreter", "classdynamic__graph_1_1RosPythonInterpreter.html", null ],
[ "dynamic_graph::RosRobotStatePublisherInternal", "structdynamic__graph_1_1RosRobotStatePublisherInternal.html", null ],
[ "dynamic_graph::RosRobotStatePublisherMtInternal", "structdynamic__graph_1_1RosRobotStatePublisherMtInternal.html", null ],
[ "dynamic_graph::PeriodicCall::SignalToCall", "structdynamic__graph_1_1PeriodicCall_1_1SignalToCall.html", null ],
[ "dynamic_graph::internal::TransformListenerData", "structdynamic__graph_1_1internal_1_1TransformListenerData.html", null ],
[ "dynamic_graph::specific::Twist", "classdynamic__graph_1_1specific_1_1Twist.html", null ],
[ "dynamic_graph::specific::Vector3", "classdynamic__graph_1_1specific_1_1Vector3.html", null ]
]; | 87.546875 | 183 | 0.76227 |
fce803f7523334aa4ee7765b583b3f9859fd6422 | 525 | js | JavaScript | src/tag-cloud.js | cherrry/static-tag-cloud | 331fc27204da4a4614dc043acd6f85ce1a040002 | [
"MIT"
] | null | null | null | src/tag-cloud.js | cherrry/static-tag-cloud | 331fc27204da4a4614dc043acd6f85ce1a040002 | [
"MIT"
] | null | null | null | src/tag-cloud.js | cherrry/static-tag-cloud | 331fc27204da4a4614dc043acd6f85ce1a040002 | [
"MIT"
] | null | null | null | 'use strict'
var assign = require('object-assign')
var distribute = require('./distribute')
var shuffle = require('./shuffle')
var DEFAULT_NUM_OF_BUCKETS = 4
var tagCloud = function (tagDefs, options) {
// only process tags with positive count
tagDefs = tagDefs.filter(function (tagDef) { return tagDef.count > 0 })
if (tagDefs.length === 0) return []
var numOfBuckets = (options && options.numOfBuckets) || DEFAULT_NUM_OF_BUCKETS
return shuffle(distribute(tagDefs, numOfBuckets))
}
module.exports = tagCloud
| 26.25 | 80 | 0.727619 |
fce8d7e4242f422cf237961831123365c31c7c46 | 3,406 | js | JavaScript | node_modules/flatlist-react/lib/___subComponents/ScrollToTopButton.js | MatheusBrodt/App_LabCarolVS | 9552149ceaa9bee15ef9a45fab2983c6651031c4 | [
"MIT"
] | null | null | null | node_modules/flatlist-react/lib/___subComponents/ScrollToTopButton.js | MatheusBrodt/App_LabCarolVS | 9552149ceaa9bee15ef9a45fab2983c6651031c4 | [
"MIT"
] | null | null | null | node_modules/flatlist-react/lib/___subComponents/ScrollToTopButton.js | MatheusBrodt/App_LabCarolVS | 9552149ceaa9bee15ef9a45fab2983c6651031c4 | [
"MIT"
] | null | null | null | "use strict";
var __importStar = (this && this.__importStar) || function (mod) {
if (mod && mod.__esModule) return mod;
var result = {};
if (mod != null) for (var k in mod) if (Object.hasOwnProperty.call(mod, k)) result[k] = mod[k];
result["default"] = mod;
return result;
};
Object.defineProperty(exports, "__esModule", { value: true });
var prop_types_1 = require("prop-types");
var react_1 = __importStar(require("react"));
var isType_1 = require("../___utils/isType");
var uiFunctions_1 = require("./uiFunctions");
var ScrollToTopButton = function (props) {
var anchor = react_1.createRef();
var button = props.button, position = props.position, padding = props.padding, offset = props.offset, scrollingContainer = props.scrollingContainer;
var btn = isType_1.isFunction(button) ? button() : button;
var _a = react_1.useState(false), mounted = _a[0], setMounted = _a[1];
react_1.useEffect(function () {
var buttonElement = anchor.current.nextElementSibling;
var container = anchor.current.parentNode;
var scrollContainer = scrollingContainer.current;
var containerStyle = getComputedStyle(container);
container.style.overflow = 'hidden';
container.style.position = ['absolute', 'fixed', 'relative'].includes(containerStyle.overflow)
? containerStyle.overflow : 'relative';
scrollContainer.style.overflow = 'auto';
scrollContainer.style.padding = containerStyle.padding;
scrollContainer.style.height = '100%';
container.style.padding = '0';
var positionBtn = uiFunctions_1.btnPosition(scrollContainer, buttonElement);
var pos = position.split(' ');
var updateBtnPosition = function () { return positionBtn(pos[0], pos[1], padding, offset); };
window.addEventListener('resize', updateBtnPosition);
scrollContainer.addEventListener('scroll', updateBtnPosition);
buttonElement.addEventListener('click', function () {
scrollContainer.scrollTo({
top: 0,
behavior: 'smooth'
});
});
setTimeout(function () { return updateBtnPosition(); }, 250);
setMounted(true);
return function () {
container.style.removeProperty('overflow');
container.style.removeProperty('position');
container.style.removeProperty('padding');
window.removeEventListener('resize', updateBtnPosition);
};
}, []);
return (react_1.default.createElement(react_1.default.Fragment, null,
!mounted && react_1.default.createElement("span", { ref: anchor, style: { display: 'none' } }),
button ? btn : react_1.default.createElement("button", { type: "button" }, "To Top")));
};
ScrollToTopButton.propTypes = {
scrollingContainer: prop_types_1.shape({ current: prop_types_1.oneOf([prop_types_1.element, prop_types_1.node]) }).isRequired,
button: prop_types_1.oneOfType([prop_types_1.node, prop_types_1.element, prop_types_1.func]),
position: prop_types_1.oneOf(['top right', 'top left', 'bottom right', 'bottom left']),
padding: prop_types_1.number,
offset: prop_types_1.number
};
ScrollToTopButton.defaultProps = {
button: null,
padding: 20,
offset: 50,
position: 'bottom right'
};
exports.default = ScrollToTopButton;
//# sourceMappingURL=ScrollToTopButton.js.map | 49.362319 | 152 | 0.66882 |
fce97f365c3034a37837b3bfa85833cf9bfd8271 | 2,808 | js | JavaScript | packages/bitcore-p2p-dvt/lib/messages/builder.js | proteanx/bitcore | afaa97e6c4e8472cdc4bea0ea58891da588f24b0 | [
"MIT"
] | null | null | null | packages/bitcore-p2p-dvt/lib/messages/builder.js | proteanx/bitcore | afaa97e6c4e8472cdc4bea0ea58891da588f24b0 | [
"MIT"
] | 5 | 2020-07-19T06:14:13.000Z | 2020-07-21T12:52:21.000Z | packages/bitcore-p2p-dvt/lib/messages/builder.js | proteanx/bitcore | afaa97e6c4e8472cdc4bea0ea58891da588f24b0 | [
"MIT"
] | 1 | 2019-04-08T17:11:08.000Z | 2019-04-08T17:11:08.000Z | 'use strict';
var bitcore = require('bitcore-lib-dvt');
var Inventory = require('../inventory');
function builder(options) {
/* jshint maxstatements: 20 */
/* jshint maxcomplexity: 10 */
if (!options) {
options = {};
}
if (!options.network) {
options.network = bitcore.Networks.defaultNetwork;
}
options.Block = options.Block || bitcore.Block;
options.BlockHeader = options.BlockHeader || bitcore.BlockHeader;
options.Transaction = options.Transaction || bitcore.Transaction;
options.MerkleBlock = options.MerkleBlock || bitcore.MerkleBlock;
options.protocolVersion = 70018 || 70001;
var exported = {
constructors: {
Block: options.Block,
BlockHeader: options.BlockHeader,
Transaction: options.Transaction,
MerkleBlock: options.MerkleBlock
},
defaults: {
protocolVersion: options.protocolVersion,
network: options.network
},
inventoryCommands: [
'getdata',
'inv',
'notfound'
],
commandsMap: {
version: 'Version',
verack: 'VerAck',
ping: 'Ping',
pong: 'Pong',
block: 'Block',
tx: 'Transaction',
getdata: 'GetData',
headers: 'Headers',
notfound: 'NotFound',
inv: 'Inventory',
addr: 'Addresses',
alert: 'Alert',
reject: 'Reject',
merkleblock: 'MerkleBlock',
filterload: 'FilterLoad',
filteradd: 'FilterAdd',
filterclear: 'FilterClear',
getblocks: 'GetBlocks',
getheaders: 'GetHeaders',
mempool: 'MemPool',
getaddr: 'GetAddr',
xversion: 'Xversion'
},
commands: {}
};
exported.add = function(key, Command) {
exported.commands[key] = function(obj) {
return new Command(obj, options);
};
exported.commands[key]._constructor = Command;
exported.commands[key].fromBuffer = function(buffer) {
var message = exported.commands[key]();
message.setPayload(buffer);
return message;
};
};
Object.keys(exported.commandsMap).forEach(function(key) {
exported.add(key, require('./commands/' + key));
});
exported.inventoryCommands.forEach(function(command) {
// add forTransaction methods
exported.commands[command].forTransaction = function forTransaction(hash) {
return new exported.commands[command]([Inventory.forTransaction(hash)]);
};
// add forBlock methods
exported.commands[command].forBlock = function forBlock(hash) {
return new exported.commands[command]([Inventory.forBlock(hash)]);
};
// add forFilteredBlock methods
exported.commands[command].forFilteredBlock = function forFilteredBlock(hash) {
return new exported.commands[command]([Inventory.forFilteredBlock(hash)]);
};
});
return exported;
}
module.exports = builder;
| 25.761468 | 83 | 0.646724 |
fce9908b2c887566e869b3c43450e61a4ac8b13e | 1,859 | js | JavaScript | test/math.js | mattbasta/crass | 59172f33d306cd0b6dc160db17b8a0ee286ce4de | [
"MIT"
] | 90 | 2015-02-22T16:09:00.000Z | 2022-02-21T03:03:39.000Z | test/math.js | mattbasta/crass | 59172f33d306cd0b6dc160db17b8a0ee286ce4de | [
"MIT"
] | 55 | 2015-01-29T15:26:07.000Z | 2021-05-08T00:24:10.000Z | test/math.js | mattbasta/crass | 59172f33d306cd0b6dc160db17b8a0ee286ce4de | [
"MIT"
] | 11 | 2016-10-25T17:51:58.000Z | 2020-01-12T01:32:18.000Z | var assert = require('assert');
var crass = require('../src');
var parseString = function(data) {
return crass.parse(data).toString();
};
describe('Math Expressions', function() {
it('should parse', function() {
assert.equal(parseString('a{foo:calc(50% - 100px)}'), 'a{foo:calc(50% - 100px)}');
});
it('should parse with products', function() {
assert.equal(parseString('a{foo:calc(50% * 100px)}'), 'a{foo:calc(50%*100px)}');
assert.equal(parseString('a{foo:calc(50% / 100px)}'), 'a{foo:calc(50%/100px)}');
assert.equal(parseString('a{foo:calc(5px + 50% * 100px)}'), 'a{foo:calc(5px + 50%*100px)}');
});
it('should parse with sums in products', function() {
assert.equal(parseString('a{foo:calc((5px + 50%) * 100px)}'), 'a{foo:calc((5px + 50%)*100px)}');
assert.equal(parseString('a{foo:calc(100px * (5px + 50%))}'), 'a{foo:calc(100px*(5px + 50%))}');
});
it('should pretty print', function() {
assert.equal(
crass.parse('a{foo:calc(50% * 100px)}').pretty(),
'a {\n foo: calc(50% * 100px);\n}\n'
);
assert.equal(
crass.parse('a{foo:calc(50% * 100px+5px)}').pretty(),
'a {\n foo: calc(50% * 100px + 5px);\n}\n'
);
});
it('should optimize the terms of a product', function() {
assert.equal(
crass.parse('a{foo:calc(12pt * 96px)}').optimize().toString(),
'a{foo:calc(1pc*1in)}'
);
});
it('should optimize the terms of a sum', function() {
assert.equal(
crass.parse('a{foo:calc(12pt + 96px)}').optimize().toString(),
'a{foo:calc(1pc + 1in)}'
);
assert.equal(
crass.parse('a{foo:calc(12pt - 96px)}').optimize().toString(),
'a{foo:calc(1pc - 1in)}'
);
});
});
| 37.938776 | 104 | 0.528241 |
fcea913076ab698b3f6ef323f98d8a54f231339f | 847 | js | JavaScript | bin/build-sprite-string.js | jdorfman/feather | 3422f0aaf74b57812daf064eaa6c0b162c1942e6 | [
"MIT"
] | null | null | null | bin/build-sprite-string.js | jdorfman/feather | 3422f0aaf74b57812daf064eaa6c0b162c1942e6 | [
"MIT"
] | 1 | 2017-08-12T01:52:26.000Z | 2017-08-12T01:52:26.000Z | bin/build-sprite-string.js | jdorfman/feather | 3422f0aaf74b57812daf064eaa6c0b162c1942e6 | [
"MIT"
] | null | null | null | import defaultAttrs from '../src/default-attrs.json';
const svgStartTag = `<svg xmlns="${defaultAttrs.xmlns}">\n<defs>\n`;
const svgEndTag = '</defs>\n</svg>';
/**
* Renders the inner sprites as SVG Symbols
* @param {object} icons the icons object
* @returns {string} the rendered string with SVG symbols
*/
function buildSpriteString(icons) {
const symbols = Object.keys(icons)
.map(icon => toSvgSymbol(icon, icons[icon]))
.join('');
return svgStartTag + symbols + svgEndTag;
}
/**
* Renders a SVG symbol tag
* @param {string} name The name of the icon
* @param {string} contents The contents of the icon
* @returns {string} the rendered SVG symbol
*/
function toSvgSymbol(name, contents) {
return `<symbol id="${name}" viewBox="${defaultAttrs.viewBox}">
${contents}\n</symbol>\n`;
}
export default buildSpriteString;
| 27.322581 | 68 | 0.693034 |
fceb19ee0b5fd8a6f4757d5236026e65ae779e78 | 4,276 | js | JavaScript | App_13/public/devices/controllers/devices.client.controller.js | vibhatha/digitalocean_3 | 08e8a8794d51eea642595228e353a499ca81f613 | [
"MIT"
] | null | null | null | App_13/public/devices/controllers/devices.client.controller.js | vibhatha/digitalocean_3 | 08e8a8794d51eea642595228e353a499ca81f613 | [
"MIT"
] | null | null | null | App_13/public/devices/controllers/devices.client.controller.js | vibhatha/digitalocean_3 | 08e8a8794d51eea642595228e353a499ca81f613 | [
"MIT"
] | null | null | null | // Invoke 'strict' JavaScript mode
'use strict';
// Create the 'devices' controller
angular.module('devices').controller('DevicesController', ['$scope', '$routeParams', '$location', 'Authentication', 'Devices','SmartPlugs',
function($scope, $routeParams, $location, Authentication, Devices,SmartPlugs) {
// Expose the Authentication service
$scope.authentication = Authentication;
// Create a new controller method for creating new devices
$scope.create = function() {
// Use the form fields to create a new device $resource object
var device = new Devices({
did: this.did,
name: this.name,
type: this.type,
model: this.model,
smartplugs: this.smartplugs
});
// Use the device '$save' method to send an appropriate POST request
device.$save(function(response) {
// If an device was created successfully, redirect the user to the device's page
$location.path('devices/' + response._id);
}, function(errorResponse) {
// Otherwise, present the user with the error message
$scope.error = errorResponse.data.message;
});
};
// Create a new controller method for retrieving a list of devices
$scope.find = function() {
// Use the device 'query' method to send an appropriate GET request
$scope.devices = Devices.query();
};
// Create a new controller method for retrieving a single device
$scope.findOne = function() {
// Use the device 'get' method to send an appropriate GET request
$scope.device = Devices.get({
deviceId: $routeParams.deviceId
},function(data){
SmartPlugs.get({smartplugId:data.smartplugs[data.smartplugs.length-1]},function(data1){
$scope.device.smartplugs = data1._id;
// data.smartplugs = data1.name;
// data.selectedsmartplug = 1;
console.log('Earlier Smart Plug: '+data1.name)
})
console.log(data)
});
//detect the device connected smartplug
};
// Create a new controller method for updating a single device
$scope.update = function() {
// Use the device '$update' method to send an appropriate PUT request
$scope.device.$update(function() {
// If an device was updated successfully, redirect the user to the device's page
$location.path('devices/' + $scope.device._id);
}, function(errorResponse) {
// Otherwise, present the user with the error message
$scope.error = errorResponse.data.message;
});
};
// Create a new controller method for deleting a single device
$scope.delete = function(device) {
// If an device was sent to the method, delete it
if (device) {
// Use the device '$remove' method to delete the device
device.$remove(function() {
// Remove the device from the devices list
for (var i in $scope.devices) {
if ($scope.devices[i] === device) {
$scope.devices.splice(i, 1);
}
}
});
} else {
// Otherwise, use the device '$remove' method to delete the device
$scope.device.$remove(function() {
$location.path('devices');
});
}
};
//retrieving all the Smart Plugs currently created
$scope.findSmartPlugs = function() {
// Use the device 'query' method to send an appropriate GET request
$scope.smartpluglist = SmartPlugs.query();
$scope.selectedSmartPlug = $scope.smartpluglist[1];
};
$scope.findSmartPlugs();
}
]); | 39.229358 | 139 | 0.525023 |
fcec13c93cd8000a697103ac2a4624823c214836 | 489 | js | JavaScript | db/lib/querys/inventarios_x_empleados/index.js | ucab-guayana-iinf/proyecto-bd | 35e7c72157bc56563d9d8fe11dd028d4af01e364 | [
"MIT"
] | null | null | null | db/lib/querys/inventarios_x_empleados/index.js | ucab-guayana-iinf/proyecto-bd | 35e7c72157bc56563d9d8fe11dd028d4af01e364 | [
"MIT"
] | 1 | 2021-01-28T20:33:07.000Z | 2021-01-28T20:33:07.000Z | db/lib/querys/inventarios_x_empleados/index.js | ucab-guayana-iinf/proyecto-bd | 35e7c72157bc56563d9d8fe11dd028d4af01e364 | [
"MIT"
] | null | null | null | const createInventariosxEmpleados = require('./create-inventarios_x_empleados.query');
const updateInventariosxEmpleados = require('./update-inventarios_x_empleados.query');
const readInventariosxEmpleados = require('./read-inventarios_x_empleados.query');
const deleteInventariosxEmpleados = require('./delete-inventarios_x_empleados.query');
module.exports = {
createInventariosxEmpleados,
updateInventariosxEmpleados,
readInventariosxEmpleados,
deleteInventariosxEmpleados,
};
| 40.75 | 86 | 0.832311 |
fcec2b4b7e2f3bde23e86fe9b7fce6754bcc8bfa | 147 | js | JavaScript | docs/doxygen/html/search/defines_0.js | Nero-Disney/NumPy_C_Plus_Plus | 149c236d6893225ffb859d42bb03a762fa1f667a | [
"MIT"
] | 1 | 2021-03-02T01:08:28.000Z | 2021-03-02T01:08:28.000Z | docs/doxygen/html/search/defines_0.js | wusopp/NumCpp | 149c236d6893225ffb859d42bb03a762fa1f667a | [
"MIT"
] | null | null | null | docs/doxygen/html/search/defines_0.js | wusopp/NumCpp | 149c236d6893225ffb859d42bb03a762fa1f667a | [
"MIT"
] | 1 | 2021-07-14T13:42:57.000Z | 2021-07-14T13:42:57.000Z | var searchData=
[
['no_5fexcept_2363',['NO_EXCEPT',['../_stl_algorithms_8hpp.html#a21a26d02e8952e85df87e4c35bb25ff5',1,'StlAlgorithms.hpp']]]
];
| 29.4 | 125 | 0.761905 |
fcec415d469ca235636cc93d4e58b0c55148f887 | 997 | js | JavaScript | src/helpers/objects/mergeObj/__tests__/mergeObj.test.js | pfmartins4/componentSystem | e831f5a11b20817c41fadc306697b30c67b26b38 | [
"MIT"
] | null | null | null | src/helpers/objects/mergeObj/__tests__/mergeObj.test.js | pfmartins4/componentSystem | e831f5a11b20817c41fadc306697b30c67b26b38 | [
"MIT"
] | null | null | null | src/helpers/objects/mergeObj/__tests__/mergeObj.test.js | pfmartins4/componentSystem | e831f5a11b20817c41fadc306697b30c67b26b38 | [
"MIT"
] | null | null | null | import mergeObj from "../mergeObj";
const Obj1 = {
a: 1,
b: 2,
c: "dado",
};
const Obj2 = {
a: 1,
b: 3,
d: "arroz",
};
const Obj3 = {
a: 1,
b: 3,
d: "batata",
};
const Obj4 = {
a: 1,
b: 3,
c: "xadrez",
};
const merged1In2 = {
a: 1,
b: 2,
c: "dado",
d: "arroz",
};
const merged1In3 = {
a: 1,
b: 2,
c: "dado",
d: "batata",
};
const merged2In4 = {
/*
a: 1,
b: 3,
d: "arroz",
a: 1,
b: 3,
c: "xadrez",
*/
a: 1,
b: 3,
c: "xadrez",
d: "arroz",
};
const Obj5 = {
obj1: Obj1,
obj2: Obj2,
};
const Obj6 = {
obj1: Obj3,
obj2: Obj4,
};
const merged5In6 = {
obj1: merged1In3,
obj2: merged2In4,
};
describe("Object merging", () => {
test("simple merge", () => {
expect(mergeObj(Obj2, Obj1)).toEqual(merged1In2);
expect(mergeObj(Obj3, Obj1)).toEqual(merged1In3);
expect(mergeObj(Obj4, Obj2)).toEqual(merged2In4);
});
test("deep merge", () => {
expect(mergeObj(Obj6, Obj5)).toEqual(merged5In6);
});
});
| 12.782051 | 53 | 0.51655 |
fcec89c3add6325e554cd03a2a6c81b8bde52fe8 | 1,232 | js | JavaScript | console/block-platform-console/gulpfile.js | CBD-Forum/N0003-app-container | de2d08c0d3f5ce47b835b1e416a758e8082c864f | [
"Apache-2.0"
] | 2 | 2017-05-31T08:10:19.000Z | 2017-12-15T00:23:06.000Z | console/block-platform-console/gulpfile.js | xyzLOL/app-container | de2d08c0d3f5ce47b835b1e416a758e8082c864f | [
"Apache-2.0"
] | null | null | null | console/block-platform-console/gulpfile.js | xyzLOL/app-container | de2d08c0d3f5ce47b835b1e416a758e8082c864f | [
"Apache-2.0"
] | 3 | 2017-05-22T06:58:09.000Z | 2018-02-22T15:02:34.000Z | // Copyright [2016] [Lele Guo]
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
/**
* The gulp tasks are splitted in several files in the gulp directory
* because putting all here was really too long
*/
'use strict';
var gulp = require('gulp');
var wrench = require('wrench');
/**
* This will load all js or coffee files in the gulp directory
* in order to load all gulp tasks
*/
wrench.readdirSyncRecursive('./gulp').filter(function(file) {
return (/\.(js|coffee)$/i).test(file);
}).map(function(file) {
require('./gulp/' + file);
});
/**
* Default task clean temporaries directories and launch the
* main optimization build task
*/
gulp.task('default', function () {
gulp.start('build');
});
| 28.651163 | 75 | 0.700487 |
fced7703abcdb941322947e19692383f4cf8d262 | 395 | js | JavaScript | reference/JavaScript/Child_Process/spawn.js | steadylearner/code | ba6df6c38a6e25b7ea996f4df905921e27760e04 | [
"MIT"
] | 4 | 2019-07-17T14:43:32.000Z | 2022-03-27T21:38:01.000Z | reference/JavaScript/Child_Process/spawn.js | steadylearner/code | ba6df6c38a6e25b7ea996f4df905921e27760e04 | [
"MIT"
] | 39 | 2020-09-04T03:31:16.000Z | 2022-03-08T22:54:03.000Z | reference/JavaScript/Child_Process/spawn.js | steadylearner/code | ba6df6c38a6e25b7ea996f4df905921e27760e04 | [
"MIT"
] | 1 | 2021-03-03T13:04:28.000Z | 2021-03-03T13:04:28.000Z | // using child.process.spawn
const { spawn } = require('child_process');
const pwd = spawn('pwd'); // no error -> code 0
// const pwd = spawn('pwd', ['-g']); // error -> code 1
pwd.stdout.on('data', (data) => console.log('stdout: ' + data));
pwd.stderr.on('data', (data) => console.error('stderr: ' + data));
pwd.on('close', (code) => console.log('child process exited with code: ' + code)); | 35.909091 | 82 | 0.610127 |
fcedafc75ea42c5b7d120f8ae118b2bc625069e9 | 760 | js | JavaScript | src/firebase/config.js | giang184/card-suggestor-react-hooks | 12c514dd543254bb097cdfb9324135047eafa11d | [
"Unlicense"
] | null | null | null | src/firebase/config.js | giang184/card-suggestor-react-hooks | 12c514dd543254bb097cdfb9324135047eafa11d | [
"Unlicense"
] | null | null | null | src/firebase/config.js | giang184/card-suggestor-react-hooks | 12c514dd543254bb097cdfb9324135047eafa11d | [
"Unlicense"
] | null | null | null | import * as firebase from 'firebase/app';
import "firebase/auth"
import 'firebase/storage';
import 'firebase/firestore';
const firebaseConfig = {
apiKey: process.env.REACT_APP_FIREBASE_API_KEY,
authDomain: process.env.REACT_APP_FIREBASE_AUTH_DOMAIN,
databaseURL: process.env.REACT_APP_FIREBASE_DATABASE_URL,
projectId: process.env.REACT_APP_FIREBASE_PROJECT_ID,
storageBucket: process.env.REACT_APP_FIREBASE_STORAGE_BUCKET,
messagingSenderId: process.env.REACT_APP_FIREBASE_SENDER_ID,
appId: process.env.REACT_APP_FIREBASE_APP_ID
};
firebase.initializeApp(firebaseConfig);
const projectStorage = firebase.storage();
const projectFirestore = firebase.firestore();
const auth = firebase.auth();
export {projectStorage, projectFirestore, auth}; | 34.545455 | 63 | 0.819737 |
fcedbf1011e9394dd7e3eed2841d6c2b3396fcbb | 4,084 | js | JavaScript | node_modules/ory-editor-core/lib/components/Editable/index.js | fsdanniel/cleverstry | e889b3149d505e9b33640e0cf98621b49f3adf7b | [
"MIT"
] | null | null | null | node_modules/ory-editor-core/lib/components/Editable/index.js | fsdanniel/cleverstry | e889b3149d505e9b33640e0cf98621b49f3adf7b | [
"MIT"
] | null | null | null | node_modules/ory-editor-core/lib/components/Editable/index.js | fsdanniel/cleverstry | e889b3149d505e9b33640e0cf98621b49f3adf7b | [
"MIT"
] | null | null | null | "use strict";
/*
* This file is part of ORY Editor.
*
* ORY Editor is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* ORY Editor is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with ORY Editor. If not, see <http://www.gnu.org/licenses/>.
*
* @license LGPL-3.0
* @copyright 2016-2018 Aeneas Rekkas
* @author Aeneas Rekkas <aeneas+oss@aeneas.io>
*
*/
var __extends = (this && this.__extends) || (function () {
var extendStatics = function (d, b) {
extendStatics = Object.setPrototypeOf ||
({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
return extendStatics(d, b);
};
return function (d, b) {
extendStatics(d, b);
function __() { this.constructor = d; }
d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
};
})();
var __importStar = (this && this.__importStar) || function (mod) {
if (mod && mod.__esModule) return mod;
var result = {};
if (mod != null) for (var k in mod) if (Object.hasOwnProperty.call(mod, k)) result[k] = mod[k];
result["default"] = mod;
return result;
};
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
var React = __importStar(require("react"));
var react_redux_1 = require("react-redux");
var DragDropContext_1 = __importDefault(require("../DragDropContext"));
var Decorator_1 = __importDefault(require("../HotKey/Decorator"));
var editable_1 = require("../../selector/editable");
var Inner_1 = __importDefault(require("./Inner"));
var Editable = /** @class */ (function (_super) {
__extends(Editable, _super);
function Editable(props) {
var _this = _super.call(this, props) || this;
_this.previousState = {};
_this.onChange = function () {
var onChange = _this.props.onChange;
if (typeof onChange !== 'function') {
return;
}
var state = editable_1.editable(_this.props.editor.store.getState(), {
id: _this.props.id,
});
if (state === _this.previousState || !state) {
return;
}
var serialized = _this.props.editor.plugins.serialize(state);
onChange(serialized);
};
_this.DragDropContext = DragDropContext_1.default(props.editor.dragDropContext);
return _this;
}
Editable.prototype.componentDidMount = function () {
if (!this.props.id) {
throw new Error('The state must have an unique id');
}
this.unsubscribe = this.props.editor.store.subscribe(this.onChange);
this.previousState = null;
};
Editable.prototype.componentWillUnmount = function () {
this.unsubscribe();
};
Editable.prototype.render = function () {
var _a = this.props, id = _a.id, _b = _a.editor, store = _b.store, defaultPlugin = _b.defaultPlugin;
var DragDropContext = this.DragDropContext;
return (React.createElement(react_redux_1.Provider, { store: store },
React.createElement(DragDropContext, null,
React.createElement(Decorator_1.default, { id: id },
React.createElement(Inner_1.default, { id: id, defaultPlugin: defaultPlugin })))));
};
return Editable;
}(React.PureComponent));
exports.default = Editable;
//# sourceMappingURL=index.js.map | 42.541667 | 108 | 0.630509 |
fcedd5927a6e90ad89d26fe6b5f1432e63eecd8b | 2,119 | js | JavaScript | client/src/redux/student/auth/authReducer.js | opensource-NITT/ClassWeb | 97b0b50e47acc01c1b8d941f536c88a5a92bd556 | [
"MIT"
] | 1 | 2021-01-01T19:49:28.000Z | 2021-01-01T19:49:28.000Z | client/src/redux/student/auth/authReducer.js | opensource-NITT/ClassWeb | 97b0b50e47acc01c1b8d941f536c88a5a92bd556 | [
"MIT"
] | null | null | null | client/src/redux/student/auth/authReducer.js | opensource-NITT/ClassWeb | 97b0b50e47acc01c1b8d941f536c88a5a92bd556 | [
"MIT"
] | null | null | null | import * as type from './authTypes';
const initialState = {
token:sessionStorage.getItem('token'),
isAuthenticated:null,
user:null,
registerMessage:null,
resend:false
};
export default function(state=initialState, action){
switch(action.type){
case type.LOGIN_SUCCESS:
sessionStorage.setItem('token', action.payload.token);
return {
...state,
...action.payload,
isAuthenticated: true,
registerMessage:null,
};
case type.REGISTER_SUCCESS:
return{
...state,
registerMessage:action.payload.msg
};
case type.LOGIN_FAIL:
case type.LOGOUT_SUCCESS:
sessionStorage.removeItem('token');
return {
...state,
token: null,
user: null,
isAuthenticated: false,
registerMessage:null,
};
case type.REGISTER_FAIL:
sessionStorage.removeItem('token');
return {
...state,
token: null,
user: null,
class:null,
isAuthenticated: false,
registerMessage:null,
resend:action.payload.resend
};
case type.PROFILE_CHANGE:
return{
...state,
user:{...state.user,photo:action.payload}
}
case type.TABLE:
return{
...state,
class:{...state.class,timetable:action.payload.data}
}
case type.VOTE:
return{
...state,
class:{...state.class,poll:action.payload.data}
}
case type.MESSAGE:
return{
...state,
class:{...state.class,messages:[...state.class.messages,action.payload]}
}
case type.CLASS:
return{
...state,
class:{...state.class,onlineclass:action.payload}
}
default:
return state;
}
} | 28.253333 | 88 | 0.480887 |
fcee253b5398b1984d247e9750390b507743f303 | 238 | js | JavaScript | demo/server.js | kvsur/audio2wave | d0dadeec24453d7763d3a8e46d6e0da13c93d1f9 | [
"MIT"
] | 3 | 2020-12-04T12:29:29.000Z | 2021-05-24T04:39:48.000Z | demo/server.js | kvsur/audio2wave | d0dadeec24453d7763d3a8e46d6e0da13c93d1f9 | [
"MIT"
] | null | null | null | demo/server.js | kvsur/audio2wave | d0dadeec24453d7763d3a8e46d6e0da13c93d1f9 | [
"MIT"
] | null | null | null | const Express = require('express');
const path = require('path');
const App = Express();
const PORT = 3000;
App.use(Express.static(path.resolve(__dirname, './')))
App.listen(PORT, () => {
console.log(`http://localhost:${PORT}`)
}) | 19.833333 | 54 | 0.642857 |