code
stringlengths
2
1.05M
var mongoose = require('mongoose'); var Schema = mongoose.Schema; var schema = new Schema({ imagePath: { type: String, required: true }, title: { type: String, required: true }, description: { type: String, required: true }, price: { type: Number, required: true }, qty: { type: Number, required: true }, }); module.exports = mongoose.model('Product', schema);
(function ($) { Ss_input.fileSystemHandlers['sort'] = Ss_input.Handler.extend({ defaults: { sortType: 'asc', sortBy: 'ext', sortableFields: ['ext', 'name', 'date'] } }) })(jQuery);
/* eslint-disable no-console */ var client = require('bellman'); var AWS = require('aws-sdk'); var sts = new AWS.STS(); var R = {}; R.RoleSessionName = 'assuming-role-from-builder'; R.RoleArn = 'arn:aws:iam::181472263199:role/Deployer'; sts.assumeRole(R, function(err,response) { if( err ) { console.log( err ); return; } const { AccessKeyId: accessKey, SecretAccessKey: secretKey, SessionToken: sessionToken } = response.Credentials; const cfg = { accessKey, secretKey, sessionToken }; var api = client.prod.deploy(cfg); api.build().then( ok => console.log( 'OK', ok ) ) .catch( err => console.log( 'ERR', err )); });
Tinytest.add('ServerSession - set', function (test) { if (Meteor.isServer) { test.isUndefined(ServerSession.setCondition(function () { return true; })); } test.throws(function () { ServerSession.set(); }, Error, 'Should throw an error if no key and value are provided when using set' ); test.isUndefined(ServerSession.set('testKey', 'testValue')); test.equal('testValue', ServerSession.get('testKey')); ServerSession.set('testKey'); test.isTrue(undefined == ServerSession.get('testKey') || null == ServerSession.get('testKey')); }); Tinytest.add('ServerSession - get', function (test) { ServerSession.set('null', null); ServerSession.set('aBool', true); ServerSession.set('anInteger', 12345); ServerSession.set('aString', 'meIzAString'); ServerSession.set('anArray', [1, 2, 3, ['4', '5', '6', [12, 23, 34]]]); ServerSession.set('anObject', { 'keyOfObject' : 'value', 'keyOfObj' : {'a' : ['b', 'c'] } }); test.equal(null, ServerSession.get('null')); test.equal(true, ServerSession.get('aBool')); test.equal(12345, ServerSession.get('anInteger')); test.equal('meIzAString', ServerSession.get('aString')); test.equal([1, 2, 3, ['4', '5', '6', [12, 23, 34]]], ServerSession.get('anArray')); test.equal({ 'keyOfObject' : 'value', 'keyOfObj' : {'a' : ['b', 'c'] } }, ServerSession.get('anObject')); }); Tinytest.add('ServerSession - equals (identical)', function (test) { ServerSession.set('null', null); ServerSession.set('true', true); ServerSession.set('54321', 54321); ServerSession.set('aRandomString', 'aRandomString1'); ServerSession.set('array', [1, 2, 3, ['4', '5', '6', [11, 12, 31]]]); ServerSession.set('object', { 'keyOfObject' : '_value'}); ServerSession.set('emptyObj', {}); ServerSession.set('emptyArray', []); test.isTrue(ServerSession.equals('null', null)); test.isTrue(ServerSession.equals('true', true)); test.isTrue(ServerSession.equals('54321', 54321)); test.isTrue(ServerSession.equals('emptyObj', {})); test.isTrue(ServerSession.equals('emptyArray', [])); test.isTrue(ServerSession.equals('array', [1, 2, 3, ['4', '5', '6', [11, 12, 31]]])); test.isFalse(ServerSession.equals('emptyObj', [])); test.isFalse(ServerSession.equals('emptyArray', {})); test.isFalse(ServerSession.equals('aRandomString', 'aRandomString')); test.isFalse(ServerSession.equals('array', [1, 2, 3, ['4', '5', '6', [11, 12, 30]]])); test.isFalse(ServerSession.equals('object', { 'keyOfObject' : 'value'})); }); Tinytest.add('ServerSession - equals (not identical)', function (test) { ServerSession.set('54321', 1); ServerSession.set('null', null); ServerSession.set('true', true); ServerSession.set('aStringString', 'stringity'); test.isTrue(ServerSession.equals('null', undefined, false)); test.isTrue(ServerSession.equals('true', !null, false)); test.isTrue(ServerSession.equals('54321', true, false)); test.isFalse(ServerSession.equals('aStringString', 'stringity11', false)); }); if (Meteor.isServer) { Tinytest.add('ServerSession - Conditions', function (test) { test.isUndefined(ServerSession.setCondition(function () { return false; })); test.throws(function () { ServerSession.set('theKey', { foo : 'bar' }); }, Meteor.Error); test.isFalse(ServerSession.equals('theKey', { foo : 'bar' })); // Also test with return true test.isUndefined(ServerSession.setCondition(function () { return true; })); ServerSession.set('newKey', { foo : 'bar' }); test.equal('bar', ServerSession.get('newKey').foo); ServerSession.set('newKey', undefined); }); }
/** * @author alteredq / http://alteredqualia.com/ */ THREE.BinaryLoader = function ( showStatus ) { THREE.Loader.call( this, showStatus ); }; THREE.BinaryLoader.prototype = Object.create( THREE.Loader.prototype ); // Load models generated by slim OBJ converter with BINARY option (converter_obj_three_slim.py -t binary) // - binary models consist of two files: JS and BIN // - parameters // - url (required) // - callback (required) // - texturePath (optional: if not specified, textures will be assumed to be in the same folder as JS model file) // - binaryPath (optional: if not specified, binary file will be assumed to be in the same folder as JS model file) THREE.BinaryLoader.prototype.load = function( url, callback, texturePath, binaryPath ) { texturePath = texturePath ? texturePath : this.extractUrlBase( url ); binaryPath = binaryPath ? binaryPath : this.extractUrlBase( url ); var callbackProgress = this.showProgress ? THREE.Loader.prototype.updateProgress : null; this.onLoadStart(); // #1 load JS part via web worker this.loadAjaxJSON( this, url, callback, texturePath, binaryPath, callbackProgress ); }; THREE.BinaryLoader.prototype.loadAjaxJSON = function ( context, url, callback, texturePath, binaryPath, callbackProgress ) { var xhr = new XMLHttpRequest(); xhr.onreadystatechange = function () { if ( xhr.readyState == 4 ) { if ( xhr.status == 200 || xhr.status == 0 ) { var json = JSON.parse( xhr.responseText ); context.loadAjaxBuffers( json, callback, binaryPath, texturePath, callbackProgress ); } else { console.error( "THREE.BinaryLoader: Couldn't load [" + url + "] [" + xhr.status + "]" ); } } }; xhr.open( "GET", url, true ); if ( xhr.overrideMimeType ) xhr.overrideMimeType( "text/plain; charset=x-user-defined" ); xhr.setRequestHeader( "Content-Type", "text/plain" ); xhr.send( null ); }; THREE.BinaryLoader.prototype.loadAjaxBuffers = function ( json, callback, binaryPath, texturePath, callbackProgress ) { var xhr = new XMLHttpRequest(), url = binaryPath + "/" + json.buffers; var length = 0; xhr.onreadystatechange = function () { if ( xhr.readyState == 4 ) { if ( xhr.status == 200 || xhr.status == 0 ) { var buffer = xhr.response; if ( buffer === undefined ) buffer = ( new Uint8Array( xhr.responseBody ) ).buffer; // IEWEBGL needs this THREE.BinaryLoader.prototype.createBinModel( buffer, callback, texturePath, json.materials ); } else { console.error( "THREE.BinaryLoader: Couldn't load [" + url + "] [" + xhr.status + "]" ); } } else if ( xhr.readyState == 3 ) { if ( callbackProgress ) { if ( length == 0 ) { length = xhr.getResponseHeader( "Content-Length" ); } callbackProgress( { total: length, loaded: xhr.responseText.length } ); } } else if ( xhr.readyState == 2 ) { length = xhr.getResponseHeader( "Content-Length" ); } }; xhr.open( "GET", url, true ); xhr.responseType = "arraybuffer"; xhr.send( null ); }; // Binary AJAX parser THREE.BinaryLoader.prototype.createBinModel = function ( data, callback, texturePath, materials ) { var Model = function ( texturePath ) { var scope = this, currentOffset = 0, md, normals = [], uvs = [], start_tri_flat, start_tri_smooth, start_tri_flat_uv, start_tri_smooth_uv, start_quad_flat, start_quad_smooth, start_quad_flat_uv, start_quad_smooth_uv, tri_size, quad_size, len_tri_flat, len_tri_smooth, len_tri_flat_uv, len_tri_smooth_uv, len_quad_flat, len_quad_smooth, len_quad_flat_uv, len_quad_smooth_uv; THREE.Geometry.call( this ); THREE.Loader.prototype.initMaterials( scope, materials, texturePath ); md = parseMetaData( data, currentOffset ); currentOffset += md.header_bytes; /* md.vertex_index_bytes = Uint32Array.BYTES_PER_ELEMENT; md.material_index_bytes = Uint16Array.BYTES_PER_ELEMENT; md.normal_index_bytes = Uint32Array.BYTES_PER_ELEMENT; md.uv_index_bytes = Uint32Array.BYTES_PER_ELEMENT; */ // buffers sizes tri_size = md.vertex_index_bytes * 3 + md.material_index_bytes; quad_size = md.vertex_index_bytes * 4 + md.material_index_bytes; len_tri_flat = md.ntri_flat * ( tri_size ); len_tri_smooth = md.ntri_smooth * ( tri_size + md.normal_index_bytes * 3 ); len_tri_flat_uv = md.ntri_flat_uv * ( tri_size + md.uv_index_bytes * 3 ); len_tri_smooth_uv = md.ntri_smooth_uv * ( tri_size + md.normal_index_bytes * 3 + md.uv_index_bytes * 3 ); len_quad_flat = md.nquad_flat * ( quad_size ); len_quad_smooth = md.nquad_smooth * ( quad_size + md.normal_index_bytes * 4 ); len_quad_flat_uv = md.nquad_flat_uv * ( quad_size + md.uv_index_bytes * 4 ); len_quad_smooth_uv = md.nquad_smooth_uv * ( quad_size + md.normal_index_bytes * 4 + md.uv_index_bytes * 4 ); // read buffers currentOffset += init_vertices( currentOffset ); currentOffset += init_normals( currentOffset ); currentOffset += handlePadding( md.nnormals * 3 ); currentOffset += init_uvs( currentOffset ); start_tri_flat = currentOffset; start_tri_smooth = start_tri_flat + len_tri_flat + handlePadding( md.ntri_flat * 2 ); start_tri_flat_uv = start_tri_smooth + len_tri_smooth + handlePadding( md.ntri_smooth * 2 ); start_tri_smooth_uv = start_tri_flat_uv + len_tri_flat_uv + handlePadding( md.ntri_flat_uv * 2 ); start_quad_flat = start_tri_smooth_uv + len_tri_smooth_uv + handlePadding( md.ntri_smooth_uv * 2 ); start_quad_smooth = start_quad_flat + len_quad_flat + handlePadding( md.nquad_flat * 2 ); start_quad_flat_uv = start_quad_smooth + len_quad_smooth + handlePadding( md.nquad_smooth * 2 ); start_quad_smooth_uv= start_quad_flat_uv + len_quad_flat_uv + handlePadding( md.nquad_flat_uv * 2 ); // have to first process faces with uvs // so that face and uv indices match init_triangles_flat_uv( start_tri_flat_uv ); init_triangles_smooth_uv( start_tri_smooth_uv ); init_quads_flat_uv( start_quad_flat_uv ); init_quads_smooth_uv( start_quad_smooth_uv ); // now we can process untextured faces init_triangles_flat( start_tri_flat ); init_triangles_smooth( start_tri_smooth ); init_quads_flat( start_quad_flat ); init_quads_smooth( start_quad_smooth ); this.computeCentroids(); this.computeFaceNormals(); if ( THREE.Loader.prototype.hasNormals( this ) ) this.computeTangents(); function handlePadding( n ) { return ( n % 4 ) ? ( 4 - n % 4 ) : 0; }; function parseMetaData( data, offset ) { var metaData = { 'signature' :parseString( data, offset, 12 ), 'header_bytes' :parseUChar8( data, offset + 12 ), 'vertex_coordinate_bytes' :parseUChar8( data, offset + 13 ), 'normal_coordinate_bytes' :parseUChar8( data, offset + 14 ), 'uv_coordinate_bytes' :parseUChar8( data, offset + 15 ), 'vertex_index_bytes' :parseUChar8( data, offset + 16 ), 'normal_index_bytes' :parseUChar8( data, offset + 17 ), 'uv_index_bytes' :parseUChar8( data, offset + 18 ), 'material_index_bytes' :parseUChar8( data, offset + 19 ), 'nvertices' :parseUInt32( data, offset + 20 ), 'nnormals' :parseUInt32( data, offset + 20 + 4*1 ), 'nuvs' :parseUInt32( data, offset + 20 + 4*2 ), 'ntri_flat' :parseUInt32( data, offset + 20 + 4*3 ), 'ntri_smooth' :parseUInt32( data, offset + 20 + 4*4 ), 'ntri_flat_uv' :parseUInt32( data, offset + 20 + 4*5 ), 'ntri_smooth_uv' :parseUInt32( data, offset + 20 + 4*6 ), 'nquad_flat' :parseUInt32( data, offset + 20 + 4*7 ), 'nquad_smooth' :parseUInt32( data, offset + 20 + 4*8 ), 'nquad_flat_uv' :parseUInt32( data, offset + 20 + 4*9 ), 'nquad_smooth_uv' :parseUInt32( data, offset + 20 + 4*10 ) }; /* console.log( "signature: " + metaData.signature ); console.log( "header_bytes: " + metaData.header_bytes ); console.log( "vertex_coordinate_bytes: " + metaData.vertex_coordinate_bytes ); console.log( "normal_coordinate_bytes: " + metaData.normal_coordinate_bytes ); console.log( "uv_coordinate_bytes: " + metaData.uv_coordinate_bytes ); console.log( "vertex_index_bytes: " + metaData.vertex_index_bytes ); console.log( "normal_index_bytes: " + metaData.normal_index_bytes ); console.log( "uv_index_bytes: " + metaData.uv_index_bytes ); console.log( "material_index_bytes: " + metaData.material_index_bytes ); console.log( "nvertices: " + metaData.nvertices ); console.log( "nnormals: " + metaData.nnormals ); console.log( "nuvs: " + metaData.nuvs ); console.log( "ntri_flat: " + metaData.ntri_flat ); console.log( "ntri_smooth: " + metaData.ntri_smooth ); console.log( "ntri_flat_uv: " + metaData.ntri_flat_uv ); console.log( "ntri_smooth_uv: " + metaData.ntri_smooth_uv ); console.log( "nquad_flat: " + metaData.nquad_flat ); console.log( "nquad_smooth: " + metaData.nquad_smooth ); console.log( "nquad_flat_uv: " + metaData.nquad_flat_uv ); console.log( "nquad_smooth_uv: " + metaData.nquad_smooth_uv ); var total = metaData.header_bytes + metaData.nvertices * metaData.vertex_coordinate_bytes * 3 + metaData.nnormals * metaData.normal_coordinate_bytes * 3 + metaData.nuvs * metaData.uv_coordinate_bytes * 2 + metaData.ntri_flat * ( metaData.vertex_index_bytes*3 + metaData.material_index_bytes ) + metaData.ntri_smooth * ( metaData.vertex_index_bytes*3 + metaData.material_index_bytes + metaData.normal_index_bytes*3 ) + metaData.ntri_flat_uv * ( metaData.vertex_index_bytes*3 + metaData.material_index_bytes + metaData.uv_index_bytes*3 ) + metaData.ntri_smooth_uv * ( metaData.vertex_index_bytes*3 + metaData.material_index_bytes + metaData.normal_index_bytes*3 + metaData.uv_index_bytes*3 ) + metaData.nquad_flat * ( metaData.vertex_index_bytes*4 + metaData.material_index_bytes ) + metaData.nquad_smooth * ( metaData.vertex_index_bytes*4 + metaData.material_index_bytes + metaData.normal_index_bytes*4 ) + metaData.nquad_flat_uv * ( metaData.vertex_index_bytes*4 + metaData.material_index_bytes + metaData.uv_index_bytes*4 ) + metaData.nquad_smooth_uv * ( metaData.vertex_index_bytes*4 + metaData.material_index_bytes + metaData.normal_index_bytes*4 + metaData.uv_index_bytes*4 ); console.log( "total bytes: " + total ); */ return metaData; }; function parseString( data, offset, length ) { var charArray = new Uint8Array( data, offset, length ); var text = ""; for ( var i = 0; i < length; i ++ ) { text += String.fromCharCode( charArray[ offset + i ] ); } return text; }; function parseUChar8( data, offset ) { var charArray = new Uint8Array( data, offset, 1 ); return charArray[ 0 ]; }; function parseUInt32( data, offset ) { var intArray = new Uint32Array( data, offset, 1 ); return intArray[ 0 ]; }; function init_vertices( start ) { var nElements = md.nvertices; var coordArray = new Float32Array( data, start, nElements * 3 ); var i, x, y, z; for( i = 0; i < nElements; i ++ ) { x = coordArray[ i * 3 ]; y = coordArray[ i * 3 + 1 ]; z = coordArray[ i * 3 + 2 ]; vertex( scope, x, y, z ); } return nElements * 3 * Float32Array.BYTES_PER_ELEMENT; }; function init_normals( start ) { var nElements = md.nnormals; if ( nElements ) { var normalArray = new Int8Array( data, start, nElements * 3 ); var i, x, y, z; for( i = 0; i < nElements; i ++ ) { x = normalArray[ i * 3 ]; y = normalArray[ i * 3 + 1 ]; z = normalArray[ i * 3 + 2 ]; normals.push( x/127, y/127, z/127 ); } } return nElements * 3 * Int8Array.BYTES_PER_ELEMENT; }; function init_uvs( start ) { var nElements = md.nuvs; if ( nElements ) { var uvArray = new Float32Array( data, start, nElements * 2 ); var i, u, v; for( i = 0; i < nElements; i ++ ) { u = uvArray[ i * 2 ]; v = uvArray[ i * 2 + 1 ]; uvs.push( u, v ); } } return nElements * 2 * Float32Array.BYTES_PER_ELEMENT; }; function init_uvs3( nElements, offset ) { var i, uva, uvb, uvc, u1, u2, u3, v1, v2, v3; var uvIndexBuffer = new Uint32Array( data, offset, 3 * nElements ); for( i = 0; i < nElements; i ++ ) { uva = uvIndexBuffer[ i * 3 ]; uvb = uvIndexBuffer[ i * 3 + 1 ]; uvc = uvIndexBuffer[ i * 3 + 2 ]; u1 = uvs[ uva*2 ]; v1 = uvs[ uva*2 + 1 ]; u2 = uvs[ uvb*2 ]; v2 = uvs[ uvb*2 + 1 ]; u3 = uvs[ uvc*2 ]; v3 = uvs[ uvc*2 + 1 ]; uv3( scope.faceVertexUvs[ 0 ], u1, v1, u2, v2, u3, v3 ); } }; function init_uvs4( nElements, offset ) { var i, uva, uvb, uvc, uvd, u1, u2, u3, u4, v1, v2, v3, v4; var uvIndexBuffer = new Uint32Array( data, offset, 4 * nElements ); for( i = 0; i < nElements; i ++ ) { uva = uvIndexBuffer[ i * 4 ]; uvb = uvIndexBuffer[ i * 4 + 1 ]; uvc = uvIndexBuffer[ i * 4 + 2 ]; uvd = uvIndexBuffer[ i * 4 + 3 ]; u1 = uvs[ uva*2 ]; v1 = uvs[ uva*2 + 1 ]; u2 = uvs[ uvb*2 ]; v2 = uvs[ uvb*2 + 1 ]; u3 = uvs[ uvc*2 ]; v3 = uvs[ uvc*2 + 1 ]; u4 = uvs[ uvd*2 ]; v4 = uvs[ uvd*2 + 1 ]; uv4( scope.faceVertexUvs[ 0 ], u1, v1, u2, v2, u3, v3, u4, v4 ); } }; function init_faces3_flat( nElements, offsetVertices, offsetMaterials ) { var i, a, b, c, m; var vertexIndexBuffer = new Uint32Array( data, offsetVertices, 3 * nElements ); var materialIndexBuffer = new Uint16Array( data, offsetMaterials, nElements ); for( i = 0; i < nElements; i ++ ) { a = vertexIndexBuffer[ i * 3 ]; b = vertexIndexBuffer[ i * 3 + 1 ]; c = vertexIndexBuffer[ i * 3 + 2 ]; m = materialIndexBuffer[ i ]; f3( scope, a, b, c, m ); } }; function init_faces4_flat( nElements, offsetVertices, offsetMaterials ) { var i, a, b, c, d, m; var vertexIndexBuffer = new Uint32Array( data, offsetVertices, 4 * nElements ); var materialIndexBuffer = new Uint16Array( data, offsetMaterials, nElements ); for( i = 0; i < nElements; i ++ ) { a = vertexIndexBuffer[ i * 4 ]; b = vertexIndexBuffer[ i * 4 + 1 ]; c = vertexIndexBuffer[ i * 4 + 2 ]; d = vertexIndexBuffer[ i * 4 + 3 ]; m = materialIndexBuffer[ i ]; f4( scope, a, b, c, d, m ); } }; function init_faces3_smooth( nElements, offsetVertices, offsetNormals, offsetMaterials ) { var i, a, b, c, m; var na, nb, nc; var vertexIndexBuffer = new Uint32Array( data, offsetVertices, 3 * nElements ); var normalIndexBuffer = new Uint32Array( data, offsetNormals, 3 * nElements ); var materialIndexBuffer = new Uint16Array( data, offsetMaterials, nElements ); for( i = 0; i < nElements; i ++ ) { a = vertexIndexBuffer[ i * 3 ]; b = vertexIndexBuffer[ i * 3 + 1 ]; c = vertexIndexBuffer[ i * 3 + 2 ]; na = normalIndexBuffer[ i * 3 ]; nb = normalIndexBuffer[ i * 3 + 1 ]; nc = normalIndexBuffer[ i * 3 + 2 ]; m = materialIndexBuffer[ i ]; f3n( scope, normals, a, b, c, m, na, nb, nc ); } }; function init_faces4_smooth( nElements, offsetVertices, offsetNormals, offsetMaterials ) { var i, a, b, c, d, m; var na, nb, nc, nd; var vertexIndexBuffer = new Uint32Array( data, offsetVertices, 4 * nElements ); var normalIndexBuffer = new Uint32Array( data, offsetNormals, 4 * nElements ); var materialIndexBuffer = new Uint16Array( data, offsetMaterials, nElements ); for( i = 0; i < nElements; i ++ ) { a = vertexIndexBuffer[ i * 4 ]; b = vertexIndexBuffer[ i * 4 + 1 ]; c = vertexIndexBuffer[ i * 4 + 2 ]; d = vertexIndexBuffer[ i * 4 + 3 ]; na = normalIndexBuffer[ i * 4 ]; nb = normalIndexBuffer[ i * 4 + 1 ]; nc = normalIndexBuffer[ i * 4 + 2 ]; nd = normalIndexBuffer[ i * 4 + 3 ]; m = materialIndexBuffer[ i ]; f4n( scope, normals, a, b, c, d, m, na, nb, nc, nd ); } }; function init_triangles_flat( start ) { var nElements = md.ntri_flat; if ( nElements ) { var offsetMaterials = start + nElements * Uint32Array.BYTES_PER_ELEMENT * 3; init_faces3_flat( nElements, start, offsetMaterials ); } }; function init_triangles_flat_uv( start ) { var nElements = md.ntri_flat_uv; if ( nElements ) { var offsetUvs = start + nElements * Uint32Array.BYTES_PER_ELEMENT * 3; var offsetMaterials = offsetUvs + nElements * Uint32Array.BYTES_PER_ELEMENT * 3; init_faces3_flat( nElements, start, offsetMaterials ); init_uvs3( nElements, offsetUvs ); } }; function init_triangles_smooth( start ) { var nElements = md.ntri_smooth; if ( nElements ) { var offsetNormals = start + nElements * Uint32Array.BYTES_PER_ELEMENT * 3; var offsetMaterials = offsetNormals + nElements * Uint32Array.BYTES_PER_ELEMENT * 3; init_faces3_smooth( nElements, start, offsetNormals, offsetMaterials ); } }; function init_triangles_smooth_uv( start ) { var nElements = md.ntri_smooth_uv; if ( nElements ) { var offsetNormals = start + nElements * Uint32Array.BYTES_PER_ELEMENT * 3; var offsetUvs = offsetNormals + nElements * Uint32Array.BYTES_PER_ELEMENT * 3; var offsetMaterials = offsetUvs + nElements * Uint32Array.BYTES_PER_ELEMENT * 3; init_faces3_smooth( nElements, start, offsetNormals, offsetMaterials ); init_uvs3( nElements, offsetUvs ); } }; function init_quads_flat( start ) { var nElements = md.nquad_flat; if ( nElements ) { var offsetMaterials = start + nElements * Uint32Array.BYTES_PER_ELEMENT * 4; init_faces4_flat( nElements, start, offsetMaterials ); } }; function init_quads_flat_uv( start ) { var nElements = md.nquad_flat_uv; if ( nElements ) { var offsetUvs = start + nElements * Uint32Array.BYTES_PER_ELEMENT * 4; var offsetMaterials = offsetUvs + nElements * Uint32Array.BYTES_PER_ELEMENT * 4; init_faces4_flat( nElements, start, offsetMaterials ); init_uvs4( nElements, offsetUvs ); } }; function init_quads_smooth( start ) { var nElements = md.nquad_smooth; if ( nElements ) { var offsetNormals = start + nElements * Uint32Array.BYTES_PER_ELEMENT * 4; var offsetMaterials = offsetNormals + nElements * Uint32Array.BYTES_PER_ELEMENT * 4; init_faces4_smooth( nElements, start, offsetNormals, offsetMaterials ); } }; function init_quads_smooth_uv( start ) { var nElements = md.nquad_smooth_uv; if ( nElements ) { var offsetNormals = start + nElements * Uint32Array.BYTES_PER_ELEMENT * 4; var offsetUvs = offsetNormals + nElements * Uint32Array.BYTES_PER_ELEMENT * 4; var offsetMaterials = offsetUvs + nElements * Uint32Array.BYTES_PER_ELEMENT * 4; init_faces4_smooth( nElements, start, offsetNormals, offsetMaterials ); init_uvs4( nElements, offsetUvs ); } }; }; function vertex ( scope, x, y, z ) { scope.vertices.push( new THREE.Vector3( x, y, z ) ); }; function f3 ( scope, a, b, c, mi ) { scope.faces.push( new THREE.Face3( a, b, c, null, null, mi ) ); }; function f4 ( scope, a, b, c, d, mi ) { scope.faces.push( new THREE.Face4( a, b, c, d, null, null, mi ) ); }; function f3n ( scope, normals, a, b, c, mi, na, nb, nc ) { var nax = normals[ na*3 ], nay = normals[ na*3 + 1 ], naz = normals[ na*3 + 2 ], nbx = normals[ nb*3 ], nby = normals[ nb*3 + 1 ], nbz = normals[ nb*3 + 2 ], ncx = normals[ nc*3 ], ncy = normals[ nc*3 + 1 ], ncz = normals[ nc*3 + 2 ]; scope.faces.push( new THREE.Face3( a, b, c, [new THREE.Vector3( nax, nay, naz ), new THREE.Vector3( nbx, nby, nbz ), new THREE.Vector3( ncx, ncy, ncz )], null, mi ) ); }; function f4n ( scope, normals, a, b, c, d, mi, na, nb, nc, nd ) { var nax = normals[ na*3 ], nay = normals[ na*3 + 1 ], naz = normals[ na*3 + 2 ], nbx = normals[ nb*3 ], nby = normals[ nb*3 + 1 ], nbz = normals[ nb*3 + 2 ], ncx = normals[ nc*3 ], ncy = normals[ nc*3 + 1 ], ncz = normals[ nc*3 + 2 ], ndx = normals[ nd*3 ], ndy = normals[ nd*3 + 1 ], ndz = normals[ nd*3 + 2 ]; scope.faces.push( new THREE.Face4( a, b, c, d, [new THREE.Vector3( nax, nay, naz ), new THREE.Vector3( nbx, nby, nbz ), new THREE.Vector3( ncx, ncy, ncz ), new THREE.Vector3( ndx, ndy, ndz )], null, mi ) ); }; function uv3 ( where, u1, v1, u2, v2, u3, v3 ) { var uv = []; uv.push( new THREE.UV( u1, v1 ) ); uv.push( new THREE.UV( u2, v2 ) ); uv.push( new THREE.UV( u3, v3 ) ); where.push( uv ); }; function uv4 ( where, u1, v1, u2, v2, u3, v3, u4, v4 ) { var uv = []; uv.push( new THREE.UV( u1, v1 ) ); uv.push( new THREE.UV( u2, v2 ) ); uv.push( new THREE.UV( u3, v3 ) ); uv.push( new THREE.UV( u4, v4 ) ); where.push( uv ); }; Model.prototype = Object.create( THREE.Geometry.prototype ); callback( new Model( texturePath ) ); };
// ========================================================================== // Project: SproutCore - JavaScript Application Framework // Copyright: ©2006-2010 Apple Inc. and contributors. // License: Licensed under MIT license (see license.js) // ========================================================================== /*global module test equals context ok same */ // .......................................................... // createChildViews() // module("SC.View#createChildViews"); test("calls createChildView() for each class or string in childViews array", function() { var called = []; var v = SC.View.create({ childViews: [ SC.View.extend({ key: 0 }), // class - should be called SC.View.create({ key: 1 }), // NOT class - should NOT be called 'customClassName' // string - should be called ], // this shuld be used for the 'customClassName' item above customClassName: SC.View.extend({ key: 2 }), // patch to record results... createChildView: function(childView) { called.push(childView.prototype.key); ok(childView.isClass, "childView: %@ isClass".fmt(childView)); return sc_super(); } }); // createChildViews() is called automatically during create. same(called, [0,2], 'called createChildView for correct children'); // make sure childViews array is correct now. var cv = v.childViews, len = cv.length, idx; for(idx=0;idx<len;idx++) { equals(cv[idx].key, idx, 'has correct index key'); ok(cv[idx].isObject, 'isObject - %@'.fmt(cv[idx])); } }); test("should not error when there is a dud view name in childViews list.", function() { var called = []; var v = SC.View.create({ childViews: [ "nonExistantClassNme", // string - should NOT be called 'customClassName' // string - should be called ], // this shuld be used for the 'customClassName' item above customClassName: SC.View.extend({ key: 2 }), // patch to record results... createChildView: function(childView) { called.push(childView.prototype.key); ok(childView.isClass, "childView: %@ isClass".fmt(childView)); return sc_super(); } }); // createChildViews() is called automatically during create. same(called, [2], 'called createChildView for correct children'); }); test("should not throw error when there is an extra space in the childViews list", function() { var called = []; var v = SC.View.create({ childViews: "customClassName customKlassName".w(), // this shuld be used for the 'customClassName' item above customClassName: SC.View.extend({ key: 2 }), customKlassName: SC.View.extend({ key: 3 }) }); ok(true, "called awake without issue."); }); test("should not create layer for created child views", function() { var v = SC.View.create({ childViews: [SC.View] }); ok(v.childViews[0].isObject, 'precondition - did create child view'); equals(v.childViews[0].get('layer'), null, 'childView does not have layer'); }); // .......................................................... // createChildView() // var view, myViewClass ; module("SC.View#createChildView", { setup: function() { view = SC.View.create({ page: SC.Object.create() }); myViewClass = SC.View.extend({ isMyView: YES, foo: 'bar' }); } }); test("should create view from class with any passed attributes", function() { var v = view.createChildView(myViewClass, { foo: "baz" }); ok(v.isMyView, 'v is instance of myView'); equals(v.foo, 'baz', 'view did get custom attributes'); }); test("should set newView.owner & parentView to receiver", function() { var v = view.createChildView(myViewClass) ; equals(v.get('owner'), view, 'v.owner == view'); equals(v.get('parentView'), view, 'v.parentView == view'); }); test("should set newView.page to receiver.page unless custom attr is passed", function() { var v = view.createChildView(myViewClass) ; equals(v.get('page'), view.get('page'), 'v.page == view.page'); var myPage = SC.Object.create(); v = view.createChildView(myViewClass, { page: myPage }) ; equals(v.get('page'), myPage, 'v.page == custom page'); });
"use strict"; angular.module('app.graphs').directive('morrisNoGridGraph', function(){ return { restrict: 'E', replace: true, template: '<div class="chart no-padding"></div>', link: function(scope, element){ var day_data = [{ "period" : "2012-10-01", "licensed" : 3407, "sorned" : 660 }, { "period" : "2012-09-30", "licensed" : 3351, "sorned" : 629 }, { "period" : "2012-09-29", "licensed" : 3269, "sorned" : 618 }, { "period" : "2012-09-20", "licensed" : 3246, "sorned" : 661 }, { "period" : "2012-09-19", "licensed" : 3257, "sorned" : 667 }, { "period" : "2012-09-18", "licensed" : 3248, "sorned" : 627 }, { "period" : "2012-09-17", "licensed" : 3171, "sorned" : 660 }, { "period" : "2012-09-16", "licensed" : 3171, "sorned" : 676 }, { "period" : "2012-09-15", "licensed" : 3201, "sorned" : 656 }, { "period" : "2012-09-10", "licensed" : 3215, "sorned" : 622 }]; Morris.Line({ element : element, grid : false, data : day_data, xkey : 'period', ykeys : ['licensed', 'sorned'], labels : ['Licensed', 'SORN'] }); } } });
'use strict'; var gulp = require('gulp'), eslint = require('gulp-eslint'), mocha = require('gulp-mocha'); // lint gulp.task('lint', function() { return gulp.src([ './src/**/*.js', './test/**/*.js', './gulpfile.js' ]) .pipe(eslint()) .on('error', function() {}) .pipe(eslint.format()) .pipe(eslint.failAfterError()); }); // travis gulp.task('test', ['lint'], function() { return gulp.src('./test/**/*.js') .pipe(mocha()) .on('error', function() {}); }); // default task gulp.task('default', ['lint'], function() {});
module.exports = function(config) { config.set({ basePath: '', frameworks: ['mocha', 'sinon'], files: [ 'test.js' ], exclude: [ ], preprocessors: { 'test.js': ['webpack', 'sourcemap'] }, reporters: ['progress'], port: 9876, colors: true, logLevel: config.LOG_INFO, autoWatch: true, browsers: ['Chrome'], singleRun: false, concurrency: Infinity, webpack: { cache: true, devtool: 'inline-source-map', module: { loaders: [ { test: /\.js$/, exclude: /node_modules/, loader: 'babel', query: { presets: ['es2015'] } } ] } } }) }
// Copyright (c) 2015 Uber Technologies, Inc. // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. 'use strict'; var allocCluster = require('./lib/alloc-cluster.js'); allocCluster.test('peer should use the identified connection', { numPeers: 2 }, function t(cluster, assert) { var server = cluster.channels[0]; var client = cluster.channels[1]; var serverHost = cluster.hosts[0]; server.makeSubChannel({ serviceName: 'server' }); var subClient = client.makeSubChannel({ serviceName: 'server', peers: [server.hostPort] }); client.waitForIdentified({ host: serverHost }, onIdentified); function onIdentified(err) { if (err) { return assert.end(err); } var peer = subClient.peers.get(serverHost); var socket = peer.makeOutSocket(); var conn = peer.makeOutConnection(socket); peer.addConnection(conn); assert.doesNotThrow( function noThrow() { subClient.request({ host: peer.hostPort, hasNoParent: true, headers: { as: 'wat', cn: 'hi' } }).send('', '', '', noop); function noop() {} }, 'should use the identified connection' ); assert.notEqual(conn, peer.getIdentifiedOutConnection(), 'should return the identified connection'); assert.equals(conn, peer.getOutConnection(), 'should return the latest connection'); client.close(); server.close(); assert.end(); } }); allocCluster.test('peer should return the latest connection when none is identified', { numPeers: 2 }, function t(cluster, assert) { var server = cluster.channels[0]; var client = cluster.channels[1]; var serverHost = cluster.hosts[0]; server.makeSubChannel({ serviceName: 'server' }); var subClient = client.makeSubChannel({ serviceName: 'server', peers: [server.hostPort] }); var peer = subClient.peers.get(serverHost); var socket = peer.makeOutSocket(); var conn = peer.makeOutConnection(socket); peer.addConnection(conn); assert.equals(conn, peer.getIdentifiedOutConnection(), 'should return the latest connection'); assert.equals(conn, peer.getOutConnection(), 'should return the latest connection'); client.close(); server.close(); assert.end(); }); allocCluster.test('peer close should not leak connections', { numPeers: 2 }, function t(cluster, assert) { var server = cluster.channels[0]; var client = cluster.channels[1]; var serverHost = cluster.hosts[0]; server.makeSubChannel({ serviceName: 'server' }); var subClient = client.makeSubChannel({ serviceName: 'server', peers: [server.hostPort] }); var peer = subClient.peers.get(serverHost); var connection = peer.connect(); connection.identifiedEvent.on(onIdentified); function onIdentified() { peer = server.peers.values()[0]; var socket = peer.makeOutSocket(); var conn = peer.makeOutConnection(socket); peer.addConnection(conn); var count = 2; peer.removeConnectionEvent.on(function onClose() { count--; }); peer.close(function onClose() { assert.equals(0, count, 'both connections should be closed'); client.close(); server.close(); assert.end(); }); } });
'use strict'; /** * Module dependencies. */ var mongoose = require('mongoose'), Schema = mongoose.Schema; /** * Contract Schema */ var ContractSchema = new Schema({ name: { type: String, default: '', required: 'Please fill Contract name', trim: true }, contract_number: { type: String, default: '', trim: true }, con_type: { type: String, default: '', trim: true }, transport_cost: { type: Number, default: '', trim: true }, days_effective: { type: Number, default: '', trim: true }, expected_profit: { type: Number, default: '', trim: true }, created: { type: Date, default: Date.now }, user: { type: Schema.ObjectId, ref: 'User' } }); mongoose.model('Contract', ContractSchema);
'use strict'; const _ = require('lodash'); const getSecureMiddleware = require('./get-secure-middleware'); const getHeader = require('./get-header'); const mergeOptions = require('./merge-options'); function statelessAuth(options) { const opts = mergeOptions(_.pick(options, ['jwt', 'jwtCookie', 'secure'])); const header = getHeader(opts); const secure = getSecureMiddleware(opts); return { options: opts, decodeAuthHeader: header.decode, jwt: header.jwt, secure, }; } module.exports = statelessAuth;
import React, {Component} from 'react' import {Link} from 'react-router-dom' import './../../css/test/A.css' class A1 extends Component { constructor(props) { super(props) } render() { return ( <div> <div className="demo-blog mdl-layout mdl-js-layout has-drawer is-upgraded"> <main className="mdl-layout__content"> <div className="demo-blog__posts mdl-grid"> <div className="mdl-card coffee-pic mdl-cell mdl-cell--8-col"> <div className="mdl-card__media mdl-color-text--grey-50"> <h3><Link to={"/A2"}>Coffee Pic</Link></h3> </div> <div className="mdl-card__supporting-text meta mdl-color-text--grey-600"> <div className="minilogo"></div> <div> <strong>The Newist</strong> <span>2 days ago</span> </div> </div> </div> <div className="mdl-card something-else mdl-cell mdl-cell--8-col mdl-cell--4-col-desktop"> <button className="mdl-button mdl-js-ripple-effect mdl-js-button mdl-button--fab mdl-color--accent"> <i className="material-icons mdl-color-text--white" role="presentation">add</i> <span className="visuallyhidden">add</span> </button> <div className="mdl-card__media mdl-color--white mdl-color-text--grey-600"> </div> <div className="mdl-card__supporting-text meta meta--fill mdl-color-text--grey-600"> <div> <strong>The Newist</strong> </div> <ul className="mdl-menu mdl-js-menu mdl-menu--bottom-right mdl-js-ripple-effect" htmlFor="menubtn"> <li className="mdl-menu__item">About</li> <li className="mdl-menu__item">Message</li> <li className="mdl-menu__item">Favorite</li> <li className="mdl-menu__item">Search</li> </ul> <button id="menubtn" className="mdl-button mdl-js-button mdl-js-ripple-effect mdl-button--icon"> <i className="material-icons" role="presentation">more_vert</i> <span className="visuallyhidden">show menu</span> </button> </div> </div> <div className="mdl-card on-the-road-again mdl-cell mdl-cell--12-col"> <div className="mdl-card__media mdl-color-text--grey-50"> <h3><Link to={"/A2"}>On the road again</Link></h3> </div> <div className="mdl-color-text--grey-600 mdl-card__supporting-text"> Enim labore aliqua consequat ut quis ad occaecat aliquip incididunt. Sunt nulla eu enim irure enim nostrud aliqua consectetur ad consectetur sunt ullamco officia. Ex officia laborum et consequat duis. </div> <div className="mdl-card__supporting-text meta mdl-color-text--grey-600"> <div className="minilogo"></div> <div> <strong>The Newist</strong> <span>2 days ago</span> </div> </div> </div> <div className="mdl-card amazing mdl-cell mdl-cell--12-col"> <div className="mdl-card__title mdl-color-text--grey-50"> <h3 className="quote"><Link to={"/A2"}>I couldn’t take any pictures but this was an amazing thing…</Link></h3> </div> <div className="mdl-card__supporting-text mdl-color-text--grey-600"> Enim labore aliqua consequat ut quis ad occaecat aliquip incididunt. Sunt nulla eu enim irure enim nostrud aliqua consectetur ad consectetur sunt ullamco officia. Ex officia laborum et consequat duis. </div> <div className="mdl-card__supporting-text meta mdl-color-text--grey-600"> <div className="minilogo"></div> <div> <strong>The Newist</strong> <span>2 days ago</span> </div> </div> </div> <div className="mdl-card shopping mdl-cell mdl-cell--12-col"> <div className="mdl-card__media mdl-color-text--grey-50"> <h3><Link to={"/A2"}>Shopping</Link></h3> </div> <div className="mdl-card__supporting-text mdl-color-text--grey-600"> Enim labore aliqua consequat ut quis ad occaecat aliquip incididunt. Sunt nulla eu enim irure enim nostrud aliqua consectetur ad consectetur sunt ullamco officia. Ex officia laborum et consequat duis. </div> <div className="mdl-card__supporting-text meta mdl-color-text--grey-600"> <div className="minilogo"></div> <div> <strong>The Newist</strong> <span>2 days ago</span> </div> </div> </div> <nav className="demo-nav mdl-cell mdl-cell--12-col"> <div className="section-spacer"></div> <Link to={"/A2"} className="demo-nav__button" title="show more"> More <button className="mdl-button mdl-js-button mdl-js-ripple-effect mdl-button--icon"> <i className="material-icons" role="presentation">arrow_forward</i> </button> </Link> </nav> </div> <footer className="mdl-mini-footer"> <div className="mdl-mini-footer--left-section"> <button className="mdl-mini-footer--social-btn social-btn social-btn__twitter"> <span className="visuallyhidden">Twitter</span> </button> <button className="mdl-mini-footer--social-btn social-btn social-btn__blogger"> <span className="visuallyhidden">Facebook</span> </button> <button className="mdl-mini-footer--social-btn social-btn social-btn__gplus"> <span className="visuallyhidden">Google Plus</span> </button> </div> <div className="mdl-mini-footer--right-section"> <button className="mdl-mini-footer--social-btn social-btn__share"> <i className="material-icons" role="presentation">share</i> <span className="visuallyhidden">share</span> </button> </div> </footer> </main> <div className="mdl-layout__obfuscator"></div> </div> </div> ) } } export default A1;
var MongoClient = require('mongodb').MongoClient; var mongourl = 'mongodb://192.168.17.52:27050/db_bot'; function play(content,userName,groupName,callback){ MongoClient.connect(mongourl, function(err, db) { var cl_user = db.collection('cl_user'); var query = {'_id':userName}; var now = new Date(); var dur = Math.floor(Math.random()*666666+123456); var endtime = new Date(now.getTime()+dur); cl_user.findOne(query, function(err, data) { if(data){ var end = data.end; if(now.getTime()>end.getTime()){ var sub = now.getTime()-end.getTime(); var add = Math.floor(sub/60000); var newhp = (data.hp+add)>(100*lv)?(100*lv):(data.hp+add); var newmp = (data.mp+add)>(100*lv)?(100*lv):(data.mp+add); var newtp = (data.tp+add)>(100*lv)?(100*lv):(data.tp+add); cl_user.updateOne(query,{'$set':{start:now,end:endtime,hp:newhp,mp:newmp,tp:newtp}}); playstart(); }else{ //nowplay(); } }else{ var init = {'_id':userName,hp:100,mp:100,tp:100,gold:100,lv:1,str:9,int:9,agi:9,love:0,start:now,end:endtime,item:[]}; cl_user.insertOne(init); data=init; playstart(); } }); }); } function playstart(data,userName,endtime){ var eventts=data.eventts; var now = new Date(); if(eventts){ var eventdur = now.getTime()-eventts.getTime(); if(eventdur>60000){ newevent(); }else{ nowevent(); } }else{ newevent(); } } function nowplay(){ } function newevent(){ var nextEvent = Math.floor(Math.random()*99999+12345); var nexttime = new Date(new Date().getTime()+nextEvent); setTimeout(function(){ }) }
var __context = this; var depth = 0; var LOCALE = 'en'; // TODO Add support for more locales later Array.prototype.insert = function(index) { this.splice.apply(this, [index, 0].concat( Array.prototype.slice.call(arguments, 1))); return this; }; var sprequirejs = function (exports) { var Spotify = function () { }; exports.Spotify = Spotify; exports.Spotify.prototype.bind = function (func, obj) { return function (args) { return func.apply(obj, [args]); }; }; exports.SP = new Spotify(); exports.LangModule = function (stringFile) { this.strings = {}; var xmlHttp = new XMLHttpRequest(); xmlHttp.open('GET', stringFile, false); xmlHttp.send(null); if (xmlHttp.readyState == 4 && xmlHttp.status == 200) { var data = JSON.parse(xmlHttp.responseText); this.strings = data; } }; exports.LangModule.prototype.get = function (key, var_args) { if (typeof(this.strings[key]) != 'undefined') { return this.strings[key]; } else { return typeof(var_args) !== 'undefined' ? var_args : key; } }; exports.require = function () { var modules = arguments[0]; var callback = arguments[1]; var items = []; for (var i = 0; i < modules.length; i++) { var xmlHttp = new XMLHttpRequest(); var module = modules[i]; console.log(module); var _class = module.indexOf('#') > 0 ? module.split('#')[1] : null; if (_class != null) { module = module.split('#')[0]; } if (module.indexOf('.lang') > 0) { // Emulate the lang module var parts = module.split('/'); parts.insert(parts.length - 2, LOCALE + '.loc'); parts.slice(1); var url = parts.join('/'); if (url.indexOf('/') == 0) { url = url.substr(1); } if (url.indexOf('$') != 0 && url.indexOf('sp') != 0 && url.indexOf('http') != 0) { // url = '$' + window.appName + '/' + url; } var code = eval('(function () { var exports = {}; exports = new LangModule("' + url + '"); console.log("exports", exports); return exports; })();'); console.log(code); var mod = eval(code); console.log("Mod", mod); if (_class != null) { console.log(mod); mod = mod[_class]; } items.push(mod); } else { module = module + '.js'; if (module.indexOf('$') == 0) { var parts = module.split('/'); // Append scripts like in the real spotify apps api parts.insert(parts.length - 1, 'scripts'); module = parts.join('/'); if (module.indexOf('/') == 0) module = module.substr(1); } xmlHttp.open('GET', module, false); xmlHttp.send(null); if (xmlHttp.readyState == 4 && xmlHttp.status == 200) { console.log(xmlHttp.responseText); var code = ("(function () { var exports = {}; " + xmlHttp.responseText + "; console.log('exports" + depth + "', exports); return exports; })();"); console.log(code); console.log(url); var mod = eval(code); console.log("Mod", mod); if (_class != null) { console.log(mod); mod = mod[_class]; } items.push(mod); } } } callback.apply(__context, items); }; var Promise = function () { var self = this; this._done = function () { return self; }; this._fail = function () { return self; }; this._always = function () { return self; }; }; Promise.prototype = { done: function (callback) { this._done = callback; return this; }, fail: function (callback) { this._fail = callback; return this; }, always: function (callback) { this._always = callback; return this; }, setDone: function (data) { this._done.call(this, data); this._always.call(this, data); }, setFail: function (data) { this._fail.call(this, data); this._always.call(this, data); }, }; exports.Promise = Promise; var Observable = function() { }; Observable.prototype = { addEventListener: function(type, method) { var listeners, handlers, scope; if (!(listeners = this.listeners)) { listeners = this.listeners = {}; } if (!(handlers = listeners[type])){ handlers = listeners[type] = []; } scope = (scope ? scope : window); handlers.push({ method: method, scope: scope, // context: (context ? context : scope) }); }, dispatchEvent: function(type, data) { var listeners, handlers, i, n, handler, scope; if (!(listeners = this.listeners)) { return; } if (!(handlers = listeners[type])){ return; } for (i = 0, n = handlers.length; i < n; i++){ handler = handlers[i]; //if (typeof(context)!=="undefined" && context !== handler.context) continue; if (handler.method.call( handler.scope, /*this, type,*/ { data: data, type: type } )===false) { return false; } } return true; } }; exports.Observable = Observable; exports.Observer = Observable; exports.Promise = Promise; }; sprequirejs(window);
$(function(){ $('.del').click(function(e){ var target = $(e.target); var id = target.data('id'); var tr = $('.item-id-'+id); $.ajax({ type:'DELETE', url:'/movie/del?id='+id }) .done(function(results){ if(results.success === 1){ if (tr.length > 0) { tr.remove(); } } }) }) $('#douban').blur(function(){ var douban = $(this); var id = douban.val(); if(id){ $.ajax({ url:'https://api.douban.com/v2/movie/subject/' + id, cache:true, type:'get', dataType:'jsonp', crossDomain:true, jsonp:'callback', success:function(data){ $('#inputTitle').val(data.title) $('#inputDirector').val(data.directors[0].name) $('#inputCountry').val(data.countries[0]) $('#inputPoster').val(data.images.large) $('#inputYear').val(data.year) $('#inputSummary').val(data.summary) } }) } }) })
module.exports = "0.4.0";
"use strict"; var __extends = (this && this.__extends) || (function () { var 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 function (d, b) { extendStatics(d, b); function __() { this.constructor = d; } d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); }; })(); Object.defineProperty(exports, "__esModule", { value: true }); var Action_1 = require("../Action"); var ShiftAction = (function (_super) { __extends(ShiftAction, _super); function ShiftAction(_a) { var time = _a.time, container = _a.container, _b = _a.n, n = _b === void 0 ? 1 : _b; var _this = _super.call(this, { time: time }) || this; _this.container = container; _this.n = n; return _this; } ShiftAction.prototype.reduce = function (state) { var fn = this.fn(state).bind(state); return fn({ n: this.n, time: this.time, container: this.container }); }; return ShiftAction; }(Action_1.default)); exports.default = ShiftAction; //# sourceMappingURL=ShiftAction.js.map
#!/usr/bin/env node 'use strict'; var app = require('../server/app'); // start sockets for this instance and start server app.startServer().listen(app.get('port'), app.get('ip'), function serverStarted() { console.log('vendorApp started server on ip %s on port %d, in %s mode', app.get('ip'), app.get('port'), app.get('env')); }); // expose app exports = module.exports = app;
describe('projectFeatured', function() { // Load the module that contains the `projectDetail` component before each test beforeEach(module('projectFeatured')); // Test the controller describe('ProjectFeaturedController', function() { var $httpBackend, ctrl; beforeEach(inject(function($componentController, _$httpBackend_, $routeParams) { $httpBackend = _$httpBackend_; $httpBackend.expectGET('projects/xyz.json').respond({name: 'project xyz'}); $routeParams.projectId = 'xyz'; ctrl = $componentController('projectFeatured'); })); it('should fetch the project details', function() { expect(ctrl.project).toBeUndefined(); $httpBackend.flush(); expect(ctrl.project).toEqual({name: 'project xyz'}); }); }); });
// Copyright (c) 2012 Ecma International. All rights reserved. // Ecma International makes this code available under the terms and conditions set // forth on http://hg.ecmascript.org/tests/test262/raw-file/tip/LICENSE (the // "Use Terms"). Any redistribution of this code must retain the above // copyright and this notice and otherwise comply with the Use Terms. /*--- es5id: 15.2.3.14-5-7 description: > Object.keys - inherted enumerable data property that is over-ridden by non-enumerable own data property is not defined in returned array includes: [runTestCase.js] ---*/ function testcase() { var proto = {}; Object.defineProperty(proto, "prop", { value: 1003, enumerable: true, configurable: true }); var Con = function () { }; Con.prototype = proto; var obj = new Con(); Object.defineProperty(obj, "prop", { value: 1004, enumerable: false, configurable: true }); var arr = Object.keys(obj); for (var p in arr) { if (arr[p] === "prop") { return false; } } return true; } runTestCase(testcase);
App = angular.module('App', ['ngRoute', 'ngMessages', 'ngCookies']); /* App configuration */ App.config(function($routeProvider, $locationProvider) { /* remove any hash prefixes in the URL */ $locationProvider.hashPrefix(''); $routeProvider .when('/', { templateUrl: 'partials/main.html', controller: 'MainCtrl', controllerAs: 'c', resolve: { load: function($q, UserSrv, $cookies){ var defer = $q.defer(); var auth = $cookies.get('auth'); if (auth) { auth = JSON.parse(auth); UserSrv.setUser(auth); } if(UserSrv.getUser()){ defer.resolve(); } else { defer.reject("not_logged_in"); } return defer.promise; } } }) .when('/login', { templateUrl: 'partials/login.html', controller: 'LoginCtrl', controllerAs: 'c' }) .otherwise({ redirectTo: '/' }); /* remove the '#' from the URL */ $locationProvider.html5Mode(true); });
/*! * devextreme-angular * Version: 16.2.5 * Build date: Tue Feb 28 2017 * * Copyright (c) 2012 - 2017 Developer Express Inc. ALL RIGHTS RESERVED * * This software may be modified and distributed under the terms * of the MIT license. See the LICENSE file in the root of the project for details. * * https://github.com/DevExpress/devextreme-angular */ "use strict"; var __extends = (this && this.__extends) || function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; function __() { this.constructor = d; } d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); }; var nested_option_1 = require('../../../core/nested-option'); var DxoGaugeIndicator = (function (_super) { __extends(DxoGaugeIndicator, _super); function DxoGaugeIndicator() { _super.apply(this, arguments); } Object.defineProperty(DxoGaugeIndicator.prototype, "arrowLength", { get: function () { return this._getOption('arrowLength'); }, set: function (value) { this._setOption('arrowLength', value); }, enumerable: true, configurable: true }); Object.defineProperty(DxoGaugeIndicator.prototype, "backgroundColor", { get: function () { return this._getOption('backgroundColor'); }, set: function (value) { this._setOption('backgroundColor', value); }, enumerable: true, configurable: true }); Object.defineProperty(DxoGaugeIndicator.prototype, "baseValue", { get: function () { return this._getOption('baseValue'); }, set: function (value) { this._setOption('baseValue', value); }, enumerable: true, configurable: true }); Object.defineProperty(DxoGaugeIndicator.prototype, "color", { get: function () { return this._getOption('color'); }, set: function (value) { this._setOption('color', value); }, enumerable: true, configurable: true }); Object.defineProperty(DxoGaugeIndicator.prototype, "horizontalOrientation", { get: function () { return this._getOption('horizontalOrientation'); }, set: function (value) { this._setOption('horizontalOrientation', value); }, enumerable: true, configurable: true }); Object.defineProperty(DxoGaugeIndicator.prototype, "indentFromCenter", { get: function () { return this._getOption('indentFromCenter'); }, set: function (value) { this._setOption('indentFromCenter', value); }, enumerable: true, configurable: true }); Object.defineProperty(DxoGaugeIndicator.prototype, "length", { get: function () { return this._getOption('length'); }, set: function (value) { this._setOption('length', value); }, enumerable: true, configurable: true }); Object.defineProperty(DxoGaugeIndicator.prototype, "offset", { get: function () { return this._getOption('offset'); }, set: function (value) { this._setOption('offset', value); }, enumerable: true, configurable: true }); Object.defineProperty(DxoGaugeIndicator.prototype, "palette", { get: function () { return this._getOption('palette'); }, set: function (value) { this._setOption('palette', value); }, enumerable: true, configurable: true }); Object.defineProperty(DxoGaugeIndicator.prototype, "secondColor", { get: function () { return this._getOption('secondColor'); }, set: function (value) { this._setOption('secondColor', value); }, enumerable: true, configurable: true }); Object.defineProperty(DxoGaugeIndicator.prototype, "secondFraction", { get: function () { return this._getOption('secondFraction'); }, set: function (value) { this._setOption('secondFraction', value); }, enumerable: true, configurable: true }); Object.defineProperty(DxoGaugeIndicator.prototype, "size", { get: function () { return this._getOption('size'); }, set: function (value) { this._setOption('size', value); }, enumerable: true, configurable: true }); Object.defineProperty(DxoGaugeIndicator.prototype, "spindleGapSize", { get: function () { return this._getOption('spindleGapSize'); }, set: function (value) { this._setOption('spindleGapSize', value); }, enumerable: true, configurable: true }); Object.defineProperty(DxoGaugeIndicator.prototype, "spindleSize", { get: function () { return this._getOption('spindleSize'); }, set: function (value) { this._setOption('spindleSize', value); }, enumerable: true, configurable: true }); Object.defineProperty(DxoGaugeIndicator.prototype, "text", { get: function () { return this._getOption('text'); }, set: function (value) { this._setOption('text', value); }, enumerable: true, configurable: true }); Object.defineProperty(DxoGaugeIndicator.prototype, "verticalOrientation", { get: function () { return this._getOption('verticalOrientation'); }, set: function (value) { this._setOption('verticalOrientation', value); }, enumerable: true, configurable: true }); Object.defineProperty(DxoGaugeIndicator.prototype, "width", { get: function () { return this._getOption('width'); }, set: function (value) { this._setOption('width', value); }, enumerable: true, configurable: true }); Object.defineProperty(DxoGaugeIndicator.prototype, "type", { get: function () { return this._getOption('type'); }, set: function (value) { this._setOption('type', value); }, enumerable: true, configurable: true }); return DxoGaugeIndicator; }(nested_option_1.NestedOption)); exports.DxoGaugeIndicator = DxoGaugeIndicator; //# sourceMappingURL=gauge-indicator.js.map
;(function() { "use strict"; var app = angular.module("AddressApp",[]); app.controller("AddressBookController", function() { var vm = this; vm.contacts = [ { name: "Hank", email: "blahblah@ymail.com", phone: 9876543210, address: "Know Your Role Blvd " }, { name: "Cookie Monster", email: "lovecookies@gmail.com", phone: 1234567890, address: "Sesame Street" }, { name: "Clifford", email: "bigreddog@aol.com", phone: 127361239, address: "Too big for an address" }, { name: "Hank", email: "blahblah@ymail.com", phone: 9876543210, address: "Know Your Role Blvd " }, { name: "Cookie Monster", email: "lovecookies@gmail.com", phone: 1234567890, address: "Sesame Street" }, { name: "Clifford", email: "bigreddog@aol.com", phone: 127361239, address: "Too big for an address" } ]; vm.addContact = function() { vm.contacts.push(vm.newContact); vm.newContact = null; }; vm.removeContact = function(contact) { var index = vm.contacts.indexOf(contact); vm.contacts.splice(index,1); }; }); })();
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var react_component_1 = require("./react.component"); exports.NguiReactComponent = react_component_1.NguiReactComponent; var react_module_1 = require("./react.module"); exports.NguiReactModule = react_module_1.NguiReactModule; //# sourceMappingURL=index.js.map
/** * Created by yuwh on 2017/4/30. */ const core=require('./core') const dom=require('./dom') const fp=require('./fp') const type=require('./type') const array=require('./array') const convert=require('./convert') const string=require('./string') const ajax=require('./ajax') module.exports={ core:core, dom:dom, fp:fp, type:type, array:array, convert:convert, string:string, ajax:ajax };
module.exports = { ADD_SERVERS: 'add_servers', REMOVE_SERVERS: 'remove_servers', REPLACE_SERVERS: 'replace_servers', BIND_SESSION: 'bind_session', UNBIND_SESSION: 'unbind_session', CLOSE_SESSION: 'close_session', ADD_CRONS: 'add_crons', REMOVE_CRONS: 'remove_crons', START_SERVER: 'start_server', START_ALL: 'start_all' };
'use strict'; var _ = require('lodash'); var $ = require('preconditions').singleton(); var async = require('async'); var log = require('npmlog'); log.debug = log.verbose; log.disableColor(); var EmailValidator = require('email-validator'); var WalletUtils = require('bitcore-wallet-utils'); var Bitcore = WalletUtils.Bitcore; var PublicKey = Bitcore.PublicKey; var HDPublicKey = Bitcore.HDPublicKey; var Address = Bitcore.Address; var ClientError = require('./errors/clienterror'); var Errors = require('./errors/errordefinitions'); var Package = require('../package'); var Utils = require('./utils'); var Lock = require('./lock'); var Storage = require('./storage'); var MessageBroker = require('./messagebroker'); var BlockchainExplorer = require('./blockchainexplorer'); var Model = require('./model'); var Wallet = Model.Wallet; var initialized = false; var lock; var storage; var blockchainExplorer; var blockchainExplorerOpts; var messageBroker; var MAX_KEYS = 100; /** * Creates an instance of the Bitcore Wallet Service. * @constructor */ function WalletService() { if (!initialized) throw new Error('Server not initialized'); this.lock = lock; this.storage = storage; this.blockchainExplorer = blockchainExplorer; this.blockchainExplorerOpts = blockchainExplorerOpts; this.messageBroker = messageBroker; this.notifyTicker = 0; this.serviceVersion = 'bws-' + Package.version; }; // Time after which a Tx proposal can be erased by any copayer. in seconds WalletService.DELETE_LOCKTIME = 24 * 3600; // Allowed consecutive txp rejections before backoff is applied. WalletService.BACKOFF_OFFSET = 3; // Time a copayer need to wait to create a new TX after her tx previous proposal we rejected. (incremental). in Minutes. WalletService.BACKOFF_TIME = 2; // Fund scanning parameters WalletService.SCAN_CONFIG = { scanWindow: 20, derivationDelay: 10, // in milliseconds }; WalletService.FEE_LEVELS = [{ name: 'priority', nbBlocks: 1, defaultValue: 50000 }, { name: 'normal', nbBlocks: 2, defaultValue: 20000 }, { name: 'economy', nbBlocks: 6, defaultValue: 10000 }]; /** * Initializes global settings for all instances. * @param {Object} opts * @param {Storage} [opts.storage] - The storage provider. * @param {Storage} [opts.blockchainExplorer] - The blockchainExporer provider. * @param {Callback} cb */ WalletService.initialize = function(opts, cb) { $.shouldBeFunction(cb); opts = opts || {}; lock = opts.lock || new Lock(opts.lockOpts); blockchainExplorer = opts.blockchainExplorer; blockchainExplorerOpts = opts.blockchainExplorerOpts; function initStorage(cb) { if (opts.storage) { storage = opts.storage; return cb(); } else { var newStorage = new Storage(); newStorage.connect(opts.storageOpts, function(err) { if (err) return cb(err); storage = newStorage; return cb(); }); } }; function initMessageBroker(cb) { if (opts.messageBroker) { messageBroker = opts.messageBroker; } else { messageBroker = new MessageBroker(opts.messageBrokerOpts); } return cb(); }; async.series([ function(next) { initStorage(next); }, function(next) { initMessageBroker(next); }, ], function(err) { if (err) { log.error('Could not initialize', err); throw err; } initialized = true; return cb(); }); }; WalletService.shutDown = function(cb) { if (!initialized) return cb(); storage.disconnect(function(err) { if (err) return cb(err); initialized = false; return cb(); }); }; /** * Gets an instance of the server without authentication. * @param {Object} opts * @param {string} opts.clientVersion - A string that identifies the client issuing the request */ WalletService.getInstance = function(opts) { opts = opts || {}; var server = new WalletService(); server.clientVersion = opts.clientVersion; return server; }; /** * Gets an instance of the server after authenticating the copayer. * @param {Object} opts * @param {string} opts.copayerId - The copayer id making the request. * @param {string} opts.message - The contents of the request to be signed. * @param {string} opts.signature - Signature of message to be verified using one of the copayer's requestPubKeys * @param {string} opts.clientVersion - A string that identifies the client issuing the request */ WalletService.getInstanceWithAuth = function(opts, cb) { if (!Utils.checkRequired(opts, ['copayerId', 'message', 'signature'])) return cb(new ClientError('Required argument missing')); var server = new WalletService(); server.storage.fetchCopayerLookup(opts.copayerId, function(err, copayer) { if (err) return cb(err); if (!copayer) return cb(new ClientError(Errors.codes.NOT_AUTHORIZED, 'Copayer not found')); var isValid = !!server._getSigningKey(opts.message, opts.signature, copayer.requestPubKeys); if (!isValid) return cb(new ClientError(Errors.codes.NOT_AUTHORIZED, 'Invalid signature')); server.copayerId = opts.copayerId; server.walletId = copayer.walletId; server.clientVersion = opts.clientVersion; return cb(null, server); }); }; WalletService.prototype._runLocked = function(cb, task) { $.checkState(this.walletId); this.lock.runLocked(this.walletId, cb, task); }; /** * Creates a new wallet. * @param {Object} opts * @param {string} opts.id - The wallet id. * @param {string} opts.name - The wallet name. * @param {number} opts.m - Required copayers. * @param {number} opts.n - Total copayers. * @param {string} opts.pubKey - Public key to verify copayers joining have access to the wallet secret. * @param {string} [opts.network = 'livenet'] - The Bitcoin network for this wallet. * @param {string} [opts.supportBIP44AndP2PKH = true] - Client supports BIP44 & P2PKH for new wallets. */ WalletService.prototype.createWallet = function(opts, cb) { var self = this, pubKey; if (!Utils.checkRequired(opts, ['name', 'm', 'n', 'pubKey'])) return cb(new ClientError('Required argument missing')); if (_.isEmpty(opts.name)) return cb(new ClientError('Invalid wallet name')); if (!Wallet.verifyCopayerLimits(opts.m, opts.n)) return cb(new ClientError('Invalid combination of required copayers / total copayers')); opts.network = opts.network || 'livenet'; if (!_.contains(['livenet', 'testnet'], opts.network)) return cb(new ClientError('Invalid network')); opts.supportBIP44AndP2PKH = _.isBoolean(opts.supportBIP44AndP2PKH) ? opts.supportBIP44AndP2PKH : true; var derivationStrategy = opts.supportBIP44AndP2PKH ? WalletUtils.DERIVATION_STRATEGIES.BIP44 : WalletUtils.DERIVATION_STRATEGIES.BIP45; var addressType = (opts.n == 1 && opts.supportBIP44AndP2PKH) ? WalletUtils.SCRIPT_TYPES.P2PKH : WalletUtils.SCRIPT_TYPES.P2SH; try { pubKey = new PublicKey.fromString(opts.pubKey); } catch (ex) { return cb(new ClientError('Invalid public key')); }; var newWallet; async.series([ function(acb) { if (!opts.id) return acb(); self.storage.fetchWallet(opts.id, function(err, wallet) { if (wallet) return acb(Errors.WALLET_ALREADY_EXISTS); return acb(err); }); }, function(acb) { var wallet = Wallet.create({ id: opts.id, name: opts.name, m: opts.m, n: opts.n, network: opts.network, pubKey: pubKey.toString(), derivationStrategy: derivationStrategy, addressType: addressType, }); self.storage.storeWallet(wallet, function(err) { log.debug('Wallet created', wallet.id, opts.network); newWallet = wallet; return acb(err); }); } ], function(err) { return cb(err, newWallet ? newWallet.id : null); }); }; /** * Retrieves a wallet from storage. * @param {Object} opts * @returns {Object} wallet */ WalletService.prototype.getWallet = function(opts, cb) { var self = this; self.storage.fetchWallet(self.walletId, function(err, wallet) { if (err) return cb(err); if (!wallet) return cb(Errors.WALLET_NOT_FOUND); return cb(null, wallet); }); }; /** * Retrieves wallet status. * @param {Object} opts * @param {Object} opts.includeExtendedInfo - Include PKR info & address managers for wallet & copayers * @returns {Object} status */ WalletService.prototype.getStatus = function(opts, cb) { var self = this; opts = opts || {}; var status = {}; async.parallel([ function(next) { self.getWallet({}, function(err, wallet) { if (err) return next(err); var walletExtendedKeys = ['publicKeyRing', 'pubKey', 'addressManager']; var copayerExtendedKeys = ['xPubKey', 'requestPubKey', 'signature', 'addressManager', 'customData']; wallet.copayers = _.map(wallet.copayers, function(copayer) { if (copayer.id == self.copayerId) return copayer; return _.omit(copayer, 'customData'); }); if (!opts.includeExtendedInfo) { wallet = _.omit(wallet, walletExtendedKeys); wallet.copayers = _.map(wallet.copayers, function(copayer) { return _.omit(copayer, copayerExtendedKeys); }); } status.wallet = wallet; next(); }); }, function(next) { self.getBalance({}, function(err, balance) { if (err) return next(err); status.balance = balance; next(); }); }, function(next) { self.getPendingTxs({}, function(err, pendingTxps) { if (err) return next(err); status.pendingTxps = pendingTxps; next(); }); }, function(next) { self.getPreferences({}, function(err, preferences) { if (err) return next(err); status.preferences = preferences; next(); }); }, ], function(err) { if (err) return cb(err); return cb(null, status); }); }; /* * Verifies a signature * @param text * @param signature * @param pubKeys */ WalletService.prototype._verifySignature = function(text, signature, pubkey) { return WalletUtils.verifyMessage(text, signature, pubkey); }; /* * Verifies signature againt a collection of pubkeys * @param text * @param signature * @param pubKeys */ WalletService.prototype._getSigningKey = function(text, signature, pubKeys) { var self = this; return _.find(pubKeys, function(item) { return self._verifySignature(text, signature, item.key); }); }; /** * _notify * * @param {String} type * @param {Object} data * @param {Object} opts * @param {Boolean} opts.isGlobal - If true, the notification is not issued on behalf of any particular copayer (defaults to false) */ WalletService.prototype._notify = function(type, data, opts, cb) { var self = this; if (_.isFunction(opts)) { cb = opts; opts = {}; } opts = opts || {}; log.debug('Notification', type, data); cb = cb || function() {}; var walletId = self.walletId || data.walletId; var copayerId = self.copayerId || data.copayerId; $.checkState(walletId); var notification = Model.Notification.create({ type: type, data: data, ticker: this.notifyTicker++, creatorId: opts.isGlobal ? null : copayerId, walletId: walletId, }); this.storage.storeNotification(walletId, notification, function() { self.messageBroker.send(notification); return cb(); }); }; WalletService.prototype._addCopayerToWallet = function(wallet, opts, cb) { var self = this; var copayer = Model.Copayer.create({ name: opts.name, copayerIndex: wallet.copayers.length, xPubKey: opts.xPubKey, requestPubKey: opts.requestPubKey, signature: opts.copayerSignature, customData: opts.customData, derivationStrategy: wallet.derivationStrategy, }); self.storage.fetchCopayerLookup(copayer.id, function(err, res) { if (err) return cb(err); if (res) return cb(Errors.COPAYER_REGISTERED); if (opts.dryRun) return cb(null, { copayerId: null, wallet: wallet }); wallet.addCopayer(copayer); self.storage.storeWalletAndUpdateCopayersLookup(wallet, function(err) { if (err) return cb(err); async.series([ function(next) { self._notify('NewCopayer', { walletId: opts.walletId, copayerId: copayer.id, copayerName: copayer.name, }, next); }, function(next) { if (wallet.isComplete() && wallet.isShared()) { self._notify('WalletComplete', { walletId: opts.walletId, }, { isGlobal: true }, next); } else { next(); } }, ], function() { return cb(null, { copayerId: copayer.id, wallet: wallet }); }); }); }); }; WalletService.prototype._addKeyToCopayer = function(wallet, copayer, opts, cb) { var self = this; wallet.addCopayerRequestKey(copayer.copayerId, opts.requestPubKey, opts.signature, opts.restrictions, opts.name); self.storage.storeWalletAndUpdateCopayersLookup(wallet, function(err) { if (err) return cb(err); return cb(null, { copayerId: copayer.id, wallet: wallet }); }); }; /** * Adds access to a given copayer * * @param {Object} opts * @param {string} opts.copayerId - The copayer id * @param {string} opts.requestPubKey - Public Key used to check requests from this copayer. * @param {string} opts.copayerSignature - S(requestPubKey). Used by other copayers to verify the that the copayer is himself (signed with REQUEST_KEY_AUTH) * @param {string} opts.restrictions * - cannotProposeTXs * - cannotXXX TODO * @param {string} opts.name (name for the new access) */ WalletService.prototype.addAccess = function(opts, cb) { var self = this; if (!Utils.checkRequired(opts, ['copayerId', 'requestPubKey', 'signature'])) return cb(new ClientError('Required argument missing')); self.storage.fetchCopayerLookup(opts.copayerId, function(err, copayer) { if (err) return cb(err); if (!copayer) return cb(Errors.NOT_AUTHORIZED); self.storage.fetchWallet(copayer.walletId, function(err, wallet) { if (err) return cb(err); if (!wallet) return cb(Errors.NOT_AUTHORIZED); var xPubKey = _.find(wallet.copayers, { id: opts.copayerId }).xPubKey; if (!WalletUtils.verifyRequestPubKey(opts.requestPubKey, opts.signature, xPubKey)) { return cb(Errors.NOT_AUTHORIZED); } if (copayer.requestPubKeys.length > MAX_KEYS) return cb(Errors.TOO_MANY_KEYS); self._addKeyToCopayer(wallet, copayer, opts, cb); }); }); }; WalletService.prototype._parseClientVersion = function() { function parse(version) { var v = {}; if (!version) return null; var x = version.split('-'); if (x.length != 2) { v.agent = version; return v; } v.agent = _.contains(['bwc', 'bws'], x[0]) ? 'bwc' : x[0]; x = x[1].split('.'); v.major = parseInt(x[0]); v.minor = parseInt(x[1]); v.patch = parseInt(x[2]); return v; }; if (_.isUndefined(this.parsedClientVersion)) { this.parsedClientVersion = parse(this.clientVersion); } return this.parsedClientVersion; }; WalletService.prototype._clientSupportsTXPv2 = function() { var version = this._parseClientVersion(); if (!version) return false; if (version.agent != 'bwc') return true; // Asume 3rd party clients are up-to-date if (version.major == 0 && version.minor == 0) return false; return true; }; /** * Joins a wallet in creation. * @param {Object} opts * @param {string} opts.walletId - The wallet id. * @param {string} opts.name - The copayer name. * @param {string} opts.xPubKey - Extended Public Key for this copayer. * @param {string} opts.requestPubKey - Public Key used to check requests from this copayer. * @param {string} opts.copayerSignature - S(name|xPubKey|requestPubKey). Used by other copayers to verify that the copayer joining knows the wallet secret. * @param {string} opts.customData - (optional) Custom data for this copayer. * @param {string} [opts.supportBIP44AndP2PKH = true] - Client supports BIP44 & P2PKH for joining wallets. */ WalletService.prototype.joinWallet = function(opts, cb) { var self = this; if (!Utils.checkRequired(opts, ['walletId', 'name', 'xPubKey', 'requestPubKey', 'copayerSignature'])) return cb(new ClientError('Required argument missing')); if (_.isEmpty(opts.name)) return cb(new ClientError('Invalid copayer name')); opts.supportBIP44AndP2PKH = _.isBoolean(opts.supportBIP44AndP2PKH) ? opts.supportBIP44AndP2PKH : true; self.walletId = opts.walletId; self._runLocked(cb, function(cb) { self.storage.fetchWallet(opts.walletId, function(err, wallet) { if (err) return cb(err); if (!wallet) return cb(Errors.WALLET_NOT_FOUND); if (opts.supportBIP44AndP2PKH) { // New client trying to join legacy wallet if (wallet.derivationStrategy == WalletUtils.DERIVATION_STRATEGIES.BIP45) { return cb(new ClientError('The wallet you are trying to join was created with an older version of the client app.')); } } else { // Legacy client trying to join new wallet if (wallet.derivationStrategy == WalletUtils.DERIVATION_STRATEGIES.BIP44) { return cb(new ClientError(Errors.codes.UPGRADE_NEEDED, 'To join this wallet you need to upgrade your client app.')); } } var hash = WalletUtils.getCopayerHash(opts.name, opts.xPubKey, opts.requestPubKey); if (!self._verifySignature(hash, opts.copayerSignature, wallet.pubKey)) { return cb(new ClientError()); } if (_.find(wallet.copayers, { xPubKey: opts.xPubKey })) return cb(Errors.COPAYER_IN_WALLET); if (wallet.copayers.length == wallet.n) return cb(Errors.WALLET_FULL); self._addCopayerToWallet(wallet, opts, cb); }); }); }; /** * Save copayer preferences for the current wallet/copayer pair. * @param {Object} opts * @param {string} opts.email - Email address for notifications. * @param {string} opts.language - Language used for notifications. * @param {string} opts.unit - Bitcoin unit used to format amounts in notifications. */ WalletService.prototype.savePreferences = function(opts, cb) { var self = this; opts = opts || {}; var preferences = [{ name: 'email', isValid: function(value) { return EmailValidator.validate(value); }, }, { name: 'language', isValid: function(value) { return _.isString(value) && value.length == 2; }, }, { name: 'unit', isValid: function(value) { return _.isString(value) && _.contains(['btc', 'bit'], value.toLowerCase()); }, }]; opts = _.pick(opts, _.pluck(preferences, 'name')); try { _.each(preferences, function(preference) { var value = opts[preference.name]; if (!value) return; if (!preference.isValid(value)) { throw 'Invalid ' + preference.name; return false; } }); } catch (ex) { return cb(new ClientError(ex)); } self._runLocked(cb, function(cb) { self.storage.fetchPreferences(self.walletId, self.copayerId, function(err, oldPref) { if (err) return cb(err); var newPref = Model.Preferences.create({ walletId: self.walletId, copayerId: self.copayerId, }); var preferences = Model.Preferences.fromObj(_.defaults(newPref, opts, oldPref)); self.storage.storePreferences(preferences, function(err) { return cb(err); }); }); }); }; /** * Retrieves a preferences for the current wallet/copayer pair. * @param {Object} opts * @returns {Object} preferences */ WalletService.prototype.getPreferences = function(opts, cb) { var self = this; self.storage.fetchPreferences(self.walletId, self.copayerId, function(err, preferences) { if (err) return cb(err); return cb(null, preferences || {}); }); }; /** * Creates a new address. * @param {Object} opts * @returns {Address} address */ WalletService.prototype.createAddress = function(opts, cb) { var self = this; self._runLocked(cb, function(cb) { self.getWallet({}, function(err, wallet) { if (err) return cb(err); if (!wallet.isComplete()) return cb(Errors.WALLET_NOT_COMPLETE); var address = wallet.createAddress(false); self.storage.storeAddressAndWallet(wallet, address, function(err) { if (err) return cb(err); self._notify('NewAddress', { address: address.address, }, function() { return cb(null, address); }); }); }); }); }; /** * Get all addresses. * @param {Object} opts * @returns {Address[]} */ WalletService.prototype.getMainAddresses = function(opts, cb) { var self = this; self.storage.fetchAddresses(self.walletId, function(err, addresses) { if (err) return cb(err); var onlyMain = _.reject(addresses, { isChange: true }); return cb(null, onlyMain); }); }; /** * Verifies that a given message was actually sent by an authorized copayer. * @param {Object} opts * @param {string} opts.message - The message to verify. * @param {string} opts.signature - The signature of message to verify. * @returns {truthy} The result of the verification. */ WalletService.prototype.verifyMessageSignature = function(opts, cb) { var self = this; if (!Utils.checkRequired(opts, ['message', 'signature'])) return cb(new ClientError('Required argument missing')); self.getWallet({}, function(err, wallet) { if (err) return cb(err); var copayer = wallet.getCopayer(self.copayerId); var isValid = !!self._getSigningKey(opts.message, opts.signature, copayer.requestPubKeys); return cb(null, isValid); }); }; WalletService.prototype._getBlockchainExplorer = function(network) { if (!this.blockchainExplorer) { var opts = {}; if (this.blockchainExplorerOpts && this.blockchainExplorerOpts[network]) { opts = this.blockchainExplorerOpts[network]; } // TODO: provider should be configurable opts.provider = 'insight'; opts.network = network; this.blockchainExplorer = new BlockchainExplorer(opts); } return this.blockchainExplorer; }; WalletService.prototype._getUtxosForAddresses = function(addresses, cb) { var self = this; if (addresses.length == 0) return cb(null, []); var networkName = Bitcore.Address(addresses[0]).toObject().network; var bc = self._getBlockchainExplorer(networkName); bc.getUnspentUtxos(addresses, function(err, utxos) { if (err) return cb(err); var utxos = _.map(utxos, function(utxo) { var u = _.pick(utxo, ['txid', 'vout', 'address', 'scriptPubKey', 'amount', 'satoshis', 'confirmations']); u.confirmations = u.confirmations || 0; u.locked = false; u.satoshis = u.satoshis ? +u.satoshis : Utils.strip(u.amount * 1e8); delete u.amount; return u; }); return cb(null, utxos); }); }; WalletService.prototype._getUtxosForCurrentWallet = function(cb) { var self = this; function utxoKey(utxo) { return utxo.txid + '|' + utxo.vout }; // Get addresses for this wallet self.storage.fetchAddresses(self.walletId, function(err, addresses) { if (err) return cb(err); var addressStrs = _.pluck(addresses, 'address'); self._getUtxosForAddresses(addressStrs, function(err, utxos) { if (err) return cb(err); if (utxos.length == 0) return cb(null, []); self.getPendingTxs({}, function(err, txps) { if (err) return cb(err); var lockedInputs = _.map(_.flatten(_.pluck(txps, 'inputs')), utxoKey); var utxoIndex = _.indexBy(utxos, utxoKey); _.each(lockedInputs, function(input) { if (utxoIndex[input]) { utxoIndex[input].locked = true; } }); // Needed for the clients to sign UTXOs var addressToPath = _.indexBy(addresses, 'address'); _.each(utxos, function(utxo) { utxo.path = addressToPath[utxo.address].path; utxo.publicKeys = addressToPath[utxo.address].publicKeys; }); return cb(null, utxos); }); }); }); }; /** * Returns list of UTXOs * @param {Object} opts * @param {Array} opts.addresses (optional) - List of addresses from where to fetch UTXOs. * @returns {Array} utxos - List of UTXOs. */ WalletService.prototype.getUtxos = function(opts, cb) { var self = this; opts = opts || {}; if (_.isUndefined(opts.addresses)) { self._getUtxosForCurrentWallet(cb); } else { self._getUtxosForAddresses(opts.addresses, cb); } }; WalletService.prototype._totalizeUtxos = function(utxos) { var balance = { totalAmount: _.sum(utxos, 'satoshis'), lockedAmount: _.sum(_.filter(utxos, 'locked'), 'satoshis'), totalConfirmedAmount: _.sum(_.filter(utxos, 'confirmations'), 'satoshis'), lockedConfirmedAmount: _.sum(_.filter(_.filter(utxos, 'locked'), 'confirmations'), 'satoshis'), }; balance.availableAmount = balance.totalAmount - balance.lockedAmount; balance.availableConfirmedAmount = balance.totalConfirmedAmount - balance.lockedConfirmedAmount; return balance; }; WalletService.prototype._computeBytesToSendMax = function(utxos, cb) { var self = this; var unlockedUtxos = _.reject(utxos, 'locked'); if (_.isEmpty(unlockedUtxos)) return cb(null, 0); self.getWallet({}, function(err, wallet) { if (err) return cb(err); var txp = Model.TxProposal.create({ walletId: self.walletId, requiredSignatures: wallet.m, walletN: wallet.n, }); txp.inputs = unlockedUtxos; var size = txp.getEstimatedSize(); return cb(null, size); }); }; /** * Creates a new transaction proposal. * @param {Object} opts * @returns {Object} balance - Total amount & locked amount. */ WalletService.prototype.getBalance = function(opts, cb) { var self = this; self.getUtxos({}, function(err, utxos) { if (err) return cb(err); var balance = self._totalizeUtxos(utxos); // Compute balance by address var byAddress = {}; _.each(_.indexBy(utxos, 'address'), function(value, key) { byAddress[key] = { address: key, path: value.path, amount: 0, }; }); _.each(utxos, function(utxo) { byAddress[utxo.address].amount += utxo.satoshis; }); balance.byAddress = _.values(byAddress); self._computeBytesToSendMax(utxos, function(err, size) { if (err) { log.error('Could not compute fees needed to transfer max amount', err); } balance.totalBytesToSendMax = size || 0; return cb(null, balance); }); }); }; WalletService.prototype._sampleFeeLevels = function(network, points, cb) { var self = this; var bc = self._getBlockchainExplorer(network); bc.estimateFee(points, function(err, result) { if (err) { log.error('Error estimating fee', err); return cb(err); } var levels = _.zipObject(_.map(points, function(p) { var feePerKb = _.isObject(result) ? +result[p] : -1; if (feePerKb < 0) { log.warn('Could not compute fee estimation (nbBlocks=' + p + ')'); } return [p, Utils.strip(feePerKb * 1e8)]; })); return cb(null, levels); }); }; /** * Returns fee levels for the current state of the network. * @param {Object} opts * @param {string} [opts.network = 'livenet'] - The Bitcoin network to estimate fee levels from. * @returns {Object} feeLevels - A list of fee levels & associated amount per kB in satoshi. */ WalletService.prototype.getFeeLevels = function(opts, cb) { var self = this; opts = opts || {}; var network = opts.network || 'livenet'; if (network != 'livenet' && network != 'testnet') return cb(new ClientError('Invalid network')); var levels = WalletService.FEE_LEVELS; var samplePoints = _.uniq(_.pluck(levels, 'nbBlocks')); self._sampleFeeLevels(network, samplePoints, function(err, feeSamples) { var values = _.map(levels, function(level) { var result = { level: level.name, }; if (err || feeSamples[level.nbBlocks] < 0) { result.feePerKb = level.defaultValue; result.nbBlocks = null; } else { result.feePerKb = feeSamples[level.nbBlocks]; result.nbBlocks = level.nbBlocks; } return result; }); return cb(null, values); }); }; WalletService.prototype._selectTxInputs = function(txp, utxosToExclude, cb) { var self = this; function sortUtxos(utxos) { var list = _.map(utxos, function(utxo) { var order; if (utxo.confirmations == 0) { order = 0; } else if (utxo.confirmations < 6) { order = -1; } else { order = -2; } return { order: order, utxo: utxo }; }); return _.pluck(_.sortBy(list, 'order'), 'utxo'); }; self.getUtxos({}, function(err, utxos) { if (err) return cb(err); var excludeIndex = _.reduce(utxosToExclude, function(res, val) { res[val] = val; return res; }, {}); utxos = _.reject(utxos, function(utxo) { return excludeIndex[utxo.txid + ":" + utxo.vout]; }); var totalAmount; var availableAmount; var balance = self._totalizeUtxos(utxos); if (txp.excludeUnconfirmedUtxos) { totalAmount = balance.totalConfirmedAmount; availableAmount = balance.availableConfirmedAmount; } else { totalAmount = balance.totalAmount; availableAmount = balance.availableAmount; } if (totalAmount < txp.getTotalAmount()) return cb(Errors.INSUFFICIENT_FUNDS); if (availableAmount < txp.amount) return cb(Errors.LOCKED_FUNDS); // Prepare UTXOs list utxos = _.reject(utxos, 'locked'); if (txp.excludeUnconfirmedUtxos) { utxos = _.filter(utxos, 'confirmations'); } var i = 0; var total = 0; var selected = []; var inputs = sortUtxos(utxos); var bitcoreTx, bitcoreError; var serializationOpts = { disableIsFullySigned: true, }; if (!_.startsWith(txp.version, '1.')) { serializationOpts.disableSmallFees = true; serializationOpts.disableLargeFees = true; } while (i < inputs.length) { selected.push(inputs[i]); total += inputs[i].satoshis; i++; if (total >= txp.getTotalAmount()) { try { txp.setInputs(selected); txp.estimateFee(); bitcoreTx = txp.getBitcoreTx(); bitcoreError = bitcoreTx.getSerializationError(serializationOpts); if (!bitcoreError) { txp.fee = bitcoreTx.getFee(); return cb(); } } catch (ex) { log.error('Error building Bitcore transaction', ex); return cb(ex); } } } if (bitcoreError instanceof Bitcore.errors.Transaction.FeeError) return cb(Errors.INSUFFICIENT_FUNDS_FOR_FEE); if (bitcoreError instanceof Bitcore.errors.Transaction.DustOutputs) return cb(Errors.DUST_AMOUNT); return cb(bitcoreError || new Error('Could not select tx inputs')); }); }; WalletService.prototype._canCreateTx = function(copayerId, cb) { var self = this; self.storage.fetchLastTxs(self.walletId, copayerId, 5 + WalletService.BACKOFF_OFFSET, function(err, txs) { if (err) return cb(err); if (!txs.length) return cb(null, true); var lastRejections = _.takeWhile(txs, { status: 'rejected' }); var exceededRejections = lastRejections.length - WalletService.BACKOFF_OFFSET; if (exceededRejections <= 0) return cb(null, true); var lastTxTs = txs[0].createdOn; var now = Math.floor(Date.now() / 1000); var timeSinceLastRejection = now - lastTxTs; var backoffTime = 60 * Math.pow(WalletService.BACKOFF_TIME, exceededRejections); if (timeSinceLastRejection <= backoffTime) log.debug('Not allowing to create TX: timeSinceLastRejection/backoffTime', timeSinceLastRejection, backoffTime); return cb(null, timeSinceLastRejection > backoffTime); }); }; /** * Creates a new transaction proposal. * @param {Object} opts * @param {string} opts.type - Proposal type. * @param {string} opts.toAddress || opts.outputs[].toAddress - Destination address. * @param {number} opts.amount || opts.outputs[].amount - Amount to transfer in satoshi. * @param {string} opts.outputs[].message - A message to attach to this output. * @param {string} opts.message - A message to attach to this transaction. * @param {string} opts.proposalSignature - S(toAddress|amount|message|payProUrl). Used by other copayers to verify the proposal. * @param {string} opts.feePerKb - Optional: Use an alternative fee per KB for this TX * @param {string} opts.payProUrl - Optional: Paypro URL for peers to verify TX * @param {string} opts.excludeUnconfirmedUtxos - Optional: Do not use UTXOs of unconfirmed transactions as inputs * @returns {TxProposal} Transaction proposal. */ WalletService.prototype.createTx = function(opts, cb) { var self = this; if (!opts.outputs) { opts.outputs = _.pick(opts, ['amount', 'toAddress']); } opts.outputs = [].concat(opts.outputs); if (!Utils.checkRequired(opts, ['outputs', 'proposalSignature'])) return cb(new ClientError('Required argument missing')); var type = opts.type || Model.TxProposal.Types.SIMPLE; if (!Model.TxProposal.isTypeSupported(type)) return cb(new ClientError('Invalid proposal type')); _.each(opts.outputs, function(output) { if (!Utils.checkRequired(output, ['toAddress', 'amount'])) { output.valid = false; cb(new ClientError('Required outputs argument missing')); return false; } }); if (_.any(opts.outputs, { valid: false })) return; var feePerKb = opts.feePerKb || WalletUtils.DEFAULT_FEE_PER_KB; if (feePerKb < WalletUtils.MIN_FEE_PER_KB || feePerKb > WalletUtils.MAX_FEE_PER_KB) return cb(new ClientError('Invalid fee per KB value')); self._runLocked(cb, function(cb) { self.getWallet({}, function(err, wallet) { if (err) return cb(err); if (!wallet.isComplete()) return cb(Errors.WALLET_NOT_COMPLETE); var copayer = wallet.getCopayer(self.copayerId); var hash; if (!opts.type || opts.type == Model.TxProposal.Types.SIMPLE) { hash = WalletUtils.getProposalHash(opts.toAddress, opts.amount, opts.message, opts.payProUrl); } else { // should match bwc api _computeProposalSignature var header = { outputs: _.map(opts.outputs, function(output) { return _.pick(output, ['toAddress', 'amount', 'message']); }), message: opts.message, payProUrl: opts.payProUrl }; hash = WalletUtils.getProposalHash(header) } var signingKey = self._getSigningKey(hash, opts.proposalSignature, copayer.requestPubKeys) if (!signingKey) return cb(new ClientError('Invalid proposal signature')); self._canCreateTx(self.copayerId, function(err, canCreate) { if (err) return cb(err); if (!canCreate) return cb(Errors.TX_CANNOT_CREATE); _.each(opts.outputs, function(output) { output.valid = false; var toAddress = {}; try { toAddress = new Bitcore.Address(output.toAddress); } catch (ex) { cb(Errors.INVALID_ADDRESS); return false; } if (toAddress.network != wallet.getNetworkName()) { cb(Errors.INCORRECT_ADDRESS_NETWORK); return false; } if (!_.isNumber(output.amount) || _.isNaN(output.amount) || output.amount <= 0) { cb(new ClientError('Invalid amount')); return false; } if (output.amount < Bitcore.Transaction.DUST_AMOUNT) { cb(Errors.DUST_AMOUNT); return false; } output.valid = true; }); if (_.any(opts.outputs, { valid: false })) return; var txOpts = { type: type, walletId: self.walletId, creatorId: self.copayerId, outputs: opts.outputs, toAddress: opts.toAddress, amount: opts.amount, message: opts.message, proposalSignature: opts.proposalSignature, changeAddress: wallet.createAddress(true), feePerKb: feePerKb, payProUrl: opts.payProUrl, requiredSignatures: wallet.m, requiredRejections: Math.min(wallet.m, wallet.n - wallet.m + 1), walletN: wallet.n, excludeUnconfirmedUtxos: !!opts.excludeUnconfirmedUtxos, derivationStrategy: wallet.derivationStrategy, addressType: wallet.addressType, customData: opts.customData, }; if (signingKey.selfSigned) { txOpts.proposalSignaturePubKey = signingKey.key; txOpts.proposalSignaturePubKeySig = signingKey.signature; } var txp = Model.TxProposal.create(txOpts); if (!self._clientSupportsTXPv2()) { txp.version = '1.0.1'; } self._selectTxInputs(txp, opts.utxosToExclude, function(err) { if (err) return cb(err); $.checkState(txp.inputs); self.storage.storeAddressAndWallet(wallet, txp.changeAddress, function(err) { if (err) return cb(err); self.storage.storeTx(wallet.id, txp, function(err) { if (err) return cb(err); self._notify('NewTxProposal', { amount: txp.getTotalAmount() }, function() { return cb(null, txp); }); }); }); }); }); }); }); }; /** * Retrieves a tx from storage. * @param {Object} opts * @param {string} opts.txProposalId - The tx id. * @returns {Object} txProposal */ WalletService.prototype.getTx = function(opts, cb) { var self = this; self.storage.fetchTx(self.walletId, opts.txProposalId, function(err, txp) { if (err) return cb(err); if (!txp) return cb(Errors.TX_NOT_FOUND); return cb(null, txp); }); }; /** * removeWallet * * @param opts * @param cb * @return {undefined} */ WalletService.prototype.removeWallet = function(opts, cb) { var self = this; self._runLocked(cb, function(cb) { self.storage.removeWallet(self.walletId, cb); }); }; WalletService.prototype.getRemainingDeleteLockTime = function(txp) { var now = Math.floor(Date.now() / 1000); var lockTimeRemaining = txp.createdOn + WalletService.DELETE_LOCKTIME - now; if (lockTimeRemaining < 0) return 0; // not the creator? need to wait if (txp.creatorId !== this.copayerId) return lockTimeRemaining; // has other approvers? need to wait var approvers = txp.getApprovers(); if (approvers.length > 1 || (approvers.length == 1 && approvers[0] !== this.copayerId)) return lockTimeRemaining; return 0; }; /** * removePendingTx * * @param opts * @param {string} opts.txProposalId - The tx id. * @return {undefined} */ WalletService.prototype.removePendingTx = function(opts, cb) { var self = this; if (!Utils.checkRequired(opts, ['txProposalId'])) return cb(new ClientError('Required argument missing')); self._runLocked(cb, function(cb) { self.getTx({ txProposalId: opts.txProposalId, }, function(err, txp) { if (err) return cb(err); if (!txp.isPending()) return cb(Errors.TX_NOT_PENDING); var deleteLockTime = self.getRemainingDeleteLockTime(txp); if (deleteLockTime > 0) return cb(Errors.TX_CANNOT_REMOVE); self.storage.removeTx(self.walletId, txp.id, function() { self._notify('TxProposalRemoved', {}, cb); }); }); }); }; WalletService.prototype._broadcastRawTx = function(network, raw, cb) { var bc = this._getBlockchainExplorer(network); bc.broadcast(raw, function(err, txid) { if (err) return cb(err); return cb(null, txid); }) }; /** * Broadcast a raw transaction. * @param {Object} opts * @param {string} [opts.network = 'livenet'] - The Bitcoin network for this transaction. * @param {string} opts.rawTx - Raw tx data. */ WalletService.prototype.broadcastRawTx = function(opts, cb) { var self = this; if (!Utils.checkRequired(opts, ['network', 'rawTx'])) return cb(new ClientError('Required argument missing')); var network = opts.network || 'livenet'; if (network != 'livenet' && network != 'testnet') return cb(new ClientError('Invalid network')); self._broadcastRawTx(network, opts.rawTx, cb); }; WalletService.prototype._checkTxInBlockchain = function(txp, cb) { if (!txp.txid) return cb(); var bc = this._getBlockchainExplorer(txp.getNetworkName()); bc.getTransaction(txp.txid, function(err, tx) { if (err) return cb(err); return cb(null, !!tx); }) }; /** * Sign a transaction proposal. * @param {Object} opts * @param {string} opts.txProposalId - The identifier of the transaction. * @param {string} opts.signatures - The signatures of the inputs of this tx for this copayer (in apperance order) */ WalletService.prototype.signTx = function(opts, cb) { var self = this; if (!Utils.checkRequired(opts, ['txProposalId', 'signatures'])) return cb(new ClientError('Required argument missing')); self.getWallet({}, function(err, wallet) { if (err) return cb(err); self.getTx({ txProposalId: opts.txProposalId }, function(err, txp) { if (err) return cb(err); if (!self._clientSupportsTXPv2()) { if (!_.startsWith(txp.version, '1.')) { return cb(new ClientError(Errors.codes.UPGRADE_NEEDED, 'To sign this spend proposal you need to upgrade your client app.')); } } var action = _.find(txp.actions, { copayerId: self.copayerId }); if (action) return cb(Errors.COPAYER_VOTED); if (!txp.isPending()) return cb(Errors.TX_NOT_PENDING); var copayer = wallet.getCopayer(self.copayerId); if (!txp.sign(self.copayerId, opts.signatures, copayer.xPubKey)) return cb(Errors.BAD_SIGNATURES); self.storage.storeTx(self.walletId, txp, function(err) { if (err) return cb(err); async.series([ function(next) { self._notify('TxProposalAcceptedBy', { txProposalId: opts.txProposalId, copayerId: self.copayerId, }, next); }, function(next) { if (txp.isAccepted()) { self._notify('TxProposalFinallyAccepted', { txProposalId: opts.txProposalId, }, next); } else { next(); } }, ], function() { return cb(null, txp); }); }); }); }); }; WalletService.prototype._processBroadcast = function(txp, opts, cb) { var self = this; $.checkState(txp.txid); opts = opts || {}; txp.setBroadcasted(); self.storage.storeTx(self.walletId, txp, function(err) { if (err) return cb(err); var args = { txProposalId: txp.id, txid: txp.txid, amount: txp.getTotalAmount(), }; if (opts.byThirdParty) { self._notify('NewOutgoingTxByThirdParty', args); } else { self._notify('NewOutgoingTx', args); } return cb(err, txp); }); }; /** * Broadcast a transaction proposal. * @param {Object} opts * @param {string} opts.txProposalId - The identifier of the transaction. */ WalletService.prototype.broadcastTx = function(opts, cb) { var self = this; if (!Utils.checkRequired(opts, ['txProposalId'])) return cb(new ClientError('Required argument missing')); self.getWallet({}, function(err, wallet) { if (err) return cb(err); self.getTx({ txProposalId: opts.txProposalId }, function(err, txp) { if (err) return cb(err); if (txp.status == 'broadcasted') return cb(Errors.TX_ALREADY_BROADCASTED); if (txp.status != 'accepted') return cb(Errors.TX_NOT_ACCEPTED); var raw; try { raw = txp.getRawTx(); } catch (ex) { return cb(ex); } self._broadcastRawTx(txp.getNetworkName(), raw, function(err, txid) { if (err) { var broadcastErr = err; // Check if tx already in blockchain self._checkTxInBlockchain(txp, function(err, isInBlockchain) { if (err) return cb(err); if (!isInBlockchain) return cb(broadcastErr); self._processBroadcast(txp, { byThirdParty: true }, cb); }); } else { self._processBroadcast(txp, { byThirdParty: false }, function(err) { if (err) return cb(err); return cb(null, txp); }); } }); }); }); }; /** * Reject a transaction proposal. * @param {Object} opts * @param {string} opts.txProposalId - The identifier of the transaction. * @param {string} [opts.reason] - A message to other copayers explaining the rejection. */ WalletService.prototype.rejectTx = function(opts, cb) { var self = this; if (!Utils.checkRequired(opts, ['txProposalId'])) return cb(new ClientError('Required argument missing')); self.getTx({ txProposalId: opts.txProposalId }, function(err, txp) { if (err) return cb(err); var action = _.find(txp.actions, { copayerId: self.copayerId }); if (action) return cb(Errors.COPAYER_VOTED); if (txp.status != 'pending') return cb(Errors.TX_NOT_PENDING); txp.reject(self.copayerId, opts.reason); self.storage.storeTx(self.walletId, txp, function(err) { if (err) return cb(err); async.series([ function(next) { self._notify('TxProposalRejectedBy', { txProposalId: opts.txProposalId, copayerId: self.copayerId, }, next); }, function(next) { if (txp.status == 'rejected') { var rejectedBy = _.pluck(_.filter(txp.actions, { type: 'reject' }), 'copayerId'); self._notify('TxProposalFinallyRejected', { txProposalId: opts.txProposalId, rejectedBy: rejectedBy, }, next); } else { next(); } }, ], function() { return cb(null, txp); }); }); }); }; /** * Retrieves pending transaction proposals. * @param {Object} opts * @returns {TxProposal[]} Transaction proposal. */ WalletService.prototype.getPendingTxs = function(opts, cb) { var self = this; self.storage.fetchPendingTxs(self.walletId, function(err, txps) { if (err) return cb(err); _.each(txps, function(txp) { txp.deleteLockTime = self.getRemainingDeleteLockTime(txp); }); async.each(txps, function(txp, a_cb) { if (txp.status != 'accepted') return a_cb(); self._checkTxInBlockchain(txp, function(err, isInBlockchain) { if (err || !isInBlockchain) return a_cb(err); self._processBroadcast(txp, { byThirdParty: true }, a_cb); }); }, function(err) { return cb(err, _.reject(txps, function(txp) { return txp.status == 'broadcasted'; })); }); }); }; /** * Retrieves all transaction proposals in the range (maxTs-minTs) * Times are in UNIX EPOCH * * @param {Object} opts.minTs (defaults to 0) * @param {Object} opts.maxTs (defaults to now) * @param {Object} opts.limit * @returns {TxProposal[]} Transaction proposals, newer first */ WalletService.prototype.getTxs = function(opts, cb) { var self = this; self.storage.fetchTxs(self.walletId, opts, function(err, txps) { if (err) return cb(err); return cb(null, txps); }); }; /** * Retrieves notifications in the range (maxTs-minTs). * Times are in UNIX EPOCH. Order is assured even for events with the same time * * @param {Object} opts.minTs (defaults to 0) * @param {Object} opts.maxTs (defaults to now) * @param {Object} opts.limit * @param {Object} opts.reverse (default false) * @returns {Notification[]} Notifications */ WalletService.prototype.getNotifications = function(opts, cb) { var self = this; self.storage.fetchNotifications(self.walletId, opts, function(err, notifications) { if (err) return cb(err); return cb(null, notifications); }); }; WalletService.prototype._normalizeTxHistory = function(txs) { var now = Math.floor(Date.now() / 1000); return _.map(txs, function(tx) { var inputs = _.map(tx.vin, function(item) { return { address: item.addr, amount: item.valueSat, } }); var outputs = _.map(tx.vout, function(item) { var itemAddr; // If classic multisig, ignore if (item.scriptPubKey && _.isArray(item.scriptPubKey.addresses) && item.scriptPubKey.addresses.length == 1) { itemAddr = item.scriptPubKey.addresses[0]; } return { address: itemAddr, amount: parseInt((item.value * 1e8).toFixed(0)), } }); return { txid: tx.txid, confirmations: tx.confirmations, fees: parseInt((tx.fees * 1e8).toFixed(0)), time: tx.firstSeenTs || (!_.isNaN(tx.time) ? tx.time : now) || now, inputs: inputs, outputs: outputs, }; }); }; /** * Retrieves all transactions (incoming & outgoing) * Times are in UNIX EPOCH * * @param {Object} opts * @param {Number} opts.skip (defaults to 0) * @param {Number} opts.limit * @returns {TxProposal[]} Transaction proposals, first newer */ WalletService.prototype.getTxHistory = function(opts, cb) { var self = this; function decorate(txs, addresses, proposals) { var indexedAddresses = _.indexBy(addresses, 'address'); var indexedProposals = _.indexBy(proposals, 'txid'); function sum(items, isMine, isChange) { var filter = {}; if (_.isBoolean(isMine)) filter.isMine = isMine; if (_.isBoolean(isChange)) filter.isChange = isChange; return _.sum(_.filter(items, filter), 'amount'); }; function classify(items) { return _.map(items, function(item) { var address = indexedAddresses[item.address]; return { address: item.address, amount: item.amount, isMine: !!address, isChange: address ? address.isChange : false, } }); }; return _.map(txs, function(tx) { var amountIn, amountOut, amountOutChange; var amount, action, addressTo; var inputs, outputs; if (tx.outputs.length || tx.inputs.length) { inputs = classify(tx.inputs); outputs = classify(tx.outputs); amountIn = sum(inputs, true); amountOut = sum(outputs, true, false); amountOutChange = sum(outputs, true, true); if (amountIn == (amountOut + amountOutChange + (amountIn > 0 ? tx.fees : 0))) { amount = amountOut; action = 'moved'; } else { amount = amountIn - amountOut - amountOutChange - (amountIn > 0 ? tx.fees : 0); action = amount > 0 ? 'sent' : 'received'; } amount = Math.abs(amount); if (action == 'sent' || action == 'moved') { var firstExternalOutput = _.find(outputs, { isMine: false }); addressTo = firstExternalOutput ? firstExternalOutput.address : 'N/A'; }; } else { action = 'invalid'; amount = 0; } function outputMap(o) { return { amount: o.amount, address: o.address } }; var newTx = { txid: tx.txid, action: action, amount: amount, fees: tx.fees, time: tx.time, addressTo: addressTo, outputs: _.map(_.filter(outputs, { isChange: false }), outputMap), confirmations: tx.confirmations, }; var proposal = indexedProposals[tx.txid]; if (proposal) { newTx.proposalId = proposal.id; newTx.proposalType = proposal.type; newTx.creatorName = proposal.creatorName; newTx.message = proposal.message; newTx.actions = _.map(proposal.actions, function(action) { return _.pick(action, ['createdOn', 'type', 'copayerId', 'copayerName', 'comment']); }); _.each(newTx.outputs, function(output) { var query = { toAddress: output.address, amount: output.amount }; var txpOut = _.find(proposal.outputs, query); output.message = txpOut ? txpOut.message : null; }); // newTx.sentTs = proposal.sentTs; // newTx.merchant = proposal.merchant; //newTx.paymentAckMemo = proposal.paymentAckMemo; } return newTx; }); }; // Get addresses for this wallet self.storage.fetchAddresses(self.walletId, function(err, addresses) { if (err) return cb(err); if (addresses.length == 0) return cb(null, []); var addressStrs = _.pluck(addresses, 'address'); var networkName = Bitcore.Address(addressStrs[0]).toObject().network; var bc = self._getBlockchainExplorer(networkName); async.parallel([ function(next) { self.storage.fetchTxs(self.walletId, {}, function(err, txps) { if (err) return next(err); next(null, txps); }); }, function(next) { var from = opts.skip || 0; var to = from + (_.isUndefined(opts.limit) ? 100 : opts.limit); bc.getTransactions(addressStrs, from, to, function(err, txs) { if (err) return cb(err); next(null, self._normalizeTxHistory(txs)); }); }, ], function(err, res) { if (err) return cb(err); var proposals = res[0]; var txs = res[1]; txs = decorate(txs, addresses, proposals); return cb(null, txs); }); }); }; /** * Scan the blockchain looking for addresses having some activity * * @param {Object} opts * @param {Boolean} opts.includeCopayerBranches (defaults to false) */ WalletService.prototype.scan = function(opts, cb) { var self = this; opts = opts || {}; function deriveAddresses(size, derivator, cb) { async.mapSeries(_.range(size), function(i, next) { setTimeout(function() { next(null, derivator.derive()); }, WalletService.SCAN_CONFIG.derivationDelay) }, cb); }; function checkActivity(addresses, networkName, cb) { var bc = self._getBlockchainExplorer(networkName); bc.getAddressActivity(addresses, cb); }; function scanBranch(derivator, cb) { var activity = true; var allAddresses = []; var networkName; async.whilst(function() { return activity; }, function(next) { deriveAddresses(WalletService.SCAN_CONFIG.scanWindow, derivator, function(err, addresses) { if (err) return next(err); networkName = networkName || Bitcore.Address(addresses[0].address).toObject().network; checkActivity(_.pluck(addresses, 'address'), networkName, function(err, thereIsActivity) { if (err) return next(err); activity = thereIsActivity; if (thereIsActivity) { allAddresses.push(addresses); } else { derivator.rewind(WalletService.SCAN_CONFIG.scanWindow); } next(); }); }); }, function(err) { return cb(err, _.flatten(allAddresses)); }); }; self._runLocked(cb, function(cb) { self.getWallet({}, function(err, wallet) { if (err) return cb(err); if (!wallet.isComplete()) return cb(Errors.WALLET_NOT_COMPLETE); wallet.scanStatus = 'running'; self.storage.storeWallet(wallet, function(err) { if (err) return cb(err); var derivators = []; _.each([false, true], function(isChange) { derivators.push({ derive: _.bind(wallet.createAddress, wallet, isChange), rewind: _.bind(wallet.addressManager.rewindIndex, wallet.addressManager, isChange), }); if (opts.includeCopayerBranches) { _.each(wallet.copayers, function(copayer) { if (copayer.addressManager) { derivators.push({ derive: _.bind(copayer.createAddress, copayer, wallet, isChange), rewind: _.bind(copayer.addressManager.rewindIndex, copayer.addressManager, isChange), }); } }); } }); async.eachSeries(derivators, function(derivator, next) { scanBranch(derivator, function(err, addresses) { if (err) return next(err); self.storage.storeAddressAndWallet(wallet, addresses, next); }); }, function(error) { self.storage.fetchWallet(wallet.id, function(err, wallet) { if (err) return cb(err); wallet.scanStatus = error ? 'error' : 'success'; self.storage.storeWallet(wallet, function() { return cb(error); }); }) }); }); }); }); }; /** * Start a scan process. * * @param {Object} opts * @param {Boolean} opts.includeCopayerBranches (defaults to false) */ WalletService.prototype.startScan = function(opts, cb) { var self = this; function scanFinished(err) { var data = { result: err ? 'error' : 'success', }; if (err) data.error = err; self._notify('ScanFinished', data, { isGlobal: true }); }; self.getWallet({}, function(err, wallet) { if (err) return cb(err); if (!wallet.isComplete()) return cb(Errors.WALLET_NOT_COMPLETE); setTimeout(function() { self.scan(opts, scanFinished); }, 100); return cb(null, { started: true }); }); }; module.exports = WalletService; module.exports.ClientError = ClientError;
module.exports={A:{A:{"2":"L H G E jB","6308":"A","6436":"B"},B:{"1":"BB","6436":"C D d K I N J"},C:{"1":"GB HB","2":"2 3 5 gB IB F L H G E A B C D d K I N J P Q R S T U V W X Y Z a b c e f g h aB ZB","2052":"0 1 6 7 8 9 i j k l m n o M q r s t u v w x y z AB CB DB EB O"},D:{"1":"HB TB PB NB mB OB LB BB QB RB","2":"0 1 2 3 5 6 7 8 9 F L H G E A B C D d K I N J P Q R S T U V W X Y Z a b c e f g h i j k l m n o M q r s t u v w x y z AB CB DB","8258":"EB O GB"},E:{"1":"4 B C D p bB","2":"2 F L H G SB KB UB VB WB","3108":"E A XB YB"},F:{"2":"3 4 5 E B C K I N J P Q R S T U V W X Y Z a b c e f g h i j k l m n o M q r s t u v w cB dB eB fB p FB hB","8258":"0 1 x y z"},G:{"1":"D sB tB uB vB","2":"G KB iB JB kB lB MB nB","3108":"oB pB qB rB"},H:{"2":"wB"},I:{"1":"O","2":"IB F xB yB zB 0B JB 1B 2B"},J:{"2":"H A"},K:{"2":"4 A B C M p FB"},L:{"1":"LB"},M:{"2052":"O"},N:{"2":"A B"},O:{"2":"3B"},P:{"2":"F 4B 5B 6B 7B 8B"},Q:{"2":"9B"},R:{"2":"AC"},S:{"2052":"BC"}},B:4,C:"CSS Scroll snap"};
var path = require('path'); var mout = require('mout'); var rimraf = require('rimraf'); var fs = require('graceful-fs'); var Q = require('q'); var expect = require('expect.js'); var mkdirp = require('mkdirp'); var ResolveCache = require('../../lib/core/ResolveCache'); var defaultConfig = require('../../lib/config'); var cmd = require('../../lib/util/cmd'); var copy = require('../../lib/util/copy'); var md5 = require('../../lib/util/md5'); describe('ResolveCache', function () { var resolveCache; var testPackage = path.resolve(__dirname, '../assets/package-a'); var tempPackage = path.resolve(__dirname, '../assets/temp'); var tempPackage2 = path.resolve(__dirname, '../assets/temp2'); var cacheDir = path.join(__dirname, '../assets/temp-resolve-cache'); before(function (next) { // Delete cache folder rimraf.sync(cacheDir); // Instantiate resolver cache resolveCache = new ResolveCache(mout.object.deepMixIn(defaultConfig, { storage: { packages: cacheDir } })); // Checkout test package version 0.2.0 cmd('git', ['checkout', '0.2.0'], { cwd: testPackage }) .then(next.bind(next, null), next); }); beforeEach(function () { // Reset in memory cache for each test resolveCache.reset(); }); after(function () { // Remove cache folder afterwards rimraf.sync(cacheDir); }); describe('.constructor', function () { beforeEach(function () { // Delete temp folder rimraf.sync(tempPackage); }); after(function () { // Delete temp folder rimraf.sync(tempPackage); }); function initialize(cacheDir) { return new ResolveCache(mout.object.deepMixIn(defaultConfig, { storage: { packages: cacheDir } })); } it('should create the cache folder if it doesn\'t exists', function () { initialize(tempPackage); expect(fs.existsSync(tempPackage)).to.be(true); }); it('should not error out if the cache folder already exists', function () { mkdirp.sync(tempPackage); initialize(tempPackage); }); }); describe('.store', function () { var oldFsRename = fs.rename; beforeEach(function (next) { // Restore oldFsRename fs.rename = oldFsRename; // Create a fresh copy of the test package into temp rimraf.sync(tempPackage); copy.copyDir(testPackage, tempPackage, { ignore: ['.git'] }) .then(next.bind(next, null), next); }); it('should move the canonical dir to source-md5/version/ folder if package meta has a version', function (next) { resolveCache.store(tempPackage, { name: 'foo', version: '1.0.0', _source: 'foo', _target: '*' }) .then(function (dir) { expect(dir).to.equal(path.join(cacheDir, md5('foo'), '1.0.0')); expect(fs.existsSync(dir)).to.be(true); expect(fs.existsSync(path.join(dir, 'baz'))).to.be(true); expect(fs.existsSync(tempPackage)).to.be(false); next(); }) .done(); }); it('should move the canonical dir to source-md5/target/ folder if package meta has no version', function (next) { resolveCache.store(tempPackage, { name: 'foo', _source: 'foo', _target: 'some-branch' }) .then(function (dir) { expect(dir).to.equal(path.join(cacheDir, md5('foo'), 'some-branch')); expect(fs.existsSync(dir)).to.be(true); expect(fs.existsSync(path.join(dir, 'baz'))).to.be(true); expect(fs.existsSync(tempPackage)).to.be(false); next(); }) .done(); }); it('should move the canonical dir to source-md5/_wildcard/ folder if package meta has no version and target is *', function (next) { resolveCache.store(tempPackage, { name: 'foo', _source: 'foo', _target: '*' }) .then(function (dir) { expect(dir).to.equal(path.join(cacheDir, md5('foo'), '_wildcard')); expect(fs.existsSync(dir)).to.be(true); expect(fs.existsSync(path.join(dir, 'baz'))).to.be(true); expect(fs.existsSync(tempPackage)).to.be(false); next(); }) .done(); }); it('should overwrite if the exact same package source/version exists', function (next) { var cachePkgDir = path.join(cacheDir, md5('foo'), '1.0.0-rc.blehhh'); mkdirp.sync(cachePkgDir); fs.writeFileSync(path.join(cachePkgDir, '_bleh'), 'w00t'); resolveCache.store(tempPackage, { name: 'foo', version: '1.0.0-rc.blehhh', _source: 'foo', _target: '*' }) .then(function (dir) { expect(dir).to.equal(cachePkgDir); expect(fs.existsSync(dir)).to.be(true); expect(fs.existsSync(path.join(dir, 'baz'))).to.be(true); expect(fs.existsSync(tempPackage)).to.be(false); expect(fs.existsSync(path.join(cachePkgDir, '_bleh'))).to.be(false); next(); }) .done(); }); it('should read the package meta if not present', function (next) { var pkgMeta = path.join(tempPackage, '.bower.json'); // Copy bower.json to .bower.json and add some props copy.copyFile(path.join(tempPackage, 'component.json'), pkgMeta) .then(function () { return Q.nfcall(fs.readFile, pkgMeta) .then(function (contents) { var json = JSON.parse(contents.toString()); json._target = '~0.2.0'; json._source = 'git://github.com/bower/test-package.git'; return Q.nfcall(fs.writeFile, pkgMeta, JSON.stringify(json, null, ' ')); }); }) // Store as usual .then(function () { return resolveCache.store(tempPackage); }) .then(function (dir) { expect(dir).to.equal(path.join(cacheDir, md5('git://github.com/bower/test-package.git'), '0.2.0')); expect(fs.existsSync(dir)).to.be(true); expect(fs.existsSync(path.join(dir, 'baz'))).to.be(true); expect(fs.existsSync(tempPackage)).to.be(false); next(); }) .done(); }); it('should error out when reading the package meta if the file does not exist', function (next) { resolveCache.store(tempPackage) .then(function () { next(new Error('Should have failed')); }, function (err) { expect(err).to.be.an(Error); expect(err.code).to.equal('ENOENT'); expect(err.message).to.contain(path.join(tempPackage, '.bower.json')); next(); }) .done(); }); it('should error out when reading an invalid package meta', function (next) { var pkgMeta = path.join(tempPackage, '.bower.json'); return Q.nfcall(fs.writeFile, pkgMeta, 'w00t') .then(function () { return resolveCache.store(tempPackage) .then(function () { next(new Error('Should have failed')); }, function (err) { expect(err).to.be.an(Error); expect(err.code).to.equal('EMALFORMED'); expect(err.message).to.contain(path.join(tempPackage, '.bower.json')); next(); }); }) .done(); }); it('should move the canonical dir, even if it is in a different drive', function (next) { var hittedMock = false; fs.rename = function (src, dest, cb) { hittedMock = true; setTimeout(function () { var err = new Error(); err.code = 'EXDEV'; cb(err); }, 10); }; resolveCache.store(tempPackage, { name: 'foo', _source: 'foo', _target: 'some-branch' }) .then(function (dir) { // Ensure mock was called expect(hittedMock).to.be(true); expect(dir).to.equal(path.join(cacheDir, md5('foo'), 'some-branch')); expect(fs.existsSync(dir)).to.be(true); expect(fs.existsSync(path.join(dir, 'baz'))).to.be(true); expect(fs.existsSync(tempPackage)).to.be(false); next(); }) .done(); }); it('should update the in-memory cache', function (next) { // Feed the cache resolveCache.versions('test-in-memory') // Copy temp package to temp package 2 .then(function () { return copy.copyDir(tempPackage, tempPackage2, { ignore: ['.git'] }); }) // Store the two packages .then(function () { return resolveCache.store(tempPackage, { name: 'foo', version: '1.0.0', _source: 'test-in-memory', _target: '*' }); }) .then(function () { return resolveCache.store(tempPackage2, { name: 'foo', version: '1.0.1', _source: 'test-in-memory', _target: '*' }); }) // Cache should have been updated .then(function () { return resolveCache.versions('test-in-memory') .then(function (versions) { expect(versions).to.eql(['1.0.1', '1.0.0']); next(); }); }) .done(); }); it('should url encode target when storing to the fs', function (next) { resolveCache.store(tempPackage, { name: 'foo', _source: 'foo', _target: 'foo/bar' }) .then(function (dir) { expect(dir).to.equal(path.join(cacheDir, md5('foo'), 'foo%2Fbar')); expect(fs.existsSync(dir)).to.be(true); expect(fs.existsSync(path.join(dir, 'baz'))).to.be(true); expect(fs.existsSync(tempPackage)).to.be(false); next(); }) .done(); }); }); describe('.versions', function () { it('should resolve to an array', function (next) { resolveCache.versions(String(Math.random())) .then(function (versions) { expect(versions).to.be.an('array'); next(); }) .done(); }); it('should ignore non-semver folders of the source', function (next) { var source = String(Math.random()); var sourceId = md5(source); var sourceDir = path.join(cacheDir, sourceId); // Create some versions fs.mkdirSync(sourceDir); fs.mkdirSync(path.join(sourceDir, '0.0.1')); fs.mkdirSync(path.join(sourceDir, '0.1.0')); fs.mkdirSync(path.join(sourceDir, 'foo')); resolveCache.versions(source) .then(function (versions) { expect(versions).to.not.contain('foo'); expect(versions).to.contain('0.0.1'); expect(versions).to.contain('0.1.0'); next(); }) .done(); }); it('should order the versions', function (next) { var source = String(Math.random()); var sourceId = md5(source); var sourceDir = path.join(cacheDir, sourceId); // Create some versions fs.mkdirSync(sourceDir); fs.mkdirSync(path.join(sourceDir, '0.0.1')); fs.mkdirSync(path.join(sourceDir, '0.1.0')); fs.mkdirSync(path.join(sourceDir, '0.1.0-rc.1')); resolveCache.versions(source) .then(function (versions) { expect(versions).to.eql(['0.1.0', '0.1.0-rc.1', '0.0.1']); next(); }) .done(); }); it('should cache versions to speed-up subsequent calls', function (next) { var source = String(Math.random()); var sourceId = md5(source); var sourceDir = path.join(cacheDir, sourceId); // Create some versions fs.mkdirSync(sourceDir); fs.mkdirSync(path.join(sourceDir, '0.0.1')); resolveCache.versions(source) .then(function () { // Remove folder rimraf.sync(sourceDir); return resolveCache.versions(source); }) .then(function (versions) { expect(versions).to.eql(['0.0.1']); next(); }) .done(); }); }); describe('.retrieve', function () { it('should resolve to empty if there are no packages for the requested source', function (next) { resolveCache.retrieve(String(Math.random())) .spread(function () { expect(arguments.length).to.equal(0); next(); }) .done(); }); it('should resolve to empty if there are no suitable packages for the requested target', function (next) { var source = String(Math.random()); var sourceId = md5(source); var sourceDir = path.join(cacheDir, sourceId); // Create some versions fs.mkdirSync(sourceDir); fs.mkdirSync(path.join(sourceDir, '0.0.1')); fs.mkdirSync(path.join(sourceDir, '0.1.0')); fs.mkdirSync(path.join(sourceDir, '0.1.9')); fs.mkdirSync(path.join(sourceDir, '0.2.0')); resolveCache.retrieve(source, '~0.3.0') .spread(function () { expect(arguments.length).to.equal(0); return resolveCache.retrieve(source, 'some-branch'); }) .spread(function () { expect(arguments.length).to.equal(0); next(); }) .done(); }); it('should remove invalid packages from the cache if their package meta is missing or invalid', function (next) { var source = String(Math.random()); var sourceId = md5(source); var sourceDir = path.join(cacheDir, sourceId); // Create some versions fs.mkdirSync(sourceDir); fs.mkdirSync(path.join(sourceDir, '0.0.1')); fs.mkdirSync(path.join(sourceDir, '0.1.0')); fs.mkdirSync(path.join(sourceDir, '0.1.9')); fs.mkdirSync(path.join(sourceDir, '0.2.0')); // Create an invalid package meta fs.writeFileSync(path.join(sourceDir, '0.2.0', '.bower.json'), 'w00t'); resolveCache.retrieve(source, '~0.1.0') .spread(function () { var dirs = fs.readdirSync(sourceDir); expect(arguments.length).to.equal(0); expect(dirs).to.contain('0.0.1'); expect(dirs).to.contain('0.2.0'); next(); }) .done(); }); it('should resolve to the highest package that matches a range target, ignoring pre-releases', function (next) { var source = String(Math.random()); var sourceId = md5(source); var sourceDir = path.join(cacheDir, sourceId); var json = { name: 'foo' }; // Create some versions fs.mkdirSync(sourceDir); json.version = '0.0.1'; fs.mkdirSync(path.join(sourceDir, '0.0.1')); fs.writeFileSync(path.join(sourceDir, '0.0.1', '.bower.json'), JSON.stringify(json, null, ' ')); json.version = '0.1.0'; fs.mkdirSync(path.join(sourceDir, '0.1.0')); fs.writeFileSync(path.join(sourceDir, '0.1.0', '.bower.json'), JSON.stringify(json, null, ' ')); json.version = '0.1.0-rc.1'; fs.mkdirSync(path.join(sourceDir, '0.1.0-rc.1')); fs.writeFileSync(path.join(sourceDir, '0.1.0-rc.1', '.bower.json'), JSON.stringify(json, null, ' ')); json.version = '0.1.9'; fs.mkdirSync(path.join(sourceDir, '0.1.9')); fs.writeFileSync(path.join(sourceDir, '0.1.9', '.bower.json'), JSON.stringify(json, null, ' ')); json.version = '0.2.0'; fs.mkdirSync(path.join(sourceDir, '0.2.0')); fs.writeFileSync(path.join(sourceDir, '0.2.0', '.bower.json'), JSON.stringify(json, null, ' ')); resolveCache.retrieve(source, '~0.1.0') .spread(function (canonicalDir, pkgMeta) { expect(pkgMeta).to.be.an('object'); expect(pkgMeta.version).to.equal('0.1.9'); expect(canonicalDir).to.equal(path.join(sourceDir, '0.1.9')); return resolveCache.retrieve(source, '*'); }) .spread(function (canonicalDir, pkgMeta) { expect(pkgMeta).to.be.an('object'); expect(pkgMeta.version).to.equal('0.2.0'); expect(canonicalDir).to.equal(path.join(sourceDir, '0.2.0')); next(); }) .done(); }); it('should resolve to the highest package that matches a range target, not ignoring pre-releases if they are the only versions', function (next) { var source = String(Math.random()); var sourceId = md5(source); var sourceDir = path.join(cacheDir, sourceId); var json = { name: 'foo' }; // Create some versions fs.mkdirSync(sourceDir); json.version = '0.1.0-rc.1'; fs.mkdirSync(path.join(sourceDir, '0.1.0-rc.1')); fs.writeFileSync(path.join(sourceDir, '0.1.0-rc.1', '.bower.json'), JSON.stringify(json, null, ' ')); json.version = '0.1.0-rc.2'; fs.mkdirSync(path.join(sourceDir, '0.1.0-rc.2')); fs.writeFileSync(path.join(sourceDir, '0.1.0-rc.2', '.bower.json'), JSON.stringify(json, null, ' ')); resolveCache.retrieve(source, '~0.1.0') .spread(function (canonicalDir, pkgMeta) { expect(pkgMeta).to.be.an('object'); expect(pkgMeta.version).to.equal('0.1.0-rc.2'); expect(canonicalDir).to.equal(path.join(sourceDir, '0.1.0-rc.2')); next(); }) .done(); }); it('should resolve to exact match (including build metadata) if available', function (next) { var source = String(Math.random()); var sourceId = md5(source); var sourceDir = path.join(cacheDir, sourceId); var json = { name: 'foo' }; // Create some versions fs.mkdirSync(sourceDir); json.version = '0.1.0'; fs.mkdirSync(path.join(sourceDir, '0.1.0')); fs.writeFileSync(path.join(sourceDir, '0.1.0', '.bower.json'), JSON.stringify(json, null, ' ')); json.version = '0.1.0+build.4'; fs.mkdirSync(path.join(sourceDir, '0.1.0+build.4')); fs.writeFileSync(path.join(sourceDir, '0.1.0+build.4', '.bower.json'), JSON.stringify(json, null, ' ')); json.version = '0.1.0+build.5'; fs.mkdirSync(path.join(sourceDir, '0.1.0+build.5')); fs.writeFileSync(path.join(sourceDir, '0.1.0+build.5', '.bower.json'), JSON.stringify(json, null, ' ')); json.version = '0.1.0+build.6'; fs.mkdirSync(path.join(sourceDir, '0.1.0+build.6')); fs.writeFileSync(path.join(sourceDir, '0.1.0+build.6', '.bower.json'), JSON.stringify(json, null, ' ')); resolveCache.retrieve(source, '0.1.0+build.5') .spread(function (canonicalDir, pkgMeta) { expect(pkgMeta).to.be.an('object'); expect(pkgMeta.version).to.equal('0.1.0+build.5'); expect(canonicalDir).to.equal(path.join(sourceDir, '0.1.0+build.5')); next(); }) .done(); }); it('should resolve to the _wildcard package if target is * and there are no semver versions', function (next) { var source = String(Math.random()); var sourceId = md5(source); var sourceDir = path.join(cacheDir, sourceId); var json = { name: 'foo' }; // Create some versions fs.mkdirSync(sourceDir); fs.mkdirSync(path.join(sourceDir, '_wildcard')); fs.writeFileSync(path.join(sourceDir, '_wildcard', '.bower.json'), JSON.stringify(json, null, ' ')); resolveCache.retrieve(source, '*') .spread(function (canonicalDir, pkgMeta) { expect(pkgMeta).to.be.an('object'); expect(canonicalDir).to.equal(path.join(sourceDir, '_wildcard')); next(); }) .done(); }); it('should resolve to the exact target it\'s not a semver range', function (next) { var source = String(Math.random()); var sourceId = md5(source); var sourceDir = path.join(cacheDir, sourceId); var json = { name: 'foo' }; // Create some versions fs.mkdirSync(sourceDir); fs.mkdirSync(path.join(sourceDir, 'some-branch')); fs.writeFileSync(path.join(sourceDir, 'some-branch', '.bower.json'), JSON.stringify(json, null, ' ')); fs.mkdirSync(path.join(sourceDir, 'other-branch')); fs.writeFileSync(path.join(sourceDir, 'other-branch', '.bower.json'), JSON.stringify(json, null, ' ')); resolveCache.retrieve(source, 'some-branch') .spread(function (canonicalDir, pkgMeta) { expect(pkgMeta).to.be.an('object'); expect(pkgMeta).to.not.have.property('version'); next(); }) .done(); }); }); describe('.eliminate', function () { beforeEach(function () { mkdirp.sync(cacheDir); }); it('should delete the source-md5/version folder', function (next) { var source = String(Math.random()); var sourceId = md5(source); var sourceDir = path.join(cacheDir, sourceId); // Create some versions fs.mkdirSync(sourceDir); fs.mkdirSync(path.join(sourceDir, '0.0.1')); fs.mkdirSync(path.join(sourceDir, '0.1.0')); resolveCache.eliminate({ name: 'foo', version: '0.0.1', _source: source, _target: '*' }) .then(function () { expect(fs.existsSync(path.join(sourceDir, '0.0.1'))).to.be(false); expect(fs.existsSync(path.join(sourceDir, '0.1.0'))).to.be(true); next(); }) .done(); }); it('should delete the source-md5/target folder', function (next) { var source = String(Math.random()); var sourceId = md5(source); var sourceDir = path.join(cacheDir, sourceId); // Create some versions fs.mkdirSync(sourceDir); fs.mkdirSync(path.join(sourceDir, '0.0.1')); fs.mkdirSync(path.join(sourceDir, 'some-branch')); resolveCache.eliminate({ name: 'foo', _source: source, _target: 'some-branch' }) .then(function () { expect(fs.existsSync(path.join(sourceDir, 'some-branch'))).to.be(false); expect(fs.existsSync(path.join(sourceDir, '0.0.1'))).to.be(true); next(); }) .done(); }); it('should delete the source-md5/_wildcard folder', function (next) { var source = String(Math.random()); var sourceId = md5(source); var sourceDir = path.join(cacheDir, sourceId); // Create some versions fs.mkdirSync(sourceDir); fs.mkdirSync(path.join(sourceDir, '0.0.1')); fs.mkdirSync(path.join(sourceDir, '_wildcard')); resolveCache.eliminate({ name: 'foo', _source: source, _target: '*' }) .then(function () { expect(fs.existsSync(path.join(sourceDir, '_wildcard'))).to.be(false); expect(fs.existsSync(path.join(sourceDir, '0.0.1'))).to.be(true); next(); }) .done(); }); it('should delete the source-md5 folder if empty', function (next) { var source = String(Math.random()); var sourceId = md5(source); var sourceDir = path.join(cacheDir, sourceId); // Create some versions fs.mkdirSync(sourceDir); fs.mkdirSync(path.join(sourceDir, '0.0.1')); resolveCache.eliminate({ name: 'foo', version: '0.0.1', _source: source, _target: '*' }) .then(function () { expect(fs.existsSync(path.join(sourceDir, '0.0.1'))).to.be(false); expect(fs.existsSync(path.join(sourceDir))).to.be(false); next(); }) .done(); }); it('should remove entry from in memory cache if the source-md5 folder was deleted', function (next) { var source = String(Math.random()); var sourceId = md5(source); var sourceDir = path.join(cacheDir, sourceId); // Create some versions fs.mkdirSync(sourceDir); fs.mkdirSync(path.join(sourceDir, '0.0.1')); // Feed up the cache resolveCache.versions(source) // Eliminate .then(function () { return resolveCache.eliminate({ name: 'foo', version: '0.0.1', _source: source, _target: '*' }); }) .then(function () { // At this point the parent folder should be deleted // To test against the in-memory cache, we create a folder // manually and request the versions mkdirp.sync(path.join(sourceDir, '0.0.2')); resolveCache.versions(source) .then(function (versions) { expect(versions).to.eql(['0.0.2']); next(); }); }) .done(); }); }); describe('.clear', function () { beforeEach(function () { mkdirp.sync(cacheDir); }); it('should empty the whole cache folder', function (next) { resolveCache.clear() .then(function () { var files; expect(fs.existsSync(cacheDir)).to.be(true); files = fs.readdirSync(cacheDir); expect(files.length).to.be(0); next(); }) .done(); }); it('should erase the in-memory cache', function (next) { var source = String(Math.random()); var sourceId = md5(source); var sourceDir = path.join(cacheDir, sourceId); // Create some versions fs.mkdirSync(sourceDir); fs.mkdirSync(path.join(sourceDir, '0.0.1')); // Feed the in-memory cache resolveCache.versions(source) // Clear .then(function () { return resolveCache.clear(); }) .then(function () { // To test against the in-memory cache, we create a folder // manually and request the versions mkdirp.sync(path.join(sourceDir, '0.0.2')); resolveCache.versions(source) .then(function (versions) { expect(versions).to.eql(['0.0.2']); next(); }); }) .done(); }); }); describe('.reset', function () { it('should erase the in-memory cache', function (next) { var source = String(Math.random()); var sourceId = md5(source); var sourceDir = path.join(cacheDir, sourceId); // Create some versions fs.mkdirSync(sourceDir); fs.mkdirSync(path.join(sourceDir, '0.0.1')); // Feed the in-memory cache resolveCache.versions(source) .then(function () { // Delete 0.0.1 and create 0.0.2 fs.rmdirSync(path.join(sourceDir, '0.0.1')); fs.mkdirSync(path.join(sourceDir, '0.0.2')); // Reset cache resolveCache.reset(); // Get versions return resolveCache.versions(source); }) .then(function (versions) { expect(versions).to.eql(['0.0.2']); next(); }) .done(); }); }); describe('.list', function () { beforeEach(function () { rimraf.sync(cacheDir); mkdirp.sync(cacheDir); }); it('should resolve to an empty array if the cache is empty', function (next) { resolveCache.list() .then(function (entries) { expect(entries).to.be.an('array'); expect(entries.length).to.be(0); next(); }) .done(); }); it('should resolve to an ordered array of entries (name ASC, release ASC)', function (next) { var source = 'list-package-1'; var sourceId = md5(source); var sourceDir = path.join(cacheDir, sourceId); var source2 = 'list-package-2'; var sourceId2 = md5(source2); var sourceDir2 = path.join(cacheDir, sourceId2); var json = { name: 'foo' }; // Create some versions for different sources fs.mkdirSync(sourceDir); fs.mkdirSync(path.join(sourceDir, '0.0.1')); json.version = '0.0.1'; fs.writeFileSync(path.join(sourceDir, '0.0.1', '.bower.json'), JSON.stringify(json, null, ' ')); fs.mkdirSync(path.join(sourceDir, '0.1.0')); json.version = '0.1.0'; fs.writeFileSync(path.join(sourceDir, '0.1.0', '.bower.json'), JSON.stringify(json, null, ' ')); delete json.version; fs.mkdirSync(path.join(sourceDir, 'foo')); json._target = 'foo'; fs.writeFileSync(path.join(sourceDir, 'foo', '.bower.json'), JSON.stringify(json, null, ' ')); fs.mkdirSync(path.join(sourceDir, 'bar')); json._target = 'bar'; fs.writeFileSync(path.join(sourceDir, 'bar', '.bower.json'), JSON.stringify(json, null, ' ')); fs.mkdirSync(path.join(sourceDir, 'aa')); json._target = 'aa'; fs.writeFileSync(path.join(sourceDir, 'aa', '.bower.json'), JSON.stringify(json, null, ' ')); delete json._target; fs.mkdirSync(sourceDir2); fs.mkdirSync(path.join(sourceDir2, '0.2.1')); json.version = '0.2.1'; fs.writeFileSync(path.join(sourceDir2, '0.2.1', '.bower.json'), JSON.stringify(json, null, ' ')); fs.mkdirSync(path.join(sourceDir2, '0.2.0')); json.name = 'abc'; json.version = '0.2.0'; fs.writeFileSync(path.join(sourceDir2, '0.2.0', '.bower.json'), JSON.stringify(json, null, ' ')); resolveCache.list() .then(function (entries) { var expectedJson; var bowerDir = path.join(__dirname, '../..'); expect(entries).to.be.an('array'); expectedJson = fs.readFileSync(path.join(__dirname, '../assets/resolve-cache/list-json-1.json')); expectedJson = expectedJson.toString(); mout.object.forOwn(entries, function (entry) { // Trim absolute bower path from json entry.canonicalDir = entry.canonicalDir.substr(bowerDir.length); // Convert windows \ paths to / entry.canonicalDir = entry.canonicalDir.replace(/\\/g, '/'); }); json = JSON.stringify(entries, null, ' '); expect(json).to.equal(expectedJson); next(); }) .done(); }); it('should ignore lurking files where dirs are expected', function (next) { var source = 'list-package-1'; var sourceId = md5(source); var sourceDir = path.join(cacheDir, sourceId); var json = { name: 'foo' }; // Create some versions fs.mkdirSync(sourceDir); fs.mkdirSync(path.join(sourceDir, '0.0.1')); json.version = '0.0.1'; fs.writeFileSync(path.join(sourceDir, '0.0.1', '.bower.json'), JSON.stringify(json, null, ' ')); // Create lurking files fs.writeFileSync(path.join(cacheDir, 'foo'), 'w00t'); fs.writeFileSync(path.join(cacheDir, '.DS_Store'), ''); fs.writeFileSync(path.join(sourceDir, 'foo'), 'w00t'); fs.writeFileSync(path.join(sourceDir, '.DS_Store'), ''); // It should not error out resolveCache.list() .then(function (entries) { expect(entries).to.be.an('array'); expect(entries.length).to.be(1); expect(entries[0].pkgMeta).to.eql(json); // Lurking file should have been removed expect(fs.existsSync(path.join(cacheDir, 'foo'))).to.be(false); expect(fs.existsSync(path.join(cacheDir, '.DS_Store'))).to.be(false); expect(fs.existsSync(path.join(sourceDir, 'foo'))).to.be(false); expect(fs.existsSync(path.join(sourceDir, '.DS_Store'))).to.be(false); next(); }) .done(); }); it('should delete entries if failed to read package meta', function (next) { var source = 'list-package-1'; var sourceId = md5(source); var sourceDir = path.join(cacheDir, sourceId); var json = { name: 'foo' }; // Create invalid versions fs.mkdirSync(sourceDir); fs.mkdirSync(path.join(sourceDir, '0.0.1')); fs.mkdirSync(path.join(sourceDir, '0.0.2')); fs.writeFileSync(path.join(sourceDir, '0.0.2', '.bower.json'), 'w00t'); // Create valid version fs.mkdirSync(path.join(sourceDir, '0.0.3')); json.version = '0.0.3'; fs.writeFileSync(path.join(sourceDir, '0.0.3', '.bower.json'), JSON.stringify(json, null, ' ')); // It should not error out resolveCache.list() .then(function (entries) { expect(entries).to.be.an('array'); expect(entries.length).to.be(1); expect(entries[0].pkgMeta).to.eql(json); // Packages with invalid metas should have been removed expect(fs.existsSync(path.join(sourceDir, '0.0.1'))).to.be(false); expect(fs.existsSync(path.join(sourceDir, '0.0.2'))).to.be(false); next(); }) .done(); }); }); describe('#clearRuntimeCache', function () { it('should clear the in-memory cache for all sources', function (next) { var source = String(Math.random()); var sourceId = md5(source); var sourceDir = path.join(cacheDir, sourceId); var source2 = String(Math.random()); var sourceId2 = md5(source2); var sourceDir2 = path.join(cacheDir, sourceId2); // Create some versions fs.mkdirSync(sourceDir); fs.mkdirSync(path.join(sourceDir, '0.0.1')); fs.mkdirSync(sourceDir2); fs.mkdirSync(path.join(sourceDir2, '0.0.2')); // Feed the cache resolveCache.versions(source) .then(function () { return resolveCache.versions(source2); }) .then(function () { // Create some more fs.mkdirSync(path.join(sourceDir, '0.0.3')); fs.mkdirSync(path.join(sourceDir2, '0.0.4')); // Reset cache ResolveCache.clearRuntimeCache(); }) .then(function () { return resolveCache.versions(source) .then(function (versions) { expect(versions).to.eql(['0.0.3', '0.0.1']); return resolveCache.versions(source2); }) .then(function (versions) { expect(versions).to.eql(['0.0.4', '0.0.2']); next(); }); }) .done(); }); }); });
var url = require('url'); var fs = require('fs'); var postcss = require('postcss'); var path = require('canonical-path'); module.exports = postcss.plugin('postcss-cachebuster', function (opts) { opts = opts || {}; return function (css) { var inputFile = css.source.input.file; css.eachDecl(function(declaration){ // only background, background-image declarations if (declaration.prop !== 'background' && declaration.prop !== 'background-image') return; // only url if (!/url\(('|")?[^'"\)]+('|")?\)/.test(declaration.value)) return; var background = /^(.*?)url\(('|")?([^'"\)]+)('|")?\)(.*?)$/.exec(declaration.value); var assetUrl = url.parse(background[3]); var inputPath = url.parse(inputFile); // only locals if (inputPath.host) return; if (assetUrl.pathname.indexOf('//') == 0) return; // resolve path var assetPath = path.dirname(inputPath.pathname) assetPath = assetPath+'/'+assetUrl.pathname; assetPath = path.normalize(assetPath); // cachebuster var mtime = fs.statSync(assetPath).mtime; var cachebuster = mtime.getTime().toString(16); // complete url with cachebuster if (assetUrl.search) { assetUrl.search = assetUrl.search + '&v' + cachebuster; } else { assetUrl.search = '?v' + cachebuster; } // replace old value declaration.value = background[1]+"url('"+url.format(assetUrl)+"')"+background[5]; }) }; });
var twilio = require('twilio'); var accountSid = 'ACd07fa19be220015c1f623bc38c1785e7'; var authToken = '78b4e06ced50c8cc150dbccbf0880ab9'; var client = new twilio.RestClient(accountSid, authToken); // Pass in parameters to the REST API using an object literal notation. The // REST client will handle authentication and response serialzation for you. client.sms.messages.create({ to:'+19162218736', from:'+12097819195', body:'Testing text message capabilities for app!' }, function(error, message) { // The HTTP request to Twilio will run asynchronously. This callback // function will be called when a response is received from Twilio // The "error" variable will contain error information, if any. // If the request was successful, this value will be "false" if (!error) { // The second argument to the callback will contain the information // sent back by Twilio for the request. In this case, it is the // information about the text messsage you just sent: console.log('Success! The SID for this SMS message is:'); console.log(message.sid); console.log('Message sent on:'); console.log(message.dateCreated); } else { console.log('Oops! There was an error.'); } });
function colorRect(topLeftX,topLeftY,boxWidth,boxHeight,fillColor) { ctx.fillStyle = fillColor; ctx.fillRect(topLeftX,topLeftY, boxWidth,boxHeight); } function drawBall(centerX,centerY,radius,fillColor) { ctx.fillStyle = fillColor; ctx.beginPath(); ctx.arc(centerX,centerY,10,0,Math.PI*2,true); ctx.fill(); } function colorText(showWords,textX,textY,fillColor,fontface,textAlign = 'left' ) { ctx.textAlign = textAlign; ctx.font = fontface; ctx.fillStyle = fillColor; ctx.fillText(showWords, textX, textY); }
/* Copyright 2008-2009 University of Cambridge Copyright 2008-2009 University of Toronto Licensed under the Educational Community License (ECL), Version 2.0 or the New BSD license. You may not use this file except in compliance with one these Licenses. You may obtain a copy of the ECL 2.0 License and BSD License at https://source.fluidproject.org/svn/LICENSE.txt */ /*global jQuery*/ var fluid_1_1 = fluid_1_1 || {}; var fluid = fluid || fluid_1_1; (function ($, fluid) { // $().fluid("selectable", args) // $().fluid("selectable".that() // $().fluid("pager.pagerBar", args) // $().fluid("reorderer", options) /** Create a "bridge" from code written in the Fluid standard "that-ist" style, * to the standard JQuery UI plugin architecture specified at http://docs.jquery.com/UI/Guidelines . * Every Fluid component corresponding to the top-level standard signature (JQueryable, options) * will automatically convert idiomatically to the JQuery UI standard via this adapter. * Any return value which is a primitive or array type will become the return value * of the "bridged" function - however, where this function returns a general hash * (object) this is interpreted as forming part of the Fluid "return that" pattern, * and the function will instead be bridged to "return this" as per JQuery standard, * permitting chaining to occur. However, as a courtesy, the particular "this" returned * will be augmented with a function that() which will allow the original return * value to be retrieved if desired. * @param {String} name The name under which the "plugin space" is to be injected into * JQuery * @param {Object} peer The root of the namespace corresponding to the peer object. */ fluid.thatistBridge = function (name, peer) { var togo = function(funcname) { var segs = funcname.split("."); var move = peer; for (var i = 0; i < segs.length; ++i) { move = move[segs[i]]; } var args = [this]; if (arguments.length === 2) { args = args.concat($.makeArray(arguments[1])); } var ret = move.apply(null, args); this.that = function() { return ret; } var type = typeof(ret); return !ret || type === "string" || type === "number" || type === "boolean" || ret && ret.length !== undefined? ret: this; }; $.fn[name] = togo; return togo; }; fluid.thatistBridge("fluid", fluid); fluid.thatistBridge("fluid_1_1", fluid_1_1); // Private constants. var NAMESPACE_KEY = "fluid-keyboard-a11y"; /** * Gets stored state from the jQuery instance's data map. */ var getData = function(target, key) { var data = $(target).data(NAMESPACE_KEY); return data ? data[key] : undefined; }; /** * Stores state in the jQuery instance's data map. Unlike jQuery's version, * accepts multiple-element jQueries. */ var setData = function(target, key, value) { $(target).each(function() { var data = $.data(this, NAMESPACE_KEY) || {}; data[key] = value; $.data(this, NAMESPACE_KEY, data); }); }; /** Global focus manager - makes use of jQuery delegate plugin if present, * detecting presence of "focusin" event. */ var lastFocusedElement = "disabled"; if ($.event.special["focusin"]) { lastFocusedElement = null; $(document).bind("focusin", function(event){ lastFocusedElement = event.target; }); } fluid.getLastFocusedElement = function () { if (lastFocusedElement === "disabled") { fluid.fail("Focus manager not enabled - please include jquery.delegate.js or equivalent for support of 'focusin' event"); } return lastFocusedElement; } /************************************************************************* * Tabindex normalization - compensate for browser differences in naming * and function of "tabindex" attribute and tabbing order. */ // -- Private functions -- var normalizeTabindexName = function() { return $.browser.msie ? "tabIndex" : "tabindex"; }; var canHaveDefaultTabindex = function(elements) { if (elements.length <= 0) { return false; } return $(elements[0]).is("a, input, button, select, area, textarea, object"); }; var getValue = function(elements) { if (elements.length <= 0) { return undefined; } if (!fluid.tabindex.hasAttr(elements)) { return canHaveDefaultTabindex(elements) ? Number(0) : undefined; } // Get the attribute and return it as a number value. var value = elements.attr(normalizeTabindexName()); return Number(value); }; var setValue = function(elements, toIndex) { return elements.each(function(i, item) { $(item).attr(normalizeTabindexName(), toIndex); }); }; // -- Public API -- /** * Gets the value of the tabindex attribute for the first item, or sets the tabindex value of all elements * if toIndex is specified. * * @param {String|Number} toIndex */ fluid.tabindex = function(target, toIndex) { target = $(target); if (toIndex !== null && toIndex !== undefined) { return setValue(target, toIndex); } else { return getValue(target); } }; /** * Removes the tabindex attribute altogether from each element. */ fluid.tabindex.remove = function(target) { target = $(target); return target.each(function(i, item) { $(item).removeAttr(normalizeTabindexName()); }); }; /** * Determines if an element actually has a tabindex attribute present. */ fluid.tabindex.hasAttr = function(target) { target = $(target); if (target.length <= 0) { return false; } var togo = target.map( function() { var attributeNode = this.getAttributeNode(normalizeTabindexName()); return attributeNode ? attributeNode.specified : false; } ); return togo.length === 1? togo[0] : togo; }; /** * Determines if an element either has a tabindex attribute or is naturally tab-focussable. */ fluid.tabindex.has = function(target) { target = $(target); return fluid.tabindex.hasAttr(target) || canHaveDefaultTabindex(target); }; var ENABLEMENT_KEY = "enablement"; /** Queries or sets the enabled status of a control. An activatable node * may be "disabled" in which case its keyboard bindings will be inoperable * (but still stored) until it is reenabled again. */ fluid.enabled = function(target, state) { target = $(target); if (state === undefined) { return getData(target, ENABLEMENT_KEY) !== false; } else { $("*", target).each(function() { if (getData(this, ENABLEMENT_KEY) !== undefined) { setData(this, ENABLEMENT_KEY, state); } else if (/select|textarea|input/i.test(this.nodeName)) { $(this).attr("disabled", !state); } }); setData(target, ENABLEMENT_KEY, state); } }; // Keyboard navigation // Public, static constants needed by the rest of the library. fluid.a11y = $.a11y || {}; fluid.a11y.orientation = { HORIZONTAL: 0, VERTICAL: 1, BOTH: 2 }; var UP_DOWN_KEYMAP = { next: $.ui.keyCode.DOWN, previous: $.ui.keyCode.UP }; var LEFT_RIGHT_KEYMAP = { next: $.ui.keyCode.RIGHT, previous: $.ui.keyCode.LEFT }; // Private functions. var unwrap = function(element) { return element.jquery ? element[0] : element; // Unwrap the element if it's a jQuery. }; var makeElementsTabFocussable = function(elements) { // If each element doesn't have a tabindex, or has one set to a negative value, set it to 0. elements.each(function(idx, item) { item = $(item); if (!item.fluid("tabindex.has") || item.fluid("tabindex") < 0) { item.fluid("tabindex", 0); } }); }; // Public API. /** * Makes all matched elements available in the tab order by setting their tabindices to "0". */ fluid.tabbable = function(target) { target = $(target); makeElementsTabFocussable(target); }; /*********************************************************************** * Selectable functionality - geometrising a set of nodes such that they * can be navigated (by setting focus) using a set of directional keys */ var CONTEXT_KEY = "selectionContext"; var NO_SELECTION = -32768; var cleanUpWhenLeavingContainer = function(selectionContext) { if (selectionContext.options.onLeaveContainer) { selectionContext.options.onLeaveContainer( selectionContext.selectables[selectionContext.activeItemIndex]); } else if (selectionContext.options.onUnselect) { selectionContext.options.onUnselect( selectionContext.selectables[selectionContext.activeItemIndex]); } if (!selectionContext.options.rememberSelectionState) { selectionContext.activeItemIndex = NO_SELECTION; } }; /** * Does the work of selecting an element and delegating to the client handler. */ var drawSelection = function(elementToSelect, handler) { if (handler) { handler(elementToSelect); } }; /** * Does does the work of unselecting an element and delegating to the client handler. */ var eraseSelection = function(selectedElement, handler) { if (handler && selectedElement) { handler(selectedElement); } }; var unselectElement = function(selectedElement, selectionContext) { eraseSelection(selectedElement, selectionContext.options.onUnselect); }; var selectElement = function(elementToSelect, selectionContext) { // It's possible that we're being called programmatically, in which case we should clear any previous selection. unselectElement(selectionContext.selectedElement(), selectionContext); elementToSelect = unwrap(elementToSelect); var newIndex = selectionContext.selectables.index(elementToSelect); // Next check if the element is a known selectable. If not, do nothing. if (newIndex === -1) { return; } // Select the new element. selectionContext.activeItemIndex = newIndex; drawSelection(elementToSelect, selectionContext.options.onSelect); }; var selectableFocusHandler = function(selectionContext) { return function(evt) { selectElement(evt.target, selectionContext); // Force focus not to bubble on some browsers. return evt.stopPropagation(); }; }; var selectableBlurHandler = function(selectionContext) { return function(evt) { unselectElement(evt.target, selectionContext); // Force blur not to bubble on some browsers. return evt.stopPropagation(); }; }; var reifyIndex = function(sc_that) { var elements = sc_that.selectables; if (sc_that.activeItemIndex >= elements.length) { sc_that.activeItemIndex = 0; } if (sc_that.activeItemIndex < 0 && sc_that.activeItemIndex !== NO_SELECTION) { sc_that.activeItemIndex = elements.length - 1; } if (sc_that.activeItemIndex >= 0) { $(elements[sc_that.activeItemIndex]).focus(); } }; var prepareShift = function(selectionContext) { unselectElement(selectionContext.selectedElement(), selectionContext); if (selectionContext.activeItemIndex === NO_SELECTION) { selectionContext.activeItemIndex = -1; } }; var focusNextElement = function(selectionContext) { prepareShift(selectionContext); ++selectionContext.activeItemIndex; reifyIndex(selectionContext); }; var focusPreviousElement = function(selectionContext) { prepareShift(selectionContext); --selectionContext.activeItemIndex; reifyIndex(selectionContext); }; var arrowKeyHandler = function(selectionContext, keyMap, userHandlers) { return function(evt) { if (evt.which === keyMap.next) { focusNextElement(selectionContext); evt.preventDefault(); } else if (evt.which === keyMap.previous) { focusPreviousElement(selectionContext); evt.preventDefault(); } }; }; var getKeyMapForDirection = function(direction) { // Determine the appropriate mapping for next and previous based on the specified direction. var keyMap; if (direction === fluid.a11y.orientation.HORIZONTAL) { keyMap = LEFT_RIGHT_KEYMAP; } else if (direction === fluid.a11y.orientation.VERTICAL) { // Assume vertical in any other case. keyMap = UP_DOWN_KEYMAP; } return keyMap; }; var tabKeyHandler = function(selectionContext) { return function(evt) { if (evt.which !== $.ui.keyCode.TAB) { return; } cleanUpWhenLeavingContainer(selectionContext); // Catch Shift-Tab and note that focus is on its way out of the container. if (evt.shiftKey) { selectionContext.focusIsLeavingContainer = true; } }; }; var containerFocusHandler = function(selectionContext) { return function(evt) { var shouldOrig = selectionContext.options.autoSelectFirstItem; var shouldSelect = typeof(shouldOrig) === "function" ? shouldOrig() : shouldOrig; // Override the autoselection if we're on the way out of the container. if (selectionContext.focusIsLeavingContainer) { shouldSelect = false; } // This target check works around the fact that sometimes focus bubbles, even though it shouldn't. if (shouldSelect && evt.target === selectionContext.container.get(0)) { if (selectionContext.activeItemIndex === NO_SELECTION) { selectionContext.activeItemIndex = 0; } $(selectionContext.selectables[selectionContext.activeItemIndex]).focus(); } // Force focus not to bubble on some browsers. return evt.stopPropagation(); }; }; var containerBlurHandler = function(selectionContext) { return function(evt) { selectionContext.focusIsLeavingContainer = false; // Force blur not to bubble on some browsers. return evt.stopPropagation(); }; }; var makeElementsSelectable = function(container, defaults, userOptions) { var options = $.extend(true, {}, defaults, userOptions); var keyMap = getKeyMapForDirection(options.direction); var selectableElements = options.selectableElements? options.selectableElements : container.find(options.selectableSelector); // Context stores the currently active item(undefined to start) and list of selectables. var that = { container: container, activeItemIndex: NO_SELECTION, selectables: selectableElements, focusIsLeavingContainer: false, options: options }; that.selectablesUpdated = function(focusedItem) { // Remove selectables from the tab order and add focus/blur handlers if (typeof(that.options.selectablesTabindex) === "number") { that.selectables.fluid("tabindex", that.options.selectablesTabindex); } that.selectables.unbind("focus." + NAMESPACE_KEY); that.selectables.unbind("blur." + NAMESPACE_KEY); that.selectables.bind("focus."+ NAMESPACE_KEY, selectableFocusHandler(that)); that.selectables.bind("blur." + NAMESPACE_KEY, selectableBlurHandler(that)); if (focusedItem) { selectElement(focusedItem, that); } else { reifyIndex(that); } }; that.refresh = function() { if (!that.options.selectableSelector) { throw("Cannot refresh selectable context which was not initialised by a selector"); } that.selectables = container.find(options.selectableSelector); that.selectablesUpdated(); }; that.selectedElement = function() { return that.activeItemIndex < 0? null : that.selectables[that.activeItemIndex]; }; // Add various handlers to the container. if (keyMap) { container.keydown(arrowKeyHandler(that, keyMap)); } container.keydown(tabKeyHandler(that)); container.focus(containerFocusHandler(that)); container.blur(containerBlurHandler(that)); that.selectablesUpdated(); return that; }; /** * Makes all matched elements selectable with the arrow keys. * Supply your own handlers object with onSelect: and onUnselect: properties for custom behaviour. * Options provide configurability, including direction: and autoSelectFirstItem: * Currently supported directions are jQuery.a11y.directions.HORIZONTAL and VERTICAL. */ fluid.selectable = function(target, options) { target = $(target); var that = makeElementsSelectable(target, fluid.selectable.defaults, options); setData(target, CONTEXT_KEY, that); return that; }; /** * Selects the specified element. */ fluid.selectable.select = function(target, toSelect) { $(toSelect).focus(); }; /** * Selects the next matched element. */ fluid.selectable.selectNext = function(target) { target = $(target); focusNextElement(getData(target, CONTEXT_KEY)); }; /** * Selects the previous matched element. */ fluid.selectable.selectPrevious = function(target) { target = $(target); focusPreviousElement(getData(target, CONTEXT_KEY)); }; /** * Returns the currently selected item wrapped as a jQuery object. */ fluid.selectable.currentSelection = function(target) { target = $(target); var that = getData(target, CONTEXT_KEY); return $(that.selectedElement()); }; fluid.selectable.defaults = { direction: fluid.a11y.orientation.VERTICAL, selectablesTabindex: -1, autoSelectFirstItem: true, rememberSelectionState: true, selectableSelector: ".selectable", selectableElements: null, onSelect: null, onUnselect: null, onLeaveContainer: null }; /******************************************************************** * Activation functionality - declaratively associating actions with * a set of keyboard bindings. */ var checkForModifier = function(binding, evt) { // If no modifier was specified, just return true. if (!binding.modifier) { return true; } var modifierKey = binding.modifier; var isCtrlKeyPresent = modifierKey && evt.ctrlKey; var isAltKeyPresent = modifierKey && evt.altKey; var isShiftKeyPresent = modifierKey && evt.shiftKey; return isCtrlKeyPresent || isAltKeyPresent || isShiftKeyPresent; }; /** Constructs a raw "keydown"-facing handler, given a binding entry. This * checks whether the key event genuinely triggers the event and forwards it * to any "activateHandler" registered in the binding. */ var makeActivationHandler = function(binding) { return function(evt) { var target = evt.target; if (!fluid.enabled(evt.target)) { return; } // The following 'if' clause works in the real world, but there's a bug in the jQuery simulation // that causes keyboard simulation to fail in Safari, causing our tests to fail: // http://ui.jquery.com/bugs/ticket/3229 // The replacement 'if' clause works around this bug. // When this issue is resolved, we should revert to the original clause. // if (evt.which === binding.key && binding.activateHandler && checkForModifier(binding, evt)) { var code = evt.which? evt.which : evt.keyCode; if (code === binding.key && binding.activateHandler && checkForModifier(binding, evt)) { var event = $.Event("fluid-activate"); $(evt.target).trigger(event, [binding.activateHandler]); if (event.isDefaultPrevented()) { evt.preventDefault(); } } }; }; var makeElementsActivatable = function(elements, onActivateHandler, defaultKeys, options) { // Create bindings for each default key. var bindings = []; $(defaultKeys).each(function(index, key) { bindings.push({ modifier: null, key: key, activateHandler: onActivateHandler }); }); // Merge with any additional key bindings. if (options && options.additionalBindings) { bindings = bindings.concat(options.additionalBindings); } setData(elements, ENABLEMENT_KEY, true); // Add listeners for each key binding. for (var i = 0; i < bindings.length; ++ i) { var binding = bindings[i]; elements.keydown(makeActivationHandler(binding)); } elements.bind("fluid-activate", function(evt, handler) { handler = handler || onActivateHandler; return handler? handler(evt): null; }); }; /** * Makes all matched elements activatable with the Space and Enter keys. * Provide your own handler function for custom behaviour. * Options allow you to provide a list of additionalActivationKeys. */ fluid.activatable = function(target, fn, options) { target = $(target); makeElementsActivatable(target, fn, fluid.activatable.defaults.keys, options); }; /** * Activates the specified element. */ fluid.activate = function(target) { $(target).trigger("fluid-activate"); }; // Public Defaults. fluid.activatable.defaults = { keys: [$.ui.keyCode.ENTER, $.ui.keyCode.SPACE] }; })(jQuery, fluid_1_1);
var structCS__AUDIODEVICE = [ [ "device_id", "structCS__AUDIODEVICE.html#acaaaa3af3e56f33d6c83612eecc5af5b", null ], [ "device_name", "structCS__AUDIODEVICE.html#a0bc59d45f53cad0863859f38e573c9a2", null ], [ "isOutput", "structCS__AUDIODEVICE.html#abe34361d001528d150f4c5976d195d41", null ], [ "max_nchnls", "structCS__AUDIODEVICE.html#ad290a89b60a4119d913ca98b765e3a2c", null ], [ "rt_module", "structCS__AUDIODEVICE.html#a2f6742e5f4b735f67adb0a61a0548ed2", null ] ];
import Bubble from './bubble'; import * as types from'../../../common/constants'; class CommonBubble extends Bubble { constructor({ context, levelConfig }) { super(); this.context = context; this.radius = Math.floor(Math.random() * 10) + 5; this.maxY = types.CANVAS_HEIGHT - levelConfig.WATER_BORDER_BOTTOM - this.radius; this.minY = levelConfig.WATER_BORDER_TOP + this.radius; this.x = types.OBJECT_INIT_X; this.y = Math.floor(Math.random() * (this.maxY - this.minY + 1) + this.minY); this.xSpeed = Math.floor(Math.random() * 3) + 1; this.ySpeed = Math.floor(Math.random() * 2) + 1; this.xDirection = 'left'; this.yDirection = null; this.borderColor = 'black'; this.background = 'white'; this.canChangeDirection = true; } } export default (data) => { const random = Math.floor(Math.random() * 100) + 1; return (random < 5) ? new CommonBubble(data) : null ; };
var Bookshelf = require('bookshelf'), Q = require('q'), uuid = require('node-uuid'), Mailgun = require('mailgun').Mailgun; var conf = require('./config'); var DB = Bookshelf.initialize(conf.database); var Participant = DB.Model.extend({ tableName: 'participants' }); var model = new Participant({email: process.argv[2], name: process.argv[3], hash: uuid.v4()}); model.save().then(function() { if (process.env.MAILGUN_API_KEY) { var mg = new Mailgun(process.env.MAILGUN_API_KEY); mg.sendText('Turku Agile Day <info@turkuagileday.fi>', model.get('email'), 'Choose your workshops', 'Hi there!\nYou can choose in which workshops to participate by following the following link: http://localhost:1337/' + model.get('hash') + '\n\nBest regards,\nTurku Agile Day Organizers', function() { console.log('Check your email for instructions'); process.exit(0); }); } else { console.log('Login at http://localhost:1337/%s', model.get('hash')); process.exit(0); } });
import MonsterData from '../../data/MonsterData'; import MonsterEncounterData from '../../data/MonsterEncounterData'; import MonsterEncounterStorageService from "./MonsterEncounterStorageService"; import MonsterListData from '../../data/MonsterListData'; import Prefix from "./Prefix"; import Q from "./Q"; import type StorageData from "../../data/StorageData"; import SyncStorageService from "./SyncStorageService"; const getCurrentOrderValue = function (encounterId: string, storageData: StorageData): number { const lists = MonsterEncounterStorageService.getEncounterLists(encounterId, storageData); if (!lists || lists.length === 0) return 0; let maxOrder = 0; lists.forEach(list => { if (maxOrder < list.order) maxOrder = list.order; }); return maxOrder + 1; }; const getCurrentOrderWithEncounter = function (encounter: MonsterEncounterData): number { if (!encounter.lists || encounter.lists.length === 0) return 0; const lastList = encounter.lists[encounter.lists.length - 1]; return lastList.order + 1; }; class MonsterListStorageService { static findList(storageId: string, storageData: StorageData): MonsterListData { return SyncStorageService.findSingle(storageData, Q.clazz("MonsterListData"), Q.eq("storageId", storageId)); } static findListGroupedByEncounter(storageData: StorageData): Promise<Map<string, MonsterListData[]>> { const listMap: Map<string, MonsterListData[]> = SyncStorageService.findGroupedBy(storageData, "encounterId", Q.clazz("MonsterListData")); if (listMap.length === 0) { return Promise.resolve(listMap); } // check existing ordering info const firstList: MonsterListData = SyncStorageService.findSingle(storageData, Q.clazz("MonsterListData")); let checkOrderPromise = Promise.resolve(); if (firstList && (firstList.order === null || firstList.order === undefined)) { const toSaveLists = []; for (var encounterId of listMap.keys()) { let lists = listMap.get(encounterId); if (!lists || lists.length === 0) continue; lists = lists.sort((a: MonsterListData, b: MonsterListData) => a.name.localeCompare(b.name)); lists.forEach((list, idx) => { list.order = idx; toSaveLists.push(list); }); } checkOrderPromise = SyncStorageService.updateData(toSaveLists); } return checkOrderPromise.then(() => listMap); } static getListMonsters(listId: string, storageData: StorageData): MonsterData[] { return SyncStorageService.find(storageData, Q.clazz("MonsterData"), Q.eq("listId", listId)); } static createList(name: string, monsterId: string, encounterId: string, storageData: StorageData): Promise<MonsterListData> { const newList = new MonsterListData(null, encounterId, monsterId, name, 0); newList.order = getCurrentOrderValue(encounterId, storageData); return SyncStorageService.createData("MonsterListData", newList); } static createCustomList(name: string, hpexp: string, encounter: MonsterEncounterData): Promise<MonsterListData> { const newLisId = Prefix.createStorageId("MonsterListData"); const customMonsterId = Prefix.createCustomMonsterId(); const newList = new MonsterListData(newLisId, encounter.storageId, customMonsterId, name, 0); newList.order = getCurrentOrderWithEncounter(encounter); newList.hpexp = hpexp; return SyncStorageService.createData(null, newList); } static deleteList(list: MonsterListData): Promise { if (!list) return Promise.resolve(); const toDelete = []; toDelete.push(list); if (list.monsters) list.monsters.forEach(monster => toDelete.push(monster)); return SyncStorageService.deleteData(toDelete); } } export default MonsterListStorageService;
import { unstable_batchedUpdates } from 'preact/compat'; describe('unstable_batchedUpdates', () => { it('should call the callback', () => { const spy = sinon.spy(); unstable_batchedUpdates(spy); expect(spy).to.be.calledOnce; }); it('should call callback with only one arg', () => { const spy = sinon.spy(); unstable_batchedUpdates(spy, 'foo', 'bar'); expect(spy).to.be.calledWithExactly('foo'); }); });
var account_app = account_app || {}; (function(){ var Action_btn = account_app.Action_btn = React.createClass({displayName: "Action_btn", handleClick:function(){ this.props.perform_action(); }, render:function(){ return (React.createElement("button", {className: "btn btn-primary", onClick: this.handleClick}, this.props.content)); } }); var Username_field = account_app.Username_field = React.createClass({displayName: "Username_field", handleChange:function(){ this.props.update_username(this.refs.username.value); }, render:function(){ return (React.createElement("input", {className: "input-base input-username", ref: "username", placeholder: "Input Username", onChange: this.handleChange})); } }); var Password_field = account_app.Password_field = React.createClass({displayName: "Password_field", handleChange:function(){ this.props.update_password(this.refs.pass.value); }, render:function(){ return (React.createElement("input", {className: "input-base input-password", ref: "pass", type: "password", placeholder: "Input password", onChange: this.handleChange})) } }); account_app.Login_window = React.createClass({displayName: "Login_window", render:function(){ } }); })();
requirejs.config({ paths: { 'text': '../lib/require/text', 'durandal':'../lib/durandal/js', 'plugins' : '../lib/durandal/js/plugins', 'transitions' : '../lib/durandal/js/transitions', 'knockout': '../lib/knockout/knockout-2.3.0', 'jquery': '../lib/jquery/jquery-1.9.1' } }); define(function (require) { var system = require('durandal/system'), app = require('durandal/app'); system.debug(true); app.title = 'Durandal Starter Kit'; app.configurePlugins({ router:true, dialog: true }); app.start().then(function() { app.setRoot('shell'); }); });
// pages/movies/movie.js Page({ /** * 页面的初始数据 */ data: { }, /** * 生命周期函数--监听页面加载 */ onLoad: function (options) { }, /** * 生命周期函数--监听页面初次渲染完成 */ onReady: function () { }, /** * 生命周期函数--监听页面显示 */ onShow: function () { }, /** * 生命周期函数--监听页面隐藏 */ onHide: function () { }, /** * 生命周期函数--监听页面卸载 */ onUnload: function () { }, /** * 页面相关事件处理函数--监听用户下拉动作 */ onPullDownRefresh: function () { }, /** * 页面上拉触底事件的处理函数 */ onReachBottom: function () { }, /** * 用户点击右上角分享 */ onShareAppMessage: function () { } })
/*$(document).ready(function(){ $("#checkout").click(function () { var dat = []; for (var counter = 0; counter < shoppingCart.length; counter++) { dat.push({ name: shoppingCart[counter][0], amount: shoppingCart[counter][1] }); } console.log(dat); /*hide("#invoice-card"); hide(floatingButton); updateShoppingCartNumber(); $.post("?url=Foodmenu/makeOrder", { ss: JSON.stringify(dat), address:$("#address").val(), paymentmethod:$("#payment-method-select").val(), credit_number:$("#credit-card-number-text").val(), cvc:$("#cvc-text").val(), expire_date:$("#expire-date-text").val(), }, function (data) { console.log(data); }); }); });*/
export const encode = s => encodeURIComponent(String(s || "").replace(/\s/g, "_")).replace( /"%27"/g, "%20" ); export const decode = s => decodeURIComponent(String(s || "").replace(/(\s|_|\+)/g, " ")).replace( /%20/g, "'" );
import ActionTypes from "./actionTypes"; // Action to hide the panel export function hide() { return { type: ActionTypes.Hide.Panel, visible: false }; } // Action to show the panel export function show() { return { type: ActionTypes.Show.Panel, visible: true }; }
import { isSelected } from '../../src/utils/selection' describe('isSelected', () => { test('it returns true if it is the same object by reference', () => { const value = { x: { sample: 'value' }, y: 1, } expect(isSelected(value, value)).toBeTruthy() }) test('it returns true if it is the same object by equality', () => { const value = { x: { sample: 'value' }, y: 1, } const equalivalentValue = { x: { sample: 'value' }, y: 1, } expect(isSelected(value, equalivalentValue)).toBeTruthy() }) test('it returns false if the object is not equal', () => { const value = { x: { sample: 'value' }, y: 1, } const nonEqualivalentValue = { x: { sample: 'value' }, y: 2, } expect(isSelected(value, nonEqualivalentValue)).toBeFalsy() }) })
module.exports = /******/ (function(modules) { // webpackBootstrap /******/ // The module cache /******/ var installedModules = {}; /******/ // The require function /******/ function __webpack_require__(moduleId) { /******/ // Check if module is in cache /******/ if(installedModules[moduleId]) /******/ return installedModules[moduleId].exports; /******/ // Create a new module (and put it into the cache) /******/ var module = installedModules[moduleId] = { /******/ exports: {}, /******/ id: moduleId, /******/ loaded: false /******/ }; /******/ // Execute the module function /******/ modules[moduleId].call(module.exports, module, module.exports, __webpack_require__); /******/ // Flag the module as loaded /******/ module.loaded = true; /******/ // Return the exports of the module /******/ return module.exports; /******/ } /******/ // expose the modules object (__webpack_modules__) /******/ __webpack_require__.m = modules; /******/ // expose the module cache /******/ __webpack_require__.c = installedModules; /******/ // __webpack_public_path__ /******/ __webpack_require__.p = ""; /******/ // Load entry module and return exports /******/ return __webpack_require__(0); /******/ }) /************************************************************************/ /******/ ({ /***/ 0: /***/ (function(module, exports, __webpack_require__) { __webpack_require__(248); module.exports = __webpack_require__(248); /***/ }), /***/ 248: /***/ (function(module, exports) { (function( window, undefined ) { kendo.cultures["mn"] = { name: "mn", numberFormat: { pattern: ["-n"], decimals: 2, ",": " ", ".": ",", groupSize: [3], percent: { pattern: ["-n %","n %"], decimals: 2, ",": " ", ".": ",", groupSize: [3], symbol: "%" }, currency: { name: "", abbr: "", pattern: ["-n $","n $"], decimals: 2, ",": " ", ".": ",", groupSize: [3], symbol: "₮" } }, calendars: { standard: { days: { names: ["Ням","Даваа","Мягмар","Лхагва","Пүрэв","Баасан","Бямба"], namesAbbr: ["Ня","Да","Мя","Лха","Пү","Ба","Бя"], namesShort: ["Ня","Да","Мя","Лх","Пү","Ба","Бя"] }, months: { names: ["1 дүгээр сар","2 дугаар сар","3 дугаар сар","4 дүгээр сар","5 дугаар сар","6 дугаар сар","7 дугаар сар","8 дугаар сар","9 дүгээр сар","10 дугаар сар","11 дүгээр сар","12 дугаар сар"], namesAbbr: ["1-р сар","2-р сар","3-р сар","4-р сар","5-р сар","6-р сар","7-р сар","8-р сар","9-р сар","10-р сар","11-р сар","12-р сар"] }, AM: [""], PM: [""], patterns: { d: "yyyy-MM-dd", D: "yyyy 'оны' M'-р сарын' d. dddd 'гариг'.", F: "yyyy 'оны' M'-р сарын' d. dddd 'гариг'. HH:mm:ss", g: "yyyy-MM-dd HH:mm", G: "yyyy-MM-dd HH:mm:ss", m: "MMMM d.", M: "MMMM d.", s: "yyyy'-'MM'-'dd'T'HH':'mm':'ss", t: "HH:mm", T: "HH:mm:ss", u: "yyyy'-'MM'-'dd HH':'mm':'ss'Z'", y: "yyyy 'оны' MMMM", Y: "yyyy 'оны' MMMM" }, "/": "-", ":": ":", firstDay: 1 } } } })(this); /***/ }) /******/ });
// Copyright (c) 2012 Ecma International. All rights reserved. // Ecma International makes this code available under the terms and conditions set // forth on http://hg.ecmascript.org/tests/test262/raw-file/tip/LICENSE (the // "Use Terms"). Any redistribution of this code must retain the above // copyright and this notice and otherwise comply with the Use Terms. /*--- es5id: 15.4.4.19-8-b-10 description: > Array.prototype.map - deleting property of prototype causes prototype index property not to be visited on an Array-like Object includes: [runTestCase.js] ---*/ function testcase() { function callbackfn(val, idx, obj) { return idx === 1 && typeof val === "undefined"; } var obj = { 2: 2, length: 20 }; Object.defineProperty(obj, "0", { get: function () { delete Object.prototype[1]; return 0; }, configurable: true }); try { Object.prototype[1] = 1; var testResult = Array.prototype.map.call(obj, callbackfn); return testResult.length === 20 && typeof testResult[1] === "undefined"; } finally { delete Object.prototype[1]; } } runTestCase(testcase);
'use strict'; class Store { constructor(game, type) { this.game = game; this.type = type; } draw(context, x, y) { context.fillStyle = 'green'; context.fillRect(x, y, 100, 100); } } export default Store;
'use strict'; //# sourceMappingURL=Transaction.js.map
import React, { PropTypes } from 'react'; import { Provider } from 'react-redux'; import { Router } from 'react-router'; import routes from './routes'; let hmrKey = Math.random(); const Root = ({ store, history }) => ( <Provider store={store}> <Router key={hmrKey} history={history}> {routes} </Router> </Provider> ); if (module.hot) { hmrKey = Math.random(); } Root.propTypes = { store: PropTypes.object.isRequired, history: PropTypes.object.isRequired, }; export default Root;
module.exports = function(grunt) { grunt.initConfig({ pkg: grunt.file.readJSON('package.json'), paths: { assets: { js: './resources/assets/js/', less: './resources/assets/less/', vendor: './vendor/' }, js: './public/assets/js/', css: './public/assets/css/', fonts: './public/assets/fonts/' }, // Environment Settings ngconstant: { // Options for all targets options: { space: ' ', wrap: '"use strict";\n\n {%= __ngModule %}', name: 'config', }, // Environment targets development: { options: { dest: '<%= paths.assets.js %>config.js' }, constants: { ENV: { name: 'development', apiEndpoint: 'http://LOCALPATH/public/api/', baseUrl: 'http://LOCALPATH/public/', googleMapsKey: 'GOOGLE_MAPS_KEY' } } }, production: { options: { dest: '<%= paths.assets.js %>config.js' }, constants: { ENV: { name: 'production', apiEndpoint: 'http://PRODPATH', baseUrl: 'http://PRODPATH', googleMapsKey: 'GOOGLE_MAPS_KEY' } } }, staging: { options: { dest: '<%= paths.assets.js %>config.js' }, constants: { ENV: { name: 'staging', apiEndpoint: 'http://STAGINGPATH/api/', baseUrl: 'http://STAGINGPATH', googleMapsKey: 'GOOGLE_MAPS_KEY' } } } }, copy: { main: { expand: true, cwd: '<%= paths.assets.vendor %>fonts/', src: '**', dest: '<%= paths.fonts %>', flatten: true, filter: 'isFile', }, variables: { expand: true, cwd: '<%= paths.assets.vendor %>bootstrap/less/', src: 'variables.less', dest: '<%= paths.assets.css %>', flatten: true, filter: 'isFile', } }, concat: { options: { separator: ';' }, frontend: { src: [ '<%= paths.assets.vendor %>components/jquery/jquery.js', '<%= paths.assets.vendor %>bower_components/moment/min/moment.min.js', '<%= paths.assets.vendor %>twitter/bootstrap/dist/js/bootstrap.js', '<%= paths.assets.vendor %>modernizr/modernizr.js', '<%= paths.assets.vendor %>angular/angular.js', '<%= paths.assets.vendor %>bower_components/angular-google-maps/dist/angular-google-maps.js', '<%= paths.assets.vendor %>bower_components/eonasdan-bootstrap-datetimepicker/build/js/bootstrap-datetimepicker.min.js', '<%= paths.assets.vendor %>angular/angular-animate.js', '<%= paths.assets.vendor %>angular/angular-ui-router.min.js', '<%= paths.assets.vendor %>bower_components/textAngular/src/textAngularSetup.js', '<%= paths.assets.vendor %>bower_components/textAngular/src/textAngular-sanitize.js', '<%= paths.assets.vendor %>bower_components/textAngular/src/textAngular.js', '<%= paths.assets.vendor %>bower_components/lodash/dist/lodash.js', '<%= paths.assets.vendor %>bower_components/ng-file-upload/angular-file-upload-shim.js', '<%= paths.assets.vendor %>bower_components/ng-file-upload/angular-file-upload.js', '<%= paths.assets.vendor %>bower_components/angular-loading-bar/build/loading-bar.js', '<%= paths.assets.vendor %>bower_components/ngInfiniteScroll/build/ng-infinite-scroll.js', '<%= paths.assets.vendor %>bower_components/angular-bootstrap/ui-bootstrap-tpls.js', '<%= paths.assets.vendor %>bower_components/bootbox/bootbox.js', '<%= paths.assets.vendor %>bower_components/ngBootbox/dist/ngBootbox.js', '<%= paths.assets.js %>**/*.js', '!<%= paths.assets.js %>admin.js' ], dest: '<%= paths.js %>all.js', }, admin: { src: [ '<%= paths.assets.vendor %>bower_components/tinymce/tinymce.js', '<%= paths.assets.vendor %>bower_components/angular-ui-tinymce/src/tinymce.js', '<%= paths.assets.js %>**/admin.js' ], dest: '<%= paths.js %>admin.js', } }, less: { development: { options: { compress: false, }, files: { "<%= paths.css %>all.css" : "<%= paths.assets.less %>bootstrap.less" } }, production: { options: { cleancss: true, compress: true, }, files: { "<%= paths.css %>all.min.css" : "<%= paths.assets.less %>bootstrap.less" } } }, uglify: { options: { mangle: false, preserveComments: false, sourceMap: true }, frontend: { files: { '<%= paths.js %>all.min.js' : '<%= paths.js %>all.js', '<%= paths.js %>admin.min.js' : '<%= paths.js %>admin.js', } }, }, cachebreaker: { dev: { options: { match: ['all.min.js'], replacement: 'md5', src: { path: 'public/assets/js/all.min.js' } }, files: { src: ['app/views/includes/head.blade.php'] } } }, phpunit: { classes: { dir: 'tests/' }, options: { bin: 'vendor/bin/phpunit', colors: true } }, autoprefixer: { options: { browsers: ['last 2 versions'] }, dist: { files: { "<%= paths.css %>all.css": "<%= paths.css %>all.css", "<%= paths.css %>all.min.css": "<%= paths.css %>all.min.css" } } }, watch : { less: { files: ['<%= paths.assets.less %>*.less', '<%= paths.assets.less %>less-files/*.less'], tasks: ['less', 'autoprefixer'], options: { livereload: true } }, scripts: { files: ['<%= paths.assets.js %>/**/*.js'], tasks: ['jshint'], options: { livereload: true, spawn: false, }, tasks: ['concat','uglify'] }, tests: { files: ['app/views/*.php', 'resources/views/**/*'] //tasks: ['phpunit'] } } }); // Load Plugins grunt.loadNpmTasks('grunt-contrib-concat'); grunt.loadNpmTasks('grunt-contrib-watch'); grunt.loadNpmTasks('grunt-contrib-less'); grunt.loadNpmTasks('grunt-contrib-uglify'); grunt.loadNpmTasks('grunt-contrib-copy'); grunt.loadNpmTasks('grunt-ng-constant'); grunt.loadNpmTasks('grunt-phpunit'); grunt.loadNpmTasks('grunt-autoprefixer'); grunt.loadNpmTasks('grunt-cache-breaker'); // Task list grunt.registerTask('prod', ['ngconstant:production','copy','less','concat','uglify','autoprefixer','cachebreaker']); grunt.registerTask('stage', ['ngconstant:staging','copy','less','concat','uglify','autoprefixer','cachebreaker']); grunt.registerTask('dev', ['ngconstant:development','concat','uglify','watch']); };
/** * Karma Listener listening for CucumberJS events * * @author Benjamin Nowack <mail@bnowack.de> * * @param {module:karma} karma - Karma * @returns {KarmaCukesListener} */ var KarmaCukesListener = function(karma) { /** * Initialises the listener */ this.init = function() { this.karma = karma; this.feature = null; this.scenario = null; this.step = null; this.stepCount = 0; // don't let errors cause Karma to exit window.onerror = $.proxy(this.onError, this); }; /* * Registers event handlers for cucumber events * * Available events: * * * BeforeFeatures * * BeforeFeature * * Background * * BeforeScenario * * BeforeStep * * StepResult * * AfterStep * * ScenarioResult * * AfterScenario * * AfterFeature * * FeaturesResult * * AfterFeatures * * @param {module:cucumber/runtime/ast_tree_walker/event.js} event - Cucumber event * @param {function} callback - Callback for cucumber's AST walker */ this.hear = function (event, defaultTimeout, callback) { var eventName = event.getName(); var methodName = 'on' + eventName; if (this[methodName]) { this[methodName](event); } callback(); }; /** * Initializes the listener before any features are run * * @param {module:cucumber/runtime/ast_tree_walker/event.js} event - Cucumber event */ this.onBeforeFeatures = function(event) { this.init(); }; /** * Sets the current feature reference * * @param {module:cucumber/runtime/ast_tree_walker/event.js} event - Cucumber event */ this.onBeforeFeature = function(event) { var feature = event.getPayload(); this.feature = { id: feature.getName().toLowerCase().replace(/\s+/g, '-'), uri: feature.getUri().replace(/^(.*\/(base)\/)/, ''), // remove leading path noise name: feature.getName(), description: feature.getDescription(), line: feature.getLine(), keyword: feature.getKeyword(), tags: feature.getTags().map(function(tag) { return { name: tag.getName(), line: tag.getLine() }; }) }; }; /** * Sets the current scenario reference * * @param {module:cucumber/runtime/ast_tree_walker/event.js} event - Cucumber event */ this.onBeforeScenario = function(event) { var scenario = event.getPayload(); this.scenario = { id: this.feature.id + ';' + scenario.getName().toLowerCase().replace(/\s+/g, '-'), name: scenario.getName(), line: scenario.getLine(), keyword: 'Scenario', description: scenario.getDescription(), type: 'scenario', tags: scenario.getTags().map(function(tag) { return { name: tag.getName(), line: tag.getLine() }; }), examples: []// does not seem to be fillable via CucumberJS as outlines are split into individual scenarios }; }; /** * Sets the current step reference * * @param {module:cucumber/runtime/ast_tree_walker/event.js} event - Cucumber event */ this.onBeforeStep = function(event) { var step = event.getPayload(); this.step = { keyword: step.getKeyword(), name: step.getName(), line: step.getLine(), //hidden: step.isHidden(), match: { location: step.getUri() + ':' + step.getLine() }, result: { status: null, error_message: '', duration: 0 } }; }; /** * Creates a step/spec result and passes it to karma (which passes it to registered reporters) * * @param {module:cucumber/runtime/ast_tree_walker/event.js} event - Cucumber event */ this.onStepResult = function(event) { var stepResult = event.getPayload(); // don't report hook results if (this.isHook(stepResult.getStep())) { return; } var karmaResult = { feature: this.feature, scenario: this.scenario, step: this.step, // add some standard props for other reporters that rely on them (e.g. karma-junit-reporter) suite: [this.feature.name + ': ' + this.scenario.name], description: this.step.keyword + this.step.name, log: [], time: (stepResult.getDuration() || 0) / 1000000 }; // match.location var stepDefinition = stepResult.getStepDefinition(); if (stepDefinition && stepDefinition.getUri() !== 'unknown') { karmaResult.step.match.location = stepDefinition.getUri() + ':' + stepDefinition.getLine(); } karmaResult.step.match.location = karmaResult.step.match.location .replace(/^(.*\/(base)\/)/, '') // remove leading path noise .replace(/^(.*\/(absolute)\/)/, '/') // remove leading path noise .replace(/\?[^\:]+/g, '') // remove query strings ; // result.status karmaResult.step.result.status = stepResult.getStatus(); // result.duration karmaResult.step.result.duration = stepResult.getDuration() || 0; // error message if (karmaResult.step.result.status === 'failed') { var failureException = stepResult.getFailureException(); var stack = ''; if (failureException && typeof failureException.stack === 'string') { stack = failureException.stack; } else if (failureException && failureException.message && failureException instanceof Error) { stack = failureException.message; } else if (failureException && typeof failureException === 'string') { stack = failureException; } karmaResult.step.result.error_message += stack .replace(/^(.*\/(base)\/)/gm, '') // remove leading path noise .replace(/^(.*\/(absolute)\/)/gm, '/') // remove leading path noise .replace(/^(.*\/release\/cucumber.js.*$)/gm, '') // cucumberjs entries .replace(/\?[^\:]+/g, '') // remove query strings .replace(/\n*$/, '') // remove trailing line-breaks ; } // attachments var attachments = stepResult.getAttachments(); if (attachments && attachments.length) { karmaResult.step.embeddings = []; attachments.forEach(function (attachment) { karmaResult.step.embeddings.push({ mime_type: attachment.getMimeType(), data: base64encode(attachment.getData()) }); }); } // report step count to karma this.karma.info({ total: ++this.stepCount }); // inject karma result keywords to trigger correct exit code karmaResult.success = (karmaResult.step.result.status.match(/(passed)/)); karmaResult.skipped = (karmaResult.step.result.status.match(/(skipped|pending|undefined|ambiguous)/)); // pass result to all registered karma reporters this.karma.result(karmaResult);// triggers `reporter.onSpecComplete(browser, karmaResult)` }; /** * Cleans up object references */ onAfterFeatures = function() { this.feature = null; this.scenario = null; this.step = null; this.stepCount = 0; }; /** * Adds script errors to step's error message * * @param {string} message - Error message * @param {string} source - Error source/file * @param {number} line - Error line * @param {number} column - Error column */ this.onError = function (message, source, line, column) { var fullMessage = message + ' at ' + source.replace(/\?.*$/, '') + ':' + line + ':' + column; console.error(fullMessage); this.step.result.error_message += fullMessage + "\n"; }; /** * Checks if a step is a hook * * @param {module:cucumber/step} step - Step object * @returns {boolean} TRUE for hooks, FALSE otherwise */ this.isHook = function(step) { return step.getKeyword().match(/^(Before|After)/); }; };
var searchData= [ ['c',['C',['../struct_s_a_c_bitstream_1_1_channel_type.html#a31c32b34085c06a1c58d920ca28c17c9a5c9b81e6c191dc59f0f4680421cafa72',1,'SACBitstream::ChannelType']]], ['channel',['Channel',['../class_channel.html',1,'Channel'],['../class_channel.html#a3a5079024e870e5188f7af98772ae38c',1,'Channel::Channel()']]], ['channels',['channels',['../class_process_manager.html#a325109138cabf342e5beacf7af67480b',1,'ProcessManager::channels()'],['../class_s_a_c_bitstream.html#a385f676be794f5bb9bec896ef6eda43c',1,'SACBitstream::channels()']]], ['channelscharts',['ChannelsCharts',['../class_channels_charts.html',1,'ChannelsCharts'],['../class_channels_charts.html#a6fd985f15981dde4bca95c029ec3549f',1,'ChannelsCharts::ChannelsCharts()']]], ['channelslist',['ChannelsList',['../class_channels_list.html',1,'ChannelsList'],['../class_channels_list.html#a2be2b5b850d9841fc90208afc7c6f112',1,'ChannelsList::ChannelsList()']]], ['channeltype',['ChannelType',['../struct_s_a_c_bitstream_1_1_channel_type.html',1,'SACBitstream::ChannelType'],['../struct_s_a_c_bitstream_1_1_channel_type.html#a31c32b34085c06a1c58d920ca28c17c9',1,'SACBitstream::ChannelType::channeltype()']]], ['chart2d',['Chart2D',['../class_chart2_d.html',1,'Chart2D'],['../class_chart2_d.html#a6883ce065d3a6a52f6f72efdf35d62aa',1,'Chart2D::Chart2D(QWidget *framework)'],['../class_chart2_d.html#a4d29e59bc8eafa3267c62034b51725b4',1,'Chart2D::Chart2D(QWidget *framework, double range[2][2], std::string title, std::string xlabel, std::string ylabel, int options)']]], ['chartoptions',['ChartOptions',['../struct_chart2_d_1_1_chart_options.html',1,'Chart2D']]], ['charts',['charts',['../class_effects_monitor.html#a2b5f5373404adac3f94bdab2f423d958',1,'EffectsMonitor']]], ['chunkid',['chunkID',['../struct_w_a_v_file_1_1_header.html#a796a84d05ba0ddeb837804dff90b730b',1,'WAVFile::Header']]], ['chunksize',['chunksize',['../struct_w_a_v_file_1_1_header.html#aee17e466b00a8b1d274be731f58d5fc0',1,'WAVFile::Header']]], ['clear',['clear',['../class_output_device.html#a9c3515a8c1812a08bd74d87389554767',1,'OutputDevice::clear()'],['../class_chart2_d.html#adc92e3ebe94275e02cf547c81d0410e9',1,'Chart2D::clear()'],['../class_effects_monitor.html#ad6ad01ab2de7ca57a57e5fb71c2f85d9',1,'EffectsMonitor::clear()'],['../class_audio_signal.html#a69279f3fee0a4fe11d3e9a8361615a96',1,'AudioSignal::clear()'],['../class_process_manager.html#a9c807d64f58ca890b9b4acde3f1c1bb2',1,'ProcessManager::clear()']]], ['combfilter',['combfilter',['../class_reverb.html#ab6dd1add7689fcf4ef2d2958e0a5acc4',1,'Reverb']]], ['compressor',['Compressor',['../class_compressor.html',1,'Compressor'],['../class_compressor.html#a8a728ed1544cc0f82e8390f4606026b0',1,'Compressor::Compressor()']]], ['consolelog',['consolelog',['../_logger_8cpp.html#ad3268f5fc285cfb356a498e2d24b27f4',1,'Logger.cpp']]], ['cursor',['cursor',['../class_process_manager.html#a337af1b32b2f6bf94ed98ef98e6d1226',1,'ProcessManager']]], ['cursor_5fread',['cursor_read',['../class_output_device.html#ab49ebf067d9b6f15f2305d5028cde85e',1,'OutputDevice']]], ['cursor_5fwrite',['cursor_write',['../class_output_device.html#ad770c7e5e833ccd9030382e16691f331',1,'OutputDevice']]], ['cyan',['cyan',['../_logger_8cpp.html#a318c6830790132f4763b2f2b6dbaf126',1,'Logger.cpp']]] ];
/** * Lo-Dash 2.3.0 (Custom Build) <http://lodash.com/> * Build: `lodash modularize exports="node" -o ./compat/` * Copyright 2012-2013 The Dojo Foundation <http://dojofoundation.org/> * Based on Underscore.js 1.5.2 <http://underscorejs.org/LICENSE> * Copyright 2009-2013 Jeremy Ashkenas, DocumentCloud and Investigative Reporters & Editors * Available under MIT license <http://lodash.com/license> */ var assign = require('../objects/assign'), baseEach = require('./baseEach'), forOwn = require('../objects/forOwn'), getArray = require('./getArray'), isArray = require('../objects/isArray'), isNode = require('./isNode'), isObject = require('../objects/isObject'), releaseArray = require('./releaseArray'), slice = require('./slice'), support = require('../support'); /** Used to match regexp flags from their coerced string values */ var reFlags = /\w*$/; /** `Object#toString` result shortcuts */ var argsClass = '[object Arguments]', arrayClass = '[object Array]', boolClass = '[object Boolean]', dateClass = '[object Date]', funcClass = '[object Function]', numberClass = '[object Number]', objectClass = '[object Object]', regexpClass = '[object RegExp]', stringClass = '[object String]'; /** Used to identify object classifications that `_.clone` supports */ var cloneableClasses = {}; cloneableClasses[funcClass] = false; cloneableClasses[argsClass] = cloneableClasses[arrayClass] = cloneableClasses[boolClass] = cloneableClasses[dateClass] = cloneableClasses[numberClass] = cloneableClasses[objectClass] = cloneableClasses[regexpClass] = cloneableClasses[stringClass] = true; /** Used for native method references */ var objectProto = Object.prototype; /** Used to resolve the internal [[Class]] of values */ var toString = objectProto.toString; /** Native method shortcuts */ var hasOwnProperty = objectProto.hasOwnProperty; /** Used to lookup a built-in constructor by [[Class]] */ var ctorByClass = {}; ctorByClass[arrayClass] = Array; ctorByClass[boolClass] = Boolean; ctorByClass[dateClass] = Date; ctorByClass[funcClass] = Function; ctorByClass[objectClass] = Object; ctorByClass[numberClass] = Number; ctorByClass[regexpClass] = RegExp; ctorByClass[stringClass] = String; /** * The base implementation of `_.clone` without argument juggling or support * for `thisArg` binding. * * @private * @param {*} value The value to clone. * @param {boolean} [isDeep=false] Specify a deep clone. * @param {Function} [callback] The function to customize cloning values. * @param {Array} [stackA=[]] Tracks traversed source objects. * @param {Array} [stackB=[]] Associates clones with source counterparts. * @returns {*} Returns the cloned value. */ function baseClone(value, isDeep, callback, stackA, stackB) { if (callback) { var result = callback(value); if (typeof result != 'undefined') { return result; } } // inspect [[Class]] var isObj = isObject(value); if (isObj) { var className = toString.call(value); if (!cloneableClasses[className] || (!support.nodeClass && isNode(value))) { return value; } var ctor = ctorByClass[className]; switch (className) { case boolClass: case dateClass: return new ctor(+value); case numberClass: case stringClass: return new ctor(value); case regexpClass: result = ctor(value.source, reFlags.exec(value)); result.lastIndex = value.lastIndex; return result; } } else { return value; } var isArr = isArray(value); if (isDeep) { // check for circular references and return corresponding clone var initedStack = !stackA; stackA || (stackA = getArray()); stackB || (stackB = getArray()); var length = stackA.length; while (length--) { if (stackA[length] == value) { return stackB[length]; } } result = isArr ? ctor(value.length) : {}; } else { result = isArr ? slice(value) : assign({}, value); } // add array properties assigned by `RegExp#exec` if (isArr) { if (hasOwnProperty.call(value, 'index')) { result.index = value.index; } if (hasOwnProperty.call(value, 'input')) { result.input = value.input; } } // exit for shallow clone if (!isDeep) { return result; } // add the source value to the stack of traversed objects // and associate it with its clone stackA.push(value); stackB.push(result); // recursively populate clone (susceptible to call stack limits) (isArr ? baseEach : forOwn)(value, function(objValue, key) { result[key] = baseClone(objValue, isDeep, callback, stackA, stackB); }); if (initedStack) { releaseArray(stackA); releaseArray(stackB); } return result; } module.exports = baseClone;
/** * Created by Estelle on 16/06/2016. */ 'use strict'; angular.module('core.context', ['ngResource']);
/** * @overview datejs * @version 1.0.0-beta-2014-03-25 * @author Gregory Wild-Smith <gregory@wild-smith.com> * @copyright 2014 Gregory Wild-Smith * @license MIT * @homepage https://github.com/abritinthebay/datejs */ /* * DateJS Culture String File * Country Code: es-AR * Name: Spanish (Argentina) * Format: "key" : "value" * Key is the en-US term, Value is the Key in the current language. */ Date.CultureStrings = Date.CultureStrings || {}; Date.CultureStrings["es-AR"] = { "name": "es-AR", "englishName": "Spanish (Argentina)", "nativeName": "Español (Argentina)", "Sunday": "domingo", "Monday": "lunes", "Tuesday": "martes", "Wednesday": "miércoles", "Thursday": "jueves", "Friday": "viernes", "Saturday": "sábado", "Sun": "dom", "Mon": "lun", "Tue": "mar", "Wed": "mié", "Thu": "jue", "Fri": "vie", "Sat": "sáb", "Su": "do", "Mo": "lu", "Tu": "ma", "We": "mi", "Th": "ju", "Fr": "vi", "Sa": "sá", "S_Sun_Initial": "d", "M_Mon_Initial": "l", "T_Tue_Initial": "m", "W_Wed_Initial": "m", "T_Thu_Initial": "j", "F_Fri_Initial": "v", "S_Sat_Initial": "s", "January": "enero", "February": "febrero", "March": "marzo", "April": "abril", "May": "mayo", "June": "junio", "July": "julio", "August": "agosto", "September": "septiembre", "October": "octubre", "November": "noviembre", "December": "diciembre", "Jan_Abbr": "ene", "Feb_Abbr": "feb", "Mar_Abbr": "mar", "Apr_Abbr": "abr", "May_Abbr": "may", "Jun_Abbr": "jun", "Jul_Abbr": "jul", "Aug_Abbr": "ago", "Sep_Abbr": "sep", "Oct_Abbr": "oct", "Nov_Abbr": "nov", "Dec_Abbr": "dic", "AM": "a.m.", "PM": "p.m.", "firstDayOfWeek": 0, "twoDigitYearMax": 2029, "mdy": "dmy", "M/d/yyyy": "dd/MM/yyyy", "dddd, MMMM dd, yyyy": "dddd, dd' de 'MMMM' de 'yyyy", "h:mm tt": "hh:mm tt", "h:mm:ss tt": "hh:mm:ss tt", "dddd, MMMM dd, yyyy h:mm:ss tt": "dddd, dd' de 'MMMM' de 'yyyy hh:mm:ss tt", "yyyy-MM-ddTHH:mm:ss": "yyyy-MM-ddTHH:mm:ss", "yyyy-MM-dd HH:mm:ssZ": "yyyy-MM-dd HH:mm:ssZ", "ddd, dd MMM yyyy HH:mm:ss": "ddd, dd MMM yyyy HH:mm:ss", "MMMM dd": "dd MMMM", "MMMM, yyyy": "MMMM' de 'yyyy", "/jan(uary)?/": "ene(ro)?", "/feb(ruary)?/": "feb(rero)?", "/mar(ch)?/": "mar(zo)?", "/apr(il)?/": "abr(il)?", "/may/": "may(o)?", "/jun(e)?/": "jun(io)?", "/jul(y)?/": "jul(io)?", "/aug(ust)?/": "ago(sto)?", "/sep(t(ember)?)?/": "sep(tiembre)?", "/oct(ober)?/": "oct(ubre)?", "/nov(ember)?/": "nov(iembre)?", "/dec(ember)?/": "dic(iembre)?", "/^su(n(day)?)?/": "^do(m(ingo)?)?", "/^mo(n(day)?)?/": "^lu(n(es)?)?", "/^tu(e(s(day)?)?)?/": "^ma(r(tes)?)?", "/^we(d(nesday)?)?/": "^mi(é(rcoles)?)?", "/^th(u(r(s(day)?)?)?)?/": "^ju(e(ves)?)?", "/^fr(i(day)?)?/": "^vi(e(rnes)?)?", "/^sa(t(urday)?)?/": "^sá(b(ado)?)?", "/^next/": "^next", "/^last|past|prev(ious)?/": "^last|past|prev(ious)?", "/^(\\+|aft(er)?|from|hence)/": "^(\\+|aft(er)?|from|hence)", "/^(\\-|bef(ore)?|ago)/": "^(\\-|bef(ore)?|ago)", "/^yes(terday)?/": "^yes(terday)?", "/^t(od(ay)?)?/": "^t(od(ay)?)?", "/^tom(orrow)?/": "^tom(orrow)?", "/^n(ow)?/": "^n(ow)?", "/^ms|milli(second)?s?/": "^ms|milli(second)?s?", "/^sec(ond)?s?/": "^sec(ond)?s?", "/^mn|min(ute)?s?/": "^mn|min(ute)?s?", "/^h(our)?s?/": "^h(our)?s?", "/^w(eek)?s?/": "^w(eek)?s?", "/^m(onth)?s?/": "^m(onth)?s?", "/^d(ay)?s?/": "^d(ay)?s?", "/^y(ear)?s?/": "^y(ear)?s?", "/^(a|p)/": "^(a|p)", "/^(a\\.?m?\\.?|p\\.?m?\\.?)/": "^(a\\.?m?\\.?|p\\.?m?\\.?)", "/^((e(s|d)t|c(s|d)t|m(s|d)t|p(s|d)t)|((gmt)?\\s*(\\+|\\-)\\s*\\d\\d\\d\\d?)|gmt|utc)/": "^((e(s|d)t|c(s|d)t|m(s|d)t|p(s|d)t)|((gmt)?\\s*(\\+|\\-)\\s*\\d\\d\\d\\d?)|gmt|utc)", "/^\\s*(st|nd|rd|th)/": "^\\s*(st|nd|rd|th)", "/^\\s*(\\:|a(?!u|p)|p)/": "^\\s*(\\:|a(?!u|p)|p)", "LINT": "LINT", "TOT": "TOT", "CHAST": "CHAST", "NZST": "NZST", "NFT": "NFT", "SBT": "SBT", "AEST": "AEST", "ACST": "ACST", "JST": "JST", "CWST": "CWST", "CT": "CT", "ICT": "ICT", "MMT": "MMT", "BIOT": "BST", "NPT": "NPT", "IST": "IST", "PKT": "PKT", "AFT": "AFT", "MSK": "MSK", "IRST": "IRST", "FET": "FET", "EET": "EET", "CET": "CET", "UTC": "UTC", "GMT": "GMT", "CVT": "CVT", "GST": "GST", "BRT": "BRT", "NST": "NST", "AST": "AST", "EST": "EST", "CST": "CST", "MST": "MST", "PST": "PST", "AKST": "AKST", "MIT": "MIT", "HST": "HST", "SST": "SST", "BIT": "BIT", "CHADT": "CHADT", "NZDT": "NZDT", "AEDT": "AEDT", "ACDT": "ACDT", "AZST": "AZST", "IRDT": "IRDT", "EEST": "EEST", "CEST": "CEST", "BST": "BST", "PMDT": "PMDT", "ADT": "ADT", "NDT": "NDT", "EDT": "EDT", "CDT": "CDT", "MDT": "MDT", "PDT": "PDT", "AKDT": "AKDT", "HADT": "HADT" }; Date.CultureStrings.lang = "es-AR"; /** * @overview datejs * @version 1.0.0-beta-2014-03-25 * @author Gregory Wild-Smith <gregory@wild-smith.com> * @copyright 2014 Gregory Wild-Smith * @license MIT * @homepage https://github.com/abritinthebay/datejs */(function () { var $D = Date; var lang = Date.CultureStrings ? Date.CultureStrings.lang : null; var loggedKeys = {}; // for debug purposes. var __ = function (key, language) { var output, split, length, last; var countryCode = (language) ? language : lang; if (Date.CultureStrings && Date.CultureStrings[countryCode] && Date.CultureStrings[countryCode][key]) { output = Date.CultureStrings[countryCode][key]; } else { switch(key) { case "name": output = "en-US"; break; case "englishName": output = "English (United States)"; break; case "nativeName": output = "English (United States)"; break; case "twoDigitYearMax": output = 2049; break; case "firstDayOfWeek": output = 0; break; default: output = key; split = key.split("_"); length = split.length; if (length > 1 && key.charAt(0) !== "/") { // if the key isn't a regex and it has a split. last = split[(length - 1)].toLowerCase(); if (last === "initial" || last === "abbr") { output = split[0]; } } } } if (key.charAt(0) === "/") { // Assume it's a regex if (Date.CultureStrings && Date.CultureStrings[countryCode] && Date.CultureStrings[countryCode][key]) { output = new RegExp(Date.CultureStrings[countryCode][key], "i"); } else { output = new RegExp(key.replace(new RegExp("/", "g"),""), "i"); } } loggedKeys[key] = key; return output; }; var loadI18nScript = function (code) { // paatterned after jQuery's getScript. var url = Date.Config.i18n + code + '.js'; var head = document.getElementsByTagName("head")[0] || document.documentElement; var script = document.createElement("script"); script.src = url; var completed = false; var events = { done: function (){} // dummy function }; // Attach handlers for all browsers script.onload = script.onreadystatechange = function() { if ( !completed && (!this.readyState || this.readyState === "loaded" || this.readyState === "complete") ) { done = true; events.done(); head.removeChild(script); } }; setTimeout(function() { head.insertBefore(script, head.firstChild); }, 0); // allows return to execute first return { done: function (f) { events.done = function() { if (f) { f(); } }; } }; }; var CultureInfo = function () { var buildTimeZones = function (data) { var zone; for (zone in data.abbreviatedTimeZoneStandard) { if (data.abbreviatedTimeZoneStandard.hasOwnProperty(zone)) { data.timezones.push({ name: zone, offset: data.abbreviatedTimeZoneStandard[zone]}); } } for (zone in data.abbreviatedTimeZoneDST) { if (data.abbreviatedTimeZoneDST.hasOwnProperty(zone)) { data.timezones.push({ name: zone, offset: data.abbreviatedTimeZoneDST[zone], dst: true}); } } return data.timezones; }; var info = { name: __("name"), englishName: __("englishName"), nativeName: __("nativeName"), /* Day Name Strings */ dayNames: [ __("Sunday"), __("Monday"), __("Tuesday"), __("Wednesday"), __("Thursday"), __("Friday"), __("Saturday") ], abbreviatedDayNames: [ __("Sun"), __("Mon"), __("Tue"), __("Wed"), __("Thu"), __("Fri"), __("Sat") ], shortestDayNames: [ __("Su"), __("Mo"), __("Tu"), __("We"), __("Th"), __("Fr"), __("Sa") ], firstLetterDayNames: [ __("S_Sun_Initial"), __("M_Mon_Initial"), __("T_Tues_Initial"), __("W_Wed_Initial"), __("T_Thu_Initial"), __("F_Fri_Initial"), __("S_Sat_Initial") ], /* Month Name Strings */ monthNames: [ __("January"), __("February"), __("March"), __("April"), __("May"), __("June"), __("July"), __("August"), __("September"), __("October"), __("November"), __("December") ], abbreviatedMonthNames: [ __("Jan_Abbr"), __("Feb_Abbr"), __("Mar_Abbr"), __("Apr_Abbr"), __("May_Abbr"), __("Jun_Abbr"), __("Jul_Abbr"), __("Aug_Abbr"), __("Sep_Abbr"), __("Oct_Abbr"), __("Nov_Abbr"), __("Dec_Abbr") ], /* AM/PM Designators */ amDesignator: __("AM"), pmDesignator: __("PM"), firstDayOfWeek: __("firstDayOfWeek"), twoDigitYearMax: __("twoDigitYearMax"), dateElementOrder: __("mdy"), /* Standard date and time format patterns */ formatPatterns: { shortDate: __("M/d/yyyy"), longDate: __("dddd, MMMM dd, yyyy"), shortTime: __("h:mm tt"), longTime: __("h:mm:ss tt"), fullDateTime: __("dddd, MMMM dd, yyyy h:mm:ss tt"), sortableDateTime: __("yyyy-MM-ddTHH:mm:ss"), universalSortableDateTime: __("yyyy-MM-dd HH:mm:ssZ"), rfc1123: __("ddd, dd MMM yyyy HH:mm:ss"), monthDay: __("MMMM dd"), yearMonth: __("MMMM, yyyy") }, regexPatterns: { inTheMorning: __("/( in the )(morn(ing)?)\\b/"), thisMorning: __("/(this )(morn(ing)?)\\b/"), amThisMorning: __("/(\b\\d(am)? )(this )(morn(ing)?)/"), inTheEvening: __("/( in the )(even(ing)?)\\b/"), thisEvening: __("/(this )(even(ing)?)\\b/"), pmThisEvening: __("/(\b\\d(pm)? )(this )(even(ing)?)/"), jan: __("/jan(uary)?/"), feb: __("/feb(ruary)?/"), mar: __("/mar(ch)?/"), apr: __("/apr(il)?/"), may: __("/may/"), jun: __("/jun(e)?/"), jul: __("/jul(y)?/"), aug: __("/aug(ust)?/"), sep: __("/sep(t(ember)?)?/"), oct: __("/oct(ober)?/"), nov: __("/nov(ember)?/"), dec: __("/dec(ember)?/"), sun: __("/^su(n(day)?)?/"), mon: __("/^mo(n(day)?)?/"), tue: __("/^tu(e(s(day)?)?)?/"), wed: __("/^we(d(nesday)?)?/"), thu: __("/^th(u(r(s(day)?)?)?)?/"), fri: __("/fr(i(day)?)?/"), sat: __("/^sa(t(urday)?)?/"), future: __("/^next/"), past: __("/last|past|prev(ious)?/"), add: __("/^(\\+|aft(er)?|from|hence)/"), subtract: __("/^(\\-|bef(ore)?|ago)/"), yesterday: __("/^yes(terday)?/"), today: __("/^t(od(ay)?)?/"), tomorrow: __("/^tom(orrow)?/"), now: __("/^n(ow)?/"), millisecond: __("/^ms|milli(second)?s?/"), second: __("/^sec(ond)?s?/"), minute: __("/^mn|min(ute)?s?/"), hour: __("/^h(our)?s?/"), week: __("/^w(eek)?s?/"), month: __("/^m(onth)?s?/"), day: __("/^d(ay)?s?/"), year: __("/^y(ear)?s?/"), shortMeridian: __("/^(a|p)/"), longMeridian: __("/^(a\\.?m?\\.?|p\\.?m?\\.?)/"), timezone: __("/^((e(s|d)t|c(s|d)t|m(s|d)t|p(s|d)t)|((gmt)?\\s*(\\+|\\-)\\s*\\d\\d\\d\\d?)|gmt|utc)/"), ordinalSuffix: __("/^\\s*(st|nd|rd|th)/"), timeContext: __("/^\\s*(\\:|a(?!u|p)|p)/") }, timezones: [], abbreviatedTimeZoneDST: {}, abbreviatedTimeZoneStandard: {} }; info.abbreviatedTimeZoneDST[__("CHADT")] = "+1345"; info.abbreviatedTimeZoneDST[__("NZDT")] = "+1300"; info.abbreviatedTimeZoneDST[__("AEDT")] = "+1100"; info.abbreviatedTimeZoneDST[__("ACDT")] = "+1030"; info.abbreviatedTimeZoneDST[__("AZST")] = "+0500"; info.abbreviatedTimeZoneDST[__("IRDT")] = "+0430"; info.abbreviatedTimeZoneDST[__("EEST")] = "+0300"; info.abbreviatedTimeZoneDST[__("CEST")] = "+0200"; info.abbreviatedTimeZoneDST[__("BST")] = "+0100"; info.abbreviatedTimeZoneDST[__("PMDT")] = "-0200"; info.abbreviatedTimeZoneDST[__("ADT")] = "-0300"; info.abbreviatedTimeZoneDST[__("NDT")] = "-0230"; info.abbreviatedTimeZoneDST[__("EDT")] = "-0400"; info.abbreviatedTimeZoneDST[__("CDT")] = "-0500"; info.abbreviatedTimeZoneDST[__("MDT")] = "-0600"; info.abbreviatedTimeZoneDST[__("PDT")] = "-0700"; info.abbreviatedTimeZoneDST[__("AKDT")] = "-0800"; info.abbreviatedTimeZoneDST[__("HADT")] = "-0900"; info.abbreviatedTimeZoneStandard[__("LINT")] = "+1400"; info.abbreviatedTimeZoneStandard[__("TOT")] = "+1300"; info.abbreviatedTimeZoneStandard[__("CHAST")] = "+1245"; info.abbreviatedTimeZoneStandard[__("NZST")] = "+1200"; info.abbreviatedTimeZoneStandard[__("NFT")] = "+1130"; info.abbreviatedTimeZoneStandard[__("SBT")] = "+1100"; info.abbreviatedTimeZoneStandard[__("AEST")] = "+1000"; info.abbreviatedTimeZoneStandard[__("ACST")] = "+0930"; info.abbreviatedTimeZoneStandard[__("JST")] = "+0900"; info.abbreviatedTimeZoneStandard[__("CWST")] = "+0845"; info.abbreviatedTimeZoneStandard[__("CT")] = "+0800"; info.abbreviatedTimeZoneStandard[__("ICT")] = "+0700"; info.abbreviatedTimeZoneStandard[__("MMT")] = "+0630"; info.abbreviatedTimeZoneStandard[__("BST")] = "+0600"; info.abbreviatedTimeZoneStandard[__("NPT")] = "+0545"; info.abbreviatedTimeZoneStandard[__("IST")] = "+0530"; info.abbreviatedTimeZoneStandard[__("PKT")] = "+0500"; info.abbreviatedTimeZoneStandard[__("AFT")] = "+0430"; info.abbreviatedTimeZoneStandard[__("MSK")] = "+0400"; info.abbreviatedTimeZoneStandard[__("IRST")] = "+0330"; info.abbreviatedTimeZoneStandard[__("FET")] = "+0300"; info.abbreviatedTimeZoneStandard[__("EET")] = "+0200"; info.abbreviatedTimeZoneStandard[__("CET")] = "+0100"; info.abbreviatedTimeZoneStandard[__("GMT")] = "+0000"; info.abbreviatedTimeZoneStandard[__("UTC")] = "+0000"; info.abbreviatedTimeZoneStandard[__("CVT")] = "-0100"; info.abbreviatedTimeZoneStandard[__("GST")] = "-0200"; info.abbreviatedTimeZoneStandard[__("BRT")] = "-0300"; info.abbreviatedTimeZoneStandard[__("NST")] = "-0330"; info.abbreviatedTimeZoneStandard[__("AST")] = "-0400"; info.abbreviatedTimeZoneStandard[__("EST")] = "-0500"; info.abbreviatedTimeZoneStandard[__("CST")] = "-0600"; info.abbreviatedTimeZoneStandard[__("MST")] = "-0700"; info.abbreviatedTimeZoneStandard[__("PST")] = "-0800"; info.abbreviatedTimeZoneStandard[__("AKST")] = "-0900"; info.abbreviatedTimeZoneStandard[__("MIT")] = "-0930"; info.abbreviatedTimeZoneStandard[__("HST")] = "-1000"; info.abbreviatedTimeZoneStandard[__("SST")] = "-1100"; info.abbreviatedTimeZoneStandard[__("BIT")] = "-1200"; buildTimeZones(info); return info; }; $D.i18n = { __: function (key, lang) { return __(key, lang); }, currentLanguage: function () { return lang || "en-US"; }, setLanguage: function (code, force) { if (force || code === "en-US" || (!!Date.CultureStrings && !!Date.CultureStrings[code])) { lang = code; Date.CultureStrings.lang = code; Date.CultureInfo = CultureInfo(); } else { if (!(!!Date.CultureStrings && !!Date.CultureStrings[code])) { if (typeof exports !== 'undefined' && this.exports !== exports) { // we're in a Node enviroment, load it using require try { require("../i18n/" + code + ".js"); lang = code; Date.CultureStrings.lang = code; Date.CultureInfo = CultureInfo(); } catch (e) { // var str = "The language for '" + code + "' could not be loaded by Node. It likely does not exist."; throw new Error("The DateJS IETF language tag '" + code + "' could not be loaded by Node. It likely does not exist."); } } else if (Date.Config && Date.Config.i18n) { // we know the location of the files, so lets load them loadI18nScript(code).done(function(){ lang = code; Date.CultureStrings.lang = code; Date.CultureInfo = CultureInfo(); }); } else { Date.console.error("The DateJS IETF language tag '" + code + "' is not available and has not been loaded."); } } } }, getLoggedKeys: function () { return loggedKeys; }, updateCultureInfo: function () { Date.CultureInfo = CultureInfo(); } }; $D.i18n.updateCultureInfo(); // run automatically }()); (function () { var $D = Date, $P = $D.prototype, p = function (s, l) { if (!l) { l = 2; } return ("000" + s).slice(l * -1); }; if (typeof window !== "undefined" && typeof window.console !== "undefined" && typeof window.console.log !== "undefined") { $D.console = console; // used only to raise non-critical errors if available } else { // set mock so we don't give errors. $D.console = { log: function(){}, error: function(){} }; } $D.Config = {}; $D.initOverloads = function() { /** * Overload of Date.now. Allows an alternate call for Date.now where it returns the * current Date as an object rather than just milliseconds since the Unix Epoch. * * Also provides an implementation of now() for browsers (IE<9) that don't have it. * * Backwards compatible so with work with either: * Date.now() [returns ms] * or * Date.now(true) [returns Date] */ if (!$D.now) { $D._now = function now() { return new Date().getTime(); }; } else if (!$D._now) { $D._now = $D.now; } $D.now = function (returnObj) { if (returnObj) { return $D.present(); } else { return $D._now(); } }; if ( !$P.toISOString ) { $P.toISOString = function() { return this.getUTCFullYear() + "-" + p(this.getUTCMonth() + 1) + "-" + p(this.getUTCDate()) + "T" + p(this.getUTCHours()) + ":" + p(this.getUTCMinutes()) + ":" + p(this.getUTCSeconds()) + "." + String( (this.getUTCMilliseconds()/1000).toFixed(3)).slice(2, 5) + "Z"; }; } // private if ( $P._toString === undefined ){ $P._toString = $P.toString; } }; $D.initOverloads(); /** * Resets the time of this Date object to 12:00 AM (00:00), which is the start of the day. * @param {Boolean} .clone() this date instance before clearing Time * @return {Date} this */ $P.clearTime = function () { this.setHours(0); this.setMinutes(0); this.setSeconds(0); this.setMilliseconds(0); return this; }; /** * Resets the time of this Date object to the current time ('now'). * @return {Date} this */ $P.setTimeToNow = function () { var n = new Date(); this.setHours(n.getHours()); this.setMinutes(n.getMinutes()); this.setSeconds(n.getSeconds()); this.setMilliseconds(n.getMilliseconds()); return this; }; /** * Gets a date that is set to the current date. The time is set to the start of the day (00:00 or 12:00 AM). * @return {Date} The current date. */ $D.today = function () { return new Date().clearTime(); }; /** * Gets a date that is set to the current date and time (same as new Date, but chainable) * @return {Date} The current date. */ $D.present = function () { return new Date(); }; /** * Compares the first date to the second date and returns an number indication of their relative values. * @param {Date} First Date object to compare [Required]. * @param {Date} Second Date object to compare to [Required]. * @return {Number} -1 = date1 is lessthan date2. 0 = values are equal. 1 = date1 is greaterthan date2. */ $D.compare = function (date1, date2) { if (isNaN(date1) || isNaN(date2)) { throw new Error(date1 + " - " + date2); } else if (date1 instanceof Date && date2 instanceof Date) { return (date1 < date2) ? -1 : (date1 > date2) ? 1 : 0; } else { throw new TypeError(date1 + " - " + date2); } }; /** * Compares the first Date object to the second Date object and returns true if they are equal. * @param {Date} First Date object to compare [Required] * @param {Date} Second Date object to compare to [Required] * @return {Boolean} true if dates are equal. false if they are not equal. */ $D.equals = function (date1, date2) { return (date1.compareTo(date2) === 0); }; /** * Gets the language appropriate day name when given the day number(0-6) * eg - 0 == Sunday * @return {String} The day name */ $D.getDayName = function (n) { return Date.CultureInfo.dayNames[n]; }; /** * Gets the day number (0-6) if given a CultureInfo specific string which is a valid dayName, abbreviatedDayName or shortestDayName (two char). * @param {String} The name of the day (eg. "Monday, "Mon", "tuesday", "tue", "We", "we"). * @return {Number} The day number */ $D.getDayNumberFromName = function (name) { var n = Date.CultureInfo.dayNames, m = Date.CultureInfo.abbreviatedDayNames, o = Date.CultureInfo.shortestDayNames, s = name.toLowerCase(); for (var i = 0; i < n.length; i++) { if (n[i].toLowerCase() === s || m[i].toLowerCase() === s || o[i].toLowerCase() === s) { return i; } } return -1; }; /** * Gets the month number (0-11) if given a Culture Info specific string which is a valid monthName or abbreviatedMonthName. * @param {String} The name of the month (eg. "February, "Feb", "october", "oct"). * @return {Number} The day number */ $D.getMonthNumberFromName = function (name) { var n = Date.CultureInfo.monthNames, m = Date.CultureInfo.abbreviatedMonthNames, s = name.toLowerCase(); for (var i = 0; i < n.length; i++) { if (n[i].toLowerCase() === s || m[i].toLowerCase() === s) { return i; } } return -1; }; /** * Gets the language appropriate month name when given the month number(0-11) * eg - 0 == January * @return {String} The month name */ $D.getMonthName = function (n) { return Date.CultureInfo.monthNames[n]; }; /** * Determines if the current date instance is within a LeapYear. * @param {Number} The year. * @return {Boolean} true if date is within a LeapYear, otherwise false. */ $D.isLeapYear = function (year) { return ((year % 4 === 0 && year % 100 !== 0) || year % 400 === 0); }; /** * Gets the number of days in the month, given a year and month value. Automatically corrects for LeapYear. * @param {Number} The year. * @param {Number} The month (0-11). * @return {Number} The number of days in the month. */ $D.getDaysInMonth = function (year, month) { if (!month && $D.validateMonth(year)) { month = year; year = Date.today().getFullYear(); } return [31, ($D.isLeapYear(year) ? 29 : 28), 31, 30, 31, 30, 31, 31, 30, 31, 30, 31][month]; }; $D.getTimezoneAbbreviation = function (offset, dst) { var p, n = (dst || false) ? Date.CultureInfo.abbreviatedTimeZoneDST : Date.CultureInfo.abbreviatedTimeZoneStandard; for (p in n) { if (n.hasOwnProperty(p)) { if (n[p] === offset) { return p; } } } return null; }; $D.getTimezoneOffset = function (name, dst) { var i, a =[], z = Date.CultureInfo.timezones; if (!name) { name = (new Date()).getTimezone()} for (i = 0; i < z.length; i++) { if (z[i].name === name.toUpperCase()) { a.push(i); } } if (!z[a[0]]) { return null; } if (a.length === 1 || !dst) { return z[a[0]].offset; } else { for (i=0; i < a.length; i++) { if (z[a[i]].dst) { return z[a[i]].offset; } } } }; $D.getQuarter = function (d) { d = d || new Date(); // If no date supplied, use today var q = [1,2,3,4]; return q[Math.floor(d.getMonth() / 3)]; // ~~~ is a bitwise op. Faster than Math.floor }; $D.getDaysLeftInQuarter = function (d) { d = d || new Date(); var qEnd = new Date(d); qEnd.setMonth(qEnd.getMonth() + 3 - qEnd.getMonth() % 3, 0); return Math.floor((qEnd - d) / 8.64e7); }; /** * Returns a new Date object that is an exact date and time copy of the original instance. * @return {Date} A new Date instance */ $P.clone = function () { return new Date(this.getTime()); }; /** * Compares this instance to a Date object and returns an number indication of their relative values. * @param {Date} Date object to compare [Required] * @return {Number} -1 = this is lessthan date. 0 = values are equal. 1 = this is greaterthan date. */ $P.compareTo = function (date) { return Date.compare(this, date); }; /** * Compares this instance to another Date object and returns true if they are equal. * @param {Date} Date object to compare. If no date to compare, new Date() [now] is used. * @return {Boolean} true if dates are equal. false if they are not equal. */ $P.equals = function (date) { return Date.equals(this, (date !== undefined ? date : new Date())); }; /** * Determines if this instance is between a range of two dates or equal to either the start or end dates. * @param {Date} Start of range [Required] * @param {Date} End of range [Required] * @return {Boolean} true is this is between or equal to the start and end dates, else false */ $P.between = function (start, end) { return this.getTime() >= start.getTime() && this.getTime() <= end.getTime(); }; /** * Determines if this date occurs after the date to compare to. * @param {Date} Date object to compare. If no date to compare, new Date() ("now") is used. * @return {Boolean} true if this date instance is greater than the date to compare to (or "now"), otherwise false. */ $P.isAfter = function (date) { return this.compareTo(date || new Date()) === 1; }; /** * Determines if this date occurs before the date to compare to. * @param {Date} Date object to compare. If no date to compare, new Date() ("now") is used. * @return {Boolean} true if this date instance is less than the date to compare to (or "now"). */ $P.isBefore = function (date) { return (this.compareTo(date || new Date()) === -1); }; /** * Determines if the current Date instance occurs today. * @return {Boolean} true if this date instance is 'today', otherwise false. */ /** * Determines if the current Date instance occurs on the same Date as the supplied 'date'. * If no 'date' to compare to is provided, the current Date instance is compared to 'today'. * @param {date} Date object to compare. If no date to compare, the current Date ("now") is used. * @return {Boolean} true if this Date instance occurs on the same Day as the supplied 'date'. */ $P.isToday = $P.isSameDay = function (date) { return this.clone().clearTime().equals((date || new Date()).clone().clearTime()); }; /** * Adds the specified number of milliseconds to this instance. * @param {Number} The number of milliseconds to add. The number can be positive or negative [Required] * @return {Date} this */ $P.addMilliseconds = function (value) { if (!value) { return this; } this.setTime(this.getTime() + value * 1); return this; }; /** * Adds the specified number of seconds to this instance. * @param {Number} The number of seconds to add. The number can be positive or negative [Required] * @return {Date} this */ $P.addSeconds = function (value) { if (!value) { return this; } return this.addMilliseconds(value * 1000); }; /** * Adds the specified number of seconds to this instance. * @param {Number} The number of seconds to add. The number can be positive or negative [Required] * @return {Date} this */ $P.addMinutes = function (value) { if (!value) { return this; } return this.addMilliseconds(value * 60000); /* 60*1000 */ }; /** * Adds the specified number of hours to this instance. * @param {Number} The number of hours to add. The number can be positive or negative [Required] * @return {Date} this */ $P.addHours = function (value) { if (!value) { return this; } return this.addMilliseconds(value * 3600000); /* 60*60*1000 */ }; /** * Adds the specified number of days to this instance. * @param {Number} The number of days to add. The number can be positive or negative [Required] * @return {Date} this */ $P.addDays = function (value) { if (!value) { return this; } this.setDate(this.getDate() + value * 1); return this; }; /** * Adds the specified number of weekdays (ie - not sat or sun) to this instance. * @param {Number} The number of days to add. The number can be positive or negative [Required] * @return {Date} this */ $P.addWeekdays = function (value) { if (!value) { return this; } var day = this.getDay(); var weeks = (Math.ceil(Math.abs(value)/7)); if (day === 0 || day === 6) { if (value > 0) { this.next().monday(); this.addDays(-1); } } if (value < 0) { while (value < 0) { this.addDays(-1); day = this.getDay(); if (day !== 0 && day !== 6) { value++; } } return this; } else if (value > 5 || (6-day) <= value) { value = value + (weeks * 2); } return this.addDays(value); }; /** * Adds the specified number of weeks to this instance. * @param {Number} The number of weeks to add. The number can be positive or negative [Required] * @return {Date} this */ $P.addWeeks = function (value) { if (!value) { return this; } return this.addDays(value * 7); }; /** * Adds the specified number of months to this instance. * @param {Number} The number of months to add. The number can be positive or negative [Required] * @return {Date} this */ $P.addMonths = function (value) { if (!value) { return this; } var n = this.getDate(); this.setDate(1); this.setMonth(this.getMonth() + value * 1); this.setDate(Math.min(n, $D.getDaysInMonth(this.getFullYear(), this.getMonth()))); return this; }; $P.addQuarters = function (value) { if (!value) { return this; } // note this will take you to the same point in the quarter as you are now. // i.e. - if you are 15 days into the quarter you'll be 15 days into the resulting one. // bonus: this allows adding fractional quarters return this.addMonths(value * 3); }; /** * Adds the specified number of years to this instance. * @param {Number} The number of years to add. The number can be positive or negative [Required] * @return {Date} this */ $P.addYears = function (value) { if (!value) { return this; } return this.addMonths(value * 12); }; /** * Adds (or subtracts) to the value of the years, months, weeks, days, hours, minutes, seconds, milliseconds of the date instance using given configuration object. Positive and Negative values allowed. * Example <pre><code> Date.today().add( { days: 1, months: 1 } ) new Date().add( { years: -1 } ) </code></pre> * @param {Object} Configuration object containing attributes (months, days, etc.) * @return {Date} this */ $P.add = function (config) { if (typeof config === "number") { this._orient = config; return this; } var x = config; if (x.day) { // If we should be a different date than today (eg: for 'tomorrow -1d', etc). // Should only effect parsing, not direct usage (eg, Finish and FinishExact) if ((x.day - this.getDate()) !== 0) { this.setDate(x.day); } } if (x.milliseconds) { this.addMilliseconds(x.milliseconds); } if (x.seconds) { this.addSeconds(x.seconds); } if (x.minutes) { this.addMinutes(x.minutes); } if (x.hours) { this.addHours(x.hours); } if (x.weeks) { this.addWeeks(x.weeks); } if (x.months) { this.addMonths(x.months); } if (x.years) { this.addYears(x.years); } if (x.days) { this.addDays(x.days); } return this; }; /** * Get the week number. Week one (1) is the week which contains the first Thursday of the year. Monday is considered the first day of the week. * The .getWeek() function does NOT convert the date to UTC. The local datetime is used. * Please use .getISOWeek() to get the week of the UTC converted date. * @return {Number} 1 to 53 */ $P.getWeek = function (utc) { // Create a copy of this date object var self, target = new Date(this.valueOf()); if (utc) { target.addMinutes(target.getTimezoneOffset()); self = target.clone(); } else { self = this; } // ISO week date weeks start on monday // so correct the day number var dayNr = (self.getDay() + 6) % 7; // ISO 8601 states that week 1 is the week // with the first thursday of that year. // Set the target date to the thursday in the target week target.setDate(target.getDate() - dayNr + 3); // Store the millisecond value of the target date var firstThursday = target.valueOf(); // Set the target to the first thursday of the year // First set the target to january first target.setMonth(0, 1); // Not a thursday? Correct the date to the next thursday if (target.getDay() !== 4) { target.setMonth(0, 1 + ((4 - target.getDay()) + 7) % 7); } // The weeknumber is the number of weeks between the // first thursday of the year and the thursday in the target week return 1 + Math.ceil((firstThursday - target) / 604800000); // 604800000 = 7 * 24 * 3600 * 1000 }; /** * Get the ISO 8601 week number. Week one ("01") is the week which contains the first Thursday of the year. Monday is considered the first day of the week. * The .getISOWeek() function does convert the date to it's UTC value. Please use .getWeek() to get the week of the local date. * @return {String} "01" to "53" */ $P.getISOWeek = function () { return p(this.getWeek(true)); }; /** * Moves the date to Monday of the week set. Week one (1) is the week which contains the first Thursday of the year. * @param {Number} A Number (1 to 53) that represents the week of the year. * @return {Date} this */ $P.setWeek = function (n) { if ((n - this.getWeek()) === 0) { if (this.getDay() !== 1) { return this.moveToDayOfWeek(1, (this.getDay() > 1 ? -1 : 1)); } else { return this; } } else { return this.moveToDayOfWeek(1, (this.getDay() > 1 ? -1 : 1)).addWeeks(n - this.getWeek()); } }; $P.setQuarter = function (qtr) { var month = Math.abs(((qtr-1) * 3) + 1); return this.setMonth(month, 1); }; $P.getQuarter = function () { return Date.getQuarter(this); }; $P.getDaysLeftInQuarter = function () { return Date.getDaysLeftInQuarter(this); }; // private var validate = function (n, min, max, name) { name = name ? name : "Object"; if (typeof n === "undefined") { return false; } else if (typeof n !== "number") { throw new TypeError(n + " is not a Number."); } else if (n < min || n > max) { // As failing validation is *not* an exceptional circumstance // lets not throw a RangeError Exception here. // It's semantically correct but it's not sensible. return false; } return true; }; /** * Validates the number is within an acceptable range for milliseconds [0-999]. * @param {Number} The number to check if within range. * @return {Boolean} true if within range, otherwise false. */ $D.validateMillisecond = function (value) { return validate(value, 0, 999, "millisecond"); }; /** * Validates the number is within an acceptable range for seconds [0-59]. * @param {Number} The number to check if within range. * @return {Boolean} true if within range, otherwise false. */ $D.validateSecond = function (value) { return validate(value, 0, 59, "second"); }; /** * Validates the number is within an acceptable range for minutes [0-59]. * @param {Number} The number to check if within range. * @return {Boolean} true if within range, otherwise false. */ $D.validateMinute = function (value) { return validate(value, 0, 59, "minute"); }; /** * Validates the number is within an acceptable range for hours [0-23]. * @param {Number} The number to check if within range. * @return {Boolean} true if within range, otherwise false. */ $D.validateHour = function (value) { return validate(value, 0, 23, "hour"); }; /** * Validates the number is within an acceptable range for the days in a month [0-MaxDaysInMonth]. * @param {Number} The number to check if within range. * @return {Boolean} true if within range, otherwise false. */ $D.validateDay = function (value, year, month) { return validate(value, 1, $D.getDaysInMonth(year, month), "day"); }; /** * Validates the number is within an acceptable range for months [0-11]. * @param {Number} The number to check if within range. * @return {Boolean} true if within range, otherwise false. */ $D.validateWeek = function (value) { return validate(value, 0, 53, "week"); }; /** * Validates the number is within an acceptable range for months [0-11]. * @param {Number} The number to check if within range. * @return {Boolean} true if within range, otherwise false. */ $D.validateMonth = function (value) { return validate(value, 0, 11, "month"); }; /** * Validates the number is within an acceptable range for years. * @param {Number} The number to check if within range. * @return {Boolean} true if within range, otherwise false. */ $D.validateYear = function (value) { /** * Per ECMAScript spec the range of times supported by Date objects is * exactly –100,000,000 days to 100,000,000 days measured relative to * midnight at the beginning of 01 January, 1970 UTC. * This gives a range of 8,640,000,000,000,000 milliseconds to either * side of 01 January, 1970 UTC. * * Earliest possible date: Tue, 20 Apr 271,822 B.C. 00:00:00 UTC * Latest possible date: Sat, 13 Sep 275,760 00:00:00 UTC */ return validate(value, -271822, 275760, "year"); }; /** * Set the value of year, month, day, hour, minute, second, millisecond of date instance using given configuration object. * Example <pre><code> Date.today().set( { day: 20, month: 1 } ) new Date().set( { millisecond: 0 } ) </code></pre> * * @param {Object} Configuration object containing attributes (month, day, etc.) * @return {Date} this */ $P.set = function (config) { if ($D.validateMillisecond(config.millisecond)) { this.addMilliseconds(config.millisecond - this.getMilliseconds()); } if ($D.validateSecond(config.second)) { this.addSeconds(config.second - this.getSeconds()); } if ($D.validateMinute(config.minute)) { this.addMinutes(config.minute - this.getMinutes()); } if ($D.validateHour(config.hour)) { this.addHours(config.hour - this.getHours()); } if ($D.validateMonth(config.month)) { this.addMonths(config.month - this.getMonth()); } if ($D.validateYear(config.year)) { this.addYears(config.year - this.getFullYear()); } /* day has to go last because you can't validate the day without first knowing the month */ if ($D.validateDay(config.day, this.getFullYear(), this.getMonth())) { this.addDays(config.day - this.getDate()); } if (config.timezone) { this.setTimezone(config.timezone); } if (config.timezoneOffset) { this.setTimezoneOffset(config.timezoneOffset); } if (config.week && $D.validateWeek(config.week)) { this.setWeek(config.week); } return this; }; /** * Moves the date to the first day of the month. * @return {Date} this */ $P.moveToFirstDayOfMonth = function () { return this.set({ day: 1 }); }; /** * Moves the date to the last day of the month. * @return {Date} this */ $P.moveToLastDayOfMonth = function () { return this.set({ day: $D.getDaysInMonth(this.getFullYear(), this.getMonth())}); }; /** * Moves the date to the next n'th occurrence of the dayOfWeek starting from the beginning of the month. The number (-1) is a magic number and will return the last occurrence of the dayOfWeek in the month. * @param {Number} The dayOfWeek to move to * @param {Number} The n'th occurrence to move to. Use (-1) to return the last occurrence in the month * @return {Date} this */ $P.moveToNthOccurrence = function (dayOfWeek, occurrence) { if (dayOfWeek === "Weekday") { if (occurrence > 0) { this.moveToFirstDayOfMonth(); if (this.is().weekday()) { occurrence -= 1; } } else if (occurrence < 0) { this.moveToLastDayOfMonth(); if (this.is().weekday()) { occurrence += 1; } } else { return this; } return this.addWeekdays(occurrence); } var shift = 0; if (occurrence > 0) { shift = occurrence - 1; } else if (occurrence === -1) { this.moveToLastDayOfMonth(); if (this.getDay() !== dayOfWeek) { this.moveToDayOfWeek(dayOfWeek, -1); } return this; } return this.moveToFirstDayOfMonth().addDays(-1).moveToDayOfWeek(dayOfWeek, +1).addWeeks(shift); }; /** * Move to the next or last dayOfWeek based on the orient value. * @param {Number} The dayOfWeek to move to * @param {Number} Forward (+1) or Back (-1). Defaults to +1. [Optional] * @return {Date} this */ $P.moveToDayOfWeek = function (dayOfWeek, orient) { var diff = (dayOfWeek - this.getDay() + 7 * (orient || +1)) % 7; return this.addDays((diff === 0) ? diff += 7 * (orient || +1) : diff); }; /** * Move to the next or last month based on the orient value. * @param {Number} The month to move to. 0 = January, 11 = December * @param {Number} Forward (+1) or Back (-1). Defaults to +1. [Optional] * @return {Date} this */ $P.moveToMonth = function (month, orient) { var diff = (month - this.getMonth() + 12 * (orient || +1)) % 12; return this.addMonths((diff === 0) ? diff += 12 * (orient || +1) : diff); }; /** * Get the Ordinate of the current day ("th", "st", "rd"). * @return {String} */ $P.getOrdinate = function () { var num = this.getDate(); return ord(num); }; /** * Get the Ordinal day (numeric day number) of the year, adjusted for leap year. * @return {Number} 1 through 365 (366 in leap years) */ $P.getOrdinalNumber = function () { return Math.ceil((this.clone().clearTime() - new Date(this.getFullYear(), 0, 1)) / 86400000) + 1; }; /** * Get the time zone abbreviation of the current date. * @return {String} The abbreviated time zone name (e.g. "EST") */ $P.getTimezone = function () { return $D.getTimezoneAbbreviation(this.getUTCOffset(), this.isDaylightSavingTime()); }; $P.setTimezoneOffset = function (offset) { var here = this.getTimezoneOffset(), there = Number(offset) * -6 / 10; return (there || there === 0) ? this.addMinutes(there - here) : this; }; $P.setTimezone = function (offset) { return this.setTimezoneOffset($D.getTimezoneOffset(offset)); }; /** * Indicates whether Daylight Saving Time is observed in the current time zone. * @return {Boolean} true|false */ $P.hasDaylightSavingTime = function () { return (Date.today().set({month: 0, day: 1}).getTimezoneOffset() !== Date.today().set({month: 6, day: 1}).getTimezoneOffset()); }; /** * Indicates whether this Date instance is within the Daylight Saving Time range for the current time zone. * @return {Boolean} true|false */ $P.isDaylightSavingTime = function () { return Date.today().set({month: 0, day: 1}).getTimezoneOffset() !== this.getTimezoneOffset(); }; /** * Get the offset from UTC of the current date. * @return {String} The 4-character offset string prefixed with + or - (e.g. "-0500") */ $P.getUTCOffset = function (offset) { var n = (offset || this.getTimezoneOffset()) * -10 / 6, r; if (n < 0) { r = (n - 10000).toString(); return r.charAt(0) + r.substr(2); } else { r = (n + 10000).toString(); return "+" + r.substr(1); } }; /** * Returns the number of milliseconds between this date and date. * @param {Date} Defaults to now * @return {Number} The diff in milliseconds */ $P.getElapsed = function (date) { return (date || new Date()) - this; }; /** * Converts the value of the current Date object to its equivalent string representation. * Format Specifiers <pre> CUSTOM DATE AND TIME FORMAT STRINGS Format Description Example ------ --------------------------------------------------------------------------- ----------------------- s The seconds of the minute between 0-59. "0" to "59" ss The seconds of the minute with leading zero if required. "00" to "59" m The minute of the hour between 0-59. "0" or "59" mm The minute of the hour with leading zero if required. "00" or "59" h The hour of the day between 1-12. "1" to "12" hh The hour of the day with leading zero if required. "01" to "12" H The hour of the day between 0-23. "0" to "23" HH The hour of the day with leading zero if required. "00" to "23" d The day of the month between 1 and 31. "1" to "31" dd The day of the month with leading zero if required. "01" to "31" ddd Abbreviated day name. Date.CultureInfo.abbreviatedDayNames. "Mon" to "Sun" dddd The full day name. Date.CultureInfo.dayNames. "Monday" to "Sunday" M The month of the year between 1-12. "1" to "12" MM The month of the year with leading zero if required. "01" to "12" MMM Abbreviated month name. Date.CultureInfo.abbreviatedMonthNames. "Jan" to "Dec" MMMM The full month name. Date.CultureInfo.monthNames. "January" to "December" yy The year as a two-digit number. "99" or "08" yyyy The full four digit year. "1999" or "2008" t Displays the first character of the A.M./P.M. designator. "A" or "P" Date.CultureInfo.amDesignator or Date.CultureInfo.pmDesignator tt Displays the A.M./P.M. designator. "AM" or "PM" Date.CultureInfo.amDesignator or Date.CultureInfo.pmDesignator S The ordinal suffix ("st, "nd", "rd" or "th") of the current day. "st, "nd", "rd" or "th" || *Format* || *Description* || *Example* || || d || The CultureInfo shortDate Format Pattern || "M/d/yyyy" || || D || The CultureInfo longDate Format Pattern || "dddd, MMMM dd, yyyy" || || F || The CultureInfo fullDateTime Format Pattern || "dddd, MMMM dd, yyyy h:mm:ss tt" || || m || The CultureInfo monthDay Format Pattern || "MMMM dd" || || r || The CultureInfo rfc1123 Format Pattern || "ddd, dd MMM yyyy HH:mm:ss GMT" || || s || The CultureInfo sortableDateTime Format Pattern || "yyyy-MM-ddTHH:mm:ss" || || t || The CultureInfo shortTime Format Pattern || "h:mm tt" || || T || The CultureInfo longTime Format Pattern || "h:mm:ss tt" || || u || The CultureInfo universalSortableDateTime Format Pattern || "yyyy-MM-dd HH:mm:ssZ" || || y || The CultureInfo yearMonth Format Pattern || "MMMM, yyyy" || STANDARD DATE AND TIME FORMAT STRINGS Format Description Example ("en-US") ------ --------------------------------------------------------------------------- ----------------------- d The CultureInfo shortDate Format Pattern "M/d/yyyy" D The CultureInfo longDate Format Pattern "dddd, MMMM dd, yyyy" F The CultureInfo fullDateTime Format Pattern "dddd, MMMM dd, yyyy h:mm:ss tt" m The CultureInfo monthDay Format Pattern "MMMM dd" r The CultureInfo rfc1123 Format Pattern "ddd, dd MMM yyyy HH:mm:ss GMT" s The CultureInfo sortableDateTime Format Pattern "yyyy-MM-ddTHH:mm:ss" t The CultureInfo shortTime Format Pattern "h:mm tt" T The CultureInfo longTime Format Pattern "h:mm:ss tt" u The CultureInfo universalSortableDateTime Format Pattern "yyyy-MM-dd HH:mm:ssZ" y The CultureInfo yearMonth Format Pattern "MMMM, yyyy" </pre> * @param {String} A format string consisting of one or more format spcifiers [Optional]. * @return {String} A string representation of the current Date object. */ var ord = function (n) { switch (n * 1) { case 1: case 21: case 31: return "st"; case 2: case 22: return "nd"; case 3: case 23: return "rd"; default: return "th"; } }; $P.toString = function (format, ignoreStandards) { var x = this; // Standard Date and Time Format Strings. Formats pulled from CultureInfo file and // may vary by culture. if (!ignoreStandards && format && format.length === 1) { var y, c = Date.CultureInfo.formatPatterns; x.t = x.toString; switch (format) { case "d": return x.t(c.shortDate); case "D": return x.t(c.longDate); case "F": return x.t(c.fullDateTime); case "m": return x.t(c.monthDay); case "r": case "R": y = x.clone().addMinutes(x.getTimezoneOffset()); return y.toString(c.rfc1123) + " GMT"; case "s": return x.t(c.sortableDateTime); case "t": return x.t(c.shortTime); case "T": return x.t(c.longTime); case "u": y = x.clone().addMinutes(x.getTimezoneOffset()); return y.toString(c.universalSortableDateTime); case "y": return x.t(c.yearMonth); } } return format ? format.replace(/((\\)?(dd?d?d?|MM?M?M?|yy?y?y?|hh?|HH?|mm?|ss?|tt?|S|q|Q|WW?W?W?)(?![^\[]*\]))/g, function (m) { if (m.charAt(0) === "\\") { return m.replace("\\", ""); } x.h = x.getHours; switch (m) { case "hh": return p(x.h() < 13 ? (x.h() === 0 ? 12 : x.h()) : (x.h() - 12)); case "h": return x.h() < 13 ? (x.h() === 0 ? 12 : x.h()) : (x.h() - 12); case "HH": return p(x.h()); case "H": return x.h(); case "mm": return p(x.getMinutes()); case "m": return x.getMinutes(); case "ss": return p(x.getSeconds()); case "s": return x.getSeconds(); case "yyyy": return p(x.getFullYear(), 4); case "yy": return p(x.getFullYear()); case "dddd": return Date.CultureInfo.dayNames[x.getDay()]; case "ddd": return Date.CultureInfo.abbreviatedDayNames[x.getDay()]; case "dd": return p(x.getDate()); case "d": return x.getDate(); case "MMMM": return Date.CultureInfo.monthNames[x.getMonth()]; case "MMM": return Date.CultureInfo.abbreviatedMonthNames[x.getMonth()]; case "MM": return p((x.getMonth() + 1)); case "M": return x.getMonth() + 1; case "t": return x.h() < 12 ? Date.CultureInfo.amDesignator.substring(0, 1) : Date.CultureInfo.pmDesignator.substring(0, 1); case "tt": return x.h() < 12 ? Date.CultureInfo.amDesignator : Date.CultureInfo.pmDesignator; case "S": return ord(x.getDate()); case "W": return x.getWeek(); case "WW": return x.getISOWeek(); case "Q": return "Q" + x.getQuarter(); case "q": return String(x.getQuarter()); default: return m; } }).replace(/\[|\]/g, "") : this._toString(); }; }()); (function () { "use strict"; Date.Parsing = { Exception: function (s) { this.message = "Parse error at '" + s.substring(0, 10) + " ...'"; } }; var $P = Date.Parsing; var dayOffsets = { standard: [0,31,59,90,120,151,181,212,243,273,304,334], leap: [0,31,60,91,121,152,182,213,244,274,305,335] }; $P.isLeapYear = function(year) { return ((year % 4 === 0) && (year % 100 !== 0)) || (year % 400 === 0); }; $P.processTimeObject = function (obj) { var d, jan4, date, offset, dayOffset; d = new Date(); dayOffset = ($P.isLeapYear(obj.year)) ? dayOffsets.leap : dayOffsets.standard; obj.hours = obj.hours ? obj.hours : 0; obj.minutes = obj.minutes ? obj.minutes : 0; obj.seconds = obj.seconds ? obj.seconds : 0; obj.milliseconds = obj.milliseconds ? obj.milliseconds : 0; if (!obj.year) { obj.year = d.getFullYear(); } if (!obj.month && (obj.week || obj.dayOfYear)) { // work out the day of the year... if (!obj.dayOfYear) { obj.weekDay = (!obj.weekDay && obj.weekDay !== 0) ? 1 : obj.weekDay; d = new Date(obj.year, 0, 4); jan4 = d.getDay() === 0 ? 7 : d.getDay(); // JS is 0 indexed on Sunday. offset = jan4+3; obj.dayOfYear = ((obj.week * 7) + (obj.weekDay === 0 ? 7 : obj.weekDay))-offset; } for (var i=0;i <= dayOffset.length;i++) { if (obj.dayOfYear < dayOffset[i] || i === dayOffset.length) { obj.day = obj.day ? obj.day : (obj.dayOfYear - dayOffset[i-1]); break; } else { obj.month = i; } } } else { obj.month = obj.month ? obj.month : 0; obj.day = obj.day ? obj.day : 1; obj.dayOfYear = dayOffset[obj.month] + obj.day; } date = new Date(obj.year, obj.month, obj.day, obj.hours, obj.minutes, obj.seconds, obj.milliseconds); if (obj.zone) { // adjust (and calculate) for timezone here if (obj.zone.toUpperCase() === "Z" || (obj.zone_hours === 0 && obj.zone_minutes === 0)) { // it's UTC/GML so work out the current timeszone offset offset = -date.getTimezoneOffset(); } else { offset = (obj.zone_hours*60) + (obj.zone_minutes ? obj.zone_minutes : 0); if (obj.zone_sign === "+") { offset *= -1; } offset -= date.getTimezoneOffset(); } date.setMinutes(date.getMinutes()+offset); } return date; }; $P.ISO = { regex : /^([\+-]?\d{4}(?!\d{2}\b))((-?)((0[1-9]|1[0-2])(\3([12]\d|0[1-9]|3[01]))?|W([0-4]\d|5[0-3])(-?[1-7])?|(00[1-9]|0[1-9]\d|[12]\d{2}|3([0-5]\d|6[1-6])))([T\s]((([01]\d|2[0-4])((:?)[0-5]\d)?|24\:?00)([\.,]\d+(?!:))?)?(\17[0-5]\d([\.,]\d+)?)?\s?([zZ]|([\+-])([01]\d|2[0-3]):?([0-5]\d)?)?)?)?$/, parse : function (s) { var data = s.match(this.regex); if (!data || !data.length) { return null; } var time = { year : data[1] ? Number(data[1]) : data[1], month : data[5] ? (Number(data[5])-1) : data[5], day : data[7] ? Number(data[7]) : data[7], week : data[8] ? Number(data[8]) : data[8], weekDay : data[9] ? (Math.abs(Number(data[9])) === 7 ? 0 : Math.abs(Number(data[9]))) : data[9], // 1-7, starts on Monday. Convert to JS's 0-6 index. dayOfYear : data[10] ? Number(data[10]) : data[10], hours : data[15] ? Number(data[15]) : data[15], minutes : data[16] ? Number(data[16].replace(":","")) : data[16], seconds : data[19] ? Math.floor(Number(data[19].replace(":","").replace(",","."))) : data[19], milliseconds : data[20] ? (Number(data[20].replace(",","."))*1000) : data[20], zone : data[21], zone_sign : data[22], zone_hours : (data[23] && typeof data[23] !== "undefined") ? Number(data[23]) : data[23], zone_minutes : (data[24] && typeof data[23] !== "undefined") ? Number(data[24]) : data[24] }; if (data[18]) { data[18] = 60 * Number(data[18].replace(",", ".")); if (!time.minutes) { time.minutes = data[18]; } else if (!time.seconds) { time.seconds = data[18]; } } if (!time.year || (!time.year && (!time.month && !time.day) && (!time.week && !time.dayOfYear)) ) { return null; } return $P.processTimeObject(time); } }; $P.Numeric = { isNumeric: function (e){return!isNaN(parseFloat(e))&&isFinite(e)}, regex: /\b([0-1]?[0-9])([0-3]?[0-9])([0-2]?[0-9]?[0-9][0-9])\b/i, parse: function (s) { var data, i, time = {}, order = Date.CultureInfo.dateElementOrder.split(""); if (!(this.isNumeric(s)) || // if it's non-numeric OR (s[0] === "+" && s[0] === "-")) { // It's an arithmatic string (eg +/-1000) return null; } if (s.length < 5) { // assume it's just a year. time.year = s; return $P.processTimeObject(time); } data = s.match(this.regex); if (!data || !data.length) { return null; } for (i=0; i < order.length; i++) { switch(order[i]) { case "d": time.day = data[i+1]; break; case "m": time.month = (data[i+1]-1); break; case "y": time.year = data[i+1]; break; } } return $P.processTimeObject(time); } }; $P.Normalizer = { parse: function (s) { var $C = Date.CultureInfo; var $R = Date.CultureInfo.regexPatterns; var __ = Date.i18n.__; s = s.replace($R.jan.source, "January"); s = s.replace($R.feb, "February"); s = s.replace($R.mar, "March"); s = s.replace($R.apr, "April"); s = s.replace($R.may, "May"); s = s.replace($R.jun, "June"); s = s.replace($R.jul, "July"); s = s.replace($R.aug, "August"); s = s.replace($R.sep, "September"); s = s.replace($R.oct, "October"); s = s.replace($R.nov, "November"); s = s.replace($R.dec, "December"); s = s.replace($R.tomorrow, Date.today().addDays(1).toString("d")); s = s.replace($R.yesterday, Date.today().addDays(-1).toString("d")); // s = s.replace(new RegExp($R.today.source + "\\b", "i"), Date.today().toString("d")); s = s.replace(/\bat\b/gi, ""); // replace "at", eg: "tomorrow at 3pm" s = s.replace(/\s{2,}/, " "); // repliace multiple spaces with one. s = s.replace(new RegExp("(\\b\\d\\d?("+__("AM")+"|"+__("PM")+")? )("+$R.tomorrow.source.slice(1)+")", "i"), function(full, m1, m2, m3, m4) { var t = Date.today().addDays(1).toString("d"); var s = t + " " + m1; return s; }); s = s.replace(new RegExp("(("+$R.past.source+')\\s('+$R.mon.source+'))'), Date.today().last().monday().toString("d")); s = s.replace(new RegExp("(("+$R.past.source+')\\s('+$R.tue.source+'))'), Date.today().last().tuesday().toString("d")); s = s.replace(new RegExp("(("+$R.past.source+')\\s('+$R.wed.source+'))'), Date.today().last().wednesday().toString("d")); s = s.replace(new RegExp("(("+$R.past.source+')\\s('+$R.thu.source+'))'), Date.today().last().thursday().toString("d")); s = s.replace(new RegExp("(("+$R.past.source+')\\s('+$R.fri.source+'))'), Date.today().last().friday().toString("d")); s = s.replace(new RegExp("(("+$R.past.source+')\\s('+$R.sat.source+'))'), Date.today().last().saturday().toString("d")); s = s.replace(new RegExp("(("+$R.past.source+')\\s('+$R.sun.source+'))'), Date.today().last().sunday().toString("d")); // s = s.replace($R.thisMorning, "9am")) s = s.replace($R.amThisMorning, function(str, am){return am;}); s = s.replace($R.inTheMorning, "am"); s = s.replace($R.thisMorning, "9am"); s = s.replace($R.amThisEvening, function(str, pm){return pm;}); s = s.replace($R.inTheEvening, "pm"); s = s.replace($R.thisEvening, "7pm"); try { var n = s.split(/([\s\-\.\,\/\x27]+)/); if (n.length === 3) { if ($P.Numeric.isNumeric(n[0]) && $P.Numeric.isNumeric(n[2])) { if (n[2].length >= 4) { // ok, so we're dealing with x/year. But that's not a full date. // This fixes wonky dateElementOrder parsing when set to dmy order. if (Date.CultureInfo.dateElementOrder[0] === 'd') { s = '1/' + n[0] + '/' + n[2]; // set to 1st of month and normalize the seperator } } } } } catch (e) { // continue... } return s; } }; }()); (function () { var $P = Date.Parsing; var _ = $P.Operators = { // // Tokenizers // rtoken: function (r) { // regex token return function (s) { var mx = s.match(r); if (mx) { return ([ mx[0], s.substring(mx[0].length) ]); } else { throw new $P.Exception(s); } }; }, token: function (s) { // whitespace-eating token return function (s) { return _.rtoken(new RegExp("^\s*" + s + "\s*"))(s); // Removed .strip() // return _.rtoken(new RegExp("^\s*" + s + "\s*"))(s).strip(); }; }, stoken: function (s) { // string token return _.rtoken(new RegExp("^" + s)); }, // // Atomic Operators // until: function (p) { return function (s) { var qx = [], rx = null; while (s.length) { try { rx = p.call(this, s); } catch (e) { qx.push(rx[0]); s = rx[1]; continue; } break; } return [ qx, s ]; }; }, many: function (p) { return function (s) { var rx = [], r = null; while (s.length) { try { r = p.call(this, s); } catch (e) { return [ rx, s ]; } rx.push(r[0]); s = r[1]; } return [ rx, s ]; }; }, // generator operators -- see below optional: function (p) { return function (s) { var r = null; try { r = p.call(this, s); } catch (e) { return [ null, s ]; } return [ r[0], r[1] ]; }; }, not: function (p) { return function (s) { try { p.call(this, s); } catch (e) { return [null, s]; } throw new $P.Exception(s); }; }, ignore: function (p) { return p ? function (s) { var r = null; r = p.call(this, s); return [null, r[1]]; } : null; }, product: function () { var px = arguments[0], qx = Array.prototype.slice.call(arguments, 1), rx = []; for (var i = 0 ; i < px.length ; i++) { rx.push(_.each(px[i], qx)); } return rx; }, cache: function (rule) { var cache = {}, r = null; return function (s) { try { r = cache[s] = (cache[s] || rule.call(this, s)); } catch (e) { r = cache[s] = e; } if (r instanceof $P.Exception) { throw r; } else { return r; } }; }, // vector operators -- see below any: function () { var px = arguments; return function (s) { var r = null; for (var i = 0; i < px.length; i++) { if (px[i] == null) { continue; } try { r = (px[i].call(this, s)); } catch (e) { r = null; } if (r) { return r; } } throw new $P.Exception(s); }; }, each: function () { var px = arguments; return function (s) { var rx = [], r = null; for (var i = 0; i < px.length ; i++) { if (px[i] == null) { continue; } try { r = (px[i].call(this, s)); } catch (e) { throw new $P.Exception(s); } rx.push(r[0]); s = r[1]; } return [ rx, s]; }; }, all: function () { var px = arguments, _ = _; return _.each(_.optional(px)); }, // delimited operators sequence: function (px, d, c) { d = d || _.rtoken(/^\s*/); c = c || null; if (px.length == 1) { return px[0]; } return function (s) { var r = null, q = null; var rx = []; for (var i = 0; i < px.length ; i++) { try { r = px[i].call(this, s); } catch (e) { break; } rx.push(r[0]); try { q = d.call(this, r[1]); } catch (ex) { q = null; break; } s = q[1]; } if (!r) { throw new $P.Exception(s); } if (q) { throw new $P.Exception(q[1]); } if (c) { try { r = c.call(this, r[1]); } catch (ey) { throw new $P.Exception(r[1]); } } return [ rx, (r?r[1]:s) ]; }; }, // // Composite Operators // between: function (d1, p, d2) { d2 = d2 || d1; var _fn = _.each(_.ignore(d1), p, _.ignore(d2)); return function (s) { var rx = _fn.call(this, s); return [[rx[0][0], r[0][2]], rx[1]]; }; }, list: function (p, d, c) { d = d || _.rtoken(/^\s*/); c = c || null; return (p instanceof Array ? _.each(_.product(p.slice(0, -1), _.ignore(d)), p.slice(-1), _.ignore(c)) : _.each(_.many(_.each(p, _.ignore(d))), px, _.ignore(c))); }, set: function (px, d, c) { d = d || _.rtoken(/^\s*/); c = c || null; return function (s) { // r is the current match, best the current 'best' match // which means it parsed the most amount of input var r = null, p = null, q = null, rx = null, best = [[], s], last = false; // go through the rules in the given set for (var i = 0; i < px.length ; i++) { // last is a flag indicating whether this must be the last element // if there is only 1 element, then it MUST be the last one q = null; p = null; r = null; last = (px.length == 1); // first, we try simply to match the current pattern // if not, try the next pattern try { r = px[i].call(this, s); } catch (e) { continue; } // since we are matching against a set of elements, the first // thing to do is to add r[0] to matched elements rx = [[r[0]], r[1]]; // if we matched and there is still input to parse and // we don't already know this is the last element, // we're going to next check for the delimiter ... // if there's none, or if there's no input left to parse // than this must be the last element after all ... if (r[1].length > 0 && ! last) { try { q = d.call(this, r[1]); } catch (ex) { last = true; } } else { last = true; } // if we parsed the delimiter and now there's no more input, // that means we shouldn't have parsed the delimiter at all // so don't update r and mark this as the last element ... if (!last && q[1].length === 0) { last = true; } // so, if this isn't the last element, we're going to see if // we can get any more matches from the remaining (unmatched) // elements ... if (!last) { // build a list of the remaining rules we can match against, // i.e., all but the one we just matched against var qx = []; for (var j = 0; j < px.length ; j++) { if (i != j) { qx.push(px[j]); } } // now invoke recursively set with the remaining input // note that we don't include the closing delimiter ... // we'll check for that ourselves at the end p = _.set(qx, d).call(this, q[1]); // if we got a non-empty set as a result ... // (otw rx already contains everything we want to match) if (p[0].length > 0) { // update current result, which is stored in rx ... // basically, pick up the remaining text from p[1] // and concat the result from p[0] so that we don't // get endless nesting ... rx[0] = rx[0].concat(p[0]); rx[1] = p[1]; } } // at this point, rx either contains the last matched element // or the entire matched set that starts with this element. // now we just check to see if this variation is better than // our best so far, in terms of how much of the input is parsed if (rx[1].length < best[1].length) { best = rx; } // if we've parsed all the input, then we're finished if (best[1].length === 0) { break; } } // so now we've either gone through all the patterns trying them // as the initial match; or we found one that parsed the entire // input string ... // if best has no matches, just return empty set ... if (best[0].length === 0) { return best; } // if a closing delimiter is provided, then we have to check it also if (c) { // we try this even if there is no remaining input because the pattern // may well be optional or match empty input ... try { q = c.call(this, best[1]); } catch (ey) { throw new $P.Exception(best[1]); } // it parsed ... be sure to update the best match remaining input best[1] = q[1]; } // if we're here, either there was no closing delimiter or we parsed it // so now we have the best match; just return it! return best; }; }, forward: function (gr, fname) { return function (s) { return gr[fname].call(this, s); }; }, // // Translation Operators // replace: function (rule, repl) { return function (s) { var r = rule.call(this, s); return [repl, r[1]]; }; }, process: function (rule, fn) { return function (s) { var r = rule.call(this, s); return [fn.call(this, r[0]), r[1]]; }; }, min: function (min, rule) { return function (s) { var rx = rule.call(this, s); if (rx[0].length < min) { throw new $P.Exception(s); } return rx; }; } }; // Generator Operators And Vector Operators // Generators are operators that have a signature of F(R) => R, // taking a given rule and returning another rule, such as // ignore, which parses a given rule and throws away the result. // Vector operators are those that have a signature of F(R1,R2,...) => R, // take a list of rules and returning a new rule, such as each. // Generator operators are converted (via the following _generator // function) into functions that can also take a list or array of rules // and return an array of new rules as though the function had been // called on each rule in turn (which is what actually happens). // This allows generators to be used with vector operators more easily. // Example: // each(ignore(foo, bar)) instead of each(ignore(foo), ignore(bar)) // This also turns generators into vector operators, which allows // constructs like: // not(cache(foo, bar)) var _generator = function (op) { function gen() { var args = null, rx = [], px, i; if (arguments.length > 1) { args = Array.prototype.slice.call(arguments); } else if (arguments[0] instanceof Array) { args = arguments[0]; } if (args) { px = args.shift(); if (px.length > 0) { args.unshift(px[i]); rx.push(op.apply(null, args)); args.shift(); return rx; } } else { return op.apply(null, arguments); } } return gen; }; var gx = "optional not ignore cache".split(/\s/); for (var i = 0 ; i < gx.length ; i++) { _[gx[i]] = _generator(_[gx[i]]); } var _vector = function (op) { return function () { if (arguments[0] instanceof Array) { return op.apply(null, arguments[0]); } else { return op.apply(null, arguments); } }; }; var vx = "each any all".split(/\s/); for (var j = 0 ; j < vx.length ; j++) { _[vx[j]] = _vector(_[vx[j]]); } }()); (function () { var $D = Date; var flattenAndCompact = function (ax) { var rx = []; for (var i = 0; i < ax.length; i++) { if (ax[i] instanceof Array) { rx = rx.concat(flattenAndCompact(ax[i])); } else { if (ax[i]) { rx.push(ax[i]); } } } return rx; }; $D.Grammar = {}; $D.Translator = { hour: function (s) { return function () { this.hour = Number(s); }; }, minute: function (s) { return function () { this.minute = Number(s); }; }, second: function (s) { return function () { this.second = Number(s); }; }, /* for ss.s format */ secondAndMillisecond: function (s) { return function () { var mx = s.match(/^([0-5][0-9])\.([0-9]{1,3})/); this.second = Number(mx[1]); this.millisecond = Number(mx[2]); }; }, meridian: function (s) { return function () { this.meridian = s.slice(0, 1).toLowerCase(); }; }, timezone: function (s) { return function () { var n = s.replace(/[^\d\+\-]/g, ""); if (n.length) { this.timezoneOffset = Number(n); } else { this.timezone = s.toLowerCase(); } }; }, day: function (x) { var s = x[0]; return function () { this.day = Number(s.match(/\d+/)[0]); if (this.day < 1) { throw "invalid day"; } }; }, month: function (s) { return function () { this.month = (s.length === 3) ? "jan feb mar apr may jun jul aug sep oct nov dec".indexOf(s)/4 : Number(s) - 1; if (this.month < 0) { throw "invalid month"; } }; }, year: function (s) { return function () { var n = Number(s); this.year = ((s.length > 2) ? n : (n + (((n + 2000) < Date.CultureInfo.twoDigitYearMax) ? 2000 : 1900))); }; }, rday: function (s) { return function () { switch (s) { case "yesterday": this.days = -1; break; case "tomorrow": this.days = 1; break; case "today": this.days = 0; break; case "now": this.days = 0; this.now = true; break; } }; }, finishExact: function (x) { x = (x instanceof Array) ? x : [ x ]; for (var i = 0 ; i < x.length ; i++) { if (x[i]) { x[i].call(this); } } var now = new Date(); if ((this.hour || this.minute) && (!this.month && !this.year && !this.day)) { this.day = now.getDate(); } if (!this.year) { this.year = now.getFullYear(); } if (!this.month && this.month !== 0) { this.month = now.getMonth(); } if (!this.day) { this.day = 1; } if (!this.hour) { this.hour = 0; } if (!this.minute) { this.minute = 0; } if (!this.second) { this.second = 0; } if (!this.millisecond) { this.millisecond = 0; } if (this.meridian && (this.hour || this.hour === 0)) { if (this.meridian == "a" && this.hour > 11 && Date.Config.strict24hr){ throw "Invalid hour and meridian combination"; } else if (this.meridian == "p" && this.hour < 12 && Date.Config.strict24hr){ throw "Invalid hour and meridian combination"; } else if (this.meridian == "p" && this.hour < 12) { this.hour = this.hour + 12; } else if (this.meridian == "a" && this.hour == 12) { this.hour = 0; } } if (this.day > $D.getDaysInMonth(this.year, this.month)) { throw new RangeError(this.day + " is not a valid value for days."); } var r = new Date(this.year, this.month, this.day, this.hour, this.minute, this.second, this.millisecond); if (this.year < 100) { r.setFullYear(this.year); // means years less that 100 are process correctly. JS will parse it otherwise as 1900-1999. } if (this.timezone) { r.set({ timezone: this.timezone }); } else if (this.timezoneOffset) { r.set({ timezoneOffset: this.timezoneOffset }); } return r; }, finish: function (x) { x = (x instanceof Array) ? flattenAndCompact(x) : [ x ]; if (x.length === 0) { return null; } for (var i = 0 ; i < x.length ; i++) { if (typeof x[i] == "function") { x[i].call(this); } } var today = $D.today(); if (this.now && !this.unit && !this.operator) { return new Date(); } else if (this.now) { today = new Date(); } var expression = !!(this.days && this.days !== null || this.orient || this.operator); var gap, mod, orient; orient = ((this.orient == "past" || this.operator == "subtract") ? -1 : 1); if(!this.now && "hour minute second".indexOf(this.unit) != -1) { today.setTimeToNow(); } if (this.month && this.unit == "week") { this.value = this.month + 1; delete this.month; delete this.day; } if (this.month || this.month === 0) { if ("year day hour minute second".indexOf(this.unit) != -1) { if (!this.value) { this.value = this.month + 1; } this.month = null; expression = true; } } if (!expression && this.weekday && !this.day && !this.days) { var temp = Date[this.weekday](); this.day = temp.getDate(); if (!this.month) { this.month = temp.getMonth(); } this.year = temp.getFullYear(); } if (expression && this.weekday && this.unit != "month" && this.unit != "week") { this.unit = "day"; gap = ($D.getDayNumberFromName(this.weekday) - today.getDay()); mod = 7; this.days = gap ? ((gap + (orient * mod)) % mod) : (orient * mod); } if (this.month && this.unit == "day" && this.operator) { if (!this.value) { this.value = (this.month + 1); } this.month = null; } if (this.value != null && this.month != null && this.year != null) { this.day = this.value * 1; } if (this.month && !this.day && this.value) { today.set({ day: this.value * 1 }); if (!expression) { this.day = this.value * 1; } } if (!this.month && this.value && this.unit == "month" && !this.now) { this.month = this.value; expression = true; } if (expression && (this.month || this.month === 0) && this.unit != "year") { this.unit = "month"; gap = (this.month - today.getMonth()); mod = 12; this.months = gap ? ((gap + (orient * mod)) % mod) : (orient * mod); this.month = null; } if (!this.unit) { this.unit = "day"; } if (!this.value && this.operator && this.operator !== null && this[this.unit + "s"] && this[this.unit + "s"] !== null) { this[this.unit + "s"] = this[this.unit + "s"] + ((this.operator == "add") ? 1 : -1) + (this.value||0) * orient; } else if (this[this.unit + "s"] == null || this.operator != null) { if (!this.value) { this.value = 1; } this[this.unit + "s"] = this.value * orient; } if (this.meridian && (this.hour || this.hour === 0)) { if (this.meridian == "a" && this.hour > 11 && Date.Config.strict24hr){ throw "Invalid hour and meridian combination"; } else if (this.meridian == "p" && this.hour < 12 && Date.Config.strict24hr){ throw "Invalid hour and meridian combination"; } else if (this.meridian == "p" && this.hour < 12) { this.hour = this.hour + 12; } else if (this.meridian == "a" && this.hour == 12) { this.hour = 0; } } if (this.weekday && this.unit !== "week" && !this.day && !this.days) { var temp = Date[this.weekday](); this.day = temp.getDate(); if (temp.getMonth() !== today.getMonth()) { this.month = temp.getMonth(); } } if ((this.month || this.month === 0) && !this.day) { this.day = 1; } if (!this.orient && !this.operator && this.unit == "week" && this.value && !this.day && !this.month) { return Date.today().setWeek(this.value); } if (this.unit == "week" && this.weeks && !this.day && !this.month) { var weekday = (this.weekday) ? this.weekday : "today"; var d = Date[weekday]().addWeeks(this.weeks); if (this.now) { d.setTimeToNow(); } return d; } if (expression && this.timezone && this.day && this.days) { this.day = this.days; } return (expression) ? today.add(this) : today.set(this); } }; var _ = $D.Parsing.Operators, g = $D.Grammar, t = $D.Translator, _fn; g.datePartDelimiter = _.rtoken(/^([\s\-\.\,\/\x27]+)/); g.timePartDelimiter = _.stoken(":"); g.whiteSpace = _.rtoken(/^\s*/); g.generalDelimiter = _.rtoken(/^(([\s\,]|at|@|on)+)/); var _C = {}; g.ctoken = function (keys) { var fn = _C[keys]; if (! fn) { var c = Date.CultureInfo.regexPatterns; var kx = keys.split(/\s+/), px = []; for (var i = 0; i < kx.length ; i++) { px.push(_.replace(_.rtoken(c[kx[i]]), kx[i])); } fn = _C[keys] = _.any.apply(null, px); } return fn; }; g.ctoken2 = function (key) { return _.rtoken(Date.CultureInfo.regexPatterns[key]); }; // hour, minute, second, meridian, timezone g.h = _.cache(_.process(_.rtoken(/^(0[0-9]|1[0-2]|[1-9])/), t.hour)); g.hh = _.cache(_.process(_.rtoken(/^(0[0-9]|1[0-2])/), t.hour)); g.H = _.cache(_.process(_.rtoken(/^([0-1][0-9]|2[0-3]|[0-9])/), t.hour)); g.HH = _.cache(_.process(_.rtoken(/^([0-1][0-9]|2[0-3])/), t.hour)); g.m = _.cache(_.process(_.rtoken(/^([0-5][0-9]|[0-9])/), t.minute)); g.mm = _.cache(_.process(_.rtoken(/^[0-5][0-9]/), t.minute)); g.s = _.cache(_.process(_.rtoken(/^([0-5][0-9]|[0-9])/), t.second)); g.ss = _.cache(_.process(_.rtoken(/^[0-5][0-9]/), t.second)); g["ss.s"] = _.cache(_.process(_.rtoken(/^[0-5][0-9]\.[0-9]{1,3}/), t.secondAndMillisecond)); g.hms = _.cache(_.sequence([g.H, g.m, g.s], g.timePartDelimiter)); // _.min(1, _.set([ g.H, g.m, g.s ], g._t)); g.t = _.cache(_.process(g.ctoken2("shortMeridian"), t.meridian)); g.tt = _.cache(_.process(g.ctoken2("longMeridian"), t.meridian)); g.z = _.cache(_.process(_.rtoken(/^((\+|\-)\s*\d\d\d\d)|((\+|\-)\d\d\:?\d\d)/), t.timezone)); g.zz = _.cache(_.process(_.rtoken(/^((\+|\-)\s*\d\d\d\d)|((\+|\-)\d\d\:?\d\d)/), t.timezone)); g.zzz = _.cache(_.process(g.ctoken2("timezone"), t.timezone)); g.timeSuffix = _.each(_.ignore(g.whiteSpace), _.set([ g.tt, g.zzz ])); g.time = _.each(_.optional(_.ignore(_.stoken("T"))), g.hms, g.timeSuffix); // days, months, years g.d = _.cache(_.process(_.each(_.rtoken(/^([0-2]\d|3[0-1]|\d)/), _.optional(g.ctoken2("ordinalSuffix"))), t.day)); g.dd = _.cache(_.process(_.each(_.rtoken(/^([0-2]\d|3[0-1])/), _.optional(g.ctoken2("ordinalSuffix"))), t.day)); g.ddd = g.dddd = _.cache(_.process(g.ctoken("sun mon tue wed thu fri sat"), function (s) { return function () { this.weekday = s; }; } )); g.M = _.cache(_.process(_.rtoken(/^(1[0-2]|0\d|\d)/), t.month)); g.MM = _.cache(_.process(_.rtoken(/^(1[0-2]|0\d)/), t.month)); g.MMM = g.MMMM = _.cache(_.process(g.ctoken("jan feb mar apr may jun jul aug sep oct nov dec"), t.month)); // g.MMM = g.MMMM = _.cache(_.process(g.ctoken(Date.CultureInfo.abbreviatedMonthNames.join(" ")), t.month)); g.y = _.cache(_.process(_.rtoken(/^(\d\d?)/), t.year)); g.yy = _.cache(_.process(_.rtoken(/^(\d\d)/), t.year)); g.yyy = _.cache(_.process(_.rtoken(/^(\d\d?\d?\d?)/), t.year)); g.yyyy = _.cache(_.process(_.rtoken(/^(\d\d\d\d)/), t.year)); // rolling these up into general purpose rules _fn = function () { return _.each(_.any.apply(null, arguments), _.not(g.ctoken2("timeContext"))); }; g.day = _fn(g.d, g.dd); g.month = _fn(g.M, g.MMM); g.year = _fn(g.yyyy, g.yy); // relative date / time expressions g.orientation = _.process(g.ctoken("past future"), function (s) { return function () { this.orient = s; }; } ); g.operator = _.process(g.ctoken("add subtract"), function (s) { return function () { this.operator = s; }; } ); g.rday = _.process(g.ctoken("yesterday tomorrow today now"), t.rday); g.unit = _.process(g.ctoken("second minute hour day week month year"), function (s) { return function () { this.unit = s; }; } ); g.value = _.process(_.rtoken(/^([-+]?\d+)?(st|nd|rd|th)?/), function (s) { return function () { this.value = s.replace(/\D/g, ""); }; } ); g.expression = _.set([ g.rday, g.operator, g.value, g.unit, g.orientation, g.ddd, g.MMM ]); // pre-loaded rules for different date part order preferences _fn = function () { return _.set(arguments, g.datePartDelimiter); }; g.mdy = _fn(g.ddd, g.month, g.day, g.year); g.ymd = _fn(g.ddd, g.year, g.month, g.day); g.dmy = _fn(g.ddd, g.day, g.month, g.year); g.date = function (s) { return ((g[Date.CultureInfo.dateElementOrder] || g.mdy).call(this, s)); }; // parsing date format specifiers - ex: "h:m:s tt" // this little guy will generate a custom parser based // on the format string, ex: g.format("h:m:s tt") g.format = _.process(_.many( _.any( // translate format specifiers into grammar rules _.process( _.rtoken(/^(dd?d?d?(?!e)|MM?M?M?|yy?y?y?|hh?|HH?|mm?|ss?|tt?|zz?z?)/), function (fmt) { if (g[fmt]) { return g[fmt]; } else { throw $D.Parsing.Exception(fmt); } } ), // translate separator tokens into token rules _.process(_.rtoken(/^[^dMyhHmstz]+/), // all legal separators function (s) { return _.ignore(_.stoken(s)); } ) )), // construct the parser ... function (rules) { return _.process(_.each.apply(null, rules), t.finishExact); } ); var _F = { //"M/d/yyyy": function (s) { // var m = s.match(/^([0-2]\d|3[0-1]|\d)\/(1[0-2]|0\d|\d)\/(\d\d\d\d)/); // if (m!=null) { // var r = [ t.month.call(this,m[1]), t.day.call(this,m[2]), t.year.call(this,m[3]) ]; // r = t.finishExact.call(this,r); // return [ r, "" ]; // } else { // throw new Date.Parsing.Exception(s); // } //} //"M/d/yyyy": function (s) { return [ new Date(Date._parse(s)), ""]; } }; var _get = function (f) { _F[f] = (_F[f] || g.format(f)[0]); return _F[f]; }; g.allformats = function (fx) { var rx = []; if (fx instanceof Array) { for (var i = 0; i < fx.length; i++) { rx.push(_get(fx[i])); } } else { rx.push(_get(fx)); } return rx; }; g.formats = function (fx) { if (fx instanceof Array) { var rx = []; for (var i = 0 ; i < fx.length ; i++) { rx.push(_get(fx[i])); } return _.any.apply(null, rx); } else { return _get(fx); } }; // check for these formats first g._formats = g.formats([ "\"yyyy-MM-ddTHH:mm:ssZ\"", "yyyy-MM-ddTHH:mm:ss.sz", "yyyy-MM-ddTHH:mm:ssZ", "yyyy-MM-ddTHH:mm:ssz", "yyyy-MM-ddTHH:mm:ss", "yyyy-MM-ddTHH:mmZ", "yyyy-MM-ddTHH:mmz", "yyyy-MM-ddTHH:mm", "ddd, MMM dd, yyyy H:mm:ss tt", "ddd MMM d yyyy HH:mm:ss zzz", "MMddyyyy", "ddMMyyyy", "Mddyyyy", "ddMyyyy", "Mdyyyy", "dMyyyy", "yyyy", "Mdyy", "dMyy", "d" ]); // starting rule for general purpose grammar g._start = _.process(_.set([ g.date, g.time, g.expression ], g.generalDelimiter, g.whiteSpace), t.finish); // real starting rule: tries selected formats first, // then general purpose rule g.start = function (s) { try { var r = g._formats.call({}, s); if (r[1].length === 0) { return r; } } catch (e) {} return g._start.call({}, s); }; /** * @desc Converts the specified string value into its JavaScript Date equivalent using CultureInfo specific format information. * * Example <pre><code> /////////// // Dates // /////////// // 15-Oct-2004 var d1 = Date.parse("10/15/2004"); // 15-Oct-2004 var d1 = Date.parse("15-Oct-2004"); // 15-Oct-2004 var d1 = Date.parse("2004.10.15"); //Fri Oct 15, 2004 var d1 = Date.parse("Fri Oct 15, 2004"); /////////// // Times // /////////// // Today at 10 PM. var d1 = Date.parse("10 PM"); // Today at 10:30 PM. var d1 = Date.parse("10:30 P.M."); // Today at 6 AM. var d1 = Date.parse("06am"); ///////////////////// // Dates and Times // ///////////////////// // 8-July-2004 @ 10:30 PM var d1 = Date.parse("July 8th, 2004, 10:30 PM"); // 1-July-2004 @ 10:30 PM var d1 = Date.parse("2004-07-01T22:30:00"); //////////////////// // Relative Dates // //////////////////// // Returns today's date. The string "today" is culture specific. var d1 = Date.parse("today"); // Returns yesterday's date. The string "yesterday" is culture specific. var d1 = Date.parse("yesterday"); // Returns the date of the next thursday. var d1 = Date.parse("Next thursday"); // Returns the date of the most previous monday. var d1 = Date.parse("last monday"); // Returns today's day + one year. var d1 = Date.parse("next year"); /////////////// // Date Math // /////////////// // Today + 2 days var d1 = Date.parse("t+2"); // Today + 2 days var d1 = Date.parse("today + 2 days"); // Today + 3 months var d1 = Date.parse("t+3m"); // Today - 1 year var d1 = Date.parse("today - 1 year"); // Today - 1 year var d1 = Date.parse("t-1y"); ///////////////////////////// // Partial Dates and Times // ///////////////////////////// // July 15th of this year. var d1 = Date.parse("July 15"); // 15th day of current day and year. var d1 = Date.parse("15"); // July 1st of current year at 10pm. var d1 = Date.parse("7/1 10pm"); </code></pre> * * @param {String} The string value to convert into a Date object [Required] * @return {Date} A Date object or null if the string cannot be converted into a Date. */ function parse (s) { var ords, d, t, r = null; if (!s) { return null; } if (s instanceof Date) { return s.clone(); } if (s.length >= 4 && s.charAt(0) !== "0" && s.charAt(0) !== "+"&& s.charAt(0) !== "-") { // ie: 2004 will pass, 0800 won't. // Start with specific formats d = $D.Parsing.ISO.parse(s) || $D.Parsing.Numeric.parse(s); } if (d instanceof Date && !isNaN(d.getTime())) { return d; } else { // find ordinal dates (1st, 3rd, 8th, etc and remove them as they cause parsing issues) ords = s.match(/\b(\d+)(?:st|nd|rd|th)\b/); // find ordinal matches s = ((ords && ords.length === 2) ? s.replace(ords[0], ords[1]) : s); s = $D.Parsing.Normalizer.parse(s); try { r = $D.Grammar.start.call({}, s.replace(/^\s*(\S*(\s+\S+)*)\s*$/, "$1")); } catch (e) { return null; } d = ((r[1].length === 0) ? r[0] : null); if (d !== null) { return d; } else { try { // ok we haven't parsed it, last ditch attempt with the built-in parser. t = Date._parse(s); return (t || t === 0) ? new Date(t) : null; } catch (e) { return null; } } } } if (!$D._parse) { $D._parse = $D.parse; } $D.parse = parse; Date.getParseFunction = function (fx) { var fns = Date.Grammar.allformats(fx); return function (s) { var r = null; for (var i = 0; i < fns.length; i++) { try { r = fns[i].call({}, s); } catch (e) { continue; } if (r[1].length === 0) { return r[0]; } } return null; }; }; /** * Converts the specified string value into its JavaScript Date equivalent using the specified format {String} or formats {Array} and the CultureInfo specific format information. * The format of the string value must match one of the supplied formats exactly. * * Example <pre><code> // 15-Oct-2004 var d1 = Date.parseExact("10/15/2004", "M/d/yyyy"); // 15-Oct-2004 var d1 = Date.parse("15-Oct-2004", "M-ddd-yyyy"); // 15-Oct-2004 var d1 = Date.parse("2004.10.15", "yyyy.MM.dd"); // Multiple formats var d1 = Date.parseExact("10/15/2004", ["M/d/yyyy", "MMMM d, yyyy"]); </code></pre> * * @param {String} The string value to convert into a Date object [Required]. * @param {Object} The expected format {String} or an array of expected formats {Array} of the date string [Required]. * @return {Date} A Date object or null if the string cannot be converted into a Date. */ $D.parseExact = function (s, fx) { return $D.getParseFunction(fx)(s); }; }()); /************************************************************* * SugarPak - Domain Specific Language - Syntactical Sugar * *************************************************************/ (function () { var $D = Date, $P = $D.prototype, $N = Number.prototype; // private $P._orient = +1; // private $P._nth = null; // private $P._is = false; // private $P._same = false; // private $P._isSecond = false; // private $N._dateElement = "days"; /** * Moves the date to the next instance of a date as specified by the subsequent date element function (eg. .day(), .month()), month name function (eg. .january(), .jan()) or day name function (eg. .friday(), fri()). * Example <pre><code> Date.today().next().friday(); Date.today().next().fri(); Date.today().next().march(); Date.today().next().mar(); Date.today().next().week(); </code></pre> * * @return {Date} date */ $P.next = function () { this._move = true; this._orient = +1; return this; }; /** * Creates a new Date (Date.today()) and moves the date to the next instance of the date as specified by the subsequent date element function (eg. .day(), .month()), month name function (eg. .january(), .jan()) or day name function (eg. .friday(), fri()). * Example <pre><code> Date.next().friday(); Date.next().fri(); Date.next().march(); Date.next().mar(); Date.next().week(); </code></pre> * * @return {Date} date */ $D.next = function () { return $D.today().next(); }; /** * Moves the date to the previous instance of a date as specified by the subsequent date element function (eg. .day(), .month()), month name function (eg. .january(), .jan()) or day name function (eg. .friday(), fri()). * Example <pre><code> Date.today().last().friday(); Date.today().last().fri(); Date.today().last().march(); Date.today().last().mar(); Date.today().last().week(); </code></pre> * * @return {Date} date */ $P.last = $P.prev = $P.previous = function () { this._move = true; this._orient = -1; return this; }; /** * Creates a new Date (Date.today()) and moves the date to the previous instance of the date as specified by the subsequent date element function (eg. .day(), .month()), month name function (eg. .january(), .jan()) or day name function (eg. .friday(), fri()). * Example <pre><code> Date.last().friday(); Date.last().fri(); Date.previous().march(); Date.prev().mar(); Date.last().week(); </code></pre> * * @return {Date} date */ $D.last = $D.prev = $D.previous = function () { return $D.today().last(); }; /** * Performs a equality check when followed by either a month name, day name or .weekday() function. * Example <pre><code> Date.today().is().friday(); // true|false Date.today().is().fri(); Date.today().is().march(); Date.today().is().mar(); </code></pre> * * @return {Boolean} true|false */ $P.is = function () { this._is = true; return this; }; /** * Determines if two date objects occur on/in exactly the same instance of the subsequent date part function. * The function .same() must be followed by a date part function (example: .day(), .month(), .year(), etc). * * An optional Date can be passed in the date part function. If now date is passed as a parameter, 'Now' is used. * * The following example demonstrates how to determine if two dates fall on the exact same day. * * Example <pre><code> var d1 = Date.today(); // today at 00:00 var d2 = new Date(); // exactly now. // Do they occur on the same day? d1.same().day(d2); // true // Do they occur on the same hour? d1.same().hour(d2); // false, unless d2 hour is '00' (midnight). // What if it's the same day, but one year apart? var nextYear = Date.today().add(1).year(); d1.same().day(nextYear); // false, because the dates must occur on the exact same day. </code></pre> * * Scenario: Determine if a given date occurs during some week period 2 months from now. * * Example <pre><code> var future = Date.today().add(2).months(); return someDate.same().week(future); // true|false; </code></pre> * * @return {Boolean} true|false */ $P.same = function () { this._same = true; this._isSecond = false; return this; }; /** * Determines if the current date/time occurs during Today. Must be preceded by the .is() function. * Example <pre><code> someDate.is().today(); // true|false new Date().is().today(); // true Date.today().is().today();// true Date.today().add(-1).day().is().today(); // false </code></pre> * * @return {Boolean} true|false */ $P.today = function () { return this.same().day(); }; /** * Determines if the current date is a weekday. This function must be preceded by the .is() function. * Example <pre><code> Date.today().is().weekday(); // true|false </code></pre> * * @return {Boolean} true|false */ $P.weekday = function () { if (this._nth) { return df("Weekday").call(this); } if (this._move) { return this.addWeekdays(this._orient); } if (this._is) { this._is = false; return (!this.is().sat() && !this.is().sun()); } return false; }; /** * Determines if the current date is on the weekend. This function must be preceded by the .is() function. * Example <pre><code> Date.today().is().weekend(); // true|false </code></pre> * * @return {Boolean} true|false */ $P.weekend = function () { if (this._is) { this._is = false; return (this.is().sat() || this.is().sun()); } return false; }; /** * Sets the Time of the current Date instance. A string "6:15 pm" or config object {hour:18, minute:15} are accepted. * Example <pre><code> // Set time to 6:15pm with a String Date.today().at("6:15pm"); // Set time to 6:15pm with a config object Date.today().at({hour:18, minute:15}); </code></pre> * * @return {Date} date */ $P.at = function (time) { return (typeof time === "string") ? $D.parse(this.toString("d") + " " + time) : this.set(time); }; /** * Creates a new Date() and adds this (Number) to the date based on the preceding date element function (eg. second|minute|hour|day|month|year). * Example <pre><code> // Undeclared Numbers must be wrapped with parentheses. Requirment of JavaScript. (3).days().fromNow(); (6).months().fromNow(); // Declared Number variables do not require parentheses. var n = 6; n.months().fromNow(); </code></pre> * * @return {Date} A new Date instance */ $N.fromNow = $N.after = function (date) { var c = {}; c[this._dateElement] = this; return ((!date) ? new Date() : date.clone()).add(c); }; /** * Creates a new Date() and subtract this (Number) from the date based on the preceding date element function (eg. second|minute|hour|day|month|year). * Example <pre><code> // Undeclared Numbers must be wrapped with parentheses. Requirment of JavaScript. (3).days().ago(); (6).months().ago(); // Declared Number variables do not require parentheses. var n = 6; n.months().ago(); </code></pre> * * @return {Date} A new Date instance */ $N.ago = $N.before = function (date) { var c = {}, s = (this._dateElement[this._dateElement.length-1] !== "s") ? this._dateElement + "s" : this._dateElement; c[s] = this * -1; return ((!date) ? new Date() : date.clone()).add(c); }; // Do NOT modify the following string tokens. These tokens are used to build dynamic functions. // All culture-specific strings can be found in the CultureInfo files. var dx = ("sunday monday tuesday wednesday thursday friday saturday").split(/\s/), mx = ("january february march april may june july august september october november december").split(/\s/), px = ("Millisecond Second Minute Hour Day Week Month Year Quarter Weekday").split(/\s/), pxf = ("Milliseconds Seconds Minutes Hours Date Week Month FullYear Quarter").split(/\s/), nth = ("final first second third fourth fifth").split(/\s/), de; /** * Returns an object literal of all the date parts. * Example <pre><code> var o = new Date().toObject(); // { year: 2008, month: 4, week: 20, day: 13, hour: 18, minute: 9, second: 32, millisecond: 812 } // The object properties can be referenced directly from the object. alert(o.day); // alerts "13" alert(o.year); // alerts "2008" </code></pre> * * @return {Date} An object literal representing the original date object. */ $P.toObject = function () { var o = {}; for (var i = 0; i < px.length; i++) { if (this["get" + pxf[i]]) { o[px[i].toLowerCase()] = this["get" + pxf[i]](); } } return o; }; /** * Returns a date created from an object literal. Ignores the .week property if set in the config. * Example <pre><code> var o = new Date().toObject(); return Date.fromObject(o); // will return the same date. var o2 = {month: 1, day: 20, hour: 18}; // birthday party! Date.fromObject(o2); </code></pre> * * @return {Date} An object literal representing the original date object. */ $D.fromObject = function(config) { config.week = null; return Date.today().set(config); }; // Create day name functions and abbreviated day name functions (eg. monday(), friday(), fri()). var df = function (n) { return function () { if (this._is) { this._is = false; return this.getDay() === n; } if (this._move) { this._move = null; } if (this._nth !== null) { // If the .second() function was called earlier, remove the _orient // from the date, and then continue. // This is required because 'second' can be used in two different context. // // Example // // Date.today().add(1).second(); // Date.march().second().monday(); // // Things get crazy with the following... // Date.march().add(1).second().second().monday(); // but it works!! // if (this._isSecond) { this.addSeconds(this._orient * -1); } // make sure we reset _isSecond this._isSecond = false; var ntemp = this._nth; this._nth = null; var temp = this.clone().moveToLastDayOfMonth(); this.moveToNthOccurrence(n, ntemp); if (this > temp) { throw new RangeError($D.getDayName(n) + " does not occur " + ntemp + " times in the month of " + $D.getMonthName(temp.getMonth()) + " " + temp.getFullYear() + "."); } return this; } return this.moveToDayOfWeek(n, this._orient); }; }; var sdf = function (n) { return function () { var t = $D.today(), shift = n - t.getDay(); if (n === 0 && Date.CultureInfo.firstDayOfWeek === 1 && t.getDay() !== 0) { shift = shift + 7; } return t.addDays(shift); }; }; for (var i = 0; i < dx.length; i++) { // Create constant static Day Name variables. Example: Date.MONDAY or Date.MON $D[dx[i].toUpperCase()] = $D[dx[i].toUpperCase().substring(0, 3)] = i; // Create Day Name functions. Example: Date.monday() or Date.mon() $D[dx[i]] = $D[dx[i].substring(0, 3)] = sdf(i); // Create Day Name instance functions. Example: Date.today().next().monday() $P[dx[i]] = $P[dx[i].substring(0, 3)] = df(i); } // Create month name functions and abbreviated month name functions (eg. january(), march(), mar()). var month_instance_functions = function (n) { return function () { if (this._is) { this._is = false; return this.getMonth() === n; } return this.moveToMonth(n, this._orient); }; }; var month_static_functions = function (n) { return function () { return $D.today().set({ month: n, day: 1 }); }; }; for (var j = 0; j < mx.length; j++) { // Create constant static Month Name variables. Example: Date.MARCH or Date.MAR $D[mx[j].toUpperCase()] = $D[mx[j].toUpperCase().substring(0, 3)] = j; // Create Month Name functions. Example: Date.march() or Date.mar() $D[mx[j]] = $D[mx[j].substring(0, 3)] = month_static_functions(j); // Create Month Name instance functions. Example: Date.today().next().march() $P[mx[j]] = $P[mx[j].substring(0, 3)] = month_instance_functions(j); } // Create date element functions and plural date element functions used with Date (eg. day(), days(), months()). var ef = function (j) { return function () { // if the .second() function was called earlier, the _orient // has alread been added. Just return this and reset _isSecond. if (this._isSecond) { this._isSecond = false; return this; } if (this._same) { this._same = this._is = false; var o1 = this.toObject(), o2 = (arguments[0] || new Date()).toObject(), v = "", k = j.toLowerCase(); // the substr trick with -1 doesn't work in IE8 or less k = (k[k.length-1] === "s") ? k.substring(0,k.length-1) : k; for (var m = (px.length - 1); m > -1; m--) { v = px[m].toLowerCase(); if (o1[v] !== o2[v]) { return false; } if (k === v) { break; } } return true; } if (j.substring(j.length - 1) !== "s") { j += "s"; } if (this._move) { this._move = null; } return this["add" + j](this._orient); }; }; var nf = function (n) { return function () { this._dateElement = n; return this; }; }; for (var k = 0; k < px.length; k++) { de = px[k].toLowerCase(); if(de !== "weekday") { // Create date element functions and plural date element functions used with Date (eg. day(), days(), months()). $P[de] = $P[de + "s"] = ef(px[k]); // Create date element functions and plural date element functions used with Number (eg. day(), days(), months()). $N[de] = $N[de + "s"] = nf(de + "s"); } } $P._ss = ef("Second"); var nthfn = function (n) { return function (dayOfWeek) { if (this._same) { return this._ss(arguments[0]); } if (dayOfWeek || dayOfWeek === 0) { return this.moveToNthOccurrence(dayOfWeek, n); } this._nth = n; // if the operator is 'second' add the _orient, then deal with it later... if (n === 2 && (dayOfWeek === undefined || dayOfWeek === null)) { this._isSecond = true; return this.addSeconds(this._orient); } return this; }; }; for (var l = 0; l < nth.length; l++) { $P[nth[l]] = (l === 0) ? nthfn(-1) : nthfn(l); } }()); (function () { var $D = Date, $P = $D.prototype, // $C = $D.CultureInfo, // not used atm $f = [], p = function (s, l) { if (!l) { l = 2; } return ("000" + s).slice(l * -1); }; /** * Converts a PHP format string to Java/.NET format string. * A PHP format string can be used with .$format or .format. * A Java/.NET format string can be used with .toString(). * The .parseExact function will only accept a Java/.NET format string * * Example <pre> var f1 = "%m/%d/%y" var f2 = Date.normalizeFormat(f1); // "MM/dd/yy" new Date().format(f1); // "04/13/08" new Date().$format(f1); // "04/13/08" new Date().toString(f2); // "04/13/08" var date = Date.parseExact("04/13/08", f2); // Sun Apr 13 2008 </pre> * @param {String} A PHP format string consisting of one or more format spcifiers. * @return {String} The PHP format converted to a Java/.NET format string. */ $D.normalizeFormat = function (format) { // function does nothing atm // $f = []; // var t = new Date().$format(format); // return $f.join(""); return format; }; /** * Format a local Unix timestamp according to locale settings * * Example <pre> Date.strftime("%m/%d/%y", new Date()); // "04/13/08" Date.strftime("c", "2008-04-13T17:52:03Z"); // "04/13/08" </pre> * @param {String} A format string consisting of one or more format spcifiers [Optional]. * @param {Number} The number representing the number of seconds that have elapsed since January 1, 1970 (local time). * @return {String} A string representation of the current Date object. */ $D.strftime = function (format, time) { return new Date(time * 1000).$format(format); }; /** * Parse any textual datetime description into a Unix timestamp. * A Unix timestamp is the number of seconds that have elapsed since January 1, 1970 (midnight UTC/GMT). * * Example <pre> Date.strtotime("04/13/08"); // 1208044800 Date.strtotime("1970-01-01T00:00:00Z"); // 0 </pre> * @param {String} A format string consisting of one or more format spcifiers [Optional]. * @param {Object} A string or date object. * @return {String} A string representation of the current Date object. */ $D.strtotime = function (time) { var d = $D.parse(time); d.addMinutes(d.getTimezoneOffset() * -1); return Math.round($D.UTC(d.getUTCFullYear(), d.getUTCMonth(), d.getUTCDate(), d.getUTCHours(), d.getUTCMinutes(), d.getUTCSeconds(), d.getUTCMilliseconds()) / 1000); }; /** * Converts the value of the current Date object to its equivalent string representation using a PHP/Unix style of date format specifiers. * * The following descriptions are from http://www.php.net/strftime and http://www.php.net/manual/en/function.date.php. * Copyright � 2001-2008 The PHP Group * * Format Specifiers <pre> Format Description Example ------ --------------------------------------------------------------------------- ----------------------- %a abbreviated weekday name according to the current localed "Mon" through "Sun" %A full weekday name according to the current locale "Sunday" through "Saturday" %b abbreviated month name according to the current locale "Jan" through "Dec" %B full month name according to the current locale "January" through "December" %c preferred date and time representation for the current locale "4/13/2008 12:33 PM" %C century number (the year divided by 100 and truncated to an integer) "00" to "99" %d day of the month as a decimal number "01" to "31" %D same as %m/%d/%y "04/13/08" %e day of the month as a decimal number, a single digit is preceded by a space "1" to "31" %g like %G, but without the century "08" %G The 4-digit year corresponding to the ISO week number (see %V). "2008" This has the same format and value as %Y, except that if the ISO week number belongs to the previous or next year, that year is used instead. %h same as %b "Jan" through "Dec" %H hour as a decimal number using a 24-hour clock "00" to "23" %I hour as a decimal number using a 12-hour clock "01" to "12" %j day of the year as a decimal number "001" to "366" %m month as a decimal number "01" to "12" %M minute as a decimal number "00" to "59" %n newline character "\n" %p either "am" or "pm" according to the given time value, or the "am" or "pm" corresponding strings for the current locale %r time in a.m. and p.m. notation "8:44 PM" %R time in 24 hour notation "20:44" %S second as a decimal number "00" to "59" %t tab character "\t" %T current time, equal to %H:%M:%S "12:49:11" %u weekday as a decimal number ["1", "7"], with "1" representing Monday "1" to "7" %U week number of the current year as a decimal number, starting with the "0" to ("52" or "53") first Sunday as the first day of the first week %V The ISO 8601:1988 week number of the current year as a decimal number, "00" to ("52" or "53") range 01 to 53, where week 1 is the first week that has at least 4 days in the current year, and with Monday as the first day of the week. (Use %G or %g for the year component that corresponds to the week number for the specified timestamp.) %W week number of the current year as a decimal number, starting with the "00" to ("52" or "53") first Monday as the first day of the first week %w day of the week as a decimal, Sunday being "0" "0" to "6" %x preferred date representation for the current locale without the time "4/13/2008" %X preferred time representation for the current locale without the date "12:53:05" %y year as a decimal number without a century "00" "99" %Y year as a decimal number including the century "2008" %Z time zone or name or abbreviation "UTC", "EST", "PST" %z same as %Z %% a literal "%" character "%" d Day of the month, 2 digits with leading zeros "01" to "31" D A textual representation of a day, three letters "Mon" through "Sun" j Day of the month without leading zeros "1" to "31" l A full textual representation of the day of the week (lowercase "L") "Sunday" through "Saturday" N ISO-8601 numeric representation of the day of the week (added in PHP 5.1.0) "1" (for Monday) through "7" (for Sunday) S English ordinal suffix for the day of the month, 2 characters "st", "nd", "rd" or "th". Works well with j w Numeric representation of the day of the week "0" (for Sunday) through "6" (for Saturday) z The day of the year (starting from "0") "0" through "365" W ISO-8601 week number of year, weeks starting on Monday "00" to ("52" or "53") F A full textual representation of a month, such as January or March "January" through "December" m Numeric representation of a month, with leading zeros "01" through "12" M A short textual representation of a month, three letters "Jan" through "Dec" n Numeric representation of a month, without leading zeros "1" through "12" t Number of days in the given month "28" through "31" L Whether it's a leap year "1" if it is a leap year, "0" otherwise o ISO-8601 year number. This has the same value as Y, except that if the "2008" ISO week number (W) belongs to the previous or next year, that year is used instead. Y A full numeric representation of a year, 4 digits "2008" y A two digit representation of a year "08" a Lowercase Ante meridiem and Post meridiem "am" or "pm" A Uppercase Ante meridiem and Post meridiem "AM" or "PM" B Swatch Internet time "000" through "999" g 12-hour format of an hour without leading zeros "1" through "12" G 24-hour format of an hour without leading zeros "0" through "23" h 12-hour format of an hour with leading zeros "01" through "12" H 24-hour format of an hour with leading zeros "00" through "23" i Minutes with leading zeros "00" to "59" s Seconds, with leading zeros "00" through "59" u Milliseconds "54321" e Timezone identifier "UTC", "EST", "PST" I Whether or not the date is in daylight saving time (uppercase i) "1" if Daylight Saving Time, "0" otherwise O Difference to Greenwich time (GMT) in hours "+0200", "-0600" P Difference to Greenwich time (GMT) with colon between hours and minutes "+02:00", "-06:00" T Timezone abbreviation "UTC", "EST", "PST" Z Timezone offset in seconds. The offset for timezones west of UTC is "-43200" through "50400" always negative, and for those east of UTC is always positive. c ISO 8601 date "2004-02-12T15:19:21+00:00" r RFC 2822 formatted date "Thu, 21 Dec 2000 16:01:07 +0200" U Seconds since the Unix Epoch (January 1 1970 00:00:00 GMT) "0" </pre> * @param {String} A format string consisting of one or more format spcifiers [Optional]. * @return {String} A string representation of the current Date object. */ $P.$format = function (format) { var x = this, y, t = function (v, overrideStandardFormats) { $f.push(v); return x.toString(v, overrideStandardFormats); }; return format ? format.replace(/(%|\\)?.|%%/g, function (m) { if (m.charAt(0) === "\\" || m.substring(0, 2) === "%%") { return m.replace("\\", "").replace("%%", "%"); } switch (m) { case "d": case "%d": return t("dd"); case "D": case "%a": return t("ddd"); case "j": case "%e": return t("d", true); case "l": case "%A": return t("dddd"); case "N": case "%u": return x.getDay() + 1; case "S": return t("S"); case "w": case "%w": return x.getDay(); case "z": return x.getOrdinalNumber(); case "%j": return p(x.getOrdinalNumber(), 3); case "%U": var d1 = x.clone().set({month: 0, day: 1}).addDays(-1).moveToDayOfWeek(0), d2 = x.clone().addDays(1).moveToDayOfWeek(0, -1); return (d2 < d1) ? "00" : p((d2.getOrdinalNumber() - d1.getOrdinalNumber()) / 7 + 1); case "W": case "%V": return x.getISOWeek(); case "%W": return p(x.getWeek()); case "F": case "%B": return t("MMMM"); case "m": case "%m": return t("MM"); case "M": case "%b": case "%h": return t("MMM"); case "n": return t("M"); case "t": return $D.getDaysInMonth(x.getFullYear(), x.getMonth()); case "L": return ($D.isLeapYear(x.getFullYear())) ? 1 : 0; case "o": case "%G": return x.setWeek(x.getISOWeek()).toString("yyyy"); case "%g": return x.$format("%G").slice(-2); case "Y": case "%Y": return t("yyyy"); case "y": case "%y": return t("yy"); case "a": case "%p": return t("tt").toLowerCase(); case "A": return t("tt").toUpperCase(); case "g": case "%I": return t("h"); case "G": return t("H"); case "h": return t("hh"); case "H": case "%H": return t("HH"); case "i": case "%M": return t("mm"); case "s": case "%S": return t("ss"); case "u": return p(x.getMilliseconds(), 3); case "I": return (x.isDaylightSavingTime()) ? 1 : 0; case "O": return x.getUTCOffset(); case "P": y = x.getUTCOffset(); return y.substring(0, y.length - 2) + ":" + y.substring(y.length - 2); case "e": case "T": case "%z": case "%Z": return x.getTimezone(); case "Z": return x.getTimezoneOffset() * -60; case "B": var now = new Date(); return Math.floor(((now.getHours() * 3600) + (now.getMinutes() * 60) + now.getSeconds() + (now.getTimezoneOffset() + 60) * 60) / 86.4); case "c": return x.toISOString().replace(/\"/g, ""); case "U": return $D.strtotime("now"); case "%c": return t("d") + " " + t("t"); case "%C": return Math.floor(x.getFullYear() / 100 + 1); case "%D": return t("MM/dd/yy"); case "%n": return "\\n"; case "%t": return "\\t"; case "%r": return t("hh:mm tt"); case "%R": return t("H:mm"); case "%T": return t("H:mm:ss"); case "%x": return t("d"); case "%X": return t("t"); default: $f.push(m); return m; } }) : this._toString(); }; if (!$P.format) { $P.format = $P.$format; } }()); /* * TimeSpan(milliseconds); * TimeSpan(days, hours, minutes, seconds); * TimeSpan(days, hours, minutes, seconds, milliseconds); */ var TimeSpan = function (days, hours, minutes, seconds, milliseconds) { var attrs = "days hours minutes seconds milliseconds".split(/\s+/); var gFn = function (attr) { return function () { return this[attr]; }; }; var sFn = function (attr) { return function (val) { this[attr] = val; return this; }; }; for (var i = 0; i < attrs.length ; i++) { var $a = attrs[i], $b = $a.slice(0, 1).toUpperCase() + $a.slice(1); TimeSpan.prototype[$a] = 0; TimeSpan.prototype["get" + $b] = gFn($a); TimeSpan.prototype["set" + $b] = sFn($a); } if (arguments.length === 4) { this.setDays(days); this.setHours(hours); this.setMinutes(minutes); this.setSeconds(seconds); } else if (arguments.length === 5) { this.setDays(days); this.setHours(hours); this.setMinutes(minutes); this.setSeconds(seconds); this.setMilliseconds(milliseconds); } else if (arguments.length === 1 && typeof days === "number") { var orient = (days < 0) ? -1 : +1; this.setMilliseconds(Math.abs(days)); this.setDays(Math.floor(this.getMilliseconds() / 86400000) * orient); this.setMilliseconds(this.getMilliseconds() % 86400000); this.setHours(Math.floor(this.getMilliseconds() / 3600000) * orient); this.setMilliseconds(this.getMilliseconds() % 3600000); this.setMinutes(Math.floor(this.getMilliseconds() / 60000) * orient); this.setMilliseconds(this.getMilliseconds() % 60000); this.setSeconds(Math.floor(this.getMilliseconds() / 1000) * orient); this.setMilliseconds(this.getMilliseconds() % 1000); this.setMilliseconds(this.getMilliseconds() * orient); } this.getTotalMilliseconds = function () { return (this.getDays() * 86400000) + (this.getHours() * 3600000) + (this.getMinutes() * 60000) + (this.getSeconds() * 1000); }; this.compareTo = function (time) { var t1 = new Date(1970, 1, 1, this.getHours(), this.getMinutes(), this.getSeconds()), t2; if (time === null) { t2 = new Date(1970, 1, 1, 0, 0, 0); } else { t2 = new Date(1970, 1, 1, time.getHours(), time.getMinutes(), time.getSeconds()); } return (t1 < t2) ? -1 : (t1 > t2) ? 1 : 0; }; this.equals = function (time) { return (this.compareTo(time) === 0); }; this.add = function (time) { return (time === null) ? this : this.addSeconds(time.getTotalMilliseconds() / 1000); }; this.subtract = function (time) { return (time === null) ? this : this.addSeconds(-time.getTotalMilliseconds() / 1000); }; this.addDays = function (n) { return new TimeSpan(this.getTotalMilliseconds() + (n * 86400000)); }; this.addHours = function (n) { return new TimeSpan(this.getTotalMilliseconds() + (n * 3600000)); }; this.addMinutes = function (n) { return new TimeSpan(this.getTotalMilliseconds() + (n * 60000)); }; this.addSeconds = function (n) { return new TimeSpan(this.getTotalMilliseconds() + (n * 1000)); }; this.addMilliseconds = function (n) { return new TimeSpan(this.getTotalMilliseconds() + n); }; this.get12HourHour = function () { return (this.getHours() > 12) ? this.getHours() - 12 : (this.getHours() === 0) ? 12 : this.getHours(); }; this.getDesignator = function () { return (this.getHours() < 12) ? Date.CultureInfo.amDesignator : Date.CultureInfo.pmDesignator; }; this.toString = function (format) { this._toString = function () { if (this.getDays() !== null && this.getDays() > 0) { return this.getDays() + "." + this.getHours() + ":" + this.p(this.getMinutes()) + ":" + this.p(this.getSeconds()); } else { return this.getHours() + ":" + this.p(this.getMinutes()) + ":" + this.p(this.getSeconds()); } }; this.p = function (s) { return (s.toString().length < 2) ? "0" + s : s; }; var me = this; return format ? format.replace(/dd?|HH?|hh?|mm?|ss?|tt?/g, function (format) { switch (format) { case "d": return me.getDays(); case "dd": return me.p(me.getDays()); case "H": return me.getHours(); case "HH": return me.p(me.getHours()); case "h": return me.get12HourHour(); case "hh": return me.p(me.get12HourHour()); case "m": return me.getMinutes(); case "mm": return me.p(me.getMinutes()); case "s": return me.getSeconds(); case "ss": return me.p(me.getSeconds()); case "t": return ((me.getHours() < 12) ? Date.CultureInfo.amDesignator : Date.CultureInfo.pmDesignator).substring(0, 1); case "tt": return (me.getHours() < 12) ? Date.CultureInfo.amDesignator : Date.CultureInfo.pmDesignator; } } ) : this._toString(); }; return this; }; /** * Gets the time of day for this date instances. * @return {TimeSpan} TimeSpan */ Date.prototype.getTimeOfDay = function () { return new TimeSpan(0, this.getHours(), this.getMinutes(), this.getSeconds(), this.getMilliseconds()); }; /* * TimePeriod(startDate, endDate); * TimePeriod(years, months, days, hours, minutes, seconds, milliseconds); */ var TimePeriod = function (years, months, days, hours, minutes, seconds, milliseconds) { var attrs = "years months days hours minutes seconds milliseconds".split(/\s+/); var gFn = function (attr) { return function () { return this[attr]; }; }; var sFn = function (attr) { return function (val) { this[attr] = val; return this; }; }; for (var i = 0; i < attrs.length ; i++) { var $a = attrs[i], $b = $a.slice(0, 1).toUpperCase() + $a.slice(1); TimePeriod.prototype[$a] = 0; TimePeriod.prototype["get" + $b] = gFn($a); TimePeriod.prototype["set" + $b] = sFn($a); } if (arguments.length === 7) { this.years = years; this.months = months; this.setDays(days); this.setHours(hours); this.setMinutes(minutes); this.setSeconds(seconds); this.setMilliseconds(milliseconds); } else if (arguments.length === 2 && arguments[0] instanceof Date && arguments[1] instanceof Date) { // startDate and endDate as arguments var d1 = years.clone(); var d2 = months.clone(); var temp = d1.clone(); var orient = (d1 > d2) ? -1 : +1; this.years = d2.getFullYear() - d1.getFullYear(); temp.addYears(this.years); if (orient === +1) { if (temp > d2) { if (this.years !== 0) { this.years--; } } } else { if (temp < d2) { if (this.years !== 0) { this.years++; } } } d1.addYears(this.years); if (orient === +1) { while (d1 < d2 && d1.clone().addMonths(1) <= d2) { d1.addMonths(1); this.months++; } } else { while (d1 > d2 && d1.clone().addDays(-d1.getDaysInMonth()) > d2) { d1.addMonths(-1); this.months--; } } var diff = d2 - d1; if (diff !== 0) { var ts = new TimeSpan(diff); this.setDays(ts.getDays()); this.setHours(ts.getHours()); this.setMinutes(ts.getMinutes()); this.setSeconds(ts.getSeconds()); this.setMilliseconds(ts.getMilliseconds()); } } return this; };
{ var data = ""; req.on("data", function(chunk) { data += chunk; }); req.on("end", function() { console.log("File uploaded"); res.writeHead(200); res.end(); }); }
/** * Created by zhengguorong on 16/6/22. */ import Vue from 'vue' import Vuex from 'vuex' import contentManage from './modules/contentManage' import app from './modules/app' Vue.use(Vuex) const debug = process.env.NODE_ENV !== 'production' export default new Vuex.Store({ modules: { contentManage, app }, strict: debug })
version https://git-lfs.github.com/spec/v1 oid sha256:051c513c1bccfd5530e6080a7d95f1d567300a748e9668be84ed52b0d109cc5f size 65815
import Application from 'ember-application'; import run from 'ember-runloop'; import { initialize } from '../../../instance-initializers/-sustains'; import { module, test } from 'qunit'; import destroyApp from '../../helpers/destroy-app'; module('Unit | Instance Initializer | sustains', { beforeEach() { run(() => { this.application = Application.create(); this.appInstance = this.application.buildInstance(); }); }, afterEach() { run(this.appInstance, 'destroy'); destroyApp(this.application); } }); // Replace this with your real tests. test('it works', function(assert) { initialize(this.appInstance); // you would normally confirm the results of the initializer here assert.ok(true); });
var a00015 = [ [ "player_t", "a00005.html", "a00005" ], [ "player", "a00015.html#ga423655ccd6f0739c6cd730982fa6de05", null ], [ "player_init", "a00015.html#ga5c83feea6dbd6e2448404261375365e3", null ], [ "player_new", "a00015.html#ga75b1ecd76f93fa8893c4f2bab9fbf03b", null ], [ "player_set_fifo_name", "a00015.html#ga2d7b416518d58ac941d831b808273f2c", null ], [ "player_set_name", "a00015.html#ga761441bacf27fb156667785386ad8f21", null ] ];
//~ name b605 alert(b605); //~ component b606.js
import babel from 'rollup-plugin-babel'; import fs from 'fs'; const pkg = JSON.parse(fs.readFileSync('./package.json')); export default { entry: 'src/index.js', external: ['query-string'], moduleName: 'hashHandler', globals: { 'query-string': 'queryString', }, useStrict: false, sourceMap: true, plugins: [ babel({ presets: [['es2015', { modules: false }], 'flow'], babelrc: false, }), ], targets: [ { dest: pkg.main, format: 'umd' }, { dest: pkg.module, format: 'es' }, ], };
(function () { 'use strict'; var app = angular.module('Fablab'); app.factory('TrainingService', function ($log, $resource, $http) { var training = $resource(App.API.TRAINING_API + "/:id", {id: '@id'}); return { list: function (successFn) { $http( { method: 'GET', url: App.API.TRAINING_API } ).success(successFn); }, remove: function (id, successFn) { $log.debug("TrainingService: remove..."); training.remove({id: id}, successFn); }, softRemove: function (id, successFn) { $http.get(App.API.TRAINING_API + "/softRemove?id=" + id).success(successFn); $log.debug("TrainingService: soft remove..."); }, save: function (trainingParam, successFn, errorFn) { $log.debug("TrainingService: save..."); var saved = training.save(trainingParam, successFn, errorFn); return saved; }, get: function (id, successFn) { $log.debug("TrainingService: get..."); var trainingRes = training.get({id: id}, successFn); return trainingRes; }, getId: function(name, successFn) { $http.get(App.API.TRAINING_API + "/getId?name=" + name.latinise()).success(successFn); } }; }); }());
/*! * robust-admin-theme (http://demo.pixinvent.com/robust-admin) * Copyright 2017 PIXINVENT * Licensed under the Themeforest Standard Licenses */ $(window).on("load",function(){function getRandomData(){for(data.length>0&&(data=data.slice(1));data.length<totalPoints;){var prev=data.length>0?data[data.length-1]:50,y=prev+10*Math.random()-5;y<0?y=0:y>100&&(y=100),data.push(y)}for(var res=[],i=0;i<data.length;++i)res.push([i,data[i]]);return res}function update(){plot.setData([getRandomData()]),plot.draw(),setTimeout(update,updateInterval)}var data=[],totalPoints=300,updateInterval=30;$("#updateInterval").val(updateInterval).change(function(){var v=$(this).val();v&&!isNaN(+v)&&(updateInterval=+v,updateInterval<1?updateInterval=1:updateInterval>2e3&&(updateInterval=2e3),$(this).val(""+updateInterval))});var plot=$.plot("#realtime",[getRandomData()],{grid:{borderWidth:1,borderColor:"transparent",color:"#999",minBorderMargin:20,labelMargin:10,margin:{top:8,bottom:20,left:20}},series:{shadowSize:0,lines:{fill:!0,fillColor:{colors:[{opacity:.8},{opacity:.1}]}}},yaxis:{min:0,max:100},xaxis:{show:!1},colors:["#ffc107"]});update()});
import { uglify } from 'rollup-plugin-uglify' import resolve from '@rollup/plugin-node-resolve' import commonjs from '@rollup/plugin-commonjs' export default { input: 'packages/react/dist/index.js', plugins: [ resolve({ browser: true }), uglify(), commonjs() ], output: { name: 'JSONEditor', file: 'packages/react/dist/react-schema-based-json-editor.min.js', format: 'umd' }, external: [ 'react', 'react-dom' ] }
var packraturl = 'http://localhost:3000'; $(document).ready(function() { $.ajaxSetup({ xhrFields: { withCredentials: true } }); var form2object = function(form) { var data = {}; $(form).find('input').each(function(index, element) { var type = $(this).attr('type'); if ($(this).attr('name') && type !== 'submit' && type !=='hidden') { data[$(this).attr('name')] = $(this).val(); } }); return data; }; var callback = function callback(error, data) { if (error) { console.error(error); $('#result').val('status: ' + error.status + ', error: ' + error.error); return; } $('#result').val(JSON.stringify(data, null, 4)); }; $('#register').on('submit', function(e) { e.preventDefault(); var credentials = form2object(this); console.log(credentials); packrat.register(credentials, callback); }); $('#login').on('submit', function(e) { var credentials = form2object(this); var cb = function cb(error, data) { if (error) { callback(error); return; } callback(null, data); $('#login').each(function(){ this.reset(); }); $(".home-links").hide(); // $("#home-page").hide(); $("#about").hide(); $("#signup").hide(); $("#contact").hide(); $("#logout").show(); }; e.preventDefault(); packrat.login(credentials, cb); }); $('#get-files').on('click', function(e) { $(".files").html(''); var images = form2object(this); var cb = function cb(error, data) { if (error) { callback(error); return; } callback(null, data); var urls = data; // console.log(urls[0].path); for (var i = 0; i < urls.length; i++) { console.log(urls[i].name); $(".files").append("<li> File Name: " + urls[i].name.toString() + " ID: " + urls[i]._id.toString() + "</li>"); } // $(".files").append("<li>" + data + "</li>"); }; e.preventDefault(); packrat.showfiles(images, cb); }); $('#update').on('submit', function(e) { var image = form2object(this); console.log(image); var cb = function cb(error, data) { if (error) { callback(error); return; } callback(null, data); $('#update').reset(); }; e.preventDefault(); packrat.update(image, cb); }); $('#deleteall').on('submit', function(e) { var image = form2object(this); var cb = function cb(error, data) { if (error) { callback(error); return; } callback(null, data); console.log('success'); }; e.preventDefault(); packrat.deleteall(image, cb); console.log("click handler success"); }); $("#deleteone").on('submit', function(e){ var image = form2object(this); var cb = function cb(error, data) { if (error) { callback(error); return; } callback(null, data); console.log('success'); }; e.preventDefault(); console.log(image); packrat.deleteone(image, cb); packrat.deletefile(image, cb); }); $('#logout').on('click', function(e) { var cb = function cb(error, data) { if (error) { callback(error); return; } callback(null, data); $(".home-links").show(); // $("#home-page").show(); $("#about").show(); $("#signup").show(); $("#contact").show(); $(".logged-in").hide(); $("#logout").hide(); }; e.preventDefault(); packrat.logout(cb); }); }); //document.ready
import { module, inject } from "angular-mocks"; import "../../../app/auth/auth.module"; (function () { 'use strict'; describe('HttpHeaderInterceptor', function () { var httpHeaderInterceptor, CookiesServiceMock; beforeEach(module('xr.auth')); beforeEach(module(function ($provide) { CookiesServiceMock = { get: function () {} }; $provide.value('$cookies', CookiesServiceMock); })); beforeEach(inject(function (_httpHeaderInterceptor_) { httpHeaderInterceptor = _httpHeaderInterceptor_; })); describe('request', function () { it('should add Authorization header if token exists', function () { var token = '1234'; spyOn(CookiesServiceMock, 'get').and.returnValue(token); var config = httpHeaderInterceptor.request({ headers: {} }); expect(config.headers.Authorization).toBe('Bearer ' + token); }); it('should not add Authorization header if no token', function () { var config = httpHeaderInterceptor.request({ headers: {} }); expect(config.headers.Authorization).toBeUndefined(); }); }); }); })();
/** * Copyright (c) Facebook, Inc. and its affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. * * @flow strict-local * @format */ 'use strict'; const invariant = require('invariant'); const stableCopy = require('./stableCopy'); import type {RequestParameters} from './RelayConcreteNode'; import type {Variables} from './RelayRuntimeTypes'; export opaque type Identifier: string = string; /** * Returns a stable identifier for the given pair of `RequestParameters` + * variables. */ function getRequestParametersIdentifier( parameters: RequestParameters, variables: Variables, ): Identifier { const requestID = parameters.id != null ? parameters.id : parameters.text; invariant( requestID != null, 'getRequestParametersIdentifier: Expected request `%s` to have either a ' + 'valid `id` or `text` property', parameters.name, ); return requestID + JSON.stringify(stableCopy(variables)); } module.exports = getRequestParametersIdentifier;
import * as types from '../actions/action-types' const initialState = { blocked: false } const commonReducer = function(state = initialState, action) { switch(action.type) { case types.BLOCK_UI: return Object.assign({}, state, {blocked: true}) case types.UNBLOCK_UI: return Object.assign({}, state, {blocked: false}) } return state } export default commonReducer
var gulp = require('gulp'), jshint = require('gulp-jshint'), concat = require('gulp-concat'), rename = require('gulp-rename'), browserSync = require('browser-sync').create(), uglify = require('gulp-uglify'), minifyCss = require('gulp-minify-css'), jasmine = require('gulp-jasmine'); // Jasmine Testing gulp.task('test', function(){ console.log((new Date).toLocaleTimeString() + " Tests Excecuted!"); return gulp.src('spec/test.js') .pipe(jasmine()); }); // Linting and minifying gulp.task('js-liniting-compliling', function(){ console.log((new Date).toLocaleTimeString() + " ReMinified JS!"); return gulp.src('scripts/*.js') .pipe(jshint()) .pipe(jshint.reporter('default')) .pipe(concat('all.js')) .pipe(gulp.dest('dist/js')) .pipe(rename('all.min.js')) .pipe(uglify()) .pipe(gulp.dest('dist/js'), browserSync.reload()); }); gulp.task('js-watch', ['js-liniting-compliling']); gulp.task('server', function(){ browserSync.init({ server: { baseDir: "./" } }); gulp.watch("scripts/*.js", ['js-watch']); gulp.watch("styles/*.css", ['minify-css']); }); //minify css gulp.task('minify-css', function() { console.log((new Date).toLocaleTimeString() + " ReMinified CSS!"); return gulp.src('styles/*.css') .pipe(minifyCss()) .pipe(gulp.dest('dist/styles'), browserSync.reload()); });
/* * grunt-tilecutter * https://github.com/jlawson/tilecutter-grunt * * Copyright (c) 2015 James Lawson * Licensed under the MIT license. */ 'use strict'; var gdal = require('gdal'), chalk = require('chalk'); module.exports = function (grunt) { grunt.registerMultiTask('tilecutter', 'Tilecutter Plugin', function () { var complete = this.async(); var template = "<!DOCTYPE html><html><head><title>Map Overview</title><meta charset='utf-8' /><meta name='viewport' content='width=device-width, initial-scale=1.0'><link rel='stylesheet' href='http://cdn.leafletjs.com/leaflet-0.7.3/leaflet.css' /></head><body><div id='map' style='width: 600px; height: 400px'></div><script src='http://cdn.leafletjs.com/leaflet-0.7.3/leaflet.js'></script><script>var southWest = L.latLng(<%= south %>, <%= west %>),northEast = L.latLng(<%= north %>, <%= east %>),bounds = L.latLngBounds(southWest, northEast);var map = L.map('map', {center: [<%= south %>,<%= west %>],zoom: <%= mapZoom %>,attributionControl: false,maxBounds: bounds,});L.tileLayer('./{z}/{x}/{y}.png', {minZoom: <%= minZoom %>,maxZoom: <%= maxZoom %>,tms: true,detectRetina: true,bounds: bounds}).addTo(map);function onMapClick(e) {console.log(e.latlng.toString() + ' @ ' + e.target.getZoom() + ' zoom');}map.on('click', onMapClick);</script></body></html>"; // Merge task-specific and/or target-specific options with these defaults. var options = this.options({ projection: 'WGS84', resampling: 'near', minZoom: 1, maxZoom: 5, gdal2tiles: '/Library/Frameworks/GDAL.framework/Programs/gdal2tiles.py' }); // Iterate over all specified file groups. this.files.forEach(function (f) { options.tiles = options.tiles || f.orig.dest + 'tiles/'; var src = f.src.filter(function (filepath) { if (!grunt.file.exists(filepath)) { grunt.log.warn('Source file', chalk.cyan(filepath), 'not found.'); return false; } else { return true; } }).map(function (filepath) { // need to get the dimensions of the source file var dataset = gdal.open(filepath); var x = dataset.rasterSize.x, y = dataset.rasterSize.y; grunt.file.mkdir(f.orig.dest); grunt.util.spawn({ cmd: 'gdal_translate', args: [ '-a_srs', options.projection, '-gcp', '0', '0', options.latitude.west, options.longitude.north, '-gcp', x, '0', options.latitude.east, options.longitude.north, '-gcp', x, y, options.latitude.east, options.longitude.south, filepath, f.dest ] }, function done(error, result, code) { if(error) { grunt.log.error('Could not translate', filepath); grunt.log.error(error); complete(); return false; } else { grunt.log.writeln('Translated', chalk.cyan(filepath), 'to', chalk.cyan(f.dest)); grunt.util.spawn({ cmd: 'gdalwarp', args: [ '-s_srs', options.projection, '-r', options.resampling, f.dest, f.dest ] }, function done(error, result, code) { if(error) { grunt.log.error('Could not warp', f.dest); grunt.log.error(error); complete(); return false; } else { grunt.log.writeln('Warped', chalk.cyan(f.dest), 'to', chalk.cyan(f.dest)); grunt.util.spawn({ cmd: 'python', args: [ options.gdal2tiles, '-r', options.resampling, '-z', options.minZoom + '-' + options.maxZoom, '-w', 'none', f.dest, options.tiles ] }, function done(error, result, code) { if(error) { grunt.log.error('Could not tile', f.dest); grunt.log.error(error); complete(); return false; } else { grunt.log.writeln('Tiled', chalk.cyan(f.dest), 'to', chalk.cyan(options.tiles)); complete(); return true; } }); } }); return true; } }); var templateOptions = { data: { north: options.longitude.north, east: options.latitude.east, south: options.longitude.south, west: options.latitude.west, minZoom: options.minZoom, maxZoom: options.maxZoom, mapZoom: Math.floor((options.maxZoom - options.minZoom)/2) } }; var result = grunt.template.process(template, templateOptions); grunt.file.write(options.tiles + '/map.html', result); }); }); }); };
function JsonUtil() { /** * Given a provided object, * return a string representation of the object type. */ this.isType = function (obj_) { if (obj_ === null) { return "null"; } if (obj_ === NaN) { return "Nan"; } var _type = typeof obj_; switch (_type) { case "undefined": return "undefined"; case "number": return "number"; case "boolean": return "boolean"; case "string": return "string"; case "function": return "function"; case "object": if (this.isArray(obj_)) { return "array"; } return "associative"; } }, /** * Recursively search and display array as an HTML table. */ this.tableifyArray = function (array_) { if (array_.length === 0) { return "[ empty ]"; } var _out = "<table class='arrayTable'>"; _out += "<tr class='label arrayTr'><td class='arrayTd'>" + "<span>array</span></td></tr>"; for (var i = array_.length - 1; i >= 0; i--) { _out += "<tr class='label arrayTr'><td class='arrayTd'><span>index: " + i + "</span></td></tr>"; _out += "<tr class='arrayTr'><td class='arrayTd'>" + this.tableifyObject(array_[i]) + "</td></tr>"; } _out += "</table>"; return _out; }, /** * Recursively search and display common javascript types as an HTML table. */ this.tableifyObject = function (obj_) { /* if (obj_ === '') { return "[ empty ]"; } */ switch (this.isType(obj_)) { case "null": return "null"; case "undefined": return "undefined"; case "number": return obj_; case "boolean": return obj_; case "string": return obj_; case "array": return this.tableifyArray(obj_); case "associative": return this.tableifyAssociative(obj_); } return "!error converting object!"; }, /** * Recursively search and display associative array as an HTML table. */ this.tableifyAssociative = function (array_) { if (this.isEmpty(array_)) { return "{ empty }"; } var _out = "<table class='associativeTable'>"; _out += "<tr class='label associativeTr'>" + "<td class='associativeTd' colspan='2'><span>associative</span></td></tr>"; _out += "<tr class='label associativeTr'>" + "<td class='associativeTd'><span>key</span></td><td >" + "<span>value</span></td></tr>"; for (var _index in array_) { _out += "<tr class='associativeTr'><td class='associativeTd'>" + this.tableifyObject(_index) + "</td><td class='associativeTd'>" + this.tableifyObject(array_[_index]) + "</td></tr>"; } _out += "</table>"; return _out; }, /** * identify if an associative array is empty */ this.isEmpty = function (map_) { for (var _key in map_) { if (map_.hasOwnProperty(_key)) { return false; } } return true; }, /** * Identify is an array is a 'normal' (not associative) array */ this.isArray = function (v_) { return Object.prototype.toString.call(v_) == "[object Array]"; }, /** * given the desire to populate a map of maps, adds a master key, * and child key and value to a provided object. */ this.addToMapOfMaps = function (map_, mkey_, key_, value_) { if (map_ === undefined) { map_ = {}; } if (map_[mkey_] === undefined) { map_[mkey_] = {} } if (map_[mkey_][key_] === undefined) { map_[mkey_][key_] = null; } map_[mkey_][key_] = value_; return map_; } }
export default '0.0.50';
module.exports={A:{A:{"2":"H D G E A B HB"},B:{"2":"0 C p J L N I"},C:{"1":"1 4 6 7 8 9 t u v w x y z AB BB","16":"0 3 cB F K H D G E A B C p J L N I O P aB UB","33":"2 Q R S T U V W X Y Z a c d e f g h i j k l m n o M q r s"},D:{"16":"0 F K H D G E A B C p J L N I O P Q R S","33":"1 2 4 6 7 8 9 T U V W X Y Z a c d e f g h i j k l m n o M q r s t u v w x y z AB BB OB eB GB IB FB JB KB LB MB"},E:{"16":"F K H NB EB PB","33":"D G E A B C QB RB SB TB b VB"},F:{"2":"E B C WB XB YB ZB b CB bB DB","33":"2 J L N I O P Q R S T U V W X Y Z a c d e f g h i j k l m n o M q r s t u v w x y z"},G:{"16":"5 EB dB fB","33":"G C gB hB iB jB kB lB mB nB oB"},H:{"2":"pB"},I:{"16":"3 5 F qB rB sB tB uB vB","33":"GB"},J:{"16":"D A"},K:{"2":"A B C b CB DB","33":"M"},L:{"33":"FB"},M:{"33":"1"},N:{"2":"A B"},O:{"16":"wB"},P:{"16":"F","33":"K xB yB"},Q:{"33":"zB"},R:{"33":"0B"}},B:5,C:"CSS :any-link selector"};
/* @flow */ 'use strict'; var React = require('react-native'); var { AppRegistry, NetInfo, Text, StyleSheet, View, } = React; var NetInfoExample = React.createClass({ getInitialState(){ return { reachabilityHistory: [], reachayility: null, isConnected: null, }; }, componentDidMoutn: function(){ NetInfo.addEventListener('change', this._handleReachabilityChange); NetInfo.isConnected.addEventListener('change', this._handleConnectivityChange); NetInfo.fetch().done((reachability) => {this.setState({reachability})}); NetInfo.isConnected.fetch().done((isConnected) => {this.setState({isConnected})}); }, componentWillUnmount: function(){ NetInfo.removeEventListener('change', this._handleReachabilityChange); NetInfo.isConnected.removeEventListener('change', this._handleConnectivityChange); }, _handleReachabilityChange: function (reachability) { var reachabilityHistory = this.state.reachabilityHistory.slice(); reachabilityHistory.push(reachability); this.setState({ reachabilityHistory, reachability, }); }, _handleConnectivityChange:function (isConnected) { this.setState({ isConnected, }); }, render: function() { return ( <View style={styles.container}> <Text> {JSON.stringify(this.state.reachabilityHistory)} </Text> <Text> {this.state.reachability} </Text> <Text> {this.state.isConnected ? 'Online' : 'Offline'} </Text> </View> ); } }); var styles = StyleSheet.create({ container: { flex: 1, justifyContent: 'center', alignItems: 'center', }, }); AppRegistry.registerComponent('reactnative', () => NetInfoExample);
/** * [RHbnyDefectList] author by $YourName$ * @include "../../extclient/RowExpander.js" * @include "../../extclient/gridToExcel.js" * @include "../../extclient/SearchField.js" */ Ext.namespace('com.trend.hbny'); Ext.namespace('com.trend.hbny.rhbnydefectlist'); /** * 查询表单 * @class com.trend.hbny.rhbnydefectlist.queryformpanel * @extends Ext.form.FormPanel */ com.trend.hbny.rhbnydefectlist.queryformpanel = Ext.extend(Ext.form.FormPanel,{ initComponent:function() { Ext.apply(this,{ labelAlign:'right', labelWidth:80, defaultType:'textfield', bodyStyle:'padding:20px;', defaults:{width:290}, items:[{ xtype:'panel', html:'请在下面输入查询条件:', width:370, border:false, style:'padding:10 0 0 3;margin:0 0 20 10;border-bottom:1px solid #ccc;font-size:14px;font-weight:bold;' } ,{ xtype:'panel', layout:'column', width:400, border:false, defaults:{border:false} } ,{xtype:'textfield',fieldLabel:'coNo',name:'s_coNo',width:288} ,{xtype:'textfield',fieldLabel:'datatime',name:'s_datatime',width:288} ,{xtype:'textfield',fieldLabel:'authname',name:'s_authname',width:288} ,{xtype:'textfield',fieldLabel:'defectNo',name:'s_defectNo',width:288} ,{xtype:'textfield',fieldLabel:'defectsEquipment',name:'s_defectsEquipment',width:288} ,{xtype:'textfield',fieldLabel:'defectLevels',name:'s_defectLevels',width:288} ,{xtype:'textfield',fieldLabel:'defectState',name:'s_defectState',width:288} ,{xtype:'textfield',fieldLabel:'defectsStartTime',name:'s_defectsStartTime',width:288} ,{xtype:'textfield',fieldLabel:'defectDescription',name:'s_defectDescription',width:288} ,{xtype:'textfield',fieldLabel:'defectsEndTime',name:'s_defectsEndTime',width:288} ,{xtype:'textfield',fieldLabel:'defectsEndInfo',name:'s_defectsEndInfo',width:288} ] }); com.trend.hbny.rhbnydefectlist.queryformpanel.superclass.initComponent.call(this); } }); /** * 查询窗口 * @class com.trend.hbny.rhbnydefectlist.querywin * @extends Ext.Window */ com.trend.hbny.rhbnydefectlist.querywin = Ext.extend(Ext.Window,{ initComponent:function() { Ext.apply(this,{ title:'高级查询', width:455, height:395, modal:true, closeAction:'hide', layout:'fit' }); com.trend.hbny.rhbnydefectlist.querywin.superclass.initComponent.call(this); } }); /** * 内容表单 * @class com.trend.hbny.rhbnydefectlist.dtlformpanel * @extends Ext.form.FormPanel */ com.trend.hbny.rhbnydefectlist.dtlformpanel = Ext.extend(Ext.form.FormPanel,{ initComponent:function() { Ext.apply(this,{ labelWidth:100, labelAlign:'right', frame:true, // bodyStyle:'padding:10px', autoScroll:true,//滚动条 items:[{ xtype:'panel', layout:'column', width:400, border:false, defaults:{border:false} } ,{xtype:'textfield',fieldLabel:'coNo',name:'coNo',width:288} ,{xtype:'textfield',fieldLabel:'datatime',name:'datatime',width:288} ,{xtype:'textfield',fieldLabel:'authname',name:'authname',width:288} ,{xtype:'textfield',fieldLabel:'defectNo',name:'defectNo',width:288} ,{xtype:'textfield',fieldLabel:'defectsEquipment',name:'defectsEquipment',width:288} ,{xtype:'textfield',fieldLabel:'defectLevels',name:'defectLevels',width:288} ,{xtype:'textfield',fieldLabel:'defectState',name:'defectState',width:288} ,{xtype:'textfield',fieldLabel:'defectsStartTime',name:'defectsStartTime',width:288} ,{xtype:'textfield',fieldLabel:'defectDescription',name:'defectDescription',width:288} ,{xtype:'textfield',fieldLabel:'defectsEndTime',name:'defectsEndTime',width:288} ,{xtype:'textfield',fieldLabel:'defectsEndInfo',name:'defectsEndInfo',width:288} ,{xtype:'hidden',fieldLabel:'id',name:'id',width:288} ] }); com.trend.hbny.rhbnydefectlist.dtlformpanel .superclass.initComponent.call(this); } }); /** * 表单窗口 * @class com.trend.hbny.rhbnydefectlist.dtlwin * @extends Ext.Window */ com.trend.hbny.rhbnydefectlist.dtlwin = Ext.extend(Ext.Window,{ initComponent:function() { Ext.apply(this,{ width:535, height:400, layout:'fit', border:false, closeAction:'hide', modal:true, maximizable:true, constrain: true, collapsible:true }); com.trend.hbny.rhbnydefectlist.dtlwin.superclass.initComponent.call(this); } }); /** * 主表格入口 * @class com.trend.hbny.rhbnydefectlist * @extends Ext.grid.GridPanel */ com.trend.hbny.rhbnydefectlistGrid = Ext.extend(Ext.grid.GridPanel,{ initComponent:function() { this.pageSize=10; this.ds = new Ext.data.Store({ url:'../RHbnyDefectList/extlist.do', reader:new Ext.data.JsonReader({ root:'list', totalProperty:'totalSize', id:'id' } ,['coNo','datatime','authname','defectNo','defectsEquipment','defectLevels','defectState','defectsStartTime','defectDescription','defectsEndTime','defectsEndInfo','id',] ), baseParams:{ limit:this.pageSize }, remoteSort:true }); //行扩展 this.expander = new Ext.grid.RowExpander({ tpl : new Ext.Template( '<p style="margin-left:70px"><b>字典内容:</b> {kvalue}</p><br>' ) }); this.sm = new Ext.grid.CheckboxSelectionModel(); this.cm = new Ext.grid.ColumnModel([ new Ext.grid.RowNumberer(), this.sm, this.expander ,{header:'coNo',width:100,sortable:true,dataIndex:'coNo'} ,{header:'datatime',width:100,sortable:true,dataIndex:'datatime'} ,{header:'authname',width:100,sortable:true,dataIndex:'authname'} ,{header:'defectNo',width:100,sortable:true,dataIndex:'defectNo'} ,{header:'defectsEquipment',width:100,sortable:true,dataIndex:'defectsEquipment'} ,{header:'defectLevels',width:100,sortable:true,dataIndex:'defectLevels'} ,{header:'defectState',width:100,sortable:true,dataIndex:'defectState'} ,{header:'defectsStartTime',width:100,sortable:true,dataIndex:'defectsStartTime'} ,{header:'defectDescription',width:100,sortable:true,dataIndex:'defectDescription'} ,{header:'defectsEndTime',width:100,sortable:true,dataIndex:'defectsEndTime'} ,{header:'defectsEndInfo',width:100,sortable:true,dataIndex:'defectsEndInfo'} ]); /** * 扩展类的构建开始 */ Ext.apply(this,{ store:this.ds ,sm:this.sm ,cm: this.cm ,plugins:this.expander ,collapsible: true ,viewConfig:{forceFit:true} ,bbar:new Ext.PagingToolbar({ pageSize:this.pageSize, store:this.ds, displayInfo:true }) , tbar:[ {text:'新增',cls:'x-btn-text-icon',iconCls:'addicon',handler:this.addRHbnyDefectList,scope:this},'-' ,{text:'修改',cls:'x-btn-text-icon',iconCls:'editicon',handler:this.editRHbnyDefectList,scope:this},'-' ,{text:'删除',cls:'x-btn-text-icon',iconCls:'deleteicon',handler:this.deleteRHbnyDefectList,scope:this},'-' ,{text:'查询',id:'btn-query',cls:'x-btn-text-icon',iconCls:'queryicon',handler:this.buildQueryWin,scope:this} ,'->' ,'搜索范围:' ,{xtype:'combo', fieldLabel:'搜索范围', emptyText:'请选择...', name:'field_type', hiddenName:'field_type', store:new Ext.data.ArrayStore({ fields: ['name','code'], data: [['coNo', 'coNo'],['datatime', 'datatime'],['authname', 'authname'],['defectNo', 'defectNo'],['defectsEquipment', 'defectsEquipment'],['defectLevels', 'defectLevels'],['defectState', 'defectState'],['defectsStartTime', 'defectsStartTime'],['defectDescription', 'defectDescription'],['defectsEndTime', 'defectsEndTime'],['defectsEndInfo', 'defectsEndInfo']] }), displayField:'name', valueField:'code', forceSelection: false, selectOnFocus: true, editable: false, triggerAction: 'all', allowBlank:true, mode: 'local', width:120 ,listeners: { select:{fn:function(object,record,index){ this.getTopToolbar().items.get("searchfld").getStore().baseParams['field_type'] = object.getValue(); },scope:this} } },{xtype:"searchfield",itemId:"searchfld",width: 130,store:this.ds} ] }); //调用父类构建函数 com.trend.hbny.rhbnydefectlistGrid.superclass.initComponent.call(this); //加载数据 this.store.load({params:{start:0}}); //扩展类的详细弹出窗口 this.dtlformpanel = new com.trend.hbny.rhbnydefectlist.dtlformpanel(); this.dtlwin = new com.trend.hbny.rhbnydefectlist.dtlwin({items:this.dtlformpanel,buttons:[{ text:'保存', handler:this.saveRHbnyDefectList, scope:this },{ text:'取消', handler:function(){this.dtlwin.hide();}, scope:this }]}); //扩展类的查询弹出窗口 this.queryformpanel = new com.trend.hbny.rhbnydefectlist.queryformpanel(); this.querywin = new com.trend.hbny.rhbnydefectlist.querywin({items:this.queryformpanel,buttons:[{ text:'确定', handler:this.queryOrder, scope:this },{ text:'取消', handler:function(){this.querywin.hide();}, scope:this }]}); //双击操作 this.on({"dblclick":this.dblclick}); //右键菜单监听 this.addListener('rowcontextmenu', this.onMessageContextMenu); } /** * 构建函数结束 */ //右键菜单 ,onMessageContextMenu : function (grid, rowIndex, e) { e.stopEvent(); var coords = e.getXY(); var record = grid.getStore().getAt(rowIndex); var messageContextMenu = new Ext.menu.Menu({ id: 'messageContextMenu', items: [{icon:'../../images/edit.gif',text: '编辑',handler: rgtEdit,scope: this}, {id: 'delete',icon:'../../images/delete.gif',handler: rgtDelete,text: '删除' }] }); //右键编辑 function rgtEdit() { messageContextMenu.hide(); this.dtlwin.setTitle('修改RHbnyDefectList'); this.dtlwin.show(); this.dtlformpanel.form.reset(); this.dtlformpanel.form.loadRecord(record); this.dtlformpanel.url = '../RHbnyDefectList/extupdate.do'; }; //右键删除 function rgtDelete() { messageContextMenu.hide(); if (!record||record.length == 0) { Ext.Msg.alert("提示", "请先选择要删除的�记录"); return; } Ext.MessageBox.confirm('确认删除','确定要删除这些记录?',function(btn){ if (btn == 'yes'){ Ext.Ajax.request({ url:'../RHbnyDefectList/extdelete.do?ids='+record.data.id, method:'POST', success:function(response){ var data = Ext.util.JSON.decode(response.responseText); if (data.success == true){ grid.getStore().remove(record); grid.getView().refresh(); } else{ Ext.MessageBox.alert('警告',data.msg); } grid.getStore().reload(); }, scope:this }); }},this); }; messageContextMenu.showAt([coords[0], coords[1]]); e.preventDefault();//to disable the standard browser context menu } //双击事件 ,dblclick :function(){ var sm = this.getSelectionModel(); var record=null; try{ record=sm.getSelected(); if(record==null){ return; } } catch(e){ try{ record=sm.selection.record(); } catch(ex){} } this.showWinForm(record); } //双击打开窗口 ,showWinForm:function(record){ this.dtlwin.setTitle('修改RHbnyDefectList'); this.dtlwin.show(); this.dtlformpanel.form.reset(); this.dtlformpanel.form.loadRecord(record); this.dtlformpanel.url = '../RHbnyDefectList/extupdate.do'; } //新建窗口 ,addRHbnyDefectList : function(){ this.dtlwin.setTitle('新建RHbnyDefectList'); this.dtlwin.show(); this.dtlformpanel.form.reset(); this.dtlformpanel.url = '../RHbnyDefectList/extsave.do'; } //编辑操作 ,editRHbnyDefectList:function(){ var records = this.getSelectionModel().getSelections();//单选 if (records.length!=1) { Ext.Msg.alert("提示", "请先选择要修改的记录"); return; } this.dtlwin.setTitle('修改RHbnyDefectList'); this.dtlwin.show(); this.dtlformpanel.form.reset(); this.dtlformpanel.form.loadRecord(records[0]); this.dtlformpanel.url = '../RHbnyDefectList/extupdate.do'; } //删除操作 ,deleteRHbnyDefectList:function(){ var records = this.getSelectionModel().getSelections(); if (!records||records.length == 0) { Ext.Msg.alert("提示", "请先选择要删除的�记录"); return; } Ext.MessageBox.confirm('确认删除','确定要删除这些记录?',function(btn){ if (btn == 'yes'){ Ext.Ajax.request({ url:'../RHbnyDefectList/extdelete.do?ids='+this.getRecordArrayUtils(records, 'id'), method:'POST', success:function(response){ var data = Ext.util.JSON.decode(response.responseText); if (data.success == true){ for(var i = 0; i < records.length; i++) { this.getStore().remove(records[i]); this.getView().refresh(); } this.getStore().reload(); } else{ Ext.MessageBox.alert('警告',data.msg); } }, scope:this }); } },this); } //保存操作 ,saveRHbnyDefectList:function(){ if (this.dtlformpanel.form.isValid() == false){ return; } this.dtlformpanel.form.submit({ url:this.dtlformpanel.url, success:function(form,action){ Ext.MessageBox.alert('警告',action.result.msg); this.dtlwin.hide(); this.getStore().reload(); }, scope:this, failure:function(form,action){ Ext.MessageBox.alert('警告',action.result.msg); } }) } //新建查询窗口 ,buildQueryWin: function(){ this.querywin.setTitle('查询'); this.querywin.show(); this.getTopToolbar().items.get("searchfld").setValue(""); this.getTopToolbar().items.get("searchfld").getStore().baseParams['field_type']=null; } //查询操作 ,queryOrder:function(){ this.getStore().baseParams['s_coNo'] = this.queryformpanel.form.findField('s_coNo').getRawValue(); this.getStore().baseParams['s_datatime'] = this.queryformpanel.form.findField('s_datatime').getRawValue(); this.getStore().baseParams['s_authname'] = this.queryformpanel.form.findField('s_authname').getRawValue(); this.getStore().baseParams['s_defectNo'] = this.queryformpanel.form.findField('s_defectNo').getRawValue(); this.getStore().baseParams['s_defectsEquipment'] = this.queryformpanel.form.findField('s_defectsEquipment').getRawValue(); this.getStore().baseParams['s_defectLevels'] = this.queryformpanel.form.findField('s_defectLevels').getRawValue(); this.getStore().baseParams['s_defectState'] = this.queryformpanel.form.findField('s_defectState').getRawValue(); this.getStore().baseParams['s_defectsStartTime'] = this.queryformpanel.form.findField('s_defectsStartTime').getRawValue(); this.getStore().baseParams['s_defectDescription'] = this.queryformpanel.form.findField('s_defectDescription').getRawValue(); this.getStore().baseParams['s_defectsEndTime'] = this.queryformpanel.form.findField('s_defectsEndTime').getRawValue(); this.getStore().baseParams['s_defectsEndInfo'] = this.queryformpanel.form.findField('s_defectsEndInfo').getRawValue(); this.getStore().load(); this.querywin.hide(); } //工具类 ,getRecordArrayUtils : function(records,field) { var result = []; for(var i = 0; i < records.length; i++) { result.push(records[i].get(field)); } return result; } }); /** * 注册主表格的xtype */ Ext.reg('rhbnydefectlist', com.trend.hbny.rhbnydefectlistGrid);
import {metadata} from 'aurelia-metadata'; import {ValidationConfig} from './validation-config'; import {ValidationEngine} from './validation-engine'; import {validationMetadataKey} from './metadata-key'; export function observeProperty(target, key, descriptor) { let config = metadata.getOrCreateOwn(validationMetadataKey, ValidationConfig, target); // TODO: REMOVE let innerPropertyName = `_${key}`; // typescript or babel? let babel = descriptor !== undefined; if (babel) { // babel passes in the property descriptor with a method to get the initial value. // set the initial value of the property if it is defined. if (typeof descriptor.initializer === 'function') { target[innerPropertyName] = descriptor.initializer(); } } else { descriptor = {}; } delete descriptor.writable; delete descriptor.initializer; descriptor.get = function() { return this[innerPropertyName]; }; descriptor.set = function(newValue) { let reporter = ValidationEngine.getValidationReporter(this); this[innerPropertyName] = newValue; config.validate(this, reporter); }; descriptor.get.dependencies = [innerPropertyName]; if (!babel) { Reflect.defineProperty(target, key, descriptor); } }
/* eslint-disable prefer-destructuring */ const { performance } = require('perf_hooks'); const { createCanvas } = require('canvas'); /** * To not impact browser performance at all * I am using the node implementation of canvas, * doing all the rendering server side and * returning a base64 string to render within * an <img/> element */ function drawCanvas(colors) { const width = 256; const height = 128; const canvas = createCanvas(width, height); const ctx = canvas.getContext('2d'); const imgData = ctx.createImageData(width, height); for (let i = 0; i < imgData.data.length; i += 4) { const cPos = i / 4; imgData.data[i] = colors[cPos][0]; imgData.data[i + 1] = colors[cPos][1]; imgData.data[i + 2] = colors[cPos][2]; imgData.data[i + 3] = colors[cPos][3]; } ctx.putImageData(imgData, 0, 0); return canvas.toDataURL(); } export default (req, res) => { const { query } = req; const palette = []; const steps = 32; const increment = 8; const params = new Array(steps + 1).fill().map((_, i) => i * increment); // remove 0 column color so the resulting loop returns 32,768 colors params.shift(); /** * This was my first attempt at building out the color array I would use to build the image. * Nesting loops is usually something to avoid so I wanted to see how well it performed. * Using the performance module it takes usually ~4ms. * Since it's still fast and is easy to read and reason about I decided to stick with it. */ const startP = performance.now(); const alpha = query.alpha || 255; params.forEach(r => { params.forEach(g => { params.forEach(b => { /** * One thing to note, the top value here is 256 which is above the 255 limit * for an rgb color value. Anything over 255 is treated as 255 when rendered * in canvas or the browser, so while this works there could be a case to check * and clamp >=256 down to 255. * * Adding alpha value here to match up with canvas pixel data: (r,g,b,a). */ palette.push([r, g, b, alpha]); }); }); }); const endP = performance.now(); console.log('loop time:', `${endP - startP}ms`); /** * Sort by total value of all three color components * Results in a dark to light fade effect while ignoring * the color itself. */ if (query.sort === '1') { const startS = performance.now(); const reducer = (a, b) => a + b; palette.sort((a, b) => a.reduce(reducer) - b.reduce(reducer)); const endS = performance.now(); console.log('sort time:', `${endS - startS}ms`); } res.end(JSON.stringify(drawCanvas(palette))); };
import Test from '../../_helpers/Test' import bp from '../../_helpers/breakpoints' import mq from '../../_helpers/mq' import report_result_summary from '../../_helpers/report_result_summary' import sequence from '../../_helpers/sequence' import ResultTracker from '../../_helpers/ResultTracker' import apply_style from '../../_helpers/apply_style' export default function () { let minHeightResults = new ResultTracker() class positiveTest extends Test { constructor({ name, test }) { super({ name: `positive minHeight ${name}`, test, size: [bp.large, bp.large + 1], mqMatch: true, localTracker: minHeightResults, }) } } class negativeTest extends Test { constructor({ name, test }) { super({ name: `negative minHeight ${name}`, size: [bp.large], mqMatch: false, test: test, localTracker: minHeightResults, }) } } const positive_tests = [ new positiveTest({ name: `"large" (if)`, test: () => mq.minHeight('large'), }), new positiveTest({ name: `${bp.large} (if)`, test: () => mq.minHeight(bp.large), }), new positiveTest({ name: `"large" (cb)`, test: () => { let result = false mq.minHeight('large', () => { result = true }) return result }, }), new positiveTest({ name: `${bp.large} (cb)`, test: () => { let result = false mq.minHeight(bp.large, () => { result = true }) return result }, }), ] const negative_tests = [ new negativeTest({ name: `"large" (if)`, test: () => mq.minHeight('large'), }), new negativeTest({ name: `${bp.large} (if)`, test: () => mq.minHeight(bp.large), }), new negativeTest({ name: `"large" (cb)`, test: () => { let result = false mq.minHeight('large', () => { result = true }) return result }, }), new negativeTest({ name: `${bp.large} (cb)`, test: () => { let result = false mq.minHeight(bp.large, () => { result = true }) return result }, }), ] return sequence([ apply_style('minHeight'), ...positive_tests, ...negative_tests, report_result_summary('minHeight', minHeightResults), ]) }
/*! * angular-translate - v2.5.2 - 2015-01-13 * http://github.com/angular-translate/angular-translate * Copyright (c) 2015 ; Licensed MIT */ angular.module('pascalprecht.translate') /** * @ngdoc object * @name pascalprecht.translate.$translateStaticFilesLoader * @requires $q * @requires $http * * @description * Creates a loading function for a typical static file url pattern: * "lang-en_US.json", "lang-de_DE.json", etc. Using this builder, * the response of these urls must be an object of key-value pairs. * * @param {object} options Options object, which gets prefix, suffix and key. */ .factory('$translateStaticFilesLoader', ['$q', '$http', function ($q, $http) { return function (options) { if (!options || (!angular.isString(options.prefix) || !angular.isString(options.suffix))) { throw new Error('Couldn\'t load static files, no prefix or suffix specified!'); } var deferred = $q.defer(); $http(angular.extend({ url: [ options.prefix, options.key, options.suffix ].join(''), method: 'GET', params: '' }, options.$http)).success(function (data) { deferred.resolve(data); }).error(function (data) { deferred.reject(options.key); }); return deferred.promise; }; }]);
define(function(require) { var Class = require('class/Class'); //Abstraction of relative positioning information, modeled after jQuery UI //(more predictable) and jquery.qTip (more precise) var Position = Class.extend(/** @lends Position.prototype */ { __defaults: { x: null, y: null, precedence: null }, /** * @constructs */ constructor: function(opts) { if (opts && opts.constructor === String) { return Position.fromString(opts); } this._apply(opts); }, /** @type {String} */ x: { get: null, set: null }, /** @type {String} */ y: { get: null, set: null }, /** @type {String} */ precedence: { get: null, set: null }, /** @type {Array<String>} */ order: { get: function() { if (this.precedence === 'x') { return ['x', 'y']; } return ['y', 'x']; } }, /** @type {Array<String>} */ parts: { get: function() { if (this.precedence === 'x') { return [this.x, this.y]; } return [this.y, this.x]; } }, /** * @return {joss/geometry/Position} */ reverse: function() { var pos = this.clone(); if (pos.x === 'left') { pos.x = 'right'; } else if (pos.x === 'right') { pos.x = 'left'; } else { pos.x = 'center'; } if (pos.y === 'top') { pos.y = 'bottom'; } else if (pos.y === 'bottom') { pos.y = 'top'; } else { pos.y = 'center'; } return pos; }, /** * @return {String} */ toString: function() { if (this.precedence === 'x') { return this.x + ' ' + this.y; } else { return this.y + ' ' + this.x; } } }); //Position /** * translate something like 'left top' into a joss.Position object. order * doesn't matter. * @param {String} str * @return {joss/geometry/Position} */ Position.fromString = function(str) { var parts = str.split(' '); var axes = []; if (parts.length === 1) { parts[1] = 'center'; } parts.forEach(function(part, i) { switch (part) { case 'left': case 'right': axes[i] = 'x'; break; case 'top': case 'bottom': axes[i] = 'y'; break; default: axes[i] = null; parts[i] = 'center'; break; } }); //each axis, if null ("center" was given), is the opposite of the other axis axes[0] = axes[0] || ((axes[1] === 'x') ? 'y' : 'x'); axes[1] = axes[1] || ((axes[0] === 'x') ? 'y' : 'x'); var pos = new Position(); pos.precedence = axes[0]; axes.forEach(function(axis, i) { switch(axis) { case 'x': pos.x = parts[i]; break; case 'y': pos.y = parts[i]; break; } }); return pos; }; return Position; });
import ReactVelocityTransitionGroup from './lib/ReactVelocityTransitionGroup'; export default ReactVelocityTransitionGroup;
function EDMDGraphics(simulation, canvas) { this._simulation = simulation; this._canvas = canvas; this._sim_dt_per_frame = 1000.0; this.update = function() { this._simulation.step(this._sim_dt_per_frame); }; this.show = function() { this._show_background(); this._show_particles(); this._highlight_first_event(); this._show_time(); this._show_fps(); }; this._show_background = function() { push(); background(51); stroke(255); strokeWeight(1); pop(); }; this._show_particles = function() { for (var i=0; i < this._simulation.particles.length; i++) { this._simulation.particles[i].show(); }; }; this._show_time = function() { push(); textSize(32); fill(255, 255, 255); textAlign(LEFT, TOP); text(this._simulation.time.toFixed(1)+'s', this._canvas.width*0.02, this._canvas.height*0.02); pop(); }; this._show_fps = function() { push() textAlign(LEFT,BOTTOM); text(frameRate().toFixed(0) + 'fps', this._canvas.width*0.02, this._canvas.height*0.98); pop() }; this._highlight_first_event = function() { /* Highlight the particle(s) involved in first event (if any exists) */ var event = this._simulation.first_event(); if (event != null) { event.part_1.highlight(); if (event.part_2) { event.part_2.highlight(); }; }; }; }
angular.module( 'comparcelTester', [ 'templates-app', 'templates-common', 'comparcelTester.home', 'ui.state', 'ui.route' ]) .config( function myAppConfig ( $stateProvider, $urlRouterProvider ) { // default route is home $urlRouterProvider.otherwise( '/home' ); }) .run( function run ( titleService ) { titleService.setSuffix( ' | comparcel.com' ); }) .controller( 'AppCtrl', function AppCtrl ( $scope, $location ) { // some main app stuff goes here }) ;
/** Copyright (c) 2007 Bill Orcutt (http://lilyapp.org, http://publicbeta.cx) Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ /** * Construct a new dialog object * @class * @constructor * @extends LilyObjectBase */ function $dialog() { var thisPtr=this; this.outlet1 = new this.outletClass("outlet1",this,"result of dialog if any"); this.inlet1=new this.inletClass("inlet1",this,"\"alert\",\"confirm\",\"prompt\""); this.inlet1["alert"]=function(msg) { thisPtr.parent.patchView.oWin.alert(msg); } this.inlet1["confirm"]=function(msg) { thisPtr.outlet1.doOutlet(thisPtr.parent.patchView.oWin.confirm(msg)); } this.inlet1["prompt"]=function(msg) { thisPtr.outlet1.doOutlet(thisPtr.parent.patchView.oWin.prompt(msg)); } return this; } var $dialogMetaData = { textName:"dialog", htmlName:"dialog", objectCategory:"System", objectSummary:"Display an alert, confirm or prompt dialog.", objectArguments:"" }
$('.comment').each(function(){ if(this.id.length > 0){ player_id = $("#"+this.id+' .comment-player a').attr("href").substr(9); $("#"+this.id + ' .comment-body div').after('<div id="comment-sig' + player_id + '"><a target="__new" href="http://getdotastats.com/sig/' + player_id + '.png"><img style="margin:auto; margin-bottom:20px; display:block;" src="http://getdotastats.com/sig/forum.php?aid=' + player_id + '"></a><div style="margin-top:-15px;text-align: center;"><a href="http://strawpoll.me/1511023">Want these to stay? Vote now!</a> || <a href="http://getdotastats.com/dbe/forum_sigs.php">What is this?</a></div></div>'); } });
const DrawCard = require('../../drawcard.js'); const { Locations, Players, CardTypes, PlayTypes} = require('../../Constants'); const AbilityDsl = require('../../abilitydsl'); class WarmWelcome extends DrawCard { setupCardAbilities() { this.action({ title: 'Play a conflict card from discard', condition: context => context.player.opponent && context.player.showBid < context.player.opponent.showBid, target: { location: Locations.ConflictDiscardPile, controller: Players.Self, gameAction: AbilityDsl.actions.sequential([ AbilityDsl.actions.playCard(context => ({ target: context.target, playType: PlayTypes.PlayFromHand })), AbilityDsl.actions.moveCard(context => ({ target: context.target.type === CardTypes.Event ? context.target : [], destination: Locations.ConflictDeck, bottom: true })) ]) } }); } } WarmWelcome.id = 'warm-welcome'; module.exports = WarmWelcome;
var data = { contents: [ // { // top: '1', // date: 'Dec 14, 2017', // datecn: '2017.12.14', // cover: 'images/news/'+'', // title: '', // titlecn: '', // intro: '', // introcn: '', // url: 'news/'+''+'.html', // urlcn: 'news/'+''+'_cn.html' // }, { top: '1', date: 'Dec 14, 2017', datecn: '2017.12.14', cover: 'images/news/' + 'uk_think_tank_blockchain.jpg', title: 'UK Think Tank:Blockchain Radically Changes the State-Individual Relationship\n', titlecn: '英智囊团称区块链将从根本上改变国家与个人的关系\n', intro: 'Recently, Reform, an independent think tank in the UK, recommended that the British government should use blockchain technology to manage personal information of citizens, which means a radical shift in the role of the government.', introcn: '近日,英国独立智囊团Reform建议英国政府使用区块链技术来管理市民的个人信息,这意味着政府角色的根本性转变。', url: 'news/' + 'uk_think_tank_blockchain_radically_change_the_state_individual_relationship' + '.html', urlcn: 'news/' + 'uk_think_tank_blockchain_radically_change_the_state_individual_relationship' + '_cn.html' }, { top: '1', date: 'Dec 14, 2017', datecn: '2017.12.14', cover: 'images/news/' + 'group_of_banks.jpg', title: 'Group of Banks and Startups to Build Blockchain for Sharing Supply Chain Data in Malawi \n', titlecn: '银行和初创企业合作为马拉维建立区块链共享供应链数据', intro: 'The first pilot will be conducted in January 2018, which will see data on environmental and social standards in the supply chain transmitted via blockchain technology', introcn: '首次试点将于2018年1月进行。此次试点将通过区块链技术传输供应链中有关环境和社会标准的数据。', url: 'news/' + 'group_of_banks_and_startups_to_build_blockchain_for_sharing_supply_chain_data_in_malawi' + '.html', urlcn: 'news/' + 'group_of_banks_and_startups_to_build_blockchain_for_sharing_supply_chain_data_in_malawi' + '_cn.html' }, { date: 'Dec 14, 2017', datecn: '2017.12.14', cover: 'images/news/' + 'us_president.jpg', title: 'U.S. President Signs $700 Billion Defense Bill, Authorizing Blockchain Security Study\n', titlecn: '特朗普签署7000亿美元军费国防法案,授权区块链安全性研究\n', intro: 'Yesterday, U.S. President Donald Trump signed a $700 billion military spending bill, authorizing a blockchain security study.', introcn: '“昨日,美国总统特朗签署了一份7000亿美元的军费开支法案,授权进行区块链安全性研究,旨在提升政府IT和网络安全系统”\n', url: 'news/' + 'us_president_signs_700_billion_defense_bill' + '.html', urlcn: 'news/' + 'us_president_signs_700_billion_defense_bill' + '_cn.html' }, { date: 'Dec 13, 2017', datecn: '2017.12.13', cover: 'images/news/' + 'financial_companies_led.jpg', title: 'Financial Companies Led by UBS Pilot Testing Ethereum Blockchain for Data Reporting\n', titlecn: '瑞银牵头的金融公司测试利用以太坊区块链技术进行数据报告\n', intro: 'The Ethereum platform can provide the transparency needed to fulfil new regulations on data sharing set by the European Union', introcn: '以太坊平台可以提供履行欧盟制定的数据共享新规定所需的透明度', url: 'news/' + 'financial_companies_led_by_ubs_pilot_testing_ethereum_blockchain_for_data_reporting' + '.html', urlcn: 'news/' + 'financial_companies_led_by_ubs_pilot_testing_ethereum_blockchain_for_data_reporting' + '_cn.html' }, { date: 'Dec 13, 2017', datecn: '2017.12.13', cover: 'images/news/' + 'japanese_internet.jpg', title: 'Japanese Internet Giant GMO Introduces Bitcoin Salary Payment System\n', titlecn: '日本互联网巨头GMO推出比特币薪酬体系', intro: 'Japanese Internet giant GMO has launched a new payroll system to allow its 4,700+ staffs to receive part of their salaries in bitcoin.', introcn: '日本互联网巨头GMO推出了一个全新的薪酬体系,公司旗下4700多名员工的部分工资会以比特币的形式发放。', url: 'news/' + 'japanese_internet_giant_gmo_pay_employees_bitcoin' + '.html', urlcn: 'news/' + 'japanese_internet_giant_gmo_pay_employees_bitcoin' + '_cn.html' }, { date: 'Dec 13, 2017', datecn: '2017.12.13', cover: 'images/news/' + 'russia_biggest.jpg', title: 'Sberbank Conducts Money Transfer on an IBM Blockchain\n', titlecn: '俄最大资产银行Sberbank通过IBM区块链软件实现资金转账\n', intro: 'Recently, Sberbank, Russia’s largest bank by asset, has conducted the first money transfer over an IBM-built blockchain based on the Hyperledger Fabric 1.0 .', introcn: '日前,俄罗斯最大资产银行Sberbank通过IBM基于Hyperledger Fabric 1.0构建的区块链,实现了首笔资金转账。', url: 'news/' + 'russia_biggest_bank_pilots_money_transfer_on_an_ibm_blockchain' + '.html', urlcn: 'news/' + 'russia_biggest_bank_pilots_money_transfer_on_an_ibm_blockchain' + '_cn.html' }, { date: 'Dec 12, 2017', datecn: '2017.12.12', cover: 'images/news/' + 'deutsche_bank_voices.jpg', title: 'Deutsche Bank Voices High Confidence in Blockchain Technology to Change Financial Sector', titlecn: '德意志银行:对区块链技术改变金融业充满信心\n', intro: 'Stance on cryptocurrencies is more conservative, and Deutsche Bank noted that digital currencies may develop into a new asset class with more governmental regulations', introcn: '德意志银行对加密货币持保守态度,并指出随着更多政府监管政策的出台,数字货币可能会成为一种新的资产类别', url: 'news/' + 'deutsche_bank_voices_high_confidence_in_blockchain_technology_to_change_financial_sector' + '.html', urlcn: 'news/' + 'deutsche_bank_voices_high_confidence_in_blockchain_technology_to_change_financial_sector' + '_cn.html' }, { date: 'Dec 12, 2017', datecn: '2017.12.12', cover: 'images/news/' + 'cryptokitties_could.jpg', title: ' Sales Hit $12 Million, CryptoKitties is Predicted as Ethereum’s Killer App \n', titlecn: '销售额破1200万美元,“加密猫”或成为以太坊杀手级APP\n', intro: 'With one kitten sold at the price of $120,000 and the total volume of 70,000 in two weeks, the sales of Cryptokitties had exceeded $12 million by the end of yesterday. ', introcn: '一只卖到12万,两周交易7万只,截止昨日加密猫销售额破1200万美元,CryptoKitties证明了无摩擦和无缝数字资产交易的可能性', url: 'news/' + 'cryptokitties_could_be_ethereum_killer_app' + '.html', urlcn: 'news/' + 'cryptokitties_could_be_ethereum_killer_app' + '_cn.html' }, { date: 'Dec 12, 2017', datecn: '2017.12.12', cover: 'images/news/' + 'cboe_bitcoin_futures.jpg', title: 'CBOE’s Bitcoin Futures Started So Hot in its Debut, Halted Twice within Two Hours\n', titlecn: 'CBOE比特币期货首秀收涨20%,两小时内熔断两次 \n', intro: 'Yesterday, bitcoin futures was officially launched on CBOE, triggering two temporary trading halts designed to calm the market', introcn: '昨日,比特币期货合约正式在CBOE上线交易。至今可以看出,其展现出的话题性和波动性,并不逊于现货市场。', url: 'news/' + 'cboe_bitcoin_futures_started_so_hot_in_its_debut' + '.html', urlcn: 'news/' + 'cboe_bitcoin_futures_started_so_hot_in_its_debut' + '_cn.html' }, { id: '', date: 'Dec 11, 2017', datecn: '2017.12.11', cover: 'images/news/' + 'un_appoints_new.jpg', title: 'UN Appoints New Member to Its Blockchain Commission for Sustainable Development\n', titlecn: '联合国区块链可持续发展委员会增加新成员', intro: 'The United Nations has been actively promoting the application of blockchain technology in various projects including food distribution system, climate change, identity authentication and financial remittance.', introcn: '联合国一直积极推动区块链技术在分发援助、气候变化、身份证明和金融汇款等各类项目上的应用。', url: 'news/' + 'un_appoints_new_member_to_its_blockchain_commission_for_sustainable_development' + '.html', urlcn: 'news/' + 'un_appoints_new_member_to_its_blockchain_commission_for_sustainable_development' + '_cn.html' }, { id: '', date: 'Dec 11, 2017', datecn: '2017.12.11', cover: 'images/news/' + 'craigslist_users.jpg', title: 'Craigslist Users Can Now Indicate They Want to Transact via Cryptocurrency\n', titlecn: 'Craigslist用户现在可以选择通过加密货币进行交易', intro: 'Users can also filter their search results to show only sellers that accept cryptocurrency payments', introcn: '用户也可以筛选他们的搜索结果,使其只显示接受加密货币支付的卖家', url: 'news/' + 'craigslist_users_can_now_indicate_they_want_to_transact_via_cryptocurrency' + '.html', urlcn: 'news/' + 'craigslist_users_can_now_indicate_they_want_to_transact_via_cryptocurrency' + '_cn.html' }, { id: '', date: 'Dec 11, 2017', datecn: '2017.12.11', cover: 'images/news/' + 'russia_telegram.jpg', title: 'Russia Telegram Group: Bittrex Users Information Probably Leaked\n', titlecn: '俄罗斯电报:Bittrex交易所用户信息可能遭泄露\n', intro: 'For digital currency investors, asset security is their most concerned issue, followed by the protection of personal information.', introcn: '对于数字货币投资者而言,资产的安全问题最为重要,其次就是个人信息的保护,加密货币交易目前仍是网络罪犯的主要目标。', url: 'news/' + 'russia_telegram_group_bittrex_users_information_probably_leaked' + '.html', urlcn: 'news/' + 'russia_telegram_group_bittrex_users_information_probably_leaked' + '_cn.html' }, { id: '', date: 'Dec 10, 2017', datecn: '2017.12.10', cover: 'images/news/' + 'france_makes_it.jpg', title: 'France Makes It Legal for Use of Blockchain to Trade Non-listed Securities', titlecn: '法国规定用区块链交易未上市证券是合法行为', intro: 'Reportedly, blockchain will pave the way for a quicker, more secure and cost-effective mode for securities exchanges', introcn: '据报道,区块链将有助于建立更快、更安全、更划算的证券交易模式', url: 'news/' + 'france_makes_it_legal_for_use_of_blockchain' + '.html', urlcn: 'news/' + 'france_makes_it_legal_for_use_of_blockchain' + '_cn.html' }, { id: '', date: 'Dec 9, 2017', datecn: '2017.12.09', cover: 'images/news/' + 'indonesia_bans_Fintech.jpg', title: 'Indonesia Bans Fintech Companies from Receiving Payments via Cryptocurrencies', titlecn: '印度尼西亚禁止金融科技公司通过加密货币接收付款', intro: 'Exchange and trading of cryptocurrencies, however, is not banned', introcn: '然而,加密货币的兑换和交易并没有被禁止', url: 'news/' + 'indonesia_bans_Fintech_Companies_from_Receiving_Payments_via_Cryptocurrencies' + '.html', urlcn: 'news/' + 'indonesia_bans_Fintech_Companies_from_Receiving_Payments_via_Cryptocurrencies' + '_cn.html' }, { id: '', date: 'Dec 8, 2017', datecn: '2017.12.08', cover: 'images/news/' + 'australia_is__first.jpg', title: 'Australia Is World’s First to Replace Existing Technology for Trade Platform with Blockchain\n', titlecn: '澳大利亚全球首例:用区块链技术取代贸易平台的现有技术\n', intro: 'With Digital Asset as partner, the Australian Securities Exchange aims to release the first blockchain prototype by March 2018 for market review', introcn: '澳大利亚证券交易所与数字资产控股公司合作,旨在于2018年3月底之前发布首个区块链原型进行市场观察', url: 'news/' + 'australia_is__first_to_replace_existing_technology' + '.html', urlcn: 'news/' + 'australia_is__first_to_replace_existing_technology' + '_cn.html' }, { id: '', date: 'Dec 8, 2017', datecn: '2017.12.08', cover: 'images/news/' + 'huobi_cooperates.jpg', title: 'Huobi Cooperates with SBI to Jointly Develop Digital Asset Markets\n', titlecn: '火币与日本SBI达成战略合作,共同开拓数字资产市场\n', intro: 'Huobi Group and SBI Group reached strategic cooperation to jointly develop digital asset markets.', introcn: '火币集团与日本SBI集团达成战略合作,共同开拓数字资产市场。', url: 'news/' + 'huobi_cooperates_with_sbi_to_develop_digital_asset_markets' + '.html', urlcn: 'news/' + 'huobi_cooperates_with_sbi_to_develop_digital_asset_markets' + '_cn.html' }, { id: '', date: 'Dec 8, 2017', datecn: '2017.12.08', cover: 'images/news/' + 'yahoo_co_founder.jpg', title: 'Yahoo’s Co-founder Jerry Yang Is Positive on Bitcoin\n', titlecn: '雅虎联合创始人杨致远对比特币持积极态度\n', intro: 'Bitcoin’s skyrocketing price has drawn attention from all walks of life and received mixed opinions. Yesterday, Yahoo’s co-founder Jerry Yang said Bitcoin would be beneficial to the society', introcn: '比特币价格的疯涨吸引了各界的关注,其受到的评价也褒贬不一。昨日,雅虎联合创始人杨致远表示比特币将对社会有益。', url: 'news/' + 'yahoo_co_founder_jerry_yang__a_positive_stance_on_bitcoin' + '.html', urlcn: 'news/' + 'yahoo_co_founder_jerry_yang__a_positive_stance_on_bitcoin' + '_cn.html' }, { id: '', date: 'Dec 7, 2017', datecn: '2017.12.07', cover: 'images/news/' + 'ubs_applies_for_intellectual.jpg', title: 'UBS Applies for Intellectual Property Protection for Smart Contract Blockchain Validation\n', titlecn: '瑞银为智能合约区块链验证申请知识产权保护\n', intro: 'The largest financial services company in Europe-United Bank of Switzerland is looking to creating more secure computer systems for the patent application of smart contract blockchain validation.', introcn: '欧洲最大的金融控股集团——瑞士联合银行集团目前正在研究创建更安全的计算机系统,为智能合约区块链验证申请专利保护。', url: 'news/' + 'ubs_applies_for_intellectual_property_protection_for_smart_contract_blockchain_validation' + '.html', urlcn: 'news/' + 'ubs_applies_for_intellectual_property_protection_for_smart_contract_blockchain_validation' + '_cn.html' }, { id: '', date: 'Dec 7, 2017', datecn: '2017.12.07', cover: 'images/news/' + 'nokia_looks_to_blockchain.jpg', title: 'Nokia Looks to Blockchain Technology for Users to Share Health Data Securely', titlecn: '诺基亚寻求运用区块链技术使用户安全分享健康数据\n', intro: 'Nokia is partnering with OP Financial Group to launch a blockchain pilot program, aimed at boosting customer confidence in sharing health data securely', introcn: '诺基亚正与OP金融集团合作开启区块链试点项目,旨在增强用户对安全分享健康数据的信心', url: 'news/' + 'nokia_looks_to_blockchain_technology_for_users_to_share_health_data_securely' + '.html', urlcn: 'news/' + 'nokia_looks_to_blockchain_technology_for_users_to_share_health_data_securely' + '_cn.html' }, { id: '', date: 'Dec 7, 2017', datecn: '2017.12.07', cover: 'images/news/' + 'blockchain_new.jpg', title: 'Blockchain New Use: CryptoKitties\n', titlecn: '区块链新应用,养一只别人抢不走还能赚钱的喵星人!\n', intro: 'The combination of game application and blockchain marks that the blockchain industry has entered a historic phase', introcn: '游戏应用和区块链的成功结合,说明区块链行业进入了一个新的阶段,这也是一次历史性的事件。', url: 'news/' + 'blockchain_new_use_cryptokitties' + '.html', urlcn: 'news/' + 'blockchain_new_use_cryptokitties' + '_cn.html' }, { id: '', date: 'Dec 6, 2017', datecn: '2017.12.06', cover: 'images/news/' + 'ukraine_bank_expands.jpg', title: 'Ukraine’s Central Bank Expands its Research Team to Move National Currency to Blockchain\n', titlecn: '乌克兰央行扩建区块链研究团队,拟推出国家数字货币\n', intro: 'Bring your vision closer to reality: In recent years, central banks around the world have been exploring blockchain technology, while the Ukraine central bank took the lead in making a more detailed plan of creating ‘national digital currency’ with the intention of launching e-hryvnia. ', introcn: '让理想更贴近现实:近年来,全球各国央行一直在探索区块链技术,但乌克兰央行率先对创建“国家数字货币”作出了更详细的设想,打算推出电子格里夫纳(e-hryvnia)。', url: 'news/' + 'ukraine_bank_expands_its_research_team_to_move_national_currency_to_blockchain' + '.html', urlcn: 'news/' + 'ukraine_bank_expands_its_research_team_to_move_national_currency_to_blockchain' + '_cn.html' }, { id: '', date: 'Dec 6, 2017', datecn: '2017.12.06', cover: 'images/news/' + 'weekly_tracker_state.jpg', title: 'Weekly Tracker, Russia and Ukraine Government Seeks Further Use of Blockchain in Public Sector', titlecn: '每周追踪报道:俄罗斯和乌克兰政府进一步研究将区块链用在公共部门\n', intro: 'This week, Russia looks to blockchain for voting technology and Ukraine central bank expands its research team to move its currency – hyrvnia – to blockchain.', introcn: '本周,俄罗斯政府寻求利用区块链进行投票,与此同时,乌克兰中央银行扩大其研究团队,旨在将该国的国家货币-hyrvnia-转移至区块链上。', url: 'news/' + 'weekly_tracker_russia_and_ukraine_government_seeks_further_use_of_blockchain_in_public_sector' + '.html', urlcn: 'news/' + 'weekly_tracker_russia_and_ukraine_government_seeks_further_use_of_blockchain_in_public_sector' + '_cn.html' }, { id: '', date: 'Dec 6, 2017', datecn: '2017.12.06', cover: 'images/news/' + 'ethereum_founder_vitalik.jpg', title: 'Ethereum Founder Vitalik Buterin Was named as One of Bloomberg’s Top 50 Most Influential People\n', titlecn: '以太坊创始人Vitalik Buterin入选彭博社全球50位最具影响力人物\n', intro: '“From finance and politics to technology and culture, there is always people to promote the whole industry development from all walks of life. Among the 50 top influential figures released by the Bloomberg, Vitalik Buterin, the founder of Ethereum , takes one of the seats.”\n', introcn: '从金融、政治到技术、文化领域,各行各业都不乏对整个行业起到推动作用的人物。此次彭博社发布的最具影响力的50位人物中,以太坊创始人Vitalik Buterin榜上有名。', url: 'news/' + 'ethereum_founder_vitalik_buterin_one_of_bloomberg_50_most_influential_people' + '.html', urlcn: 'news/' + 'ethereum_founder_vitalik_buterin_one_of_bloomberg_50_most_influential_people' + '_cn.html' }, { id: '', date: 'Dec 5, 2017', datecn: '2017.12.05', cover: 'images/news/' + 'block_one_officially.jpg', title: 'Block.One Officially Releases EOS.IO Single-Thread Application Test Network (EOS STAT)\n', titlecn: 'block.one正式发布EOS.IO单线程应用测试网络EOS STAT\n', intro: 'Following a new record Block.One set by raising $185 million in the ICO of its EOS in July this year, the company officially released EOS.IO single-thread application test network EOS STAT yesterday.”', introcn: '继今年7月block.one以发行EOS加密货币的形式筹资1.85亿美元创下历史记录后,该公司于昨日正式发布EOS.IO单线程应用测试网络EOS STAT。', url: 'news/' + 'block_one_officially_releases_eos_io_single' + '.html', urlcn: 'news/' + 'block_one_officially_releases_eos_io_single' + '_cn.html' }, { id: '', date: 'Dec 5, 2017', datecn: '2017.12.05', cover: 'images/news/' + 'new_york_lawmaker.jpg', title: 'New York Lawmaker Introduces Four New Bills on Blockchain Technology', titlecn: '纽约州立法者引入四项区块链技术新法案\n', intro: 'All bills aim to further the research of blockchain technology for possible implementation in various public processes', introcn: '所有法案旨在推进区块链技术在各种公共领域可能的应用研究。', url: 'news/' + 'new_york_lawmaker_introduces_four_new_bills_on_blockchain_technology' + '.html', urlcn: 'news/' + 'new_york_lawmaker_introduces_four_new_bills_on_blockchain_technology' + '_cn.html' }, { id: '', date: 'Dec 5, 2017', datecn: '2017.12.05', cover: 'images/news/' + 'cboe_takes_the_lead.jpg', title: 'CBOE Takes the Lead to Begin Bitcoin Futures Trading on December 10\n', titlecn: '明争暗斗:CBOE抢先CME将于12月10日推出比特币期货\n', intro: 'The cryptocurrency bitcoin is currently trading at roughly $11,400. About One week earlier than CME, CBOE will take the lead to begin Bitcoin Futures Trading on Dec. 10. The firm also offers XBT futures trading for free.\n', introcn: '比特币期货赛场消息:目前比特币市场价已接近11,400美元。CBOE抢先CME 8天,将于12月10日推出比特币期货,并在本月免除交易费为抢跑发力。', url: 'news/' + 'cboe_takes_the_lead_to_begin_bitcoin_futures_trading' + '.html', urlcn: 'news/' + 'cboe_takes_the_lead_to_begin_bitcoin_futures_trading' + '_cn.html' }, { id: '', date: 'Dec 5, 2017', datecn: '2017.12.05', cover: 'images/news/' + 'ant_financial.jpg', title: 'Ant Financial Services Shows its Blockchain Achievements at the Fourth World Internet Conference\n', titlecn: '蚂蚁金服区块链成果亮相第四届世界互联网大会\n', intro: 'As long as the license plate is tied to Alipay, visitors can smoothly drive out without a stop or paying in cash, even without the need to take out the phone.', introcn: '只要先将车牌和支付宝绑定好,来客开车离场时,无需停车、不掏现金,甚至连手机也不用拿,就能顺利出行。', url: 'news/' + 'ant_financial__shows_its_blockchain_achievements' + '.html', urlcn: 'news/' + 'ant_financial__shows_its_blockchain_achievements' + '_cn.html' }, { id: '', date: 'Dec 4, 2017', datecn: '2017.12.04', cover: 'images/news/' + 'financial_regulator_in.jpg', title: 'Financial Regulator in South Korea Close to Classifying Unauthorized Cryptocurrency Exchanges as Illegal Fundraising under New Regulations\n', titlecn: '未经授权的加密货币交易所为非法融资? 韩国金融监管机构拟定新条例\n', intro: 'Cryptocurrency exchanges can however apply for authorization to operate, on condition they implement standards and measures for customer protection and enhanced transparency', introcn: '然而,加密货币交易所也可以申请授权操作,条件是它们要执行客户保护和提高透明度的标准及措施。', url: 'news/' + 'financial_regulator_in_south_korea_close_to_classifying_unauthorized_cryptocurrency_exchanges' + '.html', urlcn: 'news/' + 'financial_regulator_in_south_korea_close_to_classifying_unauthorized_cryptocurrency_exchanges' + '_cn.html' }, { id: '', date: 'Dec 4, 2017', datecn: '2017.12.04', cover: 'images/news/' + 'uraiden_payment_channels.jpg', title: 'uRaiden Payment Channels Launches on the Main Ethereum Blockchain Network \n', titlecn: '微型雷电网络正式上线以太坊主网络\n', intro: 'As one of the recently fastest-growing digital assets, a streamlined version of Ethereum’s Lightning Network, uRaiden, has been officially launched on main Ethereum blockchain yesterday', introcn: '作为近期涨幅最快的数字资产之一,雷电网络的简化版本微型雷电网络昨日已正式上线', url: 'news/' + 'uraiden_payment_channels_launches_on_the_main_ethereum_blockchain_network' + '.html', urlcn: 'news/' + 'uraiden_payment_channels_launches_on_the_main_ethereum_blockchain_network' + '_cn.html' }, { id: '', date: 'Dec 4, 2017', datecn: '2017.12.04', cover: 'images/news/' + 'asia_pacific_ethereum.jpg', title: 'Asia-Pacific Ethereum Community Meetup Successfully Taken Place in Shenzhen, China\n', titlecn: '亚太以太坊社区首次技术培训暨交流活动在深圳成功举办\n', intro: 'Blockchain Technology is seen as another mainstream trend apart from mobile internet. Its properties of decentralization, trustlessness, tamper-resistance have unparalleled advantages over traditional technologies. ', introcn: '区块链技术被认为是继移动互联网之后的又一发展趋势,其去中心化、去信用化、数据不可篡改的特性,相对传统技术有着不可比拟的优势,行业应用场景十分多元。', url: 'news/' + 'asia_pacific_ethereum_community_meetup' + '.html', urlcn: 'news/' + 'asia_pacific_ethereum_community_meetup' + '_cn.html' }, { id: '', date: 'Dec 3, 2017', datecn: '2017.12.03', cover: 'images/news/' + 'professor_at_cmu.jpg', title: 'Professor at CMU Predicts Ethereum Will Overtake Bitcoin as The Number One Cryptocurrency', titlecn: 'CMU的教授预测以太坊将超越比特币成为第一大加密货币', intro: 'According to Professor Vipul Goyal, Ethereum’s main edge over Bitcoin is its powerful and versatile blockchain platform that goes beyond the facilitation of payments', introcn: '根据Vipul Goyal教授的说法,与比特币相比,以太坊的主要优势在于其强大且多功能的区块链平台。这一平台提供的不仅仅只是支付的便利性。', url: 'news/' + 'professor_at_cmu_ethereum_will_overtake_bitcoin' + '.html', urlcn: 'news/' + 'professor_at_cmu_ethereum_will_overtake_bitcoin' + '_cn.html' }, { id: '', date: 'Dec 3, 2017', datecn: '2017.12.03', cover: 'images/news/' + 'kyber_network_partners.jpg', title: 'Kyber Network Partners With imToken\n', titlecn: 'Kyber Netwok将与imToken合作', intro: 'China’s leading mobile wallet app just got more im-pressive.\n', introcn: '中国领先的移动端钱包应用程序刚刚取得了更加显著的发展。', url: 'news/' + 'kyber_network_partners_with_imtoken' + '.html', urlcn: 'news/' + 'kyber_network_partners_with_imtoken' + '_cn.html' }, { id: '', date: 'Dec 2, 2017', datecn: '2017.12.02', cover: 'images/news/' + 'san_francisco_federal.png', title: 'San Francisco Federal Reserve Bank President Says No to Native Digital Currency, While Counterpart in New York Says Yes', titlecn: '旧金山联邦储备银行行长不同意推出银行自身的数字货币,而纽约联邦储备银行行长则持相反态度', intro: 'Remarks by John Williams also reaffirm confidence in blockchain technology, in the U.S.', introcn: 'John Williams在讲话中也重申了对美国采用区块链技术的信心。', url: 'news/' + 'san_francisco_federal_reserve_president_says_no_to_native_digital_currency' + '.html', urlcn: 'news/' + 'san_francisco_federal_reserve_president_says_no_to_native_digital_currency' + '_cn.html' }, { id: '', date: 'Dec 2, 2017', datecn: '2017.12.02', cover: 'images/news/' + 'top_religious_body.jpg', title: 'Top religious body in Turkey denounces cryptocurrencies as incompatible with Islam', titlecn: '土耳其最高宗教团体谴责加密货币与伊斯兰教不相容', intro: 'Reasons include the volatility of cryptocurrencies, the lack of a central authority, and possible uses for money laundering', introcn: '其原因包括加密货币的波动性,缺乏国家中央机构的监督以及可能用于洗钱活动', url: 'news/' + 'top_religious_body_in_turkey__cryptocurrencies_as_incompatible_with_islam' + '.html', urlcn: 'news/' + 'top_religious_body_in_turkey__cryptocurrencies_as_incompatible_with_islam' + '_cn.html' }, { id: '', date: 'Dec 1, 2017', datecn: '2017.12.01', cover: 'images/news/' + 'sberbank_successfully.jpg', title: 'Sberbank Successfully Completes Its First Blockchain-powered Payment Transaction\n', titlecn: 'Sberbank成功完成了首次区块链支付交易\n', intro: 'Conducted under the IBM Blockchain Platform, the transaction was reported to be a lot quicker as compared to traditional methods of money transfer', introcn: '据悉,与传统的转账方式相比,在IBM区块链平台上进行交易要快得多', url: 'news/' + 'sberbank_successfully_completes_its_first_blockchain_powered_payment_transaction' + '.html', urlcn: 'news/' + 'sberbank_successfully_completes_its_first_blockchain_powered_payment_transaction' + '_cn.html' }, { id: '', date: 'Dec 1, 2017', datecn: '2017.12.01', cover: 'images/news/' + 'forbes_5_predictions.jpg', title: 'Forbes: 5 Predictions On How Blockchain Will Drive Digital Transformation', titlecn: '福布斯:区块链使数字变革发展到更高程度的预测\n', intro: 'The technology that once was the lesser known force behind Bitcoin is now seeing its own day in the sun. There will be a time when it seems impossible that we ever survived without blockchain technology.', introcn: '曾经,比特币背后的区块链技术鲜为人知,如今它已大放异彩。将来终会有一天我们根本离不开区块链技术!', url: 'news/' + 'forbes_5_predictions_on_how_blockchain_will_drive_digital_transformation' + '.html', urlcn: 'news/' + 'forbes_5_predictions_on_how_blockchain_will_drive_digital_transformation' + '_cn.html' }, { id: '', date: 'Dec 1, 2017', datecn: '2017.12.01', cover: 'images/news/' + 'blockchain_drives_artificial.jpg', title: 'Blockchain Drives Artificial Intelligence? NEO Announces Its Strategic Investment in Deep Brain Chain\n', titlecn: '区块链驱动人工智能?NEO战略投资深脑链\n', intro: 'From Go to human speech recognition, researchers in the field of artificial intelligence (AI) have made great achievements in recent years. In short, big data has changed AI, and blockchain technology also expects to transform AI in its own way.', introcn: '从围棋到人类级别的语音识别,近年来人工智能领域的研究人员已攻克了诸多问题。简言之,大数据改变了人工智能,区块链技术也有望以自己独特的方式彻底改变人工智能。', url: 'news/' + 'blockchain_drives_artificial_intelligence' + '.html', urlcn: 'news/' + 'blockchain_drives_artificial_intelligence' + '_cn.html' }, { id: '', date: 'Nov 30, 2017', datecn: '2017.11.30', cover: 'images/news/' + 'ethereum_proof_of_stake.jpeg', title: 'Ethereum’s Proof of Stake Casper Testnet Nears Launch\n', titlecn: '以太坊重大升级将来临:权益证明系统Casper测试网络即将启动', intro: 'One of the biggest upgrade in ethereum, and perhaps in the entire ecosystem, might be closer to implementation than previously thought', introcn: '以太坊权益证明机制Casper的测试网络即将启动,本文作者预测,这将对以太坊可扩展性和用户体验上带来极大提升,其被认为是以太坊最为重大的升级之一。', url: 'news/' + 'ethereum_proof_of_stake_casper_testnet_nears_launch' + '.html', urlcn: 'news/' + 'ethereum_proof_of_stake_casper_testnet_nears_launch' + '_cn.html' }, { id: '', date: 'Nov 30, 2017', datecn: '2017.11.30', cover: 'images/news/' + 'vitalik_buterin_lays.jpeg', title: 'Vitalik Buterin Lays Roadmap for Ethereum Visa Levels Quadratic Sharding\n', titlecn: 'Vitalik 公布以太坊 2.0 路线图:通过二次分片来匹配Visa交易规模\n', intro: 'The ethereum killer is ethereum, the ethereum of China is ethereum, the ethereum of Taiwan is ethereum… 2.0.', introcn: '能消灭以太坊的将是以太坊本身,以太坊在中国大陆仍旧是以太坊,但在台湾,以太坊2.0将从这里开始诞生。', url: 'news/' + 'vitalik_buterin_lays_roadmap_for_ethereum_visa_levels_quadratic_sharding' + '.html', urlcn: 'news/' + 'vitalik_buterin_lays_roadmap_for_ethereum_visa_levels_quadratic_sharding' + '_cn.html' }, { id: '', date: 'Nov 30, 2017', datecn: '2017.11.30', cover: 'images/news/' + 'from_evolution_theory.png', title: 'From the Perspective of Evolutionism, Is Blockchain Fork a Matter of Technology or Consensus?', titlecn: '进化论的角度看区块链分叉问题,是技术还是共识?\n', intro: 'Evolution showcased changes from unicellular organisms to multicellular organisms, and from neurons to neural networks. In this process, the ability of organisms to adapt to the environment was also growing. So what will it be like when looking at the blockchain fork from the perspective of evolutioism?', introcn: '生物进化的方向是从单细胞到多细胞、从神经元到神经网络,在此过程中其适应环境的能力也在不断增强。那么如果从进化论的角度看区块链的分叉问题又是如何呢?', url: 'news/' + 'from_evolution_theory_is_blockchain_fork_a_matter_of_technology_or_consensus' + '.html', urlcn: 'news/' + 'from_evolution_theory_is_blockchain_fork_a_matter_of_technology_or_consensus' + '_cn.html' }, { id: '', date: 'Nov 29, 2017', datecn: '2017.11.29', cover: 'images/news/' + 'paxful_we_plan_to.jpg', title: 'Paxful: We Plan to Build 100 Schools in Africa with Bitcoin', titlecn: 'Paxful:我们要用比特币在非洲建100所学校', intro: 'Bitcoin can be used beyond investment. Recently, Paxful, a big bitcoin market, said that they would use bitcoin to build schools in Africa to help people get rid of poverty and backwardness.', introcn: '不止于投资,比特币能做的还有慈善:目前,大型比特币市场Paxful宣布将使用比特币在非洲创办学校,帮助当地人早日摆脱贫困落后的局面。', url: 'news/' + 'paxful_we_plan_to_build_100_schools_in_africa_with_bitcoin' + '.html', urlcn: 'news/' + 'paxful_we_plan_to_build_100_schools_in_africa_with_bitcoin' + '_cn.html' }, { id: '', date: 'Nov 29, 2017', datecn: '2017.11.29', cover: 'images/news/' + 'central_bank_of_russia.jpg', title: 'Central Bank of Russia Says Cryptocurrencies Market May Be Facing A “Bubble”', titlecn: '俄罗斯央行称加密货币市场可能面临“泡沫”', intro: 'According to the regulator’s Financial Stability Report, Russia will also develop a regulatory framework to protect consumers and prevent illegal activities funded by cryptocurrencies', introcn: '根据监管机构的金融稳定分析报告, 俄罗斯还将制定出一个监管框架以保护消费者, 并且防止发生加密货币资助的非法活动。', url: 'news/' + 'central_bank_of_russia_says_cryptocurrencies_market_may_be_facing_a_bubble' + '.html', urlcn: 'news/' + 'central_bank_of_russia_says_cryptocurrencies_market_may_be_facing_a_bubble' + '_cn.html' }, { id: '', date: 'Nov 29, 2017', datecn: '2017.11.29', cover: 'images/news/' + 'cambridge_professor.jpg', title: 'Cambridge Professor: Bitcoin is an Economic Miracle', titlecn: '剑桥教授:比特币是经济奇迹', intro: 'If you\'re only paying a $2 transaction fee on a piece of art that\'s worth tens of thousands, the fee is basically zero. But if you\'re paying two or three percent on a piece of art of that value, then the numbers can go up quite a bit.', introcn: '如果你需要为一件价值好几万的艺术品支付2美元手续费,这个费用少的可以忽略不计。然而,如果让你为同样的艺术品支付2%或3%的手续费,那这个费用就大得多了。', url: 'news/' + 'cambridge_professor_bitcoin_is_an_economic_miracle' + '.html', urlcn: 'news/' + 'cambridge_professor_bitcoin_is_an_economic_miracle' + '_cn.html' }, { id: '', date: 'Nov 28, 2017', datecn: '2017.11.28', cover: 'images/news/' + 'samsung_sds_cooperates.jpg', title: 'Samsung SDS Cooperates with Seoul Government for Blockchain Platform', titlecn: '三星SDS与首尔政府合作,共同打造区块链平台', intro: 'Samsung SDS has signed a deal with the Seoul Metropolitan Government to jointly develop its "information strategy" plan. It has been nearly seven months since Samsung unveiled Nexledger – an enterprise-grade blockchain platform hosted in the cloud', introcn: '三星SDS已经与首尔市政府签署了一项合作协议,共同制定一个“信息战略”计划。这一合作距其推出基于云端的企业级区块链平台Nexledger已过去近七个月。', url: 'news/' + 'samsung_sds_cooperates_with_seoul_government_for_blockchain_platform' + '.html', urlcn: 'news/' + 'samsung_sds_cooperates_with_seoul_government_for_blockchain_platform' + '_cn.html' }, { id: '', date: 'Nov 28, 2017', datecn: '2017.11.28', cover: 'images/news/' + 'iran_welcomes_bitcoin.jpg', title: 'Iran Welcomes Bitcoin and Virtual Currencies in the Country, Says They Must Follow Regulations', titlecn: '伊朗欢迎比特币和虚拟货币,但称其必须遵守法规', intro: 'The High Council of Cyberspace (HCC) in Iran is also studying cryptocurrencies in conjunction with the Central Bank of Iran (CBI)', introcn: '伊朗网络空间高级理事会正与伊朗中央银行协力研究加密货币', url: 'news/' + 'iran_welcomes_bitcoin_and_virtual_currencies_in_the_country' + '.html', urlcn: 'news/' + 'iran_welcomes_bitcoin_and_virtual_currencies_in_the_country' + '_cn.html' }, { id: '', date: 'Nov 28, 2017', datecn: '2017.11.28', cover: 'images/news/' + 'bitcoin_prices_at_several.jpg', title: 'Bitcoin Exceeds $ 10,000 at Bithum and Keeps up All the Way', titlecn: '韩国Bithumb领先,全球多个交易平台比特币价格今日相继突破1万美元大关', intro: 'This means that some of the biggest Bitcoin bulls have already been proven right with their long term price predictions. As 2017 coming to an end, a widespread price of $10,000 + is looking a lot more like a case of “when” rather than “if” now', introcn: '这个消息意味着那些看涨比特币的人作出的长期价格预测是正确的。伴随着2017年的结束,比特币突破1万美元+的价格不再是神话,而是时间问题。', url: 'news/' + 'bitcoin_prices_at_several_global_trading_platforms_exceed_the_10000_mark' + '.html', urlcn: 'news/' + 'bitcoin_prices_at_several_global_trading_platforms_exceed_the_10000_mark' + '_cn.html' }, { id: '', date: 'Nov 27, 2017', datecn: '2017.11.27', cover: 'images/news/' + 'shinhan_bank_looking.jpg', title: 'Shinhan Bank Looking to Launch a Secure Cryptocurrency Wallet for Its Customers', titlecn: '韩国新韩银行希望为客户推出安全的加密货币钱包', intro: 'Wallet will help users keep cryptocurrency holdings secure, even if blockchain key is compromised', introcn: '即使区块链密钥泄露,该钱包也能帮助用户保护加密货币的安全', url: 'news/' + 'shinhan_bank_looking_to_launch_a_secure_cryptocurrency_wallet_for_its_customers' + '.html', urlcn: 'news/' + 'shinhan_bank_looking_to_launch_a_secure_cryptocurrency_wallet_for_its_customers' + '_cn.html' }, { id: '', date: 'Nov 27, 2017', datecn: '2017.11.27', cover: 'images/news/' + 'putting_singapore_dollar.jpg', title: 'Putting Singapore\'s Dollar on Blockchain May Prove It\'s the Most Crypto Friendly Place on Earth', titlecn: '福布斯:新加坡可能是全球加密货币友好型程度最高的国家', intro: 'Singapore is widely regarded as one of the most crypto-friendly countries in the world, largely due to its stable politics, reliable infrastructure, and favorable business environment.', introcn: '新加坡因政治稳定、基础设施可靠且商业环境良好,被广泛认为是世界上对加密货币最友好的国家之一。', url: 'news/' + 'putting_singapore_dollar__blockchain_may_prove' + '.html', urlcn: 'news/' + 'putting_singapore_dollar__blockchain_may_prove' + '_cn.html' }, { id: '', date: 'Nov 27, 2017', datecn: '2017.11.27', cover: 'images/news/' + 'parity_bugs_still_exists.jpg', title: 'Parity Bugs Still Exists with no Ideal Solutions Currently', titlecn: '以太坊Parity钱包漏洞仍在,重挫之后如何解决尚存争议', intro: 'The dark history: The Parity team has been looking for ideal solutions for the issue since the bug was disclosed on November 7.', introcn: '以太坊黑暗历史:自11月7日以太坊Parity钱包被爆出现重大安全漏洞,官方至今还未确定理想的解决方案', url: 'news/' + 'parity_bugs_still_exists_with_no_ideal_solutions_currently' + '.html', urlcn: 'news/' + 'parity_bugs_still_exists_with_no_ideal_solutions_currently' + '_cn.html' }, { id: '', date: 'Nov 26, 2017', datecn: '2017.11.26', cover: 'images/news/' + 'the_philippines_considers.jpg', title: 'The Philippines Considers Treating All Future Icos as Securities', titlecn: '菲律宾考虑将ICO视为证券', intro: 'This move will see ICOs governed under the Securities Regulation Code, which will limit financial risk for Filipinos investing in cryptocurrencies', introcn: '此举将使ICO受《证券监管法》管制,限制菲律宾人投资加密货币的财务风险', url: 'news/' + 'the_philippines_considers_treating_all_future_icos_as_securities' + '.html', urlcn: 'news/' + 'the_philippines_considers_treating_all_future_icos_as_securities' + '_cn.html' }, { id: '', date: 'Nov 25, 2017', datecn: '2017.11.25', cover: 'images/news/' + 'chairman_of_swiss.jpg', title: 'Chairman of Swiss National Bank Says Cryptocurrencies Are An Investment, Not A Currency', titlecn: '瑞士国家银行行长:加密货币是一种投资,而非货币', intro: 'Thomas Jordan also said that cryptocurrencies can ‘ potentially strongly affect the financial system ’ ', introcn: '瑞士央行行长Thomas Jordan还表示,加密货币 ‘可能会对金融体系产生巨大影响’', url: 'news/' + 'chairman_of_swiss_national_bank_says_cryptocurrencies_are_an_investment' + '.html', urlcn: 'news/' + 'chairman_of_swiss_national_bank_says_cryptocurrencies_are_an_investment' + '_cn.html' }, { id: '', date: 'Nov 24, 2017', datecn: '2017.11.24', cover: 'images/news/' + 'central_bank_of_malaysia.jpg', title: 'Central Bank of Malaysia Introduces First Regulatory Move for Cryptocurrency Exchanges', titlecn: '马来西亚央行针对加密货币交易所推出首个监管举措', intro: 'Cryptocurrency exchanges in Malaysia will need to disclose information of users by 2018', introcn: '马来西亚的加密货币交易所需要在2018年之前披露用户信息', url: 'news/' + 'central_bank_of_malaysia_introduces_first_regulatory_move' + '.html', urlcn: 'news/' + 'central_bank_of_malaysia_introduces_first_regulatory_move' + '_cn.html' }, { id: '', date: 'Nov 24, 2017', datecn: '2017.11.24', cover: 'images/news/' + 'air_new_zealand.jpg', title: 'Air New Zealand Works with Winding Tree to Explore Applications of Blockchain Technology in Aviation Sector', titlecn: '新西兰航空联手Winding Tree,探索区块链在航空领域的应用潜力', intro: 'Aviation industry is a data-intensive industry with complex procedures, which can gain a lot from blockchain technology.', introcn: '航空业是一个程序复杂、数据密集型的行业,可以从区块链技术中获益良多。', url: 'news/' + 'air_new_zealand_winding_tree_team_up_for_blockchain_exploration' + '.html', urlcn: 'news/' + 'air_new_zealand_winding_tree_team_up_for_blockchain_exploration' + '_cn.html' }, { id: '', date: 'Nov 24, 2017', datecn: '2017.11.24', cover: 'images/news/' + 'ethereum_transaction_volume.jpg', title: 'Ethereum’s Transaction Volume Doubles That of Bitcoin; Also Reaching Record High Prices Above $420', titlecn: '以太坊交易量超越比特币两倍,创420美元历史新高 ', intro: 'Founder of Ethereum Vitalik Buterin has previously expressed that Ethereum will match the scale and capacity of Visa in ‘a couple of years’ ', introcn: '以太坊创始人Vitalik Buterin曾表示,以太坊将在‘未来几年内’达到与Visa相当的规模和容量', url: 'news/' + 'ethereum_transaction_volume_doubles_that_of_bitcoin' + '.html', urlcn: 'news/' + 'ethereum_transaction_volume_doubles_that_of_bitcoin' + '_cn.html' }, { id: '', date: 'Nov 23, 2017', datecn: '2017.11.23', cover: 'images/news/' + 'australia_awards.jpg', title: 'Australia Awards US$6 Million in Grants to Blockchain-powered Energy Pilot Project', titlecn: '澳大利亚向区块链能源试点项目提供600万美元奖励', intro: 'Power Ledger, who previously raised the token POWR, will develop the underlying blockchain technology enabling peer-to-peer energy and water transactions', introcn: '之前筹集代币POWR的区块链公司Power Ledger 将开发底层区块链技术,以实现点对点的水和能源交易', url: 'news/' + 'australia_awards_us_6_million_in_grants' + '.html', urlcn: 'news/' + 'australia_awards_us_6_million_in_grants' + '_cn.html' }, { id: '', date: 'Nov 23, 2017', datecn: '2017.11.23', cover: 'images/news/' + 'cboe_announces_bitcoin.jpg', title: 'CBOE Announces Bitcoin Futures Specs, Can the “Runaway Horse” Be Reined?', titlecn: 'CBOE公布比特币期货规格,“脱缰野马”能否被拴?', intro: 'Times are not what they used to be: There were people who used 10000 bitcoins in exchange for two pizzas, while now, the price of a bitcoin has surpassed 8000 US dollars. The people would probably feel quite regretful. CBOE, the largest options exchange in the US, has recently announced its futures specs. Can the ‘runaway horse’, Bitcoin , be reined?', introcn: '三十年河东,三十年河西:曾有人用10000枚比特币换了两块披萨,而如今,一枚比特币的价格就高逾8000美元,不知换披萨的人作何感想,恐怕相当追悔莫及。美国最大的期权交易所CBOE近期公布其期货规格,比特币这匹“脱缰野马”究竟能否被拴?', url: 'news/' + 'cboe_announces_bitcoin_futures_specs' + '.html', urlcn: 'news/' + 'cboe_announces_bitcoin_futures_specs' + '_cn.html' }, { id: '', date: 'Nov 23, 2017', datecn: '2017.11.23', cover: 'images/news/' + 'zhonggaohui.jpg', title: '', titlecn: '中高会区块链产业联盟优秀活动评选专家起评暨区块链成果评价体系工作座谈会在北京召开', intro: '', introcn: '为进一步推动区块链技术在国内的研究、应用及发展,深入推进区块链技术产业化进程,中高会区块链产业联盟优秀活动评选专家起评暨区块链成果评价体系工作座谈会在北京正式召开。', url: 'news/' + 'zhonggaohui' + '.html', urlcn: 'news/' + 'zhonggaohui' + '_cn.html' }, { id: '', date: 'Nov 23, 2017', datecn: '2017.11.23', cover: 'images/news/' + 'lightening_network_expands.jpg', title: 'Lightening Network Expands the Scale of Bitcoin Transactions, Are Large Transactions a Barrier?', titlecn: '闪电网络可扩大比特币交易规模,大额交易或成障碍?', intro: 'Many developers believe that the Lightning Network is the best way to increase the number of transactions handled by bitcoin network. While can the Lightning Network live up to its ambition? The answer remains controversial.', introcn: '许多开发人员都相信闪电网络是增加比特币网络处理交易数量的最佳方式。那么闪电网络究竟能否达到其雄心壮志呢?答案尚存争议。', url: 'news/' + 'lightening_network_expands_the_scale_of_bitcoin_transactions' + '.html', urlcn: 'news/' + 'lightening_network_expands_the_scale_of_bitcoin_transactions' + '_cn.html' }, { id: '', date: 'Nov 22, 2017', datecn: '2017.11.22', cover: 'images/news/' + 'wall_street_now.jpg', title: 'Wall Street: "Now We Know Blockchain is Useful!"', titlecn: '华尔街:“现在我们知道区块链有用了!”', intro: 'Blockchain can dramatically reduce back-end operation costs and speed up the pace of transaction settlement. Banks must have funds in reserve while waiting for deals to close, so billions of dollars can be released and used elsewhere once the transaction time lasted for days or weeks is reduced to minutes. ', introcn: '区块链可以大幅度减少后端操作成本,加速交易结算时间。银行在等待交易结算时必须储备资金,所以一旦几天甚至几周的交易时间缩短到几分钟,就可以释放几十亿美元的资金用于其他地方。', url: 'news/' + 'wall_street_now_we_blockchain_is_useful' + '.html', urlcn: 'news/' + 'wall_street_now_we_blockchain_is_useful' + '_cn.html' }, { id: '', date: 'Nov 22, 2017', datecn: '2017.11.22', cover: 'images/news/' + 'experts_caution_investors.jpg', title: 'Experts Caution Investors Against Cash Grab ICOs, Buterin Speaks Out', titlecn: 'Vitalik:ICO是否适合,唯一评判标准在于代币在系统中的必要性', intro: 'This week several prominent venture capital investors, experts and developers including Jason Calacanis and Ethereum co-founder Vitalik Buterin spoke out against initial coin offering (ICO) pump and dump schemes.', introcn: '本周,以太坊联合创始人之一Vitalik Buterin针对目前的ICO热再度发声,明确表示反对ICO项目中恶意炒作和虚假宣传导致的哄抬价格的行为', url: 'news/' + 'experts_caution_investors_against_cash_grab_icos_buterin_speaks_out' + '.html', urlcn: 'news/' + 'experts_caution_investors_against_cash_grab_icos_buterin_speaks_out' + '_cn.html' }, { id: '', date: 'Nov 22, 2017', datecn: '2017.11.22', cover: 'images/news/' + 'russian_minister_of.jpg', title: 'Russian Minister of Communications and Mass Media Believes that Russia is Unlikely to Legalize Bitcoin', titlecn: '俄罗斯通信和传媒部长:国家不会考虑比特币合法化', intro: 'it is reported that a senior official at Russia\'s central bank said initial coin offerings (ICOs) could drive funding opportunities for startups. And, a week prior, the head of Russia’s Federal Agency for Tourism predicted that blockchain could transform the country\'s tourism industry', introcn: '据悉就在一周前,俄罗斯央行一位高级官员表示,首次代币发行(ICO)可能会为创业公司带来融资机会。而且,一周前,俄罗斯联邦旅游局负责人也预测说区块链可以改变该国的旅游业', url: 'news/' + 'russian_minister_of_communications_and_mass_media' + '.html', urlcn: 'news/' + 'russian_minister_of_communications_and_mass_media' + '_cn.html' }, { id: '', date: 'Nov 22, 2017', datecn: '2017.11.22', cover: 'images/news/' + 'european_central_bank.jpg', title: 'European Central Bank Mulls over Decision to Regulate Cryptocurrency', titlecn: '欧洲央行正在考虑规范加密货币', intro: 'ECB’s Ewald Nowonty also compares cryptocurrencies to shares investments, cautioning users of volatility in prices', introcn: '欧洲央行的Ewald Nowonty将加密货币与股票投资进行比较,提醒用户小心价格波动风险', url: 'news/' + 'european_central_bank_mulls_over_decision_to_regulate_cryptocurrency' + '.html', urlcn: 'news/' + 'european_central_bank_mulls_over_decision_to_regulate_cryptocurrency' + '_cn.html' }, { id: '', date: 'Nov 21, 2017', datecn: '2017.11.21', cover: 'images/news/' + 'co_founder_of.jpg', title: 'Co-founder of Ethereum and CEO of Ripple Agree that Many ICOs are Actually Frauds', titlecn: '以太坊联合创始人和瑞波首席执行官认同许多ICO实际上是欺诈行为', intro: 'Both executives also said they believe future regulations in the cryptocurrency space can spur innovation by providing more safety and transparency for startups and investors', introcn: '两位高管还表示,他们相信未来对加密货币领域的监管可以为初创公司和投资者提供更多的安全性和透明度,进而刺激创新', url: 'news/' + 'co_founder_of_ethereum_and_ceo_of_ripple_agree' + '.html', urlcn: 'news/' + 'co_founder_of_ethereum_and_ceo_of_ripple_agree' + '_cn.html' }, { id: '', date: 'Nov 21, 2017', datecn: '2017.11.21', cover: 'images/news/' + 'south_korea_hyosung_s.jpg', title: 'South Korea’s Hyosung Group Announces the Integration of Bitcoin into Its ATM Model', titlecn: '亚洲最大ATM制造商宣布整合比特币交易功能', intro: 'Long-awaited news: South Korea’s Hyosung Group, one of the Asia‘s largest ATM producers, announced the integration of bitcoin into its international ATM models for retailers. In the long run, the integration of bitcoin into hundreds of thousands of bank ATMs worldwide will further increase the mainstream adoption of bitcoin.', introcn: '千呼万唤始出来:亚洲最大ATM制造商之一韩国晓星集团宣布将比特币整合到其零售商国际ATM模型中。从长远来看,将比特币整合到全球数十万台银行ATM中将进一步增加比特币的主流应用。', url: 'news/' + 'south_korea_hyosung_group_announces_the_integration_of_bitcoin_into_its_atm_model' + '.html', urlcn: 'news/' + 'south_korea_hyosung_group_announces_the_integration_of_bitcoin_into_its_atm_model' + '_cn.html' }, { id: '', date: 'Nov 21, 2017', datecn: '2017.11.21', cover: 'images/news/' + 'huawei_executives_blockchain.jpg', title: 'Huawei Executives: Blockchain Can Help Create Smart City', titlecn: '华为高管: 区块链可助力实现智慧城市', intro: 'Blockchain technology has been widely used in financial sector, but what is its value outside the sector? The decentralization of the blockchain has made it effective in avoiding the involvement of the third parties and helps reduce risks. The building of smart cities in the future will also depend on the application of blockchain technology.', introcn: '区块链技术在金融领域已得到广泛应用,但它在金融领域之外的价值是什么呢?区块链的去中心化特性使其可以有效规避第三方的介入,从而降低风险。未来智慧城市的建立,也有赖于区块链技术的应用。', url: 'news/' + 'huawei_executives_blockchain_can_help_create_smart_city' + '.html', urlcn: 'news/' + 'huawei_executives_blockchain_can_help_create_smart_city' + '_cn.html' }, { id: '', date: 'Nov 20, 2017', datecn: '2017.11.20', cover: 'images/news/' + 'sbi_to_use.jpg', title: 'SBI to Use Blockchain for Smart Contracts and KYC by Next Month', titlecn: '印度国家银行将于下月推出区块链智能合约和KYC', intro: 'India’s largest lender State Bank of India will launch beta version of blockchain-enabled smart contracts and Blockchain-enabled Know Your Customer by next month. The project was supported by Pune-based startup Primechain Technologies.', introcn: '下个月,印度最大信贷机构——印度国家银行将发布基于区块链的智能合约beta版本及KYC应用程序。该项目获得当地区块链初创企业Primechain Technologies的支持。', url: 'news/' + 'sbi_to_use_blockchain_for_smart_contracts_and_kyc_by_next_month' + '.html', urlcn: 'news/' + 'sbi_to_use_blockchain_for_smart_contracts_and_kyc_by_next_month' + '_cn.html' }, { id: '', date: 'Nov 20, 2017', datecn: '2017.11.20', cover: 'images/news/' + 'hong_kong_based_gatecoin.jpg', title: 'Hong Kong-based Gatecoin and Bitspark Speaks Out Against Bank-imposed Limitations', titlecn: '香港Gatecoin和 Bitspark 公司反对银行施加的限制', intro: 'Gatecoin faced with suspension and daily transaction limits from local banks, while Bitspark was denied setting up of bank accounts', introcn: 'Gatecoin被当地银行暂停业务并限制了每日的交易额;Bitspark 则被拒绝开设银行账户。', url: 'news/' + 'hong_kong_based_gatecoin_and_bitspark_speaks_out_against_bank_imposed_limitations' + '.html', urlcn: 'news/' + 'hong_kong_based_gatecoin_and_bitspark_speaks_out_against_bank_imposed_limitations' + '_cn.html' }, { id: '', date: 'Nov 20, 2017', datecn: '2017.11.20', cover: 'images/news/' + 'developers_begin_turning.jpg', title: 'Developers Begin Turning to Hard Forks for Fundraising Rather Than ICOs', titlecn: '融资新方式:从ICO到IFO', intro: 'Companies who wanted to raise money for developing their projects in the cryptoworld traditionally did so through Initial Coin Offerings. Now another trend has emerged for those wanting to do so - the hard fork', introcn: '在密码学世界中,公司为了开发项目通常是通过ICO来募集资金。现在出现了一种新的融资趋势-硬分叉融资(IFO)', url: 'news/' + 'developers_begin_turning_to_hard_forks_for_fundraising_rather_than_icos' + '.html', urlcn: 'news/' + 'developers_begin_turning_to_hard_forks_for_fundraising_rather_than_icos' + '_cn.html' }, { id: '', date: 'Nov 19, 2017', datecn: '2017.11.19', cover: 'images/news/' + 'twenty_banks_join_s.jpg', title: 'Twenty Banks Join Hong Kong-Singapore Blockchain Partnership', titlecn: '又添新成员!20家银行加入香港新加坡区块链联盟', intro: 'The message is that when you work with one of us, you work with both of us.', introcn: '我们传递的信息是,如果你和我们其中一个国家合作,你就是在和两个国家一起合作。', url: 'news/' + 'twenty_banks_join_hong_kong_singapore_blockchain_partnership' + '.html', urlcn: 'news/' + 'twenty_banks_join_hong_kong_singapore_blockchain_partnership' + '_cn.html' }, { id: '', date: 'Nov 19, 2017', datecn: '2017.11.19', cover: 'images/news/' + 'ubs_remarks.jpg', title: 'UBS Remarks that Bitcoin Is Unstable Due to the Lack of Government Oversight', titlecn: '瑞银表示比特币因缺乏政府监管而不稳定', intro: 'Mark Haefele, CIO of UBS also added that cryptocurrencies are unstable due to relatively few users, as compared to traditional currencies', introcn: '瑞银全球首席投资官Mark Haefele也表示,与传统货币相比,加密货币因其用户相对较少而不稳定。', url: 'news/' + 'ubs_remarks_that_bitcoin_is_unstable_due_to_the_lack_of_government_oversight' + '.html', urlcn: 'news/' + 'ubs_remarks_that_bitcoin_is_unstable_due_to_the_lack_of_government_oversight' + '_cn.html' }, { id: '', date: 'Nov 18, 2017', datecn: '2017.11.18', cover: 'images/news/' + 'vontobel_and_Leonteq.jpg', title: 'Vontobel and Leonteq Securities AG Launch Their Respective Futures Products to Allow Hedging of Bitcoin', titlecn: 'Vontobel和Leonteq Securities AG推出各自版本的期货产品,允许对冲比特币', intro: 'Investors can now also bet on the rise and fall of bitcoin prices under these newly launched futures products', introcn: '投资者现在也可以下注这些新推出期货产品下比特币价格的涨跌', url: 'news/' + 'vontobel_and_leonteq_securities_ag_launch_their_respective_futures_products' + '.html', urlcn: 'news/' + 'vontobel_and_leonteq_securities_ag_launch_their_respective_futures_products' + '_cn.html' }, { id: '', date: 'Nov 18, 2017', datecn: '2017.11.18', cover: 'images/news/' + 'square_Has_Quietly.jpg', title: 'Square Has Quietly Allowed Some Customers to Buy and Sell Bitcoin on Their Payments App Cash', titlecn: 'Square已悄然允许一些用户在其支付应用程序Cash上买卖比特币', intro: 'This support for bitcoin represents the first time Square is implementing cryptocurrency in their offerings', introcn: '此次对比特币的支持是Square首次在其产品中实现加密货币功能', url: 'news/' + 'square_has_quietly_allowed_some_customers_to_buy_and_sell_bitcoin' + '.html', urlcn: 'news/' + 'square_has_quietly_allowed_some_customers_to_buy_and_sell_bitcoin' + '_cn.html' }, { id: '', date: 'Nov 17, 2017', datecn: '2017.11.17', cover: 'images/news/' + 'amex_and_santander.jpg', title: 'Amex and Santander partners Ripple to transfer funds on blockchain platform', titlecn: '美国运通和和桑坦德与Ripple合作利用区块链平台转账', intro: 'American Express business customers can now transfer funds between the UK and US in a matter of seconds', introcn: '美国运通的商业客户能够在几秒内完成英国和美国间的资金转移', url: 'news/' + 'amex_and_santander_partners_ripple_to_transfer_funds_on_blockchain_platform' + '.html', urlcn: 'news/' + 'amex_and_santander_partners_ripple_to_transfer_funds_on_blockchain_platform' + '_cn.html' }, { id: '', date: 'Nov 17, 2017', datecn: '2017.11.17', cover: 'images/news/' + 'bch_btc.jpg', title: 'BCH=BTC?While Ethereum Founder Vitalik Buterin Doesn\'t Think So!', titlecn: 'BCH=BTC?以太坊创始人Vitalik Buterin并不这么认为', intro: 'Between BTC and BCH, a seemingly white war is at a trigger. Both blockchains are seeking for establishing dominance. For a long time to come, BCH will remain controversial. And what might happen in the future, let’s go and see. ', introcn: 'BTC与BCH之间,一场看似没有硝烟的战争一触即发,两条链都在争取主导地位。在未来很长一段时间,BCH仍将具有争议性,后事的发展如何,需待我们且行且观察。', url: 'news/' + 'bch_btc_while_ethereum_founder_vitalik_buterin' + '.html', urlcn: 'news/' + 'bch_btc_while_ethereum_founder_vitalik_buterin' + '_cn.html' }, { id: '', date: 'Nov 17, 2017', datecn: '2017.11.17', cover: 'images/news/' + 'confidential_transactions.jpg', title: 'Confidential Transactions Could Add Anonymity to Bitcoin and Litecoin', titlecn: '利好!机密交易可增加比特币和莱特币的匿名性', intro: 'With bitcoin being courted by the investment banking industry and attracting increasing attention from CEOs and heads of state, untraceable transactions probably aren’t going to win a show of hands. There are legitimate and justifiable reasons why it is desirable to be able to transact anonymously on the web.', introcn: '随着比特币受到投资银行业的追捧,并引起CEO和国家元首越来越多的关注,无法追踪的加密货币交易可能不会赢得太多关注。然而对于匿名虚拟货币交易,我们有合理和正当的理由认为它是可取的。', url: 'news/' + 'confidential_transactions_could_add_anonymityto_bitcoin_and_litecoin' + '.html', urlcn: 'news/' + 'confidential_transactions_could_add_anonymityto_bitcoin_and_litecoin' + '_cn.html' }, { id: '', date: 'Nov 17, 2017', datecn: '2017.11.17', cover: 'images/news/' + 'singapore_central.jpg', title: 'Singapore\'s Central Bank Outlines When ICOs Are and Aren\'t Securities', titlecn: 'ICO代币是否属于证券?新加坡央行划定范围', intro: 'Singapore\'s de facto central bank has published new guidelines on initial coin offerings (ICOs), outlining how token sales would be viewed under its securities laws.', introcn: '新加坡央行(MAS)发布了新的ICO指导意见,概述了证券法如何界定代币销售。', url: 'news/' + 'singapore_central_bank_outlines' + '.html', urlcn: 'news/' + 'singapore_central_bank_outlines' + '_cn.html' }, { id: '', date: 'Nov 16, 2017', datecn: '2017.11.16', cover: 'images/news/' + 'singapore_fintech_festival.jpg', title: 'Singapore Fintech Festival 2017 (Day 3): Singapore to Open Up Regulatory Sandbox for ICOs 2017', titlecn: '新加坡金融科技节(第三天):新加坡将为2017年的ICO开放监管沙盒', intro: 'According to the MAS, ICOs will only qualify for a regulatory sandbox if they offer innovative use cases for improving the efficiency of capital markets.', introcn: '“据MAS称,ICO只有通过提供创新型用例来提高资本市场的效率,才有资格进入监管沙盒。”', url: 'news/' + 'singapore_fintech_festival_2017_day_3' + '.html', urlcn: 'news/' + 'singapore_fintech_festival_2017_day_3' + '_cn.html' }, { id: '', date: 'Nov 16, 2017', datecn: '2017.11.16', cover: 'images/news/' + 'bitcoin_Price_Soars.jpg', title: 'Bitcoin Price Soars to $13,000 in Zimbabwe Because of Military Coup', titlecn: '津巴布韦爆发军事政变,当地比特币涨至13000美元', intro: 'Bitcoin climbed as much as 10 percent because of the military coup. The price of the cryptocurrency jumped to $13,499, almost double the rate at which it trades in other international exchanges.', introcn: '受津巴布韦政局波动的影响,当地比特币盘中大涨10%,触及13499美元,几乎是国际价格的两倍。', url: 'news/' + 'bitcoin_price_soars_to_13,000_in_zimbabwe' + '.html', urlcn: 'news/' + 'bitcoin_price_soars_to_13,000_in_zimbabwe' + '_cn.html' }, { id: '', date: 'Nov 16, 2017', datecn: '2017.11.16', cover: 'images/news/' + 'will_bitcoin_mining.jpg', title: 'Will Bitcoin Mining Face Punishment? Electric Company Said the Statement Was Misworded', titlecn: '比特币挖矿将受处罚?电力公司回应称文件表述有误', intro: 'An electricity company from Sichuan Province has just informed miners to stop bitcoin mining immediately, otherwise they would face punishment for illegal operations. This electricity company, however, said the statement was misworded in a later reply.', introcn: '四川省一电力公司称比特币挖矿属于非法运营,要求各并网电站立刻停止比特币生产,否则将予以解网处罚。而后该电力公司回应称通知表述有误', url: 'news/' + 'will_bitcoin_mining_face_punishment' + '.html', urlcn: 'news/' + 'will_bitcoin_mining_face_punishment' + '_cn.html' }, { id: '', date: 'Nov 15, 2017', datecn: '2017.11.15', cover: 'images/news/' + 'mastercard_Files_Blockchain.jpg', title: 'Mastercard Files Blockchain-based Patent to Improve Efficiency of Payment and Settlement', titlecn: '万事达申请区块链技术专利以提高支付结算效率', intro: 'Blockchain has immeasurable potential in the future, especially in the commercial sector, may even subvert the underlying system of the payment and settlement in the current banking industry.', introcn: '区块链未来具有不可估量的潜力,尤其在商业领域,甚至可能会颠覆当前银行业支付结算的底层系统。', url: 'news/' + 'mastercard_files_blockchain_based_patent_to_improve_efficiency_of_payment_and_settlement' + '.html', urlcn: 'news/' + 'mastercard_files_blockchain_based_patent_to_improve_efficiency_of_payment_and_settlement' + '_cn.html' }, { id: '', date: 'Nov 15, 2017', datecn: '2017.11.15', cover: 'images/news/' + 'singapore_Fintech.jpg', title: 'Singapore Fintech Festival 2017: Singapore, Hong Kong and Canada Will Use Blockchain for Trade Finance; MAS and ABS Publicly Release Source Codes', titlecn: '2017新加坡金融科技节:新加坡、香港和加拿大将使用区块链进行贸易融资;MAS和ABS公开发布源代码', intro: 'MAS will work with Hong Kong’s Monetary Authority and Bank of Canada to develop blockchain payments; MAS and ABS releases source codes of prototypes under Project Ubin', introcn: '新加坡金融管理局(MAS)将与香港金融管理局和加拿大银行合作开发区块链支付系统;MAS和新加坡银行协会(ABS)发布了Ubin项目下软件原型的源代码。', url: 'news/' + 'singapore_fintech_festival_2017' + '.html', urlcn: 'news/' + 'singapore_fintech_festival_2017' + '_cn.html' }, { id: '', date: 'Nov 15, 2017', datecn: '2017.11.15', cover: 'images/news/' + 'li_Xiaolai_Team.jpg', title: 'Li Xiaolai Team Will Fork BTC to Produce SBTC, Block Capacity Will Be Expanded to 8MB', titlecn: '李笑来团队将分叉出超级比特币,支持智能合约,区块扩大至8M', intro: 'In general, Super Bitcoin (STBC) added many new qualities, and the block capacity will be extended to 8MB.', introcn: '总的来看,超级比特币SBTC融入了诸多新特性,区块容量将扩大至8MB', url: 'news/' + 'li_xiaolai_team_will_fork_btc_to_produce_sbtc' + '.html', urlcn: 'news/' + 'li_xiaolai_team_will_fork_btc_to_produce_sbtc' + '_cn.html' }, { id: '', date: 'Nov 14, 2017', datecn: '2017.11.14', cover: 'images/news/' + 'un_launches_Blockchain.jpg', title: 'UN Launches Blockchain-powered Identity Project to Fight Against Child Trafficking', titlecn: '联合国开启区块链身份认证项目以打击贩卖儿童行为', intro: 'Blockchain-powered Identity is not only to secure people’s data and information, but to protect the children who do not possess birth certificates. The project will be incredible value to the issue.', introcn: '基于区块链进行身份认证,意义不仅仅在于保护人们的数据信息,更大的用途是保护那些没有身份证明的儿童,开展这一项目带来的价值将是颠覆性的。', url: 'news/' + 'un_launches_blockchain_powered_identity_project_to_crack_down_on_child_trafficking' + '.html', urlcn: 'news/' + 'un_launches_blockchain_powered_identity_project_to_crack_down_on_child_trafficking' + '_cn.html' }, { id: '', date: 'Nov 14, 2017', datecn: '2017.11.14', cover: 'images/news/' + 'a_tale_of_two.jpg', title: 'A Tale of Two Bitcoins: Where Bitcoin, Bitcoin Cash Are Headed', titlecn: '比特币之殇:BTC和BCH将何去何从?', intro: 'The currency which had been drifting steadily downward was lifted as high as $2,600 in a dramatic pump following the news of SegWit2x’s cancellation. While the price has since experienced a 50% retrace, spectators were stunned at the sudden rise.', introcn: '目前来看,BCH是一匹黑马。SegWit2X失败后,BCH这个之前稳定下行的币种突然暴涨至2600美元,尽管之后币价再次回调,人们还是震惊于这次突然上涨。', url: 'news/' + 'a_tale_of_two_bitcoins_where_bitcoin_bitcoin_cash_are_headed' + '.html', urlcn: 'news/' + 'a_tale_of_two_bitcoins_where_bitcoin_bitcoin_cash_are_headed' + '_cn.html' }, { id: '', date: 'Nov 14, 2017', datecn: '2017.11.14', cover: 'images/news/' + 'hong_kong_contemplates_use.jpg', title: 'Hong Kong Contemplates Use of Blockchain for Cross-country Trade Finance', titlecn: '香港考虑利用区块链进行跨国贸易融资', intro: 'Hong Kong is the latest in a string of government bodies in Asia seeking to leverage the capabilities of blockchain', introcn: '香港是亚洲诸多政府机构中最新利用区块链技术的成员', url: 'news/' + 'hong_kong_contemplates_use_of_blockchain_for_cross_country_trade_finance' + '.html', urlcn: 'news/' + 'hong_kong_contemplates_use_of_blockchain_for_cross_country_trade_finance' + '_cn.html' }, { id: '', date: 'Nov 13, 2017', datecn: '2017.11.13', cover: 'images/news/' + 'hewlett_packard.jpg', title: 'Hewlett Packard Enterprise Is to Launch Blockchain-based New Product in 2018', titlecn: '惠普企业(HPE)将于2018年发布区块链新产品', intro: 'Enterprises interested in blockchain are now realizing that public cloud alone does not always meet their non-functional requirements', introcn: '对区块链感兴趣的企业意识到,单凭公有云本身并不总能满足企业的非功能性需求', url: 'news/' + 'hewlett_packard_enterprise_is_to_launch_blockchain_based' + '.html', urlcn: 'news/' + 'hewlett_packard_enterprise_is_to_launch_blockchain_based' + '_cn.html' }, { id: '', date: 'Nov 12, 2017', datecn: '2017.11.12', cover: 'images/news/' + 'us_treasury.jpg', title: 'US Treasury Secretary Says They Are Investigating Use of Bitcoin for Illicit Activities', titlecn: '美国财长表示正在调查比特币的非法使用活动', intro: 'Several organizations in the US are collaborating closely to watch the use of Bitcoin in the dark web, to prevent transactions related to terrorism and money laundering', introcn: '美国一些组织正密切合作,关注比特币在暗网中的使用情况,以防止发生与恐怖主义和洗钱有关的交易', url: 'news/' + 'us_treasury_secretary_says_they_are_investigating_use_of_bitcoin_for_illicit_activities' + '.html', urlcn: 'news/' + 'us_treasury_secretary_says_they_are_investigating_use_of_bitcoin_for_illicit_activities' + '_cn.html' }, { id: '', date: 'Nov 11, 2017', datecn: '2017.11.11', cover: 'images/news/' + 'unified_signal.jpg', title: 'Unified Signal And Burstiq Partners To Launch Crypto Wallet for Wireless Network Providers', titlecn: 'Unified Signal和BurstIQ携手为无线网络供应商推出加密钱包', intro: 'Built on blockchain, wallet enables customers to transact via cryptocurrency, make mobile payments and peer-to-peer fund transfers', introcn: '基于区块链构建的钱包使客户能够通过加密货币进行交易,进行移动支付和点对点资金转账', url: 'news/' + 'unified_signal_and_burstiq_partners_to_launch_crypto_wallet' + '.html', urlcn: 'news/' + 'unified_signal_and_burstiq_partners_to_launch_crypto_wallet' + '_cn.html' }, { id: '', date: 'Nov 10, 2017', datecn: '2017.11.10', cover: 'images/news/' + 'only_8_of.jpg', title: 'Only 8% of 26,000 Blockchain Projects Started in 2016 Are Still Active', titlecn: '2016年启动的2.6万个区块链项目中,只有8%仍然活跃', intro: 'Study says that successful projects tend to be developed by organizations, with a high number of committers and copiers', introcn: '研究表明,成功的项目往往由各组织开发,并拥有大量的贡献者和复制者', url: 'news/' + 'only_8%25_of_26,000_blockchain_projects_started' + '.html', urlcn: 'news/' + 'only_8%25_of_26,000_blockchain_projects_started' + '_cn.html' }, { id: '', date: 'Nov 9, 2017', datecn: '2017.11.09', cover: 'images/news/' + 'cuba_ventures.jpg', title: 'Cuba Ventures Seeks to Launch Blockchain-Enabled Revolupay® App And Cryptocurrency ₡CU Coin for Remittance And Tourism Industry', titlecn: '古巴风投力图在汇款和旅游业推出区块链Revolupay®应用及加密货币₡CU', intro: 'Mobile app will facilitate remittances in Cuba, and ₡CU Coin will be used as a centralized currency for payments in the tourism sector', introcn: '移动应用程序将促进古巴的汇款业发展,并且加密货币₡CU将用于支付旅游业中的服务费用。', url: 'news/' + 'cuba_ventures_seeks_to_launch_blockchain' + '.html', urlcn: 'news/' + 'cuba_ventures_seeks_to_launch_blockchain' + '_cn.html' }, { id: '', date: 'Nov 8, 2017', datecn: '2017.11.08', cover: 'images/news/' + 'weekly_tracker.jpg', title: 'Weekly Tracker: State Bank of India Incorporates Blockchain into KYC Processes; Russia and UK Officials Touts New Blockchain Use Cases', titlecn: '每周追踪报道:印度国家银行利用区块链技术管理KYC系统;英国和俄罗斯官员盛赞区块链新用例', intro: 'SBI says blockchain technology can counter money laundering and financing terrorism, UK officer says blockchain can verify digital evidence in court, and Russian officer say blockchain can revolutionize tourism industry', introcn: 'SBI认为区块链技术可以抵制洗钱和恐怖主义融资行为;UK官员表示区块链技术可以用于验证法庭数字证据;俄罗斯官员也表示区块链可以变革旅游业', url: 'news/' + 'weekly_tracker_state_bank_of_india_incorporates_blockchain_into_kyc_processes' + '.html', urlcn: 'news/' + 'weekly_tracker_state_bank_of_india_incorporates_blockchain_into_kyc_processes' + '_cn.html' }, { id: '', date: 'Nov 7, 2017', datecn: '2017.11.07', cover: 'images/news/' + 'ibm_proposes.jpg', title: 'IBM Proposes Blockchain Technology To Help Canada Track Marijuana Sales', titlecn: 'IBM 计划利用区块链技术助力加拿大追踪大麻销售过程', intro: 'The proposal sees blockchain technology enabling regulation of marijuana sales to manage entire supply chain', introcn: '该提议见证了区块链技术能够监管大麻的销售过程,以实现对整个供应链的管理', url: 'news/' + 'ibm_proposes_blockchain_technology_to_help_Canada_track_marijuana_sales' + '.html', urlcn: 'news/' + 'ibm_proposes_blockchain_technology_to_help_Canada_track_marijuana_sales' + '_cn.html' }, { id: '', date: 'Nov 6, 2017', datecn: '2017.11.06', cover: 'images/news/' + 'rofex_Argentina.jpg', title: 'Rofex, Argentina’s Largest Futures Market Plans to provide Custody Services for Bitcoin', titlecn: '阿根廷最大期货市场Rofex计划推出比特币产品托管服务', intro: 'Argentina’s Largest Futures Market has initially drawn up the plan to offer investors bitcoin service.', introcn: '阿根廷最大期货市场初步拟定了向投资者提供比特币服务的计划。', url: 'news/' + 'rofex_argentina_largest_futures_market_plans_to_provide_custody_services_for_bitcoin' + '.html', urlcn: 'news/' + 'rofex_argentina_largest_futures_market_plans_to_provide_custody_services_for_bitcoin' + '_cn.html' }, { id: '', date: 'Nov 5, 2017', datecn: '2017.11.05', cover: 'images/news/' + 'devcon3_seens.jpg', title: 'DEVCON 3: Ethereum Founder Proposed ‘Modest Proposal\' for Future Challenges', titlecn: 'DEVCON3圆满落下帷幕,以太坊创始人表示新挑战需要新变革', intro: 'As Ethereum entered Metropolis stages, privacy, safety and scalability are the three main challenges that we need to deal with---Vitalik', introcn: '进入新的阶段就会面临新的挑战,而且挑战会越来越多,为了以太坊的未来发展,我们必须要进行深入的变革-Vitalik Buterin', url: 'news/' + 'devcon3_sees_an_end' + '.html', urlcn: 'news/' + 'devcon3_sees_an_end' + '_cn.html' }, { id: '43', date: 'Nov 4, 2017', datecn: '2017.11.04', cover: 'images/news/japan_releases.jpg', title: 'Japan Releases A Blockchain-Powered Shared Id System', titlecn: '日本推出区块链共享ID计划,银行客户信息有望实现共享', intro: 'People don’t need to reenter personal information with the shared ID system when opening accounts at new financial institutions, which helps people save much time and energy.', introcn: '人们在新的金融机构申请银行服务时,使用共享ID将不再需要重新输入个人信息,为客户节省了大量的时间和精力', url: 'news/japan_releases_a_blockchain_powered_shared_id_system' + '.html', urlcn: 'news/japan_releases_a_blockchain_powered_shared_id_system' + '_cn.html' }, { id: '42', date: 'Nov 3, 2017', datecn: '2017.11.03', cover: 'images/news/bank_of_jiangsu.jpg', title: 'Bank of Jiangsu Launches First “Blockchain-based” Cross-bank Bills Discounted Business', titlecn: '江苏银行首单票据“区块链”跨行贴现业务落地', intro: 'Bank of Jiangsu has completed the first “blockchain-based”cross-bank bills discounted business transaction in collaboration with Wuxi Rural Commercial Bank.', introcn: '江苏银行与无锡农商行合作完成首单票据“区块链”跨行贴现业务交易。该业务由无锡农商行的企业客户发起,江苏银行签收票据。', url: 'news/bank_of_jiangsu_launches_first_blockchain_based' + '.html', urlcn: 'news/bank_of_jiangsu_launches_first_blockchain_based' + '_cn.html' }, { id: '41', date: 'Nov 2, 2017', datecn: '2017.11.02', cover: 'images/news/korea_Launches.jpg', title: 'Korea Launches World’s First Commercial Blockchain for “the Secure User Identification”', titlecn: '韩国落地全球首个“用户安全识别”商业区块链项目', intro: 'Chain ID goes beyond merely replacing Korea’s outdated banking certificates. It brings blockchain to the normal people. Blockchain will bring us a better future.', introcn: 'Chain ID不仅仅会取代韩国已经过时的银行证书识别系统,它还将区块链放进了每个韩国人的口袋里,区块链就是未来', url: 'news/korea_launches_world_first_commercial_blockchain' + '.html', urlcn: 'news/korea_launches_world_first_commercial_blockchain' + '_cn.html' }, { id: '40', date: 'Nov 1, 2017', datecn: '2017.11.01', cover: 'images/news/state_Bank_of_Vietnam_Announces.jpg', title: 'State Bank of Vietnam Announces Prohibition of Bitcoin Payment', titlecn: '越南央行宣布禁止比特币作为支付方式', intro: 'SBV believes cryptocurrencies are ‘illegal payment tools’ in the country, and the issue, supply and use of Bitcoin and other virtual currencies should be prohibited.', introcn: 'SBV 认为加密货币在该国 ‘不是合法支付手段’,应该禁止发行、供应、使用比特币和其他类似的虚拟货币作为支付手段。', url: 'news/state_bank_of_vietnam_announces_prohibition_of_bitcoin_payment.html', urlcn: 'news/state_bank_of_vietnam_announces_prohibition_of_bitcoin_payment_cn.html' }, { id: '39', date: 'Oct 31, 2017', datecn: '2017.10.31', cover: 'images/news/kyberNetwork_Announces.jpg', title: 'KyberNetwork Announces Latest Progresses and Cooperations with Multiple Platforms', titlecn: 'KyberNetwork发布项目最新进展,近期宣布与多家平台建立合作', intro: 'With a quite inspiring development momentum,KyberNetwork has made accomplishments recently not only in its project progress, but also in collaborations with multiple platforms', introcn: 'KyberNetwork近期持续发力,不仅在项目进展上取得喜人成果,近期与多家平台建立了合作关系', url: 'news/kybernetwork_announces_latest_progresses_and_cooperations_with_multiple_platforms.html', urlcn: 'news/kybernetwork_announces_latest_progresses_and_cooperations_with_multiple_platforms_cn.html' }, { id: '38', date: 'Oct 30, 2017', datecn: '2017.10.30', cover: 'images/news/omisego_releases.jpg', title: 'OmiseGo Releases Latest Progress and Roadmap', titlecn: '金融科技创业公司项目OmiseGo发布最新路线图', intro: 'Featuring an Ethereum-based network and wallet, they want to offer customers an easy and quick way to handle money without having to rely on a bank as 3rd party.', introcn: '用基于Ethereum的网络和钱包,OmiseGo希望为客户提供一个方便快捷的方式来处理资金,而无需依赖第三方银行机构。', url: 'news/omisego_releases_latest_progress_and_roadmap.html', urlcn: 'news/omisego_releases_latest_progress_and_roadmap_cn.html' }, { id: '37', date: 'Oct 29, 2017', datecn: '2017.10.29', cover: 'images/news/kyber_network.jpg', title: 'Kyber Network Announces Strategic Partnership with Enigma', titlecn: 'KyberNetwork与Enigma建立战略合作关系', intro: 'Besides serving as an exchange, Kyber Network also provides payment APIs that will allow wallet accounts to easily receive payments from any crypto tokens.', introcn: 'Kyber Network除了发挥交易所以的功能外,也可提供各种支付API,能允许钱包账户轻松接收任何代币形式的付款。', url: 'news/kyber_network_announces_strategic_partnership_with_enigma.html', urlcn: 'news/kyber_network_announces_strategic_partnership_with_enigma_cn.html' }, { id: '36', date: 'Oct 27, 2017', datecn: '2017.10.27', cover: 'images/news/red_belly.jpg', title: 'Red Belly Blockchain Boasts the Fastest Network Worldwide', titlecn: '悉尼大学红腹区块链,交易处理速度全球领先', intro: 'Red Belly Blockchain can process 660,000 transactions/sec in the latest tests, much quicker than the Visa network and 50 percent faster than first anticipated.', introcn: '红腹区块链在最新测试中每秒处理了66万笔交易,远远超越了Visa的支付处理系统,也比预期速度超出50%。', url: 'news/red_belly_blockchain_boasts_the_fastest_network_worldwide.html', urlcn: 'news/red_belly_blockchain_boasts_the_fastest_network_worldwide_cn.html' }, { id: '35', date: 'Oct 26, 2017', datecn: '2017.10.26', cover: 'images/news/nyu_Professor.jpg', title: 'NYU Professor:Bitcoin Should Be A Widely Used Currency', titlecn: '纽约大学教授:比特币应该更多的用于日常交易', intro: 'Bitcoin is a cryptocurrency, people should focus more on its value and daily applications rather than the unstable price.', introcn: '比特币是一种加密货币,更多的焦点应该被放在它的价值及可能支持的日常应用上,而并非它本身的价格', url: 'news/nyu_professor_bitcoin_should_be_a_widely_used_currency.html', urlcn: 'news/nyu_professor_bitcoin_should_be_a_widely_used_currency_cn.html' }, { id: '34', date: 'Oct 25, 2017', datecn: '2017.10.25', cover: 'images/news/diploma_on_blockchain.jpg', title: 'Diploma On Blockchain!!!', titlecn: '区块链上的数字毕业证!!!', intro: 'The Blockchain is penetrating into various currently. Isn’t it amazing to have our' + ' diploma recorded on Blockchain for permanent storage? Of course it is, and it is' + ' impossible to happen years ago.', introcn: '区块链技术正逐渐渗透到各个行业,听说MIT利用区块链应用程序为学生颁发毕业证,小伙伴们都惊呆了!', url: 'news/diploma_on_blockchain.html', urlcn: 'news/diploma_on_blockchain_cn.html' }, { id: '33', date: 'Oct 24, 2017', datecn: '2017.10.24', cover: 'images/news/australia_officially.jpg', title: 'Australia Officially Ends Bitcoin GST', titlecn: '澳大利亚正式取消比特币双重征税', intro: 'The end of Bitcoin GST will definitely be a good sign to cryptocurrency world.', introcn: '取消比特币双重征税,对虚拟货币大环境来说无疑又是一大利好消息', url: 'news/australia_officially_ends_bitcoin_gst.html', urlcn: 'news/australia_officially_ends_bitcoin_gst_cn.html' }, { id: '31', date: 'Oct 23, 2017', datecn: '2017.10.23', cover: 'images/news/kazakhstan_intends.jpg', title: 'Kazakhstan Intends to Launch National Cryptocurrency Backed by Fiat', titlecn: '哈萨克斯坦计划推出法币支撑的国家加密货币', intro: 'Blcokchain and cryptocurrency are entering the mainstream of today’s economic' + ' reality and supported by quite positive development environment', introcn: '区块链与加密货币正逐渐成为当今经济世界的主流技术,具有相当乐观的发展环境。', url: 'news/kazakhstan_intends_to_launch_national_cryptocurrency_backed_by_fiat.html', urlcn: 'news/kazakhstan_intends_to_launch_national_cryptocurrency_backed_by_fiat_cn.html' }, { id: '30', date: 'Oct 20, 2017', cover: 'images/news/switzerland_awards.jpg', title: 'Switzerland Awards First AML/KYC Licence To Bitcoin Company', titlecn: '瑞士首家比特币合规企业出炉', intro: 'Government licensing is quite important when establishing a payments business.' + ' Official approval in a leading European financial center like Switzerland is a key' + ' plus in the competitive environment.', introcn: '对于支付企业来说,政府的许可证是很重要的。在竞争环境中,能够获得瑞士等欧洲顶尖金融中心政府的认可是一个关键优势。', url: 'news/switzerland_awards_first_aml_kyc_licence_to_bitcoin_company.html', urlcn: 'news/switzerland_awards_first_aml_kyc_licence_to_bitcoin_company_cn.html' }, { id: '29', date: 'Oct 19, 2017', cover: 'images/news/new_members.jpg', title: 'New Members Join Enterprise Ethereum Alliance', titlecn: '企业以太坊联盟迎来新成员EEA并非以营利为目的,其目标是为以太坊创建一系列关于最佳实践、安全性、隐私权、扩容性和互操作性的标准。', intro: 'EEA is a nonprofit alliance with the objective of creating a series of standards for' + ' Ethereum in terms of security, privacy, scalability and interoperability.', introcn: 'EEA并非以营利为目的,其目标是为以太坊创建一系列关于最佳实践、安全性、隐私权、扩容性和互操作性的标准。', url: 'news/new_members_join_enterprise_ethereum_alliance.html', urlcn: 'news/new_members_join_enterprise_ethereum_alliance_cn.html' }, { id: '28', date: 'Oct 18, 2017', cover: 'images/news/blockchain_helps.jpg', title: 'Blockchain Helps Refugees to Recreate Lost Identities', titlecn: '区块链可以为难民做些什么?', intro: 'Blockchain technology is believed to be the best way to help refugees to recreate' + ' their lost identities', introcn: '帮助难民重建丢失的身份,区块链技术无疑是最好的选择', url: 'news/blockchain_helps_refugees_to_recreate_lost_identities.html', urlcn: 'news/blockchain_helps_refugees_to_recreate_lost_identities_cn.html' }, { id: '27', date: '10.17', cover: 'images/news/digital_asset.jpg', title: 'Digital Asset Holdings LLC Completes Series B Fundraising', titlecn: '数字资产公司(DAH)完成B轮4000万美元融资', intro: 'DAH has raised $40 million in Series B round, bringing the its current total funding' + ' to $110 million', introcn: 'DAH完成了B轮融资,筹得4000万美元,迄今为止,该企业获得的总融资额已经达到了1.1亿美元', url: 'news/digital_asset_holdings_llc_completes_series_b_fundraising.html', urlcn: 'news/digital_asset_holdings_llc_completes_series_b_fundraising_cn.html' }, { id: '26', date: '10.16', cover: 'images/news/bitcoin_price.jpg', title: 'Bitcoin Price Hits a Record High, Can People Keep Mining?', titlecn: '比特币价格再创新高,挖矿能否继续引关注', intro: 'China’s current bitcoin transaction in global market share has plunged to 2%, while' + ' people in bitcoin circle are wondering whether ‘mining’ will also be restricted or' + ' prohibited or not.', introcn: '目前中国比特币交易量在全球市场所占份额已暴跌至2%。然而现在币圈人士关注的是,中国的 ‘挖矿’是否也会被限制或者禁止?', url: 'news/bitcoin_price_hits_a_record_high.html', urlcn: 'news/bitcoin_price_hits_a_record_high_cn.html' }, { id: '25', date: '10.12', cover: 'images/news/development_of_fiat.jpg', title: 'Development of Fiat Digital Currency Should Keep up with Times', titlecn: '央行数字货币研究所姚前:法定数字货币发展需迎头赶上', intro: 'Fiat digital currency is far more than the digitization of currency; most' + ' importantly, it makes the currency smarter.', introcn: '法定数字货币不仅是简单的将货币进行数字化和网络化,更重要的是可以让货币变的更加智能化', url: 'news/development_of_fiat_digital_currency_should_keep_up_with_times.html', urlcn: 'news/development_of_fiat_digital_currency_should_keep_up_with_times_cn.html' }, { id: '24', date: '10.11', cover: 'images/news/alibaba_establishes.jpg', title: 'Alibaba Establishes Global Research Academy', titlecn: '阿里巴巴成立达摩院,将投千亿启动资金', intro: 'Alibaba today is more than a commercial company. The public empowered us, it’s time' + ' to be giving back, we must do something to live up to people’s expectations. We' + ' should develop the vision that to take responsibility for the world. –Jack Ma, Jack' + ' Ma, the founder of Alibaba', introcn: '今天的阿里巴巴已经不是普通的商业公司。我们拥有的资源是社会和时代给与的,我们要回馈社会,而不是只想着赚更多钱。阿里巴巴要对世界和未来有担当。-马云', url: 'news/alibaba_establishes_global_research_academy.html', urlcn: 'news/alibaba_establishes_global_research_academy_cn.html' }, { id: '23', date: '9.23', cover: 'images/news/c4-thumb.jpg', title: 'Shanghai 17 Platforms Stop Virtual Currency Trading, Top Leadership Is Asked to Stay', titlecn: '上海17家虚拟货币交易平台停业,高管不得离沪', intro: 'After the China’s ban on ICO related activities, many ICO and virtual currency' + ' trading platforms stop their business and some are arranging refunding affairs in' + ' according with the law, the upcoming ICO projects also stops here.', introcn: 'ICO禁令一出,虚拟货币融资和交易平台依法停业,平台已完成项目组织退币,即将上线项目就此止步', url: 'news/shanghai_17_platforms_stop_virtual_currency_trading.html', urlcn: 'news/shanghai_17_platforms_stop_virtual_currency_trading_cn.html' }, { id: '22', date: '9.18', cover: 'images/news/c5-thumb.jpg', title: 'The 3rd Global Blockchain Summit Successfully Held in Shanghai', titlecn: '第三届全球区块链峰会在上海成功召开', intro: 'As the morning sun rises, glowing rays shine. Not dazzling though, the first light' + ' of the morning heralds limitless possibilities.', introcn: '破晓,曙光虽不强烈,却象征着光明,孕育着无限可能性', url: 'news/the_3rd_global_blockchain_summit_successfully.html', urlcn: 'news/the_3rd_global_blockchain_summit_successfully_cn.html' }, { id: '21', date: '9.12', cover: 'images/news/w5-thumb.jpg', title: 'Swiss Town Chiasso Accepts Tax Payments in Bitcoin', titlecn: '瑞士基亚索市将接受比特币支付税款', intro: 'Tax payment in Bitcoin in Swiss Chiasso will put into place at the beginning of the' + ' next year', introcn: '瑞士比特币纳税方案明年落地,人们即将可以使用比特币缴纳税款了', url: 'news/swiss_town_chiasso_accept_tax_payments.html', urlcn: 'news/swiss_town_chiasso_accept_tax_payments_cn.html' }, { id: '20', date: '9.12', cover: 'images/news/w6-thumb.jpg', title: 'SBI Ripple Asia to Test Blockchain Bank Transfers Between Japan and South Korea', titlecn: 'SBI Ripple Asia 将在日本与韩国进行区块链银行转账测试', intro: 'Blockchain bank transfers test is just a beginning, what will happen in the upcoming' + ' future? Will this completely replace the existing bank transfer system? Let’s see!', introcn: '测试只是个开始,未来会发生什么?是否区块链会完全取代现有的银行系统?待我们一起见证', url: 'news/sbi_ripple_asia_to_test_blockchain_bank.html', urlcn: 'news/sbi_ripple_asia_to_test_blockchain_bank_cn.html' }, { id: '19', date: '9.11', cover: 'images/news/w1-thumb.jpg', title: 'New Blockchain Embassy Opens in Panama', titlecn: '巴拿马设立全球首家区块链使馆', intro: 'The Blockchain Embassy functions not only as a place for technology fans, but also' + ' for developers to share and communicate views and researches on this space. You can' + ' also enjoy talking over a cup of coffee or beer as it provides cafeteria service', introcn: '兼具学习交流与娱乐功能,该区块链使馆尽其所能满足爱好者需求,尽最大努力让更多的人了解区块链知识', url: 'news/new_blockchain_embassy_opens_in_panama.html', urlcn: 'news/new_blockchain_embassy_opens_in_panama_cn.html' }, { id: '18', date: '9.11', cover: 'images/news/w2-thumb.jpg', title: 'Russia’s Finance Ministry Drafts Law to Cryptocurrencies', titlecn: '俄罗斯财政部起草法案推动加密货币合法化', intro: 'Many countries are working on the legislation for the use of cryptocurrency. They' + ' are a kind of unstable digital asset, thus certain regulatory is necessary to avoid' + ' the potential risks that may be faced by investors.', introcn: '所有国家都在努力立法,试图规范加密货币的使用。他们是不稳定的,为了防范可能存在的风险,监管非常有必要。', url: 'news/russia_finance_ministry_drafts_law.html', urlcn: 'news/russia_finance_ministry_drafts_law_cn.html' }, { id: '17', date: '9.11', cover: 'images/news/w3-thumb.jpg', title: 'The EU Has Invested over €5 Million in Blockchain Startups', titlecn: '欧盟已向区块链初创公司投资500多万欧元', intro: 'The EU explores Blockchain technology, investing big amount of money to help' + ' startups in this space.', introcn: '欧盟探索区块链技术,投资千万级助力行业初创公司', url: 'news/the_eu_has_invested_over_5_million.html', urlcn: 'news/the_eu_has_invested_over_5_million_cn.html' }, { id: '16', date: '9.11', cover: 'images/news/w4-thumb.jpg', title: 'Ethereum\'s ERC-20 Token Standard Has Been Finalized', titlecn: '以太坊ERC-20代币标准已正式确定', intro: 'ERC-20 standard guarantees a common rule when issuing Ethereum-based tokens, which' + ' means in the future, all Ethereum-based tokens should perform under this standard.', introcn: 'ERC-20标准确立了一套通过以太坊智能合约发行代币的通用规则,这就意味着,在未来,所有在以太坊上构建的代币都要符合该标准。', url: 'news/ethereum_erc-20_token_standard.html', urlcn: 'news/ethereum_erc-20_token_standard_cn.html' }, { id: '15', date: '9.5', cover: 'images/news/c3-1.jpg', title: 'Hong Kong SFC: ICO Tokens May be Securities & Subject to Laws', titlecn: '香港证监会:部分ICO代币属于证券,在港需受证券法例规管', intro: 'HongKong SFC suggests that some tokens issued by ICO projects may belong to' + ' securities', introcn: '香港证监会表示,部分ICO项目发行的代币可能属于证券', url: 'news/hong_kong_sfc_ico_tokens.html', urlcn: 'news/hong_kong_sfc_ico_tokens_cn.html' }, { id: '14', date: '9.4', cover: 'images/news/c2-thumb.jpg', title: 'China Bans All Token Offering Financing Activities, Price of The Virtual Currencies Decline', titlecn: '中国正式禁止各类代币发行融资活动,虚拟货币价格应声暴跌', intro: 'Regulatory authorities said ICO is an unauthorized illegal fund-raising that may' + ' involve in illegal sale of tokens, financial fraud, pyramid schemes and other' + ' criminal activities.', introcn: 'ICO在中国遭禁止,《公告》称,代币发行融资行为涉嫌非法集资、金融诈骗,传销等违法活动', url: 'news/china_bans_all_token_offering_financing_activities.html', urlcn: 'news/china_bans_all_token_offering_financing_activities_cn.html' }, { id: '13', date: '8.28', cover: 'images/news/ibm_launches.jpg', title: 'IBM Launches a Food Blockchain Consortium, Food Industry Giants Join In', titlecn: 'IBM成立全球食品供应链区块链联盟,沃尔玛与雀巢等巨头加入', intro: 'Technology giant IBM has partnered with giants in global food supply chain to launch' + ' a blockchain consortium focusing on food safety.', introcn: '科技巨头IBM已经与全球食品供应链知名品牌达成合作,共同推出专注于食品安全的区块链联盟', url: 'news/ibm_launches_a_food_blockchain_consortium.html', urlcn: 'news/ibm_launches_a_food_blockchain_consortium_cn.html' }, { id: '12', date: '8.23', cover: 'images/news/sawtooth_ethereum.jpg', title: 'Sawtooth Ethereum Tech Makes It Easy to Develop Smart Contracts', titlecn: '锯齿以太坊技术让智能合约开发变得更加容易', intro: 'Ethereum developers build enterprise-level open-source technology implementations in' + ' a new way.', introcn: '以太坊开发者创建企业级开源技术实施的新方式', url: 'news/sawtooth_ethereum_tech_makes_it_easy_to_develop_smart_contracts.html', urlcn: 'news/sawtooth_ethereum_tech_makes_it_easy_to_develop_smart_contracts_cn.html' }, { id: '11', date: '', cover: 'images/news/ten_law_firms.jpg', title: 'Ten Law Firms and Four Legal Institutions Join Enterprise Ethereum Alliance', titlecn: '10家律师事务所4家法律机构宣布加入企业以太坊联盟', intro: 'Are smart contracts legally binding? If the Enterprise Ethereum Alliance’s new' + ' members have anything to say about it, that might someday change.', introcn: '智能合约是否具有法律约束力?如果企业以太坊联盟的新成员有什么想法,或许有一天情况会发生改变', url: 'news/ten_law_firms_and_four_legal_institutions_join_enterprise_ethereum_alliance.html', urlcn: 'news/ten_law_firms_and_four_legal_institutions_join_enterprise_ethereum_alliance_cn.html' }, { id: '10', date: '', cover: 'images/news/ibm_and_sony.jpg', title: 'IBM and Sony to Develop Educational Platform with Blockchain', titlecn: 'IBM与索尼合作开发区块链学生教育数据平台', intro: 'Securing and sharing student records, Blockchain begins to be used in Education.', introcn: '通过区块链技术保护和共享学生数据记录,区块链开始在教育行业发力', url: 'news/ibm_and_sony_to_develop_educational_platform_with_blockchain.html', urlcn: 'news/ibm_and_sony_to_develop_educational_platform_with_blockchain_cn.html' }, { id: '9', date: '', cover: 'images/news/russian_airline.jpg', title: 'Russian Airline Executes the First Payment Using the Blockchain', titlecn: '用区块链出售机票,俄航空公司迈出改革第一步', intro: 'A Russian airline has announced that it will use the ethereum blockchain to sell' + ' flight tickets backed by the country’s largest private commercial bank.', introcn: '俄罗斯西伯利亚航空宣布,他们将在该国最大的私有商业银行的支持下,使用以太坊区块链出售机票', url: 'news/russian_airline_executes_the_first_payment_using_the_blockchain.html', urlcn: 'news/russian_airline_executes_the_first_payment_using_the_blockchain_cn.html' }, { id: '8', date: '', cover: 'images/news/logistics_industry.jpg', title: 'Logistics Industry—Next Step to Global Economy ‘Blockchainization’', titlecn: '物流业——全球经济区块链化发展的下一步', intro: 'The block chain is gradually penetrating into the logistics industry. Block chain' + ' and logistics seem to be a perfect combination. This year, we witness the market’s' + ' growing interest in block chain’s influence in logistics and transportation.', introcn: '区块链技术正在稳步渗透到物流领域,这似乎是一种完美的结合。今年我们目睹了市场对区块链如何改变物流运输行业的兴趣的兴起', url: 'news/logistics_industry.html', urlcn: 'news/logistics_industry_cn.html' }, { id: '7', date: '', cover: 'images/news/mizuho_bank.jpg', title: 'Mizuho Bank Cuts the Time for Its Financial Transactions with Australia from Days to 2' + ' Hours through Blockchain', titlecn: '日本瑞穗银行在日本与澳大利亚之间完成区块链贸易金融交易,将时间从数天缩短至2小时', intro: 'A trade finance transaction through blockchain ended between Mizuho Bank, a Japanese' + ' banking giant and Australia. The detailed information of this trade was also' + ' released.', introcn: '日本银行巨头瑞穗银行已经在日本与澳大利亚之间通过区块链完成了一项贸易金融交易,并发布了关于这次交易的详细信息', url: 'news/mizuho_bank_cuts_the_time_for_its_financial_transactions.html', urlcn: 'news/mizuho_bank_cuts_the_time_for_its_financial_transactions_cn.html' }, { id: '6', date: '', cover: 'images/news/university_of_sydney.jpg', title: 'University of Sydney’s Independently-developed Blockchain System Processes over 400' + ' Thousand Transactions Per Second', titlecn: '悉尼大学自主研发区块链系统,每秒处理40多万笔交易', intro: 'Australia’s University of Sydney (USYD) researchers are currently developing a new' + ' block chain model which reportedly can handle 440 thousand transactions every' + ' second. The participants believe this new system has a potential to revolutionize' + ' the global economy.', introcn: '澳大利亚悉尼大学(USYD)研究者目前正在研发一个新型区块链模型。据悉,这个区块链每秒能够处理44万笔交易。该项目参与者认为这个新型系统具有改革全球经济的潜力', url: 'news/university_of_sydney_independently_developed_blockchain_system.html', urlcn: 'news/university_of_sydney_independently_developed_blockchain_system_cn.html' }, { id: '5', date: '', cover: 'images/news/daimler_ag.jpg', title: 'Daimler AG Issues Blockchain Corporate Bond, Realizing Automatic Bond Transaction Cycle', titlecn: '戴姆勒公司发行1亿欧元区块链公司债券,实现整个债券交易周期自动化', intro: 'As part of a pilot trial, Daimler AG, the German automaker and the parent company of' + ' Mercedes-Benz has issued a corporate bond worth 100 million Euros.', introcn: '梅赛德斯-奔驰母公司,德国汽车制造商戴姆勒股份公司(Daimler AG)已经发布了一种价值1亿欧元的公司债券,作为一个区块链试验项目的一部分', url: 'news/daimler_ag_Issues_blockchain_corporate_bond.html', urlcn: 'news/daimler_ag_Issues_blockchain_corporate_bond_cn.html' }, { id: '4', date: '', cover: 'images/news/barclays_recommends.jpeg', title: 'Barclays Recommends Permissive Regulation of Bitcoin', titlecn: '巴克莱银行建议宽松化监管比特币', intro: 'Recently, Barclays CEO, Ashok Vaswani revealed that the bank has been communicating' + ' with Britain’s Financial Conduct Authority (FCA) and actively talking with UK' + ' regulators about how to bring bitcoin into play within the UK fintech industry.' + ' According to Ashok Vaswani, Barclays has met with FCA, Britain’s chief regulatory' + ' watchdog overseeing the fintech industry, to talk about the regulation of virtual' + ' currency with the aim to work out ways to safely regulate bitcoin.', introcn: '巴克莱银行(Barclays)CEO Ashok' + ' Vaswani透露,该银行一直在和英国金融管理局(FCA)沟通,与英国监管部门展开积极对话,谈到了如何让比特币在英国金融科技领域发挥作用,他们之前和英国主要负责金融科技领域的监管部门FCA碰头,谈论了虚拟货币的监管问题。', url: 'news/barclaysr_ecommends_permissive_regulation_of_bitcoin.html', urlcn: 'news/barclaysr_ecommends_permissive_regulation_of_bitcoin_cn.html' }, { id: '3', date: '', cover: 'images/news/first_case.jpg', title: 'First Case of Bitcoin Used to Buy Stake on Australian Securities Exchange', titlecn: '比特币购买股票?澳交所上演首笔用比特币支付的股权收购案', intro: 'The Australian Securities Exchange (hereinafter referred to as ASX) announced on' + ' Wednesday that bitcoin can be used to buy the stake in a company listed on its' + ' exchange. Blockchain Global Limited (BGL) has committed to buy a 40 percent interest' + ' in Digitalx, paying partly in bitcoins.', introcn: '澳大利亚证券交易所(ASX,以下简称澳交所)本周三宣布,比特币能够用于购买在该交易所上线的公司股份。Blockchain Global' + ' Limited(BGL)承诺购买Digitalx 40%的股权,其中部分资金通过比特币进行支付。', url: 'news/first_case_of_bitcoin_used_to_buy_stake_on_australian_securities_exchange.html', urlcn: 'news/first_case_of_bitcoin_used_to_buy_stake_on_australian_securities_exchange_cn.html' }, { id: '2', date: '6.1', cover: 'images/news/bitcoin_market.jpg', title: 'Bitcoin’s Market Capitalization Overtook Deutsche Bank, May Leading the Future of' + ' Financial System', titlecn: '比特币市值已超越德意志银行,或将领导未来金融系统发展', intro: 'Recently, the executive director of Taurus Wealth Advisors, Rainer Michael Preiss' + ' said that bitcoin can save the global economy.', introcn: '近日,Taurus Wealth Advisors的执行董事Rainer Michael Preiss告诉记者,比特币能够拯救全球经济。', url: 'news/bitcoin_market_capitalization_overtook_deutsche_bank.html', urlcn: 'news/bitcoin_market_capitalization_overtook_deutsche_bank_cn.html' }, { id: '1', date: '4.24', cover: 'images/news/c1-thumb.jpg', title: 'Chinese Internet Giant Tencent is Building New Blockchain Services', titlecn: '腾讯发布区块链方案白皮书,打造区块链共赢生态', intro: 'In the future, the Blockchain will lead the internet of information towards the' + ' internet of value to build a brand new trustworthy society', introcn: '未来区块链将引领信息互联网走向价值互联网,实现互联网价值的真实体现与透明转移,构建全新的诚信社会', url: 'news/chinese_internet_giant_tencent_is_building_new_blockchain_services.html', urlcn: 'news/chinese_internet_giant_tencent_is_building_new_blockchain_services_cn.html' } ] }; var vm = new Vue({ el: '#gtco-maine', data: data });
'use strict'; module.exports = { db: process.env.MONGOHQ_URL || process.env.MONGOLAB_URI || 'mongodb://localhost/store-app', assets: { lib: { css: [ 'public/lib/bootstrap/dist/css/bootstrap.min.css', 'public/lib/fontawesome/css/font-awesome.min.css', 'public/lib/angular-xeditable/dist/css/xeditable.css', 'public/lib/angular-dialog-service/dialogs.min.css', 'public/lib/animate.css/animate.css', 'public/lib/bootstrap-tagsinput/dist/bootstrap-tagsinput.min.css', ], js: [ 'public/lib/jquery/dist/jquery.min.js', 'public/lib/angular/angular.min.js', 'public/lib/angular-resource/angular-resource.js', 'public/lib/angular-cookies/angular-cookies.js', 'public/lib/angular-animate/angular-animate.js', 'public/lib/angular-touch/angular-touch.js', 'public/lib/angular-sanitize/angular-sanitize.js', 'public/lib/angular-ui-router/release/angular-ui-router.min.js', 'public/lib/angular-ui-utils/ui-utils.min.js', 'public/lib/angular-bootstrap/ui-bootstrap-tpls.min.js', 'public/lib/restangular/dist/restangular.min.js', 'public/lib/lodash/dist/lodash.min.js', 'public/lib/angular-xeditable/dist/js/xeditable.min.js', 'public/lib/angular-translate/angular-translate.min.js', 'public/lib/angular-dialog-service/dialogs.min.js', 'public/lib/bootstrap-tagsinput/dist/bootstrap-tagsinput.min.js', 'public/lib/bootstrap-tagsinput/dist/bootstrap-tagsinput-angular.js', 'public/lib/inflection/inflection.min.js', ] }, css: 'public/dist/application.min.css', js: 'public/dist/application.min.js' }, facebook: { clientID: process.env.FACEBOOK_ID || 'APP_ID', clientSecret: process.env.FACEBOOK_SECRET || 'APP_SECRET', callbackURL: 'http://localhost:3000/auth/facebook/callback' }, twitter: { clientID: process.env.TWITTER_KEY || 'CONSUMER_KEY', clientSecret: process.env.TWITTER_SECRET || 'CONSUMER_SECRET', callbackURL: 'http://localhost:3000/auth/twitter/callback' }, google: { clientID: process.env.GOOGLE_ID || 'APP_ID', clientSecret: process.env.GOOGLE_SECRET || 'APP_SECRET', callbackURL: 'http://localhost:3000/auth/google/callback' }, linkedin: { clientID: process.env.LINKEDIN_ID || 'APP_ID', clientSecret: process.env.LINKEDIN_SECRET || 'APP_SECRET', callbackURL: 'http://localhost:3000/auth/linkedin/callback' } };
window.Utils = (function() { const DIGITS = 6; function numberToFixed (number) { return parseFloat(number.toFixed(DIGITS)); } function arrayNumbersToFixed (array) { for (var i = 0; i < array.length; i++) { array[i] = numberToFixed(array[i]); } return array; } function getTooltips (controllerName) { var tooltips; var tooltipName; switch (controllerName) { case 'windows-motion-samsung-controls': { tooltipName = '.windows-motion-samsung-tooltips'; break; } case 'windows-motion-controls': { tooltipName = '.windows-motion-tooltips'; break; } case 'oculus-touch-controls': { tooltipName = '.oculus-tooltips'; break; } case 'vive-controls': { tooltipName = '.vive-tooltips'; break; } default: { break; } } tooltips = Array.prototype.slice.call(document.querySelectorAll(tooltipName)); return tooltips; } return { numberToFixed: numberToFixed, arrayNumbersToFixed: arrayNumbersToFixed, getTooltips: getTooltips } }());
/*jshint node: true, browser: true, nomen: true */ /*global projects_ss*/ 'use strict'; var Reflux = require('reflux'); var ProjectsActions = require('../actions/projects-actions'); var DataHelpers = require('../mixins/data-helpers'); var ProjectStore = require('./project-store'); var ProjectsStore = Reflux.createStore({ mixins: [DataHelpers], listenables: ProjectsActions, init: function () { this.listenTo(ProjectStore, this.projectsUpdated); this.projects = typeof projects_ss === 'undefined' ? [] : projects_ss; }, projectsUpdated: function (evt) { if (evt.success) { switch (evt.type) { case 'create': this.projects.push(evt.data); break; case 'addField': case 'removeField': this.UpdateArrayById(this.projects, evt.data); break; } } this.trigger(this.projects); }, getDefaultData: function () { return this.projects; } }); module.exports = ProjectsStore;
var fs = require('fs'), still = require('../'), testutils = require('./testutils'), build = still.build.build, server = still.server; describe('Templates', function () { afterEach(testutils.teardown); describe('Swig', function () { var out = 'tests/tmp/swigout'; it('renders', function (done) { build({ _: [__dirname + '/templates/swig'], e: 'swig', o: out, verbose: 0, encoding: 'utf-8' }, function () { fs.readFile(out + '/index.html', 'utf8', function (err, data) { data.should.eql('\nhi\n\n'); done(); }); }); }); }); });
export default { ratio: function(value){ return Math.max(0, Math.min(1, value)); } };
/* "THE BEER-WARE LICENSE" (Revision 42): * <m-widmer@gmx> wrote this file. As long as you retain this notice you * can do whatever you want with this stuff. If we meet some day, and you think * this stuff is worth it, you can buy me a beer in return - Manuel Widmer */ // automatically generate TOC when document is ready // use http://closure-compiler.appspot.com/home to make jscript code smaller /* The following conventions must be followed in order to support automatic TOC generation and heading numbers. This script requires jquery (tested with version 1.12.4.min.js) The script will generate two tables of content (TOCs), each one of them residing in a <div id=xyz></div> the id has to be either "ltoc" or "rtoc" (left or right table of content) Headers h1 to h3 are automatically numbered in 1.1.1 style ltoc includes the numbers, whereas rtoc only has unnumbered headings (e.g. quicklinks) So all you have to do is to include on your homepage somewhere the <div> as follows: <div id='ltoc'> Table of Contents: <br /> </div> <div id='rtoc'> Quicklinks: <br /> </div> All the content will then be added automatically by the script below There are two predefined classes for headings. appear in the ltoc only: no special class needed, by default all h1, h2 and h3 will be indexed appear in the rtoc only: class="rtoconly" appear in both tocs: class="bothtoc" example: <h2 class="rtoconly">This title will only appear in the toc on the right</h2> The script can create jumplinks to the most recent h1 or h2 tag. use the classes "h1" or "h2" in an anchor tag: <a class="h1">hyperlink to most recent h1</a> <a class="h2">hyperlink to most recent h2</a> */ $(document).ready(function() { // below section includes headings or elements with the corresponding class // to the right hand toc (aka. quicklinks) // to include new chapters in the right div tag use class=rtoconly or bothtoc $("[class=rtoconly],[class=bothtoc]").each(function(i) { //alert("h1:"+i); // i is just a counter that increments for each match var current = $(this); // refer to the current <h1> element // set the id var type = current.attr("class"); current.attr("id", type + i); // e.g. id="bothtoc3" $("#rtoc").append("<a href='#" + type + i + "'>" + current.html() + "</a> <br />\n"); //current.html returns everything between <h1> </h1> }); // global counter (i.e. no "var") for auto-numbering the chapters: h1index = 0; h2index = 0; h3index = 0; // reason for .toUpperCase() string comparison instead of .toLowerCase() // https://msdn.microsoft.com/en-us/library/bb386042.aspx // https://en.wikipedia.org/wiki/Capital_%E1%BA%9E // below section generates/fills the left table of content (ltoc) // scan the document top down // i = starting at 0 increases for each matched tag / class $("h1, h2, h3, a.h2, a.h1").each(function(i) { var current = $(this);// refer to the current <hX> or <a> element // use correct id if it was already defined by bothtoc or define ltoc id if (current.attr("id") == undefined) { current.attr("id", "title"+i); //ltoc id } // autonumbering + ltoc to previous chapters (h1,h2,h3) if ("H1" == current.prop("tagName").toUpperCase()) { // auto numbering h1index += 1; h2index = 0; h3index = 0; current.prepend(h1index + " "); // prepend Number $("#ltoc").append("<br />\n"); // add line break to ltoc // save the link to the previous <h1> lasth1 = "#" + current.attr("id"); lasth1cont = current.html(); } else if ("H2" == current.prop("tagName").toUpperCase()) { h2index += 1; h3index = 0; current.prepend(h1index + "." + h2index + " "); lasth2 = "#" + current.attr("id"); lasth2cont = current.html(); } else if ("H3" == current.prop("tagName").toUpperCase()) { h3index += 1; current.prepend(h1index + "." + h2index + "." + h3index + " "); } else if(current.attr("class").toUpperCase() == "H1") { current.attr("href", lasth1); current.html(lasth1cont); // add hyperlink to last h1 tag return 0; } else if(current.attr("class").toUpperCase() == "H2") { current.attr("href", lasth2); current.html(lasth2cont); // add hyperlink to last h2 tag return 0; } // exclude rtoconly from ltoc if (typeof current.attr("class") != 'undefined') { if (current.attr("class").toUpperCase() == "RTOCONLY") { return 0;// we have to use return 0 b/c we are in a callback function } } // add the quicklink to the ltoc // for ltoc insert also a folding -/+ hyperlink // to be able to fold properly with the jquery toggle() method, we put // both hyperlinks (folding & chapter) into a div tag which we then can toggle // note the href has to be empty, otherwise the document ready will trigger upon click // and this function will override the html which was just added by the click function below $("#ltoc").append("<div id='div_fold_"+h1index+"_"+h2index+"_"+h3index+"'>" + "<a id='a_fold_"+h1index+"_"+h2index+"_"+h3index+"' style='cursor:pointer'>&#160;-&#160;</a> " + "<a id='link" + i + "' href='#" + current.attr("id") + "' >" + current.html() + "</a> <br /> </div>\n"); return 0; }); // $("h1, h2, h3, a.h2, a.h1").each // implements folding button for elements in ltoc $('a[id^="a_fold"]').click(function() { var current = $(this); // refers to the a tag // grab the current chapter indices from the id var arr = current.attr("id").match(/(\d+)_(\d+)_(\d+)/); //alert(arr.join('\n')) if (current.html().match(/-/)) { var content = "&#160;+&#160;" var show = false; // hide current.html(content); } else { var content = "&#160;-&#160;" var show = true; // show current.html(content); } // check which index equals zero and hide all sub chapters if (arr[2]=="0") { // toggle all h2 below current h1 // everything that contains index1 = arr[1] and index2 not zero var re = new RegExp("div_fold_"+arr[1]+"_[1-9]\\d*_0"); $("div").filter(function(){return this.id.match(re)}).each(function() { $(this).children('a[id^="a_fold"]').html(content) $(this).toggle(show) }); // toggle all h3 below current h1 // h1 can have h3 children without any h2, so toggle also all items where index 3 var re = new RegExp("div_fold_"+arr[1]+"_\\d+_[1-9]\\d*"); $("div").filter(function(){return this.id.match(re)}).each(function() { $(this).children('a[id^="a_fold"]').html(content) $(this).toggle(show) }); } else if (arr[3]=="0") { // only toggle all h3 below current h2 // hide everything that contains index1 = arr[1] and index2 = arr[2] and index3 not zero var re = new RegExp("div_fold_"+arr[1]+"_"+arr[2]+"_[1-9]\\d*"); $("div").filter(function(){return this.id.match(re)}).each(function() { $(this).children('a[id^="a_fold"]').html(content) $(this).toggle(show) }); } }); // click toc chapter folding });
function Paddle(x, y) { this.x = x; this.y = y; this.width = 25; this.height = 100; this.up(false); this.down(false); this.ai = false; this.color = "green"; } Paddle.ACCEL = 3; Paddle.MAXSPD = 10; Paddle.FROTT = .8; Paddle.prototype = new Polygon(); Paddle.prototype.up = function(b) { this.b_up = b; }; Paddle.prototype.down = function(b) { this.b_down = b; }; Paddle.prototype.doAI = function(pong) { this.b_down = false; this.b_up = false; var bally = pong.h / 2; var balld = Infinity; var ballx = -Infinity; var ballvx = -Infinity for(var i in pong.entities) if (pong.entities[i] instanceof Ball) { var ball = pong.entities[i]; var bvx = (this.x - pong.h / 2) * ball.vx; var vd = Math.abs(ball.x - this.x) / ball.vx; vd = (vd < 0 ? vd * -2 : vd); if ( (ballvx < 0 && bvx > 0) || (bvx * ballvx > 0 && vd < balld) || balld == Infinity ) { balld = vd; bally = ball.y; ballx = ball.x; ballvx = bvx; } } if (balld == Infinity) return ; if (pong.debug) { pong.ctx.beginPath(); pong.ctx.moveTo(this.x + this.width/2 , this.y + this.height/2); pong.ctx.lineTo(ballx, bally); pong.ctx.stroke(); pong.ctx.closePath(); } if (this.y + this.height*3/4 < bally) this.b_down = true; if (this.y + this.height/4 > bally) this.b_up = true; } Paddle.prototype.update = function(pong) { if (this.ai) this.doAI(pong); if (this.b_up && this.vy > -Paddle.MAXSPD) this.vy -= Paddle.ACCEL; if (this.b_down && this.vy < Paddle.MAXSPD) this.vy += Paddle.ACCEL; this.vy *= Paddle.FROTT; Polygon.prototype.update.call(this); if (this.y < 0) { this.vy *= -1; this.y = 0; } else if (this.y > pong.h - this.height) { this.vy *= -1; this.y = pong.h - this.height; } };
/** * Entry of client script * @return {[type]} [description] */ ;(function () { 'use strict'; var slice = Array.prototype.slice var clientId = '<%= clientId %>' var _requestHandlers = {} var dataPacketQueue = [] var localBaseDocumentData var serverTime = <%= serverTime %> var clientTime = +new Date var differ, socket, anchor function fillURL(url) { if (/\w+:/.test(url)) return url if (url === null || url === undefined || url === '') return '' if (!anchor) anchor = document.createElement('a') anchor.href = url return (anchor.origin || '') + (anchor.pathname || '') + anchor.search } /** * Get document html **/ var lastOuterHTML function getDocument () { var doc = document.documentElement if (lastOuterHTML === doc.outerHTML) return null var scripts = slice.call(document.scripts) var links = slice.call(doc.querySelectorAll('link[rel="stylesheet"],a,link[rel="icon"]')) var styles = slice.call(doc.querySelectorAll('style')) var images = slice.call(doc.querySelectorAll('img')) var inputs = slice.call(doc.querySelectorAll('input,textarea')) var selects = slice.call(doc.querySelectorAll('select')) // avoid regexp match uncorrectly scripts.forEach(function (item) { if (!item.__jsinspecotr_fixed_url) { item.__jsinspecotr_fixed_url = 1 if (item.getAttribute('src')) { item.setAttribute('src', fillURL(item.src)) } item.setAttribute('jsi-script', '') } }); links.forEach(function (item) { if (item.__jsinspecotr_fixed_url) return item.__jsinspecotr_fixed_url = true item.setAttribute('href', fillURL(item.href || '')) }); images.forEach(function (item) { if (item.__jsinspecotr_fixed_url) return item.__jsinspecotr_fixed_url = true item.setAttribute('src', fillURL(item.src)) }); styles.forEach(function (item) { if (item.innerHTML) { item.innerHTML = item.innerHTML.replace( /url\(([\'\"])*[\/]*(?!http:\/\/|data:|https:\/\/)/g, 'url($1' + window.location.protocol + '//' + window.location.host + '/' ); } }); inputs.forEach(function (item) { if (item.getAttribute('value') !== item.value) { item.setAttribute('value', item.value); } }); selects.forEach(function (item) { var options = slice.call(item.querySelectorAll('option')); options.forEach(function (option) { if (item.value == option.value) { option.setAttribute('selected', 'true'); return true; } }); }); // get document doctype var node = document.doctype var doctype = '<!DOCTYPE ' + node.name + (node.publicId ? ' PUBLIC "' + node.publicId + '"' : '') + (!node.publicId && node.systemId ? ' SYSTEM' : '') + (node.systemId ? ' "' + node.systemId + '"' : '') + '>'; var content = lastOuterHTML = doc.outerHTML content = content // .replace(/<link\s[^\>]*?href="([^\"]+)"[^\>]*?\/?>/g, function (m, u) { // if (/\bjsi-link/.test(m)) { // var l = m.replace(/\bhref="[^\"]+"/, 'href="' + fillURL(u) + '"') // return l // } else return m // }) .replace(/<script\s[^\>]*?>[\s\S]*?<\/script>/g, function (m) { var l = m.match(/^<script\s[^\>]*?>/m)[0] var scriptTypeReg = /\stype="(application|text)\/javascript"/m if (!/\sjsi-script=/.test(l)) return m m = m.replace(/\sjsi-script=""/, '') if (/\stype="/.test(l) && !scriptTypeReg.test(l)) return m else if (scriptTypeReg.test(l)) return m.replace(scriptTypeReg, function (n, t) { return ' type="jsi-' + t + '\/javascript"' }) else return m.replace(/^<script\b/, '<script type="jsi/javascript"') }) return doctype + content } /* =================================================================== */ /** * request and callback **/ var requestId = 1 function $send (options, success, error) { var id = requestId ++ socket.emit('client:' + options.type, { pid: id, // packet id cid: clientId, data: options.data }) /** * register postMessage callback **/ _requestHandlers[id] = { success: success, error: error }; } /* =================================================================== */ /** * Client inpspect ready */ document.addEventListener('connectionReady', function (e) { socket = e.socket differ = jsondiffpatch.create({ textDiff: { // default 60, minimum string length (left and right sides) // to use text diff algorythm: google-diff-match-patch minLength: 256 } }); clientReady() }); function clientReady () { /** * receive server-side response **/ socket.on('server:answer:init:' + clientId, function (data) { var handler = _requestHandlers[data.pid] if (!handler) return delete _requestHandlers[data.pid] handler.success && handler.success(data.data) }); socket.on('server:answer:update:' + clientId, function (data) { var handler = _requestHandlers[data.pid] if (!handler) return delete _requestHandlers[data.pid] handler.success && handler.success(data.data) }); /** * initialize step **/ function documentInitalize (done) { var docHTML = getDocument() var uploadData = { browser: { clientWidth: document.documentElement.clientWidth, clientHeight: document.documentElement.clientHeight, clientId: clientId, userAgent: navigator.userAgent, language: navigator.language, platform: navigator.platform }, html: docHTML, meta: { scrollTop: document.body.scrollTop } } documentUpload(uploadData, done) } function documentUpload (data, cb) { initialSend(data, function () { localBaseDocumentData = data; cb && cb(); }, function () { // if fail, retry documentUpload(data, cb); }); } function initialSend (data, success, error) { $send({ type: 'init', data: data, }, success, error); } /* =================================================================== */ /** * delta checking step **/ function deltaCheckingStart () { dirtyChecking(function (dataPacket) { // call when check for the delta change dataPacket.meta.scrollElements = scrollMetas() sendToQueue(dataPacket); }); consoleChecking(function (dataPacket) { dataPacket.meta.scrollElements = scrollMetas() sendToQueue(dataPacket); }); window.addEventListener('hashchange', function () { var dataPacket = genDetalData(); if (dataPacket) { // update base document content localBaseDocumentData.html = dataPacket.html; // if delta exist, use it if (dataPacket.delta) delete dataPacket.html; // sync the meta localBaseDocumentData.meta.scrollTop = dataPacket.meta.scrollTop localBaseDocumentData.meta.scrollElements = scrollMetas() // TODO sendToQueue(dataPacket); } }); window.addEventListener('scroll', function () { var dataPacket = { meta: { scrollTop: document.body.scrollTop, scrollElements: scrollMetas() } }; sendToQueue(dataPacket); }); var scrollElements = [] function scrollMetas() { var nextSES = [] var scrollMetas = [] scrollElements.forEach(function (xpath) { var el = document.querySelector(xpath) if (el) { nextSES.push(xpath) scrollMetas.push({ xpath: xpath, scrollTop: el.scrollTop }) } }) scrollElements = nextSES return scrollMetas } function elementPath(el) { var pn = el.parentNode var selector = [] var tn while(pn) { tn = el.tagName var childs = pn.children var nth [].slice.call(childs).some(function (c, index) { if (c == el) { nth = index + 1 return true } }) selector.unshift(tn + ':nth-child(' + nth + ')') if (pn !== document.body) { el = pn pn = el.parentNode } else { pn = null } } return 'body>' + selector.join('>') } document.documentElement.addEventListener('scroll', function (e) { var tar = e.target var xpath = elementPath(tar) !~scrollElements.indexOf(xpath) && scrollElements.push(xpath) var dataPacket = { meta: { scrollElements: scrollMetas() } } sendToQueue(dataPacket); }, true) } function dirtyChecking (hasDirtyCallback) { setTimeout(function() { var dataPacket = genDetalData(); if (dataPacket) { // update base document content localBaseDocumentData.html = dataPacket.html; if (dataPacket.delta) delete dataPacket.html; // sync the meta localBaseDocumentData.meta.scrollTop = dataPacket.meta.scrollTop // dirty checking callback hasDirtyCallback(dataPacket); } // polling dirtyChecking(hasDirtyCallback); }, 200); } function consoleChecking (hasConsoleCallback) { setTimeout(function() { var dataPacket; var consoles = window._jsinspector_consoles if (consoles.length > 0) { dataPacket = { meta: { consoles: consoles, } } window._jsinspector_consoles = [] hasConsoleCallback(dataPacket) } consoleChecking(hasConsoleCallback) }, 10) } /** * Generate delta data when has dirty data, else if return null **/ function genDetalData () { var checkedDoc = getDocument(), dirtyDataPacket; if (checkedDoc !== localBaseDocumentData.html) { dirtyDataPacket = { html: checkedDoc, time: new Date - (clientTime - serverTime), delta: <%= delta %> ? differ.diff(localBaseDocumentData.html, checkedDoc) : null, meta: { scrollTop: document.body.scrollTop } } // dirty checking callback return dirtyDataPacket; } return null; } function deltaPost (data, success, error) { $send({ type: 'update', data: data }, success, error); } function sendToQueue (dataPacket) { dataPacketQueue.push(dataPacket); // trigger a event to notify queue manager onDataPacketPush(); } /* =================================================================== */ var queueProcessing = false; /** * queue **/ function onDataPacketPush () { // task queue manager is working now, lock if (queueProcessing) return queueProcess() } var MAX_RETRY_TIMES = 5 var retryTimes = 0 function queueProcess () { if (dataPacketQueue.length === 0) { // stop when the queue is empty queueProcessing = false; return; } queueProcessing = true; var taskData = dataPacketQueue[0]; deltaPost(taskData, function () { // reset retry time retryTimes = 0; dataPacketQueue.shift(); // aync for the performance setTimeout( function() { queueProcess(); }, 50); }, function (err) { if (retryTimes >= MAX_RETRY_TIMES) { // max retry times alert(err || 'network error!'); } else { // retry retryTimes ++; setTimeout( function() { queueProcess(); }); } }); } // document base content initial upload documentInitalize(function () { // delta upload after base document upload done deltaCheckingStart(); }); } })();
import {parseAndGetExpression} from '../../../utils'; import {expect} from 'chai'; describe('LogicalExpression', () => { it('should return correct type', () => { expect(parseAndGetExpression('x&&y').type).to.equal('LogicalExpression'); }); it('should accept parentheses', () => { var assignment = parseAndGetExpression('(x) && (y)'); expect(assignment.operator).to.equal('&&'); expect(assignment.left.name).to.equal('x'); expect(assignment.right.name).to.equal('y'); }); it('should accept &&', () => { var assignment = parseAndGetExpression('x && y'); expect(assignment.operator).to.equal('&&'); expect(assignment.left.name).to.equal('x'); expect(assignment.right.name).to.equal('y'); }); it('should accept ||', () => { var assignment = parseAndGetExpression('x || y'); expect(assignment.operator).to.equal('||'); expect(assignment.left.name).to.equal('x'); expect(assignment.right.name).to.equal('y'); }); });
//steal/js d3px/scripts/compress.js load("steal/rhino/rhino.js"); steal('steal/clean',function(){ steal.clean('d3px/d3px.html',{ indent_size: 1, indent_char: '\t', jslint : false, ignore: /jquery\/jquery.js/, predefined: { steal: true, jQuery: true, $ : true, window : true } }); });