text
stringlengths 2
6.14k
|
|---|
module.exports = {
"name": "ATmega16HVB",
"timeout": 200,
"stabDelay": 100,
"cmdexeDelay": 25,
"syncLoops": 32,
"byteDelay": 0,
"pollIndex": 3,
"pollValue": 83,
"preDelay": 1,
"postDelay": 1,
"pgmEnable": [172, 83, 0, 0],
"erase": {
"cmd": [172, 128, 0, 0],
"delay": 45,
"pollMethod": 1
},
"flash": {
"write": [64, 76, 0],
"read": [32, 0, 0],
"mode": 65,
"blockSize": 128,
"delay": 10,
"poll2": 0,
"poll1": 0,
"size": 16384,
"pageSize": 128,
"pages": 128,
"addressOffset": null
},
"eeprom": {
"write": [193, 194, 0],
"read": [160, 0, 0],
"mode": 65,
"blockSize": 4,
"delay": 10,
"poll2": 0,
"poll1": 0,
"size": 512,
"pageSize": 4,
"pages": 128,
"addressOffset": 0
},
"sig": [30, 148, 13],
"signature": {
"size": 3,
"startAddress": 0,
"read": [48, 0, 0, 0]
},
"fuses": {
"startAddress": 0,
"write": {
"low": [172, 160, 0, 0],
"high": [172, 168, 0, 0]
},
"read": {
"low": [80, 0, 0, 0],
"high": [88, 8, 0, 0]
}
}
}
|
const express = require('express');
const app = express();
const path = require('path');
const userCtrl = require('./userCtrl.js');
//extra middleware
const bodyParser = require('body-parser');
app.use(bodyParser.urlencoded({extended: true}), bodyParser.json());
app.use(express.static(path.join(__dirname, '../../node_modules/')));
app.use(express.static(path.join(__dirname, '../client/')));
app.post('/requestDB', userCtrl.sendTableList);
app.post('/requestTable', userCtrl.sendTable);
app.post('/createTable', userCtrl.createTable);
app.post('/insert', userCtrl.insertEntry);
app.post('/update', userCtrl.updateEntry);
app.post('/delete', userCtrl.deleteEntry);
app.post('/query', userCtrl.rawQuery);
app.post('/dropTable', userCtrl.dropTable);
app.listen(3000, ()=> console.log('listening on port 3000'));
|
exports.find = function(options) {
options || (options = {});
options.param || (options.param = 'query');
options.parse || (options.parse = JSON.parse);
return function(req, res, next) {
var query = req.query[options.param];
var conditions = query ? options.parse(query) : {};
req.find = req.model.find(conditions);
next();
};
};
exports.limit = function(options) {
options || (options = {});
options.param || (options.param = 'limit');
return function(req, res, next) {
if (req.query[options.param] !== undefined) {
var limit = parseInt(req.query[options.param], 10);
if (options.max) {
limit = Math.min(limit, options.max);
}
req.find = req.find.limit(limit);
}
next();
};
};
exports.skip = function(options) {
options || (options = {});
options.param || (options.param = 'skip');
return function(req, res, next) {
if (req.query[options.param] !== undefined) {
var skip = parseInt(req.query[options.param], 10);
req.find = req.find.skip(skip);
}
next();
};
};
exports.select = function(options) {
options || (options = {});
options.param || (options.param = 'select');
options.delimiter || (options.delimiter = ',');
return function(req, res, next) {
if (req.query[options.param] !== undefined) {
var select = req.query[options.param].split(options.delimiter).join(' ');
req.find = req.find.select(select);
}
next();
};
};
exports.sort = function(options) {
options || (options = {});
options.param || (options.param = 'sort');
options.delimiter || (options.delimiter = ',');
return function(req, res, next) {
if (req.query[options.param] !== undefined) {
var sort = req.query[options.param].split(options.delimiter).join(' ');
req.find = req.find.sort(sort);
}
next();
};
};
exports.exec = function() {
return function(req, res, next) {
req.find.exec(function(err, results) {
if (err) return next(err);
req.results = results;
next();
});
};
};
exports.count = function(options) {
options || (options = {});
options.param || (options.param = 'query');
options.parse || (options.parse = JSON.parse);
return function(req, res, next) {
var query = req.query[options.param];
var conditions = query ? options.parse(query) : {};
req.model.count(conditions, function(err, count) {
if (err) return next(err);
req.count = count;
next();
});
};
};
|
'use strict';
module.exports = require('./toPairsIn');
//# sourceMappingURL=data:application/json;base64,eyJ2ZXJzaW9uIjozLCJzb3VyY2VzIjpbIi4uLy4uLy4uL2NsaWVudC9saWIvbG9kYXNoL2VudHJpZXNJbi5qcyJdLCJuYW1lcyI6W10sIm1hcHBpbmdzIjoiOztBQUFBLE9BQU8sT0FBUCxHQUFpQixRQUFRLGFBQVIsQ0FBakIiLCJmaWxlIjoiZW50cmllc0luLmpzIiwic291cmNlc0NvbnRlbnQiOlsibW9kdWxlLmV4cG9ydHMgPSByZXF1aXJlKCcuL3RvUGFpcnNJbicpO1xuIl19
|
var chalk = require('chalk');
var safeStringify = require('fast-safe-stringify')
function handleErrorObject(key, value) {
if (value instanceof Error) {
return Object.getOwnPropertyNames(value).reduce(function(error, key) {
error[key] = value[key]
return error
}, {})
}
return value
}
function stringify(o) { return safeStringify(o, handleErrorObject, ' '); }
function debug() {
if (!process.env.WINSTON_CLOUDWATCH_DEBUG) return;
var args = [].slice.call(arguments);
var lastParam = args.pop();
var color = chalk.red;
if (lastParam !== true) {
args.push(lastParam);
color = chalk.green;
}
args[0] = color(args[0]);
args.unshift(chalk.blue('DEBUG:'));
console.log.apply(console, args);
}
module.exports = {
stringify: stringify,
debug: debug
};
|
"use strict"
const createTileGridConverter = require(`./createTileGridConverter`)
const colorDepth = require(`./colorDepth`)
module.exports = ({palette, images}) => {
const converter = createTileGridConverter({
tileWidth: 7,
tileHeight: 9,
columns: 19,
tileCount: 95,
raw32bitData: colorDepth.convert8to32({palette, raw8bitData: images}),
})
return {
convertToPng: converter.convertToPng
}
}
|
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
$(document).ready(function(){
var oldAction = $('#comment-form').attr("action");
hljs.initHighlightingOnLoad();
$('#coolness div').hover(function(){
$('#coolness .second').fadeOut(500);
}, function(){
$('#coolness .second').fadeIn(1000).stop(false, true);
});
$(".reply a").click(function() {
var add = this.className;
var action = oldAction + '/' + add;
$("#comment-form").attr("action", action);
console.log($('#comment-form').attr("action"));
});
});
|
(function(Object) {
Object.Model.Background = Object.Model.PresentationObject.extend({
"initialize" : function() {
Object.Model.PresentationObject.prototype.initialize.call(this);
}
},{
"type" : "Background",
"attributes" : _.defaults({
"skybox" : {
"type" : "res-texture",
"name" : "skybox",
"_default" : ""
},
"name" : {
"type" : "string",
"_default" : "new Background",
"name" : "name"
}
}, Object.Model.PresentationObject.attributes)
});
}(sp.module("object")));
|
import './Modal.scss'
import pugTpl from './Modal.pug'
import mixin from '../../mixin'
import alert from '@vue2do/component/module/Modal/alert'
import confirm from '@vue2do/component/module/Modal/confirm'
export default {
name: 'PageCompModal',
template: pugTpl(),
mixins: [mixin],
data() {
return {
testName: 'test'
}
},
methods: {
simple() {
this.$refs.simple.show()
},
alert() {
alert({
message: '่ฟๆฏไธไธช่ญฆๅๅผน็ช',
theme: this.typeTheme,
ui: this.typeUI
})
},
confirm() {
confirm({
message: '่ฟๆฏไธไธช็กฎ่ฎคๅผน็ช',
title: 'ๆต่ฏ็กฎ่ฎคๅผนๅบ',
theme: 'danger',
ui: 'bootstrap'
})
},
showFullPop() {
this.$refs.fullPop.show()
},
hideFullPop() {
this.$refs.fullPop.hide()
},
showPureModal() {
this.$refs.pureModal.show()
},
hidePureModal() {
this.$refs.pureModal.hide()
}
}
}
|
"use strict";
var i = 180; //3ๅๅบๅฎ
function count(){
if(i <= 0){
document.getElementById("output").innerHTML = "ๅฎๆ!";
}else{
document.getElementById("output").innerHTML = i + "s";
}
i -= 1;
}
window.onload = function(){
setInterval("count()", 1000);
};
|
define(['omega/entity', 'omega/core'], function (e, o) {
'use strict';
var triggerKey = function (action, e) {
o.trigger(action, {
keyCode: e.keyCode,
shiftKey: e.shiftKey,
ctrlKey: e.ctrlKey,
altKey: e.altKey
});
};
window.onkeydown = function (e) {
triggerKey('KeyDown', e);
};
window.onkeyup = function (e) {
triggerKey('KeyUp', e);
};
// ---
return e.extend({
keyboard: {keys: {}},
init: function () {
o.bind('KeyDown', function (e) {
this.keyboard.keys[e.keyCode] = true;
this.trigger('KeyDown', e);
}, this);
o.bind('KeyUp', function (e) {
this.keyboard.keys[e.keyCode] = false;
this.trigger('KeyUp', e);
}, this);
},
isKeyDown: function (keyCode) {
return (this.keyboard.keys[keyCode]);
}
});
});
|
'use strict';
memoryApp.controller('AuthCtrl', function ($scope, $location, AuthService) {
$scope.register = function () {
var username = $scope.registerUsername;
var password = $scope.registerPassword;
if (username && password) {
AuthService.register(username, password).then(
function () {
$location.path('/dashboard');
},
function (error) {
$scope.registerError = error;
}
);
} else {
$scope.registerError = 'Username and password required';
}
};
$scope.login = function () {
var username = $scope.loginUsername;
var password = $scope.loginPassword;
if (username && password) {
AuthService.login(username, password).then(
function () {
$location.path('/dashboard');
},
function (error) {
$scope.loginError = error;
}
);
} else {
$scope.error = 'Username and password required';
}
};
});
|
var xmas = {};
(function() {
xmas.present = {
box: {}
};
}());
(function(global) {
global.xmas.present.box.color = 'Red';
}(this));
|
/**
* A decorator for making sure specific function being invoked serializely.
*
* Usage:
* class A {
* @serialize
* async foo() {}
* }
*
*/
export default function serialize(target, key, descriptor) {
let prev = null;
function serializeFunc(...args) {
const next = () =>
Promise.resolve(descriptor.value.apply(this, args)).then(() => {
prev = null;
});
prev = prev ? prev.then(next) : next();
return prev;
}
return {
...descriptor,
value: serializeFunc,
};
}
|
var functions = {}
functions.evaluateSnapshotType = function (name) {
var splittedName = name.split('-')
var type = splittedName[splittedName.length - 1].split('.')[0]
return type === 'motion' ? type : type === 'snapshot' ? 'periodic' : 'unknown'
}
functions.getSnapshotDate = function (name) {
var splittedData = name.split('.')[0].split('-')[0].split('/')
return splittedData[splittedData.length - 1]
}
module.exports = functions
|
(function() {
'use strict';
angular
.module('rtsApp')
.directive('hasAuthority', hasAuthority);
hasAuthority.$inject = ['Principal'];
function hasAuthority(Principal) {
var directive = {
restrict: 'A',
link: linkFunc
};
return directive;
function linkFunc(scope, element, attrs) {
var authority = attrs.hasAuthority.replace(/\s+/g, '');
var setVisible = function () {
element.removeClass('hidden');
},
setHidden = function () {
element.addClass('hidden');
},
defineVisibility = function (reset) {
if (reset) {
setVisible();
}
Principal.hasAuthority(authority)
.then(function (result) {
if (result) {
setVisible();
} else {
setHidden();
}
});
};
if (authority.length > 0) {
defineVisibility(true);
scope.$watch(function() {
return Principal.isAuthenticated();
}, function() {
defineVisibility(true);
});
}
}
}
})();
|
var async = require('async');
function captainHook(schema) {
// Pre-Save Setup
schema.pre('validate', function (next) {
var self = this;
this._wasNew = this.isNew;
if (this.isNew) {
this.runPreMethods(schema.preCreateMethods, self, function(){
next();
});
} else {
this.runPreMethods(schema.preUpdateMethods, self, function(){
next();
});
}
});
// Post-Save Setup
schema.post('save', function () {
var self = this;
if (this._wasNew) {
this.runPostMethods(schema.postCreateMethods, self);
} else {
this.runPostMethods(schema.postUpdateMethods, self);
}
});
/**
* Pre-Hooks
* These hooks run before an instance has been created / updated
*/
schema.methods.runPreMethods = function(methods, self, callback){
async.eachSeries(methods,
function(fn, cb) {
fn(self, cb);
}, function(err){
if (err){ throw err; }
callback();
});
};
// Pre-Create Methods
schema.preCreateMethods = [];
schema.preCreate = function(fn){
schema.preCreateMethods.push(fn);
};
// Pre-Update Methods
schema.preUpdateMethods = [];
schema.preUpdate = function(fn){
schema.preUpdateMethods.push(fn);
};
/**
* Post-Hooks
* These hooks run after an instance has been created / updated
*/
schema.methods.runPostMethods = function(methods, self){
async.eachSeries(methods,
function(fn, cb) {
fn(self, cb);
}, function(err){
if (err){ throw err; }
});
};
// Post-Create Methods
schema.postCreateMethods = [];
schema.postCreate = function(fn){
schema.postCreateMethods.push(fn);
};
// Post-Update Methods
schema.postUpdateMethods = [];
schema.postUpdate = function(fn){
schema.postUpdateMethods.push(fn);
};
}
module.exports = captainHook;
|
import * as React from 'react';
function CubeIcon(props) {
return (
<svg
xmlns="http://www.w3.org/2000/svg"
fill="none"
viewBox="0 0 24 24"
stroke="currentColor"
{...props}
>
<path
strokeLinecap="round"
strokeLinejoin="round"
strokeWidth={2}
d="M20 7l-8-4-8 4m16 0l-8 4m8-4v10l-8 4m0-10L4 7m8 4v10M4 7v10l8 4"
/>
</svg>
);
}
export default CubeIcon;
|
var repl = require('repl');
var server = repl.start({});
var con = server.context;
con.name='zfpx';
con.age = 5;
con.grow = function(){
return ++con.age;
}
|
export default {
queryRouteList: '/routes',
queryUserInfo: '/user',
logoutUser: '/user/logout',
loginUser: 'POST /user/login',
queryUser: '/user/:id',
queryUserList: '/users',
updateUser: 'Patch /user/:id',
createUser: 'POST /user',
removeUser: 'DELETE /user/:id',
removeUserList: 'POST /users/delete',
queryPostList: '/posts',
queryDashboard: '/dashboard',
}
|
import Controller from '@ember/controller';
import { debounce } from '@ember/runloop';
import fetch from 'fetch';
import RSVP from 'rsvp';
export default class extends Controller {
searchRepo(term) {
return new RSVP.Promise((resolve, reject) => {
debounce(_performSearch, term, resolve, reject, 600);
});
}
}
function _performSearch(term, resolve, reject) {
let url = `https://api.github.com/search/repositories?q=${term}`;
fetch(url).then((resp) => resp.json()).then((json) => resolve(json.items), reject);
}
|
import controller from './controller';
import template from './template.pug';
routes.$inject = ['$stateProvider', '$urlRouterProvider'];
export default function routes($stateProvider, $urlRouterProvider){
$stateProvider.state('main.item', {
url: '/:id/item',
template: template,
controllerAs: 'ctrl',
controller: controller
})
}
|
var config = require('./config')
var webpack = require('webpack')
var merge = require('webpack-merge')
var utils = require('./utils')
var baseWebpackConfig = require('./webpack.base.conf')
var HtmlWebpackPlugin = require('html-webpack-plugin')
var FriendlyErrors = 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, {
module: {
loaders: utils.styleLoaders({ sourceMap: config.dev.cssSourceMap })
},
// eval-source-map is faster for development
devtool: '#eval-source-map',
plugins: [
new webpack.DefinePlugin({
'process.env': config.dev.env
}),
// https://github.com/glenjamin/webpack-hot-middleware#installation--usage
new webpack.optimize.OccurrenceOrderPlugin(),
new webpack.HotModuleReplacementPlugin(),
new webpack.NoErrorsPlugin(),
// https://github.com/ampedandwired/html-webpack-plugin
new HtmlWebpackPlugin({
filename: 'example/index.html',
template: 'example/index.html',
inject: true
}),
new FriendlyErrors()
]
})
|
var margin = {top: 0, right: 0, bottom: 0, left: 130},
width = 1500 - margin.right - margin.left,
height = 470 - margin.top - margin.bottom;
var i = 0,
duration = 750,
root;
var tree = d3.layout.tree()
.size([height, width]);
var diagonal = d3.svg.diagonal()
.projection(function(d) { return [d.y, d.x]; });
var svg = d3.select("#treeplot").append("svg")
.attr("width", width + margin.right + margin.left)
.attr("height", height + margin.top + margin.bottom)
.append("g")
.attr("transform", "translate(" + margin.left + "," + margin.top + ")");
d3.json("/pattern_discovery/data?id={{selections.current_dataset}}", function(error, flare) {
if (error) throw error;
$("#wait").empty();
root = flare;
root.x0 = height / 2;
root.y0 = 0;
function collapse(d) {
if (d.children) {
d._children = d.children;
d._children.forEach(collapse);
d.children = null;
}
}
root.children.forEach(collapse);
update(root);
});
d3.select(self.frameElement).style("height", "800px");
function update(source) {
// Compute the new tree layout.
var nodes = tree.nodes(root).reverse(),
links = tree.links(nodes);
// Normalize for fixed-depth.
nodes.forEach(function(d) { d.y = d.depth * 300; });
// Update the nodesโฆ
var node = svg.selectAll("g.node")
.data(nodes, function(d) { return d.id || (d.id = ++i); });
// Enter any new nodes at the parent's previous position.
var nodeEnter = node.enter().append("g")
.attr("class", "node")
.attr("transform", function(d) { return "translate(" + source.y0 + "," + source.x0 + ")"; })
.on("click", click);
nodeEnter.append("circle")
.attr("r", 1e-6)
.style("fill", function(d) { return d._children ? "lightsteelblue" : "#fff"; });
nodeEnter.append("text")
.attr("x", function(d) { return d.children || d._children ? -10 : 10; })
.attr("dy", ".35em")
.attr("text-anchor", function(d) { return d.children || d._children ? "end" : "start"; })
.text(function(d) { return d.name; })
.style("fill-opacity", 1e-6);
// Transition nodes to their new position.
var nodeUpdate = node.transition()
.duration(duration)
.attr("transform", function(d) { return "translate(" + d.y + "," + d.x + ")"; });
nodeUpdate.select("circle")
.attr("r", 4.5)
.style("fill", function(d) { return d._children ? "lightsteelblue" : "#fff"; });
nodeUpdate.select("text")
.style("fill-opacity", 1);
// Transition exiting nodes to the parent's new position.
var nodeExit = node.exit().transition()
.duration(duration)
.attr("transform", function(d) { return "translate(" + source.y + "," + source.x + ")"; })
.remove();
nodeExit.select("circle")
.attr("r", 1e-6);
nodeExit.select("text")
.style("fill-opacity", 1e-6);
// Update the linksโฆ
var link = svg.selectAll("path.link")
.data(links, function(d) { return d.target.id; });
// Enter any new links at the parent's previous position.
link.enter().insert("path", "g")
.attr("class", "link")
.attr("d", function(d) {
var o = {x: source.x0, y: source.y0};
return diagonal({source: o, target: o});
});
// Transition links to their new position.
link.transition()
.duration(duration)
.attr("d", diagonal);
// Transition exiting nodes to the parent's new position.
link.exit().transition()
.duration(duration)
.attr("d", function(d) {
var o = {x: source.x, y: source.y};
return diagonal({source: o, target: o});
})
.remove();
// Stash the old positions for transition.
nodes.forEach(function(d) {
d.x0 = d.x;
d.y0 = d.y;
});
}
// Toggle children on click.
function click(d) {
if (d.children) {
d._children = d.children;
d.children = null;
} else {
d.children = d._children;
d._children = null;
}
update(d);
}
|
import { EventBus } from '../wires/event_bus';
class EventStore {
constructor(storeAdapter) {
this.adapter = storeAdapter;
}
appendToStream(streamId, expectedVersion, events) {
if (events.length === 0) {
return;
}
events.forEach(function(event) {
this.adapter.append(streamId, expectedVersion, event);
EventBus.publish('domain.'+streamId+'.'+event.name, event);
expectedVersion++;
}, this);
}
loadEventStream(streamId) {
var version = 0,
events = [],
records = this.readEventStream(streamId, 0, null);
records.forEach(function(r) {
version = r.version;
events.push(r.data);
});
return new EventStream(streamId, events, version);
}
readEventStream(streamId, skipEvents, maxCount) {
return this.adapter.read(streamId, skipEvents, maxCount);
}
}
class EventStream {
constructor(streamId, events, version) {
this.streamId = streamId;
this.events = events;
this.version = version;
}
}
export { EventStore, EventStream };
|
import { h } from 'omi';
import createSvgIcon from './utils/createSvgIcon';
export default createSvgIcon(h("path", {
d: "M19 3h-4.18C14.4 1.84 13.3 1 12 1c-1.3 0-2.4.84-2.82 2H5c-1.1 0-2 .9-2 2v14c0 1.1.9 2 2 2h14c1.1 0 2-.9 2-2V5c0-1.1-.9-2-2-2zm-7 0c.55 0 1 .45 1 1s-.45 1-1 1-1-.45-1-1 .45-1 1-1zm0 15l-5-5h3V9h4v4h3l-5 5z"
}), 'AssignmentReturned');
|
(function () {
'use strict';
angular
.module('app.home')
.config(appRun);
/* @ngInject */
function appRun($stateProvider) {
$stateProvider
.state('root.home', {
url: '/',
templateUrl: 'app/home/home.html',
controller: 'Home',
controllerAs: 'vm',
});
}
})();
|
import React from 'react';
import {
Text,
View,
TextInput,
} from 'react-native';
import newChallengeStyles from '../../styles/newChallenge/newChallengeStyles';
import mainStyles from '../../styles/main/mainStyles';
import ItemSelectView from './ItemSelectView';
const propTypes = {
onChallengeUpdate: React.PropTypes.func,
};
const prizeItemStyle = {
marginTop: 10,
labelFontSize: 22,
iconFontSize: 30,
iconColor: mainStyles.themeColors.textPrimary,
};
class PrizeView extends React.Component {
constructor(props) {
super(props);
this.state = {
prize: null,
customPrize: '',
prizes: [
{ label: 'Diner', style: prizeItemStyle },
{ label: 'Drinks', style: prizeItemStyle },
{ label: 'Gift', style: prizeItemStyle },
{ label: 'Define your own', style: prizeItemStyle },
],
};
}
setCustomPrize = (customPrize) => {
this.setState({ customPrize });
this.props.onChallengeUpdate({ prize: customPrize });
}
selectPrize = (prizeLabel) => {
const prizes = this.state.prizes;
prizes.forEach(prize => {
if (prizeLabel === prize.label) {
prize.style = { ...prizeItemStyle, iconColor: mainStyles.themeColors.primary };
} else {
prize.style = { ...prizeItemStyle, opacity: 0.2 };
}
});
this.setState({ prize: prizeLabel, prizes });
this.props.onChallengeUpdate({ prize: prizeLabel });
}
render = () => (
<View style={newChallengeStyles.mainContainer}>
<View style={newChallengeStyles.contentContainer}>
<Text style={newChallengeStyles.titleFont}>Prize (optional)</Text>
<View style={newChallengeStyles.itemsContainer} >
{this.state.prizes.map(prize =>
(<ItemSelectView
key={prize.label}
label={prize.label}
style={prize.style}
onItemSelect={this.selectPrize}
/>)
)}
</View>
{this.state.prize === 'Define your own' ?
<View style={newChallengeStyles.settingInputContainer} >
<TextInput
style={newChallengeStyles.inputFont}
placeholder="Birthday cake for Paul"
placeholderTextColor={mainStyles.themeColors.textPrimary}
onChangeText={this.setCustomPrize}
value={this.state.customPrize}
/>
</View>
: null}
</View>
</View>
);
}
PrizeView.propTypes = propTypes;
export default PrizeView;
|
import React, {PropTypes} from 'react';
import L from 'leaflet';
import gh from '../api/GitHubApi';
import RaisedButton from 'material-ui/RaisedButton';
const REPO_TIMESPAN = {
ALLTIME: 0,
THIRTYDAYS: 1,
SIXTYDAYS: 2,
ONEYEAR: 3
};
const defaultMapConfig = {
options: {
center: [
39.7589, -84.1916
],
zoomControl: false,
zoom: 4,
maxZoom: 20,
minZoom: 2,
scrollwheel: false,
infoControl: false,
attributionControl: false
},
tileLayer: {
uri: 'http://{s}.tiles.wmflabs.org/bw-mapnik/{z}/{x}/{y}.png',
options: {
maxZoom: 18,
id: ''
}
}
};
class RepoUserHeatmap extends React.Component {
constructor(props, context) {
super(props, context);
this.state = {
timespan: REPO_TIMESPAN.THIRTYDAYS,
data: []
};
this.initializeMap = this.initializeMap.bind(this);
}
componentDidMount() {
this.initializeMap();
this.updateData();
gh.getTopRepos().then(data => {
console.log('=== REPOS ===');
console.log(data);
return gh.getContributors(data.data[0].full_name);
}).then(contribs => {
console.log('=== CONTRIBS ===');
console.log(contribs);
return gh.getUser(contribs.data[0].login);
}).then(user => {
console.log('=== USER ===');
console.log(user);
return gh.getRateLimit();
}).then(limit => {
console.log('=== RATE LIMIT ===');
console.log(limit);
}).catch(err => {
console.log('ERROR:');
console.log(err);
});
}
componentWillUnmount() {
this.map = null;
}
initializeMap() {
if (this.map) {
return;
}
this.map = L.map(this.mapDiv, this.props.mapOptions || defaultMapConfig.options);
if (this.props.mapLayers && this.props.mapLayers.length > 0) {
for (let i=0; i < this.props.mapLayers.length; i++) {
this.props.mapLayers[i].addTo(this.map);
}
}
else {
L.tileLayer(defaultMapConfig.tileLayer.uri, defaultMapConfig.tileLayer.options).addTo(this.map);
}
}
updateData() {
}
render() {
return (
<div className="map-container">
<div className="os-map" ref={(div) => { this.mapDiv = div; }}></div>
<RaisedButton label="Default" />
</div>
);
}
}
RepoUserHeatmap.propTypes = {
mapOptions: PropTypes.object,
mapLayers: PropTypes.array
};
export default RepoUserHeatmap;
|
function lessThan (a, b) {
return a < b
}
function main () {
for (var i = 0; i < 10000; i++) {
lessThan(1, 0x7fffffff)
}
for (var i = 0; i < 10000; i++) {
lessThan(1, Infinity)
}
for (var i = 0; i < 10000; i++) {
lessThan(1, 0x7fffffff)
}
}
main()
|
/*!
* hybridify-all <https://github.com/hybridables/hybridify-all>
*
* Copyright (c) 2015 Charlike Mike Reagent, contributors.
* Released under the MIT license.
*/
'use strict'
var reduce = require('object.reduce')
var hybridify = require('hybridify')
/**
* > Hybridifies all the selected functions in an object.
*
* **Example:**
*
* ```js
* var hybridifyAll = require('hybridify-all')
* var fs = require('fs')
*
* fs = hybridifyAll(fs)
* fs.readFile(__filename, 'utf8', function(err, res) {
* //=> err, res
* })
* .then(function(res) {
* //=> res
* return fs.stat(__filename)
* })
* .then(function(stat) {
* assert.strictEqual(stat.size, fs.statSync(__filename).size)
* })
* ```
*
* @name hybridifyAll
* @param {Object|Function} `<source>` the source object for the async functions
* @param {Object|Function} `[dest]` the destination to set all the hybridified methods
* @return {Object|Function}
* @api public
*/
module.exports = function hybridifyAll (source, dest) {
if (!source) {
throw new Error('hybridify-all: should have at least 1 arguments')
}
if (typeOf(source) !== 'function' && typeOf(source) !== 'object') {
throw new TypeError('hybridify-all: expect `source` be object|function')
}
dest = dest || {}
if (typeof source === 'function') {
dest = hybridify(source)
}
return Object.keys(source).length ? reduce(source, function (dest, fn, key) {
if (typeof fn === 'function') {
dest[key] = hybridify(fn)
}
return dest
}, dest) : dest
}
/**
* Get correct type of value
*
* @param {*} `val`
* @return {String}
* @api private
*/
function typeOf (val) {
if (Array.isArray(val)) {
return 'array'
}
if (typeof val !== 'object') {
return typeof val
}
return Object.prototype.toString(val).slice(8, -1).toLowerCase()
}
|
import { createStore } from '@utils/store.utils';
import placeholderImage from '../images/placeholder.jpeg';
import { getPhotoUrl, getPrefetchedPhotoForDisplay } from './api';
import { getLocalPhotoPath, getRandomLocalPhoto } from './photos.local';
import Settings from './settings';
export const getStateObject = (force = false) => {
const fetchFromServer = Settings.fetchFromServer;
const newPhotoDuration = Settings.newPhotoDuration;
let photoUrl;
let placeholderPhotoUrl;
let photoMeta;
let placeholderPhotoMeta;
// if allowed to fetch from server
// begin with assuming we get a
// prefetched photo from the api
if (fetchFromServer) {
photoMeta = getPrefetchedPhotoForDisplay(force ? 0 : newPhotoDuration);
photoUrl = getPhotoUrl(photoMeta);
}
// or a locally stored photo
if (!photoUrl) {
photoMeta = getRandomLocalPhoto();
photoUrl = getLocalPhotoPath(photoMeta);
}
// or a fallback placeholder photo
if (!photoUrl) {
photoMeta = null;
photoUrl = placeholderImage;
}
// get a random image as placeholder
// to handle offline network scenarios
placeholderPhotoMeta = getRandomLocalPhoto();
placeholderPhotoUrl = getLocalPhotoPath(placeholderPhotoMeta);
return {
fetchFromServer,
photoUrl,
photoMeta,
placeholderPhotoUrl,
placeholderPhotoMeta,
newPhotoDuration,
};
};
export default createStore();
|
import {Component} from 'react';
import {reduxForm} from 'redux-form';
import './CreateTodoForm.styl';
class CreateTodoForm extends Component {
render() {
return (
<form className="create-todo-form" onSubmit={this.props.handleSubmit} autoComplete="off">
<input type="text" placeholder="Todo text..." {...this.props.fields.text}></input>
<button type="submit">Create</button>
</form>
);
}
}
CreateTodoForm.propTypes = {
fields: React.PropTypes.object.isRequired,
handleSubmit: React.PropTypes.func.isRequired
};
export default reduxForm({
form: 'CreateTodoForm',
fields: ['text']
})(CreateTodoForm);
|
import React, { useState, useRef } from 'react';
import { computeOutOffsetByIndex, computeInOffsetByIndex } from './lib/Util';
// import { SVGComponent } from './lib-hooks/svgComp-hooks';
import Spline from './lib/Spline';
import DragNode from './lib/Node';
const index = ({
data,
onNodeDeselect,
onNodeMove,
onNodeStartMove,
onNodeSelect,
onNewConnector,
onRemoveConnector
}) => {
const [dataS, setDataS] = useState(data);
const [source, setSource] = useState([]);
const [dragging, setDragging] = useState(false);
const [mousePos, setMousePos] = useState({x: 0, y: 0});
const svgRef = useRef();
const onMouseMove = e => {
let [pX, pY] = [e.clientX, e.clientY];
e.stopPropagation();
e.preventDefault();
const svgRect = svgRef.current.getBoundingClientRect();
// console.log(svgRect);
setMousePos(old => {
return {
...old,
...{x: pX - svgRect.left, y: pY - svgRect.top}
}
});
}
const onMouseUp = e => {
setDragging(false);
}
const handleNodeStart = nid => {
onNodeStartMove(nid);
}
const handleNodeStop = (nid, pos) => {
onNodeMove(nid, pos);
}
const handleNodeMove = (idx, pos) => {
let dataT = dataS;
dataT.nodes[idx].x = pos.x;
dataT.nodes[idx].y = pos.y;
// console.log(dataT);
// console.log({...dataS,...dataT});
setDataS(old => {
return {
...old,
...dataT
}
});
}
const handleStartConnector = (nid, outputIdx) => {
let newSrc = [nid, outputIdx];
setDragging(true);
setSource(newSrc); // Not sure if this will work...
}
const handleCompleteConnector = (nid, inputIdx) => {
if (dragging) {
let fromNode = getNodeById(data.nodes, source[0]);
let fromPinName = fromNode.fields.out[source[1]].name;
let toNode = getNodeById(data.nodes, nid);
let toPinName = toNode.fields.in[inputIdx].name;
onNewConnector(fromNode.nid, fromPinName, toNode.nid, toPinName);
}
setDragging(false);
}
const handleRemoveConnector = connector => {
if (onRemoveConnector) {
onRemoveConnector(connector);
}
}
const handleNodeSelect = nid => {
if (onNodeSelect) {
onNodeSelect(nid);
}
}
const handleNodeDeselect = nid => {
if (onNodeDeselect) {
onNodeDeselect(nid);
}
}
const computePinIdxfromLabel = (pins, pinLabel) => {
let reval = 0;
for (let pin of pins) {
if (pin.name === pinLabel) {
return reval;
} else {
reval++;
}
}
}
const getNodeById = (nodes, nid) => {
let reval = 0;
for(const node of nodes) {
if (node.nid === nid) {
return nodes[reval];
} else {
reval++;
}
}
}
let newConn = null;
let i = 0;
// console.log(dragging);
if (dragging) {
let sourceNode = getNodeById(dataS.nodes, source[0]);
let connectorStart = computeOutOffsetByIndex(sourceNode.x, sourceNode.y, source[1]);
let connectorEnd = {
x: mousePos.x,
y: mousePos.y
};
// console.log(mousePos);
newConn = <Spline
start={connectorStart}
end={connectorEnd}
/>
}
let splineIdx = 0;
return (
<div className={dragging ? 'dragging' : ''}
onMouseMove={onMouseMove}
onMouseUp={onMouseUp}
>
{dataS.nodes.map(node => {
// console.log(node);
return <DragNode
index={i++}
nid={node.nid}
title={node.type}
inputs={node.fields.in}
outputs={node.fields.out}
pos={{x: node.x, y: node.y}}
key={node.nid}
onNodeStart={nid => handleNodeStart(nid)}
onNodeStop={(nid, pos) => handleNodeStop(nid, pos)}
onNodeMove={(idx, pos) => handleNodeMove(idx, pos)}
onStartConnector={(nid, outputIdx) => handleStartConnector(nid, outputIdx)}
onCompleteConnector={(nid, inputIdx) => handleCompleteConnector(nid, inputIdx)}
onNodeSelect={nid => handleNodeSelect(nid)}
onNodeDeselect={nid => handleNodeDeselect(nid)}
/>
})}
<svg style={{position: 'absolute', height: "100%", width: "100%", zIndex: 9000}}
ref={svgRef}>
{data.connections.map(connector => {
// console.log(data);
// console.log(connector);
let fromNode = getNodeById(data.nodes, connector.from_node);
let toNode = getNodeById(data.nodes, connector.to_node);
let splinestart = computeOutOffsetByIndex(fromNode.x, fromNode.y, computePinIdxfromLabel(fromNode.fields.out, connector.from));
let splineend = computeInOffsetByIndex(toNode.x, toNode.y, computePinIdxfromLabel(toNode.fields.in, connector.to));
return <Spline
start={splinestart}
end={splineend}
key={splineIdx++}
mousePos={mousePos}
onRemove={() => handleRemoveConnector(connector)}
/>
})}
{newConn}
</svg>
</div>
);
}
export default index;
|
var t = require('chai').assert;
var P = require('bluebird');
var Renderer = require('../').Renderer;
var view = {
"name": {
"first": "Michael",
"last": "Jackson"
},
"age": "RIP",
calc: function () {
return 2 + 4;
},
delayed: function () {
return new P(function (resolve) {
setTimeout(resolve.bind(undefined, 'foo'), 100);
});
}
};
describe('Renderer', function () {
describe('Basics features', function () {
it('should render properties', function (done) {
var renderer = new Renderer();
renderer.render('Hello {{name.first}} {{name.last}}', {
"name": {
"first": "Michael",
"last": "Jackson"
}
}).then(function (result) {
t.equal(result, 'Hello Michael Jackson');
done();
})
});
it('should render variables', function (done) {
var renderer = new Renderer();
renderer.render('* {{name}} * {{age}} * {{company}} * {{{company}}} * {{&company}}{{=<% %>=}} * {{company}}<%={{ }}=%>', {
"name": "Chris",
"company": "<b>GitHub</b>"
}).then(function (result) {
t.equal(result, '* Chris * * <b>GitHub</b> * <b>GitHub</b> * <b>GitHub</b> * {{company}}');
done();
})
});
it('should render variables with dot notation', function (done) {
var renderer = new Renderer();
renderer.render('{{name.first}} {{name.last}} {{age}}', {
"name": {
"first": "Michael",
"last": "Jackson"
},
"age": "RIP"
}).then(function (result) {
t.equal(result, 'Michael Jackson RIP');
done();
})
});
it('should render sections with false values or empty lists', function (done) {
var renderer = new Renderer();
renderer.render('Shown. {{#person}}Never shown!{{/person}}', {
"person": false
}).then(function (result) {
t.equal(result, 'Shown. ');
done();
})
});
it('should render sections with non-empty lists', function (done) {
var renderer = new Renderer();
renderer.render('{{#stooges}}<b>{{name}}</b>{{/stooges}}', {
"stooges": [
{"name": "Moe"},
{"name": "Larry"},
{"name": "Curly"}
]
}).then(function (result) {
t.equal(result, '<b>Moe</b><b>Larry</b><b>Curly</b>');
done();
})
});
it('should render sections using . for array of strings', function (done) {
var renderer = new Renderer();
renderer.render('{{#musketeers}}* {{.}}{{/musketeers}}', {
"musketeers": ["Athos", "Aramis", "Porthos", "D'Artagnan"]
}).then(function (result) {
t.equal(result, '* Athos* Aramis* Porthos* D'Artagnan');
done();
})
});
it('should render function', function (done) {
var renderer = new Renderer();
renderer.render('{{title}} spends {{calc}}', {
title: "Joe",
calc: function () {
return 2 + 4;
}
}).then(function (result) {
t.equal(result, 'Joe spends 6');
done();
})
});
it('should render function with variable as context', function (done) {
var renderer = new Renderer();
renderer.render('{{#beatles}}* {{name}} {{/beatles}}', {
"beatles": [
{"firstName": "John", "lastName": "Lennon"},
{"firstName": "Paul", "lastName": "McCartney"},
{"firstName": "George", "lastName": "Harrison"},
{"firstName": "Ringo", "lastName": "Starr"}
],
"name": function () {
return this.firstName + " " + this.lastName;
}
}).then(function (result) {
t.equal(result, '* John Lennon * Paul McCartney * George Harrison * Ringo Starr ');
done();
})
});
it('should render inverted sections', function (done) {
var renderer = new Renderer();
renderer.render('{{#repos}}<b>{{name}}</b>{{/repos}}{{^repos}}No repos :({{/repos}}', {
"repos": []
}).then(function (result) {
t.equal(result, 'No repos :(');
done();
})
});
it('should render ignore comments', function (done) {
var renderer = new Renderer();
renderer.render('Today{{! ignore me }}.').then(function (result) {
t.equal(result, 'Today.');
done();
})
});
it('should render partials', function (done) {
var renderer = new Renderer();
renderer.render('{{#names}}{{> user}}{{/names}}', {
names: [{
name: 'Athos'
}, {
name: 'Porthos'
}]
}, {
user: 'Hello {{name}}.'
}).then(function (result) {
t.equal(result, 'Hello Athos.Hello Porthos.');
done();
})
});
});
describe('Promise functions', function () {
it('should render with promise functions', function (done) {
var renderer = new Renderer();
renderer.render('3+5={{#add}}[3,5]{{/add}}', {
add: function (a, b) {
return new P(function (resolve) {
setTimeout(function () {
resolve(a + b);
}, 100);
})
}
}).then(function (result) {
t.equal(result, '3+5=8');
done();
});
});
});
describe('Custom view', function () {
function View() {
this.buffer = [];
this.text = function (text) {
this.buffer.push(text);
return this;
};
this.write = function (i) {
this.buffer.push(i);
return this;
};
}
it('should render with custom view', function (done) {
var view = new View();
var renderer = new Renderer();
renderer.render('The number is:{{#write}}1{{/write}}', view).then(function (result) {
t.notOk(result);
t.deepEqual(view.buffer, ['The number is:', 1]);
done();
})
});
});
})
;
|
/**
* Pre Tests
* Check to make sure jQuery and Zest are loaded
*/
module("Setup");
test("jQuery is loaded", function() {
expect(3);
ok( jQuery,
"jQuery is defined." );
ok( $,
"$ is defined.");
equal( typeof jQuery, "function",
"jQuery is a function." );
});
test("Zest is loaded", function() {
expect(3);
ok( Zest,
"Zest is defined." );
ok( Z$,
"Z$ is defined." );
equal( typeof Zest, "function",
"Zest is a function." );
});
|
'use strict';
/**
* Module dependencies.
*/
var mongoose = require('mongoose'),
errorHandler = require('./errors.server.controller'),
Task = mongoose.model('Task'),
Project = mongoose.model('Project'),
Person = mongoose.model('Person'),
_ = require('lodash');
/**
* Create a Task
*/
var person, project;
exports.createTask = function(req, res) {
var task = new Task(req.body);
task.user = req.user;
Person.findById(req.body.personId).exec(function(err, person_object) {
person = person_object;
Project.findById(req.body.projectId).exec(function(err, project_object) {
project = project_object;
task.projectName = project.name;
task.personName = person.name;
task.save(function(err) {
if (err) {
return res.status(400).send({
message: errorHandler.getErrorMessage(err)
});
} else {
person.tasks.push(task);
person.save();
project.tasks.push(task);
project.save();
res.jsonp(task);
}
});
});
});
};
/**
* Show the current Task
*/
exports.readTask = function(req, res) {
res.jsonp(req.task);
};
/**
* Update a Task
*/
exports.updateTask = function(req, res) {
var task = req.task;
task = _.extend(task, req.body);
task.save(function(err) {
if (err) {
return res.status(400).send({
message: errorHandler.getErrorMessage(err)
});
} else {
res.jsonp(task);
}
});
};
/**
* Delete an Task
*/
exports.deleteTask = function(req, res) {
var task = req.task;
Project.findById(req.task.project).exec(function(err, project) {
if (project && project.tasks) {
var i = project.tasks.indexOf(task._id);
project.tasks.splice(i, 1);
project.save();
}
});
Person.findById(req.task.person).exec(function(err, person) {
if (person && person.tasks) {
var i = person.tasks.indexOf(task._id);
person.tasks.splice(i, 1);
person.save();
}
});
task.remove(function(err) {
if (err) {
return res.status(400).send({
message: errorHandler.getErrorMessage(err)
});
} else {
res.jsonp(task);
}
});
};
/**
* List of Tasks
*/
exports.listTasks = function(req, res) {
Task.find({'user':req.user._id}).sort('-created').populate('person', 'name').populate('project', 'name').exec(function(err, tasks) {
if (err) {
return res.status(400).send({
message: errorHandler.getErrorMessage(err)
});
} else {
res.jsonp(tasks);
}
});
};
/**
* Task middleware
*/
exports.taskByID = function(req, res, next, id) {
Task.findById(id).populate('user', 'username').exec(function(err, task) {
if (err) return next(err);
if (!task) return next(new Error('Failed to load Task ' + id));
req.task = task;
next();
});
};
/**
* Task authorization middleware
*/
exports.hasAuthorization = function(req, res, next) {
if (req.task.user.id !== req.user.id) {
return res.status(403).send('User is not authorized');
}
next();
};
|
// angular.module is a global place for creating, registering and retrieving Angular modules
// 'directory' is the name of this angular module example (also set in a <body> attribute in index.html)
// the 2nd parameter is an array of 'requires'
// 'directory.services' is found in services.js
// 'directory.controllers' is found in controllers.js
angular.module('directory', ['ionic', 'directory.controllers', 'ionic.contrib.ui.cards'])
.config(function ($stateProvider, $urlRouterProvider) {
// Ionic uses AngularUI Router which uses the concept of states
// Learn more here: https://github.com/angular-ui/ui-router
// Set up the various states which the app can be in.
// Each state's controller can be found in controllers.js
$stateProvider
.state('landing', {
url: '/landing',
templateUrl: 'templates/index.html',
controller: 'FbCtrl'
})
.state('profilec', {
url: '/createProfile',
templateUrl: 'templates/profilec.html',
controller: 'ProfileCtrl'
})
.state('matches', {
url: '/matches',
templateUrl: 'templates/matches.html',
controller: 'TestCtrl'
})
.state('food', {
url: '/restaurants',
templateUrl: 'templates/restaurants.html',
controller: 'RecCtrl'
})
.state('chat', {
url: '/chat',
templateUrl: 'templates/chat.html',
controller: 'ChatCtrl'
})
.state('home', {
url: '/home',
templateUrl: 'templates/home.html',
controller: 'DocCtrl'
})
.state('stats', {
url: '/stats',
templateUrl: 'templates/stats.html',
controller: 'DocCtrl'
})
.state('graphs', {
url: '/graphs',
templateUrl: 'templates/graphs.html',
controller: 'GraphCtrl'
})
.state('doc-index', {
url: '/docs',
templateUrl: 'templates/doc-index.html',
controller: 'DocCtrl'
})
.state('doc-detail', {
url: '/doclist/:doclistId',
templateUrl: 'templates/doc-detail.html',
controller: 'DocCtrl'
});
/*.state('employee-index', {
url: '/employees',
templateUrl: 'templates/employee-index.html',
controller: 'EmployeeIndexCtrl'
})
.state('employee-detail', {
url: '/employee/:employeeId',
templateUrl: 'templates/employee-detail.html',
controller: 'EmployeeDetailCtrl'
})
.state('employee-reports', {
url: '/employee/:employeeId/reports',
templateUrl: 'templates/employee-reports.html',
controller: 'EmployeeReportsCtrl'
}); */
// if none of the above states are matched, use this as the fallback
$urlRouterProvider.otherwise('landing');
});
|
import Route from '@ember/routing/route';
import { inject as service } from '@ember/service';
import { get } from '@ember/object';
export default Route.extend({
ajax: service(),
model() {
return get(this, 'ajax').request(
'https://api.github.com/repos/ember-cli/ember-ajax/commits',
{
headers: {
'User-Agent': 'Ember AJAX Testing'
}
}
);
}
});
|
const fs = require('fs');
class Loader {
static extend (name, loader) {
return { name, loader };
}
static get (name, options) {
const item = options.loaders.find((loader) => name === loader.name);
if (!item) {
throw new Error(`Missing loader for ${name}`);
}
return item.loader;
}
static getFileContent (filename, options) {
return fs.readFileSync(filename, options).toString();
}
constructor (options) {
this.options = options;
}
/* istanbul ignore next */
/* eslint-disable-next-line class-methods-use-this */
load () {
throw new Error('Cannot call abstract Loader.load() method');
}
emitTemplate (source) {
this.options.source.template = source || '';
return Promise.resolve();
}
emitScript (source) {
this.options.source.script = source || '';
return Promise.resolve();
}
emitErrors (errors) {
this.options.source.errors.push(...errors);
return Promise.resolve();
}
pipe (name, source) {
const LoaderClass = Loader.get(name, this.options);
return new LoaderClass(this.options).load(source);
}
}
module.exports = Loader;
|
/**
* @license angular-sortable-column
* (c) 2013 Knight Rider Consulting, Inc. http://www.knightrider.com
* License: MIT
*/
/**
*
* @author Dale "Ducky" Lotts
* @since 7/21/13
*/
basePath = '..';
files = [
JASMINE,
JASMINE_ADAPTER,
'bower_components/jquery/dist/jquery.js',
'bower_components/angular/angular.js',
'bower_components/angular-route/angular-route.js',
'bower_components/angular-mocks/angular-mocks.js',
'src/js/sortableColumn.js',
'test/*.spec.js'
];
// list of files to exclude
exclude = [
];
preprocessors = {
'**/src/js/*.js': 'coverage'
};
// test results reporter to use
// possible values: 'dots', 'progress', 'junit'
reporters = ['progress', 'coverage'];
// web server port
port = 9876;
// cli runner port
runnerPort = 9100;
// enable / disable colors in the output (reporters and logs)
colors = true;
// level of logging
// possible values: LOG_DISABLE || LOG_ERROR || LOG_WARN || LOG_INFO || LOG_DEBUG
logLevel = LOG_INFO;
// enable / disable watching file and executing tests whenever any file changes
autoWatch = false;
// Start these browsers, currently available:
// - Chrome
// - ChromeCanary
// - Firefox
// - Opera
// - Safari (only Mac)
// - PhantomJS
// - IE (only Windows)
browsers = ['Chrome'];
// If browser does not capture in given timeout [ms], kill it
captureTimeout = 60000;
// Continuous Integration mode
// if true, it capture browsers, run tests and exit
singleRun = true;
|
const storage = require("./storage");
const recognition = require("./recognition");
async function labelPictures(bucketName) {
const bucket = await storage.getOrCreateBucket(bucketName);
const fileNames = await storage.ls(bucket);
for (const file of fileNames) {
console.log(`Retrieve labels for file ${file.name}`);
try {
const labels = await recognition.getLabels(file.metadata.mediaLink);
const metadata = {
metadata: {
labels: JSON.stringify(labels)
}
};
console.log(`Set metadata for file ${file.name}`);
await storage.setMetadata(file, metadata);
} catch (ex) {
console.warn("Failed to set metadata for file ${file.name}", ex);
}
}
}
async function main(bucketName) {
try {
await labelPictures(bucketName);
} catch (error) {
console.error(error);
}
}
if (process.argv.length < 3) {
throw new Error("Please specify a bucket name");
}
main(process.argv[2]);
|
'use strict';
describe('TestComponent', function () {
var componentController;
beforeEach(module('APPLICATION'));
beforeEach(inject(function ($componentController) {
componentController = $componentController('testComponent', null, {
test: {
data: 'data'
}
});
}));
it('is defined', function () {
expect(componentController).toBeDefined();
});
describe('when called', function () {
it('modifyTestData modifies test data', function () {
componentController.data = 'data';
componentController.modifyTestData();
expect(componentController.data).toBe(' edited in the component controller');
});
});
});
|
import Ember from 'ember';
export default Ember.Controller.extend({
resume: Ember.inject.controller(),
actions: {
scrollToElem: function(selector) {
this.get('resume').send('scrollToElem', selector);
},
selectTemplate: function(template) {
this.get('resume').send('selectTemplate', template);
},
selectPalette: function(palette) {
this.get('resume').send('selectPalette', palette);
}
}
});
|
process.env.NODE_ENV = 'test';
const chai = require('chai');
const chaiHttp = require('chai-http');
const should = chai.should();
const CostCalculator = require("../libs/costcalculator");
describe('Calculate Cost', () => {
describe("Book Meeting Room", () => {
it("it should calcuate cost for meeting room for 30m", async (done) => {
try {
let result = await CostCalculator("5bd7283ebfc02163c7b4d5d7", new Date("2020-01-01T09:00:00"), new Date("2020-01-01T09:30:00"));
result.should.equal(2.8);
done();
} catch(err) {
done(err);
}
});
});
});
|
module.exports = {
// Token you get from discord
"token": "",
// Prefix before your commands
"prefix": "",
// Port for webserver (Not working)
"port": 8080,
// Mongodb stuff
"mongodb": {
// Mongodb uri
"uri": ""
},
// Channel IDs
"channelIDs": {
// Where to announce the events in ACCF
"events": "",
// Where to announce online towns
"onlineTowns": "",
// Where to log the logs
"logs": ""
}
}
|
Object.prototype.getKeyByValue = function( value ) {
for( var prop in this ) {
if( this.hasOwnProperty( prop ) ) {
if( this[ prop ] === value )
return prop;
}
}
}
|
require('./ramda-mori')
|
var Branch = function (origin, baseRadius, baseSegment, maxSegments, depth, tree) {
this.gid = Math.round(Math.random() * maxSegments);
this.topPoint = origin;
this.radius = baseRadius;
this.maxSegments = maxSegments;
this.lenghtSubbranch = tree.genes.pSubBranch !== 0 ? Math.floor(maxSegments * tree.genes.pSubBranch) : 0;
this.segmentLenght = baseSegment;
this.depth = depth; //current position of the branch in chain
this.tree = tree;
this.segments = 0; //always start in 0
//Directions are represented as a Vector3 where dirx*i+diry*j+dirz*k and
//each dir is the magnitude that can go from 0 to 1 and multiplies the max segment lenght
//Starting direction is UP
this.direction = {
x: 0,
y: 1,
z: 0
};
this.material = new THREE.MeshLambertMaterial({
color: Math.floor(Math.random()*16777215),//tree.genes.color,
side: 2,
shading: THREE.FlatShading
});
};
/**
* Conceptually grows and renders the branch
* @param {THREE.Scene} scene The scene to which the branch belongs
*/
Branch.prototype.grow = function (scene) {
var thisBranch = this;
//calculate new direction, our drawing space is a 200x200x200 cube
var newX = newPos('x');
var newY = newPos('y');
var newZ = newPos('z');
if (newY < 0 || newY > 300 ){
// newZ < -100 || newZ > 100 ||
// newX < -100 || newX > 100) {
randomizeDir();
return true;
} else {
//direction is ok and branch is going to grow
thisBranch.segments += 1;
}
var destination = new THREE.Vector3(newX, newY, newZ);
var lcurve = new THREE.LineCurve3(this.topPoint, destination);
var geometry = new THREE.TubeGeometry(
lcurve, //path
thisBranch.tree.genes.segmentLenght, //segments
thisBranch.radius, //radius
8, //radiusSegments
true //opened, muuuch more efficient but not so nice
);
// modify next segment's radius
thisBranch.radius = thisBranch.radius * thisBranch.tree.genes.radiusDimP;
var tube = new THREE.Mesh(geometry, this.material);
scene.add(tube);
this.topPoint = destination;
randomizeDir();
//Helper functions.
function randomizeDir() {
//we want our dir to be from -1 to
thisBranch.direction.x = (thisBranch.tree.mtwister.random() * 2) - 1;
thisBranch.direction.y = (thisBranch.tree.mtwister.random() * 2) - 1;
thisBranch.direction.z = (thisBranch.tree.mtwister.random() * 2) - 1;
}
function newPos(dimension) {
return thisBranch.topPoint[dimension] + (thisBranch.direction[dimension] * thisBranch.segmentLenght);
}
//calculate segment lenght for new segment
thisBranch.segmentLenght = thisBranch.segmentLenght * thisBranch.tree.genes.segmentLenghtDim;
if (thisBranch.lenghtSubbranch !== 0 && thisBranch.segments % thisBranch.lenghtSubbranch === 0) {
thisBranch.tree.spawnBranch(thisBranch.topPoint, thisBranch.radius, thisBranch.segmentLenght, this.maxSegments, this.depth);
}
//check if we can kill branch
if (thisBranch.radius <= thisBranch.tree.genes.minRadius) {
return false; //kill branch
}
//Kill if we have reached the max number of segments
if (thisBranch.segments > thisBranch.maxSegments) {
return false;
} else {
return true;
}
};
|
'use strict';
var assert = require('assert')
, TestEvents = require('../lib/TestEvents');
var wasCalled = false;
var FN = function (ev) {
wasCalled = true;
};
describe('TestEvents', function () {
beforeEach(function () {
wasCalled = false;
});
describe('#on', function () {
it('Should bind a function for an event', function () {
TestEvents.on(TestEvents.EMITTED_EVENTS, FN);
});
});
describe('#emit', function () {
it('Should call bound function for an event', function () {
TestEvents.emit(TestEvents.EMITTED_EVENTS);
assert.equal(wasCalled, true);
});
});
})
|
//process.argv.forEach(function (val, index, array) { console.log(index + ': ' + val); });
var fs = require('fs');
(function () {
function slugify(text) {
text = text.replace(/[^-a-zA-Z0-9,&\s]+/ig, '');
text = text.replace(/-/gi, "_");
text = text.replace(/\s/gi, "-");
return text;
}
var DocGen = {
filesArr: null,
files: {},
functions: [],
nbLoaded: 0,
init: function (files) {
this.filesArr = files;
},
start: function () {
for (var i=0, len=this.filesArr.length; i<len; i++) {
var file = this.filesArr[i];
this.processFile(file);
}
},
fileLoaded: function() {
this.nbLoaded++;
if (this.nbLoaded == this.filesArr.length) {
this.exportHtml();
}
},
getSignatures: function (m) {
var sig = null;
var signatures = [];
var rSig = /\\*\s?(@sig\s.*)\n/gi;
while (sig = rSig.exec(m)) {
var params = [];
var rParam = /(\w+):(\w+)/gi;
while (param = rParam.exec(sig[1])) {
var name = param[1];
var type = param[2];
params.push({ name: name, type: type });
}
if (params.length >= 1) {
ret = params.pop();
}
signatures.push({ params: params, ret: ret});
}
return signatures;
},
extractInfos: function (m) {
var self = this;
var fun = m[2];
var rFun = /['|"]?([a-zA-Z0-9._-]+)['|"]?\s?:\s?function\s?\(.*\)\s?{/gi;
var isFun = rFun.exec(fun);
if (!isFun) {
rFun = /socket\.on\(['|"]([a-zA-Z0-9._-]+)['|"]\s?,\s?function\s?\(.*\)\s?{/gi;
isFun = rFun.exec(fun);
}
if (isFun) {
var comment = m[1];
var name = isFun[1];
var sigs = self.getSignatures(comment);
var desc = (/\*\s(.*?)\n/gi).exec(m[1])[1];
var f = { name: name, description: desc, sigs: sigs };
return f;
}
return null;
},
processFile: function (file) {
var self = this;
// Get the file in a buffer
fs.readFile(file, function(err, data) {
var buf = data.toString('binary');
var functions = [];
// Get all long comment ( /** )
var rgx = new RegExp("/\\*\\*\n([a-zA-Z0-9 -_\n\t]*)\\*/\n(.*)\n", "gi");
while (m = rgx.exec(buf)) {
info = self.extractInfos(m);
if (info) {
functions.push(info);
}
}
self.files[file] = { functions: functions };
self.fileLoaded();
});
},
sortFunctions: function (fun1, fun2) {
var name1 = fun1.name.toLowerCase();
var name2 = fun2.name.toLowerCase();
if (name1 < name2) { return -1; }
else if (name1 > name2) { return 1; }
else { return 0; }
},
exportHtml: function() {
for (var fileName in this.files) {
var file = this.files[fileName];
file.functions.sort(this.sortFunctions);
console.log(fileName, file.functions.length);
var html = '<!DOCTYPE html>\n' +
'<html>\n' +
'<head>\n' +
' <title></title>\n' +
' <link rel="stylesheet" href="css/reset.css" type="text/css" media="screen" charset="utf-8" />\n' +
' <link rel="stylesheet" href="css/style.css" type="text/css" media="screen" charset="utf-8" />\n' +
//' <script src="js/scripts.js" type="text/javascript"></script>' +
'</head>\n' +
'<body>\n' +
'\n' +
'<div class="menu" id="menu">\n' +
' <h1>Files</h1>\n' +
' <ul>\n';
for (var f in this.files) {
html += ' <li><a href="'+f+'.html">'+f+'</a></li>\n';
}
html += ' </ul>\n' +
' <h1>Functions</h1>\n' +
' <ul>\n';
for (var i=0, len=file.functions.length; i<len; i++) {
html += ' <li><a href="#'+slugify(file.functions[i].name)+'">'+file.functions[i].name+'</a></li>\n';
}
html += ' </ul>\n'
html += '</div>\n' +
'<div id="page">\n' +
' <div class="content">\n';
for (var i=0, len=file.functions.length; i<len; i++) {
var fn = file.functions[i];
if (fn.sigs.length > 0) {
html += '<h3><a name="'+slugify(fn.name)+'">'+fn.name+'</a></h3>\n';
html += '<span class="signature">\n';
for (var s=0, len2=fn.sigs.length; s<len2; s++) {
var sig = fn.sigs[s];
html += '<span class="name">'+fn.name+'</span> ( ';
for (var p=0, len3=sig.params.length; p<len3; p++) {
var param = sig.params[p];
html += '<span class="param">'+param.name+'</span>:<span class="type">'+param.type+'</span>, ';
}
html = html.substr(0, html.length-2);
html += ' ) : <span class="param">'+sig.ret.name+'</span>:<span class="type">'+sig.ret.type+'</span><br />';
}
html = html.substr(0, html.length-6);
html += '</span>\n';
html += '<p>'+fn.description+'</p>';
}
}
html += ' </div>\n' +
'</div>\n' +
'\n' +
'</body>\n'
'</html>';
fs.writeFile('doc/'+fileName+'.html', html);
}
}
};
var files =ย ['sockets.js', 'database_operations.js'];
DocGen.init(files);
DocGen.start();
})();
|
'use strict';
exports.name = '/activation';
|
const _ = require('lodash')
const Joi = require('joi')
module.exports = {
name: 'href',
params: {
href: Joi.array().items(
Joi.string(),
Joi.func().ref()
).min(1)
},
setup (params) {
params.href = [''].concat(params.href)
this._flags.href = params.href
},
validate (params, value, state, options) {
let parts = value.split('/').slice(1)
if (!parts.every((p) => _.size(p) > 0)) {
return this.createError('link.href', { v: value }, state, options)
} else {
return value
}
}
}
|
// Mucking with different levels
let currentLevel = { cells: undefined, dims: undefined };
if (0) {
currentLevel.cells = level;
currentLevel.dims = level_dims;
} else {
currentLevel.cells = LEVEL_ONE;
currentLevel.dims = LEVEL_ONE_DIMS;
}
// Return a reference to the (logical) cell's unique object
const _getCellReference = (i, j, k = 1) => {
if (i < 0 || j < 0) {
return undefined;
}
if (i >= currentLevel.dims.i || j >= currentLevel.dims.j) {
return undefined;
}
return currentLevel.cells[i + j * (currentLevel.dims.j)];
};
/**
* The drawing grid used to represent the editable regions of the level.
* [i, j] refer to logical coordinates. [w, h] represent the number of pixels
* per grid division on the target 2D rendering surface.
*/
const grid = {
i: 20,
j: 20,
w: undefined,
h: undefined,
};
// Translate party front/back/left/right to N/S/E/W
const XLATE_UCS2PARTY = {
n: { f: 'n', b: 's', r: 'e', l: 'w' },
s: { f: 's', b: 'n', r: 'w', l: 'e' },
e: { f: 'e', b: 'w', r: 's', l: 'n' },
w: { f: 'w', b: 'e', r: 'n', l: 's' }
};
// JavaScript divmod is boned
const divMod = (n, d) => {
return n - d * Math.floor(n / d);
};
// Give an [i, j] coordinate and wrap it if exceeds grid dimensions
const gridWrap = (i, j) => {
return [divMod(i, grid.i), divMod(j, grid.j)];
};
|
var fastn = require('fastn')({
_generic: require('fastn/genericComponent'),
list: require('fastn/listComponent'),
templater: require('fastn/templaterComponent'),
text: require('fastn/textComponent'),
ratingControl: require('./ratingControlComponent')
});
module.exports = function(settings){
return fastn('ratingControl', settings).attach().render();
};
|
#!/usr/bin/env node
'use strict';
var assert = require('assert');
var depRep = require('../../lib/depRep');
var oldJson = require('../fixtures/old.json');
var newJson = require('../fixtures/new.json');
var unsupported = require('../fixtures/unsupported.json');
function key(number, dev) {
var prefix = "/dependencies/";
if (dev) prefix = "/devDependencies/";
return prefix + number;
}
describe('Compare', function () {
// describe('#report()', function () {
// it('should generate a proper report for dependencies', function () {
// depRep
// .report(oldJson, newJson)
// .then(function () {
// assert.equal(analyze[key(1)].status, "major");
// assert.equal(report[key(2)].status, null);
// assert.equal(report[key(3)], null);
// assert.equal(report[key(4)].status, null);
// assert.equal(report[key(5)].status, null);
// assert.equal(report[key(6)], null);
// assert.equal(report[key(7)].status, null);
// assert.equal(report[key(8)].status, "minor");
// assert.equal(report[key(9)].status, "major");
// done();
// });
// });
// });
//
// describe('#report()', function () {
// it('should generate a proper report for devDependencies', function () {
// depRep
// .report(oldJson, newJson)
// .then(function () {
// assert.equal(report[key(1, true)].status, "major");
// assert.equal(report[key(2, true)].status, null);
// assert.equal(report[key(3, true)], null);
// assert.equal(report[key(4, true)].status, null);
// assert.equal(report[key(5, true)].status, null);
// assert.equal(report[key(6, true)], null);
// assert.equal(report[key(7, true)].status, null);
// assert.equal(report[key(8, true)].status, "minor");
// assert.equal(report[key(9, true)].status, "major");
// done();
// });
// });
// });
});
|
var express = require('express')
var braintree = require('braintree')
var router = express.Router() // eslint-disable-line new-cap
var gateway = require('../lib/gateway')
var TRANSACTION_SUCCESS_STATUSES = [
braintree.Transaction.Status.Authorizing,
braintree.Transaction.Status.Authorized,
braintree.Transaction.Status.Settled,
braintree.Transaction.Status.Settling,
braintree.Transaction.Status.SettlementConfirmed,
braintree.Transaction.Status.SettlementPending,
braintree.Transaction.Status.SubmittedForSettlement
]
function formatErrors(errors) {
var formattedErrors = ''
for (var i in errors) { // eslint-disable-line no-inner-declarations, vars-on-top
if (errors.hasOwnProperty(i)) {
formattedErrors += 'Error: ' + errors[i].code + ': ' + errors[i].message + '\n'
}
}
return formattedErrors
}
function createResultObject(transaction) {
var result
var status = transaction.status
if (TRANSACTION_SUCCESS_STATUSES.indexOf(status) !== -1) {
result = {
header: 'Sweet Success!',
icon: 'success',
message: 'Your test transaction has been successfully processed. See the Braintree API response and try again.'
}
} else {
result = {
header: 'Transaction Failed',
icon: 'fail',
message: 'Your test transaction has a status of ' + status + '. See the Braintree API response and try again.'
}
}
return result
}
router.get('/', function (req, res) {
res.redirect('/checkouts/new')
})
router.get('/checkouts/new', function (req, res) {
gateway.clientToken.generate({}, function (err, response) {
res.render('checkouts/new', {clientToken: response.clientToken, messages: req.flash('error')})
})
})
router.get('/checkouts/:id', function (req, res) {
var result
var transactionId = req.params.id
gateway.transaction.find(transactionId, function (err, transaction) {
result = createResultObject(transaction)
res.render('checkouts/show', {transaction: transaction, result: result})
})
})
router.post('/checkouts', function (req, res) {
var transactionErrors
var amount = req.body.amount // In production you should not take amounts directly from clients
var nonce = req.body.payment_method_nonce
gateway.transaction.sale({
amount: amount,
paymentMethodNonce: nonce,
customer: {
firstName: req.body.firstName,
lastName: req.body.lastName,
email: req.body.email
},
options: {
submitForSettlement: true,
storeInVaultOnSuccess: true
}
}, function (err, result) {
if (result.success || result.transaction) {
res.redirect('checkouts/' + result.transaction.id)
} else {
transactionErrors = result.errors.deepErrors()
req.flash('error', {msg: formatErrors(transactionErrors)})
res.redirect('checkouts/new')
}
})
})
module.exports = router
|
import { Component } from 'react';
import Router from 'next/router';
import io from 'socket.io-client';
import fetch from 'isomorphic-fetch';
import Page from '../../layouts/page.js';
import Slide from '../../components/slide.js';
import Code from '../../components/code.js'
import Emojis from '../../components/emojis.js';
import SlideNavigation from '../../components/slidenavigation.js';
import { Title, Headline, Enum, Column } from '../../components/text.js';
import withRedux from 'next-redux-wrapper';
import { makeStore, _changeRole } from '../../components/store.js';
class SlideFour extends Component {
constructor(props) {
super(props);
this.props = props;
this.state = {
socket: undefined
};
this.emojiModule = this.emojiModule.bind(this);
this.navModule = this.navModule.bind(this);
}
static async getInitialProps({ isServer }) {
let host = 'http://localhost:3000';
if (!isServer)
host = `${location.protocol}//${location.host}`;
const response = await fetch(`${host}/static/html_template.txt`);
const htmlCode = await response.text();
return { htmlCode };
}
componentDidMount() {
// socket
if (!this.state.socket) {
const socket = io(`${location.protocol}//${location.host}/`);
socket.on('viewer-update', data => {
if (this.props.role === 'VIEWER') {
Router.replace(data.url);
}
});
this.setState(state => ( {socket: socket} ));
}
}
componentWillUnmount() {
if (this.state.socket)
this.state.socket.close();
}
emojiModule() {
if (this.state.socket) {
return (
<Emojis
socket={this.state.socket}
/>
);
}
}
navModule() {
if (this.state.socket && this.props.role) {
return (
<SlideNavigation
role={this.props.role}
socket={this.state.socket}
prev="/slides/0x04_y_tho"
next="/slides/0x06_include"
/>
);
}
}
render() {
return (
<Page>
<Slide>
<Title>0x05_call_by_reference</Title>
<Headline>Anwendung im Browser</Headline>
<Column>
<Enum>JavaScript kann direkt im { '<script>-Tag' } geschrieben werden</Enum>
<Enum>oder als externe Datei durch das src-Attribut eingebunden werden</Enum>
</Column>
<Column>
<Code language='html'>{ this.props.htmlCode }</Code>
</Column>
{ this.navModule() }
</Slide>
{ this.emojiModule() }
</Page>
);
}
};
const mapStateToProps = state => ({
role: state.role
});
const mapDispatchToProps = dipatch => ({
changeRole: role => (dispatch(_changeRole(role)))
});
export default withRedux(makeStore, mapStateToProps, mapDispatchToProps)(SlideFour);
|
'use strict';
/**
* Module dependencies.
*/
var mongoose = require('mongoose'),
Example = mongoose.model('Example'),
_ = require('lodash'),
upload = require('./upload');
/**
* Find example by id
*/
exports.example = function(req, res, next, id) {
Example.load(id, function(err, example) {
if (err) return next(err);
if (!example) return next(new Error('Failed to load example ' + id));
req.example = example;
next();
});
};
/**
* Create a example
*/
exports.create = function(req, res) {
var example = new Example(req.body);
example.user = req.user;
example.save(function(err) {
if (err) {
return res.send('/login', {
errors: err.errors,
example: example
});
} else {
res.jsonp(example);
}
});
};
/**
* Update a example
*/
exports.update = function(req, res) {
var example = req.example;
example = _.extend(example, req.body);
example.save(function(err) {
if (err) {
console.log("Error -" + err);
return res.send('/login', {
errors: err,
example: example
});
} else {
console.log("Example Saved - " + example);
res.jsonp(example);
}
});
};
/**
* Delete an example
*/
exports.destroy = function(req, res) {
var example = req.example;
example.remove(function(err) {
if (err) {
return res.send('/login', {
errors: err.errors,
example: example
});
} else {
res.jsonp(example);
}
});
};
/**
* Show an example
*/
exports.show = function(req, res) {
res.jsonp(req.example);
};
/**
* List of Examples
*/
exports.all = function(req, res) {
Example.find().sort('-created').populate('user', 'name username').exec(function(err, examples) {
if (err) {
res.render('error', {
status: 500
});
} else {
res.jsonp(examples);
}
});
};
|
import { fireShuffleTasks } from 'src/model/ModelBase';
import { REFERENCE } from 'config/types';
import { rebindMatch } from 'shared/rebind';
import { isArray, isString } from 'utils/is';
import { escapeKey } from 'shared/keypaths';
import ExpressionProxy from './ExpressionProxy';
import resolveReference from './resolveReference';
import resolve from './resolve';
import LinkModel, { Missing } from 'src/model/LinkModel';
export default class ReferenceExpressionProxy extends LinkModel {
constructor(fragment, template) {
super(null, null, null, '@undefined');
this.root = fragment.ractive.viewmodel;
this.template = template;
this.rootLink = true;
this.template = template;
this.fragment = fragment;
this.rebound();
}
getKeypath() {
return this.model ? this.model.getKeypath() : '@undefined';
}
rebound() {
const fragment = this.fragment;
const template = this.template;
let base = (this.base = resolve(fragment, template));
let idx;
if (this.proxy) {
teardown(this);
}
const proxy = (this.proxy = {
rebind: (next, previous) => {
if (previous === base) {
next = rebindMatch(template, next, previous);
if (next !== base) {
this.base = base = next;
}
} else if (~(idx = members.indexOf(previous))) {
next = rebindMatch(template.m[idx].n, next, previous);
if (next !== members[idx]) {
members.splice(idx, 1, next || Missing);
}
}
if (next !== previous) {
previous.unregister(proxy);
if (next) next.addShuffleTask(() => next.register(proxy));
}
},
handleChange: () => {
pathChanged();
}
});
base.register(proxy);
const members = (this.members = template.m.map(tpl => {
if (isString(tpl)) {
return { get: () => tpl };
}
let model;
if (tpl.t === REFERENCE) {
model = resolveReference(fragment, tpl.n);
model.register(proxy);
return model;
}
model = new ExpressionProxy(fragment, tpl);
model.register(proxy);
return model;
}));
const pathChanged = () => {
const model =
base &&
base.joinAll(
members.reduce((list, m) => {
const k = m.get();
if (isArray(k)) return list.concat(k);
else list.push(escapeKey(String(k)));
return list;
}, [])
);
if (model !== this.model) {
this.model = model;
this.relinking(model);
fireShuffleTasks();
refreshPathDeps(this);
this.fragment.shuffled();
}
};
pathChanged();
}
teardown() {
teardown(this);
super.teardown();
}
unreference() {
super.unreference();
if (!this.deps.length && !this.refs) this.teardown();
}
unregister(dep) {
super.unregister(dep);
if (!this.deps.length && !this.refs) this.teardown();
}
}
function teardown(proxy) {
if (proxy.base) proxy.base.unregister(proxy.proxy);
if (proxy.models) {
proxy.models.forEach(m => {
if (m.unregister) m.unregister(proxy);
});
}
}
function refreshPathDeps(proxy) {
let len = proxy.deps.length;
let i, v;
for (i = 0; i < len; i++) {
v = proxy.deps[i];
if (v.pathChanged) v.pathChanged();
if (v.fragment && v.fragment.pathModel) v.fragment.pathModel.applyValue(proxy.getKeypath());
}
len = proxy.children.length;
for (i = 0; i < len; i++) {
refreshPathDeps(proxy.children[i]);
}
}
const eproto = ExpressionProxy.prototype;
const proto = ReferenceExpressionProxy.prototype;
proto.unreference = eproto.unreference;
proto.unregister = eproto.unregister;
proto.unregisterLink = eproto.unregisterLink;
|
'use strict';
const config = require('config');
const esdoc = require('gulp-esdoc');
const gulp = require('gulp');
module.exports = function documentationBuilder() {
return gulp.src('./src')
.pipe(esdoc({
destination: config.get('build.documentation.outputPath'),
unexportIdentifier: config.get('build.documentation.unexportedIdentifiers'),
undocumentIdentifier: config.get('build.documentation.undocumentedIdentifiers'),
test: {
type: config.get('build.documentation.testType'),
source: config.get('build.documentation.testRoot'),
},
}));
};
|
'use strict'
var test = require('tape')
var createDate = require('./')
test(function (t) {
t.ok(createDate('1-1-2000') instanceof Date)
t.end()
})
|
'use strict';
// Configuring the Articles module
angular.module('categories').run(['Menus',
function(Menus) {
// Set top bar menu items
// Menus.addMenuItem('topbar', 'Categories', 'categories', 'item', '/categories(?:/[^/]+)?', null, null, 9);
// Set admin menu items
Menus.addMenuItem('admin', 'Categories', 'categories', 'dropdown', '/categories(/create)?');
Menus.addSubMenuItem('admin', 'categories', 'List Categories', 'categories');
Menus.addSubMenuItem('admin', 'categories', 'New Category', 'categories/create');
}
]);
|
/**
* Created by zhang on 16/5/19.
*/
$.myjq = function () {
alert("hello my jQuery")
};
//js็ๆฉๅฑ
$.fn.myjq=function(){
$(this).text("hello")
};
|
// Generated by CoffeeScript 1.10.0
var Graphics;
Graphics = (function() {
function Graphics(ctx, viewport1) {
this.ctx = ctx;
this.viewport = viewport1;
this.transform = {
x: 0,
y: 0,
rotation: 0,
scale: 1
};
}
Graphics.prototype.translate = function(dx, dy) {
this.transform.x += dx;
this.transform.y += dy;
return this.ctx.translate(dx, dy);
};
Graphics.prototype.setColor = function(color) {
this.ctx.fillStyle = color;
return this.ctx.strokeStyle = color;
};
Graphics.prototype.setLineWidth = function(linewidth) {
return this.ctx.lineWidth = linewidth;
};
Graphics.prototype.setFont = function(fontdef) {
return this.ctx.font = fontdef;
};
Graphics.prototype.drawArc = function(x, y, r, sAngle, eAngle) {
this.ctx.beginPath();
this.ctx.arc(x, y, r, sAngle, eAngle, true);
return this.ctx.stroke();
};
Graphics.prototype.fillArc = function(x, y, r, sAngle, eAngle) {
this.ctx.beginPath();
this.ctx.arc(x, y, r, sAngle, eAngle, true);
return this.ctx.fill();
};
Graphics.prototype.drawCircle = function(x, y, r) {
return this.drawArc(x, y, r, 0, 2 * Math.PI);
};
Graphics.prototype.fillCircle = function(x, y, r) {
return this.fillArc(x, y, r, 0, 2 * Math.PI);
};
Graphics.prototype.drawRect = function(x, y, width, height) {
return this.ctx.strokeRect(x, y, width, height);
};
Graphics.prototype.fillRect = function(x, y, width, height) {
return this.ctx.fillRect(x, y, width, height);
};
Graphics.prototype.drawText = function(x, y, text) {
return this.ctx.fillText(text, x, y);
};
Graphics.prototype.drawLine = function(x1, y1, x2, y2) {
this.ctx.beginPath();
this.ctx.moveTo(x1, y1);
this.ctx.lineTo(x2, y2);
return this.ctx.stroke();
};
Graphics.prototype.drawPoly = function(ptlist) {
var i, len, pt;
this.ctx.beginPath();
this.ctx.moveTo(ptlist[0].x, ptlist[0].y);
for (i = 0, len = ptlist.length; i < len; i++) {
pt = ptlist[i];
this.ctx.lineTo(pt.x, pt.y);
}
this.ctx.closePath();
return this.ctx.stroke();
};
Graphics.prototype.fillPoly = function(ptlist) {
var i, len, pt;
this.ctx.beginPath();
this.ctx.moveTo(ptlist[0].x, ptlist[0].y);
for (i = 0, len = ptlist.length; i < len; i++) {
pt = ptlist[i];
this.ctx.lineTo(pt.x, pt.y);
}
this.ctx.closePath();
return this.ctx.fill();
};
return Graphics;
})();
exports.createFromCanvas = function(canvas, viewport) {
return new Graphics(canvas.getContext('2d'), viewport);
};
|
"use strict";
var EventEmitter = require ('events');
module.exports = new EventEmitter ();
|
'use strict'
const tap = require('tap')
const ActiveDirectory = require('../index')
const config = require('./config')
const serverFactory = require('./mockServer')
const settings = require('./settings').getGroupMembershipForUser
tap.beforeEach((done, t) => {
serverFactory(function (err, server) {
if (err) return done(err)
const connectionConfig = config(server.port)
t.context.ad = new ActiveDirectory(connectionConfig)
t.context.server = server
done()
})
})
tap.afterEach((done, t) => {
if (t.context.server) t.context.server.close()
done()
})
tap.test('#getGroupMembershipForUser()', t => {
settings.users.forEach((user) => {
['dn', 'userPrincipalName', 'sAMAccountName'].forEach((attr) => {
const len = user.members.length
t.test(`should return ${len} groups for ${attr}`, t => {
t.context.ad.getGroupMembershipForUser(user[attr], function (err, groups) {
t.error(err)
t.true(groups.length >= user.members.length)
const groupNames = groups.map((g) => {
return g.cn
})
user.members.forEach((g) => {
t.true(groupNames.includes(g))
})
t.end()
})
})
})
})
t.test('should return empty groups if groupName doesn\'t exist', t => {
t.context.ad.getGroupMembershipForUser('!!!NON-EXISTENT GROUP!!!', function (err, groups) {
t.error(err)
t.type(groups, Array)
t.equal(groups.length, 0)
t.end()
})
})
t.test('should return default group attributes when not specified', t => {
const defaultAttributes = ['objectCategory', 'distinguishedName', 'cn', 'description']
const user = settings.users[0]
t.context.ad.getGroupMembershipForUser(user.userPrincipalName, function (err, groups) {
t.error(err)
t.ok(groups)
groups.forEach((g) => {
const keys = Object.keys(g)
defaultAttributes.forEach((attr) => {
t.true(keys.includes(attr))
})
})
t.end()
})
})
t.end()
})
tap.test('#getGroupMembershipForUser(opts)', t => {
t.test('should return only requested attributes', t => {
const opts = {
attributes: ['createTimeStamp']
}
const user = settings.users[0]
t.context.ad.getGroupMembershipForUser(opts, user.userPrincipalName, function (err, groups) {
t.error(err)
t.ok(groups)
t.true(groups.length >= user.members.length)
groups.forEach((g) => {
const keys = Object.keys(g)
keys.forEach((attr) => {
t.true(opts.attributes.includes(attr))
})
})
t.end()
})
})
t.end()
})
|
version https://git-lfs.github.com/spec/v1
oid sha256:b1b66ad7cf63a081650856aed61fbfdf1b6b511e47c622989e9927e504424a5d
size 2493
|
tinyMCE.init({
mode : 'textareas',
theme : "advanced",
theme_advanced_buttons1 : "save,newdocument,|,bold,italic,underline,strikethrough,|,justifyleft,justifycenter,justifyright,justifyfull,|,styleselect,formatselect,fontselect,fontsizeselect",
theme_advanced_buttons2 : "cut,copy,paste,pastetext,pasteword,|,search,replace,|,bullist,numlist,|,outdent,indent,blockquote,|,undo,redo,|,link,unlink,anchor,image,cleanup,help,code,|,insertdate,inserttime,preview,|,forecolor,backcolor",
});
|
/* eslint-env node */
'use strict';
const EmberAddon = require('ember-cli/lib/broccoli/ember-addon');
module.exports = function(defaults) {
let app = new EmberAddon(defaults, {
'ember-cli-babel': {
includePolyfill: true
}
});
app.import('node_modules/highlightjs/styles/monokai-sublime.css');
/*
This build file specifies the options for the dummy test app of this
addon, located in `/tests/dummy`
This build file does *not* influence how the addon or the app using it
behave. You most likely want to be modifying `./index.js` or app's build file
*/
return app.toTree();
};
|
import { SplashEffect } from "./effect.js";
import { Linear } from "../interpolation.js";
export class TranslateFromPosition extends SplashEffect {
constructor(element, options) {
super(element);
options = options || {};
this.x = options.x || 0;
this.y = options.y || 0;
// Can be whatever, but the effect won't do
// anything if it isn't a valid css unit.
this.unit = options.unit || "px";
// Can be either "transform" or "position"
this.translationType = options.translationType || "transform";
this.interpolation = options.interpolation || new Linear();
}
in(value) {
this._set(
this.interpolation.in(value * -1 + 1) * this.x,
this.interpolation.in(value * -1 + 1) * this.y
);
}
out(value) {
this._set(
this.interpolation.out(value) * this.x,
this.interpolation.out(value) * this.y
);
}
_set(x, y) {
if (this.translationType = "transform") {
this.setTransform("translateX", x + this.unit);
this.setTransform("translateY", y + this.unit);
} else if (this.translationType = "position") {
this.setStyle("left", x + this.unit);
this.setStyle("top", y + this.unit);
} else {
console.error("Unknown translation type: " + this.translationType);
}
}
}
|
/**
* Wheel, copyright (c) 2019 - present by Arno van der Vegt
* Distributed under an MIT license: https://arnovandervegt.github.io/wheel/license.txt
**/
const File = require('./File');
exports.FileDetail = class extends File.File {
constructor(opts) {
opts.className = 'file detail';
super(opts);
}
initDOM(parentNode) {
let file = this._file;
this.create(
parentNode,
{
id: this.setElement.bind(this),
className: this._className,
children: [
File.getIcon(this._getImage, file),
{
id: this.setLinkElement.bind(this),
type: 'a',
href: '#',
className: 'no-select name',
innerHTML: file.name
},
!file.directory && file.size ?
{
type: 'span',
href: '#',
className: 'no-select size',
innerHTML: file.size + ' - ' + this.bytesToSize(file.size)
} :
null,
(file.modified || file.hash) ?
{
type: 'span',
href: '#',
className: 'no-select modified',
innerHTML: file.modified || file.hash
} :
null
]
}
);
}
/**
* https://stackoverflow.com/questions/15900485/correct-way-to-convert-size-in-bytes-to-kb-mb-gb-in-javascript
**/
bytesToSize(bytes) {
const sizes = ['Bytes', 'KB', 'MB', 'GB', 'TB'];
if (parseInt(bytes, 10) === 0) {
return '0 Byte';
}
let i = parseInt(Math.floor(Math.log(bytes) / Math.log(1024)));
return Math.round(bytes / Math.pow(1024, i), 2) + ' ' + sizes[i];
}
};
|
const _transform = require('lodash/transform');
function MatchTransformer(match) {
if( !(this instanceof MatchTransformer) ) {
return this.transform(new MatchTransformer(match));
}
if( typeof match === 'string' ) {
// Escape string
match = match.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
match = new RegExp(match);
}
this._match = match;
}
MatchTransformer.prototype.parse = function(source) {
return _transform(source, (result, value, key) => {
if( this._match.test(key) )
result[key] = value;
}, {});
};
MatchTransformer.prototype.reverse = MatchTransformer.prototype.parse;
module.exports = MatchTransformer;
|
import ProgressBar from "progress";
import padEnd from "lodash/padEnd";
class ProgressBarController {
constructor() {
this.bar = null;
}
init(total) {
if (this.bar) {
this.terminate();
}
// Intentionally a noop because node-progress doesn't work well in non-TTY
// environments
if (!process.stdout.isTTY) {
return;
}
// Don't do any of this while testing
if (process.env.NODE_ENV === "lerna-test") {
return;
}
this.bar = new ProgressBar(":packagename โข:barโ", {
total: total,
complete: "โ",
incomplete: "โ",
clear: true,
// terminal columns - package name length - additional characters length
width: (process.stdout.columns || 100) - 50 - 3
});
}
tick(name) {
if (this.bar) {
this.bar.tick({
packagename: padEnd(name.slice(0, 50), 50)
});
}
}
clear() {
if (this.bar) {
this.bar.terminate();
}
}
restore() {
if (this.bar) {
// This is a hack to get the bar to redraw it's last state.
// See: https://github.com/tj/node-progress/blob/d47913502ba5b551fcaad9e94fe7b2f5876a7939/lib/node-progress.js#L154-L159
this.bar.stream.write(this.bar.lastDraw);
}
}
terminate() {
this.clear();
this.bar = null;
}
}
export default new ProgressBarController();
|
var commons = require('../commons')
var frisby = require('frisby');
var FormData = require('form-data');
frisby.create('Get file')
.get(commons.host+'/file/2134354/zgzhrthztrh/sgeh' )
.after(function(err, res, body) {
expect(res.request.href.match(/errcode=404/)).not.toBeNull()
})
.toss()
|
$(document).ready(function () {
startAnimation();
});
if (!window.requestAnimationFrame) {
window.requestAnimationFrame = (window.webkitRequestAnimationFrame || window.mozRequestAnimationFrame || window.msRequestAnimationFrame || window.oRequestAnimationFrame || function (callback) {
return window.setTimeout(callback, 1000 / 60);
});
}
(function ($, window) {
function Constellation (canvas, options) {
var $canvas = $(canvas),
context = canvas.getContext('2d'),
defaults = {
star: {
color: 'rgba(255, 255, 255, .5)',
width: 2
},
line: {
color: 'rgba(255, 255, 255, .5)',
width: 0.4
},
position: {
x: 0, // This value will be overwritten at startup
y: 0 // This value will be overwritten at startup
},
width: window.innerWidth,
height: window.innerHeight,
velocity: 0.1,
length: 100,
distance: 120,
radius: 150,
stars: []
},
config = $.extend(true, {}, defaults, options);
function Star () {
this.x = Math.random() * canvas.width;
this.y = Math.random() * canvas.height;
this.vx = (config.velocity - (Math.random() * 0.5));
this.vy = (config.velocity - (Math.random() * 0.5));
this.radius = Math.random() * config.star.width;
}
Star.prototype = {
create: function(){
context.beginPath();
context.arc(this.x, this.y, this.radius, 0, Math.PI * 2, false);
context.fill();
},
animate: function(){
var i;
for (i = 0; i < config.length; i++) {
var star = config.stars[i];
if (star.y < 0 || star.y > canvas.height) {
star.vx = star.vx;
star.vy = - star.vy;
} else if (star.x < 0 || star.x > canvas.width) {
star.vx = - star.vx;
star.vy = star.vy;
}
star.x += star.vx;
star.y += star.vy;
}
},
line: function(){
var length = config.length,
iStar,
jStar,
i,
j;
for (i = 0; i < length; i++) {
for (j = 0; j < length; j++) {
iStar = config.stars[i];
jStar = config.stars[j];
if (
(iStar.x - jStar.x) < config.distance &&
(iStar.y - jStar.y) < config.distance &&
(iStar.x - jStar.x) > - config.distance &&
(iStar.y - jStar.y) > - config.distance
) {
if (
(iStar.x - config.position.x) < config.radius &&
(iStar.y - config.position.y) < config.radius &&
(iStar.x - config.position.x) > - config.radius &&
(iStar.y - config.position.y) > - config.radius
) {
context.beginPath();
context.moveTo(iStar.x, iStar.y);
context.lineTo(jStar.x, jStar.y);
context.stroke();
context.closePath();
}
}
}
}
}
};
this.createStars = function () {
var length = config.length,
star,
i;
context.clearRect(0, 0, canvas.width, canvas.height);
for (i = 0; i < length; i++) {
config.stars.push(new Star());
star = config.stars[i];
star.create();
}
star.line();
star.animate();
};
this.setCanvas = function () {
canvas.width = config.width;
canvas.height = config.height;
};
this.setContext = function () {
context.fillStyle = config.star.color;
context.strokeStyle = config.line.color;
context.lineWidth = config.line.width;
};
this.setInitialPosition = function () {
if (!options || !options.hasOwnProperty('position')) {
config.position = {
x: canvas.width * 0.5,
y: canvas.height * 0.5
};
}
};
this.loop = function (callback) {
callback();
window.requestAnimationFrame(function () {
this.loop(callback);
}.bind(this));
};
this.bind = function () {
$canvas.on('mousemove', function(e){
config.position.x = e.pageX - $canvas.offset().left;
config.position.y = e.pageY - $canvas.offset().top;
});
};
this.init = function () {
this.setCanvas();
this.setContext();
this.setInitialPosition();
this.loop(this.createStars);
this.bind();
};
}
$.fn.constellation = function (options) {
return this.each(function () {
var c = new Constellation(this, options);
c.init();
});
};
})($, window);
var startAnimation = function() {
window.addEventListener("resize", function() { startAnimation()} );
$('canvas').constellation({
line: {
color: 'rgba(255, 255, 255, .5)'
}
});
};
|
module.exports = function(grunt) {
// load all grunt tasks
require('matchdep').filterDev('grunt-*').forEach(grunt.loadNpmTasks);
grunt.initConfig({
// watch for changes and trigger compass, jshint, uglify and livereload
watch: {
js: {
files: ['jquery.accrue.js'],
tasks: ['jshint','uglify'],
options: {
livereload: true,
},
},
css: {
files: 'example.scss',
tasks: ['sass'],
options: {
livereload: true,
},
}
},
// we use the Sass
sass: {
dist: {
options: {
// nested, compact, compressed, expanded
style: 'compressed'
},
files: {
'example.css': 'example.scss'
}
}
},
// uglify to concat & minify
uglify: {
js: {
files: {
'jquery.accrue.min.js': 'jquery.accrue.js',
}
}
},
// lint me.
jshint: {
all: ['jquery.accrue.js']
}
});
// register task
grunt.registerTask('default', ['watch']);
};
|
import React, { Component } from 'react';
import logo from './logo.svg';
import './App.css';
import update from 'immutability-helper';
class ListItemBullet extends Component {
render() {
let cssClasses = `listbullet`;
const bulletStyle = {
border: `5px solid ${this.props.color}`,
backgroundColor: 'white'
};
return (
<div className={cssClasses} style={bulletStyle}></div>
);
}
};
class MyRouteMap extends Component {
render() {
const renderList = (list) => {
const lis = list.map((data, index) => {
return (<li key={index}><ListItemBullet color={this.props.color} />
{
data.url?
(<a href={data.url}><span className='description'>{data.name}</span><div className='details'>This is a test.<br/>This is second line</div></a>)
:
(<span className='description'>{data.name}</span>)
}
</li>);
})
return lis;
};
const cssClasses = `App-routemap ${this.props.color}`;
const ulStyle = {
//color: this.props.color,
marginTop: '30px'
};
const ulBeforeStyle = {
content: " ",
position: 'absolute',
marginLeft: '8px',
left: '0px',
top: '20px',
bottom: '40px',
width: '12px',
zIndex: -5,
backgroundColor: this.props.color
};
return (
<div className="App-routemap-div">
<h2>{this.props.title}</h2>
<ul className={cssClasses} style={ulStyle}>
<div style={ulBeforeStyle}></div>
{ renderList(this.props.datalist) }
</ul>
</div>
);
}
}
class App extends Component {
constructor() {
super();
this.state = {
list_unix: [
{
name: "Git ไฝฟ็จ่ๆๅญธ",
url: "https://se101.mtsa.me/Slide/Git/#/"
}
],
'list_system': [
"ไฝๆฅญ็ณป็ตฑๆฆ่ฟฐ",
"ๅๆฃๅผ็ณป็ตฑๆถๆง",
"Scaling Up"
],
'list_data': [
"ๅคงๆธๆๅๆ็ฐกไป",
"TensorFlow ็ฐกไป",
],
'list_algo': [
"Python3 ่ชๆณไป็ดน",
"ๆผ็ฎๆณ็ฐกไป",
"ๅบ็ค่ณๆ็ตๆง",
"ๅญไธฒ่็",
"ๅๆ
่ฆๅ",
"ๅ่ซๆผ็ฎๆณ"
]
};
}
handleClick(e) {
var p = this.state.list_data;
p.push("Test Item");
var newState = update(this.state, {'list_data': {$set: p}});
this.setState(newState);
}
render() {
return (
<div className="App">
<div className="App-header">
<h1>SE101: ๆๆณๆ็บ่ป้ซๅทฅ็จๅธซ๏ผ</h1>
<span className="App-intro">UMich Taiwanese Software Engineers Reading Group - Fall 2017</span>
</div>
<div className="App-contents">
<MyRouteMap title='้ปๆกๆก่้็ผ่
ๅทฅๅ
ท'datalist={this.state.list_unix} color='red' />
<MyRouteMap title='็ณป็ตฑๆถ่จญ่็ถญ้' datalist={this.state.list_system} color='darkgreen' />
<MyRouteMap title='่ณๆ็งๅญธ่ๆ่ก' datalist={this.state.list_data} color='darkblue' />
<MyRouteMap title='็ทจ็จ้ข่ฉฆ่็จๅผ่ช่จ' datalist={this.state.list_algo} color='orange' />
</div>
</div>
);
//<button onClick={() => this.handleClick()}>Add Item</button>
}
}
export default App;
|
import Ember from 'ember';
export default Ember.Component.extend({
tagName: '',
didInsertElement: function() {
this.startPoppover();
},
willDestroyElement: function() {
this.dismissPoppover();
},
startPoppover: function() {
var options = this.getPoppoverOptions();
Ember.$(function() {
Ember.$('[data-toggle="popover"]').popover(options);
});
},
getPoppoverOptions: function() {
var template = Ember.$('.poppover-template').innerHTML;
var content = Ember.$('.poppover-content').html();
return {
template: template,
placement: 'right',
title: 'Download Tip',
trigger: 'hover',
content: content,
html: true
};
},
dismissPoppover: function() {
Ember.$('[data-toggle="popover"]').popover('hide');
}
});
|
'use strict';
/**
* Module dependencies.
*/
var mongoose = require('mongoose'),
Schema = mongoose.Schema;
/**
* SoundcloudSearch Schema
*/
var SoundcloudSearchSchema = new Schema({
// SoundcloudSearch model fields
// ...
search: {
type: String,
required: 'There must be a search term',
trim: true
},
result: {
type: Object
},
created: {
type: Date,
default: Date.now
}
});
mongoose.model('SoundcloudSearch', SoundcloudSearchSchema);
|
// * โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ * //
// * cli upload
// * uploads image by providing a link by running:
// * enduro upload http://www.imgur.com/asd.png
// * โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ * //
var cli_upload = function () {}
// vendor dependencies
var Promise = require('bluebird')
// local dependencies
var logger = require(ENDURO_FOLDER + '/libs/logger')
var file_uploader = require(ENDURO_FOLDER + '/libs/admin_utilities/file_uploader')
// * โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ * //
// * cli upload
// * generates object based on flag array
// *
// * @return {string} - url for uploaded link
// * โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ * //
cli_upload.prototype.cli_upload = function (file_url) {
if (!file_url) {
logger.err('File url not specified\nUsage: $ enduro upload http://yourdomain.com/yourimage.png')
return Promise.reject()
}
return file_uploader.upload_by_url(file_url)
}
module.exports = new cli_upload()
|
var debug = require('debug')('harmonyhubjs:client:login:hub')
var Client = require('node-xmpp-client')
var Q = require('q')
var util = require('../util')
/** PrivateFunction: getIdentity
* Logs in to a Harmony hub as a guest and uses the userAuthToken from logitech's
* web service to retrieve an identity token.
*
* Parameters:
* (String) hubhost - Hostname/IP of the Harmony hub to connect.
* (int) hubport - Optional. Port of the Harmony hub to connect. By default,
* this is set to 5222.
*
* Returns:
* (Q.promise) - The resolved promise passes the retrieved identity token.
*/
function getIdentity (hubhost, hubport) {
debug('retrieve identity by logging in as guest')
// guest@x.com / guest
// guest@connect.logitech.com/gatorade
var deferred = Q.defer()
var iqId
var xmppClient = new Client({
jid: 'guest@x.com/gatorade',
password: 'guest',
host: hubhost,
port: hubport,
disallowTLS: true,
reconnect: true
})
xmppClient.on('online', function () {
debug('XMPP client connected')
var body = 'method=pair:name=harmonyjs#iOS6.0.1#iPhone'
var iq = util.buildIqStanza(
'get', 'connect.logitech.com', 'vnd.logitech.connect/vnd.logitech.pair',
body, 'guest')
iqId = iq.attr('id')
xmppClient.send(iq)
})
xmppClient.on('error', function (e) {
debug('XMPP client error', e)
xmppClient.end()
deferred.reject(e)
})
xmppClient.on('stanza', function (stanza) {
debug('received XMPP stanza: ' + stanza)
if (stanza.attrs.id === iqId.toString()) {
var body = stanza.getChildText('oa')
var response = util.decodeColonSeparatedResponse(body)
if (response.identity && response.identity !== undefined) {
debug('received identity token: ' + response.identity)
xmppClient.end()
deferred.resolve(response.identity)
} else {
debug('could not find identity token')
xmppClient.end()
deferred.reject(new Error('Did not retrieve identity.'))
}
}
})
return deferred.promise
}
/** PrivateFunction: loginWithIdentity
* After fetching an identity from the Harmony hub, this function creates an
* XMPP client using that identity. It returns a promise which, when resolved,
* passes that XMPP client.
*
* Parameters:
* (String) identity - Identity token to login to the Harmony hub.
* (String) hubhost - Hostname/IP of the Harmony hub to connect.
* (int) hubport - Optional. Port of the Harmony hub to connect. By default,
* this is set to 5222.
*
* Returns:
* (Q.promise) - When resolved, passes the logged in XMPP client, ready to
* communicate with the Harmony hub.
*/
function loginWithIdentity (identity, hubhost, hubport) {
debug('create xmpp client using retrieved identity token: ' + identity)
var deferred = Q.defer()
var jid = identity + '@connect.logitech.com/gatorade'
var password = identity
var xmppClient = new Client({
jid: jid,
password: password,
host: hubhost,
port: hubport,
disallowTLS: true
})
xmppClient.on('error', function (e) {
debug('XMPP login error', e)
xmppClient.end()
deferred.reject(e)
})
xmppClient.once('online', function () {
debug('XMPP client connected using identity token')
deferred.resolve(xmppClient)
})
return deferred.promise
}
/** Function: loginToHub
* Uses a userAuthToken to login to a Harmony hub.
*
* Parameters:
* (String) userAuthToken - A authentication token, retrieved from logitechs
* web service.
* (String) hubhost - Hostname/IP of the Harmony hub to connect.
* (int) hubport - Optional. Port of the Harmony hub to connect. By default,
* this is set to 5222.
*
* Returns:
* (Q.promise) - The final resolved promise will pass a fully authenticated
* XMPP client which can be used to communicate with the
* Harmony hub.
*/
function loginToHub (hubhost, hubport) {
debug('perform hub login')
hubport = hubport || 5222
return getIdentity(hubhost, hubport)
.then(function (identity) {
return loginWithIdentity(identity, hubhost, hubport)
})
}
module.exports = loginToHub
|
/**
* Scale Interpolation Function.
*
* @param {number} a start scale
* @param {number} b end scale
* @param {number} v progress
* @returns {string} the interpolated scale
*/
export default function scale(a, b, v) {
// eslint-disable-next-line no-bitwise
return `scale(${((a + (b - a) * v) * 1000 >> 0) / 1000})`;
}
|
/*
* jQuery ZenPen url/link action
*
* Copyright (c) 2013 Deux Huit Huit (http://www.deuxhuithuit.com/)
* Licensed under the MIT (http://deuxhuithuit.mit-license.org)
* Based on the work of Tim Holman (https://github.com/tholman/zenpen)
* Licensed under the Apache License (https://github.com/tholman/zenpen/blob/master/licence.md)
*/
(function ($) {
if (!$.zenpen) {
return;
}
var api = $.zenpen.api;
$.zenpen.actions.url = {
validNode: function (node) {
return !!node.closest('a').length;
},
create: function (options) {
var btn = api.createButtonFactory('url useicons', '', 'url')();
var input = $('<input />').addClass('url-input')
.attr('type','text')
.attr('placeholder','Type or Paste URL here');
var self = this;
var exit = function () {
setTimeout(function () {
self._options.opts.removeClass('url-mode');
self._options.popup.width(self._options.popup.data().width);
}, 100);
};
var realExec = function () {
var url = input.val();
api.rehighlightLastSelection(self._options.range);
// Unlink any current links
document.execCommand( 'unlink', false );
if (!!url) {
// Insert HTTP if it doesn't exist.
if ( !url.match("^(http|https|ftp|ftps|sftp)://")
&& !url.match("^(mailto|tel|fax|skype|irc):")
&& !url.match("^/") ) {
url = "http://" + url;
}
document.execCommand( 'createLink', false, url );
input.val(''); // creates a blur
self._options.popup.trigger('update');
}
};
input.keyup(function (e) {
if (e.which === 13) {
realExec();
} else if (e.which === 27) {
exit();
}
});
input.blur(exit);
return btn.add(input);
},
exec: function ( btn, popup, lastSelection, options ) {
var opts = popup.find('.zenpen-options');
if (!opts.hasClass('url-mode')) {
var width = popup.width();
opts.addClass('url-mode');
var newWidth = /*popup.find('input.url-input').width()*/245 + btn.width();
popup.width(newWidth);
// save options
if (!!lastSelection && !lastSelection.isCollapsed) {
this._options = {
btn: btn,
popup: popup,
opts: opts,
range: lastSelection.getRangeAt(0)
};
popup.data('width', width);
popup.find('input.url-input').val($(lastSelection.focusNode).closest('a').attr('href'));
}
setTimeout(function () {
popup.find('input.url-input').focus();
}, 50);
}
}
};
})(jQuery);
|
'use strict';
var assert = require('assert');
var fs = require('fs');
var path = require('path');
describe('responsive-compass-sprite', function() {
describe('icon-sprite', function() {
function compare(expected, tmp, done) {
var baseExpected = __dirname + '/expected/icon-sprite',
baseTmp = __dirname + '/tmp/icon-sprite';
if(typeof tmp === 'function') {
done = tmp;
tmp = expected;
}
assert.equal(fs.readFileSync(baseExpected + '/' + expected, 'utf-8'), fs.readFileSync(baseTmp + '/' + tmp, 'utf-8'));
done();
};
it('simple test', function(done) {
compare('simple.css', done);
});
it('renderAll test', function(done) {
compare('renderAllSprites.css', done);
});
});
});
|
//~ name a744
alert(a744);
//~ component a745.js
|
'use strict';
var Q = require('q')
, _ = require('underscore');
exports.defaults = function () { return { storage: {} }; };
exports.mixin = {
/**
* Converts `arguments` to a key to be stored.
*/
toKey: function () {
return _.toArray(arguments);
},
contains: function () {
return this.containsKey(this.toKey.apply(this, _.toArray(arguments)));
},
containsKey: function (key) {
return Q.when(_.has(this.storage, key));
},
del: function () {
var args = _.toArray(arguments)
, key = this.toKey.apply(this, arguments);
if (!this.containsKey(key)) return Q.when(false);
this.emit.apply(this, [ 'del' ].concat(args));
delete this.storage[key];
return Q.when(true);
},
set: function (key, val) {
this.storage[key] = val;
return Q.when(true);
},
get: function (key) {
return Q.when(this.storage[key]);
}
};
|
capstone.controller("RegisterCtrl", function($scope,$http,AuthFactory,$location,user1){
// $(".button-collapse").sideNav();
$http.get(`states.json`)
.then((data)=>{
$scope.stateName = data.data
console.log($scope.stateName)
$('input.autocomplete').autocomplete({
data: $scope.stateName,
limit: 10 // The max amount of results that can be shown at once. Default: Infinity.
});
})
$scope.date = new Date();
let storageRef = firebase.storage().ref();
let inputElement = document.getElementById("fileInput");
inputElement.addEventListener("change", handleFiles, false)
function handleFiles() {
var fileList = this.files; /* now you can work with the file list */
console.log("filelist[0]", fileList[0])
storageRef.child(fileList[0].name).put(fileList[0])
.then(function(snapshot) {
console.log('Uploaded a blob or file!');
storageRef.child(fileList[0].name).getDownloadURL()
.then((url)=>{
var img =document.getElementById("myImg")
img.src = url;
$scope.img = img.src;
})
.catch((error)=>{
alert("error")
})
});
}
$scope.register = () => {
if($scope.user_email === $scope.user_confirmEmail){
AuthFactory.getter($scope.user_email,$scope.user_password)
.then ((data)=> {
console.log(data)
$scope.UID = data
// $http.post(`https://frontendcapstone.firebaseio.com/users/.json`,{
// uid: $scope.UID
// })
$http.post(`https://frontendcapstone.firebaseio.com/users/${$scope.UID}.json`,{
uid: $scope.UID,
Firstname: $scope.firstName,
Lastname: $scope.lastName,
email: $scope.user_email,
password: $scope.user_password,
DOB: $scope.user_dob,
imageUrl : $scope.img,
Address: {Address1: $scope.user_addressLine1,
Address2: $scope.user_addressLine2,
City: $scope.user_city,
state: $scope.user_state,
zipcode: $scope.user_zipcode}
})
Materialize.toast("registered successfully", 2000)
$location.path(`/`)
})
}
else {
Materialize.toast("Emails have to match", 1000)
$("input[type='email']").focus()
}
}
})
|
// # Ghost Configuration
// Setup your Ghost install for various environments
// Documentation can be found at http://support.ghost.org/config/
var path = require('path'),
config;
config = {
// ### Production
// When running Ghost in the wild, use the production environment
// Configure your URL and mail settings here
production: {
url: 'http://my-ghost-blog.com',
mail: {},
database: {
client: 'sqlite3',
connection: {
filename: path.join(__dirname, '/content/data/ghost.db')
},
debug: false
},
// ้
็ฝฎMySQL ๆฐๆฎๅบ
/*database: {
client: 'mysql',
connection: {
host : 'host',
user : 'user',
password : 'password',
database : 'database',
charset : 'utf8'
},
debug: false
},*/
server: {
// Host to be passed to node's `net.Server#listen()`
host: '127.0.0.1',
// Port to be passed to node's `net.Server#listen()`, for iisnode set this to `process.env.PORT`
port: '2368'
},
//Storage.Now,we can support `qiniu`,`upyun`, `aliyun oss`, `aliyun ace-storage` and `local-file-store`
storage: {
provider: 'local-file-store'
}
// or
// ๅ่ๆๆกฃ๏ผ http://www.ghostchina.com/qiniu-cdn-for-ghost/
/*storage: {
provider: 'qiniu',
bucketname: 'your-bucket-name',
ACCESS_KEY: 'xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx',
SECRET_KEY: 'xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx',
root: '/image/',
prefix: 'http://your-bucket-name.qiniudn.com'
}*/
// or
// ๅ่ๆๆกฃ๏ผ http://www.ghostchina.com/upyun-cdn-for-ghost/
/*storage: {
provider: 'upyun',
bucketname: 'your-bucket-name',
username: 'your user name',
password: 'your password',
root: '/image/',
prefix: 'http://your-bucket-name.b0.upaiyun.com'
}*/
// or
// ๅ่ๆๆกฃ๏ผ http://www.ghostchina.com/aliyun-oss-for-ghost/
/*storage: {
provider: 'oss',
bucketname: 'your-bucket-name',
ACCESS_KEY: 'xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx',
SECRET_KEY: 'xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx',
root: '/image/',
prefix: 'http://your-bucket-name.oss-cn-hangzhou.aliyuncs.com'
}*/
// or
// ๅ่ๆๆกฃ๏ผ http://www.ghostchina.com/install-ghost-on-aliyun-ace/
/*storage: {
provider: 'ace-storage',
bucketname: 'your-bucket-name'
}*/
},
// ### Development **(default)**
development: {
// The url to use when providing links to the site, E.g. in RSS and email.
// Change this to your Ghost blogs published URL.
url: 'http://localhost:2368',
// Example mail config
// Visit http://support.ghost.org/mail for instructions
// ```
// mail: {
// transport: 'SMTP',
// options: {
// service: 'Mailgun',
// auth: {
// user: '', // mailgun username
// pass: '' // mailgun password
// }
// }
// },
// ```
database: {
client: 'sqlite3',
connection: {
filename: path.join(__dirname, '/content/data/ghost-dev.db')
},
debug: false
},
server: {
// Host to be passed to node's `net.Server#listen()`
host: '127.0.0.1',
// Port to be passed to node's `net.Server#listen()`, for iisnode set this to `process.env.PORT`
port: '2368'
},
paths: {
contentPath: path.join(__dirname, '/content/')
}
},
// **Developers only need to edit below here**
// ### Testing
// Used when developing Ghost to run tests and check the health of Ghost
// Uses a different port number
testing: {
url: 'http://127.0.0.1:2369',
database: {
client: 'sqlite3',
connection: {
filename: path.join(__dirname, '/content/data/ghost-test.db')
}
},
server: {
host: '127.0.0.1',
port: '2369'
},
logging: false
},
// ### Testing MySQL
// Used by Travis - Automated testing run through GitHub
'testing-mysql': {
url: 'http://127.0.0.1:2369',
database: {
client: 'mysql',
connection: {
host : '127.0.0.1',
user : 'root',
password : '',
database : 'ghost_testing',
charset : 'utf8'
}
},
server: {
host: '127.0.0.1',
port: '2369'
},
logging: false
},
// ### Testing pg
// Used by Travis - Automated testing run through GitHub
'testing-pg': {
url: 'http://127.0.0.1:2369',
database: {
client: 'pg',
connection: {
host : '127.0.0.1',
user : 'postgres',
password : '',
database : 'ghost_testing',
charset : 'utf8'
}
},
server: {
host: '127.0.0.1',
port: '2369'
},
logging: false
}
};
// Export config
module.exports = config;
|
(function(){
angular
.module('users')
.controller('UserController', [
'userService', '$mdSidenav', '$mdBottomSheet', '$log', '$q',
UserController
]);
/**
* Main Controller for the Angular Material Starter App
* @param $scope
* @param $mdSidenav
* @param avatarsService
* @constructor
*/
function UserController( userService, $mdSidenav, $mdBottomSheet, $log, $q) {
var self = this;
self.selected = null;
self.users = [ ];
self.selectUser = selectUser;
self.toggleList = toggleUsersList;
self.share = share;
// Load all registered users
userService
.loadAllUsers()
.then( function( users ) {
self.users = [].concat(users);
self.selected = users[0];
});
// *********************************
// Internal methods
// *********************************
/**
* First hide the bottomsheet IF visible, then
* hide or Show the 'left' sideNav area
*/
function toggleUsersList() {
var pending = $mdBottomSheet.hide() || $q.when(true);
pending.then(function(){
$mdSidenav('left').toggle();
});
}
/**
* Select the current avatars
* @param menuId
*/
function selectUser ( user ) {
self.selected = angular.isNumber(user) ? $scope.users[user] : user;
self.toggleList();
}
/**
* Show the bottom sheet
*/
function share($event) {
var user = self.selected;
$mdBottomSheet.show({
parent: angular.element(document.getElementById('content')),
templateUrl: '/src/users/view/contactSheet.html',
controller: [ '$mdBottomSheet', UserSheetController],
controllerAs: "vm",
bindToController : true,
targetEvent: $event
}).then(function(clickedItem) {
clickedItem && $log.debug( clickedItem.name + ' clicked!');
});
/**
* Bottom Sheet controller for the Avatar Actions
*/
function UserSheetController( $mdBottomSheet ) {
this.user = user;
this.items = [
{ name: 'Github' , icon: 'github' , icon_url: 'assets/svg/github.svg', urlPath: "https://github.com/hassanabidpk/"},
{ name: 'Twitter' , icon: 'twitter' , icon_url: 'assets/svg/twitter.svg', urlPath: "https://twitter.com/hassanabidpk"},
{ name: 'Google+' , icon: 'google_plus' , icon_url: 'assets/svg/google_plus.svg', urlPath: "https://plus.google.com/+HassanAbid/"},
{ name: 'Linkedin' , icon: 'linkedin' , icon_url: 'assets/svg/linkedin.svg', urlPath: "https://kr.linkedin.com/pub/hassan-abid/12/700/66b"}
];
this.performAction = function(action) {
window.location.href = action.urlPath;
$mdBottomSheet.hide(action);
};
}
}
}
})();
|
var gulp = require('gulp'),
concat = require('gulp-concat'),
compass = require('gulp-compass'),
notify = require('gulp-notify');
function swallowError(error) {
this.emit('end');
}
function reportError(error) {
notify.onError().apply(this, arguments);
this.emit('end');
}
// combine js into single file
//===========================================
gulp.task('scripts', function() {
gulp.src([
'./src/js/lib/jquery.min.js',
'./src/js/lib/cssbeautify.js',
'./src/js/lib/specificity.js',
'./src/js/lib/tablesorter.js',
'./src/js/local/helpers.js',
// './src/js/local/syntax-highlight.js',
'./src/js/local/build-html.js',
// './src/js/local/build-specificity.js',
'./src/js/local/button-control.js',
// './src/js/local/css-highlight.js',
'./src/js/local/tabs.js'
])
.pipe(concat('smprof.js'))
.pipe(gulp.dest('./ext/js/'))
});
// compass: compile sass to css
//===========================================
gulp.task('compass', function() {
gulp.src('./assets/sass/*.scss')
.pipe(compass({
config_file: './config.rb',
css: './ext/css/',
sass: './assets/sass'
}))
.on('error', reportError);
});
// watch: monitor html and static assets updates
//===========================================
gulp.task('watch', function() {
// watch task for sass
gulp.watch('./assets/sass/**/*.scss', ['compass']);
gulp.watch('./src/js/**/*.js', ['scripts']);
});
// Default Gulp Task
//===========================================
gulp.task('default', ['compass', 'scripts', 'watch']);
|
module.exports = require( "./src/LRUCache" );
|
'use strict';
angular.module('sportzCast')
.controller('FooterCtrl', function ($scope) {
$('#footer').hide();
$(function () {
$(window).scroll(function () {
// set distance user needs to scroll before we start fadeIn
if ($(this).scrollTop() > 500) {
$('.navbar').fadeIn();
} else {
$('.navbar').fadeOut();
}
});
});
});
|
/**
* Usuario Controller Test Suite
*
* @author Thiago Paes <mrprompt@gmail.com>
* @license MIT
*/
'use strict';
var connection = require('../test');
var Usuario = require('../../src/controllers/UsuarioController');
var sinon = require('sinon');
var assert = require('assert');
var request = require('request');
var response = {
content: null,
statusCode: 0,
json: function(content){
this.content = content;
return this;
},
status: function(status) {
this.statusCode = status;
return this;
}
};
describe('Usuario Controller', function () {
it('#lista() deve retornar um array', function (done) {
request.headers = {};
request.params = { };
request.query = {
page : 1,
limit: 1
};
Usuario.lista(request, response, function() {
assert.equal(response.content.object, 'list');
done();
});
});
it('#abre() deve retornar um objeto', function (done) {
request.headers = { };
request.params = {
id: 1
};
request.query = {
page : 1,
limit: 1
};
Usuario.abre(request, response, function() {
assert.equal(response.content.object, 'error');
assert.equal(response.statusCode, 404);
done();
});
});
it('#adiciona() deve retornar um objeto', function (done) {
request.headers = { };
request.body = {
nome : 'Foo Bar',
email : 'foo@bar.bar',
password: 'foo',
uf : 'AA',
estado : 'aaa aaa',
cidade : 'bbb bbb bb'
};
Usuario.adiciona(request, response, function() {
assert.equal(response.content.object, 'error');
done();
});
});
it('#atualiza() deve retornar um objeto', function (done) {
request.headers = { };
request.params = {
id: 1
};
request.query = {
page : 1,
limit: 1
};
Usuario.atualiza(request, response, function() {
assert.equal(response.content.object, 'error');
done();
});
});
it('#apaga() deve retornar um objeto', function (done) {
request.headers = { };
request.params = {
id: 1
};
request.query = {
page : 1,
limit: 1
};
Usuario.apaga(request, response, function() {
assert.equal(response.content.object, 'error');
done();
});
});
});
|
define([
], function () {
'use strict';
return function (req, res, next) {
function filterParams(req, action) {
var paramsWhitelist = action.params,
whitelistParam,
paramValue,
type,
filteredParams = {};
// check all actions params
for (whitelistParam in paramsWhitelist) {
if (paramsWhitelist.hasOwnProperty(whitelistParam)) {
type = '';
// get param from body or query
if (paramsWhitelist[whitelistParam].query === true) {
paramValue = req.query[whitelistParam];
} else {
paramValue = req.body[whitelistParam];
}
// if defined or not optional -> validate
if (paramValue !== undefined || !paramsWhitelist[whitelistParam].optional) {
// validate missing params
if (paramValue === undefined && !paramsWhitelist[whitelistParam].optional) { // necessary param missing
type = 'missing_parameter';
} else if (paramValue && paramValue.constructor !== paramsWhitelist[whitelistParam].type) { // validate param type
type = 'wrong_type';
} else if (paramsWhitelist[whitelistParam].hasOwnProperty('regex') && !paramsWhitelist[whitelistParam].regex.test(paramValue)) {
type = 'invalid_structure'; // validate param for custom regex
} else if (paramsWhitelist[whitelistParam].hasOwnProperty('validate') && !paramsWhitelist[whitelistParam].validate(paramValue)) {
type = 'custom_validation'; // validate param for custom validate function
}
// if error type is set -> throw error
if (type) {
throw {
error: type,
param: whitelistParam
};
}
// set validated param
filteredParams[whitelistParam] = paramValue;
}
}
}
return filteredParams;
}
if (req.customData && req.customData.action) {
try {
req.customData.params = filterParams(req, req.customData.action);
} catch (e) {
return res.status(400).send(e);
}
}
next();
};
});
|
var gulp = require('gulp'),
webserver = require('gulp-webserver'),
htmlreplace = require('gulp-html-replace');
//gulp.task('default', function() {
// gulp.run('watcher', 'webserver');
//});
gulp.task('webserver', function() {
gulp.src('build')
.pipe(webserver({
livereload: true
}));
});
gulp.task('watcher', function() {
gulp.watch('app/**', function (event) {
gulp.run('copy');
});
});
gulp.task('copy', function(){
gulp.src('app/index.html')
.pipe(htmlreplace({
'css': 'css/styles.css',
'js' : 'js/main.js',
'jslib': 'js/lib/jquery.js'
}))
.pipe(gulp.dest('build/'));
gulp.src('app/index.html')
.pipe(htmlreplace({
'css': 'app/css/styles.css',
'jslib' : 'bower_components/jQuery/dist/jquery.js',
'js' : 'app/js/main.js'
}))
.pipe(gulp.dest(''));
gulp.src('bower_components/jQuery/dist/jquery.js')
.pipe(gulp.dest('build/js/lib/'));
gulp.src('app/js/main.js')
.pipe(gulp.dest('build/js/'));
gulp.src('app/css/styles.css')
.pipe(gulp.dest('build/css/'));
gulp.src('app/structure.json')
.pipe(gulp.dest('build/'));
gulp.src('app/tasks/**')
.pipe(gulp.dest('build/tasks'));
});
|
/**
* Created by siddharthsharma on 5/21/16.
*/
var React = require('react');
var Contact = require('./contact/app-catalog');
var Cart = require('./cart/app-cart');
var Router = require('react-router-component');
var CatalogDetail = require('./product/app-catalogdetail');
var Template = require('./app-template.js');
var Locations = Router.Locations;
var Location = Router.Location;
var App = React.createClass({
render:function(){
return (
<Template>
<Locations>
<Location path="/" handler={Catalog} />
<Location path="/cart" handler={Cart} />
<Location path="/item/:item" handler={CatalogDetail} />
</Locations>
</Template>
);
}
});
module.exports = App;
|
"use strict";
var gulp = require('gulp');
var clean = require('gulp-clean');
var cleanTask = function() {
return gulp.src('dist', { read: false })
.pipe(clean());
};
gulp.task('clean', cleanTask);
module.exports = cleanTask;
|
var scroller = angular.module("scroller", ["ngTouch", "angular-websql"]);
|
import { get_definition } from './../base';
export const push_link = (
oid, linkurl, linkname, onmenu='true', instance_name,
when, additional_args, description
) => get_definition({
oid,
linkurl,
linkname,
onmenu,
instance_name
},
{
label: 'VersionOne - Push Link',
method: 'push_link',
module: 'main',
name: 'v1plugin'
},
when, additional_args, description
);
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.