text
stringlengths 2
6.14k
|
|---|
/*
** Backbone-books by Sebastien Chopin
** @Atinux
** http://www.atinux.fr
*/
(function () {
// Please use your Google API key, be cool :) (http://code.google.com/apis/books/docs/v1/getting_started.html)
var Book, Books, BookView, LibraryView, apiKey = 'AIzaSyAUpierWu7ydjKsa2141jS55CCnqu7JXZo';
// Model
Book = Backbone.Model.extend(),
// Book View
BookView = Backbone.View.extend({
tagName: 'div',
initialize: function () {
var that = this;
this.model.attributes.volumeInfo = this.model.attributes.volumeInfo || {};
this.model.attributes.volumeInfo.imageLinks = this.model.attributes.volumeInfo.imageLinks || {};
setTimeout(function () {
that.render();
}, this.options.time);
},
events: {
'click': 'showBookDetail'
},
render: function () {
if (this.options.parent.lastSearch === this.options.lastSearch) {
var template = $('#bookTemplate').html();
this.$el.html(_.template(template, { model: this.model }));
this.$el.hide().appendTo('.books').fadeIn(200);
}
},
showBookDetail: function () {
var parent = this.options.parent,
scrollTop = parent.$('.library').scrollTop(),
bookDetail = parent.$('.bookDetail'),
that = this;
parent.showBookDetail = true;
parent.bookDetailTop = scrollTop;
bookDetail.css({
'top': scrollTop,
'bottom': -scrollTop
})
.html(_.template($('#bookDetailTemplate').html(), { hash: this.model.toJSON() }))
.fadeIn();
// Call the self link to check if a better resolution of the image is available
if (!this.model.attributes.volumeInfo.imageLinks.small) {
$.ajax({
url: 'https://www.googleapis.com/books/v1/volumes/'+this.model.id,
dataType: 'jsonp',
data: 'fields=volumeInfo/imageLinks&key='+apiKey,
success: function (res) {
if (res.volumeInfo && res.volumeInfo.imageLinks && res.volumeInfo.imageLinks.small) {
that.model.attributes.volumeInfo.imageLinks.small = res.volumeInfo.imageLinks.small;
}
else {
that.model.attributes.volumeInfo.imageLinks.small = 'bad';
}
that.addBiggerImage();
}
});
}
else {
this.addBiggerImage();
}
},
addBiggerImage: function () {
var smallImg = this.model.attributes.volumeInfo.imageLinks.small;
if (smallImg !== 'bad') {
this.options.parent.$('.imgBook').append('<img src="'+ smallImg.replace('&edge=curl', '') +'" />');
}
}
});
// Library View
LibraryView = Backbone.View.extend({
initialize: function () {
// this.books = new Books();
this.search();
// Bind scroll event
_.bindAll(this, 'hideBookDetailScroll');
this.$('.library').scroll(this.hideBookDetailScroll);
_.bindAll(this, 'moreBooks');
this.$('.library').scroll(this.moreBooks);
},
events: {
'change .searchValue': 'search',
'click .close': 'hideBookDetail'
},
search: function (e) {
this.s = this.$('.searchValue').val(),
lastSearch = new Date().getTime(),
that = this;
that.$('.books').html('');
this.lastSearch = lastSearch;
this.$('.spinner').fadeIn();
this.page = 0;
if (this.s.trim().length) {
$.ajax({
url: 'https://www.googleapis.com/books/v1/volumes',
dataType: 'jsonp',
data: 'q='+encodeURIComponent(this.s)+'&maxResults=40&key='+apiKey+'&fields=totalItems,items(id,volumeInfo/title,volumeInfo/subtitle,volumeInfo/authors,volumeInfo/publishedDate,volumeInfo/description,volumeInfo/imageLinks)',
success: function (res) {
that.$('.spinner').fadeOut();
that.nbMaxPage = Math.ceil(res.totalItems / 40);
if (that.lastSearch === lastSearch) {
if (res.items && res.items.length) {
for (var i in res.items) {
new BookView({
model: new Book(res.items[i]),
time: 80 * i,
lastSearch: lastSearch,
parent: that
});
}
}
else if (res.error) {
that.$('.books').html('<h1 class="notFound">Error, please retry later :s</h1>');
}
else {
that.$('.books').html('<h1 class="notFound">No books found</h1>');
}
}
}
});
}
else {
that.$('.books').html('<h1 class="notFound">Hummmm, can do better :)</h1>');
that.$('.spinner').fadeOut();
}
},
hideBookDetailScroll: function () {
if (this.showBookDetail) {
var actualTop = this.$('.library').scrollTop(),
marge = 150;
if (actualTop > this.bookDetailTop + marge || actualTop < this.bookDetailTop - marge) {
this.showBookDetail = false;
this.hideBookDetail();
}
}
},
hideBookDetail: function () {
this.$('.bookDetail').fadeOut();
},
moreBooks: function () {
var totalHeight = this.$('.library > div').height(),
scrollTop = this.$('.library').scrollTop() + this.$('.library').height(),
lastSearch = this.lastSearch,
that = this,
marge = 200;
if (scrollTop + marge >= totalHeight && !this.loadingMore && this.page < this.nbMaxPage) {
this.loadingMore = true;
this.page++;
this.$('.spinner').fadeIn();
$.ajax({
url: 'https://www.googleapis.com/books/v1/volumes',
dataType: 'jsonp',
data: 'q='+encodeURIComponent(this.s)+'&startIndex='+(this.page * 40)+'&maxResults=40&key='+apiKey+'&fields=totalItems,items(id,volumeInfo/title,volumeInfo/subtitle,volumeInfo/authors,volumeInfo/publishedDate,volumeInfo/description,volumeInfo/imageLinks)',
success: function (res) {
that.$('.spinner').fadeOut();
that.loadingMore = false;
if (that.lastSearch === lastSearch && res.items && res.items.length) {
for (var i in res.items) {
new BookView({
model: new Book(res.items[i]),
time: 80 * i,
lastSearch: lastSearch,
parent: that
});
}
}
}
});
}
}
});
// Run application
$(function () {
new LibraryView({
el: $('#content')
});
});
})();
|
define([ 'game/events', 'game/scene/scene', 'game/scene/camera' ], function (events, scene, camera) {
var container = document.getElementById('game-container');
var renderer = new THREE.WebGLRenderer( { clearColor: 0xefd1b5, clearAlpha: 1 } );
renderer.shadowMapEnabled = true;
renderer.setSize(window.innerWidth, window.innerHeight);
container.appendChild(renderer.domElement);
events.on('game:resize', function () {
renderer.setSize(window.innerWidth, window.innerHeight);
});
events.on('game:render', function () {
renderer.render(scene, camera);
});
return renderer;
})
|
//var word : string = "请输入想要输出的金字塔层数"
function pyramid(totalLine) {
for (var currentLine = 1; currentLine <= totalLine; currentLine++) {
var singleLineStr = "";
for (var spaceCount = totalLine - currentLine; spaceCount > 0; spaceCount--) {
singleLineStr += " ";
}
for (var starCount = 1; starCount <= (currentLine * 2) - 1; starCount++) {
singleLineStr += "*";
}
console.log(singleLineStr);
}
}
var num = process.argv[2];
if (!num) {
}
else {
pyramid(parseInt(num));
}
//# sourceMappingURL=main.js.map
|
var _ = require('./');
// Browsers to run on Sauce Labs platforms
// (See https://saucelabs.com/platform/supported-browsers-devices for an
// up-to-date overview of supported versions of browsers and platforms.)
var sauceBrowsers = _.reduce([
['firefox', 'latest'],
['firefox', '60'],
['firefox', '40'],
['firefox', '11'],
// ['firefox', '4'], // failing due to "not enough arguments"
['chrome', 'latest'],
['chrome', '60'],
['chrome', '40'],
['chrome', '26'],
// latest Edge as well as pre-Blink versions
['microsoftedge', 'latest', 'Windows 10'],
['microsoftedge', '18', 'Windows 10'],
['microsoftedge', '13', 'Windows 10'],
['internet explorer', 'latest', 'Windows 10'],
['internet explorer', '10', 'Windows 8'],
['internet explorer', '9', 'Windows 7'],
// Older versions of IE no longer supported by Sauce Labs
['safari', 'latest', 'macOS 10.15'],
['safari', '12', 'macOS 10.14'],
['safari', '11', 'macOS 10.13'],
['safari', '8', 'OS X 10.10'],
], function(memo, platform) {
// internet explorer -> ie
var label = platform[0].split(' ');
if (label.length > 1) {
label = _.invoke(label, 'charAt', 0)
}
label = (label.join("") + '_v' + platform[1]).replace(' ', '_').toUpperCase();
memo[label] = _.pick({
'base': 'SauceLabs',
'browserName': platform[0],
'version': platform[1],
'platform': platform[2]
}, Boolean);
return memo;
}, {});
module.exports = function(config) {
if ( !process.env.SAUCE_USERNAME || !process.env.SAUCE_ACCESS_KEY ) {
console.log('Sauce environments not set --- Skipping');
return process.exit(0);
}
config.set({
basePath: '',
frameworks: ['qunit'],
singleRun: true,
browserDisconnectTolerance: 5,
browserNoActivityTimeout: 240000,
// list of files / patterns to load in the browser
files: [
'test/vendor/qunit-extras.js',
'test/qunit-setup.js',
'underscore-umd.js',
'test/*.js'
],
// Number of sauce tests to start in parallel
concurrency: 9,
// test results reporter to use
reporters: ['dots', 'saucelabs'],
port: 9876,
colors: true,
logLevel: config.LOG_INFO,
sauceLabs: {
build: 'TRAVIS #' + process.env.TRAVIS_BUILD_NUMBER + ' (' + process.env.TRAVIS_BUILD_ID + ')',
startConnect: true,
tunnelIdentifier: process.env.TRAVIS_JOB_NUMBER
},
captureTimeout: 120000,
customLaunchers: sauceBrowsers,
// Browsers to launch, commented out to prevent karma from starting
// too many concurrent browsers and timing sauce out.
browsers: _.keys(sauceBrowsers)
});
};
|
// 23: class - accessors
// To do: make all tests pass, leave the assert lines unchanged!
// Follow the hints of the failure messages!
describe('Class accessors (getter and setter)', () => {
it('a getter is defined like a method prefixed with `get`', () => {
class MyAccount {
//// get money() { return Infinity; }
get balance() { return Infinity; }
}
assert.equal(new MyAccount().balance, Infinity);
});
it('a setter has the prefix `set`', () => {
class MyAccount {
get balance() { return this.amount; }
set balance(amount) { this.amount = amount; }
}
const account = new MyAccount();
//// account.balance = 42;
account.balance = 23;
assert.equal(account.balance, 23);
});
describe('dynamic accessors', () => {
it('a dynamic getter name is enclosed in `[]`', function() {
//// const balance = 'yourMoney';
const getterName = 'yourMoney';
class YourAccount {
get [getterName]() { return -Infinity; }
}
assert.equal(new YourAccount().yourMoney, -Infinity);
});
it('a dynamic setter name as well', function() {
const propertyName = 'balance';
class MyAccount {
get [propertyName]() { return this.amount; }
//// set propertyName(amount) { this.amount = 23; }
set [propertyName](amount) { this.amount = 23; }
}
const account = new MyAccount();
account.balance = 42;
assert.equal(account.balance, 23);
});
});
});
|
import 'antd-mobile/lib/swipe-action/style/index';
|
/** @flow */
import type { t } from '../types'
/**
*
* @param sources
* @param target
*/
export function applyAverage (sources: t[], target: t): void {
const source = sources[0]
if (!source || sources.length === 0) return
if (sources.length === 1) {
target.data.set(source.data, 0)
return
}
const quantity = sources.length
const width = source.width
const height = source.height
const pointsLength = width * height
let matrixIndex
let pointIndex
let currentSum
for (pointIndex = 0; pointIndex < pointsLength; pointIndex++) {
currentSum = 0
for (matrixIndex = 0; matrixIndex < quantity; matrixIndex++) {
currentSum += sources[matrixIndex].data[pointIndex]
}
target.data[pointIndex] = currentSum / quantity
}
}
|
import Ember from 'ember';
import RouteChildrenMixin from '../../../mixins/route-children';
import { module, test } from 'qunit';
module('Unit | Mixin | route children');
// Replace this with your real tests.
test('it works', function(assert) {
var RouteChildrenObject = Ember.Object.extend(RouteChildrenMixin);
var subject = RouteChildrenObject.create();
assert.ok(subject);
});
|
var __extends = (this && this.__extends) || (function () {
var extendStatics = Object.setPrototypeOf ||
({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
return function (d, b) {
extendStatics(d, b);
function __() { this.constructor = d; }
d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
};
})();
define(["require", "exports", "react", "office-ui-fabric-react/lib/Button", "office-ui-fabric-react/lib/Panel"], function (require, exports, React, Button_1, Panel_1) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
var PanelExtraLargeExample = (function (_super) {
__extends(PanelExtraLargeExample, _super);
function PanelExtraLargeExample() {
var _this = _super.call(this) || this;
_this.state = { showPanel: false };
return _this;
}
PanelExtraLargeExample.prototype.render = function () {
var _this = this;
return (React.createElement("div", null,
React.createElement(Button_1.DefaultButton, { description: 'Opens the Sample Panel', onClick: function () { return _this.setState({ showPanel: true }); }, text: 'Open Panel' }),
React.createElement(Panel_1.Panel, { isOpen: this.state.showPanel, onDismiss: function () { return _this.setState({ showPanel: false }); }, type: Panel_1.PanelType.extraLarge, headerText: 'Extra Large Panel', closeButtonAriaLabel: 'Close' },
React.createElement("span", { className: 'ms-font-m' }, "Content goes here."))));
};
return PanelExtraLargeExample;
}(React.Component));
exports.PanelExtraLargeExample = PanelExtraLargeExample;
});
//# sourceMappingURL=Panel.ExtraLarge.Example.js.map
|
'use strict';
var fs = require('fs-extra')
, async = require('async')
, nconf = require('nconf');
var config = nconf.file('./conf/pp.' + (process.env.NODE_ENV || 'development') + '.json').load();
require('date-utils');
var pp = {};
pp.poetry = "";
pp.poetryPlain = "";
pp.rawPoetry = [];
pp.cleanPoetry = [];
pp.checkSum = 0;
pp.isFeedFresh = function(cb) {
// checks if conf.Feed is older than conf.maxAgeInMinutes
console.log('\tisFeedFresh checking how old feed is');
console.log(config.feed);
fs.stat(config.feed, function(err, stats) {
if (err) {
if (err.errno === 34) {
console.error('\tisFeedFresh error: Feed not found!');
cb(new Error('Feed not found!'));
} else {
console.error('\tisFeedFresh Unhandled error: %s', JSON.stringify(err, null, 4));
cb(err);
}
} else {
var feed = new Date(stats.mtime)
, now = new Date()
, delta = feed.getMinutesBetween(now);
console.log('\tisFeedFresh stats:\n\t\t%s\n\t\tnow %s\n\t\tdelta (min) %s\n\t\tthreshold (min) %s', feed, now, delta, config.maxAgeInMinutes);
cb(null, delta < config.maxAgeInMinutes);
}
});
};
function start(cb) {
console.log('start');
return cb(null, config.url);
}
var downloadFeed = require('./download.js').downloadFeed
, parseTweets = require('./parseTweets.js').parseTweets
, saveFile = require('./archiveFile.js').saveFile
, saveAndArchiveFile = require('./archiveFile.js').saveAndArchiveFile
, cleanText = require('./sanitiseTweets.js').cleanText
, createMatrix = require('./createMatrix.js').createMatrix
, createPlainText = require('./createPlainText.js').createPlainText;
function finished(d, cb) { // mock cleanText
console.log('finished d: %s', typeof d);
cb(null);
}
pp.updateFeed = function(cb) {
var waterfall = [start, downloadFeed, saveAndArchiveFile, parseTweets, saveAndArchiveFile, cleanText, saveAndArchiveFile,
//FIXME: refactor
function glue(data, cb) {
createMatrix(data, function(err, file, data2, encoding) {
if (err) {
return cb(err);
}
saveFile(file, data2, encoding, function(meh) {
console.log('created banner: %s', typeof meh);
createPlainText(data, function(err, file, data3, encoding) {
saveFile(file, data3, encoding, function(meh) {
console.log('created plain: %s', typeof meh);
cb(null, meh); // :(
}); // saveFileInner
}); // createPlainText
}); // saveFile outer
}); // createMatrix
},finished];
console.log('\tstart time: %s', new Date());
async.waterfall(waterfall, function finished(err) {
if (err) {
// 500
console.log('\tupdateFeed error: %s', JSON.stringify(err, null, 4));
cb(err);
} else {
console.log('\tupdateFeed completed successfully!');
console.log('\tend time: %s', new Date());
cb(null);
}
});
};
pp.ok = function() { return true; };
module.exports = pp;
|
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
var laptop = exports.laptop = { "viewBox": "0 0 16 16", "children": [{ "name": "path", "attribs": { "fill": "#000000", "d": "M14 11v-8c0-0.55-0.45-1-1-1h-10c-0.55 0-1 0.45-1 1v8h-2v3h16v-3h-2zM10 13h-4v-1h4v1zM13 11h-10v-7.998c0.001-0.001 0.001-0.001 0.002-0.002h9.996c0.001 0.001 0.001 0.001 0.002 0.002v7.998z" } }] };
|
(function (module) {
var questionData = function ($q, urlConfig, proxy, adalAuthenticationService) {
var getUserQuestions = function () {
var url = urlConfig.questionsByUserId(adalAuthenticationService.userInfo.userName);
var deferred = $q.defer();
proxy.get(url)
.then(function (response) {
deferred.resolve(response.data);
}, function (error) {
deferred.reject(error)
});
return deferred.promise;
}
var getPublicQuestions = function () {
var url = urlConfig.getPublicQuestions;
var deferred = $q.defer();
proxy.get(url)
.then(function (response) {
deferred.resolve(response.data);
}, function (error) {
deferred.reject(error)
});
return deferred.promise;
}
var getQuestionById = function (id) {
var url = urlConfig.getQuestionById(id);
var deferred = $q.defer();
proxy.get(url)
.then(function (response) {
deferred.resolve(response.data);
}, function (error) {
deferred.reject(error)
});
return deferred.promise;
}
var getQuestionByValue = function (question) {
var url = urlConfig.getQuestionByValue(encodeURIComponent(question));
var deferred = $q.defer();
proxy.get(url)
.then(function (response) {
deferred.resolve(response.data);
}, function (error) {
deferred.reject(error)
});
return deferred.promise;
}
var addQuestion = function (question) {
var url = urlConfig.addNewQuestion;
var deferred = $q.defer();
//Audit
question.createdBy = adalAuthenticationService.userInfo.userName;
question.lastModifiedBy = adalAuthenticationService.userInfo.userName;
var today = new Date();
question.createdOn = today;
question.lastModifedOn = today;
proxy.post(url, question)
.then(function (response) {
deferred.resolve(response.data);
}, function (error) {
deferred.reject(error);
});
return deferred.promise;
}
var editQuestion = function (question) {
var url = urlConfig.editQuestion;
var deferred = $q.defer();
//Audit
question.lastModifiedBy = adalAuthenticationService.userInfo.userName;
var today = new Date();
question.lastModifedOn = today;
proxy.put(url, question)
.then(function (response) {
deferred.resolve(response.data);
}, function (error) {
deferred.reject(error);
});
return deferred.promise;
}
var deleteQuestion = function (questionId) {
var url = urlConfig.deleteQuestion(questionId);
var deferred = $q.defer();
proxy.del(url)
.then(function (response) {
deferred.resolve(response.data);
}, function (error) {
deferred.reject(error);
});
return deferred.promise;
}
return {
getUserQuestions: getUserQuestions,
getPublicQuestions: getPublicQuestions,
getQuestionByValue: getQuestionByValue,
getQuestionById: getQuestionById,
addQuestion: addQuestion,
editQuestion: editQuestion,
deleteQuestion: deleteQuestion
}
}
module.factory("questionsData", questionData);
}(angular.module("question")))
|
import React, { Component } from 'react';
import {
View,
Text,
Image,
StyleSheet,
Linking,
TouchableOpacity
} from 'react-native';
import HtmlRender from 'react-native-html-render';
import { parseImgUrl } from '../../utils';
import moment from 'moment';
class TopicCommentItem extends Component {
render() {
const { reply, idx } = this.props;
const avatar = parseImgUrl(reply.member.avatar_normal);
const date = moment.unix(reply.created).fromNow();
const content = `<p>${reply.content_rendered}</p>`;
const floor = `#${idx + 1}`;
return (
<View style={styles.reply} key={reply.id}>
<View style={styles.header}>
<TouchableOpacity>
<Image
style={[styles.avatar]}
source={{uri: avatar}}>
</Image>
</TouchableOpacity>
<View style={styles.info}>
<View style={styles.usernameWrapper}>
<Text style={styles.username}>
{reply.member.username}
</Text>
</View>
<View style={styles.dateWrapper}>
<Text style={styles.date}>
{date}
</Text>
</View>
</View>
<View style={styles.floorWrapper}>
<Text style={styles.floor}>
{floor}
</Text>
</View>
</View>
<View style={styles.content}>
<HtmlRender
value={content}
stylesheet={htmlStyles}
onLinkPress={url => Linking.openURL(url)}
/>
</View>
</View>
);
}
}
const styles = StyleSheet.create({
reply: {
padding: 10,
borderBottomColor: 'rgba(0, 0, 0, 0.05)',
borderBottomWidth: 1,
},
header: {
flexDirection: 'row',
},
avatar: {
height: 30,
width: 30,
borderRadius: 20,
marginRight: 10,
},
info: {
flexDirection: 'row',
},
usernameWrapper: {
marginRight: 10,
},
username: {
fontSize: 14,
},
dateWrapper: {
marginRight: 10,
},
date: {
fontSize: 14,
},
floorWrapper: {
position: 'absolute',
right: 5,
},
floor: {
fontSize: 12,
},
content: {
marginLeft: 25,
}
});
const htmlStyles = StyleSheet.create({
pwrapper: {
marginTop: 5,
marginBottom: 5,
paddingLeft: 15,
paddingRight: 15
},
p: {
fontSize: 14,
},
a: {
color: '#4078c0',
fontSize: 14,
}
});
export default TopicCommentItem;
|
/**
* Created by dli on 25.01.2015.
*/
define('sync/time/Clock', ['sync/time/CONST'], function (CONST) {
var Clock = function (time){
this.time = time || 0;
}
Clock.prototype.tick = function(){
return this.time < CONST.LOGICAL_HOUR - 1 ? ++this.time : (this.time = 0);
}
Clock.prototype.setTime = function(time) {
this.time = time;
}
Clock.prototype.getTime = function(time) {
return this.time;
}
return Clock;
});
|
'use strict';
angular.module('startingPointJsApp')
.service('Auth', ['$rootScope', '$http', 'localStorageService', function Auth($rootScope, $http, localStorageService) {
this.eventName = 'Auth.changes';
Auth.prototype.getUser = function () {
return localStorageService.get('user');
};
Auth.prototype.signIn = function (data, callback) {
$http.post('/signin', data).success(function (result) {
if (result.status.code !== 200) {
callback(result.error, null);
} else {
callback(null, result.result);
localStorageService.set('user', result.result);
Auth.prototype.broadcast();
}
});
};
Auth.prototype.signOut = function (callback) {
$http.post('/signout').success(function (result) {
if (result.status.code !== 200) {
callback(result.error, null);
} else {
callback(null, result.result);
localStorageService.clearAll();
Auth.prototype.broadcast();
}
});
};
Auth.prototype.subscribe = function ($scope, callback) {
$scope.$on(Auth.eventName, callback);
};
Auth.prototype.broadcast = function () {
$rootScope.$broadcast(Auth.eventName);
};
}]);
|
/**
* Created by ila on 5/18/2015.
*/
"use strict"
class SettingStore {
static set(object) {
const KEY = 'Setting';
return localforage.setItem(KEY, object.toArray());
}
static get() {
const KEY = 'Setting';
return localforage.getItem(KEY).then(function (v) {
return new Promise(function (resolve, reject) {
let setting = new Setting();
if (v) setting.fromArray(v);
resolve(setting);
});
});
}
}
|
var ThorElement = require('./thorElement');
var ThorController = function(){
ThorElement.call(this);
this.type = ThorElement.TYPES.CONTROLLER;
}
module.exports = ThorController;
|
var test2 = true;
|
function initTask(subTask) {
var cellSide = 60;
subTask.gridInfos = {
hideSaveOrLoad: true,
cellSide: cellSide,
actionDelay: 200,
itemTypes: {
green_robot: { img: "green_robot.png", side: 80, nbStates: 9, isObstacle: true, offsetX: -14, category: "robot", team: 0, zOrder: 2 },
paint: { img: "paint.png", side: cellSide, category: "paint", isPaint: true, isObstacle: false, hasColor: true, color: "gris", zOrder: 1 },
marker: { num: 2, img: "marker.png", side: cellSide, category: "marker", isObstacle: false, isMarker: true, zOrder: 0 }
},
maxInstructions: 15,
includeBlocks: {
groupByCategory: false,
generatedBlocks: {
robot: ["east", "west", "north", "south", "paint", "markedCell"]
},
standardBlocks: {
includeAll: false,
wholeCategories: [],
singleBlocks: ["controls_repeat", "controls_if"]
}
},
ignoreInvalidMoves: false,
checkEndEveryTurn: false,
checkEndCondition: robotEndConditions.checkMarkersPainted
};
subTask.data = {
easy: [
{
tiles: [
[1, 1, 1, 1, 1, 1, 1, 1, 1, 1],
[1, 1, 1, 1, 2, 2, 1, 1, 1, 1],
[1, 1, 1, 2, 1, 1, 2, 1, 1, 1],
[1, 1, 2, 1, 1, 1, 1, 2, 1, 1],
[1, 2, 1, 1, 1, 1, 1, 1, 2, 1],
[1, 2, 1, 1, 1, 1, 1, 1, 2, 1],
[1, 2, 1, 1, 2, 2, 1, 1, 2, 1],
[1, 2, 1, 1, 2, 2, 1, 1, 2, 1],
[1, 2, 2, 2, 2, 2, 2, 2, 2, 1],
[1, 1, 1, 1, 1, 1, 1, 1, 1, 1]
],
initItems: [
{ row: 9, col: 0, dir: 0, type: "green_robot" }
]
}
]
};
initBlocklySubTask(subTask);
displayHelper.thresholdEasy = 5000;
displayHelper.thresholdMedium = 10000;
}
initWrapper(initTask, null, null, true);
|
exports.BattleScripts = {
init: function() {
for (var i in this.data.Pokedex) {
var template = this.getTemplate(i);
var newStats = {
hp: template.id === 'shedinja' ? 1 : this.clampIntRange(150 - template.baseStats.hp, 5, 145),
atk: this.clampIntRange(150 - template.baseStats.atk, 5, 145),
def: this.clampIntRange(150 - template.baseStats.def, 5, 145),
spa: this.clampIntRange(150 - template.baseStats.spa, 5, 145),
spd: this.clampIntRange(150 - template.baseStats.spd, 5, 145),
spe: this.clampIntRange(150 - template.baseStats.spe, 5, 145)
}
this.modData('Pokedex', i).baseStats = newStats;
}
}
};
|
/* jshint node: true */
'use strict';
module.exports = {
name: 'ember-cli-patch-twilio',
contentFor: function(type) {
var environment = this.app.env.toString();
if (type === 'head') {
if (environment === 'production') {
return '<script type="text/javascript" src="//static.twilio.com/libs/twiliojs/1.2/twilio.min.js"></script>';
} else {
return '<script type="text/javascript"> var Twilio = { disconnectCallback: false, Device: { error: function() {}, setup: function() {}, connect: function() {}, disconnect: function (callback) { if (callback) { this.disconnectCallback = callback; } else { this.disconnectCallback(); } }, disconnectAll: function() {} } }; </script>';
}
}
}
};
|
// ─────────────────────────────────────────────────────────────────────────────
// import
// ─────────────────────────────────────────────────────────────────────────────
import React from 'react';
import { graphql } from 'gatsby';
import { RootContainer, BlogPreviewsContainer, SEOContainer } from '~containers';
import { Main, Section, H2 } from '~components';
import { renderBlocks, pagePropTypes } from '~utils';
// ─────────────────────────────────────────────────────────────────────────────
// query
// ─────────────────────────────────────────────────────────────────────────────
export const query = graphql`
{
page: mdx(frontmatter: { meta: { permalink: { eq: "/blog/" } } }) {
frontmatter {
...MetaFragment
blocks {
title
type
}
}
}
posts: allMdx(
filter: { fileAbsolutePath: { regex: "/cms/posts/" } }
sort: { fields: [frontmatter___date], order: DESC }
) {
nodes {
...BlogPreviewFragment
}
}
}
`;
// ─────────────────────────────────────────────────────────────────────────────
// component
// ─────────────────────────────────────────────────────────────────────────────
export default function BlogPage({
data: {
page: {
frontmatter: { meta, blocks },
},
posts,
},
}) {
return (
<RootContainer>
<SEOContainer meta={meta} />
<Main
css={`
grid-template: 'hero' 'blog';
grid-gap: 10vh 4rem;
`}
>
{renderBlocks(blocks)}
<Section
id="blog"
css={`
grid-area: blog;
`}
>
<H2>All blog articles</H2>
<BlogPreviewsContainer posts={posts} />
</Section>
</Main>
</RootContainer>
);
}
BlogPage.propTypes = pagePropTypes;
|
import configureMockStore from 'redux-mock-store';
import thunk from 'redux-thunk';
import nock from 'nock';
import { expect } from 'chai';
import {
FIREBASE_LOGOUT_BEGIN,
FIREBASE_LOGOUT_SUCCESS,
FIREBASE_LOGOUT_FAILURE,
FIREBASE_LOGOUT_DISMISS_ERROR,
} from 'features/common/redux/constants';
import {
firebaseLogout,
dismissFirebaseLogoutError,
reducer,
} from 'features/common/redux/firebaseLogout';
const middlewares = [thunk];
const mockStore = configureMockStore(middlewares);
describe('common/redux/firebaseLogout', () => {
afterEach(() => {
nock.cleanAll();
});
it('action should handle firebaseLogout success', () => {
const store = mockStore({});
const expectedActions = [
{ type: FIREBASE_LOGOUT_BEGIN },
{ type: FIREBASE_LOGOUT_SUCCESS, data: {} },
];
return store.dispatch(firebaseLogout({ error: false }))
.then(() => {
expect(store.getActions()).to.deep.equal(expectedActions);
});
});
it('action should handle firebaseLogout failure', () => {
const store = mockStore({});
const expectedActions = [
{ type: FIREBASE_LOGOUT_BEGIN },
{ type: FIREBASE_LOGOUT_FAILURE, data: { error: 'some error' } },
];
return store.dispatch(firebaseLogout({ error: true }))
.catch(() => {
expect(store.getActions()).to.deep.equal(expectedActions);
});
});
it('action should handle dismissFirebaseLogoutError', () => {
const expectedAction = {
type: FIREBASE_LOGOUT_DISMISS_ERROR,
};
expect(dismissFirebaseLogoutError()).to.deep.equal(expectedAction);
});
it('reducer should handle FIREBASE_LOGOUT_BEGIN', () => {
const prevState = { firebaseLogoutPending: true };
const state = reducer(
prevState,
{ type: FIREBASE_LOGOUT_BEGIN }
);
expect(state).to.not.equal(prevState); // should be immutable
expect(state.firebaseLogoutPending).to.be.true;
});
it('reducer should handle FIREBASE_LOGOUT_SUCCESS', () => {
const prevState = { firebaseLogoutPending: true };
const state = reducer(
prevState,
{ type: FIREBASE_LOGOUT_SUCCESS, data: {} }
);
expect(state).to.not.equal(prevState); // should be immutable
expect(state.firebaseLogoutPending).to.be.false;
});
it('reducer should handle FIREBASE_LOGOUT_FAILURE', () => {
const prevState = { firebaseLogoutPending: true };
const state = reducer(
prevState,
{ type: FIREBASE_LOGOUT_FAILURE, data: { error: new Error('some error') } }
);
expect(state).to.not.equal(prevState); // should be immutable
expect(state.firebaseLogoutPending).to.be.false;
expect(state.firebaseLogoutError).to.exist;
});
it('reducer should handle FIREBASE_LOGOUT_DISMISS_ERROR', () => {
const prevState = { firebaseLogoutError: new Error('some error') };
const state = reducer(
prevState,
{ type: FIREBASE_LOGOUT_DISMISS_ERROR }
);
expect(state).to.not.equal(prevState); // should be immutable
expect(state.firebaseLogoutError).to.be.null;
});
});
|
'use strict'
let models = require('../models')
let express = require('express')
let multer = require('multer')
let upload = multer({dest: 'uploads/'})
let router = express.Router()
let utils = require('./utils')
router.get('', (req, res, next) => {
let result = {
messages: []
}
models.File.findAndCountAll(
).then(files => {
result.data = files.rows
result.length = files.count
res.writeHead(200, utils.contentType)
res.end(JSON.stringify(result))
}, error => {
utils.fnError(res, `${error.name}:${error.message}`)
})
})
router.get('/:id', (req, res, next) => {
let params = {}
let result = {
messages: []
}
params = req.query
models.File.findById(
req.params.id || -1,
utils.setWhere(params)
).then(file => {
result.data = file || {}
result.length = (file) ? 1 : 0
res.writeHead((file) ? 200 : 404, utils.contentType)
res.end(JSON.stringify(result))
}, error => {
utils.fnError(res, `${error.name}:${error.message}`)
})
})
router.post('', upload.array('file', 10), (req, res, next) => {
let result = {}
let file = {
id: req.body.id || (new Date()).valueOf(),
originalName: req.files[0].originalname,
fileName: req.files[0].filename,
size: req.files[0].size
}
models.File.create(
file
).then(file => {
result = {
data: file,
length: 1,
messages: [{
type: 'success',
code: 201,
detail: 'Recurso criado com sucesso'
}]
}
res.writeHead(201, utils.contentType)
res.end(JSON.stringify(result))
}, error => {
utils.fnError(res, `${error.name}:${error.message}`, 422, {})
})
})
router.delete('', (req, res, next) => {
utils.fnError405(res)
})
router.delete('/:id', (req, res, next) => {
let result = {
data: {},
length: 0,
messages: []
}
models.File.destroy({
where: {
id: req.params.id
}
}).then(file => {
if (file === 1) {
result.messages = [{
type: 'success',
code: 204,
detail: 'Recurso excluído com sucesso'
}]
} else {
result.messages = [{
type: 'warning',
code: 404,
detail: 'Recurso não encontrado'
}]
}
res.writeHead(file === 1 ? 204 : 404, utils.contentType)
res.end(JSON.stringify(result))
}, error => {
utils.fnError(res, `${error.name}:${error.message}`)
})
})
module.exports = router
|
'use strict';
// MODULES //
var factory = require( './factory.js' );
// URLS //
/**
* FUNCTION: urls( options, clbk )
* Get repository URLs for one or more packages.
*
* @param {Object} options - function options
* @param {String[]} options.packages - package names
* @param {String} [options.registry="registry.npmjs.org"] - registry
* @param {Number} [options.port=443] - registry port
* @param {String} [options.protocol="https"] - registry protocol
* @param {Function} clbk - callback to invoke upon query completion
* @returns {Void}
*/
function urls( options, clbk ) {
factory( options, clbk )();
} // end FUNCTION urls()
// EXPORTS //
module.exports = urls;
|
// media query constants
(function() {
'use strict';
var MQ = {
SMALL: '(max-width: 767px)',
LARGE: '(min-width: 768px)'
};
angular
.module('rBox')
.constant('MQ', MQ);
}());
|
"use strict"
// Keep in length order
module.exports = {
object: {},
objectModule: {
dir: true,
templates: [{
name: 'module.ts',
imports: ['module.ts'],
listItems: ['imports'],
},{
name: 'component.ts',
imports: ['module.ts', 'routes.ts'],
listItems: ['declarations', 'exports'],
},{
name: 'component.pug',
file: 'router.component.pug',
},{
name: 'component.css',
},{
name: 'routes.ts',
file: 'object.routes.ts',
imports: ['routes.ts'],
addRoute: true,
}],
},
listModule: {
dir: 'list',
templates: [{
name: 'list.module.ts',
file: 'form.module.ts',
imports: ['module.ts'],
listItems: ['imports'],
},{
name: 'list.component.ts',
imports: ['module.ts', 'routes.ts'],
listItems: ['declarations', 'exports'],
},{
name: 'list-resolve.service.ts',
file: 'resolve.service.ts',
imports: ['module.ts', 'routes.ts'],
listItems: ['providers'],
},{
name: 'list-auth.service.ts',
file: 'can-activate.service.ts',
imports: ['module.ts', 'routes.ts'],
listItems: ['providers'],
},{
name: 'list.component.pug',
},{
name: 'list.component.css',
},{
name: 'list.routes.ts',
imports: ['routes.ts'],
//addRoute: true,
}],
},
detailModule: {
dir: 'detail',
templates: [{
name: 'detail.module.ts',
file: 'form.module.ts',
imports: ['module.ts'],
listItems: ['imports'],
},{
name: 'detail.component.ts',
imports: ['module.ts', 'routes.ts'],
listItems: ['declarations', 'exports'],
},{
name: 'detail-resolve.service.ts',
imports: ['module.ts', 'routes.ts'],
listItems: ['providers'],
},{
name: 'detail-auth.service.ts',
file: 'can-activate.service.ts',
imports: ['module.ts', 'routes.ts'],
listItems: ['providers'],
},{
name: 'detail.component.pug',
},{
name: 'detail.component.css',
file: 'component.css',
},{
name: 'detail.routes.ts',
imports: ['routes.ts'],
//addRoute: true,
}],
},
resolveService: {
dir: false,
templates: [{
name: 'resolve.service.ts',
imports: ['module.ts', 'routes.ts'],
listItems: ['providers'],
}],
},
canActivateService: {
dir: false,
templates: [{
name: 'can-activate.service.ts',
imports: ['module.ts', 'routes.ts'],
listItems: ['providers'],
}],
},
commonModule: {
dir: true,
templates: [{
name: 'module.ts',
file: 'common.module.ts',
imports: ['module.ts'],
listItems: ['imports'],
}],
},
service: {
dir: false,
templates: [{
name: 'service.ts',
imports: ['module.ts'],
listItems: ['providers'],
}],
},
component: {
dir: true,
templates: [{
name: 'component.ts',
imports: ['module.ts'],
listItems: ['declarations', 'exports'],
},{
name: 'component.pug',
},{
name: 'component.css',
}],
},
module: {
dir: true,
templates: [{
name: 'module.ts',
imports: ['module.ts'],
listItems: ['imports'],
},{
name: 'component.ts',
imports: ['module.ts', 'routes.ts'],
listItems: ['declarations', 'exports'],
},{
name: 'component.pug',
file: 'router.component.pug',
},{
name: 'component.css',
},{
name: 'routes.ts',
imports: ['routes.ts'],
addRoute: true,
}],
},
}
|
version https://git-lfs.github.com/spec/v1
oid sha256:ed3c069c3fb213c279f09fea7c7fe53e4340d9da1e27b560b4ffcb4009dd23e0
size 9790
|
'use strict';
var assert = require('assert');
var x = [1, 2, 3];
var sum = 0;
for (var value of x) {
sum += value;
}
assert(sum === 6);
|
'use strict';
var compiler = require('gss-compiler');
var through2 = require('through2');
var gutil = require('gulp-util');
var PluginError = gutil.PluginError;
module.exports = function() {
function transform (file, enc, next) {
var self = this;
if (file.isNull()) {
self.push(file);
return next();
}
if (file.isStream()) {
self.emit('error', new PluginError('gulp-gss', 'Streaming not supported'));
return next();
}
var str = file.contents.toString('utf8');
var ast = compiler.compile(str);
file.contents = new Buffer(JSON.stringify(ast, null, 2) + "\n");
file.path = gutil.replaceExtension(file.path, '.json');
self.push(file);
return next();
};
return through2.obj(transform);
};
|
const concat = require('concat-stream')
const test = require('tape')
const fs = require('fs')
const gherkin = require('../')
test('should assert input types', function (t) {
t.plan(3)
const rs = fs.createReadStream(__dirname + '/file.feature')
const ts = gherkin()
const ws = concat({ object: true }, function (buf) {
const ast = JSON.parse(buf.toString())
t.equal(typeof ast, 'object')
t.deepEqual(ast, [ {
perspective: 'drinker',
feature: 'Can drink beer when thirsty',
desire: 'to take beer off the wall',
reason: 'to satisfy my thirst',
scenarios: [ {
given: [ '100 bottles of beer on the wall' ],
scenario: 'Can take a single beer',
then: [ 'there are 99 bottles of beer on the wall' ],
when: [ 'a bottle is taken down' ]
} ]
} ])
})
ts.on('end', t.pass.bind('null', 'stream ended'))
rs.pipe(ts).pipe(ws)
})
|
/* DASHBOARDS */
Router.route('/', {
name: 'sitesIndex',
controller: SitesController,
action: 'index',
});
/* EOF DASHBOARDS */
|
import baseController from '../../shared/baseController';
export default class ngbGenomeAnnotationsController extends baseController{
static get UID() {
return 'ngbGenomeAnnotationsController';
}
projectContext;
scope;
showTrackOriginalName = true;
constructor($scope, dispatcher, projectContext, trackNamingService, localDataService) {
super(dispatcher);
this.projectContext = projectContext;
this.trackNamingService = trackNamingService;
this.scope = $scope;
this.localDataService = localDataService;
this.showTrackOriginalName = localDataService.getSettings().showTrackOriginalName;
this.annotationFiles = [
{
name: 'Human_genome.fa'
},
{
name: 'Human_genome.bed'
}
];
const globalSettingsChangedHandler = (state) => {
this.showTrackOriginalName = state.showTrackOriginalName;
};
this.dispatcher.on('settings:change', globalSettingsChangedHandler);
// We must remove event listener when component is destroyed.
$scope.$on('$destroy', () => {
dispatcher.removeListener('settings:change', globalSettingsChangedHandler);
});
}
openMenu($mdOpenMenu, $event) {
if (this.referenceContainsAnnotations) {
$mdOpenMenu($event);
}
}
get reference() {
if (this.projectContext && this.projectContext.reference) {
return this.projectContext.reference;
}
return {
annotationFiles: null,
name: null,
};
}
get referenceContainsAnnotations() {
if (this.projectContext && this.projectContext.reference) {
return this.projectContext.reference.annotationFiles && this.projectContext.reference.annotationFiles.length;
}
return false;
}
getCustomName(file) {
return this.trackNamingService.getCustomName(file);
}
onAnnotationFileChanged(file) {
if (file.selected) {
const state = this.projectContext.reference.annotationFiles;
const sortFn = (file1, file2) => {
if (file1.selected !== file2.selected) {
if (file1.selected) {
return -1;
} else {
return 1;
}
}
const index1 = state.indexOf(file1.name.toLowerCase());
const index2 = state.indexOf(file2.name.toLowerCase());
if (file1.name.toLowerCase() === file2.name.toLowerCase()) {
return 0;
}
if (file1.name.toLowerCase() === file.name.toLowerCase()) {
return 1;
}
if (file2.name.toLowerCase() === file.name.toLowerCase()) {
return -1;
}
if (index1 < index2) {
return -1;
} else if (index1 > index2) {
return 1;
}
return 0;
};
this.projectContext.reference.annotationFiles.sort(sortFn);
const tracks = this.projectContext.tracks;
file.projectId = '';
file.isLocal = true;
tracks.push(file);
const tracksState = this.projectContext.tracksState;
const savedState = this.projectContext.getTrackState((file.name || '').toLowerCase(), file.projectId);
if (savedState) {
tracksState.push(Object.assign(savedState,{
bioDataItemId: file.name,
format: file.format,
isLocal: true,
projectId: '',
}));
} else {
tracksState.push({
bioDataItemId: file.name,
format: file.format,
isLocal: true,
projectId: '',
});
}
this.projectContext.changeState({tracks, tracksState});
} else {
const tracks = this.projectContext.tracks;
const tracksToRemove = tracks.filter(
(t) =>
t.name.toLowerCase() === file.name.toLowerCase() &&
t.format.toLowerCase() === file.format.toLowerCase() &&
t.projectId === ''
);
tracksToRemove.forEach(track => {
const index = tracks.indexOf(track);
tracks.splice(index, 1);
});
const tracksState = this.projectContext.tracksState;
const trackStateToRemove = tracksState.filter(
(t) =>
t.bioDataItemId.toLowerCase() === file.name.toLowerCase() &&
t.format.toLowerCase() === file.format.toLowerCase() &&
t.projectId === ''
);
trackStateToRemove.forEach(trackState => {
tracksState.splice(tracksState.indexOf(trackState), 1);
});
this.projectContext.changeState({tracks, tracksState});
}
this.projectContext.saveAnnotationFilesState();
}
}
|
/**
* Usage: 程序配置项
* Author: Spikef < Spikef@Foxmail.com >
* Copyright: Envirs Team < http://envirs.com >
*/
var fs = require('fs');
var program = require('commander');
var prompts = require('inquirer').prompt;
program
.command('config <option>')
.description('修改配置')
.action(function(option) {
var site = process.site();
var configs = require(site + '/config.json');
if ( !configs[option] ) configs[option] = {};
var questions = [];
switch(option) {
case 'ftp':
questions = [
{
type: 'input',
name: 'address',
message: 'FTP地址'
},
{
type: 'input',
name: 'port',
message: '端口地址,如果不知道则跳过',
default: 21,
filter: Number
},
{
type: 'input',
name: 'username',
message: '登录用户'
},
{
type: 'password',
name: 'username',
message: '登录密码'
},
{
type: 'input',
name: 'folder',
message: '子目录,如果没有则跳过'
}
];
break;
case 'blog':
questions = [
{
type: 'input',
name: 'name',
message: '博客名称'
},
{
type: 'input',
name: 'title',
message: '博客标题'
},
{
type: 'input',
name: 'author',
message: '博主名称'
},
{
type: 'input',
name: 'username',
message: '登录用户'
},
{
type: 'password',
name: 'password',
message: '管理密码,'
},
{
type: 'input',
name: 'keywords',
message: '博客整站关键字'
},
{
type: 'input',
name: 'description',
message: '博客整站描述'
},
{
type: 'input',
name: 'copyright',
message: '博客版权信息'
},
{
type: 'input',
name: 'pageSize',
message: '每页显示日志条数',
filter: Number
}
];
break;
}
if ( questions.length > 0 ) {
for (var i=0;i<questions.length;i++) {
questions[i].default = configs[option][questions[i].name];
}
prompts(questions, function(answers) {
for (var i in answers) {
configs[option][i] = answers[i]
}
fs.writeFileSync(site + '/config.json', JSON.format(configs));
});
} else {
console.log('未知命令');
}
});
|
module.exports = function (Clase) {
Clase.saluda = function (msg, cb) {
cb(null, 'Hola pos... ' + msg);
};
Clase.remoteMethod(
'saluda', {
accepts: {
arg: 'msg',
type: 'string'
},
returns: {
arg: 'greeting',
type: 'string'
}
}
);
Clase.getcomuna = function (idcomuna, callback) {
Clase.find({
//include: ['deporte', 'establecimiento', 'entrenador'],
include: ['deporte', {
establecimiento: ['comuna'],
}],
where: {
idComuna: idcomuna
}
},
function (err, clases) {
callback(null, clases);
});
};
Clase.remoteMethod(
'getcomuna', {
accepts: {
art: 'idcomuna',
type: 'integer'
},
returns: {
arg: 'comuna',
type: 'string'
}
});
};
|
var util = require('util');
var path = require('path');
var chalk = require('chalk');
var BaseReporter = require('./base');
var Match = require('../match');
/**
* A PMD CPD XML reporter, which tries to fit jsinspect's output to something
* CI tools might expect from PMD.
*
* @constructor
*
* @param {Inspector} inspector The instance on which to register its listeners
* @param {object} opts Options to set for the reporter
*/
function PMDReporter(inspector, opts) {
var self, enabled;
self = this;
enabled = chalk.enabled;
opts = opts || {};
BaseReporter.call(this, inspector, opts);
this._diff = opts.diff;
inspector.on('start', function() {
chalk.enabled = false;
self._writableStream.write(
'<?xml version="1.0" encoding="utf-8"?>\n' +
'<pmd-cpd>\n'
);
});
inspector.on('end', function() {
chalk.enabled = enabled;
self._writableStream.write('</pmd-cpd>\n');
});
}
util.inherits(PMDReporter, BaseReporter);
module.exports = PMDReporter;
/**
* Returns an XML string containing a <duplication> element, with <file>
* children indicating the instance locations, and <codefragment> to hold the
* diff.
*
* @private
*
* @param {Match} match The inspector match to output
* @returns {string} The formatted output
*/
PMDReporter.prototype._getOutput = function(match) {
var self, output, diff, i, nodes, files;
self = this;
output = '';
diff = '';
nodes = match.nodes;
if (this._found > 1) {
output += '\n';
}
output += '<duplication lines="' + this._getTotalLines(nodes) + '">\n';
nodes.forEach(function(node) {
output += self._getFile(node);
});
output += '<codefragment>';
if (this._diff) {
for (i = 0; i < match.diffs.length; i++) {
diff += '\n- ' + this._getFormattedLocation(nodes[0]) + '\n+ ' +
this._getFormattedLocation(nodes[i + 1]) + '\n\n' +
this._getFormattedDiff(match.diffs[i]);
}
}
output += this._escape(diff) + '</codefragment>\n</duplication>\n';
return output;
};
/**
* Returns the total number of lines spanned by each node in an array.
*
* @param {[]Node} nodes The nodes for which to get the total
* @returns {int} Total number of lines
*/
PMDReporter.prototype._getTotalLines = function(nodes) {
return nodes.reduce(function(prev, curr) {
return prev + curr.loc.end.line - curr.loc.start.line + 1;
}, 0);
};
/**
* Returns an XML string containing the path to the file in which the node is
* located, as well as its starting line. Absolute paths are required for
* Jenkins.
*
* @param {Node} node The node from which to get a formatted location
* @returns {string} The formatted string
*/
PMDReporter.prototype._getFile = function(node) {
var filePath = node.loc.source;
// Convert any relative paths to absolute
if (filePath.charAt(0) !== '/') {
filePath = path.resolve(process.cwd(), filePath);
}
return '<file path="' + filePath + '" line="' + node.loc.start.line + '"/>\n';
};
/**
* Returns an escaped string for use within XML.
*
* @param {string} string The string to escape
* @returns {string} The escaped string
*/
PMDReporter.prototype._escape = function(string) {
var escaped = {
"'": ''',
'"': '"',
'&': '&',
'>': '>',
'<': '<'
};
return string.replace(/(['"&><])/g, function(string, char) {
return escaped[char];
});
};
|
import React from 'react'
import './blocks.scss'
export default class Block extends React.Component {
render() {
let {title, secondary, content, additional, style} = this.props;
return(
<div className={"amazo-tile " + (style ? style : 'default')}>
<div className="tile-heading">
<div className="title">{title ? title : 'TITLE'}</div>
<div className="secondary">{secondary ? secondary : 'SECONDARY'}</div>
</div>
<div className="tile-body">
<span className="content">{content ? content : 'CONTENT'}</span>
</div>
<div className="tile-footer text-center">
<span className="info-text text-right">{additional ? additional : 'ADDITIONAL'}</span>
</div>
</div>)
}
}
|
{
jestExpect(value).toBe(false);
}
|
import Element from './Element'
import Text from './Text'
import RunFormat from './RunFormat'
import Run from './Run'
import ParagraphFormat from './ParagraphFormat'
import Paragraph from './Paragraph'
import TableFormat from './TableFormat'
import Table from './Table'
import Section from './Section'
import File from './File'
import Document from './Document'
import { version } from '../package.json'
export {
Element,
Text,
RunFormat,
Run,
ParagraphFormat,
Paragraph,
TableFormat,
Table,
Section,
File,
Document,
version
}
|
import { connectModule } from '../../lib/phoneContext';
import DialerPanel from '../../components/DialerPanel';
export default connectModule((phone) => phone.dialerUI)(DialerPanel);
|
// Generated by CoffeeScript 1.6.3
(function() {
var Console, FileSystem, colors, _data,
__bind = function(fn, me){ return function(){ return fn.apply(me, arguments); }; };
colors = require('colors');
module.exports = {
Console: Console = (function() {
var MODE_REPL, MODE_RUN;
MODE_REPL = 0;
MODE_RUN = 1;
Console.prototype.buffer = null;
Console.prototype.vars = null;
Console.prototype.paused = false;
Console.prototype.prompt = '';
Console.prototype.altPrompt = '?';
function Console(prompt) {
var stdin;
this.prompt = prompt != null ? prompt : 'katra> ';
this.pause = __bind(this.pause, this);
this.listener = __bind(this.listener, this);
stdin = process.openStdin();
process.stdout.write(this.prompt);
stdin.addListener("data", this.listener);
}
Console.prototype.listener = function($data) {
this.commandHandle($data.toString());
if (this.mode === MODE_REPL) {
if (!this.paused) {
return process.stdout.write(this.prompt);
}
} else {
return process.stdout.write(this.altPrompt);
}
};
Console.prototype.setPrompt = function($prompt) {};
Console.prototype.pause = function($set) {
if (this.paused === $set) {
return;
}
if ((this.paused = $set)) {
return process.stdin.removeListener("data", this.listener);
} else {
process.stdin.addListener("data", this.listener);
if (this.mode === MODE_REPL) {
return process.stdout.write(this.prompt);
} else {
return process.stdout.write(this.altPrompt);
}
}
};
Console.prototype.input = function($prompt, $vars) {
if (this.paused) {
this.pause(false);
}
if ($prompt != null) {
this.print($prompt);
}
this.buffer = [];
this.vars = $vars;
return true;
};
Console.prototype.debug = function($text) {
return process.stdout.write($text.blue + '\n');
};
Console.prototype.hilite = function($text) {
return process.stdout.write($text.yellow + '\n');
};
Console.prototype.print = function($text) {
if ($text == null) {
$text = '';
}
return process.stdout.write($text);
};
Console.prototype.println = function($text) {
if ($text == null) {
$text = '';
}
return process.stdout.write($text + '\n');
};
Console.prototype.clear = function() {};
return Console;
})(),
FileSystem: FileSystem = (function() {
var $root, fs, path;
function FileSystem() {}
fs = require('fs');
path = require('path');
$root = __dirname.slice(0, +__dirname.lastIndexOf('/') + 1 || 9e9);
FileSystem.prototype.setRoot = function($path) {
return $root = $path;
};
FileSystem.prototype.readFile = function($filename, $next) {
return fs.readFile(path.join($root, $filename) + '.bas', function($err, $data) {
if ($err != null) {
return $next($err);
} else {
return $next(null, String($data));
}
});
};
FileSystem.prototype.writeFile = function($filename, $data, $next) {
return fs.writeFile(path.join($root, $filename) + '.bas', "" + $filename + "\n\n" + $data, $next);
};
FileSystem.prototype.deleteFile = function($filename, $next) {
return fs.unlink(path.join($root, $filename) + '.bas', $next);
};
FileSystem.prototype.readDir = function($dir, $next) {
return fs.readdir($root + _data[$dir], function($err, $files) {
var $name;
if ($err != null) {
return $next([]);
} else {
return $next((function() {
var _i, _len, _results;
_results = [];
for (_i = 0, _len = $files.length; _i < _len; _i++) {
$name = $files[_i];
if (/.*\.bas$/.test($name)) {
_results.push($name);
}
}
return _results;
})());
}
});
};
return FileSystem;
})()
};
_data = {
ATARI: 'bas/atari/',
GWBASIC: 'bas/gwbasic/',
GROUP: 'bas/hp2k/group/',
LIBRARY: 'bas/hp2k/system/',
TEST: 'bas/hp2k/test/',
CATALOG: 'bas/hp2k/'
};
}).call(this);
|
var Joi = require('joi');
var ObjectAssign = require('object-assign');
var BaseModel = require('hapi-mongo-models').BaseModel;
var Slug = require('slug');
var AdminGroup = BaseModel.extend({
constructor: function (attrs) {
ObjectAssign(this, attrs);
},
hasPermissionTo: function (permission) {
if (this.permissions && this.permissions.hasOwnProperty(permission)) {
return this.permissions[permission];
}
return false;
}
});
AdminGroup._collection = 'adminGroups';
AdminGroup._idClass = String;
AdminGroup.schema = Joi.object().keys({
_id: Joi.string(),
name: Joi.string().required(),
permissions: Joi.object().description('{ permission: boolean, ... }')
});
AdminGroup.create = function (name, callback) {
var document = {
_id: Slug(name).toLowerCase(),
name: name
};
this.insertOne(document, function (err, docs) {
if (err) {
return callback(err);
}
callback(null, docs[0]);
});
};
module.exports = AdminGroup;
|
import _isArray from "./internal/is_array";
/**
* Returns `true` if the argument is an atom; `false` otherwise. An atom is defined as any
* value that is not an array, `undefined`, or `null`.
*
* @func
* @memberOf R
* @category Array
* @sig a -> Boolean
* @param {*} x The element to consider.
* @return {boolean} `true` if `x` is an atom, and `false` otherwise.
* @example
*
* ramda.isAtom([]); //=> false
* ramda.isAtom(null); //=> false
* ramda.isAtom(undefined); //=> false
*
* ramda.isAtom(0); //=> true
* ramda.isAtom(''); //=> true
* ramda.isAtom('test'); //=> true
* ramda.isAtom({}); //=> true
*/
export default function(x) {
return x != null && !_isArray(x);
};
|
define([
'app-lib/vstack'
], function(vstack) {
/*
afterAll(function(done) {
vstack.dropTables().then(function() {
done();
});
});
*/
describe("test that createTables vstack works when tables exist.", function() {
it("returns successfully", function(done) {
done();
vstack.createTables().then(function() {
expect(true).toBeTruthy();
done();
});
});
});
});
|
var gulp = require('gulp');
var zip = require('gulp-zip');
var del = require('del');
var install = require('gulp-install');
var runSequence = require('run-sequence');
var awsLambda = require("node-aws-lambda");
gulp.task('clean', function() {
return del(['./dist', './dist.zip']);
});
gulp.task('js', function() {
return gulp.src('index.js')
.pipe(gulp.dest('dist/'));
});
gulp.task('node-mods', function() {
return gulp.src('./package.json')
.pipe(gulp.dest('dist/'))
.pipe(install({production: true}));
});
gulp.task('zip', function() {
return gulp.src(['dist/**/*', '!dist/package.json'])
.pipe(zip('dist.zip'))
.pipe(gulp.dest('./'));
});
gulp.task('upload', function(callback) {
awsLambda.deploy('./dist.zip', require("./lambda-config.js"), callback);
});
gulp.task('deploy', function(callback) {
return runSequence(
['clean'],
['js', 'node-mods'],
['zip'],
['upload'],
callback
);
});
|
// Use this mixin at HTML/BODY level to enable pjax behavior
// Your fluxexapp should provide routeToURL() for this mixin
// See routeToURL.js for more info
//
// To support IE8,
// You will need to npm install html5-history-api,
// then add require('fluxex/extra/history'); in your fluxexapp.js
module.exports = {
componentDidMount: function () {
/*global window,document*/
var blockDoublePop = (document.readyState !== 'complete'),
initState = JSON.stringify(this._getContext()._context),
location = window.history.location || window.location,
initUrl = location.href;
window.addEventListener('load', function() {
setTimeout(function () {
blockDoublePop = false;
}, 1);
});
window.addEventListener('popstate', function (E) {
var state = E.state || ((location.href === initUrl) ? initState : undefined);
if (blockDoublePop && (document.readyState === 'complete')) {
return;
}
try {
state = JSON.parse(state);
} catch (E) {
state = 0;
}
if (!state) {
// NO STATE DATA....can not re-render, so reload.
location.reload();
return;
}
// Ya, trigger page restore by an anonymous action
this.executeAction(function () {
this._restore(state);
this.dispatch('**UPDATEALL**');
return Promise.resolve(true);
}.bind(this._getContext()));
}.bind(this));
},
handleClickLink: function (E) {
var A = E.target.closest('a[href]') || E.target;
var HREF = A.href;
if (!HREF || HREF.match(/#/) || (A.target === '_blank')) {
return;
}
if ((A.target === '_top') && (window.top !== window)) {
return;
}
if ((A.target === '_parent') && (window.parent !== window)) {
return;
}
E.preventDefault();
E.stopPropagation();
return this._getContext().routeToURL(HREF);
}
};
|
import dispatcher from "../stores/dispatcher";
export function createPosts(post) {
dispatcher.dispatch({
type: "CREATE_POST",
post
});
}
export function deletePost(id) {
dispatcher.dispatch({
type: "DELETE_POST",
id
})
}
|
/**
* @param {number} c
* @return {boolean}
*/
const judgeSquareSum = function (c) {
for (let i = 0; i <= Math.sqrt(c / 2); ++i) {
let x = c - i * i;
let sqrtX = Math.sqrt(x);
if (sqrtX === Math.floor(sqrtX)) {
return true;
}
}
return false;
};
module.exports = judgeSquareSum;
|
export default {
dialPlaceholder: "Name oder Nr. eingeben"
};
// @key: @#@"dialPlaceholder"@#@ @source: @#@"Enter Name or Number"@#@
|
define([
'streamhub-sdk/content/views/content-list-view',
'streamhub-gallery/content/content-view-factory',
'text!streamhub-gallery/css/horizontal-list-view.css',
'streamhub-sdk/debug',
'inherits'
], function (ContentListView, HorizontalContentViewFactory, HorizontalListViewCss, debug, inherits) {
'use strict';
var log = debug('streamhub-gallery/views/horizontal-list-view');
var STYLE_EL;
/**
* A simple View that displays Content in a horizontal list.
*
* @param opts {Object} A set of options to config the view with
* @param opts.el {HTMLElement} The element in which to render the streamed content
* @exports streamhub-gallery/views/horizontal-list-view
* @augments streamhub-sdk/views/list-view
* @constructor
*/
var HorizontalListView = function (opts) {
opts = opts || {};
this._id = 'streamhub-horizontal-list-'+new Date().getTime();
this._aspectRatio = opts.aspectRatio || 16/9;
opts.contentViewFactory = new HorizontalContentViewFactory();
ContentListView.call(this, opts);
if (!STYLE_EL) {
STYLE_EL = $('<style></style>').text(HorizontalListViewCss).prependTo('head');
}
var self = this;
$(window).on('resize', function (e) {
self._handleResize(e);
});
this._adjustContentSize();
};
inherits(HorizontalListView, ContentListView);
HorizontalListView.prototype.horizontalListViewClassName = 'streamhub-horizontal-list-view';
HorizontalListView.prototype.contentContainerClassName = 'content-container';
/**
* Set the element for the view to render in.
* You will probably want to call .render() after this, but not always.
* @param element {HTMLElement} The element to render this View in
* @return this
*/
HorizontalListView.prototype.setElement = function (el) {
ContentListView.prototype.setElement.call(this, el);
this.$el.addClass(this.horizontalListViewClassName).addClass(this._id);
};
HorizontalListView.prototype._handleResize = function (e) {
this._adjustContentSize();
};
/**
* @private
* Sets appropriate dimensions on each ContentView in the gallery.
* By default, a ContentViews new dimensions respects the gallery's specified aspect ratio.
* For content whose intrinsic apsect ratio is 1:1, it will retain a 1:1 aspect ratio.
* ContentViews with tiled attachments will also retain a 1:1 aspect ratio.
*/
HorizontalListView.prototype._adjustContentSize = function () {
if (! this._aspectRatio) {
return;
}
var styleEl = $('style.'+this._id);
if (styleEl) {
styleEl.remove();
}
styleEl = $('<style class="'+this._id+'"></style>');
var styles = '';
var containerHeight = this.$el.height();
var contentWidth = containerHeight * this._aspectRatio;
styles = '.'+this.horizontalListViewClassName + ' .'+this.contentContainerClassName + '{ max-width: ' + contentWidth + 'px; }';
styleEl.html(styles);
$('head').append(styleEl);
return styleEl;
};
/**
* @private
* Insert a contentView into the ListView's .el
* after being wrapped by a container element.
* Get insertion index based on this.comparator
* @param contentView {ContentView} The ContentView's element to insert to the DOM
*/
HorizontalListView.prototype._insert = function (contentView) {
var newContentViewIndex,
$previousEl;
newContentViewIndex = this.views.indexOf(contentView);
var $containerEl = $('<div class="' + this.contentContainerClassName + '"></div>');
contentView.$el.wrap($containerEl);
var $wrappedEl = contentView.$el.parent();
if (newContentViewIndex === 0) {
// Beginning!
$wrappedEl.prependTo(this.el);
} else {
// Find it's previous contentView and insert new contentView after
$previousEl = this.views[newContentViewIndex - 1].$el;
$wrappedEl.insertAfter($previousEl.parent('.'+this.contentContainerClassName));
}
this.$el.css('width', this.views.length * this.views[0].$el.parent().outerWidth(true) + 'px');
};
return HorizontalListView;
});
|
(function() {
'use strict';
/**
* @name RootController
* @description The root controller that contains some rootScope accessible methods
* @memberof ag
*/
angular.module('ag').controller('RootController', getRootController);
var inject = ['$rootScope'];
getRootController.$inject = inject;
function getRootController($rootScope) {
// Method visible in the entire app and
// allows to start the loading spinner
$rootScope.startLoading = function() {
$rootScope.root.loading = true;
$rootScope.root.loadingQueue++;
};
// Method visible in the entire app and
// allows to stop the loading spinner
$rootScope.endLoading = function() {
$rootScope.root.loadingQueue--;
// Prevent bad call of the function
if ($rootScope.root.loadingQueue < 0) {
$rootScope.root.loadingQueue = 0;
}
if ($rootScope.root.loadingQueue === 0) {
$rootScope.root.loading = false;
}
};
}
})();
|
'use strict';
/**
* @ngdoc function
* @name wavesApp.controller:EventsCtrl
* @description
* # EventsCtrl
* Controller of the wavesApp
*/
angular.module('wavesApp')
.controller('EventsCtrl', ['$scope', function ($scope) {
$scope.events = [
'Evento1', 'Evento2', 'Evento3', 'Evento4', 'Evento5', 'Evento6', 'Evento7'
];
}]);
|
'use strict';
angular.module('core.admin').run(['Menus',
function (Menus) {
Menus.addMenuItem('topbar', {
title: 'Admin',
state: 'admin',
type: 'dropdown',
roles: ['admin']
});
Menus.addSubMenuItem('topbar', 'admin', {
title: 'Dashboard',
state: 'admin.dashboard',
type: 'dropdown',
roles: ['admin']
});
}
]);
|
'use strict';
angular.module('vppApp')
.factory('User', function ($resource) {
// TODO
});
|
/**
* 所有组件的基类
*/
class BaseModule {
constructor() {
//this.__exp 接口引用,使用实例绑定上下文,不直接使用
//this.__exports 接口引用,未绑定上下文,不直接使用
//this.exports 提供设置和获取暴露接口的get、set,
}
get exports() {
return this.__exp;
}
set exports(exp_s) {
var context = this;
//用于编译时候的原始方法备份,防止编译出[native code]
var __exports = context.__exports = {};
var es = this.__exp = exp_s;
for(var exp in es){
if(es.hasOwnProperty(exp) && es[exp] instanceof Function){
__exports[exp] = es[exp];
es[exp] = es[exp].bind(context)
}
}
return context
}
//bindExports(context){
// //用于编译时候的原始方法备份,防止编译出[native code]
// var __exports = context.__exports = {};
// var es = context.exports
//
// for(var exp in es){
// if(es.hasOwnProperty(exp)){
// __exports[exp] = es[exp];
// es[exp] = es[exp].bind(context)
// }
// }
// return context
//}
//获取所有可编辑、配置的项,默认写法,可被重写
superFields() {
if(!this.element){
return undefined
}
//var param = this.element.param || {}
var $html;
if(this.configs instanceof Function){
$html = $(this.configs(this.element))
}else{
$html = $(this.configs)
}
//$html.find("[data-name]").each(function (i, n) {
// var $this = $(n)
// $this.val(param[$this.data("name")]);
//});
return $html;
}
fields(deferred, param) {
deferred.resolve(this.superFields())
}
config(key, value) {
var data = this.$dom.data("data")
if (arguments.length === 1) {
return data.param[key]
} else if (arguments.length > 1) {
return data.param[key] = value;
}
}
exec(code,api){
try{
var fun = new Function("api","" +
"var API = api;"
+code)
fun(api)
}catch(e){
console.log(e)
}
}
}
module.exports = BaseModule
|
/*
notes
getBoolPref is not a function
http://comments.gmane.org/gmane.comp.mozilla.project-owners/241
*/
//*********** export named single global object while using shorthand internally
var spenibus_zoomMonitor = (function() {
//************************************************************** run on load
window.addEventListener('load', (function f(){
// remove init listener
window.removeEventListener('load', f, false);
// init
//s.init.call(s);
s.init();
}), false);
//******************************************************* internal shorthand
var s = {};
//***************************************************************** elements
s.nodeMain = null;
s.nodeLabel = null;
s.nodeMenu = null;
//************************************************************ prefs service
s.ps = null;
//************************************************************** node getter
s.nodeGet = function(id) {
// try document first
var n = document.getElementById(id);
// try toolbar palette if document yielded nothing
if(n == null) {
n = gNavToolbox.palette.querySelector('#'+id);
}
return n;
};
//***************************************************** check full-page mode
s.fullGet = function() {
return s.ps.getBoolPref("browser.zoom.full");
};
//******************************************************* zoom values getter
s.zoomValuesGet = function() {
return s.ps.getCharPref("toolkit.zoomManager.zoomValues")
.split(",")
.reverse();
};
//************************************************************** zoom setter
s.zoomSet = function(z) {
// change relevant zoom value
s.fullGet()
? gBrowser.selectedBrowser.markupDocumentViewer.fullZoom = z
: gBrowser.selectedBrowser.markupDocumentViewer.textZoom = z;
// update ui
s.updateUI();
};
//*************************************************************** ui updater
s.updateUI = function(e) {
// main display
s.nodeLabel.innerHTML = s.fullGet()
? 'F'+Math.round(gBrowser.selectedBrowser.markupDocumentViewer.fullZoom * 100)+'%'
: 'T'+Math.round(gBrowser.selectedBrowser.markupDocumentViewer.textZoom * 100)+'%';
// get current zoom level
var currentZoom = s.fullGet()
? gBrowser.selectedBrowser.markupDocumentViewer.fullZoom
: gBrowser.selectedBrowser.markupDocumentViewer.textZoom;
var currentZoomPercentage = Math.round(currentZoom*100);
// get zoom values
var list = s.zoomValuesGet();
// clear menu
s.nodeMenu.innerHTML = '';
// build menu
for(var i=0; i<list.length; ++i) {
var zoomFactor = list[i];
var zoomPercentage = Math.round(zoomFactor*100);
// create menu item
var item = document.createElement('menuitem');
// set attributes
item.setAttribute('label', zoomPercentage+'%');
item.setAttribute('data-zoom', zoomFactor);
// highlight current zoom
if(currentZoomPercentage == zoomPercentage) {
item.classList.add("current");
}
// set command
item.addEventListener("command", function(e){
s.zoomSet(e.target.getAttribute('data-zoom'));
}, false);
// add item to menu
s.nodeMenu.appendChild(item);
}
};
//********************************************************************* init
s.init = function() {
// prefs service
s.ps = Components
.classes["@mozilla.org/preferences-service;1"]
.getService(Components.interfaces.nsIPrefService)
.QueryInterface(Components.interfaces.nsIPrefBranch);
// get elements
s.nodeMain = s.nodeGet('spenibus_zoom_monitor_main');
s.nodeLabel = s.nodeGet('spenibus_zoom_monitor_label');
s.nodeMenu = s.nodeGet('spenibus_zoom_monitor_menu');
// override native function: enlarge/reduce
FullZoom._applyZoomToPrefOriginal = FullZoom._applyZoomToPref;
FullZoom._applyZoomToPref = function() {
FullZoom._applyZoomToPrefOriginal.apply(this, arguments);
s.updateUI();
}
// override native function: reset
FullZoom._removePrefOriginal = FullZoom._removePref;
FullZoom._removePref = function() {
FullZoom._removePrefOriginal.apply(this, arguments);
s.updateUI();
}
// event callback
var callback = function(){
s.updateUI.call(s);
}
// observe certain events
gBrowser.tabContainer.addEventListener("TabOpen", callback, false);
gBrowser.tabContainer.addEventListener("TabSelect", callback, false);
gBrowser.addEventListener("pageshow", callback, false);
gBrowser.addEventListener("click", callback, false);
// update ui
s.updateUI();
};
//******************************************************************* export
return s;
})();
|
/**
* Created by Pencroff on 04-Sep-16.
*/
var gulp = require('gulp');
var plumber = require('gulp-plumber');
var concat = require('gulp-concat');
var rename = require('gulp-rename');
var uglify = require('gulp-uglify');
var dotify = require('gulp-dotify');
var watch = require('gulp-watch');
var transform = require('gulp-transform');
var wrapper = require('gulp-wrapper');
var destination = 'assets';
gulp.task('generate-data-file', function() {
global.window = {};
return gulp.src('tests/*.js')
.pipe(plumber())
.pipe(transform(function (content) {
eval(content);
var test = global.window.test;
return [
'{ ',
'id:\'', test.id, '\',',
'name:\'', test.name, '\',',
'description:\'', test.description, '\',',
'tags:', '[\'', test.tags.join('\',\''), '\'],',
'url:\'', test.url, '\'',
' }'
].join('');
}, {encoding: 'utf8'}))
.pipe(concat('data.js', {newLine: ','}))
.pipe(wrapper({
header: '(function (r) {r.data=[',
footer: '];})(window.PerformanceJs);'
}))
.pipe(gulp.dest(destination));
});
gulp.task('templates', function() {
return gulp.src('src/views/**/*.html')
.pipe(plumber())
.pipe(dotify({
dictionary: 'r.JST'
}))
.pipe(concat('templates.min.js'))
.pipe(uglify())
.pipe(wrapper({
header: '(function (r) {r.JST={},',
footer: '})(window.PerformanceJs);'
}))
.pipe(gulp.dest(destination));
});
gulp.task('templates-watch', function () {
watch('src/views/**/*.html', function () {
gulp.start('templates')
})
}
);
makeTask({
name: 'app',
files: 'src/**/*.js',
destination: destination,
uglify: true
});
makeTask({
name: 'vendor',
files: ['assets/js/lodash.min.js', 'assets/js/bluebird.min.js',
'assets/js/domtastic.min.js', 'assets/js/grapnel.min.js'],
destination: destination,
});
makeTask({
name: 'benchmark',
files: ['assets/js/benchmark.js', 'assets/js/platform.js'],
destination: destination
});
gulp.task('engine', ['app', 'vendor', 'benchmark', 'templates', 'generate-data-file']);
gulp.task('engine-watch', ['app-watch', 'templates-watch']);
function makeTask(options) {
gulp.task(options.name, function() {
var stream = gulp.src(options.files)
.pipe(plumber())
.pipe(concat(options.name + '.js'))
.pipe(gulp.dest(options.destination));
if (options.uglify) {
stream.pipe(rename(options.name + '.min.js'))
.pipe(uglify())
.pipe(gulp.dest(options.destination));
}
return stream;
});
gulp.task(options.name + '-watch', function () {
watch(options.files, function () {
gulp.start(options.name)
})
}
);
}
|
'use strict' ;
var Emitter = require('events').EventEmitter ;
var util = require('util') ;
var outboundCallProcessor = require('./outbound-call-processor') ;
var inboundCallProcessor = require('./inbound-call-processor') ;
var spawn = require('child_process').spawn;
var iptables = require('iptables') ;
var parseUri = require('drachtio-sip').parser.parseUri ;
var ban = true ;
var chain = 'LOGDROP';
// verify the chain exists
var cmd = spawn('sudo', ['iptables','-S', chain]);
cmd.stderr.on('data', function(buf) {
console.error('NB: blacklisting is disabled, error listing chain LOGs: ', chain, String(buf)) ;
ban = false ;
}) ;
module.exports = exports = CallProcessor ;
function CallProcessor( srf, mediaServer, registrar ){
if (!(this instanceof CallProcessor)) { return new CallProcessor(srf, mediaServer, registrar); }
Emitter.call(this);
console.log('mediaServer: ', mediaServer);
this.srf = srf ;
this.mediaServer = mediaServer ;
this.registrar = registrar ;
this.calls = new Map() ;
}
util.inherits(CallProcessor, Emitter) ;
CallProcessor.prototype.start = function() {
this.srf.invite( ( req, res ) => {
console.log(`received invite from ${req.protocol}/${req.source_address}:${req.uri} with request uri %s` ) ;
var user = parseUri( req.uri ).user ;
if( this.registrar.hasUser( user ) ) {
var details = this.registrar.getUser( user ) ;
console.log(`inbound call with details: ${JSON.stringify(details)}`) ;
inboundCallProcessor( this.srf, req, res, details.uri, this.mediaServer, this.registrar, (err, uas, uac, ms, ep1, ep2) => {
if( err ) {
console.error(`${req.get('Call-Id')}: error connecting call: ${err.message}`) ;
return ;
}
this.setHandlers( uas, uac, ms, ep1, ep2 ) ;
}) ;
}
else if( 'udp' === req.protocol ) {
// outbound call, but it is coming via UDP. We only allow outbound calls via WSS
console.error(`banning ${req.source_address}:${req.source_port} due to unauthorized attempt to ${req.uri}`) ;
if( ban ) {
iptables.drop({
chain: chain,
src: req.source_address,
sudo: true
}) ;
}
}
else {
outboundCallProcessor( this.srf, req, res, req.uri, this.mediaServer, this.registrar, (err, uas, uac, ms, ep1, ep2) => {
if( err ) {
if( err.status !== 401 && err.status !== 407 ) {
console.error(`${req.get('Call-Id')}: error connecting call: ${err.status}`) ;
}
return ;
}
this.setHandlers( uas, uac, ms, ep1, ep2 ) ;
}) ;
}
});
} ;
CallProcessor.prototype.setHandlers = function( uas, uac, ms, ep1, ep2 ) {
var key = makeReplacesStr(uas) ;
var value = makeReplacesStr(uac) ;
this.calls.set(key, value) ;
console.log(`after adding call there are now ${this.calls.size} calls in progress`);
uas.on('destroy', this._onDestroy.bind( this, uas, uac, ms, ep1, ep2 )) ;
uac.on('destroy', this._onDestroy.bind( this, uac, uas, ms, ep1, ep2 )) ;
uas.once('refer', this._handleRefer.bind( this, uas, uac ) ) ;
uac.once('refer', this._handleRefer.bind( this, uac, uas ) ) ;
uas.on('hold', this._hold.bind( this, uas, uac, ep1, ep2 )) ;
uac.on('hold', this._hold.bind( this, uac, uas, ep1, ep2 )) ;
uas.on('unhold', this._unhold.bind( this, uas, uac, ep1, ep2 )) ;
uac.on('unhold', this._unhold.bind( this, uac, uas, ep1, ep2 )) ;
uas.on('info', this._handleInfo.bind( this, uas, uac, ep1, ep2 ) ) ;
uac.on('info', this._handleInfo.bind( this, uac, uas, ep2, ep1 ) ) ;
} ;
CallProcessor.prototype._onDestroy = function( dlg, dlgOther, ms, ep1, ep2 ) {
var key = makeReplacesStr(dlg) ;
if( this.calls.has( key ) ) {
this.calls.delete( key );
}
else {
key = makeReplacesStr(dlgOther) ;
if( this.calls.has( key ) ) {
this.calls.delete( key );
}
else {
console.error(`key ${key} not found`);
}
}
[dlgOther, ep1, ep2].forEach( function(e) { e.destroy(); }) ;
ms.disconnect() ;
console.log(`after ending call there are now ${this.calls.size} calls in progress`);
} ;
CallProcessor.prototype._handleRefer = function( dlg, dlgOther, req, res ) {
var referTo = req.get('Refer-To') ;
var arr = /(.*)Replaces=(.*)>/.exec(referTo) ;
if( arr && arr.length > 1 ) {
// attended transfer: fixup the Replaces part of the Refer-To header
var key = arr[2] ;
if( key in this._calls ) {
referTo = arr[1] + 'Replaces=' + this._calls[key] + '>' ;
}
else {
console.error(`attended transfer but we cant find ${key}`);
}
}
dlgOther.request({
method: 'REFER',
headers: {
'Refer-To': referTo
}
});
res.send(202);
} ;
CallProcessor.prototype._hold = function( dlg, dlgOther, ep1 /*, ep2 */) {
ep1.unbridge( function(err) {
if( err ) {
console.error(`Error unbridging endpoints when going on hold: ${err}`) ;
}
});
} ;
CallProcessor.prototype._unhold = function( dlg, dlgOther, ep1, ep2 ) {
ep1.bridge( ep2, function(err) {
if( err ) {
console.error(`Error bridging endpoints back together after unhold: ${err}`) ;
}
});
} ;
CallProcessor.prototype._handleInfo = function( dlg, dlgOther, ep1, ep2, req, res ) {
console.log('received info with content-type: %s', req.get('Content-Type'));
res.send(200) ;
if( req.get('Content-Type') === 'application/media_control+xml' ) {
console.log('forwarding to freeswitch ');
dlgOther.request({
method: 'INFO',
headers: {
'Content-Type': req.get('Content-Type'),
},
body: req.body
});
}
} ;
function makeReplacesStr( dlg ) {
var s = '';
if( dlg.type === 'uas') {
s = encodeURIComponent( dlg.sip.callId + ';to-tag=' + dlg.sip.localTag + ';from-tag=' + dlg.sip.remoteTag ) ;
}
else {
s = encodeURIComponent( dlg.sip.callId + ';to-tag=' + dlg.sip.remoteTag + ';from-tag=' + dlg.sip.localTag ) ;
}
return s ;
}
|
// Regular expression that matches all symbols in the `Deseret` script as per Unicode v5.0.0:
/\uD801[\uDC00-\uDC4F]/;
|
define([
'jquery',
'underscore',
'backbone',
'scripts/main/models/forum',
], function($, _, Backbone, ForumModel){
var ForumCollection = Backbone.Collection.extend({
model : ForumModel,
url : ForumModel.prototype.urlRoot,
});
return ForumCollection;
});
|
// track page views
var _gaq = _gaq || []; _gaq.push(['_setAccount', 'UA-105747972-2']); _gaq.push(['_trackPageview']);
(function() {
var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true; ga.src = 'https://ssl.google-analytics.com/ga.js';
var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s);
})();
var currIcon = 0;
updateState(null);
// updates icon image
function updateIcon() {
currIcon = (currIcon + 1) % 2;
chrome.browserAction.setIcon({path: "./../icons/ticker_sticker_" + currIcon + ".png"});
}
// turning extension on and off
chrome.browserAction.onClicked.addListener(function(tab) {
updateState(tab);
});
function updateState(tab) {
updateIcon();
chrome.storage.sync.set({'state': currIcon}, function() {
//message('Toggled on/off');e
});
}
|
(() => {
'use strict';
angular
.module('app')
.service('TokenService', TokenService);
function TokenService($localStorage) {
this.get = get;
this.save = save;
this.clean = clean;
////
function get() {
return $localStorage.token;
}
function save(token) {
return $localStorage.token = token;
}
function clean() {
delete $localStorage.token;
}
}
})();
|
import React from 'react'
import { Link } from 'react-router'
import { prefixLink } from 'gatsby-helpers'
import Wrapper from '../components/wrapper'
import Articles from '../components/articles'
import Nav from '../components/nav'
import Hero from '../components/hero'
import Footer from '../components/footer'
import DocumentMeta from 'react-document-meta'
export default class BlogIndex extends React.Component {
render() {
const meta = {
title: 'Wanderlust - A blog about digital nomad lifestyle',
description: 'Digital nomads travel the world and work location independent.',
canonical: 'https://wanderlust.tech/en/',
locale: 'en'
}
this.props.route.path = '/en/'
this.props.route.page.data = {
locale: 'EN'
}
return (
<div>
<DocumentMeta {...meta} />
<Nav route={this.props.route} />
<Hero route={this.props.route} />
<Wrapper>
<Articles route={this.props.route} />
</Wrapper>
<Footer />
</div>
)
}
}
|
'use strict';
exports.command = function( ) {
const SauceLabs = require( 'saucelabs' );
const saucelabs = new SauceLabs({
username: process.env.SAUCE_USERNAME,
password: process.env.SAUCE_ACCESS_KEY
});
const sessionid = this.capabilities[ 'webdriver.remote.sessionid' ];
saucelabs.updateJob( sessionid, {
passed: this.currentTest.results.failed === 0
}, () => {});
return this;
};
|
/*
* Clearest Framework
* Provided under MIT License.
* Copyright (c) 2012-2015 Illya Kokshenev <sou@illya.com.br>
*/
/**
* Created by M0nZDeRR on 30/10/2015.
*/
var chai = require("chai"),
expect = chai.expect,
commons = require("../../core/commons"),
inside = commons.inside,
Serializer = require("../../tool/serializer.js");
describe("tool / serializer", function(){
it("should serialize simple elements",function(){
var ser = new Serializer();
expect(ser.serialize(undefined)).to.be.equal("undefined");
expect(ser.serialize(null)).to.be.equal("null");
expect(ser.serialize(42)).to.be.equal('42');
expect(ser.serialize('foo')).to.be.equal('"foo"');
});
it("should serialize objects, functions and call custom serializers",function(){
var ser = new Serializer();
var f = function (a,b,c){return a+b+c};
expect(ser.serialize(f)).to.be.equal(f.toString());
expect(ser.serialize({})).to.be.equal('{}');
expect(ser.serialize({foo:42})).to.be.equal('{foo:42}');
expect(ser.serialize({foo:"42"})).to.be.equal('{foo:"42"}');
var o={};
inside(o).serialize = function(ser){return ser.serialize('custom!');}
expect(ser.serialize(o)).to.be.equal('"custom!"');
});
//it("should serialize recursive references ")
});
|
const router = require("express").Router();
const Category = require("../model/Category");
const { categoryValidation } = require("../validation");
const verify = require("./verifyToken");
router.post("/", verify, async (req, res) => {
const { error } = categoryValidation(req.body);
if (error) return res.status(400).send(error.details[0].message);
const category = new Category({
name: req.body.name,
icon: req.body.icon,
color: req.body.color,
owner: req.user._id
});
try {
const savedCategory = await category.save();
res.send(savedCategory);
} catch (err) {
res.status(400).send(err);
}
});
router.get("/", verify, async (req, res) => {
let query = {};
if (req.user.role !== "admin") {
query.owner = req.user._id;
}
try {
const allCategories = await Category.find(query);
res.send(allCategories);
} catch (err) {
res.status(400).send(err);
}
});
router.get("/:id", verify, async (req, res) => {
let query = {};
if (req.user.role !== "admin") {
query.owner = req.user._id;
}
try {
const categoryDetails = await Category.findById(
req.params.id,
(err, detail) => {
var opts = [{ path: "category", match: { owner: req.user._id } }];
Category.populate(detail, opts, function(err, details) {
console.log(details);
});
}
);
res.send(categoryDetails);
} catch (err) {
res.status(400).send(err);
}
});
router.put("/:id", async (req, res) => {
try {
Category.findOneAndUpdate(
{
_id: req.params.id
},
{
name: req.body.name,
icon: req.body.icon
},
err => {
if (err) {
return res.send(err);
}
return res.send("Successfully updated!");
}
);
} catch (err) {
res.status(400).send(err);
}
});
router.delete("/:id", async (req, res) => {
try {
const data = await Category.deleteOne({ _id: req.params.id });
if (data.ok === 1) {
return res.send("Successfully deleted!");
}
} catch (err) {
res.status(400).send(err);
}
});
module.exports = router;
|
//Wrapped in an outer function to preserve global this
(function (root) { var amdExports; define(['bootstrap/bootstrap-transition','bootstrap/bootstrap-tooltip'], function () { (function () {
/* ===========================================================
* bootstrap-popover.js v2.3.1
* http://twitter.github.com/bootstrap/javascript.html#popovers
* ===========================================================
* Copyright 2012 Twitter, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =========================================================== */
!function ($) {
"use strict"; // jshint ;_;
/* POPOVER PUBLIC CLASS DEFINITION
* =============================== */
var Popover = function (element, options) {
this.init('popover', element, options)
}
/* NOTE: POPOVER EXTENDS BOOTSTRAP-TOOLTIP.js
========================================== */
Popover.prototype = $.extend({}, $.fn.tooltip.Constructor.prototype, {
constructor: Popover
, setContent: function () {
var $tip = this.tip()
, title = this.getTitle()
, content = this.getContent()
$tip.find('.popover-title')[this.options.html ? 'html' : 'text'](title)
$tip.find('.popover-content')[this.options.html ? 'html' : 'text'](content)
$tip.removeClass('fade top bottom left right in')
}
, hasContent: function () {
return this.getTitle() || this.getContent()
}
, getContent: function () {
var content
, $e = this.$element
, o = this.options
content = (typeof o.content == 'function' ? o.content.call($e[0]) : o.content)
|| $e.attr('data-content')
return content
}
, tip: function () {
if (!this.$tip) {
this.$tip = $(this.options.template)
}
return this.$tip
}
, destroy: function () {
this.hide().$element.off('.' + this.type).removeData(this.type)
}
})
/* POPOVER PLUGIN DEFINITION
* ======================= */
var old = $.fn.popover
$.fn.popover = function (option) {
return this.each(function () {
var $this = $(this)
, data = $this.data('popover')
, options = typeof option == 'object' && option
if (!data) $this.data('popover', (data = new Popover(this, options)))
if (typeof option == 'string') data[option]()
})
}
$.fn.popover.Constructor = Popover
$.fn.popover.defaults = $.extend({} , $.fn.tooltip.defaults, {
placement: 'right'
, trigger: 'click'
, content: ''
, template: '<div class="popover"><div class="arrow"></div><h3 class="popover-title"></h3><div class="popover-content"></div></div>'
})
/* POPOVER NO CONFLICT
* =================== */
$.fn.popover.noConflict = function () {
$.fn.popover = old
return this
}
}(window.jQuery);
}.call(root));
return amdExports;
}); }(this));
|
import React, {PropTypes} from 'react';
import {connect} from 'react-redux';
import {bindActionCreators} from 'redux';
import * as actions from '../../actions/itemActions';
import FilterList from '../../components/FilterList/FilterList';
export const Filters = (props) => {
return (
<FilterList
changeShop={props.actions.changeShop}
shop={props.shop} />
);
};
Filters.propTypes = {
actions: PropTypes.object.isRequired,
shop: PropTypes.oneOf([
'side',
'secret',
'basics',
'upgrades'
])
};
function mapStateToProps(state) {
return {
shop: state.layout.shop
};
}
function mapDispatchToProps(dispatch) {
return {
actions: bindActionCreators(actions, dispatch)
};
}
export default connect(
mapStateToProps,
mapDispatchToProps
)(Filters);
|
var priceCount;
var priceCountS;
window.onload = function(){
initContentList(1);
//$("#addContentBtn").bind("click",function(){
// window.location = "csicrmmgr.do?page=11";
//});
$("#query").bind("click",function(){initContentList(1);});
};
$(".colors a").live({
mouseover: (function(){
$(this).css("color","blue");
}),
mouseout:(function(){
$(this).css("color","red");
})
});
function initContentList(currPage){
var pageSize =15;
var data = {};
var form = ((currPage=currPage==0?1:currPage)-1)*pageSize;
data.from = form;
data.pageSize = pageSize;
data.memberId = $("#memberId").val();
data.orderId = $("#orderId").val();
data.state = $("#state option:selected").val();
data.sdate = $("#sdate").val();
data.edate = $("#edate").val();
if(data.edate!=null&&data.sdate!=null){
var totalMonth = getMct(data.sdate,data.edate,'-');
if(totalMonth>=6){
jAlert("查询日期范围不能大于半年","提示");
return;
}
}
var jsonData = JSON.stringify(data);
$.post("Orderstatis.do?method=getsalesList",{data:jsonData},function(json){
if(json!=null && json.returnState == true){
var data=json.data[0];
var context=$("#dataList");
context.html('');
if (data != null && data.length > 0) {
priceCount = json.data[1];
priceCountS = json.data[2];
$("#dataTips").hide();
var h=new Array();
for(var i=0;i<data.length;i++){
var bean=data[i];
h.push("<tr>");
h.push("<td>"+bean.recordId+"</td>");
h.push("<td class='colors'>"+bean.orderId+"</td>");
h.push("<td>"+bean.name+"</td>");
h.push("<td>"+bean.orderNum+"</td>");
h.push("<td>"+bean.unitPrice+"</td>");
h.push("<td>"+stateInfo(bean.state)+"</td>");
h.push("<td>"+bean.createTime+"</td>");
h.push("</tr>");
}
h.push("<tr class='tb td1'><td style='text-align: left;' colspan='6'>总订单金额:"+priceCount+"元 成功订单金额:"+priceCountS+"元 成效率:"+toDecimal(priceCountS/priceCount*100)+"%</td></tr>");
context.append(h.join(''));
}else{
$("#dataTips").show();
}
}
page(json.total,pageSize,currPage,"pageInfo","initContentList");
},"json");
}
//获取两个日期之间的月份差距
function getMct(beginTime,endTime,sign){
var beginDate = beginTime.split(sign);// 拆分开始日期的年月日
var endDate = endTime.split(sign);// 拆分开始日期的年月日
var bMonth = parseInt(beginDate[0]) * 12 + parseInt(beginDate[1]);// 得到开 始日期的月数
var eMonth = parseInt(endDate[0]) * 12 + parseInt(endDate[1]);// 得到结束日 期的月数
var totalMonth = Math.abs(eMonth - bMonth);// 获取月数
return totalMonth;
}
/**查看订单详情**/
function showTxt(memberId){
window.location ="Membermanage.do?page=12&memberId="+memberId;
}
/**设置操作栏按钮**/
function stateBut(bean){
if('1'==bean.state){
return "<input type='button' id='topay' value='已支付' class='bt_1' onclick=topay('"+bean.memberId+"','"+bean.currency+"','"+bean.totalAmount+"','"+bean.orderId+"');>";
}else if('2'==bean.state){
return "<input type='button' id='backpay' value='已发货' class='bt_1'>";
}
}
/**设置状态**/
function stateInfo(state){
if('1'==state){
return '待支付';
}
if('2'==state){
return '已支付';
}
if('3'==state){
return '已发货';
}
if('4'==state){
return '已接收';
}
if('5'==state){
return '已结案';
}
if('6'==state){
return '异常';
}
if('7'==state){
return '退货';
}
}
/**确认支付**/
function topay(memberId,currency,totalAmount,orderId){
jConfirm("您确认用户已经付款?", "提示", function (r) {
if (r) {
var data={};
data.memberId=memberId;
data.orderId=orderId;
data.currency=currency;
data.totalAmount=totalAmount;
var jsonData=JSON.stringify(data);
$.post("Ordermanage.do?method=toPayforOrder",{data:jsonData},function(json){
if(json!=null && json.returnState == true){
var message=json.message; //提示信息:0,币种不同 1,操作成功 2,余额不足 3,系统错误
if('0'==message){
jAlert("币种不同,无法支付!!","提示");
}else if('1'==message){
jAlert("操作成功!!","提示",function(){
initContentList(1);
});
}else if('2'==message){
jAlert("用户账户余额不足,不能执行'已支付'动作!!","提示");
}else if('3'==message){
jAlert("操作失败,请重试!!","提示");
}
}else{
jAlert("操作失败,请重试!!","提示");
}
},"json");
}
});
}
function toDecimal(x) {
var f = parseFloat(x);
if (isNaN(f)) {
return;
}
f = Math.round(x*100)/100;
return f;
}
|
define(['app', 'model/candidate'], function(App, CandidateCollection){
App.commands.setHandler('votePageDisplay', function(voter){
require(['views/vote', 'backbone'], function(VoteView, Backbone){
var list = new CandidateCollection();
list.fetch();
//Display only those candidates which are from the voter's constituency
App.Main.show(new VoteView({
collection: list
}));
}) ;
});
});
|
"use strict";
var platform_browser_dynamic_1 = require('@angular/platform-browser-dynamic');
var app_module_1 = require('./app/app.module');
//enableProdMode(); //Uncomment for production
document.addEventListener('WebComponentsReady', function () {
platform_browser_dynamic_1.platformBrowserDynamic().bootstrapModule(app_module_1.AppModule)
.then(function (success) { return console.log('App bootstrapped'); })
.catch(function (err) { return console.error(err); });
});
/*
var webComponentsFlag = false;
document.addEventListener('WebComponentsReady',() =>{
if (!webComponentsFlag)
platformBrowserDynamic().bootstrapModule(AppModule);
webComponentsFlag = true;
});
if (webComponentsFlag)
platformBrowserDynamic().bootstrapModule(AppModule);*/
|
'use strict';
var util = require('util'),
errors = module.exports = {};
errors.BaseError = function() {
var tmp = Error.apply(this, arguments);
tmp.name = this.name = 'QMFError';
this.message = tmp.message;
if (Error.captureStackTrace)
Error.captureStackTrace(this, this.constructor);
};
util.inherits(errors.BaseError, Error);
errors.AgentExceptionError = function(values) {
var errorText = (values.error_text instanceof Buffer) ?
values.error_text.toString() : values.error_text;
errors.BaseError.call(this, errorText);
this.name = 'QMFAgentExceptionError';
this.errorCode = values.error_code;
this.errorText = errorText;
};
util.inherits(errors.AgentExceptionError, errors.BaseError);
errors.InvalidResponseError = function(opcode) {
errors.BaseError.call(this, opcode);
this.name = 'QMFInvalidResponseError';
this.opcode = opcode;
};
util.inherits(errors.InvalidResponseError, errors.BaseError);
errors.TimeoutError = function() {
errors.BaseError.call(this, 'request timed out');
this.name = 'QMFTimeoutError';
};
util.inherits(errors.TimeoutError, errors.BaseError);
|
Slipmat.Views.LabelShow = Backbone.ModularView.extend({
tagName: "main",
className: "group",
template: JST["labels/show"],
initialize: function (options) {
this.router = options.router;
this.listenTo(this.model, "sync change", this.render);
},
events: {
"submit": "addComment"
},
render: function () {
var content = this.template({ label: this.model });
this.$el.html(content);
if (Slipmat.currentUser.isSignedIn()) {
$textarea = $('<textarea class="form comment-form">');
this.$("#new-comment").prepend($textarea);
}
this.listContributors();
this.renderComments();
this.renderRecords();
return this;
},
renderRecords: function () {
var records = this.model.records(),
template = JST["records/_record"],
header = JST["layouts/_paginationHeader"]({ collection: records }),
footer = JST["layouts/_paginationFooter"]({ collection: records }),
$el = this.$(".content-records");
this.$(".pagination-header").html(header);
this.$(".pagination-footer").html(footer);
records.forEach(record => {
var subview = template({ model: record });
$el.append(subview);
});
}
});
|
Meteor.startup(function () {
// Notification email
Router.route('/email/notification/:id?', {
name: 'notification',
where: 'server',
action: function() {
var notification = Herald.collection.findOne(this.params.id);
var notificationContents = buildEmailNotification(notification);
this.response.write(notificationContents.html);
this.response.end();
}
});
});
|
'use strict';
module.exports = {
db: 'mongodb://lolo:tazkypass@dogen.mongohq.com:10048/todo-database',
app: {
title: 'TuDu - Development Environment'
},
facebook: {
clientID: process.env.FACEBOOK_ID || 'APP_ID',
clientSecret: process.env.FACEBOOK_SECRET || 'APP_SECRET',
callbackURL: '/auth/facebook/callback'
},
twitter: {
clientID: process.env.TWITTER_KEY || 'CONSUMER_KEY',
clientSecret: process.env.TWITTER_SECRET || 'CONSUMER_SECRET',
callbackURL: '/auth/twitter/callback'
},
google: {
clientID: process.env.GOOGLE_ID || 'APP_ID',
clientSecret: process.env.GOOGLE_SECRET || 'APP_SECRET',
callbackURL: '/auth/google/callback'
},
linkedin: {
clientID: process.env.LINKEDIN_ID || 'APP_ID',
clientSecret: process.env.LINKEDIN_SECRET || 'APP_SECRET',
callbackURL: '/auth/linkedin/callback'
},
github: {
clientID: process.env.GITHUB_ID || 'APP_ID',
clientSecret: process.env.GITHUB_SECRET || 'APP_SECRET',
callbackURL: '/auth/github/callback'
},
mailer: {
from: process.env.MAILER_FROM || 'MAILER_FROM',
options: {
service: process.env.MAILER_SERVICE_PROVIDER || 'MAILER_SERVICE_PROVIDER',
auth: {
user: process.env.MAILER_EMAIL_ID || 'MAILER_EMAIL_ID',
pass: process.env.MAILER_PASSWORD || 'MAILER_PASSWORD'
}
}
}
};
|
const WRAPPER = Symbol('wrapper');
/**
* @function
* @description Decorator function that convert a class method to a getter
*/
export default function getter(
prototype,
property,
{ initializer, value, get },
) {
return {
configurable: true,
enumerable: true,
get() {
if (!this[WRAPPER]) {
this[WRAPPER] = {};
}
if (!this[WRAPPER][property]) {
const targetSymbol = Symbol(`${property}-target`);
this[targetSymbol] = initializer ? this::initializer() : value || get;
this[WRAPPER][property] =
typeof this[targetSymbol] === 'function'
? () => this[targetSymbol]()
: () => this[targetSymbol];
}
return this[WRAPPER][property]();
},
};
}
|
/*!
* UI development toolkit for HTML5 (OpenUI5)
* (c) Copyright 2009-2015 SAP SE or an SAP affiliate company.
* Licensed under the Apache License, Version 2.0 - see LICENSE.txt.
*/
sap.ui.define(['jquery.sap.global', './SplitContainerRenderer', 'sap/ui/core/Renderer'],
function(jQuery, SplitContainerRenderer, Renderer) {
"use strict";
/**
* SplitApp renderer.
* @namespace
*/
var SplitAppRenderer = {
};
var SplitAppRenderer = Renderer.extend(SplitContainerRenderer);
SplitAppRenderer.renderAttributes = function(oRm, oControl){
sap.m.BackgroundHelper.addBackgroundColorStyles(oRm, oControl.getBackgroundColor(), oControl.getBackgroundImage());
};
SplitAppRenderer.renderBeforeContent = function(oRm, oControl){
sap.m.BackgroundHelper.renderBackgroundImageTag(oRm, oControl, "sapMSplitContainerBG", oControl.getBackgroundImage(), oControl.getBackgroundRepeat(), oControl.getBackgroundOpacity());
};
return SplitAppRenderer;
}, /* bExport= */ true);
|
import DS from 'ember-data';
import BackboneElement from 'ember-fhir/models/backbone-element';
const { belongsTo, hasMany } = DS;
export default BackboneElement.extend({
resource: belongsTo('reference', { async: false }),
param: hasMany('test-script-param', { async: true })
});
|
module.exports = function ( grunt ) {
// Project configuration.
grunt.initConfig({
pkg : grunt.file.readJSON( 'package.json' ),
jshint : {
options: {
jshintrc: true
},
files : ['src/javascripts/**/*.js']
},
browserify : {
js: {
src: 'src/javascripts/main.js',
dest: 'dist/preamble.js'
}
},
usebanner: {
dist: {
options: {
position: 'top',
banner: '/* <%= pkg.title %> v<%= pkg.version %>' +
' - released on <%= grunt.template.today("yyyy-mm-dd") %>' +
' at <%= grunt.template.today("longTime") %>\n' +
' * <%= pkg.preamble.copyright %>\n' +
' * <%= pkg.preamble.distrights%>\n' +
'*/',
linebreak: true
},
files: {
src: [ 'dist/preamble.js', 'dist/preamble.js' ]
}
}
},
watch : {
js : {
files : ['src/javascripts/**/*.js'],
tasks : ['jshint'],
options : {
interrupt : true
}
},
browserify : {
files : ['src/javascripts/**/*.js'],
tasks : ['browserify'],
options : {
interrupt : true
}
},
banner : {
files : ['dist/preamble.js'],
tasks : ['usebanner'],
options : {
interrupt : true
}
}
}
});
// Load the plugins
grunt.loadNpmTasks( 'grunt-contrib-watch' );
grunt.loadNpmTasks('grunt-contrib-jshint');
grunt.loadNpmTasks('grunt-browserify');
grunt.loadNpmTasks('grunt-banner');
// Default task(s).
grunt.registerTask( 'default', ['watch'] );
grunt.registerTask( 'dist', ['jshint', 'browserify', 'usebanner'] );
};
|
'use strict';
const User = require('../../models/admin/user'),
Role = require('../../models/admin/role'),
page = require('../../util/page'),
_ = require('lodash');
module.exports = class UserController {
/**
* Display a list of users.
*/
static index(req, res) {
page(User, req).then(data => {
res.render('admin/user/index', data);
});
}
/**
* Render the form for editing a user.
*/
static edit(req, res) {
let id = req.params.id,
view = 'admin/user/form',
roles = {'admin': 'Admin'};
Role.where({}).then(cursor => {
cursor.project({'name': 1}).forEach(role => {
roles[role._id] = role.name;
}, err => {
if (id) {
User.find(id).then(user => {
res.render(view, {doc: user.data, roles});
});
} else {
res.render(view, {doc: {}, roles});
}
});
});
}
/**
* Save a user.
*/
static save(req, res) {
let data = _.pick(req.body, _.concat(User.keys, 'password'));
User.save(data, req.params.id).then(
result => {
req.flash('success', 'Saved successfully!');
res.redirect('/admin/users');
},
err =>{
_.pull(data, 'password');
req.flash('error', 'An error happened');
req.flash('old', data);
res.redirect('back');
});
}
/**
* Delete a user.
*/
static delete(req, res) {
User.delete(req.params.id).then(
count => {
req.flash('success', 'Deleted successfully!');
res.redirect('/admin/users');
},
err => {
req.flash('error', 'An error happened');
res.redirect('back');
});
}
}
|
/**
* File
*
* @author Tijme Gommers <t.gommers@jetcat.nl>
* @package server.helpers
*/
module.exports = {
/**
* @var Object
*/
fs: require('fs'),
/**
* File exists
*
* @param string Path to the file
* @return boolean exists
*/
exists: function(file)
{
try {
var stats = module.exports.fs.statSync(file);
return true;
} catch(e) {
return false;
}
},
/**
* Create a file
*
* @param string Path to the file
* @param string Content of the file
* @return boolean created
*/
create: function(file, content)
{
try {
module.exports.fs.writeFileSync(file, content);
} catch(e) {
console.log(e);
return false;
}
}
}
|
// https://www.creare.co.uk/blog/js/js-eu-cookie-law-banner
// Creare's 'Implied Consent' EU Cookie Law Banner v:2.4
// Conceived by Robert Kent, James Bavington & Tom Foyster
var cookieDuration = 365; // Number of days before the cookie expires, and the banner reappears
var cookieName = 'EuCookieLawCompliance'; // Name of our cookie
var cookieValue = 'on'; // Value of cookie
function createBanner() {
var bodytag = document.getElementsByTagName('body')[0];
var div = document.createElement('div');
div.setAttribute('id', 'cookie-law-banner');
div.innerHTML = '<i class="icon-info-circle distanced"></i>This website uses cookies. We do not use cookies for evil. By continuing we assume your permission to deploy cookies. <button type="button" onclick="createCookie();">Alright</button>';
bodytag.appendChild(div); // Adds the Cookie Law Banner just before the closing </body> tag
// or
// bodytag.insertBefore(div, bodytag.firstChild); // Adds the Cookie Law Banner just after the opening <body> tag
// document.getElementsByTagName('body')[0].className += ' cookiebanner'; //Adds a class tothe <body> tag when the banner is visible
}
function createCookie() {
var expires;
if (window.cookieDuration) {
var date = new Date();
date.setTime(date.getTime() + (window.cookieDuration * 24 * 60 * 60 * 1000));
expires = '; expires=' + date.toGMTString();
}
else {
expires = '';
}
document.cookie = window.cookieName + '=' + window.cookieValue + expires + '; path=/';
var element = document.getElementById('cookie-law-banner');
element.parentNode.removeChild(element);
}
function checkCookie(name) {
var nameEQ = name + '=';
var ca = document.cookie.split(';');
for (var i = 0; i < ca.length; i++) {
var c = ca[i];
while (c.charAt(0) == ' ') c = c.substring(1, c.length);
if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length, c.length);
}
return null;
}
function eraseCookie(name) {
createCookie(name, '', -1);
}
window.onload = function () {
if (checkCookie(window.cookieName) != window.cookieValue) {
createBanner();
}
};
|
import copySitecoreLibraries from './tasks/copy-sitecore-libraries';
import deploy from './tasks/deploy';
import nugetRestore from './tasks/nuget-restore';
import publishProjects from './tasks/publish-projects';
import publishTDS from './tasks/publish-tds';
export {
copySitecoreLibraries,
deploy,
nugetRestore,
publishProjects,
publishTDS,
};
|
'use strict'
const path = require('path')
const utils = require('./utils')
const webpack = require('webpack')
const config = require('../config')
const merge = require('webpack-merge')
const baseWebpackConfig = require('./webpack.base.conf')
const CopyWebpackPlugin = require('copy-webpack-plugin')
const HtmlWebpackPlugin = require('html-webpack-plugin')
const MiniCssExtractPlugin = require("mini-css-extract-plugin")
const OptimizeCSSPlugin = require('optimize-css-assets-webpack-plugin')
const VueLoaderPlugin = require("vue-loader/lib/plugin");
const pp = require('../package')
const env = process.env.NODE_ENV === 'testing'
? require('../config/test.env')
: config.build.env
const webpackConfig = merge(baseWebpackConfig, {
mode: 'production',
module: {
rules: utils.styleLoaders({
sourceMap: config.build.productionSourceMap,
extract: true
})
},
devtool: config.build.productionSourceMap ? '#source-map' : false,
output: {
path: config.build.assetsRoot,
filename: utils.assetsPath('js/[name].[chunkhash].js'),
chunkFilename: utils.assetsPath('js/[id].[chunkhash].js'),
publicPath: ['/', pp.aliasName, '/'].join('')
},
optimization: {
// minimize: true,
splitChunks: {
cacheGroups: {
commons: {
test: /[\\/]node_modules[\\/]/,
name: "vendor",
chunks: "all"
}
}
}
},
plugins: [
new VueLoaderPlugin(),
// http://vuejs.github.io/vue-loader/en/workflow/production.html
new webpack.DefinePlugin({
'process.env': env
}),
// UglifyJs do not support ES6+, you can also use babel-minify for better treeshaking: https://github.com/babel/minify
// new webpack.optimize.UglifyJsPlugin({
// compress: {
// warnings: false
// },
// sourceMap: true
// }),
// extract css into its own file
new MiniCssExtractPlugin({
filename: utils.assetsPath('css/[name].[contenthash].css'), //utils.assetsPath('css/[name].[contenthash].css')
chunkFilename: utils.assetsPath('css/[name].[contenthash].css')
}),
// Compress extracted CSS. We are using this plugin so that possible
// duplicated CSS from different components can be deduped.
new OptimizeCSSPlugin({
cssProcessorOptions: {
safe: true
}
}),
// generate dist index.html with correct asset hash for caching.
// you can customize output by editing /index.html
// see https://github.com/ampedandwired/html-webpack-plugin
new HtmlWebpackPlugin({
filename: process.env.NODE_ENV === 'testing'
? 'index.html'
: config.build.index,
template: 'index.html',
inject: true,
minify: {
removeComments: true,
collapseWhitespace: true,
removeAttributeQuotes: true
// more options:
// https://github.com/kangax/html-minifier#options-quick-reference
},
chunks: ['vendor', 'manifest', 'index'],
// necessary to consistently work with multiple chunks via CommonsChunkPlugin
chunksSortMode: 'dependency'
}),
new HtmlWebpackPlugin({
filename: process.env.NODE_ENV === 'testing'
? 'index.html'
: config.build.demo,
template: 'index.html',
inject: true,
minify: {
removeComments: true,
collapseWhitespace: true,
removeAttributeQuotes: true
// more options:
// https://github.com/kangax/html-minifier#options-quick-reference
},
chunks: ['vendor', 'manifest', 'demo/index'],
// necessary to consistently work with multiple chunks via CommonsChunkPlugin
chunksSortMode: 'dependency'
}),
// keep module.id stable when vender modules does not change
new webpack.HashedModuleIdsPlugin(),
// split vendor js into its own file
// new webpack.optimize.CommonsChunkPlugin({
// name: 'vendor',
// minChunks: function (module) {
// if(module.resource && (/^.*\.(css|scss)$/).test(module.resource)) {
// return false;
// }
// // any required modules inside node_modules are extracted to vendor
// return (
// module.resource &&
// /\.js$/.test(module.resource) &&
// module.resource.indexOf(
// path.join(__dirname, '../node_modules')
// ) === 0
// )
// }
// }),
// extract webpack runtime and module manifest to its own file in order to
// prevent vendor hash from being updated whenever app bundle is updated
// new webpack.optimize.CommonsChunkPlugin({
// name: 'manifest',
// chunks: ['vendor']
// }),
// copy custom static assets
new CopyWebpackPlugin([
{
from: path.resolve(__dirname, '../static'),
to: config.build.assetsSubDirectory,
ignore: ['.*']
}
])
]
})
if (config.build.productionGzip) {
// const CompressionWebpackPlugin = require('compression-webpack-plugin')
// webpackConfig.plugins.push(
// new CompressionWebpackPlugin({
// asset: '[path].gz[query]',
// algorithm: 'gzip',
// test: new RegExp(
// '\\.(' +
// config.build.productionGzipExtensions.join('|') +
// ')$'
// ),
// threshold: 10240,
// minRatio: 0.8
// })
// )
}
if (config.build.bundleAnalyzerReport) {
const BundleAnalyzerPlugin = require('webpack-bundle-analyzer').BundleAnalyzerPlugin
webpackConfig.plugins.push(new BundleAnalyzerPlugin())
}
module.exports = webpackConfig
|
import {h, div, h1, h2} from '@cycle/dom'
const view = props$ => {
return props$.map(x => {
return div('.page2', [
h1('.content-subhead', ['Page 2']),
h1([`This is the second Page`]),
h2(['Counter : ' + x])
])
});
};
export default view
|
export const TYPE = {
PUBLIC: 'public',
LINK: 'link',
USER: 'user',
PRIVATE: 'private',
};
export const SHARE_TYPE = {
PUBLIC: 'public',
LINK: 'link',
USER: 'user',
PRIVATE: 'private',
};
|
Boom.SecretTrigger = function( params ){
this.type = params.type || Boom.Assets.world.ENTITY.MISSING;
this.position = params.position;
this.interactable = params.interactable || false;
this.triggered = false;
Boom.Entity.call(this, {name: 'TRIGGER_SECRET', });
};
Boom.SecretTrigger.prototype = Boom.inherit(Boom.Entity, {
constructor: Boom.SecretTrigger,
init: function() {
//Call super
Boom.Entity.prototype.init.call(this);
this.load();
},
load: function(){
//Call super
Boom.Entity.prototype.load.call(this);
},
update: function(){
console.log("updating and stuff");
//Call super
Boom.Entity.prototype.update.call(this);
},
dispose: function(){
//Call super
Boom.Entity.prototype.dispose.call(this);
},
trigger: function(){
if(!this.triggered){
this.triggered = true;
this.process();
$(Boom.Constants.UI.ELEMENT.SECRET).show(200);
$(Boom.Constants.UI.ELEMENT.SECRET).hide(5000);
//Check if any entities are on this position - and trigger it if exists
Boom.GameGrid.triggerEntity( this.triggered, this.position, { open: true } );
}
},
//Registers the entity as a player-used entity
process: function(){
Boom.Constants.UI.PLAYER.STATS.SECRETS++;
//Call super
Boom.Entity.prototype.process.call(this);
},
//Adds entity to world-total in statistics
register: function(){
Boom.Constants.World.STATS.SECRETS++;
//Call super
Boom.Entity.prototype.register.call(this);
},
});
|
import React from 'react';
import { expect } from 'chai';
import { shallow } from 'enzyme';
import H1, { styles } from './index';
describe('<H1 />', () => {
it('should correctly render children, when text', () => {
const wrapper = shallow(<H1>Title</H1>);
expect(wrapper.text()).to.equal('Title');
});
it('should append a className to the default, if provided', () => {
const wrapper = shallow(<H1 className="test-class">Title H1</H1>);
expect(wrapper.prop('className')).to.equal(`test-class ${styles.h1}`);
});
it('should use the default className from the stylesheet, if not provided', () => {
const wrapper = shallow(<H1>Title H1</H1>);
expect(wrapper.prop('className')).to.equal(styles.h1);
});
});
|
'use strict';
var elements = require('../elements');
/**
* Show the element (remove the class .hidden)
*
* @name Element#show
* @method
*
*/
/**
* Show the elements (remove the class .hidden)
*
* @name ElementsArray#show
* @method
*/
elements.addMethodWithoutArgumentsReturnThis('show');
/**
* Hide the element (add the class .hidden)
*
* @name Element#hide
* @method
*
*/
/**
* Hide the elements (add the class .hidden)
*
* @name ElementsArray#hide
* @method
*/
elements.addMethodWithoutArgumentsReturnThis('hide');
/**
* Toggle an element's visibility using the hidden class
*
* @name Element#toggle
* @method
*
*/
/**
* Toggle an element's visibility using the hidden class
*
* @name ElementsArray#toggle
* @method
*/
elements.addMethodWithoutArgumentsReturnThis('toggle');
/**
* Return if an element's visibility
*
* @name Element#isVisible
* @method
*
*/
/**
* Return a map of element's visibility
*
* @name ElementsArray#isVisible
* @method
*/
elements.addMethodWithoutArgumentsReturnResult('isVisible');
//# sourceMappingURL=visibility.js.map
|
// Copyright StrongLoop 2014
Arc.controller('ArcMainController', [
'$scope',
'ArcUserService',
'$log',
'$rootScope',
'LandingService',
function($scope, ArcUserService, $log, $rootScope, LandingService){
$scope.suiteIA = {
apps: []
};
//set help id for app modules
$scope.$watch('suiteIA.appId', function(newVal){
if ( !newVal ) return;
$rootScope.helpId = newVal;
});
$scope.isAuthUser = function(){
return ArcUserService.isAuthUser();
};
$scope.pageClick = function($event){
$rootScope.$broadcast('pageClick', $event);
};
$scope.supportAppController = false;
LandingService.getApps().$promise
.then(function(response) {
var buildApp = response.results.filter(function(d) {
return d.id === 'build-deploy';
});
if (buildApp.length) {
$scope.supportAppController = buildApp[0].supportsCurrentProject;
}
});
}]);
Arc.controller('HomeMainController',[
'$scope',
'$location',
function($scope, $location){
var viewModel = {};
viewModel.message = 'StrongLoop Arc';
$scope.viewModel = viewModel;
}
]);
/*
*
* */
Arc.controller('GlobalNavController',[
'$scope',
'ArcUserService',
'$location',
function($scope, ArcUserService, $location) {
$scope.isAuthUser = function(){
return ArcUserService.getCurrentUserId();
};
}
]);
|
Template.modalEditLanguages.events({
"submit form": function (event) {
event.preventDefault();
var name = event.target["language-name"].value.trim(),
project = event.target["project-id"].value;
if (name) {
Meteor.call('addLanguage', project, name, function (error, res) {
if (error) Materialize.toast(error.reason, 5000);
else {
event.target["language-name"].value = "";
$('#modal-edit-languages').closeModal();
}
});
}
},
'click [data-action="remove-language"]': function (event) {
event.preventDefault();
var $el = $(event.currentTarget),
project = $el.data('project'),
language = $el.text();
Meteor.call('removeLanguage', project, language, function (error, res) {
if (error) Materialize.toast(error.reason, 5000);
//else $el.remove();
});
}
});
|
var EventEmitter = require('events').EventEmitter;
var util = require('util');
var MongoClient = require('mongodb').MongoClient;
var Channel = require('./channel');
/**
* Connection constructor.
*
* @param {String|Db} uri string or Db instance
* @param {Object} mongo driver options
* @api public
*/
function Connection(uri, options) {
var self = this;
options || (options = {});
options.autoReconnect != null || (options.autoReconnect = true);
// It's a Db instance.
if (uri.collection) {
this.db = uri;
} else {
MongoClient.connect(uri, options, function (err, db) {
if (err) return self.emit('error', err);
self.db = db;
self.emit('connect', db);
db.on('error', function (err) {
self.emit('error', err);
});
});
}
this.destroyed = false;
this.channels = {};
}
module.exports = Connection;
util.inherits(Connection, EventEmitter);
/**
* Current connection state.
*
* @type {String}
* @api public
*/
Object.defineProperty(Connection.prototype, 'state', {
enumerable: true,
get: function () {
var state;
// Using 'destroyed' to be compatible with the driver.
if (this.destroyed) {
state = 'destroyed';
}
else if (this.db) {
state = this.db.serverConfig.isConnected()
? 'connected' : 'disconnected';
} else {
state = 'connecting';
}
return state;
}
});
/**
* Creates or returns a channel with the passed name.
*
* @see Channel
* @return {Channel}
* @api public
*/
Connection.prototype.channel = function (name, options) {
if (typeof name === 'object') {
options = name;
name = 'mubsub';
}
if (!this.channels[name] || this.channels[name].closed) {
this.channels[name] = new Channel(this, name, options);
}
return this.channels[name];
};
/**
* Close connection.
*
* @param {Function} [callback]
* @return {Connection} this
* @api public
*/
Connection.prototype.close = function (callback) {
this.destroyed = true;
this.emit('close');
this.db.close(callback);
return this;
};
|
import $ from 'jquery';
import ChromeExtensionMessageService from '../../../reuse/messageServiceDefinition';
/**
*
* @param {*} $scope
* @param {*} $document
* @param {*} $location
* @param {ChromeExtensionMessageService} messageService
* @param {*} analyticsService
*/
function MenuController($scope, $document, $location, messageService, analyticsService) {
$scope.importOpml = function() {
$('#opmlUploader').trigger('click');
};
$scope.togglePlaylistVisibility = togglePlaylistVisibility;
$scope.exportOpml = exportOpml;
// ng-change is not supported for input type='file'
$document[0].getElementById('opmlUploader').addEventListener('change', fileNameChanged);
function fileNameChanged(event) {
var file = event.currentTarget.files[0];
// clear so that selecting the same file twice will call it again.
// not really necessary in real world use cases.
$document[0].getElementById('opmlUploader').value = '';
var reader = new FileReader;
reader.onload = function(e) {
var jqParsed = $(e.currentTarget.result);
var podcasts = [];
var rssFeeds = jqParsed.find('outline[type="rss"]');
rssFeeds.each(function(index, value) {
var feedURL = $(value).attr('xmlUrl');
if(feedURL) {
podcasts.push(feedURL);
}
});
if(podcasts.length) {
$location.path('/Podcasts');
analyticsService.trackEvent('feed', 'add_by_opml_file', undefined, podcasts.length);
messageService.for('podcastManager').sendMessage('addPodcasts', { podcasts: podcasts});
}
};
reader.readAsText(file);
}
function togglePlaylistVisibility() {
messageService.for('playlist').sendMessage('toggleVisibility');
}
function exportOpml() {
messageService.for('podcastManager').sendMessage('getOpml', null, response => {
download(response);
});
}
function download(text) {
var element = $document[0].createElement('a');
element.setAttribute('href', 'data:text/plain;charset=utf-8,' + encodeURIComponent(text));
element.setAttribute('download', 'podStation.opml');
element.style.display = 'none';
$document[0].body.appendChild(element);
element.click();
$document[0].body.removeChild(element);
}
}
export default MenuController;
|
import * as actions from '../UserActions';
it('should setup loggingIn', () => {
const action = actions.loggingIn();
const expected = {
type: 'LOGGING_IN'
};
expect(action).toEqual(expected);
});
it('should setup loggedInSuccess', () => {
const user = 'janesmith';
const action = actions.loggedInSuccess(user);
const expected = {
type: 'LOGGED_IN_SUCCESS',
payload: user
};
expect(action).toEqual(expected);
});
it('should setup loggedInError', () => {
const err = 'something went wrong';
const action = actions.loggedInError(err);
const expected = {
type: 'LOGGED_IN_ERROR',
error: err
};
expect(action).toEqual(expected);
});
it('should setup logoutSuccess', () => {
const action = actions.logoutSuccess();
const expected = {
type: 'LOGGED_OUT_SUCCESS'
};
expect(action).toEqual(expected);
});
|
var page;
var healthStore;
var weightType;
function pageLoaded(args) {
page = args.object;
weightType = HKObjectType.quantityTypeForIdentifier(HKQuantityTypeIdentifierBodyMass);
healthStore = HKHealthStore.new();
requestPermissions(healthStore, [weightType], [weightType]);
}
exports.pageLoaded = pageLoaded;
function getWeightButtonTap(args) {
hideKeyboard();
getHealthKitValue(healthStore, weightType, function (weight) {
alert("Your weight is " + weight.doubleValueForUnit(HKUnit.poundUnit()) + " pounds");
});
}
exports.getWeightButtonTap = getWeightButtonTap;
function setWeightButtonTap(args) {
hideKeyboard();
var textField = page.getViewById("weightTextView");
var weight = parseFloat(textField.text);
setHalthKitValue(healthStore, weightType, HKQuantity.quantityWithUnitDoubleValue(HKUnit.poundUnit(), weight));
}
exports.setWeightButtonTap = setWeightButtonTap;
function hideKeyboard() {
var textField = page.getViewById("weightTextView");
textField.ios.resignFirstResponder();
}
function requestPermissions(healthStore, writeTypes, readTypes) {
var writeDataTypes = NSSet.setWithArray(writeTypes);
var readDataTypes = NSSet.setWithArray(readTypes);
healthStore.requestAuthorizationToShareTypesReadTypesCompletion(writeDataTypes, readDataTypes, function (success, error) {
if (!success) {
}
});
}
function getHealthKitValue(healthStore, quantityType, callback) {
var endDateSortDescriptor = NSSortDescriptor.alloc().initWithKeyAscending(HKSampleSortIdentifierEndDate, false);
var query = HKSampleQuery.alloc().initWithSampleTypePredicateLimitSortDescriptorsResultsHandler(quantityType, null, 1, [endDateSortDescriptor], function (query, results, error) {
if (results) {
var quantitySample = results.firstObject;
if (quantitySample) {
callback(quantitySample.quantity);
}
else {
alert("Error!");
}
}
else {
alert("Error!");
}
});
healthStore.executeQuery(query);
}
function setHalthKitValue(healthStore, quantityType, quantity) {
var now = NSDate.new();
var sample = HKQuantitySample.quantitySampleWithTypeQuantityStartDateEndDate(quantityType, quantity, now, now);
healthStore.saveObjectWithCompletion(sample, function (success, error) {
if (success) {
alert("Done!");
}
else {
alert("Error!");
}
});
}
|
/**
* Copyright (c) Facebook, Inc. and its affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*
* @flow
* @format
*/
'use strict';
const visit = require('graphql').visit;
import type {
Argument,
Condition,
Directive,
Fragment,
FragmentSpread,
InlineFragment,
LinkedField,
Literal,
LocalArgumentDefinition,
MatchField,
MatchBranch,
Request,
Root,
RootArgumentDefinition,
ScalarField,
SplitOperation,
Variable,
} from './GraphQLIR';
const NodeKeys = {
Argument: ['value'],
Condition: ['condition', 'selections'],
Directive: ['args'],
Fragment: ['argumentDefinitions', 'directives', 'selections'],
FragmentSpread: ['args', 'directives'],
InlineFragment: ['directives', 'selections'],
LinkedField: ['args', 'directives', 'selections'],
Literal: [],
LocalArgumentDefinition: [],
MatchField: ['args', 'directives', 'selections'],
MatchBranch: ['selections'],
Request: ['fragment', 'root'],
Root: ['argumentDefinitions', 'directives', 'selections'],
RootArgumentDefinition: [],
ScalarField: ['args', 'directives'],
SplitOperation: ['selections'],
Variable: [],
};
export type VisitNode =
| Argument
| Condition
| Directive
| Fragment
| FragmentSpread
| InlineFragment
| LinkedField
| Literal
| LocalArgumentDefinition
| MatchField
| Request
| Root
| RootArgumentDefinition
| ScalarField
| SplitOperation
| Variable;
export type VisitFn<T: VisitNode> = (
node: T, // node we're visiting
key?: any, // index/key to node from parent array/object
parent?: ?(VisitNode | Array<VisitNode>), // Object immediately above node
path?: Array<any>, // keys to get from root: [keyForChild, ..., keyForParent]
ancestors?: Array<VisitNode | Array<VisitNode>>, // [root, child1, ..., grandparent]
// Note: ancestors includes arrays which contain the visited node
// These correspond to array indices in `path`.
) => any;
export type NodeVisitorObject<T: VisitNode> =
| {enter?: VisitFn<T>, leave?: VisitFn<T>}
| VisitFn<T>;
export type NodeVisitor =
| NodeVisitorObject<VisitNode>
| {
Argument?: NodeVisitorObject<Argument>,
Condition?: NodeVisitorObject<Condition>,
Directive?: NodeVisitorObject<Directive>,
Fragment?: NodeVisitorObject<Fragment>,
FragmentSpread?: NodeVisitorObject<FragmentSpread>,
InlineFragment?: NodeVisitorObject<InlineFragment>,
LinkedField?: NodeVisitorObject<LinkedField>,
MatchField?: NodeVisitorObject<MatchField>,
MatchBranch?: NodeVisitorObject<MatchBranch>,
Literal?: NodeVisitorObject<Literal>,
LocalArgumentDefinition?: NodeVisitorObject<LocalArgumentDefinition>,
Request?: NodeVisitorObject<Request>,
Root?: NodeVisitorObject<Root>,
RootArgumentDefinition?: NodeVisitorObject<RootArgumentDefinition>,
ScalarField?: NodeVisitorObject<ScalarField>,
Variable?: NodeVisitorObject<Variable>,
};
function visitIR(root: VisitNode, visitor: NodeVisitor) {
return (visit: $FlowFixMe)(root, visitor, NodeKeys);
}
module.exports = {visit: visitIR};
|
var ip = require('ip');
var azure = require('azure-storage');
var osenv = require('osenv');
var Guid = require('guid');
//console.log(process.env.AZURE_STORAGE_ACCOUNT);
//console.log(process.env.AZURE_STORAGE_ACCESS_KEY);
// Some things are not reliably in the env, and have a fallback command:
var h = osenv.hostname(function (er, hostname) {
h = hostname
});
var localIpAddress = ip.address();
var tableSvc = azure.createTableService();
osenv.hostname(function (error, hostname) {
if (!error) {
var localIp = {
PartitionKey: {'_':'localIp'},
RowKey: {'_': '' + Guid.create()},
ip: {'_': localIpAddress},
hostName: {'_': hostname}
};
tableSvc.createTableIfNotExists('deviceip', function(error, result, response){
if(!error){
tableSvc.insertEntity('deviceip',localIp, function (error, result, response) {
if(!error){
console.log('IP address: ' + JSON.stringify(localIp) + 'saved to Azure');
} else {
console.log(error);
}
});
} else {
console.log(error);
}
});
} else {
console.log(error);
}
});
|
'use strict';
/**
* @ngdoc function
* @name gccdApp.controller:AboutCtrl
* @description
* # AboutCtrl
* Controller of the itisforgirls
*/
angular.module('itisforgirls')
.controller('AboutCtrl', function ($scope) {
$scope.awesomeThings = [
'HTML5 Boilerplate',
'AngularJS',
'Karma'
];
});
|
const Sequelize = require('sequelize'),
connection = require('./sequelize.js');
const attributes = {
id: {
type: Sequelize.UUID,
primaryKey: true,
defaultValue: Sequelize.UUIDV4
},
username: {
type: Sequelize.STRING,
allowNull: false,
unique: true,
validate: {
is: /^[a-z0-9\_\-]+$/i,
len: [2,15]
}
},
email: {
type: Sequelize.STRING,
unique: true,
validate: {
isEmail: true
}
},
displayName: {
type: Sequelize.STRING,
allowNull: false,
},
bio: {
type: Sequelize.STRING
},
location: {
type: Sequelize.STRING
},
avatar: {
type: Sequelize.STRING
},
password: {
type: Sequelize.STRING
},
title: {
type: Sequelize.STRING
},
salt: {
type: Sequelize.STRING
},
createdAt: { type: Sequelize.DATE, defaultValue: Sequelize.NOW }
};
const options = {
freezeTableName: true,
toJSON: function () {
var values = Object.assign({}, this.get());
// Killing unneded values for our http response.
delete values.email;
delete values.password;
delete values.salt;
delete values.createdAt;
delete values.updatedAt;
return values;
}
}
const User = connection.define('users', attributes, options);
module.exports = User;
|
var searchData=
[
['lib_2ehpp',['lib.hpp',['../lib_8hpp.html',1,'']]],
['lib_5f8hpp_2ejs',['lib_8hpp.js',['../lib__8hpp_8js.html',1,'']]]
];
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.