text
stringlengths 2
6.14k
|
|---|
{
"status" : "active"
}
|
export const throttle = (func, limit) => {
let inThrottle
return function () {
const args = arguments
const context = this
if (!inThrottle) {
func.apply(context, args)
inThrottle = true
setTimeout(() => { inThrottle = false }, limit)
}
}
}
export const debounce = (func, delay) => {
let inDebounce
return function () {
const context = this
const args = arguments
clearTimeout(inDebounce)
inDebounce = setTimeout(() => func.apply(context, args), delay)
}
}
|
/*!
* UI development toolkit for HTML5 (OpenUI5)
* (c) Copyright 2009-2016 SAP SE or an SAP affiliate company.
* Licensed under the Apache License, Version 2.0 - see LICENSE.txt.
*/
// Provides control sap.ui.commons.layout.MatrixLayout.
sap.ui.define(['jquery.sap.global', './MatrixLayoutCell', './MatrixLayoutRow', 'sap/ui/commons/library', 'sap/ui/core/Control', 'sap/ui/core/EnabledPropagator'],
function(jQuery, MatrixLayoutCell, MatrixLayoutRow, library, Control, EnabledPropagator) {
"use strict";
/**
* Constructor for a new layout/MatrixLayout.
*
* @param {string} [sId] id for the new control, generated automatically if no id is given
* @param {object} [mSettings] initial settings for the new control
*
* @class
*
* <p>
* A matrix layout arranges controls in a grid structure, using rows which
* need not have the same number of cells.
* </p>
*
* <p>
* It uses predefined cell classes that guarantee appropriate distances
* between cells in the grid. The cell's <code>vGutter</code> property lets
* you specify additional horizontal distances easily. You can set these
* additional distances (known as gutters) with or without separators.
* The distance for each cell is specified by assigning a specific
* enumeration value of the class <code>LayoutCellSeparator</code> of the
* matrix data object.
* </p>
*
* <p>
* You should <b>avoid nesting</b> matrix layouts. You should only use a
* matrix layout if you need to align controls horizontally across rows.
* </p>
* @extends sap.ui.core.Control
*
* @author SAP SE
* @version 1.38.4
*
* @constructor
* @public
* @deprecated Since version 1.38. Instead, use the <code>sap.ui.layout.Grid</code> control.
* @alias sap.ui.commons.layout.MatrixLayout
* @ui5-metamodel This control/element also will be described in the UI5 (legacy) designtime metamodel
*/
var MatrixLayout = Control.extend("sap.ui.commons.layout.MatrixLayout", /** @lends sap.ui.commons.layout.MatrixLayout.prototype */ { metadata : {
library : "sap.ui.commons",
properties : {
/**
* CSS width of the matrix layout.
* If the LayoutFixed = true a adequate width should be provided.
*/
width : {type : "sap.ui.core.CSSSize", group : "Dimension", defaultValue : null},
/**
*
* CSS height of the matrix layout.
*/
height : {type : "sap.ui.core.CSSSize", group : "Dimension", defaultValue : null},
/**
* Sets the table layout. If fixed the width parameter of a column has priority, if not the width of the content of the colums has priority.
* The default is "fixed".
* If the fixed layout is used a adequate width of the MatrixLayout should be provided. Otherwise the column width displayed could be different than the given ones because of browser dependend optimazations.
*/
layoutFixed : {type : "boolean", group : "Appearance", defaultValue : true},
/**
* Number of columns. If not specified, the number of columns will be determined from the given cells.
*/
columns : {type : "int", group : "Appearance", defaultValue : null},
/**
* Widths of the columns. Use an array to define the widths of the columns.
* If a column shall have an automatical sizing enter "auto" for this column width.
*/
widths : {type : "sap.ui.core.CSSSize[]", group : "Appearance", defaultValue : null}
},
defaultAggregation : "rows",
aggregations : {
/**
*
* The matrix layout's individual rows.
*/
rows : {type : "sap.ui.commons.layout.MatrixLayoutRow", multiple : true, singularName : "row"}
}
}});
EnabledPropagator.call(MatrixLayout.prototype, true, /* legacy mode */ true);
/**
* Creates a new matrix layout row and appends it to this matrix layout.
*
* Each argument must be either a matrix layout cell, which is added to the row
* "as is", or an arbitrary content control, which is wrapped with a new
* (default) matrix layout cell first and then added to the row.
*
* @param {sap.ui.core.Control|sap.ui.commons.layout.MatrixLayoutCell|string} rowContent to add
* @return {sap.ui.commons.layout.MatrixLayout} <code>this</code> to allow method chaining
* @public
* @ui5-metamodel This method also will be described in the UI5 (legacy) designtime metamodel
*/
MatrixLayout.prototype.createRow = function() {
var oRow = new MatrixLayoutRow();
this.addRow(oRow);
for (var i = 0; i < arguments.length; i++) {
var oContent = arguments[i];
var oCell;
if (oContent instanceof MatrixLayoutCell) {
// matrix layout cell given, use as is
oCell = oContent;
} else if (oContent instanceof Control) {
// any control given, wrap with matrix layout cell first
oCell = new MatrixLayoutCell({content : oContent});
} else if (oContent instanceof Object && oContent.height) {
oRow.setHeight(oContent.height);
} else {
// any string(?) given, display it
var sText = oContent ? oContent.toString() : "";
oCell = new MatrixLayoutCell({
content : new sap.ui.commons.TextView({text : sText})});
}
oRow.addCell(oCell);
}
return this;
};
/*
* Overwrites Setter for property <code>widths</code>.
* Sets the widths of the columns. The values must be stored in an array to be used in renderer.
* to be compatible with previous version also allow list of values.
* @param {sap.ui.core.CSSSize[]} aWidths new value for property <code>widths</code>
* @return {sap.ui.commons.layout.MatrixLayout} <code>this</code> to allow method chaining
* @public
*/
MatrixLayout.prototype.setWidths = function( aWidths ) {
var aSetWidths;
if (!jQuery.isArray(aWidths)) {
// a list of values is used instead of an array -> use this as array
aSetWidths = jQuery.makeArray(arguments);
} else {
aSetWidths = aWidths;
}
// set "auto" for empty values
for ( var i = 0; i < aSetWidths.length; i++) {
if (aSetWidths[i] == "" || !aSetWidths[i]) {
aSetWidths[i] = "auto";
}
}
this.setProperty("widths", aSetWidths);
return this;
};
return MatrixLayout;
}, /* bExport= */ true);
|
import glob from 'glob';
import { CLIEngine } from 'eslint';
import { assert } from 'chai';
const paths = glob.sync('./src/**/!(*.spec).js');
const engine = new CLIEngine({
envs: ['node', 'mocha'],
useEslintrc: true
});
const results = engine.executeOnFiles(paths).results;
describe('ESLint', function() {
results.forEach((result) => generateTest(result));
});
function generateTest(result) {
const { filePath, messages, errorCount } = result;
it(`validates ${filePath}`, function() {
if (messages.length > 0 && errorCount > 0) {
assert.fail(false, true, formatMessages(messages));
}
});
}
function formatMessages(messages) {
const errors = messages.map((message) => {
return `${message.line}:${message.column} ${message.message.slice(0, -1)} - ${message.ruleId}\n`;
});
return `\n${errors.join('')}`;
}
|
module.exports = {
options: {
width: 300,
height: 300,
overwrite: true
},
resize: {
files: {
'public/assets/projects/thumbnails/*': 'public/assets/projects/*'
}
}
};
|
// set timeouts for feedback messages
$(document).ready(function () {
$('.feedback .alert-success').delay(2000).fadeOut(500);
$('.feedback .alert-info').delay(2500).fadeOut(500);
$('.feedback .alert-warning').delay(3000).fadeOut(500);
$('.feedback .alert-danger').delay(4500).fadeOut(500);
$('.timeshift-blink').each(function() {
var elem = $(this);
setInterval(function() {
if (elem.css('visibility') == 'hidden') {
elem.css('visibility', 'visible');
} else {
elem.css('visibility', 'hidden');
}
}, 500);
});
});
|
var $ = global.jQuery = require('jquery');
var add = require('lodash/math/add');
var flow = require('lodash/function/flow');
require('bootstrap/js/button');
function square(n) {
return n * n;
}
var addSquare = flow(add, square);
$('#myButton').on('click', function() {
var $btn = $(this);
var loading = $btn.data('myButton-loading');
if (!loading) {
$btn.data('myButton-loading', true);
$btn.button('loading');
setTimeout(function(){
$btn.removeData('myButton-loading');
$btn.button('reset');
}, 1000);
}
});
|
import { ConnectDataClass, UserClass, UserDataClass } from './class_models'
import { ivanka } from './base64img'
const createConnectData = (description, text) => {
return new ConnectDataClass(description,text)
}
const createUser = () => {
let userData_personalData_name = createConnectData('Name','Trump')
let userData_personalData_surname = createConnectData('Vorname','Ivanka')
let userData_personalData_phone = createConnectData('Handy','2341234 12341234')
let userData_personalData_image = createConnectData('Image',ivanka)
let userData_hashTagData_color = createConnectData('Lieblingsstyle','Bizz')
let userData_hashTagData_hobby = createConnectData('Interessen','Mode, Beauty')
let userData_socialData_facebook = createConnectData('Facebook','https://web.facebook.com/DonaldTrump/?_rdc=1&_rdr')
let userData_socialData_linkedIn = createConnectData('LinkedIn','https://www.linkedin.com/in/donald-trump-jr-4454b862/?locale=de_DE')
let userData_socialData_twitter = createConnectData('Twitter','https://twitter.com/realdonaldtrump?lang=de')
let publicSharedData_personalData = []
publicSharedData_personalData.push(userData_personalData_name)
publicSharedData_personalData.push(userData_personalData_phone)
let publicSharedData_socialData = []
publicSharedData_socialData.push(userData_socialData_facebook)
publicSharedData_socialData.push(userData_socialData_twitter)
let publicSharedData_hashTagData = []
publicSharedData_hashTagData.push(userData_hashTagData_hobby)
publicSharedData_hashTagData.push(userData_hashTagData_color)
let userData_personalData = []
userData_personalData.push(userData_personalData_surname)
userData_personalData.push(userData_personalData_name)
userData_personalData.push(userData_personalData_phone)
userData_personalData.push(userData_personalData_image)
let userData_socialData = []
userData_socialData.push(userData_socialData_facebook)
userData_socialData.push(userData_socialData_linkedIn)
userData_socialData.push(userData_socialData_twitter)
let userData_hashTagData = []
userData_hashTagData.push(userData_hashTagData_hobby)
userData_hashTagData.push(userData_hashTagData_color)
let userDataClass = new UserDataClass(userData_personalData, userData_socialData, userData_hashTagData)
let publicSharedDataClass = new UserDataClass(publicSharedData_personalData, publicSharedData_socialData, publicSharedData_hashTagData)
let ivanka_user = new UserClass('a2',userDataClass,publicSharedDataClass,[])
return ivanka_user
}
const ivanka_user = createUser()
export default ivanka_user
|
var bell_sounds = function () {
var ctx = new AudioContext();
var ring_bell = function (freq, length) {
var osc = ctx.createOscillator();
var gain = ctx.createGain();
osc.frequency.value = freq;
osc.connect(gain);
gain.connect(ctx.destination);
osc.start();
gain.gain.linearRampToValueAtTime(1.0, ctx.currentTime + 0.01);
gain.gain.linearRampToValueAtTime(0, ctx.currentTime + length / 1000 * 4);
var stop = function () {
osc.stop(ctx.currentTime + length / 1000 * 4 + 0.02);
};
setTimeout(stop.bind(window), length);
};
return {
ring_bell: ring_bell,
};
}();
bell_sounds.ring_bell();
module.exports = bell_sounds;
|
import React, { Component } from 'react';
import {sub} from 'elegant-react';
import Counters from './Counters';
import {on, stream} from 'flyd';
import counterPlugin from './counter-plugin';
export default class App extends Component {
constructor(props) {
super(props);
const {atom} = this.props;
this.edit = ::atom.updateState;
this.state = {state: atom.getState()};
}
componentWillMount() {
const {atom} = this.props;
const state = atom.getState();
this.incrementActionStreams =
state.get('counts').map((_,i) =>
counterPlugin(sub(this.edit, 'counts', i)).incrementAction$
).toArray();
// connect atom updates to component's state
on(state => this.setState({state}), atom.didSetState$);
}
render() {
const {state} = this.state;
const {edit} = this;
const sort = state.get('sort');
const sortOrder = state.get('sortOrder');
const compact = state.get('compact');
const toggleSort = sub(edit, 'sort');
const toggleSortOrder = sub(edit, 'sortOrder');
const toggleCompact = sub(edit, 'compact');
return <div>
<label style={{ position: 'absolute', top: 5, right: 50}}>
<input type="checkbox" checked={sort}
onChange={event => toggleSort(v => !v)}/>
sort
</label>
<label style={{ position: 'absolute', top: 5, right: 100}}>
<input type="checkbox" checked={sortOrder===1}
onChange={event => {
toggleSort(v => true);
toggleSortOrder(v => -v)}}/>
sort asc
</label>
<label style={{ position: 'absolute', top: 5, right: 180}}>
<input type="checkbox" checked={compact}
onChange={event => toggleCompact(c => !c)}/>
compact
</label>
<Counters
lineHeight={compact ? 30 : 40}
sortOrder={sortOrder * ~~sort}
counts={state.get('counts')}
incrementActionStreams={this.incrementActionStreams} />
</div>
}
}
|
'use strict';
/**
* @ngdoc function
* @name com.module.users.controller:LoginCtrl
* @description Login Controller
* @requires $scope
* @requires $routeParams
* @requires $location
* Contrller for Login Page
**/
angular.module('com.module.users')
.controller('LoginCtrl', function($scope, $routeParams, $location,
CoreService, User, AppAuth, AuthProvider, gettextCatalog) {
var TWO_WEEKS = 1000 * 60 * 60 * 24 * 7 * 2;
$scope.credentials = {
ttl: TWO_WEEKS,
rememberMe: true
};
if (CoreService.env.name === 'development') {
$scope.credentials.email = 'boris@g.com';
$scope.credentials.password = '1234';
}
$scope.schema = [{
label: '',
property: 'email',
placeholder: gettextCatalog.getString('Email'),
type: 'email',
attr: {
required: true,
ngMinlength: 4
},
msgs: {
required: gettextCatalog.getString('You need an email address'),
email: gettextCatalog.getString('Email address needs to be valid'),
valid: gettextCatalog.getString('Nice email address!')
}
}, {
label: '',
property: 'password',
placehodler: gettextCatalog.getString('Password'),
type: 'password',
attr: {
required: true
}
}, {
property: 'rememberMe',
label: gettextCatalog.getString('Stay signed in'),
type: 'checkbox'
}];
$scope.options = {
validation: {
enabled: true,
showMessages: false
},
layout: {
type: 'basic',
labelSize: 3,
inputSize: 9
}
};
$scope.socialLogin = function(provider) {
window.location = CoreService.env.siteUrl + provider.authPath;
};
AuthProvider.count(function(result) {
if (result.count > 0) {
AuthProvider.find(function(result) {
$scope.authProviders = result;
});
}
});
$scope.login = function() {
$scope.loginResult = User.login({
include: 'user',
rememberMe: $scope.credentials.rememberMe
}, $scope.credentials,
function(user) {
console.log(user.id); // => acess token
console.log(user.ttl); // => 1209600 time to live
console.log(user.created); // => 2013-12-20T21:10:20.377Z
console.log(user.userId); // => 1
var next = $location.nextAfterLogin || '/';
$location.nextAfterLogin = null;
AppAuth.currentUser = $scope.loginResult.user;
CoreService.toastSuccess(gettextCatalog.getString('Logged in'),
gettextCatalog.getString('You are logged in!'));
if (next === '/login') {
next = '/';
}
$location.path(next);
},
function(res) {
$scope.loginError = res.data.error;
});
};
});
|
var mariadb = require('../database/mariadb');
module.exports = function (email, callback) {
mariadb.get(function (err, con) {
if (err) {
if (con) {
con.release();
}
console.log("Failed to get mariadb.");
return callback(err);
}
var sql = "SELECT email FROM account WHERE email=?";
var data = [email];
var exec = con.query(sql, data, function (err, result) {
if (con) {
con.release();
}
console.log("[findEmail] SQL : " + exec.sql);
if (err) {
callback(err);
} else {
callback(null, (result.length > 0));
}
});
});
};
|
/* Handles converting the app's concept of a 'project'
* to/from the GitHub API's concept of an 'issue'
*/
const commentExtractionRegex = /<!-- ([.\d]+),([.\d]+) -->/
function parseCoordinatesFromComment (commentLines) {
var lastLine = commentLines.slice(-1)[0]
var matches = commentExtractionRegex.exec(lastLine)
return matches ? { x: matches[1], y: matches[2] }
: { x: 0, y: 0 }
}
export default {
deserializeCommentToProject: function (comment) {
var textLines = comment.body.split('\r\n')
var coords = parseCoordinatesFromComment(textLines)
return {
id: comment.id,
title: textLines[0],
description: textLines[1],
username: comment.user.login,
userId: comment.user.id,
avatar_thumbnail: comment.user.avatar_url + '&s=' + 40,
avatar: comment.user.avatar_url + '&s=' + 120,
x: coords.x,
y: coords.y,
editMode: false
}
},
serializeProjectToComment: function (project) {
let body = project.title + '\r\n' +
(project.description || '') + '\r\n' +
`<!-- ${project.x},${project.y} -->`
return body
}
}
|
var searchData=
[
['lecture_5fdata',['lecture_data',['../projet__MAUSSION__RIOU_8cpp.html#a667003cfd6f66a62d7f583af4a61459b',1,'projet_MAUSSION_RIOU.cpp']]]
];
|
// All code points in the `Inscriptional_Pahlavi` script as per Unicode v9.0.0:
[
0x10B60,
0x10B61,
0x10B62,
0x10B63,
0x10B64,
0x10B65,
0x10B66,
0x10B67,
0x10B68,
0x10B69,
0x10B6A,
0x10B6B,
0x10B6C,
0x10B6D,
0x10B6E,
0x10B6F,
0x10B70,
0x10B71,
0x10B72,
0x10B78,
0x10B79,
0x10B7A,
0x10B7B,
0x10B7C,
0x10B7D,
0x10B7E,
0x10B7F
];
|
//tv.js
Page({
data: {
listArray:[
{date:"2016ๅนด11ๆ20ๆฅ ๆๆไบ ไปๅคฉ",
items:[
{name:"ๆ็ฅ",imageUrl:"http://www.hzeduask.com/edit5.0/uploadfile/201009/20100918133824708.jpg"
,scores:"9.0",id:"123123"
}
]
}
],
},
onLoad: function () {
},
didSelected:function(event) {
console.log(event)
}
})
|
import React, { Component } from 'react';
/**
* Button that counts how many times it was pressed and exposes a `@public` method to reset itself.
*/
export default class CounterButton extends Component {
constructor() {
super();
this.state = {
value: 0,
};
}
/**
* Sets the counter to a particular value.
*
* @public
* @version 1.0.5
* @param {Number} [newValue=0] New value for the counter
* @returns {string} Test
*/
set(newValue = 0) {
this.setState({
value: parseInt(newValue, 10),
});
}
/**
* Increments the counter. This method is not marked @public and is not visible in the styleguide.
*/
increment() {
this.setState({
value: this.state.value + 1,
});
}
render() {
return (
<button className="button" onClick={this.increment.bind(this)}>
{this.state.value}
</button>
);
}
}
|
/**
CSRF
Provides Cross-Site Request Forgery protection for applications.
ยป Configuration Options
{string} tokenSuffix: Suffix to append to csrf tokens
{int} onFailure: HTTP Error code to respond on token validation failure
ยป Usage example
The ideal usage is to create the csrf token before rendering the view,
this allows the token to be present in logicless templates (e.g. mustachioed
template engines, such as hogan):
res.render('form', {
myToken: req.csrfToken('protect')
});
You can also use the csrf middleware directly:
res.render('form', {
myToken: app.csrf.getToken(req, 'protect')
});
Additionally, you can create the token from inside any template engine
that supports logic. The following example uses the liquor engine:
<input type="hidden" name="protect_key" value="#{req.csrfToken('protect')}" />
*/
var app = protos.app;
require('./request.js');
function Csrf(config, middleware) {
// Dependency check
if (!app.supports.session) {
throw new Error("The 'csrf' middleware requires 'session'");
} else if (!app.supports.body_parser) {
throw new Error("The 'csrf' middleware requires 'body_parser'");
}
// Attach instance to app singleton
app[middleware] = this;
// Middleware configuration
config = protos.extend({
tokenSuffix: '_key',
}, config);
// Add non-enumerable config
Object.defineProperty(this, 'config',{
value: config,
writable: true,
enumerable: false,
configurable: true
});
}
/**
Checks the CSRF Token for a given form
@param {object} req
@param {string} token
@param {object} fields
@returns {boolean} Whether or not the token is valid
@public
*/
Csrf.prototype.checkToken = function(req, token, fields) {
// Accessing `this` is faster than accessing `app` in outer closure
token += this.config.tokenSuffix;
// These conditions must be satisfied:
// a) Token is available in received fields
// b) Token is available in session
// c) If fields token matches session token
var isValid = (token in fields) && (token in req.session) && (fields[token] === req.session[token]);
// Return valid value
return isValid;
}
/**
Retrieves and/or sets a csrf token
@param {object} req
@param {string} token
@returns {string} hash
@public
*/
Csrf.prototype.getToken = function(req, token) {
token += this.config.tokenSuffix;
if (! req.session[token]) req.session[token] = this.createHash();
return req.session[token];
}
/**
Creates a hash to be used as a token
@returns {string} hash
@public
*/
Csrf.prototype.createHash = function() {
return app.md5(Math.random().toString());
}
module.exports = Csrf;
|
const mongoose = require("mongoose");
const db = require("../../models");
mongoose.Promise = global.Promise;
//This file seeds the database
mongoose.connect(
process.env.MONGODB_URI || "mongodb://localhost/petrescuers",
{
useMongoClient: true
}
);
//Seeding the breed collection with the breed recommendation (breed) for each search combination (breedId)
const breedLookupSeed = [
{
breedId: 'smallhomelightcalm',
breed: 'Chihuahua'
},
{
breedId: 'smallhomeanycalm',
breed: 'Pug'
},
{
breedId: 'smallhomelighthighenergy',
breed: 'Beagle'
},
{
breedId: 'smallhomeanyhighenergy',
breed: 'Jack Russell Terrier'
},
{
breedId: 'smallapartmentlightcalm',
breed: 'Shih Tzu'
},
{
breedId: 'smallapartmentanycalm',
breed: 'Dachshund'
},
{
breedId: 'smallapartmentlighthighenergy',
breed: 'Poodle'
},
{
breedId: 'smallapartmentanyhighenergy',
breed: 'Corgi'
},
{
breedId: 'mediumhomelightcalm',
breed: 'Chow Chow'
},
{
breedId: 'mediumhomeanycalm',
breed: 'Hound'
},
{
breedId: 'mediumhomelighthighenergy',
breed: 'Pit Bull'
},
{
breedId: 'mediumhomeanyhighenergy',
breed: 'Labrador Retriever'
},
{
breedId: 'mediumapartmentlightcalm',
breed: 'Bulldog'
},
{
breedId: 'mediumapartmentanycalm',
breed: 'Shar Pei'
},
{
breedId: 'mediumapartmentlighthighenergy',
breed: 'Border Collie'
},
{
breedId: 'mediumapartmentanyhighenergy',
breed: 'Boxer'
},
{
breedId: 'largehomelightcalm',
breed: 'Mastiff'
},
{
breedId: 'largehomeanycalm',
breed: 'Great Dane'
},
{
breedId: 'largehomelighthighenergy',
breed: 'Pit Bull'
},
{
breedId: 'largehomeanyhighenergy',
breed: 'German Shepherd'
},
{
breedId: 'largeapartmentlightcalm',
breed: 'American Bulldog'
},
{
breedId: 'largeapartmentanycalm',
breed: 'Shar Pei'
},
{
breedId: 'largeapartmentlighthighenergy',
breed: 'Border Collie'
},
{
breedId: 'largeapartmentanyhighenergy',
breed: 'Greyhound'
},
{
breedId: 'smallyesyes',
breed: 'Bombay'
},
{
breedId: 'smallyesno',
breed: 'Russian Blue'
},
{
breedId: 'smallnono',
breed: 'Persian'
},
{
breedId: 'smallnoyes',
breed: 'Oriental'
},
{
breedId: 'mediumyesyes',
breed: 'Siamese'
},
{
breedId: 'mediumyesno',
breed: 'Russian Blue'
},
{
breedId: 'mediumnono',
breed: 'Persian'
},
{
breedId: 'mediumnoyes',
breed: 'Turkish Van'
},
{
breedId: 'largeyesyes',
breed: 'Maine Coon'
},
{
breedId: 'largeyesno',
breed: 'Russian Blue'
},
{
breedId: 'largenono',
breed: 'American Shorthair'
},
{
breedId: 'largenoyes',
breed: 'Manx'
},
];
db.BreedLookup
.remove({})
.then(() => db.BreedLookup.collection.insertMany(breedLookupSeed))
.then(data => {
console.log(data.insertedIds.length + " records inserted!");
process.exit(0);
})
.catch(err => {
console.error(err);
process.exit(1);
});
|
/**
* This module formats precise time differences as a vague/fuzzy
* time, e.g. '3 weeks ago', 'just now' or 'in 2 hours'.
*/
/*globals define, module */
(function (globals) {
'use strict';
var times = {
year: 31557600000, // 1000 ms * 60 s * 60 m * 24 h * 365.25 d
month: 2629800000, // 31557600000 ms / 12 m
week: 604800000, // 1000 ms * 60 s * 60 m * 24 h * 7 d
day: 86400000, // 1000 ms * 60 s * 60 m * 24 h
hour: 3600000, // 1000 ms * 60 s * 60 m
minute: 60000 // 1000 ms * 60 s
},
languages = {
en: {
year: [ 'year', 'years' ],
month: [ 'month', 'months' ],
week: [ 'week', 'weeks' ],
day: [ 'day', 'days' ],
hour: [ 'hour', 'hours' ],
minute: [ 'minute', 'minutes' ],
past: function (vagueTime, unit) {
return vagueTime + ' ' + unit + ' ago';
},
future: function (vagueTime, unit) {
return 'in ' + vagueTime + ' ' + unit;
},
defaults: {
past: 'just now',
future: 'soon'
}
},
fr: {
year: [ 'an', 'ans' ],
month: [ 'mois', 'mois' ],
week: [ 'semaine', 'semaines' ],
day: [ 'jour', 'jours' ],
hour: [ 'heure', 'heures' ],
minute: [ 'minute', 'minutes' ],
past: function (vagueTime, unit) {
return 'il y a ' + vagueTime + ' ' + unit;
},
future: function (vagueTime, unit) {
return 'dans ' + vagueTime + ' ' + unit;
},
defaults: {
past: 'tout de suite',
future: 'bientรดt'
}
}
},
defaultLanguage = 'en',
functions = {
get: getVagueTime
};
exportFunctions();
/**
* Public function `get`.
*
* Returns a vague time, such as '3 weeks ago', 'just now' or 'in 2 hours'.
*
* @option [from] {Date} The origin time. Defaults to `Date.now()`.
* @option [to] {Date} The target time. Defaults to `Date.now()`.
* @option [units] {string} If `from` or `to` are timestamps rather than date
* instances, this indicates the units that they are
* measured in. Can be either `ms` for milliseconds
* or `s` for seconds. Defaults to `ms`.
* @option [lang] {string} The output language. Default is specified as a
* build option.
*/
function getVagueTime (options) {
var units = normaliseUnits(options.units),
now = Date.now(),
from = normaliseTime(options.from, units, now),
to = normaliseTime(options.to, units, now),
difference = from - to,
type;
if (difference > 0) {
type = 'past';
} else {
type = 'future';
difference = -difference;
}
return estimate(difference, type, options.lang);
}
function normaliseUnits (units) {
if (typeof units === 'undefined') {
return 'ms';
}
if (units === 's' || units === 'ms') {
return units;
}
throw new Error('Invalid units');
}
function normaliseTime(time, units, defaultTime) {
if (typeof time === 'undefined') {
return defaultTime;
}
if (typeof time === 'string') {
time = parseInt(time, 10);
}
if (isNotDate(time) && isNotTimestamp(time)) {
throw new Error('Invalid time');
}
if (typeof time === 'number' && units === 's') {
time *= 1000;
}
return time;
}
function isNotDate (date) {
return Object.prototype.toString.call(date) !== '[object Date]' || isNaN(date.getTime());
}
function isNotTimestamp (timestamp) {
return typeof timestamp !== 'number' || isNaN(timestamp);
}
function estimate (difference, type, language) {
var time, vagueTime, lang = languages[language] || languages[defaultLanguage];
for (time in times) {
if (times.hasOwnProperty(time) && difference >= times[time]) {
vagueTime = Math.floor(difference / times[time]);
return lang[type](vagueTime, lang[time][(vagueTime > 1)+0]);
}
}
return lang.defaults[type];
}
function exportFunctions () {
if (typeof define === 'function' && define.amd) {
define(function () {
return functions;
});
} else if (typeof module !== 'undefined' && module !== null) {
module.exports = functions;
} else {
globals.vagueTime = functions;
}
}
}(this));
|
Package.describe({
summary: 'A solution for the allow/deny vs methods dilemma',
name: 'mquandalle:collection-mutations',
version: '0.1.0',
documentation: null,
});
Package.onUse(function(api) {
api.versionsFrom('1.2-rc.7');
api.use('mongo');
api.use('ecmascript');
api.use('underscore');
api.use('dburles:collection-helpers@1.0.0');
api.addFiles('mutations.js');
});
|
var co = require('co')
var os = require('os')
var fs = require('fs')
var path = require('path')
var http = require('http')
var request = require('..')
var tmpdir = os.tmpdir()
var uri = 'https://raw.github.com/component/domify/84b1917ea5a9451f5add48c5f61e477f2788532b/component.json'
var redirect = 'https://raw.github.com/jonathanong/inherits/master/component.json'
describe('cogent', function () {
it('should work with HTTPS', co(function* () {
var res = yield* request(uri)
res.statusCode.should.equal(200)
res.headers['content-encoding'].should.equal('gzip')
res.resume()
}))
it('should save to a file', co(function* () {
var destination = path.join(tmpdir, Math.random().toString(36).slice(2))
var res = yield* request(uri, destination)
res.statusCode.should.equal(200)
res.destination.should.equal(destination)
fs.statSync(destination)
}))
it('should resolve redirects', co(function* () {
var res = yield* request(redirect, true)
res.urls.length.should.equal(2)
res.statusCode.should.equal(200)
res.body.name.should.equal('inherits')
}))
it('should work with retries', co(function* () {
var res = yield* request(uri, {
retries: 2
})
res.statusCode.should.equal(200)
res.headers['content-encoding'].should.equal('gzip')
res.resume()
}))
})
|
/*!
* This file is part of me-cms.
*
* Licensed under The MIT License
* For full copyright and license information, please see the LICENSE.txt
* Redistributions of files must retain the above copyright notice.
*
* @copyright Copyright (c) Mirko Pagliai
* @link https://github.com/mirko-pagliai/me-cms
* @license https://opensource.org/licenses/mit-license.php MIT License
*/
$(function () {
//On click on button to display passwords
$(".display-password").click(function (event) {
event.preventDefault();
//Gets the icon
var icon = $(this).children("i.fas");
//Gets the password field
var oldField = $(this).closest(".input").find("input");
//Creates a replace field, setting the same value
var replaceField = $("<input />").val(oldField.val());
//Copies each attribute to the replace field
oldField.each(function () {
$.each(this.attributes, function () {
if (this.specified) {
replaceField.attr(this.name, this.value);
}
});
});
//Sets the `type` for the replace field and changes the button icon
if (oldField.attr("type") === "password") {
replaceField.attr("type", "text");
icon.removeClass("fa-eye").addClass("fa-eye-slash");
} else {
replaceField.attr("type", "password");
icon.removeClass("fa-eye-slash").addClass("fa-eye");
}
//Inserts the replace field and removes the old field
replaceField.insertBefore(oldField);
oldField.remove();
});
});
|
/*jshint node:true*/
module.exports = {
scenarios: [
{
name: 'default',
dependencies: { }
},
{
name: 'ember-1.13',
dependencies: {
'ember': '~1.13.0'
},
resolutions: {
'ember': '~1.13.0'
}
},
{
name: 'ember-2.0',
dependencies: {
'ember': '~2.0.0'
},
resolutions: {
'ember': '~2.0.0'
}
},
{
name: 'ember-2.1',
dependencies: {
'ember': '~2.1.0'
},
resolutions: {
'ember': '~2.1.0'
}
},
{
name: 'ember-2.2',
dependencies: {
'ember': '~2.2.0'
},
resolutions: {
'ember': '~2.2.0'
}
},
{
name: 'ember-2.3',
dependencies: {
'ember': '~2.3.0'
},
resolutions: {
'ember': '~2.3.0'
}
},
{
name: 'ember-release',
dependencies: {
'ember': 'components/ember#release'
},
resolutions: {
'ember': 'release'
}
},
{
name: 'ember-beta',
dependencies: {
'ember': 'components/ember#beta'
},
resolutions: {
'ember': 'beta'
}
},
{
name: 'ember-canary',
dependencies: {
'ember': 'components/ember#canary'
},
resolutions: {
'ember': 'canary'
}
}
]
};
|
describe('wokArmyBuilder.builder.army.optionList', function () {
beforeEach(module('wokArmyBuilder'));
describe('wokOptionListController', function () {
var controller, $scope, Army, Models, gameSizes;
beforeEach(function () {
module('wokArmyBuilder.builder.army.coreList', function ($provide) {
$provide.service('Army', function () {
angular.extend(this, {
options: jasmine.createSpy('options').and.callFake(function () { return 0; }),
gameSize: 'Skirmish',
lists: {
'Core List': {
Leader: [0],
Infantry: [0],
Specialist: [0]
},
'Options List #1': {
Infantry: [0],
Specialist: [0]
},
'Options List #2': {
Infantry: [0],
Specialist: [0]
}
}
});
});
});
});
beforeEach(inject(function ($controller, $rootScope, _Army_, _Models_, _gameSizes_) {
$scope = $rootScope.$new();
$scope.list = 'Options List #1';
Army = _Army_;
Models = _Models_;
gameSizes = _gameSizes_;
controller = $controller('OptionListController', {
$scope: $scope,
Army: Army,
Models: Models,
gameSizes: gameSizes
});
}));
describe('army', function () {
beforeEach(function () {
spyOn($scope, '$broadcast');
Models.load('Goritsi');
});
it('should be initialized to Army service', function () {
expect($scope.army).toEqual(Army);
});
it('should call options when lists[Options List #] arrays change', function () {
Army.lists['Options List #1'].Infantry[0] = 1;
$scope.$digest();
expect(Army.options).toHaveBeenCalled();
expect($scope.options).toEqual(0);
expect($scope.$broadcast).toHaveBeenCalledWith('setNotEnoughRanks', Models.Infantry[0], false);
});
});
describe('maxOptions', function () {
it('should return the maximum options for a given list', function () {
expect($scope.maxOptions()).toEqual(6);
});
});
describe('models', function () {
it('should be initialized to Models service', function () {
expect($scope.models).toBe(Models);
});
});
describe('options', function () {
it('should be initialized to 0', function () {
expect($scope.options).toEqual(0);
});
});
describe('coreListCharacterSelected event', function () {
beforeEach(function () {
spyOn($scope, '$broadcast');
$scope.$emit('coreListCharacterSelected', {}, false);
});
it('should broadcast a setSelectedCharacter event', function () {
expect($scope.$broadcast).toHaveBeenCalledWith('setSelectedCharacter', {}, false);
});
});
});
});
|
//
const express = require('express');
const Activity = require("../models/activities");
const Trip = require("../models/trip");
const User = require("../models/user");
const router = express.Router();
var app = express();
/* GET activities. */
router.get('/trip/:id/activities', (req, res, next) => {
var tripid = req.params.id;
Trip
.findOne({ _id: tripid })
.populate("activities")
.exec((err, trip) => {
if (err) {
next(err);
return;
}
res.render('app/activity', { trip, user: req.user });
});
});
router.post('/trip/:id/activities', (req, res, next) => {
// tripId that is selected
var tripid = req.body.tripid;
console.log("tripid", tripid);
var newActivity = new Activity({
date: req.body.date,
location: req.body.location_name,
latitude: req.body.lat,
longitude: req.body.lng,
category: req.body.category,
text: req.body.notes,
price: req.body.price
});
newActivity.save((err, doc) => {
// Trip.findByIdAndUpdate(push newActivity.id) if err else
console.log("doooooc", doc);
Trip.findById(tripid, (err, trip) => {
trip.activities.push(doc._id);
trip.save();
res.json(doc);
})
});
})
module.exports = router;
|
'use strict';
const assert = require('assert');
//const app = require('../../../src/app');
describe('user service', function() {
it('registered the users service', () => {
// assert.ok(app.service('users'));
});
});
|
'use strict'
const sgf = require('staged-git-files')
const Listr = require('listr')
const has = require('lodash/has')
const pify = require('pify')
const makeCmdTasks = require('./makeCmdTasks')
const generateTasks = require('./generateTasks')
const resolveGitDir = require('./resolveGitDir')
const debug = require('debug')('lint-staged:run')
/**
* Executes all tasks and either resolves or rejects the promise
* @param config {Object}
* @returns {Promise}
*/
module.exports = function runAll(config) {
debug('Running all linter scripts')
// Config validation
if (!config || !has(config, 'concurrent') || !has(config, 'renderer')) {
throw new Error('Invalid config provided to runAll! Use getConfig instead.')
}
const { concurrent, renderer, chunkSize, subTaskConcurrency } = config
const gitDir = resolveGitDir()
debug('Resolved git directory to be `%s`', gitDir)
sgf.cwd = gitDir
return pify(sgf)('ACM').then(files => {
/* files is an Object{ filename: String, status: String } */
const filenames = files.map(file => file.filename)
debug('Loaded list of staged files in git:\n%O', filenames)
const tasks = generateTasks(config, filenames).map(task => ({
title: `Running tasks for ${task.pattern}`,
task: () =>
new Listr(
makeCmdTasks(task.commands, task.fileList, {
chunkSize,
subTaskConcurrency
}),
{
// In sub-tasks we don't want to run concurrently
// and we want to abort on errors
dateFormat: false,
concurrent: false,
exitOnError: true
}
),
skip: () => {
if (task.fileList.length === 0) {
return `No staged files match ${task.pattern}`
}
return false
}
}))
if (tasks.length) {
return new Listr(tasks, {
dateFormat: false,
concurrent,
renderer,
exitOnError: !concurrent // Wait for all errors when running concurrently
}).run()
}
return 'No tasks to run.'
})
}
|
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');
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(path.join(__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('/get', routes);
module.exports = app;
|
//document.write ๅช่ฝ้็ปๆดไธช้กต้ข
//
//innerHTML ๅฏไปฅ้็ป้กต้ข็ไธ้จๅ
var d = document.getElementById("d");
|
import Test from '../../_helpers/Test'
import bp from '../../_helpers/breakpoints'
import mq from '../../_helpers/mq'
import report_result_summary from '../../_helpers/report_result_summary'
import sequence from '../../_helpers/sequence'
import ResultTracker from '../../_helpers/ResultTracker'
import apply_style from '../../_helpers/apply_style'
export default function () {
let outsideHeightResults = new ResultTracker()
class positiveTest_low extends Test {
constructor({ name, test }) {
super({
name: `positive low outsideHeight ${name}`,
test,
size: [bp.small],
mqMatch: true,
localTracker: outsideHeightResults,
})
}
}
class positiveTest_high extends Test {
constructor({ name, test }) {
super({
name: `positive high outsideHeight ${name}`,
test,
size: [bp.large, bp.large + 1],
mqMatch: true,
localTracker: outsideHeightResults,
})
}
}
class negativeTest_low extends Test {
constructor({ name, test }) {
super({
name: `negative low outsideHeight ${name}`,
size: [bp.small, bp.small + 1],
mqMatch: false,
test: test,
localTracker: outsideHeightResults,
})
}
}
class negativeTest_high extends Test {
constructor({ name, test }) {
super({
name: `negative high outsideHeight ${name}`,
size: [bp.large],
mqMatch: false,
test: test,
localTracker: outsideHeightResults,
})
}
}
const positive_tests = [
new positiveTest_low({
name: `"small" (if)`,
test: () => mq.outsideHeight('small', 'large'),
}),
new positiveTest_low({
name: `${bp.small} (if)`,
test: () => mq.outsideHeight(bp.large, bp.small),
}),
new positiveTest_low({
name: `"small" (cb)`,
test: () => {
let result = false
mq.outsideHeight('large', 'small', () => {
result = true
})
return result
},
}),
new positiveTest_low({
name: `${bp.small} (cb)`,
test: () => {
let result = false
mq.outsideHeight(bp.small, bp.large, () => {
result = true
})
return result
},
}),
new positiveTest_high({
name: `"large" (if)`,
test: () => mq.outsideHeight('small', 'large'),
}),
new positiveTest_high({
name: `${bp.large} (if)`,
test: () => mq.outsideHeight(bp.large, bp.small),
}),
new positiveTest_high({
name: `"large" (cb)`,
test: () => {
let result = false
mq.outsideHeight('large', 'small', () => {
result = true
})
return result
},
}),
new positiveTest_high({
name: `${bp.large} (cb)`,
test: () => {
let result = false
mq.outsideHeight(bp.small, bp.large, () => {
result = true
})
return result
},
}),
]
const negative_tests = [
new negativeTest_high({
name: `"large" (if)`,
test: () => mq.outsideHeight('large', 'small'),
}),
new negativeTest_high({
name: `${bp.large} (if)`,
test: () => mq.outsideHeight(bp.small, bp.large),
}),
new negativeTest_high({
name: `"large" (cb)`,
test: () => {
let result = false
mq.outsideHeight('small', 'large', () => {
result = true
})
return result
},
}),
new negativeTest_high({
name: `${bp.large} (cb)`,
test: () => {
let result = false
mq.outsideHeight(bp.large, bp.small, () => {
result = true
})
return result
},
}),
new negativeTest_low({
name: `"small" (if)`,
test: () => mq.outsideHeight('large', 'small'),
}),
new negativeTest_low({
name: `${bp.small} (if)`,
test: () => mq.outsideHeight(bp.small, bp.large),
}),
new negativeTest_low({
name: `"small" (cb)`,
test: () => {
let result = false
mq.outsideHeight('small', 'large', () => {
result = true
})
return result
},
}),
new negativeTest_low({
name: `${bp.small} (cb)`,
test: () => {
let result = false
mq.outsideHeight(bp.large, bp.small, () => {
result = true
})
return result
},
}),
]
return sequence([
apply_style('outsideHeight'),
...positive_tests,
...negative_tests,
report_result_summary('outsideHeight', outsideHeightResults),
])
}
|
// gulpfile.js
"use strict";
import gulp from "gulp";
import path from "path";
import fs from "fs";
import htmlmin from "gulp-htmlmin";
import uglify from "gulp-uglify";
import rename from "gulp-rename";
import concatCss from "gulp-concat-css";
import csso from "gulp-csso";
import inject from "gulp-inject";
import replace from "gulp-replace";
import browserify from "browserify";
import source from "vinyl-source-stream";
import gutil from "gulp-util";
import tap from "gulp-tap";
import buffer from "gulp-buffer";
import sourcemaps from "gulp-sourcemaps";
import concat from "gulp-concat";
import uncss from "gulp-uncss";
import eslint from "gulp-eslint";
import del from "del";
import gulpIf from "gulp-if";
const APP_PATH = path.join(__dirname, "app");
const APP_CSS_PATH = path.join(APP_PATH, "css");
const APP_JS_PATH = path.join(APP_PATH, "js");
const INDEX_TEMPLATE_PATH = path.join(APP_PATH, "index.template.html");
const DEST_PATH = path.join(APP_PATH, "assets");
const DEST_PATH_JS = path.join(DEST_PATH, "js");
const DEST_PATH_CSS = path.join(DEST_PATH, "css");
const DEST_PATH_FONTS = path.join(DEST_PATH, "fonts");
const TEMPLATES_PATH = path.join(APP_PATH, "templates/**/*.html");
const IS_PRODUCTION = !process.env.NODE_ENV || process.env.NODE_ENV == "production";
function getDirectories(dir) {
return fs.readdirSync(dir)
.filter(function(file) {
return fs.statSync(path.join(dir, file)).isDirectory();
});
}
gulp.task("inject-html", (cb) => {
let srcCss = gulp.src([DEST_PATH_CSS + "/*.css", "!" + DEST_PATH_CSS + "/*.min.css"], {read: false});
let appJs = gulp.src([APP_JS_PATH + "/*.js", APP_JS_PATH + "/*.min.js"], {read: false});
let allJS = gulp.src([DEST_PATH_JS + "/*.js", "!" + DEST_PATH_CSS + "/*.min.js"], {read: false});
gulp.src(INDEX_TEMPLATE_PATH)
.pipe(inject(srcCss, {
removeTags: true
}))
.pipe(inject(allJS, {
starttag: "<!-- inject:all-js -->",
removeTags: true
}))
.pipe(inject(appJs, {
starttag: "<!-- inject:js-app -->",
removeTags: true
}))
.pipe(replace("/app/", ""))
.pipe(rename("index.html"))
.pipe(gulpIf(IS_PRODUCTION, htmlmin({
collapseWhitespace: true,
removeComments: true,
quoteCharacter: "\""
})))
.pipe(gulpIf(IS_PRODUCTION, rename("index.min.html")))
.pipe(gulp.dest(DEST_PATH));
cb();
});
gulp.task("clean:js", () => {
return del(DEST_PATH_JS);
});
gulp.task("concat-js", (cb) => {
let directories = getDirectories(APP_JS_PATH);
directories.map( (dirName) => {
return gulp.src([path.join(APP_JS_PATH, dirName, "/*.js"), "!" + path.join(APP_JS_PATH, dirName, "/angular.js")])
// concat into dirName.bundle.js
.pipe(concat(dirName + ".bundle.js"))
// write to output
.pipe(gulp.dest(DEST_PATH_JS));
})
cb();
});
gulp.task("eslint", (cb) => {
let allJS = gulp.src([path.join(APP_JS_PATH, "**/*.js"), "!" + path.join(APP_JS_PATH, "vendors/*.js"), path.join(__dirname, "gulpfile.babel.js")]);
allJS
// eslint() attaches the lint output to the "eslint" property
// of the file object so it can be used by other modules.
.pipe(eslint())
// eslint.format() outputs the lint results to the console.
// Alternatively use eslint.formatEach() (see Docs).
.pipe(eslint.format())
// To have the process exit with an error code (1) on
// lint error, return the stream and pipe to failAfterError last.
.pipe(eslint.failAfterError());
cb();
});
gulp.task("uglify-js", (cb) => {
let allJS = gulp.src(path.join(DEST_PATH_JS, "/*.js"));
allJS
.pipe(uglify())
.pipe(rename({
extname: ".min.js"
}))
.pipe(gulp.dest(DEST_PATH_JS));
cb();
});
gulp.task("transpile", (cb) => {
let assetsJS = gulp.src(path.join(DEST_PATH_JS, "/*.bundle.js"));
assetsJS
.pipe(tap( (file) => {
gutil.log("bundling " + file.path)
file.contents = browserify(file.path, {
debug: true
})
.transform("babelify")
.bundle();
}))
// transform streaming contents into buffer contents (because gulp-sourcemaps does not support streaming contents)
.pipe(buffer())
.pipe(gulp.dest(DEST_PATH_JS));
cb();
});
gulp.task("copy-css", () => {
let bootstrapCss = path.normalize("bower_components/bootstrap/dist/css/bootstrap.css");
return gulp.src(bootstrapCss)
.pipe(gulp.dest(APP_CSS_PATH));
});
gulp.task("minify-css", (cb) => {
let allCss = gulp.src(path.join(APP_CSS_PATH, "/*.css"));
allCss
.pipe(concatCss("styles.css"))
.pipe(gulp.dest(DEST_PATH_CSS))
.pipe(uncss({
html: [INDEX_TEMPLATE_PATH, TEMPLATES_PATH]
}))
.pipe(csso({
restructure: false,
sourceMap: true,
debug: true,
comments: false
}))
.pipe(rename("styles.min.css"))
.pipe(gulp.dest(DEST_PATH_CSS));
cb();
});
gulp.task("copy-fonts", (cb) => {
let bootstrapFonts = gulp.src(path.normalize("bower_components/bootstrap/fonts/glyphicons*"));
bootstrapFonts
.pipe(gulp.dest(DEST_PATH_FONTS));
cb();
});
gulp.task("assets", ["copy-css", "copy-fonts", "minify-css", "transpile", "uglify-js", "inject-html"]);
gulp.task("default", ["clean:js", "concat-js", "transpile"]);
|
import React from 'react'
import cookie from 'react-cookie'
import { Link } from 'react-router'
import url from '../../config.js'
// components
import NavBar from './NavBar'
import Header from './Header'
import ToggleDisplay from 'react-toggle-display'
import FlatButton from 'material-ui/lib/flat-button'
import RaisedButton from 'material-ui/lib/raised-button'
import TextField from 'material-ui/lib/text-field'
// database functions
import postRequest from '../postRequest.js'
import getRequest from '../getRequest.js'
// material-ui helpers
import GetMuiTheme from 'material-ui/lib/styles/getMuiTheme'
import MyTheme from '../theme.js';
export default React.createClass ({
childContextTypes : {
muiTheme: React.PropTypes.object
},
getChildContext() {
return {
muiTheme: GetMuiTheme(MyTheme),
}
},
getInitialState: function () {
return {
name: "",
target: 0,
sobstory: "",
photo: "",
isUploaded: false,
alreadyHasTeeth: false,
isLoggedIn: false,
profileURL: ""
}
},
handleName: function (e) {
this.setState({'name': e.target.value})
},
handleTarget: function (e) {
this.setState({'target': e.target.value})
},
handleSobstory: function (e) {
this.setState({'sobstory': e.target.value})
},
photoUploaded: function (error, l){
this.setState({'photo': l[0].secure_url})
this.setState({'isUploaded': true})
},
componentDidMount: function () {
if (cookie.load('donorID')) {
this.setState({'isLoggedIn': true})
}
var _this = this
document.getElementById("upload_widget_opener").addEventListener("click", function () {
cloudinary.openUploadWidget({ cloud_name: 'toothandpail', upload_preset: 'fasiveib' },
function (error, result) {
_this.photoUploaded(error, result)
})
}, false)
this.handleIsUser()
},
handleIsUser: function () {
var _this = this
getRequest(url + '/recipientsbydonor/' + cookie.load('donorID'), _this.handleExistingUser)
},
handleExistingUser: function (err, data) {
console.log("data", data)
if (data !== undefined) {
var profileURL = "/recipient/" + data.recipientID
this.setState({'profileURL': profileURL})
this.setState({'alreadyHasTeeth': true})
}
},
handleSubmit: function () {
let _this = this
let dataObject = {
name: this.state.name,
imgURL: this.state.photo,
received: 0,
target: this.state.target,
sobStory: this.state.sobstory,
donorID: cookie.load('donorID')
}
postRequest(url + '/recipients', dataObject, _this.handleIsUser)
},
render: function () {
return (
<div>
<NavBar/>
<Header header={this.props.recipientID}/>
<div className="twelve columns" id="RecipientForm">
<ToggleDisplay show={this.state.isLoggedIn}>
<ToggleDisplay hide={this.state.alreadyHasTeeth}>
<h2>Submit Your Teeth</h2>
<p>Need funding for dental treatment? Submit your details here and with the help of our generous donors, the funding you need could be closer than you think.</p>
Your name
<br />
<TextField id={1} type="text" className="name" id="name" onChange={this.handleName} />
<br />
How much do you need to raise for your treatment?
<br />
<TextField id={2} type="number" className="target" id="target" onChange={this.handleTarget} />
<br />
Tell us about why you need funding?
<br />
<TextField id={3} type='text' multiLine={true} id="sobstory" rows={8} fullWidth onChange={this.handleSobstory} />
<br />
<FlatButton secondary={true} label="Upload picture" backgroundColor='red' id="upload_widget_opener" />
<br />
<ToggleDisplay show={this.state.isUploaded}>
<p>Photo uploaded!</p>
</ToggleDisplay>
<br />
<RaisedButton label="Submit your teeth!" onClick={this.handleSubmit} />
</ToggleDisplay>
<ToggleDisplay show={this.state.alreadyHasTeeth}>
<p>Thank you for requesting funding for your teeth. Check out your profile!</p>
<RaisedButton label="Show me my teeth" className="showmyteeth" onClick={() => {this.props.history.push(this.state.profileURL)}}/>
</ToggleDisplay>
</ToggleDisplay>
<ToggleDisplay hide={this.state.isLoggedIn}>
<h2>Oops!</h2>
<p>You need to log in before you can request funding!</p>
<RaisedButton label="Login / Signup" className="login-signup" onClick={() => {this.props.history.push('/')}}/>
</ToggleDisplay>
</div>
</div>
)
}
})
|
import React from 'react';
import style from 'PVWStyle/ReactProperties/CheckboxProperty.mcss';
export default React.createClass({
displayName: 'Checkbox',
propTypes: {
idx: React.PropTypes.number,
label: React.PropTypes.string,
onChange: React.PropTypes.func,
value: React.PropTypes.bool,
},
getDefaultProps() {
return {
value: false,
label: '',
};
},
valueChange(e) {
if (this.props.onChange) {
if (this.props.idx >= 0) {
this.props.onChange(this.props.idx, e.target.checked);
} else {
this.props.onChange(null, e.target.checked);
}
}
},
render() {
return (
<div>
<label className={style.label}>{this.props.label}</label>
<input
className={style.input}
type="checkbox"
checked={this.props.value}
onChange={this.valueChange}
/>
</div>);
},
});
|
/**
* runApp
* Created by dcorns on 1/3/15.
* Returns a new object with a run method that executes os commands in node.
*/
'use strict';
module.exports = function(){
this.run = function run(arg, cnn, cmd){
var spawn = require('child_process').spawn;
var proc = spawn(cmd, arg);
proc.on('exit', function(code){
console.log(cmd + ' exit code:' + code);
});
proc.stderr.on('data', function (data) {
console.log('stderr: ' + data);
cnn.write(data);
});
proc.stdout.on('data', function (ot) {
cnn.write(ot);
});
};
};
|
define(function () {
var Meal = function () {
this.ids = {};
this.time = null;
this.timezone = null; // if available
this.params = {
};
/*
this.params = { // in grams or ml
'calories': 900,
'fat': 99
};
*/
};
return Meal;
});
|
var gulp = require('gulp');
var del = require('del');
var config = require('../config');
gulp.task('clean', function(cb) {
del([config.dir_dist + '/**'], cb);
});
|
module.exports = {
re: /^https?:\/\/(?:[\w\-]+\.)?genius\.com\/(?!jobs)([a-zA-Z\-]+)/i,
mixins: [
"domain-icon",
"*"
],
getLinks: function(urlMatch, twitter) {
var id = twitter.app.url.iphone.match(/\d+/)[0];
if (id) {
return {
html: '<div id="rg_embed_link_' + id + '" class="rg_embed_link" data-song-id="' + id + '"></div><script src="//genius.com/songs/' + id + '/embed.js?dark=1"></script>',
type: CONFIG.T.text_html,
rel: [CONFIG.R.reader, CONFIG.R.ssl]
};
}
},
tests: [{
page: 'http://rap.genius.com/',
selector: '.song_link'
}, { skipMixins: ["favicon"]},
"http://rock.genius.com/Bruce-springsteen-4th-of-july-asbury-park-sandy-lyrics",
"http://rap.genius.com/Beyonce-flawless-remix-lyrics"
]
};
|
// Karma configuration
// Generated on Thu Oct 01 2015 17:56:10 GMT+0900 (JST)
module.exports = function(config) {
config.set({
// base path that will be used to resolve all patterns (eg. files, exclude)
basePath: '',
// frameworks to use
// available frameworks: https://npmjs.org/browse/keyword/karma-adapter
frameworks: ['jasmine', 'browserify'],
// list of files / patterns to load in the browser
files: [
'spec/**/*.js'
],
// list of files to exclude
exclude: [
],
// preprocess matching files before serving them to the browser
// available preprocessors: https://npmjs.org/browse/keyword/karma-preprocessor
preprocessors: {
'src/js/**/*.js': ['browserify'],
'spec/**/*.js': ['browserify']
},
browserify: {
debug: true,
transform: ['rewireify', 'babelify']
},
// test results reporter to use
// possible values: 'dots', 'progress'
// available reporters: https://npmjs.org/browse/keyword/karma-reporter
reporters: ['mocha'],
// web server port
port: 9876,
// enable / disable colors in the output (reporters and logs)
colors: true,
// level of logging
// possible values: config.LOG_DISABLE || config.LOG_ERROR || config.LOG_WARN || config.LOG_INFO || config.LOG_DEBUG
logLevel: config.LOG_INFO,
// enable / disable watching file and executing tests whenever any file changes
autoWatch: true,
// start these browsers
// available browser launchers: https://npmjs.org/browse/keyword/karma-launcher
browsers: ['Chrome'],
// Continuous Integration mode
// if true, Karma captures browsers, runs the tests and exits
singleRun: false,
// To prevent this error: https://github.com/karma-runner/karma/issues/598
browserNoActivityTimeout: 60000
})
}
|
var creds = (function () {
var creds = {};
creds.API_SECRET="";
creds.API_KEY="";
creds.AUTHOR='';
return creds;
}());
|
/*
* grunt-arcgis-press
* https://github.com/agrc/grunt-arcgis-press
*
* Copyright (c) 2015 Steve Gourley & Scott Davis
* Licensed under the MIT license.
*/
'use strict';
module.exports = function(grunt) {
var PythonShell = require('python-shell');
var chalk = require('chalk');
var mixin = require('./lib/mixin_options');
var Promise = require('promise');
var path = require('path');
grunt.registerMultiTask('arcgis_press',
'A grunt task for covering your ArcGIS service publishing needs. Hot off the press!',
function() {
var done = this.async();
// create temp folder if needed
var tempFolder = path.join(process.cwd(), '.grunt', 'grunt-arcgis-press');
if (!grunt.file.exists(tempFolder)) {
grunt.file.mkdir(tempFolder);
}
// need to use our own mixin because grunt's doesn't do a deep mixin
var config = mixin(grunt.config('arcgis_press'), this.target);
var commonArgs = [
config.server.host,
config.server.username,
config.server.password
];
var shellOptions = {
cwd: __dirname + '/scripts',
pythonOptions: ['-m'],
scriptPath: 'press'
};
var promises = [];
var invokePython = function(command, args) {
shellOptions.args = [command].concat(commonArgs, args);
return new Promise(function(resolve, reject) {
PythonShell.run('', shellOptions, function(err, results) {
if (err) {
grunt.log.error(err.message);
grunt.verbose.error(err.stack);
reject();
}
resolve(results);
});
});
};
var publishService = function(service) {
var basePath = null;
if(service.type.toUpperCase() === 'MAPSERVER'){
basePath = config.mapServerBasePath;
}else if(service.type.toUpperCase() === 'GPSERVER'){
basePath = config.gpServerBasePath;
}
service.resource = path.join(basePath, service.resource);
var args = [
JSON.stringify(service),
tempFolder
];
var sn = service.serviceName;
grunt.log.writelns(chalk.blue('Publishing: ' + sn + ' to ' + config.server.host));
grunt.verbose.writelns(chalk.blue(sn + ': staging...'));
return invokePython('stage', args)
.then(function(results) {
// the return value from the python script has an extra
// character that causes the next script to error so we
// need to trim it
results[0] = results[0].trim();
results[1] = results[1].trim();
grunt.verbose.writelns(chalk.blue(sn + ': uploading...'));
return invokePython('upload', results);
})
.then(function() {
grunt.verbose.writelns(chalk.blue(sn + ': updating service properties...'));
return invokePython('edit', args);
})
.then(function () {
var msg = sn + ' (' + service.type +
') was successfully published to ' + config.server.host;
grunt.log.writelns(chalk.blue(msg));
});
};
// loop through services
for (var prop in config.services) {
if (config.services.hasOwnProperty(prop)) {
promises.push(publishService(config.services[prop]));
}
}
Promise.all(promises).then(function() {
done();
}, function() {
done(false);
});
});
};
|
var d = global.d;
describe("bfs", function () {
it("should throw a TypeError when no arguments are given", function () {
expect(() => d.bfs().next()).toThrow(new TypeError("Argument 1 must be an Object or Array"));
});
it("should throw a TypeError when any arguments are the wrong type", function () {
expect(() => d.bfs(123).next()).toThrow(new TypeError("Argument 1 must be an Object or Array"));
expect(() => d.bfs("test").next()).toThrow(new TypeError("Argument 1 must be an Object or Array"));
expect(() => d.bfs({}, 123).next()).toThrow(new TypeError("Argument 2 must be a non-empty Object or Array"));
expect(() => d.bfs({}, "test").next()).toThrow(new TypeError("Argument 2 must be a non-empty Object or Array"));
});
it("should iterate all nodes and properties", function () {
var keyCounts = global.createKeyCounter();
var testObject = global.testObjects["Multidimensional Cyclic"]();
var iterator = d.bfs(testObject, testObject);
var iteration = iterator.next();
while (!iteration.done) {
keyCounts[iteration.value.accessor]++;
iteration = iterator.next();
}
//console.info("bfs Traversal & Iteration Results:");
for (var accessor in keyCounts) {
//console.info("Accessor \"" + accessor + "\" was visited " + keyCounts[accessor] + " time(s).");
expect(keyCounts[accessor] > 0).toBe(true);
}
});
});
describe("dfs", function () {
it("should throw a TypeError when no arguments are given", function () {
expect(() => d.dfs().next()).toThrow(new TypeError("Argument 1 must be an Object or Array"));
});
it("should throw a TypeError when any arguments are the wrong type", function () {
expect(() => d.dfs(123).next()).toThrow(new TypeError("Argument 1 must be an Object or Array"));
expect(() => d.dfs("test").next()).toThrow(new TypeError("Argument 1 must be an Object or Array"));
expect(() => d.dfs({}, 123).next()).toThrow(new TypeError("Argument 2 must be a non-empty Object or Array"));
expect(() => d.dfs({}, "test").next()).toThrow(new TypeError("Argument 2 must be a non-empty Object or Array"));
});
it("should iterate all nodes and properties", function () {
var keyCounts = global.createKeyCounter();
var testObject = global.testObjects["Multidimensional Cyclic"]();
var iterator = d.dfs(testObject, testObject);
var iteration = iterator.next();
while (!iteration.done) {
keyCounts[iteration.value.accessor]++;
iteration = iterator.next();
}
//console.info("bfs Traversal & Iteration Results:");
for (var accessor in keyCounts) {
//console.info("Accessor \"" + accessor + "\" was visited " + keyCounts[accessor] + " time(s).");
expect(keyCounts[accessor] > 0).toBe(true);
}
});
});
|
window.onload = function() {
var video = document.getElementById('video');
var canvas = document.getElementById('canvas');
var context = canvas.getContext('2d');
var tracker = new tracking.ObjectTracker('eye');
tracking.track('#video', tracker, { camera: true });
tracker.on('track', function(event) {
context.clearRect(0, 0, canvas.width, canvas.height);
event.data.forEach(function(rect) {
console.log(rect.x, rect.y, rect.width, rect.height);
//print tracking to the page
var log = document.getElementById("location-data").innerHTML;
//document.getElementById("location-data").innerHTML = log + '<br />' + rect.x + ',' + rect.y + ',' + rect.width + ',' + rect.height
context.strokeStyle = '#a64ceb';
context.strokeRect(rect.x, rect.y, rect.width, rect.height);
context.font = '11px Helvetica';
context.fillStyle = "#fff";
context.fillText('x: ' + rect.x + 'px', rect.x + rect.width + 5, rect.y + 11);
context.fillText('y: ' + rect.y + 'px', rect.x + rect.width + 5, rect.y + 22);
});
});
};
|
'use strict';
exports.init = function(req, res){
res.render('new/index');
};
|
var CancelTextCommand = function() {
this.Extends = SimpleCommand;
this.execute = function(note) {
//alert("CancelTextCommand");
var mediator = note.getBody();
var textEditor = null;
if (mediator instanceof ModelObjectsTextsEditorMediator) {
textEditor = mediator.getViewComponent().gridListSplitter.right.modelObjectsTextsEditor;
} else {
textEditor = mediator.getViewComponent().gridListSplitter.right.modelRelationsTextsEditor;
}
var properties = {
"state": SjamayeeMediator.STATE_LIST,
"textEditor": textEditor
};
this.sendNotification(SjamayeeFacade.DATA_MODEL_CHANGE, properties);
//this.sendNotification(SjamayeeFacade.TEXT_CANCELED,mediator);
var toolBarMediator = null;
if (mediator instanceof ModelObjectsTextsEditorMediator) {
toolBarMediator = this.facade.retrieveMediator(ModelObjectsListMediator.ID);
} else {
toolBarMediator = this.facade.retrieveMediator(ModelRelationsGridMediator.ID);
}
toolBarMediator.setMessageText("Text canceled.");
};
};
CancelTextCommand = new Class(new CancelTextCommand());
|
version https://git-lfs.github.com/spec/v1
oid sha256:1d9080414602f6f5917e7b36b5aba29a65872741dae9d855477b867a38088897
size 7969
|
'use strict';
var React = require('react-native');
var Navigation = require('./Navigation');
var CatalogCell = require('./CatalogCell');
var {
StyleSheet,
Text,
View,
ListView,
Image,
DrawerLayoutAndroid,
TouchableHighlight,
TouchableNativeFeedback,
ToolbarAndroid,
} = React;
import {manager, ReactCBLite} from 'react-native-couchbase-lite'
ReactCBLite.init(5984, 'admin', 'password', (e) => {});
var MyBooks = React.createClass({
getInitialState() {
return {
dataSource: new ListView.DataSource({
rowHasChanged: (row1, row2) => row1 !== row2,
}),
};
},
componentDidMount() {
var remoteURL = 'https://infinitelibrary.cloudant.com/gitburg'
var database = new manager('http://admin:password@localhost:5984/', 'demoapp');
database.createDatabase()
.then((res) => {
database.replicate(remoteURL, 'demoapp')
})
.then((res) => {
return database.getDesignDocument('_all_docs?include_docs=true&attachments=true')
})
.then((res) => {
this.setState({
dataSource: this.state.dataSource.cloneWithRows(res.rows)
});
console.log(res.rows)
})
.catch((ex) => {file:///android_asset/
console.log(ex)
})
},
selectBook(book) {
// fix for iOS/Android dismiss keyboard needs to be added
this.props.navigator.push({
title: book.title,
name: 'reader',
book: book,
});
},
goTo(route) {
// fix for iOS/Android dismiss keyboard needs to be added
this.props.navigator.push({
name: route,
});
},
renderRow(data) {
var book = data.doc
return (
<CatalogCell
key= {book._id}
onSelect={() => this.selectBook(book)}
book={book}
style={styles.catalogCell} />
);
},
render() {
var navigationView = (
<Navigation
goToRoute= {(route) => this.goTo(route)}/>
);
return (
<DrawerLayoutAndroid
drawerWidth={300}
drawerPosition={DrawerLayoutAndroid.positions.Left}
ref={(drawer) => { return this.drawer = drawer }}
renderNavigationView={() => navigationView}>
<ToolbarAndroid
actions={[]}
navIcon={require('image!three_bar')}
onIconClicked={() => this.drawer.openDrawer()}
style={styles.toolBar}
titleColor="white"
title="My Books" />
<ListView
dataSource={this.state.dataSource}
renderRow={this.renderRow}
style={styles.listView} />
</DrawerLayoutAndroid>
);
},
});
var styles = StyleSheet.create({
catalogCell: {
flex: 1
},
listView: {
flex: 1,
backgroundColor: '#F5FCFF',
},
toolBar: {
backgroundColor: '#FF5252',
height: 56,
},
});
module.exports = MyBooks;
|
// Always request javascript when sending xhr
$(function() {
$.ajaxSetup({
'beforeSend': function(xhr) {
xhr.setRequestHeader("Accept", "text/javascript");
}
});
});
$().ready(function(){
jQuery(top).trigger('initialize:frame');
// hide roxanne toolbar if mercury toolbar is present in parent window
if(window.location != window.parent.location){
$("#roxanne_toolbar").hide();
} else {
$("a.add_container").hide();
}
$("a.add_container").live("click", function(){
var url = "/containers/new"
if ($(this).attr('data-page')){
url += '?page_id=' + $(this).attr('data-page') + '&name=' + $(this).attr('data-name');
} else if($(this).attr('data-parent')){
url += '?parent_id=' + $(this).attr('data-parent');
}
if ($(this).attr('data-sibling')){
url += '?sibling_id=' + $(this).attr('data-sibling');
}
Mercury.modal(url, {
'title': "New Container"
})
});
$("a.add_container").live("hover", function(){
var id = $(this).attr("data-sibling");
if(id){
$("#container_" + id).toggleClass('highlight_content');
} else {
$(this).parent(".container_list").toggleClass('highlight_content');
}
});
$("a.add_container_list").live("click", function(){
alert("add_container_list");
});
});
|
const
weekly = require('./'),
botMessages = require('../messages/bot-msgs'),
sendMessage = require('../tools/sendMessage')
;
module.exports = function (datastore, userObject, quick_reply) {
let day = quick_reply.payload.split('_')[1].toLowerCase();
weekly(datastore, userObject, day).then(postsElements => {
console.log(day, 'offers posts', postsElements);
for (let posts of postsElements) {
sendMessage.sendObjectMessage(userObject.mId, {
attachment: {
type: "template",
payload: {
template_type: "generic",
elements: posts
}
}
});
}
}, (e) => {
console.error(`No ${day} offers error`, e);
sendMessage.sendTextMessage(userObject.mId, botMessages.WEEKLY_NO_POSTS, [], function(){},
[{
"type": "postback",
"title": botMessages.START_SENDING_OFFERS_BUTTON2,
"payload": "WEEKLY_PAYLOAD"
}]);
});
};
|
var app = angular.module('js');
app.controller('RegistrationOwnEditCtrl', function($scope, $filter, $routeParams, $location, NotificationSvc, ActivitiesSvc, RegistrationSvc, conf, PlatformSvc) {
//$scope.busyPromise = RegistrationSvc.findById;
$scope.cities = PlatformSvc.getCities();
$scope.platform = PlatformSvc;
$scope.hasDisability = undefined;
$scope.hasHealthIssues = undefined;
$scope.setHasHealthIssues = function(b) { $scope.hasHealthIssues = b; }
$scope.isHasHealthIssuesSet = function() { return $scope.hasHealthIssues !== undefined && $scope.hasHealthIssues !== null; }
$scope.setHasDisability = function(b) { $scope.hasDisability = b; }
$scope.isHasDisabilitySet = function() { return $scope.hasDisability !== undefined && $scope.hasDisability !== null; }
$scope.save = function() {
if($scope.registrationForm.$valid) {
$scope.registration.firstNameParent = $scope.firstNameParent;
$scope.registration.lastNameParent = $scope.lastNameParent;
$scope.registration.phoneNumberParent = $scope.phoneNumberParent;
$scope.registration.emailParent = $scope.emailParent;
$scope.registration.firstNameChild = $scope.firstNameChild;
$scope.registration.lastNameChild = $scope.lastNameChild;
$scope.registration.birthdayChild = $scope.birthdayChild;
$scope.registration.schoolChild = $scope.schoolChild;
$scope.registration.hasHealthIssues = $scope.hasHealthIssues;
$scope.registration.healthAllergy = $scope.healthAllergy;
$scope.registration.healthIncompatibility = $scope.healthIncompatibility;
$scope.registration.healthIllnes = $scope.healthIllnes;
$scope.registration.cityChild = $scope.cityChild;
$scope.registration.addressChild = $scope.addressChild;
$scope.registration.hasDisability = $scope.hasDisability;
$scope.registration.disabilityDescription = $scope.disabilityDescription;
$scope.registration.diagnosticDescription = $scope.diagnosticDescription;
$scope.registration.nameContact1 = $scope.nameContact1;
$scope.registration.nameContact2 = $scope.nameContact2;
$scope.registration.telContact1 = $scope.telContact1;
$scope.registration.telContact2 = $scope.telContact2;
$scope.registration.needsEbK = $scope.needsEbK;
$scope.registration.canSwim = $scope.canSwim;
$scope.registration.canGoHomeAllone = $scope.canGoHomeAllone;
RegistrationSvc.update( $scope.registration
).success(function(reg) {
$scope.firstNameParent = null;
$scope.lastNameParent = null;
$scope.emailParent = null;
$scope.phoneNumberParent = null;
$scope.firstNameChild = null;
$scope.lastNameChild = null;
$scope.birthdayChild = null;
$scope.schoolChild = null;
$scope.addressChild = null;
$scope.cityChild = null;
$scope.hasHealthIssues = undefined;
$scope.healthAllergy = null;
$scope.healthIncompatibility = null;
$scope.healthIllnes = null;
$scope.hasDisability = undefined;
$scope.disabilityDescription = null;
$scope.diagnosticDescription = null;
$scope.nameContact1 = null;
$scope.nameContact2 = null;
$scope.telContact1 = null;
$scope.telContact2 = null;
$scope.needsEbK = false;
$scope.canSwim = false;
$scope.canGoHomeAllone = false;
})
.error(function(err) {
console.log("ERR:", err);
})
.then(function() {
NotificationSvc.notify('Aenderungen erfolgreich gespeichert');
$location.path('/myRegistrations');
});
}
}
RegistrationSvc.findById($routeParams.registrationId).success(function(registration) {
$scope.registration = registration;
$scope.firstNameParent = registration.firstNameParent;
$scope.lastNameParent = registration.lastNameParent;
$scope.phoneNumberParent = registration.phoneNumberParent;
$scope.emailParent = registration.emailParent;
$scope.firstNameChild = registration.firstNameChild;
$scope.lastNameChild = registration.lastNameChild;
$scope.birthdayChild = $filter('date')(new Date(registration.birthdayChild), 'yyyy-MM-dd');
$scope.schoolChild = registration.schoolChild;
$scope.cityChild = registration.cityChild;
$scope.addressChild = registration.addressChild;
$scope.hasHealthIssues = registration.hasHealthIssues;
$scope.healthIncompatibility = registration.healthIncompatibility;
$scope.healthAllergy = registration.healthAllergy;
$scope.healthIllnes = registration.healthIllnes;
$scope.hasDisability = registration.hasDisability;
$scope.disabilityDescription = registration.disabilityDescription;
$scope.diagnosticDescription = registration.diagnosticDescription;
$scope.nameContact1 = registration.nameContact1;
$scope.nameContact2 = registration.nameContact2;
$scope.telContact1 = registration.telContact1;
$scope.telContact2 = registration.telContact2;
$scope.needsEbK = registration.needsEbK;
$scope.canSwim = registration.canSwim;
$scope.canGoHomeAllone = registration.canGoHomeAllone;
});
});
|
import differenceInCalendarWeeks from '../differenceInCalendarWeeks/index.js'
import lastDayOfMonth from '../lastDayOfMonth/index.js'
import startOfMonth from '../startOfMonth/index.js'
/**
* @name getWeeksInMonth
* @category Week Helpers
* @summary Get the number of calendar weeks a month spans.
*
* @description
* Get the number of calendar weeks the month in the given date spans.
*
* ### v2.0.0 breaking changes:
*
* - [Changes that are common for the whole library](https://github.com/date-fns/date-fns/blob/master/docs/upgradeGuide.md#Common-Changes).
*
* @param {Date|Number} date - the given date
* @param {Object} [options] - an object with options.
* @param {0|1|2|3|4|5|6} [options.weekStartsOn=0] - the index of the first day of the week (0 - Sunday)
* @param {Locale} [options.locale=defaultLocale] - the locale object. See [Locale]{@link https://date-fns.org/docs/Locale}
* @returns {Number} the number of calendar weeks
* @throws {TypeError} 2 arguments required
* @throws {RangeError} `options.weekStartsOn` must be between 0 and 6
*
* @example
* // How many calendar weeks does February 2015 span?
* var result = getWeeksInMonth(new Date(2015, 1, 8))
* //=> 4
*
* @example
* // If the week starts on Monday,
* // how many calendar weeks does July 2017 span?
* var result = getWeeksInMonth(new Date(2017, 6, 5), { weekStartsOn: 1 })
* //=> 6
*/
export default function getWeeksInMonth(date, options) {
if (arguments.length < 1) {
throw new TypeError(
'1 argument required, but only ' + arguments.length + ' present'
)
}
return (
differenceInCalendarWeeks(
lastDayOfMonth(date),
startOfMonth(date),
options
) + 1
)
}
|
(function(){
'use strict';
var app = angular.module('readingList', []);
app.controller = ('ReadingListController', function(){
this.books = books;
this.genres = genres;
}
);
var genres = ['fable', 'fantasy', 'fiction', 'folklore', 'horror', 'humor', 'legend', 'metafiction', 'mystery', 'mythology', 'non-fiction', 'poetry']
var books = [
{
title: 'A Game of Thrones: A Song of Ice and Fire',
author: 'George R.R. Martin',
isbn: '0553593714',
review: 'The most inventive and entertaining fantasy saga of our timeโwarrants one hell of an introduction. I loved this book!',
rating: 4,
genres: { 'non-fiction': true, fantasy: true }
},{
title: 'HTML for Babies',
author: 'John C Vanden-Heuvel Sr',
isbn: '0615487661',
review: "It's never too early to be standards compliant! I taught my little one mark-up in under one hour!",
rating: 5,
genres: { fiction: true }
},{
title: 'A is for Array',
author: 'Brandon J Hansen',
isbn: '1489522212',
review: 'A is for Array is the ABC book for future programmers. Filled with fun illustrations and simple real-world examples, my children loved seeing my world intertwined with theirs!',
rating: 4,
genres: { fiction: true }
},{
title: 'The Dragon Reborn',
author: 'Robert Jordan',
isbn: '0812513711',
review: 'The Wheel weaves as the Wheel wills, and we are only the thread of the Pattern. Moiraine',
rating: 4,
genres: { 'non-fiction': true, fantasy: true }
}
];
})();
|
'use strict';
// Load modules
const Code = require('code');
const Hapi = require('hapi');
const Lab = require('lab');
const Info = require('../lib/modules/hello-world');
// Declare internals
const internals = {};
// Test shortcuts
const lab = exports.lab = Lab.script();
const it = lab.it;
const describe = lab.describe;
const expect = Code.expect;
describe('Hello World', () => {
it('200 - GET /', (done) => {
const server = new Hapi.Server();
server.connection();
server.register(Info, (err) => {
expect(err).to.not.exist();
const request = {
method: 'GET',
url: '/'
};
server.inject(request, (response) => {
expect(response.statusCode).to.equal(200);
expect(response.result).to.equal({ msg: 'hello world!' });
done();
});
});
});
});
|
'use strict';
var commander = require('../../lib/commander');
var config = require('../../lib/config');
var gulp = require('gulp');
var gulpIf = require('gulp-if');
var gulpLess = require('gulp-less');
var gulpWatchLess = require('gulp-watch-less');
var mac = require('mac');
var path = require('path');
module.exports = mac.mac({
on: 'data end'
}).series(
function () {
var dest = config('dist.less.destination');
var src = config('dist.less.source');
return gulp.src(src)
.pipe(gulpIf(!!commander.watch, gulpWatchLess.bind(null, src)))
.pipe(gulpLess({
paths: [
path.basename(src)
]
}))
.pipe(gulp.dest(dest));
}
);
|
const path = require("path");
var DuplicatePackageCheckerPlugin = require("../../src");
module.exports = function(options, mode = "development") {
return {
entry: "./entry.js",
mode,
context: __dirname,
output: {
path: path.resolve(__dirname, "dist"),
filename: "bundle.js"
},
plugins: [new DuplicatePackageCheckerPlugin(options)]
};
};
|
/*
Known Modes:
- neutral
- walkaway
- Enable walkaway option
- play-by-play
- Enable play-by-play popup window showing the history of this game
- condition-random
- Utilize a random condition provided by the auth server
- condition
- Utilize a specific condition provided by the auth server
- MUST provide a 'slug' or 'id' param indicating the slug / id of the condition that should be used
- reputation-request
- Each player is asked to provide a reputation for the player at the end of the game.
- reputation-display
- The recorded reputation for a given player is displayed
- MUST provide a 'from' date param indicating which reputation should be displayed (typically yesterday's, but sometimes not).
- cooperation-display
- reputation-request-plus-scoreboard
- The player is asked for their opponent's reputation at the end of the game
*/
module.exports = {
'52e16ff5da19f40200000066': {
'2014-01-27': 'walkaway',
'2014-01-28': 'reputation-request',
'2014-01-29': 'reputation-display',
'2014-01-30': 'cooperation-display',
'2014-01-31': 'reputation-request-plus-scoreboard'
},
'52e16fbada19f40200000065': {
'2014-01-27': 'condition-random',
'2014-01-28': {
'mode': 'condition',
'id': '52a73159058f8d0200000005'
},
'2014-01-29': 'play-by-play',
'2014-01-30': {
'mode': 'condition',
'id': '52a72f64058f8d0200000002'
},
'2014-01-31': {
'mode': 'condition',
'id': '52a73c24058f8d0200000006'
}
},
'*': {
'2014-02-01': 'neutral',
'2014-02-02': {
'mode': 'condition',
'slug': 'condition-color'
},
'2014-02-04': {
'mode': 'condition',
'slug': 'condition-political'
},
'2014-02-05': {
'mode': 'walkaway'
},
'2014-02-07': {
'mode': 'play-by-play'
},
'2014-02-08': {
'mode': 'condition',
'slug': 'condition-transportation'
},
'2014-02-09': {
'mode': 'condition',
'slug': 'condition-political'
},
'2014-02-10': {
'mode': 'condition',
'slug': 'condition-color'
},
'2014-02-11': {
'mode': 'play-by-play'
},
'2014-02-12': {
'mode': 'reputation-request'
},
'2014-02-13': {
'mode': 'reputation-display',
'from': '2014-02-12'
},
'2014-02-14': {
'mode': 'reputation-request'
},
'2014-02-15': {
'mode': 'reputation-display',
'from': '2014-02-14'
},
'2014-02-17': {
'mode': 'walkaway'
},
'2014-02-18': {
'mode': 'play-by-play'
},
'2014-02-19': {
'mode': 'condition',
'slug': 'condition-transportation'
},
'2014-02-20': {
'mode': 'condition',
'slug': 'condition-color'
},
'2014-02-22': {
'mode': 'condition',
'slug': 'condition-transportation'
},
'2014-02-23': {
'mode': 'play-by-play'
},
'2014-02-24': {
'mode': 'condition',
'slug': 'condition-political'
},
'2014-02-25': {
'mode': 'cooperation-display'
},
'2014-02-28': {
'mode': 'reputation-request-plus-scoreboard'
}
}
};
|
version https://git-lfs.github.com/spec/v1
oid sha256:cc94bba58e6d6997e534f1aad9e9b1f76f8b8c5ee0356b423bebed6ad1024ace
size 2601
|
define('dojorama/layers/nls/release_zh-cn',{
'dojorama/ui/release/mixin/nls/_ReleaseActionsMixin':{"indexLabel":"Overview","createLabel":"Create New Release"}
,
'dojorama/ui/release/mixin/nls/_ReleaseBreadcrumbsMixin':{"homeLabel":"Home","releaseIndexLabel":"Releases","releaseCreateLabel":"Create New Release"}
,
'dojorama/ui/release/mixin/nls/_ReleaseComponentTitleMixin':{"sectionTitle":"Releases"}
,
'dojorama/ui/release/widget/snippet/nls/ReleaseFormSnippet':{"fieldTitleLabel":"Title","fieldFormatLabel":"Format","fieldFormatOptionLabel":"Select a format","fieldReleaseDateLabel":"Date","fieldPriceLabel":"Price","fieldPublishLabel":"Publish","fieldInfoLabel":"Info","submitLabel":"Save Release","submitBusyLabel":"Saving...","fieldPriceInvalidMessage":"Invalid entry"}
,
'dojorama/ui/release/widget/nls/ReleaseCreateFormWidget':{"title":"Create New Release","notificationCreateOk":"Created ok"}
,
'dojorama/ui/release/widget/nls/ReleaseGridWidget':{"filterSubmitLabel":"Filter","gridColumnLabelTitle":"Title","gridColumnLabelReleaseDate":"Release Date","gridColumnLabelPublish":"Publish","gridLoadingState":"Loading...","gridNoDataAvailable":"No data available","gridSaveButtonLabel":"Save","gridDeleteButtonLabel":"Delete selected","notificationUnknownError":"An error has occured","notificationUpdateOk":"Updated ok","notificationUpdateError":"Update error","notificationDeleteOk":"Delete ok","notificationDeleteError":"Delete error"}
,
'dojorama/ui/release/widget/nls/ReleaseUpdateFormWidget':{"notificationUpdateOk":"Updated ok"}
,
'dojorama/ui/release/nls/ReleaseCreatePage':{"pageTitle":"Create New Release"}
,
'dojorama/ui/release/nls/ReleaseIndexPage':{"pageTitle":"Releases"}
,
'dojorama/ui/release/nls/ReleaseUpdatePage':{"pageTitle":"Releases"}
});
|
import { elt, removeChildren } from "../util/dom"
import { indexOf } from "../util/misc"
import { updateGutterSpace } from "./update_display"
// Rebuild the gutter elements, ensure the margin to the left of the
// code matches their width.
export function updateGutters(cm) {
var gutters = cm.display.gutters, specs = cm.options.gutters
removeChildren(gutters)
for (var i = 0; i < specs.length; ++i) {
var gutterClass = specs[i]
var gElt = gutters.appendChild(elt("div", null, "CodeMirror-gutter " + gutterClass))
if (gutterClass == "CodeMirror-linenumbers") {
cm.display.lineGutter = gElt
gElt.style.width = (cm.display.lineNumWidth || 1) + "px"
}
}
gutters.style.display = i ? "" : "none"
updateGutterSpace(cm)
}
// Make sure the gutters options contains the element
// "CodeMirror-linenumbers" when the lineNumbers option is true.
export function setGuttersForLineNumbers(options) {
var found = indexOf(options.gutters, "CodeMirror-linenumbers")
if (found == -1 && options.lineNumbers) {
options.gutters = options.gutters.concat(["CodeMirror-linenumbers"])
} else if (found > -1 && !options.lineNumbers) {
options.gutters = options.gutters.slice(0)
options.gutters.splice(found, 1)
}
}
|
import isArray from '../util/isArray'
import isNumber from '../util/isNumber'
import isArrayEqual from '../util/isArrayEqual'
/**
@internal
*/
class Coordinate {
/**
@param {Array} path the address of a property, such as ['text_1', 'content']
@param {int} offset the position in the property
*/
constructor(path, offset) {
// HACK: to allow this class be inherited but without calling this ctor
if (arguments[0] === 'SKIP') return
if (arguments.length === 1) {
let data = arguments[0]
this.path = data.path
this.offset = data.offset
} else {
this.path = path
this.offset = offset
}
if (!isArray(this.path)) {
throw new Error('Invalid arguments: path should be an array.')
}
if (!isNumber(this.offset) || this.offset < 0) {
throw new Error('Invalid arguments: offset must be a positive number.')
}
}
equals(other) {
return (other === this ||
(isArrayEqual(other.path, this.path) && other.offset === this.offset) )
}
withCharPos(offset) {
return new Coordinate(this.path, offset)
}
getNodeId() {
return this.path[0]
}
getPath() {
return this.path
}
getOffset() {
return this.offset
}
toJSON() {
return {
path: this.path.slice(),
offset: this.offset
}
}
toString() {
return "(" + this.path.join('.') + ", " + this.offset + ")"
}
isPropertyCoordinate() {
return this.path.length > 1
}
isNodeCoordinate() {
return this.path.length === 1
}
hasSamePath(other) {
return isArrayEqual(this.path, other.path)
}
}
Coordinate.prototype._isCoordinate = true
export default Coordinate
|
(function () {
angular
.module('mogul')
.constant('OPTS', {
'server': 'http://localhost:9292/',
'itemsPerPage': 12
});
})();
|
angular.module('companyService',[])
.factory('Company', function($http){
var companyFactory = {};
companyFactory.create = function(companyData){
return $http.post('/api/companycreate', companyData);
};
companyFactory.allCompany = function(){
return $http.get('/api/companygetall');
};
// companyFactory.detail = function(){
// return $http.get('/api/companydetail/'+data.id);
// }
return companyFactory;
});
|
define([
"dojo/_base/declare",
"mijit/_WidgetBase",
"mijit/_TemplatedMixin",
"dojo/dom-construct"
], function (
declare,
_WidgetBase,
_TemplatedMixin,
domConstruct
) {
return declare([_WidgetBase, _TemplatedMixin], {
templateString: '<input type="text" data-dojo-attach-point="containerNode">',
name: '',
valueNode: null, // <input type="hidden"> holding the serialized value
_setNameAttr: function (name) {
if (this.valueNode) {
this.valueNode.name = name;
}
this._set('name', name);
},
_setValueAttr: function (v) {
var v = this._parseValue(v),
oldVal = this.get('value');
if (this.valueNode) {
this.valueNode.value = this._serializeValue(v);
}
this.domNode.value = this._formatValue(v);
this._set('value', v);
if (oldVal !== v) {
this.onChange(v);
}
},
_parseValue: function (v) {
return v;
},
_serializeValue: function (v) {
return v;
},
_formatValue: function (v) {
return v;
},
_attrToDom: function (attr, value, commands) {
// summary:
// the name must be set on the hidden field holding the serialized date to be submitted by a form.
// here we make sure that _WidgetBase::_attrToDom() doesn't set it on domNOde
if (attr !== 'name') {
this.inherited(arguments);
}
},
onChange: function (newValue) {},
_getDisplayValueAttr: function () {
return this.domNode.value;
},
startup: function () {
this.inherited(arguments);
this.valueNode = domConstruct.create('input', {
type: 'hidden',
name: this.get('name'),
value: this._serializeValue(this.get('value'))
}, this.domNode, 'after');
},
destroy: function () {
domConstruct.destroy(this.valueNode);
this.inherited(arguments);
}
});
});
|
'use strict';
var path = require('path')
, _ = require('lodash')
, chalk = require('chalk')
, yo = require('yeoman-generator')
, utils = require('../lib/utils')
, Base = yo.generators.Base;
_.mixin(require('lodash-deep'));
var AppGenerator = Base.extend({
constructor: function () {
Base.apply(this, arguments);
this.option('skip-welcome-message', {
desc: 'Do not show the Yeoman welcome message'
});
this.on('end', function () {
/* istanbul ignore if */
if (!this.options['skip-welcome-message']) {
console.log(chalk.yellow(
'\nThat was it! Open up this folder in your favorite editor\n' +
'and start hacking away.\n'
));
}
});
},
init: function () {
var self = this
, cb = this.async()
, base = this.dest._base()
, type = this.config.get('type');
utils.getAddon(base, type, function (err, addon) {
self.addon = addon;
cb();
});
},
welcome: function () {
// Have Yeoman greet the user
/* istanbul ignore if */
if (!this.options['skip-welcome-message']) {
console.log(this.yeoman);
console.log(chalk.yellow(
'I\'m here to guide you through the process of setting up\n' +
'a basic Addon for Vanilla. You can start by telling me a\n' +
'little bit about yourself. I will store this information\n' +
'in your addon so you only have to enter it once...\n'
));
}
},
askForAuthor: function () {
var next = this.async()
, prompts = [{
type: 'input'
, name: 'author'
, message: 'What is your full name?'
, default: _.deepGetValue(this, 'addon.author.name')
}, {
type: 'input'
, name: 'email'
, message: 'I would also like your email'
, default: _.deepGetValue(this, 'addon.author.email')
}, {
type: 'input'
, name: 'url'
, message: 'Optionally, enter your website'
, default: _.deepGetValue(this, 'addon.author.url')
}];
this.prompt(prompts, function (props) {
this.author = {
name : props.author
, email : props.email
, url : props.url
};
next();
}.bind(this));
},
askForLicense: function () {
/* istanbul ignore if */
if (!this.options['skip-welcome-message']) {
console.log(chalk.yellow(
'\nNow for a bit of information about your addon...\n'
));
}
var next = this.async()
, prompts = [{
type: 'list'
, name: 'license'
, message: 'Which license would you like to use?'
, default: _.deepGetValue(this, 'addon.license') || 'MIT'
, choices: [{
name: 'None'
, value: false
}, 'MIT', 'GPLv2', 'GPLv3', 'Apache']
}];
this.prompt(prompts, function (props) {
this.license = props.license;
next();
}.bind(this));
},
askForAddon: function () {
var next = this.async()
, prompts = [{
type: 'list'
, name: 'type'
, message: 'What kind of addon is this?'
, default: this.config.get('type')
, choices: ['Application', 'Plugin', 'Theme']
}, {
type: 'input'
, name: 'name'
, message: 'Enter the name of your addon'
, default: _.deepGetValue(this, 'addon.name')
}, {
type: 'input'
, name: 'desc'
, message: 'Describe your addon in a sentence or two'
, default: _.deepGetValue(this, 'addon.desc')
}, {
type: 'input'
, name: 'url'
, message: 'Optionally, enter the addons website'
, default: _.deepGetValue(this, 'addon.url')
}, {
type: 'checkbox'
, name: 'extras'
, message: 'Optional files to include in your application'
, choices: [
'class.hooks.php'
, 'configuration.php'
, 'bootstrap.php'
, 'structure.php'
]
, when: /* istanbul ignore next */ function (props) {
return props.type === 'Application';
}
}, {
type: 'checkbox'
, name: 'extras'
, message: 'Optional files to include in your theme'
, choices: [
'class.themehooks.php'
]
, when: /* istanbul ignore next */ function (props) {
return props.type === 'Theme';
}
}];
this.prompt(prompts, function (props) {
this.type = props.type;
this.name = props.name;
this.desc = props.desc;
this.url = props.url;
this.extras = props.extras || [];
this.config.set('type', this.type);
next();
}.bind(this));
},
files: function () {
var self = this
, today = new Date();
this.year = today.getFullYear();
this.directory = path.basename(this.dest._base());
this.copy('editorconfig', '.editorconfig');
if (this.license) {
this.template('licenses/' + this.license + '.md', 'LICENSE.md');
} else {
this.license = 'Proprietary';
}
this.template('README.md');
/* istanbul ignore next */
var extra = function (template, dest) {
if (self.extras.indexOf(template) !== -1) {
self.template(template, dest);
}
};
switch (this.type) {
case 'Application':
this.template('about.php', 'settings/about.php');
// Optional application files
extra('class.hooks.php', 'settings/class.hooks.php');
extra('configuration.php', 'settings/configuration.php');
extra('bootstrap.php', 'settings/bootstrap.php');
extra('structure.php', 'settings/structure.php');
break;
case 'Plugin':
this.template(
'class.plugin.php',
'class.' + this.directory.toLowerCase() + '.plugin.php'
);
break;
case 'Theme':
this.copy('default.master.tpl', 'views/default.master.tpl');
this.template('about.php');
// Optional theme files
extra('class.themehooks.php');
break;
}
this.config.save();
}
});
module.exports = AppGenerator;
|
/*
--- Day 15: Science for Hungry People ---
Today, you set out on the task of perfecting your milk-dunking cookie recipe.
All you have to do is find the right balance of ingredients.
Your recipe leaves room for exactly 100 teaspoons of ingredients. You make a
list of the remaining ingredients you could use to finish the recipe (your
puzzle input) and their properties per teaspoon:
capacity (how well it helps the cookie absorb milk)
durability (how well it keeps the cookie intact when full of milk)
flavor (how tasty it makes the cookie)
texture (how it improves the feel of the cookie)
calories (how many calories it adds to the cookie)
You can only measure ingredients in whole-teaspoon amounts accurately, and you
have to be accurate so you can reproduce your results in the future. The total
score of a cookie can be found by adding up each of the properties (negative
totals become 0) and then multiplying together everything except calories.
For instance, suppose you have these two ingredients:
Butterscotch: capacity -1, durability -2, flavor 6, texture 3, calories 8
Cinnamon: capacity 2, durability 3, flavor -2, texture -1, calories 3
Then, choosing to use 44 teaspoons of butterscotch and 56 teaspoons of cinnamon
(because the amounts of each ingredient must add up to 100) would result in a
cookie with the following properties:
- A capacity of 44*-1 + 56*2 = 68
- A durability of 44*-2 + 56*3 = 80
- A flavor of 44*6 + 56*-2 = 152
- A texture of 44*3 + 56*-1 = 76
Multiplying these together (68 * 80 * 152 * 76, ignoring calories for now)
results in a total score of 62842880, which happens to be the best score
possible given these ingredients. If any properties had produced a negative
total, it would have instead become zero, causing the whole score to multiply
to zero.
Given the ingredients in your kitchen and their properties, what is the total
score of the highest-scoring cookie you can make?
*/
const AMOUNT = 100;
export default function solution(input) {
const ingredients = input.trim()
.split('\n')
.map(line => line.split(':').map(i => i.trim()))
.map(([title, params]) => {
return params.split(',')
.map(i => i.trim().split(' '))
.reduce((a, i) => {
a[i[0]] = parseInt(i[1]);
return a;
}, {});
});
function score(ingredients, amounts) {
const all = ingredients
.reduce((a, item, i) => {
Object.keys(item).forEach(key => {
a[key] = a[key] || 0;
a[key] += item[key] * amounts[i];
});
return a;
}, {});
return Object.keys(all)
.reduce((a, key) => {
if (key === 'calories') {
return a;
}
return a * Math.max(0, all[key]);
}, 1);
}
const amounts = [];
for (let i = 0; i < ingredients.length; i++) {
amounts.push(0);
}
let answer = 0;
function calc(id = 0, amount = AMOUNT) {
if (amount === 0) {
answer = Math.max(answer, score(ingredients, amounts));
} else if (id < ingredients.length) {
for (let i = 0; i <= amount; i++) {
amounts[id] = i;
calc(id + 1, amount - i);
}
}
return answer;
}
return calc();
};
|
import run from './run';
/**
* Compiles the project from source files into a distributable
* format and copies it to the output (build) folder.
*/
async function build() {
await run(require('./clean'));
await run(require('./copy'));
await run(require('./bundle'));
}
export default build;
|
const assert = require('assert');
const { execSync } = require('child_process');
const fs = require('fs');
const specMarkdown = require('../');
const shouldRecord = Boolean(process.env.RECORD);
function testSource(dir, input, options) {
return [input || `test/${dir}/input.md`, `test/${dir}/ast.json`, `test/${dir}/output.html`, options];
}
runTests([
testSource('duplicated-notes'),
testSource('escape-sequence'),
testSource('graphql-spec', 'test/graphql-spec/GraphQL.md'),
testSource('productions'),
testSource('readme', 'README.md'),
testSource('readme-gh', 'README.md', '--githubSource https://github.com/leebyron/spec-md/blame/main'),
testSource('sections'),
testSource('simple-header'),
testSource('links'),
testSource('headers'),
testSource('smart-quotes'),
testSource('tables'),
testSource('task-lists'),
testSource('definitions'),
]);
function runTests(tests) {
for (const [input, ast, html, options] of tests) {
try {
runTest(input, ast, html, options);
} catch (error) {
process.exitCode = 1
if (error.code === 'ERR_ASSERTION') {
process.stderr.write('\n' + error.message + '\n\n');
if (!error.expected) {
process.stderr.write('\nNo recorded output found to compare to.\n\n');
} else {
const jestDiff = require('jest-diff').default;
process.stderr.write(
jestDiff(error.expected, error.actual, { expand: false }) + '\n\n'
);
}
} else {
process.stderr.write(
'\n\n' +
String(error.location ? error.message : (error.stack || error)) +
'\n\n'
);
}
}
}
}
function runTest(input, ast, html, options) {
const start = Date.now();
process.stdout.write(`testing: ${input} ... `);
const actualAST = specMarkdown.parse(input)
let expectedAST
try {
expectedAST = JSON.parse(fs.readFileSync(ast, 'utf8'));
} catch (_) {
// Ignore FS or parse error
}
try {
assert.deepEqual(
actualAST,
expectedAST,
'Did not parse expected AST.\n\n' +
'If confident the changes are correct, rerun with RECORD set:\n' +
' $ RECORD=1 yarn test'
);
} catch (error) {
if (error.code === 'ERR_ASSERTION' && shouldRecord) {
fs.writeFileSync(ast, JSON.stringify(actualAST, null, 2));
} else {
throw error;
}
}
// Test printing via command line, since that's how most use spec-md.
const actualHTML = execSync(`node ./bin/spec-md ${input} ${options || ''}`, { encoding: 'utf8' });
let expectedHTML
try {
// Normalize line endings
expectedHTML = fs.readFileSync(html, 'utf8').replace(/\r\n|\n|\r/g, '\n');
} catch (_) {
// Ignore FS error
}
try {
assert.strictEqual(
actualHTML,
expectedHTML,
'Did not print expected HTML.\n\n' +
'If confident the changes are correct, rerun with RECORD set:\n' +
' $ RECORD=1 npm test'
);
} catch (error) {
if (error.code === 'ERR_ASSERTION' && shouldRecord) {
fs.writeFileSync(html, actualHTML);
} else {
throw error;
}
}
process.stdout.write(`DONE (${Date.now() - start}ms) \n`);
}
|
import { Mongo } from 'meteor/mongo'
import { SimpleSchema } from 'meteor/aldeed:simple-schema'
const Articles = new Mongo.Collection('articles')
export const UPVOTE = 1
export const DOWNVOTE = -1
export const ELASTIC_SEARCH_INDEX = 'articles'
export const ELASTIC_SEARCH_TYPE = 'publications'
export const ArticleReportSchema = new SimpleSchema({
message: {
type: String,
},
authorId: {
type: SimpleSchema.RegEx.Id,
},
authorName: {
type: String,
},
createdAt: {
type: Date,
},
})
export const ArticleVoteSchema = new SimpleSchema({
vote: {
type: Number,
allowedValues: [DOWNVOTE, UPVOTE],
},
voterId: {
type: SimpleSchema.RegEx.Id,
},
voterName: {
type: String,
},
createdAt: {
type: Date,
},
})
export const ArticleSummarySchema = new SimpleSchema({
authorId: {
type: String,
},
authorName: {
type: String,
},
content: {
type: String,
},
createdAt: {
type: Date,
},
updatedAt: {
type: Date,
},
upVotes: {
type: Number,
},
downVotes: {
type: Number,
},
voters: {
type: [ArticleVoteSchema],
optional: true,
},
status: {
type: String,
allowedValues: ['enabled', 'disabled'],
},
})
export const ArticleKnowledgeBitSchema = new SimpleSchema({
type: {
type: String,
allowedValues: ['pdf', 'github'],
},
link: {
type: SimpleSchema.RegEx.Url,
},
label: {
type: String,
},
addedById: {
type: SimpleSchema.RegEx.Email,
},
addedByName: {
type: String,
},
status: {
type: String,
allowedValues: ['enabled', 'disabled'],
},
createdAt: {
type: Date,
},
updatedAt: {
type: Date,
},
upVotes: {
type: Number,
optional: true,
},
downVotes: {
type: Number,
optional: true,
},
voters: {
type: [ArticleVoteSchema],
optional: true,
},
})
export const ArticleRelatedArticleSchema = new SimpleSchema({
DOI: {
type: String,
},
title: {
type: String,
},
createdAt: {
type: Date,
},
addedById: {
type: SimpleSchema.RegEx.Id,
},
addedByName: {
type: String,
},
authors: {
type: [String],
},
abstract: {
type: String,
},
})
const schema = new SimpleSchema({
createdAt: {
type: Date,
optional: true,
autoValue() {
if (this.isInsert) {
return new Date()
} else if (this.isUpsert) {
return { $setOnInsert: new Date() }
} else {
this.unset()
}
},
},
updatedAt: {
type: Date,
optional: true,
autoValue() {
if (this.isUpdate) {
return new Date()
}
},
denyInsert: true,
},
title: {
label: 'Article name',
type: String,
},
authors: {
type: [String],
},
DOI: {
type: String,
unique: true,
},
abstract: {
type: String,
},
summaries: {
type: [ArticleSummarySchema],
optional: true,
},
informations: {
type: [ArticleKnowledgeBitSchema],
optional: true,
},
relatedArticles: {
type: [ArticleRelatedArticleSchema],
optional: true,
},
slug: {
type: String,
optional: true,
},
inappropriatedContentReports: {
type: [ArticleReportSchema],
optional: true,
},
})
Articles.attachSchema(schema)
Articles.friendlySlugs('title')
export default Articles
|
angular.module('devlogin', [
'devlogin.index',
'devlogin.forgot',
'devlogin.reset'
]);
|
// @flow strict
import { renderHook, act } from '@testing-library/react-hooks';
import * as PopperJs from '@popperjs/core';
// Public API
import { usePopper } from '.';
const referenceElement = document.createElement('div');
const popperElement = document.createElement('div');
describe('userPopper', () => {
afterEach(() => {
jest.clearAllMocks();
});
it('initializes the Popper instance', async () => {
const { result, wait } = renderHook(() =>
usePopper(referenceElement, popperElement)
);
await wait(() => {
expect(result.current.state).not.toBe(null);
});
});
it("doesn't update Popper instance on props update if not needed by Popper", async () => {
const spy = jest.spyOn(PopperJs, 'createPopper');
const { wait, rerender } = renderHook(
({ referenceElement, popperElement }) =>
usePopper(referenceElement, popperElement),
{ initialProps: { referenceElement, popperElement } }
);
await act(async () => {
await rerender({ referenceElement, popperElement });
});
await wait(() => {
expect(spy).toHaveBeenCalledTimes(1);
});
});
it('updates Popper on explicitly listed props change', async () => {
const spy = jest.spyOn(PopperJs, 'createPopper');
const { waitForNextUpdate, rerender } = renderHook(
({ referenceElement, popperElement }) =>
usePopper(referenceElement, popperElement),
{ initialProps: { referenceElement, popperElement } }
);
rerender({
referenceElement,
popperElement: document.createElement('div'),
});
await waitForNextUpdate();
expect(spy).toHaveBeenCalledTimes(2);
});
it('does not update Popper on generic props change', async () => {
const spy = jest.spyOn(PopperJs, 'createPopper');
const { waitForNextUpdate, rerender } = renderHook(
({ referenceElement, popperElement, options }) =>
usePopper(referenceElement, popperElement, options),
{ initialProps: { referenceElement, popperElement } }
);
rerender({
referenceElement,
popperElement,
options: { foo: 'bar' },
});
await waitForNextUpdate();
expect(spy).not.toHaveBeenCalledTimes(2);
});
it('destroys Popper on instance on unmount', async () => {
const spy = jest.spyOn(PopperJs, 'createPopper');
const { waitForNextUpdate, unmount } = renderHook(() =>
usePopper(referenceElement, popperElement)
);
await waitForNextUpdate();
const popperInstance = spy.mock.results[0].value;
const destroy = jest.spyOn(popperInstance, 'destroy');
await unmount();
expect(destroy).toHaveBeenCalled();
});
it('Initializes the arrow positioning', async () => {
const arrowElement = document.createElement('div');
const popperElementWithArrow = document.createElement('div');
popperElementWithArrow.appendChild(arrowElement);
const { result, waitForNextUpdate } = renderHook(() =>
usePopper(referenceElement, popperElementWithArrow, {
placement: 'bottom',
modifiers: [{ name: 'arrow', options: { element: arrowElement } }],
})
);
expect(result.current.styles.arrow.position).toBe('absolute');
expect(result.current.styles.arrow.transform).toBeUndefined();
await waitForNextUpdate();
expect(result.current.styles.arrow.transform).toBeDefined();
});
});
|
// JavaScript Document
var datable_result;
var _url_path = baseurl+'enrolment/new_enrolment/';
var _url_edit = baseurl+'enrolment/new_enrolment/';
var _url_del = baseurl+'enrolment/delete/';
$(document).ready(function() {
datable_result = $('#datable_score_student').DataTable( {
// fixedColumns : true,
"filter" : true,
"info" : true,
"paging" : true,
"ordering" : true,
"processing" : true,
"serverSide" : true ,
dom : "<'row'<'col-sm-4'l><'col-sm-4 text-center'B><'col-sm-4'f>>tp",
buttons: [
{extend: 'copy',className: 'btn-sm'},
{extend: 'csv',title: 'ExampleFile', className: 'btn-sm'},
{extend: 'pdf', title: 'ExampleFile', className: 'btn-sm'},
{extend: 'print',className: 'btn-sm'}
],
"ajax" : {
"url" : baseurl+'staff/get_employee_data',
"type" : 'POST',
"destroy" : true
},
language: {
processing: "<img src='"+baseurl+"assets/images/reload.gif'>",
loadingRecords: "<img src='"+baseurl+"assets/images/reload.gif'>",
"url": baseurl+"assets/langs/kh.json"
},
"columns" : [
{ "data" : "emp_code"},
{ "data" : "latin_last_name" },
{ "data" : "gender_id" },
{ "data" : "position_level" },
{ "data" : "position_level" },
{ "data" : "position_level" },
{ "data" : "position_level" },
{ "data" : "position_level" },
{ "data" : "position_level" },
{ "data" : "position_level" },
{ "data" : "position_level" },
{ "data" : "position_level" },
{ "data" : "position_level" },
{ "data" : "position_level" },
{ "data" : "position_level" },
{ "data" : "position_level" },
{ "data" : "position_level" },
{ "data" : "position_level" }
],
"order": [[0, 'desc']]
});
} );
function edit_enrolment_data(url){
$.ajax({
type: "POST",
url: url,
//dataType:"JSON",
//data: $("#frmNewEnrolment").serialize(), // serializes the form's elements.
success: function(data){
//alert(data);
$('#modal_ajax').modal('hide');
$('#document_render').html(data);
}
});
}
//
function on_delete_data(url){
delete_data(url,remove_row);
}
//
function remove_row(url){
$.ajax({
type: "POST",
url: url,
success: function(data){
datable_result.draw();
}
});
}
|
import React from 'react';
import { shallow } from 'enzyme';
import FormElementControl from '../FormElementControl';
describe('<FormElementControl />', () => {
let mounted = null;
const child = <div className="foo" />;
beforeEach(() => {
mounted = shallow(<FormElementControl>{child}</FormElementControl>);
});
it('renders the correct markup', () => {
expect(mounted.find('.slds-form-element__control').contains(child)).toBeTruthy();
});
it('renders left icon', () => {
mounted.setProps({ hasIconLeft: true });
expect(mounted.hasClass('slds-input-has-icon_right')).toBeFalsy();
expect(mounted.find('.slds-form-element__control').hasClass('slds-input-has-icon')).toBeTruthy();
expect(mounted.find('.slds-form-element__control').hasClass('slds-input-has-icon_left')).toBeTruthy();
});
it('renders right icon', () => {
mounted.setProps({ hasIconRight: true });
expect(mounted.hasClass('slds-input-has-icon_left')).toBeFalsy();
expect(mounted.find('.slds-form-element__control').hasClass('slds-input-has-icon')).toBeTruthy();
expect(mounted.find('.slds-form-element__control').hasClass('slds-input-has-icon_right')).toBeTruthy();
});
it('renders left and right icon together', () => {
mounted.setProps({ hasIconLeft: true, hasIconRight: true });
expect(mounted.hasClass('slds-input-has-icon_right')).toBeFalsy();
expect(mounted.hasClass('slds-input-has-icon_left')).toBeFalsy();
expect(mounted.find('.slds-form-element__control').hasClass('slds-input-has-icon')).toBeTruthy();
expect(mounted.find('.slds-form-element__control').hasClass('slds-input-has-icon_left-right')).toBeTruthy();
});
it('applies className and rest-properties', () => {
mounted.setProps({ className: 'foo', 'data-test': 'bar' });
expect(mounted.find('.slds-form-element__control').hasClass('foo')).toBeTruthy();
expect(mounted.find('.slds-form-element__control').prop('data-test')).toEqual('bar');
});
});
|
function init_types_categories() {
var init = function () { init_edit_modal(); };
load_modal_on_click('#create-type', { target: '#modal-sm', controller: 'admin', action: 'type' }, { todo: init });
load_modal_on_click('#create-category', { target: '#modal-sm', controller: 'admin', action: 'category' }, { todo: init });
init_bind_edit_remove();
}
function init_bind_edit_remove() {
var init_edit = function () { init_edit_modal(); };
load_modal_on_click('.edit-type', { target: '#modal-sm', controller: 'admin', action: 'type' }, { todo: init_edit });
load_modal_on_click('.edit-category', { target: '#modal-sm', controller: 'admin', action: 'category' }, { todo: init_edit });
var init_delete = function () { init_bind_edit_remove(); };
bind_delete('.remove-type', '#type-list', init_delete);
bind_delete('.remove-category', '#category-list', init_delete);
}
function init_edit_modal() {
var url = $('#modal-sm #send-infos-url').val();
var todo = function () { init_bind_edit_remove(); };
var success_message = 'Vos modifications ont รฉtรฉ prises en compte';
$('#modal-sm #send-type-modal-new').click(function() {
var name = $('#modal-sm #type_name').val();
send_infos(url, { name: name }, '#type-list', { todo: todo, success_message: success_message });
});
$('#modal-sm #send-type-modal-edit').click(function() {
var id = $('#modal-sm #type_id').val();
var name = $('#modal-sm #type_name').val();
send_infos(url, { id: id, name: name }, '.editable-type-' + id, { todo: todo, success_message: success_message });
});
$('#modal-sm #send-category-modal-new').click(function() {
var name = $('#modal-sm #category_name').val();
var type = $('#modal-sm #category_type').val();
send_infos(url, { name: name, type: type }, '#category-list', { todo: todo, success_message: success_message });
});
$('#modal-sm #send-category-modal-edit').click(function() {
var id = $('#modal-sm #category_id').val();
var name = $('#modal-sm #category_name').val();
var type = $('#modal-sm #category_type').val();
send_infos(url, { id: id, name: name, type: type }, '.editable-category-' + id, { todo: todo, success_message: success_message });
});
}
|
module.exports = {
verbose: true,
testURL: "http://localhost",
transform: {
".+\\.tsx?$": "ts-jest"
},
transformIgnorePatterns: ["/node_modules/", "/dist/"],
testRegex: "/__tests__/.*\\.spec\\.tsx?$",
moduleFileExtensions: ["ts", "tsx", "js", "jsx", "json", "node"]
};
|
import config from '../config';
import path from 'path';
import gulp from 'gulp';
import {Server} from 'karma';
gulp.task('unit', ['blogViews'], function(cb) {
new Server({
configFile: path.resolve(__dirname, '../..', config.test.karma),
singleRun: true
}, cb).start();
});
|
/**
* Vehicle payload
*
* LIGNA scenario: step 15
*
* Display description: - A chart of the vehicle payload for the current day
*
* Input variables: - machine[mid].technical_data.vehicle_payload
*
* @@source_header
*
* --
*
* This file is part of the focus-app-demonstrator package.
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*
*/
'use strict';
(function() {
angular.module('focusApp.vehiclePayload', [ 'focusApp.dataService', 'focusApp.navigationService' ])
.controller('VehiclePayloadController',
[ '$location', 'DataService', 'NavigationService', function($location, DataService, NavigationService) {
var _self = this;
/**
* Reference to DataService
*/
_self.dataSvc = DataService;
/**
* Get the id of the currently accessed machine
*/
var parts = $location.path().split(/\//);
_self.currentMachineId = parts[2] || 0;
/**
* Reference to the current data sample being rendered
*/
_self.dataSvc = DataService;
_self.data = DataService.data;
_self.dataMachine = DataService.data.machine[_self.currentMachineId];
/**
* Set the title of the page
*/
NavigationService.currentTitle = 'Vehicle payload - ' + _self.dataMachine.name;
/**
* Table with latest values
*/
_self.last_values = [];
/**
* Initialize everything.
*/
var _init = function() {
// infer max value for yAxis
var max_value = 10000 * 1.3;
angular
.forEach(
DataService.dataSet.timedependent['<TIME:machine[' + _self.currentMachineId + '].technical_data.vehicle_payload>'],
function(v) {
if (v > max_value) {
max_value = v * 1.3;
}
});
// init data array
_self.chartData = [ {
label : ' Payload: ' + _self.dataMachine.name,
color: '#4444ff',
data : [ [ DataService.startDateTime.getTime(), 0 ] ]
},
{
label : ' Overload threshold',
color: '#ff0000',
data : [ [ DataService.startDateTime.getTime(), 10000 ] ]
}];
// init chart options
_self.chartOptions = {
series : {
lines : {
show : true
},
points : {
show : false
},
},
xaxis : {
show : true,
mode : "time",
timezone : "browser",
ticks: 6
},
yaxis : {
min : 0,
max : max_value
},
legend: {
position: 'nw',
margin: [12, 6]
},
grid:
{
labelMargin: 12
}
};
};
_init();
/**
* Update the drawing of the map
*/
_self.drawDynamicData = function() {
// we store the new data in a tmp array, otherwise flot/angularjs will try to update the view on every data change
// and that's very CPU demanding
var new_data = [[],[]];
var TOTAL_SPAN_IN_INCREMENTS = 30 * 60 / 2;
// we want to always display a 30min timeline, so let's fill
// empty values if necessary
var num_empty = Math.max(TOTAL_SPAN_IN_INCREMENTS - DataService.currentTimeIncrement, 0);
for (var i = num_empty; i > 0; --i) {
var cur = DataService.startDateTime.getTime() - 2 * i * 1000;
new_data[0].push([ cur, null ]);
new_data[1].push([ cur, 10000 ]);
}
for (var i = 0; i < DataService.currentTimeIncrement; ++i) {
var cur = DataService.startDateTime.getTime() + 2 * i * 1000;
var val = DataService.dataSet.timedependent['<TIME:machine[' + _self.currentMachineId + '].technical_data.vehicle_payload>'][i];
new_data[0].push([ cur, val ]);
new_data[1].push([ cur, 10000 ]);
}
// do fill the new 'last values'
var last_elem = new_data[0].length - 1;
_self.last_values = [];
for (var i = 0; i < 10; ++i) {
_self.last_values.push({
date: new_data[0][last_elem - i*30][0],
value: new_data[0][last_elem - i*30][1]
});
}
angular.copy(new_data[0], _self.chartData[0].data);
angular.copy(new_data[1], _self.chartData[1].data);
};
_self.drawDynamicData();
/**
* Register refresh callback
*/
DataService.registerRefreshCallback(_self.drawDynamicData);
} ]);
}());
|
import cp from 'child_process';
import fs from 'fs';
import path from 'path';
import test from 'ava';
import helpers from 'yeoman-test';
const files = [
'lib/config.js',
'lib/persister.js',
'lib/logger.js',
'lib/sub.js',
'sub/commands.js',
'sub/completions.js',
'sub/example.js',
'sub/help.js',
'sub/init.js',
'sub/version.js',
'sub/update.js',
'tests/lib/config.spec.js',
'tests/lib/persister.spec.js',
'tests/lib/sub.spec.js',
'tests/sub/commands.spec.js',
'tests/sub/example.spec.js',
'tests/sub/version.spec.js',
'tests/fixtures/mockPersister.js',
'tests/fixtures/spyLogger.js',
'.eslintignore',
'.eslintrc',
'.gitignore',
'README.md',
'package.json',
'index.js',
'cli.js'
];
const testCases = [{
updateInterval: 7,
updater : 'git',
repo : 'http://github.com/doug-wade/example-sub',
argParser : 'minimist',
name : 'minimist-and-git'
}, {
updateInterval: 7,
updater : 'npm',
repo : 'http://github.com/doug-wade/example-sub',
argParser : 'yargs',
name : 'yargs-and-npm'
}];
testCases.forEach(testCase => {
test(`generator-sub:app ${testCase.name} creates files`, async t => {
let testDir;
await helpers.run(path.join(__dirname, '../generators/app'))
.inTmpDir(dir => {
testDir = dir;
})
.withPrompts(testCase)
.toPromise();
t.plan(files.length);
files.forEach(file => {
t.true(exists(file, testDir));
});
});
// These don't terminate on ci and take forever locally, so only run them when
// publishing
if (!process.env.CONTINUOUS_INTEGRATION) {
test(`generator-sub:app ${testCase.name} passes the test target`, async t => {
let testDir;
await helpers.run(path.join(__dirname, '../generators/app'))
.inTmpDir(dir => {
testDir = dir;
})
.withPrompts({name: 'foo', dockerCfg: false})
.toPromise();
await installDeps(testDir);
t.true(await runsSuccessfully('npm test', testDir));
});
}
});
function exists(filename, dir) {
filename = path.join(dir, filename);
try {
fs.accessSync(filename, fs.F_OK);
return true;
} catch (error) {
return false;
}
}
function runsSuccessfully(command, dir) {
return new Promise((resolve, reject) => {
cp.exec(command, {
cwd: dir
}, error => {
if (error) {
reject(error);
} else {
resolve(true);
}
});
});
}
function installDeps(dir) {
return new Promise((resolve, reject) => {
cp.exec('npm install', {
cwd: dir
}, error => {
if (error) {
reject(error);
} else {
resolve();
}
});
});
}
|
export default class {
constructor(jsonInputData = {}, storyInputData = {}) {
this.jsonInputData = jsonInputData;
this.storyInputData = storyInputData;
}
get input() {
let {jsonInputData = {}, storyInputData = {}} = this;
let {radioButtons = []} = jsonInputData;
let {options = []} = storyInputData;
let newRadioButtons = options.map(option => {
let {display, value} = option;
let radio = hasRadio(option, radioButtons);
if (radio) {
let newRadio = Object.assign({}, radio);
return newRadio;
} else {
return {
value,
label: display
}
}
});
let newInputData = Object.assign({},
jsonInputData, {
radioButtons: newRadioButtons,
type: "radio"
})
return newInputData;
function hasRadio(option, radioButtons = []) {
return radioButtons.find(radioButton => {
return radioButton.value === option.value;
})
}
}
}
|
// @flow
import * as React from 'react';
import Benchmark, { type BenchmarkRef } from '../Benchmark';
import BenchmarkType from '../BenchmarkType';
import { act, render, waitFor } from '@testing-library/react';
import type { Sample } from '../types';
type Props = {| testID: number |};
function Test({ testID }: Props) {
return <div id={testID}>hello</div>;
}
describe('new', () => {
beforeEach(() => {
jest.useRealTimers();
});
test('renders nothing if not running', () => {
const { getByTestId } = render(<Benchmark component={Test} onComplete={jest.fn()} samples={2} />);
expect(() => getByTestId('test')).toThrow('Unable to find an element');
});
test.each([[BenchmarkType.MOUNT], [BenchmarkType.UPDATE], [BenchmarkType.UNMOUNT]])(
'samples for %s',
async (type: $Values<typeof BenchmarkType>) => {
const ref = React.createRef<BenchmarkRef | void>();
const handleComplete = jest.fn();
render(<Benchmark ref={ref} component={Test} onComplete={handleComplete} samples={10} type={type} />);
act(() => {
ref.current && ref.current.start();
});
await waitFor(() =>
expect(handleComplete).toHaveBeenCalledWith(
expect.objectContaining({
sampleCount: 10,
})
)
);
}
);
describe('results', () => {
let results;
beforeAll(async () => {
const ref = React.createRef<BenchmarkRef | void>();
const handleComplete = jest.fn();
render(<Benchmark ref={ref} component={Test} onComplete={handleComplete} samples={2} />);
act(() => {
ref.current && ref.current.start();
});
await waitFor(() => expect(handleComplete).toHaveBeenCalled());
results = handleComplete.mock.calls[0][0];
});
test.each([
['startTime', 'number'],
['endTime', 'number'],
['runTime', 'number'],
['sampleCount', 'number'],
['max', 'number'],
['min', 'number'],
['median', 'number'],
['mean', 'number'],
['stdDev', 'number'],
['p70', 'number'],
['p95', 'number'],
['p99', 'number'],
])('include a key %s that is a %s', (key: string, type: string) => {
expect(results).toHaveProperty(key);
expect(typeof results[key]).toEqual(type);
});
test('includes an array for samples', () => {
expect(results).toHaveProperty('samples');
expect(Array.isArray(results.samples)).toBe(true);
results.samples.forEach((sample: Sample) => {
expect(sample).toHaveProperty('start');
expect(sample).toHaveProperty('end');
expect(sample).toHaveProperty('elapsed');
expect(sample).toHaveProperty('layout');
});
});
});
});
|
Cufon.replace('h1', {fontFamily: 'Comfortaa'});
Cufon.replace('p.c_soon strong', {fontFamily: 'Comfortaa'});
|
import React from 'react';
class AboutPage extends React.Component {
render() {
return (
<div>
<h1>About </h1>
</div>
)
}
}
export default AboutPage;
|
/*
Function: buttonPress
Params: - onclick - Function to call when button is clicked.
Returns: Nothing.
Operation: Adds consistent onmouse* events to a button.
*/
Element.prototype.buttonPress = function(onclick) {
this.onmouseover = function() {
this.style.borderColor = DEFAULT_COLOR;
};
this.onmouseout = function() {
this.style.borderColor = BACKGROUND_COLOR;
};
this.onmousedown = function() {
this.style.backgroundColor = DEFAULT_COLOR_TRANSLUCENT;
};
this.onmouseup = function() {
this.style.backgroundColor = BACKGROUND_COLOR;
};
this.onclick = onclick;
};
/*
Function: createShareButton
Params: - service - ShareService object to create the button for.
Returns: HTML "td" element for the button for the service.
Operation: Creates a button cell for the specified service. The cell contains the
service's title and icon and, when clicked, sends a share message to the
service's extension.
*/
function createShareButton(service) {
var cell = document.createElement("td");
cell.setAttribute("class", "service-button");
cell.setAttribute("id", service.extensionId + " " + service.id);
var image = document.createElement("img");
image.setAttribute("class", "service-icon");
image.setAttribute("src", service.icon);
image.setAttribute("alt", service.name);
var text = document.createElement("div");
text.setAttribute("class", "service-name");
text.innerText = service.name;
cell.appendChild(image);
cell.appendChild(document.createElement("br"));
cell.appendChild(text);
cell.buttonPress(function() {
service.sendShareMessageFromTab(displayResponseMessage);
});
return cell;
};
/*
Function: addCell
Params: - cell - the cell to be added.
Returns: Nothing.
Operation: Adds a new cell to the table of buttons. Buttons are added in rows of
four, so this function creates new rows in the table to maintain rows of
four buttons.
*/
function addCell(cell) {
var table = document.getElementById("button-table")
var row;
if (table.rows.length == 0) {
row = table.insertRow();
}
else if (table.rows[table.rows.length - 1].cells.length == 4) {
row = table.insertRow(-1);
}
else {
row = table.rows[table.rows.length - 1];
};
row.appendChild(cell);
};
/*
Function: refreshButtons
Params: None.
Returns: Nothing.
Operation: Clears any present buttons, then gets the active ShareServices from
storage and displays buttons for them all.
*/
function refreshButtons() {
var table = document.getElementById("button-table");
while (table.rows.length > 0) {
table.deleteRow(0);
};
getShareServiceFromStorage(null, function(services) {
for (var key in services) {
var button = createShareButton(services[key]);
addCell(button);
};
});
};
/*
Function: displayResponseMessage
Params: - response - object containing the response.
Returns: Nothing.
Operation: Takes a response from the ShareService extension and displays it in a
temporary box in the popup.
*/
function displayResponseMessage(response) {
if (response) {
console.log("Displaying response message", response);
var message_display = document.createElement("div");
message_display.setAttribute("id", "message");
message_display.innerText = response.message;
document.body.appendChild(message_display);
setTimeout(function() {
message_display.parentNode.removeChild(message_display)},
RESPONSE_MESSAGE_TIMEOUT);
};
};
document.addEventListener("DOMContentLoaded", function() {
// Add listeners for refresh and options buttons
document.getElementById("refresh").buttonPress(function() {
console.log("Refresh button clicked");
pingAllServices();
});
document.getElementById("options").buttonPress(function() {
console.log("Options button clicked");
chrome.tabs.create(
{url: "/options/options.html"},
function(tab) {chrome.windows.update(tab.windowId,{"focused": true});}
);
});
// Add listener to update buttons if services in storage changes.
chrome.storage.onChanged.addListener(function(changes) {
if (changes.services) {
refreshButtons();
};
});
refreshButtons();
});
|
(function (window, document) {
var layout = document.getElementById('layout'),
menu = document.getElementById('menu'),
menuLink = document.getElementById('menuLink');
function toggleClass(element, className) {
var classes = element.className.split(/\s+/),
length = classes.length,
i = 0;
for(; i < length; i++) {
if (classes[i] === className) {
classes.splice(i, 1);
break;
}
}
// The className is not found
if (length === classes.length) {
classes.push(className);
}
element.className = classes.join(' ');
}
menuLink.onclick = function (e) {
var active = 'active';
e.preventDefault();
toggleClass(layout, active);
toggleClass(menu, active);
toggleClass(menuLink, active);
};
$("pre").addClass("prettyprint").addClass("linenums");
if(typeof(prettyPrint)=='function'){
prettyPrint();
}
}(this, this.document));
|
'use strict';
/* Controllers */
angular.module('restBrowser.controllers', [])
.controller('MyCtrl1', ['$scope', 'Restangular', function($scope, Restangular) {
$scope.itemSelected = function(item) {
console.log(item.attr('id'));
var listing = Restangular.all(item.attr('id')).getList();
return listing;
};
}]);
|
/* OrderPortal
Meta documents indexed by id.
Value: title.
*/
function(doc) {
if (doc.orderportal_doctype !== 'meta') return;
emit(doc._id, null);
}
|
๏ปฟ(function () {
"use strict";
angular.module("mailCRMApp", ["ngRoute", "MailCRM.services", "MailCRM.controllers"])
.config(function ($routeProvider, $locationProvider) {
$routeProvider.when("/login", {
controller: "loginCtrl",
templateUrl: "../../templates/view-MailCRM-Login.html"
})
.when("/lookup", {
controller: "lookupCtrl",
templateUrl: "../../templates/view-MailCRM-Create.html"
})
.when("/detail", {
controller: "crmCtrl",
templateUrl: "../../templates/view-MailCRM-Detail.html"
})
.when("/contacts", {
controller: "crmCtrl",
templateUrl: "../../templates/view-MailCRM-Contacts.html"
})
.when("/invoices", {
controller: "crmCtrl",
templateUrl: "../../templates/view-MailCRM-Invoices.html"
})
.when("/location", {
controller: "geoCtrl",
templateUrl: "../../templates/view-MailCRM-Location.html"
})
.when("/notes", {
controller: "crmCtrl",
templateUrl: "../../templates/view-MailCRM-Notes.html"
})
.when("/attachments", {
controller: "crmCtrl",
templateUrl: "../../templates/view-MailCRM-Attachments.html"
})
.otherwise({ redirectTo: "/login" });
})
.directive("sideNav", ["$rootScope", "$location", "stateSvc", function ($rootScope, $location, stateSvc) {
return {
restrict: "E",
templateUrl: "../../templates/directive-MailCRM-SideNav.html",
scope: {
ngModel: "="
},
link: function (scope, element, attrs) {
scope.user = stateSvc.idToken.user;
scope.activeNavIndex = stateSvc.activeNavIndex;
scope.nav = function (path, index) {
stateSvc.activeNavIndex = index;
$location.path(path);
};
}
};
}])
.directive("spinner", function () {
return {
restrict: "E",
templateUrl: "../../templates/directive-MailCRM-Spinner.html"
};
});
})();
|
Meteor.startup(function() {
/**
* Sets Mideor.MIDI to the Web MIDI API object if there is a MIDI device
* detected otherwise false.
*
* Handles API change in Chrome 29.
*/
navigator.requestMIDIAccess()
.then(function (m) {
// Web MIDI API changed in Chrome 29 here's a catchall.
// Chrome < 29:
if (typeof m.inputs === 'function') {
Mideor.MIDI = m.inputs()[0];
} else {
// Chrome > 29:
Mideor.MIDI = m.inputs.values().next().value;
}
if (Mideor.MIDI) {
Mideor.log(Mideor.MIDI);
Mideor.MIDI.onmidimessage = Mideor.playNote;
} else {
Mideor.log('no midi device.');
}
}, function(err) {
Mideor.log("MIDI Access Failure. Error code: " + err.code );
});
});
|
// All symbols in the Kangxi Radicals block as per Unicode v6.1.0:
[
'\u2F00',
'\u2F01',
'\u2F02',
'\u2F03',
'\u2F04',
'\u2F05',
'\u2F06',
'\u2F07',
'\u2F08',
'\u2F09',
'\u2F0A',
'\u2F0B',
'\u2F0C',
'\u2F0D',
'\u2F0E',
'\u2F0F',
'\u2F10',
'\u2F11',
'\u2F12',
'\u2F13',
'\u2F14',
'\u2F15',
'\u2F16',
'\u2F17',
'\u2F18',
'\u2F19',
'\u2F1A',
'\u2F1B',
'\u2F1C',
'\u2F1D',
'\u2F1E',
'\u2F1F',
'\u2F20',
'\u2F21',
'\u2F22',
'\u2F23',
'\u2F24',
'\u2F25',
'\u2F26',
'\u2F27',
'\u2F28',
'\u2F29',
'\u2F2A',
'\u2F2B',
'\u2F2C',
'\u2F2D',
'\u2F2E',
'\u2F2F',
'\u2F30',
'\u2F31',
'\u2F32',
'\u2F33',
'\u2F34',
'\u2F35',
'\u2F36',
'\u2F37',
'\u2F38',
'\u2F39',
'\u2F3A',
'\u2F3B',
'\u2F3C',
'\u2F3D',
'\u2F3E',
'\u2F3F',
'\u2F40',
'\u2F41',
'\u2F42',
'\u2F43',
'\u2F44',
'\u2F45',
'\u2F46',
'\u2F47',
'\u2F48',
'\u2F49',
'\u2F4A',
'\u2F4B',
'\u2F4C',
'\u2F4D',
'\u2F4E',
'\u2F4F',
'\u2F50',
'\u2F51',
'\u2F52',
'\u2F53',
'\u2F54',
'\u2F55',
'\u2F56',
'\u2F57',
'\u2F58',
'\u2F59',
'\u2F5A',
'\u2F5B',
'\u2F5C',
'\u2F5D',
'\u2F5E',
'\u2F5F',
'\u2F60',
'\u2F61',
'\u2F62',
'\u2F63',
'\u2F64',
'\u2F65',
'\u2F66',
'\u2F67',
'\u2F68',
'\u2F69',
'\u2F6A',
'\u2F6B',
'\u2F6C',
'\u2F6D',
'\u2F6E',
'\u2F6F',
'\u2F70',
'\u2F71',
'\u2F72',
'\u2F73',
'\u2F74',
'\u2F75',
'\u2F76',
'\u2F77',
'\u2F78',
'\u2F79',
'\u2F7A',
'\u2F7B',
'\u2F7C',
'\u2F7D',
'\u2F7E',
'\u2F7F',
'\u2F80',
'\u2F81',
'\u2F82',
'\u2F83',
'\u2F84',
'\u2F85',
'\u2F86',
'\u2F87',
'\u2F88',
'\u2F89',
'\u2F8A',
'\u2F8B',
'\u2F8C',
'\u2F8D',
'\u2F8E',
'\u2F8F',
'\u2F90',
'\u2F91',
'\u2F92',
'\u2F93',
'\u2F94',
'\u2F95',
'\u2F96',
'\u2F97',
'\u2F98',
'\u2F99',
'\u2F9A',
'\u2F9B',
'\u2F9C',
'\u2F9D',
'\u2F9E',
'\u2F9F',
'\u2FA0',
'\u2FA1',
'\u2FA2',
'\u2FA3',
'\u2FA4',
'\u2FA5',
'\u2FA6',
'\u2FA7',
'\u2FA8',
'\u2FA9',
'\u2FAA',
'\u2FAB',
'\u2FAC',
'\u2FAD',
'\u2FAE',
'\u2FAF',
'\u2FB0',
'\u2FB1',
'\u2FB2',
'\u2FB3',
'\u2FB4',
'\u2FB5',
'\u2FB6',
'\u2FB7',
'\u2FB8',
'\u2FB9',
'\u2FBA',
'\u2FBB',
'\u2FBC',
'\u2FBD',
'\u2FBE',
'\u2FBF',
'\u2FC0',
'\u2FC1',
'\u2FC2',
'\u2FC3',
'\u2FC4',
'\u2FC5',
'\u2FC6',
'\u2FC7',
'\u2FC8',
'\u2FC9',
'\u2FCA',
'\u2FCB',
'\u2FCC',
'\u2FCD',
'\u2FCE',
'\u2FCF',
'\u2FD0',
'\u2FD1',
'\u2FD2',
'\u2FD3',
'\u2FD4',
'\u2FD5',
'\u2FD6',
'\u2FD7',
'\u2FD8',
'\u2FD9',
'\u2FDA',
'\u2FDB',
'\u2FDC',
'\u2FDD',
'\u2FDE',
'\u2FDF'
];
|
import { Base } from './base';
export class Asset extends Base {
setStage(stage) {
this.stage = stage;
}
set(params) {}
}
|
import Utils from './Utils';
import TestIDs from '../playground/src/testIDs';
const { elementById } = Utils;
describe.e2e('Lazy Registration', () => {
beforeEach(async () => {
await device.relaunchApp();
await elementById(TestIDs.STACK_BTN).tap();
});
it('push and pop lazily registered screen', async () => {
await elementById(TestIDs.PUSH_LAZY_BTN).tap();
await expect(elementById(TestIDs.LAZILY_REGISTERED_SCREEN_HEADER)).toBeVisible();
await expect(elementById(TestIDs.LAZY_TOP_PAR)).toBeVisible();
await elementById(TestIDs.POP_BTN).tap();
await expect(elementById(TestIDs.STACK_SCREEN_HEADER)).toBeVisible();
});
});
|
class x509enrollment_cx500distinguishedname {
constructor() {
// string EncodedName (EncodingType) {get}
this.Parameterized = undefined;
// string Name () {get}
this.Name = undefined;
}
// void Decode (string, EncodingType, X500NameFlags)
Decode(string, EncodingType, X500NameFlags) {
}
// void Encode (string, X500NameFlags)
Encode(string, X500NameFlags) {
}
}
module.exports = x509enrollment_cx500distinguishedname;
|
/**
* Talisman tokenizers/ngrams tests
* =================================
*
*/
import assert from 'assert';
import ngrams, {
bigrams,
trigrams,
quadrigrams
} from '../../src/tokenizers/ngrams';
describe('ngrams', function() {
it('should throw if n is < 1.', function() {
assert.throws(function() {
ngrams(-1, [1, 2, 3]);
}, Error);
});
it('should properly compute ngrams.', function() {
const solutions = {
1: [['h'], ['e'], ['l'], ['l'], ['o']],
2: [['h', 'e'], ['e', 'l'], ['l', 'l'], ['l', 'o']],
3: [['h', 'e', 'l'], ['e', 'l', 'l'], ['l', 'l', 'o']],
4: [['h', 'e', 'l', 'l'], ['e', 'l', 'l', 'o']]
};
Object.keys(solutions).forEach(n => {
assert.deepEqual(ngrams(n, 'hello'.split('')), solutions[n], `n = ${n}`);
assert.deepEqual(ngrams(n, 'hello'), solutions[n].map(s => s.join('')), `n = ${n}`);
});
});
it('popular aliases should also work.', function() {
assert.deepEqual(bigrams('hello'), ngrams(2, 'hello'));
assert.deepEqual(trigrams('hello'), ngrams(3, 'hello'));
assert.deepEqual(quadrigrams('hello'), ngrams(4, 'hello'));
});
});
|
import { OrderedMap, Map } from 'immutable'
import IdOrderedMap, {
ITEMS_KEY,
SELECTED_ID_KEY
} from './IdOrderedMap'
describe('(Models) IdOrderedMap', () => {
it('Should export a constant ITEMS_KEY.', () => {
expect(ITEMS_KEY).to.eql('items')
})
it('Should export a constant SELECTED_ID_KEY.', () => {
expect(SELECTED_ID_KEY).to.eql('selectedId')
})
it('Should create instance by default constructor', () => {
const instance = new IdOrderedMap()
expect(instance).to.be.ok
expect(instance.get(SELECTED_ID_KEY)).to.eql('0')
expect(instance.get(ITEMS_KEY).toObject()).to.eql(OrderedMap().toObject())
})
it('Should create instance by constructor', () => {
const instance = new IdOrderedMap(Map({
[SELECTED_ID_KEY]: '12',
[ITEMS_KEY]: Map({
'0': Map({ id: 0 }),
'1': Map({ id: 1 })
})
}))
expect(instance).to.be.ok
expect(instance.get(SELECTED_ID_KEY)).to.eql('12')
const expected = Map({
'0': Map({ id: 0 }),
'1': Map({ id: 1 })
})
expect(instance.get(ITEMS_KEY).toObject()).to.eql(expected.toObject())
})
})
|
'use strict';
describe('Controller: TestUploadCtrl', function () {
// load the controller's module
beforeEach(module('vadsenceNodeApp'));
var TestUploadCtrl, scope;
// Initialize the controller and a mock scope
beforeEach(inject(function ($controller, $rootScope) {
scope = $rootScope.$new();
TestUploadCtrl = $controller('TestUploadCtrl', {
$scope: scope
});
}));
it('should ...', function () {
expect(1).toEqual(1);
});
});
|
import fs from 'fs'
import bluebird from 'bluebird'
const readFile = bluebird.promisify(fs.readFile)
const writeFile = bluebird.promisify(fs.writeFile)
const upload = (array) =>
bluebird.each(array, (file) =>
readFile(file.path).then((img) => writeFile('/tmp/' + file.filename, img)))
export default upload
|
import React from 'react';
import { IconInfoBadgedSmallFilled, IconMarkerSmallOutline } from '@teamleader/ui-icons';
import { Icon, Input, Label, TextSmall, Tooltip } from '../../index';
import { addStoryInGroup, LOW_LEVEL_BLOCKS } from '../../../.storybook/utils';
const TooltippedIcon = Tooltip(Icon);
export default {
component: Label,
title: addStoryInGroup(LOW_LEVEL_BLOCKS, 'Form elements/Label'),
};
export const DefaultStory = (args) => (
<Label
{...args}
htmlFor="input1"
connectedLeft={
<Icon>
<IconMarkerSmallOutline />
</Icon>
}
connectedRight={
<TooltippedIcon tooltip={<TextSmall>This is the label tooltip text</TextSmall>} tooltipSize="small">
<IconInfoBadgedSmallFilled />
</TooltippedIcon>
}
>
Input label
<Input id="input1" placeholder="I am the placeholder" />
</Label>
);
DefaultStory.args = {
helpText: 'Optional',
};
|
"use strict";
let datafire = require('datafire');
let openapi = require('./openapi.json');
module.exports = datafire.Integration.fromOpenAPI(openapi, "azure_network_endpointservice");
|
// ๋ฌธ์์ด์ ์ค๋ฅธ์ชฝ์ trim ํฉ๋๋ค.์ญ์ฌ ํธ๋ฆผ ์์ ํ์ ๋ถ ์ธ์ธํจ์ด ๋๋ณด์
๋๋ค!
clean.string.rTrim = (function(){
var regExTrim;
// rTrim ์ ์ง์ํ๋ฉด
if( !!String.prototype.rTrim ){
return function( target ){
//REQUIRED: target: ๋ฐ๊ฟ ๋์์ ๋ฌธ์์ด์
๋๋ค!
return target.rTrim();
};
// rTrim ์ ์ง์ํ์ง ์์ผ๋ฉด
}else{
regExTrim = /\s+$/;
return function( target ){
//REQUIRED: target: ๋ฐ๊ฟ ๋์์ ๋ฌธ์์ด์
๋๋ค!
return target.replace( regExTrim, '' );
};
}
})();
|
function konami() {
var arr = [];
var konami = [38, 38, 40, 40, 37, 39, 37, 39, 66, 65, 13];
document.addEventListener('keyup', function(e) {
arr.push(e.keyCode);
if (arr.length >= 12) arr.shift();
if (arr.toString() === konami.toString()) cheatMode();
});
}
function cheatMode() {}
|
// Example webpack configuration for React with live reloading in development
// and asset fingerprinting in production.
"use strict";
var path = require("path");
var webpack = require("webpack");
// Helpers are hardcoded to expect dev assets at http://localhost:3808/webpack/*
var devServerPort = 3808;
// set TARGET=production on the environment to add asset fingerprints &
// omit hot-reloading
var production = process.env.TARGET === "production";
var config = {
entry: {
// Sources are expected to live in $app_root/webpack
application: [
"./webpack/application.js"
]
},
output: {
// Build assets directly in to public/webpack/, let webpack know
// that all webpacked assets start with webpack/
path: path.join(__dirname, "public", "webpack"),
publicPath: "/webpack",
// Add asset fingerprinting to production compiled assets with 'chunkhash'
filename: production ? "[name]-[chunkhash].js" : "[name].js"
},
module: {
loaders: [
// Example react JSX loader, with hot-reloading in development
{
test: /\.jsx?$/,
loaders: production ? ["jsx?harmony"] : ["react-hot", "jsx?harmony"],
include: path.join(__dirname, "webpack")
}
]
},
resolve: {
extensions: ["", ".js", ".jsx"]
},
// Sourcemaps in both production & development
devtool: "cheap-module-eval-source-map"
};
if(!production) {
config.devServer = {
port: devServerPort
};
// react-hot-loader configuration bits
config.plugins = [
new webpack.HotModuleReplacementPlugin(),
new webpack.NoErrorsPlugin()
];
Object.keys(config.entry).forEach(function(entryPoint) {
config.entry[entryPoint] = [
"webpack-dev-server/client?http://0.0.0.0:" + devServerPort,
"webpack/hot/only-dev-server"
].concat(config.entry[entryPoint]);
});
}
module.exports = config;
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.