text
stringlengths 2
6.14k
|
|---|
angular.module('luhbot',[
'ui.router',
'dashboard'
])
//TODO: Persistance of socket
.factory('IO',function(Toasts){
var IO = function(){
this.namespace = null;
this.socket = {};
var self = this;
this.connect = function(namespace){
if(namespace){
this.namespace = String('/').concat(namespace);
this.socket = io.connect(String("http://").concat(window.location.hostname).concat(':7171').concat(this.namespace));
return this;
}
this.socket = io.connect(String("http://").concat(window.location.hostname).concat(':7171').concat(this.namespace));
return this;
}
this.listenNewMessages = function(){
this.socket.on('newMessage',function(data){
Toasts.makeToast(data.msg);
});
return this;
}
this.joinChannel = function(channel){
this.socket.emit('joinChannel', channel);
console.log('join')
return this;
}
return this;
}
return new IO;
})
.factory('Toasts',function(){
function makeToast(message){
Materialize.toast(message, 4000);
}
return {
makeToast: makeToast
}
})
.factory('BOT',function($http,Toasts){
function connect(){
$http.get('/api/irc/turn/on')
.success(function(data,status){
Toasts.makeToast(data.msg)
})
.error(function(data,status){
Toasts.makeToast(data.msg)
});
$http.get('/api/twitch/update/user')
}
function disconnect(){
$http.get('/api/irc/turn/off')
.success(function(data,status){
Toasts.makeToast(data.msg)
})
.error(function(data,status){
Toasts.makeToast(data.msg)
});
}
function ping(){
$http.get('/api/irc/ping')
.success(function(data,status){
Toasts.makeToast(data.msg)
})
.error(function(data,status){
Toasts.makeToast(data.msg)
});
}
function restart(){
$http.get('/api/irc/force')
.success(function(data,status){
Toasts.makeToast(data.msg)
})
.error(function(data,status){
Toasts.makeToast(data.msg)
});
}
return {
connect : connect,
disconnect: disconnect,
ping : ping
}
})
.factory('User',function($http,$q){
var _user = new Object();
var df = $q.defer();
function getUserApi(){
$http.get('/api/users/me')
.success(function(data,status){
df.resolve(data);
})
.error(function(data,status){
console.error(data);
df.reject(data)
});
return df.promise;
}
function retrieveUserData(property){
if(!Object.keys(_user).length){
return getUserApi().then(function(data){
_user = data;
if(property){
return _user[property];
}
return _user;
});
;
}
if(property){
return _user[property];
}
return _user;
}
return {
getData: retrieveUserData
}
})
.config(function($urlRouterProvider){
$urlRouterProvider.otherwise('/dashboard');
})
.run(function(IO, User){
User.getData('twitchUser').then(function(channel){
IO.connect('alerts').listenNewMessages().joinChannel(channel);
});
});
|
class ias_machineaccountvalidation {
constructor() {
}
// System.Runtime.Remoting.ObjRef CreateObjRef(type requestedType)
CreateObjRef() {
}
// bool Equals(System.Object obj)
Equals() {
}
// int GetHashCode()
GetHashCode() {
}
// System.Object GetLifetimeService()
GetLifetimeService() {
}
// type GetType()
GetType() {
}
// System.Object InitializeLifetimeService()
InitializeLifetimeService() {
}
// string ToString()
ToString() {
}
}
module.exports = ias_machineaccountvalidation;
|
var utils = require('./utils')
var webpack = require('webpack')
var config = require('../config')
var merge = require('webpack-merge')
var baseWebpackConfig = require('./webpack.base.conf')
var HtmlWebpackPlugin = require('html-webpack-plugin')
var FriendlyErrorsPlugin = require('friendly-errors-webpack-plugin')
// add hot-reload related code to entry chunks
Object.keys(baseWebpackConfig.entry).forEach(function (name) {
baseWebpackConfig.entry[name] = ['./build/dev-client'].concat(baseWebpackConfig.entry[name])
})
module.exports = merge(baseWebpackConfig, {
node: {
console: false,
fs: 'empty',
net: 'empty',
tls: 'empty'
},
module: {
rules: utils.styleLoaders({ sourceMap: config.dev.cssSourceMap })
},
{
loader: 'file-loader',
options: {
name: '../static/theme/2001/*.fmi'
}
},
{
loader: 'file-loader',
options: {
name: '../static/10347/10347.fmap'
}
},
// cheap-module-eval-source-map is faster for development
devtool: '#cheap-module-eval-source-map',
plugins: [
new webpack.DefinePlugin({
'process.env': config.dev.env
}),
// https://github.com/glenjamin/webpack-hot-middleware#installation--usage
new webpack.HotModuleReplacementPlugin(),
new webpack.NoEmitOnErrorsPlugin(),
// https://github.com/ampedandwired/html-webpack-plugin
new HtmlWebpackPlugin({
filename: 'index.html',
template: 'index.html',
inject: true
}),
new FriendlyErrorsPlugin()
]
})
|
import { h } from 'omi';
import createSvgIcon from './utils/createSvgIcon';
export default createSvgIcon(h(h.f, null, h("circle", {
cx: "15.5",
cy: "9.5",
r: "1.5"
}), h("circle", {
cx: "8.5",
cy: "9.5",
r: "1.5"
}), h("path", {
d: "M12 16c-1.48 0-2.75-.81-3.45-2H6.88c.8 2.05 2.79 3.5 5.12 3.5s4.32-1.45 5.12-3.5h-1.67c-.7 1.19-1.97 2-3.45 2zm-.01-14C6.47 2 2 6.48 2 12s4.47 10 9.99 10C17.52 22 22 17.52 22 12S17.52 2 11.99 2zM12 20c-4.42 0-8-3.58-8-8s3.58-8 8-8 8 3.58 8 8-3.58 8-8 8z"
})), 'SentimentSatisfiedOutlined');
|
var content = '<abcdテスト>';
var result = '';
result = encodeURI(content);
console.log("encodeURI('abcdテスト')", result);
console.log("decodeURI(encodeURI('abcdテスト'))", decodeURI(encodeURI(content)));
result = encodeURIComponent(content);
console.log("encodeURIComponent('abcdテスト')", result);
console.log("decodeURIComponent(encodeURIComponent('abcdテスト'))", decodeURIComponent(encodeURIComponent(content)));
result = 'var a=1,b=2;console.log(a+b);';
eval(result);
console.log("isFinite('aa')", isFinite('aa'));
console.log("isFinite('1111')", isFinite('1111'));
console.log("isFinite('1111.23')", isFinite('1111.23'));
console.log("isFinite(null)", isFinite(null));
console.log("isFinite(undefined)", isFinite(undefined));
console.log("isFinite(NaN)", isFinite(NaN));
console.log("isFinite(true)", isFinite(true));
console.log("isNaN('aa')", isNaN('aa'));
console.log("isNaN('1111')", isNaN('1111'));
console.log("isNaN('1111.23')", isNaN('1111.23'));
console.log("isNaN(null)", isNaN(null));
console.log("isNaN(undefined)", isNaN(undefined));
console.log("isNaN(NaN)", isNaN(NaN));
console.log("isNaN(true)", isNaN(true));
console.log("parseFloat('aa')", parseFloat('aa'));
console.log("parseFloat('1111')", parseFloat('1111'));
console.log("parseFloat('1111.23')", parseFloat('1111.23'));
console.log("parseFloat(null)", parseFloat(null));
console.log("parseFloat(undefined)", parseFloat(undefined));
console.log("parseFloat(NaN)", parseFloat(NaN));
console.log("parseFloat(true)", parseFloat(true));
console.log("parseInt('aa')", parseInt('aa'));
console.log("parseInt('1111')", parseInt('1111'));
console.log("parseInt('1111.73')", parseInt('1111.73'));
console.log("parseInt(null)", parseInt(null));
console.log("parseInt(undefined)", parseInt(undefined));
console.log("parseInt(NaN)", parseInt(NaN));
console.log("parseInt(true)", parseInt(true));
|
// 使用缓存优化标签选择
// 如果没有缓存的话建立缓存,否则返回缓存中的标签对象
function getElements(name) {
if (!getElements.cache) {
getElements.cache = {};
}
return getElements.cache[name] = getElements.cache[name] || document.getElementsByTagName(name);
}
|
export default class Definition {
get module() { return this._module; }
set module(value) { this._module = value; }
get classArguments() { return this._arguments || []; }
set classArguments(value) { this._arguments = value; }
get tags() { return this._tags || []; }
set tags(value) { this._tags = value; }
constructor(module = '', classArguments = [], tags = []) {
this.module = module;
this.classArguments = classArguments;
this.tags = tags;
}
setModule(module) {
this.module = module;
}
addArgument(argument) {
this.classArguments.push(argument);
return this;
}
setArgument(index, argument) {
this.classArguments[index] = argument;
return this;
}
removeArgument(index) {
if (undefined !== this.classArguments[index]) {
delete this.classArguments[index];
}
return this;
}
setArguments(classArguments) {
this.classArguments = classArguments;
}
setTags(tags) {
this.tags = tags;
}
getTags() {
return this.tags;
}
addTag(name) {
this.tags.push(name);
}
}
|
/* eslint-disable no-console*/
import low from 'lowdb';
import fse from 'fs-extra';
import uuid from 'uuid';
import slug from 'slug';
import constants from './constants';
import { crypt } from '../utils';
const user = {
id: uuid(),
name: constants.USER_NAME,
password: crypt.encrypt(constants.USER_PASSWORD),
role: 'admin',
slug: slug(constants.USER_NAME),
};
fse.ensureFileSync(constants.DATA_FILE);
const db = low(constants.DATA_FILE);
db.defaults({
users: [user],
containers: [],
imageSources: [],
images: [],
templates: [],
volumes: [],
}).write();
console.log('DB is running');
export default () => (db);
|
/**
* Fetch configuration data using an API Key and the Application Secret Key.
* By doing so, the sconfig servers will just apply firewall rules (if any) and return
* the encrypted configuration data. The client will then decrypt the configuration
* data using the App Secret Key
* Note: Ff no API Key or App Secret is provided, it will look for it in process.env.SCONFIG_KEY and process.env.SCONFIG_SECRET
* */
var sconfig = require('sconfig');
sconfig({
key: '{YOUR_API_KEY}', // the 32-char version of an API Key
secret: '{YOUR_APP_SECRET}', // the 32 char secret key found under the App Details tab
//version: '{YOUR_VERSION}', // version name to fetch, defaults to latest version created
// json: true // expect the result data to be JSON. This is true by default.
sync: true // persist the configuration data locally in the event of an sconfig server outage
}, function(err, config) {
if (err) {
console.log(err);
return;
}
console.log("OK", config);
});
|
'use strict';
var mongoose = require('mongoose')
, Schema = mongoose.Schema;
// 스키마 구조
var PollReplySchema = new Schema({
_id: { type:Schema.Types.ObjectId, required:true },
itemMulti: [{
_id: { type:Schema.Types.ObjectId, required:true },
reply: [{
_id: { type:Schema.Types.ObjectId, required:true },
user: { type:String, required:true, trim:true }
}]
}],
itemShort: [{
_id: { type:Schema.Types.ObjectId, required:true },
reply: [{
user: { type:String, required:true, trim:true },
content: { type:String, required:true, trim:true }
}]
}],
characters: [{
_id: { type:Schema.Types.ObjectId, required:true },
reply: [{
_id: { type:Schema.Types.ObjectId, required:true },
user: { type:String, required:true, trim:true }
}]
}],
users: [{
_id: { type:String, required:true, trim:true },
ip: { type:String, trim:true },
agent: { type:String, trim:true }
}],
created: { type: Date, default: Date.now }
});
// 후킹
PollReplySchema.pre('save', function(next) {
next();
});
// 자주쓰는 Model
PollReplySchema.static({
load: function(id, callback, isCount) {
if (isCount) {
this.count({ _id: id }, callback);
} else {
this.findOne({ _id: id }, callback);
}
}
});
mongoose.model('PollReply', PollReplySchema);
|
var geometry = new (function() {
var pub = this;
pub.distance = function(object1, object2) {
return Math.sqrt(Math.pow(object1.x - object2.x, 2) + Math.pow(object1.y - object2.y, 2));
}
})();
|
/* eslint no-unused-vars:0 */
import {util} from '../../math';
/**
* Particle Emitter base class
*
* @property {number|string} id
* @property {string} name
* @property {Tw2ParticleSystem} particleSystem
* @class
*/
export class Tw2ParticleEmitter
{
constructor()
{
this._id = util.generateID();
this.name = '';
this.particleSystem = null;
}
/**
* Initializes the particle emitter
*/
Initialize()
{
}
/**
* Per frame update
* @param {number} dt - delta time
*/
Update(dt)
{
}
}
|
jQuery(function($) {
$('ul li.active').qtip({
content: 'This is an active list element',
show: 'mouseover',
hide: 'mouseout',
position: { target: 'mouse' }
})
});
|
/**
The MIT License (MIT)
Copyright (c) 2014 MyChannel-Apps.de
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.
@author Christoph Kühl <djchrisnet>, Adrian Preuß <Bizarrus>
*/
if(!Array.prototype.each) {
Object.defineProperty(Array.prototype, 'each', {
enumerable: false,
configurable: false,
writable: false,
value: function(callback) {
for(var index = 0; index < this.length; index++) {
if(callback.apply(this[index], index) === false) {
break;
}
}
}
});
}
if(!Array.prototype.random) {
Object.defineProperty(Array.prototype, 'random', {
enumerable: false,
configurable: false,
writable: false,
value: function() {
return this[RandomOperations.nextInt(this.length)];
}
});
}
if(!Array.prototype.exists) {
Object.defineProperty(Array.prototype, 'exists', {
enumerable: false,
configurable: false,
writable: false,
value: function(value) {
return (this.indexOf(value) > -1);
}
});
}
if(!Array.prototype.size) {
Object.defineProperty(Array.prototype, 'size', {
enumerable: false,
configurable: false,
writable: false,
value: function() {
return this.length;
}
});
}
|
module.exports = function(app){
var validacao = require('../validacoes/usuarios');
var Usuario = app.models.usuarios;
var UsuarioController = {
index: function(req,res){
Usuario.find(function(err,dados){
if(err){
req.flash('erro', 'Erro ao buscar usuários: '+err);
res.redirect('/usuarios');
}else{
res.render('usuarios/index', {lista: dados});
}
});
},
create: function(req,res){
res.render('usuarios/create', {user: new Usuario()});
},
post: function(req,res){
if(validacao(req,res)){
var model = new Usuario();
model.nome = req.body.nome;
model.email = req.body.email;
model.telefone = req.body.telefone;
model.password = model.generateHash(req.body.password);
Usuario.findOne({'email': model.email}, function(err,data){
if(data){
req.flash('erro', 'E-mail encontra-se cadastrado, tente outro.');
res.render('usuarios/create', {user: model});
}else{
model.save(function(err){
if(err){
req.flash('erro', 'Erro ao cadastrar: '+err);
res.render('usuarios/create', {user: req.body});
}else{
req.flash('info', 'Registro cadastrado com sucesso!');
res.redirect('/usuarios');
}
});
}
});
}else{
res.render('usuarios/create', {user: req.body});
}
},
show: function(req,res){
Usuario.findById(req.params.id, function(err,dados){
if(err){
req.flash('erro', 'Erro ao visualizar usuário: '+err);
res.redirect('/usuarios');
}else{
res.render('usuarios/show', {dados: dados});
}
});
},
delete: function(req,res){
Usuario.remove({_id: req.params.id}, function(err){
if(err){
req.flash('erro', 'Erro ao excluir usuário: '+err);
res.redirect('/usuarios');
}else{
req.flash('info', 'Registro excluído com sucesso!');
res.redirect('/usuarios');
}
});
},
edit: function(req,res){
Usuario.findById(req.params.id, function(err,data){
if(err){
req.flash('erro', 'Erro ao editar: '+err);
res.redirect('/usuarios');
}else{
res.render('usuarios/edit', {dados: data});
}
});
},
update: function(req,res){
if(validacao(req,res)){
Usuario.findById(req.params.id, function(err,data){
var model = data;
model.nome = req.body.nome;
model.telefone = req.body.telefone;
model.save(function(err){
if(err){
req.flash('erro', 'Erro ao editar: '+err);
res.render('usuarios/edit', {dados: model});
}else{
req.flash('info', 'Registro atualizado com sucesso!');
res.redirect('/usuarios');
}
});
});
}else{
res.render('usuarios/edit', {user: req.body});
}
}
}
return UsuarioController;
}
|
console.log("J U I loaded");
var timer;
var timer2;
var timer3;
var counter;
var cell;
var curCount = 0;
var gameLost = false;
var multiUp = 0;
var total = 10;
var score = 0;
var points = 100;
var board = [ 0,0,0,0,0,0,0,0,0,0,0,0,
0,0,0,0,0,0,0,0,0,0,0,0,
0,0,0,0,0,0,0,0,0,0,0,0,
0,0,0,0,0,0,0,0,0,0,0,0,
0,0,0,0,0,0,0,0,0,0,0,0,
0,0,0,0,0,0,0,0,0,0,0,0,
0,0,0,0,0,0,0,0,0,0,0,0,
0,0,0,0,0,0,0,0,0,0,0,0];
var cellTypes = [
{name: "empty", color: "white"},
{name: "normal", color: "black"},
{name: "freeze", color: "blue"},
{name: "multi", color: "green"},
{name: "max", color: "yellow"},
{name: "super", color: "red"}
];
var WHITE = 0,
BLACK = 1,
BLUE = 2,
GREEN = 3,
YELLOW = 4,
RED = 5;
var randomType = function() {
var randomNum = Math.floor((Math.random() * 100) + 1);
if (randomNum < 88) return BLACK; // 88%
else if (randomNum < 91) return BLUE; // 3%
else if (randomNum < 94) return GREEN; // 3%
else if (randomNum < 97) return YELLOW; // 3%
else return RED; // 3%
};
// EFFECTS -------------------------------------------------------------
var freezeEffect = function() {
clearInterval(timer2);
setTimeout(function() {
timer2 = setInterval(tickCell, counter);
}, 2000);
};
var multiEffect = function() {
multiUp++;
points = Math.floor((1 + (multiUp * 0.1)) * points);
};
var maxEffect = function() {
total++;
};
var superEffect = function() {
for (var i = 0; i < board.length; i++) {
if (board[i] < 2) board[i] = 0;
};
};
// LOSING & PRINTSTATE ------------------------------------------------
var hasLost = function() {
var count = 0;
for (var i = 0; i < board.length; i++) {
if (board[i] > 0 && board[i] < 2) count++;
if (count > total) break;
};
curCount = count;
return count > total;
};
var printState = function() {
$("#max2").text(curCount);
$("#max4").text(total);
$("#score2").text(score);
};
// PICKCELL & FADE ----------------------------------------------------
var pickCell = function() {
var randomIndex;
do {
randomIndex = Math.floor(Math.random() * board.length);
}
while (board[randomIndex] !== 0);
board[randomIndex] = randomType();
var $fade = $("#cell" + randomIndex);
if (board[randomIndex] > BLACK) {
setTimeout(function() {
$fade.animate({backgroundColor: "white"}, 700);
setTimeout(function() {
board[randomIndex] = 0;
}, 690);
}, 1000);
};
};
// CLICK MOVE ---------------------------------------------------------
var click = function(evt) {
clickValue = parseInt(this.id.substr(4));
if (board[clickValue] > BLACK) {
$(this).stop()
.toggle("explode", {pieces:16})
.css({backgroundColor: "white"})
.fadeIn();
};
if (board[clickValue] === BLACK) score += points;
else if (board[clickValue] === BLUE) freezeEffect();
else if (board[clickValue] === GREEN) multiEffect();
else if (board[clickValue] === YELLOW) maxEffect();
else if (board[clickValue] === RED) superEffect();
board[clickValue] = 0;
render();
};
// RENDER -------------------------------------------------------------
var render = function() {
if (gameLost === false) renderBoard();
function renderBoard() {
board.forEach(function(cell, idx) {
var el = $('#cell' + idx);
el.css('background-color', cellTypes[cell].color);
});
};
};
// TICKS --------------------------------------------------------------
var tick = function() {
printState();
if (hasLost()) {
clearInterval(timer);
clearInterval(timer2);
gameLost = true;
var lose = function() {
$(".lose").css({opacity:1});
setTimeout(function() {
$(".lose").css({opacity:0});
}, 400);
};
timer3 = setInterval(lose, 800);
};
printState();
};
var tickCell = function() {
pickCell();
render();
clearInterval(timer2);
counter *= 0.99;
timer2 = setInterval(tickCell, counter);
};
// STARTGAME ----------------------------------------------------------
var startGame = function() {
for (var i = 0; i < board.length; i++) {
board[i] = 0;
};
curCount = 0;
gameLost = false;
multiUp = 0;
total = 10;
score = 0;
points = 100;
counter = 800;
printState();
render();
clearInterval(timer3);
clearInterval(timer2);
clearInterval(timer);
timer = setInterval(tick, 10);
timer2 = setInterval(tickCell, counter);
};
// BUTTONS ------------------------------------------------------------
$("#startgame").on('click', function() {
$(".one").css("display", "none");
$(".two").css("display","inline");
$(".three").css("display","none");
startGame();
});
$("#restart").on('click', function() {
startGame();
});
$("#mainmenu").on('click', function() {
$(".one").css("display", "inline");
$(".two").css("display","none");
$(".three").css("display","none");
});
$("#howtoplay").on('click', function() {
$(".one").css("display", "none");
$(".two").css("display","none");
$(".three").css("display","inline");
});
$("#mainmenu2").on('click', function() {
$(".one").css("display", "inline");
$(".two").css("display","none");
$(".three").css("display","none");
});
$("#startgame2").on('click', function() {
$(".one").css("display", "none");
$(".two").css("display","inline");
$(".three").css("display","none");
startGame();
});
var audio = document.getElementById("tomb");
var mute = document.getElementById('mute');
mute.onclick = function() {
audio.muted = !audio.muted;
};
audio.addEventListener('ended', function() {
this.currentTime = 0;
this.play();
}, false);
// EVENTLISTENERS -----------------------------------------------------
document.addEventListener("DOMContentLoaded", function(evt) {
var cellEls = document.querySelectorAll("td");
for (var i = 0; i < board.length; i++) {
cellEls[i].addEventListener("click", click);
};
});
|
module.exports = {
label: {
display: 'block',
width: '90%',
marginBottom: 15
},
labelText: {
color: '#777',
fontSize: '15px',
display: 'block'
},
input: {
display: 'block',
fontSize: '20px',
padding: 10,
width: '100%',
border: '1px solid #ddd'
},
textarea: {
display: 'block',
fontSize: '20px',
border: '1px solid #ddd',
width: 'auto',
height: 100,
padding: 10,
width: '100%'
}
};
|
module.exports = function(grunt) {
// Project configuration.
grunt.initConfig({
pkg: grunt.file.readJSON('package.json'),
"download-atom-shell": {
version: "0.23.0",
outputDir: "./atom-shell",
rebuild: true
}
});
grunt.loadNpmTasks('grunt-download-atom-shell');
};
|
// Dependencies
var UFirst = require("ucfirst");
/**
* CrossStyle
* Returns an array of cross-browser CSS properties for given input.
*
* @name CrossStyle
* @function
* @param {String} input The CSS property (e.g. `"transform"` or `"transformOrigin"`).
* @return {Array} An array of strings representing the cross-browser CSS properties for the given input.
*/
function CrossStyle(input) {
var uInput = UFirst(input);
return [
"webkit" + uInput
, "moz" + uInput
, "ms" + uInput
, "o" + uInput
, input
]
}
module.exports = CrossStyle;
|
export default {
forward: "转发",
reply: "回复",
ignore: "忽略",
toVoicemail: "到语音信箱",
answer: "接听",
answerAndEnd: "接听并结束",
answerAndHold: "接听并保持"
};
// @key: @#@"forward"@#@ @source: @#@"Forward"@#@
// @key: @#@"reply"@#@ @source: @#@"Reply"@#@
// @key: @#@"ignore"@#@ @source: @#@"Ignore"@#@
// @key: @#@"toVoicemail"@#@ @source: @#@"To Voicemail"@#@
// @key: @#@"answer"@#@ @source: @#@"Answer"@#@
// @key: @#@"answerAndEnd"@#@ @source: @#@"Answer & End"@#@
// @key: @#@"answerAndHold"@#@ @source: @#@"Answer & Hold"@#@
|
/*
用 action 来描述“发生了什么”,和使用 reducers 来根据 action 更新 state 的用法。
Store 就是把它们联系到一起的对象。Store 有以下职责:
维持应用的 state;
提供 getState() 方法获取 state;
提供 dispatch(action) 方法更新 state;
通过 subscribe(listener) 注册监听器;
通过 subscribe(listener) 返回的函数注销监听器。
再次强调一下 Redux 应用只有一个单一的 store。当需要拆分数据处理逻辑时,你应该使用 reducer 组合 而不是创建多个 store
*/
import { AsyncStorage } from 'react-native';
import { Iterable } from 'immutable';
import { applyMiddleware, createStore, compose } from 'redux';
import { autoRehydrate, persistStore, purgeStoredState } from 'redux-persist';
import reduxThunk from 'redux-thunk';
import createLogger from 'redux-logger';
import rootReducer from '../reducers/rootReducer';
let reduxMiddleware = [reduxThunk];
let reduxLogger = createLogger(
/* {
level = 'log': 'log' | 'console' | 'warn' | 'error' | 'info', // console's level
duration = false: Boolean, // Print the duration of each action?
timestamp = true: Boolean, // Print the timestamp with each action?
colors: ColorsObject, // Object with color getters. See the ColorsObject interface.
logger = console: LoggerObject, // Implementation of the `console` API.
logErrors = true: Boolean, // Should the logger catch, log, and re-throw errors?
collapsed, // Takes a boolean or optionally a function that receives `getState` function for accessing current store state and `action` object as parameters. Returns `true` if the log group should be collapsed, `false` otherwise.
predicate, // If specified this function will be called before each action is processed with this middleware.
stateTransformer, // Transform state before print. Eg. convert Immutable object to plain JSON.
actionTransformer, // Transform state before print. Eg. convert Immutable object to plain JSON.
errorTransformer, // Transform state before print. Eg. convert Immutable object to plain JSON.
titleFormatter, // Format the title used when logging actions.
diff = false: Boolean, // Show diff between states.
diffPredicate // Filter function for showing states diff.'
}*/
{
level: 'log',
duration: true,
timestamp: true,
colors: {
title: () => 'inherit',
prevState: () => '#9E9E9E',
action: () => '#03A9F4',
nextState: () => '#4CAF50',
error: () => '#F20404',
},
logger: console,
logErrors: true,
collapsed : (getState, action) => (
action.type === 'REACT_NATIVE_ROUTER_FLUX_FOCUS' ||
action.type === 'REACT_NATIVE_ROUTER_FLUX_RESET'
),
stateTransformer: (state) => {
if (Iterable.isIterable(state)) {
return state.toJS();
}
return state;
},
actionTransformer: (action) => {
// if() { some judgement code}
return action;
},
errorTransformer: (error) => {
// if() {some judgement code}
return error;
},
diff: true,
diffPredicate: (getState, action) => (
action.type === 'ADD_TODO' ||
action.type === 'SET_VISIBILITY_FILTER' ||
action.type === 'SHOW_ACTIVE'
)
}
);
if (__DEV__) {
// 开发环境打印 action 日志
reduxMiddleware.push(reduxLogger);
}
export let store = null;
let enhancers = compose(...[
applyMiddleware(...reduxMiddleware),
autoRehydrate()
]);
function hotReloading() {
// https://github.com/gaearon/redux-devtools/issues/233#issuecomment-176210686
// Enable Webpack hot module replacement for reducers
if (module.hot) {
let reducerPath = '../reducers/rootReducer';
module.hot.accept(reducerPath, () => {
let nextRootReducer = require(reducerPath).default;
store.replaceReducer(nextRootReducer);
});
}
}
export default function configureStore(initialState = {}) {
store = createStore(rootReducer, initialState, enhancers);
hotReloading();
setPersistStore();
return store;
}
function setPersistStore() {
// more information: http://gold.xitu.io/entry/57cac7b167f3560057bb00a7
persistStore(store, {
blacklist: ['signIn', 'someKey'], // 黑名单数组,可以忽略指定 reducers 中的 key
// whitelist: ['auth'], // 白名单数组,一旦设置,其他的 key 都会被忽略。
storage: AsyncStorage,
// transforms: // 在 rehydration 和 storage 阶段被调用的转换器
debounce: 100 // storage 操作被调用的频度, ms
// store: // redux store 我们要存储的 store
// config: // 对象
}, () => {
});
}
export function resetPersistStore() {
purgeStoredState({storage: AsyncStorage});
}
|
'use strict';
angular.module('citizenForumsShowApp', [
'citizenForumsShowApp.services',
'ngCookies',
'ngResource',
'ngSanitize',
'ngRoute',
'uiGmapgoogle-maps',
'xeditable',
'restangular',
'nl2br'
]).config(['$interpolateProvider', function($interpolateProvider) {
$interpolateProvider.startSymbol('[[');
$interpolateProvider.endSymbol(']]');
}]).config(function(uiGmapGoogleMapApiProvider) {
uiGmapGoogleMapApiProvider.configure({
// key: '', // TODO set Google Maps API key
v: '3.17',
language: 'es',
sensor: false,
libraries: 'drawing,geometry,visualization'
});
})
.run(function(editableOptions) {
editableOptions.theme = 'bs3'; // X-editable form theme
})
.constant('CFG', {
DELAY: 600,
RANGE_STEPS: 20,
GMAPS_ZOOM: 14,
GPS_CENTER_POS: { lat: 41.4926867, lng: 2.3613954}, // Premià de Mar (Barcelona) center
PROCESS_PARTICIPATION_STATE: { DRAFT: 1, PRESENTATION: 2, DEBATE: 3, CLOSED: 4 }
})
;
|
window.onload = function () {
// Start a new marked instance and renderer
var marked = window.marked;
var renderer = new marked.Renderer();
var counter = 0;
var specs = [];
var opts = {"mode": "vega-lite", "renderer": "svg" };
// Render the ```vis as a div and save the json spec
renderer.code = function (code, lang, escaped) {
if (lang == "vis") {
jsonVis = YAML.parse(code);
specs.push(jsonVis);
counter++;
el = "#vis-" + counter;
htmlChart = "<div id='vis-" + counter + "'></div>";
return htmlChart;
}
var result = marked.Renderer.prototype.code.call(this, code, lang, escaped);
return result;
};
// Render the vega-lite chart for each json spec
vegaliteRender = function (err, content) {
for (var i=0; i < specs.length; i++) {
j = i + 1;
el = "#vis-" + j;
vega.embed(el, specs[i], opts);
}
return content;
};
// Convert from Markdown to HTML
var input = document.querySelector("#visdown-input");
var output = document.querySelector("#visdown-output");
window.visdown = function () {
console.log('visdown');
var markdownText = input.value;
output.innerHTML = marked(markdownText, { renderer: renderer});
vegaliteRender();
}
visdown()
}
|
module.exports = require("npm:lodash._createassigner@3.1.1/index");
|
import React from 'react';
import { Gateway } from 'react-gateway';
import ReactModal2 from './ReactModal2';
import Icon from '../Icon';
import './Modal.scss';
/**
* This component is only created to facilitate the process of using react-modal2 with react gateway
*
* You can import this Modal and use onClose props with internal state to control its appearance:
*
*export default class MyComponent extends React.Component {
* state = {
* isModalOpen: false
* };
*
* handleOpen = () => {
* this.setState({ isModalOpen: true });
* };
*
* handleClose = () => {
* this.setState({ isModalOpen: false });
* };
*
* render() {
* return (
* <div>
* <button onClick={this.handleOpen}>Open</button>
* {this.state.isModalOpen && (
* <MyCustomModal onClose={this.handleClose}>
* <h1>Hello from Modal</h1>
* <button onClick={this.handleClose}>Close</button>
* </MyCustomModal>
* )}
* </div>
* );
* }
*}
*
* more info: https://www.npmjs.com/package/react-modal2
*/
const freezeTheScroll = () => {
// eslint-disable-next-line
const body = window.document.querySelector('body');
body.style.overflow = 'hidden';
};
const unfreezeTheScroll = () => {
// eslint-disable-next-line
const body = window.document.querySelector('body');
body.style.overflow = 'initial';
};
export default class Modal extends React.Component {
static propTypes = {
onClose: React.PropTypes.func.isRequired,
};
static defaultProps = {
closeOnEsc: true,
closeOnBackdropClick: true,
};
/* eslint-disable */
componentDidMount() {
if (window) {
freezeTheScroll();
}
}
componentWillUnmount() {
if (window) {
unfreezeTheScroll();
}
}
/* eslint-enable */
render() {
return (
<Gateway into="modal">
<ReactModal2
onClose={this.props.onClose}
closeOnEsc={this.props.closeOnEsc}
closeOnBackdropClick={this.props.closeOnEsc}
backdropClassName="BusyModalBackdrop"
modalClassName="BusyModal"
>
<a className="BusyModal--close" onClick={this.props.onClose}>
<Icon name="close" />
</a>
{this.props.children}
</ReactModal2>
</Gateway>
);
}
}
|
function solve(args) {
var text = args[0].split('\n');
var textA = text[0];
var textB = text[1];
var state = 0;
for (var i = 0; i < Math.min(textA.length, textB.length); i += 1) {
if (textA[i] > textB[i]) {
state = 1;
break;
}
if (textA[i] < textB[i]) {
state = 2;
break;
}
}
if (state === 0 && textA.length > textB.length) {
state = 1;
}
if (state === 0 && textB.length > textA.length) {
state = 2;
}
switch (state) {
case 0:
console.log('=');
break;
case 1:
console.log('>');
break;
case 2:
console.log('<');
break;
default:
break;
}
}
|
/* animation.js */
Janice._Animation = {};
Janice._Animation.staticm = {};
Janice._Animation.method = {};
Janice._Animation.staticm.decomposeVersion = function(versionNumber) {
var major = Math.floor(versionNumber)
var minor = parseInt(('' + (versionNumber - major)).substr(2));
return {
major: major,
minor: minor
};
};
Janice._Animation.method.draw = function(context, t) {
this.container.draw(context, t);
};
Janice._Animation.method.save = function() {
var saveStr = '{';
saveStr += '"v":' + this.version;
saveStr += ',';
saveStr += '"w":' + this.width;
saveStr += ',';
saveStr += '"h":' + this.height;
saveStr += ',';
saveStr += '"d":' + this.duration;
saveStr += ',';
saveStr += '"c":' + Janice._Container.staticm.save(this.container);
return saveStr + '}';
};
Janice._Animation.method.load = function(data) {
if (typeof data == 'string') {
try {
data = jsonParse(data);
}
catch (ex) {
throw 'InvalidJsonData';
}
}
// Check version:
var thisVersion = Janice._Animation.staticm.decomposeVersion(this.version);
var dataVersion = Janice._Animation.staticm.decomposeVersion(data.v);
if (thisVersion.major !== dataVersion.major) {
throw 'IncompatibleMajorVersion';
}
else if (thisVersion.minor < dataVersion.minor) {
throw 'IncompatibleMinorVersion';
}
// Load animation settings:
this.width = data.w;
this.height = data.h;
this.duration = data.d;
// Load contents:
this.container = Janice._Container.staticm.load(data.c);
};
Janice.Animation = function(duration) {
var animation = {};
animation.version = 0.1;
animation.width = 480;
animation.height = 320;
animation.duration = duration ? parseInt(duration) : 5000; // In milliseconds.
animation.container = Janice.Container();
animation.draw = Janice._Animation.method.draw;
animation.save = Janice._Animation.method.save;
animation.load = Janice._Animation.method.load;
return animation;
};
|
function f() {
console.log(1);
console.log(2);
}
|
/* SPDX-License-Identifier: MIT */
function GHDataReport(apiUrl) {
apiUrl = apiUrl || '/';
var owner = this.getParameterByName('owner');
var repo = this.getParameterByName('repo');
this.api = new GHDataAPIClient(apiUrl, owner, repo);
this.buildReport();
}
GHDataReport.prototype.getParameterByName = function(name, url) {
if (!url) {
url = window.location.href;
}
name = name.replace(/[\[\]]/g, "\\$&");
var regex = new RegExp("[?&]" + name + "(=([^&#]*)|&|#|$)"),
results = regex.exec(url);
if (!results) return null;
if (!results[2]) return '';
return decodeURIComponent(results[2].replace(/\+/g, " "));
};
GHDataReport.prototype.buildReport = function () {
if (this.api.owner && this.api.repo) {
document.getElementById('repo-label').innerHTML = this.api.owner + ' / ' + this.api.repo;
// Commits
this.api.commitsByWeek().then(function (commits) {
MG.data_graphic({
title: "Commits/Week",
data: MG.convert.date(commits, 'date', '%Y-%m-%dT%H:%M:%S.%LZ'),
chart_type: 'point',
least_squares: true,
full_width: true,
height: 300,
color_range: ['#aaa'],
x_accessor: 'date',
y_accessor: 'commits',
target: '#commits-over-time'
});
});
// Stargazers
this.api.stargazersByWeek().then(function (stargazers) {
MG.data_graphic({
title: "Stars/Week",
data: MG.convert.date(stargazers, 'date', '%Y-%m-%dT%H:%M:%S.%LZ'),
chart_type: 'point',
least_squares: true,
full_width: true,
height: 300,
color_range: ['#aaa'],
x_accessor: 'date',
y_accessor: 'watchers',
target: '#stargazers-over-time'
});
});
// Forks
this.api.forksByWeek().then(function (forks) {
MG.data_graphic({
title: "Forks/Week",
data: MG.convert.date(forks, 'date', '%Y-%m-%dT%H:%M:%S.%LZ'),
chart_type: 'point',
least_squares: true,
full_width: true,
height: 300,
color_range: ['#aaa'],
x_accessor: 'date',
y_accessor: 'projects',
target: '#forks-over-time'
});
});
// Issues
this.api.issuesByWeek().then(function (issues) {
MG.data_graphic({
title: "Issues/Week",
data: MG.convert.date(issues, 'date', '%Y-%m-%dT%H:%M:%S.%LZ'),
chart_type: 'point',
least_squares: true,
full_width: true,
height: 300,
color_range: ['#aaa'],
x_accessor: 'date',
y_accessor: 'issues',
target: '#issues-over-time'
});
});
// Pull Requests
this.api.pullRequestsByWeek().then(function (pulls) {
MG.data_graphic({
title: "Pull Requests/Week",
data: MG.convert.date(pulls, 'date', '%Y-%m-%dT%H:%M:%S.%LZ'),
chart_type: 'point',
least_squares: true,
full_width: true,
height: 300,
color_range: ['#aaa'],
x_accessor: 'date',
y_accessor: 'pull_requests',
target: '#pulls-over-time'
});
});
}
};
var client = new GHDataReport();
|
import React from 'react';
import createSvgIcon from './utils/createSvgIcon';
export default createSvgIcon(
<g><path d="M12 5.9c1.16 0 2.1.94 2.1 2.1s-.94 2.1-2.1 2.1S9.9 9.16 9.9 8s.94-2.1 2.1-2.1m0 9c2.97 0 6.1 1.46 6.1 2.1v1.1H5.9V17c0-.64 3.13-2.1 6.1-2.1M12 4C9.79 4 8 5.79 8 8s1.79 4 4 4 4-1.79 4-4-1.79-4-4-4zm0 9c-2.67 0-8 1.34-8 4v3h16v-3c0-2.66-5.33-4-8-4z" /></g>
, 'PermIdentity');
|
// -------------------------------------------------------------------------------
// OEA Original colors
// --------------------------------------------------------------------------------
export default {
blue: "#3299BB",
lightBlue: "#88D4E1",
lighterBlue: "#D6EBF1",
white: "#fff",
black: "#000",
backgroundGray: "#E9E9E9",
backgroundGreen:"#d1f1eb",
darkGreen: "#1abc9c",
backgroundRed: "#f7c9c4",
red: "#E74C3C",
textGrey: "#333333",
buttonFace: "buttonface",
textColor: "#555",
linkColor: "#1abc9c",
// Colors
almost_black: "#424242",
firm: "#1abc9c",
gray: "#BCBCBC",
lightergrey: "#F3F3F3",
lightgray: "#E9E9E9",
inverse: "#fff",
// Kate Colors
kateDarkOrange: "rgb(25,153,0)",
kateOrange: "rgb(255,153,0)",
kateLightOrange: "rgb(255,173,51)",
kateLightBlue: "#A6F2FF",
// MIT OCW colors
mitocwRed: "#D20035",
mitocwDarkBrown: "#574B49",
mitocwMediumBrown: "#775C57",
mitocwLightBrown: "#E7E0DB",
mitocwDarkGray: "#363636",
mitocwLightGray: "#999",
// pony
ponyLightGray: "#EDEDED",
ponyDarkGray: "#BFBFBF",
ponyLightBlue: "#8FF1FF",
ponyLightPurple: "#770073",
ponyPink: "#FF002C",
ponyOrange: "#FF6728",
ponyYellow: "#FFF8B0",
ponyLightGreen: "#82D771",
ponyGreen: "#44C635",
ponyBlue: "#008DCF",
ponyPurple: "#A756A3",
// Lumen Learing
lumenSeafoam: "#108043",
lumenDarkGreen: "#003136",
lumenBlue: "#1e74d1",
lumenRed: "#ad4646",
// Twitter bootstrap overrides
navbarInverseBg: "#424242",
navbarInverseLinkColor: "#E9E9E9",
navbarInverseLinkHoverColor: "rgb(255,173,51)",
navbarInverseLinkHoverBg: "#424242",
navbarInverseLinkActiveColor: "rgb(255,173,51)",
navbarInverseLinkActiveBg: "#E9E9E9",
inputColor: "#4d4d4d",
}
|
// Modules
const Config = require('../config/main'),
Good = require('good');
module.exports = {
options: Config.HAPI.GOOD_OPTIONS,
register: Good
};
|
var chokidar = require('chokidar');
process.chdir(__dirname + '/../');
chokidar.watch('.', {ignoreInitial: true, useFsEvents: true}).on('all', function(event, path) {
console.log(new Date, event, path);
});
|
$(function(){
function notOk(s, m) {equal(!!s,false,m);}
module("lock");
test('create', function () {
var lock1 = $.lock(),
lock2 = $.lock(false),
lock3 = $.lock(true);
expect(3);
ok(!lock1.isLocked());
ok(!lock2.isLocked());
ok(lock3.isLocked());
});
var lock = $.lock();
test('lock', function () {
lock.unlock().lock();
expect(1);
ok(lock.isLocked());
});
test('unlock', function () {
lock.lock().unlock();
expect(1);
ok(!lock.isLocked());
});
})
|
var should=require('should');
var toast=('../toast');
describe('test/toast.js', function () {
it('toast', function () {
toast.should.equal(toast);
});
});
|
var gm = require('gm');
var request = require('request');
var cors = require('cors');
var upload = require('./s3-upload');
function crop(req, res) {
try {
var q = req.query;
var image = gm(request(q.image), 'tempImage');
image.crop(q.width, q.height, q.left, q.top).toBuffer(function(err, buffer) {
if (err) {
throw err;
}
var fileObj = {
alteration: 'cropped',
protocol: req.get('x-orig-proto') || req.protocol,
prefix: q.prefix,
buffer: buffer
};
upload(fileObj, res);
});
} catch(e) {
res.status(500).send(e);
}
}
module.exports = function (app) {
app.get('/crop', cors(), crop);
};
|
"use strict";
var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
return c > 3 && r && Object.defineProperty(target, key, r), r;
};
Object.defineProperty(exports, "__esModule", { value: true });
/**
* Created by skytzi on 15.4.17.
*/
var core_1 = require("@angular/core");
var common_1 = require("@angular/common");
var router_1 = require("@angular/router");
var login_component_1 = require("./login.component");
var LoginModule = (function () {
function LoginModule() {
}
return LoginModule;
}());
LoginModule = __decorate([
core_1.NgModule({
imports: [router_1.RouterModule, common_1.CommonModule],
declarations: [login_component_1.LoginComponent],
exports: [login_component_1.LoginComponent]
})
], LoginModule);
exports.LoginModule = LoginModule;
//# sourceMappingURL=authentication.module.js.map
|
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();
var _react = require('react');
var _react2 = _interopRequireDefault(_react);
var _libs = require('../../libs');
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; }
function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; }
var Radio = function (_Component) {
_inherits(Radio, _Component);
function Radio(props) {
_classCallCheck(this, Radio);
var _this = _possibleConstructorReturn(this, (Radio.__proto__ || Object.getPrototypeOf(Radio)).call(this, props));
_this.state = {
checked: _this.getChecked(props)
};
return _this;
}
_createClass(Radio, [{
key: 'componentWillReceiveProps',
value: function componentWillReceiveProps(props) {
var checked = this.getChecked(props);
if (this.state.checked != checked) {
this.setState({ checked: checked });
}
}
}, {
key: 'onChange',
value: function onChange(e) {
var checked = e.target.checked;
if (checked) {
if (this.props.onChange) {
if (this.props.hasOwnProperty('model')) {
this.props.onChange(this.props.value);
} else {
this.props.onChange(e);
}
}
}
this.setState({ checked: checked });
}
}, {
key: 'onFocus',
value: function onFocus() {
this.setState({
focus: true
});
}
}, {
key: 'onBlur',
value: function onBlur() {
this.setState({
focus: false
});
}
}, {
key: 'getChecked',
value: function getChecked(props) {
return props.model == props.value || Boolean(props.checked);
}
}, {
key: 'render',
value: function render() {
var checked = this.state.checked;
var _props = this.props,
disabled = _props.disabled,
focus = _props.focus,
value = _props.value,
children = _props.children;
return _react2.default.createElement(
'label',
{ style: this.style(), className: this.className('el-radio') },
_react2.default.createElement(
'span',
{ className: this.classNames({
'el-radio__input': true,
'is-checked': checked,
'is-disabled': disabled,
'is-focus': focus
}) },
_react2.default.createElement('span', { className: 'el-radio__inner' }),
_react2.default.createElement('input', {
type: 'radio',
className: 'el-radio__original',
checked: checked,
disabled: disabled,
onChange: this.onChange.bind(this),
onFocus: this.onFocus.bind(this),
onBlur: this.onBlur.bind(this)
})
),
_react2.default.createElement(
'span',
{ className: 'el-radio__label' },
children || value
)
);
}
}]);
return Radio;
}(_libs.Component);
var _default = Radio;
exports.default = _default;
Radio.propTypes = {
value: _libs.PropTypes.oneOfType([_libs.PropTypes.string, _libs.PropTypes.number]).isRequired,
onChange: _libs.PropTypes.func,
disabled: _libs.PropTypes.bool,
focus: _libs.PropTypes.bool,
/* eslint-disable */
checked: _libs.PropTypes.bool
/* eslint-enable */
};
;
var _temp = function () {
if (typeof __REACT_HOT_LOADER__ === 'undefined') {
return;
}
__REACT_HOT_LOADER__.register(Radio, 'Radio', 'src/radio/Radio.jsx');
__REACT_HOT_LOADER__.register(_default, 'default', 'src/radio/Radio.jsx');
}();
;
|
// Manipulating JavaScript Objects
// I worked on this challenge: [by myself, with: ]
// There is a section below where you will write your code.
// DO NOT ALTER THIS OBJECT BY ADDING ANYTHING WITHIN THE CURLY BRACES!
var terah = {
name: "Terah",
age: 32,
height: 66,
weight: 130,
hairColor: "brown",
eyeColor: "brown"
}
// __________________________________________
// Write your code below.
var adam = {
}
adam.name = "Adam";
terah.spouse = adam;
terah.weight = 125;
delete terah.eyeColor;
adam.spouse = terah;
terah.children = new Object();
var carson = {
name: "Carson",
}
terah.children.carson = carson;
var carter = {
name: "Carter",
}
terah.children.carter = carter;
var colton = {
name: "Colton",
}
terah.children.colton = colton;
adam.children = terah.children;
// __________________________________________
// Reflection: Use the reflection guidelines
/*
What tests did you have trouble passing? What did you do to make
it pass? Why did that work?
There were two tests that I had difficulty with, the first was
assigning terah a spouse. This was mainly because I had misread
the instructions and I was passing terah adam.name and not the
object adam. The second was assigning carson to terah.children,
again this ending up being more a confusion with the instructions
and I failed to initially create carson as a property of
terah.children. Once I realized the mistake, I passed the tests
and moved on.
How difficult was it to add and delete properties outside of the
object itself?
It was easy for the most part and I just needed to spend more
time reading the directions and figuring out what was being asked.
What did you learn about manipulating objects in this challenge?
I started this challenge before finishing 7.2 Eloquent
JavaScript, having only completed the Codecademy JavaScript
track. So I had to do some research on deleting a property. Other
than that, it was mostly things I had already covered.
*/
// __________________________________________
// Driver Code: Do not alter code below this line.
function assert(test, message, test_number) {
if (!test) {
console.log(test_number + "false");
throw "ERROR: " + message;
}
console.log(test_number + "true");
return true;
}
assert(
(adam instanceof Object),
"The value of adam should be an Object.",
"1. "
)
assert(
(adam.name === "Adam"),
"The value of the adam name property should be 'Adam'.",
"2. "
)
assert(
terah.spouse === adam,
"terah should have a spouse property with the value of the object adam.",
"3. "
)
assert(
terah.weight === 125,
"The terah weight property should be 125.",
"4. "
)
assert(
terah.eyeColor === undefined || null,
"The terah eyeColor property should be deleted.",
"5. "
)
assert(
terah.spouse.spouse === terah,
"Terah's spouse's spouse property should refer back to the terah object.",
"6. "
)
assert(
(terah.children instanceof Object),
"The value of the terah children property should be defined as an Object.",
"7. "
)
assert(
(terah.children.carson instanceof Object),
"carson should be defined as an object and assigned as a child of Terah",
"8. "
)
assert(
terah.children.carson.name === "Carson",
"Terah's children should include an object called carson which has a name property equal to 'Carson'.",
"9. "
)
assert(
(terah.children.carter instanceof Object),
"carter should be defined as an object and assigned as a child of Terah",
"10. "
)
assert(
terah.children.carter.name === "Carter",
"Terah's children should include an object called carter which has a name property equal to 'Carter'.",
"11. "
)
assert(
(terah.children.colton instanceof Object),
"colton should be defined as an object and assigned as a child of Terah",
"12. "
)
assert(
terah.children.colton.name === "Colton",
"Terah's children should include an object called colton which has a name property equal to 'Colton'.",
"13. "
)
assert(
adam.children === terah.children,
"The value of the adam children property should be equal to the value of the terah children property",
"14. "
)
console.log("\nHere is your final terah object:")
console.log(terah)
|
function Logger () {
}
Logger.getBeats = function (attacker, defender) {
return attacker.role.title + attacker.name + (attacker.weapon.name? '用' + attacker.weapon.name: '') +
'攻击了' + defender.role.title + defender.name + ', ';
};
Logger.getDetails = function (attacker, defender, damage, extra) {
var mainBody = defender.name + '受到了' + damage + '点伤害, ';
var extraText = '';
var before = false;
if(extra && extra.type == 'strike') {
extraText = attacker.name + '发动了致命一击' + ', ';
before = true;
}
else if(extra && extra.type) {
extraText = defender.name + extra.describe + '了, ';
}
return before? extraText + mainBody: mainBody + extraText;
};
Logger.getRemain = function (player) {
return player.name + '剩余生命:' + player.life;
};
Logger.getExtraDamage = function (attacker, defender, extra) {
var map = {
toxin: attacker.name + '受到' + extra.damage + '点毒性伤害, ' + attacker.name + '剩余生命:' + attacker.life,
flame: attacker.name + '受到' + extra.damage + '点火焰伤害, ' + attacker.name + '剩余生命:' + attacker.life,
frozen: attacker.name + '冻得直哆嗦, 没有击中' + defender.name,
faint: attacker.name + '晕倒了, 无法攻击, 眩晕还剩:' + --extra.remain + '轮'
};
return map[extra.type];
};
Logger.getEffect = function (attacker, defender, effect, damage) {
if(!effect) {
return '';
}
if(effect.repel) {
return defender.name + '被击退了, ';
}
if(effect.double) {
return attacker.name + '发动了连击, ' + defender.name + '受到了' + damage[0] + '点伤害, ';
}
if(effect.defence) {
return defender.name + '发动了隔挡反击, ' + attacker.name + '受到了' + damage[1] + '点伤害, ';
}
return '';
};
Logger.getDeath = function (player) {
return player.name + '被打败了.';
};
Logger.getForward = function (attacker, defender) {
return attacker.name + '靠近了' + defender.name + '.';
};
|
var webpack = require('webpack');
var helpers = require('./helpers');
var path = require('path');
var ExtractTextPlugin = require('extract-text-webpack-plugin');
var HtmlWebpackPlugin = require('html-webpack-plugin');
const ENV = process.env.NODE_ENV = process.env.ENV = 'development';
module.exports = {
devtool: 'cheap-module-eval-source-map',
entry: {
'polyfills': './app/polyfills.ts',
'vendor': './app/vendor.ts',
'app': './app/boot.ts'
},
output: {
path: helpers.root('dist'),
publicPath: 'http://localhost:8084/',
filename: '[name].js',
chunkFilename: '[id].chunk.js'
},
resolve: {
extensions: ['', '.ts', '.js']
},
module: {
loaders: [{
test: /\.ts$/,
exclude: path.resolve(__dirname, "node_modules"),
loaders: ['awesome-typescript-loader', 'angular2-template-loader', 'angular2-router-loader']
},
{
test: /\.html$/,
loader: 'html'
},
{
test: /\.(png|jpe?g|gif|ico)$/,
loader: 'file-loader?name=images/[name].[ext]'
},
{
test: /\.woff(\?v=\d+\.\d+\.\d+)?$/,
loader: 'url-loader?limit=10000&mimetype=application/font-woff'
},
{
test: /\.woff2(\?v=\d+\.\d+\.\d+)?$/,
loader: 'url-loader?limit=10000&mimetype=application/font-woff'
},
{
test: /\.ttf(\?v=\d+\.\d+\.\d+)?$/,
loader: 'url-loader?limit=10000&mimetype=application/octet-stream'
},
{
test: /\.eot(\?v=\d+\.\d+\.\d+)?$/,
loader: 'file-loader'
},
{
test: /\.svg(\?v=\d+\.\d+\.\d+)?$/,
loader: 'url-loader?limit=10000&mimetype=image/svg+xml'
},
{
// site wide css (excluding all css under the app dir)
test: /\.css$/,
exclude: helpers.root('app'),
loader: ExtractTextPlugin.extract('style', 'css?sourceMap')
},
{
// included styles under the app directory - these are for styles included
// with styleUrls
test: /\.css$/,
include: helpers.root('app'),
loader: 'raw'
},
{
test: /\.scss$/,
include: helpers.root('node_modules'),
loader: ExtractTextPlugin.extract('style-loader', 'css-loader')
},
]
},
plugins: [
new webpack.optimize.CommonsChunkPlugin({
name: ['app', 'vendor', 'polyfills']
}),
new ExtractTextPlugin('[name].css'),
new HtmlWebpackPlugin({
template: 'config/index.html'
}),
new webpack.DefinePlugin({
'process.env.NODE_ENV': JSON.stringify('development'),
'process.env.APP_VERSION': JSON.stringify(process.env.npm_package_version),
})
],
devServer: {
historyApiFallback: true,
stats: 'minimal',
}
};
|
---
layout: null
---
$(document).ready(function(){
console.log("exam.js: document is ready");
$('.template').each(function(i) {
$(this).css('display','none');
});
// Use with <div class="copy-of" data-id="foo"></div>
// Use <div id="foo" class="template"></div> on the stuff you want to copy
// The class="template" will hide it the first time.
// The class="copy-of" data-id="foo" signals that you want a copy of foo inserted here.
$('.copy-of').each(function(i) {
var id = $(this).data('id')
$(this).html($(document.getElementById(id)).clone().html());
});
$('.page-break-before').each(function(i) {
var pageNum = i+1;
var prev = $(this).prev();
var evenOddClass = (pageNum % 2 == 0)?
"even-page" : "odd-page";
$(this).addClass(evenOddClass);
var $div = $("<div>", {class: "pagebreak " + evenOddClass});
prev.append($div);
$('.exam-page-header-template').first().clone().appendTo($div);
if (pageNum %2 ==0) {
var img = $('<img>');
img.addClass("even-page-staple-img");
img.attr('src', "/images/Staple-Even-Pages.png");
img.appendTo($div);
} else {
$('.exam-name-header-template').first().clone().appendTo($div);
}
prev.css('margin-bottom','0');
});
$('td.page-num').each(function(i) {
var pageNum = i + 1
$(this).html(pageNum); // re-calculate page numbers
$(this).data("pageNum",pageNum);
if (pageNum % 2==0) {
$(this).parents(".pagebreak").removeClass("odd-page");
$(this).parents(".pagebreak").addClass("even-page");
} else {
$(this).parents(".pagebreak").removeClass("even-page");
$(this).parents(".pagebreak").addClass("odd-page");
}
});
console.log("exam.js: done");
});
|
/*-
* #%L
* ARROWHEAD::WP5::Market Manager
* %%
* Copyright (C) 2016 The ARROWHEAD Consortium
* %%
* 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.
* #L%
*/
'use strict';
angular.module('marketManApp')
.controller('HeaderCtrl', function ($scope, $location, $timeout, serviceMarket) {
$scope.isActive = function (viewLocation) {
return viewLocation === $location.path();
};
$scope.connect = function(connect) {
var c = new serviceMarket.Connection();
c.value = connect;
c.$save();
};
$scope.isConnected = { value: false };
(function tick() {
serviceMarket.Connection.get().$promise.then(
function(val) {
$scope.isConnected = val;
}, function(error){
$scope.isConnected = null;
});
$timeout(tick, 2000);
})();
});
|
// this is a little Node program, running on a Node server
// require() will look inside of a folder and get information, similar to import
// NOTE: gulpfile.js must be in the main directory
var gulp = require('gulp');
var sass = require('gulp-sass');
var concat = require('gulp-concat');
var autoprefixer = require('gulp-autoprefixer');
var minifyCss = require('gulp-minify-css');
var browserSync = require('browser-sync').create();
var reload = browserSync.reload;
var jade = require('gulp-jade');
var plumber = require('gulp-plumber');
////////////////////////////////////////////
// JADE COMPILE
////////////////////////////////////////////
gulp.task('jade', function() {
var jade_locals = {};
// using src = ./*.jade causes index.layout.jade to also compile which we don't want... unless we have multiple main directory files... in which case we do use ./*.jade
// otherwise use src = ./index.jade if there aren't other jade files in ./ (i.e. contact.jade, about.jade, etc.)
return gulp.src('./index.jade')
.pipe(plumber())
.pipe(jade({
locals: jade_locals,
pretty: true
}))
.pipe(gulp.dest('./'))
});
////////////////////////////////////////////
// END JADE COMPILE
////////////////////////////////////////////
////////////////////////////////////////////
// SASS COMPILE
////////////////////////////////////////////
gulp.task('sass', function () {
return gulp.src('css/*.scss')
.pipe(plumber())
.pipe(sass({
'sourcemap=none':true,
'errLogToConsole':true
}))
.pipe(concat('style.css'))
.pipe(autoprefixer({
browsers: ['last 2 versions'],
cascade: false
}))
// .pipe(minifyCss({compatibility: 'ie8'}))
.pipe(gulp.dest('css/'))
.pipe(browserSync.stream());
});
////////////////////////////////////////////
// END SASS COMPILE
////////////////////////////////////////////
////////////////////////////////////////////
// BROWSER SYNC
////////////////////////////////////////////
gulp.task('server', ['sass','jade'], function() {
browserSync.init({
server: "./",
});
gulp.watch("css/*.scss", ['sass']);
// to get SASS partials to trigger changes
// the SCSS partials need to be in their own folder because css/*.scss causes all of them to trigger in the same directory, in the order they currently are which messes up everything
gulp.watch("css/partials/*.scss", ['sass']);
gulp.watch('./*.jade',['jade']);
// to get jade partials to trigger changes
gulp.watch('includes/*.jade',['jade']);
// whenever the .js files change reload
gulp.watch("js/*.js").on('change', reload);
// whenever the .css file changes reload
gulp.watch("css/*.css").on('change', reload);
// whenever the .html file changes reload
gulp.watch("*.html").on('change', reload);
});
////////////////////////////////////////////
// END BROWSER SYNC
////////////////////////////////////////////
////////////////////////////////////////////
// DEFAULT
////////////////////////////////////////////
gulp.task('default', ['server'], function () {
// place everything in here in 'server'
});
////////////////////////////////////////////
// END DEFAULT
////////////////////////////////////////////
|
var $ = require('jquery');
var Backbone = require('backbone');
Backbone.$ = $;
//CHALLENGE: "bring in" the appropriate template for this view
var TodoListView = Backbone.View.extend({
tagName: 'div',
className: 'list-group',
initialize: function () {
this.listenTo(this.collection,'all', this.render);
},
render: function () {
var data = [];
this.collection.models.forEach(function (item) {
data.push({title: item.escape('title'), description: item.escape('description') });
});
this.$el.html(myTemplate({todoData:data}));
}
});
module.exports = TodoListView;
|
import {first, uniq, compact, startsWith} from 'lodash'
import cheerio from 'cheerio'
import urijs from 'urijs'
import {flattenDeepCheerioElements} from 'utils'
export function getRelevantTags(htmlText, urlToFetch){
return new Promise((resolve, reject) => {
const doc = cheerio.load(htmlText, {
ignoreWhitespace: true,
decodeEntities: true,
lowerCaseTags: true,
lowerCaseAttributeNames: true,
recognizeCDATA: true,
recognizeSelfClosing: true
})
resolve({
title: extractTitle(doc) || '',
description: extractDescription(doc) || '',
imageUrls: extractImages(doc, urlToFetch)
})
})
}
function extractDescription(doc){
return first(compact([
doc("meta[name='description']").attr('content'),
doc("meta[property='og:description']").attr('content')
]))
}
function extractTitle(doc) {
return first(compact([
doc("meta[name='title']").attr('content'),
doc("meta[property='og:title']").attr('content'),
doc('title').text(),
]))
}
function extractImages(doc, urlToFetch) {
const imageUrls = flattenDeepCheerioElements([
doc("meta[name='image']").attr("content"),
doc("meta[property='og:image']").attr("content"),
doc("img").map((i, imgNode) => doc(imgNode).attr("src"))
])
return uniq(imageUrls
.map(imageUrl => imageUrl.replace('\\', '/'))
.map(imageUrl => {
const imageProtocol = urijs(imageUrl).protocol()
if(imageProtocol){
return imageUrl
}
if(startsWith(imageUrl, '//')){
const urlToFetchProtocol = urijs(urlToFetch).protocol()
return urijs(imageUrl).protocol(urlToFetchProtocol).toString()
}
return urijs(imageUrl).absoluteTo(urlToFetch).toString()
})
)
}
|
import { Response } from 'aurelia-fetch-client';
import toastr from 'toastr';
/**
* Defines the logger service that provides logging/messaging capabilities.
*/
export class LoggerService {
/**
* @function {logApiError}
* @param {Fault} fault - The http fault message.
* @return {type} {Logs an error concerning an API call.}
*/
logApiError(fault) {
let message = fault.statusText;
if (fault.message) message = fault.message;
fault.json()
.then(result => {
if (fault.status === 500) {
toastr.error(message, 'API error:')
}
else {
toastr.warning(result.message)
}
})
.catch(() =>
toastr.error(message, 'API error:'))
}
/**
* @function {show}
* @param {string} message - The message to show.
* @return {type} {Popups a message.}
*/
show(message) {
toastr.success(message);
}
}
|
var ErrorHandler = require('./error').errorHandler;
module.exports = exports = function(app) {
// The main page of the blog
app.get('/', function(req, res, next){
return res.render('index', {
title: 'Editor homepage'
});
});
/* The main page of the blog, filtered by tag
app.get('/tag/:tag', contentHandler.displayMainPageByTag);
app.get("/post/:permalink", contentHandler.displayPostByPermalink);
app.post('/newcomment', contentHandler.handleNewComment);
app.get("/post_not_found", contentHandler.displayPostNotFound);
app.get('/newpost', contentHandler.displayNewPostPage);
app.post('/newpost', contentHandler.handleNewPost);
app.get('/login', sessionHandler.displayLoginPage);
app.post('/login', sessionHandler.handleLoginRequest);
app.get('/logout', sessionHandler.displayLogoutPage);
app.get("/welcome", sessionHandler.displayWelcomePage);
app.get('/signup', sessionHandler.displaySignupPage);
app.post('/signup', sessionHandler.handleSignup);
app.use(ErrorHandler);
*/
}
|
var Transform = require('stream').Transform,
util = require('util');
var StreamConcat = function(streams, options) {
Transform.call(this, options);
var self = this;
this.streams = streams;
this.canAddStream = true;
this.currentStream = null;
this.streamIndex = 0;
var nextStream = function() {
self.currentStream = null;
if (self.streams.constructor === Array && self.streamIndex < self.streams.length) {
self.currentStream = self.streams[self.streamIndex++];
} else if (typeof self.streams === 'function') {
this.canAddStream = false;
self.currentStream = self.streams();
}
if (self.currentStream === null) {
this.canAddStream = false;
self.push(null);
} else {
self.currentStream.pipe(self, {end: false});
self.currentStream.on('end', nextStream);
}
};
nextStream();
};
util.inherits(StreamConcat, Transform);
StreamConcat.prototype._transform = function(chunk, encoding, callback) {
callback(null, chunk);
};
StreamConcat.prototype.addStream = function(newStream) {
if (this.canAddStream)
this.streams.push(newStream);
else
this.emit('error', new Error('Can\'t add stream.'));
};
module.exports = StreamConcat;
|
'use strict';
angular.module('home', ['ngMessages'])
.controller('homeCtrl', [function() {
}]);
|
var webpack = require('webpack');
var path = require('path');
var mainPath = path.resolve(__dirname,'..','..','src','index.jsx');
var srcPath = path.resolve(__dirname,'..','..', 'src');
var config = require("./webpack.config.js");
var packageJson = require('../../package.json')
/** ============
NOTE: change the following per the dependencies
of the component you are developing.
============ **/
config.externals = {
// "react": "react",
// "react-dom": "react-dom",
// your dependencies here
// "d3": "d3",
}
config.entry = mainPath;
config.devtool = 'none';
config.plugins = [
new webpack.optimize.UglifyJsPlugin(),
new webpack.DefinePlugin({
'process.env': {
'NODE_ENV': JSON.stringify('production')
}
}),
new webpack.ProvidePlugin({
'react': "react"
})
];
config.module.loaders.unshift({
test: /\.jsx$/,
loaders: ['babel'],
exclude: ['node_modules']
})
module.exports = config;
|
//main.js
// const greeter = require('./Greeter.js');
// document.querySelector("#root").appendChild(greeter());
import React from 'react';
import {render} from 'react-dom';
import Greeter from './Greeter';
import './main.css';//使用require导入css文件
render(<Greeter />, document.getElementById('root'));
|
/**
* Created by eirikskogland on 24.09.15.
*/
angular.module('ExamApp').directive('solutionTableCell', function() {
return {
restrict: 'E',
templateUrl: 'templates/directives/solution-table-cell.html',
scope: {
tableIndex: '@',
hasSolution: '@'
},
controller: function($scope) {
console.log("Solution Table Cell Controller");
$scope.showingSolutionRow = false;
$scope.showSolutionForm = function(index) {
$(document.getElementById("solutionForm"+index)).toggle();
};
$scope.showSolutionPDF = function(index) {
$(document.getElementById("solutionPDF"+index)).toggle();
};
$scope.showSolutionClicked = function(index) {
$scope.showingSolutionRow = !$scope.showingSolutionRow;
if($scope.hasSolution) {
// show solution
$scope.showSolutionPDF(index);
} else {
// if logged in
// show solution form
$scope.showSolutionForm(index);
// else
// show login message
}
};
},
controllerAs: 'ctrl'
}
});
|
//
// Copyright (c) 2011 - 2015 ASPECTRON Inc.
// All Rights Reserved.
//
// This file is part of JSX (https://github.com/aspectron/jsx) project.
//
// Distributed under the MIT software license, see the accompanying
// file LICENSE
//
var registry = (function()
{
var log = require("log");
var _registry = new rt.bindings.library("registry");
function Registry(hkey_root_string, path)
{
var self = this;
self.__proto__ = new _registry.Registry(hkey_root_string, path);
return self;
}
function split_path(full_path) // HKEY\\...\\VALUE
{
full_path = full_path.replace(/\//g, "\\");
var list = full_path.split('\\');
if(list.length < 2)
throw new Error("Invalid registry path supplied: "+full_path);
var hkey = list[0];
var filename = list[list.length-1];
var sub_path_start = hkey.length+1;
var path_to_value = full_path.substring(sub_path_start);//, full_path.length-sub_path_start);
var sub_path_length = full_path.length-sub_path_start-(filename.length+1);
var sub_path = path_to_value.substring(0, sub_path_length);
var result =
{
hkey : hkey, // HKEY
filename: filename, // VALUE
sub_path : sub_path, // HKEY/[SUB_PATH]/VALUE
path : path_to_value, // SUB_PATH/VALUE
full_path : full_path // HKEY/SUB_PATH/VALUE
}
return result;
}
function registry_iface()
{
var self = this;
self.Registry = Registry; // Registry class for creation
self.write = function(path, value)
{
var target = split_path(path);
//log.info(target);
var inst = new Registry(target.hkey); // , target.path);
inst.write(target.path,value);
}
self.enumerate_values = function(path, cb_fn)
{
var target = split_path(path);
// log.info(target);
var inst = new Registry(target.hkey);//, target.path);
var index = 0;
while(true)
{
var filename = inst.enum_values(target.path,index++);
if(!filename)
break;
cb_fn.call(filename,filename);
}
}
self.erase_values = function(path, cb_fn)
{
var target = split_path(path);
var inst = new Registry(target.hkey);
var values = [];
var index = 0;
while(true)
{
var filename = inst.enum_values(target.path,index++);
if(!filename)
break;
values.push(filename);
}
for(var i = 0; i < values.length; i++)
{
if(cb_fn.call(values[i]))
inst.erase_value(target.path+'\\'+values[i]);
}
}
return self;
}
return new registry_iface();
})();
exports.$ = registry;
|
'use strict';
module.exports = {
skip: {
type: 'integer',
format: 'int32',
minimum: 0,
maximum: 500,
default: 0,
description: 'The number of results to skip before returning matches. Use this to support paging. Maximum of 500'
},
limit: {
type: 'integer',
format: 'int32',
minimum: 1,
maximum: 200,
default: 20,
description: 'Limit the number of results returned. Defaults to 20. Maximum of 200'
}
};
|
// Use this file to change prototype configuration.
// Note: prototype config can be overridden using environment variables (eg on heroku)
module.exports = {
// Service name used in header. Eg: 'Renew your passport'
serviceName: "Publish data",
// Default port that prototype runs on
port: '3000',
// Enable or disable password protection on production
useAuth: 'true',
// Force HTTP to redirect to HTTPs on production
useHttps: 'true',
// Cookie warning - update link to service's cookie page.
cookieText: 'GOV.UK uses cookies to make the site simpler. <a href="#" title="Find out more about cookies">Find out more about cookies</a>'
};
|
import config from '../../config/common';
import Context from '../../src/server/context';
import range from 'range';
/**
* Create an instance of Context with the given list of blacklisted IPs.
*
* @param {Array=} blacklistIPs Array of IPs to blacklist in the context.
* @returns {Object} Initialized context object.
*/
function create(blacklistIPs) {
const ctx = {
blacklist: Context.prototype.initBlacklistCache(),
db: {},
yubikey: Context.prototype.initYubikeyValidator()
};
ctx.allu = {
template: () => {}
};
range
.range(0, config.blacklist.maxFailedAttempts + 1)
.forEach(() => (blacklistIPs || []).forEach((ip) => ctx.blacklist.increment(ip)));
return ctx;
}
const contextFactory = {
create
};
export default contextFactory;
|
// @flow
import { workspacesRun, toWorkspacesRunOptions } from '../run';
test('bolt workspaces run');
|
'use strict';
var eslint = require('eslint');
var ruleTester = new eslint.RuleTester();
ruleTester.run('rules/no-exports-typo', require('../rules/no-exports-typo'), {
valid: [
'module.exports = true;',
'module.exports.house()',
'exports.mouse = 234',
'exports = module.exports = {}',
'var House = module.exports = function() {}'
],
invalid: [
{ code: 'module.exprts = 123;', errors: [ { message: 'Expected module.exports.' }] },
{ code: 'module.exprts = 123;', errors: [ { message: 'Expected module.exports.' }] },
{ code: 'module.export = 123;', errors: [ { message: 'Expected module.exports.' }] },
{ code: 'module.export()', errors: [ { message: 'Expected module.exports.' }] },
{ code: 'module.extorts.house()', errors: [ { message: 'Expected module.exports.' }] }
]
});
|
"use strict";
/**
* Copyright 2015 Google Inc. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/* jshint maxlen: false */
const apirequest_1 = require("../../lib/apirequest");
/**
* Google Cloud Datastore API
*
* Accesses the schemaless NoSQL database to provide fully managed, robust, scalable storage for your application.
*
* @example
* const google = require('googleapis');
* const datastore = google.datastore('v1beta1');
*
* @namespace datastore
* @type {Function}
* @version v1beta1
* @variation v1beta1
* @param {object=} options Options for Datastore
*/
function Datastore(options) {
const self = this;
self._options = options || {};
self.projects = {
/**
* datastore.projects.export
*
* @desc Exports a copy of all or a subset of entities from Google Cloud Datastore to another storage system, such as Google Cloud Storage. Recent updates to entities may not be reflected in the export. The export occurs in the background and its progress can be monitored and managed via the Operation resource that is created. The output of an export may only be used once the associated operation is done. If an export operation is cancelled before completion it may leave partial data behind in Google Cloud Storage.
*
* @alias datastore.projects.export
* @memberOf! datastore(v1beta1)
*
* @param {object} params Parameters for request
* @param {string} params.projectId Project ID against which to make the request.
* @param {datastore(v1beta1).GoogleDatastoreAdminV1beta1ExportEntitiesRequest} params.resource Request body data
* @param {object} [options] Optionally override request options, such as `url`, `method`, and `encoding`.
* @param {callback} callback The callback that handles the response.
* @return {object} Request object
*/
export: function (params, options, callback) {
if (typeof options === 'function') {
callback = options;
options = {};
}
options || (options = {});
const rootUrl = options.rootUrl || 'https://datastore.googleapis.com/';
const parameters = {
options: Object.assign({
url: (rootUrl + '/v1beta1/projects/{projectId}:export').replace(/([^:]\/)\/+/g, '$1'),
method: 'POST'
}, options),
params: params,
requiredParams: ['projectId'],
pathParams: ['projectId'],
context: self
};
return apirequest_1.default(parameters, callback);
},
/**
* datastore.projects.import
*
* @desc Imports entities into Google Cloud Datastore. Existing entities with the same key are overwritten. The import occurs in the background and its progress can be monitored and managed via the Operation resource that is created. If an ImportEntities operation is cancelled, it is possible that a subset of the data has already been imported to Cloud Datastore.
*
* @alias datastore.projects.import
* @memberOf! datastore(v1beta1)
*
* @param {object} params Parameters for request
* @param {string} params.projectId Project ID against which to make the request.
* @param {datastore(v1beta1).GoogleDatastoreAdminV1beta1ImportEntitiesRequest} params.resource Request body data
* @param {object} [options] Optionally override request options, such as `url`, `method`, and `encoding`.
* @param {callback} callback The callback that handles the response.
* @return {object} Request object
*/
import: function (params, options, callback) {
if (typeof options === 'function') {
callback = options;
options = {};
}
options || (options = {});
const rootUrl = options.rootUrl || 'https://datastore.googleapis.com/';
const parameters = {
options: Object.assign({
url: (rootUrl + '/v1beta1/projects/{projectId}:import').replace(/([^:]\/)\/+/g, '$1'),
method: 'POST'
}, options),
params: params,
requiredParams: ['projectId'],
pathParams: ['projectId'],
context: self
};
return apirequest_1.default(parameters, callback);
}
};
}
module.exports = Datastore;
//# sourceMappingURL=v1beta1.js.map
|
var express = require('express');
var router = express.Router();
/**
* 获得主页内容
*
*/
router.get('/', function(req, res, next) {
res.render('user/index', {
title: 'Express'
});
});
module.exports = router;
|
import Channels from './Channels'
export default Channels
export ChannelBackButton from './ChannelBackButton'
export ChannelBalance from './ChannelBalance'
export ChannelCapacity from './ChannelCapacity'
export ChannelCardList from './ChannelCardList'
export ChannelCardListItem from './ChannelCardListItem'
export ChannelCloseDialog from './ChannelCloseDialog'
export ChannelCount from './ChannelCount'
export ChannelCreate from './ChannelCreate'
export ChannelCreateForm from './ChannelCreateForm'
export ChannelCreateHeader from './ChannelCreateHeader'
export ChannelCreateSummary from './ChannelCreateSummary'
export ChannelData from './ChannelData'
export ChannelDetail from './ChannelDetail'
export ChannelFilter from './ChannelFilter'
export ChannelFooter from './ChannelFooter'
export ChannelHeader from './ChannelHeader'
export ChannelMoreButton from './ChannelMoreButton'
export ChannelNodeSearch from './ChannelNodeSearch'
export ChannelSearch from './ChannelSearch'
export ChannelStatus from './ChannelStatus'
export ChannelSummaryList from './ChannelSummaryList'
export ChannelSummaryListItem from './ChannelSummaryListItem'
export ChannelsActions from './ChannelsActions'
export ChannelsCapacity from './ChannelsCapacity'
export ChannelsCapacityDonut from './ChannelsCapacityDonut'
export ChannelsHeader from './ChannelsHeader'
export ChannelsInfo from './ChannelsInfo'
export ChannelsRefresh from './ChannelsRefresh'
export ChannelsSummaryDonut from './ChannelsSummaryDonut'
export ChannelsViewSwitcher from './ChannelsViewSwitcher'
export NodeCardList from './NodeCardList'
export NodeCardView from './NodeCardView'
|
var allcoin = require('..');
var api = allcoin.PublicApi;
api.depth('mona_btc').then(console.log);
|
function test(){return 5}
|
var _privateMethod = babelHelpers.classPrivateFieldLooseKey("privateMethod");
class Foo {
constructor() {
Object.defineProperty(this, _privateMethod, {
value: _privateMethod2
});
this.publicField = babelHelpers.classPrivateFieldLooseBase(this, _privateMethod)[_privateMethod]();
}
}
var _privateMethod2 = function _privateMethod2() {
return 42;
};
|
// @flow
import type {Action} from '../actions/types';
const initialState = {
firstMonth: -1,
dates: []
};
export type State = {
firstMonth: number;
dates: Array<Array<number>>;
};
export default function calendar(state: State = initialState, action: Action) : State {
switch (action.type) {
case 'CALENDAR_UPDATE':
return action.data;
default:
return state;
}
}
|
import {Entity} from 'aframe-react';
import React from 'react';
export default class Seat extends React.Component {
constructor(props) {
super(props);
this.state = {
opacity: 1,
};
}
render() {
return (
<Entity position={this.props.seatPos} >
<Entity visible={ true }
material={{ color: this.props.buttonColor, transparent: true, shader: 'flat', opacity: this.props.Opacity }}
geometry={{ primitive: "plane", width: 0.2, height: 0.1 }}
id={this.props.componentId}
opacity={ this.props.Opacity }
onClick={ this.props.seatAnimation }
/>
</Entity>
);
}}
|
var sample5__unittest_8cc =
[
[ "QuickTest", "class_quick_test.html", "class_quick_test" ],
[ "IntegerFunctionTest", "class_integer_function_test.html", null ],
[ "QueueTest", "class_queue_test.html", "class_queue_test" ],
[ "TEST_F", "sample5__unittest_8cc.html#ad7679328025ef6d95ee2f45d5604aa89", null ],
[ "TEST_F", "sample5__unittest_8cc.html#ab941323e5a68b9aa8125cb81f5ff3d7c", null ],
[ "TEST_F", "sample5__unittest_8cc.html#ac3e547171299114162b1e8cd5946eb5c", null ],
[ "TEST_F", "sample5__unittest_8cc.html#a0149784588d6ea2a29e0f50a05ee198e", null ]
];
|
(function() {
'use strict';
angular.module('civic.events.genes', ['ui.router']);
angular.module('civic.events.assertions', ['ui.router']);
angular.module('civic.events.variants', ['ui.router']);
angular.module('civic.events.variantGroups', ['ui.router']);
angular.module('civic.events.evidence', ['ui.router']);
angular.module('civic.events.common', []);
angular.module('civic.events')
.config(EventsViewConfig);
// @ngInject
function EventsViewConfig($stateProvider) {
$stateProvider
.state('events', {
abstract: true,
url: '/events',
template: '<ui-view id="events-view"></ui-view>',
onExit: /* @ngInject */ function($deepStateRedirect) {
$deepStateRedirect.reset();
}
});
}
})();
|
$(document).ready(function() {
$('#login-form').on('submit', login());
function login(){
$.ajax({
url: "http://localhost:9999/main/login",
type: "GET",
data: {
username:$("#username-field").val(),
password:$("#password-field").val()
},
success: function(response) {
window.location.href = "feed.php?id="+response;
},
error: function(xhr) {
console.log("Error");
}
});
};
});
|
(function(){
'use strict';
angular
.module('app')
.constant('LSVER', 1);
angular
.module('app')
.constant('LSKEYS', {
fontSize: 'fontSize',
fontBold: 'fontBold',
themeDarK: 'themeDarK',
auth: 'auth',
data: 'data'
});
angular
.module('app')
.service('LsService', function LsService(LSKEYS, LSVER){
var svc = this;
// prefix for keys in local storage
var keyPrefix = 'ntlyrics';
// linker between prefix and provided key, eg: cs.myNewKey
var keyLink = '.';
/**
* Set value to local storage
* @param {string} key
* @param {object} value
*/
function set(key, value){
localStorage.setItem(prefixKey(key), angular.toJson(value));
}
/**
* Get value from local storage
* @param {string} key
* @returns {Object|Array|string|number|*}
*/
function get(key){
var value = localStorage.getItem(prefixKey(key));
if(value){
return angular.fromJson(value);
}
return undefined;
}
/**
* Remove value from local storage
* @param {string} key
*/
function remove(key){
localStorage.removeItem(prefixKey(key));
}
/**
* Prefix the given key with keyPrefix string + keyLink symbol
* @param {string} key
* @returns {string}
*/
function prefixKey(key){
var prefixAndLink = keyPrefix + keyLink;
if(key.indexOf(prefixAndLink) === 0){
return key;
}
return prefixAndLink + key;
}
//var lsver = get(LSKEYS.lsVersion);
//if(!lsver || LSKEYS > lsver){
// localStorage.clear();
// set(LSKEYS.lsVersion, LSVER);
//}
svc.set = set;
svc.get = get;
svc.remove = remove;
svc.prefixKey = prefixKey;
});
})();
|
'use strict';
const fs = require('fs');
const execa = require('execa');
const Bluebird = require('bluebird');
const log = require('npmlog');
const fsStatAsync = Bluebird.promisify(fs.stat);
const isWin = require('./utils/is-win')();
exports.fileExists = function fileExists(path) {
return fsStatAsync(path).then(stat => stat.isFile()).catchReturn(false);
};
exports.executableExists = function executableExists(exe, options) {
let cmd = isWin ? 'where' : 'which';
let test = execa(cmd, [exe], options);
test.on('error', error => log.error('Error spawning "' + cmd + exe + '"', error));
return test.then(result => result.code === 0, () => false);
};
|
var classowncloudsharp_1_1_exceptions_1_1_o_c_s_response_error =
[
[ "OCSResponseError", "classowncloudsharp_1_1_exceptions_1_1_o_c_s_response_error.html#a4a8be342eabdb1ff56309de41bb27376", null ],
[ "OCSResponseError", "classowncloudsharp_1_1_exceptions_1_1_o_c_s_response_error.html#abe1faed2e2f100a1d5e5c051413be70a", null ],
[ "OCSResponseError", "classowncloudsharp_1_1_exceptions_1_1_o_c_s_response_error.html#a140bbc4910589e73d076ba7a977b9e88", null ]
];
|
var config = require('./config.console'),
mongoose = require('mongoose'),
chalk = require('chalk'),
http = require('http'),
fs = require('fs');
var db = mongoose.connect(config.db, function(err) {
if (err) {
console.error(chalk.red('Could not connect to MongoDB!'));
console.log(chalk.red(err));
//process.exit();
} else {
console.log(chalk.green('Connected to MongoDB'));
console.log('Do something here');
mongoose.disconnect();
//fetchWebData();
}
});
|
(function($) {
'use strict';
Crafty.scene('editor', function editorScene () {
showEditorForm();
var _width = Crafty.viewport.width;
var _height = Crafty.viewport.height;
var bricksCreated = 0;
var lvl = {
name: "Dynamic Level",
bricks: []
};
var brickSet = {};
Crafty.e('Line, 2D, Canvas, Color')
.color('#AAAAAA')
.attr({ x:0, y:8*_height/10, w:_width, h:2});
Crafty.e('Line, 2D, Canvas, Color')
.color('#000000')
.attr({ x:0, y:8*_height/10, w:_width, h:1});
var BrickCreator = Crafty.e('BrickCreator, 2D, Canvas, Color, BrickC, Mouse');
// Adds brick to level by its ID
// It will overwrite any info already saved with this ID
var addBrickToSet = function addBrickToSet (brick) {
brickSet[brick._brickID] = {
w: brick.w,
h: brick.h,
x: brick.x,
y: brick.y
};
console.log('Added brick', brickSet[brick._brickID]);
};
var onBrickDropped = function onBrickDropped (mouseEvent) {
console.log('brick %d dropped', this._brickID);
addBrickToSet(this);
};
var createBrick = function createBrick () {
console.log('Cloning');
bricksCreated++;
var newBrick = Crafty.e('DynamicBrick'+bricksCreated+', 2D, Canvas, Color, BrickC, Draggable')
.attr({_brickID: bricksCreated})
.startDrag()
.bind('StopDrag', onBrickDropped);
};
BrickCreator.bind('MouseUp', createBrick);
// SAVE BUTTON
var saveText = Crafty.e("2D, DOM, Text, Mouse").attr({
x : 5*_width / 6 + 20 - 8,
y : 9*_height / 10 + 3
})
.text('Save')
.textFont({ size: '25px', weight: 'bold' })
.textColor('#FFFFFF');
var saveButton = Crafty.e("2D, DOM, greyBtn, SpriteAnimation, Mouse").attr({
x : 5*_width / 6 - 8,
y : 9*_height / 10 + 3,
w : 100,
h : 30
})
.bind('Click', function() {
lvl.name = getLevelName();
var lvlWithBricks = withBricks(lvl);
if (lvlWithBricks.bricks.length <= 0) {
window.alert('Your level is empty, please add at least 1 brick!');
return false;
}
var lvlData = JSON.stringify(lvlWithBricks);
console.log('Trying to save level to file. ', lvl, lvlData);
var isFileSaverSupported = false;
try { isFileSaverSupported = !!new Blob(); } catch(e){}
if (isFileSaverSupported) {
var blob = new Blob([lvlData], {type: "text/plain;charset=utf-8"});
window.saveAs(blob, lvl.name+".json");
} else {
console.warn('Blob is not supported.');
window.prompt("Copy it go! (Ctrl/Cmd + C and Enter)", lvlData);
}
})
.attach(saveText);
// CANCEL BUTTON
var cancelText = Crafty.e("2D, DOM, Text, Mouse").attr({
x : 4*_width / 6,
y : 9*_height / 10 + 3
})
.text('Cancel')
.textFont({ size: '25px', weight: 'bold' })
.textColor('#FFFFFF');
var cancelButton = Crafty.e("2D, DOM, greyBtn, SpriteAnimation, Mouse").attr({
x : 4*_width / 6 - 10,
y : 9*_height / 10 + 3,
w : 100,
h : 30
})
.bind('Click', function() {
if (window.confirm('You will lose any unsaved data if you continue, are you sure?')) {
clearLevelName();
hideEditorForm();
Crafty.scene('menu');
}
})
.attach(cancelText);
function withBricks(lvl) {
lvl.bricks = [];
for (var brick in brickSet) {
if (Object.prototype.hasOwnProperty.call(brickSet, brick)) {
lvl.bricks.push(brickSet[brick]);
}
}
return lvl;
}
});
function showEditorForm () {
var $form = $('form[name="levelNameForm"]');
if ($form) {
$form.show();
}
}
function hideEditorForm () {
var $form = $('form[name="levelNameForm"]');
if ($form) {
$form.hide();
}
}
function getLevelName () {
var $input = $('input[name="levelName"]');
if ($input) {
return $input.val() || 'dynamic_' + getRandomInt(1, 10000000);
}
}
function clearLevelName () {
var $input = $('input[name="levelName"]');
if ($input) {
$input.val('');
}
}
function getRandomInt(min, max) {
return Math.floor(Math.random() * (max - min + 1) + min);
}
})(jQuery);
|
module.exports = cdn
var MaxCDN = require('maxcdn')
function cdn (self) {
if (self.settings.maxcdn.zoneId) {
var maxcdn = new MaxCDN(
self.settings.maxcdn.companyAlias,
self.settings.maxcdn.consumerKey,
self.settings.maxcdn.consumerSecret
)
maxcdn.del('zones/pull.json/' + self.settings.maxcdn.zoneId + '/cache', function (err, res) {
console.log('MAXCDN: STATUS')
if (err) {
console.error('PURGE ERROR: ', err.stack || err.message || err)
return
} else if (res.code !== 200) {
console.error('PURGE ERROR: ', res.code)
return
}
console.log('PURGE SUCCESS')
})
}
}
|
/* Copyright 2015 Dietrich Epp.
This file is part of Dash and the Jetpack Space Pirates. The Dash
and the Jetpack Space Pirates source code is distributed under the
terms of the MIT license. See LICENSE.txt for details. */
'use strict';
var glm = require('gl-matrix');
var vec2 = glm.vec2;
var color = require('./color');
var param = require('./param');
var physics = require('./physics');
function destroy(body) {
if (body.world) {
body.world.removeBody(body);
}
}
var Types = {};
/*
* Register entity types.
*
* category: The category name, or null.
* types: Mapping from type names to types
*/
function registerTypes(types, category) {
var prefix = category ? category + '.' : '';
_.forOwn(types, function(value, key) {
var inh = value.inherit, i;
if (inh) {
for (i = 0; i < inh.length; i++) {
_.defaults(value, inh[i]);
}
delete value.inherit;
}
var tname = prefix + key;
if (Types.hasOwnProperty(tname)) {
console.error('Duplicate type registered: ' + tname);
return;
}
Types[tname] = value;
});
}
function getType(type) {
return Types[type];
}
module.exports = {
destroy: destroy,
registerTypes: registerTypes,
getType: getType,
};
|
var searchData=
[
['parser_2ecpp',['Parser.cpp',['../_parser_8cpp.html',1,'']]],
['parser_2eh',['Parser.h',['../_parser_8h.html',1,'']]],
['parsercollision_2ecpp',['ParserCollision.cpp',['../_parser_collision_8cpp.html',1,'']]],
['parsercollision_2eh',['ParserCollision.h',['../_parser_collision_8h.html',1,'']]],
['pausemenu_2ecpp',['PauseMenu.cpp',['../_pause_menu_8cpp.html',1,'']]],
['pausemenu_2eh',['PauseMenu.h',['../_pause_menu_8h.html',1,'']]],
['physicalentity_2ecpp',['PhysicalEntity.cpp',['../_physical_entity_8cpp.html',1,'']]],
['physicalentity_2eh',['PhysicalEntity.h',['../_physical_entity_8h.html',1,'']]],
['physicalworld_2ecpp',['PhysicalWorld.cpp',['../_physical_world_8cpp.html',1,'']]],
['physicalworld_2eh',['PhysicalWorld.h',['../_physical_world_8h.html',1,'']]],
['player_2ecpp',['Player.cpp',['../_player_8cpp.html',1,'']]],
['player_2eh',['Player.h',['../_player_8h.html',1,'']]],
['power_2ecpp',['Power.cpp',['../_power_8cpp.html',1,'']]],
['power_2eh',['Power.h',['../_power_8h.html',1,'']]]
];
|
/* *************************
* "CLASS": Player
* *************************/
function Player(x, y){
/* ### ATTRIBUTES ### */
Entity.call(this, x, y);
this.vx = 0;
this.vy = 0;
this.currentMaxHealth = 2;
this.health = 2;
this.sprite = new Sprite('res/spritesheet.png', [0, 0], [32,32] , 12, [0,1,2,3,4,5,6,7]);
this.speed = STARTING_PLAYER_SPEED;
this.isBlocking = false;
this.blockRadius = (PLAYER_SPRITE_WIDTH/2) + BLOCK_RADIUS;
this.radius = PLAYER_SPRITE_WIDTH/2;
this.handle = PLAYER_HANDLE; // the ability to turn better
this.teleportRange = 100;
this.bulletRange = 180;
this.fireDelay = 3*1000000; // in microseconds
/* METHODS */
this.checkBoundaries = function(){
if(this.x + this.sprite.width >= canvas.width){
this.x = canvas.width - this.sprite.width;
this.vx /= 2;
}
else if(this.x <= 0){
this.x = 0;
this.vx /= 2;
}
if(this.y + this.sprite.height >= canvas.height){
this.y = canvas.height - this.sprite.height;
this.vy /= 2;
}
else if(this.y <= 0){
this.y = 0;
this.vy /= 2;
}
}
this.update = function(dt){
this.sprite.update(dt);
this.checkEnemiesCollision();
this.vx *= PLAYER_FRICTION;
this.vy *= PLAYER_FRICTION;
this.x += this.vx;
this.y += this.vy;
this.checkBoundaries();
};
this.render = function(){
renderEntity(this);
drawBar(this.x, this.y-12, this.sprite.width, 6, this.health, this.currentMaxHealth, true, "green");
//posx, posy, size, width, state, maxState, horizontal, colorInside
};
this.checkEnemiesCollision = function(){
for(var i = 0; i<enemies.length; i++){
var enemy = enemies[i];
if(circleCollision(this, enemy) ){
enemy.destroy();
createExplosion(enemy.x, enemy.y);
this.health--;
this.checkHealth();
}
}
};
this.checkHealth = function(){
if(this.health <= 0){
//todo upgrade menu, so game over instead
alert("Game over! You survived for " + gameTime.toFixed(2) + " seconds!");
location.reload(true);
}
}
/*this.block = function(){
this.isBlocking = true;
var blockX = this.x + (this.sprite.width/2);
var blockY = this.y + (this.sprite.height/2);
daux.beginPath();
daux.arc(blockX, blockY, this.blockRadius, 0, Math.PI*2, true);
daux.stroke();
setTimeout(function(){
daux.clearRect(0, 0, auxcanvas.width, auxcanvas.height);
}, 50);
setTimeout(function(){
player.isBlocking = false;
}, BLOCK_DELAY);
};*/
return this;
}
var PLAYER_START_X = (canvas.width/2) - 32/2;
var PLAYER_START_Y = (canvas.height/2) - 32/2;
var player = new Player(PLAYER_START_X, PLAYER_START_Y);
|
/**
* Common utilities
* @module glMatrix
*/
// Configuration Constants
export var EPSILON = 0.000001;
export var ARRAY_TYPE = typeof Float32Array !== 'undefined' ? Float32Array : Array;
export var RANDOM = Math.random;
/**
* Sets the type of array used when creating new vectors and matrices
*
* @param {Type} type Array type, such as Float32Array or Array
*/
export function setMatrixArrayType(type) {
ARRAY_TYPE = type;
}
var degree = Math.PI / 180;
/**
* Convert Degree To Radian
*
* @param {Number} a Angle in Degrees
*/
export function toRadian(a) {
return a * degree;
}
/**
* Tests whether or not the arguments have approximately the same value, within an absolute
* or relative tolerance of glMatrix.EPSILON (an absolute tolerance is used for values less
* than or equal to 1.0, and a relative tolerance is used for larger values)
*
* @param {Number} a The first number to test.
* @param {Number} b The second number to test.
* @returns {Boolean} True if the numbers are approximately equal, false otherwise.
*/
export function equals(a, b) {
return Math.abs(a - b) <= EPSILON * Math.max(1.0, Math.abs(a), Math.abs(b));
}
if (!Math.hypot) Math.hypot = function () {
var y = 0,
i = arguments.length;
while (i--) {
y += arguments[i] * arguments[i];
}
return Math.sqrt(y);
};
|
/* jshint node: true */
'use strict';
var util = require('util');
var _ = require('underscore');
var defaults = require('../defaults');
var options = require('../options');
var descriptor = defaults.defaultDescriptor({
'productName': {
name: 'Product Name',
required: true
},
'productDesc': {
name: 'Description'
},
'proxies': {
name: 'API Proxies',
required: true
},
'environments':{
name: 'Environments',
required: true
},
'approvalType': {
name: 'Approval Type',
required: true
},
'quota' : {
name: 'Quota',
},
'quotaInterval':{
name: 'Quota Interval'
},
'quotaTimeUnit': {
name:'Quota Time Unit'
},
'scopes': {
name: "Scope",
}
});
module.exports.descriptor = descriptor;
module.exports.run = function(opts, cb) {
options.validateSync(opts, descriptor);
if (opts.debug) {
console.log('createProduct: %j', opts);
}
var request = defaults.defaultRequest(opts);
createProduct(opts, request, function(err, results) {
if (err) {
cb(err);
} else {
if (opts.debug) {
console.log('results: %j', results);
}
cb(undefined, results);
}
});
};
function createProduct(opts,request,done){
var product = {
"approvalType": "auto",
"attributes":
[ {"name": "access", "value": "public"} ],
"scopes": []
}
product.name = opts.productName
product.displayName = opts.productName
product.description = opts.productDesc
product.proxies = []
if(opts.proxies){
var split = opts.proxies.split(',')
split.forEach(function(s){
if(s && s.trim()!= '') {
product.proxies.push(s.trim())
}
})
}
product.apiResources = []
if(opts.apiResources){
var split = opts.apiResources.split(',')
split.forEach(function(s){
if(s && s.trim()!= '') {
product.apiResources.push(s.trim())
}
})
}
if(opts.scopes){
var split = opts.scopes.split(',')
split.forEach(function(s){
if(s && s.trim()!= '') {
product.scopes.push(s.trim())
}
})
}
product.environments = []
if(opts.environments){
var split = opts.environments.split(',')
split.forEach(function(s){
if(s && s.trim()!= '') {
product.environments.push(s.trim())
}
})
}
if(opts.quota && opts.quotaInterval && opts.quotaTimeUnit){
product.quota = opts.quota
product.quotaInterval = opts.quotaInterval
product.quotaTimeUnit = opts.quotaTimeUnit
}
var uri = util.format('%s/v1/o/%s/apiproducts', opts.baseuri, opts.organization);
request({
uri: uri,
method:'POST',
body: product,
json:true
},function(err,res,body){
var jsonBody = body
if(err){
if (opts.debug) {
console.log('Error occured %s', err);
}
done(err)
}else if (res.statusCode === 201) {
if (opts.verbose) {
console.log('Create successful');
}
if (opts.debug) {
console.log('%s', body);
}
done(undefined, jsonBody);
}else {
if (opts.verbose) {
console.error('Create Product result: %j', body);
}
var errMsg;
if (jsonBody && (jsonBody.message)) {
errMsg = jsonBody.message;
} else {
errMsg = util.format('Create Product failed with status code %d', res.statusCode);
}
done(new Error(errMsg));
}
})
}
|
//~ name b486
alert(b486);
//~ component b487.js
|
/* ========================================================================
* DOM-based Routing
* Based on http://goo.gl/EUTi53 by Paul Irish
*
* Only fires on body classes that match. If a body class contains a dash,
* replace the dash with an underscore when adding it to the object below.
*
* .noConflict()
* The routing is enclosed within an anonymous function so that you can
* always reference jQuery with $, even when in .noConflict() mode.
* ======================================================================== */
(function($) {
// Use this variable to set up the common and page specific functions. If you
// rename this variable, you will also need to rename the namespace below.
var Gruntd = {
// All pages
'common': {
init: function() {
// JavaScript to be fired on all pages
},
finalize: function() {
// JavaScript to be fired on all pages, after page specific JS is fired
}
},
// Home page
'home': {
init: function() {
// JavaScript to be fired on the home page
},
finalize: function() {
// JavaScript to be fired on the home page, after the init JS
}
},
// About us page, note the change from about-us to about_us.
'about_us': {
init: function() {
// JavaScript to be fired on the about us page
}
}
};
// The routing fires all common scripts, followed by the page specific scripts.
// Add additional events for more control over timing e.g. a finalize event
var UTIL = {
fire: function(func, funcname, args) {
var fire;
var namespace = Gruntd;
funcname = (funcname === undefined) ? 'init' : funcname;
fire = func !== '';
fire = fire && namespace[func];
fire = fire && typeof namespace[func][funcname] === 'function';
if (fire) {
namespace[func][funcname](args);
}
},
loadEvents: function() {
// Fire common init JS
UTIL.fire('common');
// Fire page-specific init JS, and then finalize JS
$.each(document.body.className.replace(/-/g, '_').split(/\s+/), function(i, classnm) {
UTIL.fire(classnm);
UTIL.fire(classnm, 'finalize');
});
// Fire common finalize JS
UTIL.fire('common', 'finalize');
}
};
// Load Events
$(document).ready(UTIL.loadEvents);
})(jQuery); // Fully reference jQuery after this point.
|
// App.js
import React from 'react';
import { browserHistory } from 'react-router';
// import components
import NavBar from './navbar/components/NavBar';
export default class App extends React.Component {
constructor(props) {
super(props);
this.state = {}
this.getComponentsXHR = this.getComponentsXHR.bind(this);
this.checkUser = this.checkUser.bind(this);
this.sendComponentsToStore = this.sendComponentsToStore.bind(this);
this.getPostsXHR = this.getPostsXHR.bind(this);
this.sendPostsToStore = this.sendPostsToStore.bind(this);
}
componentDidMount() {
this.getComponentsXHR();
this.getPostsXHR();
let token = localStorage.getItem('token');
if(!token) {
this.checkUser();
}
}
checkUser() {
let that = this;
let xhr = new XMLHttpRequest();
xhr.onreadystatechange = () => {
if(xhr.status === 200 && xhr.readyState === 4) {
that.handleUserData(JSON.parse(xhr.responseText));
}
}
xhr.open('GET', '/api/users');
xhr.send();
}
handleUserData(userData) {
if(userData.length === 0) {
browserHistory.push('/signup')
}
}
getComponentsXHR() {
let xhr = new XMLHttpRequest();
xhr.onreadystatechange = () => {
if(xhr.status === 200 && xhr.readyState === 4) {
this.sendComponentsToStore(JSON.parse(xhr.responseText));
}
}
xhr.open('GET', '/api/plugins');
xhr.send();
}
sendComponentsToStore(pluginData) {
let plugins = [];
pluginData.forEach(plugin => {
plugins.push(plugin);
})
this.props.getComponents(plugins);
}
getPostsXHR() {
let xhr = new XMLHttpRequest();
xhr.onreadystatechange = () => {
if(xhr.status === 200 && xhr.readyState === 4) {
this.sendPostsToStore(JSON.parse(xhr.responseText));
}
}
xhr.open('GET', '/api/posts');
xhr.setRequestHeader('Content-Type', 'application/json');
xhr.send();
}
sendPostsToStore(postData) {
let posts = {};
postData.forEach(post => {
posts[post._id] = post;
})
this.props.getPosts(posts);
}
logoutUser() {
localStorage.removeItem('token');
localStorage.removeItem('userId')
}
render() {
return (
<div>
<NavBar hasToken={this.props.user} logoutUser={this.logoutUser} />
<div className="container-fluid">
{React.cloneElement(this.props.children, this.props)}
</div>
</div>
)
}
}
|
const vboxm = require('./vboxm.js');
//vboxm.clone('8a07a800-4bef-4cc7-9581-6d03a2fab45f', 'vboxm.cloneテスト');
// vboxm.delete('db7cd51b-ac5b-4915-859e-20b88bcf68c2');
let name = 'aiueo,kakikukeko???kdfajlsd';
let regResult = name.match(/^[a-zA-Z0-9!\(\)-=^~\\|@`\[{;+:*\]},<.>/?\_ ]+$/);
console.log(regResult);
|
"use strict";
var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault");
Object.defineProperty(exports, "__esModule", {
value: true
});
Object.defineProperty(exports, "default", {
enumerable: true,
get: function get() {
return _uxcorePopover.default;
}
});
var _uxcorePopover = _interopRequireDefault(require("uxcore-popover"));
module.exports = exports.default;
|
/*
Load a block from github.io.
Accepts a url as a parameter which can include url parameters e.g. https://megjlow.github.io/extension2.js?name=SUN&ip=10.0.0.1
*/
new (function() {
var ext = this;
var descriptor = {
blocks: [
[' ', 'Load extension block ip %s', 'loadBlock', 'ip', 'ip'],
[' ', 'Load extension block name %s', 'loadBlock', 'name', 'name'],
],
url: 'http://www.warwick.ac.uk/tilesfortales'
};
ext._shutdown = function() {};
ext._getStatus = function() {
return {status: 2, msg: 'Device connected'}
};
ext.loadBlock = function(ip) {
ScratchExtensions.loadExternalJS("https://megjlow.github.io/socket.js?ip=" + ip);
};
ext.loadBlockName = function(name) {
ScratchExtensions.loadExternalJS("https://megjlow.github.io/socket.js?name=" + name);
};
ScratchExtensions.register("extensionloader", descriptor, ext);
});
|
/*! @license pzprv3-ui.js v<%= pkg.version %> (c) 2009-<%= grunt.template.today('yyyy') %> <%= pkg.author %>, MIT license
* https://bitbucket.org/sabo2/pzprv3 */
|
const test = require('tape')
const nlp = require('../_lib')
test('number-tag:', function (t) {
let arr = [
['16.125', 'Cardinal'],
['+160.125', 'Cardinal'],
['-0.1', 'Cardinal'],
['.13', 'Cardinal'],
['(127.54)', 'Cardinal'],
['16.125th', 'Ordinal'],
['161,253th', 'Ordinal'],
['+160.125th', 'Ordinal'],
['-0.2nd', 'Ordinal'],
['(127.54th)', 'Ordinal'],
// ['(127.54)', 'Money'],
['-0.1%', 'Percent'],
['.1%', 'Percent'],
['+2,340.91%', 'Percent'],
['-2340%', 'Percent'],
['$-2340.01', 'Money'],
['-$2340', 'Money'],
['+$2340.01', 'Money'],
['$2340.01', 'Money'],
['£1,000,000', 'Money'],
['$19', 'Money'],
['($127.54)', 'Money'],
['2,000₽', 'Money'],
['2000₱', 'Money'],
['2000௹', 'Money'],
['₼2000', 'Money'],
['2.23₽', 'Money'],
['₺50', 'Money'],
['$47.5m', 'Money'],
['$47.5bn', 'Money'],
// ['1,000,000p', 'Cardinal'],
]
arr.forEach(function (a) {
let doc = nlp(a[0])
t.equal(doc.has('#' + a[1]), true, a[0] + ' is #' + a[1])
})
t.end()
})
|
(function($) {
module("autocomplete: options");
test('setAttributes', function() {
var source = $('#autocomplete').autocomplete("option", "source");
equals(source.join(','), ['ActionScript','AppleScript','Asp','BASIC','C','C++','Clojure','COBOL','ColdFusion','Erlang','Fortran','Groovy','Haskell','Java','JavaScript','Lisp','Perl','PHP','Python','Ruby','Scala','Scheme'].join(','), 'Array property');
var autoFocus = $('#autocomplete').autocomplete("option", "autoFocus");
equals(autoFocus, true, 'Boolean property');
var appendTo = $('#autocomplete').autocomplete("option", "appendTo");
equals(appendTo, '#destination', 'String property');
var minLength = $('#autocomplete').autocomplete("option", "minLength");
equals(minLength, 2, 'Number property');
});
})(jQuery);
|
'use strict'
const t = require('tap')
const test = t.test
const FindMyWay = require('../')
test('case insensitive static routes of level 1', t => {
t.plan(1)
const findMyWay = FindMyWay({
caseSensitive: false,
defaultRoute: (req, res) => {
t.fail('Should not be defaultRoute')
}
})
findMyWay.on('GET', '/woo', (req, res, params) => {
t.pass('we should be here')
})
findMyWay.lookup({ method: 'GET', url: '/WOO', headers: {} }, null)
})
test('case insensitive static routes of level 2', t => {
t.plan(1)
const findMyWay = FindMyWay({
caseSensitive: false,
defaultRoute: (req, res) => {
t.fail('Should not be defaultRoute')
}
})
findMyWay.on('GET', '/foo/woo', (req, res, params) => {
t.pass('we should be here')
})
findMyWay.lookup({ method: 'GET', url: '/FoO/WOO', headers: {} }, null)
})
test('case insensitive static routes of level 3', t => {
t.plan(1)
const findMyWay = FindMyWay({
caseSensitive: false,
defaultRoute: (req, res) => {
t.fail('Should not be defaultRoute')
}
})
findMyWay.on('GET', '/foo/bar/woo', (req, res, params) => {
t.pass('we should be here')
})
findMyWay.lookup({ method: 'GET', url: '/Foo/bAR/WoO', headers: {} }, null)
})
test('parametric case insensitive', t => {
t.plan(1)
const findMyWay = FindMyWay({
caseSensitive: false,
defaultRoute: (req, res) => {
t.fail('Should not be defaultRoute')
}
})
findMyWay.on('GET', '/foo/:param', (req, res, params) => {
t.equal(params.param, 'bAR')
})
findMyWay.lookup({ method: 'GET', url: '/Foo/bAR', headers: {} }, null)
})
test('parametric case insensitive with a static part', t => {
t.plan(1)
const findMyWay = FindMyWay({
caseSensitive: false,
defaultRoute: (req, res) => {
t.fail('Should not be defaultRoute')
}
})
findMyWay.on('GET', '/foo/my-:param', (req, res, params) => {
t.equal(params.param, 'bAR')
})
findMyWay.lookup({ method: 'GET', url: '/Foo/MY-bAR', headers: {} }, null)
})
test('parametric case insensitive with capital letter', t => {
t.plan(1)
const findMyWay = FindMyWay({
caseSensitive: false,
defaultRoute: (req, res) => {
t.fail('Should not be defaultRoute')
}
})
findMyWay.on('GET', '/foo/:Param', (req, res, params) => {
t.equal(params.Param, 'bAR')
})
findMyWay.lookup({ method: 'GET', url: '/Foo/bAR', headers: {} }, null)
})
test('case insensitive with capital letter in static path with param', t => {
t.plan(1)
const findMyWay = FindMyWay({
caseSensitive: false,
defaultRoute: (req, res) => {
t.fail('Should not be defaultRoute')
}
})
findMyWay.on('GET', '/Foo/bar/:param', (req, res, params) => {
t.equal(params.param, 'baZ')
})
findMyWay.lookup({ method: 'GET', url: '/foo/bar/baZ', headers: {} }, null)
})
test('case insensitive with multiple paths containing capital letter in static path with param', t => {
/*
* This is a reproduction of the issue documented at
* https://github.com/delvedor/find-my-way/issues/96.
*/
t.plan(2)
const findMyWay = FindMyWay({
caseSensitive: false,
defaultRoute: (req, res) => {
t.fail('Should not be defaultRoute')
}
})
findMyWay.on('GET', '/Foo/bar/:param', (req, res, params) => {
t.equal(params.param, 'baZ')
})
findMyWay.on('GET', '/Foo/baz/:param', (req, res, params) => {
t.equal(params.param, 'baR')
})
findMyWay.lookup({ method: 'GET', url: '/foo/bar/baZ', headers: {} }, null)
findMyWay.lookup({ method: 'GET', url: '/foo/baz/baR', headers: {} }, null)
})
test('case insensitive with multiple mixed-case params within same slash couple', t => {
t.plan(2)
const findMyWay = FindMyWay({
caseSensitive: false,
defaultRoute: (req, res) => {
t.fail('Should not be defaultRoute')
}
})
findMyWay.on('GET', '/foo/:param1-:param2', (req, res, params) => {
t.equal(params.param1, 'My')
t.equal(params.param2, 'bAR')
})
findMyWay.lookup({ method: 'GET', url: '/FOO/My-bAR', headers: {} }, null)
})
test('case insensitive with multiple mixed-case params', t => {
t.plan(2)
const findMyWay = FindMyWay({
caseSensitive: false,
defaultRoute: (req, res) => {
t.fail('Should not be defaultRoute')
}
})
findMyWay.on('GET', '/foo/:param1/:param2', (req, res, params) => {
t.equal(params.param1, 'My')
t.equal(params.param2, 'bAR')
})
findMyWay.lookup({ method: 'GET', url: '/FOO/My/bAR', headers: {} }, null)
})
test('case insensitive with wildcard', t => {
t.plan(1)
const findMyWay = FindMyWay({
caseSensitive: false,
defaultRoute: (req, res) => {
t.fail('Should not be defaultRoute')
}
})
findMyWay.on('GET', '/foo/*', (req, res, params) => {
t.equal(params['*'], 'baR')
})
findMyWay.lookup({ method: 'GET', url: '/FOO/baR', headers: {} }, null)
})
test('parametric case insensitive with multiple routes', t => {
t.plan(6)
const findMyWay = FindMyWay({
caseSensitive: false,
defaultRoute: (req, res) => {
t.fail('Should not be defaultRoute')
}
})
findMyWay.on('POST', '/foo/:param/Static/:userId/Save', (req, res, params) => {
t.equal(params.param, 'bAR')
t.equal(params.userId, 'one')
})
findMyWay.on('POST', '/foo/:param/Static/:userId/Update', (req, res, params) => {
t.equal(params.param, 'Bar')
t.equal(params.userId, 'two')
})
findMyWay.on('POST', '/foo/:param/Static/:userId/CANCEL', (req, res, params) => {
t.equal(params.param, 'bAR')
t.equal(params.userId, 'THREE')
})
findMyWay.lookup({ method: 'POST', url: '/foo/bAR/static/one/SAVE', headers: {} }, null)
findMyWay.lookup({ method: 'POST', url: '/fOO/Bar/Static/two/update', headers: {} }, null)
findMyWay.lookup({ method: 'POST', url: '/Foo/bAR/STATIC/THREE/cAnCeL', headers: {} }, null)
})
|
var entityMap = {
"&": "&",
"<": "<",
">": ">",
'"': '"',
"'": ''',
"/": '/'
};
function escapeHTML(string) {
return String(string).replace(/[&<>"'\/]/g, function (s) {
return entityMap[s];
});
}
function escapeCodeBlocks() {
var sections = document.querySelectorAll('.page-section');
[].forEach.call(sections, function (section) {
var sectionCodeBlocks = section.querySelectorAll('.section-code');
if (sectionCodeBlocks.length) {
[].forEach.call(sectionCodeBlocks, function (codeBlock) {
codeBlock.innerHTML = escapeHTML(codeBlock.innerHTML);
})
}
});
}
function formatCodeBlocks() {
[].forEach.call(document.querySelectorAll('code'), function($code) {
var lines = $code.textContent.split('\n');
if (lines[0] === '') {
lines.shift()
}
var matches;
var indentation = (matches = /^[\s\t]+/.exec(lines[0])) !== null ? matches[0] : null;
if (!!indentation) {
lines = lines.map(function(line) {
line = line.replace(indentation, '')
return line.replace(/\t/g, ' ')
});
$code.textContent = lines.join('\n').trim();
}
});
}
function toggleMenu() {
}
function createMenu() {
var menuList = document.querySelector('.menu-list'),
menuItems = document.querySelectorAll('a[name]'),
menuToggle = document.querySelector('.menu-toggle');
menuToggle.addEventListener('click', function () {
var menu = document.querySelector('.menu');
if (menu.classList.contains('menu-open')) {
menu.classList.remove('menu-open');
this.classList.remove('menu-toggle-open');
} else {
menu.classList.add('menu-open');
this.classList.add('menu-toggle-open');
}
});
[].forEach.call(menuItems, function (menuItem) {
var menuText = menuItem.name.charAt(0).toUpperCase() + menuItem.name.slice(1);
var anchor = document.createElement('a');
anchor.href = '#' + menuText.toLowerCase();
var listItemEl = document.createElement('li');
listItemEl.classList.add('menu-list-item');
listItemEl.innerHTML = '<a class="menu-list-link" href="#' + menuText.toLowerCase() + '""><a>' + menuText;
menuList.appendChild(listItemEl)
});
}
(function init() {
createMenu();
escapeCodeBlocks();
formatCodeBlocks();
hljs.initHighlightingOnLoad();
})();
|
'use es6';
const dotenv = require('dotenv');
const Lyft = require('./build/index');
dotenv.load();
const lyft = new Lyft(process.env.LYFT_CLIENT_ID, process.env.LYFT_CLIENT_SECRET);
const query = {
start: {
latitude: 37.7833,
longitude: -122.4167,
},
end: {
latitude: 37.7922,
longitude: -122.4012,
},
rideType: 'lyft_line',
};
lyft.getRideEstimates(query)
.then((result) => {
console.log(result);
})
.catch((error) => {
console.log(error);
});
|
;(function () {
'use strict';
angular.module('angularGAPI')
.factory('User', ['GAPI', userFact]);
function userFact(GAPI) {
var User = new GAPI('plus', 'v1', {});
User.getUserInfo = function(params) {
return User.get('people', 'me', undefined, params);
};
return User;
}
})();
|
import {
GET_POSTS,
GET_POST,
GET_POST_SLUG,
GET_TAGS,
GET_TAG,
GET_TAG_SLUG,
GET_USERS,
GET_USER,
GET_USER_SLUG,
RESET,
} from './action-types';
const initialData = { data: null, error: null, loading: false, meta: null };
const initialState = {
posts: initialData,
post: initialData,
tags: initialData,
tag: initialData,
users: initialData,
user: initialData,
};
const createStateHandler = (state, action) => (key) => {
const isSingle = !(key.substr(key.length - 1) === 's');
const statusHandlers = {
error: () => ({
...state,
[key]: {
...state[key],
data: null,
error: action.error || 'Unknown Error',
loading: false,
},
}),
loading: () => ({
...state,
[key]: {
...state[key],
loading: true,
error: null,
},
}),
success: () => ({
...state,
[key]: {
...state[key],
data: isSingle ? action.data[isSingle ? `${key}s` : key][0] : action.data[isSingle ? `${key}s` : key],
meta: action.data.meta || null,
error: null,
loading: false,
},
}),
};
return statusHandlers[action.status] ? statusHandlers[action.status]() : state;
};
const reducer = (state, action) => {
if (typeof state === 'undefined') {
return initialState;
}
const updateKey = createStateHandler(state, action);
const reducers = {
[GET_POSTS]: () => updateKey('posts'),
[GET_POST]: () => updateKey('post'),
[GET_POST_SLUG]: () => updateKey('post'),
[GET_TAGS]: () => updateKey('tags'),
[GET_TAG]: () => updateKey('tag'),
[GET_TAG_SLUG]: () => updateKey('tag'),
[GET_USERS]: () => updateKey('users'),
[GET_USER]: () => updateKey('user'),
[GET_USER_SLUG]: () => updateKey('user'),
[RESET]: () => ({
...initialState,
}),
};
return reducers[action.type] ? reducers[action.type]() : state;
};
export default reducer;
|
// COPYRIGHT © 2017 Esri
//
// All rights reserved under the copyright laws of the United States
// and applicable international laws, treaties, and conventions.
//
// This material is licensed for use under the Esri Master License
// Agreement (MLA), and is bound by the terms of that agreement.
// You may redistribute and use this code without modification,
// provided you adhere to the terms of the MLA and include this
// copyright notice.
//
// See use restrictions at http://www.esri.com/legal/pdfs/mla_e204_e300/english
//
// For additional information, contact:
// Environmental Systems Research Institute, Inc.
// Attn: Contracts and Legal Services Department
// 380 New York Street
// Redlands, California, USA 92373
// USA
//
// email: contracts@esri.com
//
// See http://js.arcgis.com/4.4/esri/copyright.txt for details.
define(["require","exports","../../core/Warning","../PointCloudClassBreaksRenderer","../PointCloudRGBRenderer","../PointCloudStretchRenderer","../PointCloudUniqueValueRenderer"],function(e,r,n,o,t,u,d){function i(e){return e?a[e.type]||null:null}function l(e,r,o){var t=i(e);if(t){var u=new t;return u.read(e,o),u}return o&&o.messages&&e&&o.messages.push(new n("renderer:unsupported","Renderers of type '"+(e.type||"unknown")+"' are not supported",{definition:e,context:o})),null}function s(e){var r=i(e);return r?r.fromJSON(e):null}Object.defineProperty(r,"__esModule",{value:!0});var a={pointCloudClassBreaksRenderer:o,pointCloudRGBRenderer:t,pointCloudStretchRenderer:u,pointCloudUniqueValueRenderer:d};r.read=l,r.fromJSON=s});
|
/**
* Created by gbaldeck on 4/17/2017.
*/
var prototype = Object.create(HTMLElement.prototype)
console.log("prototype: ", prototype)
|
var fs = require('fs'),
path = require('path'),
cleanCSS = require('clean-css'),
rjs = require('requirejs');
module.exports = function(grunt) {
// **css* task works pretty much the same as grunt's min task. The task
// target is the destination, data is an array of glob patterns. These
// files are concataned and run through requirejs optimizer to handle
// @import inlines in CSS files.
grunt.task.registerMultiTask('css', 'Concats, replaces @imports and minifies the CSS files', function() {
this.requiresConfig('staging');
// if defined, files get prepended by the output config value
var files = this.data;
// subtarget name is the output destination
var target = this.target;
// async task
var cb = this.async();
// concat prior to rjs optimize css, and before min max info
grunt.log.write('Writing css files to ' + target + '...');
var out = grunt.helper('mincss', files);
// only go through if their's file to process
if(!out) {
return cb();
}
// write minified file before going through rjs:optimize to possibly inline
// @imports (that are not handled by compass within .scss or .sass files)
grunt.file.write(target, out);
// replace @import statements
//
// XXX no error handling in this helper so far..
// Check that rjs returns an error when something wrong (if it throws...)
// if it is bubble the error back here
grunt.helper('rjs:optimize:css', target, function() {
// do the minification once inline imports are done
grunt.log.ok();
cb();
});
});
//
// **mincss** basic utility to concat CSS files and run them through
// [cleanCSS](https://github.com/GoalSmashers/clean-css), might opt to use
// [https://github.com/jzaefferer/grunt-css] plugin.
//
grunt.registerHelper('mincss', function(files, o) {
o = o || {};
files = grunt.file.expandFiles(files);
return files.map(function(filepath) {
var content = grunt.file.read(filepath);
return o.nocompress ? content : cleanCSS.process(content);
}).join('');
});
// **rjs:optimize:css** is an helper using rjs to optimize a single file,
// mainly to properly import multi-level of @import statements, which can be
// tricky with all the url rewrites.
//
// file - Path to the css file to optimize
// options - (optional) rjs configuration
// cb - callback function to call on completion
grunt.registerHelper('rjs:optimize:css', function(file, options, cb) {
if(!cb) { cb = options; options = {}; }
options.cssIn = file;
options.out = options.out || file;
options.optimizeCss = 'standard.keepComments.keepLines';
var before = grunt.file.read(file);
rjs.optimize(options, function() {
grunt.helper('min_max_info', grunt.file.read(file), before);
cb();
});
});
};
|
// Place all the behaviors and hooks related to the matching controller here.
// All this logic will automatically be available in application.js.
/* fix vertical when not overflow
call fullscreenFix() if .fullscreen content changes */
function fullscreenFix(){
var h = $('body').height();
// set .fullscreen height
$(".content-b").each(function(i){
if($(this).innerHeight() <= h){
$(this).closest(".fullscreen").addClass("not-overflow");
}
});
}
$(window).resize(fullscreenFix);
fullscreenFix();
/* resize background images */
function backgroundResize(){
var windowH = $(window).height();
$(".background").each(function(i){
var path = $(this);
// variables
var contW = path.width();
var contH = path.height();
var imgW = path.attr("data-img-width");
var imgH = path.attr("data-img-height");
var ratio = imgW / imgH;
// overflowing difference
var diff = parseFloat(path.attr("data-diff"));
diff = diff ? diff : 0;
// remaining height to have fullscreen image only on parallax
var remainingH = 0;
if(path.hasClass("parallax")){
var maxH = contH > windowH ? contH : windowH;
remainingH = windowH - contH;
}
// set img values depending on cont
imgH = contH + remainingH + diff;
imgW = imgH * ratio;
// fix when too large
if(contW > imgW){
imgW = contW;
imgH = imgW / ratio;
}
//
path.data("resized-imgW", imgW);
path.data("resized-imgH", imgH);
path.css("background-size", imgW + "px " + imgH + "px");
});
}
$(window).resize(backgroundResize);
$(window).focus(backgroundResize);
backgroundResize();
|
// PYRAMID
// Constants
const path = require("path");
const DATA_ROOT = path.join(__dirname, "..", "data");
module.exports = {
DEBUG: false,
FILE_ENCODING: "utf8",
PROJECT_ROOT: path.join(__dirname, ".."),
DATA_ROOT,
LOG_ROOT: path.join(__dirname, "..", "public", "data", "logs"),
DB_FILENAME: path.join(DATA_ROOT, "pyramid.db"),
RELATIONSHIP_NONE: 0,
RELATIONSHIP_FRIEND: 1,
RELATIONSHIP_BEST_FRIEND: 2,
CACHE_LINES: 150,
CONTEXT_CACHE_LINES: 40,
CONTEXT_CACHE_MINUTES: 60,
LAST_SEEN_UPDATE_RATE: 500,
LOG_PAGE_SIZE: 300,
BUNCHED_EVENT_SIZE: 50,
USER_MODIFYING_EVENT_TYPES:
["join", "part", "quit", "kick", "kill", "mode"],
PART_EVENT_TYPES:
["part", "quit", "kick", "kill"],
BUNCHABLE_EVENT_TYPES:
["join", "part", "quit", "kill", "mode"],
SUPPORTED_CATEGORY_NAMES: ["highlights", "allfriends", "system"],
TOKEN_COOKIE_NAME: "token",
TOKEN_COOKIE_SECONDS: 86400 * 365,
PAGE_TYPES: {
CATEGORY: "category",
CHANNEL: "channel",
USER: "user"
},
CONNECTION_STATUS: {
ABORTED: "aborted",
CONNECTED: "connected",
DISCONNECTED: "disconnected",
FAILED: "failed",
REJECTED: "rejected"
},
CHANNEL_TYPES: {
PUBLIC: 0,
PRIVATE: 1
},
USER_EVENT_VISIBILITY: {
OFF: 0,
COLLAPSE_PRESENCE: 1,
COLLAPSE_MESSAGES: 2,
SHOW_ALL: 3
},
RETAIN_DB_TYPES: {
LINES: 0,
DAYS: 1
}
};
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.