text
stringlengths 2
6.14k
|
|---|
/**
* Border Left Radius
*/
module.exports = function (decl, args) {
var radius = args[1] || '3px';
decl.replaceWith({
prop: 'border-bottom-left-radius',
value: radius,
source: decl.source
}, {
prop: 'border-top-left-radius',
value: radius,
source: decl.source
});
};
|
//=====================================================================
// This sample demonstrates using TeslaJS
//
// https://github.com/mseminatore/TeslaJS
//
// Copyright (c) 2016 Mark Seminatore
//
// Refer to included LICENSE file for usage rights and restrictions
//=====================================================================
"use strict";
require('colors');
var program = require('commander');
var framework = require('./sampleFramework.js');
//
//
//
program
.usage('[options]')
.option('-i, --index <n>', 'vehicle index (first car by default)', parseInt)
.option('-U, --uri [string]', 'URI of test server (e.g. http://127.0.0.1:3000)')
.parse(process.argv);
//
var sample = new framework.SampleFramework(program, sampleMain);
sample.run();
//
//
//
function sampleMain(tjs, options) {
var streamingOptions = {
vehicle_id: options.vehicle_id,
authToken: options.authToken
};
console.log("\nNote: " + "Inactive vehicle streaming responses can take up to several minutes.".green);
console.log("\nStreaming starting...".cyan);
console.log("Columns: timestamp," + tjs.streamingColumns.toString());
tjs.startStreaming(streamingOptions, function (error, response, body) {
if (error) {
console.log(error);
return;
}
// display the streaming results
console.log(body);
console.log("...Streaming ended.".cyan);
});
}
|
module.exports = {
dist: {
files: {
'dist/geo.js': ['src/index.js'],
}
}
};
|
var Model = require('./model');
var schema = {
name : String,
stuff: {
electronics: [{
type: String
}],
computing_dev: [{
type: String
}]
},
age:{
biological: Number
},
fruits: [
{
name: String,
fav: Boolean,
about: [{
type: String
}]
}
]
};
var person = function(data){
Model.call(this, schema, data);
}
person.prototype = Object.create(Model.prototype);
module.exports = person;
|
// Depends on jsbn.js and rng.js
// Version 1.1: support utf-8 encoding in pkcs1pad2
// convert a (hex) string to a bignum object
function parseBigInt(str,r) {
return new BigInteger(str,r);
}
function linebrk(s,n) {
var ret = "";
var i = 0;
while(i + n < s.length) {
ret += s.substring(i,i+n) + "\n";
i += n;
}
return ret + s.substring(i,s.length);
}
function byte2Hex(b) {
if(b < 0x10)
return "0" + b.toString(16);
else
return b.toString(16);
}
// PKCS#1 (type 2, random) pad input string s to n bytes, and return a bigint
function pkcs1pad2(s,n) {
if(n < s.length + 11) { // TODO: fix for utf-8
alert("Message too long for RSA");
return null;
}
var ba = new Array();
var i = s.length - 1;
while(i >= 0 && n > 0) {
var c = s.charCodeAt(i--);
if(c < 128) { // encode using utf-8
ba[--n] = c;
}
else if((c > 127) && (c < 2048)) {
ba[--n] = (c & 63) | 128;
ba[--n] = (c >> 6) | 192;
}
else {
ba[--n] = (c & 63) | 128;
ba[--n] = ((c >> 6) & 63) | 128;
ba[--n] = (c >> 12) | 224;
}
}
ba[--n] = 0;
var rng = new SecureRandom();
var x = new Array();
while(n > 2) { // random non-zero pad
x[0] = 0;
while(x[0] == 0) rng.nextBytes(x);
ba[--n] = x[0];
}
ba[--n] = 2;
ba[--n] = 0;
return new BigInteger(ba);
}
// "empty" RSA key constructor
function RSAKey() {
this.n = null;
this.e = 0;
this.d = null;
this.p = null;
this.q = null;
this.dmp1 = null;
this.dmq1 = null;
this.coeff = null;
}
// Set the public key fields N and e from hex strings
function RSASetPublic(N,E) {
if(N != null && E != null && N.length > 0 && E.length > 0) {
this.n = parseBigInt(N,16);
this.e = parseInt(E,16);
}
else
alert("Invalid RSA public key");
}
// Perform raw public operation on "x": return x^e (mod n)
function RSADoPublic(x) {
return x.modPowInt(this.e, this.n);
}
// Return the PKCS#1 RSA encryption of "text" as an even-length hex string
function RSAEncrypt(text) {
var m = pkcs1pad2(text,(this.n.bitLength()+7)>>3);
if(m == null) return null;
var c = this.doPublic(m);
if(c == null) return null;
var h = c.toString(16);
if((h.length & 1) == 0) return h; else return "0" + h;
}
// Return the PKCS#1 RSA encryption of "text" as a Base64-encoded string
function RSAEncryptB64(text) {
var h = this.encrypt(text);
if(h) return hex2b64(h); else return null;
}
// protected
RSAKey.prototype.doPublic = RSADoPublic;
// public
RSAKey.prototype.setPublic = RSASetPublic;
RSAKey.prototype.encrypt = RSAEncrypt;
RSAKey.prototype.encrypt_b64 = RSAEncryptB64;
//my encrypt function, using fixed mudulus
var modulus = "BEB90F8AF5D8A7C7DA8CA74AC43E1EE8A48E6860C0D46A5D690BEA082E3A74E1"
+"571F2C58E94EE339862A49A811A31BB4A48F41B3BCDFD054C3443BB610B5418B"
+"3CBAFAE7936E1BE2AFD2E0DF865A6E59C2B8DF1E8D5702567D0A9650CB07A43D"
+"E39020969DF0997FCA587D9A8AE4627CF18477EC06765DF3AA8FB459DD4C9AF3";
var publicExponent = "10001";
function MyRSAEncryptB64(text)
{
var rsa = new RSAKey();
rsa.setPublic(modulus, publicExponent);
return rsa.encrypt_b64(text);
}
|
import React, { PureComponent } from "react";
import { graphql } from 'gatsby'
import Link from "gatsby-link";
import path from "ramda/src/path";
import ScrollReveal from "scrollreveal";
import Layout from "../components/Layout";
import "prismjs/themes/prism.css";
import styles from "./post.module.scss";
const getPost = path(["data", "markdownRemark"]);
const getContext = path(["pageContext"]);
const PostNav = ({ prev, next }) => (
<div className={styles.postNav}>
{prev && (
<Link to={`/${prev.fields.slug}`}>
上一篇:
{prev.frontmatter.title}
</Link>
)}
{next && (
<Link to={`/${next.fields.slug}`}>
下一篇:
{next.frontmatter.title}
</Link>
)}
</div>
);
export default class Post extends PureComponent {
componentDidMount() {
ScrollReveal().reveal(".article-header>h1", {
delay: 500,
useDelay: "onload",
reset: true,
origin: "top",
distance: "120px"
});
ScrollReveal().reveal(".article-content", {
delay: 500,
useDelay: "onload",
reset: true,
origin: "bottom",
distance: "120px"
});
}
componentWillUnmount() {
ScrollReveal().destroy();
}
render() {
const post = getPost(this.props);
const { next, prev } = getContext(this.props); // Not to be confused with react context...
return (
<Layout>
<header className="article-header">
<h1>{post.frontmatter.title}</h1>
</header>
<div
className="article-content"
dangerouslySetInnerHTML={{ __html: post.html }}
/>
<PostNav prev={prev} next={next} />
</Layout>
);
}
}
export const query = graphql`
query BlogPostQuery($slug: String!) {
markdownRemark(fields: { slug: { eq: $slug } }) {
html
frontmatter {
title
}
}
}
`;
|
import React, {Component} from 'react';
import {View, Text} from 'react-native';
import {xdateToData} from '../../interface';
import XDate from 'xdate';
import dateutils from '../../dateutils';
import styleConstructor from './style';
class ReservationListItem extends Component {
constructor(props) {
super(props);
this.styles = styleConstructor(props.theme);
}
shouldComponentUpdate(nextProps) {
const r1 = this.props.item;
const r2 = nextProps.item;
let changed = true;
if (!r1 && !r2) {
changed = false;
} else if (r1 && r2) {
if (r1.day.getTime() !== r2.day.getTime()) {
changed = true;
} else if (!r1.reservation && !r2.reservation) {
changed = false;
} else if (r1.reservation && r2.reservation) {
if ((!r1.date && !r2.date) || (r1.date && r2.date)) {
changed = this.props.rowHasChanged(r1.reservation, r2.reservation);
}
}
}
return changed;
}
renderDate(date, item) {
if (this.props.renderDay) {
return this.props.renderDay(date ? xdateToData(date) : undefined, item);
}
const today = dateutils.sameDate(date, XDate()) ? this.styles.today : undefined;
if (date) {
return (
<View style={this.styles.day}>
<Text style={[this.styles.dayNum, today]}>{date.getDate()}</Text>
<Text style={[this.styles.dayText, today]}>{XDate.locales[XDate.defaultLocale].dayNamesShort[date.getDay()]}</Text>
</View>
);
} else {
return (
<View style={this.styles.day}/>
);
}
}
render() {
const {reservation, date} = this.props.item;
let content;
if (reservation) {
const firstItem = date ? true : false;
content = this.props.renderItem(reservation, firstItem);
} else {
content = this.props.renderEmptyDate(date);
}
return (
<View style={this.styles.container}>
{this.renderDate(date, reservation)}
<View style={{flex:1}}>
{content}
</View>
</View>
);
}
}
export default ReservationListItem;
|
/*global module:false*/
module.exports = function(grunt) {
// Project configuration.
grunt.initConfig({
// Metadata.
pkg: grunt.file.readJSON('package.json'),
banner: '/*! <%= pkg.title || pkg.name %> - v<%= pkg.version %> - ' +
'<%= grunt.template.today("yyyy-mm-dd") %>\n' +
'<%= pkg.homepage ? "* " + pkg.homepage + "\\n" : "" %>' +
'* Copyright (c) <%= grunt.template.today("yyyy") %> <%= pkg.author.name %>;' +
' Licensed <%= _.pluck(pkg.licenses, "type").join(", ") %> */\n',
// Task configuration.
concat: {
options: {
banner: '<%= banner %>',
stripBanners: true
},
dist: {
src: ['lib/<%= pkg.name %>.js'],
dest: 'dist/<%= pkg.name %>.js'
}
},
uglify: {
options: {
banner: '<%= banner %>'
},
dist: {
src: '<%= concat.dist.dest %>',
dest: 'dist/<%= pkg.name %>.min.js'
}
},
jshint: {
options: {
curly: true,
eqeqeq: true,
immed: true,
latedef: true,
newcap: true,
noarg: true,
sub: true,
undef: true,
unused: true,
boss: true,
eqnull: true,
browser: true,
globals: {
jQuery: true
}
},
gruntfile: {
src: 'Gruntfile.js'
},
lib_test: {
src: ['lib/**/*.js', 'test/**/*.js']
}
},
qunit: {
files: ['test/**/*.html']
},
watch: {
gruntfile: {
files: '<%= jshint.gruntfile.src %>',
tasks: ['jshint:gruntfile']
},
lib_test: {
files: '<%= jshint.lib_test.src %>',
tasks: ['jshint:lib_test', 'qunit']
},
stylesheets: {
files: 'stylesheets/sass/**/*.scss',
tasks:['sass:dist']
}
},
sass: {
dist: {
files: [{
expand: true,
cwd: 'stylesheets/sass/project',
src: ['*.scss'],
dest: 'stylesheets/styles',
ext: '.css'
}]
}
}
});
// These plugins provide necessary tasks.
//grunt.loadNpmTasks('grunt-contrib-concat');
//grunt.loadNpmTasks('grunt-contrib-uglify');
//grunt.loadNpmTasks('grunt-contrib-qunit');
//grunt.loadNpmTasks('grunt-contrib-jshint');
grunt.loadNpmTasks('grunt-contrib-watch');
grunt.loadNpmTasks('grunt-contrib-sass');
// Default task.
//grunt.registerTask('default', ['jshint', 'qunit', 'concat', 'uglify']);
};
|
version https://git-lfs.github.com/spec/v1
oid sha256:2566f139073c240a090aee1fb4254ec2b799a9402dd6494447afbe4e12c97654
size 6184
|
import React from 'react'
export default class NoteItem extends React.Component {
render () {
return (
<div>
<p>Category = {this.props.note.category}</p>
<p>The Note = {this.props.note.noteText}</p>
<hr />
</div>
)
}
}
|
///<reference path="./otmword.ts" />
///<reference path="./wmmodules.ts" />
///<reference path="./wgenerator.ts" />
///<reference path="./ntdialog.ts" />
/**
* 単語作成部で使用するViewModel
*/
class WordDisplayVM {
/**
* コンストラクタ
* @param el バインディングを適用するタグのid
* @param dict OTM形式辞書クラス
* @param createSetting 単語文字列作成に使用する設定
*/
constructor(el, dict, createSetting, equivalent) {
this.el = el;
this.data = {
dictionary: dict,
isDisabled: false,
createSetting: createSetting,
id: 1,
equivalent: equivalent,
};
this.initMethods();
}
/**
* VMで使用するメソッドを定義するメソッド
*/
initMethods() {
this.methods = {
/**
* 単語文字列を作成するメソッド
*/
create: function _create() {
let form = "";
switch (this.createSetting.mode) {
case WordGenerator.SIMPLE_SYMBOL:
form = WordGenerator.simple(this.createSetting.simple);
break;
case WordGenerator.SIMPLECV_SYMBOL:
form = WordGenerator.simplecv(this.createSetting.simplecv);
break;
case WordGenerator.DEPENDENCYCV_SYMBOL:
form = WordGenerator.dependencycv(this.createSetting.dependencycv);
break;
default:
break;
}
let word = new OtmWord(this.id++, form);
word.add("");
this.dictionary.add(word);
},
/**
* 設定されている全ての訳語に対して単語を作成するメソッド
*/
createAll: function _createAll() {
this.equivalent.equivalentsList.data.forEach((x) => {
let form = "";
switch (this.createSetting.mode) {
case WordGenerator.SIMPLE_SYMBOL:
form = WordGenerator.simple(this.createSetting.simple);
break;
case WordGenerator.SIMPLECV_SYMBOL:
form = WordGenerator.simplecv(this.createSetting.simplecv);
break;
case WordGenerator.DEPENDENCYCV_SYMBOL:
form = WordGenerator.dependencycv(this.createSetting.dependencycv);
break;
default:
break;
}
let word = new OtmWord(this.id++, form);
word.add(x.equivalents.join(","));
this.dictionary.add(word);
});
},
/**
* 作成した全ての単語を削除するメソッド
*/
removeAll: function _removeAll() {
this.dictionary.removeAll();
// idを初期値にする
this.id = 1;
},
/**
* 作成した単語一覧をOTM-JSON形式で出力するメソッド
*/
outputOtmJSON: function _outputOtmJSON() {
// idを振り直す
let id = 1;
this.dictionary.words.forEach((x) => {
x.entry.id = id++;
});
WMModules.exportJSON(this.dictionary, "dict.json");
// 引き続き作成する場合を考えてidを更新する
this.id = id;
},
// 個々で使用する部分
/**
* 訳語選択ダイアログを呼び出すメソッド
* @param 訳語を設定する単語クラス
*/
showEquivalentDialog: function _showEquivalentDialog(word) {
this.equivalent.selectedWordId = word.entry.id.toString();
WMModules.equivalentDialog.show();
},
/**
* 単語を削除するメソッド
* @param 削除する単語クラス
*/
remove: function _remove(word) {
this.dictionary.remove(word.entry.id);
},
/**
* 単語の区切りの","で文字列を区切って配列にするためのメソッド
* @param 単語の訳語(カンマ区切り)
* @return カンマを区切り文字として分割した結果の文字列配列
*/
splitter: function _splitter(value) {
return value.split(",").map(function (x) { return x.trim(); });
},
};
}
}
//# sourceMappingURL=worddisplayvm.js.map
|
var CategoryLevel = function(){
'use strict';
var categorys = {};
this.addCategory = function(_name) {
categorys[_name] = [];
};
this.addDataToLastCategory = function(_categoryName, _lineData, _className) {
var category = categorys[_categoryName];
};
};
|
define(function(){
var config = {};
config.app = 'pregapp'; // Your App name
//config.jqueryMobileTheme = "/francine/css/theme.css";
//config.jqueryMobilePath="/francine/js/jquery.mobile-1.2.0";
//config.jqueryMobileCss="/francine/css/mobile.css";
config.extraScripts = [];
config.quickformsEnding = ""; // "" or ".asp"
config.defaultPageTransition = "none"; // slide, pop, none
config.defaultDialogTransition = "none"; // slide, pop, none
return config;
});
|
describe('A Feature', function() {
it('A Scenario', function() {
// ### Given missing code
});
});
|
$(document).ready(function(){
//The user will be prompted to continue and go down the page by clicking on an HTML element
//The result will be a smooth transition of the word ">>>Continue" and then a smooth scroll down the page
//to the next stage of the user's process in the application: making an account(probably done through Google and Facebook)
$(document).ready(function(){
$('#userPrompt>span:nth-child(1)').delay(350).fadeTo(450,1.0);
$('#userPrompt>span:nth-child(2)').delay(450).fadeTo(450,1.0);
$('#userPrompt>span:nth-child(3)').delay(550).fadeTo(450,1.0); //this div represents the bottom option, or the 'quick presentation div'
$('#Continue').delay(700).fadeTo(850,1.0); //Continue button
});
/*$('#userPrompt').click(function(){
$('#promptOverlay').fadeTo(850,0.0);
$(this).delay(850).animate({marginLeft: '900px'}, 850)
$(this).delay(100).fadeOut(850);
});
The "#promptOverlay" div is not longer in use, and as a result, we do not need to use this line of code...
Let's keep things....simpler...
*/
$('#userPrompt').one("click",function(){
$(this).fadeTo(850,0);
//Scroll Down
var height = $("#navBar").css('height');
$('html , body').animate({
scrollTop: 725
}, 1250);
//Create Options on Options Bar div, first by making a dividing line
$('#imagine').delay(1250).animate({
height: '330px'
});
//Create Third option by making it now visible...
$('#quick').delay(1850).fadeTo(300, 1);
//Time to make options visible...
$('.heading').delay(2000).fadeTo(300, 1);
});
//With options now created, we can create some functionality to those options, making the user's experience both meaningful and aesthetically pleasing.
/*$('#returner, #imagine').click(function(){
//alert("Log into account"); Test
$('.heading').fadeTo(850, 0);
$('#quick').fadeOut();
$('#imagine').delay(250).animate({
height: '0px'
});
$('#optionsBar').delay(1400).css("background-color", "rgb(215,215,215)");
$('#optionsBar');
});*/
/*$('#newUser').one("click", function(){
//alert("Make account"); Test
$('#optionsBar>div').fadeOut(850);
$('#optionsBar').delay(1400).css("background-color", "rgb(215,215,215)");
var welcomeHeader = '<h3 margin-top="20px" class="heading">Welcome to ShowCase. Please Log In Below...</h3>';
var inputTypeOne = '<input type="text/plain">keep'
//$('h3').delay(1900).html("Welcome to ShowCase. Please Log In Below...").appendTo("#optionsBar");
$(welcomeHeader).hide().delay(2000).appendTo('#optionsBar').fadeIn(100);
var styles = {
fontFamily: 'Lato',
color: 'rgba(16,16,14,0.65)',
paddingTop: '10px',
};
// $(welcomeHeader).css(headerStyle);
$('#optionsBar').css(styles);
});//End of Account Creation Process...*
$('#quick').click(function(){
//alert("I just don't care."); Test
$('.heading').fadeTo(850, 0);
$('#quick').fadeOut();
$('#imagine').delay(250).animate({
height: '0px'
});
$('#optionsBar').delay(1400).css("background-color", "rgb(215,215,215)");
});*/
});
|
import AnswerRating from './answerRating';
import FeedBackResults from './feedbackResults';
import './less/feedback.less';
// Check if bar rating should be initialized
const ratingWrapper = document.querySelector('.rating-wrapper');
if (ratingWrapper !== null) {
AnswerRating();
}
// Check if feed back results charts should be initialized
const feedBackResultsElement = document.getElementById('feedback-results');
if (feedBackResultsElement !== null) {
FeedBackResults();
}
|
function initialize(grunt) {
grunt.initConfig({
pkg: grunt.file.readJSON('package.json'),
exec: {
build: {
command: 'make build'
},
// 'build-types': { command: 'make build-types' },
'build-style': { command: 'make build-style' },
'build-server': { command: 'make build-server' },
'build-client': { command: 'make build-client' },
// 'database-shell': {
// command: "echo 'mongo --username client --password testing christian.mongohq.com:10062/Beta-CitizenDish'"
// }
},
watch: {
types: {
files: [ 'types/egyptian-number-system.d.ts'],
tasks: [ 'exec:build-types'],
spawn: false
},
style: {
files: [ 'style/less/*.less', 'style/less/**/*.less','public/less/**/*.less' ],
tasks: [ 'exec:build-style'],
spawn: false
},
server: {
files: [ 'server/**/*.ts', 'server/*.ts', ],
tasks: [ 'exec:build-server' ],
spawn: false
},
client: {
files: [ 'client/**/*.ts', 'client/*.ts'],
tasks: [ 'exec:build-client' ],
spawn: false
}
},
nodemon: {
application: {
script: 'server/api.js',
options: {
ext: 'js',
watch: ['server'],
ignore: ['server/**'],
delay: 2000,
legacyWatch: false
}
},
developer: {
script: 'server/developer-api.js',
options: {
ext: 'js',
watch: ['server'],
// ignore: ['server/**'],
delay: 3000,
legacyWatch: false
}
}
} ,
concurrent: {
options: {
logConcurrentOutput: true
},
developer: {
tasks: [ 'exec:build', 'nodemon:developer', 'watch:style', 'watch:server', 'watch:client' ]
// tasks: [ 'exec:build', 'nodemon:server', 'watch:types', 'watch:style', 'watch:server', 'watch:client' ]
},
application: {
tasks: [ 'exec:build', 'nodemon:application', 'watch:style', 'watch:server', 'watch:client' ]
// tasks: [ 'exec:build', 'nodemon:server', 'watch:types', 'watch:style', 'watch:server', 'watch:client' ]
}
}
}) ;
grunt.loadNpmTasks('grunt-exec');
grunt.loadNpmTasks('grunt-nodemon');
grunt.loadNpmTasks('grunt-contrib-watch');
grunt.loadNpmTasks('grunt-concurrent');
grunt.registerTask('default', ['concurrent:application']) ;
grunt.registerTask('developer', ['concurrent:developer']) ;
grunt.option('debug', true);
// grunt.option('force', true);
}
module.exports = initialize;
|
const should = require('should');
const MissionLog = require('../lib/log').MissionLog;
const Severity = require('../lib/Severity');
describe('MissionLog', function () {
it('should test the properties', function () {
const Log = new MissionLog();
Log.should.have.property('severities').with.lengthOf(5);
Log.should.have.property('defaultSeverity');
});
it('should return the default severity', function () {
const Log = new MissionLog();
Log.getDefaultSeverity().name.should.be.equal('VERBOSE');
const severities = Log.getSeverities();
should(severities.length).be.equal(5);
});
it('should add a new severity', function() {
const severityName = 'Test123123';
const newSeverity = new Severity(severityName);
const Log = new MissionLog();
Log.addSeverity(newSeverity);
const severities = Log.getSeverities();
const length = severities.length;
should(length).be.equal(6);
should(severities[5].name).be.equal(severityName.toUpperCase());
});
it('should switch the default severity', function() {
const newSeverity = new Severity('Test');
const Log = new MissionLog();
Log.setDefaultSeverity(newSeverity);
const defaultSeverity = Log.getDefaultSeverity();
should(defaultSeverity.name).equal(newSeverity.name);
});
it('should try to add a severity twice', function() {
const firstSeverity = new Severity('UnitTesting');
const secondSeverity = new Severity('UnitTesting');
const Log = new MissionLog();
const preCount = Log.getSeverities().length;
Log.addSeverity(firstSeverity);
const afterFirst = Log.getSeverities().length;
Log.addSeverity(secondSeverity);
const afterSecond = Log.getSeverities().length;
should(afterFirst).be.equal(afterSecond);
});
it('should log using verbose severity', function () {
const Log = new MissionLog();
Log.log('VERBOSE', 'test');
});
});
|
const { getURL, sockets } = require('../common/configuration.js');
const io = require('socket.io-client');
const os = require('os');
const socket = io.connect(getURL(sockets.measures), {
query: `id=${os.hostname()}&cores=${os.cpus().length}`
});
setInterval(() => {
socket.emit('new.load', {
load: os.loadavg(),
timestamp: new Date().getTime()
});
}, 5000);
|
import React from 'react'
import { mount, shallow, render } from 'enzyme'
import { Stepper } from './Stepper'
import Step from './Stepper.Step'
import { StepUI, StepperUI } from './Stepper.css'
const mockSteps = [
{
id: 'Id1',
title: 'Test Title 1',
},
{
id: 'Id2',
title: 'Test Title 2',
},
{
id: 'Id3',
title: 'Test Title 3',
},
{
id: 'Id4',
title: 'Test Title 4',
},
]
describe('className', () => {
test('Has default className', () => {
const wrapper = render(<Stepper />)
expect(wrapper.hasClass('c-Stepper')).toBeTruthy()
})
test('Can render custom className', () => {
const customClassName = 'blue'
const wrapper = render(<Stepper className={customClassName} />)
expect(wrapper.hasClass(customClassName)).toBeTruthy()
})
})
describe('HTML props', () => {
test('Can render default HTML props', () => {
const wrapper = render(<Stepper data-cy="blue" />)
expect(wrapper.attr('data-cy')).toBe('blue')
})
})
describe('children', () => {
test('should have a child component for each step', () => {
const wrapper = mount(<Stepper steps={mockSteps} currentIndex={0} />)
const steps = wrapper.find(Step)
expect(steps.length).toEqual(4)
})
test('should assign proper isActive state to each step', () => {
const wrapper = mount(<Stepper steps={mockSteps} currentIndex={2} />)
wrapper.update()
const steps = wrapper.find(StepUI)
let results = []
steps.forEach(step => {
results.push(step.hasClass('is-active'))
})
expect(results[0]).toEqual(true)
expect(results[1]).toEqual(true)
expect(results[2]).toEqual(true)
expect(results[3]).toEqual(false)
})
})
describe('callbacks', () => {
test('should call callbacks', () => {
const onChangeSpy = jest.fn()
const onCompleteSpy = jest.fn()
const wrapper = mount(
<Stepper
onChange={onChangeSpy}
onComplete={onCompleteSpy}
currentIndex={0}
steps={mockSteps}
/>
)
expect(onChangeSpy).toHaveBeenCalledTimes(0)
expect(onCompleteSpy).toHaveBeenCalledTimes(0)
wrapper.setProps({ currentIndex: 1 })
expect(onChangeSpy).toHaveBeenCalledTimes(1)
expect(onCompleteSpy).toHaveBeenCalledTimes(0)
wrapper.setProps({ currentIndex: 2 })
expect(onChangeSpy).toHaveBeenCalledTimes(2)
expect(onCompleteSpy).toHaveBeenCalledTimes(0)
wrapper.setProps({ currentIndex: 3 })
expect(onChangeSpy).toHaveBeenCalledTimes(3)
expect(onCompleteSpy).toHaveBeenCalledTimes(1)
})
test('should call onStepClick callback', () => {
const onStepClickSpy = jest.fn()
const wrapper = shallow(
<Stepper steps={mockSteps} onStepClick={onStepClickSpy} />
)
wrapper
.find(Step)
.at(0)
.simulate('click')
expect(onStepClickSpy).toHaveBeenCalledTimes(1)
})
})
describe('StepperUI', () => {
test('should return the correct value for getProgress', () => {
const wrapper = mount(<Stepper steps={mockSteps} currentIndex={2} />)
expect(wrapper.find(StepperUI).prop('aria-valuenow')).toEqual(3)
})
})
describe('getProgress', () => {
test('should equal 2', () => {
const wrapper = mount(<Stepper steps={mockSteps} currentIndex={1} />)
expect(wrapper.instance().getProgress()).toEqual(2)
})
test('when no currentIndex is null, kkshould return 1', () => {
const wrapper = mount(<Stepper currentIndex={null} />)
expect(wrapper.instance().getProgress()).toEqual(1)
})
})
describe('getMatchIndex', () => {
test('should return 1', () => {
const wrapper = mount(<Stepper currentIndex={1} />)
expect(wrapper.instance().getMatchIndex()).toEqual(1)
})
test('when no currentIndex defined should return 0', () => {
const wrapper = mount(<Stepper currentIndex={null} />)
expect(wrapper.instance().getMatchIndex()).toEqual(-1)
})
})
describe('componentDidUpdate', () => {
test('should call onChange callback', () => {
const onChangeSpy = jest.fn()
const wrapper = mount(
<Stepper onChange={onChangeSpy} steps={mockSteps} currentIndex={1} />
)
wrapper.instance().componentDidUpdate({ currentIndex: 0 })
expect(onChangeSpy).toHaveBeenCalled()
})
test('should not call onChange callback', () => {
const onChangeSpy = jest.fn()
const wrapper = mount(
<Stepper onChange={onChangeSpy} steps={mockSteps} currentIndex={1} />
)
wrapper.instance().componentDidUpdate({ currentIndex: 1 })
expect(onChangeSpy).not.toHaveBeenCalled()
})
})
describe('handleChangeCallback', () => {
test('should not call onChange', () => {
const onChangeSpy = jest.fn()
const wrapper = mount(
<Stepper onChange={onChangeSpy} steps={[]} currentIndex={1} />
)
wrapper.instance().handleChangeCallback()
expect(onChangeSpy).not.toHaveBeenCalled()
})
})
describe('Step className', () => {
test('should call click handler if isClickable is true', () => {
const onClickSpy = jest.fn()
const wrapper = mount(<Step isClickable={true} onClick={onClickSpy} />)
wrapper
.find('.c-StepperStep')
.at(0)
.simulate('click')
expect(onClickSpy).toHaveBeenCalledTimes(1)
})
test('should NOT call click handler if isClickable is false', () => {
const onClickSpy = jest.fn()
const wrapper = mount(<Step isClickable={false} onClick={onClickSpy} />)
wrapper
.find('.c-StepperStep')
.at(0)
.simulate('click')
expect(onClickSpy).toHaveBeenCalledTimes(0)
})
})
|
module.exports = middleware;
var states = {
STANDBY: 0,
BUSY: 1
};
function middleware(options) {
var regio = require('regio'),
tessel = require('tessel'),
camera = require('camera-vc0706').use(tessel.port[options.port]),
app = regio.router(),
hwReady = false,
current;
camera.on('ready', function() {
hwReady = true;
current = states.STANDBY;
});
app.get('/', handler);
function handler(req, res) {
if (hwReady) {
if (current === states.STANDBY) {
current = states.BUSY;
camera.takePicture(function (err, image) {
res.set('Content-Type', 'image/jpeg');
res.set('Content-Length', image.length);
res.status(200).end(image);
current = states.STANDBY;
});
} else {
res.set('Retry-After', 100);
res.status(503).end();
}
} else {
res.status(503).end();
}
}
return app;
}
|
'use strict';
var ObjectUtil, self;
module.exports = ObjectUtil = function () {
self = this;
};
/**
* @method promiseWhile
* @reference http://blog.victorquinn.com/javascript-promise-while-loop
*/
ObjectUtil.prototype.promiseWhile = function () {
};
|
var assert = require('chai').assert;
var Pad = require('../lib/pad');
describe('Pad', function() {
it('should be an object', function() {
var pad = new Pad();
assert.isObject(pad);
});
it('should have a x coordinate of 310 by default', function() {
var terminator = new Pad();
assert.equal(terminator.x, 310);
});
it('should have a y coordinate of 470 by default', function() {
var jon = new Pad();
assert.equal(jon.y, 470);
});
it('should have a r value of 23 by default', function() {
var terminator = new Pad();
assert.equal(terminator.r, 23);
});
it('should have a sAngle value of 0 by default', function() {
var jon = new Pad();
assert.equal(jon.sAngle, 0);
});
it('should have an eAngle value of 2*Math.PI by default', function() {
var jon = new Pad();
assert.equal(jon.eAngle, 2*Math.PI);
});
it('should have a draw function', function(){
var jon = new Pad();
assert.isFunction(jon.draw);
});
});
|
version https://git-lfs.github.com/spec/v1
oid sha256:fd2ad8a08df37f7b13dad35da22197faf51ef6887162bf5f74ce30df59fdba0f
size 15638
|
const R = require('ramda');
const {thread} = require('davis-shared').fp;
const DataLoader = require('dataloader');
const Task = require('data.task');
const Async = require('control.async')(Task);
const when = require('when');
const task2Promise = Async.toPromise(when.promise);
module.exports = (entityRepository, entityTypes) => thread(entityTypes,
R.map(entityType => ([
entityType,
new DataLoader(ids => task2Promise(
entityRepository.queryById(entityType, ids).map(entities => {
const indexedEntities = R.indexBy(R.prop('id'), entities);
return ids.map(R.propOr(null, R.__, indexedEntities));
})))])),
R.fromPairs);
|
version https://git-lfs.github.com/spec/v1
oid sha256:b63ef97b9f85b0d4a07926b186083c9952568e26bbb65d610b592d15208f79a9
size 24953
|
/* globals Promise:true */
var _ = require('lodash')
var EventEmitter = require('events').EventEmitter
var inherits = require('util').inherits
var LRU = require('lru-cache')
var Promise = require('bluebird')
var Snapshot = require('./snapshot')
var errors = require('../errors')
var util = require('../util')
/**
* @event Blockchain#error
* @param {Error} error
*/
/**
* @event Blockchain#syncStart
*/
/**
* @event Blockchain#syncStop
*/
/**
* @event Blockchain#newBlock
* @param {string} hash
* @param {number} height
*/
/**
* @event Blockchain#touchAddress
* @param {string} address
*/
/**
* @class Blockchain
* @extends events.EventEmitter
*
* @param {Connector} connector
* @param {Object} [opts]
* @param {string} [opts.networkName=livenet]
* @param {number} [opts.txCacheSize=100]
*/
function Blockchain (connector, opts) {
var self = this
EventEmitter.call(self)
opts = _.extend({
networkName: 'livenet',
txCacheSize: 100
}, opts)
self.connector = connector
self.networkName = opts.networkName
self.latest = {hash: util.zfill('', 64), height: -1}
self._txCache = LRU({max: opts.txCacheSize, allowSlate: true})
self._isSyncing = false
self.on('syncStart', function () { self._isSyncing = true })
self.on('syncStop', function () { self._isSyncing = false })
}
inherits(Blockchain, EventEmitter)
Blockchain.prototype._syncStart = function () {
if (!this.isSyncing()) this.emit('syncStart')
}
Blockchain.prototype._syncStop = function () {
if (this.isSyncing()) this.emit('syncStop')
}
/**
* @param {errors.Connector} err
* @throws {errors.Connector}
*/
Blockchain.prototype._rethrow = function (err) {
var nerr
switch (err.name) {
case 'ErrorBlockchainJSConnectorHeaderNotFound':
nerr = new errors.Blockchain.HeaderNotFound()
break
case 'ErrorBlockchainJSConnectorTxNotFound':
nerr = new errors.Blockchain.TxNotFound()
break
case 'ErrorBlockchainJSConnectorTxSendError':
nerr = new errors.Blockchain.TxSendError()
break
default:
nerr = err
break
}
nerr.message = err.message
throw nerr
}
/**
* Return current syncing status
*
* @return {boolean}
*/
Blockchain.prototype.isSyncing = function () {
return this._isSyncing
}
/**
* @return {Promise<Snapshot>}
*/
Blockchain.prototype.getSnapshot = function () {
return Promise.resolve(new Snapshot(this))
}
/**
* @abstract
* @param {(number|string)} id height or hash
* @return {Promise<Connector~HeaderObject>}
*/
Blockchain.prototype.getHeader = function () {
return Promise.reject(new errors.NotImplemented('Blockchain.getHeader'))
}
/**
* @abstract
* @param {string} txid
* @return {Promise<string>}
*/
Blockchain.prototype.getTx = function () {
return Promise.reject(new errors.NotImplemented('Blockchain.getTx'))
}
/**
* @typedef {Object} Blockchain~TxBlockHashObject
* @property {string} source `blocks` or `mempool`
* @property {Object} [block] defined only when source is blocks
* @property {string} data.hash
* @property {number} data.height
*/
/**
* @abstract
* @param {string} txid
* @return {Promise<Blockchain~TxBlockHashObject>}
*/
Blockchain.prototype.getTxBlockHash = function () {
return Promise.reject(new errors.NotImplemented('Blockchain.getTxBlockHash'))
}
/**
* @abstract
* @param {string} rawtx
* @return {Promise<string>}
*/
Blockchain.prototype.sendTx = function () {
return Promise.reject(new errors.NotImplemented('Blockchain.sendTx'))
}
/**
* @abstract
* @param {string[]} addresses
* @param {Object} [opts]
* @param {string} [opts.source] `blocks` or `mempool`
* @param {(string|number)} [opts.from] `hash` or `height`
* @param {(string|number)} [opts.to] `hash` or `height`
* @param {string} [opts.status]
* @return {Promise<Connector~AddressesQueryObject>}
*/
Blockchain.prototype.addressesQuery = function () {
return Promise.reject(new errors.NotImplemented('Blockchain.addressesQuery'))
}
/**
* @abstract
* @param {string} address
* @return {Promise}
*/
Blockchain.prototype.subscribeAddress = function () {
return Promise.reject(new errors.NotImplemented('Blockchain.subscribeAddress'))
}
module.exports = Blockchain
|
import React, { Component } from 'react';
import { connect } from 'react-redux';
import { StyleSheet, css } from 'aphrodite';
import { changeTimeSignature } from '../../actions/track';
import HoverableText from './HoverableText';
const styles = StyleSheet.create({
text: {
fontFamily: 'Optima, Segoe, Segoe UI, Candara, Calibri, Arial, sans-serif'
},
popoverContainer: {
background: '#FEFBF7',
height: 200,
display: 'flex',
flexDirection: 'column',
justifyContent: 'space-between'
},
templateRow: {
display: 'flex',
justifyContent: 'space-around',
paddingTop: 10
},
timeSigRow: { display: 'flex', justifyContent: 'center', flexShrink: 10 },
checkboxRow: {
display: 'flex',
justifyContent: 'space-around',
paddingBottom: 10,
paddingLeft: 5,
paddingRight: 5
},
beats: {
display: 'flex',
flexDirection: 'column',
justifyContent: 'center',
paddingTop: 15,
alignItems: 'flex-end',
flexBasis: '55%'
},
beatType: {
display: 'flex',
flexDirection: 'column',
justifyContent: 'center',
paddingBottom: 15,
alignItems: 'flex-end',
flexBasis: '55%'
},
numberText: { fontSize: 40, paddingRight: 10 },
topArrows: {
display: 'flex',
flexDirection: 'column',
justifyContent: 'center',
paddingTop: 15,
flexBasis: '45%'
},
bottomArrows: {
display: 'flex',
flexDirection: 'column',
justifyContent: 'center',
paddingBottom: 15,
flexBasis: '45%'
},
checkboxText: { fontWeight: 300, fontSize: 12, paddingTop: 3 }
});
class TimeSignaturePopover extends Component {
constructor(props) {
super(props);
this.state = {
timeSignature: Object.assign({}, props.timeSignature),
toEndChecked: false,
allChecked: false
};
}
componentWillUnmount() {
const { timeSignature, toEndChecked, allChecked } = this.state;
this.props.changeTimeSignature(
{ measureIndex: this.props.measureIndex },
timeSignature,
toEndChecked,
allChecked
);
}
onTwoFourClick = () => {
// TODO extract these things into a component
this.setState({ timeSignature: { beats: 2, beatType: 4 } });
};
onFourFourClick = () => {
this.setState({ timeSignature: { beats: 4, beatType: 4 } });
};
onSixEightClick = () => {
this.setState({ timeSignature: { beats: 6, beatType: 8 } });
};
onIncrementBeats = () => {
if (this.state.timeSignature.beats < 32) {
this.setState({
timeSignature: {
beats: this.state.timeSignature.beats + 1,
beatType: this.state.timeSignature.beatType
}
});
}
};
onIncrementBeatType = () => {
if (this.state.timeSignature.beatType < 32) {
this.setState({
timeSignature: {
beats: this.state.timeSignature.beats,
beatType: this.state.timeSignature.beatType * 2
}
});
}
};
onDecrementBeats = () => {
if (this.state.timeSignature.beats > 1) {
this.setState({
timeSignature: {
beats: this.state.timeSignature.beats - 1,
beatType: this.state.timeSignature.beatType
}
});
}
};
onDecrementBeatType = () => {
if (this.state.timeSignature.beatType > 1) {
this.setState({
timeSignature: {
beats: this.state.timeSignature.beats,
beatType: this.state.timeSignature.beatType / 2
}
});
}
};
toEndChanged = () => {
this.setState({ toEndChecked: !this.state.toEndChecked });
};
allChanged = () => {
this.setState({ allChecked: !this.state.allChecked });
};
render() {
return (
<div className={css(styles.popoverContainer)}>
<span className={css(styles.templateRow)}>
<HoverableText onClick={this.onTwoFourClick} text="2/4" />
<HoverableText onClick={this.onFourFourClick} text="4/4" />
<HoverableText onClick={this.onSixEightClick} text="6/8" />
</span>
<div className={css(styles.timeSigRow)}>
<span className={css(styles.beats)}>
<h3 className={css(styles.text, styles.numberText)}>
{this.state.timeSignature.beats}
</h3>
</span>
<span className={css(styles.topArrows)}>
<HoverableText onClick={this.onIncrementBeats} text="▲" />
<HoverableText onClick={this.onDecrementBeats} text="▼" />
</span>
</div>
<div className={css(styles.timeSigRow)}>
<span className={css(styles.beatType)}>
<h3 className={css(styles.text, styles.numberText)}>
{this.state.timeSignature.beatType}
</h3>
</span>
<span className={css(styles.bottomArrows)}>
<HoverableText onClick={this.onIncrementBeatType} text="▲" />
<HoverableText onClick={this.onDecrementBeatType} text="▼" />
</span>
</div>
<span className={css(styles.checkboxRow)}>
<small className={css(styles.text, styles.checkboxText)}>
To End
</small>
<input
type="checkbox"
value={this.state.toEndChecked}
onChange={this.toEndChanged}
/>
<small className={css(styles.text, styles.checkboxText)}>
All Measures
</small>
<input
type="checkbox"
value={this.state.allChecked}
onChange={this.allChanged}
/>
</span>
</div>
);
}
}
export default connect(null, { changeTimeSignature })(TimeSignaturePopover);
|
import webpack from 'webpack';
import webpackConfig from '../webpack.config.js';
async function build() {
return new Promise((resolve, reject) => {
webpack(webpackConfig[1]).run((errServer, serverStats) => {
if (errServer) reject(errServer);
console.log(serverStats.toString(webpackConfig[1].stats));
webpack(webpackConfig[0]).run((errClient, clientStats) => {
if (errClient) reject(errClient);
console.log(clientStats.toString(webpackConfig[0].stats));
resolve();
});
});
});
}
export default build;
|
export default from './unview.container'
|
(function () {
angular.module('travelApp', ['toursApp'])
.service('dateParse', function () {
this.myDateParse = function (value) {
var pattern = /Date\(([^)]+)\)/;
var results = pattern.exec(value);
var dt = new Date(parseFloat(results[1]));
return dt;
}
})
.filter('myDateFormat', [
'dateParse', function (dateParse) {
return function (x) {
return dateParse.myDateParse(x);
};
}
]);
})();
|
import getDevTool from './devtool'
import getTarget from './target'
import getEntry from './entry'
import getOutput from './output'
import getResolve from './resolve'
import getResolveLoader from './resolveLoader'
import getModule from './module'
import getExternals from './externals'
import getPlugins from './plugins'
import getPostcss from './postcss'
import getNode from './node'
export default function make(name) {
if(typeof name !== 'string')
throw new Error('Name is required.')
return { name
, context: __dirname
, cache: true
, target: getTarget(name)
, devtool: getDevTool(name)
, entry: getEntry(name)
, output: getOutput(name)
, resolve: getResolve(name)
, resolveLoader: getResolveLoader(name)
, module: getModule(name)
, externals: getExternals(name)
, plugins: getPlugins(name)
, node: getNode(name)
, postcss: getPostcss(name)
}
}
|
import Ember from 'ember';
export default Ember.Controller.extend({
shortcuts:
[
{
title: "Task Editor",
combos: [
{
set: [["ctl","sh","del"]],
description: "delete focused task"
},
{
set: [["ctl","sh","ent"], ["ctl","+"]],
description: "create new task and edit it"
},
{
set: [["ctl","sh","h"], ["ctl", "sh", "⥢"],["esc"]],
description: "focus left into task list"
},
]
},
{
title: "Task List",
combos: [
{
set: [["down"], ["j"]],
description: "move down"
},
{
set: [["up"], ["k"]],
description: "move up"
},
{
set: [["o"], ["e"], ["ent"], ["space"]],
description: "toggle task in editor"
},
{
set: [["l"], ["⥤"]],
description: "display task in editor"
},
{
set: [["ctl", "sh", "l"],["ctl", "sh", "⥤"]],
description: "display task in editor and edit it"
},
{
set: [["h"], ["⥢"]],
description: "hide task from editor"
},
{
set: [["ctl","sh","del"]],
description: "delete focused task"
},
{
set: [["ctl","sh","ent"], ["ctl","sh","="]],
description: "create new task and edit it"
},
]
},
]
});
|
module.exports = {
framework: 'qunit',
test_page: 'tests/index.html?hidepassed',
disable_watching: true,
launch_in_ci: [
'Chrome'
],
launch_in_dev: [
'Chrome'
],
browser_args: {
Chrome: {
mode: 'ci',
args: [
// --no-sandbox is needed when running Chrome inside a container
process.env.TRAVIS ? '--no-sandbox' : null,
'--disable-gpu',
'--headless',
'--no-sandbox',
'--remote-debugging-port=9222',
'--window-size=1440,900'
].filter(Boolean)
}
}
};
|
/*
* The MIT License
* Copyright (c) 2014-2016 Nick Guletskii
*
* 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.
*/
import Util from "oolutil";
import {
property as _property,
omit as _omit
} from "lodash";
import {
services
} from "app";
class UserService {
/* @ngInject*/
constructor($http, $q, Upload, $rootScope) {
this.$http = $http;
this.$q = $q;
this.$rootScope = $rootScope;
this.Upload = Upload;
}
getCurrentUser() {
return this.$http.get("/api/user/personalInfo", {})
.then(_property("data"));
}
changePassword(passwordObj, userId) {
const passwordPatchUrl = !userId ? "/api/user/changePassword" :
`/api/admin/user/${userId}/changePassword`;
return this.$http({
method: "PATCH",
url: passwordPatchUrl,
data: _omit(Util.emptyToNull(passwordObj), "passwordConfirmation")
})
.then(_property("data"));
}
countPendingUsers() {
return this.$http.get("/api/admin/pendingUsersCount")
.then(_property("data"));
}
getPendingUsersPage(page) {
return this.$http.get("/api/admin/pendingUsers", {
params: {
page
}
})
.then(_property("data"));
}
countUsers() {
return this.$http.get("/api/admin/usersCount")
.then(_property("data"));
}
getUsersPage(page) {
return this.$http.get("/api/admin/users", {
params: {
page
}
})
.then(_property("data"));
}
getUserById(id) {
return this.$http.get("/api/user", {
params: {
id
}
})
.then(_property("data"));
}
approveUsers(users) {
return this.$http.post("/api/admin/users/approve", users)
.then(_property("data"));
}
deleteUsers(users) {
return this.$http.post("/api/admin/users/deleteUsers", users)
.then(_property("data"));
}
countArchiveUsers() {
return this.$http.get("/api/archive/rankCount")
.then(_property("data"));
}
getArchiveRankPage(page) {
return this.$http.get("/api/archive/rank", {
params: {
page
}
})
.then(_property("data"));
}
addUserToGroup(groupId, username) {
const deferred = this.$q.defer();
const formData = new FormData();
formData.append("username", username);
this.Upload.http({
method: "POST",
url: `/api/group/${groupId}/addUser`,
headers: {
"Content-Type": undefined,
"X-Auth-Token": this.$rootScope.authToken
},
data: formData,
transformRequest: angular.identity
})
.success((data) => {
deferred.resolve(data);
});
return deferred.promise;
}
removeUserFromGroup(groupId, userId) {
return this.$http.delete(`/api/group/${groupId}/removeUser`, {
params: {
user: userId
}
})
.then(_property("data"));
}
}
services.service("UserService", UserService);
|
define(['view',
'class'],
function(View, clazz) {
function Overlay(el, options) {
options = options || {};
Overlay.super_.call(this, el, options);
this.closable = options.closable;
this._autoRemove = options.autoRemove !== undefined ? options.autoRemove : true;
var self = this;
if (this.closable) {
this.el.on('click', function() {
self.hide();
return false;
});
}
}
clazz.inherits(Overlay, View);
Overlay.prototype.show = function() {
this.emit('show');
this.el.appendTo(document.body);
this.el.removeClass('hide');
return this;
}
Overlay.prototype.hide = function() {
this.emit('hide');
this.el.addClass('hide');
if (this._autoRemove) {
var self = this;
setTimeout(function() {
self.remove();
self.dispose();
}, 10);
}
return this;
}
return Overlay;
});
|
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
var androidUnlock = exports.androidUnlock = { "viewBox": "0 0 512 512", "children": [{ "name": "path", "attribs": { "d": "M376,186h-20v-40c0-55-45-100-100-100S156,91,156,146h37.998c0-34.004,28.003-62.002,62.002-62.002\r\n\tc34.004,0,62.002,27.998,62.002,62.002H318v40H136c-22.002,0-40,17.998-40,40v200c0,22.002,17.998,40,40,40h240\r\n\tc22.002,0,40-17.998,40-40V226C416,203.998,398.002,186,376,186z M256,368c-22.002,0-40-17.998-40-40s17.998-40,40-40\r\n\ts40,17.998,40,40S278.002,368,256,368z" }, "children": [] }] };
|
/* this is all example code which should be changed; see query.js for how it works */
authUrl = "http://importio-signedserver.herokuapp.com/";
reEx.push(/\/_source$/);
/*
//change doReady() to auto-query on document ready
var doReadyOrg = doReady;
doReady = function() {
doReadyOrg();
doQuery();//query on ready
}
*/
//change doReady() to add autocomplete-related events
// http://jqueryui.com/autocomplete/ http://api.jqueryui.com/autocomplete/
var acField;//autocomplete data field
var acSel;//autocomplete input selector
var acsSel = "#autocomplete-spin";//autocomplete spinner selector
var cache = {};//autocomplete cache
var termCur = "";//autocomplete current term
var doReadyOrg = doReady;
doReady = function() {
doReadyOrg();
$(acSel)
.focus()
.bind("keydown", function(event) {
// http://api.jqueryui.com/jQuery.ui.keyCode/
switch(event.keyCode) {
//don't fire autocomplete on certain keys
case $.ui.keyCode.LEFT:
case $.ui.keyCode.RIGHT:
event.stopImmediatePropagation();
return true;
break;
//submit form on enter
case $.ui.keyCode.ENTER:
doQuery();
$(this).autocomplete("close");
break;
}
})
.autocomplete({
minLength: 3,
source: function(request, response) {
var term = request.term.replace(/[^\w\s]/gi, '').trim().toUpperCase();//replace all but "words" [A-Za-z0-9_] & whitespaces
if (term in cache) {
doneCompleteCallbackStop();
response(cache[term]);
return;
}
termCur = term;
if (spinOpts) {
$(acsSel).spin(spinOpts);
}
cache[term] = [];
doComplete(term);
response(cache[term]);//send empty for now
}
});
};
function doComplete(term) {
doQueryMy();
var qObjComplete = jQuery.extend({}, qObj);//copy to new obj
qObjComplete.maxPages = 1;
importio.query(qObjComplete,
{ "data": function(data) {
dataCompleteCallback(data, term);
},
"done": function(data) {
doneCompleteCallback(data, term);
}
}
);
}
var dataCompleteCallback = function(data, term) {
console.log("Data received", data);
for (var i = 0; i < data.length; i++) {
var d = data[i];
var c = d.data[acField];
if (typeof filterComplete === 'function') {
c = filterComplete(c);
}
c = c.trim();
if (!c) {
continue;
}
cache[term].push(c);
}
}
var doneCompleteCallback = function(data, term) {
console.log("Done, all data:", data);
console.log("cache:", cache);
// http://stackoverflow.com/questions/16747798/delete-duplicate-elements-from-an-array
cache[term] = cache[term].filter(
function(elem, index, self) {
return index == self.indexOf(elem);
});
if (termCur != term) {
return;
}
doneCompleteCallbackStop();
$(acSel).trigger("keydown");
}
var doneCompleteCallbackStop = function() {
termCur = "";
if (spinOpts) {
$(acsSel).spin(false);
}
}
/* Query for tile Store Locators
*/
fFields.push({id: "postcode", html: '<input id="postcode" type="text" value="EC2M 4TP" />'});
fFields.push({id: "autocomplete-spin", html: '<span id="autocomplete-spin"></span>'});
fFields.push({id: "submit", html: '<button id="submit" onclick="doQuery();">Query</button>'});
acField = "address";
var filterComplete = function(val) {
if (val.indexOf(", ") == -1) {
return "";
}
return val.split(", ").pop();
}
acSel = "#postcode";
qObj.connectorGuids = [
"8f628f9d-b564-4888-bc99-1fb54b2df7df",
"7290b98f-5bc0-4055-a5df-d7639382c9c3",
"14d71ff7-b58f-4b37-bb5b-e2475bdb6eb9",
"9c99f396-2b8c-41e0-9799-38b039fe19cc",
"a0087993-5673-4d62-a5ae-62c67c1bcc40"
];
var doQueryMy = function() {
qObj.input = {
"postcode": $("#postcode").val()
};
}
/* Here's some other example code for a completely different API
fFields.push({id: "title", html: '<input id="title" type="text" value="harry potter" />'});
fFields.push({id: "autocomplete-spin", html: '<span id="autocomplete-spin"></span>'});
fFields.push({id: "submit", html: '<button id="submit" onclick="doQuery();">Query</button>'});
acField = "title";
acSel = "#title";
filters["image"] = function(val, row) {
return '<a href="' + val + '" target="_blank">' + val + '</a>';
}
qObj.connectorGuids = [
"ABC"
];
var doQueryMy = function() {
qObj.input = {
"search": $("#title").val()
};
}
*/
/* Here's some other example code for a completely different API
colNames = ["ranking", "title", "artist", "album", "peak_pos", "last_pos", "weeks", "image", "spotify", "rdio", "video"];
filters["title"] = function(val, row) {
return "<b>" + val + "</b>";
}
filters["video"] = function(val, row) {
if (val.substring(0, 7) != "http://") {
return val;
}
return '<a href="' + val + '" target="_blank">' + val + '</a>';
}
doQuery = function() {
doQueryPre();
for (var page = 0; page < 10; page++) {
importio.query({
"connectorGuids": [
"XYZ"
],
"input": {
"webpage/url": "http://www.billboard.com/charts/hot-100?page=" + page
}
}, { "data": dataCallback, "done": doneCallback });
}
}
*/
|
function flashMessage(type, message) {
var flashContainer = $('#flash-message');
var flash = null;
if (message.title) {
flash = $('<div class="alert alert-block alert-' + type + '"><h4 class="alert-heading">' + message.title + '</h4><p>' + message.message + '</p></div>');
}
else {
flash = $('<div class="alert alert-block alert-' + type + '"><p>' + message + '</p></div>');
}
flashContainer.append(flash);
setupFlash.call(flash);
}
function setupFlash()
{
var flash = $(this);
if (flash.html() != '') {
var timeout = flash.data('timeout');
if (timeout) {
clearTimeout(timeout);
}
if (!flash.hasClass('alert-danger')) {
flash.data('timeout', setTimeout(function() { flash.fadeOut(400, function() { $(this).remove(); }); }, 5000));
}
flash.fadeIn();
}
}
function showFlashMessage() {
var flashes = $('#flash-message .alert');
flashes.each(setupFlash);
}
function initFlashMessage(){
$('#flash-message').on('click', '.alert', function() { $(this).fadeOut(400, function() { $(this).remove(); }) ; });
showFlashMessage();
}
|
var curl = require('./lib/curl');
var clean = require('./lib/extract');
curl('http://blog.rainy.im/2015/09/02/web-content-and-main-image-extractor/', function (content) {
console.log('fetch done');
clean(content, {
blockSize: 3
});
});
|
const fs = require('fs')
const Log = require('log')
const browserify = require('browserify')
const babelify = require('babelify')
const errorify = require('errorify')
const cssNext = require('postcss-cssnext')
const cssModulesify = require('css-modulesify')
const exec = require('child_process').exec
const log = new Log('info')
const fileMap = {
'index.js': 'main'
}
const files = Object.keys(fileMap)
const srcFolder = `${__dirname}/../demo`
const buildFolder = `${__dirname}/../docs`
const outFiles = files.map(file => {
return `${buildFolder}/${fileMap[file]}.js ${buildFolder}/${fileMap[file]}.css`
}).join(' ')
exec(`rm -rf ${outFiles} ${buildFolder}/index.html`, (err) => {
if (err) {
throw err
}
exec(`cp ${srcFolder}/index.html ${buildFolder}/index.html`, (error) => {
if (error) {
throw error
}
})
files.forEach(file => {
const inFile = `${srcFolder}/${file}`
const outFile = `${buildFolder}/${fileMap[file]}`
const b = browserify({
entries: [inFile],
plugin: [
errorify
],
transform: [
[ babelify, {
presets: [
'es2015',
'stage-0',
'react'
]
}]
]
})
b.plugin(cssModulesify, {
output: `${outFile}.css`,
after: [cssNext()]
})
function bundle () {
b.bundle().pipe(fs.createWriteStream(`${outFile}.js`))
}
b.on('log', message => log.info(message))
b.on('error', message => log.error(message))
bundle()
})
})
|
var style = document.createElement('p').style,
prefixes = 'O ms Moz webkit'.split(' '),
hasPrefix = /^(o|ms|moz|webkit)/,
upper = /([A-Z])/g,
memo = {};
function get(key) {
return (key in memo) ? memo[key] : memo[key] = prefix(key);
}
function prefix(key) {
var capitalizedKey = key.replace(/-([a-z])/g, function (s, match) {
return match.toUpperCase();
}),
i = prefixes.length,
name;
if (style[capitalizedKey] !== undefined) return capitalizedKey;
capitalizedKey = capitalize(key);
while (i--) {
name = prefixes[i] + capitalizedKey;
if (style[name] !== undefined) return name;
}
throw new Error('unable to prefix ' + key);
}
function capitalize(str) {
return str.charAt(0).toUpperCase() + str.slice(1);
}
function dashedPrefix(key) {
var prefixedKey = get(key),
upper = /([A-Z])/g;
if (upper.test(prefixedKey)) {
prefixedKey = (hasPrefix.test(prefixedKey) ? '-' : '') + prefixedKey.replace(upper, '-$1');
}
return prefixedKey.toLowerCase();
}
if (typeof module != 'undefined' && module.exports) {
module.exports = get;
module.exports.dash = dashedPrefix;
} else {
return get;
}
|
'use strict';
var angular = require('angular');
var calendarUtils = require('calendar-utils');
angular
.module('mwl.calendar')
.controller('MwlCalendarHourListCtrl', function($scope, $document, moment, calendarHelper) {
var vm = this;
// source: http://stackoverflow.com/questions/13382516/getting-scroll-bar-width-using-javascript
function getScrollbarWidth() {
var outer = $document[0].createElement('div');
outer.style.visibility = 'hidden';
outer.style.width = '100px';
outer.style.msOverflowStyle = 'scrollbar'; // needed for WinJS apps
$document[0].body.appendChild(outer);
var widthNoScroll = outer.offsetWidth;
// force scrollbars
outer.style.overflow = 'scroll';
// add innerdiv
var inner = $document[0].createElement('div');
inner.style.width = '100%';
outer.appendChild(inner);
var widthWithScroll = inner.offsetWidth;
// remove divs
outer.parentNode.removeChild(outer);
return widthNoScroll - widthWithScroll;
}
vm.scrollBarWidth = getScrollbarWidth();
function updateDays() {
vm.dayViewSplit = parseInt(vm.dayViewSplit);
var dayStart = (vm.dayViewStart || '00:00').split(':');
var dayEnd = (vm.dayViewEnd || '23:59').split(':');
vm.hourGrid = calendarUtils.getDayViewHourGrid({
viewDate: vm.view === 'week' ? moment(vm.viewDate).startOf('week').toDate() : moment(vm.viewDate).toDate(),
hourSegments: 60 / vm.dayViewSplit,
dayStart: {
hour: dayStart[0],
minute: dayStart[1]
},
dayEnd: {
hour: dayEnd[0],
minute: dayEnd[1]
}
});
vm.hourGrid.forEach(function(hour) {
hour.segments.forEach(function(segment) {
segment.date = moment(segment.date);
segment.nextSegmentDate = segment.date.clone().add(vm.dayViewSplit, 'minutes');
if (vm.view === 'week') {
segment.days = [];
for (var i = 0; i < 7; i++) {
var day = {
date: moment(segment.date).add(i, 'days')
};
day.nextSegmentDate = day.date.clone().add(vm.dayViewSplit, 'minutes');
vm.cellModifier({calendarCell: day});
segment.days.push(day);
}
} else {
vm.cellModifier({calendarCell: segment});
}
});
});
}
var originalLocale = moment.locale();
$scope.$on('calendar.refreshView', function() {
if (originalLocale !== moment.locale()) {
originalLocale = moment.locale();
updateDays();
}
});
$scope.$watchGroup([
'vm.dayViewStart',
'vm.dayViewEnd',
'vm.dayViewSplit',
'vm.viewDate'
], function() {
updateDays();
});
vm.eventDropped = function(event, date) {
var newStart = moment(date);
var newEnd = calendarHelper.adjustEndDateFromStartDiff(event.startsAt, newStart, event.endsAt);
vm.onEventTimesChanged({
calendarEvent: event,
calendarDate: date,
calendarNewEventStart: newStart.toDate(),
calendarNewEventEnd: newEnd ? newEnd.toDate() : null
});
};
vm.onDragSelectStart = function(date, dayIndex) {
if (!vm.dateRangeSelect) {
vm.dateRangeSelect = {
active: true,
startDate: date,
endDate: date,
dayIndex: dayIndex
};
}
};
vm.onDragSelectMove = function(date) {
if (vm.dateRangeSelect) {
vm.dateRangeSelect.endDate = date;
}
};
vm.onDragSelectEnd = function(date) {
if (vm.dateRangeSelect) {
vm.dateRangeSelect.endDate = date;
if (vm.dateRangeSelect.endDate > vm.dateRangeSelect.startDate) {
vm.onDateRangeSelect({
calendarRangeStartDate: vm.dateRangeSelect.startDate.toDate(),
calendarRangeEndDate: vm.dateRangeSelect.endDate.toDate()
});
}
delete vm.dateRangeSelect;
}
};
})
.directive('mwlCalendarHourList', function() {
return {
restrict: 'E',
template: '<div mwl-dynamic-directive-template name="calendarHourList" overrides="vm.customTemplateUrls"></div>',
controller: 'MwlCalendarHourListCtrl as vm',
scope: {
viewDate: '=',
dayViewStart: '=',
dayViewEnd: '=',
dayViewSplit: '=',
dayWidth: '=?',
onTimespanClick: '=',
onDateRangeSelect: '=',
onEventTimesChanged: '=',
customTemplateUrls: '=?',
cellModifier: '=',
templateScope: '=',
view: '@'
},
bindToController: true
};
});
|
'use strict';
describe('Controller: MainCtrl', function() {
// load the controller's module
beforeEach(module('actionatadistanceApp'));
var MainCtrl,
scope;
// Initialize the controller and a mock scope
beforeEach(inject(function($controller) {
scope = {};
MainCtrl = $controller('MainCtrl', {
$scope: scope
});
}));
it('should attach a list of awesomeThings to the scope', function() {
expect(scope.awesomeThings.length).toBe(3);
});
});
|
import React from 'react';
import PropTypes from 'prop-types';
import _get from 'lodash.get';
import _words from 'lodash.words';
import { VictoryAxis,
VictoryBar,
VictoryChart,
VictoryTheme } from 'victory';
export class CrawlChart extends React.Component {
constructor(props) {
super(props);
this.state = {
data: [
{movie: 1, word_count: 0},
{movie: 2, word_count: 0},
{movie: 3, word_count: 0},
{movie: 4, word_count: 0},
{movie: 5, word_count: 0},
{movie: 6, word_count: 0},
{movie: 7, word_count: 0}
]
};
}
componentWillReceiveProps(nextProps) {
let movieCrawls = nextProps.movies.map((m) => _get(m, 'opening_crawl', ''));
let newState = {
data: movieCrawls.map((c, i) => { return { movie: i+1, word_count: _words(c).length}; })
};
this.setState(newState);
}
render() {
return (
<div>
<h3>Opening Crawl Word Count</h3>
<VictoryChart
// adding the material theme provided with Victory
animate={{duration: 500}}
theme={VictoryTheme.material}
domainPadding={20}
>
<VictoryAxis
tickFormat={['Ep 1', 'Ep 2', 'Ep 3', 'Ep 4', 'Ep 5', 'Ep 6', 'Ep 7']}
tickValues={[1, 2, 3, 4, 5, 6, 7]}
/>
<VictoryAxis
dependentAxis
domain={[0, 100]}
tickFormat={(x) => (`${x}`)}
/>
<VictoryBar
data={this.state.data}
style={{
data: {fill: '#fe9901', width:12}
}}
labels={(d) => `${Math.ceil(d.y)}`}
x="movie"
y="word_count"
/>
</VictoryChart>
</div>
);
}
}
CrawlChart.propTypes = {
movies: PropTypes.arrayOf(
PropTypes.shape({
opening_crawl: PropTypes.string.isRequired,
title: PropTypes.string
})
)
};
|
// ES2015 사용을 위한 babel 모듈 호출
import 'babel-polyfill';
// 전역 변수 객체 호출
import globalConfig from './helpers/global-config';
// npm 모듈 호출
import mobileDetect from 'mobile-detect';
//import scroll from 'scroll';
//import ease from 'ease-component';
import detectScrollPageObj from 'scroll-doc';
// devTools 호출
import devTools from './devtools/dev-tools';
import mirror from './devtools/mirror';
import preview from './devtools/preview';
// 헬퍼 모듈 호출
import catchEventTarget from './helpers/catch-event-target';
//import clipboardFunc from './helpers/clipboard-function';
//import cloneObj from './helpers/clone-obj';
//import colorAdjust from './helpers/color-adjust';
//import delayEvent from './helpers/delay-event';
import index from './helpers/index';
//import parents from './helpers/parents';
//import readingZero from './helpers/reading-zero';
//import toggleBoolean from './helpers/toggle-boolean';
import modifier from './helpers/modifier';
//import splitSearch from '../../app_helpers/split-search';
// 프로젝트 모듈 호출
//import {socketFunc} from './project/socket';
//import * as kbs from './project/kbs';
// 전역변수 선언
let socket;
document.addEventListener('DOMContentLoaded', () => {
// 돔 로드완료 이벤트
const WIN = window,
DOC = document,
MD = new mobileDetect(WIN.navigator.userAgent),
detectScrollPage = detectScrollPageObj();
if(MD.mobile()) console.log(`mobile DOM's been loaded`);
else console.log(`DOM's been loaded`);
DOC.addEventListener('click', (e) => {
// 클릭 이벤트 버블링
const eventTarget = catchEventTarget(e.target || e.srcElement);
console.log(eventTarget.target, eventTarget.findJsString);
switch(eventTarget.findJsString) {
case 'js-copy-link' :
console.log(index(eventTarget.target));
scroll.top(
detectScrollPage,
1000,
{
duration: 1000,
ease: ease.inQuint
},
function (error, scrollLeft) {
}
);
modifier(
'toggle',
eventTarget.target,
'paging__elm--actived'
);
break;
default :
return false;
}
}, false);
WIN.addEventListener('load', () => {
// 윈도우 로드완료 이벤트
if(MD.mobile()) console.log(`mobile WINDOW's been loaded`);
else console.log(`WINDOW's been loaded`);
// socket = io();
// socketFunc(socket);
});
WIN.addEventListener('resize', () => {
// 윈도우 리사이즈 이벤트
// delayEvent(/*second*/, /*func*/);
});
WIN.addEventListener('keypress', (e) => {
const pressedKeyCode = e.which;
switch(pressedKeyCode) {
case 0:
// some Function
break;
default :
return false;
}
});
DOC.addEventListener('wheel', (e) => {
const eventTarget = catchEventTarget(e.target || e.srcElement);
switch(eventTarget.findJsString) {
case 'js-test':
console.log(eventTarget.target);
break;
default :
return false;
}
}, true);
DOC.addEventListener('touchstart', (e) => {
let touchObj = e.changedTouches[0];
});
DOC.addEventListener('touchmove', (e) => {
let touchObj = e.changedTouches[0];
});
DOC.addEventListener('touchend', (e) => {
let touchObj = e.changedTouches[0];
});
});
|
version https://git-lfs.github.com/spec/v1
oid sha256:0f924f0bd38d3dfb7ebc34016ec96c018aee7fb62e1cd562898fdeb85ca7d283
size 2234
|
!(function(){
var spg = require('./simple-password-generator.js');
console.log(spg.generate({
length : 3
}));
})();
|
var expect = require('chai').expect;
var search = require('./');
describe('binary search', function() {
it('should search 0 elements', function() {
var arr = [];
expect(search(arr, 4)).to.equal(-1);
});
it('should search 1 element not found', function() {
var arr = [1];
expect(search(arr, 4)).to.equal(-1);
});
it('should search 1 element found', function() {
var arr = [1];
expect(search(arr, 1)).to.equal(0);
});
it('should search odd', function() {
var arr = [1, 2, 3, 4, 5, 6, 7];
expect(search(arr, 4)).to.equal(3);
});
it('should search even', function() {
var arr = [1, 2, 3, 4, 5, 6, 7, 8];
expect(search(arr, 4)).to.equal(3);
});
});
|
import { Client, ClientDao } from '../database/clientDao';
const dao = new ClientDao();
export default class ClientService {
static save(accessToken, refreshToken, profile, done) {
process.nextTick(() => {
let client = new Client();
client.name = profile.displayName;
client.email = profile.emails[0].value;
client.facebookId = profile.id;
client.token = accessToken;
client.photo = 'https://graph.facebook.com/' + profile.id + '/picture?type=large';
dao.save(client, (err, client) => {
if (err) {
return done(err);
}
done(err, client);
});
});
}
static find(req, res, next) {
dao.find((err, clients) => {
if (err) {
return next(err);
}
res.status(200).json(clients);
})
}
}
|
import { createRangeFromZeroTo } from '../../helpers/utils/range'
describe('utils range', () => {
describe('createRangeFromZeroTo range 2', () => {
const range = createRangeFromZeroTo(2)
it('return the array 0 to 1', () => {
expect(range).toEqual([0, 1])
})
})
describe('createRangeFromZeroTo range 7', () => {
const range = createRangeFromZeroTo(7)
it('return the array 0 to 6', () => {
expect(range).toEqual([0, 1, 2, 3, 4, 5, 6])
})
})
describe('createRangeFromZeroTo range 1', () => {
const range = createRangeFromZeroTo(1)
it('return the array 0', () => {
expect(range).toEqual([0])
})
})
describe('createRangeFromZeroTo range 0', () => {
const range = createRangeFromZeroTo(0)
it('return the array empty', () => {
expect(range).toEqual([])
})
})
describe('createRangeFromZeroTo range undefined', () => {
const range = createRangeFromZeroTo()
it('return the array empty', () => {
expect(range).toEqual([])
})
})
describe('createRangeFromZeroTo range string', () => {
const range = createRangeFromZeroTo('toto')
it('return the array empty', () => {
expect(range).toEqual([])
})
})
})
|
/*global YoBackbone, Backbone*/
YoBackbone.Collections = YoBackbone.Collections || {};
(function () {
'use strict';
var Todos = Backbone.Collection.extend({
model: YoBackbone.Models.Todo,
localStorage: new Backbone.LocalStorage('todos-backbone'),
// Filter down the list of all todo items that are finished.
completed: function() {
return this.filter(function( todo ) {
return todo.get('completed');
});
},
// Filter down the list to only todo items that are still not finished.
remaining: function() {
// apply allowsus to define the context of this within our function scope
return this.without.apply( this, this.completed() );
},
// We keep the Todos in sequential order, despite being saved by unordered
// GUID in the database. This generates the next order number for new items.
nextOrder: function() {
if ( !this.length ) {
return 1;
}
return this.last().get('order') + 1;
},
// Todos are sorted by their original insertion order.
comparator: function( todo ) {
return todo.get('order');
}
});
YoBackbone.Application.todos = new Todos();
})();
|
Nectar.createStruct("test", "a:string", "b:int", "c:double");
function Test()
{
var testStruct = Nectar.initStruct("test");
testStruct.NStruct("test").a = "Hello Struct!";
console.log(testStruct.NStruct("test").a);
return testStruct
}
var retStruct = Test();
retStruct.NStruct("test").a = "After return";
console.log(retStruct.NStruct("test").a);
// access to non struct member fall back on hashmap
retStruct.NStruct("test").x = "Fallback";
console.log(retStruct.NStruct("test").x);
|
define('view/rooms/users-rooms-list', [
'view'
], function (
View
) {
function UsersRoomsListView() {
View.apply(this, arguments);
}
View.extend({
constructor: UsersRoomsListView,
template: {
'root': {
each: {
view: UserRoomView,
el: '> *'
}
}
}
});
function UserRoomView() {
View.apply(this, arguments);
}
View.extend({
constructor: UserRoomView,
template: {
'root': {
'class': {
'hidden': '@hidden'
}
},
'[data-title]': {
text: '@name',
attr: {
'href': function () {
return '#user-room/' + this.model.get('id')
}
}
}
}
});
return UsersRoomsListView;
});
|
angular.module('messages')
.controller('messageCtrl',['$scope','messages','socket','$stateParams',MessageController])
function MessageController($scope,messages,socket,$stateParams) {
$scope.messages = messages;
$scope.msg = '';
$scope.sendMsg = function() {
socket.sendMsg({content : $scope.msg, to : $stateParams.id});
};
};
|
/**
* Created by uzysjung on 2016. 10. 21..
*/
import React, { PropTypes,Component } from 'react';
import Box from '../../components/widget/Box'
import { Link, browserHistory } from 'react-router'
import superagent from 'superagent';
import { Form , FormGroup, Col, Button, FormControl, Checkbox, ControlLabel , PageHeader, Alert } from 'react-bootstrap'
const styleLogin = {
panel : {
maxWidth : 600,
position : 'absolute',
top : '50%',
left : '50%',
transform : 'translate(-50%,-50%)'
},
header : {
maxHeight : 40,
bottomMargin : 100,
borderBottom : '1px solid #bababa'
}
};
class LoginPage extends React.Component {
constructor(props) {
super(props);
this.state = {
email : '',
password : ''
}
}
componentWillMount() {
const { authenticated, replace, redirect } = this.props;
if (authenticated) {
replace(redirect)
}
}
componentDidMount() {
}
handleFormSubmit = (e) => {
e.preventDefault();
const { email, password } = this.state;
setTimeout(() => this.setState({error: false}), 3000);
if ( !email || email.length < 1) {
this.setState({error: 'Insert Email address'});
return;
}
if (!/^[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,4}$/i.test(email)) {
this.setState({error: 'Please check whether this email is valid'});
return;
}
if (!password) {
this.setState({error: 'Insert Password'});
return;
}
if ( password && password.length < 5 ) {
this.setState({error: 'Password must be longer than 5 characters'});
return;
}
superagent.post('/api/login').send({login_email: email, login_pw: password}).end((err, result) => {
if (!err) {
localStorage.setItem('jwt', result.body.token);
browserHistory.push('/');
} else {
this.setState({error: 'Login email/password incorrect :('});
}
});
};
handleForChange = (e) => {
console.log('e.target.id',e.target.id);
switch(e.target.id) {
case 'formHorizontalEmail' :
this.setState( { email : e.target.value } );
break;
case 'formHorizontalPassword' :
this.setState( { password : e.target.value } );
break;
}
};
renderAlert() {
if (this.state.error) {
return (
<Alert bsStyle="danger">
{this.state.error}
</Alert>
)
}
return null;
}
render() {
return (
<div style={styleLogin.panel}>
<PageHeader style={styleLogin.header}>Weapon Management System</PageHeader>
<Box
title="Login"
status="info"
solid
>
<Form onSubmit={this.handleFormSubmit} horizontal>
<FormGroup controlId="formHorizontalEmail">
<Col componentClass={ControlLabel} sm={2}>
Email
</Col>
<Col sm={10}>
<FormControl type="email" placeholder="Email" value={this.state.email} onChange={this.handleForChange} />
</Col>
</FormGroup>
<FormGroup controlId="formHorizontalPassword">
<Col componentClass={ControlLabel} sm={2}>
Password
</Col>
<Col sm={10}>
<FormControl type="password" placeholder="Password" value={this.state.password} onChange={this.handleForChange} />
</Col>
</FormGroup>
<FormGroup>
<Col smOffset={2} sm={10}>
<Checkbox>Remember me</Checkbox>
</Col>
</FormGroup>
{this.renderAlert()}
<FormGroup>
<Col smOffset={2} sm={10}>
<Button className="btn btn-success" type="submit">
Sign in
</Button>
</Col>
</FormGroup>
</Form>
</Box>
</div>
);
}
}
export default LoginPage;
|
$(function () {
$('[data-toggle="tooltip"]').tooltip()
})
$(function () {
$('[data-toggle="popover"]').popover()
})
|
'use strict';
//var async = require('async'),
// nconf = require('nconf'),
// user = require('../user'),
// groups = require('../groups'),
// topics = require('../topics'),
// posts = require('../posts'),
// notifications = require('../notifications'),
// messaging = require('../messaging'),
// plugins = require('../plugins'),
// utils = require('../../public/src/utils'),
// websockets = require('./index'),
// meta = require('../meta'),
var linkParser = require('../controllers/mind-map/linkParser_new-format'),
swaggerBuilder = require('../modeling/swaggerBuilder'),
swaggerBuildertr069 = require('../modeling/swaggerBuilder-Scope');
var SocketCustom = {};
SocketCustom.refreshLinkParser = function(socket, sets, callback) {
if (!socket.uid) {
return callback(new Error('[[invalid-uid]]'));
}
linkParser.init(function(err) {
callback(null, '{"message": "Refreshed Link Parser"}');
});
};
SocketCustom.refreshSwagger = function(socket, data, callback) {
if (!socket.uid) {
return callback(new Error('[[invalid-uid]]'));
}
swaggerBuilder.init(function(err) {
callback(null, '{"message": "Refreshed Swagger File"}');
});
};
SocketCustom.refreshZoneSwagger = function(socket, data, callback) {
if (!socket.uid) {
return callback(new Error('[[invalid-uid]]'));
}
swaggerBuildertr069.init(function(err) {
callback(null, '{"message": "Refreshed Zone Swagger File"}');
});
};
/* Exports */
module.exports = SocketCustom;
|
import {getTims} from '../api/api';
export function loadData() {
return getTims().then(data => {
const parser = new DOMParser();
const doc = parser.parseFromString(data, 'text/xml');
if (doc.documentElement.nodeName === 'parseerror') {
throw new Error(doc);
}
return toJSON(doc);
}).catch(e => {
console.error(e);
});
}
function toJSON(doc) {
const json = {
published: null,
disruptions: []
};
const { header, disruptions } = getChildren(doc.documentElement, 'header', 'disruptions');
if (header) {
const publishedElement = getChild(header, 'publishdatetime');
if (publishedElement) {
const pubDateAttr = getAttr(publishedElement, 'canonical');
if (pubDateAttr) {
json.published = pubDateAttr.value;
}
}
const refreshRateElement = getChild(header, 'refreshrate');
if (refreshRateElement) {
const refreshRate = Number(refreshRateElement.textContent);
if (!isNaN(refreshRate) && refreshRate > 0) {
json.refreshRate = refreshRate;
}
}
}
if (disruptions) {
json.disruptions = mapDisruptions(disruptions);
}
return json;
}
function mapDisruptions(disruptions) {
const res = {};
for (let i = 0; i < disruptions.children.length; ++i) {
const disr = disruptions.children[i];
const idAttr = getAttr(disr, 'id');
if (!idAttr || !idAttr.value) {
continue;
}
const props = {};
for (let j = 0; j < disr.children.length; ++j) {
const propElem = disr.children[j];
if (propElem.children.length === 0) {
props[propElem.nodeName] = propElem.textContent;
} else if (propElem.nodeName.toLowerCase() === 'causearea') {
const displayPoint = getChild(propElem, 'displaypoint');
if (displayPoint) {
const point = getChild(displayPoint, 'point');
if (point) {
const coords = getChild(point, 'coordinatesll');
if (coords) {
const split = coords.textContent.split(',');
if (split.length === 2) {
props.coords = {
lat: parseFloat(split[1]),
lng: parseFloat(split[0])
};
}
}
}
}
}
}
res[idAttr.value] = props;
}
return res;
}
function getChildren(element, ...names) {
const res = {};
for (let i = 0; i < element.children.length; ++i) {
const name = element.children[i].nodeName.toLowerCase();
if (names.find(n => n === name)) {
res[name] = element.children[i];
}
}
return res;
}
function getChild(element, name) {
const res = getChildren(element, name);
return res[name] || null;
}
function getAttr(element, name) {
for (let i = 0; i < element.attributes.length; ++i) {
if (element.attributes[i].name === name) {
return element.attributes[i];
}
}
return null;
}
|
'use strict';
angular.module('cocoApp')
.directive('loginform', [function () {
return {
restrict: 'E',
controller: 'LoginInterceptCtrl',
scope: {
eventid: '='
},
templateUrl: 'partials/login.html'
};
}]);
|
/*
Copyright (c) 2012 Greg Reimer ( http://obadger.com/ )
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.
*/
(function(w, d, $){
// defaults
var defaultArgs = {
rays: 16,
originX: '50%',
originY: '50%',
bgColorStart: 'rgba(0,0,0,0.1)',
bgColorEnd: 'rgba(0,0,0,0.2)',
rayColorStart: 'hsla(0,0%,100%,0.2)',
rayColorEnd: 'hsla(0,0%,100%,0.3)',
sizingRatio: 1
};
$.fn.pow = (function(){
return function(args){
// bail if none
if (this.length === 0) { return; }
// set defaults
args = $.extend({}, defaultArgs, args);
// set vars and grab a few values to use later
var $el = this.eq(0);
var width = $el.outerWidth();
var height = $el.outerHeight();
var offset = $el.offset();
var originX = (parseFloat(args.originX) || 0) / 100;
var originY = (parseFloat(args.originY) || 0) / 100;
// center rays on a given element
if (args.originEl) {
var $oel = $(args.originEl);
if ($oel.length) {
var oOffset = $oel.offset();
var oWidth = $oel.outerWidth();
var oHeight = $oel.outerHeight();
originX = (((oOffset.left - offset.left) + (oWidth / 2)) / width);
originY = (((oOffset.top - offset.top) + (oHeight / 2)) / height);
}
}
// convert to absolute lengths
originX = width * originX;
originY = height * originY;
// find maximum distance to a corner
var radius = Math.max.apply(Math, [
{x:0,y:0},
{x:width,y:0},
{x:0,y:height},
{x:width,y:height}
].map(function(c){
// use the pythagorean theorem, luke
return Math.sqrt(Math.pow(c.x - originX, 2) + Math.pow(c.y - originY, 2));
}));
try{
var canvas = $('<canvas width="'+width+'" height="'+height+'" style="position:fixed;top:-999999px"></canvas>').appendTo(d.body).get(0);
var ctx = canvas.getContext('2d');
} catch(err) {
return;
}
// build the background gradient
var bgGrad = ctx.createRadialGradient(
originX, originY, 0, // inner circle, infinitely small
originX, originY, radius // outer circle, will just cover canvas area
);
bgGrad.addColorStop(0, args.bgColorStart);
bgGrad.addColorStop(1, args.bgColorEnd);
// build the foreground gradient
var rayGrad = ctx.createRadialGradient(
originX, originY, 0, // inner circle, infinitely small
originX, originY, radius // outer circle, will just cover canvas area
);
rayGrad.addColorStop(0, args.rayColorStart);
rayGrad.addColorStop(1, args.rayColorEnd);
// fill in bg
ctx.fillStyle = bgGrad;
ctx.fillRect(0,0,width,height);
// draw rays
ctx.fillStyle = rayGrad;
ctx.beginPath();
var spokeCount = args.rays * 2;
ctx.moveTo(originX, originY);
for (var i=0; i<args.rays; i++){
for (var j=0; j<2; j++) {
var thisSpoke = i * 2 + j;
var traversal = thisSpoke / spokeCount;
var ax = originX + radius * 1.5 * Math.cos(traversal * 2 * Math.PI);
var ay = originY + radius * 1.5 * Math.sin(traversal * 2 * Math.PI);
ctx.lineTo(ax,ay);
}
ctx.lineTo(originX, originY);
}
ctx.fill();
// set the data as css to the element
var data = canvas.toDataURL("image/png");
$(canvas).remove();
$el.css({
'background-image':'url("'+data+'")',
'background-repeat':'no-repeat',
'background-position':'50% 50%',
'background-size':'cover'
});
};
})();
})(window, document, jQuery);
|
'use strict'
import Macro from './macro.js'
/**
* マクロスタック
*/
export default class MacroStack {
/**
* コンストラクタ
*/
constructor () {
/**
* [*store manual] スタックの中身
* @private
* @type {Array}
*/
this.stack = []
}
/**
* スタックへ積む
* @param {Macro} macro マクロ
*/
push (macro) {
this.stack.push(macro)
}
/**
* スタックから降ろす
* @return {Macro} マクロ
*/
pop () {
return this.stack.pop()
}
/**
* スタックが空かどうか
* @return {boolean} 空ならtrue
*/
isEmpty () {
return this.stack.length <= 0
}
/**
* スタックの一番上のマクロを返す
* @return {Macro} マクロ
*/
getTop () {
if (this.isEmpty()) {
return null
} else {
return this.stack[this.stack.length - 1]
}
}
/**
* 状態を保存
* @param {number} tick 時刻
* @return {object} 保存データ
*/
store (tick) {
// Generated by genStoreMethod.js
let data = {}
// 保存
// 以下、手動で復元する
// store this.stack
data.stack = []
this.stack.forEach((macro) => {
data.stack.push(macro.store(tick))
})
return data
}
/**
* 状態を復元
* @param {object} data 復元データ
* @param {number} tick 時刻
* @param {AsyncTask} task 非同期処理管理
*/
restore (data, tick, task) {
// Generated by genRestoreMethod.js
// 復元
// 以下、手動で復元する
// restore this.stack
this.stack = []
// console.log(data)
data.stack.forEach((macroData) => {
let macro = new Macro('')
macro.restore(macroData, tick, task)
this.stock.push(macro)
})
}
}
|
const interviewSchema = require('./interview.schema');
const InterviewModel = require('mongoose').model('Interview', interviewSchema);
module.exports = InterviewModel;
|
// ch08-arrays--splice.js
'use strict';
// ADDING OR REMOVING ELEMENTS AT ANY POSITION
// SPLICE
// The first argument is the index you want to start modifying
// The second argument is the number of elements to remove (use 0 if you don’t want to remove any elements)
// The remaining arguments are the elements to be added
const arr = [1, 5, 7];
console.log(`arr: \t${arr}\tlength: \t${arr.length}`);
// arr: 1,5,7 length: 3
const arr1 = arr.splice(1, 0, 2, 3, 4);
console.log(`arr: \t${arr}\tlength: ${arr.length}\tarr1: \t${arr1}\tlength: ${arr1.length}`);
// arr: 1,2,3,4,5,7 length: 6 arr1: [] length: 0
const arr2 = arr.splice(5, 0, 6);
console.log(`arr: \t${arr}\tlength: ${arr.length}\tarr2: \t${arr2}\tlength: ${arr2.length}`);
// arr: 1,2,3,4,5,6,7 length: 7 arr2: [] length: 0
const arr3 = arr.splice(1, 2);
console.log(`arr: \t${arr}\tlength: ${arr.length}\tarr3: \t${arr3}\tlength: ${arr3.length}`);
// arr: 1,4,5,6,7 length: 5 arr3: 2,3 length: 2
const arr4 = arr.splice(2, 1, 'a', 'b');
console.log(`arr: \t${arr}\tlength: ${arr.length}\tarr4: \t${arr4}\tlength: ${arr4.length}`);
// arr: 1,4,a,b,6,7 length: 6 arr4: 5 length: 1
|
import { bind, unbind } from '@segmentstream/utils/eventListener'
import listenEvents from './listenEvents'
import Storage from '../Storage'
const timeout = 10 // 10 seconds
let interval = null
let hasActive = false
let events = []
const storagePrefix = 'timeOnSite:'
const storage = new Storage({ prefix: storagePrefix })
// Load from storage
let activeTime = storage.get('activeTime') || 0
let time = storage.get('time') || 0
const firedEventsJSON = storage.get('firedEvents')
let firedEvents = firedEventsJSON ? JSON.parse(firedEventsJSON) : []
const addEventsListener = () => {
listenEvents.forEach((eventName) => {
bind(window.document, eventName, setActive, false)
})
}
const removeEventsListener = () => {
listenEvents.forEach((eventName) => {
unbind(window.document, eventName, setActive, false)
})
}
const incActiveTime = () => {
activeTime += timeout
storage.set('activeTime', activeTime)
}
const incTime = () => {
time += timeout
storage.set('time', time)
}
const fireEvent = (eventName) => {
firedEvents.push(eventName)
storage.set('firedEvents', JSON.stringify(firedEvents))
}
const processEvents = () => {
if (hasActive) {
incActiveTime()
hasActive = false
}
incTime()
events.forEach((event) => {
const timeForEvent = event.isActiveTime ? activeTime : time
if (!firedEvents.includes(`${event.name}:${event.seconds}`) && event.seconds <= timeForEvent) {
event.handler(timeForEvent)
fireEvent(`${event.name}:${event.seconds}`)
}
})
}
const setActive = () => { hasActive = true }
const addEvent = (seconds, handler, eventName, isActiveTime) => {
events.push({ seconds, handler, isActiveTime, name: eventName })
}
const startTracking = () => {
interval = setInterval(processEvents, timeout * 1000)
addEventsListener()
}
const stopTracking = () => {
clearInterval(interval)
removeEventsListener()
}
startTracking()
export const reset = () => {
if (interval) {
stopTracking()
}
activeTime = 0
time = 0
hasActive = false
firedEvents = []
storage.remove('activeTime')
storage.remove('time')
storage.remove('firedEvents')
startTracking()
}
export default (seconds, handler, eventName, isActiveTime = false) => {
if (!seconds) return
if (typeof handler !== 'function') {
throw new TypeError('Must pass function handler to `ddManager.trackTimeOnSite`.')
}
String(seconds)
.replace(/\s+/mg, '')
.split(',')
.forEach((secondsStr) => {
const second = parseInt(secondsStr)
if (second > 0) {
addEvent(second, handler, eventName, isActiveTime)
}
})
}
|
version https://git-lfs.github.com/spec/v1
oid sha256:81e9c9e173a9043e925313a488beecd37914141528b2ccf21df1fc5620343cb8
size 2512
|
version https://git-lfs.github.com/spec/v1
oid sha256:691b4033e555f469bcdba73a60c0e6a24b38ebffbbf94ebe7ba61e3edbf61601
size 6745
|
// require(d) gulp for compatibility with sublime-gulp.
var gulp = require('gulp');
const { src, dest, series, parallel } = require('gulp');
const clean = require('gulp-clean');
const eslint = require('gulp-eslint');
const csso = require('gulp-csso');
const rename = require('gulp-rename');
const babel = require("gulp-babel");
const minify_babel = require("gulp-babel-minify");
const minify = require('gulp-minify');
const rollup = require('rollup');
// Erase build directory
function cleandist() {
return gulp.src(['build/*'], {read: false, allowEmpty: true})
.pipe(clean())
}
// Lint Task
function lint() {
return gulp.src('./src/*.js')
.pipe(eslint())
.pipe(eslint.format())
}
// Build ES6 module
function build_es6() {
return gulp.src('./src/*.js')
.pipe(minify({
ext: {
src:'.js',
min:'.min.js'
},
preserveComments: 'some',
noSource: true
}))
.pipe(gulp.dest('./build/es6/chordictionary'))
}
// Build CommonJS module
async function build_commonjs() {
const bundle = await rollup.rollup({
input: './src/main.js'
});
await bundle.write({
file: './tmp/chordictionary_cjs.js',
format: 'cjs',
name: 'chordictionary'
});
await gulp.src('./tmp/chordictionary_cjs.js', { allowEmpty: true })
.pipe(clean())
.pipe(babel())
.pipe(rename('chordictionary.min.js'))
.pipe(minify_babel())
.pipe(gulp.dest('./build/commonjs'))
}
// Build IIFE script
async function build_iife() {
const bundle = await rollup.rollup({
input: './src/main.js'
});
await bundle.write({
file: './tmp/chordictionary_iife.js',
format: 'iife',
name: 'chordictionary'
});
await gulp.src('./tmp/chordictionary_iife.js', { allowEmpty: true })
.pipe(clean())
.pipe(babel())
.pipe(rename('chordictionary.min.js'))
.pipe(minify_babel())
.pipe(gulp.dest('./build/iife'));
}
// CSS task
function css() {
return gulp.src('./src/chordictionary.css')
.pipe(csso())
.pipe(rename({ suffix: '.min' }))
.pipe(gulp.dest('./build'));
}
const build = gulp.series(cleandist, gulp.parallel(css, lint), gulp.parallel(build_es6, build_commonjs, build_iife));
exports.lint = lint;
exports.css = css;
exports.clean = cleandist;
exports.build = build;
exports.default = build;
|
var AIO = require('../../index');
// create an instance
aio = AIO(process.env.AIO_KEY || 'xxxxxxxxxxxx');
// get a list of all groups
aio.groups(function(err, data) {
if(err) {
return console.error(err);
}
// log data array
console.log(data);
});
// get a specific group by name
aio.groups('Test', function(err, data) {
if(err) {
return console.error(err);
}
// log data object
console.log(data);
});
|
module.exports = (env = "dev") =>
// you may extend to other env to produce a production build for example
require(`./webpack.${env}.config.js`);
|
'use strict';
// Configuring the Workouts module
angular.module('workouts').run(['Menus',
function(Menus) {
// Add the workouts dropdown item
Menus.addMenuItem('topbar', {
title: 'Workouts',
state: 'workouts',
type: 'dropdown',
position: 0
});
// Add the dropdown list item
Menus.addSubMenuItem('topbar', 'workouts', {
title: 'List Workouts',
state: 'workouts.list'
});
// Add the dropdown create item
Menus.addSubMenuItem('topbar', 'workouts', {
title: 'Create Workouts',
state: 'workouts.create'
});
}
]);
|
/*
Copyright (c) 2011, Chris Umbel
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.
*/
var natural = require('natural'),
classifier = new natural.BayesClassifier();
classifier.train([
{classification: 'software', text: "my unit-tests failed."},
{classification: 'software', text: "tried the program, but it was buggy."},
{classification: 'hardware', text: "the drive has a 2TB capacity."},
{classification: 'hardware', text: "i need a new power supply."}
]);
console.log(classifier.classify('did the tests pass?'));
console.log(classifier.classify('did you buy a new drive?'));
|
var helpers = require('./');
/** Boids is a lot like Castle in the way it treats elements. But it is more
predictable, and retains attribute information.
1. The root node is collapsed, but its name is preserved in document['*']
2. Attributes are stored in a Object<String -> String> mapping, called "$".
* XML elements that are named '$' will conflict with the way boids represents
attributes.
3. in between elements is discarded.
4. Namespacing is taken literally.
5. Relative order between siblings of different names (or text nodes) is
disregarded, though order between siblings of the same name will be
preserved.
*/
function convertNode(node) {
/** Convert a single node into a javascript object. */
var obj = {$: {}};
// save all attributes to the '$' field
node.attrs().forEach(function(attr) {
obj.$[helpers.fullName.apply(attr)] = attr.value();
});
var texts = [];
node.childNodes().forEach(function(node) {
var type = node.type();
if (type == 'element') {
var tag = helpers.fullName.apply(node);
if (obj[tag] === undefined) {
obj[tag] = [];
}
obj[tag].push(convertNode(node));
}
else {
texts.push(node.text());
}
});
// finally concatenate all the text nodes together and save them as the '_' field
obj._ = helpers.parseString(texts.join('').trim());
return obj;
}
function boids(xml, opts) {
var root = helpers.parseXML(xml);
var obj = convertNode(root);
// special root handling:
obj['*'] = root.name();
return obj;
}
module.exports = boids;
|
let express = require('express');
let bodyParser = require('body-parser');
let path = require('path');
module.exports = function() {
let app = express();
app.use(bodyParser.urlencoded({
extended: true
}));
app.use(bodyParser.json());
app.use('/gallery', express.static('public'));
app.get('/gallery', function(req,res) {
res.sendFile(path.join(__dirname + '/../index.html'));
});
return app;
};
|
import { module, test } from 'qunit';
module('Unit | Utility | fd common primitives');
// Replace this with your real tests.
test('it works', function(assert) {
assert.ok(true);
});
|
"use strict";
var __extends = (this && this.__extends) || function (d, b) {
for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
function __() { this.constructor = d; }
d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
};
var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
return c > 3 && r && Object.defineProperty(target, key, r), r;
};
var __metadata = (this && this.__metadata) || function (k, v) {
if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v);
};
var React = require('react');
var _1 = require("../../../");
var bemBlock = require('bem-cn');
var size = require('lodash/size');
var toArray = require('lodash/toArray');
var map = require('lodash/map');
var FilterGroupItem = (function (_super) {
__extends(FilterGroupItem, _super);
function FilterGroupItem(props) {
_super.call(this, props);
this.removeFilter = this.removeFilter.bind(this);
}
FilterGroupItem.prototype.removeFilter = function () {
var _a = this.props, removeFilter = _a.removeFilter, filter = _a.filter;
if (removeFilter) {
removeFilter(filter);
}
};
FilterGroupItem.prototype.render = function () {
var _a = this.props, bemBlocks = _a.bemBlocks, label = _a.label, itemKey = _a.itemKey;
return (React.createElement(_1.FastClick, {handler: this.removeFilter}, React.createElement("div", {className: bemBlocks.items("value"), "data-key": itemKey}, label)));
};
FilterGroupItem = __decorate([
_1.PureRender,
__metadata('design:paramtypes', [Object])
], FilterGroupItem);
return FilterGroupItem;
}(React.Component));
exports.FilterGroupItem = FilterGroupItem;
var FilterGroup = (function (_super) {
__extends(FilterGroup, _super);
function FilterGroup(props) {
_super.call(this, props);
this.removeFilters = this.removeFilters.bind(this);
}
FilterGroup.prototype.removeFilters = function () {
var _a = this.props, removeFilters = _a.removeFilters, filters = _a.filters;
if (removeFilters) {
removeFilters(filters);
}
};
FilterGroup.prototype.render = function () {
var _this = this;
var _a = this.props, mod = _a.mod, className = _a.className, title = _a.title, filters = _a.filters, removeFilters = _a.removeFilters, removeFilter = _a.removeFilter;
var bemBlocks = {
container: bemBlock(mod),
items: bemBlock(mod + "-items")
};
return (React.createElement("div", {key: title, className: bemBlocks.container().mix(className)}, React.createElement("div", {className: bemBlocks.items()}, React.createElement("div", {className: bemBlocks.items("title")}, title), React.createElement("div", {className: bemBlocks.items("list")}, map(filters, function (filter) { return _this.renderFilter(filter, bemBlocks); }))), this.renderRemove(bemBlocks)));
};
FilterGroup.prototype.renderFilter = function (filter, bemBlocks) {
var _a = this.props, translate = _a.translate, removeFilter = _a.removeFilter;
return (React.createElement(FilterGroupItem, {key: filter.value, itemKey: filter.value, bemBlocks: bemBlocks, filter: filter, label: translate(filter.value), removeFilter: removeFilter}));
};
FilterGroup.prototype.renderRemove = function (bemBlocks) {
if (!this.props.removeFilters)
return null;
return (React.createElement(_1.FastClick, {handler: this.removeFilters}, React.createElement("div", {className: bemBlocks.container("remove-action"), onClick: this.removeFilters}, "X")));
};
FilterGroup.defaultProps = {
mod: "sk-filter-group",
translate: function (str) { return str; }
};
return FilterGroup;
}(React.Component));
exports.FilterGroup = FilterGroup;
//# sourceMappingURL=FilterGroup.js.map
|
/**古代战争
* 作者:YYC
* 日期:2014-02-12
* 电子邮箱:395976266@qq.com
* QQ: 395976266
* 博客:http://www.cnblogs.com/chaogex/
*/
var PlantsSprite = YYC.Class(TerrainSprite, {
Protected: {
},
Public: {
name: "plants"
}
});
|
(function (root, undefined) {
"use strict";
|
(function () {
'use strict';
/**
* Introduce the vendorAppApp.customer.list.edit module
* and configure it.
*
* @requires 'ui.router',
* @requires 'ngMaterial',
* @requires vendorAppApp.mongooseError
* @requires vendorAppApp.customer.service
*/
angular
.module('vendorAppApp.customer.list.edit', [
'ui.router',
'ngMaterial',
'vendorAppApp.mongooseError',
'vendorAppApp.customer.service'
])
.config(configureCustomerListEdit);
// inject configCustomerListEdit dependencies
configureCustomerListEdit.$inject = ['$stateProvider'];
/**
* Route configuration function configuring the passed $stateProvider.
* Register the customer.list.edit state with the edit template
* paired with the CustomerEditController as 'edit' for the
* 'detail@customer.list' view.
* 'customer' is resolved as the customer with the id found in
* the state parameters.
*
* @param {$stateProvider} $stateProvider - The state provider to configure
*/
function configureCustomerListEdit($stateProvider) {
// The edit state configuration.
var editState = {
name: 'customer.list.edit',
parent: 'customer.list',
url: '/edit/:id',
authenticate: true,
role: 'user',
onEnter: onEnterCustomerListEdit,
views: {
'detail@customer.list': {
templateUrl: 'app/customer/list/edit/edit.html',
controller: 'CustomerEditController',
controllerAs: 'edit',
resolve: {customer: resolveCustomerFromArray}
}
}
};
$stateProvider.state(editState);
}
// inject onCustomerListEditEnter dependencies
onEnterCustomerListEdit.$inject = ['$timeout', 'ToggleComponent'];
/**
* Executed when entering the customer.list.detail state. Open the component
* registered with the component id 'customer.detailView'.
*
* @params {$timeout} $timeout - The $timeout service to wait for view initialization
* @params {ToggleComponent} ToggleComponent - The service to toggle the detail view
*/
function onEnterCustomerListEdit($timeout, ToggleComponent) {
$timeout(showDetails, 0, false);
function showDetails() {
ToggleComponent('customer.detailView').open();
}
}
// inject resolveCustomerDetailRoute dependencies
resolveCustomerFromArray.$inject = ['customers', '$stateParams', '_'];
/**
* Resolve dependencies for the customer.list.edit state. Get the customer
* from the injected Array of customers by using the '_id' property.
*
* @params {Array} customers - The array of customers
* @params {Object} $stateParams - The $stateParams to read the customer id from
* @params {Object} _ - The lodash service to find the requested customer
* @returns {Object|null} The customer whose value of the _id property equals $stateParams._id
*/
function resolveCustomerFromArray(customers, $stateParams, _) {
// return Customer.get({id: $stateParams.id}).$promise;
return _.find(customers, {'_id': $stateParams.id});
}
})();
|
jQuery(function(){
'use strict';
var Test={};
var tests=[];
var messages={
success: 'Success',
failed: 'FAILED',
pending: 'Pending...'
};
var classes = {
success: 'success',
failed: 'danger',
pending: 'warning'
}
var row_id_prefix = 'tests_td_';
var textProperty = (document.createElement('span').textContent !== undefined) ? 'textContent' : 'innerText';
var row_template = document.createElement('tr');
row_template.appendChild(document.createElement('td'));
row_template.appendChild(document.createElement('td'));
row_template.appendChild(document.createElement('td'));
var tbody = document.getElementById('results_tbody');
Test.add = function(group, func){
var row;
tests.push({group: group, func: func});
row = row_template.cloneNode(true);
row.id = 'tests_td_' + (tests.length-1);
row.getElementsByTagName('td')[0][textProperty] = group;
tbody.appendChild(row);
};
function TestController(row){
this._row = row;
this._asserted = false;
this._status='pending';
}
var assertionFailed = {};
TestController.prototype._setStatus=function(status, extra){
var status_td = this._row.getElementsByTagName('td')[1];
var display_string = messages[status];
if(extra){
display_string += " (" + extra + ")";
}
status_td[textProperty] = display_string;
status_td.className = classes[status];
this._status = status;
};
TestController.prototype._setDescription=function(desc){
var desc_td = this._row.getElementsByTagName('td')[2];
desc_td[textProperty] = desc;
}
TestController.prototype.assert = function(value, desc){
this._asserted = true;
if(value !== true){
this._setStatus('failed');
this._setDescription('Assertion failed: ' + desc);
throw assertionFailed;
}
};
TestController.prototype.must_throw = function(func, desc){
var thrown = false;
if(!desc){
desc = 'expected to throw exception';
}
try{
func();
}catch(e){
thrown = true;
}
this.assert(thrown, desc);
};
TestController.prototype.must_not_be_called = function(desc){
var test_controller = this;
if(!desc){
desc = 'function is not called';
}
return function(){
test_controller.assert(false, desc);
};
}
Test.run = function(){
var i = 0, num_tests = tests.length;
var t;
for(; i< num_tests; ++i){
t = new TestController(document.getElementById('tests_td_' + i));
t._setStatus('pending');
try{
tests[i].func(t);
if(t._status === 'pending'){
if(t._asserted){
//Success all tests
t._setStatus('success');
}else{
t._setDescription('No assertion was given.');
}
}
}catch(e){
if(e !== assertionFailed){
t._setStatus('failed','exception');
t._setDescription(e.message);
}
}
}
};
window.Test=Test;
});
|
'use strict';
var _ = require('underscore'),
through2 = require('through2'),
fs = require('fs'),
hdiff = require('hdiff'),
spawn = require('child_process').spawn,
which = require('which'),
gutil = require('gulp-util'),
path = require('path');
module.exports = function () {
var diffMapper = jsonDiffMapper();
return through2(
{objectMode: true},
function (file, enc, cb) {
log('Checking ' + file.path + 'for updates');
execCommands(_.map(_.filter(mapDiffToCommands(diffMapper(file)), filterEmptyCommands), commandToCurrentCwdMapper(path.dirname(file.path))), cb);
this.push(file);
}
)
}
function log() {
return gutil.log.apply(gutil, [].slice.call(arguments));
}
function filterEmptyCommands(cmd) {
return !!cmd.length;
}
function execCommands(cmds, cb) {
if (!cmds.length) return cb();
var cmd = cmds.shift();
which(cmd[0], function (err, cmdpath) {
if (err) {
log("Couldn't find the path to " + cmd[0]);
return cb(err);
}
log(cmd[0] + ' ' + cmd[1].join(' '));
cmd[0] = cmdpath;
cmd[2].stdio = 'inherit';
cmd = spawn.apply(spawn, cmd);
cmd.on('close', function onClose() { return execCommands(cmds, cb); })
})
}
function jsonDiffMapper() {
var cache = {};
return function (file) {
var oldJson = cache[file.path];
var newJson = JSON.parse(fs.readFileSync(file.path, {encoding: 'utf8'}));
cache[file.path] = newJson;
if (!oldJson)
return {'$new': newJson}
return hdiff(oldJson, newJson, {unchanged: false});
}
}
function commandToCurrentCwdMapper(cwd) {
return function (cmd) {
if (!cmd) return;
cmd[2] = cmd[2] || {};
cmd[2].cwd = cwd;
return cmd;
}
}
function mapDiffToCommands(diff) {
if (!diff) return [];
var mappers = [mapInstallToCmd, mapRemoveToCmd, mapUpdateToCmd];
return _.union(
mapNewToCmds(diff),
mapDependenciesToCmds(diff.dependencies, mappers),
_.map(mapDependenciesToCmds(diff.devDependencies, mappers), mapDevCmds)
);
}
function mapNewToCmds(diff) {
if (!diff['$new']) return [];
return [createCommand('npm',['install'])];
}
function mapDependenciesToCmds(deps, mappers) {
if (!_.isObject(deps)) return [];
var cmds = [];
_.each(mappers,function(mapper) {
cmds.push(_mapDependenciesToCmds(deps, mapper));
})
return _.union.apply(_, cmds);
}
function _mapDependenciesToCmds(deps, mapper) {
if (!_.isObject(deps)) return [];
var cmds = [];
_.each(deps,function(diff, pkg) {
var cmd = mapper(diff, pkg);
if (cmd)
cmds.push(cmd);
})
return cmds;
}
function mapRemoveToCmd(diff, pkg) {
if (!isRemove(diff)) return;
return createCommand('npm',['remove', pkg]);
}
function mapInstallToCmd(diff, pkg) {
if (!isInstall(diff)) return [];
return createCommand('npm',['install', resolveFullPackageName(diff, pkg)]);
}
function mapUpdateToCmd(diff, pkg) {
if (!isUpdate(diff)) return [];
return createCommand('npm',['install', resolveFullPackageName(diff, pkg)]);
}
function mapDevCmds(cmd) {
if (cmd.length)
cmd[1].push('--save-dev');
return cmd;
}
function isUpdate(diff){ return diff['$add'] && diff['$del']; }
function isInstall(diff){ return diff['$add'] && !diff['$del']; }
function isRemove(diff){ return !diff['$add'] && diff['$del']; }
function resolveFullPackageName(diff, pkg) {
if (!diff['$add']) return pkg;
return pkg + '@' + diff['$add'];
}
function createCommand(cmd, args, opts) {
return [cmd, args, opts || {}];
}
|
import { FieldErrorProcessor } from "./processors/field-error-processor";
import { RuleResolver } from "./rulesets/rule-resolver";
import { ValidationGroupBuilder } from "./builders/validation-group-builder";
import { ruleRegistry } from "./rule-registry-setup";
import { RulesetBuilder } from "./builders/ruleset-builder";
import { DefaultLocaleHandler } from "./localization/default-locale-handler";
import { locale as defaultLocale } from "./locales/en-us";
import { Ruleset } from "./rulesets/ruleset";
const defaultLocaleCode = "en-us";
const defaultLocaleHandler = new DefaultLocaleHandler();
defaultLocaleHandler.registerLocale(defaultLocaleCode, defaultLocale);
defaultLocaleHandler.useLocale(defaultLocaleCode);
const fieldErrorProcessor = new FieldErrorProcessor(ruleRegistry, defaultLocaleHandler);
const ruleResolver = new RuleResolver();
export function createRuleset(basedUpon, withRuleVerification = false) {
const rulesetBuilder = withRuleVerification ? new RulesetBuilder(ruleRegistry) : new RulesetBuilder();
return rulesetBuilder.create(basedUpon);
}
export function mergeRulesets(rulesetA, rulesetB) {
const newRuleset = new Ruleset();
newRuleset.rules = Object.assign({}, rulesetA.rules, rulesetB.rules);
newRuleset.compositeRules = Object.assign({}, rulesetA.compositeRules, rulesetB.compositeRules);
newRuleset.propertyDisplayNames = Object.assign({}, rulesetA.propertyDisplayNames, rulesetB.propertyDisplayNames);
return newRuleset;
}
export function createGroup() { return new ValidationGroupBuilder(fieldErrorProcessor, ruleResolver, defaultLocaleHandler).create(); }
export const localeHandler = defaultLocaleHandler;
export function supplementLocale(localeCode, localeResource) {
defaultLocaleHandler.supplementLocaleFrom(localeCode, localeResource);
}
|
define([],function(){
var config = {};
config.title="Domain Totals Report";
var backColor = '#ffffff';
var axisColor = '#3e3e3e';
var gridlinesColor = '#000000';
var axisTitleColor = '#333333';
var color1 = '#4BACC6';
var color2 = '#8064A2';
var color3 = '#eda637';
var color4 = '#a7a737';
var color5 = '#86aa65';
var color6 = '#8aabaf';
var color7 = '#69c8ff';
var color8 = '#3e3e3e';
var color9 = '#4bb3d3';
config.height=550,
config.width= '100%';
config.title="Domain Totals Report";
config.vAxis= {maxValue: 100};
config.backgroundColor= backColor;
config.chartArea={left: 165, width:"100%",height:"75%"};
config.hAxis= {title: 'Domain', textStyle: {color: axisTitleColor}};
config.vAxis= {title: '# of Visits', gridlines: {count: 5, color: gridlinesColor},format:0, baselineColor:axisColor, textStyle:{color: axisTitleColor}};
config.colors= [ color1, color2, color3, color4, color5, color6, color7, color8];
config.visType="PieChart";
return config;
});
|
/*
* Copyright (c) 2012-2014 André Bargull
* Alle Rechte vorbehalten / All Rights Reserved. Use is subject to license terms.
*
* <https://github.com/anba/es6draft>
*/
const {
assertSame
} = Assert;
// 22.2.1.2 %TypedArray%: Different [[Prototype]] for copied ArrayBuffer depending on element types
// https://bugs.ecmascript.org/show_bug.cgi?id=2175
class MyArrayBuffer extends ArrayBuffer {}
let source = new Int8Array(new MyArrayBuffer(10));
let copySameType = new Int8Array(source);
assertSame(copySameType.buffer.constructor, MyArrayBuffer);
assertSame(Object.getPrototypeOf(copySameType.buffer), MyArrayBuffer.prototype);
let copyDifferentType = new Uint8Array(source);
assertSame(copyDifferentType.buffer.constructor, MyArrayBuffer);
assertSame(Object.getPrototypeOf(copyDifferentType.buffer), MyArrayBuffer.prototype);
|
/* * @felipe de jesus | iti_fjpp@hotmail.com */
var msj_beforeSend=function (){
bootbox.dialog({
title: 'Vive Pueblos Mágicos',
message: '<center><i class="fa fa-spinner fa-spin fa-3x msjOk"></i><br>Espere por favor.</center>'
,onEscape : function() {}
});
//fa fa-times
$('body .modal-body').addClass('text_25');
$('.modal-title').css({
'color' : 'white',
'text-align' : 'left'
});
$('.close').css({
'color' : 'white',
'font-size' : 'x-large'
});
};
var isValidEmail=function (mail){
return /^\w+([\.-]?\w+)*@\w+([\.-]?\w+)*(\.\w{2,4})+$/.test(mail);
}
function ventana(){
coordx= screen.width ? (screen.width-200)/2 : 0;
coordy= screen.height ? (screen.height-150)/2 : 0;
window.open(base_url+ 'config/mapa','miventana','width=800,height=600,top=30,right='+coordx+',left='+coordy);
} ;
var msj_error_noti=function (msj){
Messenger().post({
message: msj,
type: 'error',
showCloseButton: true
});
}
var msj_error_serve=function (){
Messenger().post({
message: 'Error al procesar la petición al servidor',
type: 'error',
showCloseButton: true
});
}
var msj_success_noti=function (msj){
Messenger().post({
message: msj,
showCloseButton: true
});
}
var msj_ok=function (titulo,msj,redirec){
bootbox.dialog({
title: 'Vive Pueblos Mágicos | '+(titulo == undefined ? '' : titulo),
message: '<center><i class="fa fa-check fa-4x msjOk"></i><br>'+(msj == undefined ? 'Acción realizado correctamente' : msj)+'</center>',
closeButton: true,
buttons: {
success: {
label : 'Aceptar',
className : 'green-msj btn btn-primary btn-cons',
callback : function(result) {
if(redirec!=undefined){
location.replace(redirec);
}
}
}
},onEscape : function() {}
});
//fa fa-times
$('body .modal-body').addClass('text_25');
$('.modal-title').css({
'color' : 'white',
'text-align' : 'left'
});
$('.close').css({
'color' : 'white',
'font-size' : 'x-large'
});
}
var msj_error=function (titulo,msj){
bootbox.dialog({
title: 'Vive Pueblos Mágicos | '+(titulo == undefined ? '' : titulo),
message: '<center><i class="fa fa-times fa-4x msjOk"></i><br>'+(msj == undefined ? 'Error al realizar la acción' : msj)+'</center>',
closeButton: true,
buttons: {
success: {
label : 'Aceptar',
className : 'green-msj btn btn-primary btn-cons',
callback : function(result) {
//location.replace(base_url)
}
}
},onEscape : function() {}
});
//fa
$('body .modal-body').addClass('text_25');
$('.modal-title').css({
'color' : 'white',
'text-align' : 'left'
});
$('.close').css({
'color' : 'white',
'font-size' : 'x-large'
});
}
var title=function (titulo){
document.title=(titulo ==undefined ? 'Vive Pueblos Mágicos' :titulo );
}
var get_fecha=function (){
var meses = new Array ("Enero","Febrero","Marzo","Abril","Mayo","Junio","Julio","Agosto","Septiembre","Octubre","Noviembre","Diciembre");
var diasSemana = new Array("Domingo","Lunes","Martes","Miércoles","Jueves","Viernes","Sábado");
var f=new Date();
return diasSemana[f.getDay()] + " " + f.getDate() + " de " + meses[f.getMonth()] + " de " + f.getFullYear();
}
var fecha_yyyy_mm_dd=function (){
var hoy = new Date();
var dd = hoy.getDate();
var mm = hoy.getMonth()+1; //hoy es 0!
var yyyy = hoy.getFullYear();
if(dd<10) {
dd='0'+dd;
}
if(mm<10) {
mm='0'+mm;
}
return yyyy+'/'+mm+'/'+dd;
}
var fecha_dd_mm_yyyy=function (){
var hoy = new Date();
var dd = hoy.getDate();
var mm = hoy.getMonth()+1; //hoy es 0!
var yyyy = hoy.getFullYear();
if(dd<10) {
dd='0'+dd;
}
if(mm<10) {
mm='0'+mm;
}
return dd+'/'+mm+'/'+yyyy;
}
|
// @flow
import { Parser, DomHandler } from 'htmlparser2';
const textToDOM = (html: string): any => {
const handler = new DomHandler();
const parser = new Parser(handler);
parser.write(html);
parser.done();
return handler.dom;
};
export default textToDOM;
|
// Modules.
let gulp = require('gulp'),
config = require('../../config'),
path = require('path');
// Package libraries.
gulp.task('package:css', () => {
'use strict';
let sourcePath = path.join(config.development.paths.css, '**/*');
let destinationPath = config.package.paths.css;
return gulp
.src([sourcePath])
.pipe(gulp.dest(destinationPath));
});
|
const escapeStringRegexp = require('escape-string-regexp');
const query = require('../query/query');
const Sort = require('../helpers/sort');
const StringScore = require('../helpers/string-score');
const DataSource = {
cells: (name) => {
return new Promise((resolve) => {
// calculate text search score
const textMatch = (matches) => {
const arrWithScores = matches.map((matchedTerm) => {
return Object.assign(
{},
matchedTerm,
{
score: StringScore(matchedTerm.name, name),
}
);
});
const sorted = Sort.arrayOfObjectByKeyNumber(arrWithScores, 'score', 'desc');
// add _id to name because some cell lines have the same name
return sorted.map((cell) => {
return Object.assign(
{},
cell,
{
name: `${cell.name}; ${cell._id}`,
}
);
});
};
if (!name) {
resolve({
status: 200,
clientResponse: {
status: 200,
data: [],
message: 'Species string searched',
},
});
} else {
const escapedString = escapeStringRegexp(name);
const re = new RegExp(`^${escapedString}`, 'i');
query.get('cells', { name: { $regex: re } }, { })
.then((matches) => {
const sortedResults = textMatch(matches);
resolve({
status: 200,
clientResponse: {
status: 200,
data: sortedResults,
message: 'Cell string searched',
},
});
})
.catch((error) => {
resolve({
status: 500,
clientResponse: {
status: 500,
message: `There was an error querying the text string ${name}: ${error}`,
},
});
})
;
}
});
},
species: (name) => {
return new Promise((resolve) => {
// calculate text search score
const textMatch = (matches) => {
const arrWithScores = matches.map((matchedTerm) => {
return Object.assign(
{},
matchedTerm,
{
score: StringScore(matchedTerm.name, name),
}
);
});
return Sort.arrayOfObjectByKeyNumber(arrWithScores, 'score', 'desc');
};
if (!name) {
resolve({
status: 200,
clientResponse: {
status: 200,
data: [],
message: 'Species string searched',
},
});
} else {
const escapedString = escapeStringRegexp(name);
const re = new RegExp(`^${escapedString}`, 'i');
query.get('species', { name: { $regex: re } }, { })
.then((matches) => {
const sortedResults = textMatch(matches);
resolve({
status: 200,
clientResponse: {
status: 200,
data: sortedResults,
message: 'Species string searched',
},
});
})
.catch((error) => {
resolve({
status: 500,
clientResponse: {
status: 500,
message: `There was an error querying the text string ${name}: ${error}`,
},
});
})
;
}
});
},
};
module.exports = DataSource;
|
<%= grunt.util._.camelize(appname) %>.Routers.<%= _.classify(name) %>Router = Backbone.Router.extend({
routes: {
"login" : "login"
},
initialize : function(){
var self = this;
},
login: function(){
var self = this;
}
});
|
class Ranking { //object for ranking in curiosity
constructor(){// in contructor set a values for default in this class
ranking.colorActive = "#2262ae";//colors of active stars
ranking.colorUnActive = "rgba(46,46,46,0.75)";//colors for unactive stars
ranking.stars = 0;//number of stars in ranking
ranking.averageStars = 0;//average of ranking
}
show (color){
ranking.colorActive = color;//colors of active stars
ranking.colorUnActive = "rgba(46,46,46,0.75)";//colors for unactive stars
ranking.stars = 0;//number of stars in ranking
ranking.averageStars = 0;//average of ranking
$.each($(".curiosity-ranking"),function(indx,object){//rut to rankings
object.style = "display:block";//show rankings
ranking.averageStars = object.getAttribute("data-stars");// get data stars
ranking.stars = (Math.floor(ranking.averageStars));// convert to int data stars
$(object).find(".star-text").text(ranking.averageStars);
ranking.runRankingSetColors($(object),ranking.stars);
});
}
init(){//init function
this.setDatasToRankings();
}
setDatasToRankings(){//this function set values to ranking this date get from attribute data-stars in html
var these = this;
$.each($(".curiosity-ranking"),function(indx,object){//rut to rankings
object.style = "display:block";//show rankings
ranking.averageStars = object.getAttribute("data-stars");// get data stars
ranking.stars = (Math.floor(ranking.averageStars));// convert to int data stars
$(object).find(".star-text").text(ranking.averageStars);
$.each($(object).children(),function(index,obj){
obj.addEventListener("mouseover",these.hoverStar,false);
obj.addEventListener("mouseout",these.mouseOut,false);
if(index <= ranking.stars){
obj.style = "color:"+ranking.colorActive+";";
}
});
});
}
uploadStars(itemRanking,averageStars){//upload data stars in ranking element
if(averageStars>5 && averageStars<0){//validate data parameter
console.error("El segundo parametros recivido tiene que ser menor que 5 y mayor que 0");
}else{//if data parameter is correct
var parent = itemRanking.parentNode;// get ranking element(ul)
var stars = Math.floor(averageStars);// convert to int data stars
parent.setAttribute("data-stars",averageStars);//set new data stars to ranking
$(parent).find(".star-text").text(averageStars);//set text of average stars
ranking.runRankingSetColors($(parent),stars);// paint stars
}
}
hoverStar(event){//hover event
var starIndex = $(event.target).index();
ranking.runRankingSetColors($(event.target.parentNode),starIndex);
}
mouseOut(event){// mouse over event
var limitStars = Math.floor(event.target.parentNode.getAttribute("data-stars"));
ranking.runRankingSetColors($(event.target.parentNode),limitStars);
}
setColorActive(color){//set new color in case active
if(/^#[0-9][a-fA-F]{6}$/.test(color) || /^rgb\([0-9]{1,3}\,[0-9]{1,3}\,[0-9]{1,3}\)$/.test(color)){
ranking.colorActive = color;
}
else{
console.error("El parametro de la funcion setBackgroundColor debe ser hexadecimal o rgb");
}
}
setColorUnActive(color){//set new color in case unactive
if(/^#[0-9][a-fA-F]{6}$/.test(color) || /^rgb\([0-9]{1,3}\,[0-9]{1,3}\,[0-9]{1,3}\)$/.test(color)){
ranking.colorUnActive = color;
}
else{
console.error("El parametro de la funcion setBackgroundColor debe ser hexadecimal o rgb");
}
}
setEventClick(clickfunction){
if($.isFunction(clickfunction)){
$(".curiosity-ranking>li.item-ranking").click(clickfunction);
}else{
console.error("El parametro recibido tiene que ser una función");
}
}
};
var ranking = {//object with values to use in this class
colorActive : "",
colorUnActive : "",
stars : 0,
averageStars : 0,
runRankingSetColors : function(rankingElement,limitStars){//run to item ranking for set stars
$.each(rankingElement.children(),function(index,object){
if(index <= limitStars){
object.style = "color:"+ranking.colorActive+";";
}else{
object.style = "color:"+ranking.colorUnActive+";";
}
});
}
};
//end of document
|
'use strict';
const ServiceEmitter = require('./lib/ServiceEmitter');
const ServiceProvider = require('./lib/ServiceProvider');
module.exports = { ServiceEmitter, ServiceProvider };
|
const should = require('should');
var Regex = require('../');
var conStr = 'dHello World';
describe( 'replace test', function () {
it( 'left area', function () {
var regex = new Regex('H');
regex.replace(conStr,'h').should.equal('dhello World');
} );
it( 'middle area', function () {
var regex = new Regex('o\\sW');
regex.replace(conStr,'T').should.equal('dHellTorld');
} );
it( 'right area', function () {
var regex = new Regex('d$');
regex.replace(conStr,'P').should.equal('dHello WorlP');
} );
it( 'more match', function () {
var regex = new Regex('o','ig');
regex.replace(conStr,'').should.equal('dHell Wrld');
} );
} );
|
/*global beforeEach, describe, it,*/
/*eslint no-unused-expressions: 0*/
'use strict';
require('./testdom')('<html><body></body></html>');
var expect = require('chai').expect;
var React = require('react/addons');
var TestUtils = React.addons.TestUtils;
var BookmarkList = require('./../../react/component/BookmarkList');
var BookmarkListItem = require('./../../react/component/BookmarkListItem');
describe('BookmarkList', function() {
var component;
beforeEach(function() {
component = TestUtils.renderIntoDocument(<BookmarkList />);
});
it('renders a dom element', function() {
expect(component.getDOMNode().tagName.toLowerCase()).to.be.not.empty;
});
describe('with bookmarks', function() {
var bookmarks,
items;
beforeEach(function() {
bookmarks = [1, 23, 42, 678].map(v => ({
url: `http://some-url.com/${v}`,
tags: `#static #${v}`
}));
component.setProps({bookmarks: bookmarks});
items = TestUtils.scryRenderedComponentsWithType(component, BookmarkListItem);
});
it('displays a BookmarkListItem for each data element', function() {
expect(items).to.have.length.of(bookmarks.length);
});
it('passes the url as children to the BookmarkListItem', function() {
items.forEach((item, idx) =>
expect(item.props.children).to.equal(bookmarks[idx].url));
});
it('passes the tags via the tags attribute to the BookmarkListItem', function() {
items.forEach((item, idx) =>
expect(item.props.tags).to.equal(bookmarks[idx].tags));
});
});
});
|
import Icon from '../components/Icon.vue'
Icon.register({
'mars-stroke-h': {
width: 480,
height: 512,
paths: [
{
d: 'M476.2 247.5c4.7 4.7 4.7 12.3 0.1 17l-55.9 55.9c-7.6 7.5-20.5 2.2-20.5-8.5v-23.9h-23.9v20c0 6.6-5.4 12-12 12h-40c-6.6 0-12-5.4-12-12v-20h-27.6c-5.8 25.6-18.7 49.9-38.6 69.8-56.2 56.2-147.4 56.2-203.6 0s-56.2-147.4 0-203.6 147.4-56.2 203.6 0c19.9 19.9 32.8 44.2 38.6 69.8h27.6v-20c0-6.6 5.4-12 12-12h40c6.6 0 12 5.4 12 12v20h23.8v-23.9c0-10.7 12.9-16.1 20.5-8.5zM200.6 312.6c31.2-31.2 31.2-82 0-113.1-31.2-31.2-81.9-31.2-113.1 0s-31.2 81.9 0 113.1c31.2 31.2 81.9 31.2 113.1 0z'
}
]
}
})
|
'use strict';
// Use application configuration module to register a new module
ApplicationConfiguration.registerModule('client');
|
'use strict';
exports.port = process.env.PORT || 3000;
exports.mongodb = {
uri: process.env.MONGOLAB_URI || process.env.MONGOHQ_URL || 'localhost/lulucrawler'
};
exports.getThisUrl = '';
exports.companyName = '';
exports.projectName = 'luluCrawler';
exports.systemEmail = 'your@email.addy';
exports.cryptoKey = 'k3yb0ardc4t';
exports.loginAttempts = {
forIp: 50,
forIpAndUser: 7,
logExpiration: '20m'
};
exports.smtp = {
from: {
name: process.env.SMTP_FROM_NAME || exports.projectName +' Website',
address: process.env.SMTP_FROM_ADDRESS || 'your@email.addy'
},
credentials: {
user: process.env.SMTP_USERNAME || 'your@email.addy',
password: process.env.SMTP_PASSWORD || 'bl4rg!',
host: process.env.SMTP_HOST || 'smtp.gmail.com',
ssl: true
}
};
|
(function($){
$(document).ready(function(){
$('.rainbowcake').rainbowcake();
});
}(jQuery));
|
'use strict';
module.exports = function(gulp, plugins) {
// Test /task/
// Run all available test tasks.
// $ gulp test
//
gulp.task('test', function(done) {
plugins.runSequence('jshint', done);
});
// JSHint /test/
// JavaScript Code Quality Tool - Helps to detect errors and potential problems in code.
// $ gulp jshint
//
gulp.task('jshint', function() {
return gulp.src([
'./gulpfile.js',
'./task/**/*.js',
'./app/index.js'
])
.pipe(plugins.jshint('./.jshintrc'))
.pipe(plugins.jshint.reporter('jshint-stylish'))
.pipe(plugins.jshint.reporter('fail'));
});
};
|
// function add(a, b){
// return a+b;
// }
//
// console.log(add(3,1));
//
// var toAdd = [9, 5];
// console.log(add(...toAdd));
// var groupA = ['Jen', 'Cory'];
// var groupB = ['Vikram'];
// var final = [...groupB, 3, ...groupA];
// console.log(...final);
var person = ['Andew', 25];
var personTwo = ['Jen', 29];
function greetingAge(a, b){
return 'Hi '+a+', you are '+ b;
}
console.log(greetingAge(...person));
console.log(greetingAge(...personTwo));
var names = ['Mike', 'Ben'];
var final = ['Quentin', ...names];
for(i in final){
console.log('Hi '+ final[i]);
}
|
Brick.util.Language.add('en',{'mod': {'{C#MODNAME}':{
'accounteditor': {
'widget': {
'1': 'Add account'
},
'editor': {
'1': 'Edit account',
'2': 'Create account',
'3': 'Save',
'4': 'Cancel',
'5': 'Close'
},
'row': {
'1': 'Remove this account',
'2': 'Remove',
'3': 'Account type',
'4': 'Title',
'5': 'Remark',
'6': 'Opening balance',
'7': 'Currency',
'8': 'Member account'
}
}
}}});
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.