code
stringlengths 2
1.05M
| repo_name
stringlengths 5
114
| path
stringlengths 4
991
| language
stringclasses 1
value | license
stringclasses 15
values | size
int32 2
1.05M
|
|---|---|---|---|---|---|
/**
* Created by shiyunjie on 16/12/29.
*/
/**
* Created by shiyunjie on 16/12/28.
*/
import React, {
PropTypes,
Component } from 'react';
import {
StyleSheet,
Text,
View,
PixelRatio,
Image,
ActivityIndicator,
} from 'react-native';
import constants from '../constants/constant';
//import Icon from 'react-native-vector-icons/Ionicons';
import image_logo from '../images/horse.png'
/**
* types: ['CircleFlip', 'Bounce', 'Wave', 'WanderingCubes', 'Pulse',
* 'ChasingDots', 'ThreeBounce', 'Circle', '9CubeGrid', 'WordPress',
* 'FadingCircle', 'FadingCircleAlt', 'Arc', 'ArcAlt'],
*/
//let Spinner = require('react-native-spinkit');
export default class ListItemView extends Component {
// 构造
constructor(props) {
super(props);
// 初始状态
this.state = {
show: this.props.show,
hasCheckBox: this.props.hasCheckBox,
degree: props.degree,
};
}
static propTypes = {
...View.propTypes, // 包含默认的View的属性
name: PropTypes.string.isRequired,
size: PropTypes.number.isRequired,
color: PropTypes.string,
title: PropTypes.string.isRequired,
isRefresh: PropTypes.bool,
isFoot:PropTypes.bool,
degree: PropTypes.number.isRequired,
}
static defaultProps = {
isRefresh: false,
color: constants.UIInActiveColor,
degree: 0,
isFoot:false,
}
componentWillReceiveProps(nextProps) {
let degree = nextProps.degree
if (degree != this.state.degree) {
this.setState({
degree,
})
}
}
render() {
/* return (
!this.props.isRefresh ?
<View
style={styles.HeaderView}>
<View style={{transform: [{rotate: `${this.state.degree}deg`}]}}>
<Icon name={this.props.name} // 图标
size={this.props.size}
color={this.props.color}/>
</View>
<Text
style={{marginLeft:5,color:constants.PointColor}}
>{this.props.title}</Text>
</View> :
<View
style={styles.HeaderView}>
<ActivityIndicator
animating={true}
color={this.props.color}
size={'large'}/>
<Text
style={{marginLeft:5,color:constants.PointColor}}
>{this.props.title}</Text>
</View>
)*/
//console.log(`this.state.degree:`, this.state.degree)
let scale = this.state.degree / 100
//console.log(`scale:`, scale)
return (
!this.props.isRefresh ?
<View
style={[styles.HeaderView,this.props.isFoot?{justifyContent:'flex-start',}:{}]}>
<Image source={image_logo} style={{width:25*scale,height:25*scale}}/>
<Text
style={{color:constants.PointColor,fontSize:constants.DefaultFontSize}}
>{this.props.title}</Text>
</View> :
<View
style={[styles.HeaderView,]}>
<ActivityIndicator
animating={true}
color={this.props.color}
size={'small'}/>
<Text
style={{color:constants.PointColor,fontSize:constants.DefaultFontSize}}
>{this.props.title}</Text>
</View>
)
}
}
var styles = StyleSheet.create({
spinner: {
marginBottom: 3,
},
/* HeaderView: {
flex:1,
flexDirection: 'row',
height: constants.pullDownStayDistance,
justifyContent: 'center',
alignItems: 'center',
backgroundColor: 'transparent',
},*/
HeaderView: {
flex:1,
height: constants.pullDownStayDistance,
alignItems: 'center',
backgroundColor: 'transparent',
flexDirection:'column',
justifyContent:'flex-end',
},
});
|
shiyunjie/scs
|
app/components/listViewheaderView.js
|
JavaScript
|
mit
| 4,073
|
'use strict';
angular.module('timerApp')
.controller('MainCtrl', function($scope, $timeout, $navigate, events, dataStore, Timer) {
$scope.timer = dataStore.get('timer');
$scope.intervalTimer = dataStore.get('intervalTimer');
$scope.repeat = dataStore.get('repeat');
$scope.useIntervalTimer = dataStore.get('useIntervalTimer');
$scope.timeVisual = new Date($scope.timer);
$scope.$watch('timer', function(time) {
$scope.timeVisual = new Date($scope.timer);
});
$scope.$watch('useIntervalTimer', function(val) {
dataStore.save('useIntervalTimer', val);
});
var timer1, timer2, timer1Promise, timer2Promise;
$scope.isRunning = false;
$scope.isTimerRunning = false;
//default arrow intervals
$scope.hstep = 1;
$scope.mstep = 1;
$scope.sstep = 1;
$scope.showTimerModal = function() {
$navigate.go('/Timer', 'modal');
};
$scope.showIntervalModal = function() {
$navigate.go('/IntervalTimer', 'modal');
};
$scope.start = function() {
if (!$scope.isRunning) {
events.start();
dataStore.save('repeat', $scope.repeat);
}
dataStore.save('timer', $scope.timer);
dataStore.save('intervalTimer', $scope.intervalTimer);
$scope.isRunning = true;
$scope.isTimerRunning = true;
timer1 = new Timer({
timestamp: $scope.timer,
interval: 1000
});
timer1.start(function(time) {
events.intervalTick();
$scope.timer = time;
}).then(function() {
events.intervalEnd();
$scope.timer = dataStore.get('timer');
if ($scope.repeat > 1) {
$scope.repeat--;
if ($scope.useIntervalTimer) {
timer2 = new Timer({
timestamp: $scope.intervalTimer,
interval: 1000
});
timer2.start(function(time) {
$scope.isTimerRunning = false;
events.intervalTick();
$scope.intervalTimer = time;
}).then(function() {
events.intervalEnd();
$scope.intervalTimer = dataStore.get('intervalTimer');
$scope.start();
});
} else {
$scope.start();
}
} else {
$scope.isRunning = false;
$scope.stop();
}
});
};
$scope.stop = function() {
$scope.isTimerRunning = false;
if ($scope.isRunning) {
//the user interupted the timer
events.cancel();
} else {
events.complete();
}
$scope.isRunning = false;
timer1.cancel();
if (timer2) {
timer2.cancel();
}
$scope.timer = dataStore.get('timer');
$scope.intervalTimer = dataStore.get('intervalTimer');
$scope.repeat = dataStore.get('repeat');
};
$scope.settings = function() {
$navigate.go('/Settings', 'slide', true);
};
$scope.info = function() {
$navigate.go('/Info');
};
});
|
lpaulger/timerApp
|
app/scripts/controllers/main.js
|
JavaScript
|
mit
| 3,012
|
$.Redactor.prototype.textexpander = function()
{
return {
init: function()
{
if (!this.opts.textexpander) return;
this.$editor.on('keyup.redactor-limiter', $.proxy(function(e)
{
var key = e.which;
if (key == this.keyCode.SPACE)
{
var current = this.textexpander.getCurrent();
var cloned = $(current).clone();
var $div = $('<div>');
$div.html(cloned);
var text = $div.html();
$div.remove();
var len = this.opts.textexpander.length;
var replaced = 0;
for (var i = 0; i < len; i++)
{
var re = new RegExp(this.opts.textexpander[i][0]);
if (text.search(re) != -1)
{
replaced++;
text = text.replace(re, this.opts.textexpander[i][1]);
$div = $('<div>');
$div.html(text);
$div.append(this.selection.getMarker());
var html = $div.html().replace(/ /, '');
$(current).replaceWith(html);
$div.remove();
}
}
if (replaced !== 0)
{
this.selection.restore();
}
}
}, this));
},
getCurrent: function()
{
var selection
if (window.getSelection) selection = window.getSelection();
else if (document.selection && document.selection.type != "Control") selection = document.selection;
if (this.utils.browser('mozilla'))
{
return selection.anchorNode.previousSibling;
}
else
{
return selection.anchorNode;
}
}
};
};
|
CNDLS/generic-game-host
|
static/js/redactor-plugins/textexpander.js
|
JavaScript
|
mit
| 1,441
|
module.exports={A:{A:{"2":"L H G E A B jB"},B:{"1":"BB","2":"C D d K I N J"},C:{"1":"0 1 6 7 8 9 k l m n o M q r s t u v w x y z AB CB DB EB O GB HB","2":"2 3 5 gB IB F L H G E A B C D d K I N J P Q R S T U V W X Y Z a b c e f g aB ZB","194":"h i j"},D:{"1":"0 1 6 7 8 9 r s t u v w x y z AB CB DB EB O GB HB TB PB NB mB OB LB BB QB RB","2":"2 3 5 F L H G E A B C D d K I N J P Q R S T U V W X Y Z a b c e f g h i j k l m n o M q"},E:{"2":"2 F L H G E SB KB UB VB WB XB","16":"A","33":"4 B C D YB p bB"},F:{"1":"0 1 e f g h i j k l m n o M q r s t u v w x y z","2":"3 4 5 E B C K I N J P Q R S T U V W X Y Z a b c cB dB eB fB p FB hB"},G:{"1":"D qB rB sB tB uB vB","2":"G KB iB JB kB lB MB nB oB pB"},H:{"2":"wB"},I:{"1":"O","2":"IB F xB yB zB 0B JB 1B 2B"},J:{"2":"H A"},K:{"1":"M","2":"4 A B C p FB"},L:{"1":"LB"},M:{"1":"O"},N:{"2":"A B"},O:{"1":"3B"},P:{"1":"4B 5B 6B 7B 8B","2":"F"},Q:{"2":"9B"},R:{"1":"AC"},S:{"1":"BC"}},B:4,C:"CSS text-orientation"};
|
brett-harvey/Smart-Contracts
|
Ethereum-based-Roll4Win/node_modules/caniuse-lite/data/features/css-text-orientation.js
|
JavaScript
|
mit
| 959
|
"use strict";
var inherits = require('util').inherits;
var ValueValidator = require('./core/value_validator');
var Rx = function (re) {
ValueValidator.call(this);
this.re = re;
};
inherits(Rx, ValueValidator);
Rx.prototype.code = 'rx';
Rx.prototype.getExpectedStr = function () {
return ['matching regexp ', this.re].join('');
};
Rx.prototype.isValueValid = function (ctx) {
return this.re.test(ctx.value);
};
Rx.rx = function (re) {
return new Rx(re);
};
Rx.getShort = function (corrector) {
return Rx.rx;
};
module.exports = Rx;
|
dimsmol/valid
|
lib/validators/rx.js
|
JavaScript
|
mit
| 546
|
version https://git-lfs.github.com/spec/v1
oid sha256:5ecdabd85e0fb24a5a6da34f727b83267596ac21ed1994c7f06a8356e759bfb9
size 10721
|
yogeshsaroya/new-cdnjs
|
ajax/libs/rivets/0.5.0/rivets.min.js
|
JavaScript
|
mit
| 130
|
import React from 'react';
import { shallow, mount } from 'enzyme';
import TabListComponent from '../TabListComponent';
test('<TabListComponent /> should exist', () => {
const tabList = shallow((
<TabListComponent>
<span>Foo</span>
</TabListComponent>
));
expect(tabList).toBeDefined();
});
test('<TabListComponent /> should render children', () => {
const tabList = mount((
<TabListComponent>
<span id="content">Foo</span>
</TabListComponent>
));
expect(tabList.find('#content')).toBeTruthy();
});
test('<TabListComponent /> should have the correct aria attributes', () => {
const tabList = shallow((
<TabListComponent>
<span>Foo</span>
</TabListComponent>
));
expect(tabList.prop('role')).toEqual('tablist');
});
test('<TabListComponent /> should be able to set any className', () => {
const tabList = shallow((
<TabListComponent className="foo">
<span>Foo</span>
</TabListComponent>
));
expect(tabList.hasClass('foo')).toBe(true);
});
test('<TabListComponent /> should be set aria-orientation when vertical', () => {
const tabList = shallow((
<TabListComponent verticalOrientation><span>Foo</span></TabListComponent>
));
expect(tabList.prop('aria-orientation')).toBe('vertical');
});
|
marcuslindfeldt/react-web-tabs
|
src/__tests__/TabListComponent.test.js
|
JavaScript
|
mit
| 1,288
|
import React from 'react';
import PropTypes from 'prop-types';
const ExplainConstraintHyphen = props => (
<p className="card-text">
<code>{props.constraint.constraint}</code> is a <strong>hyphen</strong> constraint. It means that it will match{' '}
<strong>several versions</strong>.
</p>
);
ExplainConstraintHyphen.propTypes = {
className: PropTypes.string,
constraint: PropTypes.object.isRequired,
};
export default ExplainConstraintHyphen;
|
jubianchi/semver-check
|
src/components/ExplainConstraintHyphen.js
|
JavaScript
|
mit
| 478
|
import { makeExecutableSchema } from 'graphql-tools';
import { RoomSchema, MessageSchema, UserSchema } from './schemas';
const typeDefs = [`
${UserSchema.types}
${MessageSchema.types()}
${RoomSchema.types()}
type Query {
${UserSchema.queries}
${MessageSchema.queries}
${RoomSchema.queries}
}
type Mutation {
${UserSchema.mutations}
${MessageSchema.mutations}
}
type Subscription {
${MessageSchema.subscriptions}
${RoomSchema.subscriptions}
}
schema {
query: Query
mutation: Mutation
subscription: Subscription
}
`];
const resolvers = {
Query: {
...UserSchema.resolvers.Query,
...MessageSchema.resolvers.Query,
...RoomSchema.resolvers.Query,
},
Mutation: {
...UserSchema.resolvers.Mutation,
...MessageSchema.resolvers.Mutation,
},
Subscription: {
...MessageSchema.resolvers.Subscription,
...RoomSchema.resolvers.Subscription,
},
};
const schema = makeExecutableSchema({
typeDefs,
resolvers,
logger: { log: (err) => console.log(err) },
allowUndefinedInResolve: true, // set to false for debugging
resolverValidationOptions: {
requireResolversForArgs: false, // set to true for debugging
requireResolversForNonScalar: false, // set to true for debugging
},
});
export default schema;
|
adamjking3/react-redux-apollo-starter
|
server/api/schema.js
|
JavaScript
|
mit
| 1,312
|
// @flow
import renderer from 'react-test-renderer'
import React from 'react'
import Modal from '../modal'
describe('Component > Modal', () => {
it('renders correctly', () => {
const onRequestCloseFn = jest.fn()
renderer.create(
<Modal onRequestClose={onRequestCloseFn}>Modal content</Modal>
)
expect(onRequestCloseFn).not.toBeCalled()
})
})
|
conveyal/scenario-editor
|
lib/components/__tests__/modal.js
|
JavaScript
|
mit
| 371
|
const validator = require('../isUUID');
describe('isUUID', () => {
it('fails when not a string', async () => {
expect(validator(true)).toEqual(false);
});
it('fails when invalid', async () => {
expect(validator('xxxA987FBC9-4BED-3078-CF07-9141BA07C9F3')).toEqual(false);
});
it('fails when invalid v3', async () => {
expect(validator('987FBC97-4BED-5078-AF07-9141BA07C9F3', {version: 3})).toEqual(false);
});
it('fails when invalid v4', async () => {
expect(validator('987FBC97-4BED-5078-AF07-9141BA07C9F3', {version: 4})).toEqual(false);
});
it('fails when invalid v5', async () => {
expect(validator('713ae7e3-cb32-45f9-adcb-7c4fa86b90c1', {version: 5})).toEqual(false);
});
it('passes when valid', async () => {
expect(validator('A987FBC9-4BED-3078-CF07-9141BA07C9F3')).toEqual(true);
});
it('passes when valid v3', async () => {
expect(validator('A987FBC9-4BED-3078-CF07-9141BA07C9F3', {version: 3})).toEqual(true);
});
it('passes when valid v4', async () => {
expect(validator('713ae7e3-cb32-45f9-adcb-7c4fa86b90c1', {version: 4})).toEqual(true);
});
it('passes when valid v5', async () => {
expect(validator('987FBC97-4BED-5078-AF07-9141BA07C9F3', {version: 5})).toEqual(true);
});
});
|
xpepermint/approvedjs
|
src/validators/__tests__/isUUID.js
|
JavaScript
|
mit
| 1,275
|
import dotenv from 'dotenv'
import 'fetch-everywhere'
import test from 'ava'
import Deskbookers from '../src'
dotenv.load()
const {
LOGIN_EMAIL,
LOGIN_PASSWORD,
API_FEATURE_HOST,
API_FEATURE_PATH,
API_HTTPS,
API_HOST
} = process.env
async function client (login = false) {
const deskbookers = new Deskbookers({
https: API_HTTPS === 'true',
host: API_HOST,
sources: {
features: {
host: API_FEATURE_HOST,
path: API_FEATURE_PATH
}
}
})
if (login) {
await deskbookers.account.login(LOGIN_EMAIL, LOGIN_PASSWORD)
}
return deskbookers
}
test('list features', async t => {
// Prepare API
const deskbookers = await client(true)
t.truthy(deskbookers.session)
const data = await deskbookers.features.list()
t.truthy(data)
})
test('list features by type', async t => {
// Prepare API
const deskbookers = await client(true)
t.truthy(deskbookers.session)
const data = await deskbookers.features.list({type: 'booking'})
t.truthy(data)
})
test('list features with country', async t => {
// Prepare API
const deskbookers = await client(true)
t.truthy(deskbookers.session)
const data = await deskbookers.features.list({country: 'Hyrule'})
t.truthy(data)
})
test('list venue features', async t => {
// Prepare API
const deskbookers = await client(true)
t.truthy(deskbookers.session)
const data = await deskbookers.features.listByVenue(1)
t.truthy(data)
})
test.before('create new feature', async t => {
// Prepare API
const deskbookers = await client(true)
t.truthy(deskbookers.session)
const data = await deskbookers.features.create(
{ name: 'testName', description: 'teste description', type: 'venue' }
)
t.truthy(data)
})
test('update feature', async t => {
// Prepare API
const deskbookers = await client(true)
t.truthy(deskbookers.session)
const data = await deskbookers.features.update(
'testName',
{ name: 'testName', description: 'teste description 2', type: 'venue2', parentId: null }
)
t.truthy(data)
})
test.after('delete feature', async t => {
// Prepare API
const deskbookers = await client(true)
t.truthy(deskbookers.session)
const data = await deskbookers.features.delete('testName')
t.truthy(data)
})
test('updateFeatureByVenue feature', async t => {
// Prepare API
const deskbookers = await client(true)
t.truthy(deskbookers.session)
let start = new Date().setDate(new Date().getDate() - 20)
let end = null
const data = await deskbookers.features.updateFeatureByVenue(
2,
'bookingTool',
{
enabled: true,
start,
end
}
)
t.truthy(data)
})
test('check feature is enabled for venue', async t => {
// Prepare API
const deskbookers = await client(true)
t.truthy(deskbookers.session)
const data = await deskbookers.features.checkFeatureByVenue(
2, 'bookingTool'
)
t.truthy(data)
})
|
deskbookers/sdk-javascript
|
test/features.js
|
JavaScript
|
mit
| 2,916
|
define([], function() {
Path.map("#!/signup").to(function(){
}).enter(function() {
require([
'tpl!template/signup.html',
'alertify'
], function(tpl, alertify) {
$('#main').empty();
$('#main').append($(tpl.apply()));
$('header').hide();
$('footer').hide();
$('.js-close').on('click', function(){
$('#container-signup-error').addClass('hidden');
$('#container-signup-success').addClass('hidden');
})
$(document).delegate('.js-input-phone', 'keyup', function(e) {
var $target = $(e.target),
number = $target.val().replace('(', '').replace(')', '').replace(' ', '').replace('-', ''),
newNumber;
if(e.keyCode != 8 && e.keyCode != 46){
if(number.length == 3){
newNumber = number.replace(/(\d{3})/, "($1)");
$('.js-input-phone').val(newNumber);
}else if(number.length == 6){
newNumber = number.replace(/(\d{3})(\d{3})/, "($1) $2");
$('.js-input-phone').val(newNumber);
}else if(number.length == 10){
newNumber = number.replace(/(\d{3})(\d{3})(\d{4})/, "($1) $2-$3");
$('.js-input-phone').val(newNumber);
}
}
});
$('#signup').on('submit', function(e) {
var email = $('#email').val(),
password = $('#password').val(),
name = $('#name').val(),
phone,
xhr;
if ($('#phone').is(':visible')) {
phone = $('#phone').val().replace('(', '').replace(')', '').replace(' ', '').replace('-', '');
}else{
phone = $('#phone-alt').val().replace('(', '').replace(')', '').replace(' ', '').replace('-', '');
}
xhr = $.ajax({
url: 'api/index.php/signup',
type: 'POST',
data: JSON.stringify({
email: email,
password: password,
name: name,
phone: phone,
})
});
xhr
.done(function(response) {
alertify.success(response.statusText);
window.location.hash = '#!/home';
}).fail(function(jqXHR, status, error) {
var response = JSON.parse(jqXHR.responseText);
$('#container-signup-error').removeClass('hidden');
$('#signup-error').text(response.statusText);
})
.always(function(response) {
});
e.preventDefault();
});
});
}).exit(function() {
// Exit from route
$('#main').off().empty();
$('header').show();
$('footer').show();
});
});
|
jakekh/Fat-Cloud
|
js/app/routes/signup.js
|
JavaScript
|
mit
| 2,323
|
import { Class } from 'meteor/jagi:astronomy';
import { Mongo } from 'meteor/mongo';
import { UserSchema as User } from './user.js';
import { Color, _colors } from './color.js';
import { AccessControl as acl, TrustLevel as tl } from './access_control.js';
import { Lib as libWidget } from 'mmks_widget';
// import { Lib as libBook } from 'mmks_book';
Meteor.users.attachSchema(User);
export const Users = Meteor.users;
export const UserSchema = User;
export const Colors = Color;
export const _Colors = _colors;
export const AccessControl = acl;
export const TrustLevel = tl;
let { astroWidget, mongoWidget } = libWidget.new( Mongo, Class );
export const Widgets = astroWidget;
export const _Widgets = mongoWidget;
// let { astroBook, mongoBook } = libBook.new( Mongo, Class );
// export const Books = astroBook;
// export const _Books = mongoBook;
export const Posts = new Mongo.Collection('posts');
export const Comments = new Mongo.Collection('comments');
|
warehouseman/meteor-mantra-kickstarter
|
lib/collections.js
|
JavaScript
|
mit
| 968
|
Package.describe({
name: 'tomsp:expose-schema',
version: '0.0.1',
// Brief, one-line summary of the package.
summary: 'stores the schema into a separate collection',
// URL to the Git repository containing the source code for this package.
git: '',
// By default, Meteor will default to using README.md for documentation.
// To avoid submitting documentation, set this field to null.
documentation: 'README.md'
});
Package.onUse(function(api) {
api.versionsFrom('1.2.0.2');
api.use('ecmascript');
api.use('mongo');
api.use('underscore');
api.use('dburles:mongo-collection-instances@0.3.4');
api.addFiles('expose-schema.js');
api.export('Exposee', "client");
});
Package.onTest(function(api) {
api.use('ecmascript');
api.use('tinytest');
api.use('tomsp:expose-schema');
api.addFiles('expose-schema-tests.js');
});
|
thomasspiesser/expose-schema-testapp
|
packages/expose-schema/package.js
|
JavaScript
|
mit
| 856
|
define([
"app",
"comm/solr"
],
// Map dependencies from above array.
function (app, solr) {
"use strict";
var SuggestCollection = Backbone.Collection.extend({
url: solr.suggest,
sync: function(method, model, options) {
var success = options.success;
options.dataType = "jsonp";
options.jsonp = "json.wrf";
options.data = solr.buildQueryParams(this.options);
options.traditional = true;
options.success = function (data) {
success(data.spellcheck.suggestions[1].suggestion);
};
return Backbone.sync(method, model, options);
}
});
return SuggestCollection;
});
|
arielschiavoni/wast
|
src/client/js/collections/suggest.js
|
JavaScript
|
mit
| 683
|
(function() {
'use strict';
angular.module('kct.common')
.directive('ngShowAuth', ['KctAuth', '$timeout', ngShowAuth])
.directive('ngHideAuth', ['KctAuth', '$timeout', ngHideAuth])
;
function ngShowAuth(KctAuth, $timeout) {
return {
restrict: 'A',
link: function(scope, el) {
el.addClass('ng-cloak'); // hide until we process it
function update() {
// sometimes if ngCloak exists on same element, they argue, so make sure that
// this one always runs last for reliability
$timeout(function () {
el.toggleClass('ng-cloak', !KctAuth.$getAuth());
}, 0);
}
KctAuth.$onAuth(update);
update();
}
};
}
function ngHideAuth(KctAuth, $timeout) {
return {
restrict: 'A',
link: function(scope, el) {
el.addClass('ng-cloak'); // hide until we process it
function update() {
// sometimes if ngCloak exists on same element, they argue, so make sure that
// this one always runs last for reliability
$timeout(function () {
el.toggleClass('ng-cloak', !!KctAuth.$getAuth());
}, 0);
}
KctAuth.$onAuth(update);
update();
}
};
}
})();
|
Grobim/kspCoolTools
|
app/kctCommon/kctCommon.directives.js
|
JavaScript
|
mit
| 1,279
|
/**
* @author Slayvin / http://slayvin.net
*/
THREE.Mirror = function ( renderer, camera, options ) {
THREE.Object3D.call( this );
this.name = 'mirror_' + this.id;
options = options || {};
this.matrixNeedsUpdate = true;
var width = options.textureWidth !== undefined ? options.textureWidth : 512;
var height = options.textureHeight !== undefined ? options.textureHeight : 512;
this.clipBias = options.clipBias !== undefined ? options.clipBias : 0.0;
var mirrorColor = options.color !== undefined ? new THREE.Color( options.color ) : new THREE.Color( 0x7F7F7F );
this.renderer = renderer;
this.mirrorPlane = new THREE.Plane();
this.normal = new THREE.Vector3( 0, 0, 1 );
this.mirrorWorldPosition = new THREE.Vector3();
this.cameraWorldPosition = new THREE.Vector3();
this.rotationMatrix = new THREE.Matrix4();
this.lookAtPosition = new THREE.Vector3( 0, 0, - 1 );
this.clipPlane = new THREE.Vector4();
// For debug only, show the normal and plane of the mirror
var debugMode = options.debugMode !== undefined ? options.debugMode : false;
if ( debugMode ) {
var arrow = new THREE.ArrowHelper( new THREE.Vector3( 0, 0, 1 ), new THREE.Vector3( 0, 0, 0 ), 10, 0xffff80 );
var planeGeometry = new THREE.Geometry();
planeGeometry.vertices.push( new THREE.Vector3( - 10, - 10, 0 ) );
planeGeometry.vertices.push( new THREE.Vector3( 10, - 10, 0 ) );
planeGeometry.vertices.push( new THREE.Vector3( 10, 10, 0 ) );
planeGeometry.vertices.push( new THREE.Vector3( - 10, 10, 0 ) );
planeGeometry.vertices.push( planeGeometry.vertices[ 0 ] );
var plane = new THREE.Line( planeGeometry, new THREE.LineBasicMaterial( { color: 0xffff80 } ) );
this.add( arrow );
this.add( plane );
}
if ( camera instanceof THREE.PerspectiveCamera ) {
this.camera = camera;
} else {
this.camera = new THREE.PerspectiveCamera();
console.log( this.name + ': camera is not a Perspective Camera!' );
}
this.textureMatrix = new THREE.Matrix4();
this.mirrorCamera = this.camera.clone();
this.mirrorCamera.matrixAutoUpdate = true;
var parameters = { minFilter: THREE.LinearFilter, magFilter: THREE.LinearFilter, format: THREE.RGBFormat, stencilBuffer: false };
this.renderTarget = new THREE.WebGLRenderTarget( width, height, parameters );
this.renderTarget2 = new THREE.WebGLRenderTarget( width, height, parameters );
var mirrorShader = {
uniforms: {
mirrorColor: { value: new THREE.Color( 0x7F7F7F ) },
mirrorSampler: { value: null },
textureMatrix: { value: new THREE.Matrix4() }
},
vertexShader: [
'uniform mat4 textureMatrix;',
'varying vec4 mirrorCoord;',
'void main() {',
' vec4 mvPosition = modelViewMatrix * vec4( position, 1.0 );',
' vec4 worldPosition = modelMatrix * vec4( position, 1.0 );',
' mirrorCoord = textureMatrix * worldPosition;',
' gl_Position = projectionMatrix * mvPosition;',
'}'
].join( '\n' ),
fragmentShader: [
'uniform vec3 mirrorColor;',
'uniform sampler2D mirrorSampler;',
'varying vec4 mirrorCoord;',
'float blendOverlay(float base, float blend) {',
' return( base < 0.5 ? ( 2.0 * base * blend ) : (1.0 - 2.0 * ( 1.0 - base ) * ( 1.0 - blend ) ) );',
'}',
'void main() {',
' vec4 color = texture2DProj(mirrorSampler, mirrorCoord);',
' color = vec4(blendOverlay(mirrorColor.r, color.r), blendOverlay(mirrorColor.g, color.g), blendOverlay(mirrorColor.b, color.b), 1.0);',
' gl_FragColor = color;',
'}'
].join( '\n' )
};
var mirrorUniforms = THREE.UniformsUtils.clone( mirrorShader.uniforms );
this.material = new THREE.ShaderMaterial( {
fragmentShader: mirrorShader.fragmentShader,
vertexShader: mirrorShader.vertexShader,
uniforms: mirrorUniforms
} );
this.material.uniforms.mirrorSampler.value = this.renderTarget.texture;
this.material.uniforms.mirrorColor.value = mirrorColor;
this.material.uniforms.textureMatrix.value = this.textureMatrix;
if ( ! THREE.Math.isPowerOfTwo( width ) || ! THREE.Math.isPowerOfTwo( height ) ) {
this.renderTarget.texture.generateMipmaps = false;
this.renderTarget2.texture.generateMipmaps = false;
}
this.updateTextureMatrix();
this.render();
};
THREE.Mirror.prototype = Object.create( THREE.Object3D.prototype );
THREE.Mirror.prototype.constructor = THREE.Mirror;
THREE.Mirror.prototype.renderWithMirror = function ( otherMirror ) {
// update the mirror matrix to mirror the current view
this.updateTextureMatrix();
this.matrixNeedsUpdate = false;
// set the camera of the other mirror so the mirrored view is the reference view
var tempCamera = otherMirror.camera;
otherMirror.camera = this.mirrorCamera;
// render the other mirror in temp texture
otherMirror.renderTemp();
otherMirror.material.uniforms.mirrorSampler.value = otherMirror.renderTarget2.texture;
// render the current mirror
this.render();
this.matrixNeedsUpdate = true;
// restore material and camera of other mirror
otherMirror.material.uniforms.mirrorSampler.value = otherMirror.renderTarget.texture;
otherMirror.camera = tempCamera;
// restore texture matrix of other mirror
otherMirror.updateTextureMatrix();
};
THREE.Mirror.prototype.updateTextureMatrix = function () {
this.updateMatrixWorld();
this.camera.updateMatrixWorld();
this.mirrorWorldPosition.setFromMatrixPosition( this.matrixWorld );
this.cameraWorldPosition.setFromMatrixPosition( this.camera.matrixWorld );
this.rotationMatrix.extractRotation( this.matrixWorld );
this.normal.set( 0, 0, 1 );
this.normal.applyMatrix4( this.rotationMatrix );
var view = this.mirrorWorldPosition.clone().sub( this.cameraWorldPosition );
view.reflect( this.normal ).negate();
view.add( this.mirrorWorldPosition );
this.rotationMatrix.extractRotation( this.camera.matrixWorld );
this.lookAtPosition.set( 0, 0, - 1 );
this.lookAtPosition.applyMatrix4( this.rotationMatrix );
this.lookAtPosition.add( this.cameraWorldPosition );
var target = this.mirrorWorldPosition.clone().sub( this.lookAtPosition );
target.reflect( this.normal ).negate();
target.add( this.mirrorWorldPosition );
this.up.set( 0, - 1, 0 );
this.up.applyMatrix4( this.rotationMatrix );
this.up.reflect( this.normal ).negate();
this.mirrorCamera.position.copy( view );
this.mirrorCamera.up = this.up;
this.mirrorCamera.lookAt( target );
this.mirrorCamera.updateProjectionMatrix();
this.mirrorCamera.updateMatrixWorld();
this.mirrorCamera.matrixWorldInverse.getInverse( this.mirrorCamera.matrixWorld );
// Update the texture matrix
this.textureMatrix.set(
0.5, 0.0, 0.0, 0.5,
0.0, 0.5, 0.0, 0.5,
0.0, 0.0, 0.5, 0.5,
0.0, 0.0, 0.0, 1.0
);
this.textureMatrix.multiply( this.mirrorCamera.projectionMatrix );
this.textureMatrix.multiply( this.mirrorCamera.matrixWorldInverse );
// Now update projection matrix with new clip plane, implementing code from: http://www.terathon.com/code/oblique.html
// Paper explaining this technique: http://www.terathon.com/lengyel/Lengyel-Oblique.pdf
this.mirrorPlane.setFromNormalAndCoplanarPoint( this.normal, this.mirrorWorldPosition );
this.mirrorPlane.applyMatrix4( this.mirrorCamera.matrixWorldInverse );
this.clipPlane.set( this.mirrorPlane.normal.x, this.mirrorPlane.normal.y, this.mirrorPlane.normal.z, this.mirrorPlane.constant );
var q = new THREE.Vector4();
var projectionMatrix = this.mirrorCamera.projectionMatrix;
q.x = ( Math.sign( this.clipPlane.x ) + projectionMatrix.elements[ 8 ] ) / projectionMatrix.elements[ 0 ];
q.y = ( Math.sign( this.clipPlane.y ) + projectionMatrix.elements[ 9 ] ) / projectionMatrix.elements[ 5 ];
q.z = - 1.0;
q.w = ( 1.0 + projectionMatrix.elements[ 10 ] ) / projectionMatrix.elements[ 14 ];
// Calculate the scaled plane vector
var c = new THREE.Vector4();
c = this.clipPlane.multiplyScalar( 2.0 / this.clipPlane.dot( q ) );
// Replacing the third row of the projection matrix
projectionMatrix.elements[ 2 ] = c.x;
projectionMatrix.elements[ 6 ] = c.y;
projectionMatrix.elements[ 10 ] = c.z + 1.0 - this.clipBias;
projectionMatrix.elements[ 14 ] = c.w;
};
THREE.Mirror.prototype.render = function () {
if ( this.matrixNeedsUpdate ) this.updateTextureMatrix();
this.matrixNeedsUpdate = true;
// Render the mirrored view of the current scene into the target texture
var scene = this;
while ( scene.parent !== null ) {
scene = scene.parent;
}
if ( scene !== undefined && scene instanceof THREE.Scene ) {
// We can't render ourself to ourself
var visible = this.material.visible;
this.material.visible = false;
this.renderer.render( scene, this.mirrorCamera, this.renderTarget, true );
this.material.visible = visible;
}
};
THREE.Mirror.prototype.renderTemp = function () {
if ( this.matrixNeedsUpdate ) this.updateTextureMatrix();
this.matrixNeedsUpdate = true;
// Render the mirrored view of the current scene into the target texture
var scene = this;
while ( scene.parent !== null ) {
scene = scene.parent;
}
if ( scene !== undefined && scene instanceof THREE.Scene ) {
this.renderer.render( scene, this.mirrorCamera, this.renderTarget2, true );
}
};
|
yrns/three.js
|
examples/js/Mirror.js
|
JavaScript
|
mit
| 9,386
|
var getMeshMixin = require('../getMeshMixin');
var registerPrimitive = require('../registerPrimitive');
var utils = require('../../../utils/');
registerPrimitive('a-torus', utils.extendDeep({}, getMeshMixin(), {
defaultComponents: {
geometry: {
primitive: 'torus'
}
},
mappings: {
'arc': 'geometry.arc',
'radius': 'geometry.radius',
'radius-tubular': 'geometry.radiusTubular',
'segments-radial': 'geometry.segmentsRadial',
'segments-tubular': 'geometry.segmentsTubular'
}
}));
|
jzitelli/aframe
|
src/extras/primitives/primitives/a-torus.js
|
JavaScript
|
mit
| 521
|
import React, {Component, PropTypes} from 'react';
import {Link} from 'react-router';
import util from '../../utilities/util';
import {IdeaStore} from '../../stores/ideaStore';
import {UserStore} from '../../stores/userStore';
class PersonSearch extends Component {
static contextTypes = {
router: PropTypes.object.isRequired
}
static propTypes = {
onClose: PropTypes.func.isRequired,
searchStr: PropTypes.string
}
constructor(props) {
super(props);
this.state = {
searchStr: '',
ideaSearchResults: [],
personSearchResults: []
};
}
componentDidMount() {
this.state.searchStr = this.props.searchStr;
this.setState({searchStr: this.state.searchStr});
this._executeSearch();
}
render() {
let ideaSearchResults = this.state.ideaSearchResults.map(idea => {
return (
<li key={idea._id}>
<button onClick={this._selectIdea.bind(this, idea)}>
<span className="search-result-name">{idea.name}</span>
<span className="search-result-info">{idea.summary}</span>
<span className="search-result-info">Score: {util.round(idea.score, 1)}</span>
</button>
</li>
);
});
let personSearchResults = this.state.personSearchResults.map(person => {
return (
<li key={person._id}>
<button onClick={this._selectPerson.bind(this, person)}>
<span className="search-result-name">{person.firstName} {person.lastName}</span>
<span className="search-result-info">{person.username}</span>
<span className="search-result-info">Score: {util.round(person.score, 1)}</span>
</button>
</li>
);
});
return (
<div className="site-search fade">
<div className="site-search-container">
<button type="button" className="inline site-search-close" onClick={this.props.onClose}>(close)</button>
<form onSubmit={this._executeSearch}>
<input className="form-element small" type="text" value={this.state.searchStr} onChange={this._onChange} autoFocus={true} />
<button type="submit" className="hidden"></button>
</form>
<div className="site-search-results">
<div>
<h2>Ideas</h2>
{(() => {
if (this.state.ideaSearchResults.length > 0) {
return <ul>{ideaSearchResults}</ul>;
} else {
return <span>No results found</span>
}
})()}
</div>
<div>
<h2>People</h2>
{(() => {
if (this.state.personSearchResults.length > 0) {
return <ul>{personSearchResults}</ul>;
} else {
return <span>No results found</span>
}
})()}
</div>
</div>
</div>
</div>
);
}
_selectIdea = (idea, e) => {
e.preventDefault();
this.context.router.push('/ideas/' + idea._id);
this.props.onClose(e);
}
_selectPerson = (person, e) => {
e.preventDefault();
this.context.router.push('/people/' + person._id);
this.props.onClose(e);
}
_executeSearch = (e) => {
if (e) { e.preventDefault(); }
let searchStr = this.state.searchStr;
if (util.isEmpty(searchStr)) {
return this.setState({ideaSearchResults: [], personSearchResults: []});
}
IdeaStore.search(searchStr)
.done(results => {
this.setState({ideaSearchResults: results});
});
UserStore.search(searchStr)
.done(results => {
this.setState({personSearchResults: results});
});
}
_onChange = (e) => {
e.preventDefault();
this.setState({searchStr: e.target.value});
}
}
export default PersonSearch;
|
davelaursen/idealogue
|
react-es6-node-graphql-mongodb/src/client/components/common/siteSearch.react.js
|
JavaScript
|
mit
| 4,644
|
import React from 'react';
import PropTypes from 'prop-types';
const InputElement = ({ label, placeholder, text, setText, name }) => {
const onChange = (e) => setText(e);
return (
<div className='input-component'>
<label className='input-label-name' htmlFor={label}>
{label}
</label>
<input
className='input-element'
type='text'
placeholder={placeholder}
value={text}
name={name}
onChange={onChange}
id={label}
/>
</div>
);
};
InputElement.propTypes = {
label: PropTypes.string.isRequired,
placeholder: PropTypes.string.isRequired,
text: PropTypes.string.isRequired,
setText: PropTypes.func.isRequired,
name: PropTypes.string,
};
export default InputElement;
|
jeffslofish/open-source-help-wanted
|
src/components/InputElement.js
|
JavaScript
|
mit
| 775
|
;/* safify.jquery.js
*
* https://github.com/jamiesonbecker/jquery-safify
* Copyright (c) 2017 Jamieson Becker, http://jamiesonbecker.com
* MIT License
*
*/
function strict_safify(htm) {
// this prevents possible HTML attacks using the absolutely bare-minimum
// essentials as specified by OWASP
// https://www.owasp.org/index.php/XSS_%28Cross_Site_Scripting%29_Prevention_Cheat_Sheet
// this method of pure string replacements are much safer and faster than
// attempting to regex-match all tags
// See jQuery plugin at end for example usage
var htm = htm || "";
return htm
.replace(/&/g, '&')
.replace(/</g, '<')
.replace(/>/g, '>')
.replace(/"/g, '"')
.replace(/'/g, ''')
.replace(/\//g, '/')
.replace(/\n/g, ' <br> ');
}
function safify(htm) {
// This runs normal strict_safify but puts back in
// a few safer HTML tags. No attributes are currently allowed.
// uncomplicated regex -- easy to audit
// images coming soon! (src= can be dangerous)
// This may eventually be supplemented with a custom version of
// https://github.com/cowboy/javascript-linkify with rel=nofollow
return strict_safify(htm)
// bold
.replace(/<b>/gi, " <b> ")
.replace(/</b>/gi, " </b> ")
// strong
.replace(/<strong>/gi, " <strong> ")
.replace(/</strong>/gi, " </strong> ")
// emphasis
.replace(/<em>/gi, " <em> ")
.replace(/</em>/gi, " </em> ")
// italics
.replace(/<i>/gi, " <i> ")
.replace(/</i>/gi, " </i> ")
// li
.replace(/<li>/gi, " <li> ")
.replace(/</li>/gi, " </li> ")
// ul
.replace(/<ul>/gi, " <ul> ")
.replace(/</ul>/gi, " </ul> ")
// ol
.replace(/<ol>/gi, " <ol> ")
.replace(/</ol>/gi, " </ol> ")
// h1
.replace(/<h1>/gi, " <h1> ")
.replace(/</h1>/gi, " </h1> ")
// h2
.replace(/<h2>/gi, " <h2> ")
.replace(/</h2>/gi, " </h2> ")
// h3
.replace(/<h3>/gi, " <h3> ")
.replace(/</h3>/gi, " </h3> ")
// h4
.replace(/<h4>/gi, " <h4> ")
.replace(/</h4>/gi, " </h4> ")
// h5
.replace(/<h5>/gi, " <h5> ")
.replace(/</h5>/gi, " </h5> ")
// h6
.replace(/<h6>/gi, " <h6> ")
.replace(/</h6>/gi, " </h6> ")
// table
.replace(/<table>/gi, " <table> ")
.replace(/</table>/gi, " </table> ")
// tr
.replace(/<tr>/gi, " <tr> ")
.replace(/</tr>/gi, " </tr> ")
// td
.replace(/<td>/gi, " <td> ")
.replace(/</td>/gi, " </td> ")
// p
.replace(/<p>/gi, " <p> ")
.replace(/</p>/gi, " </p> ")
// br
.replace(/<br>/gi, " <br> ")
;
}
function unstrict_safify(htm) {
// only use this for input or non-HTML textarea plugins
// (don't use with Javascript HTML editors!)
var htm = htm || "";
return htm
.replace(/<br>/g, '\n')
.replace(/&/g, '&')
.replace(/</g, '<')
.replace(/>/g, '>')
.replace(/"/g, '"')
.replace(/'/g, "'")
.replace(///g, '/');
}
/*
* jQuery Safify
*
* Allows some minimal HTML while keeping out the bad stuff.
* (If you want to convert all HTML to plain text like pure safify.js, jQuery
* already has $.text built-in.)
*
*
* var evil = "<script>alert(1);</script>";
*
*
* To use, just replace your normal:
*
*
* $("div").html(evil);
* or:
* $("div").text(evil);
*
*
* with:
*
* $("div").safify(evil);
*
* unsafify() is not wrapped to keep it from being accidentally (mis)used.
*/
(function($) {
// Allows "safe" tags
$.fn.safify = function(evil) {
this.html(safify(evil));
return this;
};
// Allows no tags
$.fn.strict_safify = function(evil) {
this.html(strict_safify(evil));
return this;
};
})(jQuery);
|
jamiesonbecker/safify.js
|
safify.js
|
JavaScript
|
mit
| 4,387
|
// @if TARGET='app'
import { ipcRenderer } from 'electron';
// @endif
const Native = {};
// @if TARGET='app'
Native.getAppVersionInfo = () =>
new Promise(resolve => {
// @if TARGET='app'
ipcRenderer.once('version-info-received', (event, versionInfo) => {
resolve(versionInfo);
});
ipcRenderer.send('version-info-requested');
// @endif
});
// @endif
export default Native;
|
lbryio/lbry-app
|
ui/native.js
|
JavaScript
|
mit
| 405
|
(function() {
if(!window.location.origin) {
window.location.origin = window.location.protocol + "//" + window.location.hostname + (window.location.port ? ':' + window.location.port: '');
}
})();
|
webkatu/leads-router
|
lib/locationOrigin.js
|
JavaScript
|
mit
| 202
|
//= require jquery
//= require ./jquery/layout
|
rosenfeld/jquery-layout-rails
|
vendor/assets/javascripts/jquery-layout.js
|
JavaScript
|
mit
| 47
|
"use strict";
const assert = require('assert');
describe('redditWallpaper', function () {
const redditWallpaper = require(__dirname);
describe('#matchFile()', function () {
it('should match a valid file from url', function () {
let match = redditWallpaper.matchFile('http://proof.nationalgeographic.com/files/2014/11/PastedGraphic-2.jpg?asdfquerystring=yes&asdfparam=fsdf%20df');
assert(match.length > 2);
assert.equal(match[1], 'PastedGraphic-2');
assert.equal(match[2], 'jpg');
});
});
describe('#parseType()', function () {
it('should extract file extension from url', function () {
let extension = redditWallpaper.parseType('http://i.imgur.com/jEFSFKr.jpg?asdfquerystring=yes&asdfparam=fsdf%20df');
assert.equal(extension, 'jpg');
});
});
describe('#parseResolution()', function () {
it('should parse resolution tag from text', function () {
let resolution = redditWallpaper.parseResolution('Test!!##123 [1920 x 1080]asdf [OC] [9999x9999]]');
assert.equal(resolution.width, 1920);
assert.equal(resolution.height, 1080);
});
});
});
|
jmercha/reddit-wallpaper
|
test.js
|
JavaScript
|
mit
| 1,197
|
'use strict';
const city = {
name: 'Kiev',
year: 482,
f1: function() {
return `${this.name} build year ${this.year}`;
},
f2: () => {
return `${this.name} build year ${this.year}`;
}
};
console.log('city.f1() = ' + city.f1());
console.log('city.f2() = ' + city.f2());
|
wirtaw/Project
|
src/Functions/9-this.js
|
JavaScript
|
mit
| 289
|
const fs = require('fs');
const async = require('async');
const expect = require('chai').expect;
const request = require('supertest');
const parse = require('csv-parse');
const server = require('../app').server;
const Request = require('../models/Request');
const website = require('./website');
const api = require('./api');
const legacy = require('./api/legacy');
const modern = require('./api/modern');
const v10 = require('./api/modern/1.0');
const v11 = require('./api/modern/1.1');
const v12 = require('./api/modern/1.2');
const v13 = require('./api/modern/1.3');
// Start up server
before(function(done) {
this.timeout(10000);
server.on("serverStarted", () => {
done();
});
});
describe('Randomuser.me', function() {
this.timeout(10000);
describe('Website', website.bind(this, server));
describe('API', () => {
describe('General', api.bind(this, server));
describe.skip('Legacy versions <1.0', legacy.bind(this, server));
describe('Modern versions >=1.0', () => {
describe('General', modern.bind(this, server))
describe('1.0', v10.bind(this, server));
describe('1.1', v11.bind(this, server));
describe('1.2', v12.bind(this, server));
describe('1.3', v13.bind(this, server));
});
});
after((done) => {
done();
});
});
|
RandomAPI/Randomuser.me-Node
|
spec/index.js
|
JavaScript
|
mit
| 1,326
|
beforeEach(function() {
JA.initialized = false;
});
describe("JA app tests", function () {
before(function() {
document.body.innerHTML = __html__['specs/home.html'];
});
it("build", function(done) {
if (JA.get) {
done(".get() should be undefined at this point");
}
if (JA.post) {
done(".post() should be undefined at this point");
}
JA.build({
errorHandler: function (err) {
err.should.be.eql("Test");
done();
}
});
JA.get.should.be.a.Function
JA.post.should.be.a.Function
JA.errorHandler("Test");
});
// add
it('add page', function () {
JA.build();
var homePage = JA.addPage({
id: "homePage"
});
JA._pages.length.should.eql(1);
JA.page("homePage").should.be.eql(homePage);
});
it('add display', function () {
var homePage = JA.page('homePage');
var homeDisplay = homePage.addDisplay({
id: "homeDisplay",
container: "#homeContainer"
});
homePage._displays.length.should.be.eql(1);
homePage._displayById['homeDisplay'].should.be.eql(homeDisplay);
$("#homeTest").length.should.be.eql(1);
});
// navigate
it('navigate', function () {
$("#homeContainer").css("display").should.be.eql('none');
JA.navigate('homePage');
JA.page('homePage').activateAllDisplays();
$("#homeContainer").css("display").should.be.eql('block');
var page = JA.page('homePage');
page.deactivate();
$("#homeContainer").css("display").should.be.eql('none');
});
// ajax
it("get error", function (done) {
JA.build({
errorHandler: function (jqXHR, textStatus, errorThrown) {
textStatus.should.be.eql('error')
done();
}
});
JA.get("http://notexists../", function () { });
});
it("post error", function (done) {
JA.build({
errorHandler: function (jqXHR, textStatus, errorThrown) {
textStatus.should.be.eql('error')
done();
}
});
JA.get("http://notexists../", function () { });
});
//
});
|
Deividy/japp
|
specs/app.spec.js
|
JavaScript
|
mit
| 2,348
|
import HTMLControl from './HTMLControl.js';
// Simple error handling function - customize as necessary
const cachedMessages = {};
const errorHandler = ( msg ) => {
// cache the message to prevent it being displayed multiple times
if ( cachedMessages[ msg ] === true ) return;
cachedMessages[ msg ] = true;
if ( !( msg instanceof String ) ) {
console.log( msg );
return;
}
// bug in three.js or WebGL returns this error on Chrome
if ( msg.indexOf( 'gl.getProgramInfoLog()' ) !== -1 ) return;
HTMLControl.error.overlay.classList.remove( 'hide' );
const p = document.createElement( 'p' );
p.innerHTML = msg;
HTMLControl.error.messages.appendChild( p );
};
export default errorHandler;
|
looeee/blackthreaddesign.com
|
assets/js/src/pages/experiments/loader/utilities/errorHandler.js
|
JavaScript
|
mit
| 724
|
define(
"igbtoolbox/messagebus/messagebus-events",
[],
function() {
'use strict';
/**
* Enum for events supported by the message bus
* @enum {string}
*/
var messageBusEvents = {
CONNECTED: 'messagebus_connected',
DISCONNECTED: 'messagebus_disconnected',
NEED_CONNECTION_STATUS: 'messagebug_need_status',
MESSAGE: 'messagebus_message',
NEED_MESSAGE_SEND: 'messagebus_need_send'
};
/**
* Generic server-side message event
*
* @final
* @constructor
* @param {string} mod effected module id
* @param {string} ev event type
* @param {Object} data payload
*/
messageBusEvents.Message = function(mod, ev, data) {
this.module = mod;
this.eventType = ev;
this.data = data;
};
return messageBusEvents;
}
);
|
igbtoolbox/evemessagebus
|
web/js/igbtoolbox/messagebus/messagebus-events.js
|
JavaScript
|
mit
| 845
|
'use strict';
angular.module('Strawberry.welcome', ['ngRoute'])
.config(['$routeProvider', function($routeProvider) {
$routeProvider.when('/', {
templateUrl: 'views/welcome/welcome.html',
controller: 'WelcomeCtrl'
});
}])
.controller('WelcomeCtrl', ['$scope', '$routeParams', '$rootScope', function($scope,$routeParams,$rootScope) {
}]);
|
samueldelesque/strawberry
|
apps/mac/strawberry.app/Contents/Resources/app.nw/views/welcome/welcome.js
|
JavaScript
|
mit
| 347
|
'use strict';
describe('Controller: ManagerAddeventCtrl', function () {
// load the controller's module
beforeEach(module('signupSystemApp'));
var ManagerAddeventCtrl,
scope;
// Initialize the controller and a mock scope
beforeEach(inject(function ($controller, $rootScope) {
scope = $rootScope.$new();
ManagerAddeventCtrl = $controller('ManagerAddeventCtrl', {
$scope: scope
});
}));
it('should attach a list of awesomeThings to the scope', function () {
expect(scope.awesomeThings.length).toBe(3);
});
});
|
claydiffrient/signup-system
|
test/spec/controllers/manager/addevent.js
|
JavaScript
|
mit
| 555
|
var HTTP_STATUS_CODES = require('http').STATUS_CODES;
var fs = require('fs');
var os = require('os');
var EventEmitter = require('events').EventEmitter;
var util = require('util');
var request = require('request');
var xmlbuilder = require('xmlbuilder');
var stackTrace = require('stack-trace');
var hashish = require('hashish');
var querystring = require('querystring');
module.exports = Airbrake;
util.inherits(Airbrake, EventEmitter);
function Airbrake() {
this.key = null;
this.host = 'http://' + os.hostname();
this.env = process.env.NODE_ENV || 'development';
this.projectRoot = null;
this.appVersion = null;
this.timeout = 30 * 1000;
this.developmentEnvironments = ['development', 'test'];
this.protocol = 'http';
this.serviceHost = process.env.AIRBRAKE_SERVER || 'api.airbrake.io';
}
Airbrake.PACKAGE = (function() {
var json = fs.readFileSync(__dirname + '/../package.json', 'utf8');
return JSON.parse(json);
})();
Airbrake.createClient = function(key, env) {
var instance = new this();
instance.key = key;
instance.env = env || instance.env;
return instance;
};
Airbrake.prototype.expressHandler = function(disableUncaughtException) {
var self = this;
if(!disableUncaughtException) {
process.on('uncaughtException', function(err) {
self._onError(err, true);
});
}
return function errorHandler(err, req, res, next) {
if (res.statusCode < 400) res.statusCode = 500;
err.url = req.url;
err.component = req.url;
err.action = req.method;
err.params = req.body;
err.session = req.session;
self._onError(err, false);
next(err);
};
};
Airbrake.prototype._onError = function(err, die) {
var self = this;
if (!(err instanceof Error)) {
err = new Error(err);
}
self.log('Airbrake: Uncaught exception, sending notification for:');
self.log(err.stack || err);
self.notify(err, function(notifyErr, url, devMode) {
if (notifyErr) {
self.log('Airbrake: Could not notify service.');
self.log(notifyErr.stack);
} else if (devMode) {
self.log('Airbrake: Dev mode, did not send.');
} else {
self.log('Airbrake: Notified service: ' + url);
}
if (die) {
process.exit(1);
}
});
};
Airbrake.prototype.handleExceptions = function() {
var self = this;
process.on('uncaughtException', function(err) {
self._onError(err, true);
});
};
Airbrake.prototype.log = function(str) {
console.error(str);
};
Airbrake.prototype.notify = function(err, cb) {
var callback = this._callback(cb);
// log errors instead of posting to airbrake if a dev enviroment
if (this.developmentEnvironments.indexOf(this.env) != -1) {
this.log(err);
return callback(null, null, true);
}
var body = this.notifyXml(err);
var options = {
method: 'POST',
url: this.url('/notifier_api/v2/notices'),
body: body,
timeout: this.timeout,
headers: {
'Content-Length': body.length,
'Content-Type': 'text/xml',
'Accept': 'text/xml',
},
};
request(options, function(err, res, body) {
if (err) {
return callback(err);
}
if (undefined === body) {
return callback(new Error('invalid body'));
}
if (res.statusCode >= 300) {
var status = HTTP_STATUS_CODES[res.statusCode];
var explanation = body.match(/<error>([^<]+)/i);
explanation = (explanation)
? ': ' + explanation[1]
: ': ' + body;
return callback(new Error(
'Notification failed: ' + res.statusCode + ' ' + status + explanation
));
}
// Give me a break, this is legit : )
var m = body.match(/<url>([^<]+)/i);
var url = (m)
? m[1]
: null;
callback(null, url);
});
};
Airbrake.prototype._callback = function(cb) {
var self = this;
return function(err) {
if (cb) {
cb.apply(self, arguments);
return;
}
if (err) {
self.emit('error', err);
}
};
};
Airbrake.prototype.url = function(path) {
return this.protocol + '://' + this.serviceHost + path;
};
Airbrake.prototype.notifyXml = function(err, pretty) {
var notice = xmlbuilder.create().begin('notice', {
version: '1.0',
encoding: 'UTF-8'
});
this.appendHeaderXml(notice);
this.appendErrorXml(notice, err);
this.appendRequestXml(notice, err);
this.appendServerEnvironmentXml(notice);
return notice.doc().toString({pretty: pretty});
};
Airbrake.prototype.appendHeaderXml = function(notice) {
notice
.att('version', '2.2')
.ele('api-key')
.txt(this.key || '-')
.up()
.ele('notifier')
.ele('name')
.txt(Airbrake.PACKAGE.name)
.up()
.ele('version')
.txt(Airbrake.PACKAGE.version)
.up()
.ele('url')
.txt(Airbrake.PACKAGE.homepage)
.up()
.up();
};
Airbrake.prototype.appendErrorXml = function(notice, err) {
var trace = stackTrace.parse(err);
var error = notice
.ele('error')
.ele('class')
.txt(err.type || 'Error')
.up()
.ele('message')
.txt(err.message || '-')
.up()
.ele('backtrace');
trace.forEach(function(callSite) {
error
.ele('line')
.att('method', callSite.getFunctionName() || '')
.att('file', callSite.getFileName() || '')
.att('number', callSite.getLineNumber() || '');
});
};
Airbrake.prototype.appendRequestXml = function(notice, err) {
var request = notice.ele('request');
var self = this;
['url', 'component', 'action'].forEach(function(nodeName) {
var node = request.ele(nodeName);
var val = err[nodeName];
if (nodeName === 'url') {
if (!val) {
val = self.host;
} else if (val.substr(0, 1) === '/') {
val = self.host + val;
}
}
if (val) {
node.txt(val);
}
});
this.addRequestVars(request, 'cgi-data', this.cgiDataVars(err));
this.addRequestVars(request, 'session', this.sessionVars(err));
this.addRequestVars(request, 'params', this.paramsVars(err));
};
Airbrake.prototype.addRequestVars = function(request, type, vars) {
this.emit('vars', type, vars);
var node;
Object.keys(vars).forEach(function(key) {
node = node || request.ele(type);
value = vars[key];
if ('string' !== typeof value) {
value = util.inspect(value, { showHidden: true, depth: null });
}
node
.ele('var')
.att('key', key)
.txt(value);
});
};
Airbrake.prototype.cgiDataVars = function(err) {
var cgiData = {};
Object.keys(process.env).forEach(function(key) {
cgiData[key] = process.env[key];
});
var exclude = [
'type',
'message',
'arguments',
'stack',
'url',
'session',
'params',
'component',
'action',
];
Object.keys(err).forEach(function(key) {
if (exclude.indexOf(key) >= 0) {
return;
}
cgiData['err.' + key] = err[key];
});
cgiData['process.pid'] = process.pid;
if(os.platform() != "win32") {
// this two properties are *NIX only
cgiData['process.uid'] = process.getuid();
cgiData['process.gid'] = process.getgid();
}
cgiData['process.cwd'] = process.cwd();
cgiData['process.execPath'] = process.execPath;
cgiData['process.version'] = process.version;
cgiData['process.argv'] = process.argv;
cgiData['process.memoryUsage'] = process.memoryUsage();
cgiData['os.loadavg'] = os.loadavg();
cgiData['os.uptime'] = os.uptime();
return cgiData;
};
Airbrake.prototype.sessionVars = function(err) {
return (err.session instanceof Object)
? err.session
: {};
};
Airbrake.prototype.paramsVars = function(err) {
return (err.params instanceof Object)
? err.params
: {};
};
Airbrake.prototype.appendServerEnvironmentXml = function(notice) {
var serverEnvironment = notice.ele('server-environment');
if (this.projectRoot) {
serverEnvironment
.ele('project-root')
.txt(this.projectRoot);
}
serverEnvironment
.ele('environment-name')
.txt(this.env)
if (this.appVersion) {
serverEnvironment
.ele('app-version')
.txt(this.appVersion);
}
};
Airbrake.prototype.trackDeployment = function(params, cb) {
if (typeof params === 'function') {
cb = params;
params = {};
}
params = hashish.merge({
key: this.key,
env: this.env,
user: process.env.USER,
rev: '',
repo: '',
}, params);
var body = this.deploymentPostData(params);
var options = {
method: 'POST',
url: this.url('/deploys.txt'),
body: body,
timeout: this.timeout,
headers: {
'Content-Length': body.length,
'Content-Type': 'application/x-www-form-urlencoded',
},
};
var callback = this._callback(cb);
request(options, function(err, res, body) {
if (err) {
return callback(err);
}
if (res.statusCode >= 300) {
var status = HTTP_STATUS_CODES[res.statusCode];
return callback(new Error(
'Deployment failed: ' + res.statusCode + ' ' + status + ': ' + body
));
}
callback(null, params);
});
};
Airbrake.prototype.deploymentPostData = function(params) {
return querystring.stringify({
'api_key': params.key,
'deploy[rails_env]': params.env,
'deploy[local_username]': params.user,
'deploy[scm_revision]': params.rev,
'deploy[scm_repository]': params.repo
});
};
|
jirwin/node-airbrake
|
lib/airbrake.js
|
JavaScript
|
mit
| 9,355
|
import Ember from 'ember';
import layout from '../../templates/components/list-card/header';
export default Ember.Component.extend({
classNames: ['list-card-header-component', 'list-group-item'],
layout: layout,
/**
* Action when queyr option is selected
*/
onQueryOptionSelect: Ember.K,
/**
* Filter groups
*/
filterGroups: null,
/**
* Name of the grid
*/
title: null,
/**
* Active query tokens
*/
queryTokens: null,
actions: {
selectItem(item) {
this.get('onQueryTokenSelected')(item.queryToken);
},
deselectItem(item) {
this.get('onQueryTokenDeselected')(item.queryToken);
},
replaceItem(item) {
this.get('onQueryTokenReplaced')(item.queryToken);
}
}
});
|
wcurtis/ember-list-card
|
addon/components/list-card/header.js
|
JavaScript
|
mit
| 755
|
'use strict';
var assert = require('assert');
var mcpeping = require('../');
describe('mcpe-ping node module', function () {
it('must be able to ping sg.lbsg.net', function () {
mcpeping('play.lbsg.net', 19132, function(err) {
assert(null, err);
}, 5000);
});
it('must be able to ping a.a', function () {
mcpeping('play.inpvp.netkugiu', 19132, function(err) {
assert(err, null);
}, 5000);
});
});
|
Falkirks/mcpe-ping
|
test/test.js
|
JavaScript
|
mit
| 434
|
const fs = require('fs');
const filename = process.argv[2];
const chartData = JSON.parse(fs.readFileSync(filename, {encoding: 'utf8'}));
chartData.notes.forEach((note) => {
note.totalOffset = note.offset + note.beat * 24;
delete note.offset;
delete note.beat;
});
fs.writeFileSync(filename, JSON.stringify(chartData), {encoding: 'utf8'});
|
thomasboyt/bipp
|
scripts/convert_to_total_offset.js
|
JavaScript
|
mit
| 349
|
var prisonVisits = {
url: '/prison-visits',
total: 0,
digitalTotal: 0,
nonDigitalTotal: 0,
dateFrom: [],
loadData: function() {
loadUrl = prisonVisits.url;
if (typeof offline !== 'undefined') {
prisonVisits.parseData(prison_visits_json);
return;
}
$.ajax({
dataType: 'json',
cache: false,
url: loadUrl,
success: function(d) {
prisonVisits.parseData(d);
}
});
},
parseData: function(d) {
// get the oldest date WITH data (it didn't launch that long ago)
var lump = d.data[0].values;
for (var i = 0; i < lump.length; i++) {
if (lump[i]['count:sum'] !== null) {
this.dateFrom = lump[i]._start_at.split('-');
break;
}
}
this.digitalTotal = d.data[0]['count:sum'];
this.nonDigitalTotal = d.data[1]['count:sum'];
this.total = this.digitalTotal + this.nonDigitalTotal;
prisonVisits.updateDisplay();
},
updateDisplay: function() {
var $el = $('.prison-visits');
$el.find('.total-figure').text(addCommas(this.total));
$el.find('.total-digital').text(addCommas(this.digitalTotal));
$el.find('.total-non-digital').text(addCommas(this.nonDigitalTotal));
$el.find('.latest-date').text(monthsMap[this.dateFrom[1]] + ' ' + this.dateFrom[0]);
}
};
$(function() {
prisonVisits.loadData();
});
|
gds-dead/gds-data-screens
|
assets/js/items/prison-visits.js
|
JavaScript
|
mit
| 1,364
|
(function () {
'use strict';
angular.module('mgApp').factory('PracticeService', PracticeService);
PracticeService.$inject = ['$http', '$q'];
function PracticeService($http, $q) {
var service = {
create: function (wordListId) {
var deferred = $q.defer();
$http.post(
'/api/practicesession',
{
wordListId: wordListId
})
.success(function (result) {
deferred.resolve(result.practiceSessionId);
})
.error(function (response) {
deferred.reject(response);
});
return deferred.promise;
},
getUnfinished: function (wordListId) {
var deferred = $q.defer();
$http.get(
'/api/unfinishedpracticesession',
{
params:
{
wordListId: wordListId
}
})
.success(function (result) {
deferred.resolve(result);
})
.error(function (response) {
deferred.reject(response);
});
return deferred.promise;
}
};
return service;
}
})();
|
dlidstrom/MinaGlosor
|
MinaGlosor.Web/wwwroot/app/shared/practiceService.js
|
JavaScript
|
mit
| 1,543
|
//
// # SimpleServer
//
// A simple chat server using Socket.IO, Express, and Async.
//
var http = require('http'),
path = require('path'),
async = require('async'),
favicon = require('static-favicon'),
session = require('express-session'),
swig = require('swig'),
redis = require("redis").createClient(),
cookieParser = require('cookie-parser'),
bodyParser = require('body-parser'),
session = require('express-session'),
passport = require('passport'),
RedisStore = require('connect-redis')(session),
express = require('express');
var app = express();
app.engine('html', swig.renderFile);
app.set('views', path.join(__dirname, 'view'));
app.set('view engine', 'html');
swig.setDefaults({ cache: false });
app.use(favicon())
.use(express.static(path.join(__dirname, 'public')))
.use(bodyParser.json())
.use(bodyParser.urlencoded())
.use(cookieParser())
.use(session({
store: new RedisStore({client: redis }),
secret: 'Tango Down',
cookie: { maxAge : 604800000 },
saveUninitialized: false,
resave: false
}))
.use(passport.initialize())
.use(passport.session());
// development error handler
if (app.get('env') === 'development') {
app.use(function(err, req, res, next) {
res.status(err.status || 500);
res.render('error', {
message: err.message,
error: err
});
});
}
// production error handler
app.use(function(err, req, res, next) {
res.status(err.status || 500);
res.render('error', {
message: err.message,
error: {}
});
});
var server = app.listen(process.env.PORT || 3000, process.env.IP || "0.0.0.0", function(){
var addr = server.address();
console.log("Express listening at", addr.address + ":" + addr.port);
});
module.exports.app = app;
require('./route');
|
Skepton/Blog-platform
|
server.js
|
JavaScript
|
mit
| 1,765
|
// Copyright IBM Corp. 2015. All Rights Reserved.
// Node module: strong-agent
// US Government Users Restricted Rights - Use, duplication or disclosure
// restricted by GSA ADP Schedule Contract with IBM Corp.
'use strict';
// FIXME(bnoordhuis) Unclear if require('../agent') is for side effects.
var agent = require('../agent');
var proxy = require('../proxy');
var samples = require('../samples');
var counts = require('../counts');
var tiers = require('../tiers');
var topFunctions = require('../top-functions');
var tier = 'postgres';
function recordExtra(extra, timer) {
if (extra) {
extra[tier] = extra[tier] || 0;
extra[tier] += timer.ms;
if (extra.closed) {
tiers.sample(tier + '_out', timer);
} else {
tiers.sample(tier + '_in', timer);
}
} else {
tiers.sample(tier + '_in', timer);
}
}
module.exports = function(obj) {
function probe(obj) {
if (obj.__probeInstalled__) return;
obj.__probeInstalled__ = true;
function strongTraceTransaction(query, callback){
var linkName = "PostgreSQL " + query;
return agent.transactionLink(linkName, callback);
}
// Callback API
proxy.before(obj, 'query', function(obj, args, ret) {
var command = args.length > 0 ? args[0] : undefined;
var params =
args.length > 1 && Array.isArray(args[1]) ? args[1] : undefined;
var timer = samples.timer("PostgreSQL", "query");
counts.sample('postgres');
function handleCallback(obj, args, extra) {
timer.end();
topFunctions.add('postgresCalls', command, timer.ms);
recordExtra(extra, timer);
}
proxy.callback(args, -1, strongTraceTransaction(command, handleCallback));
});
// Evented API
proxy.after(obj, 'query', function(obj, args, ret) {
// If has a callback, ignore
if (args.length > 0 && typeof args[args.length - 1] === 'function')
return;
var client = obj;
var command = args.length > 0 ? args[0] : undefined;
var params =
args.length > 1 && Array.isArray(args[1]) ? args[1] : undefined;
var timer = samples.timer("PostgreSQL", "query");
counts.sample('postgres');
proxy.before(ret, 'on', function(obj, args) {
var event = args[0];
if (event !== 'end' && event !== 'error') return;
function handleEvent(obj, args, extra) {
timer.end();
topFunctions.add('postgresCalls', command, timer.ms);
recordExtra(extra, timer);
}
proxy.callback(args, -1, strongTraceTransaction(command, handleEvent));
});
});
}
// Native, reinitialize probe
proxy.getter(obj, 'native', function(obj, ret) {
proxy.after(ret, 'Client',
function(obj, args, ret) { probe(ret.__proto__); });
});
probe(obj.Client.prototype);
return obj;
};
|
tsiry95/openshift-strongloop-cartridge
|
strongloop/node_modules/strong-agent/lib/probes/pg.js
|
JavaScript
|
mit
| 2,864
|
module.exports = require('./CustomContextPadProvider');
|
korbinianHoerfurter/bpmn-js-aof
|
lib/aof-context-pad/index.js
|
JavaScript
|
mit
| 56
|
(function() {
'use strict';
angular
.module('vmsFrontend')
.controller('UserLoginController', UserLoginController);
/** @ngInject */
function UserLoginController($log, userAuthentication, $rootScope, $state) {
var vm = this;
vm.alert = [];
vm.login = function() {
$log.debug('=== vm.role ===');
$log.debug(vm.role);
var onSuccess = function() {
$log.debug('login success');
// if the next state is login, it will go to profile state
if ($rootScope.toState.name == 'login') {
$state.go('profile');
} else {
// go to next with parameters
if (angular.isDefined($rootScope.toStateParams)) {
$state.go($rootScope.toState.name, $rootScope.toStateParams);
} else {
$state.go($rootScope.toState.name);
}
}
};
var onFailure = function(alert) {
$log.debug('login error');
$log.debug(alert);
vm.alert = [];
vm.alert.push(alert);
};
userAuthentication
.login(vm.credentials, vm.role)
.then(onSuccess)
.catch(onFailure);
}
}
})();
|
OpenISDM/VMS-frontend
|
src/app/user/login/userLogin.controller.js
|
JavaScript
|
mit
| 1,173
|
var bp = {
xsmall: 479,
small: 599,
medium: 770,
large: 979,
xlarge: 1199
};
var PointerManager = {
MOUSE_POINTER_TYPE: 'mouse',
TOUCH_POINTER_TYPE: 'touch',
POINTER_EVENT_TIMEOUT_MS: 500,
standardTouch: false,
touchDetectionEvent: null,
lastTouchType: null,
pointerTimeout: null,
pointerEventLock: false,
getPointerEventsSupported: function() {
return this.standardTouch;
},
getPointerEventsInputTypes: function() {
if (window.navigator.pointerEnabled) { //IE 11+
//return string values from http://msdn.microsoft.com/en-us/library/windows/apps/hh466130.aspx
return {
MOUSE: 'mouse',
TOUCH: 'touch',
PEN: 'pen'
};
} else if (window.navigator.msPointerEnabled) { //IE 10
//return numeric values from http://msdn.microsoft.com/en-us/library/windows/apps/hh466130.aspx
return {
MOUSE: 0x00000004,
TOUCH: 0x00000002,
PEN: 0x00000003
};
} else { //other browsers don't support pointer events
return {}; //return empty object
}
},
/**
* If called before init(), get best guess of input pointer type
* using Modernizr test.
* If called after init(), get current pointer in use.
*/
getPointer: function() {
// On iOS devices, always default to touch, as this.lastTouchType will intermittently return 'mouse' if
// multiple touches are triggered in rapid succession in Safari on iOS
if(Modernizr.ios) {
return this.TOUCH_POINTER_TYPE;
}
if(this.lastTouchType) {
return this.lastTouchType;
}
return Modernizr.touch ? this.TOUCH_POINTER_TYPE : this.MOUSE_POINTER_TYPE;
},
setPointerEventLock: function() {
this.pointerEventLock = true;
},
clearPointerEventLock: function() {
this.pointerEventLock = false;
},
setPointerEventLockTimeout: function() {
var that = this;
if(this.pointerTimeout) {
clearTimeout(this.pointerTimeout);
}
this.setPointerEventLock();
this.pointerTimeout = setTimeout(function() { that.clearPointerEventLock(); }, this.POINTER_EVENT_TIMEOUT_MS);
},
triggerMouseEvent: function(originalEvent) {
if(this.lastTouchType == this.MOUSE_POINTER_TYPE) {
return; //prevent duplicate events
}
this.lastTouchType = this.MOUSE_POINTER_TYPE;
jQuery(window).trigger('mouse-detected', originalEvent);
},
triggerTouchEvent: function(originalEvent) {
if(this.lastTouchType == this.TOUCH_POINTER_TYPE) {
return; //prevent duplicate events
}
this.lastTouchType = this.TOUCH_POINTER_TYPE;
jQuery(window).trigger('touch-detected', originalEvent);
},
initEnv: function() {
if (window.navigator.pointerEnabled) {
this.standardTouch = true;
this.touchDetectionEvent = 'pointermove';
} else if (window.navigator.msPointerEnabled) {
this.standardTouch = true;
this.touchDetectionEvent = 'MSPointerMove';
} else {
this.touchDetectionEvent = 'touchstart';
}
},
wirePointerDetection: function() {
var that = this;
if(this.standardTouch) { //standard-based touch events. Wire only one event.
//detect pointer event
jQuery(window).on(this.touchDetectionEvent, function(e) {
switch(e.originalEvent.pointerType) {
case that.getPointerEventsInputTypes().MOUSE:
that.triggerMouseEvent(e);
break;
case that.getPointerEventsInputTypes().TOUCH:
case that.getPointerEventsInputTypes().PEN:
// intentionally group pen and touch together
that.triggerTouchEvent(e);
break;
}
});
} else { //non-standard touch events. Wire touch and mouse competing events.
//detect first touch
jQuery(window).on(this.touchDetectionEvent, function(e) {
if(that.pointerEventLock) {
return;
}
that.setPointerEventLockTimeout();
that.triggerTouchEvent(e);
});
//detect mouse usage
jQuery(document).on('mouseover', function(e) {
if(that.pointerEventLock) {
return;
}
that.setPointerEventLockTimeout();
that.triggerMouseEvent(e);
});
}
},
init: function() {
this.initEnv();
this.wirePointerDetection();
}
};
var ProductMediaManager = {
swapImageDetail : function(base_image,zoom_image,thumb_image){
if(jQuery('.col-main-details').hasClass('col-main-details-style_2')){
ConfigurableMediaImages.checkImageLoaded(base_image,function(image){
jQuery('.product-view .product-img-box-top .arw-fancybox').last().attr('href',image).find('img').attr('src',image);
});
}else{
ConfigurableMediaImages.checkImageLoaded(thumb_image,function(image){
jQuery('.product-view #arw-zoom img').attr('src',image);
});
ConfigurableMediaImages.checkImageLoaded(zoom_image,function(image){
if(!jQuery('body').hasClass('arexworks-quickview-index')){
jQuery('.product-view #arw-zoom').data('zoom').destroy();
jQuery('.product-view #arw-zoom').attr('href',image);
jQuery('.product-view #arw-zoom').CloudZoom();
}
});
if(jQuery('.zoom-fancybox-button').parent().length > 0){
var flag = true;
jQuery('.zoom-fancybox-button').each(function(){
if(jQuery(this).data('image') == thumb_image){
flag = false;
}
})
if(flag){
var $parent_popup = jQuery('.zoom-fancybox-button').parent();
var $popup_object = jQuery('<a/>');
$popup_object.addClass('zoom-fancybox-button')
.attr('rel','gallery')
.attr('href',base_image)
.data('image',thumb_image);
$parent_popup.append($popup_object);
}
}
}
},
swapImageList : function(list_image , $product){
ConfigurableMediaImages.checkImageLoaded(list_image,function(image){
jQuery('img.product-collection-image',$product).attr('src',image);
})
},
init: function() {
jQuery(document).trigger('product-media-loaded', ProductMediaManager);
}
};
jQuery(document).ready(function(){
PointerManager.init();
ProductMediaManager.init();
});
|
scentuals-natural-organic-skincare/scentuals
|
.modman/benz_theme/skin/frontend/nova_benz/default/js/theme.1.9.1.js
|
JavaScript
|
mit
| 7,158
|
$(document).ready(inicio);
function inicio () {
$(".button-collapse").sideNav();
medidas(); // estableco las medidas para convertir
verificar(); // verifico si existe informacion constante
//eventos
$('#defecto').click(valorPorDefecto);
$('#FormConstantes').submit(function () {
guardar();
return false;
});
}
function guardar () {
/*
creo las constantes y las almaceno en localhost
*/
try{
var CONSTANTES = {
co2: $("#CO2").val(),
ch4: $("#CH4").val(),
n2o: $("#N2O").val(),
pfc: $("#PFC").val(),
hfc: $("#HFC").val(),
sf6: $("#SF6").val(),
papelcomun: $("#papelcomun").val(),
papelreciclado: $("#papelreciclado").val(),
co2biomasa: $("#CO2Biomasa").val(),
ch4biomasa: $("#CH4Biomasa").val(),
n2obiomasa: $("#N2OBiomasa").val(),
gasnatural: $('#gasNatural').val(),
gasoleo: $('#gasoleo').val(),
gasolina98_95: $('#gasolina98_95').val(),
gasolinatransporte: $('#gasoleoTransporte').val(),
gasolinaurbano14: $('#gasolinaUrbano14').val(),
gasolinaurbano142011: $('#gasolinaUrbano142011').val(),
gasolinaurbano2011: $('#gasolinaUrbano2011').val(),
gasolinarural14: $('#gasolinaRural14').val(),
gasolinarural142011: $('#gasolinaRural142011').val(),
gasolinarural2011: $('#gasolinaRural2011').val(),
gasolinainterurbano14: $('#gasolinaInterurbano14').val(),
gasolinainterurbano142011: $('#gasolinaInterurbano142011').val(),
gasolinainterurbano2011: $('#gasolinaInterurbano2011').val(),
dieselurbano21: $('#dieselUrbano21').val(),
dieselurbanom21: $('#dieselUrbanoM21').val(),
dieselrural21: $('#dieselRural21').val(),
dieselruralm21: $('#dieselRuralM21').val(),
dieselinterurbano21: $('#dieselInterurbano21').val(),
dieselinterurbanom21: $('#dieselInterurbanoM21').val(),
cualquieraurbano: $('#CualquieraUrbano').val(),
cualquierarural: $('#CualquieraRural').val(),
cualquierainterurbano: $('#CualquieraInterurbano').val(),
rigidourbano14t: $('#rigidoUrbano14t').val(),
rigidourbanom14t: $('#rigidoUrbanoM14t').val(),
rigidorural14t: $('#rigidoRural14t').val(),
rigidoruralm14t: $('#rigidoRuralM14t').val(),
rigidointerurbano14t: $('#rigidoInterurbano14t').val(),
rigidointerurbanom14t: $('#rigidoInterurbanoM14t').val(),
articuladourbano34t: $('#articuladoUrbano34t').val(),
articuladourbanom34t: $('#articuladoUrbanoM34t').val(),
articuladorural34t: $('#articuladoRural34t').val(),
articuladoruralm34t: $('#articuladoRuralM34t').val(),
articuladointerurbano34t: $('#articuladoInterurbano34t').val(),
articuladointerurbanom34t: $('#articuladoInterurbanoM34t').val(),
cualquieraurbanogasolina: $('#CualquieraUrbanoGasolina').val(),
cualquieraruralgasolina: $('#CualquieraRuralGasolina').val(),
cualquierainterurbanogasolina: $('#CualquieraInterurbanoGasolina').val(),
cualquieraurbanodiesel: $('#CualquieraUrbanoDiesel').val(),
cualquieraruraldiesel: $('#CualquieraRuralDiesel').val(),
cualquierainterurbanodiesel: $('#CualquieraInterurbanoDiesel').val(),
_2tiemposurbano: $('#2tiemposUrbano').val(),
_2tiemposrural: $('#2tiemposRural').val(),
_2tiemposinterurbano: $('#2tiemposInterurbano').val(),
_4tiempos250urbano: $('#4tiempos250Urbano').val(),
_4tiempos250rural: $('#4tiempos250Rural').val(),
_4tiempos250interurbano: $('#4tiempos250Interurbano').val(),
_4tiempos250750urbano: $('#4tiempos250750Urbano').val(),
_4tiempos250750rural: $('#4tiempos250750Rural').val(),
_4tiempos250750interurbano: $('#4tiempos250750Interurbano').val(),
_4tiempos750urbano: $('#4tiempos750Urbano').val(),
_4tiempos750rural: $('#4tiempos750Rural').val(),
_4tiempos750interurbano: $('#4tiempos750Interurbano').val()
}
if(validar()){
guardarLocalStorage(CONSTANTES); // lo guardamos
Materialize.toast('Datos guardados', 3000);
}else{
Materialize.toast('Solo numeros', 3000);
}
}catch(e){
Materialize.toast('No se ha pudo guardar', 3000);
console.log(e);
}
return false; // para que no se vaya a refrescar
}
function verificar () {
if (verificarLocalStorage()) {
var constantes = obtenerDatos();
//GWP
$("#CO2").val(constantes.co2);
$("#CH4").val(constantes.ch4);
$("#N2O").val(constantes.n2o);
$("#PFC").val(constantes.pfc);
$("#HFC").val(constantes.hfc);
$("#SF6").val(constantes.sf6);
//Papel
$("#papelcomun").val(constantes.papelcomun);
$("#papelreciclado").val(constantes.papelreciclado);
// biomasa solida primaria
$("#CO2Biomasa").val(constantes.co2biomasa);
$("#CH4Biomasa").val(constantes.ch4biomasa);
$("#N2OBiomasa").val(constantes.n2obiomasa);
// combustibles
$('#gasNatural').val(constantes.gasnatural);
$('#gasoleo').val(constantes.gasoleo);
// Transporte
$('#gasolina98_95').val(constantes.gasolina98_95);
$('#gasoleoTransporte').val(constantes.gasolinatransporte); // OJO ACA
// Turismos
// gasolina
$('#gasolinaUrbano14').val(constantes.gasolinaurbano14);
$('#gasolinaUrbano142011').val(constantes.gasolinaurbano142011);
$('#gasolinaUrbano2011').val(constantes.gasolinaurbano2011);
$('#gasolinaRural14').val(constantes.gasolinarural14);
$('#gasolinaRural142011').val(constantes.gasolinarural142011);
$('#gasolinaRural2011').val(constantes.gasolinarural2011);
$('#gasolinaInterurbano14').val(constantes.gasolinainterurbano14);
$('#gasolinaInterurbano142011').val(constantes.gasolinainterurbano142011);
$('#gasolinaInterurbano2011').val(constantes.gasolinainterurbano2011);
// diesel
$('#dieselUrbano21').val(constantes.dieselurbano21);
$('#dieselUrbanoM21').val(constantes.dieselurbanom21);
$('#dieselRural21').val(constantes.dieselrural21);
$('#dieselRuralM21').val(constantes.dieselruralm21);
$('#dieselInterurbano21').val(constantes.dieselinterurbano21);
$('#dieselInterurbanoM21').val(constantes.dieselinterurbanom21);
// Hibrido
$('#CualquieraUrbano').val(constantes.cualquieraurbano);
$('#CualquieraRural').val(constantes.cualquierarural);
$('#CualquieraInterurbano').val(constantes.cualquierainterurbano);
// Camion, camioneta y furgoneta
// Camion diesel
$('#rigidoUrbano14t').val(constantes.rigidourbano14t);
$('#rigidoUrbanoM14t').val(constantes.rigidourbanom14t);
$('#rigidoRural14t').val(constantes.rigidorural14t);
$('#rigidoRuralM14t').val(constantes.rigidoruralm14t);
$('#rigidoInterurbano14t').val(constantes.rigidointerurbano14t);
$('#rigidoInterurbanoM14t').val(constantes.rigidointerurbanom14t);
$('#articuladoUrbano34t').val(constantes.articuladourbano34t);
$('#articuladoUrbanoM34t').val(constantes.articuladourbanom34t);
$('#articuladoRural34t').val(constantes.articuladorural34t);
$('#articuladoRuralM34t').val(constantes.articuladoruralm34t);
$('#articuladoInterurbano34t').val(constantes.articuladointerurbano34t);
$('#articuladoInterurbanoM34t').val(constantes.articuladointerurbanom34t);
// lIGERO
$('#CualquieraUrbanoGasolina').val(constantes.cualquierainterurbanogasolina);
$('#CualquieraRuralGasolina').val(constantes.cualquieraruralgasolina);
$('#CualquieraInterurbanoGasolina').val(constantes.cualquierainterurbanogasolina);
$('#CualquieraUrbanoDiesel').val(constantes.cualquieraurbanodiesel);
$('#CualquieraRuralDiesel').val(constantes.cualquieraruraldiesel);
$('#CualquieraInterurbanoDiesel').val(constantes.cualquierainterurbanodiesel);
// Motocicleta
$('#2tiemposUrbano').val(constantes._2tiemposurbano);
$('#2tiemposRural').val(constantes._2tiemposrural);
$('#2tiemposInterurbano').val(constantes._2tiemposinterurbano);
$('#4tiempos250Urbano').val(constantes._4tiempos250urbano);
$('#4tiempos250Rural').val(constantes._4tiempos250rural);
$('#4tiempos250Interurbano').val(constantes._4tiempos250interurbano);
$('#4tiempos250750Urbano').val(constantes._4tiempos250750urbano);
$('#4tiempos250750Rural').val(constantes._4tiempos250750rural);
$('#4tiempos250750Interurbano').val(constantes._4tiempos250750interurbano);
$('#4tiempos750Urbano').val(constantes._4tiempos750urbano);
$('#4tiempos750Rural').val(constantes._4tiempos750rural);
$('#4tiempos750Interurbano').val(constantes._4tiempos750interurbano);
};
}
function medidas(){
// conversion en unidades energeticas
// termia
var termia_kwh = 1.162;
var termia_kcal = 1000;
var termia_tep = Math.pow(10,-4);
var termia_julios = 4186799.94;
// kwh
var kwh_termia = 0.86;
var kwh_kcal = 859.85;
var kwh_tep = 8.6 * Math.pow(10,-5);
var kwh_julios = 3600000;
// kcal
var kcal_termia = Math.pow(10,-3);
var kcal_kwh = 1.16 * Math.pow(10,-3);
var kcal_tep = Math.pow(10,-7);
var kcal_julios = 4186.8;
// Tep
var tep_termia = 10000;
var tep_kwh = 11627.9;
var tep_kcal = 10000000;
var tep_julios = 41867999400;
// julios
var julios_termia = 2.39 * Math.pow(10,-7);
var julios_kwh = 2.78 * Math.pow(10,-7);
var julios_kcal = 2.39 * Math.pow(10,-4);
var julios_tep = 2.39 * Math.pow(10,-11);
// julio - TJ
// KWH * KWH_julios / Julios_TJ
var julios_TJ = Math.pow(10,12);
// NM3 - KWH
// NM3/ este
var nm3_kwh = 10.7056;
//alert((1605840 * kwh_julios / julios_TJ).toFixed(2));
}
function validar () {
var bandera = true;
$('input').each(function(){
if(isNaN($(this).val())){
$(this).focus();
bandera = false;
return false;
}
});
return bandera;
}
|
zlinker89/EmptySite
|
js/indexConfig.js
|
JavaScript
|
mit
| 10,301
|
(function($) {
'use strict';
var dateTimePicker = {
init: function() {
this.$picker = $('.js-date-time-picker');
this.config = $.extend(
true,
{
autoUpdateInput: false,
singleDatePicker: true,
locale: {
format: 'DD MMMM YYYY'
}
},
this.$picker.data('config')
)
this.$picker.daterangepicker(this.config);
this.bindEvents();
},
bindEvents: function() {
if (this.config.autoUpdateInput == false) {
this.$picker.bind('apply.daterangepicker', {
config: this.config,
p: this.$picker
}, function(ev, picker) {
ev.data.p.val(picker.startDate.format(ev.data.config.locale.format));
});
this.$picker.bind('cancel.daterangepicker', function(ev, picker) {
picker.val('');
});
}
}
};
window.PWPlanner = window.PWPlanner || {};
window.PWPlanner.dateTimePicker = dateTimePicker;
})(jQuery);
|
guidance-guarantee-programme/planner
|
app/assets/javascripts/date-time-picker.js
|
JavaScript
|
mit
| 1,014
|
import React, {
Component
} from 'react'
import {
observer
} from 'mobx-react'
import ProfileImage from './profile-image'
import {
observable
} from 'mobx'
import InlineInput from './inline-input'
import ImageUploader from './image-uploader'
import BoundInput from './bound-input'
import CategorySelect from './category-select'
import TargetSelect from './target-select'
import createTask from '../graphql/create-task'
import {
browserHistory
} from 'react-router'
import {
Card,
CardContent,
Columns,
Column,
Addons,
CardFooter,
Button
} from './bulma/index'
console.log(1)
|
capaj/vscode-exports-autocomplete
|
test/fixtures/some-file-with-imports.js
|
JavaScript
|
mit
| 598
|
module.exports = function(grunt) {
grunt.initConfig({
jsdoc : {
dist : {
src: [
'./*.js',
'README.md'
],
jsdoc: './node_modules/.bin/jsdoc',
options: {
destination: 'docs',
configure: './config/conf.json',
template: './node_modules/jsdoc-oblivion/template'
}
}
}
});
grunt.loadNpmTasks('grunt-jsdoc');
};
|
miguelmota/zoa
|
gruntfile.js
|
JavaScript
|
mit
| 424
|
import React from 'react'
import { storiesOf } from '@storybook/react'
import { number, select } from '@storybook/addon-knobs'
import { action } from '@storybook/addon-actions'
import { ChannelSummaryListItem } from 'components/Channels'
import { Provider } from '../../Provider'
const setSelectedChannel = action('setSelectedChannel')
storiesOf('Containers.Channels', module)
.addDecorator(story => <Provider story={story()} />)
.addWithChapters('ChannelSummaryListItem', {
chapters: [
{
sections: [
{
options: { allowPropTablesToggling: false },
sectionFn: () => {
const channel = {
chanId: 1,
displayName: 'lnd1.zaphq.io',
displayPubkey: '03cf5a37ed661e3c61c7943941834771631cd880985340ed7543ad79a968cea454',
channelPoint: '83c2839a4831c71d501ea41bdb0c3e01284bdb5302b1d16c9c52a876bd3ea6a7:1',
csvDelay: 2016,
numUpdates: 12,
localBalance: number('Local Balance', 150400),
remoteBalance: number('Remote Balance', 80044),
displayStatus: select(
'Status',
[
'open',
'pendingOpen',
'open',
'pendingClose',
'pendingForceClose',
'waitingClose',
'offline',
],
'open'
),
active: true,
}
const stateProps = {
channel,
}
const dispatchProps = {
setSelectedChannel,
}
return <ChannelSummaryListItem {...stateProps} {...dispatchProps} />
},
},
],
},
],
})
|
LN-Zap/zap-desktop
|
stories/containers/channels/channel-summary-list-item.stories.js
|
JavaScript
|
mit
| 1,866
|
describe("About Expects", function() {
// We shall contemplate truth by testing reality, via spec expectations.
it("should expect true", function() {
expect(true).toBeTruthy(); // This should be true
});
// To understand reality, we must compare our expectations against reality.
it("should expect equality", function() {
var expectedValue = 1 + 1;
var actualValue = 1 + 1;
expect(actualValue === expectedValue).toBeTruthy();
});
// Some ways of asserting equality are better than others.
it("should assert equality a better way", function() {
var expectedValue = 2;
var actualValue = 1 + 1;
// toEqual() compares using common sense equality.
expect(actualValue).toEqual(expectedValue);
});
// Sometimes you need to be precise about what you "type".
it("should assert equality with ===", function() {
var expectedValue = "2";
var actualValue = (1 + 1).toString();
// toBe() will always use === to compare.
expect(actualValue).toBe(expectedValue);
});
// Sometimes we will ask you to fill in the values.
it("should have filled in values", function() {
expect(1 + 1).toEqual(2);
});
});
|
dmoser49/javascript-koans
|
koans/AboutExpects.js
|
JavaScript
|
mit
| 1,173
|
/**
* 作者:黄鑫
* 日期:2013-03-07
* 描述:角色表单
*/
define(["dojo/_base/connect",
"dojo/_base/declare",
"capec/dialog/FormDialog",
"dojo/i18n!./nls/UserAutoExtAttrDialog",
"internal/widgets/comboBox/CodeComboBox",
"dijit/form/NumberSpinner",
"dijit/form/DateTextBox",
"dijit/form/Select",
"dijit/form/SimpleTextarea"], function($connect,$declare,$FormDialog,$i18n) {
return $declare($FormDialog,{
fid: "internal_sys_userautoextattr_UserAutoExtAttrForm",
title: $i18n.title_Create,
href: "sys/userautoextattr/userAutoExtAttrForm.html",
style: { height: "226px", width: "280px" },
_grid: null,
_store: null,
bindGrid: function($grid){
this._grid = $grid;
},
bindStore: function($store){
this._store = $store;
this._store.bindDialog(this);
},
_valid: function(){
var __frm = dijit.byId(this.fid);
return __frm.isValid();
},
_submit: function(){
if(this._valid()){
var __newItem = dijit.byId(this.fid).getValues();
if(this.model == "Create"){
console.log(__newItem);
this._store.newItem(__newItem);
}else{
this._store.setItem(__newItem);
}
}else{
dijit.byId(this.fid).validate();
}
},
_reset: function(){
if(this.model == "Create"){
dijit.byId(this.fid).reset();
}else{
this._setData();
}
},
_draw: function(){
console.log("绘制表单");
console.log("Ajax请求需同步或其他方式");
},
_setTitle: function(){
switch(this.model){
case "Create":
this.set("title",$i18n.title_Create);
break;
case "Update":
this.set("title",$i18n.title_Update);
break;
}
},
_setData: function(){
if(this.model == "Create"){
this._reset();
}else{
var __data = this._grid.getSelectItem();
if(__data == null) return;
dijit.byId(this.fid +"_idText").set("value", __data.i.id);
dijit.byId(this.fid +"_infoText").set("value", __data.i.info);
}
this._valid();
}
});
});
|
3203317/2013
|
dojo-cppt/sys/userautoextattr/UserAutoExtAttrDialog.js
|
JavaScript
|
mit
| 1,968
|
const axios = require('axios');
const DEFAULT_OPTIONS = {
limit: 100,
page: 0,
regex: /file_url=\"(.*?)\"/g,
base_url: 'http://gelbooru.com',
extra_args: 'page=dapi&s=post&q=index&',
endpoint: 'index.php',
page_arg: 'pid'
};
const createBooruFetcher = function(options) {
const fullOptions = Object.assign({}, DEFAULT_OPTIONS, options);
const {
limit,
page,
auth,
base_url,
extra_args,
endpoint,
page_arg,
regex,
prefix_base,
login,
key
} = fullOptions;
const getRequestURI = function(tags) {
let uri = `${base_url}/${endpoint}?${extra_args || ''}limit=${limit}&tags=${tags}&${page_arg}=${page}`;
if (auth) {
uri += `&login=${login}&api_key=${key}`;
}
return uri;
};
return function(tagArray) {
const tags = tagArray.map(encodeURIComponent).join('+');
const uri = getRequestURI(tags);
return axios.get(uri)
.then(({ data }) => {
const matches = data.match(regex);
return matches
? matches
.map(match => match.substring(10, match.length - 1))
.map(url => prefix_base ? base_url + url : url)
: Promise.resolve([]);
});
};
};
module.exports = {
createBooruFetcher
};
|
eltrufas/Chino
|
handlers/booruLookup/booru.js
|
JavaScript
|
mit
| 1,258
|
import { REQUEST_LOGIN, LOGGED_IN, AUTHENTICATED, REQUEST_LOGOUT, LOGGED_OUT, AUTH_CANCELLED } from '../actions/auth'
const initialState = {
authorized: false,
actionInProgress: false
}
export default function (state = initialState, action) {
switch (action.type) {
case AUTHENTICATED:
case LOGGED_IN:
return Object.assign({}, state, {
actionInProgress: false,
authorized: true,
authCodeRequired: false
})
case REQUEST_LOGIN:
case REQUEST_LOGOUT:
return Object.assign({}, state, {
actionInProgress: true
})
case LOGGED_OUT:
case AUTH_CANCELLED:
return Object.assign({}, state, {
actionInProgress: false,
authorized: false
})
default:
return state
}
}
|
mike182uk/xbl-friends
|
src/app/reducers/auth.js
|
JavaScript
|
mit
| 782
|
// Global namespace object
MeteorApp = {};
// Namespace variables
MeteorApp.listRanks = ['A', '2', '3', '4', '5', '6', '7', '8', '9', 'T', 'J', 'Q', 'K'];
MeteorApp.listSuits = ['D', 'C', 'H', 'S'];
MeteorApp.deck = [];
MeteorApp.initializeDeck;
MeteorApp.shuffleDeck;
// initialize deck
MeteorApp.initializeDeck = function() {
MeteorApp.deck = []; // clear existing deck
Session.set('deck', MeteorApp.deck);
_.forEach(MeteorApp.listRanks, function (rank) {
_.forEach(MeteorApp.listSuits, function (suit) {
MeteorApp.deck.push(rank + suit);
}); // end suits
}); // end ranks
Session.set('deck', MeteorApp.deck);
MeteorApp.setGameHands();
return MeteorApp.deck;
};
// shuffle deck
MeteorApp.shuffleDeck = function () {
MeteorApp.deck = _.shuffle(MeteorApp.deck);
Session.set('deck', MeteorApp.deck);
MeteorApp.setGameHands();
return MeteorApp.deck;
}
// set game hands, i.e. deal hands too players and game
MeteorApp.setGameHands = function() {
var deck = MeteorApp.deck;
// player1 hands
Session.set('player1-starting-hand', deck.slice(0, 5));
Session.set('player1-reserve-hand', deck.slice(5, 20));
// game hands
Session.set('game-reset1-hand', deck.slice(20, 25));;
Session.set('game-start1-hand', deck.slice(25, 26));
Session.set('game-start2-hand', deck.slice(26, 27));
Session.set('game-reset2-hand', deck.slice(27, 32));
// player 2 hands
Session.set('player2-starting-hand', deck.slice(32, 37));
Session.set('player2-reserve-hand', deck.slice(37, 52));
};
// Main start function
MeteorApp.initializeDeck();
/*
// Tracker autorun for debugging to console
Tracker.autorun(function () {
console.log('Contents of Deck: ' + Session.get('deck'));
});
*/
|
justinugerio/meteor-app
|
client/meteor-app.js
|
JavaScript
|
mit
| 1,796
|
/*
* fallback transition for turn in non-3D supporting browsers (which tend to handle complex transitions poorly in general
*/
//>>excludeStart("jqmBuildExclude", pragmas.jqmBuildExclude);
//>>description: Animation styles and fallback transitions definition for non-3D supporting browsers
//>>label: Turn Transition
//>>group: Transitions
//>>css.structure: ../../css/structure/jquery.mobile.transitions.turn.css
define( [ "../jquery", "../jquery.mobile.transition" ], function( $ ) {
//>>excludeEnd("jqmBuildExclude");
(function( $, window, undefined ) {
$.mobile.transitionFallbacks.turn = "fade";
})( jQuery, this );
//>>excludeStart("jqmBuildExclude", pragmas.jqmBuildExclude);
});
//>>excludeEnd("jqmBuildExclude");
|
trojanspike/jquery-mobile
|
js/transitions/turn.js
|
JavaScript
|
mit
| 725
|
define(["knockout", "text!./register.html", "require"], function (ko, registerTemplate, require) {
var tokenKey = "tokenInfo";
function RegisterViewModel(params) {
var self = this;
self.firstName = ko.observable("");
self.secondName = ko.observable("");
self.email = ko.observable("");
self.password = ko.observable("");
self.confirmPassword = ko.observable("");
self.register = function () {
$.ajax({
url: 'http://localhost:51952/api/account/register',
type: 'POST',
contentType: 'application/x-www-form-urlencoded',
data:
{
Email: self.email,
Password: self.password,
ConfirmPassword: self.confirmPassword,
FirstName: self.firstName,
SecondName: self.secondName
},
success: function (data) {
$("#error_message").hide();
$(".validation-summary-errors").hide();
//TODO: Create a method for this
sessionStorage.setItem(tokenKey, data.token);
sessionStorage.setItem("authorized", data.isAuthorized);
sessionStorage.setItem("username", data.firstName + " " + data.secondName);
sessionStorage.setItem("role", data.role);
//TODO: Rewrite code below this knockout. Do not use jQuery
$('#userpanel').find('#anonim').hide();
if (data.role == "Admin") {
$('#userpanel').find('#admin').show()
$('#userpanel').find('#admin').find("#user-name").text(sessionStorage.getItem("username"));
} else {
$('#userpanel').find('#user').show();
$('#userpanel').find('#user').find("#user-name").text(sessionStorage.getItem("username"));
}
window.location.href = "#";
console.log(sessionStorage.getItem(tokenKey));
},
error: function (data) {
var errors = [];
//TODO: Create a common component for error handling
$("#error_message").hide();
$(".validation-summary-errors").show();
var response = JSON.parse(data.responseText);
for (key in response.modelState) {
for (var i = 0; i < response.modelState[key].length; i++) {
errors.push(response.modelState[key][i]);
}
}
$("#error_details").text(" " + errors.join(" "));
if (errors.length > 0) {
$("#error_message").show();
$(".validation-summary-errors").hide();
}
}
});
}
return self;
}
return { viewModel: RegisterViewModel, template: registerTemplate };
});
|
BikeMates/bike-mates
|
BikeMates/BikeMates.Web/App/pages/account/register/register.js
|
JavaScript
|
mit
| 3,203
|
import r from 'rethinkdb';
export default async function(conn, numbers) {
await r.table('sequentialId').insert({
id: 'material',
number: numbers.material
}).run(conn);
await r.table('sequentialId').insert({
id: 'itemType',
number: numbers.item
}).run(conn);
await r.table('sequentialId').insert({
id: 'blockType',
number: numbers.block
}).run(conn);
console.log('Initialized all sequential IDs');
}
|
UnboundVR/metavrse-server
|
scaffold/fixtures/sequentialId.js
|
JavaScript
|
mit
| 441
|
/**
* API Routes
* @url /api/v1/[resource]
*/
// Notes
// RequestType Path Action
// ===================================================================
// GET /notes index
// POST /notes store
// GET /notes/{note} show
// PUT/PATCH /notes/{note} update
// DELETE /notes/{note} destroy
//
// Users
// RequestType Path Action
// ===================================================================
// GET /users index
// POST /users store
// GET /users/{note} show
// PUT/PATCH /users/{note} update
// DELETE /users/{note} destroy
const express = require('express');
const router = express.Router();
const noteApiController = require('../controllers/noteApi.controller');
const userApiController = require('../controllers/userApi.controller');
router.get('/notes', noteApiController.index);
router.post('/notes', noteApiController.store);
router.get('/notes/:id', noteApiController.show);
router.put('/notes/:id', noteApiController.update);
router.patch('/notes/:id', noteApiController.update);
router.delete('/notes/:id', noteApiController.destroy);
router.get('/users', userApiController.index);
router.post('/users', userApiController.store);
router.get('/users/:id', userApiController.show);
router.put('/users/:id', userApiController.update);
router.patch('/users/:id', userApiController.update);
router.delete('/users/:id', userApiController.destroy);
module.exports = router;
|
sasha7/notes-app
|
routes/api.js
|
JavaScript
|
mit
| 1,723
|
var express = require('express');
var path = require('path');
var favicon = require('serve-favicon');
var logger = require('morgan');
var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser');
var routes = require('./routes/index');
var app = express();
// view engine setup
//app.set('views', path.join(__dirname, 'views'));
//app.set('view engine', 'jade');
// uncomment after placing your favicon in /public
//app.use(favicon(__dirname + '/public/favicon.ico'));
app.use(logger('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));
app.use(function(req, res, next) {
res.header("Access-Control-Allow-Origin", "*");
res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
next();
});
app.use('/', routes);
// catch 404 and forward to error handler
app.use(function(req, res, next) {
var err = new Error('Not Found');
err.status = 404;
next(err);
});
// error handlers
// development error handler
// will print stacktrace
if (app.get('env') === 'development') {
app.use(function(err, req, res, next) {
console.log('error dev')
res.status(err.status || 500);
res.json({
message: err.message,
error: err
});
});
}
// // production error handler
// // no stacktraces leaked to user
app.use(function(err, req, res, next) {
console.log('error production')
res.status(err.status || 500);
res.json({
message: err.message,
error: {}
});
});
module.exports = app;
|
GeographicaGS/sevilla-developers
|
backend/src/sevilla-developers/app.js
|
JavaScript
|
mit
| 1,612
|
import DS from 'ember-data';
export default DS.Model.extend({
id: DS.attr("string"),
title: DS.attr("string"),
message: DS.attr("string"),
tags: DS.attr("string"),
url: DS.attr("string")
});
|
ArtooTrills/Babel
|
PolySimpleApp/app/models/ticket.js
|
JavaScript
|
mit
| 196
|
var configuration = require('../../../config/configuration.json')
var subcampaignModelCheckerLogic = require('../../subcampaign/subcampaignModelCheckerLogic')
module.exports = {
checkSubcampaignSettingModelForExistence: function (redisClient, accountHashID, campaignHashID, subCampaignHashID, callback) {
subcampaignModelCheckerLogic.checkSubcampaignModelForExistence(redisClient, accountHashID, campaignHashID, subCampaignHashID, function (err, result) {
if (err) {
callback(err, null)
return
}
callback(null, callback(null, configuration.message.subcampaign.setting.exist))
})
},
checkSubcampaignSettingModelForNotExistence: function (redisClient, accountHashID, campaignHashID, subCampaignHashID, callback) {
subcampaignModelCheckerLogic.checkSubcampaignModelForNotExistence(redisClient, accountHashID, campaignHashID, subCampaignHashID, function (err, result) {
if (err) {
callback(err, null)
return
}
callback(null, callback(null, configuration.message.subcampaign.setting.notExist))
})
}
}
|
Flieral/Announcer-Service
|
logic/setting/subcampaign/subcampaignSettingModelCheckerLogic.js
|
JavaScript
|
mit
| 1,089
|
var express = require('express');
var router = express.Router();
var _ = require('lodash');
var Promise = require('bluebird');
var security = require('../core/utils/security');
var models = require('../models');
var middleware = require('../core/middleware');
var accountManager = require('../core/services/account-manager')();
var AppError = require('../core/app-error')
var log4js = require('log4js');
var log = log4js.getLogger("cps:accessKey");
router.get('/', middleware.checkToken, (req, res, next) => {
log.debug('request get acceesKeys')
var uid = req.users.id;
accountManager.getAllAccessKeyByUid(uid)
.then((accessKeys) => {
log.debug('acceesKeys:', accessKeys)
res.send({accessKeys: accessKeys});
})
.catch((e) => {
next(e);
});
});
router.post('/', middleware.checkToken, (req, res, next) => {
var uid = req.users.id;
var identical = req.users.identical;
var createdBy = _.trim(req.body.createdBy);
var friendlyName = _.trim(req.body.friendlyName);
var ttl = parseInt(req.body.ttl);
var description = _.trim(req.body.description);
log.debug(req.body)
var newAccessKey = security.randToken(28).concat(identical);
return accountManager.isExsitAccessKeyName(uid, friendlyName)
.then((data) => {
if (!_.isEmpty(data)) {
throw new AppError.AppError(`The access key "${friendlyName}" already exists.`);
}
})
.then(() => {
return accountManager.createAccessKey(uid, newAccessKey, ttl, friendlyName, createdBy, description);
})
.then((newToken) => {
var moment = require("moment");
var info = {
name : newToken.tokens,
createdTime : parseInt(moment(newToken.created_at).format('x')),
createdBy : newToken.created_by,
expires : parseInt(moment(newToken.expires_at).format('x')),
description : newToken.description,
friendlyName: newToken.name,
};
log.debug(info);
res.send({accessKey:info});
})
.catch((e) => {
if (e instanceof AppError.AppError) {
log.debug(e)
res.status(406).send(e.message);
} else {
next(e);
}
});
});
router.delete('/:name', middleware.checkToken, (req, res, next) => {
var name = _.trim(decodeURI(req.params.name));
var uid = req.users.id;
return models.UserTokens.destroy({where: {name:name, uid: uid}})
.then((rowNum) => {
log.debug('delete acceesKey:', name)
res.send({friendlyName:name});
})
.catch((e) => {
if (e instanceof AppError.AppError) {
log.debug(e)
res.status(406).send(e.message);
} else {
next(e);
}
});
});
module.exports = router;
|
lisong/code-push-server
|
routes/accessKeys.js
|
JavaScript
|
mit
| 2,595
|
import React from 'react';
import ColorPicker from 'react-color-picker'; // https://www.npmjs.com/package/react-color-picker
import Extend from 'Extend';
import Utils from './Utils';
export default class ColorPickerCpt extends React.Component {
constructor(props) {
super(props);
let _scope = this;
_scope.state = {
color: props.color,
show: props.show
};
this.closeShow = this.closeShow.bind(this);
this.changeColor = this.changeColor.bind(this);
this.emitChangeColor = this.emitChangeColor.bind(this);
}
componentWillReceiveProps(nextProps){
this.setState(Extend.deep(
{},
this.state,
{...nextProps}
));
}
// componentWillUpdate
// componentWillUnmount(){
// console.log('** ** componentWillUnmount ** **');
// }
hideShow(){
this.setState(Extend.deep(
{},
this.state,
{show: false}
));
}
closeShow(){
this.hideShow();
this.props.onShowChanged(false);
}
changeColor( str_color ){
this.setState(Extend.deep(
{},
this.state,
{color: str_color}
));
}
emitChangeColor(){
let _scope = this;
_scope.props.onChange(_scope.state.color, {show:false});// 把關閉的功能將給外面來做
}
render(){
let _str_cn = (this.state.show===true)? 'pkg-colorpicker pkg-colorpicker_on' : 'pkg-colorpicker' ;
let _str_bg = this.state.color;
let _str_text = Utils.getPairColor(_str_bg);
return (
<div className={_str_cn}>
<div className="pkg-colorpicker-picker">
<ColorPicker
value={this.state.color}
onChange={this.changeColor}
saturationWidth={350}
saturationHeight={350}
hueWidth={30} />
<div className="pkg-colorpicker-action pkg-btnSection pkg-table wth-100pct">
<div className="pkg-table-row">
<div className="pkg-table-cell wth-50pct">
<span className="pkg-colorpicker-action-picked" style={{background:_str_bg, color:_str_text}}>{this.state.color}</span>
</div>
<div className="pkg-table-cell pkg-table-cell_right">
<button className="pkg-btnSection-btn ui-button ui-button_strong" onClick={this.emitChangeColor}>確定</button>
<button className="pkg-btnSection-btn ui-button ui-button_ignore" onClick={this.closeShow}>取消</button>
</div>
</div>
</div>
</div>
<span className="pkg-colorpicker-close ui-close" onClick={this.closeShow}></span>
</div>
);
}
}
ColorPickerCpt.propTypes = {
color: React.PropTypes.string,
onChange: React.PropTypes.func.isRequired,
onShowChanged: React.PropTypes.func.isRequired,
show: React.PropTypes.bool
},
ColorPickerCpt.defaultProps = {
control: '#fff',
onChange: ()=>{},
onShowChanged: ()=>{},
show: false
};
|
majofeechiou/drawing-board
|
src/js/ColorPickerCpt.js
|
JavaScript
|
mit
| 3,376
|
import React, {
Component,
PropTypes
} from 'react';
import Controls from './Controls';
import styles from './Player.css';
class Player extends Component {
static propTypes = {
renderVideo: PropTypes.func.isRequired,
play: PropTypes.func.isRequired,
addEventLister: PropTypes.func.isRequired,
nowPlaying: PropTypes.object.isRequired //eslint-disable-line react/forbid-prop-types
};
constructor() {
super();
this.state = {
progress: 0
};
}
componentDidMount() {
document.addEventListener('dragover', e => e.preventDefault());
document.addEventListener('drop', this.onDrop);
this.props.renderVideo(this.playerCanvas);
this.props.addEventLister('onPositionChanged', (position) => {
this.setState({
progress: position * 100
});
});
}
componentWillUnmount() {
document.removeEventListener('dragover', e => e.preventDefault());
document.removeEventListener('drop', this.onDrop);
}
onDrop = (e) => {
e.preventDefault();
this.props.play(`file://${e.dataTransfer.files[0].path}`);
};
render() {
return (
<div>
<Controls progress={this.state.progress} {...this.props.nowPlaying}/>
<canvas
className={styles.player}
ref={(playerCanvas) => { this.playerCanvas = playerCanvas; }}
id="splayer"
/>
</div>
);
}
}
export default Player;
|
thesabbir/splayer
|
app/components/Player.js
|
JavaScript
|
mit
| 1,421
|
import slider from '../ui/slider.js'
// --- Config & Local state ----------------------------------------------------
const dom = {
intervalsSlider: document.getElementById('timer-intervals-slider'),
timerSwitch: document.getElementById('timer')
}
let previousState = {}
let timer
// --- Main methods ------------------------------------------------------------
const init = (store) => {
const state = store.getState().timer
previousState = state
slider({
targetEl: dom.intervalsSlider,
leftButton: '<div class="icon icon--timer-slower">Slower</div>',
rightButton: '<div class="icon icon--timer-faster">Faster</div>',
items: state.intervalValues.map(x => x + 'ms'),
initialIndex: state.intervalValues.indexOf(state.interval),
callback: (index) => {
store.dispatch({ type: 'TIMER_INTERVAL_CHANGE', interval: state.intervalValues[index] })
}
})
store.subscribe(() => stateHandler(store))
dom.timerSwitch.addEventListener('change', () => store.dispatch({ type: 'TIMER_TOGGLE' }))
}
const stateHandler = (store) => {
const currentState = store.getState().timer
if (currentState.enabled !== previousState.enabled) {
timer = currentState.enabled
? startTimer(store, currentState.interval)
: window.clearInterval(timer)
dom.timerSwitch.checked = currentState.enabled
}
if (currentState.enabled && currentState.interval !== previousState.interval) {
timer = window.clearInterval(timer)
timer = startTimer(store, currentState.interval)
}
previousState = currentState
}
// --- Pure functions ----------------------------------------------------------
const startTimer = (store, interval) => {
return window.setInterval(() => {
store.dispatch({ type: 'WORLD_TICK' })
}, interval)
}
// --- Export ------------------------------------------------------------------
export default init
|
Hurtak/game-of-life
|
app/scripts/modules/timer.js
|
JavaScript
|
mit
| 1,885
|
/*
* jQuery File Upload Plugin JS Example 8.9.0
* https://github.com/blueimp/jQuery-File-Upload
*
* Copyright 2010, Sebastian Tschan
* https://blueimp.net
*
* Licensed under the MIT license:
* http://www.opensource.org/licenses/MIT
*/
/* global $, window */
$(function () {
'use strict';
// Initialize the jQuery File Upload widget:
$('#fileupload').fileupload({
disableImageResize: false,
// Uncomment the following to send cross-domain cookies:
//xhrFields: {withCredentials: true},
url: '/tmp/upload'
});
// Enable iframe cross-domain access via redirect option:
$('#fileupload').fileupload(
'option',
'redirect',
window.location.href.replace(
/\/[^\/]*$/,
'/cors/result.html?%s'
)
);
if (window.location.hostname === 'blueimp.github.io') {
// Demo settings:
$('#fileupload').fileupload('option', {
url: '//jquery-file-upload.appspot.com/',
// Enable image resizing, except for Android and Opera,
// which actually support image resizing, but fail to
// send Blob objects via XHR requests:
disableImageResize: /Android(?!.*Chrome)|Opera/
.test(window.navigator.userAgent),
maxFileSize: 5000000,
acceptFileTypes: /(\.|\/)(gif|jpe?g|png)$/i
});
// Upload server status check for browsers with CORS support:
if ($.support.cors) {
$.ajax({
url: '//jquery-file-upload.appspot.com/',
type: 'HEAD'
}).fail(function () {
$('<div class="alert alert-danger"/>')
.text('Upload server currently unavailable - ' +
new Date())
.appendTo('#fileupload');
});
}
} else {
// Load existing files:
$('#fileupload').addClass('fileupload-processing');
$.ajax({
// Uncomment the following to send cross-domain cookies:
//xhrFields: {withCredentials: true},
url: $('#fileupload').fileupload('option', 'url'),
dataType: 'json',
context: $('#fileupload')[0]
}).always(function () {
$(this).removeClass('fileupload-processing');
}).done(function (result) {
$(this).fileupload('option', 'done')
.call(this, $.Event('done'), {result: result});
});
}
});
|
martinengstrom/temporary_file_storage
|
static/jQuery-File-Upload-9.5.2/js/main.js
|
JavaScript
|
mit
| 2,519
|
import React from 'react';
import { Link } from 'react-router-dom';
import Checked from 'common/icons/Checked';
import Heading from 'common/base/Heading';
import P from 'common/base/P';
import Button from 'common/button/Button';
import styles from './VerificationPage.module.css';
const VerificationSuccess = () => (
<React.Fragment>
<Checked className={styles.checked} />
<Heading
size="m"
style={{
marginBottom: '20px',
}}
>
Email 認證成功
</Heading>
<P
size="m"
style={{
marginBottom: '28px',
}}
>
感謝你的驗證,未來有重大更新我們將 Email 通知你。
</P>
<Link to="/" title="GoodJob 職場透明化運動">
<Button
circleSize="lg"
btnStyle="black2"
style={{
marginBottom: '10px',
}}
>
返回首頁
</Button>
</Link>
</React.Fragment>
);
VerificationSuccess.propTypes = {};
export default VerificationSuccess;
|
goodjoblife/GoodJobShare
|
src/components/EmailVerification/VerificationSuccess.js
|
JavaScript
|
mit
| 1,012
|
const knex = require('knex')
const knexfile = require('../../api/knexfile')
const debug = require('debug')
const util = require('util')
const log = debug('app:db')
const env = process.env.NODE_ENV
const config = knexfile[env]
log(`Connected to ${config.client} with parameters: ${util.inspect(config.connection, { colors: true })}`)
module.exports = knex(config)
|
jancarloviray/graphql-react-starter
|
src/db/lib/db.js
|
JavaScript
|
mit
| 367
|
const { noop } = require('lodash');
const createTestCafe = require('../../../../lib');
const config = require('../../config');
const path = require('path');
const { expect } = require('chai');
const helper = require('./test-helper');
const { createReporter } = require('../../utils/reporter');
const DEFAULT_BROWSERS = ['chrome', 'firefox'];
let cafe = null;
const LiveModeController = require('../../../../lib/live/controller');
const LiveModeRunner = require('../../../../lib/live/test-runner');
const LiveModeKeyboardEventObserver = require('../../../../lib/live/keyboard-observer');
class LiveModeKeyboardEventObserverMock extends LiveModeKeyboardEventObserver {
_listenKeyEvents () {
}
}
class ControllerMock extends LiveModeController {
constructor (runner) {
super(runner);
this.logger = {
writeIntroMessage: noop,
writeStopRunningMessage: noop,
writeTestsFinishedMessage: noop,
writeRunTestsMessage: noop,
writeToggleWatchingMessage: noop,
writeExitMessage: noop,
};
}
_createKeyboardObserver () {
return new LiveModeKeyboardEventObserverMock();
}
}
class RunnerMock extends LiveModeRunner {
_createController () {
return new ControllerMock(this);
}
}
function createLiveModeRunner (tc, src, browsers = DEFAULT_BROWSERS) {
const { proxy, browserConnectionGateway, configuration } = tc;
const runner = new RunnerMock({
proxy,
browserConnectionGateway,
configuration: configuration.clone()
});
tc.runners.push(runner);
return runner
.src(path.join(__dirname, src))
.browsers(browsers)
.reporter(createReporter());
}
if (config.useLocalBrowsers && !config.useHeadlessBrowsers) {
describe('Live Mode', () => {
afterEach (() => {
helper.clean();
});
it('Smoke', () => {
const runCount = 2;
return createTestCafe('127.0.0.1', 1335, 1336)
.then(tc => {
cafe = tc;
})
.then(() => {
const runner = createLiveModeRunner(cafe, '/testcafe-fixtures/smoke.js');
helper.emitter.once('tests-completed', () => {
setTimeout(() => {
runner.controller.restart()
.then(() => {
runner.exit();
});
}, 1000);
});
return runner.run();
})
.then(() => {
expect(helper.counter).eql(DEFAULT_BROWSERS.length * helper.testCount * runCount);
return cafe.close();
});
});
it('Quarantine', () => {
return createTestCafe('127.0.0.1', 1335, 1336)
.then(tc => {
cafe = tc;
})
.then(() => {
const runner = createLiveModeRunner(cafe, '/testcafe-fixtures/quarantine.js');
helper.emitter.once('tests-completed', () => {
setTimeout(() => {
runner.exit();
}, 1000);
});
return runner.run({
quarantineMode: true
});
})
.then(() => {
expect(helper.attempts).eql(DEFAULT_BROWSERS.length * helper.quarantineThreshold);
return cafe.close();
});
});
it('Client scripts', () => {
return createTestCafe('127.0.0.1', 1335, 1336)
.then(tc => {
cafe = tc;
})
.then(() => {
const runner = createLiveModeRunner(cafe, '/testcafe-fixtures/client-scripts.js', ['chrome']);
helper.emitter.once('tests-completed', () => {
setTimeout(() => {
runner.controller.restart().then(() => {
expect(Object.keys(helper.data).length).eql(2);
expect(helper.data[0]).eql(true);
expect(helper.data[1]).eql(true);
runner.exit();
});
}, 1000);
});
return runner.run();
})
.then(() => {
return cafe.close();
});
});
it('Same runner stops and then runs again with other settings', function () {
let finishTest = null;
const promise = new Promise(resolve => {
finishTest = resolve;
});
createTestCafe('localhost', 1337, 1338)
.then(tc => {
cafe = tc;
const runner = createLiveModeRunner(cafe, '/testcafe-fixtures/test-1.js', ['chrome']);
setTimeout(() => {
return runner.stop()
.then(() => {
helper.emitter.once('tests-completed', () => {
runner.exit();
});
return runner
.browsers(['firefox'])
.src(path.join(__dirname, '/testcafe-fixtures/test-2.js'))
.run()
.then(() => {
return cafe.close();
})
.then(() => {
finishTest();
});
});
}, 10000);
return runner
.run();
});
return promise;
});
});
}
|
AndreyBelym/testcafe
|
test/functional/fixtures/live/test.js
|
JavaScript
|
mit
| 6,348
|
import { moduleFor, test } from 'ember-qunit';
import { Duration } from 'ember-joda';
moduleFor('transform:duration', 'Unit | Transform | duration');
const fixtureSerialized = 'PT12H';
const fixtureDeserialized = Duration.ofHours(12);
test('it exists', function(assert) {
const transform = this.subject();
assert.ok(transform);
});
test('it correctly serializes data', function(assert) {
const transform = this.subject();
const serialized = transform.serialize(fixtureDeserialized);
assert.strictEqual(serialized, fixtureSerialized);
});
test('it throws an error when trying to serialize a mismatching type', function(assert) {
const transform = this.subject();
assert.throws(() => {
transform.serialize({});
}, /DurationTransform/);
});
test('it serializes as null, when trying to serialize a null or undefined value', function(assert) {
const transform = this.subject();
assert.equal(transform.serialize(null), null);
assert.equal(transform.serialize(), null);
});
test('it correctly deserializes data', function(assert) {
const transform = this.subject();
const deserialized = transform.deserialize(fixtureSerialized);
assert.ok(fixtureDeserialized.equals(deserialized));
});
|
buschtoens/ember-joda
|
tests/unit/transforms/duration-test.js
|
JavaScript
|
mit
| 1,220
|
/* ==========================================================================
* ./src/shared/reducers/terminal.js
*
* Terminal Reducer
* ========================================================================== */
import _ from 'lodash';
import {
EXECUTE_COMMAND,
PREVIOUS_COMMAND,
DELETE_REDIRECT,
TAB_COMPLETE
} from 'src/shared/actions/terminal';
import { HELP_RESPONSE } from 'src/shared/api/commands';
const defaultTerminalState = {
executed: [
{
command: 'help',
path: '/',
response: HELP_RESPONSE
}
],
path: '/',
render: true,
selector: 0,
prevSelector: 0,
tab: ''
};
function randomNum() {
return Math.random();
}
export default function terminal(state = defaultTerminalState, action) {
switch (action.type) {
case EXECUTE_COMMAND:
const newState = _.clone(state);
const response = action.res.response;
const isClear = response === 'clear';
const executed = isClear ? [] : _.clone(newState.executed);
if (!isClear) {
executed.push({
command: action.command,
path: state.path,
response: response.message
});
}
if (response.path) {
newState.path = response.path;
}
if (response.redirect) {
newState.redirect = response.redirect;
}
newState.executed = executed;
newState.render = true;
newState.timestamp = (new Date()).toString() + randomNum().toString();
newState.selector = 0;
newState.prevSelector = 0;
newState.tab = '';
return newState;
case PREVIOUS_COMMAND:
const previousCommandState = _.clone(state);
if (action.up) {
if (state.selector + 1 <= state.executed.length) {
previousCommandState.selector += 1;
}
} else if (state.selector - 1 >= 0) {
previousCommandState.selector -= 1;
}
previousCommandState.prevSelector = state.selector;
previousCommandState.tab = '';
return previousCommandState;
case TAB_COMPLETE:
const tabState = _.clone(state);
tabState.tab = action.res.message || '';
return tabState;
case DELETE_REDIRECT:
const deleteDirectState = _.clone(state);
deleteDirectState.render = false;
delete deleteDirectState.redirect;
deleteDirectState.tab = '';
return deleteDirectState;
default:
return state;
}
}
|
cle1994/personal-website
|
src/shared/reducers/terminal.js
|
JavaScript
|
mit
| 2,425
|
import Vue from 'vue'
import Vuex from 'vuex'
Vue.use(Vuex);
// Retrieve the pokedex
import PokeDex from '../data/pokedex';
Vue.use(Vuex)
export default new Vuex.Store({
// Define the state
state: {
pokedex: PokeDex,
opponent: {
pokemon: {},
hp: 0
},
player: {
pokemon: {},
hp: 0
}
},
getters: {
// Retrieve a list of attack names from the opponent
// $store.getters.opponentAttacks
opponentAttacks(state) {
return Object.keys(state.opponent.pokemon.attacks);
},
// Retrieve a list of attack names from the player
// $store.getters.playerAttacks
playerAttacks(state) {
return Object.keys(state.player.pokemon.attacks);
}
},
mutations: {
// The payload should always be an object with a 'type' and 'hp' property
// commit('setHP', {type: 'player', hp: 6})
setHP(state, {type, hp})
{
state[type].hp = hp;
},
// Assign the opponent a pokemon based on a pokedexId
// commit('setOpponentPokemon', pokedexId)
setOpponentPokemon(state, pokedexId)
{
state.opponent.pokemon = state.pokedex[pokedexId];
state.opponent.hp = state.pokedex[pokedexId].stats.hp;
},
// Assign the player a pokemon based on a pokedexId
// commit('setPlayerPokemon', pokedexId)
setPlayerPokemon(state, pokedexId)
{
state.player.pokemon = state.pokedex[pokedexId];
state.player.hp = state.pokedex[pokedexId].stats.hp;
},
},
actions: {
// Reset a battle, this means choosing new pokemon with ful HP
// dispatch('reset')
reset({commit, state}) {
// Build an array with all the pokedex keys
let pokedexKeys = [];
for(let i=0; i<state.pokedex.length;i++)
{
pokedexKeys.push(i);
}
// Select a random pokedex entry & set the player pokemon
const playerPokemonId = Math.floor(Math.random() * pokedexKeys.length)
commit('setPlayerPokemon', pokedexKeys[playerPokemonId]);
// Remove the selected key
pokedexKeys.splice(playerPokemonId, 1);
// Select a random pokedex entry & set the opponent pokemon
const opponentPokemonId = Math.floor(Math.random() * pokedexKeys.length)
commit('setOpponentPokemon', pokedexKeys[opponentPokemonId]);
}
}
});
|
happyDemon/learning-vue-through-pokemon
|
src/store/index.js
|
JavaScript
|
mit
| 2,599
|
'use strict';
// Test specific configuration
// ===========================
module.exports = {
// MongoDB connection options
mongo: {
uri: 'mongodb://localhost/gateway-test'
},
sequelize: {
uri: 'sqlite://',
options: {
logging: false,
storage: 'test.sqlite',
define: {
timestamps: false
}
}
}
};
|
m-enochroot/websync
|
server/config/environment/test.js
|
JavaScript
|
mit
| 355
|
(function () {
"use strict";
angular
.module('astInterpreter')
.factory('l10.evaluateFactory',
[ 'l10.environmentFactory',
'l10.valueFactory', 'l8.evalErrorFactory', 'l10.IPEPFactory', 'l10.consCellFactory',
function(environmentFactory, valueFactory, evalErrorFactory, IPEPFactory, consCellFactory) {
//Be careful of code breaking due to angular module name!!!
var EvalError = evalErrorFactory.EvaluationError;
var Environment = environmentFactory.Environment;
var Value = valueFactory.Value;
var IPEP = IPEPFactory.IPEP;
var ConsCell = consCellFactory.ConsCell;
//var EvalError = evalErrorFactory.EvaluationError;
function Evaluate(scope) {
//don't set this variable to 1 when running large programs
//can cuase stack overflows due to large environments!!
this.DEBUG = 0; //always keep this set to zero when running on Angularjs!
var self = this;
this.globalEnv = null;
this.env = null;
var traverseColor = "#14A84A"; // defualt color to use when highlighting the current node or: "#14A84A" "#3885A8"
var id = 0; //used for the animation of nodes //color codes from http://color.adobe.com //^green ^light-blue
this.evaluate = function (tree) {
//throws EvalError
return this.evaluateProg(tree);
}//evaluate()
this.evaluateProg = function (tree) {
//var result := Value
var result = null;
// Instantiate the global environment
// (it will always be at the end of the
// environment chain).
this.globalEnv = new Environment(scope, null, "Global Env");
this.env = this.globalEnv;
//emit a "envStackPush" event
scope.main.addAnimationData({'name': "envStackPush",
data: {
'id': self.globalEnv.id,
'label': self.globalEnv.label,
}
});
// Check whick kind of Prog we have.
if (!(tree.element === "prog")) {
//emit a "nodeTraversal" event
scope.main.addAnimationData({'name': "nodeTraversal",
data: {
'id': tree.numId,
'color': traverseColor,
'node': tree.element,
}
});
// Evaluate the single expression.
//console.log("calling evaluateExp");
result = this.evaluateExp(tree);
}
else {
//emit a "nodeTraversal" event
scope.main.addAnimationData({'name': "nodeTraversal",
data: {
'id': tree.numId,
'color': traverseColor,
'node': tree.element,
}
});
// Evaluate each Fun or Exp in the Prog.
// Any Fun will have the side effect of putting
// a function name in the global environment.
// Any Var expressions will have the side effect
// of putting a variable in the environment chain.
// Any Set expressions will have the side effect
// of changing a value in the environment chain.
// Any Print expressions will have the side effect
// of printing an output.
// Any other expressions would be pointless!
for (var i = 0; i < tree.degree() - 1 ; i++) {
//if (tree.getSubTree(i).element === "fun") {
// scope.main.addAnimationData({'name': "nodeTraversal",
// data: {
// 'id': tree.getSubTree(i).numId,
// 'color': traverseColor,
// 'node': tree.getSubTree(i).element,
// }
// });
// this.handleFun(tree.getSubTree(i));
//}
//else {
this.evaluateExp(tree.getSubTree(i));
//}
}
// Evaluate the last expression and use its
// value as the value of the prog expression.
result = this.evaluateExp(tree.getSubTree(tree.degree() - 1));
}
return result;
}//evaluateProg()
/**
Handle a function definition. Notice that the return type
is void since Fun isn't an expression.
This method mutates the global environment object.
The Value object put into the environment by this method
has the tag "lambda" and its value field is a reference
to the function's "lambda expression".
*/
//this.handleFun = function (tree) {
// //throws EvalError
//
// //get the function name
// var name = tree.getSubTree(0).element;
// //emit a "nodeTraversal" event
// scope.main.addAnimationData({'name': "nodeTraversal",
// data: {
// 'id': tree.getSubTree(0).numId,
// 'color': traverseColor,
// 'node': name,
// }
// });
//
// // check if this function has already been defined
// if (this.env.definedLocal(name)) {
// //emit a "envLocalSearch" event
// throw new EvalError("function already exists: " + name);
// }
//
// // get the "lambda expression" (the function value)
//
// //var lambda := Tree
// var lambda = tree.getSubTree(1);
// scope.main.addAnimationData({'name': "nodeTraversal",
// data: {
// 'id': lambda.numId,
// 'color': traverseColor,
// 'node': lambda.element,
// }
// });
//
// // check if the definition really is a function
// if (!(lambda.element === "lambda")) {
// throw new EvalError("bad function definition: " + tree);
// }
//
// // create a function Value and
// // add a <name, lambda> pair to the environment
// this.env.add(name, new Value(lambda));
// //emit an "envAdd" event
// //note: handled in the environmentFactory.js file
//
// if (this.DEBUG > 0) {
// // for debugging purposes
// document.body.innerHTML += "<pre>" + this.env + "</pre>";
// }
//}//handleFun()
//Evaluate an expression
this.evaluateExp = function (tree) {
//throws EvalError
//console.log(tree + "evaluateExp param");
var result = null;
var node = tree.element;
if (node === "list") {
scope.main.addAnimationData({'name': "nodeTraversal",
data: {
'id': tree.numId,
'color': traverseColor,
'node': node,
},
});
result = this.evaluateList(tree);
}
else if (node === "sym") {
scope.main.addAnimationData({'name': "nodeTraversal",
data: {
'id': tree.numId,
'color': traverseColor,
'node': node,
},
});
result = this.evaluateSymbol(tree);
}
else if ( (node === "car")
|| (node === "cdr")
|| (node === "cons")
|| (node === "empty?") ) {
//emit "nodeTraversal" event
scope.main.addAnimationData({'name': "nodeTraversal",
data: {
'id': tree.numId,
'color': traverseColor,
'node': node,
},
});
result = this.evaluateListOp(tree);
}
else if (node === "fun") {
scope.main.addAnimationData({'name': "nodeTraversal",
data: {
'id': tree.numId,
'color': traverseColor,
'node': node,
},
});
result = this.evaluateFun(tree);
}
else if (node === "lambda") {
scope.main.addAnimationData({'name': "nodeTraversal",
data: {
'id': tree.numId,
'color': traverseColor,
'node': node,
},
});
result = this.evaluateLambda(tree);
}
else if (node === "apply") {
scope.main.addAnimationData({'name': "nodeTraversal",
data: {
'id': tree.numId,
'color': traverseColor,
'node': node,
},
});
result = this.evaluateApply(tree);
}
else if (node === "if") {
//emit "nodeTraversal" event
scope.main.addAnimationData({'name': "nodeTraversal",
data: {
'id': tree.numId,
'color': traverseColor,
'node': node,
},
});
result = this.evaluateIf(tree);
}
else if (node === "while") {
//emit "nodeTraversal" event
scope.main.addAnimationData({'name': "nodeTraversal",
data: {
'id': tree.numId,
'color': traverseColor,
'node': node,
},
});
result = this.evaluateWhile(tree);
}
else if (node === "set") {
//emit "nodeTraversal" event
scope.main.addAnimationData({'name': "nodeTraversal",
data: {
'id': tree.numId,
'color': traverseColor,
'node': node,
},
});
result = this.evaluateSet(tree);
}
else if (node === "begin") {
//emit "nodeTraversal" event
scope.main.addAnimationData({'name': "nodeTraversal",
data: {
'id': tree.numId,
'color': traverseColor,
'node': node,
},
});
result = this.evaluateBegin(tree);
}
else if (node === "var") {
//emit "nodeTraversal" event
scope.main.addAnimationData({'name': "nodeTraversal",
data: {
'id': tree.numId,
'color': traverseColor,
'node': node,
},
});
result = this.evaluateVar(tree);
}
else if (node === "print") {
//emit "nodeTraversal" event
scope.main.addAnimationData({'name': "nodeTraversal",
data: {
'id': tree.numId,
'color': traverseColor,
'node': node,
},
});
result = this.evaluatePrint(tree);
}
else if ((node === "&&") || (node === "||") || (node === "!")) {
//emit "nodeTraversal" event
scope.main.addAnimationData({'name': "nodeTraversal",
data: {
'id': tree.numId,
'color': traverseColor,
'node': node,
},
});
result = this.evaluateBexp(tree) //boolean expression
}
else if ((node === "<") || (node === ">")
|| (node === "<=") || (node === ">=")
|| (node === "==") || (node === "!=")) {
//emit "nodeTraversal" event
scope.main.addAnimationData({'name': "nodeTraversal",
data: {
'id': tree.numId,
'color': traverseColor,
'node': node,
},
});
result = this.evaluateRexp(tree); //relational operator
}
else if ((node === "+") || (node === "-")
|| (node === "*") || (node === "/")
|| (node === "%") || (node === "^")) {
//emit "nodeTraversal" event
scope.main.addAnimationData({'name': "nodeTraversal",
data: {
'id': tree.numId,
'color': traverseColor,
'node': node,
},
});
result = this.evaluateAexp(tree); //arithmetic expression
}
else if (tree.degree() === 0) {
if ((node === "true") || (node === "false")) {
//emit "nodeTraversal" event
scope.main.addAnimationData({'name': "nodeTraversal",
data: {
'id': tree.numId,
'color': traverseColor,
'node': node,
},
});
result = new Value(node === "true");
}
else if (node.match(/^[-]*[0-9][0-9]*/)) {
//emit "nodeTraversal" event
scope.main.addAnimationData({'name': "nodeTraversal",
data: {
'id': tree.numId,
'color': traverseColor,
'node': node,
},
});
result = new Value(parseInt(node, 10));
}
else if (this.env.defined(node, false)) { // a variable
//since env.defined is basically a wrapper function
//for env.lookUp we will only emit one event
//I need to think about how this will work
//emit "nodeTraversal" event
scope.main.addAnimationData({'name': "nodeTraversal",
data: {
'id': tree.numId,
'color': traverseColor,
'node': node,
},
});
//emit "envSearch" event
result = this.env.lookUp(node, true);
}
else {
//runtime check
throw new EvalError("undefined variable: " + node + "\n");
}
}
else {
throw new EvalError("invalid expression: " + tree + "\n");
}
return result;
}//EvaluateExp()
//Evaluate a list literal
this.evaluateList = function(tree){
var result = new Value(); //create an empty list
// fill up the list (notice that we work from right to left in the list)
for( var i = tree.degree() - 1; i >= 0; i--){
var element = tree.getSubTree(i).element;
if((tree.getSubTree(i).degree() !== 0) || (element === "list")){
result.valueCC = new ConsCell(this.evaluateExp(tree.getSubTree(i)), result.valueCC);
}
else {
var value;
if (element.match(/^[0-9][0-9]*/)) {
value = new Value(parseInt(element, 10));
}
else if ((element === "true") || (element === "false")) {
value = new Value(element === "true");
}
else if (this.env.defined(element)) {
value = this.env.lookUp(element);
}
else {
// unevaluated string (a "symbol")
value = new Value(element);
}
result.valueCC = new ConsCell(value, result.valueCC);
}
}
console.log("Created a new list:");
console.log(result.toString());
return result;
}
// Evaluate a symbol literal
this.evaluateSymbol = function(tree){
//throws EvalError
return new Value(tree.getSubTree(0).element);
}
/**
* Apply a list operation to the actual parameters
* contained in the child nodes of the tree.
*/
this.evaluateListOp = function(tree){
//throws EvalError
var result = null;
var op = tree.element;
if (op === "car") {
var list = this.evaluateExp(tree.getSubTree(0));
if (!(list.tag === list.LIST_TAG)) {
throw new EvalError("car: argument is not a list: " + list);
}
if (list.valueCC === null) {
throw new EvalError("car: argument is an empty list: " + list);
}
else {
result = list.valueCC.car;
}
}
else if (op === "cdr"){
var list = this.evaluateExp(tree.getSubTree(0));
if (!(list.tag === list.LIST_TAG)) {
throw new EvalError("cdr: argument is not a list: " + list);
}
if (list.valueCC === null) {
throw new EvalError("cdr: argument is an empty list: " + list);
}
else {
result = new Value(list.valueCC.cdr);
}
}
else if (op === "cons") {
var list = this.evaluateExp(tree.getSubTree(1));
if (!(list.tag === list.LIST_TAG)) {
throw new EvalError("cons: 2nd argument is not a list: " + list);
}
else {
var car = this.evaluateExp(tree.getSubTree(0));
result = new Value(new ConsCell(car, list.valueCC));
console.log("Added a new element to the list. List contains:");
console.log(result.toString());
}
}
else if (op === "empty?") {
var list = this.evaluateExp(tree.getSubTree(0));
if (!(list.tag === list.LIST_TAG)) {
throw new EvalError("empty?: argument is not a list: " + list);
}
else {
result = new Value(list.valueCC === null);
}
}
else {
// shouldn't get here
throw new EvalError("illegal list function: " + op);
}
return result;
}
/**
Evalute a function definition expression.
This method mutates the current local environment object.
The Value object put into the environment by this method
has the tag "lambda" and its value field is a reference
to an IPEP object.
An IPEP object is usually called a "closure" and it contains
two references. The first reference in a closure is an IP
(an "Instruction Pointer") and the other a reference is an EP
(an "Environment Pointer"). The IP reference refer's to the
function's lambda expression (its "instructions"). The EP
reference refer's to the function's outer scope, the scope
that is needed for looking up the function's non-local references.
Since functions in this language can be nested, the function's
outer scope need no longer be the global environment (as it was
in the previous languages). The function's outer scope is whatever
local environment is being used at the time this evaluateFun()
is called.
*/
this.evaluateFun = function (tree){
/**** Language_9 change (1) ***/
//throws EvalError
var result = null; /*** Language_9 change (2) ***/
// get the function name
var name = tree.getSubTree(0).element;
scope.main.addAnimationData({'name': "nodeTraversal",
data: {
'id': tree.getSubTree(0).numId,
'color': traverseColor,
'node': name,
}
});
// check if this function has already been defined
if (this.env.definedLocal(name)) {
throw new EvalError("function already exists: " + name);
}
// get the "lambda expression" (the function's IP)
var lambda = tree.getSubTree(1);
// check if the definition really is a function
if (!(lambda.element === "lambda")) {
throw new EvalError("bad function definition: " + tree);
}
result = this.evaluateLambda(lambda);
// add the <name, value> pair to the environment
this.env.add(name, result); /*** Language_9 change (6) ***/
//if (DEBUG > 0) {
// // for debugging purposes
// document.body.innerHTML += "<pre>" + env + "</pre>";
//}
return result; /*** Language_9 change (7) ***/
}//evaluateFun()
this.evaluateLambda = function(tree){
//throws EvalError
var result = null;
// get the "lambda expression" (the function's IP)
var lambda = tree;
// check if the definition really is a function
if (!(lambda.element === "lambda")) {
throw new EvalError("bad function definition: " + tree);
}
// get a reference to the current local Environment object (the function's EP)
var ep = this.env; /*** Language_9 change (3) ***/
// create an IPEP object (a closure)
var ipep = new IPEP(lambda, ep); /*** Language_9 change (4) ***/
// create the return value
result = new Value(ipep); /*** Language_9 change (5) ***/
console.log("IPEP really is an IPEP?");
console.log(ipep instanceof IPEP);
return result;
}
/**
This method "applies" a function value to actual parameters.
This method evaluates the body of the function in an environment
that binds the actual parameter values (from this function application)
to the formal parameters (from the function's lambda expression).
Since this language allows nested functions, the function's outer
scope (where the function finds its non-local references) may no
longer be the global Environment object. The function's closure
(the IPEP object that is the functions "value") points us to the
Environment object that the function should use for non-local
references.
*/
this.evaluateApply = function (tree) {
//throw EvalError
// Evaluate the apply's first parameter to a function value,
/*1*/
var funValue = this.evaluateExp(tree.getSubTree(0));
// check that what we are applying really is a function,
if (!(funValue.tag === funValue.LAMBDA_TAG)) {
//runtime check
throw new EvalError("bad function value: " + tree);
}
// get a reference to the function's closure
var ipep = funValue.valueL; /*** Language_8 change (1) ***/
// and to the function's "lambda expression" and its "nesting link".
var lambda = ipep.ip; /*** Language_8 change (2) ***/
var ep = ipep.ep; /*** Language_8 change (3) ***/
// Check that the number of actual parameters
// is equal to the number of formal parameters.
// (Actually, all we really need to know is that
// the number of actual parameters is at least
// the number of formal parameters.)
if (tree.degree() !== lambda.degree()) {
//runtime check
throw new Evalerror("wrong number of parameters: " + tree);
}
// Create a new environment object that is "nested"
// in this function's outer environment (lexical scope).
// This environment is used to bind actual parameter
// values to formal paramter names.
/*2*/
var localEnv = new Environment(scope, ep, "Function Activation");
//emit "envStackPush" event
//I might need to create a new event emitter named envStackPushFun
//with a reference to the enclosing ep.id
scope.main.addAnimationData({'name': "envStackPush",
data: {
'id': localEnv.id,
'label': localEnv.label,
'epId': ep.id, //added a link to the environment pointer's id for drawing Bezier curves.
}
});
// Bind, in the new environment object, the actual parameter
// values to the formal parameter names.
/*3*/
for (var zz = 1; zz < tree.degree() ; zz++) {
// iterate through the actual parameters
// Evaluate, using the current environment chain
// (NOT the new local environment object)
// an actual parameter expression's value.
/*4*/
var actualParamValue = this.evaluateExp(tree.getSubTree(zz));
// Retrieve, from within the lambda expression,
// a formal parameter name.
/*5*/
var formalParamName = lambda.getSubTree(zz - 1).element;
//emit a "nodeTraversal" event
scope.main.addAnimationData({'name': "nodeTraversal",
data: {
'id': lambda.getSubTree(zz - 1).numId,
'color': traverseColor,
'node': formalParamName,
},
});
//console.log("Formal name : " + formalParamName);
// Bind, in the new local environment object, the actual
// paramter value to a formal parameter name.
/*6*/
localEnv.add(formalParamName, actualParamValue);
//emit "envAdd" event; I don't believe we need an event emitter here
}
if (this.DEBUG > 0) {
document.body.innerHTML += "<pre>" + localEnv + "</pre>";// for debugging purposes
}
// Evaluate the body of the lambda expression using the
// new environment (which contains the binding of the actual
// parameter values to the function's formal parameter names).
/*7*/
var originalEnv = this.env;
//ask Professor Kraft to draw a diagram of this code behavior on paper.
/*8*/
this.env = localEnv;
/*9*/
var result = this.evaluateExp(lambda.getSubTree(tree.degree() - 1));
// Finally, restore the environment chain.
/*10*/
this.env = originalEnv;
scope.main.addAnimationData({'name': "envStackPop",
data: {
'id': localEnv.id,
'label': localEnv.label,
'closure': result.tag === 'lambda',
'epId': result.tag === 'lambda' ? ep.id : null,
}
});
// emit "envRemove" event?
return result;
}//evaluateApply()
//Evaluate an if-expression
this.evaluateIf = function (tree) {
if (3 !== tree.degree()) {
//runtime check
throw new EvalError("incorrect conditional expression: " + tree + "\n");
}
//var result := Value
var result = null;
var conditionalExp = this.evaluateExp(tree.getSubTree(0));
//do a runtime check
if (!(conditionalExp.tag === conditionalExp.BOOL_TAG)) {
throw new EvalError("illegal boolean expression: " + tree);
}
if (conditionalExp.valueB) {
result = this.evaluateExp(tree.getSubTree(1));
}
else {
result = this.evaluateExp(tree.getSubTree(2));
}
return result;
}//evaluateIf()
//Evalaute a while-loop expression
this.evaluateWhile = function (tree) {
//throws EvalError
if (2 !== tree.degree()) {
throw new EvalError("incorrect while expression: " + tree + "\n");
}
//var result := Value
var result = null;
//evaluate the boolean condition
var conditionalExp = this.evaluateExp(tree.getSubTree(0));
//do a runtime type check
if (!(conditionalExp.tag === conditionalExp.BOOL_TAG)) {
throw new EvalError("illegal boolean expression: " + tree);
}
while (conditionalExp.valueB) {
//evaluate the body of the loop (for its side effects)
this.evaluateExp(tree.getSubTree(1));
// re-evaluate the boolean condition
conditionalExp = this.evaluateExp(tree.getSubTree(0));
//do a runtime type check
if (!(conditionalExp.tag === conditionalExp.BOOL_TAG)) {
throw new EvalError("illegal boolean expression: " + tree);
}
}
// always return false for a while-loop expression
result = new Value(false);
return result;
}//evaluateWhile()
// Evaluate a set expression
this.evaluateSet = function (tree) {
//throws EvalError
var result = null;
//get the variable
var variable = tree.getSubTree(0).element;
//emit an "nodeTraversal" event
scope.main.addAnimationData({'name': "nodeTraversal",
data: {
'id': tree.getSubTree(0).numId,
'color': traverseColor,
'node': variable,
},
});
// check if this variable has already been declared
if (!this.env.defined(variable, true)) {
//runtime check
throw new EvalError("undefined variable: " + variable);
}
// get, and then evaluate, the expression
var expr = tree.getSubTree(1);
result = this.evaluateExp(expr);
// update this variable in the environment
this.env.update(variable, result);
if (this.DEBUG > 0) {
document.body.innerHTML += "<pre>" + this.env + "</pre>"; // for debugging purposes
}
return result;
}
this.evaluateBegin = function (tree) {
//var result := Value
var result = null;
// Create a new Environment object chained to (or "nested in")
// the previous (:outer") environment object.
var previousEnv = this.env;
this.env = new Environment(scope, previousEnv, "Local (begin)");
scope.main.addAnimationData({'name': "envStackPush",
data: {
'id': self.env.id,
'label': self.env.label,
'epId': previousEnv.id,
}
});
// Evaluate each sub expression in the begin
// expression (using the new environment chain).
// The return value of each expression is
// discarded, so any expression without a
// side-effect is worthless.
for (var i = 0; i < tree.degree() - 1; i++) {
this.evaluateExp(tree.getSubTree(i));
}
// Evaluate the last expression and use its
// value as the value of the begin expression.
result = this.evaluateExp(tree.getSubTree(tree.degree() - 1));
scope.main.addAnimationData({'name': "envStackPop",
data: {
'id': self.env.id,
'label': self.env.label,
'closure': result.tag === 'lambda',
'epId': result.tag === 'lambda' ? previousEnv.id : null,
}
});
this.env = previousEnv; // Just before this method returns, we remove from the
// chain of Environment objects the local Environment
// object we created at the beginning of this method.
// The local Environment object becomes a garbage object,
return result;
}//evaluateBegin()
//Evaluate a var expression
this.evaluateVar = function (tree) {
//throws EvalError
if (2 !== tree.degree()) {
//runtime check
throw new EvalError("wrong number of arguments: " + tree + "\n");
}
//var result := Value
var result = null;
//get the variable
var variable = tree.getSubTree(0).element;
// emit "nodeTraversal" event
scope.main.addAnimationData({'name': "nodeTraversal",
data: {
'id': tree.getSubTree(0).numId,
'color': traverseColor,
'node': variable,
},
});
//check if this variable has already been declared
//in the local environment
if (this.env.definedLocal(variable)) {
//runtime check
throw new EvalError("variable already declared: " + variable + "\n");
}
//get, and then evaluate, the expression
var expr = tree.getSubTree(1);
result = this.evaluateExp(expr);
// declare the new, local, variable
this.env.add(variable, result);
if (this.DEBUG > 0) {
//for debugging purposes
document.body.innerHTML += "<pre>" + this.env + "</pre>";
}
return result;
}//evaluateVar()
//Evaluate a print expression
this.evaluatePrint = function (tree) {
//throws EvakError
if (1 != tree.degree()) {
throw new EvalError("wrong number of arguments: " + tree + "\n");
}
var result = this.evaluateExp(tree.getSubTree(0));
//print the expression on the console.
console.log("The printed result is" + result);
return result;
}//evalautePrint()
//Evaluate a boolean expression
this.evaluateBexp = function (tree) {
//throws EvalError
var result = false;
var node = tree.element;
var value = this.evaluateExp(tree.getSubTree(0));
if (!(value.tag === value.BOOL_TAG)) {
//runtime check
throw new EvalError("not a boolean expression: "
+ tree.getSubTree(0) + "\n");
}
result = value.valueB;
if (node === "&&") {
if (2 > tree.degree()) {
//runtime check
throw new EvalError("wrong number of arguments: " + tree + "\n");
}
for (var xyz = 1; xyz < tree.degree() ; xyz++) {
if (result) {
value = this.evaluateExp(tree.getSubTree(xyz));
if (!(value.tag === value.BOOL_TAG)) {
//runtime check
throw new EvalError("not a boolean expression: "
+ tree.getSubTree(xyz) + "\n");
}
result = result && value.valueB;
}
else {
//short circuit the evaluation of "&&"
result = false;
break;
}
}
}
else if (node === "||") {
if (2 > tree.degree()) {
//runtime check
throw new EvalError("wrong number of arguments: " + tree + "\n");
}
for (var x = 1; x < tree.degree() ; x++) {
if (!result) {
value = this.evaluateExp(tree.getSubTree(x));
if (!(value.tag === value.BOOL_TAG)) {
//runtime check
throw new EvalError("not a boolean expression: "
+ tree.getSubTree(i) + "\n");
}
result = result || value.valueB;
}
else {
//short circuit the evaluation of "||"
result = true;
break;
}
}
}
else if (node === "!") {
if (1 != tree.degree()) {
//runtime check
throw new EvalError("wrong number of arguments: " + tree + "\n");
}
result = !result;
}
return new Value(result);
}//evaluateBexp()
// Evaluate a relational expression (which is a kind of boolean expression)
this.evaluateRexp = function (tree) {
if (2 != tree.degree()) {
//rumtime check
throw new EvalError("wrong number of arguments: " + tree + "\n");
}
var result = false;
var opStr = tree.element;
//emit a "nodeTraversal" event
//the event code is further down in the function definition
var valueL = this.evaluateExp(tree.getSubTree(0));
if (!(valueL.tag === valueL.INT_TAG)) {
//runtime check
throw new EvalError("not a integer expression: "
+ tree.getSubTree(0) + "\n");
}
var valueR = this.evaluateExp(tree.getSubTree(1));
if (!(valueR.tag === valueR.INT_TAG)) {
//runtime check
throw new EvalError("not a integer expression: "
+ tree.getSubTree(1) + "\n");
}
var resultL = valueL.valueI;
var resultR = valueR.valueI;
if (opStr === "<") {
result = resultL < resultR;
}
else if (opStr === ">") {
result = resultL > resultR;
}
else if (opStr === "<=") {
result = resultL <= resultR;
}
else if (opStr === ">=") {
result = resultL >= resultR;
}
else if (opStr === "==") {
result = resultL == resultR;
}
else if (opStr === "!=") {
result = resultL != resultR;
}
//emit a "nodeTraversal" event: tree.element == relational operator
var colorCode = "#ff0000"; //red color; code from http://html-color-codes.info/
if (result) {
//Color code from http://color.adobe.com
colorCode = "#87ff1d"; //green
}
scope.main.addAnimationData({'name': "nodeTraversal",
data: {
'id': tree.numId,
'color': colorCode,
'node' : opStr,
},
});
//if var result == T => highlight tree.element green, else highlight it red.
//see the code in Evaluate.js of Language_6 for more info.
return new Value(result);
}//evaluateRexp()
// Evaluate an arithmetic expression
this.evaluateAexp = function (tree) {
//throws EvalError
var result = 0;
var node = tree.element;
//do not emit a "nodeTraversal" event since we
//already did so in the evaluateExp function
var valueL = this.evaluateExp(tree.getSubTree(0));
if (!(valueL.tag === valueL.INT_TAG)) {
//runtime check
throw new EvalError("not a integer expression: "
+ tree.getSubTree(0) + "\n");
}
var resultL = valueL.valueI;
var resultR = 0;
var valueR = null;
if (tree.degree() >= 2) {
valueR = this.evaluateExp(tree.getSubTree(1));
if (!(valueR.tag === valueR.INT_TAG)) {
//runtime check
throw new EvalError("not a integer expression: "
+ tree.getSubTree(1) + "\n");
}
resultR = valueR.valueI;
}
if (node === "+") {
if (tree.degree() === 1) {
result = resultL;
}
else {
result = resultL + resultR;
for (var z = 2; z < tree.degree() ; z++) {
//temp := Value
var temp = this.evaluateExp(tree.getSubTree(z));
if (!(temp.tag === temp.INT_TAG)) {
//runtime check
throw new EvalError("not a integer expression: "
+ tree.getSubTree(z) + "\n");
}
result += temp.valueI;
}
}
}
else if (node === "-") {
if (2 < tree.degree()) {
//runtime check
throw new EvalError("wrong number of arguments: " + tree + "\n");
}
if (tree.degree() === 1) {
result = -resultL;
}
else {
result = resultL - resultR;
}
}
else if (node === "*") {
if (1 === tree.degree()) {
//runtime check
throw new EvalError("wrong number of arguments: " + tree + "\n");
}
result = resultL * resultR;
for (var a = 2; a < tree.degree() ; a++) {
var temp = this.evaluateExp(tree.getSubTree(a));
if (!(temp.tag === temp.INT_TAG)) {
//runtime check
throw new EvalError("not a integer expression: "
+ tree.getSubTree(a) + "\n");
}
result *= temp.valueI;
}
}
else if (node === "/") {
if (2 !== tree.degree()) {
//runtime check
throw new EvalError("wrong number of arguments: " + tree + "\n");
}
result = resultL / resultR;
}
else if (node === "%") {
if (2 !== tree.degree()) {
//runtime check
throw new EvalError("wrong number of arguments: " + tree + "\n");
}
result = resultL % resultR;
}
else if (node === "^") {
if (2 !== tree.degree()) {
//runtime check
throw new EvalError("wrong number of arguments: " + tree + "\n");
}
result = Math.floor(Math.pow(resultL, resultR));
}
return new Value(result);
}//evaluateAexp()
}
return {
"Evaluate": Evaluate
};
}]);
})();
|
cr7boulos/ast_interpreter
|
app/shared/factory/Language_10/evaluateFactory.js
|
JavaScript
|
mit
| 45,981
|
/*
jQuery for All-AJAX theme
Original JavaScript by Chris Coyier
Updated October 2010 by Stewart Heckenberg & Chris Coyier
Updated May 2011 by Chris Coyier
Updated Sep 2012 by Jeff Starr
*/
// Self-Executing Anonymous Function to avoid more globals
(function(){
$('.HeaderNav ul li').removeClass("selected");
// set variables
var
$mainContent = $("#containerAjax"),
$ajaxSpinner = $(".loader"),
$searchInput = $("#s"),
$allLinks = $("a"),
$el;
// auto-clear search field
$searchInput.focus(function(){
if ($(this).val() == "Search..."){
$(this).val("");
}
});
// query search results
$('#searchform').submit(function(){
var s = $searchInput.val().replace(/ /g, '+');
if (s){
var query = '/?s=' + s;
$.address.value(query);
}
return false;
});
// URL internal is via plugin http://benalman.com/projects/jquery-urlinternal-plugin/
$('a:urlInternal').live('click', function(e){
$el = $(this); // Caching
// poner la clase "noAjax" al elemento que quieras que su enlace se abra
// sin usar ajax, por ejemplo, la publicidad quieres que se abra en un link externo
if ( !$el.hasClass("noAjax") ){
var path = $(this).attr('href').replace(base, '');
$.address.value(path);
$('.HeaderNav ul li').removeClass("selected");
// Este condicional sirve para añadir la clase seleccionada
// en el caso de que hayamos pulsado dentro del menú Drop down (el que se abre abajo)
// mira si el elemento this tiene un padre que sea la clase header menu drop down
// y si la longitud es una (es decir, tiene ese padre), añade el estilo al Header nav drop
// de lo contrario, se lo añade al padre del a (caso "home", mixes...)
if ($el.parents('.HeaderMenuDropDown').length == 1)
{
$('.HeaderNavDrop').addClass('selected');
}
else
{
$el.parent().addClass("selected");
}
return false;
}
// Default action (go to link) prevented for comment-related links (which use onclick attributes)
});
// Fancy ALL AJAX Stuff
$.address.change(function(event){
if (event.value){
var adress = event.value;
// Animate to top
$("html, body").animate({ scrollTop: 0 }, 400);
$mainContent.hide(0);
$ajaxSpinner.show(0);
$mainContent.empty().load(base + event.value + ' #containerAjax', function(){
$ajaxSpinner.delay(300);
$ajaxSpinner.hide(0);
$mainContent.delay(0);
$mainContent.show(0);
});
console.log(event.value);
$('.footer').removeClass("footerHome");
$('.main').attr('class','main'); // Resetea las clases a main
$('.content').hide();
if (adress.indexOf("genero") >= 0) {
$('.main').addClass("green");
}
else if(adress.indexOf("index") >= 0) {
$('.main').addClass("home");
$('.content').show();
}
else {
$('.main').addClass("green");
}
}
var current = location.protocol + '//' + location.hostname + location.pathname;
if (base + '/' != current) {
var diff = current.replace(base, '');
location = base + '/#' + diff;
}
$ajaxSpinner.fadeOut();
});
})(); // End SEAF
|
ferreiro/MusicRadio
|
html/js/ajax.js
|
JavaScript
|
mit
| 3,125
|
(function() {
'use strict';
module.exports = function(app, io) {
var clientRoutes = io.rootPath + 'back-end/html_routes/client/',
use_app_client = {
main : require(clientRoutes + 'main'),
survey : require(clientRoutes + 'survey')
};
return useApp([
use_app_client.main,
use_app_client.survey
]);
function useApp(param) {
param.forEach(function(name) {
app.use('/', name);
});
}
};
}());
|
caninojories/x-scribe-testing-activity
|
back-end/configuration/use_app.config.js
|
JavaScript
|
mit
| 494
|
import resource from 'resource-router-middleware';
import facets from '../../models/facets';
export default resource({
/** Property name to store preloaded entity on `request`. */
id : 'facet',
/** For requests with an `id`, you can auto-load the entity.
* Errors terminate the request, success sets `req[id] = data`.
*/
load(req, id, callback) {
var facet = facets.find( facet => facet.id===id ),
err = facet ? null : 'Not found';
callback(err, facet);
},
/** GET / - List all entities */
index({ params }, res) {
res.json(facets);
},
/** POST / - Create a new entity */
create({ body }, res) {
body.id = facets.length.toString(36);
facets.push(body);
res.json(body);
},
/** GET /:id - Return a given entity */
read({ facet }, res) {
res.json(facet);
},
/** PUT /:id - Update a given entity */
update({ facet, body }, res) {
for (let key in body) {
if (key!=='id') {
facet[key] = body[key];
}
}
res.sendStatus(204);
},
/** DELETE /:id - Delete a given entity */
delete({ facet }, res) {
facets.splice(facets.indexOf(facet), 1);
res.sendStatus(204);
}
});
|
shpleef/es6-api-starter
|
server/api/noauth/facets.js
|
JavaScript
|
mit
| 1,126
|
var assert = require('assert'),
sinon = require('sinon'),
prerender = require('../index'),
util = require('../lib/util')
describe('Prerender', function() {
describe('#util', function() {
var sandbox;
beforeEach(function() {
sandbox = sinon.sandbox.create();
});
afterEach(function() {
sandbox.restore();
});
it('should remove the / from the beginning of the URL if present', function() {
var url = util.getUrl('/http://www.example.com/');
assert.equal(url, 'http://www.example.com/');
});
it('should return the correct URL for #! URLs without query strings', function() {
var url = util.getUrl('http://www.example.com/?_escaped_fragment_=/user/1');
assert.equal(url, 'http://www.example.com/#!/user/1');
});
it('should return the correct URL for #! URLs with query strings', function() {
var url = util.getUrl('http://www.example.com/?_escaped_fragment_=/user/1¶m1=yes¶m2=no');
assert.equal(url, 'http://www.example.com/?param1=yes¶m2=no#!/user/1');
});
it('should return the correct URL for #! URLs if query string is before hash', function() {
var url = util.getUrl('http://www.example.com/?param1=yes¶m2=no&_escaped_fragment_=/user/1');
assert.equal(url, 'http://www.example.com/?param1=yes¶m2=no#!/user/1');
});
it('should return the correct URL for #! URLs that are encoded with another ?', function() {
var url = util.getUrl('http://www.example.com/?_escaped_fragment_=%2Fuser%2F1%3Fparam1%3Dyes%26param2%3Dno');
assert.equal(url, 'http://www.example.com/?param1=yes¶m2=no#!/user/1');
});
it('should return the correct URL for html5 push state URLs', function() {
var url = util.getUrl('http://www.example.com/user/1?_escaped_fragment_=');
assert.equal(url, 'http://www.example.com/user/1');
});
it('should return the correct URL for html5 push state URLs with query strings', function() {
var url = util.getUrl('http://www.example.com/user/1?param1=yes¶m2=no&_escaped_fragment_=');
assert.equal(url, 'http://www.example.com/user/1?param1=yes¶m2=no');
});
it('should fix incorrect html5 URL that Bing accesses', function() {
var url = util.getUrl('http://www.example.com/?&_escaped_fragment_=');
assert.equal(url, 'http://www.example.com/');
});
it('should encode # correctly in URLs that do not use the #!', function() {
var url = util.getUrl('http://www.example.com/productNumber=123%23456?_escaped_fragment_=');
assert.equal(url, 'http://www.example.com/productNumber=123%23456');
});
it('should not encode non-english characters', function() {
var url = util.getUrl('http://www.example.com/كاليفورنيا?_escaped_fragment_=');
assert.equal(url, 'http://www.example.com/كاليفورنيا');
});
});
});
|
icilalune/prerender
|
test/index-spec.js
|
JavaScript
|
mit
| 2,819
|
module.exports = function (grunt) {
var config = grunt.file.readJSON('config.json'),
sourceDir = config.directories.scssSource,
build = config.directories.build;
grunt.registerTask('scss-compile', 'Compile SASS sources into CSS', function (mode) {
if(mode === 'build') {
grunt.task.run('sass:build');
} else {
grunt.task.run('sass:dev');
}
});
grunt.extendConfig({
sass: {
options: {
sourceMap: true,
outputStyle: 'expanded',
precision: 3,
quiet: true
},
build: {
options: {
sourceMap: true,
outputStyle: 'compressed',
quiet: true
},
files: [
{
expand: true,
cwd: sourceDir,
src: ['*.scss'],
dest: build + 'css/',
ext: '.css'
}
]
},
dev: {
options: {
sourceMap: true,
outputStyle: 'compressed',
quiet: true
},
files: [
{
expand: true,
cwd: sourceDir,
src: ['*.scss'],
dest: './css/',
ext: '.css'
}
]
}
}
});
};
|
Cooty/SetiQuest
|
source/tasks/scss-compile.js
|
JavaScript
|
mit
| 1,019
|
/*!
* Social-api-import v0.2.0
* https://npm.com/social-api-import
*
* Copyright (c) 2018 Mark Kennedy
* Licensed under the MIT license
*/
/*! *****************************************************************************
Copyright (c) Microsoft Corporation. All rights reserved.
Licensed under the Apache License, Version 2.0 (the "License"); you may not use
this file except in compliance with the License. You may obtain a copy of the
License at http://www.apache.org/licenses/LICENSE-2.0
THIS CODE IS PROVIDED ON AN *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY IMPLIED
WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE,
MERCHANTABLITY OR NON-INFRINGEMENT.
See the Apache Version 2.0 License for specific language governing permissions
and limitations under the License.
***************************************************************************** */
function __awaiter(thisArg, _arguments, P, generator) {
return new (P || (P = Promise))(function (resolve, reject) {
function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
function step(result) { result.done ? resolve(result.value) : new P(function (resolve) { resolve(result.value); }).then(fulfilled, rejected); }
step((generator = generator.apply(thisArg, _arguments || [])).next());
});
}
/*! *****************************************************************************
Copyright (c) Microsoft Corporation. All rights reserved.
Licensed under the Apache License, Version 2.0 (the "License"); you may not use
this file except in compliance with the License. You may obtain a copy of the
License at http://www.apache.org/licenses/LICENSE-2.0
THIS CODE IS PROVIDED ON AN *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY IMPLIED
WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE,
MERCHANTABLITY OR NON-INFRINGEMENT.
See the Apache Version 2.0 License for specific language governing permissions
and limitations under the License.
***************************************************************************** */
function __awaiter$1(thisArg, _arguments, P, generator) {
return new (P || (P = Promise))(function (resolve, reject) {
function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
function step(result) { result.done ? resolve(result.value) : new P(function (resolve) { resolve(result.value); }).then(fulfilled, rejected); }
step((generator = generator.apply(thisArg, _arguments || [])).next());
});
}
function ensurePathArray(paths) {
if (!paths) {
paths = [];
}
else if (typeof paths === 'string') {
paths = [paths];
}
return paths;
}
const head = document.getElementsByTagName('head')[0];
const scriptMaps = {};
const script = {
import(paths) {
return __awaiter$1(this, void 0, void 0, function* () {
let map;
const loadPromises = [];
paths = ensurePathArray(paths);
paths.forEach((path) => {
map = scriptMaps[path] = scriptMaps[path] || {};
if (!map.promise) {
map.path = path;
map.promise = new Promise((resolve) => {
const scriptElement = document.createElement('script');
scriptElement.setAttribute('type', 'text/javascript');
scriptElement.src = path;
scriptElement.addEventListener('load', resolve);
head.appendChild(scriptElement);
});
}
loadPromises.push(map.promise);
});
return Promise.all(loadPromises);
});
},
unload(paths) {
return __awaiter$1(this, void 0, void 0, function* () {
let file;
return new Promise((resolve) => {
paths = ensurePathArray(paths);
paths.forEach((path) => {
file = head.querySelectorAll('script[src="' + path + '"]')[0];
if (file) {
head.removeChild(file);
delete scriptMaps[path];
}
});
resolve();
});
});
}
};
const loadedScripts = [];
class BaseApi {
constructor(options = {}) {
if (options.apiVersion) {
console.warn(`"apiVersion" has been deprecated, please use the "version" option`);
options.version = options.apiVersion + '';
}
this.options = options;
}
destroy() {
if (!this.script)
return;
const idx = loadedScripts.indexOf(this.script);
loadedScripts.splice(idx, 1);
if (this.script && loadedScripts.indexOf(this.script) <= -1) {
script.unload(this.script);
}
}
load() {
return __awaiter(this, void 0, void 0, function* () {
if (!this.loadApiListenerPromiseMap) {
this.loadApiListenerPromiseMap = this.handleLoadApi(this.options);
}
return this.loadApiListenerPromiseMap;
});
}
login(options) {
return __awaiter(this, void 0, void 0, function* () {
return {
accessToken: '',
accessTokenSecret: '',
userId: '',
expiresAt: Date.now()
};
});
}
loadScript(path) {
this.script = path;
loadedScripts.push(this.script);
return script.import(this.script);
}
handleLoadApi(options) {
return __awaiter(this, void 0, void 0, function* () {
return Promise.resolve();
});
}
static get id() {
return 'base-api';
}
}
const PERMISSIONS_MAP = {
createPosts: ['publish_actions'],
readPosts: ['user_posts'],
updatePosts: ['publish_actions'],
deletePosts: ['publish_actions'],
readProfile: ['public_profile', 'user_about_me', 'user_birthday', 'user_location', 'user_work_history'],
readFriendProfiles: ['user_friends']
};
class Facebook extends BaseApi {
constructor(options) {
super(options);
if (options.version) {
options.version = !options.version.startsWith('v') ? 'v' + options.version : options.version;
}
options.xfbml = options.xfbml || true;
this.options = options;
}
login(options = {}) {
return __awaiter(this, void 0, void 0, function* () {
yield this.load();
const buildScope = () => {
options.permissions = options.permissions || [];
return options.permissions.reduce((prev = '', perm) => {
const values = PERMISSIONS_MAP[perm] || [];
return values.reduce((p, value) => {
const delimiter = prev ? ',' : '';
let str = value || '';
if (prev.indexOf(value || '') === -1) {
str = `${delimiter}${value}`;
return (prev += str);
}
else {
return prev;
}
}, prev);
}, '');
};
options.scope = options.scope || buildScope();
return new Promise(resolve => {
this.FB.login((response) => {
if (response.authResponse) {
// authorized!
resolve({
accessToken: response.authResponse.accessToken,
userId: response.authResponse.userID,
expiresAt: response.authResponse.expiresIn
});
}
else {
// User either abandoned the login flow or,
// for some other reason, did not fully authorize
resolve({});
}
}, options);
});
});
}
static get id() {
return 'facebook';
}
destroy() {
delete window.fbAsyncInit;
return super.destroy();
}
handleLoadApi() {
return __awaiter(this, void 0, void 0, function* () {
return new Promise(resolve => {
window.fbAsyncInit = () => {
FB.init(this.options);
this.FB = FB;
resolve(FB);
};
this.loadScript('https://connect.facebook.net/en_US/sdk.js');
});
});
}
}
export default Facebook;
|
mkay581/social-api
|
dist/facebook.js
|
JavaScript
|
mit
| 9,274
|
import {Posts} from '/libs/collections';
import {Meteor} from 'meteor/meteor';
import {check} from 'meteor/check';
import cronofy from 'cronofy';
Meteor.methods({
'posts.create'(_id, title, content) {
check(_id, String);
check(title, String);
check(content, String);
// Show the latency compensations
Meteor._sleepForMs(500);
// XXX: Do some user authorization
const createdAt = new Date();
const post = {_id, title, content, createdAt};
Posts.insert(post);
},
'cronofy.requestAccessToken'(code) {
check(code, String);
console.log('hello from posts.create code: ' + code);
var config = ServiceConfiguration.configurations.findOne({service: 'cronofy'});
if (!config) {
credentialRequestCompleteCallback && credentialRequestCompleteCallback(
new ServiceConfiguration.ConfigError());
return;
}
var redirectUrl = OAuth._redirectUri('cronofy', config);
var options = {
client_id: '_QOoOhBwuUfl3ZDBhN9lsNGXPdKJwZqP',
client_secret: 'CMlCEvq12kk_Ogrt_5KOHvHnpRiEfgRELxDsxoZHDxO0gyx6xGlQ2hnU6HPJOo-Gm2l6hTXvWZPNJylveEqIhw',
grant_type: 'authorization_code',
code: code,
redirect_uri: "http://localhost:3000/_oauth/cronofy"
};
console.dir(options);
cronofy.requestAccessToken(options, function(err, response){
if(err) {
//throw err;
console.log('error requesting access token');
console.dir(err);
} else {
console.dir(response);
}
})
}
});
|
crussi/mantra-sample-blog
|
server/methods/posts.js
|
JavaScript
|
mit
| 1,610
|
import { h } from 'omi';
import createSvgIcon from './utils/createSvgIcon';
export default createSvgIcon(h(h.f, null, h("path", {
d: "M20 11.56v-.89c0-.76-.58-1.33-1.33-1.33h-3.11v5.33h1.33v-1.78h1.02l.76 1.78H20l-.8-1.87c.44-.22.8-.71.8-1.24zm-1.33 0h-1.78v-.89h1.78v.89zM7.11 9.33H4v5.33h3.11c.76 0 1.33-.58 1.33-1.33v-2.67c0-.75-.57-1.33-1.33-1.33zm0 4H5.33v-2.67h1.78v2.67zm7-4h-1.34l-.89 3.05L11 9.33H9.66l1.56 5.34h1.33z"
}), h("path", {
d: "M3 5h18v14H3z",
opacity: ".3"
}), h("path", {
d: "M21 3H3c-1.11 0-2 .89-2 2v14c0 1.1.89 2 2 2h18c1.11 0 2-.9 2-2V5c0-1.11-.89-2-2-2zm0 16H3V5h18v14z"
})), 'FiberDvrTwoTone');
|
AlloyTeam/Nuclear
|
components/icon/esm/fiber-dvr-two-tone.js
|
JavaScript
|
mit
| 630
|
export const apiURL = '/api';
export const capitalizeFirstLetter = (string = '') =>
`${string.charAt(0).toUpperCase()}${string.slice(1)}`;
|
andy-j-d/simply-news-ui
|
client/util/index.js
|
JavaScript
|
mit
| 144
|
importClass(java.net.InetSocketAddress);
importClass(java.util.concurrent.Executors);
importClass(Packages.org.jboss.netty.bootstrap.ServerBootstrap);
importClass(Packages.org.jboss.netty.buffer.ChannelBuffers);
importClass(Packages.org.jboss.netty.channel.Channels);
importClass(Packages.org.jboss.netty.channel.ChannelFutureListener);
importClass(Packages.org.jboss.netty.channel.ChannelPipelineFactory);
importClass(Packages.org.jboss.netty.channel.MessageEvent);
importClass(Packages.org.jboss.netty.channel.SimpleChannelUpstreamHandler);
importClass(Packages.org.jboss.netty.channel.socket.nio.NioServerSocketChannelFactory);
importClass(Packages.org.jboss.netty.handler.codec.http.HttpChunkAggregator);
importClass(Packages.org.jboss.netty.handler.codec.http.HttpRequestDecoder);
importClass(Packages.org.jboss.netty.handler.codec.http.HttpResponseEncoder);
importClass(Packages.org.jboss.netty.handler.codec.http.HttpMethod);
importClass(Packages.org.jboss.netty.handler.codec.http.HttpHeaders);
importClass(Packages.org.jboss.netty.handler.codec.http.HttpHeaders.Names);
importClass(Packages.org.jboss.netty.handler.codec.http.HttpResponseStatus);
importClass(Packages.org.jboss.netty.handler.codec.http.HttpVersion);
importClass(Packages.org.jboss.netty.handler.codec.http.HttpRequest)
importClass(Packages.org.jboss.netty.handler.codec.http.DefaultHttpResponse);
importClass(Packages.org.jboss.netty.handler.codec.http.websocketx.WebSocketFrame);
importClass(Packages.org.jboss.netty.handler.codec.http.websocketx.CloseWebSocketFrame);
importClass(Packages.org.jboss.netty.handler.codec.http.websocketx.PingWebSocketFrame);
importClass(Packages.org.jboss.netty.handler.codec.http.websocketx.PongWebSocketFrame);
importClass(Packages.org.jboss.netty.handler.codec.http.websocketx.TextWebSocketFrame);
importClass(Packages.org.jboss.netty.handler.codec.http.websocketx.WebSocketServerHandshaker);
importClass(Packages.org.jboss.netty.handler.codec.http.websocketx.WebSocketServerHandshakerFactory);
var Pipeline = function(connectionListener) {
return new JavaAdapter(ChannelPipelineFactory, {getPipeline: function() {
var pipeline = Channels.pipeline();
pipeline.addLast("decoder", new HttpRequestDecoder());
pipeline.addLast("aggregator", new HttpChunkAggregator(65536));
pipeline.addLast("encoder", new HttpResponseEncoder());
pipeline.addLast("handler", ServerHandler(connectionListener));
return pipeline;
}});
}
var worker = {
onReceive: function(msg) {
this.getSender().tell(['res', "Hello, world!"]);
}
};
var boss = {
onReceive: function(msg) {
if (msg[0] == 'data') {
this.channel = msg[2].getChannel();
slave.tell(['data', msg[2].getMessage()], this.getSelf());
} else if (msg[0] == 'err') {
console.log(msg[2]);
} else if (msg[0] == 'res') {
this.handleHttp(msg[1]);
}
},
handleHttp: function(msg) {
res = new DefaultHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.OK);
res.setContent(ChannelBuffers.copiedBuffer("Hello, world!\n", "UTF-8"));
this.channel.write(res).addListener(new JavaAdapter(ChannelFutureListener, {operationComplete: function(f) {
f.getChannel().close();
}}));
/*
wsfactory = new WebSocketServerHandshakerFactory(this.getWebSocketLocation(msg), null, false);
this.handshaker = wsfactory.newHandshaker(msg);
if (this.handshaker == null) {
wsFactory.sendUnsupportedWebSocketVersionResponse(ctx.getChannel());
} else {
this.handshaker.handshake(ctx.getChannel(), msg).addListener(WebSocketServerHandshaker.HANDSHAKE_LISTENER);
}*/
},
handleWs: function(ctx, frame) {
console.log('ws');
if (frame instanceof CloseWebSocketFrame) {
this.handshaker.close(ctx.getChannel(), frame);
return;
} else if (frame instanceof PingWebSocketFrame) {
ctx.getChannel.write(new PongWebsocketFrame(frame.getBinaryData()))
return;
} else if (frame instanceof TextWebSocketFrame) {
req = frame.getText();
ctx.getChannel().write(new TextWebSocketFrame("bumeyes"));
}
},
getWebSocketLocation: function(msg) {
return "ws://" + msg.getHeader(HttpHeaders.Names.HOST) + "/ws";
}
};
var slave = new actor(worker, {"n":5});
var ServerHandler = function(connectionListener) {
return new JavaAdapter(SimpleChannelUpstreamHandler, {
supervisor: new actor(boss),
channelOpen: function(ctx, e) {
this.supervisor.tell(['open', ctx, e]);
},
messageReceived: function(ctx, e) {
this.supervisor.tell(['data', ctx, e]);
},
exceptionCaught: function(ctx, e) {
this.supervisor.tell(['err', ctx, e]);
}
});
};
var Server = function(connectionListener) {
var internalAddress = null;
this.listen = function(port, cb) {
new future(function() {
internalAddress = new InetSocketAddress(port);
var factory = new NioServerSocketChannelFactory(Executors.newSingleThreadExecutor(),
Executors.newCachedThreadPool(), 1);
var bootstrap = new ServerBootstrap(factory);
bootstrap.setPipelineFactory(Pipeline(connectionListener));
bootstrap.bind(internalAddress);
}, cb).recover(function(e) {
java.lang.System.out.println(e)
});
};
}
exports.createServer = function(listener) {
return new Server(listener);
};
|
m0wfo/rhinode
|
resources/websocket.js
|
JavaScript
|
mit
| 5,393
|
'use strict'
const BB = require('bluebird')
let addBundled
const childPath = require('../utils/child-path.js')
const createChild = require('./node.js').create
let fetchPackageMetadata
const inflateBundled = require('./inflate-bundled.js')
const moduleName = require('../utils/module-name.js')
const normalizePackageData = require('normalize-package-data')
const npm = require('../npm.js')
const realizeShrinkwrapSpecifier = require('./realize-shrinkwrap-specifier.js')
const validate = require('aproba')
const path = require('path')
const isRegistry = require('../utils/is-registry.js')
const hasModernMeta = require('./has-modern-meta.js')
const ssri = require('ssri')
const npa = require('npm-package-arg')
module.exports = function (tree, sw, opts, finishInflating) {
if (!fetchPackageMetadata) {
fetchPackageMetadata = BB.promisify(require('../fetch-package-metadata.js'))
addBundled = BB.promisify(fetchPackageMetadata.addBundled)
}
if (arguments.length === 3) {
finishInflating = opts
opts = {}
}
if (!npm.config.get('shrinkwrap') || !npm.config.get('package-lock')) {
return finishInflating()
}
tree.loaded = false
tree.hasRequiresFromLock = sw.requires
return inflateShrinkwrap(tree.path, tree, sw.dependencies, opts).then(
() => finishInflating(),
finishInflating
)
}
function inflateShrinkwrap (topPath, tree, swdeps, opts) {
if (!swdeps) return Promise.resolve()
if (!opts) opts = {}
const onDisk = {}
tree.children.forEach((child) => {
onDisk[moduleName(child)] = child
})
tree.children = []
return BB.each(Object.keys(swdeps), (name) => {
const sw = swdeps[name]
const dependencies = sw.dependencies || {}
const requested = realizeShrinkwrapSpecifier(name, sw, topPath)
if (Object.keys(sw).length === 0) {
let message = `Object for dependency "${name}" is empty.\n`
message += 'Something went wrong. Regenerate the package-lock.json with "npm install".\n'
message += 'If using a shrinkwrap, regenerate with "npm shrinkwrap".'
return Promise.reject(new Error(message))
}
return inflatableChild(
onDisk[name], name, topPath, tree, sw, requested, opts
).then((child) => {
child.hasRequiresFromLock = tree.hasRequiresFromLock
return inflateShrinkwrap(topPath, child, dependencies)
})
})
}
function normalizePackageDataNoErrors (pkg) {
try {
normalizePackageData(pkg)
} catch (ex) {
// don't care
}
}
function quotemeta (str) {
return str.replace(/([^A-Za-z_0-9/])/g, '\\$1')
}
function tarballToVersion (name, tb) {
const registry = quotemeta(npm.config.get('registry') || '')
.replace(/https?:/, 'https?:')
.replace(/([^/])$/, '$1/')
let matchRegTarball
if (name) {
const nameMatch = quotemeta(name)
matchRegTarball = new RegExp(`^${registry}${nameMatch}/-/${nameMatch}-(.*)[.]tgz$`)
} else {
matchRegTarball = new RegExp(`^${registry}(.*)?/-/\\1-(.*)[.]tgz$`)
}
const match = tb.match(matchRegTarball)
if (!match) return
return match[2] || match[1]
}
function relativizeLink (name, spec, topPath, requested) {
if (!spec.startsWith('file:')) {
return
}
let requestedPath = requested.fetchSpec
if (requested.type === 'file') {
requestedPath = path.dirname(requestedPath)
}
const relativized = path.relative(requestedPath, path.resolve(topPath, spec.slice(5)))
return 'file:' + relativized
}
function inflatableChild (onDiskChild, name, topPath, tree, sw, requested, opts) {
validate('OSSOOOO|ZSSOOOO', arguments)
const usesIntegrity = (
requested.registry ||
requested.type === 'remote' ||
requested.type === 'file'
)
const regTarball = tarballToVersion(name, sw.version)
if (regTarball) {
sw.resolved = sw.version
sw.version = regTarball
}
if (sw.requires) {
Object.keys(sw.requires).forEach(name => {
const spec = sw.requires[name]
sw.requires[name] = tarballToVersion(name, spec) ||
relativizeLink(name, spec, topPath, requested) ||
spec
})
}
const modernLink = requested.type === 'directory' && !sw.from
if (hasModernMeta(onDiskChild) && childIsEquivalent(sw, requested, onDiskChild)) {
// The version on disk matches the shrinkwrap entry.
if (!onDiskChild.fromShrinkwrap) onDiskChild.fromShrinkwrap = requested
onDiskChild.package._requested = requested
onDiskChild.package._spec = requested.rawSpec
onDiskChild.package._where = topPath
onDiskChild.package._optional = sw.optional
onDiskChild.package._development = sw.dev
onDiskChild.package._inBundle = sw.bundled
onDiskChild.fromBundle = (sw.bundled || onDiskChild.package._inBundle) ? tree.fromBundle || tree : null
if (!onDiskChild.package._args) onDiskChild.package._args = []
onDiskChild.package._args.push([String(requested), topPath])
// non-npm registries can and will return unnormalized data, plus
// even the npm registry may have package data normalized with older
// normalization rules. This ensures we get package data in a consistent,
// stable format.
normalizePackageDataNoErrors(onDiskChild.package)
onDiskChild.swRequires = sw.requires
tree.children.push(onDiskChild)
return BB.resolve(onDiskChild)
} else if ((sw.version && (sw.integrity || !usesIntegrity) && (requested.type !== 'directory' || modernLink)) || sw.bundled) {
// The shrinkwrap entry has an integrity field. We can fake a pkg to get
// the installer to do a content-address fetch from the cache, if possible.
return BB.resolve(makeFakeChild(name, topPath, tree, sw, requested))
} else {
// It's not on disk, and we can't just look it up by address -- do a full
// fpm/inflate bundle pass. For registry deps, this will go straight to the
// tarball URL, as if it were a remote tarball dep.
return fetchChild(topPath, tree, sw, requested)
}
}
function isGit (sw) {
const version = npa.resolve(sw.name, sw.version)
return (version && version.type === 'git')
}
function makeFakeChild (name, topPath, tree, sw, requested) {
const isDirectory = requested.type === 'directory'
const from = sw.from || requested.raw
const pkg = {
name: name,
version: sw.version,
_id: name + '@' + sw.version,
_resolved: sw.resolved || (isGit(sw) && sw.version),
_requested: requested,
_optional: sw.optional,
_development: sw.dev,
_inBundle: sw.bundled,
_integrity: sw.integrity,
_from: from,
_spec: requested.rawSpec,
_where: topPath,
_args: [[requested.toString(), topPath]],
dependencies: sw.requires
}
if (!sw.bundled) {
const bundleDependencies = Object.keys(sw.dependencies || {}).filter((d) => sw.dependencies[d].bundled)
if (bundleDependencies.length === 0) {
pkg.bundleDependencies = bundleDependencies
}
}
const child = createChild({
package: pkg,
loaded: isDirectory,
parent: tree,
children: [],
fromShrinkwrap: requested,
fakeChild: sw,
fromBundle: sw.bundled ? tree.fromBundle || tree : null,
path: childPath(tree.path, pkg),
realpath: isDirectory ? requested.fetchSpec : childPath(tree.realpath, pkg),
location: (tree.location === '/' ? '' : tree.location + '/') + pkg.name,
isLink: isDirectory,
isInLink: tree.isLink || tree.isInLink,
swRequires: sw.requires
})
tree.children.push(child)
return child
}
function fetchChild (topPath, tree, sw, requested) {
return fetchPackageMetadata(requested, topPath).then((pkg) => {
pkg._from = sw.from || requested.raw
pkg._optional = sw.optional
pkg._development = sw.dev
pkg._inBundle = false
return addBundled(pkg).then(() => pkg)
}).then((pkg) => {
var isLink = pkg._requested.type === 'directory'
const child = createChild({
package: pkg,
loaded: false,
parent: tree,
fromShrinkwrap: requested,
path: childPath(tree.path, pkg),
realpath: isLink ? requested.fetchSpec : childPath(tree.realpath, pkg),
children: pkg._bundled || [],
location: (tree.location === '/' ? '' : tree.location + '/') + pkg.name,
fromBundle: null,
isLink: isLink,
isInLink: tree.isLink,
swRequires: sw.requires
})
tree.children.push(child)
if (pkg._bundled) {
delete pkg._bundled
inflateBundled(child, child, child.children)
}
return child
})
}
function childIsEquivalent (sw, requested, child) {
if (!child) return false
if (child.fromShrinkwrap) return true
if (
sw.integrity &&
child.package._integrity &&
ssri.parse(sw.integrity).match(child.package._integrity)
) return true
if (child.isLink && requested.type === 'directory') return path.relative(child.realpath, requested.fetchSpec) === ''
if (sw.resolved) return child.package._resolved === sw.resolved
if (!isRegistry(requested) && sw.from) return child.package._from === sw.from
if (!isRegistry(requested) && child.package._resolved) return sw.version === child.package._resolved
return child.package.version === sw.version
}
|
dmilith/SublimeText3-dmilith
|
Package Storage/lsp_utils/node-runtime/12.20.2/node/lib/node_modules/npm/lib/install/inflate-shrinkwrap.js
|
JavaScript
|
mit
| 9,086
|
var AppDispatcher = require('../dispatcher/AppDispatcher');
var appConstants = require('../constants/appConstants');
var restUrl = "https://localhost:3001/";
function showMsg(msg, error) {
AppDispatcher.handleAction({
actionType: appConstants.FLICKR_SAVE_EVENT,
data: {msg: msg, error: error}
});
}
function showLoading() {
showMsg("Loading..", false);
}
var flickrActions = {
flickrFetchAction: function(count) {
//console.log('flickr fetch action');
var flickrUrl = restUrl + 'api/flickr';
if (count > 0) {
flickrUrl += "?count=" + count;
}
//showLoading();
$.get(flickrUrl).then(
function(data) {
//console.log(data);
AppDispatcher.handleAction({
actionType: appConstants.FLICKR_URL,
data: data.urls
});
},
function(data) {
AppDispatcher.handleAction({
actionType: appConstants.FLICKR_URL_ERR,
data: data
});
//console.log('errored');
}
).always(
function() {
//console.log('always fired');
}
); //lib does not support finally
},
flickrDoSearch: function(count, text, page, event) {
//console.log('flickr fetch action');
var flickrUrl = restUrl + 'api/flickrSearch';
if (count > 0) {
flickrUrl += "?count=" + count;
}
if (!text) {
AppDispatcher.handleAction({
actionType: appConstants.FLICKR_SEARCH_ERR_EVENT,
data: {msg: 'requires tag'}
});
return;
}
flickrUrl += "&text=" + text;
if (page) flickrUrl += "&page=" + page;
//showLoading();
$.get(flickrUrl).then(
function(data) {
//console.log(data);
AppDispatcher.handleAction({
actionType: event,
data: {urls: data.urls, search: text}
});
},
function(data) {
AppDispatcher.handleAction({
actionType: appConstants.FLICKR_SEARCH_ERR_EVENT,
data: {msg: 'no search result', data: data}
});
//console.log('errored');
}
).always(
function() {
//console.log('always fired');
}
); //lib does not support finally
},
flickrSearchAction: function(count, text, page) {
this.flickrDoSearch(count, text, page, appConstants.FLICKR_SEARCH_EVENT);
},
flickrNewSearchAction: function(count, text, page) {
this.flickrDoSearch(count, text, page, appConstants.FLICKR_NEW_SEARCH_EVENT);
},
saveImage: function(url) {
//console.log('save image ' + url);
var flickrUrl = restUrl + 'api/flickrSave';
var msg = "";
var error = false;
$.post(flickrUrl, {image: url}).then(
function() {
msg = "Image saved.";
},
function(data) {
error = true;
msg = "Save error: " + data.status + " " + data.statusText;
}
).always(
function() {
showMsg(msg, error);
}
);
},
saveImageMsgClear: function() {
showMsg();
/*AppDispatcher.handleAction({
actionType: appConstants.FLICKR_SAVE_EVENT,
data: {}
})*/
},
loadSavedImages: function() {
//console.log('fetch image ');
var flickrUrl = restUrl + 'api/flickrSaved';
//showLoading();
$.get(flickrUrl).then(
function(data) {
AppDispatcher.handleAction({
actionType: appConstants.FLICKR_LOAD_EVENT,
data: data.urls
});
/*console.log('fetched: ');
console.log(data);*/
},
function(data) {
/*console.log('fetch failed: ');
console.log(data);*/
}
).always(
function() {
}
);
},
loadLiveImages: function() {
AppDispatcher.handleAction({
actionType: appConstants.FLICKR_RESTORE_LIVE_EVENT,
data: {}
})
},
loadSearchImages: function() {
AppDispatcher.handleAction({
actionType: appConstants.FLICKR_RESTORE_SEARCH_EVENT,
data: {}
})
},
autoPlayStop: function() {
AppDispatcher.handleAction({
actionType: appConstants.FLICKR_AUTOPLAY_STOP_EVENT,
data: {}
})
}
};
module.exports = flickrActions;
|
anchung1/flickrApp
|
src/js/actions/flickrActions.js
|
JavaScript
|
mit
| 4,888
|
namespace('Dash.Browser');
(function() {
'use strict';
Dash.Browser.Location = {
change: function(url) {
window.location.replace(url);
},
hash: function() {
return window.location.hash;
},
reload: function() {
window.location.reload();
},
changeHref: function(href) {
window.location.href = href;
}
};
Dash.Browser.Navigator = {
userAgent: function() {
return window.navigator.userAgent;
}
};
Dash.Browser.changeTitle = function(title) {
document.title = title;
};
Dash.Browser.open = function(url, options) {
return window.open(url, '_blank', options);
};
Dash.Browser.close = function() {
window.close();
};
Dash.Browser.setTimeout = function(fn, timeInMilliseconds) {
return window.setTimeout(fn, timeInMilliseconds);
};
Dash.Browser.setInterval = function(fn, timeInMilliseconds) {
return window.setInterval(fn, timeInMilliseconds);
};
Dash.Browser.isInIframe = function() {
try {
return window.self !== window.top;
} catch (e) {
return true;
}
};
Dash.Browser.isIFramedBy = function(origin) {
if (Dash.Browser.isInIframe()) {
return window.top.location.origin === origin;
}
};
Dash.Browser.scrollToTop = function() {
window.parent.postMessage('scrollTo:0', window.location.origin);
};
Dash.Browser.scrollToBottom = function() {
console.log(document.body.scrollHeight);
console.log($(document).height());
window.scrollTo(0,document.body.scrollHeight);
};
}
());
|
samaritanministries/dash.js
|
js/scripts/dash/browser.js
|
JavaScript
|
mit
| 1,572
|
'use strict';
/*************************************************************
* Variables
************************************************************/
// Modules
var path = require('path');
var del = require('del');
var getFolders = require('../lib/getFolders');
var merge = require('merge-stream');
// Globals
var gulp = global.gulp;
var config = global.config;
var tasks = global.tasks;
var browserSync = global.browserSync;
/*************************************************************
* Operations
************************************************************/
// REMOVING UNTILL THE SAME SVG CAN BE USED as
// gulp.task('svg:icons', 'Build a full scss mixin & sprite file based on all available svg icons',
// function () {
// return gulp.src(config.svg.src)
// .pipe(gulp.$.svgSprite(config.svg.iconConfig))
// .pipe(gulp.dest('./'));
// }
// );
gulp.task('svg:delete', 'Step 1 - Delete the SVG destination folder\'s contents',
function () {
// Delete all files except warning file to not save Svg in destination
var deletePattern = [
config.svg.dest + '/**/*',
'!' + config.svg.dest + '/do-not-save-files-here.md'
];
return del(deletePattern);
}
);
gulp.task('svg:minify', 'Step 2 - Minfify, Remove all Strokes & Fills, and copy to new location',
['svg:delete'],
function () {
return gulp.src(config.svg.src)
.pipe(gulp.$.imagemin(config.svg.removeAttrs))
.pipe(gulp.dest(config.svg.dest) // write all the minified svg to dest.
);
}
);
gulp.task('svg:minify:keepAttributes', 'Step 3 - Minfify (Leaving Strokes & Fills) and copy to new location',
['svg:minify'],
function () {
return gulp.src(config.svg.keepAttributesSrc)
.pipe(gulp.$.imagemin(config.svg.keepAttrs))
.pipe(gulp.dest(config.svg.dest) // write all the minified svg to dest.
);
}
);
gulp.task('svg:createSprites', 'Step 4 - Sprite Minfied files',
['svg:minify:keepAttributes'],
function () {
// Each sub-folder's content becomes a single SVG sprite in the root dest folder
// Get the folders in the dest
var spriteFolders = getFolders(config.svg.dest);
// Contents of each folder will get converted to a single sprite
// spriteFolders.map - executes the function once per folder, and returns the async stream
var buildSprites = spriteFolders.map(function (folder) {
var spriteSrc = path.join(config.svg.dest, folder, '/**/*.svg');
return gulp.src(spriteSrc)
.pipe(gulp.$.svgstore())
.pipe(gulp.dest(config.svg.dest));
});
return merge(buildSprites); // Wait for all stream emitters to end then return
}
);
gulp.task('svg:sprite', 'Step 5 - Export SVGz gzipped files for better compression the server side gzip',
['svg:createSprites'],
function () {
// Test to make sure they're not too big
return gulp.src(config.svg.dest + '/*.svg')
.pipe(gulp.$.rename(function (path) {
path.extname = ''; // Trim Extension
}))
.pipe(gulp.$.gzip({extension: config.svg.gzipFormat})) // Gzip and add "svgz" extension
.pipe(gulp.dest(config.svg.dest))
.pipe(gulp.$.if(config.svg.sizeReport.enabled,
gulp.$.sizereport(config.svg.sizeReport.options)
)
);
}
);
/*************************************************************
* Builders
************************************************************/
gulp.task('svg', 'Execute all SVG related tasks', ['svg:sprite']); // Removed Icon Task for now
// gulp.task('svg', 'Execute all SVG related tasks', ['svg:icons', 'svg:sprite']);
tasks.compile.push('svg');
/*************************************************************
* Watchers
************************************************************/
if (config.svg.watcher) { // If enabled, watch for changes on SVGs
gulp.watch([config.svg.src], '', ['svg'], browserSync.reload);
}
|
finteractive/emulsify
|
gulp/tasks/svg.js
|
JavaScript
|
mit
| 3,895
|
// Copyright (c) CBC/Radio-Canada. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
import ko from 'knockout';
function KnockoutDisposer() {
this.subscriptions = [];
}
KnockoutDisposer.prototype.add = function(subscription) {
this.subscriptions.push(subscription);
};
KnockoutDisposer.prototype.dispose = function() {
for (var i in this.subscriptions) {
var subscription = this.subscriptions[i];
if (subscription && subscription.dispose) {
subscription.dispose();
}
}
};
export default KnockoutDisposer;
|
cbcrc/koco-disposer
|
src/disposer.js
|
JavaScript
|
mit
| 638
|
const path = require('path')
module.exports = {
entry: {
aeria: './index.js',
},
context: path.resolve(__dirname, 'scripts'),
output: {
path: path.resolve(__dirname, 'assets/js'),
filename: '[name].js',
},
module: {
rules: [
{
test: /\.css$/i,
use: ['style-loader', 'css-loader'],
},
{
test: /\.(js|jsx)$/,
exclude: /node_modules\/(?!(@aeria)\/).*/,
use: ['babel-loader']
},
]
}
}
|
CaffeinaLab/aeria
|
webpack.config.js
|
JavaScript
|
mit
| 480
|
//# sourceMappingURL=../../userManagement/services/profile.js.map
|
QuinntyneBrown/ngBook
|
ngBook/src/js/userManagement/services/profile.js
|
JavaScript
|
mit
| 67
|
module.exports = function(app){
var business = {};
var paramDAO = app.dao.parameters;
business.deleteClassificacao = function(key, callback)
{
if(!key)
{
callback({success: false, message: 'Invalid value data fields.', validationError:true});
}
else
{
paramDAO.deleteClassificacao(key, function(err){
if(err){
console.log('Deleting parameter error:' + err);
callback({success: false, message: err});
}else{
callback(null);
}
});
}
};
business.deleteEvento = function(key, callback)
{
if(!key)
{
callback({success: false, message: 'Invalid value data fields.', validationError:true});
}
else
{
paramDAO.deleteEvento(key, function(err){
if(err){
console.log('Deleting parameter error:' + err);
callback({success: false, message: err});
}else{
callback(null);
}
});
}
};
/**
* Realiza registro de uma classificação
* @author Edizon
*
*/
business.saveClassificacao = function(classfic, callback){
if(!classfic.descricao)
{
callback({success: false, message: 'Invalid value data fields.', validationError:true});
}
else
{
paramDAO.saveClassificacao(classfic, function(err, result){
if(err){
callback({success: false, message: err}, null);
}else{
callback(null, result);
}
});
}
};
business.saveEvento = function(evento, callback){
if(!evento.descricao)
{
callback({success: false, message: 'Invalid value data fields.', validationError:true});
}
else
{
paramDAO.saveEvento(evento, function(err, result){
if(err){
callback({success: false, message: err}, null);
}else{
callback(null, result);
}
});
}
};
return business;
};
|
BD-ITAC/BD-ITAC
|
api/server/business/parameters.js
|
JavaScript
|
mit
| 1,965
|
describe('UNIT: ViewModel', function () {
var nextTick = require('vue/src/utils').nextTick
mock('vm-test', '{{a.b.c}}')
var data = {
b: {
c: 12345
}
},
arr = [1, 2, 3],
vm = new Vue({
el: '#vm-test',
data: {
a: data,
b: arr
}
})
describe('.$set()', function () {
vm.$set('a.b.c', 54321)
it('should set correct value', function () {
assert.strictEqual(data.b.c, 54321)
})
})
describe('.$watch()', function () {
it('should trigger callback when a plain value changes', function (done) {
var val
vm.$watch('a.b.c', function (newVal) {
val = newVal
})
data.b.c = 'new value!'
nextTick(function () {
assert.strictEqual(val, data.b.c)
done()
})
})
it('should trigger callback when an object value changes', function (done) {
var val, subVal, rootVal,
target = { c: 'hohoho' }
vm.$watch('a.b', function (newVal) {
val = newVal
})
vm.$watch('a.b.c', function (newVal) {
subVal = newVal
})
vm.$watch('a', function (newVal) {
rootVal = newVal
})
data.b = target
nextTick(function () {
assert.strictEqual(val, target)
assert.strictEqual(subVal, target.c)
next()
})
function next () {
vm.a = 'hehehe'
nextTick(function () {
assert.strictEqual(rootVal, 'hehehe')
done()
})
}
})
it('should trigger callback when an array mutates', function (done) {
var val, mut
vm.$watch('b', function (array, mutation) {
val = array
mut = mutation
})
arr.push(4)
nextTick(function () {
assert.strictEqual(val, arr)
assert.strictEqual(mut.method, 'push')
assert.strictEqual(mut.args.length, 1)
assert.strictEqual(mut.args[0], 4)
done()
})
})
})
describe('.$unwatch()', function () {
it('should unwatch the stuff', function (done) {
var triggered = false
vm.$watch('a.b.c', function () {
triggered = true
})
vm.$watch('a', function () {
triggered = true
})
vm.$watch('b', function () {
triggered = true
})
vm.$unwatch('a')
vm.$unwatch('b')
vm.$unwatch('a.b.c')
vm.a = { b: { c:123123 }}
vm.b.push(5)
nextTick(function () {
assert.notOk(triggered)
done()
})
})
})
describe('.$on', function () {
it('should register listener on vm\'s compiler\'s emitter', function () {
var t = new Vue(),
triggered = false,
msg = 'on test'
t.$on('test', function (m) {
assert.strictEqual(m, msg)
triggered = true
})
t.$compiler.emitter.emit('test', msg)
assert.ok(triggered)
})
})
describe('.$once', function () {
it('should invoke the listener only once', function () {
var t = new Vue(),
triggered = 0,
msg = 'on once'
t.$once('test', function (m) {
assert.strictEqual(m, msg)
triggered++
})
t.$compiler.emitter.emit('test', msg)
t.$compiler.emitter.emit('test', msg)
assert.strictEqual(triggered, 1)
})
})
describe('$off', function () {
it('should turn off the listener', function () {
var t = new Vue(),
triggered1 = false,
triggered2 = false,
f1 = function () {
triggered1 = true
},
f2 = function () {
triggered2 = true
}
t.$on('test', f1)
t.$on('test', f2)
t.$off('test', f1)
t.$compiler.emitter.emit('test')
assert.notOk(triggered1)
assert.ok(triggered2)
})
})
describe('$emit', function () {
it('should trigger the event', function () {
var t = new Vue(),
triggered = false
t.$compiler.emitter.on('test', function (m) {
triggered = m
})
t.$emit('test', 'hi')
assert.strictEqual(triggered, 'hi')
})
})
describe('.$broadcast()', function () {
it('should notify all child VMs', function () {
var triggered = 0,
msg = 'broadcast test'
var Child = Vue.extend({
ready: function () {
this.$on('hello', function (m) {
assert.strictEqual(m, msg)
triggered++
})
}
})
var Test = Vue.extend({
template: '<div v-component="test"></div><div v-component="test"></div>',
components: {
test: Child
}
})
var t = new Test()
t.$broadcast('hello', msg)
assert.strictEqual(triggered, 2)
})
})
describe('.$dispatch', function () {
it('should notify all ancestor VMs', function (done) {
var topTriggered = false,
midTriggered = false,
msg = 'emit test'
var Bottom = Vue.extend({
ready: function () {
var self = this
nextTick(function () {
self.$dispatch('hello', msg)
assert.ok(topTriggered)
assert.ok(midTriggered)
done()
})
}
})
var Middle = Vue.extend({
template: '<div v-component="bottom"></div>',
components: { bottom: Bottom },
ready: function () {
this.$on('hello', function (m) {
assert.strictEqual(m, msg)
midTriggered = true
})
}
})
var Top = Vue.extend({
template: '<div v-component="middle"></div>',
components: { middle: Middle },
ready: function () {
this.$on('hello', function (m) {
assert.strictEqual(m, msg)
topTriggered = true
})
}
})
new Top()
})
})
describe('DOM methods', function () {
var enterCalled,
leaveCalled,
callbackCalled
var v = new Vue({
attributes: {
'v-transition': 'test'
},
transitions: {
test: {
enter: function (el, change) {
enterCalled = true
change()
},
leave: function (el, change) {
leaveCalled = true
change()
}
}
}
})
function reset () {
enterCalled = false
leaveCalled = false
callbackCalled = false
}
function cb () {
callbackCalled = true
}
it('$appendTo', function (done) {
reset()
var parent = document.createElement('div')
v.$appendTo(parent, cb)
assert.strictEqual(v.$el.parentNode, parent)
assert.ok(enterCalled)
nextTick(function () {
assert.ok(callbackCalled)
done()
})
})
it('$before', function (done) {
reset()
var parent = document.createElement('div'),
ref = document.createElement('div')
parent.appendChild(ref)
v.$before(ref, cb)
assert.strictEqual(v.$el.parentNode, parent)
assert.strictEqual(v.$el.nextSibling, ref)
assert.ok(enterCalled)
nextTick(function () {
assert.ok(callbackCalled)
done()
})
})
it('$after', function (done) {
reset()
var parent = document.createElement('div'),
ref1 = document.createElement('div'),
ref2 = document.createElement('div')
parent.appendChild(ref1)
parent.appendChild(ref2)
v.$after(ref1, cb)
assert.strictEqual(v.$el.parentNode, parent)
assert.strictEqual(v.$el.nextSibling, ref2)
assert.strictEqual(ref1.nextSibling, v.$el)
assert.ok(enterCalled)
nextTick(function () {
assert.ok(callbackCalled)
next()
})
function next () {
reset()
v.$after(ref2, cb)
assert.strictEqual(v.$el.parentNode, parent)
assert.notOk(v.$el.nextSibling)
assert.strictEqual(ref2.nextSibling, v.$el)
assert.ok(enterCalled)
nextTick(function () {
assert.ok(callbackCalled)
done()
})
}
})
it('$remove', function (done) {
reset()
var parent = document.createElement('div')
v.$appendTo(parent)
v.$remove(cb)
assert.notOk(v.$el.parentNode)
assert.ok(enterCalled)
assert.ok(leaveCalled)
nextTick(function () {
assert.ok(callbackCalled)
done()
})
})
})
describe('.$destroy', function () {
// since this simply delegates to Compiler.prototype.destroy(),
// that's what we are actually testing here.
var destroy = require('vue/src/compiler').prototype.destroy
var beforeDestroyCalled = false,
afterDestroyCalled = false,
observerOffCalled = false,
emitterOffCalled = false,
dirUnbindCalled = false,
expUnbindCalled = false,
bindingUnbindCalled = false,
unobserveCalled = 0,
elRemoved = false,
externalBindingUnbindCalled = false
var dirMock = {
binding: {
compiler: null,
instances: []
},
unbind: function () {
dirUnbindCalled = true
}
}
dirMock.binding.instances.push(dirMock)
var bindingsMock = Object.create({
'test2': {
unbind: function () {
externalBindingUnbindCalled = true
}
}
})
bindingsMock.test = {
root: true,
key: 'test',
value: {
__observer__: {
off: function () {
unobserveCalled++
return this
}
}
},
unbind: function () {
bindingUnbindCalled = true
}
}
var compilerMock = {
options: {
beforeDestroy: function () {
beforeDestroyCalled = true
},
afterDestroy: function () {
afterDestroyCalled = true
}
},
observer: {
off: function () {
observerOffCalled = true
},
proxies: {
'test.': {}
}
},
emitter: {
off: function () {
emitterOffCalled = true
}
},
dirs: [dirMock],
exps: [{
unbind: function () {
expUnbindCalled = true
}
}],
bindings: bindingsMock,
childId: 'test',
parentCompiler: {
childCompilers: [],
vm: {
$: {
'test': true
}
}
},
vm: {
$remove: function () {
elRemoved = true
}
},
execHook: function (id) {
this.options[id].call(this)
}
}
compilerMock.parentCompiler.childCompilers.push(compilerMock)
destroy.call(compilerMock)
it('should call the pre and post destroy hooks', function () {
assert.ok(beforeDestroyCalled)
assert.ok(afterDestroyCalled)
})
it('should turn observer and emitter off', function () {
assert.ok(observerOffCalled)
assert.ok(emitterOffCalled)
})
it('should unbind all directives', function () {
assert.ok(dirUnbindCalled)
})
it('should remove directives from external bindings', function () {
assert.strictEqual(dirMock.binding.instances.indexOf(dirMock), -1)
})
it('should unbind all expressions', function () {
assert.ok(expUnbindCalled)
})
it('should unbind and unobserve own bindings', function () {
assert.ok(bindingUnbindCalled)
assert.strictEqual(unobserveCalled, 3)
})
it('should not unbind external bindings', function () {
assert.notOk(externalBindingUnbindCalled)
})
it('should remove self from parentCompiler', function () {
var parent = compilerMock.parentCompiler
assert.ok(parent.childCompilers.indexOf(compilerMock), -1)
assert.strictEqual(parent.vm.$[compilerMock.childId], undefined)
})
it('should remove the dom element', function () {
assert.ok(elRemoved)
})
})
describe('$data', function () {
it('should be the same data', function () {
var data = {},
vm = new Vue({data:data})
assert.strictEqual(vm.$data, data)
})
it('should be able to be swapped', function (done) {
var data1 = { a: 1 },
data2 = { a: 2 },
vm = new Vue({data: data1}),
emittedChange = false
vm.$watch('a', function (v) {
assert.equal(v, 2)
emittedChange = true
})
vm.$data = data2
assert.equal(vm.a, 2)
nextTick(function () {
assert.ok(emittedChange)
done()
})
})
})
})
|
tjwudi/vue
|
test/unit/specs/viewmodel.js
|
JavaScript
|
mit
| 15,636
|
import Montuno from "./montuno/Montuno";
import * as qs from "./shared/querystring";
import { isValidNoteName } from "./shared/validator";
import { montunos } from "./montunos";
document.addEventListener("DOMContentLoaded", () => {
addMontunosTo(montunos)(document.getElementById("montunos-listbox"));
addEventListeners();
renderMontuno();
});
function renderMontuno() {
const canvas = document.getElementById("canvas");
clearCanvas(canvas);
let { montuno = `${montunos[0].file}` } = qs.get();
const { root = "C" } = qs.get();
montuno = `montunos/${montuno}`;
fetch(montuno)
.then(data => data.json())
.then(json => Montuno.from(addSearchOptions(Object.assign({ element: canvas }, json), root)).render())
.catch(err => console.error("something went wrong", err));
}
function clearCanvas(canvas) {
const context = canvas.getContext("2d");
context.clearRect(0, 0, canvas.width, canvas.height);
const w = canvas.width;
canvas.width = 1;
canvas.width = w;
}
function addSearchOptions(props, root) {
if (isValidNoteName(root)) {
return Object.assign({}, props, {
root
});
}
console.log(`"${root}" is not a valid root note. Using default...`);
return props;
}
function addMontunosTo(montunos) {
return element => {
element.innerHTML = montunos.map(montuno => `
<paper-item value="${montuno.file}">${montuno.name}</paper-item>
`).join("");
}
}
function addEventListeners() {
document.getElementById("key-listbox").addEventListener("iron-select", ev => {
const root = ev.target.selectedItem.innerHTML.trim().toLowerCase();
qs.update({ root });
renderMontuno();
});
document.getElementById("montunos-listbox").addEventListener("iron-select", ev => {
const montuno = ev.target.selectedItem.getAttribute("value");
qs.update({ montuno });
renderMontuno();
});
}
|
fleidloff/montunos
|
app/js/app.js
|
JavaScript
|
mit
| 1,999
|
const scoreMap = {"EAIONRTLSU": 1, "DG": 2, "BCMP": 3, "FHVWY": 4, "K": 5, "JX": 8, "QZ": 10}
function scoreForLetter(letter) {
const lettersGroup = Object.keys(scoreMap)
const group = lettersGroup.find((g) => g.includes(letter))
return scoreMap[group]
}
export function calculteScore(letters) {
return Array.from(letters).reduce((acc, letter) => {
return acc + scoreForLetter(letter)
}, 0)
}
|
rcdexta/react-scrabble
|
src/helpers/scorer.js
|
JavaScript
|
mit
| 408
|
/* @flow */
import Scheduler from './Scheduler';
import delay from 'pdelay';
test('schedule', async () => {
let c = 0;
const s = new Scheduler();
s.schedule(() => {
expect(c++).toBe(0);
});
s.schedule(() => {
expect(c++).toBe(1);
});
expect(c).toBe(0);
await delay(0);
expect(c).toBe(2);
});
test('flush', () => {
let c = 0;
const s = new Scheduler();
s.schedule(() => {
expect(c++).toBe(0);
});
s.schedule(() => {
expect(c++).toBe(1);
});
expect(c).toBe(0);
s.flush();
expect(c).toBe(2);
});
test('big queue', () => {
let c = 0;
const s = new Scheduler();
for (let i = 0; i < 3000; i++) {
s.schedule(() => {
expect(c++).toBe(i);
});
}
expect(c).toBe(0);
s.flush();
expect(c).toBe(3000);
});
test('recursive flush in big queue', () => {
let c = 0;
const s = new Scheduler();
for (let i = 0; i < 5000; i++) {
s.schedule(() => {
expect(c++).toBe(i);
s.flush();
});
}
expect(c).toBe(0);
s.flush();
expect(c).toBe(5000);
});
|
StreakYC/live-set
|
src/Scheduler.test.js
|
JavaScript
|
mit
| 1,041
|
'use strict';
angular.module('trackingSystem.users.user-assigned-projects-directive', [])
.directive('userAssignedProjects', [
'$location',
'issuesDetailsData',
'pageSize',
'userDetailsData',
'projectDetailsData',
function ($location, issuesDetailsData, pageSize, userDetailsData, projectDetailsData) {
return {
restrict: 'A',
templateUrl: 'app/users/user-assigned-projects.html',
scope: {},
link: function (scope) {
scope.params = {
'startPage': 1,
'pageSize': pageSize,
'orderBy': 'DueDate desc&IssueKey'
};
scope.reloadIssues = function () {
issuesDetailsData.getIssuesByFilter(scope.params)
.then(function (response) {
if (response.data.TotalCount > scope.params.pageSize) {
scope.params.pageSize = response.data.TotalCount;
scope.reloadIssues();
}
scope.result = [];
var indexes = {};
angular.forEach(response.data.Issues, function (value, key) {
if (!indexes.hasOwnProperty(value.Project.Id)) {
scope.result.push(value.Project);
indexes[value.Project.Id] = null;
}
});
}, function (error) {
notifier.error(error.data.Message);
});
};
userDetailsData.getUser()
.then(function (response) {
scope.params = {
'startPage': 1,
'pageSize': pageSize,
'filter': 'Assignee.Id == "' + response.data.Id + '"'
};
scope.reloadIssues();
});
scope.projectSelected = function (id) {
$location.path('/projects/' + id);
};
}
};
}]);
|
Nitroto/Tracking-System
|
app/users/user-assigned-projects-directive.js
|
JavaScript
|
mit
| 2,509
|
'use strict';
let gulp = require('gulp'),
$ = require('gulp-load-plugins')({
pattern: ['gulp-*', 'q', 'run-sequence', 'del']
}),
environment = require('./lib/environment.js'),
Jasmine = require('jasmine'),
jasmine = new Jasmine();
// Configure Jasmine
jasmine.loadConfigFile('src/spec/support/jasmine.json');
gulp.task('jasmineTests', false, () => {
let deferred = $.q.defer();
jasmine.onComplete(function (err) {
return deferred.resolve();
});
jasmine.execute();
return deferred.promise;
});
// Mocha tests
gulp.task('mochaTests', false, () => {
let reporter = environment.get('reporter', 'progress');
return gulp.src('dist/spec/routes/exampleMochaSpec.js', {read: false})
// gulp-mocha needs filepaths so you can't have any plugins before it
.pipe($.mocha({ reporter: reporter }))
.pipe(gulp.dest('coverage'));
});
// Code coverage report
gulp.task('testCoverage', 'Generate a test coverage report (for mocha tests only)', () =>
$.runSequence(['build', 'cleanCoverage'], 'copyNonTs', () =>
gulp.src('dist/**/*.js')
.pipe($.istanbul())
.pipe($.istanbul.hookRequire())
.on('finish', function () {
gulp.src('dist/spec/routes/exampleMochaSpec.js')
.pipe($.mocha({ reporter: 'spec' }))
.pipe($.istanbul.writeReports({
dir: './coverage',
reporters: ['lcov'],
reportOpts: { dir: './coverage'}
})
);
})
)
);
// Submit generated code coverage information to coveralls
gulp.task('coveralls', 'Submit generated code coverage information to coveralls (works only under travis ci environment)', ['testCoverage'], () => {
gulp.src('coverage/**/lcov.info')
.pipe($.coveralls());
});
// Cleans the coverage folder
gulp.task('cleanCoverage', false, () => $.del(['coverage']));
// Main test tasks, choose between mocha or jasmine (or keep both)
gulp.task('test', 'Run unit tests (once)', ['build'], () => {
gulp.start('jasmineTests','mochaTests');
});
gulp.task('testWithoutBuild', 'Run unit tests(once) without building application', ['jasmineTests','mochaTests'])
|
inakianduaga/node-express-boilerplate
|
gulp/testing.js
|
JavaScript
|
mit
| 2,167
|
/*
* L.GeoJSON turns any GeoJSON data into a Leaflet layer.
*/
var L = require('leaflet');
var markerClusterGroup = require('./MarkerClusterGroup');
var GeoJSON = markerClusterGroup.extend({
initialize: function (geojson, options) {
L.setOptions(this, options);
if (!this.options.iconCreateFunction) {
this.options.iconCreateFunction = this._defaultIconCreateFunction;
}
this._featureGroup = L.featureGroup();
this._featureGroup.on(L.FeatureGroup.EVENTS, this._propagateEvent, this);
this._nonPointGroup = L.featureGroup();
this._nonPointGroup.on(L.FeatureGroup.EVENTS, this._propagateEvent, this);
this._inZoomAnimation = 0;
this._needsClustering = [];
this._needsRemoving = []; //Markers removed while we aren't on the map need to be kept track of
//The bounds of the currently shown area (from _getExpandedVisibleBounds) Updated on zoom/move
this._currentShownBounds = null;
this._queue = [];
this._layers = {};
if (geojson) {
this.addData(geojson);
}
},
addData: function (geojson) {
var features = L.Util.isArray(geojson) ? geojson : geojson.features,
i, len, feature;
if (features) {
for (i = 0, len = features.length; i < len; i++) {
// only add this if geometry or geometries are set and not null
feature = features[i];
if (feature.geometries || feature.geometry || feature.features || feature.coordinates) {
this.addData(feature);
}
}
return this;
}
var options = this.options;
if (options.filter && !options.filter(geojson)) { return this; }
var layer = GeoJSON.geometryToLayer(geojson, options);
if (!layer) {
return this;
}
layer.feature = GeoJSON.asFeature(geojson);
layer.defaultOptions = layer.options;
this.resetStyle(layer);
if (options.onEachFeature) {
options.onEachFeature(geojson, layer);
}
return this.addLayer(layer);
},
resetStyle: function (layer) {
// reset any custom styles
layer.options = layer.defaultOptions;
this._setLayerStyle(layer, this.options.style);
return this;
},
setStyle: function (style) {
return this.eachLayer(function (layer) {
this._setLayerStyle(layer, style);
}, this);
},
_setLayerStyle: function (layer, style) {
if (typeof style === 'function') {
style = style(layer.feature);
}
if (layer.setStyle) {
layer.setStyle(style);
}
}
});
L.extend(GeoJSON, {
geometryToLayer: function (geojson, options) {
var geometry = geojson.type === 'Feature' ? geojson.geometry : geojson,
coords = geometry ? geometry.coordinates : null,
layers = [],
pointToLayer = options && options.pointToLayer,
coordsToLatLng = options && options.coordsToLatLng || this.coordsToLatLng,
latlng, latlngs, i, len;
if (!coords && !geometry) {
return null;
}
switch (geometry.type) {
case 'Point':
latlng = coordsToLatLng(coords);
return pointToLayer ? pointToLayer(geojson, latlng) : new L.Marker(latlng);
case 'MultiPoint':
for (i = 0, len = coords.length; i < len; i++) {
latlng = coordsToLatLng(coords[i]);
layers.push(pointToLayer ? pointToLayer(geojson, latlng) : new L.Marker(latlng));
}
return new L.FeatureGroup(layers);
case 'LineString':
case 'MultiLineString':
latlngs = this.coordsToLatLngs(coords, geometry.type === 'LineString' ? 0 : 1, coordsToLatLng);
return new L.Polyline(latlngs, options);
case 'Polygon':
case 'MultiPolygon':
latlngs = this.coordsToLatLngs(coords, geometry.type === 'Polygon' ? 1 : 2, coordsToLatLng);
return new L.Polygon(latlngs, options);
case 'GeometryCollection':
for (i = 0, len = geometry.geometries.length; i < len; i++) {
var layer = this.geometryToLayer({
geometry: geometry.geometries[i],
type: 'Feature',
properties: geojson.properties
}, options);
if (layer) {
layers.push(layer);
}
}
return new L.FeatureGroup(layers);
default:
throw new Error('Invalid GeoJSON object.');
}
},
coordsToLatLng: function (coords) {
return new L.LatLng(coords[1], coords[0], coords[2]);
},
coordsToLatLngs: function (coords, levelsDeep, coordsToLatLng) {
var latlngs = [];
for (var i = 0, len = coords.length, latlng; i < len; i++) {
latlng = levelsDeep ?
this.coordsToLatLngs(coords[i], levelsDeep - 1, coordsToLatLng) :
(coordsToLatLng || this.coordsToLatLng)(coords[i]);
latlngs.push(latlng);
}
return latlngs;
},
latLngToCoords: function (latlng) {
return latlng.alt !== undefined ?
[latlng.lng, latlng.lat, latlng.alt] :
[latlng.lng, latlng.lat];
},
latLngsToCoords: function (latlngs, levelsDeep, closed) {
var coords = [];
for (var i = 0, len = latlngs.length; i < len; i++) {
coords.push(levelsDeep ?
GeoJSON.latLngsToCoords(latlngs[i], levelsDeep - 1, closed) :
GeoJSON.latLngToCoords(latlngs[i]));
}
if (!levelsDeep && closed) {
coords.push(coords[0]);
}
return coords;
},
getFeature: function (layer, newGeometry) {
return layer.feature ?
L.extend({}, layer.feature, {geometry: newGeometry}) :
GeoJSON.asFeature(newGeometry);
},
asFeature: function (geoJSON) {
if (geoJSON.type === 'Feature') {
return geoJSON;
}
return {
type: 'Feature',
properties: {},
geometry: geoJSON
};
}
});
var PointToGeoJSON = {
toGeoJSON: function () {
return GeoJSON.getFeature(this, {
type: 'Point',
coordinates: GeoJSON.latLngToCoords(this.getLatLng())
});
}
};
L.Marker.include(PointToGeoJSON);
L.Circle.include(PointToGeoJSON);
L.CircleMarker.include(PointToGeoJSON);
L.Polyline.prototype.toGeoJSON = function () {
var multi = !L.Polyline._flat(this._latlngs);
var coords = GeoJSON.latLngsToCoords(this._latlngs, multi ? 1 : 0);
return GeoJSON.getFeature(this, {
type: (multi ? 'Multi' : '') + 'LineString',
coordinates: coords
});
};
L.Polygon.prototype.toGeoJSON = function () {
var holes = !L.Polyline._flat(this._latlngs),
multi = holes && !L.Polyline._flat(this._latlngs[0]);
var coords = GeoJSON.latLngsToCoords(this._latlngs, multi ? 2 : holes ? 1 : 0, true);
if (!holes) {
coords = [coords];
}
return GeoJSON.getFeature(this, {
type: (multi ? 'Multi' : '') + 'Polygon',
coordinates: coords
});
};
L.LayerGroup.include({
toMultiPoint: function () {
var coords = [];
this.eachLayer(function (layer) {
coords.push(layer.toGeoJSON().geometry.coordinates);
});
return GeoJSON.getFeature(this, {
type: 'MultiPoint',
coordinates: coords
});
},
toGeoJSON: function () {
var type = this.feature && this.feature.geometry && this.feature.geometry.type;
if (type === 'MultiPoint') {
return this.toMultiPoint();
}
var isGeometryCollection = type === 'GeometryCollection',
jsons = [];
this.eachLayer(function (layer) {
if (layer.toGeoJSON) {
var json = layer.toGeoJSON();
jsons.push(isGeometryCollection ? json.geometry : GeoJSON.asFeature(json));
}
});
if (isGeometryCollection) {
return GeoJSON.getFeature(this, {
geometries: jsons,
type: 'GeometryCollection'
});
}
return {
type: 'FeatureCollection',
features: jsons
};
}
});
module.exports = function (geojson, options) {
return new GeoJSON(geojson, options);
};
|
paulserraino/leaflet-geojson-cluster
|
src/GeoJSONCluster.js
|
JavaScript
|
mit
| 7,732
|
angular.module('todoService', [])
.factory('Todos', function($http) {
return {
get: function() {
return $http.get('/api/todos');
},
create: function(todoData) {
return $http.post('/api/todos', todoData);
},
delete: function(id) {
return $http.delete('/api/todos/' + id);
}
}
});
|
al3jo/mean-todo
|
public/js/services/todos.js
|
JavaScript
|
mit
| 352
|