text
stringlengths 2
6.14k
|
|---|
export * from './PythonHome';
export * from './PythonNav';
|
const JSONBox = require("../JSONBox");
const rmdir = require("rmdir");
const appRootDir = require("app-root-dir");
const Q = require("q");
const path = require("path");
const async = require("asyncawait/async");
const await = require("asyncawait/await");
const expect = require("chai").expect;
const fs = require("fs");
const mkdirp = require("mkdirp");
const sinon = require("sinon");
const uuid = require("uuid");
const assign = require("lodash.assign");
const testDir = "store-test";
const createMockData = async(function() {
this.obj = {
id: "76ba67b8-7907-11e6-8b77-86f30ca893d3",
some: "data",
is: "cool"
};
this.obj2 = {
id: "bc7e5fb6-7907-11e6-8b77-86f30ca893d3",
muchas: "gracias"
};
await(Q.nfcall(mkdirp ,path.join(appRootDir.get(), testDir)));
fs.writeFileSync(path.join(appRootDir.get(), testDir, `${this.obj.id}.json`), JSON.stringify(this.obj), {
flag: "w+"
});
fs.writeFileSync(path.join(appRootDir.get(), testDir, `${this.obj2.id}.json`), JSON.stringify(this.obj2), {
flag: "w+"
});
});
describe("JSONBox", function() {
before(function() {
this.uuid = sinon.stub(uuid, "v4").returns("53ccfe14-7916-11e6-8b77-86f30ca893d3");
});
after(function() {
this.uuid.restore();
})
afterEach(function(done) {
Q.nfcall(rmdir, path.join(appRootDir.get(), testDir))
.then(() => done())
.catch(() => done());
});
it("Get all entries (callback style)", function(done) {
createMockData.call(this)
.then(() => {
const box = JSONBox.of({
name: testDir
});
const expected = [this.obj, this.obj2];
box.all(function(error, data) {
if(error) done(error);
expect(data).to.eql(expected);
done();
});
});
});
it("Get all entries (promise style)", function(done) {
createMockData.call(this)
.then(() => {
const box = JSONBox.of({
name: testDir
});
return box.all();
})
.then(data => {
expect(data).to.eql([this.obj, this.obj2]);
done();
})
.catch(done);
});
it("Get a single entry (callback style)", function(done) {
createMockData.call(this)
.then(() => {
const box = JSONBox.of({
name: testDir
});
box.get(this.obj.id, function(error, data) {
if(error) done(error);
expect(data).to.eql(this.obj);
done();
}.bind(this));
});
});
it("Get a single entry (promise style)", function(done) {
createMockData.call(this)
.then(() => {
const box = JSONBox.of({
name: testDir
});
return box.get(this.obj.id);
})
.then(data => {
expect(data).to.eql(this.obj);
done();
})
.catch(done);
});
it("Store an entry (callback style)", function(done) {
const box = JSONBox.of({
name: testDir
});
const storable = {
abc: 123,
def: "456"
};
box.store(storable, function(error, data) {
if(error) done(error);
expect(data).to.eql(assign({}, data, {
id: "53ccfe14-7916-11e6-8b77-86f30ca893d3"
}));
done();
}.bind(this));
});
it("Store an entry (promise style)", function(done) {
const box = JSONBox.of({
name: testDir
});
const storable = {
abc: 123,
def: "456"
};
box.store(storable)
.then(data => {
expect(data).to.eql(assign({}, data, {
id: "53ccfe14-7916-11e6-8b77-86f30ca893d3"
}));
done();
})
.catch(done);
});
it("Store an null entry (callback style), expect Error", function(done) {
const box = JSONBox.of({
name: testDir
});
box.store(null, function(error, data) {
if(error) done();
else done(new Error("Expected to throw an Error!"));
});
});
it("Store an null entry (promise style), expect Error", function(done) {
const box = JSONBox.of({
name: testDir
});
box.store(null)
.then(data => done(new Error("Expected to throw an Error!")))
.catch(() => done());
});
it("Deletes an entry (callback style)", function(done) {
createMockData.call(this)
.then(() => {
const box = JSONBox.of({
name: testDir
});
box.delete(this.obj, function(error) {
if(error) done(error);
done();
}.bind(this));
});
});
it("Deletes an entry (promise style)", function(done) {
createMockData.call(this)
.then(() => {
const box = JSONBox.of({
name: testDir
});
box.delete(this.obj.id)
.then(() => done())
.catch(done);
});
});
});
|
const SafeHarborModules = require('./SafeHarborModules');
const SafeHarborInverters = require('./SafeHarborInverters');
module.exports = () => {
SafeHarborModules();
SafeHarborInverters();
}
|
'use strict';
describe('Controller: MainCtrl', function () {
// load the controller's module
beforeEach(module('tallytextApp'));
var MainCtrl,
scope;
// Initialize the controller and a mock scope
beforeEach(inject(function ($controller, $rootScope) {
scope = $rootScope.$new();
MainCtrl = $controller('MainCtrl', {
$scope: scope
});
}));
it('should attach a list of awesomeThings to the scope', function () {
expect(scope.awesomeThings.length).toBe(3);
});
});
|
'use strict'
const React = require('react');
import {Sidebar} from 'react-semantify';
const UISidebar = React.createClass({
render : function() {
return (
<Sidebar className="ui top sidebar menu push scale down" init={true}>
<a className="item">
Our company
</a>
<a className="item">
Dashboard
</a>
<a className="item">
My recipes
</a>
<a href="/logout" className="item right floated">
Logout
</a>
</Sidebar>
)
}
});
module.exports = UISidebar;
|
const express = require('express');
const app = express();
const port = 8080;
app.get('/', (req, res) => {
res.send('Hello World\n');
});
app.listen(port, () => {
console.log(`application is listening on port ${port}...`);
});
|
/*! Backstretch - v2.0.4 - 2013-06-19
* http://srobbin.com/jquery-plugins/backstretch/
* Copyright (c) 2013 Scott Robbin; Licensed MIT */
(function (a, d, p) {
a.fn.backstretch = function (c, b) {
(c === p || 0 === c.length) && a.error("No images were supplied for Backstretch");
0 === a(d).scrollTop() && d.scrollTo(0, 0);
return this.each(function () {
var d = a(this), g = d.data("backstretch");
if (g) {
if ("string" == typeof c && "function" == typeof g[c]) {
g[c](b);
return
}
b = a.extend(g.options, b);
g.destroy(!0)
}
g = new q(this, c, b);
d.data("backstretch", g)
})
};
a.backstretch = function (c, b) {
return a("body").backstretch(c, b).data("backstretch")
};
a.expr[":"].backstretch = function (c) {
return a(c).data("backstretch") !== p
};
a.fn.backstretch.defaults = {centeredX: !0, centeredY: !0, duration: 5E3, fade: 0};
var r = {left: 0, top: 0, overflow: "hidden", margin: 0, padding: 0, height: "100%", width: "100%", zIndex: -999999}, s = {position: "absolute", display: "none", margin: 0, padding: 0, border: "none", width: "auto", height: "auto", maxHeight: "none", maxWidth: "none", zIndex: -999999}, q = function (c, b, e) {
this.options = a.extend({}, a.fn.backstretch.defaults, e || {});
this.images = a.isArray(b) ? b : [b];
a.each(this.images, function () {
a("<img />")[0].src = this
});
this.isBody = c === document.body;
this.$container = a(c);
this.$root = this.isBody ? l ? a(d) : a(document) : this.$container;
c = this.$container.children(".backstretch").first();
this.$wrap = c.length ? c : a('<div class="backstretch"></div>').css(r).appendTo(this.$container);
this.isBody || (c = this.$container.css("position"), b = this.$container.css("zIndex"), this.$container.css({position: "static" === c ? "relative" : c, zIndex: "auto" === b ? 0 : b, background: "none"}), this.$wrap.css({zIndex: -999998}));
this.$wrap.css({position: this.isBody && l ? "fixed" : "absolute"});
this.index = 0;
this.show(this.index);
a(d).on("resize.backstretch", a.proxy(this.resize, this)).on("orientationchange.backstretch", a.proxy(function () {
this.isBody && 0 === d.pageYOffset && (d.scrollTo(0, 1), this.resize())
}, this))
};
q.prototype = {resize: function () {
try {
var a = {left: 0, top: 0}, b = this.isBody ? this.$root.width() : this.$root.innerWidth(), e = b, g = this.isBody ? d.innerHeight ? d.innerHeight : this.$root.height() : this.$root.innerHeight(), j = e / this.$img.data("ratio"), f;
j >= g ? (f = (j - g) / 2, this.options.centeredY && (a.top = "-" + f + "px")) : (j = g, e = j * this.$img.data("ratio"), f = (e - b) / 2, this.options.centeredX && (a.left = "-" + f + "px"));
this.$wrap.css({width: b, height: g}).find("img:not(.deleteable)").css({width: e, height: j}).css(a)
} catch (h) {
}
return this
}, show: function (c) {
if (!(Math.abs(c) > this.images.length - 1)) {
var b = this, e = b.$wrap.find("img").addClass("deleteable"), d = {relatedTarget: b.$container[0]};
b.$container.trigger(a.Event("backstretch.before", d), [b, c]);
this.index = c;
clearInterval(b.interval);
b.$img = a("<img />").css(s).bind("load",function (f) {
var h = this.width || a(f.target).width();
f = this.height || a(f.target).height();
a(this).data("ratio", h / f);
a(this).fadeIn(b.options.speed || b.options.fade, function () {
e.remove();
b.paused || b.cycle();
a(["after", "show"]).each(function () {
b.$container.trigger(a.Event("backstretch." + this, d), [b, c])
})
});
b.resize()
}).appendTo(b.$wrap);
b.$img.attr("src", b.images[c]);
return b
}
}, next: function () {
return this.show(this.index < this.images.length - 1 ? this.index + 1 : 0)
}, prev: function () {
return this.show(0 === this.index ? this.images.length - 1 : this.index - 1)
}, pause: function () {
this.paused = !0;
return this
}, resume: function () {
this.paused = !1;
this.next();
return this
}, cycle: function () {
1 < this.images.length && (clearInterval(this.interval), this.interval = setInterval(a.proxy(function () {
this.paused || this.next()
}, this), this.options.duration));
return this
}, destroy: function (c) {
a(d).off("resize.backstretch orientationchange.backstretch");
clearInterval(this.interval);
c || this.$wrap.remove();
this.$container.removeData("backstretch")
}};
var l, f = navigator.userAgent, m = navigator.platform, e = f.match(/AppleWebKit\/([0-9]+)/), e = !!e && e[1], h = f.match(/Fennec\/([0-9]+)/), h = !!h && h[1], n = f.match(/Opera Mobi\/([0-9]+)/), t = !!n && n[1], k = f.match(/MSIE ([0-9]+)/), k = !!k && k[1];
l = !((-1 < m.indexOf("iPhone") || -1 < m.indexOf("iPad") || -1 < m.indexOf("iPod")) && e && 534 > e || d.operamini && "[object OperaMini]" === {}.toString.call(d.operamini) || n && 7458 > t || -1 < f.indexOf("Android") && e && 533 > e || h && 6 > h || "palmGetResource"in d && e && 534 > e || -1 < f.indexOf("MeeGo") && -1 < f.indexOf("NokiaBrowser/8.5.0") || k && 6 >= k)
})(jQuery, window);
|
'use strict';
var request = require('request')
var uuid = require('node-uuid')
var env = require('./env')
var World = function World(callback) {
var self = this
this.collection = null
this.lastResponse = null
this.doc1 = null
this.doc2 = null
this.generateCollectionId = function() {
this.collection = uuid.v1()
}
this.generateDocumentId = function() {
// MongoDB either accepts a 12 byte string or 24 hex characters
this.doc1 = uuid.v1().replace(/-/gi, '').substring(0,24)
}
this.get = function(path, callback) {
var uri = this.uri(path)
request.get(uri, function(error, response) {
if (error) {
return callback.fail(new Error('Error on GET request to ' + uri +
': ' + error.message))
}
self.lastResponse = response
callback()
})
}
this.post = function(path, requestBody, callback) {
var uri = this.uri(path)
request({url: uri, body: requestBody, method: 'POST'},
function(error, response) {
if (error) {
return callback(new Error('Error on POST request to ' + uri + ': ' +
error.message))
}
self.lastResponse = response
callback(null, self.lastResponse.headers.location)
})
}
this.put = function(path, requestBody, callback) {
var uri = this.uri(path)
request({url: uri, body: requestBody, method: 'PUT'},
function(error, response) {
if (error) {
return callback(new Error('Error on PUT request to ' + uri + ': ' +
error.message))
}
self.lastResponse = response
callback(null, self.lastResponse.headers.locations)
})
}
this.delete = function(path, callback) {
var uri = this.uri(path)
request({url: uri, method: 'DELETE'},
function(error, response) {
if (error) {
return callback(new Error('Error on DELETE request to ' + uri + ': ' +
error.message))
}
self.lastResponse = response
callback()
})
}
this.options = function(path, callback) {
var uri = this.uri(path)
request({'uri': uri, method: 'OPTIONS'}, function(error, response) {
if (error) {
return callback.fail(new Error('Error on OPTIONS request to ' + uri +
': ' + error.message))
}
self.lastResponse = response
callback()
})
}
this.rootPath = function() {
return '/'
}
this.rootUri = function() {
return this.uri(this.rootPath())
}
this.collectionPath = function(collection) {
return '/' + collection
}
this.collectionUri = function(collection) {
return this.uri(this.collectionPath(collection))
}
this.documentPath = function(collection, document) {
return this.collectionPath(collection) + '/' + document
}
this.documentUri = function(collection, document) {
return this.uri(this.documentPath(collection, document))
}
this.uri = function(path) {
return env.BASE_URL + path
}
callback()
}
exports.World = World
|
var gulp = require('gulp');
gulp.task('default', function() {
console.log("Currently there are no available tasks. There will be!");
});
/**
* Builds the client files into a jar and moves it to the 'build/client' folder.
*/
/*
gulp.task('build-client', function() {
return gulp.src('.')
.pipe() // Build source/client/bin and data/client into a JAR.
.pipe(gulp.dest('build/client'));
});
*/
/**
* Builds the server files into a jar and moves it to the 'build/client' folder.
*/
/*
gulp.task('build-server', function() {
return gulp.src('.')
.pipe() // Build source/server/bin and data/server into a JAR.
.pipe(gulp.dest('build/server'));
});
*/
|
/***********************************************
gruntfile.js for jquery-bootstrap
https://github.com/fcoo/jquery-bootstrap
***********************************************/
module.exports = function(grunt) {
"use strict";
//***********************************************
grunt.initConfig({
"fcoo_grunt_plugin":{
default: {
"haveJavaScript": true, //true if the packages have js-files
"haveStyleSheet": true, //true if the packages have css and/or scss-files
"haveGhPages" : true, //true if there is a branch "gh-pages" used for demos
"beforeProdCmd": "", //Cmd to be run at the start of prod-task. Multi cmd can be seperated by "&"
"beforeDevCmd" : "", //Cmd to be run at the start of dev-task
"afterProdCmd" : "", //Cmd to be run at the end of prod-task
"afterDevCmd" : "", //Cmd to be run at the end of dev-task
"DEBUG" : false //if true different debugging is on and the tempoary files are not deleted
}
}
});
//****************************************************************
//Load grunt-packages
grunt.loadNpmTasks('grunt-fcoo-grunt-plugin');
};
|
// Copyright (c) 2012 Ecma International. All rights reserved.
// Ecma International makes this code available under the terms and conditions set
// forth on http://hg.ecmascript.org/tests/test262/raw-file/tip/LICENSE (the
// "Use Terms"). Any redistribution of this code must retain the above
// copyright and this notice and otherwise comply with the Use Terms.
/*---
es5id: 15.2.3.3-4-250
description: >
Object.getOwnPropertyDescriptor - returned object contains the
property 'get' if the value of property 'get' is not explicitly
specified when defined by Object.defineProperty.
includes: [runTestCase.js]
---*/
function testcase() {
var obj = {};
Object.defineProperty(obj, "property", {
set: function () {},
configurable: true
});
var desc = Object.getOwnPropertyDescriptor(obj, "property");
return "get" in desc;
}
runTestCase(testcase);
|
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.default = [['q', 'w', 'e', 'r', 't', 'y', 'u', 'i', 'o', 'p'], ['a', 's', 'd', 'f', 'g', 'h', 'j', 'k', 'l'], ['z', 'x', 'c', 'v', 'b', 'n', 'm']];
module.exports = exports['default'];
|
/**
* @file 棱镜配置文件
*/
var pkg = require('./package.json');
module.exports = {
appid: pkg.appid,
name: pkg.name,
desc: pkg.description,
host: `https://${pkg.appid}.h5app.alipay.com/www/`,
pages: [
{
entry: 'index.html',
src: './src/pages/index/index.js',
title: '首页',
desc: '首页 - 描述'
},
{
entry: 'list.html',
src : './src/pages/list/list.js',
title: 'list列表',
desc: 'list列表 - list列表页'
}
]
};
|
import { isNull } from '../checks/isNull';
import { isObject } from '../checks/isObject';
import { mustSatisfy } from '../checks/mustSatisfy';
/**
* @hidden
*/
function beObject() {
return "be a non-null `object`";
}
/**
* @hidden
*/
export function mustBeNonNullObject(name, value, contextBuilder) {
mustSatisfy(name, isObject(value) && !isNull(value), beObject, contextBuilder);
return value;
}
|
export default Ember.Handlebars.makeBoundHelper(function(price) {
var number = parseFloat(price/100).toFixed(2),
dollar = number.split('.')[0],
cents = number.split('.')[1],
dollars = dollar.split('').reverse().join('')
.replace(/(\d{3}(?!$))/g, '$1,')
.split('').reverse().join('');
return '$' + dollars + '.' + cents;
});
|
angular.module('fdb.directives', ['mcus.directives']);
angular.module('fdb.services', ['mcus.services']);
angular.module('fdb.filters', []);
angular.module('fdb', ['fdb.services', 'fdb.directives', 'fdb.filters']).
controller('UserFrontendCtrl', function($scope, $http, $timeout, $filter, $location) {
// $scope.deleteUser = function(user){
// if(confirm('Delete user ' + user.username + ' ?')){
// $http.post(Config.baseUrl + '/UsersFrontends/delete', {'id' : user.id}).success(function (resp) {
// if(resp == 'true'){
// for(var index = 0; index < $scope.users.length; index++) {
// if ($scope.users[index].UsersFrontend.id == user.id) {
// $scope.users.splice(index, 1);
// break;
// }
// }
// }else{
// alert('Error. Can not delete this user. View logs for more detail');
// }
// })
// }
// }
$scope.lockUser = function(user){
if(user.status == 'lock'){
message = 'Unlock this user with email: ';
status = 'active';
}else if(user.status == 'active'){
message = 'Lock this user with email: ';
status = 'lock';
}
if(confirm(message + user.email + '?')){
$http.post(Config.baseUrl + '/UsersFrontends/edit', {'id' : user.id, 'status' : status}).success(function (resp) {
console.log(resp);
if(resp.data){
user.status = status;
}else{
alert('Error');
}
})
}
}
$scope.search = function (row) {
if(row.UsersFrontend.username &&
angular.lowercase(row.UsersFrontend.username).indexOf($scope.query || '') !== -1){
return true;
}
if(row.UsersFrontend.fullname &&
angular.lowercase(row.UsersFrontend.fullname).indexOf($scope.query || '') !== -1){
return true;
}
if(row.UsersFrontend.email &&
angular.lowercase(row.UsersFrontend.email).indexOf($scope.query || '') !== -1){
return true;
}
if(row.UsersFrontend.facebook_id &&
angular.lowercase(row.UsersFrontend.facebook_id).indexOf($scope.query || '') !== -1){
return true;
}
if(row.UsersFrontend.status &&
angular.lowercase(row.UsersFrontend.status).indexOf($scope.query || '') !== -1){
return true;
}
return false;
};
$scope.editUser = function(user){
$scope.showError = true;
$scope.editingUser = angular.copy(user);
if ($scope.editUserForm.$invalid) {
return;
}
}
$scope.applyEditUser = function(){
$scope.showError = true;
console.log($scope.editUserForm);
if ($scope.editUserForm.$invalid) {
return;
}
var ptNotAllowSpecialCharacter = /[^a-zA-Z0-9]/;
if (ptNotAllowSpecialCharacter.test($scope.editingUser.username)) {
alert('Error, username contain special characters');
return false;
}
$http.post(Config.baseUrl + '/UsersFrontends/checkExistEmail', {'email' : $scope.editingUser.email, 'id' : $scope.editingUser.id}).success(function (res) {
// Not allow edit with existed email
if(res.check > 0){
alert('Error!. This email existed');
return;
}
})
var userData = {};
userData.id = $scope.editingUser.id;
userData.fullname = $scope.editingUser.fullname;
userData.username = $scope.editingUser.username;
userData.email = $scope.editingUser.email;
userData.facebook_id = $scope.editingUser.facebook_id;
userData.status = $scope.editingUser.status;
$http.post(Config.baseUrl + '/UsersFrontends/edit', userData).success(function (res) {
if(res.data){
response = res.data;
response.UsersFrontend.created = $scope.editingUser.created;
response.UsersFrontend.modified = $scope.editingUser.modified;
// remove old user object
for(var index = 0; index < $scope.users.length; index++) {
if ($scope.users[index].UsersFrontend.id == $scope.editingUser.id) {
$scope.users.splice(index, 1);
break;
}
}
// add new user object
$scope.users.push(response);
angular.element('#cancelEdit').trigger('click');
}
})
}
})
|
import React from "react";
import styled from "styled-components";
import Img from "gatsby-image";
import { graphql } from "gatsby";
import Center from "../components/center";
import ResponsiveContainer from "../components/responsive-container";
import Inset from "../components/inset";
import Text from "../components/text";
import colors from "../constants/colors";
import Layout from "../layouts";
import VersandhausWalzLogo from "../assets/compressed/versandhaus-walz.png";
import OttoLogo from "../assets/compressed/otto.png";
import LudwigMediaLogo from "../assets/compressed/ludwigmedia.png";
import BadischerWeinLogo from "../assets/compressed/badischer-wein.png";
import DrawkitContentManColour from "../assets/drawkit-content-man-colour.svg";
import Stack from "../components/stack";
const customers = [
{
src: OttoLogo,
alt: "Otto (GmbH & CoKG)"
},
{
src: VersandhausWalzLogo,
alt: "Versandhaus Walz"
},
{
src: LudwigMediaLogo,
alt: "LUDWIG:media gmbh"
},
{
src: BadischerWeinLogo,
alt: "Badischer Wein eKfr"
}
];
const HeroImage = styled.img`
width: 80%;
height: auto;
@media (min-width: 48em) {
width: auto;
height: 80vh;
max-height: 460px;
margin-left: -32px;
}
`;
const HeroLayout = styled(Stack)`
margin: 64px 0 32px;
@media (min-width: 48em) {
margin-top: 0;
flex-direction: row;
}
`;
const HeroArea = styled.div`
position: relative;
background-color: ${colors.black};
display: flex;
align-items: center;
@media (min-width: 48em) {
height: 80vh;
}
`;
const HeroTextArea = styled.div`
position: relative;
`;
const HeroText = styled.h1`
line-height: 1.1;
font-size: 2.5rem;
max-width: 22ch;
margin-top: 0;
color: ${colors.white};
text-align: center;
@media (min-width: 48em) {
font-size: 3rem;
text-align: left;
}
`;
const HeroTextHighlicht = styled.span`
color: ${colors.orange};
`;
const HeroTextSubheadline = styled.p`
line-height: 1.1;
font-size: 1.6rem;
max-width: 22ch;
color: #ddb992;
margin: 0;
text-align: center;
@media (min-width: 48em) {
text-align: left;
font-size: 2rem;
}
`;
const CustomerContainer = ResponsiveContainer.extend`
display: flex;
align-items: center;
flex-direction: column;
@media (min-width: 700px) {
flex-direction: row;
}
`;
const CustomerList = Center.extend`
padding: 32px 0;
background-color: hsla(31, 17%, 93%, 1);
`;
const CustomerLogo = styled.div`
flex: 1 1 auto;
max-height: 60px;
margin: 10px;
transition: all 0.5s ease-in-out;
> img {
max-width: 100%;
max-height: 100%;
}
`;
const H2 = styled.h2`
color: ${colors.textPrimary};
margin: 0 0 24px;
`;
const H3 = styled.h3`
color: ${colors.textPrimary};
margin: 0 0 16px;
`;
const SkillGrid = styled.div`
display: grid;
grid-template-columns: 1fr;
grid-gap: 16px;
@media (min-width: 700px) {
grid-template-columns: 1fr 1fr;
}
`;
const ServiceSection = styled.div`
background-color: hsla(13, 10%, 97%, 1);
padding: 32px 0;
`;
const Skill = styled.div`
background-color: white;
border-radius: 4px;
display: flex;
flex-direction: column;
text-align: left;
color: ${colors.text};
animation: fadein 2s;
`;
const SkillImage = styled.div`
max-height: 175px;
background-color: #ffe6df;
border-radius: 4px 4px 0 0;
overflow: hidden;
`;
const IndexPage = ({ data }) => (
<Layout>
<HeroArea>
<ResponsiveContainer>
<HeroLayout alignItems="center" scale="xl">
<HeroTextArea>
<HeroText>
Wir liefern digitale Lösungen,<br />
<HeroTextHighlicht>die unsere Kunden lieben.</HeroTextHighlicht>
</HeroText>
<HeroTextSubheadline>Und das seit 15 Jahren!</HeroTextSubheadline>
</HeroTextArea>
<HeroImage src={DrawkitContentManColour} alt="" />
</HeroLayout>
</ResponsiveContainer>
</HeroArea>
<CustomerList>
<CustomerContainer>
{customers.map(logo => (
<CustomerLogo key={logo.alt}>
<img src={logo.src} alt={logo.alt} />
</CustomerLogo>
))}
</CustomerContainer>
</CustomerList>
<ServiceSection>
<ResponsiveContainer>
<Center>
<H2>Unsere Leistungen</H2>
</Center>
<SkillGrid>
{data.allContentfulServices.edges.map(({ node }) => (
<Skill key={node.id}>
<SkillImage>
{node.image && <Img fluid={node.image.fluid} />}
</SkillImage>
<Inset scale="xl">
<H3>{node.title}</H3>
<Text.Detail>
<div
dangerouslySetInnerHTML={{
__html: node.description.childMarkdownRemark.html
}}
/>
</Text.Detail>
</Inset>
</Skill>
))}
</SkillGrid>
</ResponsiveContainer>
</ServiceSection>
</Layout>
);
export default IndexPage;
export const query = graphql`
query AllServices {
allContentfulServices(sort: { fields: [order], order: ASC }) {
edges {
node {
id
title
description {
childMarkdownRemark {
html
}
}
image {
fluid(maxWidth: 426) {
...GatsbyContentfulFluid
}
}
}
}
}
contentfulAsset(title: { eq: "Hero" }) {
fluid(maxHeight: 1000) {
...GatsbyContentfulFluid
}
}
}
`;
|
var fs = require('fs');
var path = require('path');
var log = require('./logging').logger;
var Project = module.exports;
Project.PROJECT_FILE = 'ionic.config.json';
Project.OLD_PROJECT_FILE = 'ionic.project';
Project.OLD_V2_PROJECT_FILE = 'ionic.config.js';
Project.PROJECT_DEFAULT = {
name: '',
app_id: '' // eslint-disable-line camelcase
};
Project.data = null;
Project.wrap = function wrap(appDirectory, data) {
return {
get: function get(key) {
return Project.get(data, key);
},
remove: function remove(key) {
return Project.remove(data, key);
},
set: function set(key, value) {
return Project.set(data, key, value);
},
save: function save() {
return Project.save(appDirectory, data);
}
};
};
Project.load = function load(appDirectory) {
if (!appDirectory) {
// Try to grab cwd
appDirectory = process.cwd();
}
var projectFile = path.join(appDirectory, Project.PROJECT_FILE);
var oldProjectFile = path.join(appDirectory, Project.OLD_PROJECT_FILE);
var oldV2ProjectFile = path.join(appDirectory, Project.OLD_V2_PROJECT_FILE);
var data;
var found;
try {
data = JSON.parse(fs.readFileSync(projectFile));
found = true;
if (fs.existsSync(oldV2ProjectFile)) {
log.warn(('WARN: ionic.config.js has been deprecated, you can remove it.').yellow);
}
} catch (e) {
if (e instanceof SyntaxError) {
log.error('Uh oh! There\'s a syntax error in your ' + Project.PROJECT_FILE + ' file:\n' + e.stack);
process.exit(1);
}
}
if (!found) {
try {
data = JSON.parse(fs.readFileSync(oldProjectFile));
log.warn('WARN: ionic.project has been renamed to ' + Project.PROJECT_FILE + ', please rename it.');
found = true;
} catch (e) {
if (e instanceof SyntaxError) {
log.error('Uh oh! There\'s a syntax error in your ionic.project file:\n' + e.stack);
process.exit(1);
}
}
}
if (!found) {
data = Project.PROJECT_DEFAULT;
if (fs.existsSync(oldV2ProjectFile)) {
log.warn('WARN: ionic.config.js has been deprecated in favor of ionic.config.json.');
log.info('Creating default ionic.config.json for you now...\n');
data.v2 = true;
if (fs.existsSync('tsconfig.json')) {
data.typescript = true;
}
}
var parts = path.join(appDirectory, '.').split(path.sep);
var dirname = parts[parts.length - 1];
Project.create(appDirectory, dirname);
Project.save(appDirectory, data);
}
return Project.wrap(appDirectory, data);
};
Project.create = function create(appDirectory, name) {
var data = Project.PROJECT_DEFAULT;
if (name) {
Project.set(data, 'name', name);
}
return Project.wrap(appDirectory, data);
};
Project.save = function save(appDirectory, data) {
if (!data) {
throw new Error('No data passed to Project.save');
}
try {
var filePath = path.join(appDirectory, Project.PROJECT_FILE);
var jsonData = JSON.stringify(data, null, 2);
fs.writeFileSync(filePath, jsonData + '\n');
} catch (e) {
log.error('Unable to save settings file:', e);
}
};
Project.get = function get(data, key) {
if (!data) {
return null;
}
if (key) {
return data[key];
} else {
return data;
}
};
Project.set = function set(data, key, value) {
if (!data) {
data = Project.PROJECT_DEFAULT;
}
data[key] = value;
};
Project.remove = function remove(data, key) {
if (!data) {
data = Project.PROJECT_DEFAULT;
}
data[key] = '';
};
|
'use strict';
var q = require('q');
var announcer = require('pd-api-announcer');
var methodNomen = require('./nomenclt');
var nm = require('./parenthood-nomenclt');
module.exports = function (Parent, Child) {
var hasChildName = methodNomen.ifOwns(Child);
Parent[hasChildName] = function (parentSid, childSid) {
return q.Promise(function (resolve, reject) {
var cId = childSid + '';
var redisKey = nm.childOf(Child.modelName(), Parent.modelName(), parentSid);
Child.redis.zsetExists(redisKey, cId).then(function (reply) {
resolve(reply);
}).fail(function (err) {
if (announcer.error(err).isSysFor('zsetItem', 'gone')) {
throw announcer.error.sys(Child.modelName(), 'gone');
}
}).fail(function (err) {
reject(err);
});
});
};
};
|
'use strict';
var inherits = require('util').inherits;
var _ = require('lodash');
var GremlinMethod = require('../function');
function GetPropertiesMethod() {
GremlinMethod.call(this, 'getProperties', arguments[0]);
}
inherits(GetPropertiesMethod, GremlinMethod);
GetPropertiesMethod.prototype.run = function(element) {
var o = {};
return element.properties;
};
module.exports = GetPropertiesMethod;
|
var gsc_basicmatch = /[a-z0-9]/i;
function gsc_getquery(elt, q)
{
q = ltrim(q);
q = q.replace('\s+', ' ');
if (q.length == 0 || !gsc_basicmatch.test(q)) {
gsc_emptyresults(elt);
return '';
}
if (elt.currentQuery && (elt.currentQuery == q || elt.tempQuery == q))
return '';
elt.currentQuery = q;
return q;
}
function gsc_hide(elt)
{
if (elt) elt.style.display = 'none';
}
function gsc_ishidden(elt)
{
return elt.style.display == 'none';
}
function gsc_show(elt)
{
if (elt) elt.style.display = 'block';
}
function gsc_emptyresults(elt)
{
if (!elt) return;
elt.innerHTML = '';
elt.numResults = 0;
elt.selectedIndex = 0;
elt.results = [];
gsc_hide(elt);
}
function gsc_addresult(elt, qElt, q, c, sel)
{
if (!elt) return;
if (sel) elt.selectedIndex = elt.numResults;
idx = elt.numResults;
elt.results[elt.numResults++] = c;
var _res = '';
_res += '<div class="' + (sel ? 'srs' : 'sr') + '"'
+ ' onmouseover="gsc_mouseover(\'' + elt.id + '\', \'' + qElt.id + '\', ' + idx + ')"'
+ ' onmouseout="gsc_mouseout(\'' + elt.id + '\', ' + idx + ')"'
+ ' onclick="gsc_mouseclick(\'' + elt.id + '\', \'' + qElt.id + '\', ' + idx + ')">';
_res += '<span class="srt">' + q + '</span>';
if (c.length > 0)
_res += '<span class="src">ID: ' + c + '</span>';
_res += '</div>';
elt.innerHTML += _res;
}
function gsc_mouseover(id, qId, idx)
{
elt = document.getElementById(id);
elt.selectedIndex = idx;
qElt = document.getElementById(qId);
qElt.focus();
gsc_highlightsel(elt);
}
function gsc_mouseout(id, idx)
{
elt = document.getElementById(id);
elt.selectedIndex = -1;
gsc_highlightsel(elt);
}
function gsc_mouseclick(id, qId, idx)
{
elt = document.getElementById(id);
qElt = document.getElementById(qId);
qElt.value = elt.results[idx];
qElt.form.submit();
}
function gsc_handleup(elt, qElt)
{
if (elt.numResults > 0 && gsc_ishidden(elt)) {
gsc_show(elt);
return;
}
if (elt.selectedIndex == 0)
return;
else if (elt.selectedIndex < 0)
elt.selectedIndex = elt.numResults - 1;
else
elt.selectedIndex--;
gsc_highlightsel(elt, qElt);
}
function gsc_handledown(elt, qElt)
{
if (elt.numResults > 0 && gsc_ishidden(elt)) {
gsc_show(elt);
return;
}
if (elt.selectedIndex == elt.numResults - 1)
return;
else if (elt.selectedIndex < 0)
elt.selectedIndex = 0;
else
elt.selectedIndex++;
gsc_highlightsel(elt, qElt);
}
function gsc_highlightsel(elt, qElt)
{
divs = elt.getElementsByTagName('div');
for (i = 0; i < divs.length; i++) {
if (i == elt.selectedIndex) {
divs[i].className = 'srs';
elt.tempQuery = elt.results[i];
if (qElt) {
qElt.value = elt.results[i];
if (qElt.createTextRange) {
r = qElt.createTextRange();
r.moveStart('character', elt.currentQuery.length);
r.moveEnd('character', qElt.value.length);
r.select();
}
}
}
else
divs[i].className = 'sr';
}
}
|
var _ = require('underscore'),
check = require('validator').check,
sanitize = require('validator').sanitize,
later = require('later'),
util = require('./util'),
condition = require('./condition');
var Rules = {
types: [
'trigger',
'schedule'
],
alertTypes: {
'email': {
// later
},
'sms': {
// later
}
},
/**
* Validates a rule type
*
* @param string type
*
* @return boolean
*/
validateRuleType: function(type) {
return typeof type == 'string' && _.contains(Rules.types, type);
},
/**
* Validates an rule scedule
*
* @param object schedule
*
* @return boolean
*/
validateSchedule: function(schedule) {
if (typeof schedule != 'object' || typeof schedule.schedules == 'undefined') {
if (_.isEmpty(schedule) || (schedule instanceof Array && schedule.length == 0) || typeof schedule == 'string')
return false;
schedule = {schedules: schedule};
}
// attempt to compile schedule in later.js
try {
later.schedule(schedule);
} catch (e) {
return false;
}
return true;
},
/**
* Validates an alert
*
* @param object|Array alert
*
* @return boolean
*/
validateAlert: function(alert) {
// validate alert type
if (typeof alert != 'object')
return false;
if( alert instanceof Array ) {
for (var i in alert) {
if (!Rules.validateAlert(alert[i]))
return false;
}
return true;
}
var alertTemplate = Rules.alertTypes[alert.type];
if (typeof alertTemplate == 'undefined')
return false;
// validate the endpoint (e-mail address, phone number)
if (typeof alert.endpoint == 'undefined')
return false;
if (alert.type == 'email') {
// validate e-mail address
try {
check(alert.endpoint).isEmail();
} catch (e) {
return false;
}
} else if (alert.type == 'sms') {
try {
check(sanitize(alert.endpoint).toInt()).len(3);
} catch (e) {
return false;
}
}
return true;
},
/**
* Validates a rule
*
* @param object rule
*
* @return boolean
*/
validate: function(rule) {
if (typeof rule != 'object')
return false;
if (!Rules.validateRuleType(rule.type))
return false;
if (!condition(rule.condition).isValid())
return false;
// validate schedule rules
if (rule.type == 'schedule' && !Rules.validateSchedule(rule.schedule))
return false;
if (!Rules.validateAlert(rule.alert))
return false;
return true;
},
};
module.exports = Rules;
|
var keystone = require('keystone'),
async = require('async');
exports = module.exports = function(req, res) {
var view = new keystone.View(req, res),
locals = res.locals;
// Init locals
locals.section = 'ideas';
locals.page.title = 'Ideas - Evilcome';
locals.filters = {
category: req.params.category
};
locals.data = {
posts: [],
categories: []
};
// Load all categories
view.on('init', function(next) {
keystone.list('PostCategory').model.find().sort('name').exec(function(err, results) {
if (err || !results.length) {
return next(err);
}
locals.data.categories = results;
// Load the counts for each category
async.each(locals.data.categories, function(category, next) {
keystone.list('Post').model.count().where('category').in([category.id]).exec(function(err, count) {
category.postCount = count;
next(err);
});
}, function(err) {
next(err);
});
});
});
// Load the current category filter
view.on('init', function(next) {
if (req.params.category) {
keystone.list('PostCategory').model.findOne({ key: locals.filters.category }).exec(function(err, result) {
locals.data.category = result;
next(err);
});
} else {
next();
}
});
// Load the posts
view.on('init', function(next) {
var q = keystone.list('Post').model.find().where('state', 'published').sort('-publishedDate').populate('author categories');
if (locals.data.category) {
q.where('categories').in([locals.data.category]);
}
q.exec(function(err, results) {
locals.data.posts = results;
next(err);
});
});
// Render the view
view.render('site/idea');
}
|
const createSortDownIcon = (button) => {
button.firstChild.remove();
const svg = document.createElementNS('http://www.w3.org/2000/svg', 'svg');
svg.setAttribute('height', '12');
svg.setAttribute('viewBox', '0 0 503 700');
const path = document.createElementNS('http://www.w3.org/2000/svg', 'path');
path.setAttribute('d', `M43.302,409.357h418.36c37.617,0,56.426,45.527,29.883,72.07l-209.18,209.18c-16.523,16.523-43.243,16.523-59.59,0
L13.419,481.428C-13.124,454.885,5.685,409.357,43.302,409.357z`);
svg.appendChild(path);
button.appendChild(svg);
};
export default createSortDownIcon;
|
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
$(function () {
$('[data-toggle="popover"]').popover();
$('.main-hide-div').hide();
$('#UserTab a').click(function (e) {
e.preventDefault();
$(this).tab('show');
});
$(document).on('click','[class*="main-JS-delete"]', function(){
if(!confirm('Etes-vous sûr de vouloir supprimer cet élément ?')) return false;
});
});
|
module.exports = (api) => {
api.cache(true);
return {
presets: [
[
"@babel/preset-env",
{
useBuiltIns: "usage",
corejs: 3,
},
],
],
};
};
|
import * as React from "react";
import Slide from "../../components/slide";
const bgImage = require("../../images/hulk-feriggno-bixby.jpg");
class ImageSlide extends React.Component {
render() {
return (
<span/>
);
}
}
export default (
<Slide key="intro-cli-productivity-illustration" bgImage={bgImage}>
<ImageSlide/>
</Slide>
);
|
const fetch = require("isomorphic-fetch");
function getUrl(query, variables) {
const urlRoot = `http://localhost:3000/graphql?query=${query}`;
if (variables == null) {
return urlRoot;
} else {
return urlRoot + `&variables=${JSON.stringify(variables)}`;
}
}
function run(query, variables) {
const url = getUrl(query, variables)
return fetch(encodeURI(url))
.then(response => response.json())
.then(json => (console.log(JSON.stringify(json, null, 2)), json))
.catch(e => console.error(e));
}
// Single operation query
run(`{
hero {
name
}
}`)
// Query Operations cna have names, but that's only
// required when a query has several operations.
// This one has a name, but only one op.
// The response looks the same as an un-named operation.
run(`
query HeroNameQuery {
hero {
name
}
}`);
// Requests more fields, including some deeply-nested members
// of the `friends` property.
// The syntax is like a relaxed version of JSON without values
run(`{
hero {
id
name
friends {
id, name
}
}
}`);
// GraphQL is designed for deeply-nested queries, hence "Graph".
run(`{
hero {
name
friends {
name
appearsIn
friends {
name
}
}
}
}`);
// Pass hard-coded parameters...
run(`{
human(id: "1000") {
name
}
}`)
// ... or typed runtime query parameters.
// parameter names start with $
// the sigil isn't included in the passed variable name
run(`
query HumanById($id: String!) {
human(id: $id) {
name
}
}`, { id: "1001" })
// fields can be aliased
// The field names in the response will be called `luke` and leia`, not `human`.
// Aliases are required to fetch the same field several times - using
/// "human" twice is invalid.
run(`{
luke: human(id: "1003") {
name
},
leia: human(id: "1000") {
name
}
}`);
// Common parts of queries can be extracted into fragmments
// with a syntax like Object rest params
run(`
fragment HumanFragment on Human {
name, homePlanet
}
{
luke: human(id: "1000") {
...HumanFragment
},
leia: human(id: "1003") {
...HumanFragment
}
}
`)
// The speciala field __typename identifies the result object's type.
// This is especially useful for interface fields.
run(`
fragment HeroFragment on Character {
name
__typename
}
{
hope: hero(episode: NEWHOPE) {
...HeroFragment
},
empire: hero(episode: EMPIRE) {
...HeroFragment
},
jedi: hero(episode: JEDI) {
...HeroFragment
},
hero {
...HeroFragment
}
}
`)
|
import React from 'react';
import IconBase from './../components/IconBase/IconBase';
export default class IosAnalytics extends React.Component {
render() {
if(this.props.bare) {
return <g>
<path d="M256,32C141.174,32,46.544,118.404,33.54,229.739C32.534,238.354,32,247.114,32,256c0,1.783,0.026,3.561,0.067,5.333
C34.901,382.581,134.071,480,256,480c105.255,0,193.537-72.602,217.542-170.454c1.337-5.451,2.474-10.979,3.404-16.579
C478.943,280.939,480,268.594,480,256C480,132.288,379.712,32,256,32z M462.585,280.352c-7.265-7.807-13.064-16.09-15.702-20.429
c-0.871-1.47-21.682-35.994-52.828-35.994c-27.937,0-42.269,26.269-51.751,43.65c-1.415,2.593-2.75,5.041-3.978,7.118
c-11.566,19.587-27.693,30.608-43.105,29.541c-13.586-0.959-25.174-11.403-32.628-29.41c-9.331-22.54-29.551-46.812-53.689-50.229
c-11.428-1.619-28.553,0.866-45.325,21.876c-3.293,4.124-6.964,9.612-11.215,15.967c-10.572,15.804-26.549,39.686-38.653,41.663
c-21.02,3.438-35.021-12.596-35.583-13.249l-0.487-0.58l-0.587-0.479c-0.208-0.17-15.041-12.417-29.047-33.334
c0-0.155-0.006-0.31-0.006-0.464c0-28.087,5.497-55.325,16.339-80.958c10.476-24.767,25.476-47.013,44.583-66.12
s41.354-34.107,66.12-44.583C200.675,53.497,227.913,48,256,48s55.325,5.497,80.958,16.339
c24.767,10.476,47.013,25.476,66.12,44.583s34.107,41.354,44.583,66.12C458.503,200.675,464,227.913,464,256
C464,264.197,463.518,272.318,462.585,280.352z"></path>
</g>;
} return <IconBase>
<path d="M256,32C141.174,32,46.544,118.404,33.54,229.739C32.534,238.354,32,247.114,32,256c0,1.783,0.026,3.561,0.067,5.333
C34.901,382.581,134.071,480,256,480c105.255,0,193.537-72.602,217.542-170.454c1.337-5.451,2.474-10.979,3.404-16.579
C478.943,280.939,480,268.594,480,256C480,132.288,379.712,32,256,32z M462.585,280.352c-7.265-7.807-13.064-16.09-15.702-20.429
c-0.871-1.47-21.682-35.994-52.828-35.994c-27.937,0-42.269,26.269-51.751,43.65c-1.415,2.593-2.75,5.041-3.978,7.118
c-11.566,19.587-27.693,30.608-43.105,29.541c-13.586-0.959-25.174-11.403-32.628-29.41c-9.331-22.54-29.551-46.812-53.689-50.229
c-11.428-1.619-28.553,0.866-45.325,21.876c-3.293,4.124-6.964,9.612-11.215,15.967c-10.572,15.804-26.549,39.686-38.653,41.663
c-21.02,3.438-35.021-12.596-35.583-13.249l-0.487-0.58l-0.587-0.479c-0.208-0.17-15.041-12.417-29.047-33.334
c0-0.155-0.006-0.31-0.006-0.464c0-28.087,5.497-55.325,16.339-80.958c10.476-24.767,25.476-47.013,44.583-66.12
s41.354-34.107,66.12-44.583C200.675,53.497,227.913,48,256,48s55.325,5.497,80.958,16.339
c24.767,10.476,47.013,25.476,66.12,44.583s34.107,41.354,44.583,66.12C458.503,200.675,464,227.913,464,256
C464,264.197,463.518,272.318,462.585,280.352z"></path>
</IconBase>;
}
};IosAnalytics.defaultProps = {bare: false}
|
self.postMessage(0);
self.addEventListener('message', function (msg) {
if (msg.data === 'Hello') {
self.postMessage(1);
}
else if (msg.data instanceof self.ArrayBuffer) {
var view = new Int32Array(msg.data);
if (view[0] === 2) {
self.postMessage(3);
}
}
});
|
'use strict';
if (/^((?!chrome).)*safari/i.test(navigator.userAgent)){
alert("We have detected you are using Safari. Please switch to Chrome or Firefox to properly use this app.");
}
var weekAbbrev = {
Mo: "monday",
Tu: "tuesday",
We: "wednesday",
Th: "thursday",
Fr: "friday",
Sa: "saturday",
Su: "sunday"
};
var badString = function(str){
return str == null || str.trim().length === 0;
}
//returns an ics object
var parseCourseworkString = function(){
var cs = document.getElementById("classes").value.trim(),
quarterLength = document.getElementById("weeks").value.trim(),
calObj = ics(),
startDate = document.getElementById("startDate").value.trim() + " ";
if(badString(cs)){ alert("Please copy paste in the Axess course table"); return; }
if(badString(startDate)){ alert("Please input start date in the MM/DD/YYYY format"); return; }
if(badString(quarterLength) || !_.isNumber(parseInt(quarterLength)) || parseInt(quarterLength) < 1){
alert("Please insert a valid number of weeks in the quarter.");
return;
}
var counter = 0;
//removes descrepancy between Firefox and Chrome copy pasting.
var prelimFilter = _.chain(cs.split("\n")).filter(function(row){
return row.trim().length > 0
}).value().join('\n').split('Academic Calendar Deadlines');
_.chain(prelimFilter).map(function(row){
return _.compact(row.split("\n"));
}).filter(function(items){
if(items.length != 6 && items.length > 3){
counter ++;
}
return items.length === 6;
}).map(function(items){
var name = items[0],
desc = items[1] + " Unit: " + items[2] + " Grading:" + items[3],
location = items[5],
timeObj = items[4].split(" "),
timeStart = new Date(startDate + timeObj[1].substr(0, timeObj[1].length - 2) + " " + timeObj[1].substr(-2)),
timeEnd = new Date(startDate + timeObj[3].substr(0, timeObj[3].length - 2) + " " + timeObj[3].substr(-2));
if(timeStart===null || timeEnd === null || timeStart.toString()==="Invalid Date" || timeEnd.toString()==="Invalid Date"){
alert("Please input a correct start date format of MM/DD/YYYY");
throw "Badly formatted Start Date (╯°□°)╯︵ ┻━┻";
}
var wkNumber = timeStart.getWeek(),
repeat = timeObj[0].match(/.{1,2}/g).join(','),
shiftedStart = Date.today().setWeek(wkNumber).sunday().last()[weekAbbrev[repeat.split(',')[0]]]().at(timeObj[1]), //Alterations to the dates because the library acts strangely
shiftedEnd = Date.today().setWeek(wkNumber).sunday().last()[weekAbbrev[repeat.split(',')[0]]]().at(timeObj[3]);
calObj.addEvent(name, desc, location, shiftedStart, shiftedEnd, repeat, quarterLength * repeat.split(',').length);
});
calObj.download("schedule", ".ics");
if(counter > 0){
alert(counter + (counter > 1 ? " classes ": " class ") + "failed to be exported. The formatting was weird.")
}
}
|
'use strict';
angular.module('core').controller('HomeController', ['$scope', 'Authentication',
function($scope, Authentication) {
// This provides Authentication context.
$scope.authentication = Authentication;
$scope.alerts = [
{
icon:'glyphicon-user',
color:'btn-success',
total:'20,408',
description:'TOTAL CUSTOMERS'
},
{
icon:'glyphicon-calendar',
color:'btn-primary',
total:'8,382',
description:'UPCOMING EVENTS'
},
{
icon:'glyphicon-edit',
color:'btn-success',
total:'527',
description:'NEW CUSTOMERS IN 24H'
},
{
icon:'glyphicon-record',
color:'btn-info',
total:'85,000',
description:'EMAILS SENT'
},
{
icon:'glyphicon-eye-open',
color:'btn-warning',
total:'20,408',
description:'FOLLOW UPS REQUIRED'
},
{
icon:'glyphicon-flag',
color:'btn-danger',
total:'348',
description:'REFERRALS TO MODERATE'
}
];
}
]);
|
"use strict";
let keyMirror = require('react/lib/keyMirror');
module.exports = keyMirror({
INITIALIZE: null,
CREATE_AUTHOR: null,
UPDATE_AUTHOR: null,
DELETE_AUTHOR: null
});
|
module.exports = function(grunt) {
'use strict';
grunt.loadNpmTasks('grunt-contrib-jshint');
grunt.loadNpmTasks('grunt-contrib-jasmine');
grunt.loadNpmTasks('grunt-contrib-less');
grunt.loadNpmTasks('grunt-contrib-uglify');
grunt.loadNpmTasks('grunt-contrib-watch');
grunt.loadNpmTasks('grunt-gh-pages');
grunt.initConfig({
pkg: grunt.file.readJSON('package.json'),
meta: {
project: 'bootstrap-timepicker',
version: '0.2.3'
},
'gh-pages': {
options: {
add: true,
push: false
},
src: [
'css/bootstrap-timepicker.min.css',
'js/bootstrap-timepicker.min.js'
]
},
jasmine: {
build: {
src : ['spec/js/libs/jquery/jquery.min.js', 'spec/js/libs/bootstrap/js/bootstrap.min.js', 'spec/js/libs/autotype/index.js', 'js/bootstrap-timepicker.js'],
options: {
specs : 'spec/js/*Spec.js',
helpers : 'spec/js/helpers/*.js',
timeout : 100
}
}
},
jshint: {
options: {
browser: true,
camelcase: true,
curly: true,
eqeqeq: true,
eqnull: true,
immed: true,
indent: 2,
latedef: true,
newcap: true,
noarg: true,
quotmark: true,
sub: true,
strict: true,
trailing: true,
undef: true,
unused: true,
white: false,
globals: {
jQuery: true,
$: true,
expect: true,
it: true,
beforeEach: true,
afterEach: true,
describe: true,
loadFixtures: true,
console: true,
module: true
}
},
files: ['js/bootstrap-timepicker.js', 'Gruntfile.js', 'package.json', 'spec/js/*Spec.js']
},
less: {
dev: {
options: {
paths: ['css']
},
files: {
'css/bootstrap-timepicker.css': ['less/*.less']
}
},
prod: {
options: {
paths: ['css'],
yuicompress: true
},
files: {
'css/bootstrap-timepicker.min.css': ['less/*.less']
}
}
},
uglify: {
options: {
banner: '/*! <%= meta.project %> v<%= meta.version %> \n' +
'* http://jdewit.github.com/bootstrap-timepicker \n' +
'* Copyright (c) <%= grunt.template.today("yyyy") %> Joris de Wit \n' +
'* MIT License \n' +
'*/'
},
build: {
src: ['<banner:meta.banner>','js/<%= pkg.name %>.js'],
dest: 'js/<%= pkg.name %>.min.js'
}
},
watch: {
js: {
files: ['js/bootstrap-timepicker.js', 'spec/js/*Spec.js'],
tasks: ['jshint', 'jasmine'],
options: {
livereload: true
}
},
less: {
files: ['less/timepicker.less'],
tasks: ['less:dev'],
options: {
livereload: true
}
}
}
});
grunt.registerTask('default', ['jshint', 'jasmine', 'less:dev']);
grunt.registerTask('test', ['jasmine', 'jshint']);
grunt.registerTask('compile', ['jshint', 'jasmine', 'uglify', 'less:prod']);
};
|
var Encore = require('@symfony/webpack-encore');
// Manually configure the runtime environment if not already configured yet by the "encore" command.
// It's useful when you use tools that rely on webpack.config.js file.
if (!Encore.isRuntimeEnvironmentConfigured()) {
Encore.configureRuntimeEnvironment(process.env.NODE_ENV || 'dev');
}
Encore
// directory where compiled assets will be stored
.setOutputPath('public/build/')
// public path used by the web server to access the output path
.setPublicPath('/build')
// only needed for CDN's or sub-directory deploy
//.setManifestKeyPrefix('build/')
/*
* ENTRY CONFIG
*
* Add 1 entry for each "page" of your app
* (including one that's included on every page - e.g. "app")
*
* Each entry will result in one JavaScript file (e.g. app.js)
* and one CSS file (e.g. app.css) if your JavaScript imports CSS.
*/
.addEntry('app', './assets/js/app.js')
//.addEntry('page1', './assets/js/page1.js')
//.addEntry('page2', './assets/js/page2.js')
// When enabled, Webpack "splits" your files into smaller pieces for greater optimization.
.splitEntryChunks()
// will require an extra script tag for runtime.js
// but, you probably want this, unless you're building a single-page app
.enableSingleRuntimeChunk()
/*
* FEATURE CONFIG
*
* Enable & configure other features below. For a full
* list of features, see:
* https://symfony.com/doc/current/frontend.html#adding-more-features
*/
.cleanupOutputBeforeBuild()
.enableBuildNotifications()
.enableSourceMaps(!Encore.isProduction())
// enables hashed filenames (e.g. app.abc123.css)
.enableVersioning(Encore.isProduction())
// enables @babel/preset-env polyfills
.configureBabelPresetEnv((config) => {
config.useBuiltIns = 'usage';
config.corejs = 3;
})
// enables Sass/SCSS support
//.enableSassLoader()
// uncomment if you use TypeScript
//.enableTypeScriptLoader()
// uncomment to get integrity="..." attributes on your script & link tags
// requires WebpackEncoreBundle 1.4 or higher
//.enableIntegrityHashes(Encore.isProduction())
// uncomment if you're having problems with a jQuery plugin
//.autoProvidejQuery()
// uncomment if you use API Platform Admin (composer req api-admin)
//.enableReactPreset()
//.addEntry('admin', './assets/js/admin.js')
;
module.exports = Encore.getWebpackConfig();
|
const Assigner = require('assign.js')
let assigner = new Assigner()
const fp = require('fastify-plugin')
const WebSocket = require('ws')
const url = require('url')
module.exports = {
addWSServer: function (paths, wsOptions = {}) {
return fp((fastify, opts, next) => {
const lib = opts.library || 'ws'
if (lib !== 'ws' && lib !== 'uws') return next(new Error('Invalid "library" option'))
let wssServers = []
for (let path in paths)
wssServers[path] = new WebSocket.Server( assigner.assign( {}, wsOptions, {
noServer: true
}) )
fastify.server.on('upgrade', (request, socket, head) => {
const pathname = url.parse(request.url).pathname
if ( wssServers[pathname] ) {
wssServers[pathname].handleUpgrade(request, socket, head, (ws) => {
wssServers[pathname].emit('connection', ws)
})
} else {
socket.destroy()
}
})
fastify.decorate('ws', {
broadcast: async function broadcast (data, identifySockets, target) {
for (let path in wssServers)
await wssServers[ path ].broadcast( data, identifySockets, target )
}
})
for (let path in wssServers) {
let wss = wssServers[ path ]
wss.broadcast = async function broadcast (data, identifySockets, target) {
let sockets = await identifySockets( wss.clients, target )
sockets.forEach(function each (client) {
if (client.readyState === WebSocket.OPEN) {
client.send(data)
}
})
}
wss.on('connection', (socket) => {
console.log('Client connected.')
socket.on('message', (msg) => {
paths[path](socket, msg).catch(console.error)
})
socket.on('close', () => {})
})
fastify.addHook('onClose', (fastify, done) => {
return wss.close(done)
})
}
next()
}, {
fastify: '>=2.x',
name: 'fastify-ws'
})
}
}
|
var _ = require('underscore');
var keystone = require('../../');
var utils = keystone.utils;
/**
* Content Class
*
* Accessed via `Keystone.content`
*
* @api public
*/
var Content = function () {};
/**
* Loads page content by page key (optional).
*
* If page key is not provided, returns a hash of all page contents in the database.
*
* ####Example:
*
* keystone.content.fetch('home', function(err, content) { ... });
*
* @param {String} key (optional)
* @param {Function} callback
* @api public
*/
Content.prototype.fetch = function (page, callback) {
if (utils.isFunction(page)) {
callback = page;
page = null;
}
var content = this;
if (!this.AppContent) {
return callback({ error: 'invalid page', message: 'No pages have been registered.' });
}
if (page) {
if (!this.pages[page]) {
return callback({ error: 'invalid page', message: 'The page ' + page + ' does not exist.' });
}
this.AppContent.findOne({ key: page }, function (err, result) {
if (err) return callback(err);
return callback(null, content.pages[page].populate(result ? result.content.data : {}));
});
} else {
this.AppContent.find(function (err, results) {
if (err) return callback(err);
var data = {};
results.forEach(function (i) {
if (content.pages[i.key]) {
data[i.key] = content.pages[i.key].populate(i.content.data);
}
});
_.each(content.pages, function (i) {
if (!data[i.key]) {
data[i.key] = i.populate();
}
});
return data;
});
}
};
/**
* Sets page content by page key.
*
* Merges content with existing content.
*
* ####Example:
*
* keystone.content.store('home', { title: 'Welcome' }, function(err) { ... });
*
* @param {String} key
* @param {Object} content
* @param {Function} callback
* @api public
*/
Content.prototype.store = function (page, content, callback) {
if (!this.pages[page]) {
return callback({ error: 'invalid page', message: 'The page ' + page + ' does not exist.' });
}
content = this.pages[page].validate(content);
// TODO: Handle validation errors
this.AppContent.findOne({ key: page }, function (err, doc) {
if (err) return callback(err);
if (doc) {
if (doc.content) {
doc.history.push(doc.content);
}
_.defaults(content, doc.content);
} else {
doc = new content.AppContent({ key: page });
}
doc.content = { data: this.pages[page].clean(content) };
doc.lastChangeDate = Date.now();
doc.save(callback);
});
};
/**
* Registers a page. Should not be called directly, use Page.register() instead.
*
* @param {Page} page
* @api private
*/
Content.prototype.page = function (key, page) {
if (!this.pages) {
this.pages = {};
}
if (arguments.length === 1) {
if (!this.pages[key]) {
throw new Error('keystone.content.page() Error: page ' + key + ' cannot be registered more than once.');
}
return this.pages[key];
}
this.initModel();
if (this.pages[key]) {
throw new Error('keystone.content.page() Error: page ' + key + ' cannot be registered more than once.');
}
this.pages[key] = page;
return page;
};
/**
* Ensures the Mongoose model for storing content is initialised.
*
* Called automatically when pages are added.
*
* @api private
*/
Content.prototype.initModel = function () {
if (this.AppContent) return;
var contentSchemaDef = {
createdAt: { type: Date, default: Date.now },
data: { type: keystone.mongoose.Schema.Types.Mixed },
};
var ContentSchema = new keystone.mongoose.Schema(contentSchemaDef);
var PageSchema = new keystone.mongoose.Schema({
page: { type: String, index: true },
lastChangeDate: { type: Date, index: true },
content: contentSchemaDef,
history: [ContentSchema],
}, { collection: 'app_content' });
this.AppContent = keystone.mongoose.model('App_Content', PageSchema);
};
/**
* Outputs client-side editable data for content management
*
* Called automatically when pages are added.
*
* @api private
*/
Content.prototype.editable = function (user, options) {
if (!user || !user.canAccessKeystone) {
return undefined;
}
if (options.list) {
var list = keystone.list(options.list);
if (!list) {
return JSON.stringify({ type: 'error', err: 'list not found' });
}
var data = {
type: 'list',
path: list.path,
singular: list.singular,
plural: list.plural,
};
if (options.id) {
data.id = options.id;
}
return JSON.stringify(data);
}
};
/**
* The exports object is an instance of Content.
*
* @api public
*/
module.exports = new Content();
// Expose Classes
exports.Page = require('./page');
exports.Types = require('./types');
|
var winston = require('winston');
var fs = require('fs');
var presets = {};
function presetsAction(player, values, callback) {
var value = decodeURIComponent(values[0]);
if (value.startsWith('{'))
var preset = JSON.parse(value);
else
var preset = presets[value];
if (preset) {
winston.info("Preset found: ", preset);
player.discovery.applyPreset(preset, function (err, result) {
if (err) {
winston.error("Error loading preset: ", err);
} else {
winston.info("Playing ", preset);
}
});
} else {
winston.error("No preset found...");
var simplePresets = [];
for (var key in presets) {
if (presets.hasOwnProperty(key)) {
simplePresets.push(key);
}
}
callback(simplePresets);
}
}
function initPresets(api) {
var presetsFilename = __dirname + '/../../presets.json';
fs.exists(presetsFilename, function (exists) {
if (exists) {
presets = require(presetsFilename);
winston.info('loaded presets', presets);
} else {
winston.info('no preset file, ignoring...');
}
api.registerAction('preset', presetsAction);
});
}
module.exports = function (api) {
initPresets(api);
}
|
export const UPDATE_TREE_FILTER = 'SIMPR_UPDATE_TREE_FILTER';
export const fireUpdateTreeFilter = (filter) => ({
type: UPDATE_TREE_FILTER,
payload: {
filter
},
});
|
module.exports = {
livereload: {
options: {
livereload: '<%= express.options.livereload %>'
},
files: [
'<%= yeoman.currentDir %>',
'<%= yeoman.demo %>/**/*.html',
'<%= yeoman.demo %>/**/*.js',
'<%= yeoman.styles %>/{,*/}*.css',
'<%= yeoman.src %>/**/*.html',
'<%= yeoman.src %>/{,*/}*.js',
'<%= yeoman.src %>/{,*/}*.css',
'<%= yeoman.src %>/images/{,*/}*.{png,jpg,jpeg,gif,webp,svg}'
]
},
test: {
options: {
livereload: {
port: 35728
}
},
files: [
'<%= yeoman.src %>/{,*/}*.html',
'{<%= yeoman.build %>,<%= yeoman.src %>}/app/{,*/}*.js'
],
tasks: ['test']
}
};
|
import { createStore } from 'redux'
import { combineReducers } from 'redux';
import { todoReducer } from '../todo-reducer';
import { appReducer } from '../app-reducer';
const todoApp = combineReducers({
todos: todoReducer,
app: appReducer
})
export const store = createStore(todoApp);
store.getState()
// outputs ->
// {
// todos: {
// todos: []
// },
// app: {
// settingsVisible: false,
// ...
// }
// }
|
version https://git-lfs.github.com/spec/v1
oid sha256:dd32b7eaa7daed7371af2e06195ec013df98eb5920727aaf459d9419ef607ff9
size 21785
|
version https://git-lfs.github.com/spec/v1
oid sha256:2624aaed17536733cabbaeeac1e3b7c75455924c253869c12a812940c3e1241f
size 1195
|
if (Meteor.isClient) {
// counter starts at 0
Template.main.helpers({
});
Template.main.events({
});
}
if (Meteor.isServer) {
Meteor.startup(function () {
// code to run on server at startup
});
}
|
/* global fetch */
import React from 'react';
import { render } from 'react-dom';
import { Link } from 'react-router';
function Home() {
return (
<div className="container">
<h2>Who are you?</h2>
<Link to="/caseHandler">A Case Handler</Link>
{' or '}
<Link to="/adjudicator">An Adjudicator</Link>
</div>
);
}
export default Home;
|
var __extends = (this && this.__extends) || (function () {
var extendStatics = Object.setPrototypeOf ||
({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
return function (d, b) {
extendStatics(d, b);
function __() { this.constructor = d; }
d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
};
})();
var UseOfAllTypeScriptObjectsBinder = (function (_super) {
__extends(UseOfAllTypeScriptObjectsBinder, _super);
function UseOfAllTypeScriptObjectsBinder() {
return _super.call(this, ['ID'], null, true, MaceTestObject) || this;
}
return UseOfAllTypeScriptObjectsBinder;
}(Binder));
//# sourceMappingURL=UseOfAllTypeScriptObjectsBinder.js.map
|
import AppDispatcher from '../dispatcher/AppDispatcher';
import AppConstants from '../constants/AppConstants';
const ActionTypes = AppConstants.ActionTypes;
export function showMenu() {
AppDispatcher.dispatchViewAction(ActionTypes.SHOW_MENU);
}
export function hideMenu() {
AppDispatcher.dispatchViewAction(ActionTypes.HIDE_MENU);
}
export function showModal() {
AppDispatcher.dispatchViewAction(ActionTypes.SHOW_MODAL);
}
export function toggleHeaderNotificationMenu() {
AppDispatcher.dispatchViewAction(ActionTypes.TOGGLE_HEADER_NOTIFICATION_MENU);
}
export function toggleHeaderMessageMenu() {
AppDispatcher.dispatchViewAction(ActionTypes.TOGGLE_HEADER_MESSAGE_MENU);
}
|
/**
* Created by suman on 09/05/16.
*/
var core = require('chanakya'),
http = require('http'),
Q = require('q');
core.validator('isPhoneno', function (message) {
var deferred = Q.defer();
http.get('http://apilayer.net/api/validate?access_key=eba101687da317945a45f798464256da&number=' + message + '&country_code=&format=1', function (res) {
res.setEncoding('utf8');
res.on('data', function (d) {
d = JSON.parse(d);
deferred.resolve(d.valid);
});
}).on('error', function (e) {
deferred.reject(new Error(e));
});
return deferred.promise;
});
core.validator('isOTP', function (message) {
return Q.fcall(function () {
return message == 1234;
});
});
core.validator('isStatement', function (message) {
// var deferred = Q.defer();
//
// http.get('http://demo1036853.mockable.io/wit', function (res) {
// res.setEncoding('utf8');
// res.on('data', function (d) {
// d = JSON.parse(d);
// deferred.resolve(d.intent);
// });
// }).on('error', function (e) {
// deferred.reject(new Error(e));
// });
// return deferred.promise;
return Q.fcall(function () {
return (message == 'hi' || message == 'Hi');
});
});
core.validator('isOffer', function (message) {
return Q.fcall(function () {
return (message == 'offer' || message == 'Offer');
});
});
|
import * as ActionTypes from '../constants/constants';
const initialState = {
isAuthenticated: false,
isFetching: false,
loaded: false,
message: ''
};
const authReducer = (state = initialState, action) => {
switch (action.type) {
case ActionTypes.REQUEST_CHECK_TOKEN:
return {
...state,
isAuthenticated: action.isAuthenticated,
isFetching: action.isFetching,
loaded: false,
};
case ActionTypes.TOKEN_VALID:
return {
...state,
isAuthenticated: action.isAuthenticated,
isFetching: action.isFetching,
loaded: true,
};
case ActionTypes.TOKEN_INVALID:
return {
...state,
isAuthenticated: action.isAuthenticated,
isFetching: action.isFetching,
loaded: true,
};
case ActionTypes.REQUEST_LOGIN:
return {
...state,
isAuthenticated: action.isAuthenticated,
isFetching: action.isFetching,
user: action.creds,
message: '',
};
case ActionTypes.LOGIN_SUCCESS:
return {
...state,
isAuthenticated: true,
isFetching: false,
message: '',
};
case ActionTypes.LOGIN_FAILURE:
return {
...state,
isAuthenticated: false,
isFetching: false,
message: action.message,
};
default:
return state;
}
};
export default authReducer;
|
function isString(value) {
if (typeof value !== 'string' || value === '' || value === null) {
return false;
}
return true;
}
function isNumber(value) {
if (typeof Number.parseInt(value, 10) !== 'number'
|| Number.isNaN(value) || value === null) {
return false;
}
return true;
}
function isInRange(value, start, end) {
if (value < start || value > end) {
return false;
}
return true;
}
function isEmail(value) {
const atIndex = value.indexOf('@');
if (atIndex < 1) {
return false;
}
if (value.substring(atIndex, value.length).indexOf('.') < 1) {
return false;
}
return true;
}
module.exports = {
isNumber,
isString,
isInRange,
isEmail,
};
|
'use strict';
/*!
* Snakeskin
* https://github.com/SnakeskinTpl/Snakeskin
*
* Released under the MIT license
* https://github.com/SnakeskinTpl/Snakeskin/blob/master/LICENSE
*/
import Snakeskin from '../core';
Snakeskin.addDirective(
'op',
{
block: true,
group: 'op',
logic: true
}
);
|
import mongoose from 'mongoose';
const friendSchema = mongoose.Schema({
"id": Number,
"gender": String,
"firstName": String,
"lastName": String,
"email": String,
"ipAddress": String,
"job": String,
"company": String,
"birthDate": Date,
"latitude": String,
"longitude": String,
});
const Friend = mongoose.model('Friend', friendSchema);
export default Friend;
|
import { isSticky } from '~/lib/utils/sticky';
describe('sticky', () => {
const el = {
offsetTop: 0,
classList: {},
};
beforeEach(() => {
el.offsetTop = 0;
el.classList.add = jasmine.createSpy('spy');
el.classList.remove = jasmine.createSpy('spy');
});
describe('classList.remove', () => {
it('does not call classList.remove when stuck', () => {
isSticky(el, 0, 0);
expect(
el.classList.remove,
).not.toHaveBeenCalled();
});
it('calls classList.remove when not stuck', () => {
el.offsetTop = 10;
isSticky(el, 0, 0);
expect(
el.classList.remove,
).toHaveBeenCalledWith('is-stuck');
});
});
describe('classList.add', () => {
it('calls classList.add when stuck', () => {
isSticky(el, 0, 0);
expect(
el.classList.add,
).toHaveBeenCalledWith('is-stuck');
});
it('does not call classList.add when not stuck', () => {
el.offsetTop = 10;
isSticky(el, 0, 0);
expect(
el.classList.add,
).not.toHaveBeenCalled();
});
});
});
|
import React from 'react';
import { assert } from 'chai';
import { createShallow, getClasses } from '../test-utils';
import CardContent from './CardContent';
describe('<CardContent />', () => {
let shallow;
let classes;
before(() => {
shallow = createShallow({ untilSelector: 'CardContent' });
classes = getClasses(<CardContent />);
});
it('should render a div with the root class', () => {
const wrapper = shallow(<CardContent />);
assert.strictEqual(wrapper.name(), 'div');
assert.strictEqual(wrapper.hasClass(classes.root), true);
});
});
|
require('dotenv').config({silent:true});
var feathers = require('feathers');
var bodyParser = require('body-parser');
var rest = require('feathers-rest');
var socketio = require('feathers-socketio');
var fms = require('../lib');
var AutoService = fms.AutoService;
const hooks = require('feathers-hooks');
const errorHandler = require('feathers-errors/handler');
const connection = {
host : process.env.FILEMAKER_SERVER_ADDRESS,
db : 'Test',
user: process.env.FILEMAKER_USER,
pass: process.env.FILEMAKER_PASS
};
const model = {
layout : 'Todos',
idField : 'id'
};
// Create a feathers instance.
const app = feathers()
.configure(hooks())
// Enable REST services
.configure(rest())
// Enable REST services
.configure(socketio())
// Turn on JSON parser for REST services
.use(bodyParser.json())
// Turn on URL-encoded parser for REST services
.use(bodyParser.urlencoded({ extended: true }))
.configure( AutoService({
connection,
prefix : 'auto'
}))
.use(errorHandler());
// Create a service with a default page size of 2 items
// and a maximum size of 4
app.use('/todos', fms({
connection, model,
paginate: {
default: 2,
max: 4
}
}));
// Start the server
module.exports = app.listen(3030);
console.log('Feathers Todo Filemaker service running on 127.0.0.1:3030');
|
// Math.extend v0.5.0
// Copyright (c) 2008-2009 Laurent Fortin
//
// Permission is hereby granted, free of charge, to any person obtaining
// a copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to
// permit persons to whom the Software is furnished to do so, subject to
// the following conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
Object.extend(Math, {
sum: function(list) {
var sum = 0;
for(var i = 0, len = list.length; i < len; i++)
sum += list[i];
return sum;
},
mean: function(list) {
return list.length ? this.sum(list) / list.length : false;
},
median: function(list) {
if(!list.length) return false;
list = this.sort(list);
if(list.length.isEven()) {
return this.mean([list[list.length / 2 - 1], list[list.length / 2]]);
} else {
return list[(list.length / 2).floor()];
}
},
variance: function(list) {
if(!list.length) return false;
var mean = this.mean(list);
var dev = [];
for(var i = 0, len = list.length; i < len; i++)
dev.push(this.pow(list[i] - mean, 2));
return this.mean(dev);
},
stdDev: function(list) {
return this.sqrt(this.variance(list));
},
sort: function(list, desc) {
// we output a clone of the original array
return list.clone().sort(function(a, b) { return desc ? b - a : a - b });
},
baseLog: function(n, base) {
return this.log(n) / this.log(base || 10);
},
factorize: function(n) {
if(!n.isNatural(true) || n == 1) return false;
if(n.isPrime()) return [n];
var sqrtOfN = this.sqrt(n);
for(var i = 2; i <= sqrtOfN; i++)
if((n % i).isNull() && i.isPrime())
return [i, this.factorize(n / i)].flatten();
},
sinh: function(n) {
return (this.exp(n) - this.exp(-n)) / 2;
},
cosh: function(n) {
return (this.exp(n) + this.exp(-n)) / 2;
},
tanh: function(n) {
return this.sinh(n) / this.cosh(n);
}
});
Object.extend(Number.prototype, {
isNaN: function() {
return isNaN(this);
},
isNull: function() {
return this == 0;
},
isEven: function() {
if(!this.isInteger()) return false;
return(this % 2 ? false : true);
},
isOdd: function() {
if(!this.isInteger()) return false;
return(this % 2 ? true : false);
},
isInteger: function(excludeZero) {
// if this == NaN ...
if(this.isNaN()) return false;
if(excludeZero && this.isNull()) return false;
return (this - this.floor()) ? false : true;
},
isNatural: function(excludeZero) {
return(this.isInteger(excludeZero) && this >= 0);
},
isPrime: function() {
var sqrtOfThis = Math.sqrt(this);
var somePrimes = [2,3,5,7,11,13,17,19,23,29,31,37,41,43,47,53,59,61,67,71,73,79,83,89,97,101];
if(!this.isNatural(true) || sqrtOfThis.isInteger()) {
return false;
}
if(somePrimes.include(this)) return true;
for(var i = 0, len = somePrimes.length; i < len; i++) {
if(somePrimes[i] > sqrtOfThis) {
return true;
}
if((this % somePrimes[i]).isNull()) {
return false;
}
}
for(var i = 103; i <= sqrtOfThis; i += 2) {
if((this % i).isNull()) {
return false;
}
}
return true;
},
compute: function(fn) {
return fn(this);
}
});
Object.extend(Array.prototype, {
swap: function(index1, index2) {
var swap = this[index1];
this[index1] = this[index2];
this[index2] = swap;
return this;
},
shuffle: function(inline, times) {
var list = (inline != false ? this : this.clone());
for(var i = 0, len = list.length * (times || 4); i < len; i++) {
list.swap(
(Math.random() * list.length).floor(),
(Math.random() * list.length).floor()
);
}
return list;
},
randomDraw: function(items) {
items = Number(items) || 1;
var list = this.shuffle(false);
if (items >= list.length) {
return list;
}
var sample = [];
for(var i = 1; i <= items; i++) {
if(list.length > 0) {
sample.push(list.shift());
} else {
return sample;
}
}
return sample;
}
});
Object.extend(Object, {
numericValues: function(object) {
return Object.values(object).select(Object.isNumber);
}
});
|
(function() {
'use strict';
/**
* Get the main module (shared for Workout).
*/
angular.module(appName)
/**
* Login Controller.
*/
.controller('ConfirmBookingController', ConfirmBooking);
ConfirmBooking.$inject = ['$state', '$filter', '$http', 'config', '$location','CommonService','BookingDataService'];
function ConfirmBooking($state, $filter, $http, config, $location, CommonService, BookingDataService) {
var BookingVm = this;
BookingVm.finalBalance = 0;
BookingVm.currentUserDetails = {};
BookingVm.successMessagePopup = false;
BookingVm.initialBalance = 0;
BookingVm.paymentDetails = {};
// Variable declarations
// Function declarations
BookingVm.decreaseOpacity = decreaseOpacity;
BookingVm.increaseOpacity = increaseOpacity;
BookingVm.bookingPayment = bookingPayment;
BookingVm.goToLive = goToLive;
activate();
function activate() {
BookingVm.bookingAmount = (CommonService.getBookingDetails().bookingCount * 157);
BookingVm.currentUserDetails = CommonService.getUserDetails();
BookingVm.initialBalance = CommonService.getUserDetails().scutops_money;
BookingVm.paymentDetails.order_id = CommonService.getBookingDetails().order_id;
BookingVm.paymentDetails.cust_id = CommonService.getUserDetails().id;
// To initialize anything before the project starts
}
function decreaseOpacity(){
document.getElementsByClassName("main-content2")[0].style.opacity="0.5";
}
function increaseOpacity(){
document.getElementsByClassName("main-content2")[0].style.opacity="1";
}
function bookingPayment(){
var balance = BookingVm.initialBalance - BookingVm.bookingAmount;
if(balance >= 0){
BookingVm.currentUserDetails.scutops_money = balance; //updating the user details
BookingVm.paymentDetails.newBalance = balance;
var paymentDetails = JSON.stringify(BookingVm.paymentDetails);// preparing for passing to the php file
//console.log(paymentDetails);
BookingDataService.makePayment(paymentDetails).then(function(response){
CommonService.setUserDetails(BookingVm.currentUserDetails);//updating user details in common service
BookingVm.finalBalance = balance;
decreaseOpacity();
BookingVm.successMessagePopup = true;
});
}
else
alert("Insufficient balance");
}
function goToLive(){
$state.go("liveUpdate");
}
}
})();
|
"use strict";
var dns = require('dns'),
os = require('os');
// Because localtunnel doesn't work reliably enough,
// hack the config to point at the local ip.
module.exports = function(ctx, done){
if(ctx.environment !== 'development'){
// Only run this hack in dev for real.
return done();
}
dns.lookup(os.hostname(), function (err, add, fam){
ctx.url = 'http://' + add + ':8080';
done();
});
};
|
var Message = require('../models/message');
exports.create = function(req, res) {
new Message({
senderID: req.body.senderID,
senderAlias: req.body.senderAlias,
acceptorID: req.body.acceptorID,
acceptorAlias: req.body.acceptorAlias,
subject: req.body.subject,
content: req.body.content
}).save(function(err, message) {
if (err) {
return res.send(400, err);
}
res.send(message);
});
};
exports.list = function(req, res) {
Message.find({}, function(err, messages) {
if (err) {
res.send(500, err);
}
res.send(messages || []);
});
};
exports.remove = function(req, res) {
var delFlag = false;
var saveFlag = false;
Message.findOne({_id: req.params.id}, function(err, doc){
if(doc.senderID == req.user._id){
if(doc.delFromAcceptor == 'true'){
delFlag=true;
}else{
doc.delFromSender = true;
saveFlag = true;
}
}
if(doc.acceptorID == req.user._id){
if(doc.delFromSender == 'true'){
delFlag = true;
}else{
doc.delFromAcceptor = true;
saveFlag = true;
}
}
if(saveFlag){
doc.save(function(err, doc){
err ? res.send(500, err) : res.send('');
})
}
if(delFlag){
doc.remove(function(err, doc) {
err ? res.send(500, err) : res.send('');
});
}
});
};
|
import { createAction, createThunkAction } from 'redux/actions';
import { getShortenUrl } from 'services/bitly';
import { saveAreaOfInterest } from 'components/forms/area-of-interest/actions';
export const setShareData = createAction('setShareData');
export const setShareUrl = createAction('setShareUrl');
export const setShareSelected = createAction('setShareSelected');
export const setShareOpen = createAction('setShareOpen');
export const setShareCopied = createAction('setShareCopied');
export const setShareLoading = createAction('setShareLoading');
export const setShareModal = createThunkAction(
'setShareModal',
(params) => (dispatch) => {
const { shareUrl } = params;
dispatch(
setShareData({
...params,
})
);
getShortenUrl(shareUrl)
.then((response) => {
let shortShareUrl = '';
if (response.status < 400) {
shortShareUrl = response.data.link;
dispatch(setShareUrl(shortShareUrl));
} else {
dispatch(setShareLoading(false));
}
})
.catch(() => {
dispatch(setShareLoading(false));
});
}
);
export const setShareAoi = createThunkAction('shareModalSaveAoi', (params) => (dispatch) => {
dispatch(saveAreaOfInterest({ ...params }))
});
|
import React from 'react'
const DefaultLayout = ({ children }) => {
return (
<div className="layout" style={{ width: '100%', height: '100%' }}>
{children}
</div>
)
}
export default DefaultLayout
|
module.exports = exports = require('./lib/rhetorical');
|
'use strict';
import { Schema } from 'mongoose';
import shortid from 'shortid';
const EntrySchema = new Schema({
_id: { type: String, unique: true, default: shortid.generate },
stepRef: { type: String, ref: 'Step' },
name: String,
value: String,
dateCreated: { type: Date, default: Date.now },
dateUpdated: { type: Date }
});
const Entry = mongoose.model('Entry', EntrySchema);
export default Entry;
|
import { strToEl } from '../utils';
export default class Ripple {
constructor() {
this.container = strToEl('<div class="ripple"></div>');
}
animate() {
this.container.classList.remove('animate');
this.container.offsetLeft;
this.container.classList.add('animate');
}
}
|
import React from 'react';
import PropTypes from 'prop-types';
import Button from 'components/Button';
Main.propTypes = {
showLoginForm: PropTypes.func.isRequired,
showSignUpForm: PropTypes.func.isRequired
};
export default function Main({ showLoginForm, showSignUpForm }) {
return (
<main>
<Button
color="logoBlue"
style={{ display: 'block', fontSize: '2.5rem', padding: '1rem' }}
onClick={showLoginForm}
>
Yes, I have an account
</Button>
<Button
color="pink"
style={{ marginTop: '1.5rem', fontSize: '2rem', padding: '1rem' }}
onClick={showSignUpForm}
>
{"No, I'm a new user. Make me a new account, please!"}
</Button>
</main>
);
}
|
import Reflux from 'Reflux';
import cartActions from '../actions/cartActions.js';
import _ from 'lodash';
// Items to fill onFillCart action
let items = [
{
title: 'Iphone 12',
price: '129',
id: 1
},
{
title: 'Galaxy S14',
price: '119',
id: 2
},
{
title: 'Siemens A52',
price: '197',
id: 3
},
{
title: 'Nokia 3310',
price: '329',
id: 4
}
];
// Storage keys to use when stroing
let localStorageKeys = ['cart', 'toggles'];
// Constructor for toggles object on init
let Toggles = () => {
let obj = {
title: false,
price: false,
quantity: false
}
return obj;
};
let cartStore = Reflux.createStore ({
// Assign actions
listenables: [cartActions],
// Initial state
getInitialState() {
// Load from local Storage or empty array
this.data = JSON.parse(localStorage.getItem(localStorageKeys[0])) || new Array;
// Load from local Storage or new Toggles object
this.toggles = JSON.parse(localStorage.getItem(localStorageKeys[1])) || new Toggles;
// return to component state
return {items: this.data};
},
// onAdd action
onAdd(item) {
// Update cart with item
this.updateCart(this.addItem(item));
},
//onDelete action
onDelete(item) {
// delete item from cart
this.updateCart(this.deleteItem(item));
},
onFillCart() {
// Add each item to cart then pass to anAdd so it updates cart
_.map(items, (item) => {this.onAdd(item)})
},
onSortTitle() {
// Set other toggles states
this.toggles.price = false;
this.toggles.quantity = false;
// Toggle this state
this.toggles.title = !this.toggles.title;
// Assign
let toggle = this.toggles.title;
// Update cart through sortBy()
this.updateCart(this.sortBy(toggle, 'title'));
},
onSortPrice() {
// Set other toggles states
this.toggles.title = false;
this.toggles.quantity = false;
// Toggle this state
this.toggles.price = !this.toggles.price;
// Assign
let toggle = this.toggles.price;
// Update cart through sortBy()
this.updateCart(this.sortBy(toggle, 'price'));
},
onSortQuantity() {
// Set other toggles states
this.toggles.title = false;
this.toggles.price = false;
// Toggle this state
this.toggles.quantity = !this.toggles.quantity;
// Assign
let toggle = this.toggles.quantity;
// Update cart through sortBy()
this.updateCart(this.sortBy(toggle, 'quantity'));
// ABOVE NEEDS INCAPSULATION
},
onSubmit() {
// Dummy ajax post to emulate success
$.ajax({
url: 'http://jsonplaceholder.typicode.com/posts',
dataType: 'json',
type: 'POST',
data: {data: this.data},
success: function(data) {
UIkit.notify({
message : 'Success!',
status : 'success',
timeout : 5000,
pos : 'top-center'
});
this.clearCart();
}.bind(this),
error: function(xhr, status, err) {
UIkit.notify({
message : 'Error! </br>' + err.toString(),
status : 'danger',
timeout : 5000,
pos : 'top-center'
});
console.error(xhr, status, err.toString());
}
});
},
sortBy(toggle, key) {
let items;
// if not sorted
if (toggle) {
items = _.orderBy(this.data, key, 'asc');
}
// if sorted -> reverse
if (!toggle) {
items = _.orderBy(this.data, key, 'desc');
}
// store state of toggles
localStorage.setItem(localStorageKeys[1], JSON.stringify(this.toggles));
return items;
},
updateCart(items) {
// save items to local storage
localStorage.setItem(localStorageKeys[0], JSON.stringify(items));
// assign to this object
this.data = items;
// trigger component state change
this.trigger({items});
},
addItem (item) {
let found, i;
found = false;
i = 0;
let items = this.data.concat();
// loop through items
while (i < items.length) {
// if find item with the same id
if (item.id === items[i].id) {
// increment quantity
items[i].quantity++;
found = true;
break;
}
i++;
}
// if not found
if (!found) {
// add new item with quantity 1
Object.assign(item, {quantity: 1});
items.push(item);
}
return items;
},
deleteItem (item) {
let items = this.data.concat();
let i = items.length;
// loop through items in reverse
while (i--) {
// if found item with the same id and quantity more than 1 -> decrement
if (item.id === items[i].id && items[i].quantity > 1) {
items[i].quantity--;
break;
};
// if found item with the same id and quantity equals 1 -> remove;
if (item.id === items[i].id && items[i].quantity === 1) {
items.splice(i, 1);
break;
};
}
return items;
},
// clearing cart on successfull submit
clearCart() {
// clear local Storage
_.map(localStorageKeys, (key) => {
localStorage.removeItem(key);
})
let empty = new Array;
// update cart with empty Array
this.updateCart(empty);
}
});
export default cartStore;
|
/*! Select2 4.0.0 | https://github.com/select2/select2/blob/master/LICENSE.md */
(function () {
if (jQuery && jQuery.fn && jQuery.fn.select2 && jQuery.fn.select2.amd)var e = jQuery.fn.select2.amd;
return e.define("select2/i18n/nb", [], function () {
return {
inputTooLong: function (e) {
var t = e.input.length - e.maximum;
return "Vennligst fjern " + t + " tegn"
}, inputTooShort: function (e) {
var t = e.minimum - e.input.length, n = "Vennligst skriv inn ";
return t > 1 ? n += " flere tegn" : n += " tegn til", n
}, loadingMore: function () {
return "Laster flere resultater…"
}, maximumSelected: function (e) {
return "Du kan velge maks " + e.maximum + " elementer"
}, noResults: function () {
return "Ingen treff"
}, searching: function () {
return "Søker…"
}
}
}), {define: e.define, require: e.require}
})();
|
var detector = (function () {
function foodCollision(snake, food, ui) {
var snakeHeadX = snake.parts[0].getPosition().x;
var snakeHeadY = snake.parts[0].getPosition().y;
var foodX = food.getPosition().x;
var foodY = food.getPosition().y;
if(snakeHeadX === foodX && snakeHeadY === foodY){
return true;
}
}
function playFieldCollision(selector, snake, ui) {
if(selector instanceof HTMLCanvasElement){
this.canvas = selector;
} else if(typeof selector === 'String' || typeof selector === 'string'){
this.canvas = document.querySelector(selector);
}
var w = this.canvas.width;
var h = this.canvas.height;
if(snake.parts[0].x >= w){
snake.parts[0].x = 0;
ui.updateCollision('Playfield');
; }
if(snake.parts[0].y >= h){
snake.parts[0].y = 0;
ui.updateCollision('Playfield');
}
if(snake.parts[0].x < 0){
snake.parts[0].x = w - 20;
ui.updateCollision('Playfield');
}
if(snake.parts[0].y < 0){
snake.parts[0].y = h - 20;
ui.updateCollision('Playfield');
}
}
function tailCollision (snake, ui) {
for (var i = 1; i < snake.parts.length; i++) {
if(snake.parts[0].x === snake.parts[i].x
&& snake.parts[0].y === snake.parts[i].y){
snake.parts = snake.parts.slice(0,2);
snake.parts[0].x = 0;
snake.parts[0].y = 0;
snake.direction = 1;
ui.scoreValue = 0;
ui.updateScore(0);
ui.updateCollision('Tail');
console.log('Self Tail Collision')
}
}
}
function wallCollision(wallArray, snake, ui) {
for (var i = 1; i < wallArray.length; i++) {
if(snake.parts[0].x === wallArray[i].x
&& snake.parts[0].y === wallArray[i].y){
snake.parts = snake.parts.slice(0,2);
snake.parts[0].x = 0;
snake.parts[0].y = 0;
snake.direction = 1;
ui.updateCollision('Wall');
ui.scoreValue = 0;
ui.updateScore(0);
console.log('Wall Collision')
}
}
}
return {
isFoodCollision: foodCollision,
playFieldCollision: playFieldCollision,
tailCollision: tailCollision,
wallCollision: wallCollision
}
}());
|
function transformPath(decisionPath) {
var path = []
for (var i=1; i<decisionPath.length; i++) {
var node = {
feature: decisionPath[i-1].feature,
side: decisionPath[i].side == 'left' ? "<=" : ">",
threshold: decisionPath[i-1].threshold.toPrecision(5),
featureIdx: decisionPath[i-1].featureIdx,
level: i
}
//copy all properties of decisionPath[i] to node if they won't overide a property
for (var attrname in decisionPath[i]) {
if (node[attrname] == null)
node[attrname] = decisionPath[i][attrname];
}
path.push(node)
}
return path;
}
var tip_features = {
feature: function(d) { return 'Feature: ' + d.feature },
count: function(d) { return d.count + ' samples' },
dataPercentage: function(d) { return d.dataPercentage + '% of the data'},
impurity: function(d) { return 'Impurity: ' + d.impurity}
}
|
import config from '../config';
import changed from 'gulp-changed';
import gulp from 'gulp';
import gulpif from 'gulp-if';
import imagemin from 'gulp-imagemin';
import browserSync from 'browser-sync';
function images(src, dest) {
return gulp.src(config.sourceDir + src)
.pipe(changed(config.buildDir + dest)) // Ignore unchanged files
.pipe(gulpif(global.isProd, imagemin())) // Optimize
.pipe(gulp.dest(config.buildDir + dest))
.pipe(browserSync.stream());
}
gulp.task('blogImages', function() {
return images(config.blog.images.src, config.blog.images.dest);
});
gulp.task('siteImages', function() {
return images(config.site.images.src, config.site.images.dest);
});
gulp.task('erpImages', function() {
return images(config.erp.images.src, config.erp.images.dest);
});
gulp.task('modulesImages', function() {
return images(config.modules.images.src, config.modules.images.dest);
});
gulp.task('fbImages', function() {
return images(config.fb.images.src, config.fb.images.dest);
});
|
'use strict';
var Promise = require('bluebird');
var IDLE = 0;
var ACTIVE = 1;
var STOPPING = 2;
function deferred () {
var _resolve;
var _reject;
var promise = new Promise(function (resolve, reject) {
_resolve = resolve;
_reject = reject;
});
return {
promise: promise,
resolve: _resolve,
reject: _reject
};
}
function IntervalWorker (workFn, delay) {
this._workFn = workFn;
this._delay = delay || 0;
this._activeWork = null;
this._timeout = null;
this._workerStopped = null;
this._state = IDLE;
}
IntervalWorker.prototype._tick = function () {
this._state = ACTIVE;
this._activeWork = Promise.try(this._workFn)
.bind(this)
.then(function () {
this._activeWork = null;
if (this._state === ACTIVE) {
this._timeout = setTimeout(function () {
this._timeout = null;
this._tick();
}.bind(this), this._delay);
}
}, function (err) {
this._activeWork = null;
this._workerStopped.reject(err);
this._state = IDLE;
});
};
IntervalWorker.prototype.start = function () {
if (this._state === IDLE) {
this._workerStopped = deferred();
this._tick();
}
return this._workerStopped.promise;
};
IntervalWorker.prototype.setDelay = function (delay) {
this._delay = delay || 0;
};
IntervalWorker.prototype.stop = function () {
if (this._state === ACTIVE) {
this._state = STOPPING;
if (this._activeWork) {
this._activeWork.cancel();
}
setImmediate(function () {
if (this._timeout) {
clearTimeout(this._timeout);
this._timeout = null;
}
Promise.resolve(this._activeWork || null)
.bind(this)
.catchReturn(Promise.CancellationError)
.then(function () {
this._state = IDLE;
this._workerStopped.resolve();
});
}.bind(this));
return this._workerStopped.promise;
} else {
return Promise.resolve();
}
};
module.exports = IntervalWorker;
|
/******/ (function(modules) { // webpackBootstrap
/******/ // install a JSONP callback for chunk loading
/******/ var parentJsonpFunction = window["webpackJsonp"];
/******/ window["webpackJsonp"] = function webpackJsonpCallback(chunkIds, moreModules, executeModules) {
/******/ // add "moreModules" to the modules object,
/******/ // then flag all "chunkIds" as loaded and fire callback
/******/ var moduleId, chunkId, i = 0, resolves = [], result;
/******/ for(;i < chunkIds.length; i++) {
/******/ chunkId = chunkIds[i];
/******/ if(installedChunks[chunkId]) {
/******/ resolves.push(installedChunks[chunkId][0]);
/******/ }
/******/ installedChunks[chunkId] = 0;
/******/ }
/******/ for(moduleId in moreModules) {
/******/ if(Object.prototype.hasOwnProperty.call(moreModules, moduleId)) {
/******/ modules[moduleId] = moreModules[moduleId];
/******/ }
/******/ }
/******/ if(parentJsonpFunction) parentJsonpFunction(chunkIds, moreModules, executeModules);
/******/ while(resolves.length) {
/******/ resolves.shift()();
/******/ }
/******/ if(executeModules) {
/******/ for(i=0; i < executeModules.length; i++) {
/******/ result = __webpack_require__(__webpack_require__.s = executeModules[i]);
/******/ }
/******/ }
/******/ return result;
/******/ };
/******/
/******/ // The module cache
/******/ var installedModules = {};
/******/
/******/ // objects to store loaded and loading chunks
/******/ var installedChunks = {
/******/ 1: 0
/******/ };
/******/
/******/ // The require function
/******/ function __webpack_require__(moduleId) {
/******/
/******/ // Check if module is in cache
/******/ if(installedModules[moduleId]) {
/******/ return installedModules[moduleId].exports;
/******/ }
/******/ // Create a new module (and put it into the cache)
/******/ var module = installedModules[moduleId] = {
/******/ i: moduleId,
/******/ l: false,
/******/ exports: {}
/******/ };
/******/
/******/ // Execute the module function
/******/ modules[moduleId].call(module.exports, module, module.exports, __webpack_require__);
/******/
/******/ // Flag the module as loaded
/******/ module.l = true;
/******/
/******/ // Return the exports of the module
/******/ return module.exports;
/******/ }
/******/
/******/ // This file contains only the entry chunk.
/******/ // The chunk loading function for additional chunks
/******/ __webpack_require__.e = function requireEnsure(chunkId) {
/******/ if(installedChunks[chunkId] === 0) {
/******/ return Promise.resolve();
/******/ }
/******/
/******/ // a Promise means "currently loading".
/******/ if(installedChunks[chunkId]) {
/******/ return installedChunks[chunkId][2];
/******/ }
/******/
/******/ // setup Promise in chunk cache
/******/ var promise = new Promise(function(resolve, reject) {
/******/ installedChunks[chunkId] = [resolve, reject];
/******/ });
/******/ installedChunks[chunkId][2] = promise;
/******/
/******/ // start chunk loading
/******/ var head = document.getElementsByTagName('head')[0];
/******/ var script = document.createElement('script');
/******/ script.type = 'text/javascript';
/******/ script.charset = 'utf-8';
/******/ script.async = true;
/******/ script.timeout = 120000;
/******/
/******/ if (__webpack_require__.nc) {
/******/ script.setAttribute("nonce", __webpack_require__.nc);
/******/ }
/******/ script.src = __webpack_require__.p + "" + chunkId + "-bundle.js";
/******/ var timeout = setTimeout(onScriptComplete, 120000);
/******/ script.onerror = script.onload = onScriptComplete;
/******/ function onScriptComplete() {
/******/ // avoid mem leaks in IE.
/******/ script.onerror = script.onload = null;
/******/ clearTimeout(timeout);
/******/ var chunk = installedChunks[chunkId];
/******/ if(chunk !== 0) {
/******/ if(chunk) {
/******/ chunk[1](new Error('Loading chunk ' + chunkId + ' failed.'));
/******/ }
/******/ installedChunks[chunkId] = undefined;
/******/ }
/******/ };
/******/ head.appendChild(script);
/******/
/******/ return promise;
/******/ };
/******/
/******/ // expose the modules object (__webpack_modules__)
/******/ __webpack_require__.m = modules;
/******/
/******/ // expose the module cache
/******/ __webpack_require__.c = installedModules;
/******/
/******/ // identity function for calling harmony imports with the correct context
/******/ __webpack_require__.i = function(value) { return value; };
/******/
/******/ // define getter function for harmony exports
/******/ __webpack_require__.d = function(exports, name, getter) {
/******/ if(!__webpack_require__.o(exports, name)) {
/******/ Object.defineProperty(exports, name, {
/******/ configurable: false,
/******/ enumerable: true,
/******/ get: getter
/******/ });
/******/ }
/******/ };
/******/
/******/ // getDefaultExport function for compatibility with non-harmony modules
/******/ __webpack_require__.n = function(module) {
/******/ var getter = module && module.__esModule ?
/******/ function getDefault() { return module['default']; } :
/******/ function getModuleExports() { return module; };
/******/ __webpack_require__.d(getter, 'a', getter);
/******/ return getter;
/******/ };
/******/
/******/ // Object.prototype.hasOwnProperty.call
/******/ __webpack_require__.o = function(object, property) { return Object.prototype.hasOwnProperty.call(object, property); };
/******/
/******/ // __webpack_public_path__
/******/ __webpack_require__.p = "";
/******/
/******/ // on error function for async loading
/******/ __webpack_require__.oe = function(err) { console.error(err); throw err; };
/******/ })
/************************************************************************/
/******/ ([]);
|
"use strict";
module.exports = function(grunt) {
require("matchdep").filterDev("grunt-*").forEach(grunt.loadNpmTasks);
grunt.initConfig({
// Define Directory
dirs: {
js: "src/js",
coffee: "src/coffee",
build: "dist"
},
// Metadata
pkg: grunt.file.readJSON("package.json"),
banner:
"\n" +
"/*\n" +
" * -------------------------------------------------------\n" +
" * Project: <%= pkg.title %>\n" +
" * Version: <%= pkg.version %>\n" +
" *\n" +
" * Author: <%= pkg.author.name %>\n" +
" * Site: <%= pkg.author.url %>\n" +
" * Contact: <%= pkg.author.email %>\n" +
" *\n" +
" *\n" +
" * Copyright (c) <%= grunt.template.today(\"yyyy\") %> <%= pkg.author.name %>\n" +
" * -------------------------------------------------------\n" +
" */\n" +
"\n",
// Compile CoffeeScript
coffee: {
compileBare: {
options: {
bare: true
},
files: {
"<%= dirs.js %>/Tabu.js" : "<%= dirs.coffee %>/Tabu.coffee"
}
}
},
// Minify and Concat archives
uglify: {
options: {
mangle: false,
banner: "<%= banner %>"
},
dist: {
files: {
"<%= dirs.build %>/Tabu.min.js": "<%= dirs.js %>/Tabu.js"
}
}
},
// Notifications
notify: {
coffee: {
options: {
title: "CoffeeScript - <%= pkg.title %>",
message: "Compiled and minified with success!"
}
},
js: {
options: {
title: "Javascript - <%= pkg.title %>",
message: "Minified and validated with success!"
}
}
}
});
// Register Taks
// --------------------------
// Observe changes, concatenate, minify and validate files
grunt.registerTask( "default", [ "coffee", "notify:coffee", "uglify", "notify:js" ]);
};
|
import typescript from 'rollup-plugin-typescript'
import bundleWorker from 'rollup-plugin-bundle-worker'
export default {
input: 'src/index.ts',
output: {
file: 'docs/nonogram.js',
format: 'iife',
},
name: 'nonogram',
plugins: [
typescript({ typescript: require('typescript') }),
bundleWorker(),
],
}
|
var path = require('path')
ScrewTurnPageFile.LATEST = -1
ScrewTurnPageFile.compare = compare
ScrewTurnPageFile.prototype.isLatest = isLatest
ScrewTurnPageFile.prototype.compareTo = compareTo
function ScrewTurnPageFile(filename) {
var revision = getRevision(filename)
, title = getTitle(filename)
this.__defineGetter__('filename', function() {
return filename
})
this.__defineGetter__('title', function() {
return title
})
this.__defineGetter__('revision', function() {
return revision
})
}
function getRevision(filename) {
var basename = path.basename(filename, '.cs')
, offset = basename.indexOf('.')
, revision = offset >= 0 ? parseInt(basename.substr(offset + 1), 10) : ScrewTurnPageFile.LATEST
return revision
}
function getTitle(filename) {
var basename = path.basename(filename, 'cs')
, offset = basename.indexOf('.')
, title = offset >= 0 ? basename.substr(0, offset) : basename
return title
}
function isLatest() {
return this.revision === ScrewTurnPageFile.LATEST
}
function compareTo(item) {
return compare(this, item)
}
function compare(a, b) {
if(a.title < b.title)
return -1
else if(a.title > b.title)
return 1
else if(a.revision === ScrewTurnPageFile.LATEST)
return 1
else if(b.revision === ScrewTurnPageFile.LATEST)
return -1
return a.revision - b.revision
}
module.exports = ScrewTurnPageFile
|
'use strict';
var gulp = require( 'gulp' );
var fontmin = require( 'gulp-fontmin' );
var path = require( '../../paths.js' );
gulp.task( 'fonts', function( )
{
return gulp.src( path.to.fonts.source )
.pipe( fontmin( )
.pipe( gulp.dest( path.to.fonts.destination ) ) );
} );
|
var http = require('http'),
fs = require('fs');
var people = {};
//var port = process.env.OPENSHIFT_NODEJS_PORT || "1337";
var port = "1337";
//var serverUrl = process.env.OPENSHIFT_NODEJS_IP || "127.0.0.1";
var serverUrl = "127.0.0.1";
var app = http.createServer(function (request, response)
{
//console.log("Server request: " + request.url)
fs.readFile("chat.html", 'utf-8', function (error, data) {
response.writeHead(200, {'Content-Type': 'text/html'});
response.write(data);
response.end();
});
}).listen(port, serverUrl);
console.log("Listening at " + serverUrl + ":" + port);
var io = require('socket.io').listen(app);
io.sockets.on('connection', function(client) {
client.emit('connected');
client.on("join", function(name){
people[client.id] = {name:name, html:'<span onclick="msgTo(\''+client.id+'\')" title="Type a message and click here to send in private">'+name+'</span>'}; //data["name"];
io.sockets.to(client.id).emit('messageMe', 'Server', 'You have connected.');
io.sockets.emit("update", name + " has joined the server.")
io.sockets.emit("update-people", people);
console.log("New join: " + name);
});
client.on('sendTo', function(id, msg, name){
if (people[client.id] == undefined || people[client.id] == null)
{
people[client.id] = {name:name, html:'<span onclick="msgTo(\''+client.id+'\')" title="Type a message and click here to send in private">'+name+'</span>'}; //data["name"];
io.sockets.to(client.id).emit('messageMe', 'Server', 'You have connected.');
io.sockets.emit("update", name + " has joined the server.")
io.sockets.emit("update-people", people);
console.log("New join: " + name);
}
io.sockets.to(id).emit('messageMe', people[client.id]["name"] + '<span style="color:red"> in PVT</span>', msg);
io.sockets.to(client.id).emit('messageMe', people[client.id]["name"] + '<span style="color:red"> in PVT</span>', msg);
});
client.on("sendAll", function(msg, name){
if (people[client.id] == undefined || people[client.id] == null)
{
people[client.id] = {name:name, html:'<span onclick="msgTo(\''+client.id+'\')" title="Type a message and click here to send in private">'+name+'</span>'}; //data["name"];
io.sockets.to(client.id).emit('messageMe', 'Server', 'You have connected.');
io.sockets.emit("update", name + " has joined the server.")
io.sockets.emit("update-people", people);
console.log("New join: " + name);
}
//console.log("Send message by " + people[client.id] + ": " + msg);
io.sockets.emit("chat", people[client.id]["name"], msg);
});
client.on("disconnect", function(){
if (people[client.id] != undefined){
io.sockets.emit("update", people[client.id]["name"] + " has left the server.");
console.log(people[client.id]["name"] + " was disconnected")
delete people[client.id];
io.sockets.emit("update-people", people);
}
});
});
|
// Here is where you can define configuration overrides based on the execution environment.
// Supply a key to the default export matching the NODE_ENV that you wish to target, and
// the base configuration will apply your overrides before exporting itself.
export default {
// ======================================================
// Overrides when NODE_ENV === 'development'
// ======================================================
// NOTE: In development, we use an explicit public path when the assets
// are served webpack by to fix this issue:
// http://stackoverflow.com/questions/34133808/webpack-ots-parsing-error-loading-fonts/34133809#34133809
development: (config) => ({
compiler_public_path: `http://${config.server_host}:${config.server_port}/`,
proxy: {
enabled: false,
options: {
host: 'http://localhost:8000',
match: /^\/api\/.*/
}
}
}),
// ======================================================
// Overrides when NODE_ENV === 'production'
// ======================================================
production: (config) => ({
compiler_public_path: '/',
compiler_fail_on_warning: false,
compiler_hash_type: 'chunkhash',
compiler_devtool: null,
compiler_stats: {
chunks: true,
chunkModules: true,
colors: true
}
})
};
|
/* globals Mustache */
var NAILS_Admin_CMS_Menus_Create_Edit;
NAILS_Admin_CMS_Menus_Create_Edit = function(items) {
/**
* Avoid scope issues in callbacks and anonymous functions by referring to `this` as `base`
* @type {Object}
*/
var base = this;
// --------------------------------------------------------------------------
/**
* The item's template
* @type {String}
*/
base.itemTemplate = '';
/**
* The length of the ID to generate
* @type {Number}
*/
base.idLength = 32;
// --------------------------------------------------------------------------
/**
* Constructs the edit page
* @param {array} items The menu items
* @return {void}
*/
base.__construct = function(items) {
base.itemTemplate = $('#template-item').html();
// Init NestedSortable
$('div.nested-sortable').each(function() {
var sortable, container, html, target;
// Get the sortable item
sortable = $(this);
// Get the container
container = sortable.children('ol.nested-sortable').first();
// Build initial menu items
for (var key in items) {
if (items.hasOwnProperty(key)) {
html = Mustache.render(base.itemTemplate, items[key]);
// Does this have a parent? If so then we need to append it there
if (items[key].parent_id !== null && items[key].parent_id !== '') {
// Find the parent and append to it's <ol class="nested-sortable-sub">
target = $('li.target-' + items[key].parent_id + ' ol.nested-sortable-sub').first();
if (target.length === 0) {
target = container;
}
} else {
target = container;
}
target.append(html);
// If the page_id is set, then make sure it's selected in the dropdown
if (parseInt(items[key].page_id, 10) > 0) {
target.find('li:last option[value=' + items[key].page_id + ']').prop('selected', true);
}
}
}
// --------------------------------------------------------------------------
// Sortitize!
container.nestedSortable({
'handle': 'div.handle',
'items': 'li',
'toleranceElement': '> div',
'stop': function() {
// Update parents
base.updateParentIds(container);
}
});
// --------------------------------------------------------------------------
// Bind to add button
sortable.find('a.add-item').on('click', function() {
var _data = {
id: base.generateId()
};
var html = Mustache.render(base.itemTemplate, _data);
container.append(html);
return false;
});
});
// --------------------------------------------------------------------------
// Bind to remove buttons
$(document).on('click', 'a.item-remove', function() {
var _obj = $(this);
$('<div>')
.html('<p>This will remove this menu item (and any children) from the interface.</p><p>You will still need to "Save Changes" to commit the removal</p>')
.dialog(
{
title: 'Are you sure?',
resizable: false,
draggable: false,
modal: true,
dialogClass: "no-close",
buttons:
{
OK: function() {
_obj.closest('li.target').remove();
$(this).dialog("close");
},
Cancel: function() {
$(this).dialog("close");
}
}
})
.show();
return false;
});
};
// --------------------------------------------------------------------------
/**
* Updates each menu item's parent ID field
* @param {Object} container The container object to restrict to
* @return {void}
*/
base.updateParentIds = function(container) {
$('input.input-parent_id', container).each(function() {
var parentId = $(this).closest('ol').closest('li').data('id');
$(this).val(parentId);
});
};
// --------------------------------------------------------------------------
/**
* Generates a unique ID for the page
* @return {String}
*/
base.generateId = function() {
var chars, idStr;
chars = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789';
do {
idStr = 'newid-';
for (var i = base.idLength; i > 0; --i) {
idStr += chars[Math.round(Math.random() * (chars.length - 1))];
}
} while ($('li.target-' + idStr).length > 0);
return idStr;
};
// --------------------------------------------------------------------------
return base.__construct(items);
};
|
import React, { PureComponent } from 'react';
import PropTypes from 'prop-types';
import { Animated, StyleSheet } from 'react-native';
import { H6 } from '@ui/typography';
import styled from '@ui/styled';
export const LabelText = styled(({ theme }) => ({
color: theme.colors.text.secondary,
backgroundColor: 'transparent',
paddingVertical: theme.sizing.baseUnit / 4,
}), 'FloatingLabel.LabelText')(H6);
const styles = StyleSheet.create({
floatLabelView: {
position: 'absolute',
bottom: 0,
top: 0,
justifyContent: 'center',
},
});
class FloatingLabel extends PureComponent {
static propTypes = {
children: PropTypes.node,
animation: PropTypes.shape({
interpolate: PropTypes.func,
}),
scaleSize: PropTypes.number, // how much smaller to make label when focused
floatingOpacity: PropTypes.number,
};
static defaultProps = {
animation: new Animated.Value(0),
scaleSize: 0.8,
floatingOpacity: 0.8,
};
state = {
labelWidth: 0,
labelHeight: 0,
};
handleLayout = ({ nativeEvent: { layout } }) => {
this.setState({
labelWidth: layout.width,
labelHeight: layout.height,
});
};
render() {
const scaledWidth = this.state.labelWidth * (1.05 - this.props.scaleSize);
const sideScaledWidth = scaledWidth / 2;
const scale = this.props.animation.interpolate({
inputRange: [0, 1],
outputRange: [1, this.props.scaleSize],
});
const opacity = this.props.animation.interpolate({
inputRange: [0, 1],
outputRange: [1, this.props.floatingOpacity],
});
const translateY = this.props.animation.interpolate({
inputRange: [0, 1],
outputRange: [0, -(this.state.labelHeight * 0.7)],
});
const translateX = this.props.animation.interpolate({
inputRange: [0, 1],
outputRange: [0, -sideScaledWidth],
});
const wrapperStyles = {
transform: [{ scale }, { translateX }, { translateY }],
opacity,
};
return (
<Animated.View
pointerEvents="none"
onLayout={this.handleLayout}
style={[styles.floatLabelView, wrapperStyles]}
>
<LabelText>
{this.props.children}
</LabelText>
</Animated.View>
);
}
}
export default FloatingLabel;
|
//= require wow
//= require formvalidation.min
//= require formvalidation/framework/bootstrap.min
//= require formvalidation/language/pt_BR
//= require_self
//= require_tree ./autoload
|
// Load in dependencies
var exec = require('./utils').exec;
// Helper function to collect information about a window
function windowInfo(id) {
// Get active window and window info
// http://unix.stackexchange.com/questions/61037/how-to-resize-application-windows-in-an-arbitrary-direction-not-vertical-and-no
var info = {
width: +exec("xwininfo -id " + id + " | grep Width | cut --delimiter ' ' --fields 4"),
height: +exec("xwininfo -id " + id + " | grep Height | cut --delimiter ' ' --fields 4"),
left: +exec("xwininfo -id " + id + " | grep 'Absolute upper-left X' | cut --delimiter ' ' --fields 7"),
top: +exec("xwininfo -id " + id + " | grep 'Absolute upper-left Y' | cut --delimiter ' ' --fields 7")
};
var state = exec('xprop -id ' + id + ' | grep _NET_WM_STATE'),
isHorzMaximized = state.match('_NET_WM_STATE_MAXIMIZED_HORZ');
// wmctrl resizes left +3 and top +24 to account for borders
// Adjust info back
info.top -= 24;
info.height += 24;
// If we are not horizontally maxed out, adjust for horizontal border
// DEV: The vertical border is always present
if (!isHorzMaximized) {
info.left -= 3;
info.width += 3;
}
// TODO: Should do some tests against chrome since borderless might not apply
// Return the info
return info;
}
// Expose windowInfo
module.exports = windowInfo;
|
(function() {
var devices = {};
$.subscribe('ninja.data', function(topic, d) {
console.log("Got some data", d);
if (!devices[d.G]) {
$.publish('mappu.zone', d.G);
devices[d.G] = true;
}
var age = new Date().getTime() - d.DA.timestamp;
$.publish('mappu.alarm.'+d.G, d.DA.Alarm1, age, d.DA.timestamp);
$.publish('mappu.battery.'+d.G, d.DA.Battery, age, d.DA.timestamp);
$.publish('mappu.tamper.'+d.G, d.DA.Tamper, age, d.DA.timestamp);
});
})();
|
version https://git-lfs.github.com/spec/v1
oid sha256:57f07eb24fc71a0deb80c59e16d9ba40da0e8cb6fe6b9156fd85cc14f56c8f8a
size 2663
|
import configureUrlQuery from '../configureUrlQuery';
import urlQueryConfig from '../urlQueryConfig';
it('updates the singleton query object', () => {
configureUrlQuery({ test: 99 });
expect(urlQueryConfig.test).toBe(99);
configureUrlQuery({ history: 123 });
expect(urlQueryConfig.history).toBe(123);
expect(urlQueryConfig.test).toBe(99);
});
it('does not break on undefined options', () => {
configureUrlQuery();
expect(Object.keys(urlQueryConfig).length).toBeGreaterThan(0);
});
it('configures entrySeparator and keyValSeparator global values', () => {
expect(urlQueryConfig.entrySeparator).toBe('_');
expect(urlQueryConfig.keyValSeparator).toBe('-');
configureUrlQuery({ entrySeparator: '__' });
expect(urlQueryConfig.entrySeparator).toBe('__');
expect(urlQueryConfig.keyValSeparator).toBe('-');
configureUrlQuery({ keyValSeparator: '--' });
expect(urlQueryConfig.entrySeparator).toBe('__');
expect(urlQueryConfig.keyValSeparator).toBe('--');
// Reset so it does not effect other tests
configureUrlQuery({ entrySeparator: '_', keyValSeparator: '-' });
});
|
'use strict';
angular
.module('personalWebsiteApp', [
'ngResource',
'ngRoute',
'ngAnimate',
'animatedBirdsDirective',
'scrollAnimDirective',
'swfTemplateDirective'
])
.config(['$routeProvider', function ($routeProvider) {
$routeProvider
.when('/', {
templateUrl: 'views/main.html',
controller: 'MainCtrl'
})
.when('/about', {
templateUrl: 'views/about.html'
})
.when('/resume', {
templateUrl: 'views/resume.html'
})
.when('/work', {
templateUrl: 'views/portfolio.html'
})
.when('/identity-design-case-study-rangleio', {
templateUrl: 'views/portfolio/identity-design-case-study-rangleio.html'
})
.when('/aid85', {
templateUrl: 'views/portfolio/aid85.html'
})
.otherwise({
redirectTo: '/'
});
}]);
|
define(['mousetrap'], function(Mousetrap){
'use strict';
var utils = require('util'),
instances = []
;
function IframeMousetrap(a){
var self = new Mousetrap(a);
/*self._instanceId = instances.push(this);
self._originalHandleKey = this._handleKey;
self._handleKey = IframeMousetrap.prototype._handleKey;*/
self.handleKey = IframeMousetrap.prototype.handleKey;
self.shutdown = IframeMousetrap.prototype.shutdown;
return self;
}
IframeMousetrap.prototype.shutdown = function() {
this._handleKey = function(){}; //:(
};
IframeMousetrap.prototype.handleKey = function() {
return Mousetrap.handleKey.apply(Mousetrap, arguments);
};
return IframeMousetrap;
});
|
'use strict';
const EmberApp = require('./ember-app');
/**
* FastBoot renders your Ember.js applications in Node.js. Start by
* instantiating this class with the path to your compiled Ember app:
*
*
* #### Sandboxing
*
* For security and correctness reasons, Ember applications running in FastBoot
* are run inside a sandbox that prohibits them from accessing the normal
* Node.js environment.
*
* This sandbox is the built-in `VMSandbox` class, which uses
* Node's `vm` module. You may add and/or override sandbox variables by
* passing the `addOrOverrideSandboxGlobals` option.
*
* @example
* const FastBoot = require('fastboot');
*
* let app = new FastBoot({
* distPath: 'path/to/dist',
* buildSandboxGlobals(globals) {
* return Object.assign({}, globals, {
* // custom globals
* });
* },
* });
*
* app.visit('/photos')
* .then(result => result.html())
* .then(html => res.send(html));
*/
class FastBoot {
/**
* Create a new FastBoot instance.
*
* @param {Object} options
* @param {string} options.distPath the path to the built Ember application
* @param {Boolean} [options.resilient=false] if true, errors during rendering won't reject the `visit()` promise but instead resolve to a {@link Result}
* @param {Function} [options.buildSandboxGlobals] a function used to build the final set of global properties setup within the sandbox
* @param {Number} [options.maxSandboxQueueSize] - maximum sandbox queue size when using buildSandboxPerRequest flag.
*/
constructor(options = {}) {
let { distPath, buildSandboxGlobals, maxSandboxQueueSize } = options;
this.resilient = 'resilient' in options ? Boolean(options.resilient) : false;
this.distPath = distPath;
// deprecate the legacy path, but support it
if (buildSandboxGlobals === undefined && options.sandboxGlobals !== undefined) {
console.warn(
'[DEPRECATION] Instantiating `fastboot` with a `sandboxGlobals` option has been deprecated. Please migrate to specifying `buildSandboxGlobals` instead.'
);
buildSandboxGlobals = globals => Object.assign({}, globals, options.sandboxGlobals);
}
this.buildSandboxGlobals = buildSandboxGlobals;
this.maxSandboxQueueSize = maxSandboxQueueSize;
this._buildEmberApp(this.distPath, this.buildSandboxGlobals, maxSandboxQueueSize);
}
/**
* Renders the Ember app at a specific URL, returning a promise that resolves
* to a {@link Result}, giving you access to the rendered HTML as well as
* metadata about the request such as the HTTP status code.
*
* @param {string} path the URL path to render, like `/photos/1`
* @param {Object} options
* @param {Boolean} [options.resilient] whether to reject the returned promise if there is an error during rendering. Overrides the instance's `resilient` setting
* @param {string} [options.html] the HTML document to insert the rendered app into. Uses the built app's index.html by default.
* @param {Object} [options.metadata] per request meta data that need to be exposed in the app.
* @param {Boolean} [options.shouldRender] whether the app should do rendering or not. If set to false, it puts the app in routing-only.
* @param {Boolean} [options.disableShoebox] whether we should send the API data in the shoebox. If set to false, it will not send the API data used for rendering the app on server side in the index.html.
* @param {Integer} [options.destroyAppInstanceInMs] whether to destroy the instance in the given number of ms. This is a failure mechanism to not wedge the Node process (See: https://github.com/ember-fastboot/fastboot/issues/90)
* @param {Boolean} [options.buildSandboxPerVisit=false] whether to create a new sandbox context per-visit (slows down each visit, but guarantees no prototype leakages can occur), or reuse the existing sandbox (faster per-request, but each request shares the same set of prototypes)
* @returns {Promise<Result>} result
*/
async visit(path, options = {}) {
let resilient = 'resilient' in options ? options.resilient : this.resilient;
let result = await this._app.visit(path, options);
if (!resilient && result.error) {
throw result.error;
} else {
return result;
}
}
/**
* Destroy the existing Ember application instance, and recreate it from the provided dist path.
* This is commonly done when `dist` has been updated, and you need to prepare to serve requests
* with the updated assets.
*
* @param {Object} options
* @param {string} options.distPath the path to the built Ember application
*/
reload({ distPath }) {
if (this._app) {
this._app.destroy();
}
this._buildEmberApp(distPath);
}
_buildEmberApp(
distPath = this.distPath,
buildSandboxGlobals = this.buildSandboxGlobals,
maxSandboxQueueSize = this.maxSandboxQueueSize
) {
if (!distPath) {
throw new Error(
'You must instantiate FastBoot with a distPath ' +
'option that contains a path to a dist directory ' +
'produced by running ember fastboot:build in your Ember app:' +
'\n\n' +
'new FastBootServer({\n' +
" distPath: 'path/to/dist'\n" +
'});'
);
}
this.distPath = distPath;
this._app = new EmberApp({
distPath,
buildSandboxGlobals,
maxSandboxQueueSize,
});
}
}
module.exports = FastBoot;
|
//# sourceURL=add.js
$(function () {
$("#frm").jValidate({
rules:{
name:{
required:true,
minlength:2,
maxlength:32,
stringCheck:true
},
code:{
required:true,
minlength:2,
maxlength:64,
pattern:/^\w{2,32}$/,
checkRepeat1:["/admin/system/courier/checkCode",'$value']
},
cost:{
money:true
},
address:{
minlength:2,
maxlength:64
},
linkman:{
minlength:2,
maxlength:32
},
linkphone:{
checkPhone:true,
minlength:8,
maxlength:32
},
email:{
email:true,
minlength:8,
maxlength:32
},
remark:{
minlength:2,
maxlength:128
}
},
messages:{
code:{
checkRepeat1:"快递公司编码已经存在",
pattern:'快递公司编码无效'
}
}
});
$('#save').click(function () {
var valid=$("#frm").valid();
if(!valid) return;
$.jAjax({
url:'/admin/system/courier/add',
data:$('#frm').formData(),
method:'post',
success:function(data){
if($.isPlainObject(data) && data.id>0){
$.notice('快递公司保存成功');
$('#frm').resetForm();
}
}
})
});
$('#reset').click(function(){
$('#frm').resetForm();
})
})
|
/* ========================================================================
* ZUI: browser.js
* http://zui.sexy
* ========================================================================
* Copyright (c) 2014 cnezsoft.com; Licensed MIT
* ======================================================================== */
(function(window, $)
{
'use strict';
var browseHappyTip = {
'zh_cn': '您的浏览器版本过低,无法体验所有功能,建议升级或者更换浏览器。 <a href="http://browsehappy.com/" target="_blank" class="alert-link">了解更多...</a>',
'zh_tw': '您的瀏覽器版本過低,無法體驗所有功能,建議升級或者更换瀏覽器。<a href="http://browsehappy.com/" target="_blank" class="alert-link">了解更多...</a>',
'en': 'Your browser is too old, it has been unable to experience the colorful internet. We strongly recommend that you upgrade a better one. <a href="http://browsehappy.com/" target="_blank" class="alert-link">Learn more...</a>'
};
// The browser modal class
var Browser = function()
{
var isIE = this.isIE;
var ie = isIE();
if (ie)
{
for (var i = 10; i > 5; i--)
{
if (isIE(i))
{
ie = i;
break;
}
}
}
this.ie = ie;
this.cssHelper();
};
// Append CSS class to html tag
Browser.prototype.cssHelper = function()
{
var ie = this.ie,
$html = $('html');
$html.toggleClass('ie', ie)
.removeClass('ie-6 ie-7 ie-8 ie-9 ie-10');
if (ie)
{
$html.addClass('ie-' + ie)
.toggleClass('gt-ie-7 gte-ie-8 support-ie', ie >= 8)
.toggleClass('lte-ie-7 lt-ie-8 outdated-ie', ie < 8)
.toggleClass('gt-ie-8 gte-ie-9', ie >= 9)
.toggleClass('lte-ie-8 lt-ie-9', ie < 9)
.toggleClass('gt-ie-9 gte-ie-10', ie >= 10)
.toggleClass('lte-ie-9 lt-ie-10', ie < 10);
}
};
// Show browse happy tip
Browser.prototype.tip = function()
{
if (this.ie && this.ie < 8)
{
var $browseHappy = $('#browseHappyTip');
if (!$browseHappy.length)
{
$browseHappy = $('<div id="browseHappyTip" class="alert alert-dismissable alert-danger alert-block" style="position: relative; z-index: 99999"><button type="button" class="close" data-dismiss="alert" aria-hidden="true">×</button><div class="container"><div class="content text-center"></div></div></div>');
$browseHappy.prependTo('body');
}
$browseHappy.find('.content').html(this.browseHappyTip || browseHappyTip[$.clientLang() || 'zh_cn']);
}
};
// Detect it is IE, can given a version
Browser.prototype.isIE = function(version)
{
// var ie = /*@cc_on !@*/false;
var b = document.createElement('b');
b.innerHTML = '<!--[if IE ' + (version || '') + ']><i></i><![endif]-->';
return b.getElementsByTagName('i').length === 1;
};
// Detect ie 10 with hack
Browser.prototype.isIE10 = function()
{
return ( /*@cc_on!@*/ false);
};
window.browser = new Browser();
$(function()
{
if (!$('body').hasClass('disabled-browser-tip'))
{
window.browser.tip();
}
});
}(window, jQuery));
|
//@ sourceMappingURL=connect.test.map
// Generated by CoffeeScript 1.6.1
(function() {
var assert, async, wongo,
__hasProp = {}.hasOwnProperty;
assert = require('assert');
async = require('async');
wongo = require('../lib/wongo');
describe('Wongo.connect()', function() {
it('should connect to the database', function(done) {
wongo.connect(process.env.DB_URL);
return done();
});
return it('should clear every registered schema', function(done) {
var _type, _types;
_types = (function() {
var _ref, _results;
_ref = wongo.schemas;
_results = [];
for (_type in _ref) {
if (!__hasProp.call(_ref, _type)) continue;
_results.push(_type);
}
return _results;
})();
return async.each(_types, function(_type, nextInLoop) {
return wongo.clear(_type, nextInLoop);
}, done);
});
});
}).call(this);
|
/*global module, process */
module.exports = process.env.AWS_REGION || 'us-east-1';
|
/**
* Open the Eyes Instance
*/
import {getBrowserFor} from './utils'
module.exports = (
person, page, done
) => {
console.log("(openEyes) Opening the Eyes for: " + person)
getBrowserFor(person).EyesOpen(page);
global.eyesIsOpen = true
done()
};
|
jQuery.fn.showMeMore = function (options) {
var options = $.extend({
current: 4, // number to be displayed at start
count: 4, // how many show in one click
fadeSpeed: 300, // animation speed
showButton: '', // show button (false / string)
hideButton: '', // hide button
showButtonText: 'showButton', //text at the showButton
hideButtonText: 'hideButton', //text at the showButton
enableHide: false, // allow to hide (true / false)
generateBtn: true,// auto generate buttons if they not added by default
list: 'li' //tile elements
}, options);
var make = function () {
var showButton = $(options.showButton),
hideButton = $(options.hideButton),
enableHide = options.enableHide,
count = options.count,
current = options.current,
fadeSpeed = options.fadeSpeed,
list = $(this).find(options.list),//find all 'list' elements
quantity = list.length;//list elements count
//add SHOW button if it is not installed by the user
if (options.generateBtn && options.showButton == '') {
$(this).append('<button class="showButton">' + options.showButtonText + '</button>');
showButton = $(this).find('.showButton');
}
//add HIDE button if it is not installed by the user and if enableHide is true
if (options.generateBtn && enableHide && options.showButton == '') {
$(this).append('<button class="hideButton">' + options.hideButtonText + '</button>');
hideButton = $(this).find('.hideButton');
}
list.hide();//hide all elements
hideButton.hide()//hide "hideButton"
if (quantity <= current) {
showButton.hide();
}
showItem(0);//show first elements
function switchButtons() {
if (enableHide == false) {
showButton.hide();
} else {
showButton.hide();
hideButton.show();
}
}
//this function show next elements
function showItem(time) {
for (var i = 0; i < current; i++) {
if ($(list[i]).is(':hidden')) {
$(list[i]).fadeIn(time);
}
}
}
//this function hide all elements
function hideAll(time) {
for (var i = current; i < quantity; i++) {
$(list[i]).fadeOut(time);
}
}
showButton.click(function (event) {
event.preventDefault();
current += count;
showItem(fadeSpeed);
if (current >= quantity) {
switchButtons();
}
});
hideButton.click(function (event) {
event.preventDefault();
current = options.current;
hideAll(fadeSpeed);
hideButton.hide();
showButton.show();
});
};
return this.each(make);
};
|
import _ from 'lodash';
import 'ui/paginated_table';
import popularityHtml from 'plugins/kibana/management/sections/indices/_field_popularity.html';
import controlsHtml from 'plugins/kibana/management/sections/indices/_field_controls.html';
import dateScripts from 'plugins/kibana/management/sections/indices/_date_scripts';
import uiModules from 'ui/modules';
import scriptedFieldsTemplate from 'plugins/kibana/management/sections/indices/_scripted_fields.html';
import { getSupportedScriptingLangs } from 'ui/scripting_langs';
import { scriptedFields as docLinks } from 'ui/documentation_links/documentation_links';
uiModules.get('apps/management')
.directive('scriptedFields', function (kbnUrl, Notifier, $filter, confirmModal) {
const rowScopes = []; // track row scopes, so they can be destroyed as needed
const filter = $filter('filter');
const notify = new Notifier();
return {
restrict: 'E',
template: scriptedFieldsTemplate,
scope: true,
link: function ($scope) {
const fieldCreatorPath = '/management/kibana/indices/{{ indexPattern }}/scriptedField';
const fieldEditorPath = fieldCreatorPath + '/{{ fieldName }}';
$scope.docLinks = docLinks;
$scope.perPage = 25;
$scope.columns = [
{ title: 'name' },
{ title: 'lang' },
{ title: 'script' },
{ title: 'format' },
{ title: 'controls', sortable: false }
];
$scope.$watchMulti(['[]indexPattern.fields', 'fieldFilter'], refreshRows);
function refreshRows() {
_.invoke(rowScopes, '$destroy');
rowScopes.length = 0;
const fields = filter($scope.indexPattern.getScriptedFields(), { name: $scope.fieldFilter });
_.find($scope.editSections, { index: 'scriptedFields' }).count = fields.length; // Update the tab count
$scope.rows = fields.map(function (field) {
const rowScope = $scope.$new();
rowScope.field = field;
rowScopes.push(rowScope);
return [
_.escape(field.name),
_.escape(field.lang),
_.escape(field.script),
_.get($scope.indexPattern, ['fieldFormatMap', field.name, 'type', 'title']),
{
markup: controlsHtml,
scope: rowScope
}
];
});
}
$scope.addDateScripts = function () {
const conflictFields = [];
let fieldsAdded = 0;
_.each(dateScripts($scope.indexPattern), function (script, field) {
try {
$scope.indexPattern.addScriptedField(field, script, 'number');
fieldsAdded++;
} catch (e) {
conflictFields.push(field);
}
});
if (fieldsAdded > 0) {
notify.info(fieldsAdded + ' script fields created');
}
if (conflictFields.length > 0) {
notify.info('Not adding ' + conflictFields.length + ' duplicate fields: ' + conflictFields.join(', '));
}
};
$scope.create = function () {
const params = {
indexPattern: $scope.indexPattern.id
};
kbnUrl.change(fieldCreatorPath, params);
};
$scope.edit = function (field) {
const params = {
indexPattern: $scope.indexPattern.id,
fieldName: field.name
};
kbnUrl.change(fieldEditorPath, params);
};
$scope.remove = function (field) {
const confirmModalOptions = {
confirmButtonText: 'Delete field',
onConfirm: () => { $scope.indexPattern.removeScriptedField(field.name); }
};
confirmModal(`Are you sure want to delete ${field.name}? This action is irreversible!`, confirmModalOptions);
};
$scope.getDeprecatedLanguagesInUse = function () {
const fields = $scope.indexPattern.getScriptedFields();
const langsInUse = _.uniq(_.map(fields, 'lang'));
return _.difference(langsInUse, getSupportedScriptingLangs());
};
}
};
});
|
import {
connecting,
connected,
reconnecting,
connectionFailed
} from './actions';
export default uri => store => {
let ws;
let hasEverConnected = false;
const RECONNECT_TIMEOUT_MS = 2000;
const ACTION = 'ACTION';
const connect = () => {
ws = new WebSocket(uri);
// NOTE: could maybe set a flat 'hasBeenOpenBefore' to help with error states/dispatches and such
ws.onopen = () => {
hasEverConnected = true;
store.dispatch(connected());
};
ws.onclose = function() {
if (hasEverConnected) {
store.dispatch(reconnecting());
setTimeout(connect, RECONNECT_TIMEOUT_MS);
} else {
//TODO: THIS TAKES A LOOOOONG TIME ON CHROME... MAYBE BUILD SOME EXTRA DISPATCHES?
store.dispatch(connectionFailed());
}
};
ws.onmessage = ({data}) => {
const serverAction = JSON.parse(data);
if (serverAction.type == ACTION) {
const localAction = serverAction.payload;
store.dispatch(localAction);
}
};
};
store.dispatch(connecting());
connect();
return next => action => {
if(WebSocket.OPEN === ws.readyState && action.meta && action.meta.remote) {
const serverAction = JSON.stringify({
type: ACTION,
payload: action
});
ws.send(serverAction);
}
return next(action);
};
};
|
import {FkJsListener} from './antlr/FkJsListener';
import {FkJsParser} from './antlr/FkJsParser';
/**
* Obtains a list of modes and mixins from a .fk
* file, as well as other information.
*/
export default class PreProcessor extends FkJsListener {
/**
* @type {string}
*/
defaultMode;
/**
* @type {Object}
*/
mixins = {};
/**
* @type {Object}
*/
modes = {};
/**
*
* @param ctx {FkJsParser.ModeDeclContext}
*/
enterModeDecl(ctx) {
this.modes[ctx.name.text] = ctx;
}
enterMixinDecl(ctx) {
this.mixins[ctx.name.text] = ctx;
}
enterDefaultModeDecl(ctx) {
this.defaultMode = ctx.ID().getText();
}
}
|
/**
* Created by Deathnerd on 1/23/2015.
*/
var gulp = require('gulp');
var usemin = require('gulp-usemin');
var uglify = require('gulp-uglify');
var shell = require('gulp-shell');
var replace = require('gulp-replace');
gulp.task('usemin', function(){
gulp.src(['./src/template.html'])
.pipe(usemin({
js:[uglify(), 'concat']
}))
.pipe(gulp.dest('dist/'));
});
gulp.task('js', function(){
gulp.src(['src/story_js/cookie.js',
'src/story_js/utils.js',
'src/story_js/story.js',
'src/story_js/js.class/js.class.js'])
.pipe(uglify())
.pipe(gulp.dest('dist'));
});
gulp.task('closure', function(){
gulp.src('')
.pipe(shell([
'ccjs dist/story.concat.js > dist/story.min.js'
]));
});
gulp.task('default', function(){
gulp.run('usemin');
gulp.run('closure');
});
|
//~ name b258
alert(b258);
//~ component b259.js
|
var WO = WO || {};
WO.Track = Backbone.Model.extend({
urlRoot: '/api/tracks',
idAttribute: '_id',
defaults: {
notes: "",
title: 'Acoustic Piano',
isMuted: false,
solo: false,
octave: 4,
volume: 0.75,
instrument: "",
type: 'MIDI'
},
initialize : function(){
this.set('notes', []);
this.set('instrument', WO.InstrumentFactory( "Acoustic Piano", this.cid));
WO.instrumentKeyHandler.create(this.get('instrument'));
this.on('changeInstrument', function(instrumentName){this.changeInstrument(instrumentName);}, this);
},
genObjectId: (function() {
function s4() {
return Math.floor((1 + Math.random()) * 0x10000)
.toString(16)
.substring(1);
}
return function() {
return s4() + s4() + s4();
};
})(),
changeInstrument: function(instrumentName) {
var instType = {
'Acoustic Piano': 'MIDI',
'Audio File': 'Audio',
'Microphone': 'Microphone',
'Acoustic Guitar Steel': 'MIDI',
'Alto Sax': 'MIDI',
'Church Organ': 'MIDI',
'Distortion Guitar': 'MIDI',
'Electric Piano 1': 'MIDI',
'Flute': 'MIDI',
'Muted Trumpet': 'MIDI',
'Oboe': 'MIDI',
'Overdriven Guitar': 'MIDI',
'Pad 3 Polysynth': 'MIDI',
'Synth': 'MIDI',
'Synth Bass 1': 'MIDI',
'Synth Strings 2': 'MIDI',
'Viola': 'MIDI',
'Violin': 'MIDI',
'Xylophone': 'MIDI'
};
var previousInstrumentType = this.get('type');
WO.appView.unbindKeys();
this.set('type', instType[instrumentName]);
this.set('title', instrumentName);
if (this.get('type') === 'MIDI') {
this.set('instrument', WO.InstrumentFactory(instrumentName, this));
WO.instrumentKeyHandler.create(this.get('instrument'));
if (previousInstrumentType !== 'MIDI') {
$('.active-track .track-notes').html('');
this.set('mRender', new WO.MidiRender(this.cid + ' .track-notes'));
}
} else {
this.set('notes', []);
$('.active-track .track-notes').html('');
this.set('instrument', WO.InstrumentFactory(instrumentName, this));
}
},
saveTrack: function(){
var instrument = this.get('instrument');
var mRender = this.get('mRender');
this.set('instrument', '');
this.set('mRender', '');
var that = this;
var newlySaveTrack = $.when(that.save()).done(function(){
that.set('instrument', instrument);
that.set('mRender', mRender);
return that;
});
return newlySaveTrack;
}
});
//see what type of instrumetn current serection is
// midi -> mic => remove svg , add mic
// midi -> audio => remove svg , add audio
// midi -> midi => null
// mic -> audio => remove mic , add audio
// mic -> midi => remove mike, add svg
// audio -> mic => remove audio, add mic
// audio -> midi => remove audio, add svg
// keep notes only for midi change to hear different instruments.
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.