text
stringlengths 2
6.14k
|
|---|
/**
* Auction collection
*/
'use strict';
var Model = require('../models/auction_model.js');
var Collection = require('tungstenjs/adaptors/backbone').Collection;
var AuctionCollection = Collection.extend({
model: Model
});
module.exports = AuctionCollection;
|
// Regular expression that matches all symbols in the Devanagari Extended block as per Unicode v6.0.0:
/[\uA8E0-\uA8FF]/;
|
// All code points in the `Hatran` script as per Unicode v10.0.0:
[
0x108E0,
0x108E1,
0x108E2,
0x108E3,
0x108E4,
0x108E5,
0x108E6,
0x108E7,
0x108E8,
0x108E9,
0x108EA,
0x108EB,
0x108EC,
0x108ED,
0x108EE,
0x108EF,
0x108F0,
0x108F1,
0x108F2,
0x108F4,
0x108F5,
0x108FB,
0x108FC,
0x108FD,
0x108FE,
0x108FF
];
|
import React, {Component, PropTypes} from 'react';
import * as actions from './ForumAction';
import ForumPage from './ForumPage';
class ForumContainer extends Component {
constructor(props) {
super(props);
this.state = {
questions: []
};
this.postQuestion = this.postQuestion.bind(this);
}
postQuestion(model) {
actions.postQuestion(model).then(response => {
const questions = this.state.questions.concat([response]);
this.setState({questions});
});
}
componentDidMount() {
actions.getQuestions().then(response => {
this.setState({questions: response});
});
}
render() {
return <ForumPage {...this.state} postQuestion={this.postQuestion}/>;
}
}
export default ForumContainer;
|
((bbn)=>{let script=document.createElement('script');script.innerHTML=`<div :class="['bbn-iblock', componentClass]">
<input class="bbn-hidden"
ref="element"
:value="modelValue"
:disabled="disabled"
:required="required"
>
<div :style="getStyle()">
<div v-for="(d, idx) in source"
:class="{
'bbn-iblock': !vertical,
'bbn-right-space': !vertical && !separator && source[idx+1],
'bbn-bottom-sspace': !!vertical && !separator && source[idx+1]
}"
>
<input :value="d[sourceValue]"
:name="name"
class="bbn-radio"
type="radio"
:disabled="disabled || d.disabled"
:required="required"
:id="id + '_' + idx"
@change="changed(d[sourceValue], d, $event)"
:checked="d[sourceValue] === modelValue"
>
<label class="bbn-radio-label bbn-iflex bbn-vmiddle"
:for="id + '_' + idx"
>
<span class="bbn-left-sspace"
v-html="render ? render(d) : d[sourceText]"
></span>
</label>
<br v-if="!vertical && step && ((idx+1) % step === 0)">
<div v-if="(source[idx+1] !== undefined) && !!separator"
:class="{
'bbn-w-100': vertical,
'bbn-iblock': !vertical
}"
v-html="separator"
></div>
</div>
</div>
</div>`;script.setAttribute('id','bbn-tpl-component-radio');script.setAttribute('type','text/x-template');document.body.insertAdjacentElement('beforeend',script);(function(bbn){"use strict";Vue.component('bbn-radio',{mixins:[bbn.vue.basicComponent,bbn.vue.inputComponent,bbn.vue.localStorageComponent,bbn.vue.eventsComponent],props:{separator:{type:String},vertical:{type:Boolean,default:false},step:{type:Number},id:{type:String,default(){return bbn.fn.randomString(10,25);}},render:{type:Function},sourceText:{type:String,default:'text'},sourceValue:{type:String,default:'value'},source:{type:Array,default(){return[{text:bbn._("Yes"),value:1},{text:bbn._("No"),value:0}];}},modelValue:{type:[String,Boolean,Number],default:undefined}},model:{prop:'modelValue',event:'input'},methods:{changed(val,d,e){this.$emit('input',val);this.$emit('change',val,d,e);},getStyle(){if(this.step&&!this.vertical){return'display: grid; grid-template-columns: '+'auto '.repeat(this.step)+';';}
else{return'';}}},beforeMount(){if(this.hasStorage){let v=this.getStorage();if(v&&(v!==this.modelValue)){this.changed(v);}}},watch:{modelValue(v){if(this.storage){if(v){this.setStorage(v);}
else{this.unsetStorage()}}},}});})(bbn);})(bbn);
|
import {StringUtils} from "../node_modules/igv-utils/src/index.js"
class Locus {
constructor({chr, start, end}) {
this.chr = chr
this.start = start
this.end = end
}
contains(locus) {
return locus.chr === this.chr && locus.start >= this.start && locus.end <= this.end
}
overlaps(locus) {
return locus.chr === this.chr && !(locus.end < this.start || locus.start > this.end)
}
extend(l) {
if (l.chr !== this.chr) return
this.start = Math.min(l.start, this.start)
this.end = Math.max(l.end, this.end)
}
getLocusString() {
if ('all' === this.chr) {
return 'all'
} else {
const ss = StringUtils.numberFormatter(Math.floor(this.start) + 1)
const ee = StringUtils.numberFormatter(Math.round(this.end))
return `${this.chr}:${ss}-${ee}`
}
}
static fromLocusString(str) {
if ('all' === str) {
return new Locus({chr: 'all'})
}
const parts = str.split(':')
const chr = parts[0]
const se = parts[1].split("-")
const start = Number.parseInt(se[0].replace(/,/g, "")) - 1
const end = Number.parseInt(se[1].replace(/,/g, ""))
return new Locus({chr, start, end})
}
}
export default Locus
|
(function () {
'use strict';
var app = angular.module('app');
// Collect the routes
app.constant('routes', getRoutes());
// Configure the routes and route resolvers
app.config(['$routeProvider', 'routes', routeConfigurator]);
function routeConfigurator($routeProvider, routes) {
routes.forEach(function (r) {
$routeProvider.when(r.url, r.config);
});
$routeProvider.otherwise({ redirectTo: '/' });
}
// Define the routes
function getRoutes() {
return [
{
url: '/',
config: {
templateUrl: 'app/dashboard/dashboard.html',
title: 'dashboard',
settings: {
nav: 1,
content: '<i class="fa fa-dashboard"></i> Dashboard'
}
}
}, {
url: '/admin',
config: {
title: 'admin',
templateUrl: 'app/admin/admin.html',
settings: {
nav: 2,
content: '<i class="fa fa-lock"></i> Admin'
}
},
access: {
requiresLogin: true,
requiredPermissions: ['Admin', 'UserManager'],
permissionType: 'AtLeastOne'
}
}, {
url: '/proposals',
config: {
title: 'proposals',
templateUrl: 'app/proposal/proposals.html',
settings: {
nav: 3,
content: '<i class="fa fa-sticky-note-o"></i> Proposals'
}
}
}, {
url: '/register',
config: {
title: 'register',
templateUrl: 'app/authentication/register.html',
settings: {
}
}
},
{
url: '/communities',
config: {
title: 'communities',
templateUrl: 'app/communities/communities.html',
settings: {
nav: 4,
content: '<i class="fa fa-group"></i> Communities'
}
}
},
{
url: '/login',
config: {
title: 'login',
templateUrl: 'app/authentication/login.html',
settings: {
}
}
},
{
url: '/register-admin',
config: {
title: 'register-admin',
templateUrl: 'app/authentication/register-admin.html',
settings: {
}
}
},
{
url: '/add-proposal',
config: {
title: 'add-proposal',
templateUrl: 'app/proposal/add-proposal.html',
settings: {
}
}
},
{
url: '/add-community',
config: {
title: 'add-community',
templateUrl: 'app/communities/add-community.html',
settings: {
}
}
}
];
}
})();
|
import Ember from 'ember';
import layout from './template';
export default Ember.Component.extend({
layout: layout,
classNames: ['kit-canvas-scroller'],
canvasStyle: Ember.computed('parentView.canvasStyle', function() {
return this.get('parentView').get('canvasStyle');
}),
numberOfItems: Ember.computed('parentView', function() {
return this.$('.kit-canvas-content').children().length;
}),
willInsertElement: Ember.on('willInsertElement', function() {
this.get('parentView').set('scroller', this);
}),
});
|
function test() {
for(var i=1; i<3; i++) {
console.log("inner i: " + i);
}
console.log("outer i: " + i);
}
function last() {
const PI = 3.1415926;
console.log(PI);
}
// test();
last();
|
'use strict';
module.exports = {
controller: function (args) {
this.config = _.merge({
salvar: _.noop,
publicar: _.noop,
descartar: _.noop,
visualizar: _.noop,
editar: _.noop
}, args);
},
view: function (ctrl) {
var salvarView = '';
if (ctrl.config.salvar !== _.noop) {
salvarView = m.component(require('cabecalho/salvar-button'), {
salvar: ctrl.config.salvar,
salvandoServico: ctrl.config.salvandoServico,
caiuSessao: ctrl.config.caiuSessao,
orgaoId: ctrl.config.orgaoId
});
}
var visualizarView = '';
if (ctrl.config.visualizar !== _.noop) {
visualizarView = m.component(require('cabecalho/visualizar-button'), {
visualizar: ctrl.config.visualizar,
salvandoServico: ctrl.config.salvandoServico,
caiuSessao: ctrl.config.caiuSessao
});
}
var publicarView = '';
if (ctrl.config.publicar !== _.noop) {
publicarView = m.component(require('cabecalho/publicar-view'), {
publicar: ctrl.config.publicar,
descartar: ctrl.config.descartar,
metadados: ctrl.config.cabecalho.metadados(),
salvandoServico: ctrl.config.salvandoServico,
caiuSessao: ctrl.config.caiuSessao,
orgaoId: ctrl.config.orgaoId
});
}
var editarView = '';
if (ctrl.config.editar !== _.noop) {
editarView = m.component(require('cabecalho/editar-button'), {
editar: ctrl.config.editar
});
}
return m('#metadados', [
m.component(require('componentes/status-conexao'), {
salvandoServico: ctrl.config.salvandoServico,
caiuSessao: ctrl.config.caiuSessao
}),
salvarView,
visualizarView,
publicarView,
editarView,
]);
}
};
|
/*
The parser for parsing US's date format that begin with month's name.
EX.
- January 13
- January 13, 2012
- January 13 - 15, 2012
- Tuesday, January 13, 2012
*/
var moment = require('moment');
require('moment-timezone');
var Parser = require('../parser').Parser;
var ParsedResult = require('../../result').ParsedResult;
var DAYS_OFFSET = { 'sunday': 0, 'sun': 0, 'monday': 1, 'mon': 1,'tuesday': 2, 'tue':2, 'wednesday': 3, 'wed': 3,
'thursday': 4, 'thur': 4, 'thu': 4,'friday': 5, 'fri': 5,'saturday': 6, 'sat': 6,}
var regFullPattern = /(\W|^)((Sunday|Monday|Tuesday|Wednesday|Thursday|Friday|Saturday|Sun|Mon|Tue|Wed|Thu|Fri|Sat)\s*,?\s*)?(Jan|January|Feb|February|Mar|March|Apr|April|May|Jun|June|Jul|July|Aug|August|Sep|September|Oct|October|Nov|November|Dec|December)\s*(([0-9]{1,2})(st|nd|rd|th)?\s*(to|\-)\s*)?([0-9]{1,2})(st|nd|rd|th)?(,)?(\s*[0-9]{4})(\s*BE)?(\W|$)/i;
var regShortPattern = /(\W|^)((Sunday|Monday|Tuesday|Wednesday|Thursday|Friday|Saturday|Sun|Mon|Tue|Wed|Thu|Fri|Sat)\s*,?\s*)?(Jan|January|Feb|February|Mar|March|Apr|April|May|Jun|June|Jul|July|Aug|August|Sep|September|Oct|October|Nov|November|Dec|December)\s*(([0-9]{1,2})(st|nd|rd|th)?\s*(to|\-)\s*)?([0-9]{1,2})(st|nd|rd|th)?([^0-9]|$)/i;
exports.Parser = function ENMonthNameMiddleEndianParser(){
Parser.call(this);
this.pattern = function() { return regShortPattern; }
this.extract = function(text, ref, match, opt){
var result = new ParsedResult();
var impliedComponents = [];
var date = null;
var originalText = '';
var index = match.index;
text = text.substr(index);
var match = text.match(regFullPattern);
if(match && text.indexOf(match[0]) == 0){
var text = match[0];
text = text.substring(match[1].length, match[0].length - match[14].length);
index = index + match[1].length;
originalText = text;
text = text.replace(match[2], '');
text = text.replace(match[4], match[4]+' ');
if(match[5]) text = text.replace(match[5],'');
if(match[10]) text = text.replace(match[10],'');
if(match[11]) text = text.replace(',',' ');
if(match[13]){
var years = match[12];
years = ' ' + (parseInt(years) - 543);
text = text.replace(match[13], '');
text = text.replace(match[12], years);
}
text = text.replace(match[9],parseInt(match[9])+'');
date = moment(text,'MMMM DD YYYY');
if(!date) return null;
result.start.assign('day', date.date());
result.start.assign('month', date.month() + 1);
result.start.assign('year', date.year());
} else {
match = text.match(regShortPattern);
if(!match) return null;
//Short Pattern (without years)
var text = match[0];
text = text.substring(match[1].length, match[0].length - match[11].length);
index = index + match[1].length;
originalText = text;
text = text.replace(match[2], '');
text = text.replace(match[4], match[4]+' ');
if(match[4]) text = text.replace(match[5],'');
date = moment(text,'MMMM DD');
if(!date) return null;
//Find the most appropriated year
impliedComponents.push('year')
date.year(moment(ref).year());
var nextYear = date.clone().add(1, 'year');
var lastYear = date.clone().add(-1, 'year');
if( Math.abs(nextYear.diff(moment(ref))) < Math.abs(date.diff(moment(ref))) ){
date = nextYear;
}
else if( Math.abs(lastYear.diff(moment(ref))) < Math.abs(date.diff(moment(ref))) ){
date = lastYear;
}
result.start.assign('day', date.date());
result.start.assign('month', date.month() + 1);
result.start.imply('year', date.year());
}
//Day of week
if(match[3]) {
result.start.assign('weekday', DAYS_OFFSET[match[3].toLowerCase()]);
}
if (match[5]) {
var endDay = parseInt(match[9]);
var startDay = parseInt(match[6]);
result.end = result.start.clone();
result.start.assign('day', startDay);
result.end.assign('day', endDay);
var endDate = date.clone();
date.date(startDay);
endDate.date(endDay);
}
result.index = index;
result.text = originalText;
result.ref = ref;
result.tags['ENMonthNameMiddleEndianParser'] = true;
return result;
}
}
|
'use strict';
import React, {PureComponent} from 'react';
import {StyleSheet, View, Text} from 'react-native';
import withMaterialTheme from './styles/withMaterialTheme';
import {withMeasurementForwarding} from './util';
import * as typo from './styles/typo';
import shades from './styles/shades';
/**
* Section heading
*/
class Subheader extends PureComponent {
static defaultProps = {
inset: false,
lines: 1,
};
render() {
const {
materialTheme,
style,
textStyle,
inset,
text,
lines,
secondary,
color: colorOverride,
dark,
light,
...textProps
} = this.props;
let color;
if ( colorOverride ) {
color = colorOverride;
} else if ( dark || light ) {
const theme = dark ? 'dark' : 'light';
if ( secondary ) color = shades[theme].secondaryText;
else color = shades[theme].primaryText;
} else {
if ( secondary ) color = materialTheme.text.secondaryColor;
else color = materialTheme.text.primaryColor;
}
return (
<View
ref={this._setMeasureRef}
style={[
styles.container,
inset && styles.inset,
style,
styles.containerOverrides
]}>
<Text
{...textProps}
numberOfLines={lines}
style={[
styles.text,
textStyle,
{color}
]}>
{text}
</Text>
</View>
);
}
}
export default withMaterialTheme(withMeasurementForwarding(Subheader));
const styles = StyleSheet.create({
container: {
height: 48,
paddingHorizontal: 16,
},
containerOverrides: {
flexDirection: 'row',
alignItems: 'center',
},
inset: {
paddingRight: 16,
paddingLeft: 72,
},
text: {
...typo.fontMedium,
fontSize: 14,
},
});
|
import { onChange, getBits } from '../state'
import { inputWidth, centerInputs } from './inputs'
const $bits = document.getElementById('bits')
const setBitsWidth = width => {
$bits.style.width = inputWidth(width)
centerInputs()
}
const setBitsValue = value => {
setBitsWidth(value.length)
$bits.value = value
}
$bits.addEventListener('input', ({ target: { value } }) => {
setBits(value)
}, false)
$bits.addEventListener('keydown', ({ keyCode }) => {
if (keyCode === 13) { // On Enter
setBitsValue(getBits())
}
}, false)
const { setBits } = onChange(() => {
setBitsValue(getBits())
})
|
var plugin = require("./plugin");
module.exports = function(PluginHost) {
var app = PluginHost.owner;
/**
* used like so:
* --external-aliases privateapi,privateAPI,hiddenAPI
* or
* -ea privateapi,privateAPI
*/
app.options.addDeclaration({ name: 'external-aliases', short: 'ea' });
/**
* used like so:
* --internal-aliases publicapi
* or
* -ia publicapi
*/
app.options.addDeclaration({ name: 'internal-aliases', short: 'ia' });
app.converter.addComponent('internal-external', plugin.InternalExternalPlugin);
};
|
var gulp = require('gulp'),
plugins = require('gulp-load-plugins')(),
Karma = require('karma').Server;
var paths = {
scripts: {
src: ['src/**/*.js'],
dest: 'dist',
file: 'mention.js'
},
styles: {
src: ['src/**/*.scss'],
dest: 'dist',
file: 'mention.css'
},
example: {
scripts: {
src: ['example/**/*.es6.js'],
dest: 'example',
file: 'example.js'
},
styles: {
src: ['example/**/*.scss'],
dest: 'example'
}
}
};
gulp.task('default', ['scripts']);
gulp.task('example', ['scripts:example', 'styles:example']);
gulp.task('watch', function(){
gulp.watch(paths.scripts.src, 'scripts');
gulp.watch(paths.styles.src, 'styles');
});
gulp.task('watch:example', function(){
gulp.watch(paths.example.scripts.src, 'scripts:example');
gulp.watch(paths.example.styles.src, 'styles:example');
});
gulp.task('scripts', scripts(paths.scripts));
gulp.task('scripts:example', scripts(paths.example.scripts));
function scripts(path, concat) {
return function() {
return gulp.src(path.src)
.pipe(plugins.sourcemaps.init())
.pipe(plugins.babel())
.pipe(plugins.angularFilesort())
.pipe(plugins.concat(path.file))
.pipe(gulp.dest(path.dest))
.pipe(plugins.uglify({ mangle: false }))
.pipe(plugins.extReplace('.min.js'))
.pipe(gulp.dest(path.dest))
.pipe(plugins.sourcemaps.write('.'));
}
}
gulp.task('styles', styles(paths.styles));
gulp.task('styles:example', styles(paths.example.styles));
function styles(path) {
return function() {
return gulp.src(path.src)
.pipe(plugins.sourcemaps.init())
.pipe(plugins.sass())
.pipe(gulp.dest(path.dest))
.pipe(plugins.sourcemaps.write('.'));
}
}
gulp.task('karma', karma());
gulp.task('watch:karma', karma({ singleRun: false, autoWatch: true }));
function karma (opts) {
opts = opts || {};
opts.configFile = __dirname + '/karma.conf.js';
return function (done) {
return new Karma(opts, done).start();
}
}
|
import { StyleSheet } from 'react-native'
const s = StyleSheet.create({
flexRowAround: {
flexDirection: 'row',
justifyContent: 'space-around',
},
dot: {
height: 7,
width: 7,
borderRadius: 3.5,
},
green: {
color: '#50d2c2',
},
flexWrap: {
flexWrap: 'wrap',
},
textCenter: {
textAlign: 'center',
},
flex: {
flex: 1,
},
activeMonth:{
backgroundColor: '#50d2c2',
borderRadius: 5
},
justifyCenter: {
justifyContent: 'center',
},
alignCenter: {
alignItems: 'center',
},
row: {
flexDirection: 'row',
},
column: {
flexDirection: 'column',
},
flexAround: {
justifyContent: 'space-around',
},
flexBetween: {
justifyContent: 'space-between',
},
activeWeek: {
backgroundColor: '#50d2c2',
},
activeCalender: {
backgroundColor: '#fff',
},
pTop: {
paddingTop: 13,
paddingBottom: 5,
},
pBottom: {
paddingBottom: 13,
},
p: {
paddingTop: 13,
paddingBottom: 13,
},
weekView: {
backgroundColor: '#f8f8f8',
},
calenderView: {
backgroundColor: '#50d2c2',
},
disabledMonth: {
color: '#9be5db',
},
white: {
color: '#fff',
},
backWhite: {
backgroundColor: '#fff',
},
});
export default s
export const setHeight = height => ({ height });
export const setWidth = width => ({ width });
export const setPaddingTop = paddingTop => ({ paddingTop });
export const setPaddingBottom = paddingBottom => ({ paddingBottom });
export const setPaddingLeft = paddingLeft => ({ paddingLeft });
export const setPaddingRight = paddingRight => ({ paddingRight });
export const setFontSize = fontSize => ({ fontSize });
export const setFlex = flex => ({ flex });
export const setColor = color => ({ color });
export const setBackGroundColor = backgroundColor => ({ backgroundColor });
export const setBorderColor = borderColor => ({ borderColor });
export const setPosition = position => ({ position });
export const setBottom = bottom => ({ bottom });
export const setLeft = left => ({ left });
export const setRight = right => ({ right });
export const setTop = top => ({ top });
export const setMarginTop = marginTop => ({ marginTop });
export const setMarginBottom = marginBottom => ({ marginBottom });
export const setMarginLeft = marginLeft => ({ marginLeft });
export const setMarginRight = marginRight => ({ marginRight });
export const setPadding = function() {
switch (arguments.length) {
case 1:
return { paddinTop: arguments[0] }
case 2:
return { paddingTop: arguments[0], paddingRight: arguments[1] }
case 3:
return { paddingTop: arguments[0], paddingRight: arguments[1], paddingBottom: arguments[2] }
case 4:
return { paddingTop: arguments[0], paddingRight: arguments[1], paddingBottom: arguments[2], paddingLeft: arguments[3] }
default:
return { padding: arguments[0] }
}
}
export const setMargin = function() {
switch (arguments.length) {
case 1:
return { paddinTop: arguments[0] }
case 2:
return { marginTop: arguments[0], marginRight: arguments[1] }
case 3:
return { marginTop: arguments[0], marginRight: arguments[1], marginBottom: arguments[2] }
case 4:
return { marginTop: arguments[0], marginRight: arguments[1], marginBottom: arguments[2], marginLeft: arguments[3] }
default:
return { margin: arguments[0] }
}
}
|
exports.CLI = require(__dirname + '/lib/cli');
exports.Events = require(__dirname + '/lib/events');
|
var Dispatcher = require('flux').Dispatcher;
var assign = require('object-assign')
var AppDispatcher = assign(new Dispatcher(), {
handleViewAction: function(action) {
this.dispatch({
actionType: 'VIEW_ACTION',
action: action
});
},
handleServerAction: function(action) {
this.dispatch({
actionType: 'SERVER_ACTION',
action: action
});
}
});
module.exports = AppDispatcher;
|
(function(){
angular.module('list-products', [])
.directive('productInfo', function() {
return {
restrict: 'E',
templateUrl: 'partials/product-info.html'
}
})
.directive('productForm', function() {
return {
restrict: 'E',
templateUrl: 'partials/product-form.html',
controller: function() {
this.review = {};
this.item = {mark:{}};
this.addReview = function(item) {
item.reviews.push(this.review);
this.review = {};
};
},
controllerAs: 'reviewCtrl',
scope: {
items: "=",
marks: "="
}
};
})
.directive('productPanels', function() {
return {
restrict: 'E',
templateUrl: 'partials/product-panels.html',
controller: function(){
this.tab = 1;
this.selectTab = function(setTab) {
this.tab = setTab;
};
this.isSelected = function(checkTab) {
return checkTab === this.tab;
};
},
controllerAs: 'panelCtrl',
scope: {
items: "=",
marks: "="
}
};
});
})();
|
angular.module('material.animations')
.directive('inkRipple', [
'$materialInkRipple',
InkRippleDirective
])
.factory('$materialInkRipple', [
'$window',
'$$rAF',
'$materialEffects',
'$timeout',
InkRippleService
]);
function InkRippleDirective($materialInkRipple) {
return function(scope, element, attr) {
if (attr.inkRipple == 'checkbox') {
$materialInkRipple.attachCheckboxBehavior(element);
} else {
$materialInkRipple.attachButtonBehavior(element);
}
};
}
function InkRippleService($window, $$rAF, $materialEffects, $timeout) {
// TODO fix this. doesn't support touch AND click devices (eg chrome pixel)
var hasTouch = !!('ontouchend' in document);
var POINTERDOWN_EVENT = hasTouch ? 'touchstart' : 'mousedown';
var POINTERUP_EVENT = hasTouch ? 'touchend touchcancel' : 'mouseup mouseleave';
return {
attachButtonBehavior: attachButtonBehavior,
attachCheckboxBehavior: attachCheckboxBehavior,
attach: attach
};
function attachButtonBehavior(element) {
return attach(element, {
mousedown: true,
center: false,
animationDuration: 350,
mousedownPauseTime: 175,
animationName: 'inkRippleButton',
animationTimingFunction: 'linear'
});
}
function attachCheckboxBehavior(element) {
return attach(element, {
mousedown: true,
center: true,
animationDuration: 300,
mousedownPauseTime: 180,
animationName: 'inkRippleCheckbox',
animationTimingFunction: 'linear'
});
}
function attach(element, options) {
// Parent element with noink attr? Abort.
if (element.controller('noink')) return angular.noop;
options = angular.extend({
mousedown: true,
hover: true,
focus: true,
center: false,
animationDuration: 300,
mousedownPauseTime: 150,
animationName: '',
animationTimingFunction: 'linear'
}, options || {});
var rippleContainer;
var node = element[0];
if (options.mousedown) {
listenPointerDown(true);
}
// Publish self-detach method if desired...
return function detach() {
listenPointerDown(false);
if (rippleContainer) {
rippleContainer.remove();
}
};
function listenPointerDown(shouldListen) {
element[shouldListen ? 'on' : 'off'](POINTERDOWN_EVENT, onPointerDown);
}
function rippleIsAllowed() {
return !Util.isParentDisabled(element);
}
function createRipple(left, top, positionsAreAbsolute) {
var rippleEl = angular.element('<div class="material-ripple">')
.css($materialEffects.ANIMATION_DURATION, options.animationDuration + 'ms')
.css($materialEffects.ANIMATION_NAME, options.animationName)
.css($materialEffects.ANIMATION_TIMING, options.animationTimingFunction)
.on($materialEffects.ANIMATIONEND_EVENT, function() {
rippleEl.remove();
});
if (!rippleContainer) {
rippleContainer = angular.element('<div class="material-ripple-container">');
element.append(rippleContainer);
}
rippleContainer.append(rippleEl);
var containerWidth = rippleContainer.prop('offsetWidth');
if (options.center) {
left = containerWidth / 2;
top = rippleContainer.prop('offsetHeight') / 2;
} else if (positionsAreAbsolute) {
var elementRect = node.getBoundingClientRect();
left -= elementRect.left;
top -= elementRect.top;
}
var css = {
'background-color': $window.getComputedStyle(rippleEl[0]).color ||
$window.getComputedStyle(node).color,
'border-radius': (containerWidth / 2) + 'px',
left: (left - containerWidth / 2) + 'px',
width: containerWidth + 'px',
top: (top - containerWidth / 2) + 'px',
height: containerWidth + 'px'
};
css[$materialEffects.ANIMATION_DURATION] = options.fadeoutDuration + 'ms';
rippleEl.css(css);
return rippleEl;
}
function onPointerDown(ev) {
if (!rippleIsAllowed()) return;
var rippleEl = createRippleFromEvent(ev);
var ripplePauseTimeout = $timeout(pauseRipple, options.mousedownPauseTime, false);
rippleEl.on('$destroy', cancelRipplePause);
// Stop listening to pointer down for now, until the user lifts their finger/mouse
listenPointerDown(false);
element.on(POINTERUP_EVENT, onPointerUp);
function onPointerUp() {
cancelRipplePause();
rippleEl.css($materialEffects.ANIMATION_PLAY_STATE, 'running');
element.off(POINTERUP_EVENT, onPointerUp);
listenPointerDown(true);
}
function pauseRipple() {
rippleEl.css($materialEffects.ANIMATION_PLAY_STATE, 'paused');
}
function cancelRipplePause() {
$timeout.cancel(ripplePauseTimeout);
}
function createRippleFromEvent(ev) {
ev = ev.touches ? ev.touches[0] : ev;
return createRipple(ev.pageX, ev.pageY, true);
}
}
}
}
|
var boletesPinya = $.merge($.merge($.merge($("#cDB").find("path"), $("#cB4").find("path")), $("#cB3").find("path")), $("#cB2").find("path"));
var boletesTronc = $.merge($.merge($("#cB4").find("path"), $("#cB3").find("path")), $("#cB2").find("path"));
var usedTweets = {};
$(document).ready(function () {
$.each(boletesPinya, function (i, e) {
$(e).tooltipster({
delay: 100,
maxWidth: 500,
speed: 300,
interactive: true,
content: '',
contentAsHTML: true,
animation: 'grow',
trigger: 'custom',
contentCloning: false
});
});
});
function initTweets() {
var path = EMOCIO.properties[lastEmotionPlayed].name + ".php";
$.ajax({
type: 'GET',
url: path,
success: function (data) {
var tweets = null;
var text, user, hashtag, ttContent, img;
tweets = JSON.parse(data);
$(boletesPinya).shuffle().each(function (i, e) {
var cTweet = tweets.statuses[i];
if (typeof cTweet === 'undefined')
return false;
var content = buildContent(cTweet);
if (content !== false) {
$(e).tooltipster('content', content);
themesAndEvents(e);
}
});
},
error: function (res) {
alert("Error finding tweets");
}
});
}
function actualitzarTweets() {
var path = EMOCIO.properties[lastEmotionPlayed].name + ".php";
resetTooltips();
$.ajax({
type: 'GET',
url: path,
success: function (data) {
var tweets = null;
var text, img, user, hashtag, ttContent, url;
tweets = JSON.parse(data);
var boletes = boletesPinya;
if (fase >= FASE.Tercos)
boletes = boletesTronc;
$(boletes).shuffle().each(function (i, e) {
var currentTweet = tweets.statuses[i];
if (typeof currentTweet === 'undefined')
return false;
var content = buildContent(currentTweet);
if (content !== false) {
$(e).tooltipster('content', content);
themesAndEvents(e);
}
});
},
error: function (res) {
alert("Error finding tweets");
}
});
}
function buildContent(info) {
var tweet = info;
if (DictContainsValue(usedTweets, tweet.id_str) || typeof tweet === 'undefined') {
usedTweets[tweet.id_str] = usedTweets[tweet.id_str] + 1;
return false;
}
usedTweets[tweet.id_str] = 1;
var text = tweet.full_text;
var user = "@" + tweet.user.screen_name + ": ";
var img = '';
var url = 'href="https://twitter.com/statuses/' + tweet.id_str + '" target="_blank"';
if ((typeof tweet.entities.media !== "undefined") && (tweet.entities.media !== null)) {
var media = tweet.entities.media;
img = '<div class="row">' +
'<div class="col">' +
'<img style="max-width: 75%; height: auto;" class="rounded mx-auto d-block" src=\'' + media[0].media_url_https + '\'/>' +
'</div></div>';
text = text.replace(' ' + tweet.entities.media[0].url, '');
}
return $('<a '+ url +'>' + img + '<div class="row"><div class="col text-left"><p style="margin-bottom: 0 !important;"><b>' + user + '</b>' + text + '</p></div></div></a>');
}
function themesAndEvents(e) {
var theme = 'tooltipster-' + EMOCIO.properties[lastEmotionPlayed].name.toString();
$(e).tooltipster('option', 'theme', theme);
$(e).tooltipster('option', 'trigger', 'click');
$(e).mouseenter(function () {
if (lastEmotionPlayed !== null) {
$(this).css("fill", EMOCIO.properties[lastEmotionPlayed].color).css("cursor", "pointer");
$(this).addClass("pathHover");
}
}).mouseleave(function () {
if (lastEmotionPlayed !== null) {
var gradient = "url(#gradient" + EMOCIO.properties[lastEmotionPlayed].name.toString().charAt(0).toUpperCase() + EMOCIO.properties[lastEmotionPlayed].name.substr(1) + ")";
$(this).css("fill", gradient).css("cursor", "default");
$(this).removeClass("pathHover");
}
});
}
function resetTooltips() {
usedTweets = {};
$.each(boletesPinya, function (i, e) {
$(e).tooltipster('destroy');
$(e).off();
$(e).unbind("mouseenter");
$(e).unbind("mouseleave");
});
$.each(boletesPinya, function (i, e) {
$(e).tooltipster({
delay: 100,
maxWidth: 500,
speed: 300,
interactive: true,
content: '',
contentAsHTML: true,
animation: 'grow',
trigger: 'custom',
contentCloning: false
});
});
}
|
var sc1 = {
//funhouse mirror
setup:function(){
// videoSetup();
tree = new TREE();
tree.generate({
joints: [5,3,1,10],
divs: [1],
start: [0,0,2,0],
angles: [0,Math.PI/2,1],
length: [20,15,4,1],
rads: [1,2,1,3],
width: [1,2,2,1]
});
scene.add(tree);
tree.position.y=-50;
console.log(tree);
var ball = new THREE.SphereGeometry(15,15,15);
var ball2 = new THREE.Geometry();
tree.xform(tree.makeInfo([
[0,0,"all"],{ballGeo:ball,ballGeo2:ball2},
]),tree.setGeo);
tree.xform(tree.makeInfo([
[0,0,"all"],{ty:-15},
]),function(obj,args){obj.children[0].children[0].position.y=7.5;});
// scene.add(tree.makeTubes({minWidth:1,func:function(t){return Math.sin(t)*2}}));
},
draw:function(time){
time=time*3;
tree.position.y = -40+Math.sin(omouseY*Math.PI*4)*3;
tree.xform(tree.makeInfo([
[0,0,[1,5]],{rz:omouseX,ry:omouseY,sc:.9},
//legs
[0,0,0,[0,1],1],{rz:Math.PI/2},
[0,0,0,[0,1],1],{ry:omouseX*3},
[0,0,0,[0,1],2],{rx:omouseY*3},
//feet
[0,0,0,[0,1],0,0,0],{rz:0},
[0,0,0,[0,1],0,0,0],{rx:omouseY*3},
[0,0,[0,4],[0,1],0],{ty:-10},
[0,0,[1,4],[0,1],[1,2]],{rz:mouseY,freq:1,offMult:.2,off:time},
//fingers
[0,0,[1,4],[0,1],0,0,0,[0,2],"all"],{rz:0,freq:1,offMult:.2,off:time},
[0,0,[1,4],[0,1],0,0,0],{rz:0,freq:1,offMult:.3,off:time+.2},
//feet
[0,0,0,[0,1],0,0,0,[0,2],"all"],{ry:0,rz:omouseY*.1,sc:.9},
[0,0,0,0,0,0,0,[0,2],0],{sc:2,ry:-2*omouseY+1.5,rz:1},
[0,0,0,1,0,0,0,[0,2],0],{sc:2,ry:-2*omouseY-1.5,rz:1},
//toes
[0,0,0,0,0,0,0,[0,2],0],{sc:2,ry:0,freq:1,offMult:.2 ,offsetter2:.5},
[0,0,0,1,0,0,0,[0,2],0],{sc:2,ry:Math.PI-.3,freq:1,offMult:.2,offsetter2:.5},
]),tree.transform);
}
}
|
'use strict';
// 頑シミュさんの装飾品検索の結果と比較しやすくする
function simplifyDecombs(decombs) {
return decombs.map(decomb => {
let torsoUp = Object.keys(decomb).map(part => decomb[part]).some(comb => {
if (comb == null) return false;
return comb.skills['胴系統倍加'] ? true : false;
});
let names = [];
Object.keys(decomb).forEach(part => {
let comb = decomb[part];
let decos = comb ? comb.decos : [];
if (torsoUp && part === 'body') decos = decos.map(deco => deco += '(胴)');
names = names.concat(decos);
});
return names.sort().join(',');
});
}
exports.simplifyDecombs = simplifyDecombs;
|
"use strict";
let datafire = require('datafire');
let openapi = require('./openapi.json');
module.exports = datafire.Integration.fromOpenAPI(openapi, "billbee");
|
// Generated by CoffeeScript 1.6.3
/*!
@author Branko Vukelic <branko@brankovukelic.com>
@license MIT
*/
var _this = this;
if (typeof define !== 'function' || !define.amd) {
this.require = function(dep) {
return (function() {
switch (dep) {
case 'jquery':
return _this.jQuery;
default:
return null;
}
})() || (function() {
throw new Error("Unmet dependency " + dep);
})();
};
this.define = function(factory) {
return _this.ribcage.utils.deserializeForm = factory(_this.require);
};
}
define(function(require) {
var $;
$ = require('jquery');
$.deserializeForm = function(form, data) {
form = $(form);
form.find(':input').each(function() {
var currentValue, input, name, type;
input = $(this);
name = input.attr('name');
type = input.attr('type');
currentValue = input.val();
if (!name) {
return;
}
switch (type) {
case 'checkbox':
return input.prop('checked', data[name] === 'on');
case 'radio':
return input.prop('checked', data[name] === currentValue);
default:
return input.val(data[name]);
}
});
return form;
};
$.fn.deserializeForm = function(data) {
return $.deserializeForm(this, data);
};
return $.deserializeForm;
});
|
'use strict'
module.exports = function (config) {
if (!process.env.COOKING_PATH) {
return
}
const rootPath = process.env.COOKING_PATH.split(',')
config.resolve = config.resolve || {}
config.resolveLoader = config.resolveLoader || {}
config.resolve.modules = (config.resolve.root || []).concat(rootPath)
config.resolveLoader.modules = (config.resolveLoader.root || []).concat(rootPath)
}
|
var xhrGet = function (url, callback) {
var xhr = new XMLHttpRequest();
xhr.open('GET', url, true);
xhr.onload = callback;
xhr.send();
};
|
/*jslint browser: true*/
/*global Tangram, gui */
map = (function () {
'use strict';
var locations = {
'Yangon': [16.8313077,96.2187007,7]
};
var map_start_location = locations['Yangon'];
/*** Map ***/
var map = L.map('map',
{"keyboardZoomOffset" : .05, maxZoom: 20 }
);
var layer = Tangram.leafletLayer({
scene: 'cinnabar-style-more-labels.yaml?r=2',
attribution: '<a href="https://mapzen.com/tangram" target="_blank">Tangram</a> | © OSM contributors | <a href="https://mapzen.com/" target="_blank">Mapzen</a>'
});
window.layer = layer;
var scene = layer.scene;
window.scene = scene;
// setView expects format ([lat, long], zoom)
map.setView(map_start_location.slice(0, 3), map_start_location[2]);
function long2tile(lon,zoom) { return (Math.floor((lon+180)/360*Math.pow(2,zoom))); }
function lat2tile(lat,zoom) { return (Math.floor((1-Math.log(Math.tan(lat*Math.PI/180) + 1/Math.cos(lat*Math.PI/180))/Math.PI)/2 *Math.pow(2,zoom))); }
/***** Render loop *****/
function addGUI () {
// Link to edit in OSM - hold 'e' and click
}
// Feature selection
function initFeatureSelection () {
// Selection info shown on hover
var selection_info = document.createElement('div');
selection_info.setAttribute('class', 'label');
selection_info.style.display = 'block';
// Show selected feature on hover
scene.container.addEventListener('mousemove', function (event) {
var pixel = { x: event.clientX, y: event.clientY };
scene.getFeatureAt(pixel).then(function(selection) {
if (!selection) {
return;
}
var feature = selection.feature;
if (feature != null) {
// console.log("selection map: " + JSON.stringify(feature));
var label = '';
if (feature.properties.name != null) {
label = feature.properties.name;
}
if (label != '') {
selection_info.style.left = (pixel.x + 5) + 'px';
selection_info.style.top = (pixel.y + 15) + 'px';
selection_info.innerHTML = '<span class="labelInner">' + label + '</span>';
scene.container.appendChild(selection_info);
}
else if (selection_info.parentNode != null) {
selection_info.parentNode.removeChild(selection_info);
}
}
else if (selection_info.parentNode != null) {
selection_info.parentNode.removeChild(selection_info);
}
});
// Don't show labels while panning
if (scene.panning == true) {
if (selection_info.parentNode != null) {
selection_info.parentNode.removeChild(selection_info);
}
}
});
// Show selected feature on hover
scene.container.addEventListener('click', function (event) {
var pixel = { x: event.clientX, y: event.clientY };
scene.getFeatureAt(pixel).then(function(selection) {
if (!selection) {
return;
}
var feature = selection.feature;
if (feature != null) {
// console.log("selection map: " + JSON.stringify(feature));
var label = '';
if (feature.properties != null) {
// console.log(feature.properties);
var obj = JSON.parse(JSON.stringify(feature.properties));
for (var x in feature.properties) {
var val = feature.properties[x]
label += "<span class='labelLine' key="+x+" value="+val+" onclick='setValuesFromSpan(this)'>"+x+" : "+val+"</span><br>"
}
}
if (label != '') {
selection_info.style.left = (pixel.x + 5) + 'px';
selection_info.style.top = (pixel.y + 15) + 'px';
selection_info.innerHTML = '<span class="labelInner">' + label + '</span>';
scene.container.appendChild(selection_info);
}
else if (selection_info.parentNode != null) {
selection_info.parentNode.removeChild(selection_info);
}
}
else if (selection_info.parentNode != null) {
selection_info.parentNode.removeChild(selection_info);
}
});
// Don't show labels while panning
if (scene.panning == true) {
if (selection_info.parentNode != null) {
selection_info.parentNode.removeChild(selection_info);
}
}
});
}
window.addEventListener('load', function () {
// Scene initialized
layer.on('init', function() {
addGUI();
//initFeatureSelection();
});
layer.addTo(map);
});
return map;
}());
|
var height = window.innerHeight;
// console.log(height);
var main = document.getElementById('main');
var btn = document.getElementById("btn");
main.style.height = height + 'px';
btn.style.top = (height-90) + 'px';
document.getElementById('usr_name').onkeydown = function(e) {
e = e || event;
if(e.keyCode === 13) {
btn.click();
}
};
btn.addEventListener("click", function() {
var name = document.getElementById("usr_name").value;
name = name.replace(/(^\s*)|(\s*$)/g, "");
if(name=='')
{
alert("请填写用户名哦!");
return false;
}
var url = window.location.href;
var splited = url.split('/');
var roomID = splited[splited.length - 1];
ajax({
url: "/login/"+roomID, //请求地址
type: "POST", //请求方式
data: {new_topic:true,username: name}, //请求参数
dataType: "json",
success: function (data) {
data=JSON.parse(data);
if(data.status==1){
//alert("登录成功");
window.location.href="/show";
}
else if(data.status==0){
alert("已经有人登录了哦");
}
// 此处放成功后执行的代码
},
fail: function (status) {
// 此处放失败后执行的代码
}
});
});
|
/*
* default/mouse-push-button.js
*/
"use strict";
var Q = require('q'),
Button = require('./../../button');
var MousePushButton = function (options) {
Button.prototype.constructor.call(this, options);
this.delay = options.delay > 0 ? options.delay : 0;
this.g = null;
if(typeof options.g === 'function') this.g = options.g;
this.promisef = null;
this.boundaries = { minX : 0, maxX : 0, minY : 0, maxY : 0 };
this.leftOrEnded = false;
};
MousePushButton.prototype = (function (proto) {
function F() {};
F.prototype = proto;
return new F();
})(Button.prototype);
MousePushButton.prototype.constructor = MousePushButton;
MousePushButton.prototype.setG = function (g) {
if (typeof g !== 'function')
throw new Error("Button setG method needs a g function as argument.");
this.g = g;
return this;
};
MousePushButton.prototype._isInActiveZone = function (touch) {
var x = touch.clientX,
y = touch.clientY,
b = this.boundaries;
return x < b.maxX && x > b.minX && y < b.maxY && y > b.minY;
};
MousePushButton.prototype.bind = function () {
Button.prototype.bind.call(this);
this.el.addEventListener('mousedown', this, false);
this.binded = true;
return this;
};
MousePushButton.prototype.unbind = function () {
Button.prototype.unbind.call(this);
this.el.removeEventListener('mousedown', this, false);
this.binded = false;
return this;
};
MousePushButton.prototype.handleEvent = function (evt) {
switch (evt.type) {
case 'mousedown':
this.onMousedown(evt);
break;
case 'mousemove':
this.onMousemove(evt);
break;
case 'mouseup':
this.onMouseup(evt);
break;
}
};
MousePushButton.prototype.onMousedown = function (evt) {
if (!this.active) {
if (evt.button === 0) {
evt.preventDefault();
this.setActive(true);
var boundingRect = this.el.getBoundingClientRect();
this.boundaries.minX = boundingRect.left;
this.boundaries.maxX = boundingRect.left + boundingRect.width;
this.boundaries.minY = boundingRect.top;
this.boundaries.maxY = boundingRect.bottom;
this.el.ownerDocument.addEventListener('mousemove', this, false);
this.el.ownerDocument.addEventListener('mouseup', this, false);
this.promisef = Q.delay(evt, this.delay).then(this.f);
}
}
};
MousePushButton.prototype.onMousemove = function (evt) {
if(this.active && !this.leftOrEnded) {
evt.preventDefault();
if (!this._isInActiveZone(evt))
this.onMouseup(evt);
}
};
MousePushButton.prototype.onMouseup = function (evt) {
if(this.active && !this.leftOrEnded) {
this._removeCls();
this.leftOrEnded = true;
this.promisef
.then(evt)
.then(this.g)
.finally(this._done(evt))
.done();
}
};
MousePushButton.prototype._done = function (evt) {
var btn = this;
return function () {
btn.setActive(false);
btn.leftOrEnded = false;
btn.el.ownerDocument.removeEventListener('mousemove', btn, false);
btn.el.ownerDocument.removeEventListener('mouseup', btn, false);
};
};
module.exports = MousePushButton;
|
const industry = [
{
"name": "金融",
"children": [
{ "name": "银行" },
{ "name": "保险" },
{ "name": "证券公司" },
{ "name": "会计/审计" },
{ "name": "其它金融服务" }
]
},
{
"name": "专业服务",
"children": [
{ "name": "科研/教育" },
{ "name": "顾问/咨询服务" },
{ "name": "法律服务" },
{ "name": "医疗/保健" },
{ "name": "其它专业服务" }
]
},
{
"name": "政府",
"children": [
{ "name": "政府机关" },
{ "name": "协会/非赢利性组织" }
]
},
{
"name": "IT/通信",
"children": [
{ "name": "计算机软/硬件" },
{ "name": "系统集成/科技公司" },
{ "name": "电信服务提供商" },
{ "name": "电信增值服务商" },
{ "name": "其它IT/通信业" }
]
},
{
"name": "媒体/娱乐",
"children": [
{ "name": "媒体/信息传播" },
{ "name": "广告公司/展会公司" },
{ "name": "印刷/出版" },
{ "name": "酒店/饭店/旅游/餐饮" },
{ "name": "文化/体育/娱乐" },
{ "name": "其它媒体/娱乐" }
]
},
{
"name": "制造",
"children": [
{ "name": "汽车制造" },
{ "name": "电子制造" },
{ "name": "快速消费品制造" },
{ "name": "制药/生物制造" },
{ "name": "工业设备制造" },
{ "name": "化工/石油制造" },
{ "name": "其它制造业" }
]
},
{
"name": "建筑",
"children": [
{ "name": "建筑工程/建设服务" },
{ "name": "楼宇" },
{ "name": "房地产" },
{ "name": "其它建筑业" }
]
},
{
"name": "能源/公共事业",
"children": [
{ "name": "能源开采" },
{ "name": "水/电/气等" },
{ "name": "公共事业" }
]
},
{
"name": "其它行业",
"children": [
{ "name": "交通运输/仓储物流" },
{ "name": "批发/零售/分销" },
{ "name": "贸易/进出口" },
{ "name": "其它" }
]
}
];
export default industry;
|
onst bcrypt = require('bcrypt-nodejs');
const crypto = require('crypto');
console.log('start');
bcrypt.genSalt(10, (err, salt) => {
bcrypt.hash('passwd', salt, null, (err, hash) => {
console.log(hash);
});
});
|
'use strict'
const { spawn } = require('@malept/cross-spawn-promise')
const which = require('which')
function updateExecutableMissingException (err, hasLogger) {
if (hasLogger && err.code === 'ENOENT' && err.syscall === 'spawn mono') {
let installer
let pkg
if (process.platform === 'darwin') {
installer = 'brew'
pkg = 'mono'
} else if (which.sync('dnf', { nothrow: true })) {
installer = 'dnf'
pkg = 'mono-core'
} else { // assume apt-based Linux distro
installer = 'apt'
pkg = 'mono-runtime'
}
err.message = `Your system is missing the ${pkg} package. Try, e.g. '${installer} install ${pkg}'`
}
}
module.exports = async function (cmd, args, logger) {
if (process.platform !== 'win32') {
args.unshift(cmd)
cmd = 'mono'
}
return spawn(cmd, args, {
logger,
updateErrorCallback: updateExecutableMissingException
})
}
|
import Ember from 'ember';
export default Ember.Object.extend({
animate($element, effect, duration) {
},
finish($elements) {
}
});
|
// validate and import user arguments
(function(args){
for (_i = 0; _i < args.length; _i += 1) {
// import arguments if defined, else defaults
_settings[args[_i]] = options && options[args[_i]] ? options[args[_i]] : defaults[args[_i]];
// validate data types
if(typeof _settings[args[_i]] !== "number") {
throw "textStretch error. Argument \"" + args[_i] + "\" must be a number. Argument given was \"" + _settings[args[_i]] + "\".";
}
}
}(["minFontSize", "maxFontSize"]));
_settings.maxFontSize = _settings.maxFontSize || Number.POSITIVE_INFINITY;
|
var baseSortedIndex = require('./_baseSortedIndex');
/**
* This method is like `_.sortedIndex` except that it returns the highest
* index at which `value` should be inserted into `array` in order to
* maintain its sort order.
*
* @static
* @memberOf _
* @category Array
* @param {Array} array The sorted array to inspect.
* @param {*} value The value to evaluate.
* @returns {number} Returns the index at which `value` should be inserted into `array`.
* @specs
*
* _.sortedLastIndex([4, 5], 4);
* // => 1
*/
function sortedLastIndex(array, value) {
return baseSortedIndex(array, value, true);
}
module.exports = sortedLastIndex;
|
/**
* Created by RSC on 05.04.2016.
*/
myApp.factory('HomeWatchFactory', function ($http, $q, $rootScope, $log) {
return {
getFhemJsonList: function (name, type) {
var url = '';
if ($rootScope.config.connection.isDebug) {
url = 'json/homewatch/data/' + name + '.json';
} else {
url = $rootScope.MetaDatafhemweb_url + $rootScope.config.globals.cmd + type + '=' + name + $rootScope.config.globals.param;
}
$log.debug('HomeWatchFactory: ' + url);
var deferred = $q.defer();
$http({method: "GET", url: url})
.success(function (data, status, headers, config) {
deferred.resolve(data);
}).error(function (data, status, headers, config) {
deferred.reject(status);
});
return deferred.promise;
},
getJson: function (name) {
var url = 'json/homewatch/' + name + '.json';
var deferred = $q.defer();
$http({method: "GET", url: url})
.success(function (data, status, headers, config) {
deferred.resolve(data);
}).error(function (data, status, headers, config) {
deferred.reject(status);
});
return deferred.promise;
},
getLocationWidgets: function (location) {
// no values
if (angular.isUndefined(location) || location == '') {
$log.debug('HomeWatchFactory.getLocationWidgets: location isUndefined');
return;
}
var widget = $rootScope.config.home;
if (widget.length == 0)
return;
var deferred = $q.defer();
var len = widget.length;
for (var i = 0; i < len; i++) {
if (widget[i].location == location) {
data = widget[i];
deferred.resolve(data);
break;
}
}
return deferred.promise;
}
};
});
|
module.exports = function(grunt) {
'use strict';
// Project configuration.
grunt.initConfig({
pkg: grunt.file.readJSON('package.json'),
bowercopy: {
options: {
clean: false
},
glob: {
files: {
'static/libs/js': [
'sprintf/dist/*.js',
'mocha/*.js',
'assert/*.js'
],
'static/libs/css': [
'mocha/*.css'
],
'static/libs/fonts': [
]
}
}
}
})
grunt.loadNpmTasks('grunt-bowercopy');
// Default tasks
grunt.registerTask('default', ['bowercopy']);
}
|
import _ from 'lodash'
import Vue from 'vue'
import test from 'ava'
import FlexTableColumn from '../../src/components/FlexTableColumn.vue'
Vue.config.productionTip = false
test('has a mounted hook', (t) => {
t.true(_.isFunction(FlexTableColumn.mounted))
})
test('has data as function', (t) => {
t.true(_.isFunction(FlexTableColumn.data))
})
|
export const plus = (f, l) => {
let next = {};
if (typeof l === 'number') {
next.low = l;
next.high = 0;
} else if (typeof l === 'object') {
if (l.high && l.low && l.unsigned) {
next = l;
} else {
throw new Error('Not a uint64 data');
}
}
return {
high: f.high + next.high,
low: f.low + next.low,
unsigned: true
};
};
export const generateKeyString = (uint64Object) => {
if (typeof uint64Object === 'number') {
return uint64Object.toString();
}
if (typeof uint64Object === 'object' && typeof uint64Object.high === 'number') {
return `${uint64Object.high}${uint64Object.low}`;
}
return Symbol(uint64Object).toString();
};
|
var q = require("./quasi");
exports.ps = function (opt) {
opt = opt || {};
var strokeWidth = opt.strokeWidth || "0.015";
if (opt.color) console.error("The ps module does not support the `color` option.");
// PS header
var ret = [
"%%!PS-Adobe-1.0 "
, "%%%%BoundingBox: -1 -1 766.354 567.929 "
, "%%%%EndComments "
, "%%%%EndProlog "
, "gsave "
, " "
, "/f {findfont exch scalefont setfont} bind def "
, "/s {show} bind def "
, "/ps {true charpath} bind def "
, "/l {lineto} bind def "
, "/m {newpath moveto} bind def "
, "/sg {setgray} bind def"
, "/a {stroke} bind def"
, "/cp {closepath} bind def"
, "/g {gsave} bind def"
, "/h {grestore} bind def"
, "matrix currentmatrix /originmat exch def "
, "/umatrix {originmat matrix concatmatrix setmatrix} def "
, " "
, "%% Flipping coord system "
, "[8.35928e-09 28.3465 -28.3465 8.35928e-09 609.449 28.6299] umatrix "
, "[] 0 setdash "
, "0 0 0 setrgbcolor "
, "0 0 m "
, strokeWidth + " setlinewidth "
];
q.quasi(
opt
, {
newPath: function () {}
, moveTo: function (x, y) {
ret.push(x.toFixed(2) + " " + y.toFixed(2) + " m");
}
, lineTo: function (x, y) {
ret.push(x.toFixed(2) + " " + y.toFixed(2) + " l");
}
, closePath: function () {
ret.push("cp");
}
, startGroup: function () {
ret.push("g");
}
, endGroup: function () {
ret.push("h");
}
, setFillGrey: function (colour) {
ret.push(colour + " sg");
ret.push("fill");
}
, setStrokeGrey: function (colour) {
ret.push(colour + " sg");
ret.push("a");
}
// we don't take these into account
, boundaries: function () {}
}
);
// PS Footer
ret.push("showpage grestore ");
ret.push("%%%%Trailer");
return ret.join("\n");
};
|
print('this is a');
print(__FILE__, __LINE__, __DIR__);
load('./b.js'); // 不能简单的加载同目录的 b,因为 engine.get(FILENAME) 未变
|
import PropTypes from 'prop-types';
export const validAxisType = PropTypes.oneOf([
'category',
'linear',
'logarithmic',
'datetime'
]);
export const validChartType = PropTypes.oneOf([
'area',
'arearange',
'areaspline',
'areasplinerange',
'bar',
'boxplot',
'bubble',
'candlestick',
'column',
'columnrange',
'errorbar',
'flags',
'funnel',
'line',
'ohlc',
'pie',
'polygon',
'pyramid',
'scatter',
'solidgauge',
'spline',
'waterfall'
]);
|
/**
* @author Richard Davey <rich@photonstorm.com>
* @copyright 2019 Photon Storm Ltd.
* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License}
*/
var Line = require('./Line');
Line.Angle = require('./Angle');
Line.BresenhamPoints = require('./BresenhamPoints');
Line.CenterOn = require('./CenterOn');
Line.Clone = require('./Clone');
Line.CopyFrom = require('./CopyFrom');
Line.Equals = require('./Equals');
Line.Extend = require('./Extend');
Line.GetMidPoint = require('./GetMidPoint');
Line.GetNearestPoint = require('./GetNearestPoint');
Line.GetNormal = require('./GetNormal');
Line.GetPoint = require('./GetPoint');
Line.GetPoints = require('./GetPoints');
Line.GetShortestDistance = require('./GetShortestDistance');
Line.Height = require('./Height');
Line.Length = require('./Length');
Line.NormalAngle = require('./NormalAngle');
Line.NormalX = require('./NormalX');
Line.NormalY = require('./NormalY');
Line.Offset = require('./Offset');
Line.PerpSlope = require('./PerpSlope');
Line.Random = require('./Random');
Line.ReflectAngle = require('./ReflectAngle');
Line.Rotate = require('./Rotate');
Line.RotateAroundPoint = require('./RotateAroundPoint');
Line.RotateAroundXY = require('./RotateAroundXY');
Line.SetToAngle = require('./SetToAngle');
Line.Slope = require('./Slope');
Line.Width = require('./Width');
module.exports = Line;
|
'use strict';
// User routes use users controller
var users = require('../controllers/users');
module.exports = function(app, passport) {
app.route('/logout')
.get(users.signout);
app.route('/users/me')
.get(users.me);
// Setting up the users api
app.route('/register')
.post(users.create);
// Setting up the userId param
app.param('userId', users.user);
// AngularJS route to check for authentication
app.route('/loggedin')
.get(function(req, res) {
res.send(req.isAuthenticated() ? req.user : '0');
});
// Setting the local strategy route
app.route('/login')
.post(passport.authenticate('local', {
failureFlash: true
}), function(req, res) {
res.send({
user: req.user,
redirect: (req.user.roles.indexOf('admin') !== -1) ? req.get('referer') : false
});
});
};
|
'use strict';
// Disable eval and Buffer.
window.eval = global.eval = global.Buffer = function() {
throw new Error("Can't use eval and Buffer.");
}
const Electron = require('electron')
const IpcRenderer = Electron.ipcRenderer;
var Urlin = null; // element of input text
window.addEventListener('load', ()=> {
Urlin = document.getElementById('input-url');
Urlin.addEventListener("keypress", (event)=>{
if(13!=event.keyCode) return;
Urlin.blur();
IpcRenderer.sendToHost('url-input', Urlin.value);
}, false);
}, false);
IpcRenderer.on('url-input', (event, s_url)=>{
Urlin.value = s_url;
});
|
var roshamboApp = angular.module('roshamboApp', []),
roshambo=
[
{
name:'Rock',
src:'img/rock.png'
},
{
name:'Paper',
src:'img/paper.png'
},
{
name:'Scissors',
src:'img/scissors.png'
}
],
roshamboMap=roshambo.reduce(function(roshamboMap,thro){
roshamboMap[thro.name.toLowerCase()]=thro.src;
return roshamboMap;
},{});
roshamboApp.controller('RoshamboCtrl', function ($scope,$http) {
$scope.roshambo=roshambo;
$scope.selection=roshambo[0];
$scope.outcome=void 0;
$scope.selectThrow=function(selected){
$scope.outcome=void 0;
$scope.selection=selected;
};
$scope.throwSelected=function(){
$http.post('http://localhost:8080/api/throw',{playerThrow:$scope.selection.name})
.then(function(successResponse){
$scope.outcome=successResponse.data;
$scope.outcome.playerSrc=roshamboMap[$scope.outcome.playerThrow];
$scope.outcome.opponentSrc=roshamboMap[$scope.outcome.opponentThrow];
$scope.outcome.announce=function(){
if($scope.outcome.outcome==='draw'){
return 'It\'s a Draw!';
}else{
return $scope.outcome.outcome.charAt(0).toUpperCase()+$scope.outcome.outcome.slice(1)+' Wins!';
}
}
},function(errorResponse){
alert('Error!');
console.log('Caught error posting throw:\n%s',JSON.stringify(errorResponse,null,2));
});
};
});
|
"use strict";
module.exports = {
"wires.json": {
":path/": `./path-`,
},
"path-test.js"() {
module.exports = `parent`;
},
"/child": {
"wires-defaults.json": {
":path/": `./defaults-`,
},
"wires.json": {
":path/": `./child-`,
},
"defaults-test.js"() {
module.exports = `defaults`;
},
"child-test.js"() {
module.exports = `child`;
},
"dirRouteOverride.unit.js"() {
module.exports = {
"dir route override"( __ ) {
__.expect( 1 );
__.strictEqual( require( `:path/test` ), `child` );
__.done();
},
};
},
},
};
|
var assert = require('assert')
var parse = require('../').parse
function addTest(arg, bulk) {
function fn_json5() {
//console.log('testing: ', arg)
try {
var x = parse(arg)
} catch(err) {
x = 'fail'
}
try {
var z = eval('(function(){"use strict"\nreturn ('+String(arg)+'\n)\n})()')
} catch(err) {
z = 'fail'
}
assert.deepEqual(x, z)
}
function fn_strict() {
//console.log('testing: ', arg)
try {
var x = parse(arg, {mode: 'json'})
} catch(err) {
x = 'fail'
}
try {
var z = JSON.parse(arg)
} catch(err) {
z = 'fail'
}
assert.deepEqual(x, z)
}
if (typeof(describe) === 'function' && !bulk) {
it('test_parse_json5: ' + JSON.stringify(arg), fn_json5)
it('test_parse_strict: ' + JSON.stringify(arg), fn_strict)
} else {
fn_json5()
fn_strict()
}
}
addTest('"\\uaaaa\\u0000\\uFFFF\\uFaAb"')
addTest(' "\\xaa\\x00\xFF\xFa\0\0" ')
addTest('"\\\'\\"\\b\\f\\t\\n\\r\\v"')
addTest('"\\q\\w\\e\\r\\t\\y\\\\i\\o\\p\\[\\/\\\\"')
addTest('"\\\n\\\r\n\\\n"')
addTest('\'\\\n\\\r\n\\\n\'')
addTest(' null')
addTest('true ')
addTest('false')
addTest(' Infinity ')
addTest('+Infinity')
addTest('[]')
addTest('[ 0xA2, 0X024324AaBf]')
addTest('-0x12')
addTest(' [1,2,3,4,5]')
addTest('[1,2,3,4,5,] ')
addTest('[1e-13]')
addTest('[null, true, false]')
addTest(' [1,2,"3,4,",5,]')
addTest('[ 1,\n2,"3,4," \r\n,\n5,]')
addTest('[ 1 , 2 , 3 , 4 , 5 , ]')
addTest('{} ')
addTest('{"2":1,"3":null,}')
addTest('{ "2 " : 1 , "3":null , }')
addTest('{ \"2\" : 25e245 , \"3\": 23 }')
addTest('{"2":1,"3":nul,}')
addTest('{:1,"3":nul,}')
addTest('[1,2] // ssssssssss 3,4,5,] ')
addTest('[1,2 , // ssssssssss \n//xxx\n3,4,5,] ')
addTest('[1,2 /* ssssssssss 3,4,*/ /* */ , 5 ] ')
addTest('[1,2 /* ssssssssss 3,4,*/ /* * , 5 ] ')
addTest('{"3":1,"3":,}')
addTest('{ чйуач:1, щцкшчлм : 4,}')
addTest('{ qef-:1 }')
addTest('{ $$$:1 , ___: 3}')
addTest('{3:1,2:1}')
addTest('{3.4e3:1}')
addTest('{-3e3:1}')
addTest('{+3e3:1}')
addTest('{.3e3:1}')
for (var i=0; i<200; i++) {
addTest('"' + String.fromCharCode(i) + '"', true)
}
// strict JSON test cases
addTest('"\\xaa"')
addTest('"\\0"')
addTest('"\0"')
addTest('"\\v"')
addTest('{null: 123}')
addTest("{'null': 123}")
assert.throws(function() {
parse('0o')
})
assert.strictEqual(parse('01234567'), 342391)
assert.strictEqual(parse('0o1234567'), 342391)
// undef
assert.strictEqual(parse(undefined), undefined)
// whitespaces
addTest('[1,\r\n2,\r3,\n]')
'\u0020\u00A0\uFEFF\x09\x0A\x0B\x0C\x0D\u1680\u180E\u2000\u2001\u2002\u2003\u2004\u2005\u2006\u2007\u2008\u2009\u200A\u2028\u2029\u202F\u205F\u3000'.split('').forEach(function(x) {
addTest(x+'[1,'+x+'2]'+x)
addTest('"'+x+'"'+x)
})
'\u000A\u000D\u2028\u2029'.split('').forEach(function(x) {
addTest(x+'[1,'+x+'2]'+x)
addTest('"\\'+x+'"'+x)
})
/* weird ES6 stuff, not working
if (process.version > 'v0.11.7') {
assert(Array.isArray(parse('{__proto__:[]}').__proto__))
assert.equal(parse('{__proto__:{xxx:5}}').xxx, undefined)
assert.equal(parse('{__proto__:{xxx:5}}').__proto__.xxx, 5)
var o1 = parse('{"__proto__":[]}')
assert.deepEqual([], o1.__proto__)
assert.deepEqual(["__proto__"], Object.keys(o1))
assert.deepEqual([], Object.getOwnPropertyDescriptor(o1, "__proto__").value)
assert.deepEqual(["__proto__"], Object.getOwnPropertyNames(o1))
assert(o1.hasOwnProperty("__proto__"))
assert(Object.prototype.isPrototypeOf(o1))
// Parse a non-object value as __proto__.
var o2 = JSON.parse('{"__proto__":5}')
assert.deepEqual(5, o2.__proto__)
assert.deepEqual(["__proto__"], Object.keys(o2))
assert.deepEqual(5, Object.getOwnPropertyDescriptor(o2, "__proto__").value)
assert.deepEqual(["__proto__"], Object.getOwnPropertyNames(o2))
assert(o2.hasOwnProperty("__proto__"))
assert(Object.prototype.isPrototypeOf(o2))
}*/
assert.throws(parse.bind(null, "{-1:42}"))
for (var i=0; i<100; i++) {
var str = '-01.e'.split('')
var rnd = [1,2,3,4,5].map(function(x) {
x = ~~(Math.random()*str.length)
return str[x]
}).join('')
try {
var x = parse(rnd)
} catch(err) {
x = 'fail'
}
try {
var y = JSON.parse(rnd)
} catch(err) {
y = 'fail'
}
try {
var z = eval(rnd)
} catch(err) {
z = 'fail'
}
//console.log(rnd, x, y, z)
if (x !== y && x !== z) throw 'ERROR'
}
|
/**
* options.js
*
* A test helper to detect which html-snapshots options to use
*
* phantomjs
* If a global phantomjs is defined, decorates html-snapshots options to specify that global
* In some test environments (travis), local phantomjs will not install if a global is found.
*/
const spawn = require("child_process").spawn;
module.exports = {
// for now, callback is passed true if global phantomjs should be used
detector: callback => {
// try to run phantom globally
const cp = spawn("phantomjs", ["--version"]);
// if it fails, use local per the defaults
cp.on("error", () => {
callback(false);
});
// if it succeeds, use the global
cp.on("exit", code => {
if (code === 0) {
callback(true);
}
});
}
};
|
/*
* Copyright (c) 2012-2014 André Bargull
* Alle Rechte vorbehalten / All Rights Reserved. Use is subject to license terms.
*
* <https://github.com/anba/es6draft>
*/
const {
assertSame,
assertDataProperty,
assertBuiltinConstructor,
assertBuiltinPrototype,
} = Assert;
function assertFunctionProperty(object, name, value = object[name]) {
return assertDataProperty(object, name, {value, writable: true, enumerable: false, configurable: true});
}
function assertCreateFunctionProperty(object, name, value = object[name]) {
return assertDataProperty(object, name, {value, writable: false, enumerable: false, configurable: true});
}
function assertConstructorProperty(object, name = "constructor", value = object[name]) {
return assertDataProperty(object, name, {value, writable: true, enumerable: false, configurable: true});
}
function assertPrototypeProperty(object, name = "prototype", value = object[name]) {
return assertDataProperty(object, name, {value, writable: false, enumerable: false, configurable: false});
}
/* Promise Objects */
assertBuiltinConstructor(Promise, "Promise", 1);
assertBuiltinPrototype(Promise.prototype);
assertSame(Promise, Promise.prototype.constructor);
/* Properties of the Promise Constructor */
assertPrototypeProperty(Promise);
assertCreateFunctionProperty(Promise, Symbol.create);
assertFunctionProperty(Promise, "all");
assertFunctionProperty(Promise, "cast");
assertFunctionProperty(Promise, "race");
assertFunctionProperty(Promise, "reject");
assertFunctionProperty(Promise, "resolve");
/* Properties of the Promise Prototype Object */
assertConstructorProperty(Promise.prototype);
assertFunctionProperty(Promise.prototype, "catch");
assertFunctionProperty(Promise.prototype, "then");
|
/*!
* Angular Material Design
* https://github.com/angular/material
* @license MIT
* v1.0.0-rc5-master-76c6299
*/
goog.provide('ng.material.components.backdrop');
goog.require('ng.material.core');
/*
* @ngdoc module
* @name material.components.backdrop
* @description Backdrop
*/
/**
* @ngdoc directive
* @name mdBackdrop
* @module material.components.backdrop
*
* @restrict E
*
* @description
* `<md-backdrop>` is a backdrop element used by other components, such as dialog and bottom sheet.
* Apply class `opaque` to make the backdrop use the theme backdrop color.
*
*/
angular
.module('material.components.backdrop', ['material.core'])
.directive('mdBackdrop', ["$mdTheming", "$animate", "$rootElement", "$window", "$log", "$$rAF", "$document", function BackdropDirective($mdTheming, $animate, $rootElement, $window, $log, $$rAF, $document) {
var ERROR_CSS_POSITION = "<md-backdrop> may not work properly in a scrolled, static-positioned parent container.";
return {
restrict: 'E',
link: postLink
};
function postLink(scope, element, attrs) {
// If body scrolling has been disabled using mdUtil.disableBodyScroll(),
// adjust the 'backdrop' height to account for the fixed 'body' top offset
var body = $window.getComputedStyle($document[0].body);
if (body.position == 'fixed') {
var hViewport = parseInt(body.height, 10) + Math.abs(parseInt(body.top, 10));
element.css({
height: hViewport + 'px'
});
}
// backdrop may be outside the $rootElement, tell ngAnimate to animate regardless
if ($animate.pin) $animate.pin(element, $rootElement);
$$rAF(function () {
// Often $animate.enter() is used to append the backDrop element
// so let's wait until $animate is done...
var parent = element.parent()[0];
if (parent) {
if ( parent.nodeName == 'BODY' ) {
element.css({position : 'fixed'});
}
var styles = $window.getComputedStyle(parent);
if (styles.position == 'static') {
// backdrop uses position:absolute and will not work properly with parent position:static (default)
$log.warn(ERROR_CSS_POSITION);
}
}
$mdTheming.inherit(element, element.parent());
});
}
}]);
ng.material.components.backdrop = angular.module("material.components.backdrop");
|
// Generated by CoffeeScript 1.7.1
(function() {
var $, CSV, ES, TEXT, TRM, TYPES, alert, badge, create_readstream, debug, echo, help, info, log, njs_fs, rainbow, route, rpr, urge, warn, whisper;
njs_fs = require('fs');
TYPES = require('coffeenode-types');
TEXT = require('coffeenode-text');
TRM = require('coffeenode-trm');
rpr = TRM.rpr.bind(TRM);
badge = 'TIMETABLE/read-gtfs-data';
log = TRM.get_logger('plain', badge);
info = TRM.get_logger('info', badge);
whisper = TRM.get_logger('whisper', badge);
alert = TRM.get_logger('alert', badge);
debug = TRM.get_logger('debug', badge);
warn = TRM.get_logger('warn', badge);
help = TRM.get_logger('help', badge);
urge = TRM.get_logger('urge', badge);
echo = TRM.echo.bind(TRM);
rainbow = TRM.rainbow.bind(TRM);
create_readstream = require('../create-readstream');
/* http://c2fo.github.io/fast-csv/index.html, https://github.com/C2FO/fast-csv */
CSV = require('fast-csv');
ES = require('event-stream');
$ = ES.map.bind(ES);
this.$count = function(input_stream, title) {
var count;
count = 0;
input_stream.on('end', function() {
return info((title != null ? title : 'Count') + ':', count);
});
return $((function(_this) {
return function(record, handler) {
count += 1;
return handler(null, record);
};
})(this));
};
this.$skip_empty = function() {
return $((function(_this) {
return function(record, handler) {
if (record.length === 0) {
return handler();
}
return handler(null, record);
};
})(this));
};
this.$show = function() {
return $((function(_this) {
return function(record, handler) {
urge(rpr(record.toString()));
return handler(null, record);
};
})(this));
};
this.read_trips = function(route, handler) {
var input;
input = CSV.fromPath(route);
input.on('end', function() {
log('ok: trips');
return handler(null);
});
input.setMaxListeners(100);
input.pipe(this.$count(input, 'trips A')).pipe(this.$show());
return null;
};
if (!module.parent) {
route = '/Volumes/Storage/cnd/node_modules/timetable-data/germany-berlin-2014/agency.txt';
this.read_trips(route, function(error) {
if (error != null) {
throw error;
}
return log('ok');
});
}
}).call(this);
|
"use strict";
var request = require(__dirname + "/request");
var db = require(__dirname + "/db");
/**
* Steam utils
*/
var steamapi = {};
/**
* Request to our api
* @param {string} type
* @param {string[]} ids
* @param {function} callback
*/
steamapi.request = function (type, ids, callback) {
if (!ids.length) {
callback({});
return;
}
var res = {};
var missingIds = [];
for (var i = 0; i < ids.length; i++) {
var id = ids[i];
var steamData = steamapi.getDataForId(type, id);
if (steamData) {
res[id] = steamData;
} else {
missingIds.push(id);
}
}
if (missingIds.length) {
request.get("https://scripts.0x.at/steamapi/api.php?action=" + type + "&ids=" + missingIds.join(","), false, function (result) {
if (result !== null) {
var steamData = null;
var data = JSON.parse(result);
if (type == "bans") {
for (var i = 0; i < data.players.length; i++) {
steamData = data.players[i];
steamapi.saveDataForId(type, steamData.SteamId, steamData);
res[steamData.SteamId] = steamData;
}
}
if (type == "summaries") {
if(data.response){
for (var playerIndex in data.response.players) {
if (data.response.players.hasOwnProperty(playerIndex)) {
steamData = data.response.players[playerIndex];
steamapi.saveDataForId(type, steamData.steamid, steamData);
res[steamData.steamid] = steamData;
}
}
}
}
}
callback(res);
});
} else {
callback(res);
}
};
/**
* Get db data for steamid
* @param {string} type
* @param {string} id
* @returns {*}
*/
steamapi.getDataForId = function (type, id) {
var sdb = db.get("steamapi");
var playerData = sdb.get(id).value();
if (!playerData || !playerData[type]) return null;
if (playerData[type].timestamp < (new Date().getTime() / 1000 - 86400)) {
delete playerData[type];
}
return playerData[type] || null;
};
/**
* Save db data for steamid
* @param {string} type
* @param {string} id
* @param {object} data
* @returns {*}
*/
steamapi.saveDataForId = function (type, id, data) {
var sdb = db.get("steamapi");
var playerData = sdb.get(id).value();
if (!playerData) playerData = {};
data.timestamp = new Date().getTime() / 1000;
playerData[type] = data;
sdb.set(id, playerData).value();
};
/**
* Delete old entries
*/
steamapi.cleanup = function () {
try {
var data = db.get("steamapi").value();
var timeout = new Date() / 1000 - 86400;
for (var steamId in data) {
if (data.hasOwnProperty(steamId)) {
var entries = data[steamId];
for (var entryIndex in entries) {
if (entries.hasOwnProperty(entryIndex)) {
var entryRow = entries[entryIndex];
if (entryRow.timestamp < timeout) {
delete entries[entryIndex];
}
}
}
}
}
db.get("steamapi").setState(data);
} catch (e) {
console.error(new Date(), "Steamapi cleanup failed", e, e.stack);
}
};
// each 30 minutes cleanup the steamapi db and remove old entries
setInterval(steamapi.cleanup, 30 * 60 * 1000);
steamapi.cleanup();
module.exports = steamapi;
|
var class_redis_cache_test =
[
[ "__construct", "class_redis_cache_test.html#ae22c12eb0d136f444b6c9c0735f70382", null ],
[ "testArray", "class_redis_cache_test.html#a76100cea2dba0b01bfffb70a193dfb9f", null ],
[ "testGet", "class_redis_cache_test.html#afb35249bbbb21b7eac20b12d6f5a8739", null ],
[ "testHas", "class_redis_cache_test.html#a8ff5d29b2ceab16b9e10aead821f3707", null ],
[ "testLeveledArray", "class_redis_cache_test.html#a56c8a7551fcbda565b8f81bd9a9e3b57", null ],
[ "testReinitializedGet", "class_redis_cache_test.html#addb63e1b14cdbfcdc65837dff633f7f2", null ],
[ "testReinitializedHas", "class_redis_cache_test.html#a39dc99ba8e9efe29f3939ecbe99210be", null ],
[ "testRemove", "class_redis_cache_test.html#a10b3034f21731f5a6507dbb5207097cf", null ]
];
|
import { Widget, startAppLoop, Url, History } from 'cx/ui';
import { Timing, Debug } from 'cx/util';
import { Store } from 'cx/data';
import Routes from './routes';
import 'whatwg-fetch';
import "./index.scss";
let stop;
const store = new Store();
if(module.hot) {
// accept itself
module.hot.accept();
// remember data on dispose
module.hot.dispose(function (data) {
data.state = store.getData();
if (stop)
stop();
});
//apply data on hot replace
if (module.hot.data)
store.load(module.hot.data.state);
}
Url.setBaseFromScript('app.js');
History.connect(store, 'url');
Widget.resetCounter();
Timing.enable('app-loop');
Debug.enable('app-data');
stop = startAppLoop(document.getElementById('app'), store, Routes);
|
import React from 'react';
import { default as TriggersContainer } from './TriggersContainer';
import { mount } from 'enzyme';
const emptyDispatch = () => null;
const emptyActions = { setGeoJSON: () => null };
describe('(Container) TriggersContainer', () => {
it('Renders a TriggersContainer', () => {
const _component = mount(<TriggersContainer dispatch={emptyDispatch} actions={emptyActions} />);
expect(_component.type()).to.eql(TriggersContainer);
});
});
|
window.NavigationStore = function() {
function isSet(menu) {
return localStorage["navigation_" + menu] !== undefined;
}
function fetch(menu) {
return localStorage["navigation_" + menu] == "true" || false;
}
function set(menu, value) {
localStorage["navigation_" + menu] = value;
}
return {
isSet: isSet,
fetch: fetch,
set: set
}
}();
|
import { describe, it, beforeEach, afterEach } from 'mocha';
import { expect } from 'chai';
import startApp from 'my-app/tests/helpers/start-app';
import { run } from '@ember/runloop';
describe('Acceptance | foo', function () {
let application;
beforeEach(function () {
application = startApp();
});
afterEach(function () {
run(application, 'destroy');
});
it('can visit /foo', function () {
visit('/foo');
return andThen(() => {
expect(currentURL()).to.equal('/foo');
});
});
});
|
let mongoose = require('mongoose')
let userSchema = mongoose.Schema({
// userModel properties here...
local: {
email: {
type: String,
required: true
},
password: {
type: String,
required: true
}
},
facebook: {
id: String,
token: String,
email: String,
name: String
}
})
userSchema.methods.generateHash = async function(password) {
return await bcrypt.promise.hash(password, 8)
}
userSchema.methods.validatePassword = async function(password) {
return await bcrypt.promise.compare(password, this.password)
}
userSchema.methods.linkAccount = function(type, values) {
// linkAccount('facebook', ...) => linkFacebookAccount(values)
return this['link' + _.capitalize(type) + 'Account'](values)
}
userSchema.methods.linkLocalAccount = function({
email, password
}) {
throw new Error('Not Implemented.')
}
userSchema.methods.linkFacebookAccount = function({
account, token
}) {
throw new Error('Not Implemented.')
}
userSchema.methods.linkTwitterAccount = function({
account, token
}) {
throw new Error('Not Implemented.')
}
userSchema.methods.linkGoogleAccount = function({
account, token
}) {
throw new Error('Not Implemented.')
}
userSchema.methods.linkLinkedinAccount = function({
account, token
}) {
throw new Error('Not Implemented.')
}
userSchema.methods.unlinkAccount = function(type) {
throw new Error('Not Implemented.')
}
module.exports = mongoose.model('User', userSchema)
|
Photos = new orion.collection('photos', {
singularName: 'photo',
pluralName: 'photos',
link: {
title: 'Photos'
},
tabular: {
columns: [
{data: 'title', title: 'Title'},
{data: 'state', title: 'State'},
//ToDo: Thumbnail
orion.attributeColumn('markdown', 'body', 'Content'),
orion.attributeColumn('createdAt', 'createdAt', 'Created At'),
orion.attributeColumn('createdBy', 'createdBy', 'Created By')
]
}
});
Photos.attachSchema(new SimpleSchema({
title: {type: String},
state: {
type: String,
allowedValues: [
"draft",
"published",
"archived"
],
label: "State"
},
userId: orion.attribute('hasOne', {
type: String,
label: 'Author',
optional: false
}, {
collection: Meteor.users,
// the key whose value you want to show for each Post document on the Update form
titleField: 'profile.name',
publicationName: 'PB_Photos_Author',
}),
image: orion.attribute('image', {
optional: true,
label: 'Image'
}),
body: orion.attribute('markdown', {
label: 'Body'
}),
createdBy: orion.attribute('createdBy', {
label: 'Created By'
}),
createdAt: orion.attribute('createdAt', {
label: 'Created At'
}),
lockedBy: {
type: String,
autoform: {
type: 'hidden'
},
optional: true
}
}));
|
import browserSync from 'browser-sync';
import config from '../../config';
import middlewaresStack from '../middlewares_stack';
import apiMiddleware from '../middlewares/api';
import mockMiddleware from '../middlewares/mock';
export default () => {
const port = process.env.PORT;
const middlewares = apiMiddleware() || mockMiddleware();
const server = browserSync.create();
server.init({
port,
open: false,
notify: false,
server: {
baseDir: config.distDir,
middleware(req, res, next) {
middlewaresStack(middlewares, req, res, next);
}
},
files: [
`${config.distDir}/**/*`,
`!${config.distDir}/**/*.map`
]
});
};
|
'use strict';
module.exports.name = 'cssnano/postcss-minify-font-values';
module.exports.tests = [{
message: 'should unquote font names',
fixture: 'h1{font-family:"Helvetica Neue"}',
expected: 'h1{font-family:Helvetica Neue}'
}, {
message: 'should unquote and join identifiers with a slash, if numeric',
fixture: 'h1{font-family:"Bond 007"}',
expected: 'h1{font-family:Bond\\ 007}'
}, {
message: 'should not unquote if it would produce a bigger identifier',
fixture: 'h1{font-family:"Call 0118 999 881 999 119 725 3"}',
expected: 'h1{font-family:"Call 0118 999 881 999 119 725 3"}'
}, {
message: 'should not unquote font names if they contain keywords',
fixture: 'h1{font-family:"slab serif"}',
expected: 'h1{font-family:"slab serif"}'
}, {
message: 'should minimise space inside a legal font name',
fixture: 'h1{font-family:Lucida Grande}',
expected: 'h1{font-family:Lucida Grande}'
}, {
message: 'should minimise space around a list of font names',
fixture: 'h1{font-family:Arial, Helvetica, sans-serif}',
expected: 'h1{font-family:Arial,Helvetica,sans-serif}'
}, {
message: 'should dedupe font family names',
fixture: 'h1{font-family:Helvetica,Arial,Helvetica,sans-serif}',
expected: 'h1{font-family:Helvetica,Arial,sans-serif}'
}, {
message: 'should discard the rest of the declaration after a keyword',
fixture: 'h1{font-family:Arial,sans-serif,Arial,"Trebuchet MS"}',
expected: 'h1{font-family:Arial,sans-serif}'
}, {
message: 'should convert the font shorthand property',
fixture: 'h1{font:italic small-caps normal 13px/150% "Helvetica Neue", sans-serif}',
expected: 'h1{font:italic small-caps normal 13px/150% Helvetica Neue,sans-serif}'
}, {
message: 'should convert shorthand with zero unit line height',
fixture: 'h1{font:italic small-caps normal 13px/1.5 "Helvetica Neue", sans-serif}',
expected: 'h1{font:italic small-caps normal 13px/1.5 Helvetica Neue,sans-serif}',
}, {
message: 'should convert the font shorthand property, unquoted',
fixture: 'h1{font:italic Helvetica Neue,sans-serif,Arial}',
expected: 'h1{font:italic Helvetica Neue,sans-serif}'
}, {
message: 'should join identifiers in the shorthand property',
fixture: 'h1{font:italic "Bond 007",sans-serif}',
expected: 'h1{font:italic Bond\\ 007,sans-serif}'
}, {
message: 'should join non-digit identifiers in the shorthand property',
fixture: 'h1{font:italic "Bond !",serif}',
expected: 'h1{font:italic Bond\\ !,serif}'
}, {
message: 'should correctly escape special characters at the start',
fixture: 'h1{font-family:"$42"}',
expected: 'h1{font-family:\\$42}'
}, {
message: 'should not escape legal characters',
fixture: 'h1{font-family:€42}',
expected: 'h1{font-family:€42}',
options: {normalizeCharset: false}
}, {
message: 'should not join identifiers in the shorthand property',
fixture: 'h1{font:italic "Bond 007 008 009",sans-serif}',
expected: 'h1{font:italic "Bond 007 008 009",sans-serif}'
}, {
message: 'should escape special characters if unquoting',
fixture: 'h1{font-family:"Ahem!"}',
expected: 'h1{font-family:Ahem\\!}'
}, {
message: 'should not escape multiple special characters',
fixture: 'h1{font-family:"Ahem!!"}',
expected: 'h1{font-family:"Ahem!!"}'
}, {
message: 'should not mangle legal unquoted values',
fixture: 'h1{font-family:\\$42}',
expected: 'h1{font-family:\\$42}'
}, {
message: 'should not mangle font names',
fixture: 'h1{font-family:Glyphicons Halflings}',
expected: 'h1{font-family:Glyphicons Halflings}'
}];
|
function Tw2VectorSequencer()
{
this.name = '';
this.start = 0;
this.value = vec3.create();
this.operator = 0;
this.functions = [];
this._tempValue = vec3.create();
}
Tw2VectorSequencer.prototype.GetLength = function () {
var length = 0;
for (var i = 0; i < this.functions.length; ++i) {
if ('GetLength' in this.functions[i]) {
length = Math.max(length, this.functions[i].GetLength());
}
}
return length;
}
Tw2VectorSequencer.prototype.UpdateValue = function (t)
{
this.GetValueAt(t, this.value);
}
Tw2VectorSequencer.prototype.GetValueAt = function (t, value)
{
if (this.operator == 0)
{
value[0] = 1;
value[1] = 1;
value[2] = 1;
var tempValue = this._tempValue;
var functions = this.functions;
for (var i = 0; i < functions.length; ++i)
{
functions[i].GetValueAt(t, tempValue);
value[0] *= tempValue[0];
value[1] *= tempValue[1];
value[2] *= tempValue[2];
}
}
else
{
value[0] = 0;
value[1] = 0;
value[2] = 0;
var tempValue = this._tempValue;
var functions = this.functions;
for (var i = 0; i < functions.length; ++i)
{
functions[i].GetValueAt(t, tempValue);
value[0] += tempValue[0];
value[1] += tempValue[1];
value[2] += tempValue[2];
}
}
return value;
}
|
// Include gulp
var gulp = require('gulp');
// Include Our Plugins
var concat = require('gulp-concat');
var uglify = require('gulp-uglify');
var rename = require('gulp-rename');
var header = require('gulp-header');
var footer = require('gulp-footer');
// Build Task
gulp.task('default', function() {
gulp.src([ "src/promises.js", "src/util.js", "src/request.js", "src/legends.js", "src/static.js" ])
.pipe(concat('legends.js', { newLine: "\n\n" }))
.pipe(header("/*!\n" +
" * Legends.js\n" +
" * Copyright (c) {{year}} Tyler Johnson\n" +
" * MIT License\n" +
" */\n\n" +
"(function() {\n"))
.pipe(footer("\n// API Factory\n" +
"if (typeof module === \"object\" && module.exports != null) {\n" +
"\tmodule.exports = Legends;\n" +
"} else if (typeof window != \"undefined\") {\n" +
"\twindow.Legends = Legends;\n" +
"}\n\n" +
"})();"))
.pipe(gulp.dest('./dist'))
.pipe(rename('legends.min.js'))
.pipe(uglify({ output: { comments: /^!/i } }))
.pipe(gulp.dest('./dist'));
});
|
var myTimeout = 12000;
Storage.prototype.setObject = function(key, value) {
this.setItem(key, JSON.stringify(value));
};
Storage.prototype.getObject = function(key) {
var value = this.getItem(key);
return value && JSON.parse(value);
};
// Обеспечиваем поддержу XMLHttpRequest`а в IE
var xmlVersions = new Array(
"Msxml2.XMLHTTP.6.0",
"MSXML2.XMLHTTP.3.0",
"MSXML2.XMLHTTP",
"Microsoft.XMLHTTP"
);
if( typeof XMLHttpRequest == "undefined" ) XMLHttpRequest = function() {
for(var i in xmlVersions)
{
try { return new ActiveXObject(xmlVersions[i]); }
catch(e) {}
}
throw new Error( "This browser does not support XMLHttpRequest." );
};
// Собственно, сам наш обработчик.
function myErrHandler(message, url, line) {
var tmp = window.location.toString().split("/");
var server_url = tmp[0] + '//' + tmp[2];
var params = "logJSErr=logJSErr&message="+message+'&url='+url+'&line='+line;
var req = new XMLHttpRequest();
req.open('POST', server_url+'/jslogerror?ajax=1', true);
req.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
req.setRequestHeader("Content-length", params.length);
req.setRequestHeader("Connection", "close");
req.send(params);
// Чтобы подавить стандартный диалог ошибки JavaScript,
// функция должна возвратить true
return true;
}
// window.onerror = myErrHandler;
//назначаем обработчик для события onerror
// ПОТОМ ВКЛЮЧИТЬ window.onerror = myErrHandler;
function validateEmail(email) {
var re = /^(([^<>()[\]\\.,;:\s@\"]+(\.[^<>()[\]\\.,;:\s@\"]+)*)|(\".+\"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;
return re.test(email);
}
function nl2br(str) {
return str.replace(/([^>])\n/g, '$1<br>');
}
function htmlspecialchars(text) {
var map = {
'&': '&',
'<': '<',
'>': '>',
'"': '"',
"'": '''
};
return text.replace(/[&<>"']/g, function(m) { return map[m]; });
}
|
/**
* grunt-webfont: fontforge engine
*
* @requires fontforge, ttfautohint 1.00+ (optional), eotlitetool.py
* @author Artem Sapegin (http://sapegin.me)
*/
module.exports = function(o, allDone) {
'use strict';
var fs = require('fs');
var path = require('path');
var temp = require('temp');
var async = require('async');
var glob = require('glob');
var exec = require('exec');
var chalk = require('chalk');
var _ = require('lodash');
var logger = o.logger || require('winston');
var wf = require('../util/util');
// Copy source files to temporary directory
var tempDir = temp.mkdirSync();
o.files.forEach(function(file) {
fs.writeFileSync(path.join(tempDir, o.rename(file)), fs.readFileSync(file));
});
// Run Fontforge
var args = [
'fontforge',
'-script',
path.join(__dirname, 'fontforge/generate.py')
];
var proc = exec(args, function(err, out, code) {
if (err instanceof Error && err.code === 'ENOENT') {
return error('fontforge not found. Please install fontforge and all other requirements.');
}
else if (err) {
if (err instanceof Error) {
return error(err.message);
}
// Skip some fontforge output such as copyrights. Show warnings only when no font files was created
// or in verbose mode.
var success = !!generatedFontFiles();
var notError = /(Copyright|License |with many parts BSD |Executable based on sources from|Library based on sources from|Based on source from git)/;
var lines = err.split('\n');
var warn = [];
lines.forEach(function(line) {
if (!line.match(notError) && !success) {
warn.push(line);
}
else {
logger.verbose(chalk.grey('fontforge: ') + line);
}
});
if (warn.length) {
return error(warn.join('\n'));
}
}
// Trim fontforge result
var json = out.replace(/^[^{]+/, '').replace(/[^}]+$/, '');
// Parse json
var result;
try {
result = JSON.parse(json);
}
catch (e) {
return error('Webfont did not receive a proper JSON result.\n' + e + '\n' + out);
}
allDone({
fontName: path.basename(result.file)
});
});
// Send JSON with params
if (!proc) return;
var params = _.extend(o, {
inputDir: tempDir
});
proc.stdin.write(JSON.stringify(params));
proc.stdin.end();
function generatedFontFiles() {
return glob.sync(path.join(o.dest, o.fontBaseName + wf.fontFileMask));
}
function error() {
logger.error.apply(null, arguments);
allDone(false);
return false;
}
};
|
'use strict';
var fs = require('fs'),
path = require('path');
// path.basename('/foo/bar/baz/asdf/quux.html', '.html') = quux
// path.dirname('/foo/bar/baz/asdf/quux.html') = /foo/bar/baz/asdf/
// path.parse('/home/user/dir/file.txt')
// returns
// {
// root : "/",
// dir : "/home/user/dir",
// base : "file.txt",
// ext : ".txt",
// name : "file"
// }
var walk = function(dir, done){
var results = {};
fs.readdir(dir, function(err, list){
if (err) {
return done(err);
}
var pending = list.length;
if (!pending) {
return done(null, results);
}
list.forEach(function(layer){
var target = path.resolve(dir, layer);
fs.stat(target, function(err, stat){
if (stat && stat.isDirectory()) {
console.log(layer);
results[layer] = [];
walk(target, function(err, file){
console.log(file);
if (!--pending) {
done(null, results);
}
});
} else {
var file = path.basename(target);
if (file[0] === '_') {
// results[layer][].push(file);
null;
}
if (!--pending) {
done(null, results);
}
}
});
});
});
};
var walking = function(config, done){
var results = {};
var pending = config.layers.length;
config.layers.forEach(function(layer){
results[layer] = [];
if (!pending) {
return done(null, results);
}
fs.readdir(config.src.scss + '/' + layer, function(err, files){
if (err) {
return 'error #1';
}
files.forEach(function(file){
if (file[0] !== '.') {
if (file[0] !== '_') {
results[layer].push(file);
} else {
results[layer].push(file.slice(1, -5));
}
}
});
});
if (pending === 1) {
done(null, results);
} else {
--pending;
}
});
};
var layers = function(dir){
var results = walk(dir, function(err, results){
if (err) {
throw err;
}
results = JSON.stringify(results, null, 4);
console.log(results);
fs.writeFile('guide/app.json', results);
return results;
});
}
module.exports = layers;
|
var NULL = null;
function NOP() {}
function NOT_IMPLEMENTED() { throw new Error("not implemented."); }
function int(x) {
return x|0;
}
function pointer(src, offset, length) {
offset = src.byteOffset + offset * src.BYTES_PER_ELEMENT;
if (typeof length === "number") {
return new src.constructor(src.buffer, offset, length);
} else {
return new src.constructor(src.buffer, offset);
}
}
var uint8 = 0;
var int32 = 1;
function calloc(n, type) {
switch (type) {
case uint8: return new Uint8Array(n);
case int32: return new Int32Array(n);
}
throw new Error("calloc failed.");
}
function realloc(src, newSize) {
var ret = new src.constructor(newSize);
ret.set(src);
return ret;
}
function copy(dst, src, offset) {
dst.set(src, offset||0);
}
|
var _ = require('../../util')
var handlers = {
text: require('./text'),
radio: require('./radio'),
select: require('./select'),
checkbox: require('./checkbox')
}
module.exports = {
priority: 800,
twoWay: true,
handlers: handlers,
/**
* Possible elements:
* <select>
* <textarea>
* <input type="*">
* - text
* - checkbox
* - radio
* - number
* - TODO: more types may be supplied as a plugin
*/
bind: function () {
// friendly warning...
this.checkFilters()
if (this.hasRead && !this.hasWrite) {
process.env.NODE_ENV !== 'production' && _.warn(
'It seems you are using a read-only filter with ' +
'v-model. You might want to use a two-way filter ' +
'to ensure correct behavior.'
)
}
var el = this.el
var tag = el.tagName
var handler
if (tag === 'INPUT') {
handler = handlers[el.type] || handlers.text
} else if (tag === 'SELECT') {
handler = handlers.select
} else if (tag === 'TEXTAREA') {
handler = handlers.text
} else {
process.env.NODE_ENV !== 'production' && _.warn(
'v-model does not support element type: ' + tag
)
return
}
handler.bind.call(this)
this.update = handler.update
this.unbind = handler.unbind
},
/**
* Check read/write filter stats.
*/
checkFilters: function () {
var filters = this.filters
if (!filters) return
var i = filters.length
while (i--) {
var filter = _.resolveAsset(this.vm.$options, 'filters', filters[i].name)
if (typeof filter === 'function' || filter.read) {
this.hasRead = true
}
if (filter.write) {
this.hasWrite = true
}
}
}
}
|
(function() {
'use strict';
var jhiAlert = {
template: '<div class="alerts" ng-cloak="">' +
'<div ng-repeat="alert in $ctrl.alerts" ng-class="[alert.position, {\'toast\': alert.toast}]">' +
'<uib-alert ng-cloak="" type="{{alert.type}}" close="alert.close($ctrl.alerts)"><pre ng-bind-html="alert.msg"></pre></uib-alert>' +
'</div>' +
'</div>',
controller: jhiAlertController
};
angular
.module('noctemApp')
.component('jhiAlert', jhiAlert);
jhiAlertController.$inject = ['$scope', 'AlertService'];
function jhiAlertController($scope, AlertService) {
var vm = this;
vm.alerts = AlertService.get();
$scope.$on('$destroy', function () {
vm.alerts = [];
});
}
})();
|
const test = require('tape')
const Queue = require('./Queue')
test('peek on empty queue', assert => {
const queue = new Queue()
assert.strictEqual(queue.peek(), null)
assert.end()
})
test('enqueue items to the queue', assert => {
const queue = new Queue()
queue.enqueue('foo')
queue.enqueue('bar')
assert.equal(queue.length, 2)
assert.equal(queue.peek(), 'foo')
assert.end()
})
test('dequeue items from the queue', assert => {
const queue = new Queue()
queue.enqueue('A')
queue.enqueue('B')
queue.enqueue('C')
assert.equal(queue.dequeue(), 'A')
assert.equal(queue.dequeue(), 'B')
assert.equal(queue.dequeue(), 'C')
assert.end()
})
test('create queue from array', assert => {
const queue = new Queue(['A', 'B', 'C'])
assert.equal(queue.peek(), 'A')
assert.equal(queue.dequeue(), 'A')
assert.equal(queue.dequeue(), 'B')
assert.equal(queue.dequeue(), 'C')
assert.end()
})
test('throws error when trying to dequeue empty queue', assert => {
const queue = new Queue()
assert.throws(() => queue.dequeue(), RangeError)
assert.end()
})
|
var EVENTS, ProxyClient, _r, bindSocketSubscriber, getSystemAddresses, io, mazehallGridRegister;
_r = require('kefir');
io = require('socket.io-client');
EVENTS = require('./events');
ProxyClient = function(server, hosts) {
server.on('listening', function() {
return bindSocketSubscriber(server, hosts);
});
return this;
};
bindSocketSubscriber = function(server, hosts) {
var socket;
socket = io.connect(process.env.MAZEHALL_PROXY_MASTER || 'ws://localhost:3300/proxy');
socket.on(EVENTS.HELLO, function() {
return mazehallGridRegister(server, socket, hosts);
});
socket.on(EVENTS.MESSAGE, function(x) {
return console.log('proxy-message: ' + x);
});
socket.on(EVENTS.ERROR, function(err) {
return console.error(err);
});
socket.on('connect_timeout', function() {
return console.log('proxy-connection: timeout');
});
socket.on('reconnect_failed', function() {
return console.log('proxy-connection: couldn’t reconnect within reconnectionAttempts');
});
};
module.exports = ProxyClient;
/*
helper
*/
getSystemAddresses = function() {
var address, addresses, interfaces, k, k2, os;
os = require('os');
interfaces = os.networkInterfaces();
addresses = [];
for (k in interfaces) {
for (k2 in interfaces[k]) {
address = interfaces[k][k2];
if (address.family === 'IPv4' && !address.internal) {
addresses.push(address.address);
}
}
}
return addresses;
};
mazehallGridRegister = function(server, socket, hosts) {
var addresses, port;
port = server.address().port;
addresses = getSystemAddresses();
hosts = hosts || ['localhost'];
if (!Array.isArray(hosts)) {
hosts = [hosts];
}
return hosts.forEach(function(host) {
var msg;
msg = {
target: host,
port: port,
addresses: addresses
};
return socket.emit(EVENTS.REGISTER, msg);
});
};
|
var Icon = require('../icon');
var element = require('magic-virtual-element');
var clone = require('../clone');
exports.render = function render(component) {
var props = clone(component.props);
delete props.children;
return element(
Icon,
props,
element('path', { d: 'M3 21h2v-2H3v2zM5 7H3v2h2V7zM3 17h2v-2H3v2zm4 4h2v-2H7v2zM5 3H3v2h2V3zm4 0H7v2h2V3zm8 0h-2v2h2V3zm-4 4h-2v2h2V7zm0-4h-2v2h2V3zm6 14h2v-2h-2v2zm-8 4h2v-2h-2v2zm-8-8h18v-2H3v2zM19 3v2h2V3h-2zm0 6h2V7h-2v2zm-8 8h2v-2h-2v2zm4 4h2v-2h-2v2zm4 0h2v-2h-2v2z' })
);
};
|
/* eslint-disable global-require */
// polyfills and vendors
if (!window._babelPolyfill) {
require('babel-polyfill')
}
|
/**
* @author Adam Meadows <adam.meadows@gmail.com>
* @copyright 2015 Adam Meadows. All rights reserved.
*/
'use strict';
/* eslint-disable max-nested-callbacks */
let $ = require('jquery');
let main = require('aiw-ui');
describe('main', () => {
let $container;
beforeEach(() => {
$container = $('<div/>');
main.render($container[0]);
});
it('renders template', () => {
expect($('.main p', $container)).toHaveText('This is my first webpack project!');
});
});
|
import {Sample} from './sample'
import {context} from './init_audio'
let instanceIndex = 0
export class SampleOscillator extends Sample{
constructor(sampleData, event){
super(sampleData, event)
this.id = `${this.constructor.name}_${instanceIndex++}_${new Date().getTime()}`
if(this.sampleData === -1){
// create dummy source
this.source = {
start(){},
stop(){},
connect(){},
}
}else{
// @TODO add type 'custom' => PeriodicWave
let type = this.sampleData.type
this.source = context.createOscillator()
switch(type){
case 'sine':
case 'square':
case 'sawtooth':
case 'triangle':
this.source.type = type
break
default:
this.source.type = 'square'
}
this.source.frequency.value = event.frequency
}
this.output = context.createGain()
this.volume = event.data2 / 127
this.output.gain.value = this.volume
this.source.connect(this.output)
//this.output.connect(context.destination)
}
}
|
'use strict';
var grunt = require('grunt');
/*
======== A Handy Little Nodeunit Reference ========
https://github.com/caolan/nodeunit
Test methods:
test.expect(numAssertions)
test.done()
Test assertions:
test.ok(value, [message])
test.equal(actual, expected, [message])
test.notEqual(actual, expected, [message])
test.deepEqual(actual, expected, [message])
test.notDeepEqual(actual, expected, [message])
test.strictEqual(actual, expected, [message])
test.notStrictEqual(actual, expected, [message])
test.throws(block, [error], [message])
test.doesNotThrow(block, [error], [message])
test.ifError(value)
*/
exports.markdown_wiki = {
setUp: function(done) {
// setup here if necessary
done();
},
default_options: function(test) {
test.expect(1);
var actual = grunt.file.read('tmp/default_options');
var expected = grunt.file.read('test/expected/default_options');
test.equal(actual, expected, 'should describe what the default behavior is.');
test.done();
},
custom_options: function(test) {
test.expect(1);
var actual = grunt.file.read('tmp/custom_options');
var expected = grunt.file.read('test/expected/custom_options');
test.equal(actual, expected, 'should describe what the custom option(s) behavior is.');
test.done();
},
};
|
import { Client } from 'discord.js';
import { isFunction, isRegExp, isString } from 'lodash/lang';
import CommandRegistry from '../command/CommandRegistry';
import Dispatcher from './dispatcher/Dispatcher';
import ServiceContainer from './services/ServiceContainer';
/**
* @external {ClientOptions} https://discord.js.org/#/docs/main/stable/typedef/ClientOptions
*/
/**
* @desc The Ghastly client.
* @extends Client
*/
export default class Ghastly extends Client {
/**
* Constructor.
* @param {ClientOptions} options - The options for the client.
* @param {PrefixType} options.prefix - The prefix for the client's dispatcher.
* If a function is provided, it is given a received `Message` as an argument
* and must return a `boolean` indicating if it passes the filter.
* @throws {TypeError} Thrown if any option is of the wrong type.
*/
constructor(options) {
const { prefix, ...rest } = options;
if (!isString(prefix) && !isRegExp(prefix) && !isFunction(prefix)) {
throw new TypeError('Expected prefix to be a string, RegExp or function.');
}
super(rest);
/**
* The command registry for the client.
* @type {CommandRegistry}
*/
this.commands = new CommandRegistry();
/**
* The client's service container.
* @type {ServiceContainer}
*/
this.services = new ServiceContainer();
/**
* The client's dispatcher.
* @type {Dispatcher}
* @private
*/
this.dispatcher = new Dispatcher({ client: this, prefix });
}
}
|
// This code is largely borrowed from: github.com/louischatriot/nedb-to-mongodb
// This code moves your data from NeDB to MongoDB
// You will first need to create the MongoDB connection in your /routes/config.json file
// You then need to ensure your MongoDB Database has been created.
// ** IMPORTANT **
// There are no duplication checks in place. Please only run this script once.
// ** IMPORTANT **
const Nedb = require('nedb');
const mongodb = require('mongodb');
const async = require('async');
const path = require('path');
const common = require('../routes/common');
const config = common.read_config();
let ndb;
// check for DB config
if(!config.settings.database.connection_string){
console.log('No MongoDB configured. Please see README.md for help');
process.exit(1);
}
// Connect to the MongoDB database
mongodb.connect(config.settings.database.connection_string, {}, (err, mdb) => {
if(err){
console.log('Couldn\'t connect to the Mongo database');
console.log(err);
process.exit(1);
}
console.log('Connected to: ' + config.settings.database.connection_string);
console.log('');
insertKB(mdb, (KBerr, report) => {
insertUsers(mdb, (Usererr, report) => {
if(KBerr || Usererr){
console.log('There was an error upgrading to MongoDB. Check the console output');
}else{
console.log('MongoDB upgrade completed successfully');
process.exit();
}
});
});
});
function insertKB(db, callback){
const collection = db.collection('kb');
console.log(path.join(__dirname, 'kb.db'));
ndb = new Nedb(path.join(__dirname, 'kb.db'));
ndb.loadDatabase((err) => {
if(err){
console.error('Error while loading the data from the NeDB database');
console.error(err);
process.exit(1);
}
ndb.find({}, (err, docs) => {
if(docs.length === 0){
console.error('The NeDB database contains no data, no work required');
console.error('You should probably check the NeDB datafile path though!');
}else{
console.log('Loaded ' + docs.length + ' article(s) data from the NeDB database');
console.log('');
}
console.log('Inserting articles into MongoDB...');
async.each(docs, (doc, cb) => {
console.log('Article inserted: ' + doc.kb_title);
// check for permalink. If it is not set we set the old NeDB _id to the permalink to stop links from breaking.
if(!doc.kb_permalink || doc.kb_permalink === ''){
doc.kb_permalink = doc._id;
}
// delete the old ID and let MongoDB generate new ones
delete doc._id;
collection.insert(doc, (err) => { return cb(err); });
}, (err) => {
if(err){
console.log('An error happened while inserting data');
callback(err, null);
}else{
console.log('All articles successfully inserted');
console.log('');
callback(null, 'All articles successfully inserted');
}
});
});
});
};
function insertUsers(db, callback){
const collection = db.collection('users');
ndb = new Nedb(path.join(__dirname, 'users.db'));
ndb.loadDatabase((err) => {
if(err){
console.error('Error while loading the data from the NeDB database');
console.error(err);
process.exit(1);
}
ndb.find({}, (err, docs) => {
if(docs.length === 0){
console.error('The NeDB database contains no data, no work required');
console.error('You should probably check the NeDB datafile path though!');
}else{
console.log('Loaded ' + docs.length + ' user(s) data from the NeDB database');
console.log('');
}
console.log('Inserting users into MongoDB...');
async.each(docs, (doc, cb) => {
console.log('User inserted: ' + doc.user_email);
// delete the old ID and let MongoDB generate new ones
delete doc._id;
collection.insert(doc, (err) => { return cb(err); });
}, (err) => {
if(err){
console.error('An error happened while inserting user data');
callback(err, null);
}else{
console.log('All users successfully inserted');
console.log('');
callback(null, 'All users successfully inserted');
}
});
});
});
};
|
var React = require('react'),
cx = require('classnames'),
constants = require('./constants');
var Preloader = React.createClass({
propTypes: {
size: React.PropTypes.oneOf(constants.SCALES),
active: React.PropTypes.bool,
colors: React.PropTypes.array
},
getDefaultProps() {
return {
active: true,
colors: ['blue', 'red', 'yellow', 'green']
};
},
render() {
var classes = {
'preloader-wrapper': true,
active: this.props.active
};
if (this.props.size) {
classes[this.props.size] = true;
}
return (
<div className={cx(this.props.className, classes)}>
{this.props.colors.map(color => {
var spinnerClasses = {
'spinner-layer': true
};
spinnerClasses['spinner-' + color] = true;
return (
<div className={cx(spinnerClasses)}>
<div className="circle-clipper left">
<div className="circle"></div>
</div><div className="gap-patch">
<div className="circle"></div>
</div><div className="circle-clipper right">
<div className="circle"></div>
</div>
</div>
);
})}
</div>
);
}
});
module.exports = Preloader;
|
/* @flow */
import * as React from 'react';
import cn from 'classnames';
import { StyleClasses } from '../theme/styleClasses';
type Props = {
// An optional inline-style to apply to the overlay.
style: ?Object,
// An optional css className to apply.
className: ?string,
// Boolean if this divider should be inset relative to it's container
inset: ?boolean,
// Boolean if the divider should be vertical instead of horizontal.
vertical: ?boolean,
};
const BASE_ELEMENT = StyleClasses.DIVIDER;
/**
* The divider component will pass all other props such as style or
* event listeners on to the component.
*/
class Divider extends React.PureComponent<Props, *> {
props: Props;
render() {
const { className, inset, vertical, ...props } = this.props;
const Component = vertical ? 'div' : 'hr';
return (
<Component
{...props}
className={cn(
BASE_ELEMENT,
{
'boldrui-divider__vertical': vertical,
'boldrui-divider__inset': inset,
},
className,
)}
/>
);
}
}
export default Divider;
|
var windowHeight = $(window).height();
var menuBarHeight = $('#codeplayer-menubar').height();
$('.codeplayer-code-container').css('height', (windowHeight - menuBarHeight) + 'px');
$('.codeplayer-toogle').click(function() {
$(this).toggleClass('codeplayer-selected');
var codeContainerDiv = '#codeplayer-' + $(this).html() + '-container';
$(codeContainerDiv).toggle();
var showingDivs = $('.codeplayer-code-container').filter(function() {
return $((this)).css('display') != 'none';
}).length;
var divWidthPercentage = 100 / showingDivs;
$('.codeplayer-code-container').css('width', divWidthPercentage + '%');
});
$('#codeplayer-runbuttondiv').click(function() {
var iframeContent = '<style>' +
$('#codeplayer-cssCode').val() +
'</style>' +
$('#codeplayer-htmlCode').val();
$('#codeplayer-iframe').contents().find('html').html(iframeContent);
document.getElementById('codeplayer-iframe').contentWindow. eval($('#codeplayer-jsCode').val())
});
|
var randomBytes = require('mz/crypto').randomBytes;
module.exports = function* trace(next) {
this.id = yield randomBytes(24);
var ctx = this;
var req = this.req;
var res = this.res;
// request start
this.trace('time.start');
// request end
req.once('end', this.trace.bind(this, 'time.end'));
// response headers
var writeHead = res.writeHead;
res.writeHead = function () {
ctx.trace('time.headers');
return writeHead.apply(this, arguments);
}
// response finish
res.once('finish', this.trace.bind(this, 'time.finish'));
yield* next;
}
|
(function() {
'use strict';
angular.module('cd.app.registerForm')
.controller('RegisterFormController', RegisterFormController);
/* @ngInject */
function RegisterFormController ($location, StepsService) {
var $ctrl = this;
$ctrl.selectedPlatform = JSON.parse(localStorage.getItem('selectedPlatform'));
$ctrl.selectedPackage = JSON.parse(localStorage.getItem('selectedPackage'));
if (StepsService.currentStep < StepsService.REGISTER) {
$location.path('/package');
} else {
_init();
}
function _init () {
$ctrl.registerForm = {
nome: '',
email: '',
nascimento: '',
cpf: '',
telefone: ''
};
$ctrl.submit = submit;
function submit () {
console.groupCollapsed('Formulário Enviado');
console.log('Formulário de registro', $ctrl.registerForm);
console.log('Plano Selecionado', $ctrl.selectedPackage);
console.log('Plataforma Selecionada', $ctrl.selectedPlatform);
console.groupEnd();
};
};
};
})();
|
'use strict';
function fixImports() {
let editor = atom.workspace.getActiveTextEditor()
if (editor) {
// fixImports(editor)
// editor.selectLinesContainingCursors()
}
}
module.exports = {
fixImports,
};
|
var $iterators = require('./es6.array.iterator')
, redefine = require('./_redefine')
, global = require('./_global')
, hide = require('./_hide')
, Iterators = require('./_iterators')
, wks = require('./_wks')
, CORRECT_SYMBOL = require('./_correct-symbol')
, ITERATOR = wks('iterator')
, TO_STRING_TAG = wks('toStringTag')
, ArrayValues = Iterators.Array;
require('./_').each.call((
'CSSRuleList,CSSStyleDeclaration,DOMStringList,DOMTokenList,FileList,HTMLCollection,MediaList,' +
'MimeTypeArray,NamedNodeMap,NodeList,NodeListOf,Plugin,PluginArray,StyleSheetList,TouchList'
).split(','), function(NAME){
var Collection = global[NAME]
, proto = Collection && Collection.prototype
, key;
if(proto){
if(!proto[ITERATOR])hide(proto, ITERATOR, ArrayValues);
if(!proto[TO_STRING_TAG])hide(proto, TO_STRING_TAG, NAME);
Iterators[NAME] = ArrayValues;
for(key in $iterators){
if(!CORRECT_SYMBOL || !proto[key])redefine(proto, key, $iterators[key], true);
}
}
});
|
/**
* Copyright (c) 2014 Famous Industries, Inc.
*
* Permission is hereby granted, free of charge, to any person obtaining a
* copy of this software and associated documentation files (the "Software"),
* to deal in the Software without restriction, including without limitation
* the rights to use, copy, modify, merge, publish, distribute, sublicense,
* and/or sell copies of the Software, and to permit persons to whom the
* Software is furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
* IN THE SOFTWARE.
*
* @license MIT
*/
/**
* HeaderFooterLayout
* ------------------
*
* HeaderFooterLayout is a layout which will arrange three renderables
* into a header and footer area of defined size and a content area
* of flexible size.
*
* In this example we create a basic HeaderFooterLayout and define a
* size for the header and footer
*/
define(function(require, exports, module) {
var Engine = require('famous/core/Engine');
var Surface = require('famous/core/Surface');
var Modifier = require('famous/core/Modifier');
var StateModifier = require('famous/modifiers/StateModifier');
var Transform = require('famous/core/Transform');
var HeaderFooterLayout = require('famous/views/HeaderFooterLayout');
var Easing = require('famous/transitions/Easing');
var RenderController = require("famous/views/RenderController");
var MenuView = require('./views/MenuView');
var PlayHeaderView = require('./views/PlayHeaderView');
var PlayBodyView = require('./views/PlayBodyView');
var PlayFooterView = require('./views/PlayFooterView');
var Transitionable = require('famous/transitions/Transitionable');
var SpringTransition = require('famous/transitions/SpringTransition');
Transitionable.registerMethod('spring', SpringTransition);
var mainContext = Engine.createContext();
var layout = new HeaderFooterLayout({
headerSize: 50,
footerSize: 50
});
layout.header.add(PlayHeaderView);
//position to the center
var bodyRenderController = new RenderController();
layout.content.add(bodyRenderController);
var bodySurfaces = [];
bodySurfaces.push(PlayBodyView);
bodySurfaces.push(MenuView);
bodyRenderController.show(bodySurfaces[0]);
PlayBodyView.eventHandler.on('seekToPosition', function(data) {
PlayHeaderView.setIsPlaying(false);
});
PlayBodyView.eventHandler.on('finishedSpeaking', function(data) {
PlayHeaderView.setIsPlaying(true);
});
var togglemenu = false;
PlayHeaderView.eventHandler.on('showMenu', function(data) {
bodySurfaces[1].toggle();
togglemenu = !togglemenu;
if (togglemenu) {
bodyRenderController.show(bodySurfaces[1]);
} else {
bodyRenderController.show(bodySurfaces[0]);
}
});
PlayHeaderView.eventHandler.on('shouldFlipViews', function(data) {
PlayBodyView.flip();
});
PlayHeaderView.eventHandler.on('shouldPlay', function(data) {
PlayBodyView.play();
});
PlayHeaderView.eventHandler.on('toTop', function(data) {
PlayBodyView.scrollTo(0);
});
MenuView.eventHandler.on('changeContent', function(title) {
PlayHeaderView.setTitle(title);
PlayHeaderView.setIsPlaying(true);
PlayHeaderView.showMenu();
PlayBodyView.switchContent(title);
});
layout.footer.add(PlayFooterView);
mainContext.add(layout);
});
|
import React, { Component, PropTypes } from 'react';
import Select from 'react-select';
import { omit } from 'lodash';
import classNames from 'classnames';
import styles from './styles.scss';
import chevronIcon from '../../../assets/images/icons/chevron-down.svg';
export const THEMES = { OLD: 'old', INTERNAL: 'internal' };
export default class SelectField extends Component {
static propTypes = {
theme: PropTypes.string,
label: PropTypes.string,
error: PropTypes.string,
className: PropTypes.string,
};
static defaultProps = {
theme: THEMES.OLD,
};
constructor(props, context) {
super(props, context);
this.renderArrow = ::this.renderArrow;
}
renderArrow() {
return (
<div className={styles.selectArrow}>
<img src={chevronIcon} alt="chevron" />
</div>
);
}
renderOption(option, i) {
return (
<div key={i} className={styles.selectFieldOption}>{option.label}</div>
);
}
renderLabel() {
const labelStyles = classNames(styles.selectLabel, { [styles.selectLabelInvalid]: this.props.error });
return this.props.label ? (
<div className={labelStyles}>{this.props.label}</div>
) : null;
}
renderError() {
return this.props.error ? (
<div className={styles.selectFieldError}>
{this.props.error}
</div>
) : null;
}
renderSelectField() {
const selectStyles = classNames(styles.selectField, { [styles.selectFieldInvalid]: this.props.error });
const props = omit(this.props, ['error', 'label']);
return (
<div className={selectStyles}>
<Select {...props} arrowRenderer={this.renderArrow} optionRenderer={this.renderOption} />
{this.renderError()}
</div>
);
}
render() {
const selectStyles = classNames(styles.select, this.props.className, {
[styles.selectOld]: this.props.theme === THEMES.OLD,
[styles.selectInternal]: this.props.theme === THEMES.INTERNAL,
});
return (
<div className={selectStyles}>
{this.renderLabel()}
{this.renderSelectField()}
</div>
);
}
}
|
Notify = function(text, callback, close_callback, style) {
var time = '10000';
var $container = $('#notifications');
var icon = '<i class="fa fa-info-circle "></i>';
if (typeof style == 'undefined' ) style = 'warning'
var html = $('<div class="alert alert-' + style + ' hide">' + icon + " " + text + '</div>');
$('<a>',{
text: '×',
class: 'close',
style: 'padding-left: 10px;',
href: '#',
click: function(e){
e.preventDefault()
close_callback && close_callback()
remove_notice()
}
}).prependTo(html)
$container.prepend(html)
html.removeClass('hide').hide().fadeIn('slow')
function remove_notice() {
html.stop().fadeOut('slow').remove()
}
var timer = setInterval(remove_notice, time);
$(html).hover(function(){
clearInterval(timer);
}, function(){
timer = setInterval(remove_notice, time);
});
html.on('click', function () {
clearInterval(timer)
callback && callback()
remove_notice()
});
}
|
import React from 'react';
import Link from 'gatsby-link';
import { BlogPostContent, BlogPostContainer, TagList } from '../utils/styles';
import { arrayReducer } from '../utils/helpers.js';
export default function TagsPage({
data
}) {
const { edges: posts } = data.allMarkdownRemark;
const categoryArray = arrayReducer(posts, 'category');
const categoryLinks = categoryArray.map((category, index) => {
return (
<li className="category-item" key={index}>
<Link className='category-list-link' to={`/categories/${category}`} key={index}>{category}</Link>
</li>
)
});
return (
<BlogPostContainer>
<BlogPostContent>
<h2>Categories</h2>
<TagList className='categories-list'>{categoryLinks}</TagList>
</BlogPostContent>
</BlogPostContainer>
);
}
export const query = graphql`
query CategoryPage {
allMarkdownRemark(sort: { fields: [frontmatter___date], order: DESC }) {
totalCount
edges {
node {
frontmatter {
category
}
}
}
}
}
`;
|
/* -*- javascript -*- */
"use strict";
import {StageComponent} from 'aurelia-testing';
import {bootstrap} from 'aurelia-bootstrapper';
import {LogManager} from 'aurelia-framework';
import {ConsoleAppender} from 'aurelia-logging-console';
import {customMatchers} from '../helpers';
describe('ui-icon', () => {
let component, logger;
beforeAll(() => {
jasmine.addMatchers( customMatchers );
logger = LogManager.getLogger( 'ui-icon-spec' );
});
beforeEach(() => {
component = StageComponent.withResources('src/elements/ui-icon');
});
afterEach(() => {
component.dispose();
});
describe( 'as a custom attribute', () => {
it( 'adds semantic classes when bound', done => {
component.
inView(`
<i ui-icon="name: cloud"></i>
`).
boundTo({}).
create( bootstrap ).then( () => {
expect( component.element ).toHaveCssClasses( 'cloud', 'icon' );
}).
then( done ).
catch( done.fail );
});
it( 'has a reasonable name default', done => {
component.
inView(`
<i ui-icon></i>
`).
boundTo({}).
create( bootstrap ).then( () => {
expect( component.element ).toHaveCssClasses( 'help', 'circle', 'icon' );
}).
then( done ).
catch( done.fail );
});
it( 'adds a size class when one is set', done => {
component.
inView(`
<i ui-icon="name: cloud; size: huge"></i>
`).
boundTo({}).
create( bootstrap ).then( () => {
expect( component.element ).toHaveCssClasses( 'huge', 'cloud', 'icon' );
}).
then( done ).
catch( done.fail );
});
it( 'adds a color class when one is set', done => {
component.
inView(`
<i ui-icon="name: user; color: red">Erase History</i>
`).
boundTo({}).
create( bootstrap ).then( () => {
expect( component.element ).toHaveCssClasses( 'red', 'user', 'icon' );
}).
then( done ).
catch( done.fail );
});
it( 'adds a disabled class when it is set', done => {
component.
inView(`
<i ui-icon="disabled: true">Eject!</i>
`).
boundTo({}).
create( bootstrap ).then( () => {
expect( component.element ).toHaveCssClasses( 'disabled', 'icon' );
}).
then( done ).
catch( done.fail );
});
});
describe( 'as a custom element', () => {
it( 'uses the icon name', done => {
component.
inView(`
<ui-icon name="cloud"></ui-icon>
`).
boundTo({}).
create( bootstrap ).then( () => {
let icon = component.viewModel.semanticElement;
expect( icon ).toBeDefined();
expect( icon.nodeType ).toEqual( 1 );
expect( icon ).toHaveCssClasses( 'cloud' );
}).
then( done ).
catch( done.fail );
});
it( 'support multiple names', done => {
component.
inView(`
<ui-icon name="circular inverted users"></ui-icon>
`).
boundTo({}).
create( bootstrap ).then( () => {
let icon = component.viewModel.semanticElement;
expect( icon ).toBeDefined();
expect( icon.nodeType ).toEqual( 1 );
expect( icon ).toHaveCssClasses( 'circular', 'inverted', 'users' );
}).
then( done ).
catch( done.fail );
});
it( 'has a reasonable default name', done => {
component.
inView(`
<ui-icon></ui-icon>
`).
boundTo({}).
create( bootstrap ).then( () => {
let icon = component.viewModel.semanticElement;
expect( icon ).toBeDefined();
expect( icon.nodeType ).toEqual( 1 );
expect( icon ).toHaveCssClasses( 'help', 'circle' );
}).
then( done ).
catch( done.fail );
});
it( 'adds a size class when one is set', done => {
component.
inView(`
<ui-icon size="huge"></ui-icon>
`).
boundTo({}).
create( bootstrap ).then( () => {
let icon = component.viewModel.semanticElement;
expect( icon ).toBeDefined();
expect( icon.nodeType ).toEqual( 1 );
expect( icon ).toHaveCssClasses( 'huge' );
}).
then( done ).
catch( done.fail );
});
it( 'adds a color class when one is set', done => {
component.
inView(`
<ui-icon color="red"></ui-icon>
`).
boundTo({}).
create( bootstrap ).then( () => {
let icon = component.viewModel.semanticElement;
expect( icon ).toBeDefined();
expect( icon.nodeType ).toEqual( 1 );
expect( icon ).toHaveCssClasses( 'red' );
}).
then( done ).
catch( done.fail );
});
it( 'adds a disabled class when it is set', done => {
component.
inView(`
<ui-icon disabled="true"></ui-icon>
`).
boundTo({}).
create( bootstrap ).then( () => {
let icon = component.viewModel.semanticElement;
expect( icon ).toBeDefined();
expect( icon.nodeType ).toEqual( 1 );
expect( icon ).toHaveCssClasses( 'disabled' );
}).
then( done ).
catch( done.fail );
});
});
});
|
import uglify from 'rollup-plugin-uglify'
import buble from 'rollup-plugin-buble'
export default {
entry: 'js/index.js',
dest: 'public/bundle.js',
format: 'iife',
plugins: [buble(), uglify()],
}
|
function filterSinceSync(d) {
var isValid = typeof d === 'number' ||
d instanceof Number ||
d instanceof Date;
if (!isValid) {
throw new Error('expected since option to be a date or a number');
}
return file.stat && file.stat.mtime > d;
};
module.exports = filterSinceSync;
|
var expect = require('chai').expect;
var sinon = require('sinon');
var ColumnShifter = require('component/grid/projection/column-shifter');
var Base = require('component/grid/projection/base');
var Response = require('component/grid/model/response');
describe('projection ColumnShifter', function () {
it('update should run normal', function () {
var model = new ColumnShifter();
var originalData = new Base();
originalData.data = new Response({
columns: {
name: { name: 'hello', property: 'name' },
id: { id: '007', property: 'id' },
},
select: ['name', 'id'],
});
originalData.pipe(model);
expect(model.data.get('select')[0]).to.be.equal('column.skip.less');
expect(model.data.get('select')[3]).to.be.equal('column.skip.more');
});
it('thClick should run normal', function () {
var model = new ColumnShifter();
model.get = sinon.stub().returns(1);
sinon.spy(model, 'set');
model.thClick({}, {
column: { $metadata: { enabled: true } },
property: 'column.skip.less',
});
expect(model.set.calledWith({ 'column.skip': 0 })).to.be.true;
});
});
|
'use strict';
let TimeseriesShowController = function($scope, $controller, $timeout,
NpolarApiSecurity, NpolarTranslate,
npdcAppConfig,
Timeseries, TimeseriesModel, TimeseriesCitation, google, Sparkline) {
'ngInject';
let ctrl = this;
ctrl.authors = (t) => {
return t.authors.map(a => {
return { name: a['@id']};
});
};
// @todo NpolarLinkModel?
ctrl.collection_link = (links,hreflang='en') => {
return links.find(l => l.rel === 'collection' && l.hreflang === hreflang);
};
$controller("NpolarBaseController", {$scope: $scope});
$scope.resource = Timeseries;
let chartElement = Sparkline.getElement();
if (chartElement) {
chartElement.innerHTML = '';
}
$scope.show().$promise.then(timeseries => {
$scope.data = timeseries.data;
$scope.data_not_null = timeseries.data.filter(t => t.value !== undefined);
// Create facet-style links with counts to timeseries with all of the same keywords...
if (!$scope.keywords && timeseries.keywords && timeseries.keywords.length > 0) {
$scope.keywords = {};
let keywords = TimeseriesModel.keywords(timeseries);
['en', 'no'].forEach(l => {
let k = keywords[l];
let href = $scope.resource.uiBase+`?filter-keywords.@value=${ k.join(',') }`;
let link = { keywords: keywords[l], count: 0, href };
Timeseries.feed({"filter-keywords.@value": k.join(','), facets: 'keywords,species,locations.placename', limit: 0}).$promise.then((r) => {
link.count = r.feed.opensearch.totalResults; // All keywords
// Count for all keywords + species
if (timeseries.species) {
let f = r.feed.facets.find(f => f.hasOwnProperty('species'));
if (f && f.species) {
let c = f.species.find(f => f.term === timeseries.species);
link.count_keywords_and_species = c.count;
}
}
// Count for first all keywords + placename[0]
if (timeseries.locations && timeseries.locations.length > 0) {
let f = r.feed.facets.find(f => f.hasOwnProperty('locations.placename'));
if (f && f['locations.placename']) {
let c = f['locations.placename'].find(f => f.term === timeseries.locations[0].placename);
link.count_keywords_and_placename = c.count;
}
}
$scope.keywords[l] = link;
}, (e) => {
$scope.keywords[l] = link;
});
});
}
$scope.citation = (t) => {
if (!t) { return; }
return TimeseriesCitation.citation(timeseries);
};
// Create graph
if ($scope.data && $scope.data.length > 0) {
$timeout(function(){
$scope.sparkline = true;
let sparkline = timeseries.data.map(d => [d.value]);
google.setOnLoadCallback(Sparkline.draw(sparkline));
});
}
// Count number of timeseries belonging to the same collection
if (timeseries.links && timeseries.links.length > 0) {
['en', 'nb'].forEach(l => {
if (!$scope.collection || !$scope.collection[l]) {
let link = ctrl.collection_link(timeseries.links, l);
if (link && link.href) {
let query = {"filter-links.href": link.href, limit: 0 };
Timeseries.feed(query).$promise.then(r => {
if (!$scope.collection) {
$scope.collection = {};
}
$scope.collection[l] = { href: $scope.resource.uiBase+`?filter-links.href=${link.href}`,
title: link.title,
count: r.feed.opensearch.totalResults
};
});
}
}
});
}
});
};
module.exports = TimeseriesShowController;
|
var should = require('should');
var npg = require('../core/npg').npg;
var config = require('./_test_config_npg');
var request = ({body: {phrase: "111"}});
describe('NPG w/ config', function () {
it('should using fixed key', function () {
config.useFixedKey.should.be.ok;
});
it('should return correct answer', function () {
npg("111",config.key1,config.key2).should.eql({ md5: '747207ac', b64: '!QWOwMWY3AjM3QzN' })
})
});
|
/**
* LICENSE : MIT
*/
"use strict";
(function (mod) {
if (typeof exports == "object" && typeof module == "object") {
mod(require("codemirror"));
}
else if (typeof define == "function" && define.amd) {
define(["codemirror"], mod);
}
else {
mod(CodeMirror);
}
})(function (CodeMirror) {
"use strict";
CodeMirror.commands.scrollSelectionToCenter = function (cm) {
if (cm.getOption("disableInput")) {
return CodeMirror.Pass;
}
var cursor = cm.getCursor('anchor');
var top = cm.charCoords({line: cursor.line, ch: 0}, "local").top;
var halfWindowHeight = cm.getWrapperElement().offsetHeight / 2;
var scrollTo = Math.round((top - halfWindowHeight));
cm.scrollTo(null, scrollTo);
};
CodeMirror.defineOption("typewriterScrolling", false, function (cm, val, old) {
if (old && old != CodeMirror.Init) {
cm.off("changes", onChanges);
}
if (val) {
cm.on("changes", onChanges);
}
});
function onChanges(cm, changes) {
if (cm.getSelection().length !== 0) {
return;
}
for (var i = 0, len = changes.length; i < len; i++) {
var each = changes[i];
if (each.origin === '+input' || each.origin === '+delete') {
cm.execCommand("scrollSelectionToCenter");
return;
}
}
}
});
|
/**
* @name Evemit
* @description Minimal and fast JavaScript event emitter for Node.js and front-end.
* @author Nicolas Tallefourtane <dev@nicolab.net>
* @link https://github.com/Nicolab/evemit
* @license MIT https://github.com/Nicolab/evemit/blob/master/LICENSE
*/
;(function() {
'use strict';
/**
* Evemit
*
* @constructor
* @api public
*/
function Evemit() {
this.events = {};
}
/**
* Register a new event listener for a given event.
*
* @param {string} event Event name.
* @param {function} fn Callback function (listener).
* @param {*} [context] Context for function execution.
* @return {Evemit} Current instance.
* @api public
*/
Evemit.prototype.on = function(event, fn, context) {
if (!this.events[event]) {
this.events[event] = [];
}
if(context) {
fn._E_ctx = context;
}
this.events[event].push(fn);
return this;
};
/**
* Add an event listener that's only called once.
*
* @param {string} event Event name.
* @param {function} fn Callback function (listener).
* @param {*} [context] Context for function execution.
* @return {Evemit} Current instance.
* @api public
*/
Evemit.prototype.once = function(event, fn, context) {
fn._E_once = true;
return this.on(event, fn, context);
};
/**
* Emit an event to all registered event listeners.
*
* @param {string} event Event name.
* @param {*} [...arg] One or more arguments to pass to the listeners.
* @return {bool} Indication, `true` if at least one listener was executed,
* otherwise returns `false`.
* @api public
*/
Evemit.prototype.emit = function(event, arg1, arg2, arg3, arg4) {
var fn, evs, args, aLn;
if(!this.events[event]) {
return false;
}
args = Array.prototype.slice.call(arguments, 1);
aLn = args.length;
evs = this.events[event];
for(var i = 0, ln = evs.length; i < ln; i++) {
fn = evs[i];
if (fn._E_once) {
this.off(event, fn);
}
// Function.apply() is a bit slower, so try to do without
switch (aLn) {
case 0:
fn.call(fn._E_ctx);
break;
case 1:
fn.call(fn._E_ctx, arg1);
break;
case 2:
fn.call(fn._E_ctx, arg1, arg2);
break;
case 3:
fn.call(fn._E_ctx, arg1, arg2, arg3);
break;
case 4:
fn.call(fn._E_ctx, arg1, arg2, arg3, arg4);
break;
default:
fn.apply(fn._E_ctx, args);
}
}
return true;
};
/**
* Remove event listeners.
*
* @param {string} event The event to remove.
* @param {function} fn The listener that we need to find.
* @return {Evemit} Current instance.
* @api public
*/
Evemit.prototype.off = function(event, fn) {
if (!this.events[event]) {
return this;
}
for (var i = 0, ln = this.events[event].length; i < ln; i++) {
if (this.events[event][i] === fn) {
this.events[event][i] = null;
delete this.events[event][i];
}
}
// re-index
this.events[event] = this.events[event].filter(function(ltns) {
return typeof ltns !== 'undefined';
});
return this;
};
/**
* Get a list of assigned event listeners.
*
* @param {string} [event] The events that should be listed.
* If not provided, all listeners are returned.
* Use the property `Evemit.events` if you want to get an object like
* ```
* {event1: [array of listeners], event2: [array of listeners], ...}
* ```
*
* @return {array}
* @api public
*/
Evemit.prototype.listeners = function(event) {
var evs, ltns;
if(event) {
return this.events[event] || [];
}
evs = this.events;
ltns = [];
for(var ev in evs) {
ltns = ltns.concat(evs[ev].valueOf());
}
return ltns;
};
/**
* Expose Evemit
* @type {Evemit}
*/
if(typeof module !== 'undefined' && module.exports) {
module.exports = Evemit;
} else {
window.Evemit = Evemit;
}
})();
|
/**
* Checks if a given DOM property of an element has the expected value. For all the available DOM element properties, consult the [Element doc at MDN](https://developer.mozilla.org/en-US/docs/Web/API/element).
*
* @example
* this.demoTest = function (browser) {
* browser.expect.element('body').to.have.property('className').equals('test-class');
* browser.expect.element('body').to.have.property('className').matches(/^something\ else/);
* browser.expect.element('body').to.not.have.property('classList').equals('test-class');
* browser.expect.element('body').to.have.property('classList').deep.equal(['class-one', 'class-two']);
* browser.expect.element('body').to.have.property('classList').contain('class-two');
* };
*
* @method property
* @param {string} property The property name
* @param {string} [message] Optional log message to display in the output. If missing, one is displayed by default.
* @display .property(name)
* @api expect.element
*/
const BaseAssertion = require('./_element-assertion.js');
class PropertyAssertion extends BaseAssertion {
static get assertionType() {
return BaseAssertion.AssertionType.METHOD;
}
init(property, msg) {
super.init();
this.flag('attributeFlag', true);
this.property = property;
this.hasCustomMessage = typeof msg != 'undefined';
this.message = msg || 'Expected element <%s> to ' + (this.negate ? 'not have' : 'have') + ' dom property "' + property + '"';
this.start();
}
executeCommand() {
return this.executeProtocolAction('getElementProperty', [this.property]).then(result => {
if (!this.transport.isResultSuccess(result) || result.value === null) {
throw result;
}
return result;
}).catch(result => {
this.propertyNotFound();
return false;
});
}
onResultSuccess() {
if (this.retries > 0 && this.negate) {
return;
}
if (!this.hasCondition()) {
this.passed = !this.negate;
this.expected = this.negate ? 'not found' : 'found';
this.actual = 'found';
}
this.addExpectedInMessagePart();
}
propertyNotFound() {
this.processFlags();
this.passed = this.hasCondition() ? false : this.negate;
if (!this.passed && this.shouldRetry()) {
this.scheduleRetry();
} else {
this.addExpectedInMessagePart();
if (!this.hasCondition()) {
//this.expected = this.negate ? 'not found' : 'found';
this.actual = 'not found';
}
if (!this.negate) {
this.messageParts.push(' - property was not found');
}
this.done();
}
}
onResultFailed() {
this.passed = false;
}
}
module.exports = PropertyAssertion;
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.