text
stringlengths 2
6.14k
|
|---|
'use strict';
var clear = require('es5-ext/array/#/clear')
, eIndexOf = require('es5-ext/array/#/e-index-of')
, setPrototypeOf = require('es5-ext/object/set-prototype-of')
, callable = require('es5-ext/object/valid-callable')
, d = require('d')
, ee = require('event-emitter')
, Symbol = require('es6-symbol')
, iterator = require('es6-iterator/valid-iterable')
, forOf = require('es6-iterator/for-of')
, Iterator = require('./lib/iterator')
, isNative = require('./is-native-implemented')
, call = Function.prototype.call, defineProperty = Object.defineProperty
, SetPoly, getValues;
module.exports = SetPoly = function (/*iterable*/) {
var iterable = arguments[0];
if (!(this instanceof SetPoly)) return new SetPoly(iterable);
if (this.__setData__ !== undefined) {
throw new TypeError(this + " cannot be reinitialized");
}
if (iterable != null) iterator(iterable);
defineProperty(this, '__setData__', d('c', []));
if (!iterable) return;
forOf(iterable, function (value) {
if (eIndexOf.call(this, value) !== -1) return;
this.push(value);
}, this.__setData__);
};
if (isNative) {
if (setPrototypeOf) setPrototypeOf(SetPoly, Set);
SetPoly.prototype = Object.create(Set.prototype, {
constructor: d(SetPoly)
});
}
ee(Object.defineProperties(SetPoly.prototype, {
add: d(function (value) {
if (this.has(value)) return this;
this.emit('_add', this.__setData__.push(value) - 1, value);
return this;
}),
clear: d(function () {
if (!this.__setData__.length) return;
clear.call(this.__setData__);
this.emit('_clear');
}),
delete: d(function (value) {
var index = eIndexOf.call(this.__setData__, value);
if (index === -1) return false;
this.__setData__.splice(index, 1);
this.emit('_delete', index, value);
return true;
}),
entries: d(function () { return new Iterator(this, 'key+value'); }),
forEach: d(function (cb/*, thisArg*/) {
var thisArg = arguments[1], iterator, result, value;
callable(cb);
iterator = this.values();
result = iterator._next();
while (result !== undefined) {
value = iterator._resolve(result);
call.call(cb, thisArg, value, value, this);
result = iterator._next();
}
}),
has: d(function (value) {
return (eIndexOf.call(this.__setData__, value) !== -1);
}),
keys: d(getValues = function () { return this.values(); }),
size: d.gs(function () { return this.__setData__.length; }),
values: d(function () { return new Iterator(this); }),
toString: d(function () { return '[object Set]'; })
}));
defineProperty(SetPoly.prototype, Symbol.iterator, d(getValues));
defineProperty(SetPoly.prototype, Symbol.toStringTag, d('c', 'Set'));
|
'use strict';
const TYPE = Symbol.for('type');
class Data {
constructor(options) {
// File details
this.filepath = options.filepath;
// Type
this[TYPE] = 'data';
// Data
Object.assign(this, options.data);
}
}
module.exports = Data;
|
function collectWithWildcard(test) {
test.expect(4);
var api_server = new Test_ApiServer(function handler(request, callback) {
var url = request.url;
switch (url) {
case '/accounts?username=chariz*':
let account = new Model_Account({
username: 'charizard'
});
return void callback(null, [
account.redact()
]);
default:
let error = new Error('Invalid url: ' + url);
return void callback(error);
}
});
var parameters = {
username: 'chariz*'
};
function handler(error, results) {
test.equals(error, null);
test.equals(results.length, 1);
var account = results[0];
test.equals(account.get('username'), 'charizard');
test.equals(account.get('type'), Enum_AccountTypes.MEMBER);
api_server.destroy();
test.done();
}
Resource_Accounts.collect(parameters, handler);
}
module.exports = {
collectWithWildcard
};
|
angular.module('appTesting').service("LoginLocalStorage", function () {
"use strict";
var STORE_NAME = "login";
var setUser = function setUser(user) {
localStorage.setItem(STORE_NAME, JSON.stringify(user));
}
var getUser = function getUser() {
var storedTasks = localStorage.getItem(STORE_NAME);
if (storedTasks) {
return JSON.parse(storedTasks);
}
return {};
}
return {
setUser: setUser,
getUser: getUser
}
});
|
/* eslint-disable no-console */
const buildData = require('./build_data');
const buildSrc = require('./build_src');
const buildCSS = require('./build_css');
let _currBuild = null;
// if called directly, do the thing.
buildAll();
function buildAll() {
if (_currBuild) return _currBuild;
return _currBuild =
Promise.resolve()
.then(() => buildCSS())
.then(() => buildData())
.then(() => buildSrc())
.then(() => _currBuild = null)
.catch((err) => {
console.error(err);
_currBuild = null;
process.exit(1);
});
}
module.exports = buildAll;
|
function LetterProps(o, sw, sc, fc, m, p) {
this.o = o;
this.sw = sw;
this.sc = sc;
this.fc = fc;
this.m = m;
this.p = p;
this._mdf = {
o: true,
sw: !!sw,
sc: !!sc,
fc: !!fc,
m: true,
p: true,
};
}
LetterProps.prototype.update = function (o, sw, sc, fc, m, p) {
this._mdf.o = false;
this._mdf.sw = false;
this._mdf.sc = false;
this._mdf.fc = false;
this._mdf.m = false;
this._mdf.p = false;
var updated = false;
if (this.o !== o) {
this.o = o;
this._mdf.o = true;
updated = true;
}
if (this.sw !== sw) {
this.sw = sw;
this._mdf.sw = true;
updated = true;
}
if (this.sc !== sc) {
this.sc = sc;
this._mdf.sc = true;
updated = true;
}
if (this.fc !== fc) {
this.fc = fc;
this._mdf.fc = true;
updated = true;
}
if (this.m !== m) {
this.m = m;
this._mdf.m = true;
updated = true;
}
if (p.length && (this.p[0] !== p[0] || this.p[1] !== p[1] || this.p[4] !== p[4] || this.p[5] !== p[5] || this.p[12] !== p[12] || this.p[13] !== p[13])) {
this.p = p;
this._mdf.p = true;
updated = true;
}
return updated;
};
|
describe('dJSON', function () {
'use strict';
var chai = require('chai');
var expect = chai.expect;
var dJSON = require('../lib/dJSON');
var path = 'x.y["q.{r}"].z';
var obj;
beforeEach(function () {
obj = {
x: {
y: {
'q.{r}': {
z: 635
},
q: {
r: {
z: 1
}
}
}
},
'x-y': 5,
falsy: false
};
});
it('gets a value from an object with a path containing properties which contain a period', function () {
expect(dJSON.get(obj, path)).to.equal(635);
expect(dJSON.get(obj, 'x.y.q.r.z')).to.equal(1);
});
it('sets a value from an object with a path containing properties which contain a period', function () {
dJSON.set(obj, path, 17771);
expect(dJSON.get(obj, path)).to.equal(17771);
expect(dJSON.get(obj, 'x.y.q.r.z')).to.equal(1);
});
it('will return undefined when requesting a property with a dash directly', function () {
expect(dJSON.get(obj, 'x-y')).to.be.undefined;
});
it('will return the proper value when requesting a property with a dash by square bracket notation', function () {
expect(dJSON.get(obj, '["x-y"]')).to.equal(5);
});
it('returns a value that is falsy', function () {
expect(dJSON.get(obj, 'falsy')).to.equal(false);
});
it('sets a value that is falsy', function () {
dJSON.set(obj, 'new', false);
expect(dJSON.get(obj, 'new')).to.equal(false);
});
it('uses an empty object as default for the value in the set method', function () {
var newObj = {};
dJSON.set(newObj, 'foo.bar.lorem');
expect(newObj).to.deep.equal({
foo: {
bar: {
lorem: {}
}
}
});
});
it('does not create an object when a path exists as empty string', function () {
var newObj = {
nestedObject: {
anArray: [
'i have a value',
''
]
}
};
var newPath = 'nestedObject.anArray[1]';
dJSON.set(newObj, newPath, 17771);
expect(newObj).to.deep.equal({
nestedObject: {
anArray: [
'i have a value',
17771
]
}
});
});
it('creates an object from a path with a left curly brace', function () {
var newObj = {};
dJSON.set(newObj, path.replace('}', ''), 'foo');
expect(newObj).to.be.deep.equal({
x: {
y: {
'q.{r': {
z: 'foo'
}
}
}
});
});
it('creates an object from a path with a right curly brace', function () {
var newObj = {};
dJSON.set(newObj, path.replace('{', ''), 'foo');
expect(newObj).to.be.deep.equal({
x: {
y: {
'q.r}': {
z: 'foo'
}
}
}
});
});
it('creates an object from a path with curly braces', function () {
var newObj = {};
dJSON.set(newObj, path, 'foo');
expect(newObj).to.be.deep.equal({
x: {
y: {
'q.{r}': {
z: 'foo'
}
}
}
});
});
it('creates an object from a path without curly braces', function () {
var newObj = {};
dJSON.set(newObj, path.replace('{', '').replace('}', ''), 'foo');
expect(newObj).to.be.deep.equal({
x: {
y: {
'q.r': {
z: 'foo'
}
}
}
});
});
});
|
var fusepm = require('./fusepm');
module.exports = fixunoproj;
function fixunoproj () {
var fn = fusepm.local_unoproj(".");
fusepm.read_unoproj(fn).then(function (obj) {
var inc = [];
if (obj.Includes) {
var re = /\//;
for (var i=0; i<obj.Includes.length;i++) {
if (obj.Includes[i] === '*') {
inc.push('./*.ux');
inc.push('./*.uno');
inc.push('./*.uxl');
}
else if (!obj.Includes[i].match(re)) {
inc.push('./' + obj.Includes[i]);
}
else {
inc.push(obj.Includes[i]);
}
}
}
else {
inc = ['./*.ux', './*.uno', './*.uxl'];
}
if (!obj.Version) {
obj.Version = "0.0.0";
}
obj.Includes = inc;
fusepm.save_unoproj(fn, obj);
}).catch(function (e) {
console.log(e);
});
}
|
import mod437 from './mod437';
var value=mod437+1;
export default value;
|
const defaults = {
base_css: true, // the base dark theme css
inline_youtube: true, // makes youtube videos play inline the chat
collapse_onebox: true, // can collapse
collapse_onebox_default: false, // default option for collapse
pause_youtube_on_collapse: true, // default option for pausing youtube on collapse
user_color_bars: true, // show colored bars above users message blocks
fish_spinner: true, // fish spinner is best spinner
inline_imgur: true, // inlines webm,gifv,mp4 content from imgur
visualize_hex: true, // underlines hex codes with their colour values
syntax_highlight_code: true, // guess at language and highlight the code blocks
emoji_translator: true, // emoji translator for INPUT area
code_mode_editor: true, // uses CodeMirror for your code inputs
better_image_uploads: true // use the drag & drop and paste api for image uploads
};
const fileLocations = {
inline_youtube: ['js/inline_youtube.js'],
collapse_onebox: ['js/collapse_onebox.js'],
user_color_bars: ['js/user_color_bars.js'],
fish_spinner: ['js/fish_spinner.js'],
inline_imgur: ['js/inline_imgur.js'],
visualize_hex: ['js/visualize_hex.js'],
better_image_uploads: ['js/better_image_uploads.js'],
syntax_highlight_code: ['js/highlight.js', 'js/syntax_highlight_code.js'],
emoji_translator: ['js/emojidata.js', 'js/emoji_translator.js'],
code_mode_editor: ['CodeMirror/js/codemirror.js',
'CodeMirror/mode/cmake/cmake.js',
'CodeMirror/mode/cobol/cobol.js',
'CodeMirror/mode/coffeescript/coffeescript.js',
'CodeMirror/mode/commonlisp/commonlisp.js',
'CodeMirror/mode/css/css.js',
'CodeMirror/mode/dart/dart.js',
'CodeMirror/mode/go/go.js',
'CodeMirror/mode/groovy/groovy.js',
'CodeMirror/mode/haml/haml.js',
'CodeMirror/mode/haskell/haskell.js',
'CodeMirror/mode/htmlembedded/htmlembedded.js',
'CodeMirror/mode/htmlmixed/htmlmixed.js',
'CodeMirror/mode/jade/jade.js',
'CodeMirror/mode/javascript/javascript.js',
'CodeMirror/mode/lua/lua.js',
'CodeMirror/mode/markdown/markdown.js',
'CodeMirror/mode/mathematica/mathematica.js',
'CodeMirror/mode/nginx/nginx.js',
'CodeMirror/mode/pascal/pascal.js',
'CodeMirror/mode/perl/perl.js',
'CodeMirror/mode/php/php.js',
'CodeMirror/mode/puppet/puppet.js',
'CodeMirror/mode/python/python.js',
'CodeMirror/mode/ruby/ruby.js',
'CodeMirror/mode/sass/sass.js',
'CodeMirror/mode/scheme/scheme.js',
'CodeMirror/mode/shell/shell.js' ,
'CodeMirror/mode/sql/sql.js',
'CodeMirror/mode/swift/swift.js',
'CodeMirror/mode/twig/twig.js',
'CodeMirror/mode/vb/vb.js',
'CodeMirror/mode/vbscript/vbscript.js',
'CodeMirror/mode/vhdl/vhdl.js',
'CodeMirror/mode/vue/vue.js',
'CodeMirror/mode/xml/xml.js',
'CodeMirror/mode/xquery/xquery.js',
'CodeMirror/mode/yaml/yaml.js',
'js/code_mode_editor.js']
};
// right now I assume order is correct because I'm a terrible person. make an order array or base it on File Locations and make that an array
// inject the observer and the utils always. then initialize the options.
injector([{type: 'js', location: 'js/observer.js'},{type: 'js', location: 'js/utils.js'}], _ => chrome.storage.sync.get(defaults, init));
function init(options) {
// inject the options for the plugins themselves.
const opts = document.createElement('script');
opts.textContent = `
const options = ${JSON.stringify(options)};
`;
document.body.appendChild(opts);
// now load the plugins.
const loading = [];
if( !options.base_css ) {
document.documentElement.classList.add('nocss');
}
delete options.base_css;
for( const key of Object.keys(options) ) {
if( !options[key] || !( key in fileLocations)) continue;
for( const location of fileLocations[key] ) {
const [,type] = location.split('.');
loading.push({location, type});
}
}
injector(loading, _ => {
const drai = document.createElement('script');
drai.textContent = `
if( document.readyState === 'complete' ) {
DOMObserver.drain();
} else {
window.onload = _ => DOMObserver.drain();
}
`;
document.body.appendChild(drai);
});
}
function injector([first, ...rest], cb) {
if( !first ) return cb();
if( first.type === 'js' ) {
injectJS(first.location, _ => injector(rest, cb));
} else {
injectCSS(first.location, _ => injector(rest, cb));
}
}
function injectCSS(file, cb) {
const elm = document.createElement('link');
elm.rel = 'stylesheet';
elm.type = 'text/css';
elm.href = chrome.extension.getURL(file);
elm.onload = cb;
document.head.appendChild(elm);
}
function injectJS(file, cb) {
const elm = document.createElement('script');
elm.type = 'text/javascript';
elm.src = chrome.extension.getURL(file);
elm.onload = cb;
document.body.appendChild(elm);
}
|
function daysLeftThisWeek (date) {
return 6 - date.getDay()
}
module.exports = daysLeftThisWeek
|
async function test(object) {
for (var key in object) {
await key;
}
}
|
var contenedor = {};
var json = [];
var json_active = [];
var timeout;
var result = {};
$(document).ready(function() {
$('#buscador').keyup(function() {
if (timeout) {
clearTimeout(timeout);
timeout = null;
}
timeout = setTimeout(function() {
search();
}, 100);
});
$("body").on('change', '#result', function() {
result = $("#result").val();
load_content(json);
});
$("body").on('click', '.asc', function() {
var name = $(this).parent().attr('rel');
console.log(name);
$(this).removeClass("asc").addClass("desc");
order(name, true);
});
$("body").on('click', '.desc', function() {
var name = $(this).parent().attr('rel');
$(this).removeClass("desc").addClass("asc");
order(name, false);
});
});
function update(id,parent,valor){
for (var i=0; i< json.length; i++) {
if (json[i].id === id){
json[i][parent] = valor;
return;
}
}
}
function load_content(json) {
max = result;
data = json.slice(0, max);
json_active = json;
$("#numRows").html(json.length);
contenedor.html('');
2
var list = table.find("th[rel]");
var html = '';
$.each(data, function(i, value) {
html += '<tr id="' + value.id + '">';
$.each(list, function(index) {
valor = $(this).attr('rel');
if (valor != 'acction') {
if ($(this).hasClass("editable")) {
html += '<td><span class="edition" rel="' + value.id + '">' + value[valor] .substring(0, 60) +'</span></td>';
} else if($(this).hasClass("view")){
if(value[valor].length > 1){
var class_1 = $(this).data('class');
html += '<td><a href="javascript:void(0)" class="'+class_1+'" rel="'+ value[valor] + '" data-id="' + value.id + '"></a></td>';
}else{
html += '<td></td>';
}
}else{
html += '<td>' + value[valor] + '</td>';
}
} else {
html += '<td>';
$.each(acction, function(k, data) {
html += '<a class="' + data.class + '" rel="' + value[data.rel] + '" href="' + data.link + value[data.parameter] + '" target="'+data.target+'" >' + data.button + '</a>';
});
html += "</td>";
}
if (index >= list.length - 1) {
html += '</tr>';
contenedor.append(html);
html = '';
}
});
});
}
function selectedRow(json) {
var num = result;
var rows = json.length;
var total = rows / num;
var cant = Math.floor(total);
$("#result").html('');
for (i = 0; i < cant; i++) {
$("#result").append("<option value=\"" + parseInt(num) + "\">" + num + "</option>");
num = num + result;
}
$("#result").append("<option value=\"" + parseInt(rows) + "\">" + rows + "</option>");
}
function order(prop, asc) {
json = json.sort(function(a, b) {
if (asc) return (a[prop] > b[prop]) ? 1 : ((a[prop] < b[prop]) ? -1 : 0);
else return (b[prop] > a[prop]) ? 1 : ((b[prop] < a[prop]) ? -1 : 0);
});
contenedor.html('');
load_content(json);
}
function search() {
var list = table.find("th[rel]");
var data = [];
var serch = $("#buscador").val();
json.forEach(function(element, index, array) {
$.each(list, function(index) {
valor = $(this).attr('rel');
if (element[valor]) {
if (element[valor].like('%' + serch + '%')) {
data.push(element);
return false;
}
}
});
});
contenedor.html('');
load_content(data);
}
String.prototype.like = function(search) {
if (typeof search !== 'string' || this === null) {
return false;
}
search = search.replace(new RegExp("([\\.\\\\\\+\\*\\?\\[\\^\\]\\$\\(\\)\\{\\}\\=\\!\\<\\>\\|\\:\\-])", "g"), "\\$1");
search = search.replace(/%/g, '.*').replace(/_/g, '.');
return RegExp('^' + search + '$', 'gi').test(this);
}
function export_csv(JSONData, ReportTitle, ShowLabel) {
var arrData = typeof JSONData != 'object' ? JSON.parse(JSONData) : JSONData;
var CSV = '';
// CSV += ReportTitle + '\r\n\n';
if (ShowLabel) {
var row = "";
for (var index in arrData[0]) {
row += index + ';';
}
row = row.slice(0, -1);
CSV += row + '\r\n';
}
for (var i = 0; i < arrData.length; i++) {
var row = "";
for (var index in arrData[i]) {
row += '"' + arrData[i][index] + '";';
}
row.slice(0, row.length - 1);
CSV += row + '\r\n';
}
if (CSV == '') {
alert("Invalid data");
return;
}
// var fileName = "Report_";
//fileName += ReportTitle.replace(/ /g,"_");
var uri = 'data:text/csv;charset=utf-8,' + escape(CSV);
var link = document.createElement("a");
link.href = uri;
link.style = "visibility:hidden";
link.download = ReportTitle + ".csv";
document.body.appendChild(link);
link.click();
document.body.removeChild(link);
}
|
import React from 'react';
import ons from 'onsenui';
import {
Page,
Toolbar,
BackButton,
LazyList,
ListItem
} from 'react-onsenui';
class InfiniteScroll extends React.Component {
renderRow(index) {
return (
<ListItem key={index}>
{'Item ' + (index + 1)}
</ListItem>
);
}
renderToolbar() {
return (
<Toolbar>
<div className='left'>
<BackButton>Back</BackButton>
</div>
<div className='center'>
Infinite scroll
</div>
</Toolbar>
);
}
render() {
return (
<Page renderToolbar={this.renderToolbar}>
<LazyList
length={10000}
renderRow={this.renderRow}
calculateItemHeight={() => ons.platform.isAndroid() ? 77 : 45}
/>
</Page>
);
}
}
module.exports = InfiniteScroll;
|
$js.module({
prerequisite:[
'/{$jshome}/modules/splice.module.extensions.js'
],
imports:[
{ Inheritance : '/{$jshome}/modules/splice.inheritance.js' },
{'SpliceJS.UI':'../splice.ui.js'},
'splice.controls.pageloader.html'
],
definition:function(){
var scope = this;
var
imports = scope.imports
;
var
Class = imports.Inheritance.Class
, UIControl = imports.SpliceJS.UI.UIControl
;
var PageLoader = Class(function PageLoaderController(){
this.base();
}).extend(UIControl);
scope.exports(
PageLoader
);
}
})
|
'use babel';
import MapQueries from '../lib/map-queries';
// Use the command `window:run-package-specs` (cmd-alt-ctrl-p) to run specs.
//
// To run a specific `it` or `describe` block add an `f` to the front (e.g. `fit`
// or `fdescribe`). Remove the `f` to unfocus the block.
describe('MapQueries', () => {
let workspaceElement, activationPromise;
beforeEach(() => {
workspaceElement = atom.views.getView(atom.workspace);
activationPromise = atom.packages.activatePackage('map-queries');
});
describe('when the map-queries:toggle event is triggered', () => {
it('hides and shows the modal panel', () => {
// Before the activation event the view is not on the DOM, and no panel
// has been created
expect(workspaceElement.querySelector('.map-queries')).not.toExist();
// This is an activation event, triggering it will cause the package to be
// activated.
atom.commands.dispatch(workspaceElement, 'map-queries:toggle');
waitsForPromise(() => {
return activationPromise;
});
runs(() => {
expect(workspaceElement.querySelector('.map-queries')).toExist();
let mapQueriesElement = workspaceElement.querySelector('.map-queries');
expect(mapQueriesElement).toExist();
let mapQueriesPanel = atom.workspace.panelForItem(mapQueriesElement);
expect(mapQueriesPanel.isVisible()).toBe(true);
atom.commands.dispatch(workspaceElement, 'map-queries:toggle');
expect(mapQueriesPanel.isVisible()).toBe(false);
});
});
it('hides and shows the view', () => {
// This test shows you an integration test testing at the view level.
// Attaching the workspaceElement to the DOM is required to allow the
// `toBeVisible()` matchers to work. Anything testing visibility or focus
// requires that the workspaceElement is on the DOM. Tests that attach the
// workspaceElement to the DOM are generally slower than those off DOM.
jasmine.attachToDOM(workspaceElement);
expect(workspaceElement.querySelector('.map-queries')).not.toExist();
// This is an activation event, triggering it causes the package to be
// activated.
atom.commands.dispatch(workspaceElement, 'map-queries:toggle');
waitsForPromise(() => {
return activationPromise;
});
runs(() => {
// Now we can test for view visibility
let mapQueriesElement = workspaceElement.querySelector('.map-queries');
expect(mapQueriesElement).toBeVisible();
atom.commands.dispatch(workspaceElement, 'map-queries:toggle');
expect(mapQueriesElement).not.toBeVisible();
});
});
});
});
|
var config = require('./config');
var express = require('express');
var superagent = require('superagent');
/**
* Auth Token
*/
var authToken = null;
var expires = 0;
var expires_in = 20160; // 14 days in minutes
/**
* Urls
*/
var OAUTH = 'https://www.arcgis.com/sharing/oauth2/token';
var GEOCODE =
'http://geocode.arcgis.com/arcgis/rest/services/World/GeocodeServer';
/**
* ESRI Query Parameter Defaults
*/
var CATEGORY = 'Address';
var CENTER = config.geocode.center;
var DISTANCE = 160 * 1000; // meters
/**
* Expose `router`
*/
var router = module.exports = express.Router();
/**
* Expose `encode` & `reverse`
*/
module.exports.encode = encode;
module.exports.reverse = reverse;
module.exports.suggest = suggest;
/**
* Geocode
*/
router.get('/:address', function(req, res) {
encode(req.params.address, function(err, addresses) {
if (err) {
console.error(err);
res.status(400).send(err);
} else {
var ll = addresses[0].feature.geometry;
res.status(200).send({
lng: ll.x,
lat: ll.y
});
}
});
});
/**
* Reverse
*/
router.get('/reverse/:coordinate', function(req, res) {
reverse(req.params.coordinate, function(err, address) {
if (err) {
console.error(err);
res.status(400).send(err);
} else {
res.status(200).send(address);
}
});
});
/**
* Suggest
*/
router.get('/suggest/:text', function(req, res) {
suggest(req.params.text, function(err, suggestions) {
if (err) {
console.error(err);
res.status(400).send(err);
} else {
res.status(200).send(suggestions);
}
});
});
/**
* Geocode
*/
function encode(address, callback) {
var text = '';
if (address.address) {
text = address.address + ', ' + address.city + ', ' + address.state + ' ' +
address.zip;
} else {
text = address;
}
auth(callback, function(token) {
superagent
.get(GEOCODE + '/find')
.query({
category: CATEGORY,
f: 'json',
text: text,
token: token
})
.end(function(err, res) {
if (err) {
callback(err, res);
} else {
var body = parseResponse(res, callback);
if (!body || !body.locations || body.locations.length === 0) {
callback(new Error('Location not found.'));
} else {
callback(null, body.locations);
}
}
});
});
}
/**
* Reverse geocode
*/
function reverse(ll, callback) {
var location = ll;
if (ll.lng) {
location = ll.lng + ',' + ll.lat;
} else if (ll.x) {
location = ll.x + ',' + ll.y;
} else if (ll[0]) {
location = ll[0] + ',' + ll[1];
}
auth(callback, function(token) {
superagent
.get(GEOCODE + '/reverseGeocode')
.query({
f: 'json',
location: location,
token: token
})
.end(function(err, res) {
if (err) {
callback(err, res);
} else {
var body = parseResponse(res, callback);
if (!body || !body.address) {
callback(new Error('Location not found.'));
} else {
var addr = body.address;
callback(null, {
address: addr.Address,
neighborhood: addr.Neighborhood,
city: addr.City,
county: addr.Subregion,
state: addr.Region,
zip: parseInt(addr.Postal, 10),
country: addr.CountryCode
});
}
}
});
});
}
/**
* Auto suggest
*/
function suggest(text, callback) {
auth(callback, function(token) {
superagent
.get(GEOCODE + '/suggest')
.query({
category: CATEGORY,
distance: DISTANCE,
f: 'json',
location: CENTER,
text: text,
token: token
})
.end(function(err, res) {
if (err) {
callback(err, res);
} else {
var body = parseResponse(res, callback);
callback(null, body.suggestions);
}
});
});
}
/**
* Auth?
*/
function auth(callback, next) {
generateAuthToken(function(err, token) {
if (err) {
callback(err);
} else {
next(token);
}
});
}
/**
* Parse
*/
function parseResponse(res, callback) {
try {
return JSON.parse(res.text);
} catch (e) {
callback(e);
}
}
/**
* Generate an auth token
*/
function generateAuthToken(callback) {
// If we're within 7 days of auth token expiration, generate a new one
if ((expires - expires_in / 2) < Date.now().valueOf()) {
superagent
.get(OAUTH)
.query({
client_id: config.arcgis_id,
client_secret: config.arcgis_secret,
expiration: expires_in,
grant_type: 'client_credentials'
})
.end(function(err, res) {
if (err || res.error || !res.ok) {
callback(err || res.error || res.text);
} else {
authToken = res.body.access_token;
// Set the expires time
expires = new Date();
expires.setSeconds(expires.getSeconds() + res.body.expires_in);
expires = expires.valueOf();
callback(null, authToken);
}
});
} else {
callback(null, authToken);
}
}
|
import Immutable from 'immutable';
import * as ActionType from '../../actions/auth/auth';
const defaultState = Immutable.fromJS({
loggedIn: false,
});
function authReducer(state = defaultState, action) {
const {
loggedIn,
} = action;
switch (action.type) {
case ActionType.VERIFIED_LOGIN:
return state.merge(Immutable.fromJS({ loggedIn }));
default:
return state;
}
}
export default authReducer;
|
var PassThrough = require('stream').PassThrough
describe('Object Streams', function () {
it('should be supported', function (done) {
var app = koala()
app.use(function* (next) {
var body = this.body = new PassThrough({
objectMode: true
})
body.write({
message: 'a'
})
body.write({
message: 'b'
})
body.end()
})
request(app.listen())
.get('/')
.expect(200)
.expect([{
message: 'a'
}, {
message: 'b'
}], done)
})
})
|
"use strict";
var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
return c > 3 && r && Object.defineProperty(target, key, r), r;
};
var __metadata = (this && this.__metadata) || function (k, v) {
if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v);
};
var core_1 = require("@angular/core");
var RemainingTimePipe = (function () {
function RemainingTimePipe() {
}
RemainingTimePipe.prototype.transform = function (date) {
var DaysInMonths = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31];
var Months = "JanFebMarAprMayJunJulAugSepOctNovDec";
var padding = "in ";
//Input pattern example: 2017-01-02T09:23:00.000Z
var input = date + "";
var splitted = input.split('T');
var today = new Date();
var year = +splitted[0].split('-')[0];
var month = +splitted[0].split('-')[1];
var day = +splitted[0].split('-')[2];
var splittedTime = splitted[1].split(':');
var hour = +splittedTime[0];
var minute = +splittedTime[1];
var second = +splittedTime[2].split('.')[0];
//Years
var currentYear = today.getFullYear();
var remaining = year - currentYear;
if (remaining < 0) {
return 'Started';
}
if (remaining > 0) {
if (remaining == 1) {
return padding + '1 year';
}
return padding + remaining + ' years';
}
//Months
var currentMonth = today.getMonth() + 1;
remaining = month - currentMonth;
if (remaining > 0) {
if (remaining == 1) {
//TODO Leap year
var currentDate = today.getDate();
var daysInPreviousMonth = (month != 0 ? DaysInMonths[month - 1] : DaysInMonths[11]);
var daysRemaining = (daysInPreviousMonth + day) - currentDate;
if (daysRemaining < 7) {
if (daysRemaining == 1) {
return padding + '1 day';
}
return padding + daysRemaining + ' days';
}
var weeksPassed = daysRemaining / 7;
weeksPassed = Math.round(weeksPassed);
if (weeksPassed == 1) {
return padding + '1 week';
}
return padding + weeksPassed + ' weeks';
}
return padding + remaining + ' months';
}
//Days
var currentDay = today.getDate();
var daysPassed = day - currentDay;
if (daysPassed > 0) {
if (daysPassed < 7) {
if (daysPassed == 1) {
return padding + '1 day';
}
return padding + daysPassed + ' days';
}
var weeksPassed = daysPassed / 7;
weeksPassed = Math.round(weeksPassed);
if (weeksPassed == 1) {
return padding + '1 week';
}
return padding + weeksPassed + ' weeks';
}
//Hours
var currentHour = today.getHours();
remaining = hour - currentHour;
if (remaining > 1) {
if (remaining == 2) {
return padding + '1 hour';
}
return padding + remaining + ' hours';
}
//Minutes
var currentMinute = today.getMinutes();
if (remaining == 1) {
remaining = 60 + minute - currentMinute;
}
else {
remaining = minute - currentMinute;
}
if (remaining > 0) {
if (remaining == 1) {
return padding + 'a minute';
}
return padding + remaining + ' minutes';
}
//Seconds
var currentSecond = today.getSeconds();
remaining = second - currentSecond;
if (remaining > 0) {
return padding + 'less than a minute';
}
return 'Started';
};
return RemainingTimePipe;
}());
RemainingTimePipe = __decorate([
core_1.Pipe({
name: 'remainingTimePipe'
}),
__metadata("design:paramtypes", [])
], RemainingTimePipe);
exports.RemainingTimePipe = RemainingTimePipe;
//# sourceMappingURL=remainingTimePipe.js.map
|
/* eslint-disable import/no-extraneous-dependencies,import/no-unresolved */
import React, { useState } from 'react';
import { Form } from 'react-bootstrap';
import { Typeahead } from 'react-bootstrap-typeahead';
/* example-start */
const options = [
'Warsaw',
'Kraków',
'Łódź',
'Wrocław',
'Poznań',
'Gdańsk',
'Szczecin',
'Bydgoszcz',
'Lublin',
'Katowice',
'Białystok',
'Gdynia',
'Częstochowa',
'Radom',
'Sosnowiec',
'Toruń',
'Kielce',
'Gliwice',
'Zabrze',
'Bytom',
'Olsztyn',
'Bielsko-Biała',
'Rzeszów',
'Ruda Śląska',
'Rybnik',
];
const FilteringExample = () => {
const [caseSensitive, setCaseSensitive] = useState(false);
const [ignoreDiacritics, setIgnoreDiacritics] = useState(true);
return (
<>
<Typeahead
caseSensitive={caseSensitive}
id="filtering-example"
ignoreDiacritics={ignoreDiacritics}
options={options}
placeholder="Cities in Poland..."
/>
<Form.Group>
<Form.Check
checked={caseSensitive}
id="case-sensitive-filtering"
label="Case-sensitive filtering"
onChange={(e) => setCaseSensitive(e.target.checked)}
type="checkbox"
/>
<Form.Check
checked={!ignoreDiacritics}
id="diacritical-marks"
label="Account for diacritical marks"
onChange={(e) => setIgnoreDiacritics(!e.target.checked)}
type="checkbox"
/>
</Form.Group>
</>
);
};
/* example-end */
export default FilteringExample;
|
export default {
hello : "hello"
};
|
TaskManager.module('ContentModule.List', function (List, App, Backbone) {
'use strict';
List.Controller = Marionette.Controller.extend({
initialize: function (options) {
var tasksList = App.request('taskList'),
listView = this.getView(tasksList);
if (options.region) {
this.region = options.region;
this.listenTo(listView, this.close);
this.region.show(listView);
}
},
getView: function (tasksList) {
return new List.View({collection: tasksList});
}
});
});
|
'use strict';
var Project = require('ember-cli/lib/models/project');
function MockProject() {
var root = process.cwd();
var pkg = {};
Project.apply(this, [root, pkg]);
}
MockProject.prototype.require = function(file) {
if (file === './server') {
return function() {
return {
listen: function() { arguments[arguments.length-1](); }
};
};
}
};
MockProject.prototype.config = function() {
return this._config || {
baseURL: '/',
locationType: 'auto'
};
};
MockProject.prototype.has = function(key) {
return (/server/.test(key));
};
MockProject.prototype.name = function() {
return 'mock-project';
};
MockProject.prototype.initializeAddons = Project.prototype.initializeAddons;
MockProject.prototype.buildAddonPackages = Project.prototype.buildAddonPackages;
MockProject.prototype.discoverAddons = Project.prototype.discoverAddons;
MockProject.prototype.addIfAddon = Project.prototype.addIfAddon;
MockProject.prototype.setupBowerDirectory = Project.prototype.setupBowerDirectory;
MockProject.prototype.dependencies = function() {
return [];
};
MockProject.prototype.isEmberCLIAddon = function() {
return false;
};
module.exports = MockProject;
|
import _curry2 from "./_curry2";
/**
* Accepts an object and build a function expecting a key to create a "pair" with the key
* and its value.
* @private
* @function
* @param {Object} obj
* @returns {Function}
*/
var _keyToPairIn = _curry2(function (obj, key) {
return [key, obj[key]];
});
export default _keyToPairIn;
|
'use strict';
/**
* The basic http module, used to create the server.
*
* @link http://nodejs.org/api/http.html
*/
alchemy.use('http', 'http');
/**
* This module contains utilities for handling and transforming file paths.
* Almost all these methods perform only string transformations.
* The file system is not consulted to check whether paths are valid.
*
* @link http://nodejs.org/api/path.html
*/
alchemy.use('path', 'path');
/**
* File I/O is provided by simple wrappers around standard POSIX functions.
*
* @link http://nodejs.org/api/fs.html
*/
alchemy.use('graceful-fs', 'fs');
/**
* Usefull utilities.
*
* @link http://nodejs.org/api/util.html
*/
alchemy.use('util', 'util');
/**
* The native mongodb library
*
* @link https://npmjs.org/package/mongodb
*/
alchemy.use('mongodb', 'mongodb');
/**
* The LESS interpreter.
*
* @link https://npmjs.org/package/less
*/
alchemy.use('less', 'less');
/**
* Hawkejs view engine
*
* @link https://npmjs.org/package/hawkejs
*/
alchemy.use('hawkejs', 'hawkejs');
alchemy.hawkejs = new Classes.Hawkejs.Hawkejs;
/**
* The function to detect when everything is too busy
*/
alchemy.toobusy = alchemy.use('toobusy-js', 'toobusy');
// If the config is a number, use that as the lag threshold
if (typeof alchemy.settings.toobusy === 'number') {
alchemy.toobusy.maxLag(alchemy.settings.toobusy);
}
/**
* Load Sputnik, the stage-based launcher
*/
alchemy.sputnik = new (alchemy.use('sputnik', 'sputnik'))();
/**
* Real-time apps made cross-browser & easy with a WebSocket-like API.
*
* @link https://npmjs.org/package/socket.io
*/
alchemy.use('socket.io', 'io');
/**
* Recursively mkdir, like `mkdir -p`.
* This is a requirement fetched from express
*
* @link https://npmjs.org/package/mkdirp
*/
alchemy.use('mkdirp', 'mkdirp');
/**
* Base useragent library
*
* @link https://npmjs.org/package/useragent
*/
alchemy.use('useragent');
/**
* Enable the `satisfies` method in the `useragent` library
*
* @link https://www.npmjs.com/package/useragent#adding-more-features-to-the-useragent
*/
require('useragent/features');
|
/**
* Copyright (c) 2015, Alexander Orzechowski.
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
/**
* Currently in beta stage. Changes can and will be made to the core mechanic
* making this not backwards compatible.
*
* Github: https://github.com/Need4Speed402/tessellator
*/
Tessellator.Model.prototype.drawObject = Tessellator.Model.prototype.add;
|
var crypto = require('crypto');
var lob = require('lob-enc')
var hashname = require('hashname');
var log = require("./log")("Handshake")
module.exports = {
bootstrap : handshake_bootstrap,
validate : handshake_validate,
from : handshake_from,
types : handshake_types,
collect : handshake_collect
};
var hcache = {}
setInterval(function(){hcache = {}}, 60 * 1000)
/**
* collect incoming handshakes to accept them
* @param {object} id
* @param {handshake} handshake
* @param {pipe} pipe
* @param {Buffer} message
*/
function handshake_collect(mesh, id, handshake, pipe, message)
{
handshake = handshake_bootstrap(handshake);
if (!handshake)
return false;
var valid = handshake_validate(id,handshake, message, mesh);
if (!valid)
return false;
// get all from cache w/ matching at, by type
var types = handshake_types(handshake, id);
// bail unless we have a link
if(!types.link)
{
log.debug('handshakes w/ no link yet',id,types);
return false;
}
// build a from json container
var from = handshake_from(handshake, pipe, types.link)
// if we already linked this hashname, just update w/ the new info
if(mesh.index[from.hashname])
{
log.debug('refresh link handshake')
from.sync = false; // tell .link to not auto-sync!
return mesh.link(from);
} else {
}
log.debug('untrusted hashname',from);
from.received = {packet:types.link._message, pipe:pipe} // optimization hints as link args
from.handshake = types; // include all handshakes
if(mesh.accept)
mesh.accept(from);
return false;
}
function handshake_bootstrap(handshake){
// default an at for bare key handshakes if not given
if(typeof handshake.json.at === 'undefined')
handshake.json.at = Date.now();
// verify at
if(typeof handshake.json.at != 'number' || handshake.json.at <= 0)
{
log.debug('invalid handshake at',handshake.json);
return false;
}
// default the handshake type
if(typeof handshake.json.type != 'string')
handshake.json.type = 'link';
// upvert deprecated key to link type
if(handshake.json.type == 'key')
{
// map only csid keys into attachment header
var json = {};
hashname.ids(handshake.json).forEach(function(csid){
if(handshake.json[csid] === true)
handshake.json.csid = csid; // cruft
json[csid] = handshake.json[csid];
});
if(message)
json[message.head.toString('hex')] = true;
var attach = lob.encode(json, handshake.body);
handshake.json.type = 'link';
handshake.body = attach;
}
return handshake
}
function handshake_validate(id,handshake, message, mesh){
if(handshake.json.type == 'link')
{
// if it came from an encrypted message
if(message)
{
// make sure the link csid matches the message csid
handshake.json.csid = message.head.toString('hex');
// stash inside the handshake, can be used later to create the exchange immediately
handshake._message = message;
}
var attach = lob.decode(handshake.body);
if(!attach)
{
log.debug('invalid link handshake attachment',handshake.body);
return false;
}
// make sure key info is at least correct
var keys = {};
keys[handshake.json.csid] = attach.body;
var csid = hashname.match(mesh.keys, keys, null, attach.json);
if(handshake.json.csid != csid)
{
log.debug('invalid key handshake, unsupported csid',attach.json, keys);
return false;
}
handshake.json.hashname = hashname.fromKeys(keys, attach.json);
if(!handshake.json.hashname)
{
log.debug('invalid key handshake, no hashname',attach.json, keys);
return false;
}
// hashname is valid now, so stash key bytes in handshake
handshake.body = attach.body;
}
// add it to the cache
hcache[id] = (hcache[id] || [] ).concat([handshake]);
return true;
}
function handshake_types (handshake, id){
var types = {}
hcache[id].forEach(function(hs){
if(hs.json.at === handshake.json.at)
types[hs.json.type] = hs;
});
return types;
}
function handshake_from (handshake, pipe, link){
return {
paths : (pipe.path) ? [pipe.path] : [],
hashname : link.json.hashname,
csid : link.json.csid,
key : link.body
};
}
|
'use strict';
/* https://github.com/angular/protractor/blob/master/docs/toc.md */
describe('my app', function() {
browser.get('index.html');
it('should automatically redirect to /home when location hash/fragment is empty', function() {
expect(browser.getLocationAbsUrl()).toMatch("/home");
});
describe('view1', function() {
beforeEach(function() {
browser.get('index.html#/home');
});
it('should render home when user navigates to /home', function() {
expect(element.all(by.css('[ng-view] p')).first().getText()).
toMatch(/partial for view 1/);
});
});
describe('view2', function() {
beforeEach(function() {
browser.get('index.html#/view2');
});
it('should render view2 when user navigates to /view2', function() {
expect(element.all(by.css('[ng-view] p')).first().getText()).
toMatch(/partial for view 2/);
});
});
});
|
function RenderPassManager(renderer)
{
// not implemented yet
throw "Not implemented";
var mRenderPasses = [];
return this;
}
RenderPassManager.prototype.addRenderPass = function(renderPass)
{
mRenderPasses.push(renderPass);
};
RenderPassManager.prototype.render = function()
{
for(var renderPass in mRenderPasses) {
renderPass.sort();
renderPass.render(renderer);
renderPass.clear();
}
};
|
#!/usr/bin/env node
var path = require('path');
var fs = require('fs');
var optimist = require('optimist');
var prompt = require('prompt');
var efs = require('efs');
var encext = require('./index');
var defaultAlgorithm = 'aes-128-cbc';
var argv = optimist
.usage('usage: encext [-r] [-a algorithm] [file ...]')
.describe('r', 'recursively encrypt supported files')
.boolean('r')
.alias('r', 'recursive')
.default('r', false)
.describe('a', 'encryption algorithm')
.string('a')
.alias('a', 'algorithm')
.default('a', defaultAlgorithm)
.argv;
if (argv.help) {
optimist.showHelp();
}
var pwdPrompt = {
name: 'password',
description: 'Please enter the encryption password',
required: true,
hidden: true
};
prompt.message = 'encext';
prompt.colors = false;
prompt.start();
prompt.get(pwdPrompt, function(err, result) {
if (err) {
console.error('[ERROR]', err);
process.exit(1);
}
efs = efs.init(argv.algorithm, result.password);
argv._.forEach(processPath);
});
function processPath(fspath) {
fs.stat(fspath, onStat);
function onStat(err, stats) {
if (err) { return exit(err) }
if (stats.isDirectory() && argv.recursive) {
fs.readdir(fspath, onReaddir);
} else if (stats.isFile() && encext.isSupported(fspath)) {
encrypt(fspath);
}
}
function onReaddir(err, fspaths) {
if (err) { return exit(err) }
fspaths.forEach(function(p) {
processPath(path.join(fspath, p));
});
}
}
function encrypt(fspath) {
var encpath = fspath + '_enc';
var writeStream = efs.createWriteStream(encpath);
writeStream.on('error', exit);
var readStream = fs.createReadStream(fspath);
readStream.on('error', exit);
readStream.on('end', function() {
console.info(fspath, 'encrypted and written to', encpath);
});
readStream.pipe(writeStream);
}
function exit(err) {
console.error(err);
process.exit(1);
}
|
export function wedgeYZ(a, b) {
return a.y * b.z - a.z * b.y;
}
export function wedgeZX(a, b) {
return a.z * b.x - a.x * b.z;
}
export function wedgeXY(a, b) {
return a.x * b.y - a.y * b.x;
}
|
var scroungejs = require('scroungejs'),
startutils = require('./startutil');
startutils.createFileIfNotExist({
pathSrc : './test/indexSrc.html',
pathFin : './test/index.html'
}, function (err, res) {
if (err) return console.log(err);
scroungejs.build({
inputPath : [
'./test/testbuildSrc',
'./node_modules',
'./bttnsys.js'
],
outputPath : './test/testbuildFin',
isRecursive : true,
isSourcePathUnique : true,
isCompressed : false,
isConcatenated : false,
basepage : './test/index.html'
}, function (err, res) {
return (err) ? console.log(err) : console.log('finished!');
});
});
|
var Struct = ( function()
{
return function ( members )
{
var mode = "default";
var ctor = function( values )
{
if ( mode === "new" )
{
mode = "void";
return new Struct();
}
if ( mode === "void" )
return;
mode = "new";
var instance = Struct();
mode = "default";
extend( instance, members, values || {} );
return instance;
};
var Struct = function() {
return ctor.apply( undefined, arguments );
};
return Struct;
};
function extend( instance, members, values )
{
var pending = [{
src: values,
tmpl: members,
dest: instance
}];
while ( pending.length )
{
var task = pending.shift();
if ( task.array )
{
var i = 0, len = task.array.length;
for ( ; i < len; i++ )
{
switch ( typeOf( task.array[ i ] ) )
{
case "object":
var template = task.array[ i ];
task.array[ i ] = {};
pending.push({
tmpl: template,
dest: task.array[ i ]
});
break;
case "array":
task.array[ i ] = task.array[ i ].slice( 0 );
pending.push({
array: task.array[ i ]
});
break;
}
}
}
else
{
for ( var prop in task.tmpl )
{
if ( task.src[ prop ] !== undefined )
task.dest[ prop ] = task.src[ prop ];
else
{
switch ( typeOf( task.tmpl[ prop ] ) )
{
case "object":
task.dest[ prop ] = {};
pending.push({
tmpl: task.tmpl[ prop ],
dest: task.dest[ prop ]
});
break;
case "array":
task.dest[ prop ] = task.tmpl[ prop ].slice( 0 );
pending.push({
array: task.dest[ prop ]
});
break;
default:
task.dest[ prop ] = task.tmpl[ prop ];
break;
}
}
}
}
}
}
} () );
|
var utils = require('./utils')
, request = require('request')
;
module.exports = {
fetchGithubInfo: function(email, cb) {
var githubProfile = {};
var api_call = "https://api.github.com/search/users?q="+email+"%20in:email";
var options = { url: api_call, headers: { 'User-Agent': 'Blogdown' } };
console.log("Calling "+api_call);
request(options, function(err, res, body) {
if(err) return cb(err);
res = JSON.parse(body);
if(res.total_count==1)
githubProfile = res.items[0];
cb(null, githubProfile);
});
},
fetchGravatarProfile: function(email, cb) {
var gravatarProfile = {};
var hash = utils.getHash(email);
var api_call = "http://en.gravatar.com/"+hash+".json";
console.log("Calling "+api_call);
var options = { url: api_call, headers: { 'User-Agent': 'Blogdown' } };
request(options, function(err, res, body) {
if(err) return cb(err);
try {
res = JSON.parse(body);
} catch(e) {
console.error("fetchGravatarProfile: Couldn't parse response JSON ", body, e);
return cb(e);
}
if(res.entry && res.entry.length > 0)
gravatarProfile = res.entry[0];
return cb(null, gravatarProfile);
});
}
};
|
module.exports = FormButtonsDirective;
function FormButtonsDirective () {
return {
restrict: 'AE',
replace: true,
scope: {
submitClick: '&submitClick',
cancelClick: '&cancelClick'
},
templateUrl: '/src/utils/views/formButtons.tmpl.html',
link: function (scope, elem) {
angular.element(elem[0].getElementsByClassName('form-button-submit')).on('click', function () {
scope.submitClick();
});
angular.element(elem[0].getElementsByClassName('form-button-cancel')).on('click', function () {
scope.cancelClick();
});
}
};
}
|
$context.section('Простое связывание', 'Иерархическое связывание с данными с использованием простых и составных ключей');
//= require data-basic
$context.section('Форматирование', 'Механизм одностороннего связывания (one-way-binding)');
//= require data-format
$context.section('Настройка', 'Управление изменением виджета при обновлении данных');
//= require data-binding
$context.section('Динамическое связывание', 'Управление коллекцией элементов виджета через источник данных');
//= require data-dynamic
$context.section('Общие данные');
//= require data-share
$context.section('"Грязные" данные', 'Уведомление родительских источников данных о том, что значение изменилось');
//= require data-dirty
|
import React from 'react';
import './skills.scss';
export default () => {
return (
<section className="skills-section">
<svg className="bigTriangleColor separator-skills" width="100%" height="100" viewBox="0 0 100 102" preserveAspectRatio="none">
<path d="M0 0 L0 100 L70 0 L100 100 L100 0 Z" />
</svg>
<h2 className="skills-header">Skills</h2>
<p className="skills tlt">
Javascript/ES6 React Redux Node Express MongoDB GraphQL REST Next.js Mocha Jest JSS PostCSS SCSS LESS AWS nginx jQuery Webpack Rollup UI/Design
</p>
<button className="button button--wayra button--inverted skills-btn">
View My <i className="fa fa-github skills-github"></i><a className="skills-btn-a" href="https://www.github.com/musicbender" target="_blank"></a>
</button>
</section>
);
}
|
import axios from 'axios';
export default axios.create({
baseURL: 'http://localhost:9000/v1/'
});
|
/*
* THIS FILE IS AUTO GENERATED FROM 'lib/lex/lexer.kep'
* DO NOT EDIT
*/
define(["require", "exports", "bennu/parse", "bennu/lang", "nu-stream/stream", "ecma-ast/token", "ecma-ast/position",
"./boolean_lexer", "./comment_lexer", "./identifier_lexer", "./line_terminator_lexer", "./null_lexer",
"./number_lexer", "./punctuator_lexer", "./reserved_word_lexer", "./string_lexer", "./whitespace_lexer",
"./regular_expression_lexer"
], (function(require, exports, parse, __o, __o0, lexToken, __o1, __o2, comment_lexer, __o3, line_terminator_lexer,
__o4, __o5, __o6, __o7, __o8, whitespace_lexer, __o9) {
"use strict";
var lexer, lexStream, lex, always = parse["always"],
attempt = parse["attempt"],
binds = parse["binds"],
choice = parse["choice"],
eof = parse["eof"],
getPosition = parse["getPosition"],
modifyState = parse["modifyState"],
getState = parse["getState"],
enumeration = parse["enumeration"],
next = parse["next"],
many = parse["many"],
runState = parse["runState"],
never = parse["never"],
ParserState = parse["ParserState"],
then = __o["then"],
streamFrom = __o0["from"],
SourceLocation = __o1["SourceLocation"],
SourcePosition = __o1["SourcePosition"],
booleanLiteral = __o2["booleanLiteral"],
identifier = __o3["identifier"],
nullLiteral = __o4["nullLiteral"],
numericLiteral = __o5["numericLiteral"],
punctuator = __o6["punctuator"],
reservedWord = __o7["reservedWord"],
stringLiteral = __o8["stringLiteral"],
regularExpressionLiteral = __o9["regularExpressionLiteral"],
type, type0, type1, type2, type3, p, type4, type5, type6, type7, p0, type8, p1, type9, p2, consume = (
function(tok, self) {
switch (tok.type) {
case "Comment":
case "Whitespace":
case "LineTerminator":
return self;
default:
return tok;
}
}),
isRegExpCtx = (function(prev) {
if ((!prev)) return true;
switch (prev.type) {
case "Keyword":
case "Punctuator":
return true;
}
return false;
}),
enterRegExpCtx = getState.chain((function(prev) {
return (isRegExpCtx(prev) ? always() : never());
})),
literal = choice(((type = lexToken.StringToken.create), stringLiteral.map((function(x) {
return [type, x];
}))), ((type0 = lexToken.BooleanToken.create), booleanLiteral.map((function(x) {
return [type0, x];
}))), ((type1 = lexToken.NullToken.create), nullLiteral.map((function(x) {
return [type1, x];
}))), ((type2 = lexToken.NumberToken.create), numericLiteral.map((function(x) {
return [type2, x];
}))), ((type3 = lexToken.RegularExpressionToken.create), (p = next(enterRegExpCtx,
regularExpressionLiteral)), p.map((function(x) {
return [type3, x];
})))),
token = choice(attempt(((type4 = lexToken.IdentifierToken), identifier.map((function(x) {
return [type4, x];
})))), literal, ((type5 = lexToken.KeywordToken), reservedWord.map((function(x) {
return [type5, x];
}))), ((type6 = lexToken.PunctuatorToken), punctuator.map((function(x) {
return [type6, x];
})))),
inputElement = choice(((type7 = lexToken.CommentToken), (p0 = comment_lexer.comment), p0.map((function(
x) {
return [type7, x];
}))), ((type8 = lexToken.WhitespaceToken), (p1 = whitespace_lexer.whitespace), p1.map((function(x) {
return [type8, x];
}))), ((type9 = lexToken.LineTerminatorToken), (p2 = line_terminator_lexer.lineTerminator), p2.map(
(function(x) {
return [type9, x];
}))), token);
(lexer = then(many(binds(enumeration(getPosition, inputElement, getPosition), (function(start, __o10, end) {
var type10 = __o10[0],
value = __o10[1];
return always(new(type10)(new(SourceLocation)(start, end, (start.file || end.file)),
value));
}))
.chain((function(tok) {
return next(modifyState(consume.bind(null, tok)), always(tok));
}))), eof));
(lexStream = (function(s, file) {
return runState(lexer, new(ParserState)(s, new(SourcePosition)(1, 0, file), null));
}));
var y = lexStream;
(lex = (function(z) {
return y(streamFrom(z));
}));
(exports["lexer"] = lexer);
(exports["lexStream"] = lexStream);
(exports["lex"] = lex);
}));
|
/* global describe, it, require */
'use strict';
// MODULES //
var // Expectation library:
chai = require( 'chai' ),
// Deep close to:
deepCloseTo = require( './utils/deepcloseto.js' ),
// Module to be tested:
log10 = require( './../lib/array.js' );
// VARIABLES //
var expect = chai.expect,
assert = chai.assert;
// TESTS //
describe( 'array log10', function tests() {
it( 'should export a function', function test() {
expect( log10 ).to.be.a( 'function' );
});
it( 'should compute the base-10 logarithm', function test() {
var data, actual, expected;
data = [
Math.pow( 10, 4 ),
Math.pow( 10, 6 ),
Math.pow( 10, 9 ),
Math.pow( 10, 15 ),
Math.pow( 10, 10 ),
Math.pow( 10, 25 )
];
actual = new Array( data.length );
actual = log10( actual, data );
expected = [ 4, 6, 9, 15, 10, 25 ];
assert.isTrue( deepCloseTo( actual, expected, 1e-7 ) );
});
it( 'should return an empty array if provided an empty array', function test() {
assert.deepEqual( log10( [], [] ), [] );
});
it( 'should handle non-numeric values by setting the element to NaN', function test() {
var data, actual, expected;
data = [ true, null, [], {} ];
actual = new Array( data.length );
actual = log10( actual, data );
expected = [ NaN, NaN, NaN, NaN ];
assert.deepEqual( actual, expected );
});
});
|
match x:
| it?(): true
|
import {Component} from 'react'
export class Greeter {
constructor (message) {
this.greeting = message;
}
greetFrom (...names) {
let suffix = names.reduce((s, n) => s + ", " + n.toUpperCase());
return "Hello, " + this.greeting + " from " + suffix;
}
greetNTimes ({name, times}) {
let greeting = this.greetFrom(name);
for (let i = 0; i < times; i++) {
console.log(greeting)
}
}
}
new Greeter("foo").greetNTimes({name: "Webstorm", times: 3})
function foo (x, y, z) {
var i = 0;
var x = {0: "zero", 1: "one"};
var a = [0, 1, 2];
var foo = function () {
}
var asyncFoo = async (x, y, z) => {
}
var v = x.map(s => s.length);
if (!i > 10) {
for (var j = 0; j < 10; j++) {
switch (j) {
case 0:
value = "zero";
break;
case 1:
value = "one";
break;
}
var c = j > 5 ? "GT 5" : "LE 5";
}
} else {
var j = 0;
try {
while (j < 10) {
if (i == j || j > 5) {
a[j] = i + j * 12;
}
i = (j << 2) & 4;
j++;
}
do {
j--;
} while (j > 0)
} catch (e) {
alert("Failure: " + e.message);
} finally {
reset(a, i);
}
}
}
|
import { stringify } from 'qs'
import _request from '@/utils/request'
import mini from '@/utils/mini'
import env from '@/config/env'
// import { modelApis, commonParams } from './model'
// import { version } from '../package.json'
let apiBaseUrl
apiBaseUrl = `${env.apiBaseUrl}`
const regHttp = /^https?/i
const isMock = true;
// const regMock = /^mock?/i
function compact(obj) {
for (const key in obj) {
if (!obj[key]) {
delete obj[key]
}
}
return obj
}
function request(url, options, success, fail) {
const originUrl = regHttp.test(url) ? url : `${apiBaseUrl}${url}`
return _request(originUrl, compact(options), success, fail)
}
/**
* API 命名规则
* - 使用 camelCase 命名格式(小驼峰命名)
* - 命名尽量对应 RESTful 风格,`${动作}${资源}`
* - 假数据增加 fake 前缀
* - 便捷易用大于规则,程序是给人看的
*/
// api 列表
const modelApis = {
// 初始化配置
test: 'https://easy-mock.com/mock/5aa79bf26701e17a67bde1d7/',
getConfig: '/common/initconfig',
getWxSign: '/common/getwxsign',
// 积分兑换
getPointIndex: '/point/index',
getPointList: '/point/skulist',
getPointDetail: '/point/iteminfo',
getPointDetaiMore: '/product/productdetail',
getRList: '/point/recommenditems',
// 专题
getPointTopicInfo: '/point/topicinfo',
getPointTopicList: '/point/topicbuskulist',
// 主站专题
getTopicInfo: '/product/topicskusinfo',
getTopicList: '/product/topicskulist',
// 个人中心
getProfile: '/user/usercenter',
// 拼团相关
getCoupleList: '/product/coupleskulist',
getCoupleDetail: '/product/coupleskudetail',
getMerchantList: '/merchant/coupleskulist',
coupleOrderInit: 'POST /order/coupleorderinit',
coupleOrderList: '/user/usercouplelist',
coupleOrderDetail: '/user/usercoupleorderdetail',
coupleUserList: '/market/pinactivitiesuserlist', // 分享页拼团头像列表
coupleShareDetail: '/user/coupleactivitiedetail', // 分享详情
// 首页
getIndex: '/common/index',
getIndexNew: '/common/index_v1',
getHotSearch: '/common/hotsearchsug',
// 主流程
orderInit: 'POST /order/orderinit',
orderSubmit: 'POST /order/submitorder',
orderPay: 'POST /order/orderpay',
orderPayConfirm: '/order/orderpayconfirm', // 确认支付状态
getUserOrders: '/order/getuserorders', // 订单列表
getNeedCommentOrders: '/order/waitcommentlist', // 待评论
getUserRefundorders: '/order/userrefundorder', // 退款
getUserServiceOrders: '/order/userserviceorders', // 售后
orderCancel: 'POST /order/cancelorder', // 取消订单
orderDetail: '/order/orderdetail',
confirmReceived: 'POST /order/userorderconfirm', // 确认收货
orderComplaint: 'POST /refund/complaint', // 订单申诉
// 积分订单相关
pointOrderInit: 'POST /tradecenter/pointorderpreview',
pointOrderSubmit: 'POST /tradecenter/pointordersubmit',
pointOrderCancel: 'POST /tradecenter/ordercancel',
pointOrderList: '/tradecenter/orderlist',
pointOrderDetail: '/tradecenter/orderinfo',
pointOrderSuccess: '/tradecenter/ordersuccess',
// 退款相关
refundInit: '/refund/init',
refundDetail: '/refund/detail',
refundApply: 'POST /refund/apply',
// 登录注销
login: 'POST /user/login',
logout: 'POST /user/logout',
// 地址管理
addressList: '/user/addresslist',
addAddress: 'POST /user/addaddress',
updateAddress: 'POST /user/updateaddress',
setDefaultAddress: 'POST /user/setdefaultaddress',
deleteAddress: 'POST /user/deleteaddress',
provinceList: '/nation/provincelist',
cityList: '/nation/citylist',
districtList: '/nation/districtlist',
// 查看物流
getDelivery: '/order/deliverymessage',
// 获取七牛 token
getQiniuToken: '/common/qiniutoken',
}
// 仅限本地调试支持
// if (__DEV__ && env.mock) {
if (__DEV__ && isMock) {
apiBaseUrl = `${env.apiMockUrl}`
// Object.assign(modelApis, require('../mock'))
}
// 线上代理
if (__DEV__ && env.proxy) {
const proxyUrl = '/proxy'
apiBaseUrl = `${env.origin}${proxyUrl}`
}
const {
width,
height,
} = window.screen
// 公共参数
const commonParams = {
uuid: '', // 用户唯一标志
udid: '', // 设备唯一标志
device: '', // 设备
net: '', // 网络
uid: '',
token: '',
timestamp: '', // 时间
channel: 'h5', // 渠道
spm: 'h5',
v: env.version, // 系统版本
terminal: env.terminal, // 终端
swidth: width, // 屏幕宽度 分辨率
sheight: height, // 屏幕高度
location: '', // 地理位置
zoneId: 857, // 必须
}
// console.log(Object.keys(modelApis))
const apiList = Object.keys(modelApis).reduce((api, key) => {
const val = modelApis[key]
const [url, methodType = 'GET'] = val.split(/\s+/).reverse()
const method = methodType.toUpperCase()
// let originUrl = regHttp.test(url) ? url : `${env.apiBaseUrl}${url}`;
// NOTE: headers 在此处设置?
// if (__DEV__ && regLocalMock.test(url)) {
// api[key] = function postRequest(params, success, fail) {
// const res = require(`../${url}.json`)
// mini.hideLoading()
// res.errno === 0 ? success(res) : fail(res)
// }
// return api
// }
switch (method) {
case 'POST':
// originUrl = `${originUrl}`;
api[key] = function postRequest(params, success, fail) {
return request(url, {
headers: {
// Accept: 'application/json',
// 我们的 post 请求,使用的这个,不是 application/json
// 'Content-Type': 'application/x-www-form-urlencoded',
},
method,
data: compact(Object.assign({}, getCommonParams(), params)),
}, success, fail)
}
break
case 'GET':
default:
api[key] = function getRequest(params, success, fail) {
params = compact(Object.assign({}, getCommonParams(), params))
let query = stringify(params)
if (query) query = `?${query}`
return request(`${url}${query}`, {}, success, fail)
}
break
}
return api
}, {})
function setCommonParams(params) {
return Object.assign(commonParams, params)
}
function getCommonParams(key) {
return key ? commonParams[key] : {
// ...commonParams,
}
}
apiList.getCommonParams = getCommonParams
apiList.setCommonParams = setCommonParams
// console.log(apiList)
export default apiList
|
version https://git-lfs.github.com/spec/v1
oid sha256:f5c198d5eef0ca0f41f87746ef8fefe819a727fcd59a6477c76b94b55d27128d
size 1730
|
import React from 'react';
import { TypeChooser } from 'react-stockcharts/lib/helper'
import Chart from './Chart'
import { getData } from './util';
class ChartComponent extends React.Component {
componentDidMount () {
getData().then(data => {
this.setState({ data})
})
}
render () {
if (this.state == null) {
return <div>
Loading...
</div>
}
return (
<Chart type='hybrid' data={this.state.data} />
)
}
}
export default ChartComponent;
|
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
$(document).ready(function(){
var div = document.getElementById('content');
var div1 = document.getElementById('leftbox');
div.style.height = document.body.clientHeight + 'px';
div1.style.height = div.style.height;
var contentToRemove = document.querySelectorAll(".collapsed-navbox");
$(contentToRemove).hide();
var oritop = -100;
$(window).scroll(function() {
var scrollt = window.scrollY;
var elm = $("#leftbox");
if(oritop < 0) {
oritop= elm.offset().top;
}
if(scrollt >= oritop) {
elm.css({"position": "fixed", "top": 0, "left": 0});
}
else {
elm.css("position", "static");
}
});
/*$(window).resize(function() {
var wi = $(window).width();
$("p.testp").text('Screen width is currently: ' + wi + 'px.');
});
$(window).resize(function() {
var wi = $(window).width();
if (wi <= 767){
var contentToRemove = document.querySelectorAll(".fullscreen-navbox");
$(contentToRemove).hide();
var contentToRemove = document.querySelectorAll(".collapsed-navbox");
$(contentToRemove).show();
$("#leftbox").css("width","30px");
$("#content").css("width","90%");
}else if (wi > 800){
var contentToRemove = document.querySelectorAll(".fullscreen-navbox");
$(contentToRemove).show();
var contentToRemove = document.querySelectorAll(".collapsed-navbox");
$(contentToRemove).hide();
$("#leftbox").css("width","15%");
$("#content").css("width","85%");
}
});*/
});
|
/* Copyright (C) 2011-2014 Mattias Ekendahl. Used under MIT license, see full details at https://github.com/developedbyme/dbm/blob/master/LICENSE.txt */
dbm.registerClass("dbm.thirdparty.facebook.constants.EventTypes", null, function(objectFunctions, staticFunctions, ClassReference) {
//console.log("dbm.thirdparty.facebook.constants.EventTypes");
//REFERENCE: http://developers.facebook.com/docs/reference/javascript/FB.Event.subscribe/
var EventTypes = dbm.importClass("dbm.thirdparty.facebook.constants.EventTypes");
staticFunctions.AUTH_LOGIN = "auth.login";
staticFunctions.AUTH_RESPONSE_CHANGE = "auth.authResponseChange";
staticFunctions.AUTH_STATUS_CHANGE = "auth.statusChange";
staticFunctions.AUTH_LOGOUT = "auth.logout";
staticFunctions.AUTH_PROMPT = "auth.prompt";
staticFunctions.XFBML_RENDER = "xfbml.render";
staticFunctions.EDGE_CREATE = "edge.create";
staticFunctions.EDGE_REMOVE = "edge.remove";
staticFunctions.COMMENT_CREATE = "comment.create";
staticFunctions.COMMENT_REMOVE = "comment.remove";
staticFunctions.MESSAGE_SEND = "message.send";
});
|
'use strict';
// This is the webpack config used for JS unit tests
const Encore = require('@symfony/webpack-encore');
const encoreConfigure = require('./webpack.base.config');
const webpackCustomize = require('./webpack.customize');
// Initialize Encore before requiring the .config file
Encore.configureRuntimeEnvironment('dev-server');
encoreConfigure(Encore);
const webpack = require('webpack');
const merge = require('webpack-merge');
const ManifestPlugin = require('@symfony/webpack-encore/lib/webpack/webpack-manifest-plugin');
const baseWebpackConfig = Encore.getWebpackConfig();
webpackCustomize(baseWebpackConfig);
const webpackConfig = merge(baseWebpackConfig, {
// use inline sourcemap for karma-sourcemap-loader
devtool: '#inline-source-map',
resolveLoader: {
alias: {
// necessary to to make lang="scss" work in test when using vue-loader's ?inject option
// see discussion at https://github.com/vuejs/vue-loader/issues/724
'scss-loader': 'sass-loader'
}
},
plugins: [
new webpack.DefinePlugin({
'process.env': {
NODE_ENV: '"testing"'
}
})
]
});
// no need for app entry during tests
delete webpackConfig.entry;
// Set writeToFileEmit option of the ManifestPlugin to false
for (const plugin of webpackConfig.plugins) {
if ((plugin instanceof ManifestPlugin) && plugin.opts) {
plugin.opts.writeToFileEmit = false;
}
}
module.exports = webpackConfig;
|
// Release 1: User Stories
// As a user, I want to be able to create a new grocery list. After that, I need to be able to add an item with a quantity to the list, remove an item, and update the quantities if they change. I need a way to print out the list in a format that is very readable.
// Release 2: Pseudocode
// input: string of items separated by spaces
// output: object
// create a new object as new variable
// convert string to array (split)
// take each item in array and add to object as a property with a default quantity/value of 1
//
// Release 3: Initial Solution
// function to create list
// var foodList = ("salmon iceCream macAndCheese")
// var groceryList = {};
// var createList = function(foodList) {
// var foodArray = foodList.split(" ");
// for (var i = 0; i < foodArray.length; i++){
// groceryList[(foodArray[i])] = 1;
// }
// console.log(groceryList);
// }
// createList(foodList)
// // function to add item to list
// var addItem = function(newItem) {
// groceryList[newItem] = 1;
// console.log(groceryList);
// }
// addItem("peas")
// // function to remove item from list
// var removeItem = function(itemToLose) {
// delete groceryList[itemToLose];
// console.log(groceryList);
// }
// removeItem("peas")
// // function to update quantity
// var updateList = function(updateItem, newQuantity) {
// groceryList[updateItem] = newQuantity;
// console.log(groceryList);
// }
// updateList("macAndCheese", 5)
// // function to display list
// var displayList = function(groceryList) {
// for (food in groceryList) {
// console.log(food + ": " + groceryList[food]);
// }
// }
// displayList(groceryList)
// Release 4: Refactor
// function to create list
var groceryList = {};
var displayList = function(groceryList) {
console.log("Your Grocery List:")
for (food in groceryList) {
console.log(food + ": " + groceryList[food]);
}
console.log("----------")
}
var createList = function(foodList) {
var foodArray = foodList.split(" ");
for (var i = 0; i < foodArray.length; i++){
groceryList[(foodArray[i])] = 1;
}
displayList(groceryList);
}
var addItem = function(newItem) {
groceryList[newItem] = 1;
displayList(groceryList);
}
var removeItem = function(itemToLose) {
delete groceryList[itemToLose];
displayList(groceryList);
}
var updateList = function(updateItem, newQuantity) {
groceryList[updateItem] = newQuantity;
displayList(groceryList);
}
var foodList = ("funfettiMix bananas chocolateCoveredAlmonds")
createList(foodList)
addItem("peaches")
updateList("peaches", 20)
removeItem("bananas")
// Release 5: Reflect
// What concepts did you solidify in working on this challenge? (reviewing the passing of information, objects, constructors, etc.)
// I solidified accessing different properties in an object. I was able to add strings from an array into an empty object and set their default value. To change those values I knew I needed to access the property using bracket notation, and change the value it was = to.
// What was the most difficult part of this challenge?
// I forgot I needed to convert the string to an array, but once I did that with the .split(" ") method, all of the strings were easily accessible to add to the new object.
// Did an array or object make more sense to use and why?
// This was weirdly WAY easier with JavaScript than it was initially with Ruby (probably because we were on our second week of Ruby at this point!). It was so easy to add each string from an array into the object as a property and set it's default. Accessing these properties to update or delete was made easier by using bracket notation. Instead of complicated hash methods and having to convert strings to arrays to hashes, all I had to do was split the string and add each string to the object with a default value.
|
var fs = require('fs')
var d3 = require('d3')
var request = require('request')
var cheerio = require('cheerio')
var queue = require('queue-async')
var _ = require('underscore')
var glob = require("glob")
var games = []
glob.sync(__dirname + "/raw-series/*").forEach(scrape)
function scrape(dir, i){
var series = dir.split('/raw-series/')[1]
process.stdout.write("parsing " + i + " " + series + "\r")
var html = fs.readFileSync(dir, 'utf-8')
var $ = cheerio.load(html)
$('a').each(function(i){
var str = $(this).text()
var href = $(this).attr('href')
if (str == 'box scores' || !~href.indexOf('/boxscores/') || i % 2) return
games.push({series: series, boxLink: $(this).attr('href').replace('/boxscores/', '')})
})
}
fs.writeFileSync(__dirname + '/playoffGames.csv', d3.csv.format(games))
var q = queue(1)
var downloaded = glob.sync(__dirname + '/raw-box/*.html').map(d => d.split('/raw-box/')[1])
games
.map(d => d.boxLink)
.filter(d => !_.contains(downloaded, d))
.forEach(d => q.defer(downloadBox, d))
function downloadBox(d, cb){
process.stdout.write("downloading " + d + "\r");
var url = 'http://www.basketball-reference.com/boxscores/' + d
// console.log(url)
setTimeout(cb, 1000)
request(url, function(error, response, html){
var path = __dirname + '/raw-box/' + d
fs.writeFileSync(path, html)
})
}
|
version https://git-lfs.github.com/spec/v1
oid sha256:2e4cfe75feb71c39771595f8dea4f59e216650e0454f3f56a2a5b38a062b94cf
size 1360
|
/*
* @param parseObject [ParseObject]
* @return [Object]
* */
export const convertBrand = (parseObject) => {
const ret = {};
const object = parseObject.toJSON();
ret.id = object.objectId;
ret.name = object.name;
ret.description = object.description;
ret.images = (object.images || []).map(image => ({ id: image.objectId, url: image.file.url }));
return ret;
};
/*
* @param parseObject [ParseObject]
* @return [Object]
* */
export const convertProduct = (parseObject) => {
const ret = {};
const object = parseObject.toJSON();
ret.id = object.objectId;
ret.brand_id = object.brand.objectId;
ret.name = object.name;
ret.description = object.description;
ret.images = object.images.map(image => ({ id: image.objectId, url: image.file.url }));
ret.size = object.size;
ret.color = object.color;
ret.cost = object.cost;
ret.price = object.price;
ret.quantity = object.quantity;
return ret;
};
|
import test from 'ava';
import { spawn } from 'child_process';
test.cb('app should boot without exiting', (t) => {
const cli = spawn('node', [ './cli' ]);
cli.stderr.on('data', (param) => {
console.log(param.toString());
});
cli.on('close', (code) => {
t.fail(`app failed to boot ${code}`);
});
setTimeout(() => {
t.pass();
t.end();
cli.kill();
}, 500);
});
|
let Demo1 = require('./components/demo1.js');
document.body.appendChild(Demo1());
|
var Handler, MiniEventEmitter;
Handler = require("./handler");
MiniEventEmitter = (function() {
function MiniEventEmitter(obj) {
var handler;
handler = new Handler(this, obj);
this.on = handler.on;
this.off = handler.off;
this.emit = handler.emit;
this.emitIf = handler.emitIf;
this.trigger = handler.emit;
this.triggerIf = handler.emitIf;
}
MiniEventEmitter.prototype.listen = function(type, event, args) {};
return MiniEventEmitter;
})();
module.exports = MiniEventEmitter;
|
/**
* React Starter Kit (https://www.reactstarterkit.com/)
*
* Copyright © 2014-present Kriasoft, LLC. All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE.txt file in the root directory of this source tree.
*/
import React from 'react';
import {connect} from 'react-redux';
import StringList from './StringList/StringList'
import TwitterSelector from './DomainSelector/TwitterSelector'
import TweetFilter from './TweetFilter/TweetFilter'
class Search extends React.Component {
constructor(props) {
super(props);
this.state = {
includedWords: []
};
this.getWords = this.getWords.bind(this);
}
getWords(words) {
this.setState({
includedWords: words
});
}
render() {
const styles = {
fontFamily: 'Helvetica Neue',
fontSize: 14,
lineHeight: '10px',
color: 'white',
display: 'flex',
alignItems: 'center',
justifyContent: 'center',
}
return (
<div>
<TweetFilter />
</div>
);
}
}
export default Search;
|
import { get } from "ember-metal/property_get";
import { set } from "ember-metal/property_set";
import Ember from "ember-metal/core"; // Ember.assert
import EmberError from "ember-metal/error";
import {
Descriptor,
defineProperty
} from "ember-metal/properties";
import { ComputedProperty } from "ember-metal/computed";
import create from "ember-metal/platform/create";
import {
meta,
inspect
} from "ember-metal/utils";
import {
addDependentKeys,
removeDependentKeys
} from "ember-metal/dependent_keys";
export default function alias(altKey) {
return new AliasedProperty(altKey);
}
export function AliasedProperty(altKey) {
this.altKey = altKey;
this._dependentKeys = [altKey];
}
AliasedProperty.prototype = create(Descriptor.prototype);
AliasedProperty.prototype.get = function AliasedProperty_get(obj, keyName) {
return get(obj, this.altKey);
};
AliasedProperty.prototype.set = function AliasedProperty_set(obj, keyName, value) {
return set(obj, this.altKey, value);
};
AliasedProperty.prototype.willWatch = function(obj, keyName) {
addDependentKeys(this, obj, keyName, meta(obj));
};
AliasedProperty.prototype.didUnwatch = function(obj, keyName) {
removeDependentKeys(this, obj, keyName, meta(obj));
};
AliasedProperty.prototype.setup = function(obj, keyName) {
Ember.assert("Setting alias '" + keyName + "' on self", this.altKey !== keyName);
var m = meta(obj);
if (m.watching[keyName]) {
addDependentKeys(this, obj, keyName, m);
}
};
AliasedProperty.prototype.teardown = function(obj, keyName) {
var m = meta(obj);
if (m.watching[keyName]) {
removeDependentKeys(this, obj, keyName, m);
}
};
AliasedProperty.prototype.readOnly = function() {
this.set = AliasedProperty_readOnlySet;
return this;
};
function AliasedProperty_readOnlySet(obj, keyName, value) {
throw new EmberError('Cannot set read-only property "' + keyName + '" on object: ' + inspect(obj));
}
AliasedProperty.prototype.oneWay = function() {
this.set = AliasedProperty_oneWaySet;
return this;
};
function AliasedProperty_oneWaySet(obj, keyName, value) {
defineProperty(obj, keyName, null);
return set(obj, keyName, value);
}
// Backwards compatibility with Ember Data
AliasedProperty.prototype._meta = undefined;
AliasedProperty.prototype.meta = ComputedProperty.prototype.meta;
|
/*
* This file is subject to the terms and conditions defined in
* file 'LICENSE.txt', which is part of this source code package.
*
* author: emicklei
*/
V8D.receiveCallback = function(msg) {
var obj = JSON.parse(msg);
var context = this;
if (obj.receiver != "this") {
var namespaces = obj.receiver.split(".");
for (var i = 0; i < namespaces.length; i++) {
context = context[namespaces[i]];
}
}
var func = context[obj.selector];
if (func != null) {
return JSON.stringify(func.apply(context, obj.args));
} else {
// try reporting the error
if (console != null) {
console.log("[JS] unable to perform", msg);
}
// TODO return error?
return "null";
}
}
// This callback is set for handling function calls from Go transferred as JSON.
// It is called from Go using "worker.Send(...)".
// Throws a SyntaxError exception if the string to parse is not valid JSON.
//
$recv(V8D.receiveCallback);
// This callback is set for handling function calls from Go transferred as JSON that expect a return value.
// It is called from Go using "worker.SendSync(...)".
// Throws a SyntaxError exception if the string to parse is not valid JSON.
// Returns the JSON representation of the return value of the handling function.
//
$recvSync(V8D.receiveCallback);
// callDispatch is used from Go to call a callback function that was registered.
//
V8D.callDispatch = function(functionRef /*, arguments */ ) {
var jsonArgs = [].slice.call(arguments).splice(1);
var callback = V8D.function_registry.take(functionRef)
if (V8D.function_registry.none == callback) {
$print("[JS] no function for reference:" + functionRef);
return;
}
callback.apply(this, jsonArgs.map(function(each){ return JSON.parse(each); }));
}
// MessageSend is a constructor.
//
V8D.MessageSend = function MessageSend(receiver, selector, onReturn) {
this.data = {
"receiver": receiver,
"selector": selector,
"callback": onReturn,
"args": [].slice.call(arguments).splice(3)
};
}
// MessageSend toJSON returns the JSON representation.
//
V8D.MessageSend.prototype = {
toJSON: function() {
return JSON.stringify(this.data);
}
}
// callReturn performs a MessageSend in Go and returns the value from that result
//
V8D.callReturn = function(receiver, selector /*, arguments */ ) {
var msg = {
"receiver": receiver,
"selector": selector,
"args": [].slice.call(arguments).splice(2)
};
return JSON.parse($sendSync(JSON.stringify(msg)));
}
// call performs a MessageSend in Go and does NOT return a value.
//
V8D.call = function(receiver, selector /*, arguments */ ) {
var msg = {
"receiver": receiver,
"selector": selector,
"args": [].slice.call(arguments).splice(2)
};
$send(JSON.stringify(msg));
}
// callThen performs a MessageSend in Go which can call the onReturn function.
// It does not return the value of the perform.
//
V8D.callThen = function(receiver, selector, onReturnFunction /*, arguments */ ) {
var msg = {
"receiver": receiver,
"selector": selector,
"callback": V8D.function_registry.put(onReturnFunction),
"args": [].slice.call(arguments).splice(3)
};
$send(JSON.stringify(msg));
}
// set adds/replaces the value for a variable in the global scope.
//
V8D.set = function(variableName,itsValue) {
V8D.outerThis[variableName] = itsValue;
}
// get returns the value for a variable in the global scope.
//
V8D.get = function(variableName) {
return V8D.outerThis[variableName];
}
|
/**
*
* Modelo de Login usando MCV
* Desenvolvido por Ricardo Hirashiki
* Publicado em: http://www.sitedoricardo.com.br
* Data: Ago/2011
*
* Baseado na extensao criada por Wemerson Januario
* http://code.google.com/p/login-window/
*
*/
Ext.define('Siccad.view.authentication.CapsWarningTooltip', {
extend : 'Ext.tip.QuickTip',
alias : 'widget.capswarningtooltip',
target : 'authentication-login',
id : 'toolcaps',
anchor : 'left',
anchorOffset : 60,
width : 305,
dismissDelay : 0,
autoHide : false,
disabled : false,
title : '<b>Caps Lock está ativada</b>',
html : '<div>Se Caps lock estiver ativado, isso pode fazer com que você</div>' +
'<div>digite a senha incorretamente.</div><br/>' +
'<div>Você deve pressionar a tecla Caps lock para desativá-la</div>' +
'<div>antes de digitar a senha.</div>'
});
|
// generates an interface file given an eni file
// you can generate an eni file using the aws-cli
// example:
// aws ec2 describe-network-interfaces --network-interface-ids eni-2492676c > eni-7290653a.json
var ENI_FILE = "json/eni-651e2c2c.json";
// the interface you want to configure
var INTERFACE = "eth1";
// port you want squid proxy to start at; doesn't matter if you're not using squid
var PORT = 3188;
// get the gateway ip by running `route -n`
var GATEWAYIP = "172.31.16.1";
// number to start with in RT TABLES
var RT_TABLES = 2;
fs = require('fs');
fs.readFile(ENI_FILE, function (err, data) {
if (!err) {
var eni = JSON.parse(data).NetworkInterfaces[0];
var netConfig = "auto " + INTERFACE + "\niface " + INTERFACE + " inet dhcp\n\n";
var squidConfig = "";
var rtTables = "";
for (var i = 0; i < eni.PrivateIpAddresses.length; i++) {
var addressObject = eni.PrivateIpAddresses[i];
// construct string
// current subinterface
var subinterface = INTERFACE + ":" + i;
netConfig += "auto " + subinterface + "\n";
netConfig += "iface "+ subinterface + " inet static\n";
netConfig += "address " + addressObject.PrivateIpAddress + "\n";
// this IP is the gateway IP
netConfig += "up ip route add default via " + GATEWAYIP + " dev " + subinterface + " table " + subinterface + "\n"
netConfig += "up ip rule add from " + addressObject.PrivateIpAddress + " lookup " + subinterface + "\n\n";
squidConfig += "http_port localhost:" + PORT + " name="+ PORT + "\nacl a" + PORT + " myportname " + PORT + " src localhost\nhttp_access allow a" + PORT + "\ntcp_outgoing_address " + addressObject.PrivateIpAddress + " a" + PORT + "\n\n";
rtTables += RT_TABLES + " " + subinterface + "\n";
PORT++;
RT_TABLES++;
};
// trim newlines
netConfig = netConfig.replace(/^\s+|\s+$/g, '');
squidConfig = squidConfig.replace(/^\s+|\s+$/g, '');
rtTables = rtTables.replace(/^\s+|\s+$/g, '');
fs.writeFile("./cfg/" + INTERFACE + ".cfg", netConfig, function(err) {
if(err) {
console.log(err);
} else {
console.log("Generated networking config and saved it to " + INTERFACE + ".cfg.");
}
});
fs.writeFile("./cfg/" + INTERFACE + "-squid.cfg", squidConfig, function(err) {
if(err) {
console.log(err);
} else {
console.log("Generated squid config and saved it to " + INTERFACE + ".cfg.");
}
});
fs.writeFile("./cfg/" + INTERFACE + "-rt_tables.cfg", rtTables, function(err) {
if(err) {
console.log(err);
} else {
console.log("Generated rt_tables and saved it to " + INTERFACE + ".cfg.");
}
});
}
if (err) {
console.log("Error! Make sure you're running this in the config-utils directory and that the JSON file + the cfg directory are both there.");
}
});
|
var width = window.innerWidth,
height = window.innerHeight,
boids = [],
destination,
canvas,
context;
const MAX_NUMBER = 100;
const MAX_SPEED = 1;
const radius = 5;
init();
animation();
function init(){
canvas = document.getElementById('canvas'),
context = canvas.getContext( "2d" );
canvas.width = width;
canvas.height = height;
destination = {
x:Math.random()*width,
y:Math.random()*height
};
for (var i = 0; i <MAX_NUMBER; i++) {
boids[i] = new Boid();
};
}
var _animation;
function animation(){
_animation = requestAnimationFrame(animation);
context.clearRect(0,0,width,height);
for (var i = 0; i < boids.length; i++) {
boids[i].rule1();
boids[i].rule2();
boids[i].rule3();
boids[i].rule4();
boids[i].rule5();
boids[i].rule6();
var nowSpeed = Math.sqrt(boids[i].vx * boids[i].vx + boids[i].vy * boids[i].vy );
if(nowSpeed > MAX_SPEED){
boids[i].vx *= MAX_SPEED / nowSpeed;
boids[i].vy *= MAX_SPEED / nowSpeed;
}
boids[i].x += boids[i].vx;
boids[i].y += boids[i].vy;
drawCircle(boids[i].x,boids[i].y);
drawVector(boids[i].x,boids[i].y,boids[i].vx,boids[i].vy);
};
}
/*
//mouseEvent
document.onmousemove = function (event){
destination ={
x:event.screenX,
y:event.screenY
}
};
*/
function Boid(){
this.x = Math.random()*width;
this.y = Math.random()*height;
this.vx = 0.0;
this.vy = 0.0;
this.dx = Math.random()*width;
this.dy = Math.random()*height;
//群れの中心に向かう
this.rule1 = function(){
var centerx = 0,
centery = 0;
for (var i = 0; i < boids.length; i++) {
if (boids[i] != this) {
centerx += boids[i].x;
centery += boids[i].y;
};
};
centerx /= MAX_NUMBER-1;
centery /= MAX_NUMBER-1;
this.vx += (centerx-this.x)/1000;
this.vy += (centery-this.y)/1000;
}
//他の個体と離れるように動く
this.rule2 = function(){
var _vx = 0,
_vy = 0;
for (var i = 0; i < boids.length; i++) {
if(this != boids[i]){
var distance = distanceTo(this.x,boids[i].x,this.y,boids[i].y);
if(distance<25){
distance += 0.001;
_vx -= (boids[i].x - this.x)/distance;
_vy -= (boids[i].y - this.y)/distance;
//this.dx = -boids[i].x;
//this.dy = -boids[i].y;
}
}
};
this.vx += _vx;
this.vy += _vy;
}
//他の個体と同じ速度で動こうとする
this.rule3 = function(){
var _pvx = 0,
_pvy = 0;
for (var i = 0; i < boids.length; i++) {
if (boids[i] != this) {
_pvx += boids[i].vx;
_pvy += boids[i].vy;
}
};
_pvx /= MAX_NUMBER-1;
_pvy /= MAX_NUMBER-1;
this.vx += (_pvx - this.vx)/10;
this.vy += (_pvy - this.vy)/10;
};
//壁側の時の振る舞い
this.rule4 = function(){
if(this.x < 10 && this.vx < 0)this.vx += 10/(Math.abs( this.x ) + 1 );
if(this.x > width && this.vx > 0)this.vx -= 10/(Math.abs( width - this.x ) + 1 );
if (this.y < 10 && this.vy < 0)this.vy += 10/(Math.abs( this.y ) + 1 );
if(this.y > height && this.vy > 0)this.vy -= 10/(Math.abs( height - this.y ) + 1 );
};
//目的地に行く
this.rule5 = function(){
var _dx = this.dx - this.x,
_dy = this.dy - this.y;
this.vx += (this.dx - this.x)/500;
this.vy += (this.dy - this.y)/500;
}
//捕食する
this.rule6 = function(){
var _vx = Math.random()-0.5,
_vy = Math.random()-0.5;
for (var i = 0; i < boids.length; i++) {
if(this != boids[i] && this.dx != boids[i].dx && this.dy != boids[i].dy){
var distance = distanceTo(this.x,boids[i].x,this.y,boids[i].y);
if(distance<20 && distance>15){
console.log(distance);
distance += 0.001;
_vx += (boids[i].x - this.x)/distance;
_vy += (boids[i].y - this.y)/distance;
drawLine(this.x,this.y,boids[i].x,boids[i].y);
this.dx = boids[i].dx;
this.dy = boids[i].dy;
}
}
};
this.vx += _vx;
this.vy += _vy;
}
}
function distanceTo(x1,x2,y1,y2){
var dx = x2-x1,
dy = y2-y1;
return Math.sqrt(dx*dx+dy*dy);
}
function drawCircle(x,y){
context.beginPath();
context.strokeStyle = "#fff";
context.arc(x,y,radius,0,Math.PI*2,false);
context.stroke();
}
const VectorLong = 10;
function drawVector(x,y,vx,vy){
context.beginPath();
var pointx = x+vx*VectorLong;
var pointy = y+vy*VectorLong;
context.moveTo(x,y);
context.lineTo(pointx,pointy);
context.stroke();
}
function drawLine(x1,y1,x2,y2){
context.beginPath();
context.moveTo(x1,y1);
context.lineTo(x2,y2);
context.stroke();
}
|
describe("Dragable Row Directive ", function () {
var scope, container, element, html, compiled, compile;
beforeEach(module("app", function ($provide) { $provide.value("authService", {}) }));
beforeEach(inject(function ($compile, $rootScope) {
html = '<div id="element-id" data-draggable-row=""'
+ ' data-draggable-elem-selector=".draggable"'
+ ' data-drop-area-selector=".drop-area">'
+ '<div class="draggable"></div>'
+ '<div class="drop-area" style="display: none;"></div>'
+ '</div>';
scope = $rootScope.$new();
compile = $compile;
}));
function prepareDirective(s) {
container = angular.element(html);
compiled = compile(container);
element = compiled(s);
s.$digest();
}
/***********************************************************************************************************************/
it('should add draggable attribute to draggable element, when initialise', function () {
prepareDirective(scope);
expect(element.find('.draggable').attr('draggable')).toBe('true');
});
it('should prevent default, when dragging over allowed element', function () {
prepareDirective(scope);
var event = $.Event('dragover');
event.preventDefault = window.jasmine.createSpy('preventDefault');
event.originalEvent = {
dataTransfer: {
types: {},
getData: window.jasmine.createSpy('getData').and.returnValue("element-id")
}
};
element.trigger(event);
expect(event.preventDefault).toHaveBeenCalled();
});
it('should show drop area, when drag enter allowed element', function () {
prepareDirective(scope);
var event = $.Event('dragenter');
event.originalEvent = {
dataTransfer: {
types: {},
getData: window.jasmine.createSpy('getData').and.returnValue("element-id")
}
};
element.trigger(event);
expect(element.find('.drop-area').css('display')).not.toEqual('none');
expect(event.originalEvent.dataTransfer.getData).toHaveBeenCalledWith('draggedRow');
});
it('should call scope onDragEnd, when dragging ends', function () {
prepareDirective(scope);
var event = $.Event('dragend');
var isolateScope = element.isolateScope();
spyOn(isolateScope, 'onDragEnd');
element.trigger(event);
expect(isolateScope.onDragEnd).toHaveBeenCalled();
});
it('should set drag data and call scope onDrag, when drag starts', function () {
prepareDirective(scope);
var event = $.Event('dragstart');
event.originalEvent = {
dataTransfer: {
setData: window.jasmine.createSpy('setData')
}
};
var isolateScope = element.isolateScope();
spyOn(isolateScope, 'onDrag');
element.find('.draggable').trigger(event);
expect(isolateScope.onDrag).toHaveBeenCalled();
expect(event.originalEvent.dataTransfer.setData).toHaveBeenCalledWith('draggedRow', 'element-id');
});
it('should prevent default, when dragging over allowed drop area', function () {
prepareDirective(scope);
var event = $.Event('dragover');
event.preventDefault = window.jasmine.createSpy('preventDefault');
event.originalEvent = {
dataTransfer: {
types: {},
getData: window.jasmine.createSpy('getData').and.returnValue("element-id")
}
};
element.find('.drop-area').trigger(event);
expect(event.preventDefault).toHaveBeenCalled();
});
it('should show drop area, when drag enter allowed drop area', function () {
prepareDirective(scope);
var event = $.Event('dragenter');
event.originalEvent = {
dataTransfer: {
types: {},
getData: window.jasmine.createSpy('getData').and.returnValue("element-id")
}
};
element.find('.drop-area').trigger(event);
expect(element.find('.drop-area').css('display')).not.toEqual('none');
expect(event.originalEvent.dataTransfer.getData).toHaveBeenCalledWith('draggedRow');
});
it('should hide drop area, when drag leave drop area', function () {
prepareDirective(scope);
var event = $.Event('dragleave');
event.originalEvent = {
dataTransfer: {
types: {},
getData: window.jasmine.createSpy('getData').and.returnValue("element-id")
}
};
element.find('.drop-area').trigger(event);
expect(element.find('.drop-area').css('display')).toEqual('none');
expect(event.originalEvent.dataTransfer.getData).toHaveBeenCalledWith('draggedRow');
});
it('should hide drop area and call scope onDrop, when drop on drop area', function () {
prepareDirective(scope);
var event = $.Event('drop');
event.preventDefault = window.jasmine.createSpy('preventDefault');
event.originalEvent = {
dataTransfer: {
types: {},
getData: window.jasmine.createSpy('getData').and.returnValue("element-id")
}
};
var isolateScope = element.isolateScope();
spyOn(isolateScope, 'onDrop');
element.find('.drop-area').trigger(event);
expect(event.originalEvent.dataTransfer.getData).toHaveBeenCalledWith('draggedRow');
expect(event.preventDefault).toHaveBeenCalled();
expect(element.find('.drop-area').css('display')).toEqual('none');
expect(isolateScope.onDrop).toHaveBeenCalled();
});
});
|
import _ from 'lodash';
import { createSelector } from 'reselect';
const srcFilesSelector = state => state.srcFiles;
const featuresSelector = state => state.features;
const featureByIdSelector = state => state.featureById;
const keywordSelector = (state, keyword) => keyword;
function getMarks(feature, ele) {
const marks = [];
switch (ele.type) {
case 'component':
if (ele.connectToStore) marks.push('C');
if (_.find(feature.routes, { component: ele.name })) marks.push('R');
break;
case 'action':
if (ele.isAsync) marks.push('A');
break;
default:
break;
}
return marks;
}
function getComponentsTreeData(feature) {
const components = feature.components;
return {
key: `${feature.key}-components`,
className: 'components',
label: 'Components',
icon: 'appstore-o',
count: components.length,
children: components.map(comp => ({
key: comp.file,
className: 'component',
label: comp.name,
icon: 'appstore-o',
searchable: true,
marks: getMarks(feature, comp),
})),
};
}
function getActionsTreeData(feature) {
const actions = feature.actions;
return {
key: `${feature.key}-actions`,
className: 'actions',
label: 'Actions',
icon: 'notification',
count: actions.length,
children: actions.map(action => ({
key: action.file,
className: 'action',
label: action.name,
icon: 'notification',
searchable: true,
marks: getMarks(feature, action),
})),
};
}
function getChildData(child) {
return {
key: child.file,
className: child.children ? 'misc-folder' : 'misc-file',
label: child.name,
icon: child.children ? 'folder' : 'file',
searchable: !child.children,
children: child.children ? child.children.map(getChildData) : null,
};
}
function getMiscTreeData(feature) {
const misc = feature.misc;
return {
key: `${feature.key}-misc`,
className: 'misc',
label: 'Misc',
icon: 'folder',
children: misc.map(getChildData),
};
}
export const getExplorerTreeData = createSelector(
srcFilesSelector,
featuresSelector,
featureByIdSelector,
(srcFiles, features, featureById) => {
const featureNodes = features.map((fid) => {
const feature = featureById[fid];
return {
key: feature.key,
className: 'feature',
label: feature.name,
icon: 'book',
children: [
{ label: 'Routes', key: `${fid}-routes`, searchable: false, className: 'routes', icon: 'share-alt', count: feature.routes.length },
getActionsTreeData(feature),
getComponentsTreeData(feature),
getMiscTreeData(feature),
],
};
});
const allNodes = [
{
key: 'features',
label: 'Features',
icon: 'features',
children: _.compact(featureNodes),
},
{
key: 'others-node',
label: 'Others',
icon: 'folder',
children: srcFiles.map(getChildData),
}
];
return { root: true, children: allNodes };
}
);
function filterTreeNode(node, keyword) {
const reg = new RegExp(_.escapeRegExp(keyword), 'i');
return {
...node,
children: _.compact(node.children.map((child) => {
if (child.searchable && reg.test(child.label)) return child;
if (child.children) {
const c = filterTreeNode(child, keyword);
return c.children.length > 0 ? c : null;
}
return null;
})),
};
}
export const getFilteredExplorerTreeData = createSelector(
getExplorerTreeData,
keywordSelector,
(treeData, keyword) => {
if (!keyword) return treeData;
return filterTreeNode(treeData, keyword);
}
);
// when searching the tree, all nodes should be expanded, the tree component needs expandedKeys property.
export const getExpandedKeys = createSelector(
getFilteredExplorerTreeData,
(treeData) => {
const keys = [];
let arr = [...treeData.children];
while (arr.length) {
const pop = arr.pop();
if (pop.children) {
keys.push(pop.key);
arr = [...arr, ...pop.children];
}
}
return keys;
}
);
|
exports.login = function* (ctx) {
const result = yield ctx.service.mine.login(ctx.request.body);
if (!result) {
ctx.status = 400;
ctx.body = {
status: 400,
msg: `please check your username and password`,
}
return;
}
ctx.body = {
access_token: result.access_token,
msg: 'login success',
};
ctx.status = 200;
}
exports.signup = function* (ctx) {
const result = yield ctx.service.mine.signup(ctx.request.body);
if (!result.result) {
ctx.status = 400;
ctx.body = {
status: 400,
msg: result.msg,
}
return;
}
ctx.status = 201;
ctx.body = {
status: 201,
msg: 'success',
}
}
exports.info = function* (ctx) {
const info = yield ctx.service.mine.info(ctx.auth.user_id);
if (info == null) {
ctx.status = 200;
ctx.body = {
status: 200,
msg: 'there is no info for current user',
}
return;
}
ctx.body = info;
ctx.status = 200;
}
exports.statistics = function* (ctx) {
const info = yield ctx.service.mine.statistics(ctx.auth.user_id);
if (info == null) {
ctx.status = 200;
ctx.body = {
shares_count: 0,
friends_count: 0,
helpful_count: 0,
};
return;
}
ctx.body = info;
ctx.status = 200;
}
exports.accounts = function* (ctx) {
const accounts = yield ctx.service.mine.accounts(ctx.auth.user_id);
ctx.body = accounts;
ctx.status = 200;
}
exports.update = function* (ctx) {
let profile = ctx.request.body;
profile.id = ctx.auth.user_id;
const result = yield ctx.service.mine.update(profile);
if (result) {
ctx.status = 204;
return;
}
ctx.status = 500;
ctx.body = {
msg: 'update profile failed',
}
}
exports.avatar = function* (ctx) {
const parts = ctx.multipart();
const { filename, error } = yield ctx.service.mine.avatar(parts, `avatar/${ctx.auth.user_id}`);
if (error) {
ctx.status = 500;
ctx.body = {
status: 500,
msg: 'update avatar failed',
};
return false;
}
ctx.status = 200;
ctx.body = {
filename,
msg: 'success',
}
}
|
export const browserVersions = () => {
let u = navigator.userAgent
return {
// 移动终端浏览器版本信息
trident: u.indexOf('Trident') > -1, // IE内核
presto: u.indexOf('Presto') > -1, // opera内核
webKit: u.indexOf('AppleWebKit') > -1, // 苹果、谷歌内核
gecko: u.indexOf('Gecko') > -1 && u.indexOf('KHTML') === -1, // 火狐内核
mobile: !!u.match(/AppleWebKit.*Mobile.*/), // 是否为移动终端
ios: !!u.match(/\(i[^;]+;( U;)? CPU.+Mac OS X/), // ios终端
android: u.indexOf('Android') > -1 || u.indexOf('Linux') > -1, // android终端或者uc浏览器
iPhone: u.indexOf('iPhone') > -1, // 是否为iPhone或者QQHD浏览器
iPad: u.indexOf('iPad') > -1, // 是否iPad
webApp: u.indexOf('Safari') === -1 // 是否web应该程序,没有头部与底部
}
}
|
/**
* Get a number suffix
* e.g. 1 -> st
* @param {int} i number to get suffix
* @return suffix
*/
var getSuffix = function (i) {
var j = i % 10,
k = i % 100;
if (j == 1 && k != 11) {
return i + "st";
}
if (j == 2 && k != 12) {
return i + "nd";
}
if (j == 3 && k != 13) {
return i + "rd";
}
return i + "th";
}
module.exports = {
getSuffix: getSuffix,
};
|
'use strict';
const chai = require('chai'),
expect = chai.expect,
config = require('../config/config'),
Support = require('./support'),
dialect = Support.getTestDialect(),
Sequelize = Support.Sequelize,
fs = require('fs'),
path = require('path');
if (dialect === 'sqlite') {
var sqlite3 = require('sqlite3'); // eslint-disable-line
}
describe(Support.getTestDialectTeaser('Configuration'), () => {
describe('Connections problems should fail with a nice message', () => {
it('when we don\'t have the correct server details', () => {
const seq = new Sequelize(config[dialect].database, config[dialect].username, config[dialect].password, { storage: '/path/to/no/where/land', logging: false, host: '0.0.0.1', port: config[dialect].port, dialect });
if (dialect === 'sqlite') {
// SQLite doesn't have a breakdown of error codes, so we are unable to discern between the different types of errors.
return expect(seq.query('select 1 as hello')).to.eventually.be.rejectedWith(Sequelize.ConnectionError, 'SQLITE_CANTOPEN: unable to open database file');
}
return expect(seq.query('select 1 as hello')).to.eventually.be.rejectedWith([Sequelize.HostNotReachableError, Sequelize.InvalidConnectionError]);
});
it('when we don\'t have the correct login information', () => {
if (dialect === 'mssql') {
// NOTE: Travis seems to be having trouble with this test against the
// AWS instance. Works perfectly fine on a local setup.
expect(true).to.be.true;
return;
}
const seq = new Sequelize(config[dialect].database, config[dialect].username, 'fakepass123', { logging: false, host: config[dialect].host, port: 1, dialect });
if (dialect === 'sqlite') {
// SQLite doesn't require authentication and `select 1 as hello` is a valid query, so this should be fulfilled not rejected for it.
return expect(seq.query('select 1 as hello')).to.eventually.be.fulfilled;
}
return expect(seq.query('select 1 as hello')).to.eventually.be.rejectedWith(Sequelize.ConnectionRefusedError, 'connect ECONNREFUSED');
});
it('when we don\'t have a valid dialect.', () => {
expect(() => {
new Sequelize(config[dialect].database, config[dialect].username, config[dialect].password, { host: '0.0.0.1', port: config[dialect].port, dialect: 'some-fancy-dialect' });
}).to.throw(Error, 'The dialect some-fancy-dialect is not supported. Supported dialects: mssql, mariadb, mysql, postgres, and sqlite.');
});
});
describe('Instantiation with arguments', () => {
if (dialect === 'sqlite') {
it('should respect READONLY / READWRITE connection modes', () => {
const p = path.join(__dirname, '../tmp', 'foo.sqlite');
const createTableFoo = 'CREATE TABLE foo (faz TEXT);';
const createTableBar = 'CREATE TABLE bar (baz TEXT);';
const testAccess = Sequelize.Promise.method(() => {
return Sequelize.Promise.promisify(fs.access)(p, fs.R_OK | fs.W_OK);
});
return Sequelize.Promise.promisify(fs.unlink)(p)
.catch(err => {
expect(err.code).to.equal('ENOENT');
})
.then(() => {
const sequelizeReadOnly = new Sequelize('sqlite://foo', {
storage: p,
dialectOptions: {
mode: sqlite3.OPEN_READONLY
}
});
const sequelizeReadWrite = new Sequelize('sqlite://foo', {
storage: p,
dialectOptions: {
mode: sqlite3.OPEN_READWRITE
}
});
expect(sequelizeReadOnly.config.dialectOptions.mode).to.equal(sqlite3.OPEN_READONLY);
expect(sequelizeReadWrite.config.dialectOptions.mode).to.equal(sqlite3.OPEN_READWRITE);
return Sequelize.Promise.join(
sequelizeReadOnly.query(createTableFoo)
.should.be.rejectedWith(Error, 'SQLITE_CANTOPEN: unable to open database file'),
sequelizeReadWrite.query(createTableFoo)
.should.be.rejectedWith(Error, 'SQLITE_CANTOPEN: unable to open database file')
);
})
.then(() => {
// By default, sqlite creates a connection that's READWRITE | CREATE
const sequelize = new Sequelize('sqlite://foo', {
storage: p
});
return sequelize.query(createTableFoo);
})
.then(testAccess)
.then(() => {
const sequelizeReadOnly = new Sequelize('sqlite://foo', {
storage: p,
dialectOptions: {
mode: sqlite3.OPEN_READONLY
}
});
const sequelizeReadWrite = new Sequelize('sqlite://foo', {
storage: p,
dialectOptions: {
mode: sqlite3.OPEN_READWRITE
}
});
return Sequelize.Promise.join(
sequelizeReadOnly.query(createTableBar)
.should.be.rejectedWith(Error, 'SQLITE_READONLY: attempt to write a readonly database'),
sequelizeReadWrite.query(createTableBar)
);
})
.finally(() => {
return Sequelize.Promise.promisify(fs.unlink)(p);
});
});
}
});
});
|
// Script by Bo Tranberg
// http://botranberg.dk
// https://github.com/tranberg/citations
//
// This script requires jQuery and jQuery UI
$(function() {
// Inser html for dialog just before the button to open it
var butt = document.getElementById('citations');
butt.insertAdjacentHTML('beforeBegin',
'\
<div id="dialog" title="Cite this paper" style="text-align:left"> \
<p style="text-align: center;"><b>Copy and paste one of the formatted citations into your bibliography manager.</b></p> \
<table style="border-collapse:separate; border-spacing:2em"> \
<tr style="vertical-align:top;"> \
<td><strong>APA</strong></td> \
<td><span id="APA1"></span><span id="APA2"></span><span id="APA3"></span><span id="APA4" style="font-style: italic"></span></td> \
</tr> \
<tr style="vertical-align:top;"> \
<td><strong>Bibtex</strong></td> \
<td> \
@article{<span id="bibtag"></span>,<br> \
title={<span id="bibtitle"></span>},<br> \
author={<span id="bibauthor"></span>},<br> \
journal={<span id="bibjournal"></span>},<br> \
year={<span id="bibyear"></span>},<br> \
url={<span id="biburl"></span>},<br> \
} \
</td> \
</tr> \
</table> \
</div>');
// Definitions of citations dialog
$("#dialog").dialog({
autoOpen: false,
show: {
effect: "fade",
duration: 200
},
hide: {
effect: "fade",
duration: 200
},
maxWidth:600,
maxHeight: 600,
width: 660,
height: 400,
modal: true,
});
// Open citation dialog on click
$("#citations").click(function() {
$("#dialog").dialog("open");
});
// Find authors
var metas = document.getElementsByTagName('meta');
var author = ''
// Determine number of authors
var numAuthors = 0
for (i=0; i<metas.length; i++) {
if (metas[i].getAttribute("name") == "citation_author") {
numAuthors += 1
};
};
// Build a string of authors for Bibtex
var authorIndex = 0
for (i=0; i<metas.length; i++) {
if (metas[i].getAttribute("name") == "citation_author") {
authorIndex += 1
if (authorIndex>1) {
if (authorIndex<=numAuthors) {
author = author+' and '
};
};
author = author+metas[i].getAttribute("content")
};
};
// Populate formatted citations in Bibtex
var title = $("meta[name='citation_title']").attr('content')
// The following test might seem stupid, but it's needed because some php function at OpenPsych appends two whitespaces to the start of the title in the meta data
if (title[1] == ' ') {
title = title.slice(2)
};
var journal = $("meta[name='citation_journal_title']").attr('content')
var pubyear = $("meta[name='citation_publication_date']").attr('content').substring(0,4)
var puburl = document.URL
// Build a string for the Bibtex tag
if (author.indexOf(',') < author.indexOf(' ')) {
var firstAuthor = author.substr(0,author.indexOf(','));
} else {
var firstAuthor = author.substr(0,author.indexOf(' '));
};
if (title.indexOf(',')<title.indexOf('0')) {
var startTitle = title.substr(0,title.indexOf(','));
} else {
var startTitle = title.substr(0,title.indexOf(' '));
};
$('#bibtag').html(firstAuthor+pubyear)
$('#bibtitle').html(title)
$('#bibauthor').html(author)
$('#bibjournal').html(journal)
$('#bibyear').html(pubyear)
$('#biburl').html(puburl)
//Build a string of authors for APA
var author = ''
var authorIndex = 0
for (i=0; i<metas.length; i++) {
if (metas[i].getAttribute("name") == "citation_author") {
authorIndex += 1
if (authorIndex>1) {
if (authorIndex<numAuthors) {
author = author+', '
};
};
if (authorIndex>1) {
if (authorIndex===numAuthors) {
author = author+', & '
};
};
// Check if author only has a single name
if (metas[i].getAttribute("content").indexOf(', ')>0) {
// Append author string with the surnames and first letter of next author's name
author = author+metas[i].getAttribute("content").substr(0,metas[i].getAttribute("content").indexOf(', ')+3)+'.'
// If the author has several names, append the first letter of these to the string
if (metas[i].getAttribute("content").indexOf(', ') < metas[i].getAttribute("content").lastIndexOf(' ')-1) {
var extraNames = metas[i].getAttribute("content").substr(metas[i].getAttribute("content").indexOf(', ')+2)
var addNames = extraNames.substr(extraNames.indexOf(' '))
author = author+addNames.substr(addNames.indexOf(' '))
};
} else {
author = author+metas[i].getAttribute("content")
};
};
};
// Populate formatted citations in APA
$('#APA1').html(author)
$('#APA2').html(' ('+pubyear+').')
$('#APA3').html(' '+title+'.')
$('#APA4').html(' '+journal+'.')
});
|
// # 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
},
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'
}
},
// ### 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: 'Gmail',
auth: {
user: 'thewanderingconsultant@gmail.com', // mailgun username
pass: 'ghostblogwandering' // 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;
|
import React from 'react';
import PropTypes from 'prop-types';
import styled, { keyframes } from 'styled-components';
const blink = keyframes`
from, to {
opacity: 1;
}
50% {
opacity: 0;
}
`;
const CursorSpan = styled.span`
font-weight: 100;
color: black;
font-size: 1em;
padding-left: 2px;
animation: ${blink} 1s step-end infinite;
`;
const Cursor = ({ className }) => (
<CursorSpan className={className}>|</CursorSpan>
);
Cursor.propTypes = { className: PropTypes.string };
Cursor.defaultProps = { className: '' };
export default Cursor;
|
var test = require('tape');
var BSFS = require('../lib/bsfs');
indexedDB.deleteDatabase('bsfs-tests');
function randomId () { return Math.random().toString(36).substr(2) }
test('bsfs exists', function (t) {
t.plan(1);
var bsfs = new BSFS('bsfs-tests');
if (!bsfs._ready) return bsfs.once('ready', ready);
else process.nextTick(ready);
function ready () {
t.equals(typeof bsfs, 'object');
}
});
test('bsfs has file router', function (t) {
t.plan(1);
var bsfs = new BSFS('bsfs-tests');
if (!bsfs._ready) return bsfs.once('ready', ready);
else process.nextTick(ready);
function ready () {
t.equal(typeof bsfs._fileRouter, 'object');
}
});
test('write without path throws', function (t) {
t.plan(1);
var bsfs = new BSFS('bsfs-tests');
if (!bsfs._ready) return bsfs.once('ready', ready);
else process.nextTick(ready);
function ready () {
t.throws(function() {
bsfs.createWriteStream(null, function() {})
});
}
});
test('write file', function (t) {
t.plan(1);
var bsfs = new BSFS('bsfs-tests');
if (!bsfs._ready) return bsfs.once('ready', ready);
else process.nextTick(ready);
function ready () {
var path = '/tmp/test-' + randomId();
var content = 'Hello cruel world ' + randomId();
var w = bsfs.createWriteStream(path, function(err, meta) {
t.equal(err, null);
});
w.end(content);
}
});
test('write then read file by key', function (t) {
t.plan(1);
var path = '/tmp/test-' + randomId();
var content = 'Hello cruel world ' + randomId();
var bsfs = new BSFS('bsfs-tests');
if (!bsfs._ready) return bsfs.once('ready', ready);
else process.nextTick(ready);
function readBack (key) {
var r = bsfs.createReadStreamFromKey(key);
var readContent = '';
r.on('data', function (chunk) {
readContent += chunk;
});
r.on('end', function () {
t.equal(content, readContent);
});
}
function ready () {
var w = bsfs.createWriteStream(path, function(err, meta) {
readBack(meta.key);
});
w.end(content);
}
});
test('write then read file by name', function (t) {
t.plan(1);
var content = 'Hello cruel world ' + randomId();
var path = '/tmp/test-' + randomId();
var bsfs = new BSFS('bsfs-tests');
if (!bsfs._ready) return bsfs.once('ready', ready);
else process.nextTick(ready);
function readBack (path) {
var r = bsfs.createReadStream(path);
var readContent = '';
r.on('data', function (chunk) {
readContent += chunk;
});
r.on('end', function () {
t.equal(content, readContent);
});
}
function ready () {
var w = bsfs.createWriteStream(path, function(err, meta) {
readBack(path);
});
w.end(content);
}
});
test('access', function (t) {
t.test('is silent (for now)', function (t) {
t.plan(3);
var bsfs = new BSFS('bsfs-tests');
if (!bsfs.ready) return bsfs.once('ready', ready)
else process.nextTick(ready);
function ready () {
bsfs.access(null, function (err) {
t.ifError(err);
});
bsfs.access('/tmp', function (err) {
t.ifError(err);
});
bsfs.access('/tmp', 2, function (err) {
t.ifError(err);
});
}
});
t.test('throws on invalid callback argument', function (t) {
t.plan(1);
var bsfs = new BSFS('bsfs-tests');
if (!bsfs.ready) return bsfs.once('ready', ready)
else process.nextTick(ready);
function ready () {
t.throws(function () {
bsfs.access('/tmp/', 0, 'potatoe');
})
}
});
});
test('accessSync', function (t) {
t.test('is silent (for now)', function (t) {
t.plan(2);
var bsfs = new BSFS('bsfs-tests');
if (!bsfs.ready) return bsfs.once('ready', ready)
else process.nextTick(ready);
function ready () {
t.ifError(bsfs.accessSync(randomId()));
t.ifError(bsfs.accessSync());
}
})
});
test('exists', function (t) {
t.test('is true for all paths (for now)', function (t) {
t.plan(1);
var bsfs = new BSFS('bsfs-tests');
if (!bsfs.ready) return bsfs.once('ready', ready);
else proccess.nextTick(ready);
function ready () {
bsfs.exists(randomId(), function (exists) {
t.ok(exists);
});
}
});
});
test('existsSync', function (t) {
t.test('throws on null path', function (t) {
t.plan(1);
var bsfs = new BSFS('bsfs-tests');
if (!bsfs.ready) return bsfs.once('ready', ready);
else proccess.nextTick(ready);
function ready () {
t.throws(bsfs.existsSync());
}
});
t.test('is true for all paths (for now)', function (t) {
t.plan(2);
var bsfs = new BSFS('bsfs-tests');
if (!bsfs.ready) return bsfs.once('ready', ready);
else proccess.nextTick(ready);
function ready () {
t.ok(bsfs.existsSync(randomId()));
t.ok(bsfs.existsSync());
}
});
});
test('appendFile without path throws', function (t) {
t.plan(1);
var bsfs = new BSFS('bsfs-tests');
if (!bsfs._ready) return bsfs.once('ready', ready);
else process.nextTick(ready);
function ready () {
t.throws(function () {
bsfs.appendFile(null, function () {});
});
}
});
|
'use strict';
angular.module('mean.system').directive('googleMaps', ['GoogleMaps', 'Global',
function(GoogleMaps, Global) {
return {
restrict: 'E',
template: '<div id="map" style="height: 600px; width: 100%;"></div>',
controller: function() {
var mapOptions;
if ( GoogleMaps ) {
mapOptions = {
center: new GoogleMaps.LatLng(-34.397, 150.644),
zoom: 14,
mapTypeId: GoogleMaps.MapTypeId.ROADMAP
};
Global.map = new GoogleMaps.Map(document.getElementById('map'), mapOptions);
}
}
};
}]);
|
var express = require('../')
, Router = express.Router
, request = require('./support/http')
, methods = require('methods')
, assert = require('assert');
describe('Router', function(){
var router, app;
beforeEach(function(){
router = new Router;
app = express();
})
describe('.match(method, url, i)', function(){
it('should match based on index', function(){
router.route('get', '/foo', function(){});
router.route('get', '/foob?', function(){});
router.route('get', '/bar', function(){});
var method = 'GET';
var url = '/foo?bar=baz';
var route = router.match(method, url, 0);
route.constructor.name.should.equal('Route');
route.method.should.equal('get');
route.path.should.equal('/foo');
var route = router.match(method, url, 1);
route.path.should.equal('/foob?');
var route = router.match(method, url, 2);
assert(!route);
url = '/bar';
var route = router.match(method, url);
route.path.should.equal('/bar');
})
})
describe('.matchRequest(req, i)', function(){
it('should match based on index', function(){
router.route('get', '/foo', function(){});
router.route('get', '/foob?', function(){});
router.route('get', '/bar', function(){});
var req = { method: 'GET', url: '/foo?bar=baz' };
var route = router.matchRequest(req, 0);
route.constructor.name.should.equal('Route');
route.method.should.equal('get');
route.path.should.equal('/foo');
var route = router.matchRequest(req, 1);
req._route_index.should.equal(1);
route.path.should.equal('/foob?');
var route = router.matchRequest(req, 2);
assert(!route);
req.url = '/bar';
var route = router.matchRequest(req);
route.path.should.equal('/bar');
})
})
describe('.middleware', function(){
it('should dispatch', function(done){
router.route('get', '/foo', function(req, res){
res.send('foo');
});
app.use(router.middleware);
request(app)
.get('/foo')
.expect('foo', done);
})
})
describe('.multiple callbacks', function(){
it('should throw if a callback is null', function(){
assert.throws(function () {
router.route('get', '/foo', null, function(){});
})
})
it('should throw if a callback is undefined', function(){
assert.throws(function () {
router.route('get', '/foo', undefined, function(){});
})
})
it('should throw if a callback is not a function', function(){
assert.throws(function () {
router.route('get', '/foo', 'not a function', function(){});
})
})
it('should not throw if all callbacks are functions', function(){
router.route('get', '/foo', function(){}, function(){});
})
})
describe('.all', function() {
it('should support using .all to capture all http verbs', function() {
var router = new Router();
router.all('/foo', function(){});
var url = '/foo?bar=baz';
methods.forEach(function testMethod(method) {
var route = router.match(method, url);
route.constructor.name.should.equal('Route');
route.method.should.equal(method);
route.path.should.equal('/foo');
});
})
})
})
|
import {Curve} from '../curve'
export class Line extends Curve {
constructor(p0, v) {
super();
this.p0 = p0;
this.v = v;
this._pointsCache = new Map();
}
intersectSurface(surface) {
if (surface.isPlane) {
const s0 = surface.normal.multiply(surface.w);
return surface.normal.dot(s0.minus(this.p0)) / surface.normal.dot(this.v); // 4.7.4
} else {
return super.intersectSurface(surface);
}
}
intersectCurve(curve, surface) {
if (curve.isLine && surface.isPlane) {
const otherNormal = surface.normal.cross(curve.v)._normalize();
return otherNormal.dot(curve.p0.minus(this.p0)) / otherNormal.dot(this.v); // (4.8.3)
}
return super.intersectCurve(curve, surface);
}
parametricEquation(t) {
return this.p0.plus(this.v.multiply(t));
}
t(point) {
return point.minus(this.p0).dot(this.v);
}
pointOfSurfaceIntersection(surface) {
let point = this._pointsCache.get(surface);
if (!point) {
const t = this.intersectSurface(surface);
point = this.parametricEquation(t);
this._pointsCache.set(surface, point);
}
return point;
}
translate(vector) {
return new Line(this.p0.plus(vector), this.v);
}
approximate(resolution, from, to, path) {
}
offset() {};
}
Line.prototype.isLine = true;
Line.fromTwoPlanesIntersection = function(plane1, plane2) {
const n1 = plane1.normal;
const n2 = plane2.normal;
const v = n1.cross(n2)._normalize();
const pf1 = plane1.toParametricForm();
const pf2 = plane2.toParametricForm();
const r0diff = pf1.r0.minus(pf2.r0);
const ww = r0diff.minus(n2.multiply(r0diff.dot(n2)));
const p0 = pf2.r0.plus( ww.multiply( n1.dot(r0diff) / n1.dot(ww)));
return new Line(p0, v);
};
Line.fromSegment = function(a, b) {
return new Line(a, b.minus(a)._normalize());
};
|
/**
* Swaggy Jenkins
* Jenkins API clients generated from Swagger / Open API specification
*
* The version of the OpenAPI document: 1.1.2-pre.0
* Contact: blah@cliffano.com
*
* NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech).
* https://openapi-generator.tech
* Do not edit the class manually.
*
*/
import ApiClient from '../ApiClient';
import PipelineRunNodeedges from './PipelineRunNodeedges';
/**
* The PipelineRunNode model module.
* @module model/PipelineRunNode
* @version 1.1.2-pre.0
*/
class PipelineRunNode {
/**
* Constructs a new <code>PipelineRunNode</code>.
* @alias module:model/PipelineRunNode
*/
constructor() {
PipelineRunNode.initialize(this);
}
/**
* Initializes the fields of this object.
* This method is used by the constructors of any subclasses, in order to implement multiple inheritance (mix-ins).
* Only for internal use.
*/
static initialize(obj) {
}
/**
* Constructs a <code>PipelineRunNode</code> from a plain JavaScript object, optionally creating a new instance.
* Copies all relevant properties from <code>data</code> to <code>obj</code> if supplied or a new instance if not.
* @param {Object} data The plain JavaScript object bearing properties of interest.
* @param {module:model/PipelineRunNode} obj Optional instance to populate.
* @return {module:model/PipelineRunNode} The populated <code>PipelineRunNode</code> instance.
*/
static constructFromObject(data, obj) {
if (data) {
obj = obj || new PipelineRunNode();
if (data.hasOwnProperty('_class')) {
obj['_class'] = ApiClient.convertToType(data['_class'], 'String');
}
if (data.hasOwnProperty('displayName')) {
obj['displayName'] = ApiClient.convertToType(data['displayName'], 'String');
}
if (data.hasOwnProperty('durationInMillis')) {
obj['durationInMillis'] = ApiClient.convertToType(data['durationInMillis'], 'Number');
}
if (data.hasOwnProperty('edges')) {
obj['edges'] = ApiClient.convertToType(data['edges'], [PipelineRunNodeedges]);
}
if (data.hasOwnProperty('id')) {
obj['id'] = ApiClient.convertToType(data['id'], 'String');
}
if (data.hasOwnProperty('result')) {
obj['result'] = ApiClient.convertToType(data['result'], 'String');
}
if (data.hasOwnProperty('startTime')) {
obj['startTime'] = ApiClient.convertToType(data['startTime'], 'String');
}
if (data.hasOwnProperty('state')) {
obj['state'] = ApiClient.convertToType(data['state'], 'String');
}
}
return obj;
}
}
/**
* @member {String} _class
*/
PipelineRunNode.prototype['_class'] = undefined;
/**
* @member {String} displayName
*/
PipelineRunNode.prototype['displayName'] = undefined;
/**
* @member {Number} durationInMillis
*/
PipelineRunNode.prototype['durationInMillis'] = undefined;
/**
* @member {Array.<module:model/PipelineRunNodeedges>} edges
*/
PipelineRunNode.prototype['edges'] = undefined;
/**
* @member {String} id
*/
PipelineRunNode.prototype['id'] = undefined;
/**
* @member {String} result
*/
PipelineRunNode.prototype['result'] = undefined;
/**
* @member {String} startTime
*/
PipelineRunNode.prototype['startTime'] = undefined;
/**
* @member {String} state
*/
PipelineRunNode.prototype['state'] = undefined;
export default PipelineRunNode;
|
class Client {
constructor(http_client){
this.http_client = http_client
this.method_list = []
}
xyz() {
return this.http_client
}
}
function chainable_client () {
HttpClient = require('./http_client.js')
http_client = new HttpClient(arguments[0])
chainable_method = require('./chainable_method.js')
return chainable_method(new Client(http_client), true)
}
module.exports = chainable_client
|
"use strict";
var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
return c > 3 && r && Object.defineProperty(target, key, r), r;
};
var __metadata = (this && this.__metadata) || function (k, v) {
if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v);
};
var core_1 = require("@angular/core");
var http_1 = require("@angular/http");
var RegService = (function () {
function RegService(_http) {
this._http = _http;
}
RegService.prototype.ngOnInit = function () {
};
RegService.prototype.getUsers = function () {
return this._http.get('http://ankitesh.pythonanywhere.com/api/v1.0/get_books_data')
.map(function (response) { return response.json(); });
};
RegService.prototype.regUser = function (User) {
var payload = JSON.stringify({ payload: { "Username": User.Username, "Email_id": User.Email_id, "Password": User.Password } });
return this._http.post('http://ankitesh.pythonanywhere.com/api/v1.0/get_book_summary', payload)
.map(function (response) { return response.json(); });
};
return RegService;
}());
RegService = __decorate([
core_1.Injectable(),
__metadata("design:paramtypes", [http_1.Http])
], RegService);
exports.RegService = RegService;
//# sourceMappingURL=register.service.js.map
|
/*
* measured-elasticsearch
*
* Copyright (c) 2015 Maximilian Antoni <mail@maxantoni.de>
*
* @license MIT
*/
'use strict';
exports.index = 'metrics-1970.01';
exports.timestamp = '1970-01-01T00:00:00.000Z';
function header(type) {
return {
index : { _type : type}
};
}
exports.headerCounter = header('counter');
exports.headerTimer = header('timer');
exports.headerMeter = header('meter');
exports.headerHistogram = header('histogram');
exports.headerGauge = header('gauge');
|
PLANT_CONFIG = [
{key: 'name', label: 'Name'},
{key: 'scienceName', label: 'Scientific name'}
];
Template.plants.helpers({
plantListConfig: function() {
return PLANT_CONFIG;
}
});
Template.newPlant.helpers({
plantListConfig: function() {
return PLANT_CONFIG;
}
});
Template.newPlant.events({
'submit .newPlantForm': function(event) {
event.preventDefault();
var data = {name:'',scienceName:''};
PLANT_CONFIG.forEach(function(entry){
var $input = $(event.target).find("[name='" + entry.key + "']");
if($input.val()) {
data[entry.key] = $input.val();
}
});
Meteor.call('createPlant', data);
PLANT_CONFIG.forEach(function(entry){
$(event.target).find("[name='" + entry.key + "']").val('');
});
}
});
Template.plantListItem.events({
'click .plant-delete': function(){
Meteor.call('deletePlant', this._id);
}
});
|
a === b
|
module.exports = {
devTemplates: {
files: [{
expand: true,
cwd: '<%= appConfig.rutatemplates %>',
dest:'<%= appConfig.rutadev %>/html',
src: ['**/*']
}]
},
devImages: {
files: [{
expand: true,
cwd: '<%= appConfig.rutaapp %>/img',
dest:'<%= appConfig.rutadev %>/img',
filter: 'isFile',
src: [ '!spr*', '!base64', '*' ]
}]
},
devGeneratedSprites: {
files: [{
expand: true,
cwd: '<%= appConfig.rutaapp %>/img/spr',
dest:'<%= appConfig.rutadev %>/img/spr',
filter: 'isFile',
src: ['**/*']
}]
},
devCSS: {
files: [{
expand: true,
cwd: '<%= appConfig.rutaapp %>/css',
dest:'<%= appConfig.rutadev %>/css',
filter: 'isFile',
src: ['**/*']
}]
},
devJs: {
files: [{
expand: true,
cwd: '<%= appConfig.rutaapp %>/js',
dest:'<%= appConfig.rutadev %>/js',
src: ['**/*']
}]
},
devTests: {
files: [{
expand: true,
cwd: '<%= appConfig.rutaapp %>/test',
dest:'<%= appConfig.rutadev %>/test',
src: ['**/*']
}]
},
proTemplates: {
files: [{
expand: true,
cwd: '<%= appConfig.rutatemplates %>',
dest:'<%= appConfig.rutapro %>/html',
src: ['**/*']
}]
},
proImages: {
files: [{
expand: true,
cwd: '<%= appConfig.rutaapp %>/img',
dest:'<%= appConfig.rutapro %>/img',
filter: 'isFile',
src: [ '!spr*', '!base64', '*' ]
}]
},
proGeneratedSprites: {
files: [{
expand: true,
cwd: '<%= appConfig.rutaapp %>/img/spr',
dest:'<%= appConfig.rutapro %>/img/spr',
filter: 'isFile',
src: ['**/*']
}]
}
};
|
import Ember from 'ember';
export default Ember.Component.extend({
tagName: 'img',
attributeBindings: ['src'],
height: 100,
width: 100,
backgroundColor: 'aaa',
textColor: '555',
format: undefined, // gif, jpg, jpeg, png
text: undefined,
src: Ember.computed('height', 'width', 'backgroundColor', 'textColor', 'format', function() {
// build url for placeholder image
var base = 'http://placehold.it/';
var src = base + this.get('width') + 'x' + this.get('height') + '/';
src += this.get('backgroundColor') + '/' + this.get('textColor');
// check for image format
if (this.get('format')) {
src += '.' + this.get('format');
}
// check for custom placeholder text
if (this.get('text')) {
src += '&text=' + this.get('text');
}
return src;
})
});
|
import database from "../api/database";
import * as types from "../actions/ActionTypes"
const receiveAspects = aspects => ({
type: types.GET_COMMON_ASPECTS,
aspects
});
export const getCommonAspects = () => dispatch => {
database.getCommonAspects(aspects => {
dispatch(receiveAspects(aspects))
})
};
export const loadAll = () => ({
type: types.LOAD_ALL_ASPECTS
});
|
var https = require('https'),
q = require('q'),
cache = require('./cache').cache;
var API_KEY = process.env.TF_MEETUP_API_KEY;
var fetch_events = function () {
var deferred = q.defer();
var options = {
host: 'api.meetup.com',
path: '/2/events?&sign=true&photo-host=public&group_urlname=GOTO-Night-Stockholm&page=20&key=' + API_KEY
};
var callback = function (response) {
var str = '';
response.on('data', function (chunk) {
str += chunk;
});
response.on('end', function () {
var json = JSON.parse(str);
deferred.resolve(json.results);
});
};
var req = https.request(options, callback);
req.on('error', function (e) {
deferred.reject(e);
});
req.end();
return deferred.promise;
};
module.exports.fetch_events = cache(fetch_events, 10000, true, []);
|
/* globals Ember, require */
(function() {
var _Ember;
var id = 0;
var dateKey = new Date().getTime();
if (typeof Ember !== 'undefined') {
_Ember = Ember;
} else {
_Ember = require('ember').default;
}
function symbol() {
return '__ember' + dateKey + id++;
}
function UNDEFINED() {}
function FakeWeakMap(iterable) {
this._id = symbol();
if (iterable === null || iterable === undefined) {
return;
} else if (Array.isArray(iterable)) {
for (var i = 0; i < iterable.length; i++) {
var key = iterable[i][0];
var value = iterable[i][1];
this.set(key, value);
}
} else {
throw new TypeError('The weak map constructor polyfill only supports an array argument');
}
}
if (!_Ember.WeakMap) {
var meta = _Ember.meta;
var metaKey = symbol();
/*
* @method get
* @param key {Object}
* @return {*} stored value
*/
FakeWeakMap.prototype.get = function(obj) {
var metaInfo = meta(obj);
var metaObject = metaInfo[metaKey];
if (metaInfo && metaObject) {
if (metaObject[this._id] === UNDEFINED) {
return undefined;
}
return metaObject[this._id];
}
}
/*
* @method set
* @param key {Object}
* @param value {Any}
* @return {Any} stored value
*/
FakeWeakMap.prototype.set = function(obj, value) {
var type = typeof obj;
if (!obj || (type !== 'object' && type !== 'function')) {
throw new TypeError('Invalid value used as weak map key');
}
var metaInfo = meta(obj);
if (value === undefined) {
value = UNDEFINED;
}
if (!metaInfo[metaKey]) {
metaInfo[metaKey] = {};
}
metaInfo[metaKey][this._id] = value;
return this;
}
/*
* @method has
* @param key {Object}
* @return {Boolean} if the key exists
*/
FakeWeakMap.prototype.has = function(obj) {
var metaInfo = meta(obj);
var metaObject = metaInfo[metaKey];
return (metaObject && metaObject[this._id] !== undefined);
}
/*
* @method delete
* @param key {Object}
*/
FakeWeakMap.prototype.delete = function(obj) {
var metaInfo = meta(obj);
if (this.has(obj)) {
delete metaInfo[metaKey][this._id];
return true;
}
return false;
}
if (typeof WeakMap === 'function' && typeof window !== 'undefined' && window.OVERRIDE_WEAKMAP !== true) {
_Ember.WeakMap = WeakMap;
} else {
_Ember.WeakMap = FakeWeakMap;
}
}
})();
|
import Resolver from 'ember/resolver';
var resolver = Resolver.create();
resolver.namespace = {
modulePrefix: 'todo-app'
};
export default resolver;
|
export { default } from './ui'
export * from './ui.selectors'
export * from './tabs'
|
define("resolver",
[],
function() {
"use strict";
/*
* This module defines a subclass of Ember.DefaultResolver that adds two
* important features:
*
* 1) The resolver makes the container aware of es6 modules via the AMD
* output. The loader's _seen is consulted so that classes can be
* resolved directly via the module loader, without needing a manual
* `import`.
* 2) is able provide injections to classes that implement `extend`
* (as is typical with Ember).
*/
function classFactory(klass) {
return {
create: function (injections) {
if (typeof klass.extend === 'function') {
return klass.extend(injections);
} else {
return klass;
}
}
};
}
var underscore = Ember.String.underscore;
var classify = Ember.String.classify;
var get = Ember.get;
function parseName(fullName) {
var nameParts = fullName.split(":"),
type = nameParts[0], fullNameWithoutType = nameParts[1],
name = fullNameWithoutType,
namespace = get(this, 'namespace'),
root = namespace;
return {
fullName: fullName,
type: type,
fullNameWithoutType: fullNameWithoutType,
name: name,
root: root,
resolveMethodName: "resolve" + classify(type)
};
}
function chooseModuleName(seen, moduleName) {
var underscoredModuleName = Ember.String.underscore(moduleName);
if (moduleName !== underscoredModuleName && seen[moduleName] && seen[underscoredModuleName]) {
throw new TypeError("Ambigous module names: `" + moduleName + "` and `" + underscoredModuleName + "`");
}
if (seen[moduleName]) {
return moduleName;
} else if (seen[underscoredModuleName]) {
return underscoredModuleName;
} else {
return moduleName;
}
}
function resolveOther(parsedName) {
var prefix = this.namespace.modulePrefix;
Ember.assert('module prefix must be defined', prefix);
var pluralizedType = parsedName.type + 's';
var name = parsedName.fullNameWithoutType;
var moduleName = prefix + '/' + pluralizedType + '/' + name;
// allow treat all dashed and all underscored as the same thing
// supports components with dashes and other stuff with underscores.
var normalizedModuleName = chooseModuleName(requirejs._eak_seen, moduleName);
if (requirejs._eak_seen[normalizedModuleName]) {
var module = require(normalizedModuleName, null, null, true /* force sync */);
if (module === undefined) {
throw new Error("Module: '" + name + "' was found but returned undefined. Did you forget to `export default`?");
}
if (Ember.ENV.LOG_MODULE_RESOLVER) {
Ember.Logger.info('hit', moduleName);
}
return module;
} else {
if (Ember.ENV.LOG_MODULE_RESOLVER) {
Ember.Logger.info('miss', moduleName);
}
return this._super(parsedName);
}
}
function resolveTemplate(parsedName) {
return Ember.TEMPLATES[parsedName.name] || Ember.TEMPLATES[Ember.String.underscore(parsedName.name)];
}
// Ember.DefaultResolver docs:
// https://github.com/emberjs/ember.js/blob/master/packages/ember-application/lib/system/resolver.js
var Resolver = Ember.DefaultResolver.extend({
resolveTemplate: resolveTemplate,
resolveOther: resolveOther,
parseName: parseName,
normalize: function(fullName) {
// replace `.` with `/` in order to make nested controllers work in the following cases
// 1. `needs: ['posts/post']`
// 2. `{{render "posts/post"}}`
// 3. `this.render('posts/post')` from Route
return Ember.String.dasherize(fullName.replace(/\./g, '/'));
}
});
return Resolver;
});
|
(function() {
'use strict';
var express = require('express');
var path = require('path');
var logger = require('morgan');
var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser');
var routes = require('./routes/index');
var app = express();
// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.engine('html', require('ejs').renderFile);
app.set('view engine', 'html');
app.use(logger('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({
extended: true
}));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, '../client')));
app.use('/', routes);
app.set('port', process.env.PORT || 3000);
var server = app.listen(app.get('port'), function() {
console.log('Express server listening on port ' + server.address().port);
});
module.exports = app;
}());
|
"use strict";
var C = function () {
function C() {
babelHelpers.classCallCheck(this, C);
}
babelHelpers.createClass(C, [{
key: "m",
value: function m(x) {
return 'a';
}
}]);
return C;
}();
|
var assert = require('assert');
var fs = require('fs');
var requireFiles = require(__dirname + '/../lib/requireFiles');
var files = [
__dirname + '/moch/custom_test.txt',
__dirname + '/moch/json_test.json',
__dirname + '/moch/test.js'
];
describe('requireFiles testing', function(){
describe('Structure type', function(){
it('requireFiles should be a function', function(){
assert.equal(typeof requireFiles, 'function');
});
});
describe('Error', function(){
it('Should throw error when an engine isn\'t supported', function(){
assert.throws(function(){
requireFiles(files, {
'.js' : require,
'.json' : require
});
}, /there is no engine registered/);
});
it('Should not throw an error when everything is ok', function(){
assert.doesNotThrow(function(){
result = requireFiles(files.slice(1, 3), {
'.js' : require,
'.json' : require
});
});
});
});
describe('Custom engine', function(){
it('Custom engines should work', function(){
var result = requireFiles(files, {
'.js' : require,
'.json' : require,
'.txt' : function(path){
return fs.readFileSync(path).toString();
}
});
assert.equal(result[files[0]], 'worked\n');
assert.equal(result[files[1]].worked, true);
assert.equal(result[files[2]], 'worked');
});
});
});
|
export default function() {
var links = [
{
icon: "fa-sign-in",
title: "Login",
url: "/login"
},
{
icon: "fa-dashboard",
title: "Dashboard",
url: "/"
},
{
icon: "fa-calendar",
title: "Scheduler",
url: "/scheduler"
}
];
return m("#main-sidebar", [
m("ul", {class: "navigation"},
links.map(function(link) {
return m("li", [
m("a", {href: link.url, config: m.route}, [
m("i.menu-icon", {class: "fa " + link.icon}), " ", link.title
])
]);
})
)
]);
}
|
const Koa = require('koa');
const http = require('http');
const destroyable = require('server-destroy');
const bodyParser = require('koa-bodyparser');
const session = require('koa-session');
const passport = require('koa-passport');
const serve = require('koa-static');
const db = require('./db');
const config = require('./config');
const router = require('./routes');
const authStrategies = require('./authStrategies');
const User = require('./models/User');
const app = new Koa();
app.use(bodyParser());
app.keys = [config.get('session_secret')];
app.use(session({}, app));
authStrategies.forEach(passport.use, passport);
passport.serializeUser((user, done) => {
done(null, user.twitterId);
});
passport.deserializeUser(async (twitterId, done) => {
const user = await User.findOne({ twitterId });
done(null, user);
});
app.use(passport.initialize());
app.use(passport.session());
app.use(router.routes());
app.use(router.allowedMethods());
app.use(serve('public'));
app.use(async (ctx, next) => {
await next();
if (ctx.status === 404) {
ctx.redirect('/');
}
});
const server = http.createServer(app.callback());
module.exports = {
start() {
db.start().then(() => {
server.listen(config.get('port'));
destroyable(server);
});
},
stop() {
server.destroy();
db.stop();
},
};
|
PhotoAlbums.Router.map(function() {
this.resource('login');
this.resource('album', {path: '/:album_id'});
this.resource('photo', {path: 'photos/:photo_id'});
});
|
import { h, Component } from 'preact';
import moment from 'moment';
const MonthPicker = ({ onChange, ...props }) => (
<select onChange={onChange} id="select-month">{ optionsFor("month", props.date) }</select>
);
const DayPicker = ({ onChange, ...props }) => (
<select onChange={onChange} id="select-date">{ optionsFor("day", props.date) }</select>
);
const YearPicker = ({ onChange, ...props }) => (
<select onChange={onChange} id="select-year">{ optionsFor("year", props.date) }</select>
);
const months = ['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December']
const startYear = 1930;
const endYear = 2018;
function optionsFor(field, selectedDate) {
if (field === 'year') {
selected = selectedDate.year();
return [...Array(endYear-startYear).keys()].map((item, i) => {
var isSelected = (startYear + item) == selected;
return (
<option value={startYear + item} selected={isSelected ? 'selected' : ''}>{startYear + item}</option>
);
});
}
else if (field === 'month') {
selected = selectedDate.month();
return months.map((item, i) => {
var isSelected = i == selected;
return (
<option value={i} selected={isSelected ? 'selected' : ''}>{item}</option>
);
});
}
else if (field === 'day') {
var selected = selectedDate.date();
var firstDay = 1;
var lastDay = moment(selectedDate).add(1, 'months').date(1).subtract(1, 'days').date() + 1;
return [...Array(lastDay-firstDay).keys()].map((item, i) => {
var isSelected = (item + 1) == selected;
return (
<option value={item + 1} selected={isSelected ? 'selected': ''}>{item + 1}</option>
)
});
}
}
export default class DatePicker extends Component {
constructor(props) {
super(props);
this.state = {
date: props.date
};
this.onChange = this.onChange.bind(this);
}
onChange(event) {
var month = document.getElementById('select-month').value;
var day = document.getElementById('select-date').value;
var year = document.getElementById('select-year').value;
var newDate = moment().year(year).month(month).date(day);
this.setState({ date: newDate })
this.props.onChange(newDate);
}
render() {
return (
<div>
<MonthPicker date={this.state.date} onChange={this.onChange} />
<DayPicker date={this.state.date} onChange={this.onChange} />
<YearPicker date={this.state.date} onChange={this.onChange} />
</div>
)
}
}
|
'use strict';
angular.module('users').factory('Permissions', ['Authentication', '$location',
function(Authentication, $location) {
// Permissions service logic
// ...
// Public API
return {
//check if user suits the right permissions for visiting the page, Otherwise go to 401
userRolesContains: function (role) {
if (!Authentication.user || Authentication.user.roles.indexOf(role) === -1) {
return false;
} else {
return true;
}
},
//This function returns true if the user is either admin or maintainer
adminOrMaintainer: function () {
if (Authentication.user && (Authentication.user.roles.indexOf('admin')> -1 || Authentication.user.roles.indexOf('maintainer')> -1)) {
return true;
} else {
return false;
}
},
isPermissionGranted: function (role) {
if (!Authentication.user || Authentication.user.roles.indexOf(role) === -1) {
$location.path('/401');
}
},
isAdmin: function () {
if (Authentication.user && (Authentication.user.roles.indexOf('admin') > -1)) {
return true;
} else {
return false;
}
}
};
}
]);
|
import $ from 'jquery';
import keyboard from 'virtual-keyboard';
$.fn.addKeyboard = function () {
return this.keyboard({
openOn: null,
stayOpen: false,
layout: 'custom',
customLayout: {
'normal': ['7 8 9 {c}', '4 5 6 {del}', '1 2 3 {sign}', '0 0 {dec} {a}'],
},
position: {
// null (attach to input/textarea) or a jQuery object (attach elsewhere)
of: null,
my: 'center top',
at: 'center top',
// at2 is used when "usePreview" is false (centers keyboard at the bottom
// of the input/textarea)
at2: 'center top',
collision: 'flipfit flipfit'
},
reposition: true,
css: {
input: 'form-control input-sm',
container: 'center-block dropdown-menu',
buttonDefault: 'btn btn-default',
buttonHover: 'btn-light',
// used when disabling the decimal button {dec}
// when a decimal exists in the input area
buttonDisabled: 'enabled',
},
});
};
|
/**
* Trait class
*/
function Trait(methods, allTraits) {
allTraits = allTraits || [];
this.traits = [methods];
var extraTraits = methods.$traits;
if (extraTraits) {
if (typeof extraTraits === "string") {
extraTraits = extraTraits.replace(/ /g, '').split(',');
}
for (var i = 0, c = extraTraits.length; i < c; i++) {
this.use(allTraits[extraTraits[i]]);
}
}
}
Trait.prototype = {
constructor: Trait,
use: function (trait) {
if (trait) {
this.traits = this.traits.concat(trait.traits);
}
return this;
},
useBy: function (obj) {
for (var i = 0, c = this.traits.length; i < c; i++) {
var methods = this.traits[i];
for (var prop in methods) {
if (prop !== '$traits' && !obj[prop] && methods.hasOwnProperty(prop)) {
obj[prop] = methods[prop];
}
}
}
}
};
module.exports = Trait;
|
(function(){
'use strict';
angular.module('GamemasterApp')
.controller('DashboardCtrl', function ($scope, $timeout, $mdSidenav, $http) {
$scope.users = ['Fabio', 'Leonardo', 'Thomas', 'Gabriele', 'Fabrizio', 'John', 'Luis', 'Kate', 'Max'];
})
})();
|
End of preview. Expand
in Data Studio
README.md exists but content is empty.
- Downloads last month
- 101