code stringlengths 2 1.05M |
|---|
import PriorityListItem from "./PriorityListItem.js";
import IntervalActionList from "./IntervalActionList.js";
import CommandActionList from "./CommandActionList.js";
import WordActionList from "./WordActionList.js";
class BotInfo extends PriorityListItem{
constructor(prop){
if(typeof(prop) !== "object"){
throw new TypeError("第一引数はObject型を与えてください");
}
super(prop);
this.id = prop.id;
this.name = prop.name;
this.iconUrl = prop.iconUrl;
this.disabled = prop.disabled || false;
this.messages = prop.messages;
this.intervalActionList = IntervalActionList.from(prop.intervalActionList);
this.commandActionList = CommandActionList.from(prop.commandActionList);
this.wordActionList = WordActionList.from(prop.wordActionList);
}
get messageId(){
return "bot_id";
}
set id(value){
if(typeof(value) !== "string"){
throw new TypeError("idはString型のプロパティです");
}
this._id = value;
}
get id(){
return this._id;
}
set name(value){
if(typeof(value) !== "string"){
throw new TypeError("nameはString型のプロパティです");
}
this._name = value;
}
get name(){
return this._name;
}
set disabled(value){
if(typeof(value) !== "boolean"){
throw new TypeError("disabledはBoolean型のプロパティです");
}
this._disabled = value;
}
get disabled(){
return this._disabled;
}
set iconUrl(value){
if(typeof(value) !== "string"){
throw new TypeError("iconUrlはString型のプロパティです");
}
this._iconUrl = value;
}
get iconUrl(){
return this._iconUrl;
}
set messages(value){
if(typeof(value)!=="object"){
throw new TypeError("messagesはObject型のプロパティです");
}
this._messages = value;
}
get messages(){
return this._messages;
}
set intervalActionList(value){
if(!(value instanceof IntervalActionList)){
throw new TypeError("intervalActionListはIntervalActionList型のプロパティです");
}
this._intervalActionList = value;
}
get intervalActionList(){
return this._intervalActionList;
}
set commandActionList(value){
if(!(value instanceof CommandActionList)){
throw new TypeError("commandActionListはCommandActionList型のプロパティです");
}
this._commandActionList = value;
}
get commandActionList(){
return this._commandActionList;
}
set wordActionList(value){
if(!(value instanceof WordActionList)){
throw new TypeError("wordActionListはWordActionList型のプロパティです");
}
this._wordActionList = value;
}
get wordActionList(){
return this._wordActionList;
}
createSequentialMessageObject(name,prop = {}){
// 指定されたキーのリストがなければ発言しない
if(!this.messages[name]) return null;
// 長さがなければ発言しない
if(!this.messages[name].length) return null;
// 秘技!Array自体にプロパティを生やす闇テク~~~www
let cnt = this.messages[name].__cnt = this.messages[name].__cnt || 0;
const text = this.messages[name][cnt++];
// カウント後の値を戻す
if(this.messages[name].length === cnt){
this.messages[name].__cnt = 0;
}
else{
this.messages[name].__cnt = cnt;
}
return this.createMessageObject(text,prop);
}
createRandomMessageObject(name,prop = {}){
// 指定されたキーのリストがなければ発言しない
if(!this.messages[name]) return null;
// 長さがなければ発言しない
if(!this.messages[name].length) return null;
const text = this._getRandomText(this.messages[name]);
return this.createMessageObject(text,prop);
}
createMessageObject(text,prop = {}){
const name = prop.name || this.name;
const id = prop.id || this.id;
const icon_url = prop.icon_url || this.iconUrl;
const username = prop.username || `${name}(@${id})`;
return Object.assign({
[this.messageId]: this.id,
text,
username,
icon_url,
},prop);
}
_getRandomText(list){
// ランダムに1つを抽出する
return list[Math.random()*list.length|0];
}
}
export default BotInfo; |
var roleBuilder = require('role.builder');
module.exports = {
// a function to run the logic for this role
/** @param {Creep} creep */
run: function(creep) {
// if creep is trying to repair something but has no energy left
if (creep.memory.working == true && creep.carry.energy == 0) {
// switch state
creep.memory.working = false;
}
// if creep is harvesting energy but is full
else if (creep.memory.working == false && creep.carry.energy == creep.carryCapacity) {
// switch state
creep.memory.working = true;
}
// if creep is supposed to repair something
if (creep.memory.working == true) {
// find closest structure with less than max hits
// Exclude walls because they have way too many max hits and would keep
// our repairers busy forever. We have to find a solution for that later.
var structure = creep.pos.findClosestByPath(FIND_STRUCTURES, {
// the second argument for findClosestByPath is an object which takes
// a property called filter which can be a function
// we use the arrow operator to define it
filter: (s) => s.hits < s.hitsMax && s.structureType != STRUCTURE_WALL
});
// if we find one
if (structure != undefined) {
// try to repair it, if it is out of range
if (creep.repair(structure) == ERR_NOT_IN_RANGE) {
// move towards it
creep.moveTo(structure);
}
}
// if we can't fine one
else {
// look for construction sites
roleBuilder.run(creep);
}
}
// if creep is supposed to get energy
else {
creep.getEnergy(true, true);
}
}
}; |
import FileSaver from 'FileSaver'
import {Injectable} from '@angular/core'
@Injectable()
export class FileSaverService {
saveAs(...args) {
return FileSaver(...args)
}
} |
'use strict';
import angular from 'angular';
const STATIC_MAP_URL = 'https://maps.googleapis.com/maps/api/staticmap';
const MAX_WIDTH = 380;
const MAX_HEIGHT = 250;
const MAP_TYPE = 'roadmap';
export class GooglePhotoController {
constructor(Util, appConfig) {
'ngInject';
this.src = Util.buildUrl(STATIC_MAP_URL, {
size: `${MAX_WIDTH}x${MAX_HEIGHT}`,
maptype: MAP_TYPE,
key: appConfig.googleMap.apiKey,
markers: `color:red|${this.lat},${this.lng}`
});
}
}
export default angular.module('barologiaApp.googlestaticmap', [])
.component('googleStaticMap', {
bindings: {
lat: '<',
lng: '<'
},
template: '<img class="card__map__image" ng-src="{{googleStaticMapCtrl.src}}" />',
controller: GooglePhotoController,
controllerAs: 'googleStaticMapCtrl'
})
.name;
|
// CodeMirror, copyright (c) by Marijn Haverbeke and others
// Distributed under an MIT license: http://codemirror.net/LICENSE
(function(mod) {
if (typeof exports == "object" && typeof module == "object") // CommonJS
mod(require("common/plugins/editor.md/lib/codemirror/lib/codemirror"), require("common/plugins/editor.md/lib/codemirror/addon/mode/simple"));
else if (typeof define == "function" && define.amd) // AMD
define(["../../lib/codemirror", "../../addon/mode/simple"], mod);
else // Plain browser env
mod(CodeMirror);
})(function(CodeMirror) {
"use strict";
// Collect all Dockerfile directives
var instructions = ["from", "maintainer", "run", "cmd", "expose", "env",
"add", "copy", "entrypoint", "volume", "user",
"workdir", "onbuild"],
instructionRegex = "(" + instructions.join('|') + ")",
instructionOnlyLine = new RegExp(instructionRegex + "\\s*$", "i"),
instructionWithArguments = new RegExp(instructionRegex + "(\\s+)", "i");
CodeMirror.defineSimpleMode("dockerfile", {
start: [
// Block comment: This is a line starting with a comment
{
regex: /#.*$/,
token: "comment"
},
// Highlight an instruction without any arguments (for convenience)
{
regex: instructionOnlyLine,
token: "variable-2"
},
// Highlight an instruction followed by arguments
{
regex: instructionWithArguments,
token: ["variable-2", null],
next: "arguments"
},
{
regex: /./,
token: null
}
],
arguments: [
{
// Line comment without instruction arguments is an error
regex: /#.*$/,
token: "error",
next: "start"
},
{
regex: /[^#]+\\$/,
token: null
},
{
// Match everything except for the inline comment
regex: /[^#]+/,
token: null,
next: "start"
},
{
regex: /$/,
token: null,
next: "start"
},
// Fail safe return to start
{
token: null,
next: "start"
}
]
});
CodeMirror.defineMIME("text/x-dockerfile", "dockerfile");
});
|
Meteor.methods({
"infoView" : function(type){
check(type,String);
infos=Information.find({infoType:type}).fetch();
console.log('server:'+ JSON.stringify(infos));
return infos;
},
"infoUpdate" : function(id){
check(id,String);
check("Yes",String);
info=Information.find({_id:id}).fetch();
Information.update({_id:id},{ $set :{"verificationStatus":"Yes"}} , function (error, result) {
console.log("result " + result + ' error ' + error );
if (error) {
console.log("Errors !!" + error + " Result - " + result);
}
});
}
});
|
/** @constructor */
ScalaJS.c.java_io_IOException = (function() {
ScalaJS.c.java_lang_Exception.call(this)
});
ScalaJS.c.java_io_IOException.prototype = new ScalaJS.inheritable.java_lang_Exception();
ScalaJS.c.java_io_IOException.prototype.constructor = ScalaJS.c.java_io_IOException;
ScalaJS.c.java_io_IOException.prototype.init___T__Ljava_lang_Throwable = (function(s$3, e) {
ScalaJS.c.java_lang_Exception.prototype.init___T.call(this, s$3);
return this
});
ScalaJS.c.java_io_IOException.prototype.init___Ljava_lang_Throwable = (function(e) {
ScalaJS.c.java_io_IOException.prototype.init___T__Ljava_lang_Throwable.call(this, null, e);
return this
});
ScalaJS.c.java_io_IOException.prototype.init___T = (function(s) {
ScalaJS.c.java_io_IOException.prototype.init___T__Ljava_lang_Throwable.call(this, s, null);
return this
});
ScalaJS.c.java_io_IOException.prototype.init___ = (function() {
ScalaJS.c.java_io_IOException.prototype.init___T__Ljava_lang_Throwable.call(this, null, null);
return this
});
/** @constructor */
ScalaJS.inheritable.java_io_IOException = (function() {
/*<skip>*/
});
ScalaJS.inheritable.java_io_IOException.prototype = ScalaJS.c.java_io_IOException.prototype;
ScalaJS.is.java_io_IOException = (function(obj) {
return (!(!((obj && obj.$classData) && obj.$classData.ancestors.java_io_IOException)))
});
ScalaJS.as.java_io_IOException = (function(obj) {
if ((ScalaJS.is.java_io_IOException(obj) || (obj === null))) {
return obj
} else {
ScalaJS.throwClassCastException(obj, "java.io.IOException")
}
});
ScalaJS.isArrayOf.java_io_IOException = (function(obj, depth) {
return (!(!(((obj && obj.$classData) && (obj.$classData.arrayDepth === depth)) && obj.$classData.arrayBase.ancestors.java_io_IOException)))
});
ScalaJS.asArrayOf.java_io_IOException = (function(obj, depth) {
if ((ScalaJS.isArrayOf.java_io_IOException(obj, depth) || (obj === null))) {
return obj
} else {
ScalaJS.throwArrayCastException(obj, "Ljava.io.IOException;", depth)
}
});
ScalaJS.data.java_io_IOException = new ScalaJS.ClassTypeData({
java_io_IOException: 0
}, false, "java.io.IOException", ScalaJS.data.java_lang_Exception, {
java_io_IOException: 1,
java_lang_Exception: 1,
java_lang_Throwable: 1,
java_io_Serializable: 1,
java_lang_Object: 1
});
ScalaJS.c.java_io_IOException.prototype.$classData = ScalaJS.data.java_io_IOException;
//@ sourceMappingURL=IOException.js.map
|
/** @constructor */
ScalaJS.c.scala_Tuple9$ = (function() {
ScalaJS.c.java_lang_Object.call(this)
});
ScalaJS.c.scala_Tuple9$.prototype = new ScalaJS.inheritable.java_lang_Object();
ScalaJS.c.scala_Tuple9$.prototype.constructor = ScalaJS.c.scala_Tuple9$;
ScalaJS.c.scala_Tuple9$.prototype.toString__T = (function() {
return "Tuple9"
});
ScalaJS.c.scala_Tuple9$.prototype.apply__O__O__O__O__O__O__O__O__O__Lscala_Tuple9 = (function(_1, _2, _3, _4, _5, _6, _7, _8, _9) {
return new ScalaJS.c.scala_Tuple9().init___O__O__O__O__O__O__O__O__O(_1, _2, _3, _4, _5, _6, _7, _8, _9)
});
ScalaJS.c.scala_Tuple9$.prototype.unapply__Lscala_Tuple9__Lscala_Option = (function(x$0) {
if (ScalaJS.anyRefEqEq(x$0, null)) {
return ScalaJS.modules.scala_None()
} else {
return new ScalaJS.c.scala_Some().init___O(new ScalaJS.c.scala_Tuple9().init___O__O__O__O__O__O__O__O__O(x$0.$$und1__O(), x$0.$$und2__O(), x$0.$$und3__O(), x$0.$$und4__O(), x$0.$$und5__O(), x$0.$$und6__O(), x$0.$$und7__O(), x$0.$$und8__O(), x$0.$$und9__O()))
}
});
ScalaJS.c.scala_Tuple9$.prototype.readResolve__p1__O = (function() {
return ScalaJS.modules.scala_Tuple9()
});
ScalaJS.c.scala_Tuple9$.prototype.unapply__Lscala_Tuple9__ = (function(x$0) {
return this.unapply__Lscala_Tuple9__Lscala_Option(x$0)
});
ScalaJS.c.scala_Tuple9$.prototype.apply__O__O__O__O__O__O__O__O__O__ = (function(_1, _2, _3, _4, _5, _6, _7, _8, _9) {
return this.apply__O__O__O__O__O__O__O__O__O__Lscala_Tuple9(_1, _2, _3, _4, _5, _6, _7, _8, _9)
});
/** @constructor */
ScalaJS.inheritable.scala_Tuple9$ = (function() {
/*<skip>*/
});
ScalaJS.inheritable.scala_Tuple9$.prototype = ScalaJS.c.scala_Tuple9$.prototype;
ScalaJS.is.scala_Tuple9$ = (function(obj) {
return (!(!((obj && obj.$classData) && obj.$classData.ancestors.scala_Tuple9$)))
});
ScalaJS.as.scala_Tuple9$ = (function(obj) {
if ((ScalaJS.is.scala_Tuple9$(obj) || (obj === null))) {
return obj
} else {
ScalaJS.throwClassCastException(obj, "scala.Tuple9")
}
});
ScalaJS.isArrayOf.scala_Tuple9$ = (function(obj, depth) {
return (!(!(((obj && obj.$classData) && (obj.$classData.arrayDepth === depth)) && obj.$classData.arrayBase.ancestors.scala_Tuple9$)))
});
ScalaJS.asArrayOf.scala_Tuple9$ = (function(obj, depth) {
if ((ScalaJS.isArrayOf.scala_Tuple9$(obj, depth) || (obj === null))) {
return obj
} else {
ScalaJS.throwArrayCastException(obj, "Lscala.Tuple9;", depth)
}
});
ScalaJS.data.scala_Tuple9$ = new ScalaJS.ClassTypeData({
scala_Tuple9$: 0
}, false, "scala.Tuple9$", ScalaJS.data.java_lang_Object, {
scala_Tuple9$: 1,
scala_Serializable: 1,
java_io_Serializable: 1,
java_lang_Object: 1
});
ScalaJS.c.scala_Tuple9$.prototype.$classData = ScalaJS.data.scala_Tuple9$;
ScalaJS.moduleInstances.scala_Tuple9 = undefined;
ScalaJS.modules.scala_Tuple9 = (function() {
if ((!ScalaJS.moduleInstances.scala_Tuple9)) {
ScalaJS.moduleInstances.scala_Tuple9 = new ScalaJS.c.scala_Tuple9$().init___()
};
return ScalaJS.moduleInstances.scala_Tuple9
});
//@ sourceMappingURL=Tuple9$.js.map
|
'use strict';
(function() {
var app = angular.module("vroomApp", ["ngRoute"]);
app.config(function($routeProvider) {
$routeProvider
.when("/", {
templateUrl: 'partials/loading',
controller: MainController
})
.when("/fuel-gauge", {
templateUrl: 'partials/fuel-gauge',
controller: FuelGaugeController
})
.when("/confirm-location", {
templateUrl: 'partials/confirm-location',
controller: ConfirmLocationController
})
.when("/station-list", {
templateUrl: 'partials/station-list',
controller: StationListController
})
.when("/select-fuel-type", {
templateUrl: 'partials/select-fuel-type',
controller: SelectFuelTypeController
})
.when("/wayfinding", {
templateUrl: 'partials/wayfinding',
controller: WayfindingController
})
.otherwise({redirectTo: "/"});
});
}());
|
'use strict';
/*------------------------------------------------------------------------------
* 2. FILE DESTINATIONS (RELATIVE TO ASSSETS FOLDER)
------------------------------------------------------------------------------*/
/*
* opt
* @param false or string: virtual host name of local machine such as . Set false to browser-sync start as server mode.
* @param false or string: Subdomains which must be between 4 and 20 alphanumeric characters.
* @param string: browser which browserSync open
*/
const options = {
autoprefix : ['> 2%', 'last 5 versions', 'ie 10'],
bs : {
tunnel : false,
browser : 'google chrome canary',
ghostMode : {
clicks : false,
scroll : false
},
fils: [
'public/assets/css/*.css',
'public/assets/html/*.html'
]
}
}
const paths = {
root : './',
srcDir : 'src/',
srcImg : 'src/images/',
srcJade : 'src/jade/',
srcJs : 'src/js/',
srcJson : './src/json/',
srcScss : 'src/scss/',
destCss : './assets/css/',
destDir : './assets/',
destGuide : './styleguide',
destImg : './assets/images/',
destJs : './assets/js/',
htmlDir : './src/html/',
reloadOnly : []
}
const nodeSassConf = {
includePaths : [
'./node_modules/',
'./node_modules/foundation-sites/scss',
'./node_modules/font-awesome/scss'
],
errLogToConsole: true
}
export { options, paths, nodeSassConf };
|
'use strict';
var debug = require('debug')('remmit:test');
function ticker (count, done, id) {
var total = count;
id = id || '';
return function (tag) {
tag = tag || '';
debug('tick', id, tag);
if (--count === 0) {
debug('boom', id);
done();
}
if (count < 0) {
throw new Error('Expected ' + total + ' ticks, but got more');
}
};
}
exports.ticker = ticker;
|
// These tests prove that performance is of no concern for a properly planned apps. JS is quite fast for what it is.
var assert = require('assert');
var iterations = 100000000;
describe ("performance", function () {
it ("closures", function () {
var i;
var v1 = 1;
var createFunc = function (level) {
var v2 = 2;
return function () {
var v3 = 3;
if (level === 1) {
v3 = v3 + 1;
} else if (level === 2) {
v3 = v2 + 1;
} else {
v3 = v1 + 1;
}
};
};
var f1 = createFunc(1);
var f2 = createFunc(2);
var f3 = createFunc(3);
console.time('f1'); for (i = iterations; --i;) f1(); console.timeEnd('f1');
console.time('f2'); for (i = iterations; --i;) f2(); console.timeEnd('f2');
console.time('f3'); for (i = iterations; --i;) f3(); console.timeEnd('f3');
});
it("props in constructor", function () {
var Obj1 = function () {
this.p1 = 'some thery long string';
this.p2 = 'some thery long string';
this.p3 = 'some thery long string';
this.p4 = 'some thery long string';
};
var Obj2 = function () {};
Obj2.prototype.p1 = 'some thery long string';
Obj2.prototype.p2 = 'some thery long string';
Obj2.prototype.p3 = 'some thery long string';
Obj2.prototype.p4 = 'some thery long string';
console.time('Obj1'); for (i = iterations; --i;) var o = new Obj1(); console.timeEnd('Obj1');
console.time('Obj2'); for (i = iterations; --i;) var o = new Obj2(); console.timeEnd('Obj2');
});
});
|
/**
* Users.js
*
* @description :: TODO: You might write a short summary of how this model works and what it represents here.
* @docs :: http://sailsjs.org/#!documentation/models
*/
module.exports = {
schema: true,
attributes:{
email: {
type: 'string',
email: true,
required: true,
unique: true
},
name:{
type: 'string'
},
lastName:{
type: 'string'
},
encryptedPassword:{
type:'string'
},
dni:{
type: 'string'
},
bithDate:{
type: 'date'
},
altaDate:{
type: 'date'
},
bajaDate:{
type: 'date'
},
porlado:{
type: 'boolean',
defaultsTo: false
},
junta:{
type: 'boolean',
defaultsTo: false
},
phone:{
type: 'integer',
maxLength: 9,
minLength: 9
},
toJSON: function(){
var obj = this.toObject();
delete obj.password;
delete obj.confirmation;
delete obj.encryptedPassword;
delete obj._csrf;
return obj;
}
},
beforeCreate: function(values, next){
//Chequear que realmente el pass y la confirm son iguales antes de continuar
if(!values.password || values.password != values.confirmation)
return next({err: ["Password doesn't match password confirmation"]});
require('bcrypt').hash(values.password,10, function passwordEncrypted(err, encryptedPassword){
if(err) return next(err);
values.encryptedPassword = encryptedPassword;
//values.online = true;
next();
});
}
};
|
/*
* GET home page.
*/
exports.view = function(req, res){
res.render('profile');
}; |
/* */
var signature = require('cookie-signature');
/**
* Parse signed cookies, returning an object
* containing the decoded key/value pairs,
* while removing the signed key from `obj`.
*
* @param {Object} obj
* @return {Object}
* @api private
*/
exports.signedCookies = function(obj, secret){
var cookies = Object.keys(obj);
var dec;
var key;
var ret = Object.create(null);
var val;
for (var i = 0; i < cookies.length; i++) {
key = cookies[i];
val = obj[key];
dec = exports.signedCookie(val, secret);
if (val !== dec) {
ret[key] = dec;
delete obj[key];
}
}
return ret;
};
/**
* Parse a signed cookie string, return the decoded value
*
* @param {String} str signed cookie string
* @param {String} secret
* @return {String} decoded value
* @api private
*/
exports.signedCookie = function(str, secret){
return str.substr(0, 2) === 's:'
? signature.unsign(str.slice(2), secret)
: str;
};
/**
* Parse JSON cookies.
*
* @param {Object} obj
* @return {Object}
* @api private
*/
exports.JSONCookies = function(obj){
var cookies = Object.keys(obj);
var key;
var val;
for (var i = 0; i < cookies.length; i++) {
key = cookies[i];
val = exports.JSONCookie(obj[key]);
if (val) {
obj[key] = val;
}
}
return obj;
};
/**
* Parse JSON cookie string
*
* @param {String} str
* @return {Object} Parsed object or null if not json cookie
* @api private
*/
exports.JSONCookie = function(str) {
if (!str || str.substr(0, 2) !== 'j:') return;
try {
return JSON.parse(str.slice(2));
} catch (err) {
// no op
}
};
|
'use strict';
/*
This diverges from `Ember.String.dasherize` so that`<XFoo />` can resolve to `x-foo`.
`Ember.String.dasherize` would resolve it to `xfoo`..
*/
const SIMPLE_DASHERIZE_REGEXP = /[A-Z]/g;
const ALPHA = /[A-Za-z]/;
module.exports = function(key) {
return key.replace(SIMPLE_DASHERIZE_REGEXP, (char, index) => {
if (index === 0 || !ALPHA.test(key[index - 1])) {
return char.toLowerCase();
}
return `-${char.toLowerCase()}`;
});
};
|
module.exports = require("./robin"); |
//A proof of concept.
//No code structure whatsoever applied
var http = require('http');
var redis = require('redis');
var redisClient = redis.createClient(6379, '10.129.123.83');
var NRP = require('node-redis-pubsub')
, config = { port: 6379 // Port of your remote Redis server
, host: '10.129.123.83' // Redis server host, defaults to 127.0.0.1
}
, nrp = new NRP(config); // This is the NRP client
var uuid = require('node-uuid');
var responseObjects = {};
http.createServer(function (req, res) {
var timing = {};
timing['gatewayGotRequest'] = Date.now();
var topicName = req.method+':'+req.headers.host+':'+req.url;
var requestUUID = uuid.v1();
responseObjects[requestUUID] = res;
redisClient.rpush('request|'+topicName+"-queue", requestUUID, function(err, reply){
timing['gatewayQueuePush'] = Date.now();
redisClient.hmset('request-'+requestUUID, {
requestUUID: requestUUID,
data: 'Test!',
method: req.method,
host: req.headers.host,
uri: req.url
}, function(err, reply){
timing['gatewayHashSet'] = Date.now();
timing['gatewaySentNotify'] = Date.now();
nrp.emit('request|'+topicName, {timing: timing}); //Notify workers to fetch the new task/request from list
});
});
}).listen(80);
nrp.on('response|*', function (data, channel) {
var requestUUID = data.requestUUID;
if(typeof responseObjects[requestUUID] !== "undefined"){
//console.log(data);
//console.log('data:', data);
//console.log('objs:', responseObjects);
responseObjects[requestUUID].end(data.response);
data.timing['gatewayResponseReady'] = Date.now();
//console.log(data.timing);
}
else{
//console.log(requestUUID);
//console.log(responseObjects);
}
console.log('total:'+(data.timing['gatewayResponseReady']-data.timing['gatewayGotRequest'])+', transit delay: '+ ((data.timing['gatewayResponseReady']-data.timing['gatewayGotRequest'])-(data.timing['serviceGotHttp']-data.timing['serviceStartHttp']))+', internal request: '+ ((data.timing['serviceGotHttp']-data.timing['serviceStartHttp'])));
//console.log(data.timing);
});
|
import chai, { expect } from 'chai'
import server from '../src/index'
export default (done) =>
{
expect(server.info.uri).to.equal('http://localhost:3000')
}
|
var buffer = require('vinyl-buffer');
var cleanCSS = require('gulp-clean-css');
var gulp = require('gulp');
var merge = require('merge-stream');
var rollup = require('rollup-stream');
var source = require('vinyl-source-stream');
var sourcemaps = require('gulp-sourcemaps');
var zip = require('gulp-zip');
function minCss() {
return gulp.src('src/css/style.css', {base: '.'})
.pipe(cleanCSS())
}
function bundle() {
return rollup({
input: 'src/newtab.js',
format: 'es',
sourcemap: true,
});
}
function js() {
return bundle()
.pipe(source('src/newtab.js'))
.pipe(buffer())
.pipe(sourcemaps.init({loadMaps: true}))
.pipe(sourcemaps.write('.'));
}
function copySrcs() {
return gulp.src([
'manifest.json',
'src/**/*.html',
'src/components/*',
], {base: '.'})
}
function compile() {
return merge(minCss(), js(), copySrcs());
}
function build() {
return compile()
.pipe(gulp.dest('out'));
}
function watch() {
gulp.watch('src/**', ['build']);
}
function dist() {
return compile()
.pipe(zip('qswitch.zip'))
.pipe(gulp.dest('dist'));
}
gulp.task('build', build);
gulp.task('watch', watch);
gulp.task('dist', dist);
gulp.task('default', watch);
|
/*
* twisty_demo.js
*
* Demonstration and testing harness for WSOH.
*
* TOOD
* - Fix document.getElementById(...) calls.
// TODO I can imagine that some users of twisty.js would want to be able to have a Heise-style
// inspection, where you are only allowed to do inspection moves during inspection, rather than
// just starting the timer when they do a turn. This will require somehow being able to cancel/prevent a move?
// TODO clicking on canvas doesn't seem to focus window in firefox
// TODO clicking and dragging is weird when the mouse leaves the window
// TODO keydown doesn't repeat on firefox
*
*/
var cache = window.applicationCache;
function updateReadyCache() {
window.applicationCache.swapCache();
location.reload(true); // For now
}
var startTime = null;
var stopTime = null;
function startTimer() {
startTime = new Date().getTime();
stopTime = null;
refreshTimer();
startRefreshTimerLoop();
}
function isTiming() {
return startTime != null && stopTime == null;
}
function stopTimer() {
assert(startTime);
stopTime = new Date().getTime();
refreshTimer();
stopRefreshTimerLoop();
}
function resetTimer() {
startTime = null;
stopTime = null;
refreshTimer();
stopRefreshTimerLoop();
}
function refreshTimer() {
var timer = $("#scrambletimer");
timer.removeClass("reset running stopped");
if(isTiming()) {
timer.addClass("running");
timer.text(prettyTime(new Date().getTime()));
} else if(startTime == null) {
assert(stopTime == null);
timer.addClass("reset");
timer.text("[Timer]");
} else if(stopTime != null) {
assert(startTime);
timer.addClass("stopped");
timer.text(prettyTime(stopTime));
}
}
var pendingTimerRefresh = null;
function startRefreshTimerLoop() {
if(pendingTimerRefresh == null) {
pendingTimerRefresh = requestAnimFrame(refreshTimerLoop, $('#scrambletimer')[0]);
}
}
function stopRefreshTimerLoop() {
if(pendingTimerRefresh != null) {
cancelRequestAnimFrame(pendingTimerRefresh);
pendingTimerRefresh = null;
}
}
function refreshTimerLoop() {
refreshTimer();
if(pendingTimerRefresh != null) {
pendingTimerRefresh = requestAnimFrame(refreshTimerLoop, $('#scrambletimer')[0]);
}
}
function pad(n, minLength) {
var str = '' + n;
while (str.length < minLength) {
str = '0' + str;
}
return str;
}
function prettyTime(endTime) {
var cumulative = endTime - startTime;
var str = "";
str += Math.floor(cumulative/1000/60);
str += ":";
str += pad(Math.floor(cumulative/1000 % 60), 2);
str += ".";
str += pad(Math.floor((cumulative % 1000) / 10), 2);
return str;
}
function scrambleCube(scramble) {
var algo = alg.sign_w.stringToAlg(scramble);
var moves = alg.sign_w.algToMoves(algo);
twistyScene.animateMoves(moves);
}
var CubeState = {
solved: 0,
scrambling: 1,
scrambled: 2,
solving: 3,
};
var cubeState = null;
var twistyScene;
function runTwisty(puzzleSize,scramble) {
/*
* Caching Stuff.
*/
if (typeof(puzzleSize) === "undefined" || puzzleSize == "" || puzzleSize < 1 || puzzleSize > 7) {
puzzleSize = 3;
}
defaultState = {"cubeDimension":puzzleSize,"renderer":"Canvas"}
cache.addEventListener('updateready', updateReadyCache, false);
log("Document ready.");
twistyScene = new twistyjs.TwistyScene();
$('#puzzle').html($(twistyScene.getDomElement()));
var currentCubeSize = parseInt(defaultState.cubeDimension);
reloadCube();
twistyScene.cam(0);
$("#createCanvasPNG").bind("click", function() {
var canvas = twistyScene.getCanvas();
var img = canvas.toDataURL("image/png");
log("Generating image...");
$("#canvasPNG").fadeTo(0, 0);
$("#canvasPNG").html('<a href="' + img + '" target="blank"><img src="'+img+'"/></a>');
$("#canvasPNG").fadeTo("slow", 1);
});
function reDimensionCube(size) {
var dim = parseInt(size);
if (!dim) {
dim = 3;
}
dim = Math.min(Math.max(dim, 1), 16);
if (dim != currentCubeSize) {
currentCubeSize = dim;
reloadCube();
}
resetTimer();
}
// From alg.garron.us
function escapeAlg(algstr){return algstr.replace(/\n/g, '%0A').replace(/-/g, '%2D').replace(/\'/g, '-').replace(/ /g, '_');}
function algUpdateCallback(alg_moves) {
var dim = defaultState.cubeDimension;
// var algString = alg.sign_w.algToString(alg_moves, dim);
// console.log(algString);
// var text;
// if (algString == "") {
// $("#typed_alg").removeAttr("href")
// $("#typed_alg").text("[Algorithm]");
// }
// else {
// var url = "http://alg.garron.us/?alg=" + escapeAlg(algString);
// $("#typed_alg").attr("href", url);
// $("#typed_alg").text(algString);
// }
}
function reloadCube() {
log("Current cube size: " + currentCubeSize);
var renderer = THREE[defaultState.renderer+"Renderer"]; //TODO: Unsafe
var stage = "full"
var speed = 2;
twistyScene.initializeTwisty({
"type": "cube",
"dimension": currentCubeSize,
"renderer": renderer,
"stage": stage,
"speed": speed,
"algUpdateCallback": algUpdateCallback,
"doubleSided": true,
"cubies": false,
"hintStickers": false,
"stickerBorder": true,
allowDragging: true,
showFps: false
});
/*$("#cubeDimension").blur();
twistyScene.resize();
cubeState = CubeState.solved;
resetTimer();*/
}
$(window).resize(twistyScene.resize);
// TODO add visual indicator of cube focus --jfly
// clear up canvasFocused stuff...
//$("#twistyContainer").addClass("canvasFocused");
//$("#twistyContainer").removeClass("canvasFocused");
$(window).keydown(function(e) {
// This is kinda weird, we want to avoid turning the cube
// if we're in a textarea, or input field.
var focusedEl = document.activeElement.nodeName.toLowerCase();
var isEditing = focusedEl == 'textarea' || focusedEl == 'input';
if(isEditing) {
return;
}
var keyCode = e.keyCode;
switch(keyCode) {
case 27:
reloadCube();
e.preventDefault();
break;
case 32:
if (!isTiming()) {
var twisty = twistyScene.getTwisty();
var scramble = twisty.generateScramble(twisty);
// We're going to get notified of the scrambling, and we don't
// want to start the timer when that's happening, so we keep track
// of the fact that we're scrambling.
cubeState = CubeState.scrambling;
twistyScene.applyMoves(scramble); //TODO: Use appropriate function.
cubeState = CubeState.scrambled;
resetTimer();
}
e.preventDefault();
break;
}
twistyScene.keydown(e);
});
twistyScene.addMoveListener(function(move, started) {
if(started) {
if(cubeState == CubeState.scrambling) {
// We don't want to start the timer if we're scrambling the cube.
} else if(cubeState == CubeState.scrambled) {
var twisty = twistyScene.getTwisty();
if(twisty.isInspectionLegalMove(twisty, move)) {
return;
}
startTimer();
cubeState = CubeState.solving;
}
} else {
var twisty = twistyScene.getTwisty();
if(cubeState == CubeState.solving && twisty.isSolved(twisty)) {
cubeState = CubeState.solved;
stopTimer();
}
}
});
scrambleCube(scramble)
}
/*
* Convenience Logging
*/
var logCounter = 0;
function log(obj) {
if(typeof(console) !== "undefined" && console.log) {
console.log(obj);
}
}
function err(obj) {
if(typeof(console) !== "undefined" && console.error) {
console.error(obj);
}
}
/*
* Algs for testing
*/
function makeCCC(n) {
var cccMoves = [];
for (var i = 1; i<=n/2; i++) {
var moreMoves = [
{base: "l", endLayer: i, amount: -1},
{base: "u", endLayer: i, amount: 1},
{base: "r", endLayer: i, amount: -1},
{base: "f", endLayer: i, amount: -1},
{base: "u", endLayer: i, amount: 1},
{base: "l", endLayer: i, amount: -2},
{base: "u", endLayer: i, amount: -2},
{base: "l", endLayer: i, amount: -1},
{base: "u", endLayer: i, amount: -1},
{base: "l", endLayer: i, amount: 1},
{base: "u", endLayer: i, amount: -2},
{base: "d", endLayer: i, amount: 1},
{base: "r", endLayer: i, amount: -1},
{base: "d", endLayer: i, amount: -1},
{base: "f", endLayer: i, amount: 2},
{base: "r", endLayer: i, amount: 2},
{base: "u", endLayer: i, amount: -1}
];
cccMoves = cccMoves.concat(moreMoves);
}
return cccMoves;
}
|
//
// This is only a SKELETON file for the 'Grains' exercise. It's been provided as a
// convenience to get you started writing code faster.
//
export const square = () => {
throw new Error("Remove this statement and implement this function");
};
export const total = () => {
throw new Error("Remove this statement and implement this function");
};
|
"use strict";
var page = require('webpage').create(),
system = require('system'),
address;
if (system.args.length === 1) {
console.log('Usage: netlog.js <some URL>');
phantom.exit(1);
} else {
address = system.args[1];
page.onResourceRequested = function (req) {
console.log('Request (#' + requestData.id + '): ' + JSON.stringify(requestData));
//console.log('requested: ' + JSON.stringify(req, undefined, 4));
};
var count = 0;
page.onResourceReceived = function (res) {
if (res.stage == 'end')
count++;
console.log('Response (#' + res.id + '): ' + res.stage + 'Status: ' + res.statusText + ' URL: '+ res.url)
//console.log('received: ' + JSON.stringify(res, undefined, 4));
};
page.onResourceError = function (resourceError) {
console.log('Unable to load resource (#' + resourceError.id + 'URL:' + resourceError.url + ')');
console.log('Error code: ' + resourceError.errorCode + '. Description: ' + resourceError.errorString);
};
page.clearMemoryCache();
page.settings.clearMemoryCaches = true;
page.open(address, function (status) {
if (status !== 'success') {
console.log('FAIL to load the address');
}
console.log('count is ' + count);
phantom.exit();
});
}
|
/**
* 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 React = require('React');
const ReactRelayContext = require('./ReactRelayContext');
const areEqual = require('areEqual');
import type {
GraphQLTaggedNode,
IEnvironment,
Snapshot,
Variables,
} from 'relay-runtime';
type Props = {
environment: IEnvironment,
query: GraphQLTaggedNode,
// $FlowFixMe
render: ({props: ?Object}) => React.Node,
variables: Variables,
};
type Disposables = {|
disposeRetain: () => void,
disposeSubscribe: () => void,
|};
type State = {
disposables: Disposables,
onNotify: Snapshot => void,
prevEnvironment: IEnvironment,
prevQuery: GraphQLTaggedNode,
prevVariables: Variables,
// $FlowFixMe
props: ?Object,
};
function subscribeAndDeriveState(
environment: IEnvironment,
query: GraphQLTaggedNode,
variables: Variables,
onNotify: Snapshot => void,
prevDisposables?: Disposables,
): State {
cleanup(prevDisposables);
const {getRequest, createOperationDescriptor} = environment.unstable_internal;
const request = getRequest(query);
const operation = createOperationDescriptor(request, variables);
const snapshot = environment.lookup(operation.fragment, operation);
environment.check(operation.root);
const disposables = {
disposeRetain: environment.retain(operation.root).dispose,
disposeSubscribe: environment.subscribe(snapshot, onNotify).dispose,
};
return {
props: snapshot.data,
prevEnvironment: environment,
prevQuery: query,
prevVariables: variables,
onNotify,
disposables,
};
}
function cleanup(disposables: ?Disposables): void {
if (disposables) {
disposables.disposeRetain();
disposables.disposeSubscribe();
}
}
class ReactRelayLocalQueryRenderer extends React.Component<Props, State> {
constructor(props: Props) {
super(props);
const {environment, query, variables} = props;
this.state = subscribeAndDeriveState(
environment,
query,
variables,
this._onNotify,
);
}
componentWillUnmount(): void {
cleanup(this.state.disposables);
}
shouldComponentUpdate(nextProps: Props, nextState: State): boolean {
return (
nextProps.render !== this.props.render ||
nextState.props !== this.state.props
);
}
static getDerivedStateFromProps(
nextProps: Props,
prevState: State,
): State | null {
if (
nextProps.query === prevState.prevQuery &&
nextProps.environment === prevState.prevEnvironment &&
areEqual(nextProps.variables, prevState.prevVariables)
) {
return null;
}
return subscribeAndDeriveState(
nextProps.environment,
nextProps.query,
nextProps.variables,
prevState.onNotify,
prevState.disposables,
);
}
_onNotify = (snapshot: Snapshot): void => {
this.setState({
props: snapshot.data,
});
};
render(): React.Node {
const {environment, render} = this.props;
const {props} = this.state;
const relayContext = {
environment,
variables: {},
};
return (
<ReactRelayContext.Provider value={relayContext}>
{render({props})}
</ReactRelayContext.Provider>
);
}
}
module.exports = ReactRelayLocalQueryRenderer;
|
"use strict";
let gulp = require('gulp');
let runSequence = require('run-sequence');
let jade = require('gulp-jade');
let clean = require('gulp-clean');
let browserSync = require('browser-sync').create();
let ghPages = require('gulp-gh-pages');
let destDir = 'public';
let paths = {
scripts: 'client/js/**/*.js',
css: 'client/css/**/*.css',
bootstrap: './node_modules/bootstrap/dist',
bootswatch: './node_modules/bootswatch/flatly',
jquery: './node_modules/jquery/dist',
font_awesome: './node_modules/font-awesome'
};
gulp.task('Copy Client', function(){
//Copy everything except jade files
let src = [
'client/**/*',
'!client/**/*.jade'
];
return gulp.src( src )
.pipe( gulp.dest( destDir ) );
});
gulp.task('Copy Client Dependencies', function() {
//Bootstrap
gulp.src( [
paths.bootstrap + '/fonts/*',
paths.bootstrap + '/js/bootstrap.min.js'
], { base: paths.bootstrap } )
.pipe( gulp.dest( destDir ) );
//Bootswatch
gulp.src( paths.bootswatch + '/bootstrap.min.css' )
.pipe( gulp.dest( destDir + '/css' ) );
//jQuery
gulp.src( paths.jquery + '/jquery.min.js' )
.pipe( gulp.dest( destDir + '/js' ) );
//Font-Awesome
return gulp.src( [
paths.font_awesome + '/css/font-awesome.min.css',
paths.font_awesome + '/fonts/**/*'
], { base: paths.font_awesome } )
.pipe( gulp.dest( destDir ) );
});
gulp.task('Templates', function(){
let src = 'client/**/*.jade';
let locals = {};
return gulp.src( src )
.pipe( jade( { locals: locals } ) )
.pipe( gulp.dest( destDir ) )
});
gulp.task( 'Clean', function(){
let src = [ destDir, '.publish' ];
return gulp.src( src, { read: false } )
.pipe( clean( {force: true} ) );
});
gulp.task( 'Serve-Watch', ['Copy Client', 'Templates'], function(){
browserSync.reload();
});
gulp.task( 'Serve', ['Copy Client', 'Templates'], function(){
browserSync.init({
server: {
baseDir: destDir
}
});
gulp.watch( ['client/**/*', 'templates/**/*'], ['Serve-Watch'] );
});
gulp.task('Create CNAME', function(){
require('fs').writeFileSync( destDir + '/CNAME', 'www.andoowhy.com');
});
gulp.task('GH Pages', function(){
return gulp.src( './' + destDir + '/**/*' )
.pipe( ghPages( { branch: "master" } ) );
});
gulp.task('Clean Deploy', function(){
return gulp.src( '.publish' )
.pipe( clean( { force: true }) );
});
gulp.task('Deploy', function( callback ) {
runSequence( 'Build', 'Create CNAME', 'GH Pages', 'Clean Deploy', callback );
});
gulp.task('Build', function( callback ){
runSequence( 'Clean',
[ 'Copy Client', 'Copy Client Dependencies', 'Templates'],
callback
);
});
|
require("kaoscript/register");
var Type = require("@kaoscript/runtime").Type;
module.exports = function() {
var __ks_Number = require("../_/_number.ks")().__ks_Number;
var __ks_String = require("../_/_string.ks")().__ks_String;
function degree(value) {
if(arguments.length < 1) {
throw new SyntaxError("Wrong number of arguments (" + arguments.length + " for 1)");
}
if(value === void 0 || value === null) {
throw new TypeError("'value' is not nullable");
}
else if(!Type.isNumber(value) && !Type.isString(value)) {
throw new TypeError("'value' is not of type 'Number' or 'String'");
}
return __ks_Number._im_mod(Type.isNumber(value) ? __ks_Number._im_toInt(value) : __ks_String._im_toInt(value), 360);
}
}; |
import { inMemory } from "@hickory/in-memory";
import { createRouter, prepareRoutes } from "@curi/router";
import app from "./app.svelte";
let routes = prepareRoutes([
{ name: "Home", path: "" },
{ name: "Sync", path: "sync" },
{
name: "Slow",
path: "slow",
resolve() {
return new Promise(resolve => {
setTimeout(resolve, 1000, "slow");
});
}
},
{
name: "Fast",
path: "fast",
resolve() {
return new Promise(resolve => {
setTimeout(resolve, 50, "slow");
});
}
},
{ name: "Catch All", path: "(.*)" }
]);
let router = createRouter(inMemory, routes);
export default function render() {
let target = document.createElement("div");
new app.default({ target, props: { router } });
let button = target.querySelector("button");
let { response: beforeResponse } = router.current();
expect(beforeResponse.name).toBe("Home");
expect(button.textContent).toBe("No op");
let url = router.url({ name: "Sync" });
router.navigate({ url });
expect(button.textContent).toBe("No op");
let { response: afterResponse } = router.current();
expect(afterResponse.name).toBe("Sync");
}
|
import React, {Component} from 'react'
import {bindActionCreators} from 'redux'
import {connect} from 'react-redux'
import {
View,
Text,
ListView,
TouchableWithoutFeedback,
} from 'react-native'
import Container from '../../../../component/layout/container'
import Content from '../../../../component/layout/content'
import Header from '../../../../component/layout/header'
import Diary_list from '../../../../component/list/diary_list'
import {
PAGE_SIZE,
} from '../../../../../variable.js'
import {
OA_INIT_PAGE_NUMBER,
home_diary_favorite_init,
home_diary_favorite_search,
} from './reducer.js'
import {
_fetch,
} from '../../../../lib/fetch'
import {
COLOR_MAIN,
BORDER_WIDTH,
BORDER_COLOR,
BORDER_SHADOW_COLOR,
HEADER_HEIGHT,
HEADER_BACKGROUND_COLOR,
HEADER_TEXT_COLOR,
HEADER_TEXT_ACTIVE_COLOR,
HEADER_ICON_TOUCH_WIDTH,
STATUSBAR_FILLUP_HEIGHT,
COLOR_GRAY_XD,
COLOR_GRAY,
COLOR_GRAY_L,
N_2,
N_3,
N_4,
N_5,
N_6,
N_10,
N_12,
N_14,
N_20,
N_40,
N_44,
} from '../../../../theme/ume-theme/variable.js'
const DATA_PATH = '/logs/follows'
export const FAVORITE_TYPE = 'favorite'
class Favorite extends Component {
constructor(prop) {
super(prop)
this.state = {
top_refreshing: false,
}
}
componentDidMount() {
this.init()
}
init() {
_fetch({
fetch_type: 'GET',
path: DATA_PATH,
param: {
wsId: this.props.auth.info.id,
pageSize: PAGE_SIZE,
pageNumber: OA_INIT_PAGE_NUMBER,
},
token: this.props.auth.info.token,
lang: this.props.i18n.lang,
success: rv => {
this.props.action.home_diary_favorite_init(rv)
},
update_state: payload => {
this.setState({
...this.state,
...payload,
// 首次加载不出现加载icon
top_refreshing: payload._fetch_loading,
})
},
})
}
search() {
_fetch({
fetch_type: 'GET',
path: DATA_PATH,
param: {
wsId: this.props.auth.info.id,
pageSize: PAGE_SIZE,
pageNumber: this.props.favorite.page_number + 1,
},
token: this.props.auth.info.token,
lang: this.props.i18n.lang,
success: rv => this.props.action.home_diary_favorite_search(rv),
update_state: payload => {
this.setState({
...this.state,
...payload,
})
},
})
}
render() {
const {
navigation,
favorite: {
data,
inited,
_fetch_error,
no_more_data,
},
auth,
i18n: {
t,
},
} = this.props
return (
<Content style={{
paddingTop: 0,
}}>
<Diary_list
type={FAVORITE_TYPE}
navigation={navigation}
data={data}
inited={inited}
fetch_error={this.state._fetch_error}
no_more_data={no_more_data}
top_refreshing={this.state.top_refreshing}
on_end_reached={this.search.bind(this)}
on_refresh={this.init.bind(this)}/>
</Content>
)
}
}
export default connect(
state => ({
favorite: state.Diary_favorite,
i18n: state.I18n,
auth: state.Auth,
}),
dispatch => ({
action: bindActionCreators({
home_diary_favorite_init,
home_diary_favorite_search,
}, dispatch),
})
)(Favorite)
|
// This file is used to define the namespaces available in the R context
// DO NOT INCLUDE IN COMPILATION OF ENGINE RUNTIME!!
R.debug = {};
R.lang = {};
R.struct = {};
R.math = {};
R.engine = {};
R.collision = {};
R.collision.broadphase = {};
R.components = {};
R.components.debug = {};
R.components.input = {};
R.components.transform = {};
R.components.logic = {};
R.components.logic.behaviors = {};
R.components.collision = {};
R.components.render = {};
R.components.physics = {};
R.objects = {};
R.particles = {};
R.particles.effects = {};
R.physics = {};
R.rendercontexts = {};
R.resources = {};
R.resources.loaders = {};
R.resources.types = {};
R.sound = {};
R.storage = {};
R.text = {};
R.ui = {};
R.util = {};
R.util.console = {}; |
export const STATE_DEFAULT = {
};
|
import { restaurantService } from '../services';
const fetchData = (restaurantId) => {
return restaurantService.getDishes(restaurantId)
.then(res => res.data)
// Returning [] as a placeholder now so it does not error out when this service
// fails. We should be handling this in our DISPATCH_REQUEST_FAILURE
.catch(() => []);
};
export default fetchData;
|
/*jshint node:true */
/*global describe:false, it:false */
"use strict";
var execify = require('../');
var Q = require('q');
var map = require('map-stream');
var should = require('should');
require('mocha');
describe('execify', function() {
describe('asStream()', function() {
it('should run sync task', function(done) {
var task, a = 0, s;
// Arrange
task = function () {
a++;
};
// Act
s = execify.asStream(task);
s.on('end', function () {
// Assert
a.should.equal(1);
done();
});
s.write({});
s.end();
});
it('should run callback task', function(done) {
var task, args, a = 0, s;
// Arrange
args = {a:'rgs'};
task = function (data, cb) {
a++;
cb(null, data);
};
// Act
s = execify.asStream(task);
s.on('end', function () {
// Assert
a.should.equal(1);
done();
});
s.write(args);
s.end();
});
it('should run promise task', function(done) {
var task, a = 0, s;
// Arrange
task = function () {
var deferred = Q.defer();
setTimeout(function () {
a++;
deferred.resolve();
},1);
return deferred.promise;
};
// Act
s = execify.asStream(task);
s.on('end', function () {
// Assert
a.should.equal(1);
done();
});
s.write({});
s.end();
});
/* TODO: why does this terminate process after asStream's runTask's cb calls [].slice.call(arguments) in map-stream's index.js?
it('should run stream task passed args', function(done) {
var task, args = {a:'rgs'}, a = 0, b = 0, s, timeout = 1;
// Arrange
task = function () {
a.should.equal(0);
a++;
var innerStream = map(function (data, cb) {
cb(null, data);
});
setTimeout(function () {
innerStream.end();
}, timeout);
return innerStream;
};
// Act
s = execify.asStream(task);
s.on('data', function (results) {
b++;
should.exist(results);
results.length.should.equal(1);
results[0].should.equal(args);
});
s.on('end', task, function () {
// Assert
a.should.equal(1);
b.should.equal(1);
done();
});
s.write(args);
s.end();
});
*/
it('should return thrown error', function (done) {
var task, expectedMessage, a = 0, s;
// Arrange
expectedMessage = 'test error';
task = function () {
a++;
throw new Error(expectedMessage);
};
// Act
s = execify.asStream(task);
// Assert
s.on('error', function (err) {
a++;
should.exist(err);
err.message.should.equal(expectedMessage);
done();
});
s.write();
s.end();
});
});
});
|
class SharedFutureBuilder {
constructor(type, name) {
this.type = type
this.name = name
this.suffix = ''
}
assign(varName) {
this.suffix = ` = ${varName}`
return this
}
assignFromPromise(promiseName) {
this.suffix = ` = ${promiseName}.get_future().share()`
return this
}
end() {
this.suffix += ';'
return this
}
build() {
return `std::shared_future<${this.type}> ${this.name}${this.suffix}`
}
}
class PromiseBuilder {
constructor(type, name) {
this.type = type
this.name = name
this.suffix = ''
}
end() {
this.suffix += ';'
return this
}
build() {
return `std::promise<${ this.type }> ${ this.name }${ this.suffix }`
}
}
|
// @flow
import type {ResponseHeader} from '../../models/response';
import * as models from '../../models/index';
import {Readable} from 'stream';
type MaybeResponse = {
parentId?: string,
statusCode?: number,
statusMessage?: string,
bytesRead?: number,
bytesContent?: number,
bodyPath?: string,
elapsedTime?: number,
headers?: Array<ResponseHeader>
}
export function init (
response: MaybeResponse,
bodyBuffer: Buffer | null = null
): {response: Object} {
if (!response) {
throw new Error('contexts.response initialized without response');
}
return {
response: {
// TODO: Make this work. Right now it doesn't because _id is
// not generated in network.js
// getId () {
// return response.parentId;
// },
getRequestId (): string {
return response.parentId || '';
},
getStatusCode (): number {
return response.statusCode || 0;
},
getStatusMessage (): string {
return response.statusMessage || '';
},
getBytesRead (): number {
return response.bytesRead || 0;
},
getTime (): number {
return response.elapsedTime || 0;
},
getBody (): Buffer | null {
return models.response.getBodyBuffer(response);
},
getBodyStream (): Readable | null {
return models.response.getBodyStream(response);
},
getHeader (name: string): string | Array<string> | null {
const headers = response.headers || [];
const matchedHeaders = headers.filter(h => h.name.toLowerCase() === name.toLowerCase());
if (matchedHeaders.length > 1) {
return matchedHeaders.map(h => h.value);
} else if (matchedHeaders.length === 1) {
return matchedHeaders[0].value;
} else {
return null;
}
},
hasHeader (name: string): boolean {
return this.getHeader(name) !== null;
}
}
};
}
|
/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
/**
* EventEmitter.
*/
(function (factory) { // Module boilerplate
if (this.module && module.id.indexOf("event-emitter") >= 0) { // require
factory.call(this, require, exports, module);
} else { // Cu.import
const Cu = Components.utils;
const { require } = Cu.import("resource://devtools/shared/Loader.jsm", {});
this.isWorker = false;
this.promise = Cu.import("resource://gre/modules/Promise.jsm", {}).Promise;
factory.call(this, require, this, { exports: this });
this.EXPORTED_SYMBOLS = ["EventEmitter"];
}
}).call(this, function (require, exports, module) {
this.EventEmitter = function EventEmitter() {};
module.exports = EventEmitter;
const { Cu, components } = require("chrome");
const Services = require("Services");
const promise = require("promise");
var loggingEnabled = true;
if (!isWorker) {
loggingEnabled = Services.prefs.getBoolPref("devtools.dump.emit");
Services.prefs.addObserver("devtools.dump.emit", {
observe: () => {
loggingEnabled = Services.prefs.getBoolPref("devtools.dump.emit");
}
}, false);
}
/**
* Decorate an object with event emitter functionality.
*
* @param Object aObjectToDecorate
* Bind all public methods of EventEmitter to
* the aObjectToDecorate object.
*/
EventEmitter.decorate = function EventEmitter_decorate (aObjectToDecorate) {
let emitter = new EventEmitter();
aObjectToDecorate.on = emitter.on.bind(emitter);
aObjectToDecorate.off = emitter.off.bind(emitter);
aObjectToDecorate.once = emitter.once.bind(emitter);
aObjectToDecorate.emit = emitter.emit.bind(emitter);
};
EventEmitter.prototype = {
/**
* Connect a listener.
*
* @param string aEvent
* The event name to which we're connecting.
* @param function aListener
* Called when the event is fired.
*/
on: function EventEmitter_on(aEvent, aListener) {
if (!this._eventEmitterListeners)
this._eventEmitterListeners = new Map();
if (!this._eventEmitterListeners.has(aEvent)) {
this._eventEmitterListeners.set(aEvent, []);
}
this._eventEmitterListeners.get(aEvent).push(aListener);
},
/**
* Listen for the next time an event is fired.
*
* @param string aEvent
* The event name to which we're connecting.
* @param function aListener
* (Optional) Called when the event is fired. Will be called at most
* one time.
* @return promise
* A promise which is resolved when the event next happens. The
* resolution value of the promise is the first event argument. If
* you need access to second or subsequent event arguments (it's rare
* that this is needed) then use aListener
*/
once: function EventEmitter_once(aEvent, aListener) {
let deferred = promise.defer();
let handler = (aEvent, aFirstArg, ...aRest) => {
this.off(aEvent, handler);
if (aListener) {
aListener.apply(null, [aEvent, aFirstArg, ...aRest]);
}
deferred.resolve(aFirstArg);
};
handler._originalListener = aListener;
this.on(aEvent, handler);
return deferred.promise;
},
/**
* Remove a previously-registered event listener. Works for events
* registered with either on or once.
*
* @param string aEvent
* The event name whose listener we're disconnecting.
* @param function aListener
* The listener to remove.
*/
off: function EventEmitter_off(aEvent, aListener) {
if (!this._eventEmitterListeners)
return;
let listeners = this._eventEmitterListeners.get(aEvent);
if (listeners) {
this._eventEmitterListeners.set(aEvent, listeners.filter(l => {
return l !== aListener && l._originalListener !== aListener;
}));
}
},
/**
* Emit an event. All arguments to this method will
* be sent to listener functions.
*/
emit: function EventEmitter_emit(aEvent) {
this.logEvent(aEvent, arguments);
if (!this._eventEmitterListeners || !this._eventEmitterListeners.has(aEvent)) {
return;
}
let originalListeners = this._eventEmitterListeners.get(aEvent);
for (let listener of this._eventEmitterListeners.get(aEvent)) {
// If the object was destroyed during event emission, stop
// emitting.
if (!this._eventEmitterListeners) {
break;
}
// If listeners were removed during emission, make sure the
// event handler we're going to fire wasn't removed.
if (originalListeners === this._eventEmitterListeners.get(aEvent) ||
this._eventEmitterListeners.get(aEvent).some(l => l === listener)) {
try {
listener.apply(null, arguments);
}
catch (ex) {
// Prevent a bad listener from interfering with the others.
let msg = ex + ": " + ex.stack;
Cu.reportError(msg);
dump(msg + "\n");
}
}
}
},
logEvent: function(aEvent, args) {
if (!loggingEnabled) {
return;
}
let caller, func, path;
if (!isWorker) {
caller = components.stack.caller.caller;
func = caller.name;
let file = caller.filename;
if (file.includes(" -> ")) {
file = caller.filename.split(/ -> /)[1];
}
path = file + ":" + caller.lineNumber;
}
let argOut = "(";
if (args.length === 1) {
argOut += aEvent;
}
let out = "EMITTING: ";
// We need this try / catch to prevent any dead object errors.
try {
for (let i = 1; i < args.length; i++) {
if (i === 1) {
argOut = "(" + aEvent + ", ";
} else {
argOut += ", ";
}
let arg = args[i];
argOut += arg;
if (arg && arg.nodeName) {
argOut += " (" + arg.nodeName;
if (arg.id) {
argOut += "#" + arg.id;
}
if (arg.className) {
argOut += "." + arg.className;
}
argOut += ")";
}
}
} catch(e) {
// Object is dead so the toolbox is most likely shutting down,
// do nothing.
}
argOut += ")";
out += "emit" + argOut + " from " + func + "() -> " + path + "\n";
dump(out);
},
};
});
|
import React from 'react';
import Icon from 'react-fontawesome';
const SearchIcon = props => <Icon {...props} name="search" />;
export default SearchIcon;
|
'use strict';
// Declare app level module which depends on views, and components
angular.module('myApp', ['ngMockE2E',
'ngRoute',
'myApp.view1',
'myApp.view2',
'myApp.version',
'myApp.search'
]).
config(['$routeProvider', function($routeProvider) {
$routeProvider.otherwise({
redirectTo: '/lists'
});
}]);
|
var request = require('request');
var Client = function(options) {
this.baseUrl = options.baseUrl || 'http://note.youdao.com';
this.access_token = options.access_token;
};
/*
* options:
* method: request method
* params: request params
*/
Client.prototype.request = function(options, callback) {
options.baseUrl = this.baseUrl;
options.gzip = true;
options.json = true;
request(options, function(err, res, body) {
if (err) {
return callback(err);
}
// error occur
if (res.statusCode === 500) {
err = new Error(body.message);
err.code = body.error;
return callback(err);
}
callback(null, body);
});
};
var extend = function(dest, source) {
for (var key in source) {
dest[key] = source[key];
}
};
extend(Client.prototype, require('./user'));
extend(Client.prototype, require('./note'));
extend(Client.prototype, require('./notebook'));
extend(Client.prototype, require('./share'));
extend(Client.prototype, require('./attachment'));
module.exports = Client;
|
var about = require('express').Router();
about.get('/', function(req, res) {
if(req.user !== undefined) {
res.render('partials/about', {
title : 'Code Agent - About',
isAboutPage : true,
user: req.user
});
}
else {
res.render('partials/about', {
title : 'Code Agent - About',
isAboutPage : true
});
}
});
module.exports = about;
|
import BaseProvider from './provider';
export default class Provider extends BaseProvider {
endpoint({ query } = {}) {
const { params } = this.options;
const paramString = this.getParamString({
...params,
format: 'json',
q: query,
});
return `https://nominatim.openstreetmap.org/search?${paramString}`;
}
endpointReverse({ data } = {}) {
const { params } = this.options;
const paramString = this.getParamString({
...params,
format: 'json',
// eslint-disable-next-line camelcase
osm_id: data.raw.osm_id,
// eslint-disable-next-line camelcase
osm_type: this.translateOsmType(data.raw.osm_type),
});
return `https://nominatim.openstreetmap.org/reverse?${paramString}`;
}
parse({ data }) {
return data.map(r => ({
x: r.lon,
y: r.lat,
label: r.display_name,
bounds: [
[parseFloat(r.boundingbox[0]), parseFloat(r.boundingbox[2])], // s, w
[parseFloat(r.boundingbox[1]), parseFloat(r.boundingbox[3])], // n, e
],
raw: r,
}));
}
async search({ query, data }) {
// eslint-disable-next-line no-bitwise
const protocol = ~location.protocol.indexOf('http') ? location.protocol : 'https:';
const url = data
? this.endpointReverse({ data, protocol })
: this.endpoint({ query, protocol });
const request = await fetch(url);
const json = await request.json();
return this.parse({ data: data ? [json] : json });
}
translateOsmType(type) {
if (type === 'node') return 'N';
if (type === 'way') return 'W';
if (type === 'relation') return 'R';
return ''; // Unknown
}
}
|
var debug = false;
var option = {
restart:false,
follow: true,
hour:9,
name:'moto',
gravity:-10,
mass:500,
engine:2000,
acceleration:100,
// car body physics
friction: 0.1,
restitution: 0,
linear: 0,
angular: 0,
rolling: 0,
// suspension
autoSuspension:true,
s_stiffness: 153,
s_compression: 2.3,
s_damping: 2.4,//2.4
s_force: 6000,
s_length: 0.03,
s_travel: 0.06,
// wheel
w_friction: 100,//10.5,//1000,
w_roll: 0.3,
susp_av:0,
susp_ar:0,
open_shell:1,
}
//0.331 // 0.662
var mat = {};
var axis_front, axis_back, front_shell, front_rim, back_rim, tire_front, tire_back, extra_susp, extra_link;
var bike, kaneda;
var decalBikeY = 0.21;
var base_q;//, q_steering = new THREE.Quaternion()
var m1 = new THREE.Matrix4(), m2 = new THREE.Matrix4();
var hour = option.hour;
function demo() {
//view.hideGrid();
view.moveCam({ theta:-90, phi:30, distance:3, target:[0,0,0] });
view.addJoystick({ sameAxis:true });
//view.addSky({ hour:option.hour, hdr:true, cloud_covr:0.6, cloud_dens:60, groundColor:0x373737 });
view.addSky({ url:'photo.jpg', hdr:true, visible:false });
view.setShadow( { size:10, near:195, far:205, groundSize:1000, debug:debug } );
physic.set({
fps:60,
numStep:8,// more numStep = more accurate simulation default set to 2
gravity:[ 0, option.gravity ,0 ],
})
//view.load ( ['track.sea'], afterLoad, true, true );
view.load ( [ 'kaneda.sea', 'track.sea' ], afterLoad, true, true );
//load ( 'gaz', afterLoad );
};
function afterLoad () {
// infinie plan
physic.add({ type:'plane', friction:0.6, restitution:0 });
// basic track
physic.add({ type:'mesh', shape:view.getGeometry('track', 'track'), pos:[5,0,0], mass:0, friction:0.6, restitution:0.1 });
//physic.add({ type:'mesh', shape:view.geo.track, mass:0, friction:0.6, restitution:0.1 });
initMaterials();
initBike();
initKaneda();
// add option setting
ui ({
base:option,
function: applyOption,
hour: { min:0, max:24, precision:2, color:0xFFFF44 },
restart: { type:'button', p:0, h:30, radius:10 },
follow: { type:'bool' },
gravity : { min:-20, max:20, color:0x8888FF },
mass : { min:100, max:10000, precision:0, color:0xFF8844 },
engine : { min:100, max:10000, precision:0, color:0xFF8844 },
acceleration : { min:1, max:1000, precision:0, color:0xFF8844 },
friction: { min:0, max:1, precision:2, color:0x88FF88 },
restitution: { min:0, max:1, precision:2, color:0x88FF88 },
linear: { min:0, max:1, precision:2, color:0x88FF88 },
angular: { min:0, max:1, precision:2, color:0x88FF88 },
rolling: { min:0, max:1, precision:2, color:0x88FF88 },
s_stiffness: { min:0, max:200, precision:0, color:0xCC88FF },
autoSuspension: { type:'bool' },
s_compression: { min:0, max:5, precision:2, color:0xCC88FF },
s_damping: { min:0, max:5, precision:2, color:0xCC88FF },
s_travel: { min:0.01, max:5, precision:2, color:0xCC88FF },
s_force: { min:0, max:10000, precision:0, color:0xCC88FF },
s_length: { min:0.01, max:1, precision:2, color:0xCC88FF },
w_friction: { min:0, max:1000, precision:2, color:0xCCCC44 },
w_roll: { min:0, max:1, precision:2, color:0xCCCC44 },
//susp_av: { min:-0.783, max:0.783, precision:2, color:0x44CCCC },
//susp_av: { min:-0.3, max:0.3, precision:2, color:0x44CCCC },
//susp_ar: { min:-0.3, max:0.3, precision:2, color:0x44CCCC },
open_shell: { min:0, max:1, precision:2, color:0xCC4444 },
});
view.update = update;
physic.drive( option.name );
follow ( option.follow ? option.name : 'none', { distance:4, decal:[0,0.3,0] } );
};
function update () {
var data = bike.userData;
option.susp_av = -data.suspension[0]*10;
option.susp_ar = -data.suspension[1]*10;
var r = data.steering * 0.5;
m1.makeRotationY( r );
m2.makeRotationFromQuaternion(base_q);
m2.multiply(m1);
axis_front.setRotationFromMatrix(m2);
var frame = 24 - (Math.round( r * THREE.Math.RAD2DEG )+12);
kaneda.playFrame( frame, 24 );
//var r = (data.speed*THREE.Math.DEG2RAD*0.8)
tire_front.rotation.x = data.wr[0];
tire_back.rotation.z = -data.wr[1];
//tire_front.rotation.x += r;
//tire_back.rotation.z -= r;
var sav = option.susp_av*2.61;
front_rim.position.y = -7.172 + sav;
back_rim.position.y = -option.susp_ar;
axis_back.setWeight( 'ak_axis_back_low', ((-option.susp_ar+0.3)*1.66666) );
extra_susp.setWeight( 'ak_extra_susp_low', 1-((sav+0.783)*0.638) );
}
function frontShell ( n ) {
// range -75 / -90
front_shell.rotation.x = - (75 + ( n * 15 )) * THREE.Math.DEG2RAD;
extra_link.setWeight( 'ak_link_low', n );
}
function applyOption () {//1.566
option.reset = option.restart ? true : false;
if( hour !== option.hour ){ hour = option.hour; view.updateSky({hour:hour}); }
if( option.reset ){
physic.matrix( [{ name: option.name, pos:[0,1,0], rot:[0,90,0] }] );
option.reset = false;
}
frontShell( option.open_shell );
follow ( option.follow ? option.name : 'none', { distance:4, decal:[0,0.3,0] } );
physic.post( 'setGravity', { gravity:[ 0, option.gravity, 0 ] });
physic.post( 'setVehicle', option );
physic.drive( option.name );
}
//----------------------------
// INIT
//----------------------------
function initKaneda () {
kaneda = view.getMesh( 'kaneda', 'ka_body' );
kaneda.material = mat.kaneda;
view.addUV2( kaneda );
kaneda.castShadow = true;
kaneda.receiveShadow = true;
kaneda.play( "turn" );
kaneda.getAnim();
//console.log( kaneda.anim )
var hair = view.getMesh( 'kaneda', 'ka_hair' );
var lunette = view.getMesh( 'kaneda', 'ka_lunette' );
var glass = view.getMesh( 'kaneda', 'ka_glass' );
var eye_l = view.getMesh( 'kaneda', 'ka_eye_l' );
var eye_r = view.getMesh( 'kaneda', 'ka_eye_r' );
hair.castShadow = true;
lunette.castShadow = false;
glass.castShadow = false;
eye_l.castShadow = false;
eye_r.castShadow = false;
hair.material = mat.kaneda;
lunette.material = mat.kaneda;
glass.material = mat.glass;
eye_l.material = mat.eye;
eye_r.material = mat.eye;
view.addUV2( hair );
view.addUV2( lunette );
hair.skeleton = kaneda.skeleton;
lunette.skeleton = kaneda.skeleton;
hair.frustumCulled = false;
lunette.frustumCulled = false;
//view.getMesh( 'kaneda', 'ka_body' );
//view.getScene().add( kaneda );
kaneda.scale.set( 0.1, 0.1, 0.1 );
kaneda.position.set(0,decalBikeY+0.38,-0.3);
kaneda.rotation.y = -90 * THREE.Math.DEG2RAD;
bike.add( kaneda );
}
function initBike () {
var mesh = view.getMesh( 'kaneda', 'ak_chassis_base' );
var k = mesh.children.length, m, m2, name, j, back, tmpName;
while( k-- ){
m = mesh.children[k];
name = mesh.children[k].name;
view.addUV2( m );
m.material = mat.bike_1;
if( name === 'ak_axis_back' || name === 'ak_axis_front' ){
m.material = mat.bike_2;
back = name === 'ak_axis_back' ? true : false;
j = m.children.length;
while( j-- ){
m2 = m.children[j];
m2.material = mat.bike_2;
if( back ){
axis_back = m;
axis_back.material = mat.bike_1_m;
back_rim = m2;
if(m2.children[0].name === 'ak_tire_ar'){
tire_back = m2.children[0];
tire_back.material = mat.tires;
m2.children[1].material = mat.glass_colors;
m2.children[1].castShadow = false;
m2.children[1].receiveShadow = false;
} else {
tire_back = m2.children[1];
tire_back.material = mat.tires;
m2.children[0].material = mat.glass_colors;
m2.children[0].castShadow = false;
m2.children[0].receiveShadow = false;
}
} else {
axis_front = m;
if( m2.name === 'ak_front_shell' ){
front_shell = m2;
tmpName = front_shell.children[0].name;
if( tmpName === 'ak_glass' ){
front_shell.children[0].material = mat.glass;
front_shell.children[1].material = mat.bike_3;
front_shell.children[1].children[0].material = mat.glass_colors;
front_shell.children[0].castShadow = false;
front_shell.children[0].receiveShadow = false;
} else {
front_shell.children[1].material = mat.glass;
front_shell.children[0].material = mat.bike_3;
front_shell.children[0].children[0].material = mat.glass_colors;
front_shell.children[1].castShadow = false;
front_shell.children[1].receiveShadow = false;
}
//
} else if ( m2.name === 'ak_rim_av' ){
front_rim = m2;
tire_front = front_rim.children[0];
tire_front.material = mat.tires;
if(m2.children[0].name === 'ak_tire_ar'){
tire_front = front_rim.children[0];
tire_front.material = mat.tires;
front_rim.children[1].material = mat.glass_colors;
front_rim.children[1].castShadow = false;
front_rim.children[1].receiveShadow = false;
} else {
tire_front = front_rim.children[1];
tire_front.material = mat.tires;
front_rim.children[0].material = mat.glass_colors;
front_rim.children[0].castShadow = false;
front_rim.children[0].receiveShadow = false;
}
} else if ( m2.name === 'ak_extra_susp' ) {
extra_susp = m2;
extra_susp.material = mat.bike_1_m;
} else {
extra_link = m2;
extra_link.material = mat.bike_1_m;
}
}
}
} else if( name === 'ak_chassis_shell' ) {
j = m.children.length;
while( j-- ){
m2 = m.children[j];
m2.material = m2.name ==='ak_panel' ? mat.bike_3 : mat.bike_1;
if( m2.name ==='ak_panel' ) m2.children[0].material = mat.glass_colors;
}
}
}
//front_shell.visible = false
base_q = axis_front.quaternion.clone();
mesh.material = mat.bike_1;
mesh.scale.set( 0.1, 0.1, 0.1 );
mesh.rotation.y = -90 * THREE.Math.DEG2RAD;
mesh.position.y = decalBikeY;
// range -75 / -90
frontShell( option.open_shell );
var o = option;
physic.add({
type:'car',
name: o.name,
shapeType:'box',
wheelMaterial: mat.debugWheel,
mesh: mesh,//debug ? null : mesh,
helper: debug,
pos:[0,1,0], // start position of car
rot:[0,90,0], // start rotation of car
size:[ 0.6, 0.5, 2.0 ], // chassis size y 0.6
//size:[ 1.2, 0.6, 3.8 ], // chassis size
masscenter:[ 0, -0.6, 0 ], // local center of mass (best is on chassis bottom)
friction: o.friction,
restitution: o.restitution,
linear: o.linear,
angular: o.angular,
limitAngular: [0.8,1,0.8],
nWheel:2,
radius:0.36,// wheels radius
radiusBack:0.39,// wheels radius
deep:0.19, // wheels deep only for three cylinder
wPos:[ 0.1, -0.02, 1.1 ], // wheels position on chassis
decalYBack:0.02,
// car setting
mass: o.mass,// mass of vehicle in kg
engine: o.engine, // Maximum driving force of the vehicle
acceleration: o.acceleration, // engine increment
// suspension setting
// Damping relaxation should be slightly larger than compression
autoSuspension: o.autoSuspension,
s_compression: o.s_compression,// 0.1 to 0.3 are real values default 0.84 // 4.4
s_damping: o.s_damping,//2.4, // The damping coefficient for when the suspension is expanding. default : 0.88 // 2.3
s_stiffness: o.s_stiffness,// 10 = Offroad buggy, 50 = Sports car, 200 = F1 Car
s_travel: o.s_travel, // The maximum distance the suspension can be compressed in meter
s_force: o.s_force, // Maximum suspension force
s_length: o.s_length,//0.1, // The maximum length of the suspension in meter
// wheel setting
// friction: The constant friction of the wheels on the surface.
// For realistic TS It should be around 0.8.
// But may be greatly increased to improve controllability (1000 and more)
// Set large (10000.0) for kart racers
w_friction: o.w_friction,
// roll: reduces torque from the wheels
// reducing vehicle barrel chance
// 0 - no torque, 1 - the actual physical behavior
w_roll: o.w_roll,
});
bike = physic.byName( option.name );
bike.userData.w[0].visible = debug;
bike.userData.w[1].visible = debug;
bike.userData.w[0].castShadow = false;
bike.userData.w[0].receiveShadow = false;
bike.userData.w[1].castShadow = false;
bike.userData.w[1].receiveShadow = false;
}
function initMaterials () {
var ao = 1.5;
mat['debugWheel'] = view.material({
type:'Basic',
name:'debugWheel',
color: 0x3c7cff,
wireframe:true,
transparent:true,
opacity:0.5,
});
mat['glass'] = view.material({
name:'glass',
roughness: 0.1,
metalness: 1.0,
color: 0xeeefff,
transparent:true,
opacity:0.3,
side:'Double',
//depthTest:false,
depthWrite:false,
});
mat['glass_colors'] = view.material({
name:'glass_colors',
roughness: 0.1,
metalness: 1.0,
map: { url:'kaneda/bike_3_l.jpg'},
emissive: 0xAAAAAA,
emissiveIntensity:1,
emissiveMap: { url:'kaneda/bike_3_l.jpg'},
transparent:true,
opacity:0.66,
});
mat['bike_1'] = view.material({
name:'bike_1',
roughness: 1.0,
metalness: 1.0,
//color:0xffffff,
map: { url:'kaneda/bike_1_c.jpg'},
metalnessMap: { url:'kaneda/bike_1_m.jpg'},
roughnessMap: { url:'kaneda/bike_1_r.jpg'},
normalMap: { url:'kaneda/bike_1_n.jpg'},
aoMap: { url:'kaneda/bike_1_a.jpg'},
aoMapIntensity:ao,
});
mat['bike_1_m'] = view.material({
name:'bike_1_m',
roughness: 1.0,
metalness: 1.0,
map: { url:'kaneda/bike_1_c.jpg'},
metalnessMap: { url:'kaneda/bike_1_m.jpg'},
roughnessMap: { url:'kaneda/bike_1_r.jpg'},
normalMap: { url:'kaneda/bike_1_n.jpg'},
aoMap: { url:'kaneda/bike_1_a.jpg' },
aoMapIntensity:ao,
morphTargets:true,
});
mat['bike_2'] = view.material({
name:'bike_2',
roughness: 1.0,
metalness: 1.0,
map: { url:'kaneda/bike_2_c.jpg'},
metalnessMap: { url:'kaneda/bike_2_m.jpg'},
roughnessMap: { url:'kaneda/bike_2_r.jpg'},
aoMap: { url:'kaneda/bike_2_a.jpg'},
aoMapIntensity:ao,
//normalMap: { url:'kaneda/bike_2_n.jpg'),
});
mat['bike_3'] = view.material({
name:'bike_3',
roughness: 1.0,
metalness: 1.0,
map: { url:'kaneda/bike_3_c.jpg'},
normalMap: { url:'kaneda/bike_3_n.jpg'},
metalnessMap: { url:'kaneda/bike_3_m.jpg'},
roughnessMap: { url:'kaneda/bike_3_r.jpg'},
aoMap: { url:'kaneda/bike_3_a.jpg'},
aoMapIntensity:ao,
});
mat['tires'] = view.material({
name:'tires',
roughness: 0.6,
metalness: 0.5,
map: { url:'kaneda/tires_c.jpg'},
normalMap: { url:'kaneda/tires_n.jpg'},
//normalScale:new THREE.Vector2( 2, 2 ),
});
mat['kaneda'] = view.material({
name:'kaneda',
skinning: true,
roughness: 1.0,
metalness: 1.0,
map: { url:'kaneda/kaneda_c.jpg'},
normalMap: { url:'kaneda/kaneda_n.jpg'},
//normalScale:new THREE.Vector2( 0.5, 0.5 ),
metalnessMap: { url:'kaneda/kaneda_m.jpg'},
roughnessMap: { url:'kaneda/kaneda_r.jpg'},
aoMap: { url:'kaneda/kaneda_a.jpg'},
aoMapIntensity:ao,
});
mat['eye'] = view.material({
name:'eye',
roughness: 0.0,
metalness: 1.0,
map: { url:'kaneda/kaneda_c.jpg'},
normalMap: { url:'kaneda/kaneda_n.jpg'},
});
} |
var GasPlugin = require("gas-webpack-plugin");
module.exports = {
resolve: {
extensions: [".js", ".gs"]
},
context: __dirname,
entry: './src/index.js',
output: {
path: __dirname+'/dist',
filename: 'sheet2form.gs'
},
plugins: [
new GasPlugin()
]
}
|
var Vue = require('vue')
var Toolbar = require('./toolbar/toolbar.vue')
var Editor = require('./editor/editor.vue')
new Vue({
el: 'body',
components: {
toolbar: Toolbar,
editor: Editor
}
})
document.addEventListener('keypress', function(e) {
if (e.keyCode == 13) {
document.execCommand('formatBlock',false, 'p');
}
});
|
const getAccount = state =>
state.get('account');
const isAuthenticated = state =>
!getAccount(state).isEmpty();
export { getAccount, isAuthenticated };
|
import {create} from './actions/create';
import {login} from './actions/login';
import {find, findById} from './actions/find';
import {register, registerPending, registerSuccess, registerError} from './actions/register';
import loginHandler from './action-handlers/login';
import registerHandler from './action-handlers/register';
import {singleParamModelMethod, doubleParamModelMethod} from './model';
export const actions = {
create: create,
login: login,
register: register,
find: find,
findById: findById
};
const actionHandlers = {
'LOOPBACK_LOGIN': loginHandler,
'LOOPBACK_REGISTER': registerHandler,
'LOOPBACK_MODEL_FIND': singleParamModelMethod,
'LOOPBACK_MODEL_FIND_BY_ID': doubleParamModelMethod
};
export default function(app, options={}) {
const loopbackMiddleware = store => next => action => {
if (actionHandlers[action.type]) {
if (options.syncAppWithState) {
options.syncAppWithState(app, store.getState());
}
actionHandlers[action.type](app, store, action);
}
return next(action);
}
return loopbackMiddleware;
}
|
const libmultiparty = require('multiparty')
const Exception = require('./Exception')
function FormParser(configs) {
//size in bytes, default: 1048576 bytes = 1 Mebibyte
const _maxEntitySize = configs.maxEntitySize ? configs.maxEntitySize : 1048576
const _uploadDir = configs.uploadDirectory
Object.defineProperty(this, 'maxEntitySize', {
get: function () {
return _maxEntitySize
},
set: function(newValue) {
throw new Exception('READ_ONLY', 'Property "maxEntitySize" is not writeable')
}
})
this.parse = function(request, maxEntitySize) {
return new Promise(function(resolve, reject) {
if(!request.headers['content-type']) {
return resolve({
fields: {},
files: {}
})
}
try {
if(request.headers['content-type'].substring(0, 19) == 'multipart/form-data') {
const form = new libmultiparty.Form({
maxFieldsSize: maxEntitySize ? maxEntitySize : _maxEntitySize,
maxFilesSize: maxEntitySize ? maxEntitySize : _maxEntitySize,
uploadDir: _uploadDir
})
form.parse(request, function(error, fields, files) {
if(error) {
if(error.status == 413) {
reject(new Exception(
'ENTITY_TOO_LARGE',
'Max upload size ('
+ maxEntitySize
+' byte) exceeded'
))
}
reject(error)
}
for(field in fields) {
fields[field] = fields[field][0]
}
for(file in files) {
files[file] = files[file][0]
delete files[file]['fieldName']
}
return resolve({
fields: fields,
files: files
})
})
} else if(request.headers['content-type'] == 'application/x-www-form-urlencoded') {
request.on('data', function(data) {
return resolve({
fields: FormParser.parseUrlEncodedFormData(data.toString('utf8'))
})
})
} else {
request.on('data', function(data) {
return resolve({
binary: data
})
})
}
} catch(error) {
reject(error)
}
})
}
}
FormParser.parseUrlEncodedFormData = function(str) {
tokens = str
.split('&')
.filter(function(el) {return el.length != 0})
var result = {}
tokens.forEach(function(token) {
const keyval = token
.split('=')
.filter(function(el) {return el.length != 0})
result[keyval[0]] = keyval[1]
})
return result
}
module.exports = FormParser |
version https://git-lfs.github.com/spec/v1
oid sha256:52d82d14979fb842dd727ad488ef9fe481bc76e402f2785dfcf7600caca03881
size 11493
|
version https://git-lfs.github.com/spec/v1
oid sha256:42ba4529cf3b71328176dddfde0c8becf7714b5a0615aa2e7288792f98ec1638
size 2717
|
var net = require('net');
var parsers = {
email: require('./parsers/Email')
};
function TwailerClient(config) {
this.config = config;
}
TwailerClient.prototype.subscribe = function (user, channels) {
var socket = net.connect(this.config.socket);
socket.write(JSON.stringify({
event: 'subscribe',
data: {
email: user,
channels: channels
}
}));
socket.end();
};
module.exports = exports = TwailerClient;
|
import $ from 'jquery';
import func from '../core/func';
import lists from '../core/lists';
import dom from '../core/dom';
export default class Style {
/**
* @method jQueryCSS
*
* [workaround] for old jQuery
* passing an array of style properties to .css()
* will result in an object of property-value pairs.
* (compability with version < 1.9)
*
* @private
* @param {jQuery} $obj
* @param {Array} propertyNames - An array of one or more CSS properties.
* @return {Object}
*/
jQueryCSS($obj, propertyNames) {
const result = {};
$.each(propertyNames, (idx, propertyName) => {
result[propertyName] = $obj.css(propertyName);
});
return result;
}
/**
* returns style object from node
*
* @param {jQuery} $node
* @return {Object}
*/
fromNode($node) {
const properties = ['font-family', 'font-size', 'text-align', 'list-style-type', 'line-height'];
const styleInfo = this.jQueryCSS($node, properties) || {};
const fontSize = $node[0].style.fontSize || styleInfo['font-size'];
styleInfo['font-size'] = parseInt(fontSize, 10);
styleInfo['font-size-unit'] = fontSize.match(/[a-z%]+$/);
return styleInfo;
}
/**
* paragraph level style
*
* @param {WrappedRange} rng
* @param {Object} styleInfo
*/
stylePara(rng, styleInfo) {
$.each(rng.nodes(dom.isPara, {
includeAncestor: true,
}), (idx, para) => {
$(para).css(styleInfo);
});
}
/**
* insert and returns styleNodes on range.
*
* @param {WrappedRange} rng
* @param {Object} [options] - options for styleNodes
* @param {String} [options.nodeName] - default: `SPAN`
* @param {Boolean} [options.expandClosestSibling] - default: `false`
* @param {Boolean} [options.onlyPartialContains] - default: `false`
* @return {Node[]}
*/
styleNodes(rng, options) {
rng = rng.splitText();
const nodeName = (options && options.nodeName) || 'SPAN';
const expandClosestSibling = !!(options && options.expandClosestSibling);
const onlyPartialContains = !!(options && options.onlyPartialContains);
if (rng.isCollapsed()) {
return [rng.insertNode(dom.create(nodeName))];
}
let pred = dom.makePredByNodeName(nodeName);
const nodes = rng.nodes(dom.isText, {
fullyContains: true,
}).map((text) => {
return dom.singleChildAncestor(text, pred) || dom.wrap(text, nodeName);
});
if (expandClosestSibling) {
if (onlyPartialContains) {
const nodesInRange = rng.nodes();
// compose with partial contains predication
pred = func.and(pred, (node) => {
return lists.contains(nodesInRange, node);
});
}
return nodes.map((node) => {
const siblings = dom.withClosestSiblings(node, pred);
const head = lists.head(siblings);
const tails = lists.tail(siblings);
$.each(tails, (idx, elem) => {
dom.appendChildNodes(head, elem.childNodes);
dom.remove(elem);
});
return lists.head(siblings);
});
} else {
return nodes;
}
}
/**
* get current style on cursor
*
* @param {WrappedRange} rng
* @return {Object} - object contains style properties.
*/
current(rng) {
const $cont = $(!dom.isElement(rng.sc) ? rng.sc.parentNode : rng.sc);
let styleInfo = this.fromNode($cont);
// document.queryCommandState for toggle state
// [workaround] prevent Firefox nsresult: "0x80004005 (NS_ERROR_FAILURE)"
try {
styleInfo = $.extend(styleInfo, {
'font-bold': document.queryCommandState('bold') ? 'bold' : 'normal',
'font-italic': document.queryCommandState('italic') ? 'italic' : 'normal',
'font-underline': document.queryCommandState('underline') ? 'underline' : 'normal',
'font-subscript': document.queryCommandState('subscript') ? 'subscript' : 'normal',
'font-superscript': document.queryCommandState('superscript') ? 'superscript' : 'normal',
'font-strikethrough': document.queryCommandState('strikethrough') ? 'strikethrough' : 'normal',
'font-family': document.queryCommandValue('fontname') || styleInfo['font-family'],
});
} catch (e) {
// eslint-disable-next-line
}
// list-style-type to list-style(unordered, ordered)
if (!rng.isOnList()) {
styleInfo['list-style'] = 'none';
} else {
const orderedTypes = ['circle', 'disc', 'disc-leading-zero', 'square'];
const isUnordered = orderedTypes.indexOf(styleInfo['list-style-type']) > -1;
styleInfo['list-style'] = isUnordered ? 'unordered' : 'ordered';
}
const para = dom.ancestor(rng.sc, dom.isPara);
if (para && para.style['line-height']) {
styleInfo['line-height'] = para.style.lineHeight;
} else {
const lineHeight = parseInt(styleInfo['line-height'], 10) / parseInt(styleInfo['font-size'], 10);
styleInfo['line-height'] = lineHeight.toFixed(1);
}
styleInfo.anchor = rng.isOnAnchor() && dom.ancestor(rng.sc, dom.isAnchor);
styleInfo.ancestors = dom.listAncestor(rng.sc, dom.isEditable);
styleInfo.range = rng;
return styleInfo;
}
}
|
"use strict"
const {promises: fs} = require("fs")
const path = require("path")
const {promisify} = require("util")
const marked = require("marked")
const rimraf = promisify(require("rimraf"))
const {execFileSync} = require("child_process")
const escapeRegExp = require("escape-string-regexp")
const HTMLMinifier = require("html-minifier")
const upstream = require("./_upstream")
const r = (file) => path.resolve(__dirname, "..", file)
// Minify our docs.
const htmlMinifierConfig = {
collapseBooleanAttributes: true,
collapseWhitespace: true,
conservativeCollapse: true,
continueOnParseError: true,
minifyCss: {
compatibility: "ie9",
},
minifyJs: true,
minifyUrls: true,
preserveLineBreaks: true,
removeAttributeQuotes: true,
removeCdatasectionsFromCdata: true,
removeComments: true,
removeCommentsFromCdata: true,
removeEmptyAttributes: true,
removeOptionalTags: true,
removeRedundantAttributes: true,
removeScriptTypeAttributes: true,
removeStyleLinkTypeAttributes: true,
useShortDoctype: true,
}
module.exports = generate
async function generate() {
return (await makeGenerator()).generate()
}
async function makeGenerator() {
await rimraf(r("dist"))
const [guides, methods, layout, pkg] = await Promise.all([
fs.readFile(r("docs/nav-guides.md"), "utf-8"),
fs.readFile(r("docs/nav-methods.md"), "utf-8"),
fs.readFile(r("docs/layout.html"), "utf-8"),
fs.readFile(r("package.json"), "utf-8"),
fs.mkdir(r("dist"), {recursive: true}),
])
const version = JSON.parse(pkg).version
// Make sure we have the latest archive.
execFileSync("git", [
"fetch", "--depth=1",
upstream.fetch.remote, "gh-pages",
])
// Set up archive directories
execFileSync("git", [
"checkout", `${upstream.fetch.remote}/gh-pages`,
"--", "archive",
])
await fs.rename(r("archive"), r("dist/archive"))
await fs.mkdir(r(`dist/archive/v${version}`), {recursive: true})
// Tell Git to ignore our changes - it's no longer there.
execFileSync("git", ["add", "archive"])
return new Generator({version, guides, methods, layout})
}
class Generator {
constructor(opts) {
this._version = opts.version
this._guides = opts.guides
this._methods = opts.methods
this._layout = opts.layout
}
compilePage(file, markdown) {
file = path.basename(file)
const link = new RegExp(
`([ \t]*)(- )(\\[.+?\\]\\(${escapeRegExp(file)}\\))`
)
const src = link.test(this._guides) ? this._guides : this._methods
let body = markdown
// fix pipes in code tags
body = body.replace(/`((?:\S| -> |, )+)(\|)(\S+)`/gim,
(match, a, b, c) =>
`<code>${(a + b + c).replace(/\|/g, "|")}</code>`
)
// inject menu
body = body.replace(
/(^# .+?(?:\r?\n){2,}?)(?:(-(?:.|\r|\n)+?)((?:\r?\n){2,})|)/m,
(match, title, nav) => {
if (!nav) {
return title + src.replace(link, "$1$2**$3**") + "\n\n"
}
return title + src.replace(link, (match, space, li, link) =>
`${space}${li}**${link}**\n${
nav.replace(/(^|\n)/g, `$1\t${space}`)
}`
) + "\n\n"
}
)
// fix links
body = body.replace(/(\]\([^\)]+)(\.md)/gim, (match, path, extension) =>
path + ((/http/).test(path) ? extension : ".html")
)
// Fix type signatures containing Array<...>
body = body.replace(/(\W)Array<([^/<]+?)>/gim, "$1Array<$2>")
const markedHtml = marked(body)
const title = body.match(/^#([^\n\r]+)/i) || []
let result = this._layout
result = result.replace(
/<title>Mithril\.js<\/title>/,
`<title>${title[1]} - Mithril.js</title>`
)
// update version
result = result.replace(/\[version\]/g, this._version)
// insert parsed HTML
result = result.replace(/\[body\]/, markedHtml)
// fix anchors
const anchorIds = new Map()
result = result.replace(
/<h([1-6]) id="([^"]+)">(.+?)<\/h\1>/gim,
(match, n, id, text) => {
let anchor = text.toLowerCase()
.replace(/<(\/?)code>/g, "")
.replace(/<a.*?>.+?<\/a>/g, "")
.replace(/[.`[\]\/()]|"/g, "")
.replace(/\s/g, "-");
const anchorId = anchorIds.get(anchor)
anchorIds.set(anchor, anchorId != null ? anchorId + 1 : 0)
if (anchorId != null) anchor += anchorId
return `<h${n} id="${anchor}">` +
`<a href="#${anchor}">${text}</a>` +
`</h${n}>`
}
)
return result
}
async eachTarget(relative, init) {
await Promise.all([
init(r(`dist/archive/v${this._version}/${relative}`)),
init(r(`dist/${relative}`)),
])
}
async generateSingle(file) {
const relative = path.relative(r("docs"), file)
const archived = (target, init) =>
this.eachTarget(target, async (dest) => {
await fs.mkdir(path.dirname(dest), {recursive: true})
await init(dest)
})
if (!(/\.(md|html)$/).test(file)) {
await archived(relative, (dest) => fs.copyFile(file, dest))
console.log(`Copied: ${relative}`)
}
else {
let html = await fs.readFile(file, "utf-8")
if (file.endsWith(".md")) html = this.compilePage(file, html)
const minified = HTMLMinifier.minify(html, htmlMinifierConfig)
await archived(
relative.replace(/\.md$/, ".html"),
(dest) => fs.writeFile(dest, minified)
)
console.log(`Compiled: ${relative}`)
}
}
async generateRec(file) {
let files
try {
files = await fs.readdir(file)
}
catch (e) {
if (e.code !== "ENOTDIR") throw e
return this.generateSingle(file)
}
const devOnly = /^layout\.html$|^archive$|^nav-/
// Don't care about the return value here.
await Promise.all(
files
.filter((f) => !devOnly.test(f))
.map((f) => this.generateRec(path.join(file, f)))
)
}
async generate() {
await this.generateRec(r("docs"))
// Just ensure it exists.
await (await fs.open(r("dist/.nojekyll"), "a")).close()
}
}
/* eslint-disable global-require */
if (require.main === module) {
require("./_command")({
exec: generate,
async watch() {
let timeout, genPromise
function updateGenerator() {
if (timeout == null) return
clearTimeout(timeout)
genPromise = new Promise((resolve) => {
timeout = setTimeout(function() {
timeout = null
resolve(makeGenerator().then((g) => g.generate()))
}, 100)
})
}
async function updateFile(file) {
if ((/^layout\.html$|^archive$|^nav-/).test(file)) {
updateGenerator()
}
(await genPromise).generateSingle(file)
}
async function removeFile(file) {
(await genPromise).eachTarget(file, (dest) => fs.unlink(dest))
}
require("chokidar").watch(r("docs"), {
ignored: ["archive/**", /(^|\\|\/)\../],
// This depends on `layout`/etc. existing first.
ignoreInitial: true,
awaitWriteFinish: true,
})
.on("ready", updateGenerator)
.on("add", updateFile)
.on("change", updateFile)
.on("unlink", removeFile)
.on("unlinkDir", removeFile)
},
})
}
|
'use strict';
var assert = require('assert');
var base = require('engine-base');
var Engines = require('..');
var engines;
describe('engines get', function() {
beforeEach(function() {
engines = new Engines();
});
describe('.getEngine()', function() {
it('should get the given engine from the `cache`.', function() {
engines.setEngine('a', {render: function() {} });
engines.setEngine('b', {render: function() {} });
engines.setEngine('c', {render: function() {} });
engines.setEngine('d', {render: function() {} });
engines.getEngine('a').hasOwnProperty('render');
engines.getEngine('b').hasOwnProperty('render');
engines.getEngine('c').hasOwnProperty('render');
engines.getEngine('d').hasOwnProperty('render');
});
it('should return undefined when a falsey value is passed', function() {
assert.equal(engines.getEngine(), undefined);
});
it('should use a default if defined:', function() {
engines.options.defaultEngine = '*';
engines.setEngine('*', require('engine-base'));
var engine = engines.getEngine('tmpl');
assert.equal(typeof engine.render, 'function');
});
it('should use a default as a function if defined:', function() {
engines.options.defaultEngine = require('engine-base');
var engine = engines.getEngine('tmpl');
assert.equal(typeof engine.render, 'function');
});
it('should render templates', function(cb) {
var base = require('engine-base');
engines.setEngine('tmpl', base);
var engine = engines.getEngine('tmpl');
engine.render('<%= name %>', {name: 'Jon Schlinkert'}, function(err, content) {
if (err) return cb(err);
assert.equal(content, 'Jon Schlinkert');
cb();
});
});
});
});
|
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
const builder = require("botbuilder");
const botbuilder_instrumentation_1 = require("botbuilder-instrumentation");
const config = require('../../config');
var model;
var recognizer;
var intents;
var _lib = new builder.Library('feedbackBot');
_lib.localePath('./bots/feedback/locale/');
_lib.dialog('/', [
function (session, results, next) {
botbuilder_instrumentation_1.setCurrentBotName(session, _lib.name);
session.userData["CLAUDIUS"] = `I SET THIS - ${_lib.name}`;
session.send(localize(session, "feedback-welcome"));
}
]);
_lib.dialog('feedback', [
function (session, results) {
session.send(localize(session, 'feedback-message'));
}
]);
_lib.dialog('info', [
function (session, results) {
session.send(localize(session, "feedback-details"));
}
]);
_lib.dialog('goback', [
function (session, results) {
session.endDialog(localize(session, "feedback-goback"));
}
]);
function createLibrary() {
return _lib;
}
exports.createLibrary = createLibrary;
function getName(session) {
return localize(session, "feedback-name");
}
exports.getName = getName;
function welcomeMessage(session) {
return localize(session, "feedback-welcome");
}
function localize(session, text) {
return session.localizer.gettext(session.preferredLocale(), text);
}
exports.localize = localize;
function initialize(locale) {
model = config.get('LUIS_modelBaseURL') + "?id=" + config.get('LUIS_applicationId_' + locale) + "&subscription-key=" + config.get('LUIS_subscriptionKey') + "&q=";
intents = new builder.IntentDialog();
intents.onDefault("feedbackBot:/");
intents.matches(/^(feedback|retroalimentación)/i, "feedbackBot:feedback");
intents.matches('info', "feedbackBot:info");
intents.matches('goback', "feedbackBot:goback");
return intents;
}
exports.initialize = initialize;
;
//# sourceMappingURL=index.js.map |
'use strict'
// meta ------------------------------------------------------------------------
const name = 'lair'
const version = '0.0.1'
const author = 'Jacob Blakely (codekirei)'
const license = 'MIT'
// links -----------------------------------------------------------------------
const homepage = 'https://github.com/lair-player/lair#readme'
const bugs = {
url: 'https://github.com/lair-player/lair/issues',
}
const repository = {
type: 'git',
url: 'git+https://github.com/lair-player/lair.git',
}
// scripts ---------------------------------------------------------------------
const scripts = {
// build ---------------------------------------------------------------------
'build': 'electron .',
'build:package': 'node scripts/build-package.js',
// clean ---------------------------------------------------------------------
// lint ----------------------------------------------------------------------
// serve ---------------------------------------------------------------------
// test ----------------------------------------------------------------------
}
// deps ------------------------------------------------------------------------
const dependencies = {
}
const devDependencies = {
// electron ------------------------------------------------------------------
'electron-prebuilt': '0.37.8',
// lint ----------------------------------------------------------------------
'eslint': '2.9.0',
'eslint-config-kirei-react': '0.2.4',
}
// combine and export ----------------------------------------------------------
module.exports = {
name,
version,
private: true,
author,
license,
repository,
bugs,
homepage,
scripts,
dependencies,
devDependencies,
}
|
var save_method; //for save method string
var table;
$(document).ready(function() {
$(".select2").select2();
$("#jenis_barang").change(function(){
var id = $(this).val();
if(id == 3){
$("#inv").show();
}else{
$("#inv").hide();
}
})
.change();
//datatables
$('.input-append.date')
.datepicker({
todayHighlight: true,
autoclose: true,
format: "dd-mm-yyyy"
});
table = $('#table').DataTable({
"processing": true, //Feature control the processing indicator.
"serverSide": true, //Feature control DataTables' server-side processing mode.
"order": [], //Initial no order.
// Load data for the table's content from an Ajax source
"ajax": {
"url": "/gsm/master/barang/ajax_list",
"type": "POST"
},
//Set column definition initialisation properties.
"columnDefs": [
{
"targets": [-1, 0, 1], //last column
"orderable": false, //set not orderable
},
{ "sClass": "text-center", "aTargets": [-1] }
],
});
table_inv = $('#table_inv').DataTable({
"processing": true, //Feature control the processing indicator.
"serverSide": true, //Feature control DataTables' server-side processing mode.
"order": [], //Initial no order.
// Load data for the table's content from an Ajax source
"ajax": {
"url": "/gsm/master/barang/list_inv",
"type": "POST"
},
//Set column definition initialisation properties.
"columnDefs": [
{
"targets": [-1, 0, 1, 4], //last column
"orderable": false, //set not orderable
},
{ "sClass": "text-center", "aTargets": [-1] }
],
});
$('#btnTambahSatuan').on('click', function(){
$(document).find("select.select2").select2();
$.ajax({
url:"/gsm/master/barang/get_satuan/",
success: function(response){
$("#satuan-lain").append(response);
},
dataType:"html"
});
});
//set input/textarea/select event when change value, remove class error and remove text help block
$("input").change(function(){
$(this).parent().parent().removeClass('has-error');
$(this).next().empty();
});
$("select").change(function(){
$(this).parent().parent().removeClass('has-error');
$(this).next().empty();
});
$("#kode").change(function() {
var kode = $(this).val();
})
.change();
});
//Ajax Crud
function add_user()
{
$('#form')[0].reset(); // reset form on modals
//$("#attachment").hide();
//$("#file").show();
$('#is_update').val('0');
$("#satuan-exist").empty();
$("#satuan-lain").empty();
$('.form-group').removeClass('has-error'); // clear error class
$("#btnTambahSatuan").trigger({ type: "click" });
$('.help-block').empty(); // clear error string
$('#modal_form').modal('show'); // show bootstrap modal
$('.modal-title').text('Tambah Data Barang'); // Set Title to Bootstrap modal title
}
function add_inv()
{
$('#form_inv')[0].reset(); // reset form on modals
//$("#attachment").hide();
//$("#file").show();
//$('#is_update').val('0');
//$("#satuan-exist").empty();
//$("#satuan-lain").empty();
//$('.form-group').removeClass('has-error'); // clear error class
//$("#btnTambahSatuan").trigger({ type: "click" });
//$('.help-block').empty(); // clear error string
$('#modal_inv').modal('show'); // show bootstrap modal
//$('.modal-title').text('Tambah Data Barang Inventaris'); // Set Title to Bootstrap modal title
}
function edit_user(id)
{
save_method = 'update';
$("#satuan-exist").empty();
$("#satuan-lain").empty();
$('#form')[0].reset(); // reset form on modals
$('#is_update').val('1');
$('.form-group').removeClass('has-error'); // clear error class
$('.help-block').empty(); // clear error string
//Ajax Load data from ajax
$.ajax({
url : "barang/ajax_edit/" + id,
type: "GET",
dataType: "JSON",
success: function(data)
{
//var satuan = data.satuan.split(",");
$('[name="id"]').val(data.data.id);
$('[name="kode"]').val(data.data.kode);
$('[name="title"]').val(data.data.title);
$('[name="alias"]').val(data.data.alias);
$('[name="merk"]').val(data.data.merk);
$('[name="catatan"]').text(data.data.catatan);
$('[name="jenis_barang_id"]').select2().select2('val',data.data.jenis_barang_id);
//$('[name="satuan_id"]').select2().select2('val',data.data.satuan_id);
$('[name="satuan"]').select2().select2('val',data.data.satuan);
$('[name="satuan_laporan"]').select2().select2('val',data.data.satuan_laporan);
/*
if(data.data.attachment != ''){
$("#attachment").html(data.data.attachment+"<button onclick='removeFile()' type='button' class='btn btn-danger btn-small' title='Remove File'><i class='fa fa-remove'></i></button>");
$("#attachment").show();
}else{
$("#file").show();
}
*/
if(data.data.jenis_barang_id == 3){
$("#inv").show();
$('[name="tgl"]').val(data.inv.tgl);
$('[name="harga"]').val(data.inv.harga);
$('[name="penyusutan"]').val(data.inv.penyusutan);
$('[name="jenis_barang_inventaris_id"]').select2().select2('val',data.inv.jenis_barang_inventaris_id);
}else{
$("#inv").hide();
}
if(data.data.photo != ''){
$("#photo").attr("src", "http://"+window.location.host+"/gsm/uploads/barang/"+data.data.id+"/"+data.data.photo);
}else{
$("#photo").attr("src", "http://"+window.location.host+"/gsm/assets/assets/images/no-image-mid.png");
}
drawSatuan(data.data.id);
//drawSatuan(satuan);
$('#modal_form').modal('show'); // show bootstrap modal when complete loaded
$('.modal-title').text('Ubah Data Barang'); // Set title to Bootstrap modal title
},
error: function (jqXHR, textStatus, errorThrown)
{
alert('Error get data from ajax');
}
});
}
function edit_inv(id)
{
save_method = 'update';
$('#form_inv')[0].reset(); // reset form on modals
$('#is_update_inv').val('1');
$('.form-group').removeClass('has-error'); // clear error class
$('.help-block').empty(); // clear error string
//Ajax Load data from ajax
$.ajax({
url : "barang/edit_inv/" + id,
type: "GET",
dataType: "JSON",
success: function(data)
{
//var satuan = data.satuan.split(",");
$('[name="id"]').val(data.id);
$('[name="kode"]').val(data.kode);
$('[name="title"]').val(data.title);
$('[name="alias"]').val(data.alias);
$('[name="brand"]').val(data.brand);
$('[name="lokasi"]').val(data.lokasi);
$('[name="tgl_beli"]').val(data.tgl_beli);
$('[name="harga_beli"]').val(data.harga_beli);
$('[name="akumulasi"]').val(data.akumulasi);
$('[name="beban_tahun_ini"]').val(data.beban_tahun_ini);
$('[name="beban_perbulan"]').val(data.beban_perbulan);
$('[name="nilai_residu"]').val(data.nilai_residu);
$('[name="nilai_buku"]').val(data.nilai_buku);
$('[name="tarif_penyusutan"]').val(data.tarif_penyusutan);
$('[name="umur_ekonomis"]').val(data.umur_ekonomis);
$('[name="terhitung_tanggal"]').val(data.terhitung_tanggal);
$('[name="catatan"]').text(data.catatan);
$('[name="jenis_inventaris_id"]').select2().select2('val',data.jenis_inventaris_id);
/*
if(data.attachment != ''){
$("#attachment").html(data.attachment+"<button onclick='removeFile()' type='button' class='btn btn-danger btn-small' title='Remove File'><i class='fa fa-remove'></i></button>");
$("#attachment").show();
}else{
$("#file").show();
}
*/
if(data.photo != ''){
$("#photo").attr("src", "http://"+window.location.host+"/gsm/uploads/barang/"+data.id+"/"+data.photo);
}else{
$("#photo").attr("src", "http://"+window.location.host+"/gsm/assets/assets/images/no-image-mid.png");
}
$('#modal_inv').modal('show'); // show bootstrap modal when complete loaded
$('.modal-title').text('Ubah Data Barang'); // Set title to Bootstrap modal title
},
error: function (jqXHR, textStatus, errorThrown)
{
alert('Error get data from ajax');
}
});
}
function drawSatuan(data) {
$("#satuan-exist").load('barang/loadsatuanexist/'+data);
}
/*
function drawSatuan(data) {
for (var i = 0; i < data.length; i++) {
$("#satuan-exist").append("<input type='hidden' class='form-control' value='"+data[i]+"' name='satuan[]' readonly><input type='text' class='form-control' value='"+getSatuanTitle(data[i])+"' readonly><br/>");
}
} */
function getSatuanTitle(id)
{
var r ="";
$.ajax({
url : "barang/get_satuan_title/" + id,
type: "GET",
async: false,
dataType: "JSON",
success: function(data)
{
r = data.value;
}
});
return r;
}
function reload_table()
{
table.ajax.reload(null,false); //reload datatable ajax
}
function save()
{
$('#btnSave').text('saving...'); //change button text
$('#btnSave').attr('disabled',true); //set button disable
var url;
if(save_method == 'add') {
url = "barang/ajax_add";
} else {
url = "barang/ajax_update";
}
// ajax adding data to database
$.ajax({
url : url,
type: "POST",
data: $('#form').serialize(),
dataType: "JSON",
success: function(data)
{
if(data.status) //if success close modal and reload ajax table
{
$('#modal_form').modal('hide');
reload_table();
}
else
{
for (var i = 0; i < data.inputerror.length; i++)
{
$('[name="'+data.inputerror[i]+'"]').parent().parent().addClass('has-error'); //select parent twice to select div form-group class and add has-error class
$('[name="'+data.inputerror[i]+'"]').next().text(data.error_string[i]); //select span help-block class set text error string
}
}
$('#btnSave').text('save'); //change button text
$('#btnSave').attr('disabled',false); //set button enable
},
error: function (jqXHR, textStatus, errorThrown)
{
alert('Error adding / update data');
$('#btnSave').text('save'); //change button text
$('#btnSave').attr('disabled',false); //set button enable
}
});
}
function delete_user(id)
{
if(confirm('Are you sure delete this data?'))
{
// ajax delete data to database
$.ajax({
url : "barang/ajax_delete/"+id,
type: "POST",
dataType: "JSON",
success: function(data)
{
//if success reload ajax table
$('#modal_form').modal('hide');
reload_table();
},
error: function (jqXHR, textStatus, errorThrown)
{
alert('Error deleting data');
}
});
}
}
function delete_inv(id)
{
if(confirm('Are you sure delete this data?'))
{
// ajax delete data to database
$.ajax({
url : "barang/delete_inv/"+id,
type: "POST",
dataType: "JSON",
success: function(data)
{
//if success reload ajax table
$('#modal_form').modal('hide');
location.reload();
},
error: function (jqXHR, textStatus, errorThrown)
{
alert('Error deleting data');
}
});
}
} |
import { fromJS } from 'immutable';
import {
SEARCH_PRODUCTS,
SEARCH_PRODUCTS_SUCCESS,
GET_PRODUCTS,
GET_PRODUCTS_SUCCESS,
GET_PRODUCTS_ERROR,
REMOVE_ERROR,
SET_QUERY,
SET_AUTOCOMPLETE,
PAGE_FORWARD,
PAGE_BACKWARD,
} from './constants';
export function setQuery(query) {
return {
type: SET_QUERY,
payload: { query },
};
}
export function setAutocomplete(items) {
return {
type: SET_AUTOCOMPLETE,
payload: fromJS({ items }),
};
}
export function searchProducts(query) {
return {
type: SEARCH_PRODUCTS,
payload: fromJS({ query }),
};
}
export function searchProductsSuccess(filteredProducts) {
return {
type: SEARCH_PRODUCTS_SUCCESS,
payload: fromJS({ filteredProducts }),
};
}
export function getProducts() {
return {
type: GET_PRODUCTS,
};
}
export function getProductsSuccess(products) {
return {
type: GET_PRODUCTS_SUCCESS,
payload: fromJS({ products }),
};
}
export function getProductsError(error) {
return {
type: GET_PRODUCTS_ERROR,
payload: fromJS({ error }),
};
}
export function removeError() {
return {
type: REMOVE_ERROR,
};
}
export function pageForward() {
return {
type: PAGE_FORWARD,
};
}
export function pageBackward() {
return {
type: PAGE_BACKWARD,
};
}
|
var searchData=
[
['index_5fof_5fshortest_5fto_5fpoint',['index_of_shortest_to_point',['../track__objects__client_8cpp.html#ab211511420b6766585fd914838c8bf10',1,'track_objects_client.cpp']]],
['index_5fof_5fshortest_5fto_5fsensor',['index_of_shortest_to_sensor',['../track__objects__client_8cpp.html#af1132126f5252aef7858889b02e5e49b',1,'track_objects_client.cpp']]],
['is_5fin_5ftracking_5farea',['is_in_tracking_area',['../class_scanner__gestures.html#a8239d96119dc8c87737774dcb786d5d4',1,'Scanner_gestures']]]
];
|
'use strict';
require('mocha');
const assert = require('assert');
const auth = require('./support/auth');
const GitHub = require('..');
let github;
describe('.put', function() {
this.timeout(5000);
beforeEach(() => (github = new GitHub(auth)));
describe('promise', function() {
it('should subscribe to repository', function() {
let owner = 'jonschlinkert';
let repo = 'github-base';
return github.put(`/repos/${owner}/${repo}/subscription`, { subscribed: true })
.then(function(res) {
assert(res.body.subscribed);
assert(!res.body.ignored);
});
});
it('should set content-length to zero (star a gist, status 204)', function() {
let id = '32a6fe359168ecc6f76a';
return github.put(`/gists/${id}/star`)
.then(res => {
assert.strictEqual(res.raw.toString(), '');
assert.strictEqual(res.body.toString(), '');
assert.strictEqual(res.statusCode, 204);
});
});
});
});
|
cordova.define("cordova-plugin-gctouch-id.GCTouchID", function(require, exports, module) {
var cordova = require('cordova');
function GCTouchID() { }
GCTouchID.prototype.isAvailable = function (onSuccess, onFail) {
cordova.exec(onSuccess, onFail, 'GCTouchID', 'isAvailable');
};
GCTouchID.prototype.authWithTouchID = function(onSuccess, onFail, data) {
cordova.exec(onSuccess, onFail, 'GCTouchID', 'authWithTouchID', [data]);
};
GCTouchID.prototype.setPassword = function(onSuccess, onFail, data) {
cordova.exec(onSuccess, onFail, 'GCTouchID', 'setPassword', [data]);
};
// Register the plugin
var gctouchid = new GCTouchID();
module.exports = gctouchid;
});
|
/***************************
*
* Extra methods
*
**************************/
var cst = require('../../constants.js');
var Common = require('../Common.js');
var UX = require('./CliUx');
var chalk = require('chalk');
var async = require('async');
var path = require('path');
var fs = require('fs');
module.exports = function(CLI) {
/**
* Get version of the daemonized PM2
* @method getVersion
* @callback cb
*/
CLI.prototype.getVersion = function(cb) {
var that = this;
that.Client.executeRemote('getVersion', {}, function(err) {
return cb ? cb.apply(null, arguments) : that.exitCli(cst.SUCCESS_EXIT);
});
};
/**
* Create PM2 memory snapshot
* @method getVersion
* @callback cb
*/
CLI.prototype.snapshotPM2 = function(cb) {
var that = this;
var moment = require('moment');
var file = path.join(process.cwd(), moment().format('dd-HH:mm:ss') + '.heapsnapshot');
that.Client.executeRemote('snapshotPM2', {
pwd : file
}, function(err) {
if (err) {
console.error(err);
return that.exitCli(1);
}
console.log('Heapdump in %s', file);
return cb ? cb.apply(null, arguments) : that.exitCli(cst.SUCCESS_EXIT);
});
};
/**
* Create PM2 memory snapshot
* @method getVersion
* @callback cb
*/
CLI.prototype.profilePM2 = function(command, cb) {
var that = this;
var moment = require('moment');
var file = path.join(process.cwd(), moment().format('dd-HH:mm:ss') + '.cpuprofile');
if (command == 'start') {
that.Client.executeRemote('profileStart', {
}, function(err) {
if (err) {
console.error(err);
return that.exitCli(1);
}
console.log('CPU profiling started, type pm2 profile stop once finished');
return cb ? cb.apply(null, arguments) : that.exitCli(cst.SUCCESS_EXIT);
});
}
else if (command == 'stop') {
that.Client.executeRemote('profileStop', {
pwd : file
}, function(err) {
if (err) {
console.error(err);
return that.exitCli(1);
}
console.log('CPU profile in %s', file);
return cb ? cb.apply(null, arguments) : that.exitCli(cst.SUCCESS_EXIT);
});
}
};
/**
* Description
* @method sendDataToProcessId
*/
CLI.prototype.sendDataToProcessId = function(proc_id, packet, cb) {
var that = this;
packet.id = proc_id;
that.Client.executeRemote('sendDataToProcessId', packet, function(err, res) {
if (err) {
Common.printError(err);
return cb ? cb(Common.retErr(err)) : that.exitCli(cst.ERROR_EXIT);
}
Common.printOut('successfully sent data to process');
return cb ? cb(null, res) : that.speedList();
});
};
/**
* Used for custom actions, allows to trigger function inside an app
* To expose a function you need to use keymetrics/pmx
*
* @method msgProcess
* @param {Object} opts
* @param {String} id process id
* @param {String} action_name function name to trigger
* @param {Object} [opts.opts] object passed as first arg of the function
* @param {String} [uuid] optionnal unique identifier when logs are emitted
*
* @todo allow to trigger custom function from CLI
*/
CLI.prototype.msgProcess = function(opts, cb) {
var that = this;
that.Client.executeRemote('msgProcess', opts, cb);
};
/**
* Description
* @method sendSignalToProcessName
* @param {} signal
* @param {} process_name
* @return
*/
CLI.prototype.sendSignalToProcessName = function(signal, process_name, cb) {
var that = this;
that.Client.executeRemote('sendSignalToProcessName', {
signal : signal,
process_name : process_name
}, function(err, list) {
if (err) {
Common.printError(err);
return cb ? cb(Common.retErr(err)) : that.exitCli(cst.ERROR_EXIT);
}
Common.printOut('successfully sent signal %s to process name %s', signal, process_name);
return cb ? cb(null, list) : that.speedList();
});
};
/**
* Description
* @method sendSignalToProcessId
* @param {} signal
* @param {} process_id
* @return
*/
CLI.prototype.sendSignalToProcessId = function(signal, process_id, cb) {
var that = this;
that.Client.executeRemote('sendSignalToProcessId', {
signal : signal,
process_id : process_id
}, function(err, list) {
if (err) {
Common.printError(err);
return cb ? cb(Common.retErr(err)) : that.exitCli(cst.ERROR_EXIT);
}
Common.printOut('successfully sent signal %s to process id %s', signal, process_id);
return cb ? cb(null, list) : that.speedList();
});
};
/**
* Launch API interface
* @method web
* @return
*/
CLI.prototype.web = function(cb) {
var that = this;
var filepath = path.resolve(path.dirname(module.filename), '../HttpInterface.js');
that.start({
script : filepath,
name : 'pm2-http-interface',
execMode : 'fork_mode'
}, function(err, proc) {
if (err) {
Common.printError(cst.PREFIX_MSG_ERR + 'Error while launching application', err.stack || err);
return cb ? cb(Common.retErr(err)) : that.speedList();
}
Common.printOut(cst.PREFIX_MSG + 'Process launched');
return cb ? cb(null, proc) : that.speedList();
});
};
/**
* Ping daemon - if PM2 daemon not launched, it will launch it
* @method ping
*/
CLI.prototype.ping = function(cb) {
var that = this;
that.Client.executeRemote('ping', {}, function(err, res) {
if (err) {
Common.printError(err);
return cb ? cb(new Error(err)) : that.exitCli(cst.ERROR_EXIT);
}
Common.printOut(res);
return cb ? cb(null, res) : that.exitCli(cst.SUCCESS_EXIT);
});
};
/**
* Execute remote command
*/
CLI.prototype.remote = function(command, opts, cb) {
var that = this;
that[command](opts.name, function(err_cmd, ret) {
if (err_cmd)
console.error(err_cmd);
console.log('Command %s finished', command);
return cb(err_cmd, ret);
});
};
/**
* This remote method allows to pass multiple arguments
* to PM2
* It is used for the new scoped PM2 action system
*/
CLI.prototype.remoteV2 = function(command, opts, cb) {
var that = this;
if (that[command].length == 1)
return that[command](cb);
opts.args.push(cb);
return that[command].apply(this, opts.args);
};
/**
* Description
* @method generateSample
* @param {} name
* @return
*/
CLI.prototype.generateSample = function() {
var that = this;
var templatePath = path.join(cst.TEMPLATE_FOLDER, cst.APP_CONF_TPL);
var sample = fs.readFileSync(templatePath);
var dt = sample.toString();
var f_name = 'ecosystem.json';
var pwd = process.env.PWD || process.cwd();
try {
fs.writeFileSync(path.join(pwd, f_name), dt);
} catch (e) {
console.error(e.stack || e);
}
Common.printOut('File %s generated', path.join(pwd, f_name));
that.exitCli(cst.SUCCESS_EXIT);
};
};
|
var fs = require('fs');
var app = require('app');
var ipc = require('ipc');
var Menu = require('menu');
var BrowserWindow = require('browser-window');
var appMenu = require('./menu_config/app_menu');
require('crash-reporter').start();
var debug = process.env.NODE_ENV === 'development',
mainWindow;
app.on('window-all-closed', function() {
if (process.platform != 'darwin') {
app.quit();
}
});
app.on('ready', function() {
//instantiate menu from template
menu = Menu.buildFromTemplate(appMenu);
Menu.setApplicationMenu(menu);
mainWindow = new BrowserWindow({ width: 1245,
height: 800,
'min-width': 864});
if (debug) {
mainWindow.loadUrl('file://' + __dirname + '/app/index.dev.html');
mainWindow.openDevTools();
} else {
mainWindow.loadUrl('file://' + __dirname + '/app/index.prod.html');
}
mainWindow.on('closed', function() {
mainWindow = null;
});
});
// listen for event to save editor text in filesystem
ipc.on('save-editor-text', function(event, arg){
fs.writeFile(`${app.getPath('userData')}/${arg.language}.txt`, arg.text, function(err){
if(err) {
console.log("Error writing into file");
}
});
});
// listen for event to load editor text in filesystem
ipc.on('load-editor-text', function(event, arg){
fs.readFile(`${app.getPath('userData')}/${arg.language}.txt`, 'utf8', function(err, data){
if(err) {
console.log("Error writing into file");
}
mainWindow.webContents.send('loaded-editor-text', data)
});
}); |
module.exports = {
"env": {
"browser": true,
"commonjs": true,
"es6": true,
"node": true
},
"extends": "eslint:recommended",
"parserOptions": {
"sourceType": "module",
"ecmaVersion": 8,
"ecmaFeatures": {
"experimentalObjectRestSpread": true,
"jsx": true
}
},
"rules": {
"no-console": 0,
"disallowMultipleVarDecl": 0,
"maximumLineLength": 0,
"linebreak-style": [
"error",
"windows"
],
"quotes": [
"error",
"single"
],
"semi": [
"error",
"always"
]
}
}; |
version https://git-lfs.github.com/spec/v1
oid sha256:50701f9e342b487422a669a4d9941b05cfceb87449f4168c828e8acaa10c31c5
size 23491
|
var tweb = angular.module('tweb', ['ngRoute', 'ngAnimate', 'chart.js', 'ui.gravatar', 'ngCookies']);
tweb.config(['$routeProvider',
function($routeProvider) {
$routeProvider.
when('/', {
templateUrl: 'res/partials/home.html',
controller: 'home'
}).
when('/login', {
templateUrl: 'res/partials/login.html',
controller: 'login'
}).
when('/polls', {
templateUrl: 'res/partials/polls.html',
controller: 'polls'
}).
when('/join', {
templateUrl: 'res/partials/join.html',
controller: 'join'
}).
when('/register', {
templateUrl: 'res/partials/register.html',
controller: 'register'
}).
when('/polldetails', {
templateUrl: 'res/partials/polldetails.html',
controller: 'polldetails'
}).
when('/polljoin', {
templateUrl: 'res/partials/polljoin.html',
controller: 'polljoin'
}).
when('/pollspeaker', {
templateUrl: 'res/partials/pollspeaker.html',
controller: 'pollspeaker'
}).
when('/pollaudience', {
templateUrl: 'res/partials/pollaudience.html',
controller: 'pollaudience'
}).
when('/pollview', {
templateUrl: 'res/partials/pollview.html',
controller: 'pollview'
}).
when('/changepassword', {
templateUrl: 'res/partials/changepassword.html',
controller: 'changepassword'
}).
when('/participation', {
templateUrl: 'res/partials/participation.html',
controller: 'participation'
}).
otherwise({
redirectTo: '/login'
});
}]);
/*
spp: Reference to the shared ServerPushPoll factory
session: User session obtained from the server
pollIdToJoin: id of the poll you want to join
cbAsSpeaker: callback to execute when the server decides to make you join as a speaker
cbAsAudience: callback to execute when the server decides to make you join as an audience member
*/
function socketIOConnectToServer(spp, session, pollIdToJoin, cbAsSpeaker, cbAsAudience) {
spp.connect(null, null, session, pollIdToJoin,
cbAsSpeaker, cbAsAudience);
}
|
// This file is part of Indico.
// Copyright (C) 2002 - 2022 CERN
//
// Indico is free software; you can redistribute it and/or
// modify it under the terms of the MIT License; see the
// LICENSE file for more details.
_.mixin({
move: function(array, fromIndex, toIndex) {
array.splice(toIndex, 0, array.splice(fromIndex, 1)[0]);
return array;
},
});
// from phpjs.org - MIT/GPL licensed
function strcmp(str1, str2) {
// http://kevin.vanzonneveld.net
// + original by: Waldo Malqui Silva
// + input by: Steve Hilder
// + improved by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
// + revised by: gorthaur
// * example 1: strcmp( 'waldo', 'owald' );
// * returns 1: 1
// * example 2: strcmp( 'owald', 'waldo' );
// * returns 2: -1
return str1 == str2 ? 0 : str1 > str2 ? 1 : -1;
}
// from phpjs.org - MIT/GPL licensed
function strnatcmp(f_string1, f_string2, f_version) {
// http://kevin.vanzonneveld.net
// + original by: Martijn Wieringa
// + namespaced by: Michael White (http://getsprink.com)
// + tweaked by: Jack
// + bugfixed by: Onno Marsman
// - depends on: strcmp
// % note: Added f_version argument against code guidelines, because it's so neat
// * example 1: strnatcmp('Price 12.9', 'Price 12.15');
// * returns 1: 1
// * example 2: strnatcmp('Price 12.09', 'Price 12.15');
// * returns 2: -1
// * example 3: strnatcmp('Price 12.90', 'Price 12.15');
// * returns 3: 1
// * example 4: strnatcmp('Version 12.9', 'Version 12.15', true);
// * returns 4: -6
// * example 5: strnatcmp('Version 12.15', 'Version 12.9', true);
// * returns 5: 6
var i = 0;
if (f_version == undefined) {
f_version = false;
}
var __strnatcmp_split = function(f_string) {
var result = [];
var buffer = '';
var chr = '';
var i = 0,
f_stringl = 0;
var text = true;
f_stringl = f_string.length;
for (i = 0; i < f_stringl; i++) {
chr = f_string.substring(i, i + 1);
if (chr.match(/\d/)) {
if (text) {
if (buffer.length > 0) {
result[result.length] = buffer;
buffer = '';
}
text = false;
}
buffer += chr;
} else if (
text == false &&
chr == '.' &&
i < f_string.length - 1 &&
f_string.substring(i + 1, i + 2).match(/\d/)
) {
result[result.length] = buffer;
buffer = '';
} else {
if (text == false) {
if (buffer.length > 0) {
result[result.length] = parseInt(buffer, 10);
buffer = '';
}
text = true;
}
buffer += chr;
}
}
if (buffer.length > 0) {
if (text) {
result[result.length] = buffer;
} else {
result[result.length] = parseInt(buffer, 10);
}
}
return result;
};
var array1 = __strnatcmp_split(f_string1 + '');
var array2 = __strnatcmp_split(f_string2 + '');
var len = array1.length;
var text = true;
var result = -1;
var r = 0;
if (len > array2.length) {
len = array2.length;
result = 1;
}
for (i = 0; i < len; i++) {
if (isNaN(array1[i])) {
if (isNaN(array2[i])) {
text = true;
if ((r = this.strcmp(array1[i], array2[i])) != 0) {
return r;
}
} else if (text) {
return 1;
} else {
return -1;
}
} else if (isNaN(array2[i])) {
if (text) {
return -1;
} else {
return 1;
}
} else {
if (text || f_version) {
if ((r = array1[i] - array2[i]) != 0) {
return r;
}
} else {
if ((r = this.strcmp(array1[i].toString(), array2[i].toString())) != 0) {
return r;
}
}
text = false;
}
}
return result;
}
|
export const port = process.env.PORT || 3000;
export const host = process.env.WEBSITE_HOSTNAME || `localhost:${port}`;
export const databaseUrl = process.env.DATABASE_URL || 'postgresql://demo:Lqk62xg6TBm5UhfR@demo.ctbl5itzitm4.us-east-1.rds.amazonaws.com:5432/membership01';
export const analytics = {
// https://analytics.google.com/
google: { trackingId: process.env.GOOGLE_TRACKING_ID || 'UA-XXXXX-X' },
};
export const auth = {
jwt: { secret: process.env.JWT_SECRET || 'React Starter Kit' },
// https://developers.facebook.com/
facebook: {
id: process.env.FACEBOOK_APP_ID || '186244551745631',
secret: process.env.FACEBOOK_APP_SECRET || 'a970ae3240ab4b9b8aae0f9f0661c6fc',
},
// https://cloud.google.com/console/project
google: {
id: process.env.GOOGLE_CLIENT_ID || '251410730550-ahcg0ou5mgfhl8hlui1urru7jn5s12km.apps.googleusercontent.com',
secret: process.env.GOOGLE_CLIENT_SECRET || 'Y8yR9yZAhm9jQ8FKAL8QIEcd',
},
};
|
import { SET_RESULTS } from './results.actions'
export const initState = []
export const initAction = {}
export default (state = initState, action = initAction) => {
switch (action.type) {
case SET_RESULTS: return action.payload
default: return state
}
}
|
(function () {
return {
createUI: function(namingContainerPrefix, container, settings) {
this.languageKeys = [
'/shell/cms/visitorgroups/criteria/timeofday/starttimeafterendtime',
'/shell/cms/visitorgroups/criteria/timeofday/nodayofweekselected',
'/shell/cms/visitorgroups/criteria/timeofday/bothornonetime'
];
this.prototype.createUI.apply(this, arguments);
},
uiCreated: function(namingContainerPrefix) {
dojo.require('dijit.form.Button');
dojo.require('dijit.TooltipDialog');
var toolTipDlg = new dijit.TooltipDialog({
}, namingContainerPrefix + 'dayCheckboxes');
var button = new dijit.form.DropDownButton({
dropDown: toolTipDlg
}, namingContainerPrefix + 'dayDropdown');
},
validate: function(namingContainerPrefix) {
var validationErrors = this.prototype.validate.apply(this, arguments);
var from = dijit.byId(namingContainerPrefix + 'StartTime');
var to = dijit.byId(namingContainerPrefix + 'EndTime');
var dow = dijit.byId(namingContainerPrefix + 'dayDropdown');
var fromTime = from.get('value');
var toTime = to.get('value');
if (fromTime === null && toTime !== null) {
validationErrors.Add(this.translatedText['/shell/cms/visitorgroups/criteria/timeofday/bothornonetime'], from);
}
if (fromTime !== null && toTime === null) {
validationErrors.Add(this.translatedText['/shell/cms/visitorgroups/criteria/timeofday/bothornonetime'], to);
}
if (fromTime >= toTime && fromTime !== null && toTime !== null) {
validationErrors.Add(this.translatedText['/shell/cms/visitorgroups/criteria/timeofday/starttimeafterendtime'], from);
}
if ((!dijit.byId(namingContainerPrefix + 'Monday').checked) &&
(!dijit.byId(namingContainerPrefix + 'Tuesday').checked) &&
(!dijit.byId(namingContainerPrefix + 'Wednesday').checked) &&
(!dijit.byId(namingContainerPrefix + 'Thursday').checked) &&
(!dijit.byId(namingContainerPrefix + 'Friday').checked) &&
(!dijit.byId(namingContainerPrefix + 'Saturday').checked) &&
(!dijit.byId(namingContainerPrefix + 'Sunday').checked)) {
validationErrors.Add(this.translatedText['/shell/cms/visitorgroups/criteria/timeofday/nodayofweekselected'], dow);
}
return validationErrors;
}
};
})(); |
(function() {
'use strict';
describe('Invitation', function() {
var httpBackend, Invitation, invitation;
beforeEach(module('weddinvApp'));
beforeEach(inject(function($injector) {
httpBackend = $injector.get('$httpBackend');
Invitation = $injector.get('Invitation');
invitation = Invitation.one('invitations');
}));
afterEach(function() {
httpBackend.verifyNoOutstandingExpectation();
httpBackend.verifyNoOutstandingRequest();
});
describe('resendEmail', function() {
describe('given a new invitation', function() {
it('should raise an exception', function() {
expect(function() {
var invitation = Invitation.one('invitations');
invitation.resendEmail();
}).toThrow('Invitation is not persisted');
});
});
describe('given an existing invitation', function() {
beforeEach(function() {
invitation.id = 1;
});
it('should POST to /invitation/:id/resend_email', function() {
httpBackend.expectPOST('/api/invitations/1/resend_email').respond(200);
invitation.resendEmail();
httpBackend.flush();
});
});
}); /* end .resendEmail */
describe('.rsvp', function() {
describe('passing no arguments to the function', function() {
it('should raise an exception', function() {
invitation.id = 1; // Avoid "Invitation not persisted" error.
expect(function() {
invitation.rsvp();
}).toThrow('Confirmation action is not valid');
});
});
describe('passing a blank string as an action', function() {
it('should raise an exception', function() {
invitation.id = 1; // Avoid "Invitation not persisted" error.
expect(function() {
invitation.rsvp('');
}).toThrow('Confirmation action is not valid');
});
});
describe('given a new invitation', function() {
it('should raise an exception', function() {
expect(function() {
var invitation = Invitation.one('invitations');
invitation.rsvp('accept');
}).toThrow('Invitation is not persisted');
});
});
describe('given an existing invitation', function() {
beforeEach(function() {
invitation.id = 1;
});
describe('passing "accept" as an argument', function() {
it("should POST to /invitation/:id/accept", function() {
httpBackend.expectPOST('/api/invitations/1/accept').respond(200);
invitation.rsvp('accept');
httpBackend.flush();
});
});
describe('passing "reject" as an argument', function() {
it("should POST to /invitation/:id/reject", function() {
httpBackend.expectPOST('/api/invitations/1/reject').respond(200);
invitation.rsvp('reject');
httpBackend.flush();
});
});
});
}); /* end .rsvp */
describe('.accept', function() {
describe('given a new invitation', function() {
it('should raise an exception', function() {
var invitation = Invitation.one('invitations');
expect(function() {
invitation.accept();
}).toThrow('Invitation is not persisted');
});
});
describe('given an existing invitation', function() {
it('should call rsvp() with "accept"', function() {
invitation.id = 1;
spyOn(invitation, 'rsvp');
invitation.accept();
expect(invitation.rsvp).toHaveBeenCalledWith('accept');
});
});
}); /* end .accept */
describe('.reject', function() {
describe('given a new invitation', function() {
it('should raise an exception', function() {
var invitation = Invitation.one('invitations');
expect(function() {
invitation.reject();
}).toThrow('Invitation is not persisted');
});
});
describe('given an existing invitation', function() {
it('should call rsvp() with "reject"', function() {
invitation.id = 1;
spyOn(invitation, 'rsvp');
invitation.reject();
expect(invitation.rsvp).toHaveBeenCalledWith('reject');
});
});
}); /* end .reject */
describe('.isAccepted', function() {
describe('when the invitation status is "accepted"', function() {
it('should return true', function() {
invitation.status = 'accepted';
expect(invitation.isAccepted()).toBe(true);
});
});
describe('when the invitation status is not "accepted"', function() {
it('should return false', function() {
invitation.status = 'pending';
expect(invitation.isAccepted()).toBe(false);
});
});
}); /* end .isAccepted */
describe('.isRejected', function() {
describe('when the invitation status is "rejected"', function() {
it('should return true', function() {
invitation.status = 'rejected';
expect(invitation.isRejected()).toBe(true);
});
});
describe('when the invitation status is not "rejected"', function() {
it('should return false', function() {
invitation.status = 'pending';
expect(invitation.isRejected()).toBe(false);
});
});
}); /* end .isRejected */
describe('.isPending', function() {
describe('when invitation status is "pending"', function() {
it('should return true', function() {
invitation.status = 'pending';
expect(invitation.isPending()).toBe(true);
});
});
describe('when invitation status is not "pending"', function() {
it('should return false', function() {
invitation.status = 'accepted';
expect(invitation.isPending()).toBe(false);
});
});
}); /* end .isPending */
});
}());
|
import OAuth2PasswordGrant from 'ember-simple-auth/authenticators/oauth2-password-grant';
import ENV from 'frontend/config/environment';
export default OAuth2PasswordGrant.extend({
serverTokenEndpoint: ENV.serverTokenEndpoint,
makeRequest: function(url, data){
data.client_id = ENV.clientId;
data.client_secret = ENV.clientSecret;
return this._super(url, data);
}
}); |
// @flow
import curry from 'lodash/fp/curry';
import flatten from './flatten';
import synchronize from './synchronize';
/**
* Return an array of `FlatRoute`s which are rooted at the given prefix.
*
* If routes that match the given prefix are asynchronous, then a promise will be returned,
* resolving with an array of `FlatRoute`s.
*/
function _query(
prefix: string,
routes: PlainRoute | PlainRoute[],
cb: CPSCallback<FlatRoute[]>,
) {
synchronize(prefix, routes, (error, syncRoutes) => {
const flatRoutes = flatten(syncRoutes);
const matchedRoutes = flatRoutes.filter(
route => route.fullPath.startsWith(prefix)
);
cb(null, matchedRoutes);
});
}
const query:
(prefix: string) =>
(routes: PlainRoute | PlainRoute[]) =>
(cb: CPSCallback<FlatRoute[]>) =>
void =
curry(_query);
export default query;
|
'use strict';
var util = require('util');
var yeoman = require('yeoman-generator');
var AngularGenerator = module.exports = function AngularGenerator(args, options, config) {
yeoman.generators.NamedBase.apply(this, arguments);
};
util.inherits(AngularGenerator, yeoman.generators.NamedBase);
AngularGenerator.prototype.files = function files() {
this.template('_config.js', 'config/' + this.name + '.js');
};
|
import React from 'react';
import MarkdownDocs from 'docs/src/modules/components/MarkdownDocs';
import { prepareMarkdown } from 'docs/src/modules/utils/parseMarkdown';
const pageFilename = 'getting-started/learn';
const requireDemo = require.context('docs/src/pages/getting-started/learn', false, /\.(js|tsx)$/);
const requireRaw = require.context(
'!raw-loader!../../src/pages/getting-started/learn',
false,
/\.(js|md|tsx)$/,
);
export default function Page({ demos, docs }) {
return <MarkdownDocs demos={demos} docs={docs} requireDemo={requireDemo} />;
}
Page.getInitialProps = () => {
const { demos, docs } = prepareMarkdown({ pageFilename, requireRaw });
return { demos, docs };
};
|
"use strict";
var datetime = require('../../../src/util/datetime-util');
function run() {
describe('convertDataToISO', function () {
it('should convert DateTimeData to datetime string, with blank timezone', function () {
var data = {
year: 1994,
month: 12,
day: 15,
hour: 13,
minute: 47,
second: 20,
};
var str = datetime.convertDataToISO(data);
expect(str).toEqual('1994-12-15T13:47:20Z');
});
it('should convert DateTimeData to datetime string, +330 tz offset', function () {
var data = {
year: 1994,
month: 12,
day: 15,
hour: 13,
minute: 47,
second: 20,
millisecond: 789,
tzOffset: 330,
};
var str = datetime.convertDataToISO(data);
expect(str).toEqual('1994-12-15T13:47:20.789+05:30');
});
it('should convert DateTimeData to datetime string, Z timezone', function () {
var data = {
year: 1994,
month: 12,
day: 15,
hour: 13,
minute: null,
second: null,
millisecond: null,
tzOffset: 0,
};
var str = datetime.convertDataToISO(data);
expect(str).toEqual('1994-12-15T13:00:00Z');
});
it('should convert DateTimeData to YYYY-MM-DD', function () {
var data = {
year: 1994,
month: 1,
day: 1,
hour: null,
minute: null,
second: null,
millisecond: null,
tzOffset: 0,
};
var str = datetime.convertDataToISO(data);
expect(str).toEqual('1994-01-01');
});
it('should convert DateTimeData to YYYY-MM', function () {
var data = {
year: 1994,
month: 1,
day: null,
hour: null,
minute: null,
second: null,
millisecond: null,
tzOffset: 0,
};
var str = datetime.convertDataToISO(data);
expect(str).toEqual('1994-01');
});
it('should convert DateTimeData to YYYY', function () {
var data = {
year: 1994,
month: null,
day: null,
hour: null,
minute: null,
second: null,
millisecond: null,
tzOffset: 0,
};
var str = datetime.convertDataToISO(data);
expect(str).toEqual('1994');
});
it('should convert DateTimeData to HH:mm:SS.SSS', function () {
var data = {
year: null,
month: null,
day: null,
hour: 13,
minute: 47,
second: 20,
millisecond: 789,
tzOffset: 0,
};
var str = datetime.convertDataToISO(data);
expect(str).toEqual('13:47:20.789');
});
it('should convert DateTimeData to HH:mm:SS string', function () {
var data = {
year: null,
month: null,
day: null,
hour: 13,
minute: 47,
second: 20,
millisecond: null,
tzOffset: 0,
};
var str = datetime.convertDataToISO(data);
expect(str).toEqual('13:47:20');
});
it('should convert DateTimeData to HH:mm string', function () {
var data = {
year: null,
month: null,
day: null,
hour: 13,
minute: 47,
second: null,
millisecond: null,
tzOffset: 0,
};
var str = datetime.convertDataToISO(data);
expect(str).toEqual('13:47');
});
it('should not convert DateTimeData with null data', function () {
var data = {
year: null,
month: null,
day: null,
hour: null,
minute: null,
second: null,
millisecond: null,
tzOffset: 0,
};
var str = datetime.convertDataToISO(data);
expect(str).toEqual('');
var str = datetime.convertDataToISO({});
expect(str).toEqual('');
});
});
describe('convertFormatToKey', function () {
it('should convert year formats to their DateParse key', function () {
expect(datetime.convertFormatToKey('YYYY')).toEqual('year');
expect(datetime.convertFormatToKey('YY')).toEqual('year');
});
it('should convert month formats to their DateParse key', function () {
expect(datetime.convertFormatToKey('MMMM')).toEqual('month');
expect(datetime.convertFormatToKey('MMM')).toEqual('month');
expect(datetime.convertFormatToKey('MM')).toEqual('month');
expect(datetime.convertFormatToKey('M')).toEqual('month');
});
it('should convert day formats to their DateParse key', function () {
expect(datetime.convertFormatToKey('DDDD')).toEqual('day');
expect(datetime.convertFormatToKey('DDD')).toEqual('day');
expect(datetime.convertFormatToKey('DD')).toEqual('day');
expect(datetime.convertFormatToKey('D')).toEqual('day');
});
it('should convert hour formats to their DateParse key', function () {
expect(datetime.convertFormatToKey('HH')).toEqual('hour');
expect(datetime.convertFormatToKey('H')).toEqual('hour');
expect(datetime.convertFormatToKey('hh')).toEqual('hour');
expect(datetime.convertFormatToKey('h')).toEqual('hour');
});
it('should convert minute formats to their DateParse key', function () {
expect(datetime.convertFormatToKey('mm')).toEqual('minute');
expect(datetime.convertFormatToKey('m')).toEqual('minute');
});
it('should convert am/pm formats to their DateParse key', function () {
expect(datetime.convertFormatToKey('A')).toEqual('ampm');
expect(datetime.convertFormatToKey('a')).toEqual('ampm');
});
});
describe('getValueFromFormat', function () {
it('should convert 24 hour to am value', function () {
var d = datetime.parseDate('00:47');
expect(datetime.getValueFromFormat(d, 'hh')).toEqual(0);
expect(datetime.getValueFromFormat(d, 'h')).toEqual(0);
var d = datetime.parseDate('11:47');
expect(datetime.getValueFromFormat(d, 'hh')).toEqual(11);
expect(datetime.getValueFromFormat(d, 'h')).toEqual(11);
});
it('should convert 24 hour to pm value', function () {
var d = datetime.parseDate('12:47');
expect(datetime.getValueFromFormat(d, 'hh')).toEqual(12);
expect(datetime.getValueFromFormat(d, 'h')).toEqual(12);
var d = datetime.parseDate('13:47');
expect(datetime.getValueFromFormat(d, 'hh')).toEqual(1);
expect(datetime.getValueFromFormat(d, 'h')).toEqual(1);
});
it('should convert am hours to am value', function () {
var d = datetime.parseDate('00:47');
expect(datetime.getValueFromFormat(d, 'A')).toEqual('am');
expect(datetime.getValueFromFormat(d, 'a')).toEqual('am');
var d = datetime.parseDate('11:47');
expect(datetime.getValueFromFormat(d, 'A')).toEqual('am');
expect(datetime.getValueFromFormat(d, 'a')).toEqual('am');
});
it('should convert pm hours to pm value', function () {
var d = datetime.parseDate('12:47');
expect(datetime.getValueFromFormat(d, 'A')).toEqual('pm');
expect(datetime.getValueFromFormat(d, 'a')).toEqual('pm');
var d = datetime.parseDate('23:47');
expect(datetime.getValueFromFormat(d, 'A')).toEqual('pm');
expect(datetime.getValueFromFormat(d, 'a')).toEqual('pm');
});
it('should convert date formats to values', function () {
var d = datetime.parseDate('1994-12-15T13:47:20.789Z');
expect(datetime.getValueFromFormat(d, 'YYYY')).toEqual(1994);
expect(datetime.getValueFromFormat(d, 'M')).toEqual(12);
expect(datetime.getValueFromFormat(d, 'DDDD')).toEqual(15);
});
});
describe('parseTemplate', function () {
it('should not parse D thats apart of a word', function () {
var formats = datetime.parseTemplate('D Days');
expect(formats.length).toEqual(1);
expect(formats[0]).toEqual('D');
});
it('should not parse D thats apart of a word', function () {
var formats = datetime.parseTemplate('DD Days');
expect(formats.length).toEqual(1);
expect(formats[0]).toEqual('DD');
});
it('should not parse m thats apart of a word', function () {
var formats = datetime.parseTemplate('m mins');
expect(formats.length).toEqual(1);
expect(formats[0]).toEqual('m');
});
it('should not parse M thats apart of a word', function () {
var formats = datetime.parseTemplate('mm Minutes');
expect(formats.length).toEqual(1);
expect(formats[0]).toEqual('mm');
});
it('should not pickup "a" within 12-hour, but its not the am/pm', function () {
var formats = datetime.parseTemplate('hh:mm is a time');
expect(formats.length).toEqual(2);
expect(formats[0]).toEqual('hh');
expect(formats[1]).toEqual('mm');
});
it('should allow am/pm when using 12-hour and no spaces', function () {
var formats = datetime.parseTemplate('hh:mma');
expect(formats.length).toEqual(3);
expect(formats[0]).toEqual('hh');
expect(formats[1]).toEqual('mm');
expect(formats[2]).toEqual('a');
});
it('should allow am/pm when using 12-hour', function () {
var formats = datetime.parseTemplate('hh:mm a');
expect(formats.length).toEqual(3);
expect(formats[0]).toEqual('hh');
expect(formats[1]).toEqual('mm');
expect(formats[2]).toEqual('a');
});
it('should not add am/pm when not using 24-hour', function () {
var formats = datetime.parseTemplate('HH:mm a');
expect(formats.length).toEqual(2);
expect(formats[0]).toEqual('HH');
expect(formats[1]).toEqual('mm');
});
it('should get formats from template "m mm h hh H HH D DD DDD DDDD M MM MMM MMMM YY YYYY"', function () {
var formats = datetime.parseTemplate('m mm h hh H HH D DD DDD DDDD M MM MMM MMMM YY YYYY');
expect(formats[0]).toEqual('m');
expect(formats[1]).toEqual('mm');
expect(formats[2]).toEqual('h');
expect(formats[3]).toEqual('hh');
expect(formats[4]).toEqual('H');
expect(formats[5]).toEqual('HH');
expect(formats[6]).toEqual('D');
expect(formats[7]).toEqual('DD');
expect(formats[8]).toEqual('DDD');
expect(formats[9]).toEqual('DDDD');
expect(formats[10]).toEqual('M');
expect(formats[11]).toEqual('MM');
expect(formats[12]).toEqual('MMM');
expect(formats[13]).toEqual('MMMM');
expect(formats[14]).toEqual('YY');
expect(formats[15]).toEqual('YYYY');
});
it('should get formats from template YYMMMMDDHHmm', function () {
var formats = datetime.parseTemplate('YYMMMMDDHHmm');
expect(formats[0]).toEqual('YY');
expect(formats[1]).toEqual('MMMM');
expect(formats[2]).toEqual('DD');
expect(formats[3]).toEqual('HH');
expect(formats[4]).toEqual('mm');
});
it('should get formats from template MM/DD/YYYY', function () {
var formats = datetime.parseTemplate('MM/DD/YYYY');
expect(formats[0]).toEqual('MM');
expect(formats[1]).toEqual('DD');
expect(formats[2]).toEqual('YYYY');
});
});
describe('renderDateTime', function () {
it('should show correct month and day name defaults', function () {
var d = datetime.parseDate('2016-05-12');
var r = datetime.renderDateTime('DDDD MMM D YYYY', d, {});
expect(r).toEqual('Thursday May 12 2016');
});
it('should format h:mm a, PM', function () {
var d = datetime.parseDate('1994-12-15T13:47:20.789Z');
expect(datetime.renderDateTime('h:mm a', d, {})).toEqual('1:47 pm');
});
it('should get empty text for format without data', function () {
var emptyObj = {};
expect(datetime.renderDateTime('MMMM D, YYYY h:mm a', emptyObj, {})).toEqual('');
var dataWithNulls = {
year: null,
month: null,
day: null,
hour: null,
minute: null,
second: null,
millisecond: null,
tzOffset: 0,
};
expect(datetime.renderDateTime('MMMM D, YYYY h:mm a', dataWithNulls, {})).toEqual('');
});
it('should format h:mm a, AM', function () {
var d = datetime.parseDate('1994-12-15T00:47:20.789Z');
expect(datetime.renderDateTime('h:mm a', d, {})).toEqual('12:47 am');
});
it('should format HH:mm', function () {
var d = datetime.parseDate('1994-12-15T13:47:20.789Z');
expect(datetime.renderDateTime('HH:mm', d, {})).toEqual('13:47');
});
it('should format MMMM D, YYYY', function () {
var d = datetime.parseDate('1994-12-15T13:47:20.789Z');
expect(datetime.renderDateTime('MMMM D, YYYY', d, {})).toEqual('December 15, 1994');
});
it('should format MM/DD/YYYY', function () {
var d = datetime.parseDate('1994-12-15T13:47:20.789Z');
expect(datetime.renderDateTime('MM/DD/YYYY', d, {})).toEqual('12/15/1994');
});
it('should format DD-MM-YY', function () {
var d = datetime.parseDate('1994-12-15T13:47:20.789Z');
expect(datetime.renderDateTime('DD-MM-YY', d, {})).toEqual('15-12-94');
});
it('should format YYYY', function () {
var d = datetime.parseDate('1994-12-15T13:47:20.789Z');
expect(datetime.renderDateTime('DD-MM-YY', d, {})).toEqual('15-12-94');
});
it('should format YYYY$MM.DD*HH?mm', function () {
var d = datetime.parseDate('1994-12-15T13:47:20.789Z');
expect(datetime.renderDateTime('YYYY$MM.DD*HH?mm', d, {})).toEqual('1994$12.15*13?47');
});
it('should return empty when template invalid', function () {
var d = datetime.parseDate('1994-12-15T13:47:20.789Z');
expect(datetime.renderDateTime('', d, {})).toEqual('');
});
it('should return empty when date invalid', function () {
var d = datetime.parseDate(null);
expect(datetime.renderDateTime('YYYY', d, {})).toEqual('');
});
});
describe('renderTextFormat', function () {
it('should return a', function () {
var d = datetime.parseDate('00:47');
expect(datetime.renderTextFormat('a', 'am', d, {})).toEqual('am');
expect(datetime.renderTextFormat('a', 'am', null, {})).toEqual('am');
var d = datetime.parseDate('11:47');
expect(datetime.renderTextFormat('a', 'am', d, {})).toEqual('am');
expect(datetime.renderTextFormat('a', 'am', null, {})).toEqual('am');
var d = datetime.parseDate('12:47');
expect(datetime.renderTextFormat('a', 'pm', d, {})).toEqual('pm');
expect(datetime.renderTextFormat('a', 'pm', null, {})).toEqual('pm');
});
it('should return A', function () {
var d = datetime.parseDate('00:47');
expect(datetime.renderTextFormat('A', 'am', d, {})).toEqual('AM');
expect(datetime.renderTextFormat('A', 'am', null, {})).toEqual('AM');
var d = datetime.parseDate('11:47');
expect(datetime.renderTextFormat('A', 'am', d, {})).toEqual('AM');
expect(datetime.renderTextFormat('A', 'am', null, {})).toEqual('AM');
var d = datetime.parseDate('12:47');
expect(datetime.renderTextFormat('A', 'pm', d, {})).toEqual('PM');
expect(datetime.renderTextFormat('A', 'pm', null, {})).toEqual('PM');
});
it('should return m', function () {
expect(datetime.renderTextFormat('m', 1, null, {})).toEqual('1');
expect(datetime.renderTextFormat('m', 12, null, {})).toEqual('12');
});
it('should return mm', function () {
expect(datetime.renderTextFormat('mm', 1, null, {})).toEqual('01');
expect(datetime.renderTextFormat('mm', 12, null, {})).toEqual('12');
});
it('should return hh', function () {
expect(datetime.renderTextFormat('hh', 0, null, {})).toEqual('12');
expect(datetime.renderTextFormat('hh', 1, null, {})).toEqual('01');
expect(datetime.renderTextFormat('hh', 11, null, {})).toEqual('11');
expect(datetime.renderTextFormat('hh', 12, null, {})).toEqual('12');
expect(datetime.renderTextFormat('hh', 13, null, {})).toEqual('01');
expect(datetime.renderTextFormat('hh', 21, null, {})).toEqual('09');
expect(datetime.renderTextFormat('hh', 23, null, {})).toEqual('11');
});
it('should return h', function () {
expect(datetime.renderTextFormat('h', 0, null, {})).toEqual('12');
expect(datetime.renderTextFormat('h', 1, null, {})).toEqual('1');
expect(datetime.renderTextFormat('h', 11, null, {})).toEqual('11');
expect(datetime.renderTextFormat('h', 12, null, {})).toEqual('12');
expect(datetime.renderTextFormat('h', 13, null, {})).toEqual('1');
expect(datetime.renderTextFormat('h', 21, null, {})).toEqual('9');
expect(datetime.renderTextFormat('h', 23, null, {})).toEqual('11');
});
it('should return hh', function () {
expect(datetime.renderTextFormat('hh', 1, null, {})).toEqual('01');
expect(datetime.renderTextFormat('hh', 12, null, {})).toEqual('12');
});
it('should return H', function () {
expect(datetime.renderTextFormat('H', 1, null, {})).toEqual('1');
expect(datetime.renderTextFormat('H', 12, null, {})).toEqual('12');
});
it('should return HH', function () {
expect(datetime.renderTextFormat('HH', 1, null, {})).toEqual('01');
expect(datetime.renderTextFormat('HH', 12, null, {})).toEqual('12');
});
it('should return D', function () {
expect(datetime.renderTextFormat('D', 1, null, {})).toEqual('1');
expect(datetime.renderTextFormat('D', 12, null, {})).toEqual('12');
});
it('should return DD', function () {
expect(datetime.renderTextFormat('DD', 1, null, {})).toEqual('01');
expect(datetime.renderTextFormat('DD', 12, null, {})).toEqual('12');
});
it('should return DDD', function () {
var d = {
year: 2016,
month: 5,
day: 12,
};
expect(datetime.renderTextFormat('DDD', null, d, {})).toEqual('Thu');
});
it('should return DDD with custom locale', function () {
var d = {
year: 2016,
month: 5,
day: 12,
};
expect(datetime.renderTextFormat('DDD', null, d, customLocale)).toEqual('qui');
});
it('should return DDDD', function () {
var d = {
year: 2016,
month: 5,
day: 12,
};
expect(datetime.renderTextFormat('DDDD', null, d, {})).toEqual('Thursday');
});
it('should return DDDD with custom locale', function () {
var d = {
year: 2016,
month: 5,
day: 12,
};
expect(datetime.renderTextFormat('DDDD', null, d, customLocale)).toEqual('quinta-feira');
});
it('should return M', function () {
expect(datetime.renderTextFormat('M', 1, null, {})).toEqual('1');
expect(datetime.renderTextFormat('M', 12, null, {})).toEqual('12');
});
it('should return MM', function () {
expect(datetime.renderTextFormat('MM', 1, null, {})).toEqual('01');
expect(datetime.renderTextFormat('MM', 12, null, {})).toEqual('12');
});
it('should return MMM', function () {
expect(datetime.renderTextFormat('MMM', 1, null, {})).toEqual('Jan');
expect(datetime.renderTextFormat('MMM', 12, null, {})).toEqual('Dec');
});
it('should return MMM with custom locale', function () {
expect(datetime.renderTextFormat('MMM', 1, null, customLocale)).toEqual('jan');
});
it('should return MMMM', function () {
expect(datetime.renderTextFormat('MMMM', 1, null, {})).toEqual('January');
expect(datetime.renderTextFormat('MMMM', 12, null, {})).toEqual('December');
});
it('should return MMMM with custom locale', function () {
expect(datetime.renderTextFormat('MMMM', 1, null, customLocale)).toEqual('janeiro');
});
it('should return YY', function () {
expect(datetime.renderTextFormat('YY', 1994, null, {})).toEqual('94');
expect(datetime.renderTextFormat('YY', 94, null, {})).toEqual('94');
});
it('should return YYYY', function () {
expect(datetime.renderTextFormat('YYYY', 1994, null, {})).toEqual('1994');
expect(datetime.renderTextFormat('YYYY', 0, null, {})).toEqual('0000');
});
it('should return empty when blank', function () {
expect(datetime.renderTextFormat(null, null, null, {})).toEqual('');
expect(datetime.renderTextFormat(null, 1994, null, {})).toEqual('1994');
});
});
describe('parseISODate', function () {
it('should get HH:MM:SS.SSS+HH:MM', function () {
var parsed = datetime.parseDate('13:47:20.789+05:30');
expect(parsed.year).toEqual(null);
expect(parsed.month).toEqual(null);
expect(parsed.day).toEqual(null);
expect(parsed.hour).toEqual(13);
expect(parsed.minute).toEqual(47);
expect(parsed.second).toEqual(20);
expect(parsed.millisecond).toEqual(789);
expect(parsed.tzOffset).toEqual(330);
});
it('should get HH:MM:SS.SSS', function () {
var parsed = datetime.parseDate('13:47:20.789');
expect(parsed.year).toEqual(null);
expect(parsed.month).toEqual(null);
expect(parsed.day).toEqual(null);
expect(parsed.hour).toEqual(13);
expect(parsed.minute).toEqual(47);
expect(parsed.second).toEqual(20);
expect(parsed.millisecond).toEqual(789);
expect(parsed.tzOffset).toEqual(0);
});
it('should get HH:MM:SS', function () {
var parsed = datetime.parseDate('13:47:20');
expect(parsed.year).toEqual(null);
expect(parsed.month).toEqual(null);
expect(parsed.day).toEqual(null);
expect(parsed.hour).toEqual(13);
expect(parsed.minute).toEqual(47);
expect(parsed.second).toEqual(20);
expect(parsed.millisecond).toEqual(null);
expect(parsed.tzOffset).toEqual(0);
});
it('should get HH:MM', function () {
var parsed = datetime.parseDate('13:47');
expect(parsed.year).toEqual(null);
expect(parsed.month).toEqual(null);
expect(parsed.day).toEqual(null);
expect(parsed.hour).toEqual(13);
expect(parsed.minute).toEqual(47);
expect(parsed.second).toEqual(null);
expect(parsed.millisecond).toEqual(null);
expect(parsed.tzOffset).toEqual(0);
});
it('should get YYYY-MM-DDTHH:MM:SS.SSS+HH:MM', function () {
var parsed = datetime.parseDate('1994-12-15T13:47:20.789+05:30');
expect(parsed.year).toEqual(1994);
expect(parsed.month).toEqual(12);
expect(parsed.day).toEqual(15);
expect(parsed.hour).toEqual(13);
expect(parsed.minute).toEqual(47);
expect(parsed.second).toEqual(20);
expect(parsed.millisecond).toEqual(789);
expect(parsed.tzOffset).toEqual(330);
});
it('should get YYYY-MM-DDTHH:MM:SS.SSS-HH:MM', function () {
var parsed = datetime.parseDate('1994-12-15T13:47:20.789-11:45');
expect(parsed.year).toEqual(1994);
expect(parsed.month).toEqual(12);
expect(parsed.day).toEqual(15);
expect(parsed.hour).toEqual(13);
expect(parsed.minute).toEqual(47);
expect(parsed.second).toEqual(20);
expect(parsed.millisecond).toEqual(789);
expect(parsed.tzOffset).toEqual(-705);
});
it('should get YYYY-MM-DDTHH:MM:SS.SSS-HH', function () {
var parsed = datetime.parseDate('1994-12-15T13:47:20.789-02');
expect(parsed.year).toEqual(1994);
expect(parsed.month).toEqual(12);
expect(parsed.day).toEqual(15);
expect(parsed.hour).toEqual(13);
expect(parsed.minute).toEqual(47);
expect(parsed.second).toEqual(20);
expect(parsed.millisecond).toEqual(789);
expect(parsed.tzOffset).toEqual(-120);
});
it('should get YYYY-MM-DDTHH:MM:SS.SSSZ and set UTC offset', function () {
var parsed = datetime.parseDate('1994-12-15T13:47:20.789Z');
expect(parsed.year).toEqual(1994);
expect(parsed.month).toEqual(12);
expect(parsed.day).toEqual(15);
expect(parsed.hour).toEqual(13);
expect(parsed.minute).toEqual(47);
expect(parsed.second).toEqual(20);
expect(parsed.millisecond).toEqual(789);
expect(parsed.tzOffset).toEqual(0);
});
it('should get YYYY-MM-DDTHH:MM:SS', function () {
var parsed = datetime.parseDate('1994-12-15T13:47:20');
expect(parsed.year).toEqual(1994);
expect(parsed.month).toEqual(12);
expect(parsed.day).toEqual(15);
expect(parsed.hour).toEqual(13);
expect(parsed.minute).toEqual(47);
expect(parsed.second).toEqual(20);
expect(parsed.millisecond).toEqual(null);
expect(parsed.tzOffset).toEqual(0);
});
it('should get YYYY-MM-DDTHH:MM', function () {
var parsed = datetime.parseDate('1994-12-15T13:47');
expect(parsed.year).toEqual(1994);
expect(parsed.month).toEqual(12);
expect(parsed.day).toEqual(15);
expect(parsed.hour).toEqual(13);
expect(parsed.minute).toEqual(47);
expect(parsed.second).toEqual(null);
expect(parsed.millisecond).toEqual(null);
expect(parsed.tzOffset).toEqual(0);
});
it('should NOT work with YYYY-MM-DDTHH', function () {
var parsed = datetime.parseDate('1994-12-15T13');
expect(parsed).toEqual(null);
});
it('should get YYYY-MM-DD', function () {
var parsed = datetime.parseDate('1994-12-15');
expect(parsed.year).toEqual(1994);
expect(parsed.month).toEqual(12);
expect(parsed.day).toEqual(15);
expect(parsed.hour).toEqual(null);
expect(parsed.minute).toEqual(null);
expect(parsed.second).toEqual(null);
expect(parsed.millisecond).toEqual(null);
expect(parsed.tzOffset).toEqual(0);
});
it('should get YYYY-MM', function () {
var parsed = datetime.parseDate('1994-12');
expect(parsed.year).toEqual(1994);
expect(parsed.month).toEqual(12);
expect(parsed.day).toEqual(null);
expect(parsed.hour).toEqual(null);
expect(parsed.minute).toEqual(null);
expect(parsed.second).toEqual(null);
expect(parsed.millisecond).toEqual(null);
expect(parsed.tzOffset).toEqual(0);
});
it('should get YYYY', function () {
var parsed = datetime.parseDate('1994');
expect(parsed.year).toEqual(1994);
expect(parsed.month).toEqual(null);
expect(parsed.day).toEqual(null);
expect(parsed.hour).toEqual(null);
expect(parsed.minute).toEqual(null);
expect(parsed.second).toEqual(null);
expect(parsed.millisecond).toEqual(null);
expect(parsed.tzOffset).toEqual(0);
});
it('should handle bad date formats', function () {
var parsed = datetime.parseDate('12/15/1994');
expect(parsed).toEqual(null);
var parsed = datetime.parseDate('12-15-1994');
expect(parsed).toEqual(null);
var parsed = datetime.parseDate('1994-1994');
expect(parsed).toEqual(null);
var parsed = datetime.parseDate('1994 12 15');
expect(parsed).toEqual(null);
var parsed = datetime.parseDate('12.15.1994');
expect(parsed).toEqual(null);
var parsed = datetime.parseDate('12\\15\\1994');
expect(parsed).toEqual(null);
var parsed = datetime.parseDate('200');
expect(parsed).toEqual(null);
var parsed = datetime.parseDate('holla');
expect(parsed).toEqual(null);
});
it('should get nothing with null date', function () {
var parsed = datetime.parseDate(null);
expect(parsed).toEqual(null);
var parsed = datetime.parseDate(undefined);
expect(parsed).toEqual(null);
var parsed = datetime.parseDate('');
expect(parsed).toEqual(null);
});
});
// pt-br
var customLocale = {
dayNames: [
'domingo',
'segunda-feira',
'ter\u00e7a-feira',
'quarta-feira',
'quinta-feira',
'sexta-feira',
's\u00e1bado'
],
dayShortNames: [
'dom',
'seg',
'ter',
'qua',
'qui',
'sex',
's\u00e1b'
],
monthNames: [
'janeiro',
'fevereiro',
'mar\u00e7o',
'abril',
'maio',
'junho',
'julho',
'agosto',
'setembro',
'outubro',
'novembro',
'dezembro'
],
monthShortNames: [
'jan',
'fev',
'mar',
'abr',
'mai',
'jun',
'jul',
'ago',
'set',
'out',
'nov',
'dez'
],
};
}
exports.run = run; |
import React, { Component } from 'react';
import { inject, observer } from 'mobx-react';
import { Redirect } from 'react-router-dom';
@inject('store')
@observer
export default class /* @echo CLASSNAME */ extends Component {
render() {
return (
<div className='page /* @echo CLASSNAME */'>
{this.props.store.authenticated &&
!this.props.store.authenticating &&
<Redirect to='/' />}
</div>
);
}
} |
"use strict";
var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault");
exports.__esModule = true;
exports["default"] = void 0;
var _useToggle2 = _interopRequireDefault(require("../hooks/useToggle"));
var _useWatchItem = _interopRequireDefault(require("./hooks/useWatchItem"));
var _A = _interopRequireDefault(require("../zhn-atoms/A"));
var _ItemCaption = _interopRequireDefault(require("./ItemCaption"));
var _CommitList = _interopRequireDefault(require("./CommitList"));
var _CL = _interopRequireDefault(require("../styles/CL"));
var _Item = _interopRequireDefault(require("./Item.Style"));
var _jsxRuntime = require("react/jsx-runtime");
var ITEM_DESCRIPTION = "GitHub Repository Commits";
/*
repo, caption, commits, onCloseItem,
onWatchItem, requestType
*/
var GitHubCommits = function GitHubCommits(props) {
var caption = props.caption,
repo = props.repo,
commits = props.commits,
onCloseItem = props.onCloseItem,
onWatchItem = props.onWatchItem,
_useToggle = (0, _useToggle2["default"])(true),
isShow = _useToggle[0],
_hToggle = _useToggle[1],
_hClickWatch = (0, _useWatchItem["default"])(onWatchItem, props, ITEM_DESCRIPTION);
return /*#__PURE__*/(0, _jsxRuntime.jsxs)("div", {
style: _Item["default"].ROOT,
children: [/*#__PURE__*/(0, _jsxRuntime.jsxs)(_ItemCaption["default"], {
style: _Item["default"].PT_8,
onClose: onCloseItem,
children: [/*#__PURE__*/(0, _jsxRuntime.jsx)("button", {
className: _CL["default"].BT_ITEM,
title: caption,
style: _Item["default"].CAPTION_OPEN,
onClick: _hToggle,
children: /*#__PURE__*/(0, _jsxRuntime.jsx)("span", {
children: repo
})
}), /*#__PURE__*/(0, _jsxRuntime.jsx)(_A["default"].ButtonCircle, {
caption: "W",
title: "Add to Watch",
style: _Item["default"].BTN_CIRCLE,
onClick: _hClickWatch
})]
}), /*#__PURE__*/(0, _jsxRuntime.jsx)(_A["default"].ShowHide, {
isShow: isShow,
children: /*#__PURE__*/(0, _jsxRuntime.jsx)(_CommitList["default"], {
commits: commits
})
})]
});
};
var _default = GitHubCommits;
exports["default"] = _default;
//# sourceMappingURL=GitHubCommits.js.map |
(function() {
'use strict';
angular.module('app.common', [
'ui.router',
'app.common.biker-info'
]);
})();
|
// region import
const View = require('./view')
const { CompositeDisposable, Disposable } = require('atom')
// endregion
// region Count
class Count {
activate() {
this.altKey = 'none'
this.ctrlKey = 'none'
this.key = 'none'
this.keyUp = false
this.metaKey = 'none'
this.shiftKey = 'none'
this.fullKeys = 'none'
this.macKeys = 'none'
this.format = atom.config.get('count.format')
this.ignoreRepeatedKeys = atom.config.get('count.ignoreRepeatedKeys')
this.view = new View()
this.view.initialize()
// config change listeners
atom.config.onDidChange('count.format', ({ newValue }) => {
this.format = newValue
this.refresh()
})
atom.config.onDidChange('count.ignoreRepeatedKeys', ({ newValue }) => {
this.ignoreRepeatedKeys = newValue
this.refresh()
})
// keypress listener
const ref = this
this.disposables = new CompositeDisposable()
this.disposables.add(
new Disposable(
atom.views.getView(atom.workspace).addEventListener('keyup', event => {
ref.keyUp = true
})
)
)
this.disposables.add(
new Disposable(
atom.views
.getView(atom.workspace)
.addEventListener('keydown', event => {
// ignore repeat keys
if (
ref.ignoreRepeatedKeys &&
!ref.keyUp &&
ref.altKey === event.altKey &&
ref.ctrlKey === event.ctrlKey &&
ref.key === event.key &&
ref.metaKey === event.metaKey &&
ref.shiftKey === event.shiftKey
)
return
// increment count
atom.config.set('count.amount', atom.config.get('count.amount') + 1)
// single key
ref.key = event.key
ref.altKey = event.altKey
ref.ctrlKey = event.ctrlKey
ref.metaKey = event.metaKey
ref.shiftKey = event.shiftKey
ref.keyUp = false
// full keys
const fullKeys = []
if (event.altKey) fullKeys.push('alt')
if (event.ctrlKey) fullKeys.push('ctrl')
if (event.metaKey) fullKeys.push('meta')
if (event.shiftKey) fullKeys.push('shift')
if (!['Alt', 'Control', 'Meta', 'Shift'].includes(event.key))
fullKeys.push(event.key)
fullKeys.push(event.key)
ref.fullKeys = fullKeys.join('+')
// mac keys
const macKeys = []
if (event.ctrlKey) macKeys.push('⌃')
if (event.altKey) macKeys.push('⌥')
if (event.shiftKey) macKeys.push('⇧')
if (event.metaKey) macKeys.push('⌘')
const macMap = {
ArrowDown: '↓',
ArrowLeft: '←',
ArrowRight: '→',
ArrowUp: '↑',
Backspace: '⌫',
Enter: '⏎',
Escape: '⎋',
}
if (!['Alt', 'Control', 'Meta', 'Shift'].includes(event.key))
macKeys.push(macMap[event.key] || event.key)
ref.macKeys = macKeys.join('')
// reload
ref.refresh()
})
)
)
// render
this.refresh()
}
refresh() {
this.view.set(
this.format
.replace(/\%c/g, atom.config.get('count.amount'))
.replace(/\%f/g, this.fullKeys)
.replace(/\%m/g, this.macKeys)
.replace(/\%k/g, this.key)
)
}
deactivate() {
this.subscriptions.dispose()
this.view.destroy()
this.statusBarTile.destroy() // TODO
}
addStatusBar(statusBar) {
this.statusBar = statusBar
this.statusBarTile = this.statusBar.addLeftTile({
item: this.view,
priority: 50,
})
}
}
// endregion
// region config
const instance = new Count()
instance.config = {
ignoreRepeatedKeys: {
type: 'boolean',
default: true,
description: 'Ignore holding down keys.',
},
format: {
type: 'string',
default: '%c %m',
description:
'Display format. %c = count, %k = last key, %m = mac full keys, %f = full keys',
},
amount: {
type: 'integer',
default: 0,
description: 'Current count.',
},
}
// endregion
// region export
module.exports = instance
// endregion
|
'use strict';
exports.__esModule = true;
exports.reset = exports.auth = exports.ui = undefined;
var _typeof = typeof Symbol === "function" && typeof Symbol.iterator === "symbol" ? function (obj) { return typeof obj; } : function (obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; };
exports.setup = setup;
exports.id = id;
exports.clientID = clientID;
exports.domain = domain;
exports.clientBaseUrl = clientBaseUrl;
exports.tenantBaseUrl = tenantBaseUrl;
exports.useTenantInfo = useTenantInfo;
exports.oidcConformant = oidcConformant;
exports.languageBaseUrl = languageBaseUrl;
exports.setSubmitting = setSubmitting;
exports.submitting = submitting;
exports.setGlobalError = setGlobalError;
exports.globalError = globalError;
exports.clearGlobalError = clearGlobalError;
exports.setGlobalSuccess = setGlobalSuccess;
exports.globalSuccess = globalSuccess;
exports.clearGlobalSuccess = clearGlobalSuccess;
exports.rendering = rendering;
exports.stopRendering = stopRendering;
exports.withAuthOptions = withAuthOptions;
exports.extractTenantBaseUrlOption = extractTenantBaseUrlOption;
exports.render = render;
exports.setLoggedIn = setLoggedIn;
exports.loggedIn = loggedIn;
exports.defaultADUsernameFromEmailPrefix = defaultADUsernameFromEmailPrefix;
exports.warn = warn;
exports.error = error;
exports.allowedConnections = allowedConnections;
exports.connections = connections;
exports.connection = connection;
exports.hasOneConnection = hasOneConnection;
exports.hasOnlyConnections = hasOnlyConnections;
exports.hasSomeConnections = hasSomeConnections;
exports.countConnections = countConnections;
exports.findConnection = findConnection;
exports.hasConnection = hasConnection;
exports.filterConnections = filterConnections;
exports.runHook = runHook;
exports.emitEvent = emitEvent;
exports.loginErrorMessage = loginErrorMessage;
exports.stop = stop;
exports.hasStopped = hasStopped;
exports.hashCleanup = hashCleanup;
exports.emitHashParsedEvent = emitHashParsedEvent;
exports.emitAuthenticatedEvent = emitAuthenticatedEvent;
exports.emitAuthorizationErrorEvent = emitAuthorizationErrorEvent;
exports.emitUnrecoverableErrorEvent = emitUnrecoverableErrorEvent;
exports.showBadge = showBadge;
exports.overrideOptions = overrideOptions;
var _urlJoin = require('url-join');
var _urlJoin2 = _interopRequireDefault(_urlJoin);
var _immutable = require('immutable');
var _immutable2 = _interopRequireDefault(_immutable);
var _media_utils = require('../utils/media_utils');
var _string_utils = require('../utils/string_utils');
var _url_utils = require('../utils/url_utils');
var _i18n = require('../i18n');
var i18n = _interopRequireWildcard(_i18n);
var _trim = require('trim');
var _trim2 = _interopRequireDefault(_trim);
var _gravatar_provider = require('../avatar/gravatar_provider');
var gp = _interopRequireWildcard(_gravatar_provider);
var _data_utils = require('../utils/data_utils');
var _index = require('../connection/social/index');
var _index2 = require('./client/index');
function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } }
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
var _dataFns = (0, _data_utils.dataFns)(["core"]),
get = _dataFns.get,
init = _dataFns.init,
remove = _dataFns.remove,
reset = _dataFns.reset,
set = _dataFns.set,
tget = _dataFns.tget,
tset = _dataFns.tset,
tremove = _dataFns.tremove;
var _dataFns2 = (0, _data_utils.dataFns)(["social"]),
tsetSocial = _dataFns2.tset;
function setup(id, clientID, domain, options, hookRunner, emitEventFn) {
var m = init(id, _immutable2.default.fromJS({
clientBaseUrl: extractClientBaseUrlOption(options, domain),
tenantBaseUrl: extractTenantBaseUrlOption(options, domain),
languageBaseUrl: extractLanguageBaseUrlOption(options, domain),
auth: extractAuthOptions(options),
clientID: clientID,
domain: domain,
emitEventFn: emitEventFn,
hookRunner: hookRunner,
useTenantInfo: options.__useTenantInfo || false,
oidcConformant: options.oidcConformant || false,
hashCleanup: options.hashCleanup === false ? false : true,
allowedConnections: _immutable2.default.fromJS(options.allowedConnections || []),
ui: extractUIOptions(id, options),
defaultADUsernameFromEmailPrefix: options.defaultADUsernameFromEmailPrefix === false ? false : true
}));
m = i18n.initI18n(m);
return m;
}
function id(m) {
return m.get("id");
}
function clientID(m) {
return get(m, "clientID");
}
function domain(m) {
return get(m, "domain");
}
function clientBaseUrl(m) {
return get(m, "clientBaseUrl");
}
function tenantBaseUrl(m) {
return get(m, "tenantBaseUrl");
}
function useTenantInfo(m) {
return get(m, "useTenantInfo");
}
function oidcConformant(m) {
return get(m, "oidcConformant");
}
function languageBaseUrl(m) {
return get(m, "languageBaseUrl");
}
function setSubmitting(m, value) {
var error = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : "";
m = tset(m, "submitting", value);
m = clearGlobalSuccess(m);
m = error && !value ? setGlobalError(m, error) : clearGlobalError(m);
return m;
}
function submitting(m) {
return tget(m, "submitting", false);
}
function setGlobalError(m, str) {
return tset(m, "globalError", str);
}
function globalError(m) {
return tget(m, "globalError", "");
}
function clearGlobalError(m) {
return tremove(m, "globalError");
}
function setGlobalSuccess(m, str) {
return tset(m, "globalSuccess", str);
}
function globalSuccess(m) {
return tget(m, "globalSuccess", "");
}
function clearGlobalSuccess(m) {
return tremove(m, "globalSuccess");
}
function rendering(m) {
return tget(m, "render", false);
}
function stopRendering(m) {
return tremove(m, "render");
}
function extractUIOptions(id, options) {
var closable = options.container ? false : undefined === options.closable ? true : !!options.closable;
var theme = options.theme || {};
var labeledSubmitButton = theme.labeledSubmitButton,
hideMainScreenTitle = theme.hideMainScreenTitle,
logo = theme.logo,
primaryColor = theme.primaryColor,
authButtons = theme.authButtons;
var avatar = options.avatar !== null;
var customAvatarProvider = options.avatar && typeof options.avatar.url === "function" && typeof options.avatar.displayName === "function" && options.avatar;
var avatarProvider = customAvatarProvider || gp;
return new _immutable2.default.fromJS({
containerID: options.container || 'auth0-lock-container-' + id,
appendContainer: !options.container,
autoclose: undefined === options.autoclose ? false : closable && options.autoclose,
autofocus: undefined === options.autofocus ? !(options.container || (0, _media_utils.isSmallScreen)()) : !!options.autofocus,
avatar: avatar,
avatarProvider: avatarProvider,
logo: typeof logo === "string" ? logo : undefined,
closable: closable,
hideMainScreenTitle: !!hideMainScreenTitle,
labeledSubmitButton: undefined === labeledSubmitButton ? true : !!labeledSubmitButton,
language: undefined === options.language ? "en" : (0, _trim2.default)(options.language || "").toLowerCase(),
dict: _typeof(options.languageDictionary) === "object" ? options.languageDictionary : {},
disableWarnings: options.disableWarnings === undefined ? false : !!options.disableWarnings,
mobile: undefined === options.mobile ? false : !!options.mobile,
popupOptions: undefined === options.popupOptions ? {} : options.popupOptions,
primaryColor: typeof primaryColor === "string" ? primaryColor : undefined,
rememberLastLogin: undefined === options.rememberLastLogin ? true : !!options.rememberLastLogin,
authButtonsTheme: (typeof authButtons === 'undefined' ? 'undefined' : _typeof(authButtons)) === "object" ? authButtons : {}
});
}
var _dataFns3 = (0, _data_utils.dataFns)(["core", "ui"]),
getUI = _dataFns3.get,
setUI = _dataFns3.set;
var _dataFns4 = (0, _data_utils.dataFns)(["core", "transient", "ui"]),
tgetUI = _dataFns4.get,
tsetUI = _dataFns4.set;
var getUIAttribute = function getUIAttribute(m, attribute) {
return tgetUI(m, attribute) || getUI(m, attribute);
};
var ui = exports.ui = {
containerID: function containerID(lock) {
return getUIAttribute(lock, "containerID");
},
appendContainer: function appendContainer(lock) {
return getUIAttribute(lock, "appendContainer");
},
autoclose: function autoclose(lock) {
return getUIAttribute(lock, "autoclose");
},
autofocus: function autofocus(lock) {
return getUIAttribute(lock, "autofocus");
},
avatar: function avatar(lock) {
return getUIAttribute(lock, "avatar");
},
avatarProvider: function avatarProvider(lock) {
return getUIAttribute(lock, "avatarProvider");
},
closable: function closable(lock) {
return getUIAttribute(lock, "closable");
},
dict: function dict(lock) {
return getUIAttribute(lock, "dict");
},
disableWarnings: function disableWarnings(lock) {
return getUIAttribute(lock, "disableWarnings");
},
labeledSubmitButton: function labeledSubmitButton(lock) {
return getUIAttribute(lock, "labeledSubmitButton");
},
hideMainScreenTitle: function hideMainScreenTitle(lock) {
return getUIAttribute(lock, "hideMainScreenTitle");
},
language: function language(lock) {
return getUIAttribute(lock, "language");
},
logo: function logo(lock) {
return getUIAttribute(lock, "logo");
},
mobile: function mobile(lock) {
return getUIAttribute(lock, "mobile");
},
popupOptions: function popupOptions(lock) {
return getUIAttribute(lock, "popupOptions");
},
primaryColor: function primaryColor(lock) {
return getUIAttribute(lock, "primaryColor");
},
authButtonsTheme: function authButtonsTheme(lock) {
return getUIAttribute(lock, "authButtonsTheme");
},
rememberLastLogin: function rememberLastLogin(m) {
return tget(m, "rememberLastLogin", getUIAttribute(m, "rememberLastLogin"));
}
};
var _dataFns5 = (0, _data_utils.dataFns)(["core", "auth"]),
getAuthAttribute = _dataFns5.get;
var auth = exports.auth = {
connectionScopes: function connectionScopes(m) {
return getAuthAttribute(m, "connectionScopes");
},
params: function params(m) {
return tget(m, "authParams") || getAuthAttribute(m, "params");
},
autoParseHash: function autoParseHash(lock) {
return getAuthAttribute(lock, "autoParseHash");
},
redirect: function redirect(lock) {
return getAuthAttribute(lock, "redirect");
},
redirectUrl: function redirectUrl(lock) {
return getAuthAttribute(lock, "redirectUrl");
},
responseType: function responseType(lock) {
return getAuthAttribute(lock, "responseType");
},
sso: function sso(lock) {
return getAuthAttribute(lock, "sso");
}
};
function extractAuthOptions(options) {
var _ref = options.auth || {},
audience = _ref.audience,
connectionScopes = _ref.connectionScopes,
params = _ref.params,
autoParseHash = _ref.autoParseHash,
redirect = _ref.redirect,
redirectUrl = _ref.redirectUrl,
responseMode = _ref.responseMode,
responseType = _ref.responseType,
sso = _ref.sso,
state = _ref.state,
nonce = _ref.nonce;
var oidcConformant = options.oidcConformant;
audience = typeof audience === "string" ? audience : undefined;
connectionScopes = (typeof connectionScopes === 'undefined' ? 'undefined' : _typeof(connectionScopes)) === "object" ? connectionScopes : {};
params = (typeof params === 'undefined' ? 'undefined' : _typeof(params)) === "object" ? params : {};
// by default is null because we need to know if it was set when we curate the responseType
redirectUrl = typeof redirectUrl === "string" && redirectUrl ? redirectUrl : null;
autoParseHash = typeof autoParseHash === "boolean" ? autoParseHash : true;
redirect = typeof redirect === "boolean" ? redirect : true;
responseMode = typeof responseMode === "string" ? responseMode : undefined;
state = typeof state === "string" ? state : undefined;
nonce = typeof nonce === "string" ? nonce : undefined;
// if responseType was not set and there is a redirectUrl, it defaults to code. Otherwise token.
responseType = typeof responseType === "string" ? responseType : redirectUrl ? "code" : "token";
// now we set the default because we already did the validation
redirectUrl = redirectUrl || window.location.href;
sso = typeof sso === "boolean" ? sso : true;
if (!oidcConformant && (0, _trim2.default)(params.scope || "") === "openid profile") {
warn(options, "Usage of scope 'openid profile' is not recommended. See https://auth0.com/docs/scopes for more details.");
}
if (oidcConformant && !redirect && responseType.indexOf('id_token') > -1) {
throw new Error("It is not posible to request an 'id_token' while using popup mode.");
}
// for legacy flow, the scope should default to openid
if (!oidcConformant && !params.scope) {
params.scope = 'openid';
}
return _immutable2.default.fromJS({
audience: audience,
connectionScopes: connectionScopes,
params: params,
autoParseHash: autoParseHash,
redirect: redirect,
redirectUrl: redirectUrl,
responseMode: responseMode,
responseType: responseType,
sso: sso,
state: state,
nonce: nonce
});
}
function withAuthOptions(m, opts) {
return _immutable2.default.fromJS(opts).merge(get(m, "auth")).toJS();
}
function extractClientBaseUrlOption(opts, domain) {
if (opts.clientBaseUrl && typeof opts.clientBaseUrl === "string") {
return opts.clientBaseUrl;
}
if (opts.configurationBaseUrl && typeof opts.configurationBaseUrl === "string") {
return opts.configurationBaseUrl;
}
if (opts.assetsUrl && typeof opts.assetsUrl === "string") {
return opts.assetsUrl;
}
var domainUrl = "https://" + domain;
var hostname = (0, _url_utils.parseUrl)(domainUrl).hostname;
var DOT_AUTH0_DOT_COM = ".auth0.com";
var AUTH0_US_CDN_URL = "https://cdn.auth0.com";
if ((0, _string_utils.endsWith)(hostname, DOT_AUTH0_DOT_COM)) {
var parts = hostname.split(".");
return parts.length > 3 ? "https://cdn." + parts[parts.length - 3] + DOT_AUTH0_DOT_COM : AUTH0_US_CDN_URL;
} else {
return domainUrl;
}
}
function extractTenantBaseUrlOption(opts, domain) {
if (opts.configurationBaseUrl && typeof opts.configurationBaseUrl === "string") {
return (0, _urlJoin2.default)(opts.configurationBaseUrl, 'info-v1.js');
}
if (opts.assetsUrl && typeof opts.assetsUrl === "string") {
return opts.assetsUrl;
}
var domainUrl = "https://" + domain;
var hostname = (0, _url_utils.parseUrl)(domainUrl).hostname;
var DOT_AUTH0_DOT_COM = ".auth0.com";
var AUTH0_US_CDN_URL = "https://cdn.auth0.com";
var parts = hostname.split(".");
var tenant_name = parts[0];
var domain;
if ((0, _string_utils.endsWith)(hostname, DOT_AUTH0_DOT_COM)) {
domain = parts.length > 3 ? "https://cdn." + parts[parts.length - 3] + DOT_AUTH0_DOT_COM : AUTH0_US_CDN_URL;
return (0, _urlJoin2.default)(domain, 'tenants', 'v1', tenant_name + '.js');
} else {
return (0, _urlJoin2.default)(domainUrl, 'info-v1.js');
}
}
function extractLanguageBaseUrlOption(opts, domain) {
if (opts.languageBaseUrl && typeof opts.languageBaseUrl === "string") {
return opts.languageBaseUrl;
}
if (opts.assetsUrl && typeof opts.assetsUrl === "string") {
return opts.assetsUrl;
}
return "https://cdn.auth0.com";
}
function render(m) {
return tset(m, "render", true);
}
exports.reset = reset;
function setLoggedIn(m, value) {
return tset(m, "loggedIn", value);
}
function loggedIn(m) {
return tget(m, "loggedIn", false);
}
function defaultADUsernameFromEmailPrefix(m) {
return get(m, "defaultADUsernameFromEmailPrefix", true);
}
function warn(x, str) {
var shouldOutput = _immutable.Map.isMap(x) ? !ui.disableWarnings(x) : !x.disableWarnings;
if (shouldOutput && console && console.warn) {
console.warn(str);
}
}
function error(x, str) {
var shouldOutput = _immutable.Map.isMap(x) ? !ui.disableWarnings(x) : !x.disableWarnings;
if (shouldOutput && console && console.error) {
console.error(str);
}
}
function allowedConnections(m) {
return tget(m, "allowedConnections") || get(m, "allowedConnections");
}
function connections(m) {
for (var _len = arguments.length, strategies = Array(_len > 2 ? _len - 2 : 0), _key = 2; _key < _len; _key++) {
strategies[_key - 2] = arguments[_key];
}
var type = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : undefined;
if (arguments.length === 1) {
return tget(m, "connections", (0, _immutable.Map)()).filter(function (v, k) {
return k !== "unknown";
}).valueSeq().flatten(true);
}
var xs = tget(m, ["connections", type], (0, _immutable.List)());
return strategies.length > 0 ? xs.filter(function (x) {
return ~strategies.indexOf(x.get("strategy"));
}) : xs;
}
function connection(m) {
var type = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : undefined;
for (var _len2 = arguments.length, strategies = Array(_len2 > 2 ? _len2 - 2 : 0), _key2 = 2; _key2 < _len2; _key2++) {
strategies[_key2 - 2] = arguments[_key2];
}
return connections.apply(undefined, [m, type].concat(strategies)).get(0);
}
function hasOneConnection(m) {
var type = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : undefined;
var xs = connections(m);
return xs.count() === 1 && (!type || xs.getIn([0, "type"]) === type);
}
function hasOnlyConnections(m) {
var type = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : undefined;
var all = connections(m).count();
for (var _len3 = arguments.length, strategies = Array(_len3 > 2 ? _len3 - 2 : 0), _key3 = 2; _key3 < _len3; _key3++) {
strategies[_key3 - 2] = arguments[_key3];
}
var filtered = connections.apply(undefined, [m, type].concat(strategies)).count();
return all > 0 && all === filtered;
}
function hasSomeConnections(m) {
var type = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : undefined;
for (var _len4 = arguments.length, strategies = Array(_len4 > 2 ? _len4 - 2 : 0), _key4 = 2; _key4 < _len4; _key4++) {
strategies[_key4 - 2] = arguments[_key4];
}
return countConnections.apply(undefined, [m, type].concat(strategies)) > 0;
}
function countConnections(m) {
var type = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : undefined;
for (var _len5 = arguments.length, strategies = Array(_len5 > 2 ? _len5 - 2 : 0), _key5 = 2; _key5 < _len5; _key5++) {
strategies[_key5 - 2] = arguments[_key5];
}
return connections.apply(undefined, [m, type].concat(strategies)).count();
}
function findConnection(m, name) {
return connections(m).find(function (m1) {
return m1.get("name") === name;
});
}
function hasConnection(m, name) {
return !!findConnection(m, name);
}
function filterConnections(m) {
var allowed = allowedConnections(m);
var order = allowed.count() === 0 ? function (_) {
return 0;
} : function (c) {
return allowed.indexOf(c.get("name"));
};
return tset(m, "connections", (0, _index2.clientConnections)(m).map(function (cs) {
return cs.filter(function (c) {
return order(c) >= 0;
}).sort(function (c1, c2) {
return order(c1) - order(c2);
});
}));
}
function runHook(m, str) {
for (var _len6 = arguments.length, args = Array(_len6 > 2 ? _len6 - 2 : 0), _key6 = 2; _key6 < _len6; _key6++) {
args[_key6 - 2] = arguments[_key6];
}
return get(m, "hookRunner").apply(undefined, [str, m].concat(args));
}
function emitEvent(m, str) {
for (var _len7 = arguments.length, args = Array(_len7 > 2 ? _len7 - 2 : 0), _key7 = 2; _key7 < _len7; _key7++) {
args[_key7 - 2] = arguments[_key7];
}
setTimeout(function () {
var emitEventFn = get(m, "emitEventFn");
var hadListener = emitEventFn.apply(undefined, [str].concat(args));
// Handle uncaught custom error
if (str === "unrecoverable_error" && !hadListener) {
throw new (Function.prototype.bind.apply(Error, [null].concat(args)))();
}
}, 0);
}
function loginErrorMessage(m, error, type) {
// NOTE: previous version of lock checked for status codes and, at
// some point, if the status code was 401 it defaults to an
// "invalid_user_password" error (actually the
// "wrongEmailPasswordErrorText" dict entry) instead of checking
// explicitly. We should figure out if there was a reason for that.
if (error.status === 0) {
return i18n.str(m, ["error", "login", "lock.network"]);
}
// Custom rule error (except blocked_user)
if (error.code === "rule_error") {
return error.description || i18n.str(m, ["error", "login", "lock.fallback"]);
}
var INVALID_MAP = {
code: "lock.invalid_code",
email: "lock.invalid_email_password",
username: "lock.invalid_username_password"
};
var code = error.error || error.code;
if (code === "invalid_user_password" && INVALID_MAP[type]) {
code = INVALID_MAP[type];
}
if (code === "a0.mfa_registration_required") {
code = "lock.mfa_registration_required";
}
if (code === "a0.mfa_invalid_code") {
code = "lock.mfa_invalid_code";
}
return i18n.str(m, ["error", "login", code]) || i18n.str(m, ["error", "login", "lock.fallback"]);
}
// TODO: rename to something less generic that is easier to grep
function stop(m, error) {
if (error) {
setTimeout(function () {
return emitEvent(m, "unrecoverable_error", error);
}, 17);
}
return set(m, "stopped", true);
}
function hasStopped(m) {
return get(m, "stopped");
}
function hashCleanup(m) {
return get(m, "hashCleanup");
}
function emitHashParsedEvent(m, parsedHash) {
emitEvent(m, "hash_parsed", parsedHash);
}
function emitAuthenticatedEvent(m, result) {
emitEvent(m, "authenticated", result);
}
function emitAuthorizationErrorEvent(m, error) {
emitEvent(m, "authorization_error", error);
}
function emitUnrecoverableErrorEvent(m, error) {
emitEvent(m, "unrecoverable_error", error);
}
function showBadge(m) {
return (0, _index2.hasFreeSubscription)(m) || false;
}
function overrideOptions(m, opts) {
if (!opts) opts = {};
if (opts.allowedConnections) {
m = tset(m, "allowedConnections", _immutable2.default.fromJS(opts.allowedConnections));
}
if (opts.socialButtonStyle) {
var curated = (0, _index.processSocialOptions)(opts);
m = tsetSocial(m, "socialButtonStyle", curated.socialButtonStyle);
}
if (opts.flashMessage) {
var key = "success" === opts.flashMessage.type ? "globalSuccess" : "globalError";
m = tset(m, key, opts.flashMessage.text);
}
if (opts.auth && opts.auth.params) {
m = tset(m, "authParams", _immutable2.default.fromJS(opts.auth.params));
}
if (opts.theme) {
if (opts.theme.primaryColor) {
m = tset(m, ["ui", "primaryColor"], opts.theme.primaryColor);
}
if (opts.theme.logo) {
m = tset(m, ["ui", "logo"], opts.theme.logo);
}
}
if (opts.language || opts.languageDictionary) {
if (opts.language) {
m = tset(m, ["ui", "language"], opts.language);
}
if (opts.languageDictionary) {
m = tset(m, ["ui", "dict"], opts.languageDictionary);
}
m = i18n.initI18n(m);
}
if (typeof opts.rememberLastLogin === "boolean") {
m = tset(m, "rememberLastLogin", opts.rememberLastLogin);
}
return m;
}
|
//All the cookie setting stuff
function catapultSetCookie(cookieName, cookieValue, nDays) {
var today = new Date();
var expire = new Date();
if (nDays==null || nDays==0) nDays=1;
expire.setTime(today.getTime() + 3600000*24*nDays);
document.cookie = cookieName+"="+escape(cookieValue)+ ";expires="+expire.toGMTString()+"; path=/";
}
function catapultReadCookie(cookieName) {
var theCookie=" "+document.cookie;
var ind=theCookie.indexOf(" "+cookieName+"=");
if (ind==-1) ind=theCookie.indexOf(";"+cookieName+"=");
if (ind==-1 || cookieName=="") return "";
var ind1=theCookie.indexOf(";",ind+1);
if (ind1==-1) ind1=theCookie.length;
// Returns true if the versions match
return ctcc_vars.version == unescape(theCookie.substring(ind+cookieName.length+2,ind1));
}
function catapultDeleteCookie(cookieName) {
document.cookie = cookieName + '=;expires=Thu, 01 Jan 1970 00:00:01 GMT;path=/';
}
function catapultAcceptCookies() {
catapultSetCookie('catAccCookies', ctcc_vars.version, ctcc_vars.expiry);
jQuery("html").removeClass('has-cookie-bar');
jQuery("html").css("margin-top","0");
jQuery("#catapult-cookie-bar").fadeOut();
}
// The function called by the timer
function ctccCloseNotification() {
catapultAcceptCookies();
}
// The function called if first page only is specified
function ctccFirstPage() {
if ( ctcc_vars.method ) {
catapultSetCookie('catAccCookies', ctcc_vars.version, ctcc_vars.expiry);
}
}
jQuery(document).ready(function($){
$('.x_close').on('click', function(){
catapultAcceptCookies();
});
}); |
require({baseUrl:requirejs.isBrowser?"./":"./universal/"},["spell"],function(e){doh.register("universal",[function(n){n.is("spell",e.name),n.is("newt",e.newtName),n.is("tail",e.tailName),n.is("eye",e.eyeName)}]),doh.run()}); |
var MonopolyTile = require('../monopoly_tile'),
inherits = require('util').inherits;
function Go() {
MonopolyTile.call(this, "Go");
};
inherits(Go, MonopolyTile);
Go.prototype.performLandingAction = function(game) {
return Go.super_.prototype.performLandingAction.call(this, game);
};
module.exports = Go;
|
/**
* Pseudoclass to manage the Accessing page
**/
function Accessing(){
"use strict";
//>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>><<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<
//>>>>>>>>>>>>>>>>>>>>>>>>>>>>>> ATTRIBUTES <<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<
//>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>><<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<
var obj=this;
obj.currentForm="login";
//>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>><<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<
//>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>> METHODS <<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<
//>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>><<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<
/**
* Configure and init the systems Scripts
* @param {Object} parameters Objeto que contiene los parámetros del script
**/
obj.init=function(parameters){
//Genera los eventos para los objetos del home
obj.events(parameters);
};
/**
* Set the login, logout and signup events
* @param {Object} parameters Objeto que contiene los parámetros del script
**/
obj.events=function(parameters){
parameters.signupForm.find(".button").click(function(){
obj.signup(parameters.signupForm);
});
parameters.loginForm.find(".button").click(function(){
obj.login(parameters.loginForm);
});
parameters.signupForm.find("input").click(function(){
$(this).removeClass("errorPlaceholder");
}).focus(function(){
obj.currentForm="signup";
});
parameters.loginForm.find("input").click(function(){
$(this).removeClass("errorPlaceholder");
}).focus(function(){
obj.currentForm="login";
});
parameters.loginForm.find("input").first().focus();
//Cuando se hace click en enter
$(document).keypress(function(e) {
if(e.which===13) {
if(obj.currentForm==="login"){
obj.login(parameters.loginForm);
}else{
obj.signup(parameters.signupForm);
}
}
});
};
/**
* Clear the fields of a form
* @param {Object} form Formulario para limpiar
**/
obj.formReset=function(form){
form.find("input").val("");
form.find("input").first().val("").focus();
};
/**
* Main method to signup, executed when the signup event is executed
* @param {Object} form Formulario de registro
**/
obj.signup=function(form){
var fields=obj.signupValidate(form);
if(fields){
maqinato.ajax.signup(fields.email,fields.password,fields.name,fields.lastname,function(response){
if(response==="exist"){
maqinato.dialog({
title:_("Correo ya existe"),
html:_("El correo ya está registrado, por favor intente de nuevo")
});
}else if(response==="success"){
maqinato.redirect("main");
}else{
maqinato.dialog({
title:_("Correo o contraseña erroneos"),
html:_("Por favor verifique los datos e intente de nuevo")
});
}
});
obj.formReset(form);
}
};
/**
* Valida los campos del formulario de registro
* @param {Object} form Formulario a verificar
* @return {mixed} false si los datos no son válidos, un obejto con los valores
* si los datos son válidos
* */
obj.signupValidate=function(form){
var email=form.find("#sgn_email");
var password=form.find("#sgn_password");
var confirm=form.find("#sgn_confirm");
var name=form.find("#sgn_name");
var lastname=form.find("#sgn_lastname");
var fields={};
if($.trim(name.val()).length>2){
fields.name=$.trim(name.val());
if($.trim(lastname.val()).length>2){
fields.lastname=$.trim(lastname.val());
if(Security.isEmail($.trim(email.val()))){
fields.email=$.trim(email.val());
if(Security.isPassword($.trim(password.val()))){
if($.trim(password.val())===$.trim(confirm.val())){
fields.password=$.trim(password.val());
}else{
confirm.val("").addClass("errorPlaceholder").attr("Placeholder",_("No coincide con el password"));
fields=false;
}
}else{
password.val("").addClass("errorPlaceholder").attr("Placeholder",_("Entre 6 and 18 characters: @#$%_-."));
fields=false;
}
}else{
email.val("").addClass("errorPlaceholder").attr("Placeholder",_("correo@ejemplo.com"));
fields=false;
}
}else{
lastname.val("").addClass("errorPlaceholder").attr("Placeholder",_("El apellido no puede estar vacío"));
fields=false;
}
}else{
name.val("").addClass("errorPlaceholder").attr("Placeholder",_("El nombre no puede estar vacío"));
fields=false;
}
return fields;
};
/**
* Main method to login, executed when the login event is executed
* @param {Object} form Formulario de login
**/
obj.login=function(form){
var fields=obj.validateLogin(form);
if(fields){
maqinato.ajax.login(fields.email,fields.password,fields.keep,function(response){
if(response==="success"){
maqinato.redirect("main");
}else{
maqinato.dialog({
title:_("Correo o contraseña erroneos"),
html:_("Por favor verifique los datos e intente de nuevo")
});
}
});
obj.formReset(form);
}
};
/**
* Valida los campos del formulario de login
* @param {Object} form Formulario a verificar
* @return {mixed} false si los datos no son válidos, un obejto con los valores
* si los datos son válidos
* */
obj.validateLogin=function(form){
var email=form.find("#email");
var password=form.find("#password");
var keep=form.find("#keep").is(':checked');
var fields={};
if(Security.isEmail($.trim(email.val()))){
fields.email=$.trim(email.val());
if(Security.isPassword($.trim(password.val()))){
fields.password=$.trim(password.val());
fields.keep=true;
}else{
password.val("").addClass("errorPlaceholder").attr("Placeholder",_("Entre 6 and 18 characters: @#$%_-."));
fields=false;
}
}else{
email.val("").addClass("errorPlaceholder").attr("Placeholder",_("correo@ejemplo.com"));
fields=false;
}
return fields;
};
} |
var main = {};
var io = require('socket.io-client');
main.sock = function(address){
var socket = io.connect(address, {reconnect: true});
// Add a connect listener
socket.on('connect', function(socket) {
console.log('Connected!');
});
return {
s:socket
}
}
module.exports = main;
|
/// <autosync enabled="true" />
/// <reference path="js/bootstrap-slider,js.js" />
/// <reference path="js/site.js" />
/// <reference path="lib/bootstrap/dist/js/bootstrap.js" />
/// <reference path="lib/jquery/dist/jquery.js" />
/// <reference path="lib/jquery-validation/dist/jquery.validate.js" />
/// <reference path="lib/jquery-validation-unobtrusive/jquery.validate.unobtrusive.js" />
|
import { createStore } from 'redux'
const initialState = {
dishList: [0],
language: 'EN'
}
export function reducer(state = initialState, action) {
let newDishList = [];
switch (action.type) {
case 'AddNewCard':
newDishList = state.dishList.slice();
newDishList.push(state.dishList.length);
return Object.assign({}, state, {
dishList: newDishList
});
case 'ChangeLanguage':
// Placeholder, nothing happens here.
return state;
default:
return state;
}
}
export const languageSelector = state => state.language;
export const dishListSelector = state => state.dishList;
export const store = createStore(reducer);
|
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
'use strict';
module.exports = {
moduleType: 'locale',
name: 'he',
dictionary: {},
format: {
days: ['ראשון', 'שני', 'שלישי', 'רביעי', 'חמישי', 'שישי', 'שבת'],
shortDays: ['א\'', 'ב\'', 'ג\'', 'ד\'', 'ה\'', 'ו\'', 'שבת'],
months: [
'ינואר', 'פברואר', 'מרץ', 'אפריל', 'מאי', 'יוני',
'יולי', 'אוגוסט', 'ספטמבר', 'אוקטובר', 'נובמבר', 'דצמבר'
],
shortMonths: ['1', '2', '3', '4', '5', '6', '7', '8', '9', '10', '11', '12'],
date: '%d/%m/%Y'
}
};
|
/*
* Description: Ghent Trees Application
* Modified: 10-11-2015
* Version: 1.0.0
* Author: Philippe De Pauw - Waterschoot
* -----------------------------------------------
* Ghent Bomen Inventaris API: http://datatank.stad.gent/4/milieuennatuur/bomeninventaris.json
*/
// Anonymous function executed when document loaded
(function() {
// Describe an App object with own functionalities
var App = {
init: function() {
this.registerNavigationToggleListeners();// Register All Navigation Toggle Listeners
this.registerWindowListeners();// Register All Navigation Toggle Listeners
},
registerNavigationToggleListeners: function() {
var toggles = document.querySelectorAll('.navigation-toggle');
if(toggles != null && toggles.length > 0) {
var toggle = null;
for(var i = 0; i < toggles.length; i++ ) {
toggle = toggles[i];
toggle.addEventListener('click', function(ev) {
ev.preventDefault();
document.querySelector('body').classList.toggle(this.dataset.navtype);
return false;
});
}
}
},
registerWindowListeners: function() {
window.addEventListener('resize', function(ev) {
if(document.querySelector('body').classList.contains('offcanvas-open')) {
document.querySelector('body').classList.remove('offcanvas-open');
}
if(document.querySelector('body').classList.contains('headernav-open')) {
document.querySelector('body').classList.remove('headernav-open');
}
});
}
};
App.init();// Intialize the application
})(); |
'use strict';
/**
* Module dependencies.
*/
var config = require('../config'),
mongoose = require('./mongoose'),
express = require('./express'),
chalk = require('chalk'),
job = require('./job'),
seed = require('./seed');
function seedDB() {
if (config.seedDB && config.seedDB.seed) {
console.log(chalk.bold.red('Warning: Database seeding is turned on'));
seed.start();
}
job.start();
}
// Initialize Models
mongoose.loadModels(seedDB);
module.exports.loadModels = function loadModels() {
mongoose.loadModels();
};
module.exports.init = function init(callback) {
mongoose.connect(function (db) {
// Initialize express
var app = express.init(db);
if (callback) callback(app, db, config);
});
};
module.exports.start = function start(callback) {
var _this = this;
_this.init(function (app, db, config) {
// Start the app by listening on <port>
app.listen(config.port, function () {
// Logging initialization
console.log('--');
console.log(chalk.green(config.app.title));
console.log(chalk.green('Environment:\t\t\t' + process.env.NODE_ENV));
console.log(chalk.green('Port:\t\t\t\t' + config.port));
console.log(chalk.green('Database:\t\t\t\t' + config.db.uri));
if (process.env.NODE_ENV === 'secure') {
console.log(chalk.green('HTTPs:\t\t\t\ton'));
}
console.log(chalk.green('App version:\t\t\t' + config.meanjs.version));
if (config.meanjs['meanjs-version'])
console.log(chalk.green('MEAN.JS version:\t\t\t' + config.meanjs['meanjs-version']));
console.log('--');
if (callback) callback(app, db, config);
});
});
};
|
$( document ).ready(function() {
$.getJSON("/sentiment/line_chart", function(result) {
var all_candidates = {}
for (candidate in result['candidates']) {
var candidateData = [];
for (k in result['candidates'][candidate]){
candidateData.push({"minute": k, "score": result['candidates'][candidate][k]})
}
all_candidates[candidate] = candidateData
}
var vis = d3.select("#visualisation"),
WIDTH = 1000,
HEIGHT = 500,
MARGINS = {
top: 20,
right: 20,
bottom: 20,
left: 50
},
xScale = d3.scale.linear().range([MARGINS.left, WIDTH - MARGINS.right]).domain([40,195]);
yScale = d3.scale.linear().range([HEIGHT - MARGINS.top, MARGINS.bottom]).domain([0,1]);
xAxis = d3.svg.axis()
.scale(xScale);
yAxis = d3.svg.axis()
.scale(yScale)
.orient("left");
vis.append("svg:g")
.attr("transform", "translate(0," + (HEIGHT - MARGINS.bottom) + ")")
.call(xAxis);
vis.append("svg:g")
.attr("transform", "translate(" + (MARGINS.left) + ",0)")
.call(yAxis);
var lineGen = d3.svg.line()
.x(function(d) {
return xScale(d.minute);
})
.y(function(d) {
return yScale(d.score);
}).interpolate("basis");
var colors = {"Trump": "red", "Bush": "purple", "Walker": "black", "Huckabee": "yellow", "Carson": "blue", "Cruz": "grey", "Rubio": "orange", "Paul": "brown", "Christie": "pink", "Kasich": "green"}
for (candidate in all_candidates) {
vis.append('svg:path')
.attr('class', candidate)
.attr('d', lineGen(all_candidates[candidate]))
.attr('stroke', colors[candidate])
.attr('stroke-width', 2)
.attr('fill', "transparent");
}
$("path").click(function(event) {
var candidate = $(this).attr("class")
var xCoord = event['offsetX']
var time = xCoord / 1000 * 155 + 40
console.log(time)
var rating = result['candidates'][candidate][parseInt(time)]
console.log(rating)
$.getJSON("/sentiment/tweet", {"time": time, "candidate": candidate, "rating": rating}, function(data) {
console.log(data)
$("#tweet").empty().append("<p>" + data.tweet + "</p>")
})
})
$("path").on("mouseover", function() {
d3.select(this)
.attr("opacity", "0.5");
});
$("path").on("mouseout", function() {
d3.select(this)
.attr("opacity", "1");
});
$(".candidate_buttons").on("click", function() {
var ID = $(this).attr("id")
$("."+ID).toggle()
})
})
});
|
import React from 'react';
import { View, StyleSheet, Animated} from 'react-native';
import AppStyles from 'dedicate/AppStyles';
import Textbox from 'fields/Textbox';
import IconMarker from 'icons/IconMarker';
import MapView, {Marker} from 'react-native-maps';
import Geocoder from 'react-native-geocoder';
// NOTE: Find Google Android Maps Developer API Key within /android/app/src/main/AndroidManifest.xml : com.google.android.geo.API_KEY
export default class LocationPicker extends React.Component {
constructor(props){
super(props);
this.state = {
location: {
latitude: 28.040990,
longitude: -82.693947,
latitudeDelta: 0.0922,
longitudeDelta: 0.0421,
},
markers:[],
timer:null, //used for waiting until user is done typing address
value: props.defaultValue || '',
opacity:new Animated.Value(0)
}
//Geocoder fallback
Geocoder.fallbackToGoogle('AIzaSyCBmthrFiDHGhNXkLiXFNV_RZuvqBjXKYA');
//bind methods
this.onMapReady = this.onMapReady.bind(this);
}
componentWillMount() {
if(this.state.value != ''){
//load existing location into map
this.onUpdateLocation(this.state.value);
}else{
//load user's current position into map
navigator.geolocation.getCurrentPosition(
(position) => {
//create a marker for the location
const location = {latitude:position.coords.latitude, longitude:position.coords.longitude};
const marker = {
latlng: location,
title: this.props.markerTitle || 'Marker',
description: 'Current location'
};
//get top address based on latitude & longitude
Geocoder.geocodePosition({lat:location.latitude, lng:location.longitude}).then(results => {
if(results != null && results.length > 0){
this.setState({value:results[0].formattedAddress});
}
})
.catch((error) => {});
//update location & marker information in state
this.setState({
location:{
...location,
latitudeDelta: 0.01,
longitudeDelta: 0.01,
},
markers:[marker]
});
},
(error) => {},
{ timeout: 30000 }
);
}
}
onChangeText(text){
//get longitude & latitude from location text
const that = this;
this.setState({value:text}, () => {
clearTimeout(this.state.timer);
this.setState({
timer:setTimeout(function(){
that.onUpdateLocation.call(that, text);
}, 2000)
});
});
}
onUpdateLocation(text){
const that = this;
//get longitude & latitude from address text
Geocoder.geocodeAddress(text).then(
(results) => {
if(results.length > 0){
//get longitudeDelta & latitudeDelta from long & lat
const location = getRegionForCoordinates([
{latitude:results[0].position.lat, longitude:results[0].position.lng}
]);
//create a marker for the location
const marker = {
latlng: {latitude:location.latitude, longitude:location.longitude},
title: this.props.markerTitle || 'Marker',
description: text
};
//check if formatted address is different from TextBox value
const value = results[0].formattedAddress;
const changed = this.state.value != value;
this.setState({ location:location, markers:[marker], value:value },
() => {
//raise onChangeEvent only if formatted address is different from TextBox value
if(changed == true && typeof this.props.onChangeText != 'undefined'){
this.props.onChangeText.call(that, value);
}
}
);
}
}
).catch(err => console.log(err))
}
onMapReady(){
Animated.timing(
this.state.opacity,
{
toValue:1,
duration:1000,
delay:1000
}
).start();
}
render(){
const that = this;
return (
<View>
<View>
<Textbox {...this.props}
value={this.state.value}
onChangeText={(text) => {
if(typeof this.props.onChangeText != 'undefined'){
this.props.onChangeText.call(that, text);
}
this.onChangeText.call(that, text);
}}
maxLength={64}
borderColor={this.props.borderColor || AppStyles.fieldOutlineColor}
></Textbox>
</View>
<Animated.View style={[styles.mapContainer, this.props.mapStyle || {}, {opacity:this.state.opacity}]}>
<MapView style={styles.mapView}
region={this.state.location}
customMapStyle={AppStyles.map}
onMapReady={this.onMapReady}
>
{this.state.markers.map(marker => (
<Marker key={'marker'} coordinate={marker.latlng} title={marker.title} description={marker.description}>
<IconMarker size="small"/>
</Marker>
))}
</MapView>
</Animated.View>
</View>
);
}
}
function getRegionForCoordinates(points) {
let minX, maxX, minY, maxY;
// init first point
((point) => {
minX = point.latitude;
maxX = point.latitude;
minY = point.longitude;
maxY = point.longitude;
})(points[0]);
// calculate rect
points.map((point) => {
minX = Math.min(minX, point.latitude);
maxX = Math.max(maxX, point.latitude);
minY = Math.min(minY, point.longitude);
maxY = Math.max(maxY, point.longitude);
});
const midX = (minX + maxX) / 2;
const midY = (minY + maxY) / 2;
let deltaX = (maxX - minX);
let deltaY = (maxY - minY);
if(deltaX < 0.0043){deltaX = 0.01;}
if(deltaY < 0.0043){deltaY = 0.01;}
return {
latitude: midX,
longitude: midY,
latitudeDelta: deltaX,
longitudeDelta: deltaY
};
}
const styles = StyleSheet.create({
mapContainer:{width:'100%', height:200, justifyContent: 'flex-end', alignItems: 'center'},
mapView:{position:'absolute', top:0, right:0, bottom:0, left:0 }
}); |
module.exports = {
debug : false,
};
module.exports.given = function (arguments) {
arguments.forEach(function (flag) {
flag = flag.slice(2);
// kv = flag.includes("=") //ES6 compliant only...
//In the future i'll add stuff to further customize karma.
switch (flag) {
case "debug":
module.exports.debug = true;
break;
default:
break;
}
})
}
|
// @flow
import type { ContentBlock, ContentState } from 'draft-js'
import {
ANNOTATION_ENTITY_TYPE,
} from '../constants'
import Annotation from '../components/Annotation'
export const findNoteEntities = (
contentBlock: ContentBlock,
callback: Function,
contentState: ContentState
) => {
contentBlock.findEntityRanges(
character => {
const entityKey = character.getEntity()
return (
entityKey !== null &&
contentState.getEntity(entityKey).getType() === ANNOTATION_ENTITY_TYPE
)
},
callback,
)
}
export const annotationDecorator = (
hoverEntityKey: string,
onHover: (entityKey: string) => void,
onClick: (entityKey: string) => void,
) => ({
strategy: findNoteEntities,
component: Annotation(hoverEntityKey, onHover, onClick)
})
|
var username = location.search && encodeURIComponent(location.search.slice(1)), source
$(function(){
if(!username){
$('#wrapper').html('<strong>请在url上附加监听的用户,方式如下:</strong><p><a href="http://jsconsole.kf0309.3g.qq.com/?yourRtxName">http://jsconsole.kf0309.3g.qq.com/?yourRtxName</a></p>')
return
}
$('#debug').attr('href', 'debug.html?' + username)
$('#rtx').text(username)
/* jQuery post sucks, 回调不执行,就不能靠谱点吗!!!!!!*/
var post = function(url, data, cb){
var xhr = new XMLHttpRequest(), form = new FormData()
for(var key in data){
form.append(key, data[key])
}
xhr.timeout = 5000
xhr.addEventListener('load', function(){
cb.call(this, JSON.parse(this.responseText))
})
xhr.addEventListener('timeout', function(e){
alert('请求超时')
})
xhr.addEventListener('error', function(e){
console.log('请求出错')
})
xhr.open('POST', url, true)
xhr.send(form)
}
/**
* 提交控制台脚本
*/
var runScript = function (){
var script = editor.getValue()
if(!script || !username){
alert('执行脚本和监听用户都不能为空')
return
}
if(source && source.readyState == source.OPEN){
post('./input', {username:username, content:encodeURIComponent(script)}, function(json){
if(json.ret == 0){
if(json.openDebug){
$('#output').val('脚本提交成功,等待远程调试页面执行结果返回...')
}else{
$('#output').val('你还没有打开任何调试页面.在移动设备上打开后,重新运行代码')
}
}
})
}else{
alert('连接已经被关闭,点击确定刷新页面继续调试')
location.reload()
}
}
/**
* CodeMirror语法高亮
*/
var editor = CodeMirror.fromTextArea($("#text")[0], {
mode: "javascript",
lineNumbers: true,
lineWrapping: true,
onCursorActivity: function() {
editor.setLineClass(hlLine, null, null);
hlLine = editor.setLineClass(editor.getCursor().line, null, "activeline");
},
onKeyEvent : function(self,e){
if(e.type == 'keydown'){
if(e.ctrlKey && e.which == 13){
e.preventDefault()
runScript()
}
}
}
})
var hlLine = editor.setLineClass(0, "activeline")
var closeConnection = function(msg){
//服务器的close事件不一定能正确响应
source.close()
source = null
document.write(msg)
document.title = '-__-你被T了'
}
/**
* Server Push,接受远程执行结果
*/
source = new EventSource('./rev_polling?' + username)
source.addEventListener('message', function(e){
console.log('接受远程数据:',e)
var key = 'jsconsole_messages', result = decodeURIComponent(e.data)
$('#output').val(result)
var messages = (localStorage[key] && JSON.parse(localStorage[key])) || []
messages.push(result)
localStorage[key] = JSON.stringify(messages)
})
source.addEventListener('kicked',function(e){
closeConnection('为了防止控制台过多干扰调试结果,同一时间段只允许使用一个控制台.刷新页面可以抢夺当前用户的控制权')
})
source.addEventListener('max', function(e){
closeConnection('当前访问人数超出了服务器限制.刷新页面可继续使用')
})
source.addEventListener('ready', function(){
$('#output').val('调试页面已经就绪,开始coding吧!')
})
source.addEventListener('rest', function(){
$('#output').val('没找到调试页面,打开一个调试页面后重新运行代码')
})
setTimeout(function(){
closeConnection('为了节约服务器资源,每个长连接最多持续5分钟.刷新页面后继续使用')
}, 5*1000*60)
$('#text').focus()
$('#sub').on('click', runScript)
/**
* 锁定代码,新请求自动执行一次编辑器的脚本
*/
$('#lock_code').on('click', function(){
var content = editor.getValue()
if(!content){
alert('请先输入代码')
return
}
var mask = $('#mask'), btn = this
if(mask[0].style.display == 'none'){
post('./lock', {username:username, content: encodeURIComponent(content)}, function(json){
if(json.ret == 0){
mask.show()
$(btn).text('解除锁定')
$('#sub').attr('disabled','').css('cursor','text')
}
})
}else{
post('./unlock', {username:username}, function(json){
if(json.ret == 0){
mask.hide()
$(btn).text('锁定代码')
$('#sub').removeAttr('disabled').css('cursor','pointer')
}
})
}
})
}) |
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__(30);
module.exports = __webpack_require__(30);
/***/ }),
/***/ 30:
/***/ (function(module, exports) {
(function( window, undefined ) {
kendo.cultures["ar-MA"] = {
name: "ar-MA",
numberFormat: {
pattern: ["n-"],
decimals: 2,
",": ",",
".": ".",
groupSize: [3],
percent: {
pattern: ["-n %","n %"],
decimals: 2,
",": ",",
".": ".",
groupSize: [3],
symbol: "%"
},
currency: {
name: "Moroccan Dirham",
abbr: "MAD",
pattern: ["$n-","$ n"],
decimals: 2,
",": ",",
".": ".",
groupSize: [3],
symbol: "د.م."
}
},
calendars: {
standard: {
days: {
names: ["الأحد","الإثنين","الثلاثاء","الأربعاء","الخميس","الجمعة","السبت"],
namesAbbr: ["الأحد","الإثنين","الثلاثاء","الأربعاء","الخميس","الجمعة","السبت"],
namesShort: ["ح","ن","ث","ر","خ","ج","س"]
},
months: {
names: ["يناير","فبراير","مارس","أبريل","ماي","يونيو","يوليوز","غشت","شتنبر","أكتوبر","نونبر","دجنبر"],
namesAbbr: ["يناير","فبراير","مارس","أبريل","ماي","يونيو","يوليوز","غشت","شتنبر","أكتوبر","نونبر","دجنبر"]
},
AM: ["ص","ص","ص"],
PM: ["م","م","م"],
patterns: {
d: "dd-MM-yyyy",
D: "dd MMMM, yyyy",
F: "dd MMMM, yyyy H:mm:ss",
g: "dd-MM-yyyy H:mm",
G: "dd-MM-yyyy H:mm:ss",
m: "dd MMMM",
M: "dd MMMM",
s: "yyyy'-'MM'-'dd'T'HH':'mm':'ss",
t: "H:mm",
T: "H:mm:ss",
u: "yyyy'-'MM'-'dd HH':'mm':'ss'Z'",
y: "MMMM, yyyy",
Y: "MMMM, yyyy"
},
"/": "-",
":": ":",
firstDay: 1
}
}
}
})(this);
/***/ })
/******/ }); |
'use strict';
//User admin service used for communicating with the articles REST endpoints
angular.module('usersadmin').factory('UsersAdmin', ['$resource',
function ($resource) {
return $resource('usersadmin/:userId', {
userId: '@_id'
}, {
update: {
method: 'PUT'
}
});
}
]); |
ReachAlbert.common = angular.module('ReachAlbert.common' ,[])
ReachAlbert.common.controller('TabController', ['$scope', '$state', '$stateParams', function($scope, $state, $stateParams){
$('body,html').animate({scrollTop: 0}, 800);
}]);
ReachAlbert.common.controller('CrewController', ['$scope', function($scope){
$('body,html').animate({scrollTop: 0}, 800);
$scope.crewsList = angular.copy(ReachAlbert.constants.crewList);
}]);
ReachAlbert.common.controller('AboutController', ['$scope', function($scope){
$('body,html').animate({scrollTop: 0}, 800);
$scope.about_image_dir = angular.copy(ReachAlbert.globals.image.about_url);
$scope.hosting_list = angular.copy(ReachAlbert.constants.about.hosting_list);
}]);
ReachAlbert.common.controller('FeedbackController', ['$scope', '$state', 'Restangular', function($scope, $state, Restangular){
$('body,html').animate({scrollTop: 0}, 800);
$scope.formData = {
data:{},
options: {
isAnonymous: false
}
};
$scope.submitFeedback = function() {
var url = '/api/feedback?name=' +($scope.formData.data.name ? $scope.formData.data.name : 'Anonymous') +'&email=' +($scope.formData.data.email ? $scope.formData.data.email : 'anonymous@amazecreationz.in') +'&feedback=' +$scope.formData.data.feedback;
$scope.formData.data = {};
Restangular.one(url).post().then(function(data){
if(data.status == 1)
alert("Feedback sent!")
else
alert("Sorry! Feedback send failed. Try Again!")
$state.reload();
})
}
}]); |
$(function() {
$("#contactForm input,#contactForm textarea").jqBootstrapValidation({
preventSubmit: true,
submitError: function($form, event, errors) {
// additional error messages or events
},
submitSuccess: function($form, event) {
// Prevent spam click and default submit behaviour
$("#btnSubmit").attr("disabled", true);
event.preventDefault();
// get values from FORM
var name = $("input#name").val();
var email = $("input#email").val();
var phone = $("input#phone").val();
var message = $("textarea#message").val();
var firstName = name; // For Success/Failure Message
// Check for white space in name for Success/Fail message
if (firstName.indexOf(' ') >= 0) {
firstName = name.split(' ').slice(0, -1).join(' ');
}
$.ajax({
url: "http://formspree.io/stanfordhays@gmail.com",
type: "POST",
data: {
name: name,
phone: phone,
email: email,
message: message
},
cache: false,
success: function() {
// Enable button & show success message
$("#btnSubmit").attr("disabled", false);
$('#success').html("<div class='alert alert-success'>");
$('#success > .alert-success').html("<button type='button' class='close' data-dismiss='alert' aria-hidden='true'>×")
.append("</button>");
$('#success > .alert-success')
.append("<strong>Your message has been sent. </strong>");
$('#success > .alert-success')
.append('</div>');
//clear all fields
$('#contactForm').trigger("reset");
},
error: function() {
// Fail message
$('#success').html("<div class='alert alert-danger'>");
$('#success > .alert-danger').html("<button type='button' class='close' data-dismiss='alert' aria-hidden='true'>×")
.append("</button>");
$('#success > .alert-danger').append("<strong>Sorry " + firstName + ", it seems that my mail server is not responding. Please try again later!");
$('#success > .alert-danger').append('</div>');
//clear all fields
$('#contactForm').trigger("reset");
},
});
},
filter: function() {
return $(this).is(":visible");
},
});
$("a[data-toggle=\"tab\"]").click(function(e) {
e.preventDefault();
$(this).tab("show");
});
});
// When clicking on Full hide fail/success boxes
$('#name').focus(function() {
$('#success').html('');
});
|
// The MIT License (MIT)
//
// Copyright (c) 2017-2021 Camptocamp SA
//
// 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.
const webpack = require('webpack');
process.traceDeprecation = true;
const resourcesRule = {
test: /\.(jpeg|png|ico|cur|eot|ttf|woff|woff2)$/,
use: [
{
loader: 'file-loader',
options: {
esModule: false,
name: '[name].[ext]',
},
},
],
};
const svgRule = {
test: /\.svg$/,
oneOf: [
{
resourceQuery: /url/,
use: [
{
loader: 'file-loader',
options: {
esModule: false,
name: '[name].[ext]',
},
},
'svgo-loader',
],
},
{
resourceQuery: /viewbox/,
use: [
{
loader: 'svg-inline-loader',
options: {
removeSVGTagAttrs: false,
},
},
'./buildtools/svg-viewbox-loader',
'svgo-loader',
],
},
{
use: [
{
loader: 'svg-inline-loader',
options: {
removeSVGTagAttrs: false,
},
},
'svgo-loader',
],
},
],
};
new webpack.LoaderOptionsPlugin({
debug: false,
});
module.exports = function () {
return {
mode: 'development',
devtool: 'inline-cheap-source-map', // 'cheap-eval-source-map',
output: {
filename: '[name].js',
},
module: {
rules: [resourcesRule, svgRule],
},
};
};
|
var rpn=require("./rpn.js");
exports. addition = function (test) {
test.expect(4);
test.equals(rpn.compute(prep("1 2 +")), 3);
test.equals(rpn.compute(prep("1 2 3 + +")), 6);
test.equals(rpn.compute(prep("1 2 + 5 6 + +")), 14);
test.equals(rpn.compute(prep("1 2 3 4 5 6 7 + + + + + +")), 28);
test.done();
};
function prep(str) {
return str.trim().split(/[ ]+/);
}
exports. decimals = function (test) {
test.expect(2);
test.equals(rpn.compute(prep("3.14159 5 *")), 15.70795);
test.equals(rpn.compute(prep("100 3 /")), 33.333333333333336);
test.done();
}
exports. empty = function (test) {
test.expect(1);
test.throws(rpn.compute([]));
test.done();
};
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.